]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/debuginfo.rs
rollup merge of #19577: aidancully/master
[rust.git] / src / librustc_trans / trans / debuginfo.rs
1 // Copyright 2012-2014 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 //! # Debug Info Module
12 //!
13 //! This module serves the purpose of generating debug symbols. We use LLVM's
14 //! [source level debugging](http://llvm.org/docs/SourceLevelDebugging.html)
15 //! features for generating the debug information. The general principle is this:
16 //!
17 //! Given the right metadata in the LLVM IR, the LLVM code generator is able to
18 //! create DWARF debug symbols for the given code. The
19 //! [metadata](http://llvm.org/docs/LangRef.html#metadata-type) is structured much
20 //! like DWARF *debugging information entries* (DIE), representing type information
21 //! such as datatype layout, function signatures, block layout, variable location
22 //! and scope information, etc. It is the purpose of this module to generate correct
23 //! metadata and insert it into the LLVM IR.
24 //!
25 //! As the exact format of metadata trees may change between different LLVM
26 //! versions, we now use LLVM
27 //! [DIBuilder](http://llvm.org/docs/doxygen/html/classllvm_1_1DIBuilder.html) to
28 //! create metadata where possible. This will hopefully ease the adaption of this
29 //! module to future LLVM versions.
30 //!
31 //! The public API of the module is a set of functions that will insert the correct
32 //! metadata into the LLVM IR when called with the right parameters. The module is
33 //! thus driven from an outside client with functions like
34 //! `debuginfo::create_local_var_metadata(bcx: block, local: &ast::local)`.
35 //!
36 //! Internally the module will try to reuse already created metadata by utilizing a
37 //! cache. The way to get a shared metadata node when needed is thus to just call
38 //! the corresponding function in this module:
39 //!
40 //!     let file_metadata = file_metadata(crate_context, path);
41 //!
42 //! The function will take care of probing the cache for an existing node for that
43 //! exact file path.
44 //!
45 //! All private state used by the module is stored within either the
46 //! CrateDebugContext struct (owned by the CrateContext) or the FunctionDebugContext
47 //! (owned by the FunctionContext).
48 //!
49 //! This file consists of three conceptual sections:
50 //! 1. The public interface of the module
51 //! 2. Module-internal metadata creation functions
52 //! 3. Minor utility functions
53 //!
54 //!
55 //! ## Recursive Types
56 //!
57 //! Some kinds of types, such as structs and enums can be recursive. That means that
58 //! the type definition of some type X refers to some other type which in turn
59 //! (transitively) refers to X. This introduces cycles into the type referral graph.
60 //! A naive algorithm doing an on-demand, depth-first traversal of this graph when
61 //! describing types, can get trapped in an endless loop when it reaches such a
62 //! cycle.
63 //!
64 //! For example, the following simple type for a singly-linked list...
65 //!
66 //! ```
67 //! struct List {
68 //!     value: int,
69 //!     tail: Option<Box<List>>,
70 //! }
71 //! ```
72 //!
73 //! will generate the following callstack with a naive DFS algorithm:
74 //!
75 //! ```
76 //! describe(t = List)
77 //!   describe(t = int)
78 //!   describe(t = Option<Box<List>>)
79 //!     describe(t = Box<List>)
80 //!       describe(t = List) // at the beginning again...
81 //!       ...
82 //! ```
83 //!
84 //! To break cycles like these, we use "forward declarations". That is, when the
85 //! algorithm encounters a possibly recursive type (any struct or enum), it
86 //! immediately creates a type description node and inserts it into the cache
87 //! *before* describing the members of the type. This type description is just a
88 //! stub (as type members are not described and added to it yet) but it allows the
89 //! algorithm to already refer to the type. After the stub is inserted into the
90 //! cache, the algorithm continues as before. If it now encounters a recursive
91 //! reference, it will hit the cache and does not try to describe the type anew.
92 //!
93 //! This behaviour is encapsulated in the 'RecursiveTypeDescription' enum, which
94 //! represents a kind of continuation, storing all state needed to continue
95 //! traversal at the type members after the type has been registered with the cache.
96 //! (This implementation approach might be a tad over-engineered and may change in
97 //! the future)
98 //!
99 //!
100 //! ## Source Locations and Line Information
101 //!
102 //! In addition to data type descriptions the debugging information must also allow
103 //! to map machine code locations back to source code locations in order to be useful.
104 //! This functionality is also handled in this module. The following functions allow
105 //! to control source mappings:
106 //!
107 //! + set_source_location()
108 //! + clear_source_location()
109 //! + start_emitting_source_locations()
110 //!
111 //! `set_source_location()` allows to set the current source location. All IR
112 //! instructions created after a call to this function will be linked to the given
113 //! source location, until another location is specified with
114 //! `set_source_location()` or the source location is cleared with
115 //! `clear_source_location()`. In the later case, subsequent IR instruction will not
116 //! be linked to any source location. As you can see, this is a stateful API
117 //! (mimicking the one in LLVM), so be careful with source locations set by previous
118 //! calls. It's probably best to not rely on any specific state being present at a
119 //! given point in code.
120 //!
121 //! One topic that deserves some extra attention is *function prologues*. At the
122 //! beginning of a function's machine code there are typically a few instructions
123 //! for loading argument values into allocas and checking if there's enough stack
124 //! space for the function to execute. This *prologue* is not visible in the source
125 //! code and LLVM puts a special PROLOGUE END marker into the line table at the
126 //! first non-prologue instruction of the function. In order to find out where the
127 //! prologue ends, LLVM looks for the first instruction in the function body that is
128 //! linked to a source location. So, when generating prologue instructions we have
129 //! to make sure that we don't emit source location information until the 'real'
130 //! function body begins. For this reason, source location emission is disabled by
131 //! default for any new function being translated and is only activated after a call
132 //! to the third function from the list above, `start_emitting_source_locations()`.
133 //! This function should be called right before regularly starting to translate the
134 //! top-level block of the given function.
135 //!
136 //! There is one exception to the above rule: `llvm.dbg.declare` instruction must be
137 //! linked to the source location of the variable being declared. For function
138 //! parameters these `llvm.dbg.declare` instructions typically occur in the middle
139 //! of the prologue, however, they are ignored by LLVM's prologue detection. The
140 //! `create_argument_metadata()` and related functions take care of linking the
141 //! `llvm.dbg.declare` instructions to the correct source locations even while
142 //! source location emission is still disabled, so there is no need to do anything
143 //! special with source location handling here.
144 //!
145 //! ## Unique Type Identification
146 //!
147 //! In order for link-time optimization to work properly, LLVM needs a unique type
148 //! identifier that tells it across compilation units which types are the same as
149 //! others. This type identifier is created by TypeMap::get_unique_type_id_of_type()
150 //! using the following algorithm:
151 //!
152 //! (1) Primitive types have their name as ID
153 //! (2) Structs, enums and traits have a multipart identifier
154 //!
155 //!     (1) The first part is the SVH (strict version hash) of the crate they were
156 //!         originally defined in
157 //!
158 //!     (2) The second part is the ast::NodeId of the definition in their original
159 //!         crate
160 //!
161 //!     (3) The final part is a concatenation of the type IDs of their concrete type
162 //!         arguments if they are generic types.
163 //!
164 //! (3) Tuple-, pointer and function types are structurally identified, which means
165 //!     that they are equivalent if their component types are equivalent (i.e. (int,
166 //!     int) is the same regardless in which crate it is used).
167 //!
168 //! This algorithm also provides a stable ID for types that are defined in one crate
169 //! but instantiated from metadata within another crate. We just have to take care
170 //! to always map crate and node IDs back to the original crate context.
171 //!
172 //! As a side-effect these unique type IDs also help to solve a problem arising from
173 //! lifetime parameters. Since lifetime parameters are completely omitted in
174 //! debuginfo, more than one `Ty` instance may map to the same debuginfo type
175 //! metadata, that is, some struct `Struct<'a>` may have N instantiations with
176 //! different concrete substitutions for `'a`, and thus there will be N `Ty`
177 //! instances for the type `Struct<'a>` even though it is not generic otherwise.
178 //! Unfortunately this means that we cannot use `ty::type_id()` as cheap identifier
179 //! for type metadata---we have done this in the past, but it led to unnecessary
180 //! metadata duplication in the best case and LLVM assertions in the worst. However,
181 //! the unique type ID as described above *can* be used as identifier. Since it is
182 //! comparatively expensive to construct, though, `ty::type_id()` is still used
183 //! additionally as an optimization for cases where the exact same type has been
184 //! seen before (which is most of the time).
185 use self::FunctionDebugContextRepr::*;
186 use self::VariableAccess::*;
187 use self::VariableKind::*;
188 use self::MemberOffset::*;
189 use self::MemberDescriptionFactory::*;
190 use self::RecursiveTypeDescription::*;
191 use self::EnumDiscriminantInfo::*;
192 use self::DebugLocation::*;
193
194 use llvm;
195 use llvm::{ModuleRef, ContextRef, ValueRef};
196 use llvm::debuginfo::*;
197 use metadata::csearch;
198 use middle::subst::{mod, Subst, Substs};
199 use trans::{mod, adt, machine, type_of};
200 use trans::common::*;
201 use trans::_match::{BindingInfo, TrByCopy, TrByMove, TrByRef};
202 use trans::type_::Type;
203 use middle::ty::{mod, Ty};
204 use middle::pat_util;
205 use session::config::{mod, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
206 use util::nodemap::{DefIdMap, NodeMap, FnvHashMap, FnvHashSet};
207 use util::ppaux;
208
209 use libc::c_uint;
210 use std::c_str::{CString, ToCStr};
211 use std::cell::{Cell, RefCell};
212 use std::ptr;
213 use std::rc::{Rc, Weak};
214 use syntax::util::interner::Interner;
215 use syntax::codemap::{Span, Pos};
216 use syntax::{ast, codemap, ast_util, ast_map};
217 use syntax::ast_util::PostExpansionMethod;
218 use syntax::parse::token::{mod, special_idents};
219
220 static DW_LANG_RUST: c_uint = 0x9000;
221
222 #[allow(non_upper_case_globals)]
223 static DW_TAG_auto_variable: c_uint = 0x100;
224 #[allow(non_upper_case_globals)]
225 static DW_TAG_arg_variable: c_uint = 0x101;
226
227 #[allow(non_upper_case_globals)]
228 static DW_ATE_boolean: c_uint = 0x02;
229 #[allow(non_upper_case_globals)]
230 static DW_ATE_float: c_uint = 0x04;
231 #[allow(non_upper_case_globals)]
232 static DW_ATE_signed: c_uint = 0x05;
233 #[allow(non_upper_case_globals)]
234 static DW_ATE_unsigned: c_uint = 0x07;
235 #[allow(non_upper_case_globals)]
236 static DW_ATE_unsigned_char: c_uint = 0x08;
237
238 static UNKNOWN_LINE_NUMBER: c_uint = 0;
239 static UNKNOWN_COLUMN_NUMBER: c_uint = 0;
240
241 // ptr::null() doesn't work :(
242 static UNKNOWN_FILE_METADATA: DIFile = (0 as DIFile);
243 static UNKNOWN_SCOPE_METADATA: DIScope = (0 as DIScope);
244
245 static FLAGS_NONE: c_uint = 0;
246
247 //=-----------------------------------------------------------------------------
248 //  Public Interface of debuginfo module
249 //=-----------------------------------------------------------------------------
250
251 #[deriving(Show, Hash, Eq, PartialEq, Clone)]
252 struct UniqueTypeId(ast::Name);
253
254 impl Copy for UniqueTypeId {}
255
256 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
257 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
258 // faster lookup, also by Ty. The TypeMap is responsible for creating
259 // UniqueTypeIds.
260 struct TypeMap<'tcx> {
261     // The UniqueTypeIds created so far
262     unique_id_interner: Interner<Rc<String>>,
263     // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
264     unique_id_to_metadata: FnvHashMap<UniqueTypeId, DIType>,
265     // A map from types to debuginfo metadata. This is a N:1 mapping.
266     type_to_metadata: FnvHashMap<Ty<'tcx>, DIType>,
267     // A map from types to UniqueTypeId. This is a N:1 mapping.
268     type_to_unique_id: FnvHashMap<Ty<'tcx>, UniqueTypeId>
269 }
270
271 impl<'tcx> TypeMap<'tcx> {
272
273     fn new() -> TypeMap<'tcx> {
274         TypeMap {
275             unique_id_interner: Interner::new(),
276             type_to_metadata: FnvHashMap::new(),
277             unique_id_to_metadata: FnvHashMap::new(),
278             type_to_unique_id: FnvHashMap::new(),
279         }
280     }
281
282     // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
283     // the mapping already exists.
284     fn register_type_with_metadata<'a>(&mut self,
285                                        cx: &CrateContext<'a, 'tcx>,
286                                        type_: Ty<'tcx>,
287                                        metadata: DIType) {
288         if self.type_to_metadata.insert(type_, metadata).is_some() {
289             cx.sess().bug(format!("Type metadata for Ty '{}' is already in the TypeMap!",
290                                    ppaux::ty_to_string(cx.tcx(), type_)).as_slice());
291         }
292     }
293
294     // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
295     // fail if the mapping already exists.
296     fn register_unique_id_with_metadata(&mut self,
297                                         cx: &CrateContext,
298                                         unique_type_id: UniqueTypeId,
299                                         metadata: DIType) {
300         if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
301             let unique_type_id_str = self.get_unique_type_id_as_string(unique_type_id);
302             cx.sess().bug(format!("Type metadata for unique id '{}' is already in the TypeMap!",
303                                   unique_type_id_str.as_slice()).as_slice());
304         }
305     }
306
307     fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
308         self.type_to_metadata.get(&type_).cloned()
309     }
310
311     fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<DIType> {
312         self.unique_id_to_metadata.get(&unique_type_id).cloned()
313     }
314
315     // Get the string representation of a UniqueTypeId. This method will fail if
316     // the id is unknown.
317     fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> Rc<String> {
318         let UniqueTypeId(interner_key) = unique_type_id;
319         self.unique_id_interner.get(interner_key)
320     }
321
322     // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
323     // type has been requested before, this is just a table lookup. Otherwise an
324     // ID will be generated and stored for later lookup.
325     fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
326                                       type_: Ty<'tcx>) -> UniqueTypeId {
327
328         // basic type           -> {:name of the type:}
329         // tuple                -> {tuple_(:param-uid:)*}
330         // struct               -> {struct_:svh: / :node-id:_<(:param-uid:),*> }
331         // enum                 -> {enum_:svh: / :node-id:_<(:param-uid:),*> }
332         // enum variant         -> {variant_:variant-name:_:enum-uid:}
333         // reference (&)        -> {& :pointee-uid:}
334         // mut reference (&mut) -> {&mut :pointee-uid:}
335         // ptr (*)              -> {* :pointee-uid:}
336         // mut ptr (*mut)       -> {*mut :pointee-uid:}
337         // unique ptr (~)       -> {~ :pointee-uid:}
338         // @-ptr (@)            -> {@ :pointee-uid:}
339         // sized vec ([T, ..x]) -> {[:size:] :element-uid:}
340         // unsized vec ([T])    -> {[] :element-uid:}
341         // trait (T)            -> {trait_:svh: / :node-id:_<(:param-uid:),*> }
342         // closure              -> {<unsafe_> <once_> :store-sigil: |(:param-uid:),* <,_...>| -> \
343         //                             :return-type-uid: : (:bounds:)*}
344         // function             -> {<unsafe_> <abi_> fn( (:param-uid:)* <,_...> ) -> \
345         //                             :return-type-uid:}
346         // unique vec box (~[]) -> {HEAP_VEC_BOX<:pointee-uid:>}
347         // gc box               -> {GC_BOX<:pointee-uid:>}
348
349         match self.type_to_unique_id.get(&type_).cloned() {
350             Some(unique_type_id) => return unique_type_id,
351             None => { /* generate one */}
352         };
353
354         let mut unique_type_id = String::with_capacity(256);
355         unique_type_id.push('{');
356
357         match type_.sty {
358             ty::ty_bool     |
359             ty::ty_char     |
360             ty::ty_str      |
361             ty::ty_int(_)   |
362             ty::ty_uint(_)  |
363             ty::ty_float(_) => {
364                 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
365             },
366             ty::ty_enum(def_id, ref substs) => {
367                 unique_type_id.push_str("enum ");
368                 from_def_id_and_substs(self, cx, def_id, substs, &mut unique_type_id);
369             },
370             ty::ty_struct(def_id, ref substs) => {
371                 unique_type_id.push_str("struct ");
372                 from_def_id_and_substs(self, cx, def_id, substs, &mut unique_type_id);
373             },
374             ty::ty_tup(ref component_types) if component_types.is_empty() => {
375                 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
376             },
377             ty::ty_tup(ref component_types) => {
378                 unique_type_id.push_str("tuple ");
379                 for &component_type in component_types.iter() {
380                     let component_type_id =
381                         self.get_unique_type_id_of_type(cx, component_type);
382                     let component_type_id =
383                         self.get_unique_type_id_as_string(component_type_id);
384                     unique_type_id.push_str(component_type_id.as_slice());
385                 }
386             },
387             ty::ty_uniq(inner_type) => {
388                 unique_type_id.push('~');
389                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
390                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
391                 unique_type_id.push_str(inner_type_id.as_slice());
392             },
393             ty::ty_ptr(ty::mt { ty: inner_type, mutbl } ) => {
394                 unique_type_id.push('*');
395                 if mutbl == ast::MutMutable {
396                     unique_type_id.push_str("mut");
397                 }
398
399                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
400                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
401                 unique_type_id.push_str(inner_type_id.as_slice());
402             },
403             ty::ty_rptr(_, ty::mt { ty: inner_type, mutbl }) => {
404                 unique_type_id.push('&');
405                 if mutbl == ast::MutMutable {
406                     unique_type_id.push_str("mut");
407                 }
408
409                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
410                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
411                 unique_type_id.push_str(inner_type_id.as_slice());
412             },
413             ty::ty_vec(inner_type, optional_length) => {
414                 match optional_length {
415                     Some(len) => {
416                         unique_type_id.push_str(format!("[{}]", len).as_slice());
417                     }
418                     None => {
419                         unique_type_id.push_str("[]");
420                     }
421                 };
422
423                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
424                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
425                 unique_type_id.push_str(inner_type_id.as_slice());
426             },
427             ty::ty_trait(ref trait_data) => {
428                 unique_type_id.push_str("trait ");
429
430                 from_def_id_and_substs(self,
431                                        cx,
432                                        trait_data.principal.def_id,
433                                        &trait_data.principal.substs,
434                                        &mut unique_type_id);
435             },
436             ty::ty_bare_fn(ty::BareFnTy{ fn_style, abi, ref sig } ) => {
437                 if fn_style == ast::UnsafeFn {
438                     unique_type_id.push_str("unsafe ");
439                 }
440
441                 unique_type_id.push_str(abi.name());
442
443                 unique_type_id.push_str(" fn(");
444
445                 for &parameter_type in sig.inputs.iter() {
446                     let parameter_type_id =
447                         self.get_unique_type_id_of_type(cx, parameter_type);
448                     let parameter_type_id =
449                         self.get_unique_type_id_as_string(parameter_type_id);
450                     unique_type_id.push_str(parameter_type_id.as_slice());
451                     unique_type_id.push(',');
452                 }
453
454                 if sig.variadic {
455                     unique_type_id.push_str("...");
456                 }
457
458                 unique_type_id.push_str(")->");
459                 match sig.output {
460                     ty::FnConverging(ret_ty) => {
461                         let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
462                         let return_type_id = self.get_unique_type_id_as_string(return_type_id);
463                         unique_type_id.push_str(return_type_id.as_slice());
464                     }
465                     ty::FnDiverging => {
466                         unique_type_id.push_str("!");
467                     }
468                 }
469             },
470             ty::ty_closure(box ref closure_ty) => {
471                 self.get_unique_type_id_of_closure_type(cx,
472                                                         closure_ty.clone(),
473                                                         &mut unique_type_id);
474             },
475             ty::ty_unboxed_closure(ref def_id, _, ref substs) => {
476                 let closure_ty = cx.tcx().unboxed_closures.borrow()
477                                    .get(def_id).unwrap().closure_type.subst(cx.tcx(), substs);
478                 self.get_unique_type_id_of_closure_type(cx,
479                                                         closure_ty,
480                                                         &mut unique_type_id);
481             },
482             _ => {
483                 cx.sess().bug(format!("get_unique_type_id_of_type() - unexpected type: {}, {}",
484                                       ppaux::ty_to_string(cx.tcx(), type_).as_slice(),
485                                       type_.sty).as_slice())
486             }
487         };
488
489         unique_type_id.push('}');
490
491         // Trim to size before storing permanently
492         unique_type_id.shrink_to_fit();
493
494         let key = self.unique_id_interner.intern(Rc::new(unique_type_id));
495         self.type_to_unique_id.insert(type_, UniqueTypeId(key));
496
497         return UniqueTypeId(key);
498
499         fn from_def_id_and_substs<'a, 'tcx>(type_map: &mut TypeMap<'tcx>,
500                                             cx: &CrateContext<'a, 'tcx>,
501                                             def_id: ast::DefId,
502                                             substs: &subst::Substs<'tcx>,
503                                             output: &mut String) {
504             // First, find out the 'real' def_id of the type. Items inlined from
505             // other crates have to be mapped back to their source.
506             let source_def_id = if def_id.krate == ast::LOCAL_CRATE {
507                 match cx.external_srcs().borrow().get(&def_id.node).cloned() {
508                     Some(source_def_id) => {
509                         // The given def_id identifies the inlined copy of a
510                         // type definition, let's take the source of the copy.
511                         source_def_id
512                     }
513                     None => def_id
514                 }
515             } else {
516                 def_id
517             };
518
519             // Get the crate hash as first part of the identifier.
520             let crate_hash = if source_def_id.krate == ast::LOCAL_CRATE {
521                 cx.link_meta().crate_hash.clone()
522             } else {
523                 cx.sess().cstore.get_crate_hash(source_def_id.krate)
524             };
525
526             output.push_str(crate_hash.as_str());
527             output.push_str("/");
528             output.push_str(format!("{:x}", def_id.node).as_slice());
529
530             // Maybe check that there is no self type here.
531
532             let tps = substs.types.get_slice(subst::TypeSpace);
533             if tps.len() > 0 {
534                 output.push('<');
535
536                 for &type_parameter in tps.iter() {
537                     let param_type_id =
538                         type_map.get_unique_type_id_of_type(cx, type_parameter);
539                     let param_type_id =
540                         type_map.get_unique_type_id_as_string(param_type_id);
541                     output.push_str(param_type_id.as_slice());
542                     output.push(',');
543                 }
544
545                 output.push('>');
546             }
547         }
548     }
549
550     fn get_unique_type_id_of_closure_type<'a>(&mut self,
551                                               cx: &CrateContext<'a, 'tcx>,
552                                               closure_ty: ty::ClosureTy<'tcx>,
553                                               unique_type_id: &mut String) {
554         let ty::ClosureTy { fn_style,
555                             onceness,
556                             store,
557                             ref bounds,
558                             ref sig,
559                             abi: _ } = closure_ty;
560         if fn_style == ast::UnsafeFn {
561             unique_type_id.push_str("unsafe ");
562         }
563
564         if onceness == ast::Once {
565             unique_type_id.push_str("once ");
566         }
567
568         match store {
569             ty::UniqTraitStore => unique_type_id.push_str("~|"),
570             ty::RegionTraitStore(_, ast::MutMutable) => {
571                 unique_type_id.push_str("&mut|")
572             }
573             ty::RegionTraitStore(_, ast::MutImmutable) => {
574                 unique_type_id.push_str("&|")
575             }
576         };
577
578         for &parameter_type in sig.inputs.iter() {
579             let parameter_type_id =
580                 self.get_unique_type_id_of_type(cx, parameter_type);
581             let parameter_type_id =
582                 self.get_unique_type_id_as_string(parameter_type_id);
583             unique_type_id.push_str(parameter_type_id.as_slice());
584             unique_type_id.push(',');
585         }
586
587         if sig.variadic {
588             unique_type_id.push_str("...");
589         }
590
591         unique_type_id.push_str("|->");
592
593         match sig.output {
594             ty::FnConverging(ret_ty) => {
595                 let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
596                 let return_type_id = self.get_unique_type_id_as_string(return_type_id);
597                 unique_type_id.push_str(return_type_id.as_slice());
598             }
599             ty::FnDiverging => {
600                 unique_type_id.push_str("!");
601             }
602         }
603
604         unique_type_id.push(':');
605
606         for bound in bounds.builtin_bounds.iter() {
607             match bound {
608                 ty::BoundSend => unique_type_id.push_str("Send"),
609                 ty::BoundSized => unique_type_id.push_str("Sized"),
610                 ty::BoundCopy => unique_type_id.push_str("Copy"),
611                 ty::BoundSync => unique_type_id.push_str("Sync"),
612             };
613             unique_type_id.push('+');
614         }
615     }
616
617     // Get the UniqueTypeId for an enum variant. Enum variants are not really
618     // types of their own, so they need special handling. We still need a
619     // UniqueTypeId for them, since to debuginfo they *are* real types.
620     fn get_unique_type_id_of_enum_variant<'a>(&mut self,
621                                               cx: &CrateContext<'a, 'tcx>,
622                                               enum_type: Ty<'tcx>,
623                                               variant_name: &str)
624                                               -> UniqueTypeId {
625         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
626         let enum_variant_type_id = format!("{}::{}",
627                                            self.get_unique_type_id_as_string(enum_type_id)
628                                                .as_slice(),
629                                            variant_name);
630         let interner_key = self.unique_id_interner.intern(Rc::new(enum_variant_type_id));
631         UniqueTypeId(interner_key)
632     }
633 }
634
635 // Returns from the enclosing function if the type metadata with the given
636 // unique id can be found in the type map
637 macro_rules! return_if_metadata_created_in_meantime(
638     ($cx: expr, $unique_type_id: expr) => (
639         match debug_context($cx).type_map
640                                 .borrow()
641                                 .find_metadata_for_unique_id($unique_type_id) {
642             Some(metadata) => return MetadataCreationResult::new(metadata, true),
643             None => { /* proceed normally */ }
644         };
645     )
646 )
647
648
649 /// A context object for maintaining all state needed by the debuginfo module.
650 pub struct CrateDebugContext<'tcx> {
651     llcontext: ContextRef,
652     builder: DIBuilderRef,
653     current_debug_location: Cell<DebugLocation>,
654     created_files: RefCell<FnvHashMap<String, DIFile>>,
655     created_enum_disr_types: RefCell<DefIdMap<DIType>>,
656
657     type_map: RefCell<TypeMap<'tcx>>,
658     namespace_map: RefCell<FnvHashMap<Vec<ast::Name>, Rc<NamespaceTreeNode>>>,
659
660     // This collection is used to assert that composite types (structs, enums,
661     // ...) have their members only set once:
662     composite_types_completed: RefCell<FnvHashSet<DIType>>,
663 }
664
665 impl<'tcx> CrateDebugContext<'tcx> {
666     pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
667         debug!("CrateDebugContext::new");
668         let builder = unsafe { llvm::LLVMDIBuilderCreate(llmod) };
669         // DIBuilder inherits context from the module, so we'd better use the same one
670         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
671         return CrateDebugContext {
672             llcontext: llcontext,
673             builder: builder,
674             current_debug_location: Cell::new(UnknownLocation),
675             created_files: RefCell::new(FnvHashMap::new()),
676             created_enum_disr_types: RefCell::new(DefIdMap::new()),
677             type_map: RefCell::new(TypeMap::new()),
678             namespace_map: RefCell::new(FnvHashMap::new()),
679             composite_types_completed: RefCell::new(FnvHashSet::new()),
680         };
681     }
682 }
683
684 pub struct FunctionDebugContext {
685     repr: FunctionDebugContextRepr,
686 }
687
688 enum FunctionDebugContextRepr {
689     DebugInfo(Box<FunctionDebugContextData>),
690     DebugInfoDisabled,
691     FunctionWithoutDebugInfo,
692 }
693
694 impl FunctionDebugContext {
695     fn get_ref<'a>(&'a self,
696                    cx: &CrateContext,
697                    span: Span)
698                    -> &'a FunctionDebugContextData {
699         match self.repr {
700             DebugInfo(box ref data) => data,
701             DebugInfoDisabled => {
702                 cx.sess().span_bug(span,
703                                    FunctionDebugContext::debuginfo_disabled_message());
704             }
705             FunctionWithoutDebugInfo => {
706                 cx.sess().span_bug(span,
707                                    FunctionDebugContext::should_be_ignored_message());
708             }
709         }
710     }
711
712     fn debuginfo_disabled_message() -> &'static str {
713         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
714     }
715
716     fn should_be_ignored_message() -> &'static str {
717         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
718          ignored by debug info!"
719     }
720 }
721
722 struct FunctionDebugContextData {
723     scope_map: RefCell<NodeMap<DIScope>>,
724     fn_metadata: DISubprogram,
725     argument_counter: Cell<uint>,
726     source_locations_enabled: Cell<bool>,
727 }
728
729 enum VariableAccess<'a> {
730     // The llptr given is an alloca containing the variable's value
731     DirectVariable { alloca: ValueRef },
732     // The llptr given is an alloca containing the start of some pointer chain
733     // leading to the variable's content.
734     IndirectVariable { alloca: ValueRef, address_operations: &'a [ValueRef] }
735 }
736
737 enum VariableKind {
738     ArgumentVariable(uint /*index*/),
739     LocalVariable,
740     CapturedVariable,
741 }
742
743 /// Create any deferred debug metadata nodes
744 pub fn finalize(cx: &CrateContext) {
745     if cx.dbg_cx().is_none() {
746         return;
747     }
748
749     debug!("finalize");
750     compile_unit_metadata(cx);
751     unsafe {
752         llvm::LLVMDIBuilderFinalize(DIB(cx));
753         llvm::LLVMDIBuilderDispose(DIB(cx));
754         // Debuginfo generation in LLVM by default uses a higher
755         // version of dwarf than OS X currently understands. We can
756         // instruct LLVM to emit an older version of dwarf, however,
757         // for OS X to understand. For more info see #11352
758         // This can be overridden using --llvm-opts -dwarf-version,N.
759         if cx.sess().target.target.options.is_like_osx {
760             "Dwarf Version".with_c_str(
761                 |s| llvm::LLVMRustAddModuleFlag(cx.llmod(), s, 2));
762         }
763
764         // Prevent bitcode readers from deleting the debug info.
765         "Debug Info Version".with_c_str(
766             |s| llvm::LLVMRustAddModuleFlag(cx.llmod(), s,
767                                             llvm::LLVMRustDebugMetadataVersion));
768     };
769 }
770
771 /// Creates debug information for the given global variable.
772 ///
773 /// Adds the created metadata nodes directly to the crate's IR.
774 pub fn create_global_var_metadata(cx: &CrateContext,
775                                   node_id: ast::NodeId,
776                                   global: ValueRef) {
777     if cx.dbg_cx().is_none() {
778         return;
779     }
780
781     // Don't create debuginfo for globals inlined from other crates. The other
782     // crate should already contain debuginfo for it. More importantly, the
783     // global might not even exist in un-inlined form anywhere which would lead
784     // to a linker errors.
785     if cx.external_srcs().borrow().contains_key(&node_id) {
786         return;
787     }
788
789     let var_item = cx.tcx().map.get(node_id);
790
791     let (ident, span) = match var_item {
792         ast_map::NodeItem(item) => {
793             match item.node {
794                 ast::ItemStatic(..) => (item.ident, item.span),
795                 ast::ItemConst(..) => (item.ident, item.span),
796                 _ => {
797                     cx.sess()
798                       .span_bug(item.span,
799                                 format!("debuginfo::\
800                                          create_global_var_metadata() -
801                                          Captured var-id refers to \
802                                          unexpected ast_item variant: {}",
803                                         var_item).as_slice())
804                 }
805             }
806         },
807         _ => cx.sess().bug(format!("debuginfo::create_global_var_metadata() \
808                                     - Captured var-id refers to unexpected \
809                                     ast_map variant: {}",
810                                    var_item).as_slice())
811     };
812
813     let (file_metadata, line_number) = if span != codemap::DUMMY_SP {
814         let loc = span_start(cx, span);
815         (file_metadata(cx, loc.file.name.as_slice()), loc.line as c_uint)
816     } else {
817         (UNKNOWN_FILE_METADATA, UNKNOWN_LINE_NUMBER)
818     };
819
820     let is_local_to_unit = is_node_local_to_unit(cx, node_id);
821     let variable_type = ty::node_id_to_type(cx.tcx(), node_id);
822     let type_metadata = type_metadata(cx, variable_type, span);
823     let namespace_node = namespace_for_item(cx, ast_util::local_def(node_id));
824     let var_name = token::get_ident(ident).get().to_string();
825     let linkage_name =
826         namespace_node.mangled_name_of_contained_item(var_name.as_slice());
827     let var_scope = namespace_node.scope;
828
829     var_name.with_c_str(|var_name| {
830         linkage_name.with_c_str(|linkage_name| {
831             unsafe {
832                 llvm::LLVMDIBuilderCreateStaticVariable(DIB(cx),
833                                                         var_scope,
834                                                         var_name,
835                                                         linkage_name,
836                                                         file_metadata,
837                                                         line_number,
838                                                         type_metadata,
839                                                         is_local_to_unit,
840                                                         global,
841                                                         ptr::null_mut());
842             }
843         })
844     });
845 }
846
847 /// Creates debug information for the given local variable.
848 ///
849 /// Adds the created metadata nodes directly to the crate's IR.
850 pub fn create_local_var_metadata(bcx: Block, local: &ast::Local) {
851     if fn_should_be_ignored(bcx.fcx) {
852         return;
853     }
854
855     let cx = bcx.ccx();
856     let def_map = &cx.tcx().def_map;
857
858     pat_util::pat_bindings(def_map, &*local.pat, |_, node_id, span, path1| {
859         let var_ident = path1.node;
860
861         let datum = match bcx.fcx.lllocals.borrow().get(&node_id).cloned() {
862             Some(datum) => datum,
863             None => {
864                 bcx.sess().span_bug(span,
865                     format!("no entry in lllocals table for {}",
866                             node_id).as_slice());
867             }
868         };
869
870         let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
871
872         declare_local(bcx,
873                       var_ident,
874                       datum.ty,
875                       scope_metadata,
876                       DirectVariable { alloca: datum.val },
877                       LocalVariable,
878                       span);
879     })
880 }
881
882 /// Creates debug information for a variable captured in a closure.
883 ///
884 /// Adds the created metadata nodes directly to the crate's IR.
885 pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
886                                                 node_id: ast::NodeId,
887                                                 env_data_type: Ty<'tcx>,
888                                                 env_pointer: ValueRef,
889                                                 env_index: uint,
890                                                 captured_by_ref: bool,
891                                                 span: Span) {
892     if fn_should_be_ignored(bcx.fcx) {
893         return;
894     }
895
896     let cx = bcx.ccx();
897
898     let ast_item = cx.tcx().map.find(node_id);
899
900     let variable_ident = match ast_item {
901         None => {
902             cx.sess().span_bug(span, "debuginfo::create_captured_var_metadata: node not found");
903         }
904         Some(ast_map::NodeLocal(pat)) | Some(ast_map::NodeArg(pat)) => {
905             match pat.node {
906                 ast::PatIdent(_, ref path1, _) => {
907                     path1.node
908                 }
909                 _ => {
910                     cx.sess()
911                       .span_bug(span,
912                                 format!(
913                                 "debuginfo::create_captured_var_metadata() - \
914                                  Captured var-id refers to unexpected \
915                                  ast_map variant: {}",
916                                  ast_item).as_slice());
917                 }
918             }
919         }
920         _ => {
921             cx.sess()
922               .span_bug(span,
923                         format!("debuginfo::create_captured_var_metadata() - \
924                                  Captured var-id refers to unexpected \
925                                  ast_map variant: {}",
926                                 ast_item).as_slice());
927         }
928     };
929
930     let variable_type = node_id_type(bcx, node_id);
931     let scope_metadata = bcx.fcx.debug_context.get_ref(cx, span).fn_metadata;
932
933     let llvm_env_data_type = type_of::type_of(cx, env_data_type);
934     let byte_offset_of_var_in_env = machine::llelement_offset(cx,
935                                                               llvm_env_data_type,
936                                                               env_index);
937
938     let address_operations = unsafe {
939         [llvm::LLVMDIBuilderCreateOpDeref(Type::i64(cx).to_ref()),
940          llvm::LLVMDIBuilderCreateOpPlus(Type::i64(cx).to_ref()),
941          C_i64(cx, byte_offset_of_var_in_env as i64),
942          llvm::LLVMDIBuilderCreateOpDeref(Type::i64(cx).to_ref())]
943     };
944
945     let address_op_count = if captured_by_ref {
946         address_operations.len()
947     } else {
948         address_operations.len() - 1
949     };
950
951     let variable_access = IndirectVariable {
952         alloca: env_pointer,
953         address_operations: address_operations[..address_op_count]
954     };
955
956     declare_local(bcx,
957                   variable_ident,
958                   variable_type,
959                   scope_metadata,
960                   variable_access,
961                   CapturedVariable,
962                   span);
963 }
964
965 /// Creates debug information for a local variable introduced in the head of a
966 /// match-statement arm.
967 ///
968 /// Adds the created metadata nodes directly to the crate's IR.
969 pub fn create_match_binding_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
970                                                  variable_ident: ast::Ident,
971                                                  binding: BindingInfo<'tcx>) {
972     if fn_should_be_ignored(bcx.fcx) {
973         return;
974     }
975
976     let scope_metadata = scope_metadata(bcx.fcx, binding.id, binding.span);
977     let aops = unsafe {
978         [llvm::LLVMDIBuilderCreateOpDeref(bcx.ccx().int_type().to_ref())]
979     };
980     // Regardless of the actual type (`T`) we're always passed the stack slot (alloca)
981     // for the binding. For ByRef bindings that's a `T*` but for ByMove bindings we
982     // actually have `T**`. So to get the actual variable we need to dereference once
983     // more. For ByCopy we just use the stack slot we created for the binding.
984     let var_type = match binding.trmode {
985         TrByCopy(llbinding) => DirectVariable {
986             alloca: llbinding
987         },
988         TrByMove => IndirectVariable {
989             alloca: binding.llmatch,
990             address_operations: &aops
991         },
992         TrByRef => DirectVariable {
993             alloca: binding.llmatch
994         }
995     };
996
997     declare_local(bcx,
998                   variable_ident,
999                   binding.ty,
1000                   scope_metadata,
1001                   var_type,
1002                   LocalVariable,
1003                   binding.span);
1004 }
1005
1006 /// Creates debug information for the given function argument.
1007 ///
1008 /// Adds the created metadata nodes directly to the crate's IR.
1009 pub fn create_argument_metadata(bcx: Block, arg: &ast::Arg) {
1010     if fn_should_be_ignored(bcx.fcx) {
1011         return;
1012     }
1013
1014     let fcx = bcx.fcx;
1015     let cx = fcx.ccx;
1016
1017     let def_map = &cx.tcx().def_map;
1018     let scope_metadata = bcx.fcx.debug_context.get_ref(cx, arg.pat.span).fn_metadata;
1019
1020     pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, span, path1| {
1021         let llarg = match bcx.fcx.lllocals.borrow().get(&node_id).cloned() {
1022             Some(v) => v,
1023             None => {
1024                 bcx.sess().span_bug(span,
1025                     format!("no entry in lllocals table for {}",
1026                             node_id).as_slice());
1027             }
1028         };
1029
1030         if unsafe { llvm::LLVMIsAAllocaInst(llarg.val) } == ptr::null_mut() {
1031             cx.sess().span_bug(span, "debuginfo::create_argument_metadata() - \
1032                                     Referenced variable location is not an alloca!");
1033         }
1034
1035         let argument_index = {
1036             let counter = &fcx.debug_context.get_ref(cx, span).argument_counter;
1037             let argument_index = counter.get();
1038             counter.set(argument_index + 1);
1039             argument_index
1040         };
1041
1042         declare_local(bcx,
1043                       path1.node,
1044                       llarg.ty,
1045                       scope_metadata,
1046                       DirectVariable { alloca: llarg.val },
1047                       ArgumentVariable(argument_index),
1048                       span);
1049     })
1050 }
1051
1052 pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1053                                                     node_id: ast::NodeId,
1054                                                     node_span: Span,
1055                                                     is_block: bool)
1056                                                  -> NodeInfo {
1057     // A debug location needs two things:
1058     // (1) A span (of which only the beginning will actually be used)
1059     // (2) An AST node-id which will be used to look up the lexical scope
1060     //     for the location in the functions scope-map
1061     //
1062     // This function will calculate the debug location for compiler-generated
1063     // cleanup calls that are executed when control-flow leaves the
1064     // scope identified by `node_id`.
1065     //
1066     // For everything but block-like things we can simply take id and span of
1067     // the given expression, meaning that from a debugger's view cleanup code is
1068     // executed at the same source location as the statement/expr itself.
1069     //
1070     // Blocks are a special case. Here we want the cleanup to be linked to the
1071     // closing curly brace of the block. The *scope* the cleanup is executed in
1072     // is up to debate: It could either still be *within* the block being
1073     // cleaned up, meaning that locals from the block are still visible in the
1074     // debugger.
1075     // Or it could be in the scope that the block is contained in, so any locals
1076     // from within the block are already considered out-of-scope and thus not
1077     // accessible in the debugger anymore.
1078     //
1079     // The current implementation opts for the second option: cleanup of a block
1080     // already happens in the parent scope of the block. The main reason for
1081     // this decision is that scoping becomes controlflow dependent when variable
1082     // shadowing is involved and it's impossible to decide statically which
1083     // scope is actually left when the cleanup code is executed.
1084     // In practice it shouldn't make much of a difference.
1085
1086     let mut cleanup_span = node_span;
1087
1088     if is_block {
1089         // Not all blocks actually have curly braces (e.g. simple closure
1090         // bodies), in which case we also just want to return the span of the
1091         // whole expression.
1092         let code_snippet = cx.sess().codemap().span_to_snippet(node_span);
1093         if let Some(code_snippet) = code_snippet {
1094             let bytes = code_snippet.as_bytes();
1095
1096             if bytes.len() > 0 && bytes[bytes.len()-1 ..] == b"}" {
1097                 cleanup_span = Span {
1098                     lo: node_span.hi - codemap::BytePos(1),
1099                     hi: node_span.hi,
1100                     expn_id: node_span.expn_id
1101                 };
1102             }
1103         }
1104     }
1105
1106     NodeInfo {
1107         id: node_id,
1108         span: cleanup_span
1109     }
1110 }
1111
1112 /// Sets the current debug location at the beginning of the span.
1113 ///
1114 /// Maps to a call to llvm::LLVMSetCurrentDebugLocation(...). The node_id
1115 /// parameter is used to reliably find the correct visibility scope for the code
1116 /// position.
1117 pub fn set_source_location(fcx: &FunctionContext,
1118                            node_id: ast::NodeId,
1119                            span: Span) {
1120     match fcx.debug_context.repr {
1121         DebugInfoDisabled => return,
1122         FunctionWithoutDebugInfo => {
1123             set_debug_location(fcx.ccx, UnknownLocation);
1124             return;
1125         }
1126         DebugInfo(box ref function_debug_context) => {
1127             let cx = fcx.ccx;
1128
1129             debug!("set_source_location: {}", cx.sess().codemap().span_to_string(span));
1130
1131             if function_debug_context.source_locations_enabled.get() {
1132                 let loc = span_start(cx, span);
1133                 let scope = scope_metadata(fcx, node_id, span);
1134
1135                 set_debug_location(cx, DebugLocation::new(scope,
1136                                                           loc.line,
1137                                                           loc.col.to_uint()));
1138             } else {
1139                 set_debug_location(cx, UnknownLocation);
1140             }
1141         }
1142     }
1143 }
1144
1145 /// Clears the current debug location.
1146 ///
1147 /// Instructions generated hereafter won't be assigned a source location.
1148 pub fn clear_source_location(fcx: &FunctionContext) {
1149     if fn_should_be_ignored(fcx) {
1150         return;
1151     }
1152
1153     set_debug_location(fcx.ccx, UnknownLocation);
1154 }
1155
1156 /// Enables emitting source locations for the given functions.
1157 ///
1158 /// Since we don't want source locations to be emitted for the function prelude,
1159 /// they are disabled when beginning to translate a new function. This functions
1160 /// switches source location emitting on and must therefore be called before the
1161 /// first real statement/expression of the function is translated.
1162 pub fn start_emitting_source_locations(fcx: &FunctionContext) {
1163     match fcx.debug_context.repr {
1164         DebugInfo(box ref data) => {
1165             data.source_locations_enabled.set(true)
1166         },
1167         _ => { /* safe to ignore */ }
1168     }
1169 }
1170
1171 /// Creates the function-specific debug context.
1172 ///
1173 /// Returns the FunctionDebugContext for the function which holds state needed
1174 /// for debug info creation. The function may also return another variant of the
1175 /// FunctionDebugContext enum which indicates why no debuginfo should be created
1176 /// for the function.
1177 pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1178                                                fn_ast_id: ast::NodeId,
1179                                                param_substs: &Substs<'tcx>,
1180                                                llfn: ValueRef) -> FunctionDebugContext {
1181     if cx.sess().opts.debuginfo == NoDebugInfo {
1182         return FunctionDebugContext { repr: DebugInfoDisabled };
1183     }
1184
1185     // Clear the debug location so we don't assign them in the function prelude.
1186     // Do this here already, in case we do an early exit from this function.
1187     set_debug_location(cx, UnknownLocation);
1188
1189     if fn_ast_id == ast::DUMMY_NODE_ID {
1190         // This is a function not linked to any source location, so don't
1191         // generate debuginfo for it.
1192         return FunctionDebugContext { repr: FunctionWithoutDebugInfo };
1193     }
1194
1195     let empty_generics = ast_util::empty_generics();
1196
1197     let fnitem = cx.tcx().map.get(fn_ast_id);
1198
1199     let (ident, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
1200         ast_map::NodeItem(ref item) => {
1201             if contains_nodebug_attribute(item.attrs.as_slice()) {
1202                 return FunctionDebugContext { repr: FunctionWithoutDebugInfo };
1203             }
1204
1205             match item.node {
1206                 ast::ItemFn(ref fn_decl, _, _, ref generics, ref top_level_block) => {
1207                     (item.ident, &**fn_decl, generics, &**top_level_block, item.span, true)
1208                 }
1209                 _ => {
1210                     cx.sess().span_bug(item.span,
1211                         "create_function_debug_context: item bound to non-function");
1212                 }
1213             }
1214         }
1215         ast_map::NodeImplItem(ref item) => {
1216             match **item {
1217                 ast::MethodImplItem(ref method) => {
1218                     if contains_nodebug_attribute(method.attrs.as_slice()) {
1219                         return FunctionDebugContext {
1220                             repr: FunctionWithoutDebugInfo
1221                         };
1222                     }
1223
1224                     (method.pe_ident(),
1225                      method.pe_fn_decl(),
1226                      method.pe_generics(),
1227                      method.pe_body(),
1228                      method.span,
1229                      true)
1230                 }
1231                 ast::TypeImplItem(ref typedef) => {
1232                     cx.sess().span_bug(typedef.span,
1233                                        "create_function_debug_context() \
1234                                         called on associated type?!")
1235                 }
1236             }
1237         }
1238         ast_map::NodeExpr(ref expr) => {
1239             match expr.node {
1240                 ast::ExprProc(ref fn_decl, ref top_level_block) |
1241                 ast::ExprClosure(_, _, ref fn_decl, ref top_level_block) => {
1242                     let name = format!("fn{}", token::gensym("fn"));
1243                     let name = token::str_to_ident(name.as_slice());
1244                     (name, &**fn_decl,
1245                         // This is not quite right. It should actually inherit
1246                         // the generics of the enclosing function.
1247                         &empty_generics,
1248                         &**top_level_block,
1249                         expr.span,
1250                         // Don't try to lookup the item path:
1251                         false)
1252                 }
1253                 _ => cx.sess().span_bug(expr.span,
1254                         "create_function_debug_context: expected an expr_fn_block here")
1255             }
1256         }
1257         ast_map::NodeTraitItem(ref trait_method) => {
1258             match **trait_method {
1259                 ast::ProvidedMethod(ref method) => {
1260                     if contains_nodebug_attribute(method.attrs.as_slice()) {
1261                         return FunctionDebugContext {
1262                             repr: FunctionWithoutDebugInfo
1263                         };
1264                     }
1265
1266                     (method.pe_ident(),
1267                      method.pe_fn_decl(),
1268                      method.pe_generics(),
1269                      method.pe_body(),
1270                      method.span,
1271                      true)
1272                 }
1273                 _ => {
1274                     cx.sess()
1275                       .bug(format!("create_function_debug_context: \
1276                                     unexpected sort of node: {}",
1277                                     fnitem).as_slice())
1278                 }
1279             }
1280         }
1281         ast_map::NodeForeignItem(..) |
1282         ast_map::NodeVariant(..) |
1283         ast_map::NodeStructCtor(..) => {
1284             return FunctionDebugContext { repr: FunctionWithoutDebugInfo };
1285         }
1286         _ => cx.sess().bug(format!("create_function_debug_context: \
1287                                     unexpected sort of node: {}",
1288                                    fnitem).as_slice())
1289     };
1290
1291     // This can be the case for functions inlined from another crate
1292     if span == codemap::DUMMY_SP {
1293         return FunctionDebugContext { repr: FunctionWithoutDebugInfo };
1294     }
1295
1296     let loc = span_start(cx, span);
1297     let file_metadata = file_metadata(cx, loc.file.name.as_slice());
1298
1299     let function_type_metadata = unsafe {
1300         let fn_signature = get_function_signature(cx,
1301                                                   fn_ast_id,
1302                                                   &*fn_decl,
1303                                                   param_substs,
1304                                                   span);
1305         llvm::LLVMDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
1306     };
1307
1308     // Get_template_parameters() will append a `<...>` clause to the function
1309     // name if necessary.
1310     let mut function_name = String::from_str(token::get_ident(ident).get());
1311     let template_parameters = get_template_parameters(cx,
1312                                                       generics,
1313                                                       param_substs,
1314                                                       file_metadata,
1315                                                       &mut function_name);
1316
1317     // There is no ast_map::Path for ast::ExprClosure-type functions. For now,
1318     // just don't put them into a namespace. In the future this could be improved
1319     // somehow (storing a path in the ast_map, or construct a path using the
1320     // enclosing function).
1321     let (linkage_name, containing_scope) = if has_path {
1322         let namespace_node = namespace_for_item(cx, ast_util::local_def(fn_ast_id));
1323         let linkage_name = namespace_node.mangled_name_of_contained_item(
1324             function_name.as_slice());
1325         let containing_scope = namespace_node.scope;
1326         (linkage_name, containing_scope)
1327     } else {
1328         (function_name.clone(), file_metadata)
1329     };
1330
1331     // Clang sets this parameter to the opening brace of the function's block,
1332     // so let's do this too.
1333     let scope_line = span_start(cx, top_level_block.span).line;
1334
1335     let is_local_to_unit = is_node_local_to_unit(cx, fn_ast_id);
1336
1337     let fn_metadata = function_name.with_c_str(|function_name| {
1338                           linkage_name.with_c_str(|linkage_name| {
1339             unsafe {
1340                 llvm::LLVMDIBuilderCreateFunction(
1341                     DIB(cx),
1342                     containing_scope,
1343                     function_name,
1344                     linkage_name,
1345                     file_metadata,
1346                     loc.line as c_uint,
1347                     function_type_metadata,
1348                     is_local_to_unit,
1349                     true,
1350                     scope_line as c_uint,
1351                     FlagPrototyped as c_uint,
1352                     cx.sess().opts.optimize != config::No,
1353                     llfn,
1354                     template_parameters,
1355                     ptr::null_mut())
1356             }
1357         })
1358     });
1359
1360     // Initialize fn debug context (including scope map and namespace map)
1361     let fn_debug_context = box FunctionDebugContextData {
1362         scope_map: RefCell::new(NodeMap::new()),
1363         fn_metadata: fn_metadata,
1364         argument_counter: Cell::new(1),
1365         source_locations_enabled: Cell::new(false),
1366     };
1367
1368     populate_scope_map(cx,
1369                        fn_decl.inputs.as_slice(),
1370                        &*top_level_block,
1371                        fn_metadata,
1372                        fn_ast_id,
1373                        &mut *fn_debug_context.scope_map.borrow_mut());
1374
1375     return FunctionDebugContext { repr: DebugInfo(fn_debug_context) };
1376
1377     fn get_function_signature<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1378                                         fn_ast_id: ast::NodeId,
1379                                         fn_decl: &ast::FnDecl,
1380                                         param_substs: &Substs<'tcx>,
1381                                         error_reporting_span: Span) -> DIArray {
1382         if cx.sess().opts.debuginfo == LimitedDebugInfo {
1383             return create_DIArray(DIB(cx), &[]);
1384         }
1385
1386         let mut signature = Vec::with_capacity(fn_decl.inputs.len() + 1);
1387
1388         // Return type -- llvm::DIBuilder wants this at index 0
1389         match fn_decl.output {
1390             ast::Return(ref ret_ty) if ret_ty.node == ast::TyTup(vec![]) =>
1391                 signature.push(ptr::null_mut()),
1392             _ => {
1393                 assert_type_for_node_id(cx, fn_ast_id, error_reporting_span);
1394
1395                 let return_type = ty::node_id_to_type(cx.tcx(), fn_ast_id);
1396                 let return_type = return_type.subst(cx.tcx(), param_substs);
1397                 signature.push(type_metadata(cx, return_type, codemap::DUMMY_SP));
1398             }
1399         }
1400
1401         // Arguments types
1402         for arg in fn_decl.inputs.iter() {
1403             assert_type_for_node_id(cx, arg.pat.id, arg.pat.span);
1404             let arg_type = ty::node_id_to_type(cx.tcx(), arg.pat.id);
1405             let arg_type = arg_type.subst(cx.tcx(), param_substs);
1406             signature.push(type_metadata(cx, arg_type, codemap::DUMMY_SP));
1407         }
1408
1409         return create_DIArray(DIB(cx), signature.as_slice());
1410     }
1411
1412     fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1413                                          generics: &ast::Generics,
1414                                          param_substs: &Substs<'tcx>,
1415                                          file_metadata: DIFile,
1416                                          name_to_append_suffix_to: &mut String)
1417                                          -> DIArray {
1418         let self_type = param_substs.self_ty();
1419
1420         // Only true for static default methods:
1421         let has_self_type = self_type.is_some();
1422
1423         if !generics.is_type_parameterized() && !has_self_type {
1424             return create_DIArray(DIB(cx), &[]);
1425         }
1426
1427         name_to_append_suffix_to.push('<');
1428
1429         // The list to be filled with template parameters:
1430         let mut template_params: Vec<DIDescriptor> =
1431             Vec::with_capacity(generics.ty_params.len() + 1);
1432
1433         // Handle self type
1434         if has_self_type {
1435             let actual_self_type = self_type.unwrap();
1436             // Add self type name to <...> clause of function name
1437             let actual_self_type_name = compute_debuginfo_type_name(
1438                 cx,
1439                 actual_self_type,
1440                 true);
1441
1442             name_to_append_suffix_to.push_str(actual_self_type_name.as_slice());
1443
1444             if generics.is_type_parameterized() {
1445                 name_to_append_suffix_to.push_str(",");
1446             }
1447
1448             // Only create type information if full debuginfo is enabled
1449             if cx.sess().opts.debuginfo == FullDebugInfo {
1450                 let actual_self_type_metadata = type_metadata(cx,
1451                                                               actual_self_type,
1452                                                               codemap::DUMMY_SP);
1453
1454                 let ident = special_idents::type_self;
1455
1456                 let param_metadata = token::get_ident(ident).get()
1457                                                             .with_c_str(|name| {
1458                     unsafe {
1459                         llvm::LLVMDIBuilderCreateTemplateTypeParameter(
1460                             DIB(cx),
1461                             file_metadata,
1462                             name,
1463                             actual_self_type_metadata,
1464                             ptr::null_mut(),
1465                             0,
1466                             0)
1467                     }
1468                 });
1469
1470                 template_params.push(param_metadata);
1471             }
1472         }
1473
1474         // Handle other generic parameters
1475         let actual_types = param_substs.types.get_slice(subst::FnSpace);
1476         for (index, &ast::TyParam{ ident, .. }) in generics.ty_params.iter().enumerate() {
1477             let actual_type = actual_types[index];
1478             // Add actual type name to <...> clause of function name
1479             let actual_type_name = compute_debuginfo_type_name(cx,
1480                                                                actual_type,
1481                                                                true);
1482             name_to_append_suffix_to.push_str(actual_type_name.as_slice());
1483
1484             if index != generics.ty_params.len() - 1 {
1485                 name_to_append_suffix_to.push_str(",");
1486             }
1487
1488             // Again, only create type information if full debuginfo is enabled
1489             if cx.sess().opts.debuginfo == FullDebugInfo {
1490                 let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
1491                 let param_metadata = token::get_ident(ident).get()
1492                                                             .with_c_str(|name| {
1493                     unsafe {
1494                         llvm::LLVMDIBuilderCreateTemplateTypeParameter(
1495                             DIB(cx),
1496                             file_metadata,
1497                             name,
1498                             actual_type_metadata,
1499                             ptr::null_mut(),
1500                             0,
1501                             0)
1502                     }
1503                 });
1504                 template_params.push(param_metadata);
1505             }
1506         }
1507
1508         name_to_append_suffix_to.push('>');
1509
1510         return create_DIArray(DIB(cx), template_params.as_slice());
1511     }
1512 }
1513
1514 //=-----------------------------------------------------------------------------
1515 // Module-Internal debug info creation functions
1516 //=-----------------------------------------------------------------------------
1517
1518 fn is_node_local_to_unit(cx: &CrateContext, node_id: ast::NodeId) -> bool
1519 {
1520     // The is_local_to_unit flag indicates whether a function is local to the
1521     // current compilation unit (i.e. if it is *static* in the C-sense). The
1522     // *reachable* set should provide a good approximation of this, as it
1523     // contains everything that might leak out of the current crate (by being
1524     // externally visible or by being inlined into something externally visible).
1525     // It might better to use the `exported_items` set from `driver::CrateAnalysis`
1526     // in the future, but (atm) this set is not available in the translation pass.
1527     !cx.reachable().contains(&node_id)
1528 }
1529
1530 #[allow(non_snake_case)]
1531 fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray {
1532     return unsafe {
1533         llvm::LLVMDIBuilderGetOrCreateArray(builder, arr.as_ptr(), arr.len() as u32)
1534     };
1535 }
1536
1537 fn compile_unit_metadata(cx: &CrateContext) {
1538     let work_dir = &cx.sess().working_dir;
1539     let compile_unit_name = match cx.sess().local_crate_source_file {
1540         None => fallback_path(cx),
1541         Some(ref abs_path) => {
1542             if abs_path.is_relative() {
1543                 cx.sess().warn("debuginfo: Invalid path to crate's local root source file!");
1544                 fallback_path(cx)
1545             } else {
1546                 match abs_path.path_relative_from(work_dir) {
1547                     Some(ref p) if p.is_relative() => {
1548                             // prepend "./" if necessary
1549                             let dotdot = b"..";
1550                             let prefix = [dotdot[0], ::std::path::SEP_BYTE];
1551                             let mut path_bytes = p.as_vec().to_vec();
1552
1553                             if path_bytes.slice_to(2) != prefix &&
1554                                path_bytes.slice_to(2) != dotdot {
1555                                 path_bytes.insert(0, prefix[0]);
1556                                 path_bytes.insert(1, prefix[1]);
1557                             }
1558
1559                             path_bytes.to_c_str()
1560                         }
1561                     _ => fallback_path(cx)
1562                 }
1563             }
1564         }
1565     };
1566
1567     debug!("compile_unit_metadata: {}", compile_unit_name);
1568     let producer = format!("rustc version {}",
1569                            (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
1570
1571     let compile_unit_name = compile_unit_name.as_ptr();
1572     work_dir.as_vec().with_c_str(|work_dir| {
1573         producer.with_c_str(|producer| {
1574             "".with_c_str(|flags| {
1575                 "".with_c_str(|split_name| {
1576                     unsafe {
1577                         llvm::LLVMDIBuilderCreateCompileUnit(
1578                             debug_context(cx).builder,
1579                             DW_LANG_RUST,
1580                             compile_unit_name,
1581                             work_dir,
1582                             producer,
1583                             cx.sess().opts.optimize != config::No,
1584                             flags,
1585                             0,
1586                             split_name);
1587                     }
1588                 })
1589             })
1590         })
1591     });
1592
1593     fn fallback_path(cx: &CrateContext) -> CString {
1594         cx.link_meta().crate_name.to_c_str()
1595     }
1596 }
1597
1598 fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1599                              variable_ident: ast::Ident,
1600                              variable_type: Ty<'tcx>,
1601                              scope_metadata: DIScope,
1602                              variable_access: VariableAccess,
1603                              variable_kind: VariableKind,
1604                              span: Span) {
1605     let cx: &CrateContext = bcx.ccx();
1606
1607     let filename = span_start(cx, span).file.name.clone();
1608     let file_metadata = file_metadata(cx, filename.as_slice());
1609
1610     let name = token::get_ident(variable_ident);
1611     let loc = span_start(cx, span);
1612     let type_metadata = type_metadata(cx, variable_type, span);
1613
1614     let (argument_index, dwarf_tag) = match variable_kind {
1615         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
1616         LocalVariable    |
1617         CapturedVariable => (0, DW_TAG_auto_variable)
1618     };
1619
1620     let (var_alloca, var_metadata) = name.get().with_c_str(|name| {
1621         match variable_access {
1622             DirectVariable { alloca } => (
1623                 alloca,
1624                 unsafe {
1625                     llvm::LLVMDIBuilderCreateLocalVariable(
1626                         DIB(cx),
1627                         dwarf_tag,
1628                         scope_metadata,
1629                         name,
1630                         file_metadata,
1631                         loc.line as c_uint,
1632                         type_metadata,
1633                         cx.sess().opts.optimize != config::No,
1634                         0,
1635                         argument_index)
1636                 }
1637             ),
1638             IndirectVariable { alloca, address_operations } => (
1639                 alloca,
1640                 unsafe {
1641                     llvm::LLVMDIBuilderCreateComplexVariable(
1642                         DIB(cx),
1643                         dwarf_tag,
1644                         scope_metadata,
1645                         name,
1646                         file_metadata,
1647                         loc.line as c_uint,
1648                         type_metadata,
1649                         address_operations.as_ptr(),
1650                         address_operations.len() as c_uint,
1651                         argument_index)
1652                 }
1653             )
1654         }
1655     });
1656
1657     set_debug_location(cx, DebugLocation::new(scope_metadata,
1658                                               loc.line,
1659                                               loc.col.to_uint()));
1660     unsafe {
1661         let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd(
1662             DIB(cx),
1663             var_alloca,
1664             var_metadata,
1665             bcx.llbb);
1666
1667         llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr);
1668     }
1669
1670     match variable_kind {
1671         ArgumentVariable(_) | CapturedVariable => {
1672             assert!(!bcx.fcx
1673                         .debug_context
1674                         .get_ref(cx, span)
1675                         .source_locations_enabled
1676                         .get());
1677             set_debug_location(cx, UnknownLocation);
1678         }
1679         _ => { /* nothing to do */ }
1680     }
1681 }
1682
1683 fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile {
1684     match debug_context(cx).created_files.borrow().get(full_path) {
1685         Some(file_metadata) => return *file_metadata,
1686         None => ()
1687     }
1688
1689     debug!("file_metadata: {}", full_path);
1690
1691     // FIXME (#9639): This needs to handle non-utf8 paths
1692     let work_dir = cx.sess().working_dir.as_str().unwrap();
1693     let file_name =
1694         if full_path.starts_with(work_dir) {
1695             full_path.slice(work_dir.len() + 1u, full_path.len())
1696         } else {
1697             full_path
1698         };
1699
1700     let file_metadata =
1701         file_name.with_c_str(|file_name| {
1702             work_dir.with_c_str(|work_dir| {
1703                 unsafe {
1704                     llvm::LLVMDIBuilderCreateFile(DIB(cx), file_name, work_dir)
1705                 }
1706             })
1707         });
1708
1709     let mut created_files = debug_context(cx).created_files.borrow_mut();
1710     created_files.insert(full_path.to_string(), file_metadata);
1711     return file_metadata;
1712 }
1713
1714 /// Finds the scope metadata node for the given AST node.
1715 fn scope_metadata(fcx: &FunctionContext,
1716                   node_id: ast::NodeId,
1717                   error_reporting_span: Span)
1718                -> DIScope {
1719     let scope_map = &fcx.debug_context
1720                         .get_ref(fcx.ccx, error_reporting_span)
1721                         .scope_map;
1722     match scope_map.borrow().get(&node_id).cloned() {
1723         Some(scope_metadata) => scope_metadata,
1724         None => {
1725             let node = fcx.ccx.tcx().map.get(node_id);
1726
1727             fcx.ccx.sess().span_bug(error_reporting_span,
1728                 format!("debuginfo: Could not find scope info for node {}",
1729                         node).as_slice());
1730         }
1731     }
1732 }
1733
1734 fn diverging_type_metadata(cx: &CrateContext) -> DIType {
1735     "!".with_c_str(|name| {
1736         unsafe {
1737             llvm::LLVMDIBuilderCreateBasicType(
1738                 DIB(cx),
1739                 name,
1740                 bytes_to_bits(0),
1741                 bytes_to_bits(0),
1742                 DW_ATE_unsigned)
1743         }
1744     })
1745 }
1746
1747 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1748                                  t: Ty<'tcx>) -> DIType {
1749
1750     debug!("basic_type_metadata: {}", t);
1751
1752     let (name, encoding) = match t.sty {
1753         ty::ty_tup(ref elements) if elements.is_empty() =>
1754             ("()".to_string(), DW_ATE_unsigned),
1755         ty::ty_bool => ("bool".to_string(), DW_ATE_boolean),
1756         ty::ty_char => ("char".to_string(), DW_ATE_unsigned_char),
1757         ty::ty_int(int_ty) => match int_ty {
1758             ast::TyI => ("int".to_string(), DW_ATE_signed),
1759             ast::TyI8 => ("i8".to_string(), DW_ATE_signed),
1760             ast::TyI16 => ("i16".to_string(), DW_ATE_signed),
1761             ast::TyI32 => ("i32".to_string(), DW_ATE_signed),
1762             ast::TyI64 => ("i64".to_string(), DW_ATE_signed)
1763         },
1764         ty::ty_uint(uint_ty) => match uint_ty {
1765             ast::TyU => ("uint".to_string(), DW_ATE_unsigned),
1766             ast::TyU8 => ("u8".to_string(), DW_ATE_unsigned),
1767             ast::TyU16 => ("u16".to_string(), DW_ATE_unsigned),
1768             ast::TyU32 => ("u32".to_string(), DW_ATE_unsigned),
1769             ast::TyU64 => ("u64".to_string(), DW_ATE_unsigned)
1770         },
1771         ty::ty_float(float_ty) => match float_ty {
1772             ast::TyF32 => ("f32".to_string(), DW_ATE_float),
1773             ast::TyF64 => ("f64".to_string(), DW_ATE_float),
1774         },
1775         _ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type")
1776     };
1777
1778     let llvm_type = type_of::type_of(cx, t);
1779     let (size, align) = size_and_align_of(cx, llvm_type);
1780     let ty_metadata = name.with_c_str(|name| {
1781         unsafe {
1782             llvm::LLVMDIBuilderCreateBasicType(
1783                 DIB(cx),
1784                 name,
1785                 bytes_to_bits(size),
1786                 bytes_to_bits(align),
1787                 encoding)
1788         }
1789     });
1790
1791     return ty_metadata;
1792 }
1793
1794 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1795                                    pointer_type: Ty<'tcx>,
1796                                    pointee_type_metadata: DIType)
1797                                    -> DIType {
1798     let pointer_llvm_type = type_of::type_of(cx, pointer_type);
1799     let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
1800     let name = compute_debuginfo_type_name(cx, pointer_type, false);
1801     let ptr_metadata = name.with_c_str(|name| {
1802         unsafe {
1803             llvm::LLVMDIBuilderCreatePointerType(
1804                 DIB(cx),
1805                 pointee_type_metadata,
1806                 bytes_to_bits(pointer_size),
1807                 bytes_to_bits(pointer_align),
1808                 name)
1809         }
1810     });
1811     return ptr_metadata;
1812 }
1813
1814 //=-----------------------------------------------------------------------------
1815 // Common facilities for record-like types (structs, enums, tuples)
1816 //=-----------------------------------------------------------------------------
1817
1818 enum MemberOffset {
1819     FixedMemberOffset { bytes: uint },
1820     // For ComputedMemberOffset, the offset is read from the llvm type definition
1821     ComputedMemberOffset
1822 }
1823
1824 // Description of a type member, which can either be a regular field (as in
1825 // structs or tuples) or an enum variant
1826 struct MemberDescription {
1827     name: String,
1828     llvm_type: Type,
1829     type_metadata: DIType,
1830     offset: MemberOffset,
1831     flags: c_uint
1832 }
1833
1834 // A factory for MemberDescriptions. It produces a list of member descriptions
1835 // for some record-like type. MemberDescriptionFactories are used to defer the
1836 // creation of type member descriptions in order to break cycles arising from
1837 // recursive type definitions.
1838 enum MemberDescriptionFactory<'tcx> {
1839     StructMDF(StructMemberDescriptionFactory<'tcx>),
1840     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1841     EnumMDF(EnumMemberDescriptionFactory<'tcx>),
1842     VariantMDF(VariantMemberDescriptionFactory<'tcx>)
1843 }
1844
1845 impl<'tcx> MemberDescriptionFactory<'tcx> {
1846     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1847                                       -> Vec<MemberDescription> {
1848         match *self {
1849             StructMDF(ref this) => {
1850                 this.create_member_descriptions(cx)
1851             }
1852             TupleMDF(ref this) => {
1853                 this.create_member_descriptions(cx)
1854             }
1855             EnumMDF(ref this) => {
1856                 this.create_member_descriptions(cx)
1857             }
1858             VariantMDF(ref this) => {
1859                 this.create_member_descriptions(cx)
1860             }
1861         }
1862     }
1863 }
1864
1865 // A description of some recursive type. It can either be already finished (as
1866 // with FinalMetadata) or it is not yet finished, but contains all information
1867 // needed to generate the missing parts of the description. See the documentation
1868 // section on Recursive Types at the top of this file for more information.
1869 enum RecursiveTypeDescription<'tcx> {
1870     UnfinishedMetadata {
1871         unfinished_type: Ty<'tcx>,
1872         unique_type_id: UniqueTypeId,
1873         metadata_stub: DICompositeType,
1874         llvm_type: Type,
1875         member_description_factory: MemberDescriptionFactory<'tcx>,
1876     },
1877     FinalMetadata(DICompositeType)
1878 }
1879
1880 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
1881     cx: &CrateContext<'a, 'tcx>,
1882     unfinished_type: Ty<'tcx>,
1883     unique_type_id: UniqueTypeId,
1884     metadata_stub: DICompositeType,
1885     llvm_type: Type,
1886     member_description_factory: MemberDescriptionFactory<'tcx>)
1887  -> RecursiveTypeDescription<'tcx> {
1888
1889     // Insert the stub into the TypeMap in order to allow for recursive references
1890     let mut type_map = debug_context(cx).type_map.borrow_mut();
1891     type_map.register_unique_id_with_metadata(cx, unique_type_id, metadata_stub);
1892     type_map.register_type_with_metadata(cx, unfinished_type, metadata_stub);
1893
1894     UnfinishedMetadata {
1895         unfinished_type: unfinished_type,
1896         unique_type_id: unique_type_id,
1897         metadata_stub: metadata_stub,
1898         llvm_type: llvm_type,
1899         member_description_factory: member_description_factory,
1900     }
1901 }
1902
1903 impl<'tcx> RecursiveTypeDescription<'tcx> {
1904     // Finishes up the description of the type in question (mostly by providing
1905     // descriptions of the fields of the given type) and returns the final type metadata.
1906     fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
1907         match *self {
1908             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
1909             UnfinishedMetadata {
1910                 unfinished_type,
1911                 unique_type_id,
1912                 metadata_stub,
1913                 llvm_type,
1914                 ref member_description_factory,
1915                 ..
1916             } => {
1917                 // Make sure that we have a forward declaration of the type in
1918                 // the TypeMap so that recursive references are possible. This
1919                 // will always be the case if the RecursiveTypeDescription has
1920                 // been properly created through the
1921                 // create_and_register_recursive_type_forward_declaration() function.
1922                 {
1923                     let type_map = debug_context(cx).type_map.borrow();
1924                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
1925                        type_map.find_metadata_for_type(unfinished_type).is_none() {
1926                         cx.sess().bug(format!("Forward declaration of potentially recursive type \
1927                                               '{}' was not found in TypeMap!",
1928                                               ppaux::ty_to_string(cx.tcx(), unfinished_type))
1929                                       .as_slice());
1930                     }
1931                 }
1932
1933                 // ... then create the member descriptions ...
1934                 let member_descriptions =
1935                     member_description_factory.create_member_descriptions(cx);
1936
1937                 // ... and attach them to the stub to complete it.
1938                 set_members_of_composite_type(cx,
1939                                               metadata_stub,
1940                                               llvm_type,
1941                                               member_descriptions.as_slice());
1942                 return MetadataCreationResult::new(metadata_stub, true);
1943             }
1944         }
1945     }
1946 }
1947
1948
1949 //=-----------------------------------------------------------------------------
1950 // Structs
1951 //=-----------------------------------------------------------------------------
1952
1953 // Creates MemberDescriptions for the fields of a struct
1954 struct StructMemberDescriptionFactory<'tcx> {
1955     fields: Vec<ty::field<'tcx>>,
1956     is_simd: bool,
1957     span: Span,
1958 }
1959
1960 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1961     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1962                                       -> Vec<MemberDescription> {
1963         if self.fields.len() == 0 {
1964             return Vec::new();
1965         }
1966
1967         let field_size = if self.is_simd {
1968             machine::llsize_of_alloc(cx, type_of::type_of(cx, self.fields[0].mt.ty)) as uint
1969         } else {
1970             0xdeadbeef
1971         };
1972
1973         self.fields.iter().enumerate().map(|(i, field)| {
1974             let name = if field.name == special_idents::unnamed_field.name {
1975                 "".to_string()
1976             } else {
1977                 token::get_name(field.name).get().to_string()
1978             };
1979
1980             let offset = if self.is_simd {
1981                 assert!(field_size != 0xdeadbeef);
1982                 FixedMemberOffset { bytes: i * field_size }
1983             } else {
1984                 ComputedMemberOffset
1985             };
1986
1987             MemberDescription {
1988                 name: name,
1989                 llvm_type: type_of::type_of(cx, field.mt.ty),
1990                 type_metadata: type_metadata(cx, field.mt.ty, self.span),
1991                 offset: offset,
1992                 flags: FLAGS_NONE,
1993             }
1994         }).collect()
1995     }
1996 }
1997
1998
1999 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2000                                      struct_type: Ty<'tcx>,
2001                                      def_id: ast::DefId,
2002                                      substs: &subst::Substs<'tcx>,
2003                                      unique_type_id: UniqueTypeId,
2004                                      span: Span)
2005                                      -> RecursiveTypeDescription<'tcx> {
2006     let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
2007     let struct_llvm_type = type_of::type_of(cx, struct_type);
2008
2009     let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
2010
2011     let struct_metadata_stub = create_struct_stub(cx,
2012                                                   struct_llvm_type,
2013                                                   struct_name.as_slice(),
2014                                                   unique_type_id,
2015                                                   containing_scope);
2016
2017     let fields = ty::struct_fields(cx.tcx(), def_id, substs);
2018
2019     create_and_register_recursive_type_forward_declaration(
2020         cx,
2021         struct_type,
2022         unique_type_id,
2023         struct_metadata_stub,
2024         struct_llvm_type,
2025         StructMDF(StructMemberDescriptionFactory {
2026             fields: fields,
2027             is_simd: ty::type_is_simd(cx.tcx(), struct_type),
2028             span: span,
2029         })
2030     )
2031 }
2032
2033
2034 //=-----------------------------------------------------------------------------
2035 // Tuples
2036 //=-----------------------------------------------------------------------------
2037
2038 // Creates MemberDescriptions for the fields of a tuple
2039 struct TupleMemberDescriptionFactory<'tcx> {
2040     component_types: Vec<Ty<'tcx>>,
2041     span: Span,
2042 }
2043
2044 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
2045     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
2046                                       -> Vec<MemberDescription> {
2047         self.component_types.iter().map(|&component_type| {
2048             MemberDescription {
2049                 name: "".to_string(),
2050                 llvm_type: type_of::type_of(cx, component_type),
2051                 type_metadata: type_metadata(cx, component_type, self.span),
2052                 offset: ComputedMemberOffset,
2053                 flags: FLAGS_NONE,
2054             }
2055         }).collect()
2056     }
2057 }
2058
2059 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2060                                     tuple_type: Ty<'tcx>,
2061                                     component_types: &[Ty<'tcx>],
2062                                     unique_type_id: UniqueTypeId,
2063                                     span: Span)
2064                                     -> RecursiveTypeDescription<'tcx> {
2065     let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
2066     let tuple_llvm_type = type_of::type_of(cx, tuple_type);
2067
2068     create_and_register_recursive_type_forward_declaration(
2069         cx,
2070         tuple_type,
2071         unique_type_id,
2072         create_struct_stub(cx,
2073                            tuple_llvm_type,
2074                            tuple_name.as_slice(),
2075                            unique_type_id,
2076                            UNKNOWN_SCOPE_METADATA),
2077         tuple_llvm_type,
2078         TupleMDF(TupleMemberDescriptionFactory {
2079             component_types: component_types.to_vec(),
2080             span: span,
2081         })
2082     )
2083 }
2084
2085
2086 //=-----------------------------------------------------------------------------
2087 // Enums
2088 //=-----------------------------------------------------------------------------
2089
2090 // Describes the members of an enum value: An enum is described as a union of
2091 // structs in DWARF. This MemberDescriptionFactory provides the description for
2092 // the members of this union; so for every variant of the given enum, this factory
2093 // will produce one MemberDescription (all with no name and a fixed offset of
2094 // zero bytes).
2095 struct EnumMemberDescriptionFactory<'tcx> {
2096     enum_type: Ty<'tcx>,
2097     type_rep: Rc<adt::Repr<'tcx>>,
2098     variants: Rc<Vec<Rc<ty::VariantInfo<'tcx>>>>,
2099     discriminant_type_metadata: Option<DIType>,
2100     containing_scope: DIScope,
2101     file_metadata: DIFile,
2102     span: Span,
2103 }
2104
2105 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
2106     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
2107                                       -> Vec<MemberDescription> {
2108         match *self.type_rep {
2109             adt::General(_, ref struct_defs, _) => {
2110                 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
2111                     .expect(""));
2112
2113                 struct_defs
2114                     .iter()
2115                     .enumerate()
2116                     .map(|(i, struct_def)| {
2117                         let (variant_type_metadata,
2118                              variant_llvm_type,
2119                              member_desc_factory) =
2120                             describe_enum_variant(cx,
2121                                                   self.enum_type,
2122                                                   struct_def,
2123                                                   &*(*self.variants)[i],
2124                                                   discriminant_info,
2125                                                   self.containing_scope,
2126                                                   self.span);
2127
2128                         let member_descriptions = member_desc_factory
2129                             .create_member_descriptions(cx);
2130
2131                         set_members_of_composite_type(cx,
2132                                                       variant_type_metadata,
2133                                                       variant_llvm_type,
2134                                                       member_descriptions.as_slice());
2135                         MemberDescription {
2136                             name: "".to_string(),
2137                             llvm_type: variant_llvm_type,
2138                             type_metadata: variant_type_metadata,
2139                             offset: FixedMemberOffset { bytes: 0 },
2140                             flags: FLAGS_NONE
2141                         }
2142                     }).collect()
2143             },
2144             adt::Univariant(ref struct_def, _) => {
2145                 assert!(self.variants.len() <= 1);
2146
2147                 if self.variants.len() == 0 {
2148                     vec![]
2149                 } else {
2150                     let (variant_type_metadata,
2151                          variant_llvm_type,
2152                          member_description_factory) =
2153                         describe_enum_variant(cx,
2154                                               self.enum_type,
2155                                               struct_def,
2156                                               &*(*self.variants)[0],
2157                                               NoDiscriminant,
2158                                               self.containing_scope,
2159                                               self.span);
2160
2161                     let member_descriptions =
2162                         member_description_factory.create_member_descriptions(cx);
2163
2164                     set_members_of_composite_type(cx,
2165                                                   variant_type_metadata,
2166                                                   variant_llvm_type,
2167                                                   member_descriptions.as_slice());
2168                     vec![
2169                         MemberDescription {
2170                             name: "".to_string(),
2171                             llvm_type: variant_llvm_type,
2172                             type_metadata: variant_type_metadata,
2173                             offset: FixedMemberOffset { bytes: 0 },
2174                             flags: FLAGS_NONE
2175                         }
2176                     ]
2177                 }
2178             }
2179             adt::RawNullablePointer { nndiscr: non_null_variant_index, nnty, .. } => {
2180                 // As far as debuginfo is concerned, the pointer this enum
2181                 // represents is still wrapped in a struct. This is to make the
2182                 // DWARF representation of enums uniform.
2183
2184                 // First create a description of the artificial wrapper struct:
2185                 let non_null_variant = &(*self.variants)[non_null_variant_index as uint];
2186                 let non_null_variant_name = token::get_name(non_null_variant.name);
2187
2188                 // The llvm type and metadata of the pointer
2189                 let non_null_llvm_type = type_of::type_of(cx, nnty);
2190                 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
2191
2192                 // The type of the artificial struct wrapping the pointer
2193                 let artificial_struct_llvm_type = Type::struct_(cx,
2194                                                                 &[non_null_llvm_type],
2195                                                                 false);
2196
2197                 // For the metadata of the wrapper struct, we need to create a
2198                 // MemberDescription of the struct's single field.
2199                 let sole_struct_member_description = MemberDescription {
2200                     name: match non_null_variant.arg_names {
2201                         Some(ref names) => token::get_ident(names[0]).get().to_string(),
2202                         None => "".to_string()
2203                     },
2204                     llvm_type: non_null_llvm_type,
2205                     type_metadata: non_null_type_metadata,
2206                     offset: FixedMemberOffset { bytes: 0 },
2207                     flags: FLAGS_NONE
2208                 };
2209
2210                 let unique_type_id = debug_context(cx).type_map
2211                                                       .borrow_mut()
2212                                                       .get_unique_type_id_of_enum_variant(
2213                                                           cx,
2214                                                           self.enum_type,
2215                                                           non_null_variant_name.get());
2216
2217                 // Now we can create the metadata of the artificial struct
2218                 let artificial_struct_metadata =
2219                     composite_type_metadata(cx,
2220                                             artificial_struct_llvm_type,
2221                                             non_null_variant_name.get(),
2222                                             unique_type_id,
2223                                             &[sole_struct_member_description],
2224                                             self.containing_scope,
2225                                             self.file_metadata,
2226                                             codemap::DUMMY_SP);
2227
2228                 // Encode the information about the null variant in the union
2229                 // member's name.
2230                 let null_variant_index = (1 - non_null_variant_index) as uint;
2231                 let null_variant_name = token::get_name((*self.variants)[null_variant_index].name);
2232                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
2233                                                 0u,
2234                                                 null_variant_name);
2235
2236                 // Finally create the (singleton) list of descriptions of union
2237                 // members.
2238                 vec![
2239                     MemberDescription {
2240                         name: union_member_name,
2241                         llvm_type: artificial_struct_llvm_type,
2242                         type_metadata: artificial_struct_metadata,
2243                         offset: FixedMemberOffset { bytes: 0 },
2244                         flags: FLAGS_NONE
2245                     }
2246                 ]
2247             },
2248             adt::StructWrappedNullablePointer { nonnull: ref struct_def,
2249                                                 nndiscr,
2250                                                 ptrfield, ..} => {
2251                 // Create a description of the non-null variant
2252                 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
2253                     describe_enum_variant(cx,
2254                                           self.enum_type,
2255                                           struct_def,
2256                                           &*(*self.variants)[nndiscr as uint],
2257                                           OptimizedDiscriminant(ptrfield),
2258                                           self.containing_scope,
2259                                           self.span);
2260
2261                 let variant_member_descriptions =
2262                     member_description_factory.create_member_descriptions(cx);
2263
2264                 set_members_of_composite_type(cx,
2265                                               variant_type_metadata,
2266                                               variant_llvm_type,
2267                                               variant_member_descriptions.as_slice());
2268
2269                 // Encode the information about the null variant in the union
2270                 // member's name.
2271                 let null_variant_index = (1 - nndiscr) as uint;
2272                 let null_variant_name = token::get_name((*self.variants)[null_variant_index].name);
2273                 let discrfield = match ptrfield {
2274                     adt::ThinPointer(field) => format!("{}", field),
2275                     adt::FatPointer(field) => format!("{}", field)
2276                 };
2277                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
2278                                                 discrfield,
2279                                                 null_variant_name);
2280
2281                 // Create the (singleton) list of descriptions of union members.
2282                 vec![
2283                     MemberDescription {
2284                         name: union_member_name,
2285                         llvm_type: variant_llvm_type,
2286                         type_metadata: variant_type_metadata,
2287                         offset: FixedMemberOffset { bytes: 0 },
2288                         flags: FLAGS_NONE
2289                     }
2290                 ]
2291             },
2292             adt::CEnum(..) => cx.sess().span_bug(self.span, "This should be unreachable.")
2293         }
2294     }
2295 }
2296
2297 // Creates MemberDescriptions for the fields of a single enum variant.
2298 struct VariantMemberDescriptionFactory<'tcx> {
2299     args: Vec<(String, Ty<'tcx>)>,
2300     discriminant_type_metadata: Option<DIType>,
2301     span: Span,
2302 }
2303
2304 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
2305     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
2306                                       -> Vec<MemberDescription> {
2307         self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
2308             MemberDescription {
2309                 name: name.to_string(),
2310                 llvm_type: type_of::type_of(cx, ty),
2311                 type_metadata: match self.discriminant_type_metadata {
2312                     Some(metadata) if i == 0 => metadata,
2313                     _ => type_metadata(cx, ty, self.span)
2314                 },
2315                 offset: ComputedMemberOffset,
2316                 flags: FLAGS_NONE
2317             }
2318         }).collect()
2319     }
2320 }
2321
2322 enum EnumDiscriminantInfo {
2323     RegularDiscriminant(DIType),
2324     OptimizedDiscriminant(adt::PointerField),
2325     NoDiscriminant
2326 }
2327
2328 impl Copy for EnumDiscriminantInfo {}
2329
2330 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
2331 // of the variant, and (3) a MemberDescriptionFactory for producing the
2332 // descriptions of the fields of the variant. This is a rudimentary version of a
2333 // full RecursiveTypeDescription.
2334 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2335                                    enum_type: Ty<'tcx>,
2336                                    struct_def: &adt::Struct<'tcx>,
2337                                    variant_info: &ty::VariantInfo<'tcx>,
2338                                    discriminant_info: EnumDiscriminantInfo,
2339                                    containing_scope: DIScope,
2340                                    span: Span)
2341                                    -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
2342     let variant_llvm_type =
2343         Type::struct_(cx, struct_def.fields
2344                                     .iter()
2345                                     .map(|&t| type_of::type_of(cx, t))
2346                                     .collect::<Vec<_>>()
2347                                     .as_slice(),
2348                       struct_def.packed);
2349     // Could do some consistency checks here: size, align, field count, discr type
2350
2351     let variant_name = token::get_name(variant_info.name);
2352     let variant_name = variant_name.get();
2353     let unique_type_id = debug_context(cx).type_map
2354                                           .borrow_mut()
2355                                           .get_unique_type_id_of_enum_variant(
2356                                               cx,
2357                                               enum_type,
2358                                               variant_name);
2359
2360     let metadata_stub = create_struct_stub(cx,
2361                                            variant_llvm_type,
2362                                            variant_name,
2363                                            unique_type_id,
2364                                            containing_scope);
2365
2366     // Get the argument names from the enum variant info
2367     let mut arg_names: Vec<_> = match variant_info.arg_names {
2368         Some(ref names) => {
2369             names.iter()
2370                  .map(|ident| {
2371                      token::get_ident(*ident).get().to_string().into_string()
2372                  }).collect()
2373         }
2374         None => variant_info.args.iter().map(|_| "".to_string()).collect()
2375     };
2376
2377     // If this is not a univariant enum, there is also the discriminant field.
2378     match discriminant_info {
2379         RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
2380         _ => { /* do nothing */ }
2381     };
2382
2383     // Build an array of (field name, field type) pairs to be captured in the factory closure.
2384     let args: Vec<(String, Ty)> = arg_names.iter()
2385         .zip(struct_def.fields.iter())
2386         .map(|(s, &t)| (s.to_string(), t))
2387         .collect();
2388
2389     let member_description_factory =
2390         VariantMDF(VariantMemberDescriptionFactory {
2391             args: args,
2392             discriminant_type_metadata: match discriminant_info {
2393                 RegularDiscriminant(discriminant_type_metadata) => {
2394                     Some(discriminant_type_metadata)
2395                 }
2396                 _ => None
2397             },
2398             span: span,
2399         });
2400
2401     (metadata_stub, variant_llvm_type, member_description_factory)
2402 }
2403
2404 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2405                                    enum_type: Ty<'tcx>,
2406                                    enum_def_id: ast::DefId,
2407                                    unique_type_id: UniqueTypeId,
2408                                    span: Span)
2409                                    -> RecursiveTypeDescription<'tcx> {
2410     let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
2411
2412     let (containing_scope, definition_span) = get_namespace_and_span_for_item(cx, enum_def_id);
2413     let loc = span_start(cx, definition_span);
2414     let file_metadata = file_metadata(cx, loc.file.name.as_slice());
2415
2416     let variants = ty::enum_variants(cx.tcx(), enum_def_id);
2417
2418     let enumerators_metadata: Vec<DIDescriptor> = variants
2419         .iter()
2420         .map(|v| {
2421             token::get_name(v.name).get().with_c_str(|name| {
2422                 unsafe {
2423                     llvm::LLVMDIBuilderCreateEnumerator(
2424                         DIB(cx),
2425                         name,
2426                         v.disr_val as u64)
2427                 }
2428             })
2429         })
2430         .collect();
2431
2432     let discriminant_type_metadata = |inttype| {
2433         // We can reuse the type of the discriminant for all monomorphized
2434         // instances of an enum because it doesn't depend on any type parameters.
2435         // The def_id, uniquely identifying the enum's polytype acts as key in
2436         // this cache.
2437         let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
2438                                                                  .borrow()
2439                                                                  .get(&enum_def_id).cloned();
2440         match cached_discriminant_type_metadata {
2441             Some(discriminant_type_metadata) => discriminant_type_metadata,
2442             None => {
2443                 let discriminant_llvm_type = adt::ll_inttype(cx, inttype);
2444                 let (discriminant_size, discriminant_align) =
2445                     size_and_align_of(cx, discriminant_llvm_type);
2446                 let discriminant_base_type_metadata = type_metadata(cx,
2447                                                                     adt::ty_of_inttype(inttype),
2448                                                                     codemap::DUMMY_SP);
2449                 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
2450
2451                 let discriminant_type_metadata = discriminant_name.get().with_c_str(|name| {
2452                     unsafe {
2453                         llvm::LLVMDIBuilderCreateEnumerationType(
2454                             DIB(cx),
2455                             containing_scope,
2456                             name,
2457                             UNKNOWN_FILE_METADATA,
2458                             UNKNOWN_LINE_NUMBER,
2459                             bytes_to_bits(discriminant_size),
2460                             bytes_to_bits(discriminant_align),
2461                             create_DIArray(DIB(cx), enumerators_metadata.as_slice()),
2462                             discriminant_base_type_metadata)
2463                     }
2464                 });
2465
2466                 debug_context(cx).created_enum_disr_types
2467                                  .borrow_mut()
2468                                  .insert(enum_def_id, discriminant_type_metadata);
2469
2470                 discriminant_type_metadata
2471             }
2472         }
2473     };
2474
2475     let type_rep = adt::represent_type(cx, enum_type);
2476
2477     let discriminant_type_metadata = match *type_rep {
2478         adt::CEnum(inttype, _, _) => {
2479             return FinalMetadata(discriminant_type_metadata(inttype))
2480         },
2481         adt::RawNullablePointer { .. }           |
2482         adt::StructWrappedNullablePointer { .. } |
2483         adt::Univariant(..)                      => None,
2484         adt::General(inttype, _, _) => Some(discriminant_type_metadata(inttype)),
2485     };
2486
2487     let enum_llvm_type = type_of::type_of(cx, enum_type);
2488     let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
2489
2490     let unique_type_id_str = debug_context(cx)
2491                              .type_map
2492                              .borrow()
2493                              .get_unique_type_id_as_string(unique_type_id);
2494
2495     let enum_metadata = enum_name.with_c_str(|enum_name| {
2496         unique_type_id_str.with_c_str(|unique_type_id_str| {
2497             unsafe {
2498                 llvm::LLVMDIBuilderCreateUnionType(
2499                 DIB(cx),
2500                 containing_scope,
2501                 enum_name,
2502                 UNKNOWN_FILE_METADATA,
2503                 UNKNOWN_LINE_NUMBER,
2504                 bytes_to_bits(enum_type_size),
2505                 bytes_to_bits(enum_type_align),
2506                 0, // Flags
2507                 ptr::null_mut(),
2508                 0, // RuntimeLang
2509                 unique_type_id_str)
2510             }
2511         })
2512     });
2513
2514     return create_and_register_recursive_type_forward_declaration(
2515         cx,
2516         enum_type,
2517         unique_type_id,
2518         enum_metadata,
2519         enum_llvm_type,
2520         EnumMDF(EnumMemberDescriptionFactory {
2521             enum_type: enum_type,
2522             type_rep: type_rep.clone(),
2523             variants: variants,
2524             discriminant_type_metadata: discriminant_type_metadata,
2525             containing_scope: containing_scope,
2526             file_metadata: file_metadata,
2527             span: span,
2528         }),
2529     );
2530
2531     fn get_enum_discriminant_name(cx: &CrateContext,
2532                                   def_id: ast::DefId)
2533                                   -> token::InternedString {
2534         let name = if def_id.krate == ast::LOCAL_CRATE {
2535             cx.tcx().map.get_path_elem(def_id.node).name()
2536         } else {
2537             csearch::get_item_path(cx.tcx(), def_id).last().unwrap().name()
2538         };
2539
2540         token::get_name(name)
2541     }
2542 }
2543
2544 /// Creates debug information for a composite type, that is, anything that
2545 /// results in a LLVM struct.
2546 ///
2547 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2548 fn composite_type_metadata(cx: &CrateContext,
2549                            composite_llvm_type: Type,
2550                            composite_type_name: &str,
2551                            composite_type_unique_id: UniqueTypeId,
2552                            member_descriptions: &[MemberDescription],
2553                            containing_scope: DIScope,
2554
2555                            // Ignore source location information as long as it
2556                            // can't be reconstructed for non-local crates.
2557                            _file_metadata: DIFile,
2558                            _definition_span: Span)
2559                         -> DICompositeType {
2560     // Create the (empty) struct metadata node ...
2561     let composite_type_metadata = create_struct_stub(cx,
2562                                                      composite_llvm_type,
2563                                                      composite_type_name,
2564                                                      composite_type_unique_id,
2565                                                      containing_scope);
2566     // ... and immediately create and add the member descriptions.
2567     set_members_of_composite_type(cx,
2568                                   composite_type_metadata,
2569                                   composite_llvm_type,
2570                                   member_descriptions);
2571
2572     return composite_type_metadata;
2573 }
2574
2575 fn set_members_of_composite_type(cx: &CrateContext,
2576                                  composite_type_metadata: DICompositeType,
2577                                  composite_llvm_type: Type,
2578                                  member_descriptions: &[MemberDescription]) {
2579     // In some rare cases LLVM metadata uniquing would lead to an existing type
2580     // description being used instead of a new one created in create_struct_stub.
2581     // This would cause a hard to trace assertion in DICompositeType::SetTypeArray().
2582     // The following check makes sure that we get a better error message if this
2583     // should happen again due to some regression.
2584     {
2585         let mut composite_types_completed =
2586             debug_context(cx).composite_types_completed.borrow_mut();
2587         if composite_types_completed.contains(&composite_type_metadata) {
2588             let (llvm_version_major, llvm_version_minor) = unsafe {
2589                 (llvm::LLVMVersionMajor(), llvm::LLVMVersionMinor())
2590             };
2591
2592             let actual_llvm_version = llvm_version_major * 1000000 + llvm_version_minor * 1000;
2593             let min_supported_llvm_version = 3 * 1000000 + 4 * 1000;
2594
2595             if actual_llvm_version < min_supported_llvm_version {
2596                 cx.sess().warn(format!("This version of rustc was built with LLVM \
2597                                         {}.{}. Rustc just ran into a known \
2598                                         debuginfo corruption problem thatoften \
2599                                         occurs with LLVM versions below 3.4. \
2600                                         Please use a rustc built with anewer \
2601                                         version of LLVM.",
2602                                        llvm_version_major,
2603                                        llvm_version_minor).as_slice());
2604             } else {
2605                 cx.sess().bug("debuginfo::set_members_of_composite_type() - \
2606                                Already completed forward declaration re-encountered.");
2607             }
2608         } else {
2609             composite_types_completed.insert(composite_type_metadata);
2610         }
2611     }
2612
2613     let member_metadata: Vec<DIDescriptor> = member_descriptions
2614         .iter()
2615         .enumerate()
2616         .map(|(i, member_description)| {
2617             let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
2618             let member_offset = match member_description.offset {
2619                 FixedMemberOffset { bytes } => bytes as u64,
2620                 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
2621             };
2622
2623             member_description.name.with_c_str(|member_name| {
2624                 unsafe {
2625                     llvm::LLVMDIBuilderCreateMemberType(
2626                         DIB(cx),
2627                         composite_type_metadata,
2628                         member_name,
2629                         UNKNOWN_FILE_METADATA,
2630                         UNKNOWN_LINE_NUMBER,
2631                         bytes_to_bits(member_size),
2632                         bytes_to_bits(member_align),
2633                         bytes_to_bits(member_offset),
2634                         member_description.flags,
2635                         member_description.type_metadata)
2636                 }
2637             })
2638         })
2639         .collect();
2640
2641     unsafe {
2642         let type_array = create_DIArray(DIB(cx), member_metadata.as_slice());
2643         llvm::LLVMDICompositeTypeSetTypeArray(composite_type_metadata, type_array);
2644     }
2645 }
2646
2647 // A convenience wrapper around LLVMDIBuilderCreateStructType(). Does not do any
2648 // caching, does not add any fields to the struct. This can be done later with
2649 // set_members_of_composite_type().
2650 fn create_struct_stub(cx: &CrateContext,
2651                       struct_llvm_type: Type,
2652                       struct_type_name: &str,
2653                       unique_type_id: UniqueTypeId,
2654                       containing_scope: DIScope)
2655                    -> DICompositeType {
2656     let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
2657
2658     let unique_type_id_str = debug_context(cx).type_map
2659                                               .borrow()
2660                                               .get_unique_type_id_as_string(unique_type_id);
2661     let metadata_stub = unsafe {
2662         struct_type_name.with_c_str(|name| {
2663             unique_type_id_str.with_c_str(|unique_type_id| {
2664                 // LLVMDIBuilderCreateStructType() wants an empty array. A null
2665                 // pointer will lead to hard to trace and debug LLVM assertions
2666                 // later on in llvm/lib/IR/Value.cpp.
2667                 let empty_array = create_DIArray(DIB(cx), &[]);
2668
2669                 llvm::LLVMDIBuilderCreateStructType(
2670                     DIB(cx),
2671                     containing_scope,
2672                     name,
2673                     UNKNOWN_FILE_METADATA,
2674                     UNKNOWN_LINE_NUMBER,
2675                     bytes_to_bits(struct_size),
2676                     bytes_to_bits(struct_align),
2677                     0,
2678                     ptr::null_mut(),
2679                     empty_array,
2680                     0,
2681                     ptr::null_mut(),
2682                     unique_type_id)
2683             })
2684         })
2685     };
2686
2687     return metadata_stub;
2688 }
2689
2690 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2691                                 unique_type_id: UniqueTypeId,
2692                                 element_type: Ty<'tcx>,
2693                                 len: uint,
2694                                 span: Span)
2695                                 -> MetadataCreationResult {
2696     let element_type_metadata = type_metadata(cx, element_type, span);
2697
2698     return_if_metadata_created_in_meantime!(cx, unique_type_id);
2699
2700     let element_llvm_type = type_of::type_of(cx, element_type);
2701     let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
2702
2703     let subrange = unsafe {
2704         llvm::LLVMDIBuilderGetOrCreateSubrange(
2705             DIB(cx),
2706             0,
2707             len as i64)
2708     };
2709
2710     let subscripts = create_DIArray(DIB(cx), &[subrange]);
2711     let metadata = unsafe {
2712         llvm::LLVMDIBuilderCreateArrayType(
2713             DIB(cx),
2714             bytes_to_bits(element_type_size * (len as u64)),
2715             bytes_to_bits(element_type_align),
2716             element_type_metadata,
2717             subscripts)
2718     };
2719
2720     return MetadataCreationResult::new(metadata, false);
2721 }
2722
2723 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2724                                 vec_type: Ty<'tcx>,
2725                                 element_type: Ty<'tcx>,
2726                                 unique_type_id: UniqueTypeId,
2727                                 span: Span)
2728                                 -> MetadataCreationResult {
2729     let data_ptr_type = ty::mk_ptr(cx.tcx(), ty::mt {
2730         ty: element_type,
2731         mutbl: ast::MutImmutable
2732     });
2733
2734     let element_type_metadata = type_metadata(cx, data_ptr_type, span);
2735
2736     return_if_metadata_created_in_meantime!(cx, unique_type_id);
2737
2738     let slice_llvm_type = type_of::type_of(cx, vec_type);
2739     let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
2740
2741     let member_llvm_types = slice_llvm_type.field_types();
2742     assert!(slice_layout_is_correct(cx,
2743                                     member_llvm_types.as_slice(),
2744                                     element_type));
2745     let member_descriptions = [
2746         MemberDescription {
2747             name: "data_ptr".to_string(),
2748             llvm_type: member_llvm_types[0],
2749             type_metadata: element_type_metadata,
2750             offset: ComputedMemberOffset,
2751             flags: FLAGS_NONE
2752         },
2753         MemberDescription {
2754             name: "length".to_string(),
2755             llvm_type: member_llvm_types[1],
2756             type_metadata: type_metadata(cx, ty::mk_uint(), span),
2757             offset: ComputedMemberOffset,
2758             flags: FLAGS_NONE
2759         },
2760     ];
2761
2762     assert!(member_descriptions.len() == member_llvm_types.len());
2763
2764     let loc = span_start(cx, span);
2765     let file_metadata = file_metadata(cx, loc.file.name.as_slice());
2766
2767     let metadata = composite_type_metadata(cx,
2768                                            slice_llvm_type,
2769                                            slice_type_name.as_slice(),
2770                                            unique_type_id,
2771                                            &member_descriptions,
2772                                            UNKNOWN_SCOPE_METADATA,
2773                                            file_metadata,
2774                                            span);
2775     return MetadataCreationResult::new(metadata, false);
2776
2777     fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2778                                          member_llvm_types: &[Type],
2779                                          element_type: Ty<'tcx>)
2780                                          -> bool {
2781         member_llvm_types.len() == 2 &&
2782         member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
2783         member_llvm_types[1] == cx.int_type()
2784     }
2785 }
2786
2787 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2788                                       unique_type_id: UniqueTypeId,
2789                                       signature: &ty::FnSig<'tcx>,
2790                                       span: Span)
2791                                       -> MetadataCreationResult {
2792     let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs.len() + 1);
2793
2794     // return type
2795     signature_metadata.push(match signature.output {
2796         ty::FnConverging(ret_ty) => match ret_ty.sty {
2797             ty::ty_tup(ref tys) if tys.is_empty() => ptr::null_mut(),
2798             _ => type_metadata(cx, ret_ty, span)
2799         },
2800         ty::FnDiverging => diverging_type_metadata(cx)
2801     });
2802
2803     // regular arguments
2804     for &argument_type in signature.inputs.iter() {
2805         signature_metadata.push(type_metadata(cx, argument_type, span));
2806     }
2807
2808     return_if_metadata_created_in_meantime!(cx, unique_type_id);
2809
2810     return MetadataCreationResult::new(
2811         unsafe {
2812             llvm::LLVMDIBuilderCreateSubroutineType(
2813                 DIB(cx),
2814                 UNKNOWN_FILE_METADATA,
2815                 create_DIArray(DIB(cx), signature_metadata.as_slice()))
2816         },
2817         false);
2818 }
2819
2820 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
2821 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
2822 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
2823 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
2824 // of a DST struct, there is no trait_object_type and the results of this
2825 // function will be a little bit weird.
2826 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2827                                     trait_type: Ty<'tcx>,
2828                                     trait_object_type: Option<Ty<'tcx>>,
2829                                     unique_type_id: UniqueTypeId)
2830                                     -> DIType {
2831     // The implementation provided here is a stub. It makes sure that the trait
2832     // type is assigned the correct name, size, namespace, and source location.
2833     // But it does not describe the trait's methods.
2834
2835     let def_id = match trait_type.sty {
2836         ty::ty_trait(box ty::TyTrait { ref principal, .. }) => principal.def_id,
2837         _ => {
2838             let pp_type_name = ppaux::ty_to_string(cx.tcx(), trait_type);
2839             cx.sess().bug(format!("debuginfo: Unexpected trait-object type in \
2840                                    trait_pointer_metadata(): {}",
2841                                    pp_type_name.as_slice()).as_slice());
2842         }
2843     };
2844
2845     let trait_object_type = trait_object_type.unwrap_or(trait_type);
2846     let trait_type_name =
2847         compute_debuginfo_type_name(cx, trait_object_type, false);
2848
2849     let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
2850
2851     let trait_llvm_type = type_of::type_of(cx, trait_object_type);
2852
2853     composite_type_metadata(cx,
2854                             trait_llvm_type,
2855                             trait_type_name.as_slice(),
2856                             unique_type_id,
2857                             &[],
2858                             containing_scope,
2859                             UNKNOWN_FILE_METADATA,
2860                             codemap::DUMMY_SP)
2861 }
2862
2863 fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2864                            t: Ty<'tcx>,
2865                            usage_site_span: Span)
2866                            -> DIType {
2867     // Get the unique type id of this type.
2868     let unique_type_id = {
2869         let mut type_map = debug_context(cx).type_map.borrow_mut();
2870         // First, try to find the type in TypeMap. If we have seen it before, we
2871         // can exit early here.
2872         match type_map.find_metadata_for_type(t) {
2873             Some(metadata) => {
2874                 return metadata;
2875             },
2876             None => {
2877                 // The Ty is not in the TypeMap but maybe we have already seen
2878                 // an equivalent type (e.g. only differing in region arguments).
2879                 // In order to find out, generate the unique type id and look
2880                 // that up.
2881                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
2882                 match type_map.find_metadata_for_unique_id(unique_type_id) {
2883                     Some(metadata) => {
2884                         // There is already an equivalent type in the TypeMap.
2885                         // Register this Ty as an alias in the cache and
2886                         // return the cached metadata.
2887                         type_map.register_type_with_metadata(cx, t, metadata);
2888                         return metadata;
2889                     },
2890                     None => {
2891                         // There really is no type metadata for this type, so
2892                         // proceed by creating it.
2893                         unique_type_id
2894                     }
2895                 }
2896             }
2897         }
2898     };
2899
2900     debug!("type_metadata: {}", t);
2901
2902     let sty = &t.sty;
2903     let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
2904         ty::ty_bool     |
2905         ty::ty_char     |
2906         ty::ty_int(_)   |
2907         ty::ty_uint(_)  |
2908         ty::ty_float(_) => {
2909             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
2910         }
2911         ty::ty_tup(ref elements) if elements.is_empty() => {
2912             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
2913         }
2914         ty::ty_enum(def_id, _) => {
2915             prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span).finalize(cx)
2916         }
2917         ty::ty_vec(typ, Some(len)) => {
2918             fixed_vec_metadata(cx, unique_type_id, typ, len, usage_site_span)
2919         }
2920         // FIXME Can we do better than this for unsized vec/str fields?
2921         ty::ty_vec(typ, None) => fixed_vec_metadata(cx, unique_type_id, typ, 0, usage_site_span),
2922         ty::ty_str => fixed_vec_metadata(cx, unique_type_id, ty::mk_i8(), 0, usage_site_span),
2923         ty::ty_trait(..) => {
2924             MetadataCreationResult::new(
2925                         trait_pointer_metadata(cx, t, None, unique_type_id),
2926             false)
2927         }
2928         ty::ty_uniq(ty) | ty::ty_ptr(ty::mt{ty, ..}) | ty::ty_rptr(_, ty::mt{ty, ..}) => {
2929             match ty.sty {
2930                 ty::ty_vec(typ, None) => {
2931                     vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
2932                 }
2933                 ty::ty_str => {
2934                     vec_slice_metadata(cx, t, ty::mk_u8(), unique_type_id, usage_site_span)
2935                 }
2936                 ty::ty_trait(..) => {
2937                     MetadataCreationResult::new(
2938                         trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
2939                         false)
2940                 }
2941                 _ => {
2942                     let pointee_metadata = type_metadata(cx, ty, usage_site_span);
2943
2944                     match debug_context(cx).type_map
2945                                            .borrow()
2946                                            .find_metadata_for_unique_id(unique_type_id) {
2947                         Some(metadata) => return metadata,
2948                         None => { /* proceed normally */ }
2949                     };
2950
2951                     MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
2952                                                 false)
2953                 }
2954             }
2955         }
2956         ty::ty_bare_fn(ref barefnty) => {
2957             subroutine_type_metadata(cx, unique_type_id, &barefnty.sig, usage_site_span)
2958         }
2959         ty::ty_closure(ref closurety) => {
2960             subroutine_type_metadata(cx, unique_type_id, &closurety.sig, usage_site_span)
2961         }
2962         ty::ty_unboxed_closure(ref def_id, _, ref substs) => {
2963             let sig = cx.tcx().unboxed_closures.borrow()
2964                         .get(def_id).unwrap().closure_type.sig.subst(cx.tcx(), substs);
2965             subroutine_type_metadata(cx, unique_type_id, &sig, usage_site_span)
2966         }
2967         ty::ty_struct(def_id, ref substs) => {
2968             prepare_struct_metadata(cx,
2969                                     t,
2970                                     def_id,
2971                                     substs,
2972                                     unique_type_id,
2973                                     usage_site_span).finalize(cx)
2974         }
2975         ty::ty_tup(ref elements) => {
2976             prepare_tuple_metadata(cx,
2977                                    t,
2978                                    elements.as_slice(),
2979                                    unique_type_id,
2980                                    usage_site_span).finalize(cx)
2981         }
2982         _ => {
2983             cx.sess().bug(format!("debuginfo: unexpected type in type_metadata: {}",
2984                                   sty).as_slice())
2985         }
2986     };
2987
2988     {
2989         let mut type_map = debug_context(cx).type_map.borrow_mut();
2990
2991         if already_stored_in_typemap {
2992             // Also make sure that we already have a TypeMap entry entry for the unique type id.
2993             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
2994                 Some(metadata) => metadata,
2995                 None => {
2996                     let unique_type_id_str =
2997                         type_map.get_unique_type_id_as_string(unique_type_id);
2998                     let error_message = format!("Expected type metadata for unique \
2999                                                  type id '{}' to already be in \
3000                                                  the debuginfo::TypeMap but it \
3001                                                  was not. (Ty = {})",
3002                                                 unique_type_id_str.as_slice(),
3003                                                 ppaux::ty_to_string(cx.tcx(), t));
3004                     cx.sess().span_bug(usage_site_span, error_message.as_slice());
3005                 }
3006             };
3007
3008             match type_map.find_metadata_for_type(t) {
3009                 Some(metadata) => {
3010                     if metadata != metadata_for_uid {
3011                         let unique_type_id_str =
3012                             type_map.get_unique_type_id_as_string(unique_type_id);
3013                         let error_message = format!("Mismatch between Ty and \
3014                                                      UniqueTypeId maps in \
3015                                                      debuginfo::TypeMap. \
3016                                                      UniqueTypeId={}, Ty={}",
3017                             unique_type_id_str.as_slice(),
3018                             ppaux::ty_to_string(cx.tcx(), t));
3019                         cx.sess().span_bug(usage_site_span, error_message.as_slice());
3020                     }
3021                 }
3022                 None => {
3023                     type_map.register_type_with_metadata(cx, t, metadata);
3024                 }
3025             }
3026         } else {
3027             type_map.register_type_with_metadata(cx, t, metadata);
3028             type_map.register_unique_id_with_metadata(cx, unique_type_id, metadata);
3029         }
3030     }
3031
3032     metadata
3033 }
3034
3035 struct MetadataCreationResult {
3036     metadata: DIType,
3037     already_stored_in_typemap: bool
3038 }
3039
3040 impl MetadataCreationResult {
3041     fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
3042         MetadataCreationResult {
3043             metadata: metadata,
3044             already_stored_in_typemap: already_stored_in_typemap
3045         }
3046     }
3047 }
3048
3049 #[deriving(PartialEq)]
3050 enum DebugLocation {
3051     KnownLocation { scope: DIScope, line: uint, col: uint },
3052     UnknownLocation
3053 }
3054
3055 impl Copy for DebugLocation {}
3056
3057 impl DebugLocation {
3058     fn new(scope: DIScope, line: uint, col: uint) -> DebugLocation {
3059         KnownLocation {
3060             scope: scope,
3061             line: line,
3062             col: col,
3063         }
3064     }
3065 }
3066
3067 fn set_debug_location(cx: &CrateContext, debug_location: DebugLocation) {
3068     if debug_location == debug_context(cx).current_debug_location.get() {
3069         return;
3070     }
3071
3072     let metadata_node;
3073
3074     match debug_location {
3075         KnownLocation { scope, line, .. } => {
3076             // Always set the column to zero like Clang and GCC
3077             let col = UNKNOWN_COLUMN_NUMBER;
3078             debug!("setting debug location to {} {}", line, col);
3079             let elements = [C_i32(cx, line as i32), C_i32(cx, col as i32),
3080                             scope, ptr::null_mut()];
3081             unsafe {
3082                 metadata_node = llvm::LLVMMDNodeInContext(debug_context(cx).llcontext,
3083                                                           elements.as_ptr(),
3084                                                           elements.len() as c_uint);
3085             }
3086         }
3087         UnknownLocation => {
3088             debug!("clearing debug location ");
3089             metadata_node = ptr::null_mut();
3090         }
3091     };
3092
3093     unsafe {
3094         llvm::LLVMSetCurrentDebugLocation(cx.raw_builder(), metadata_node);
3095     }
3096
3097     debug_context(cx).current_debug_location.set(debug_location);
3098 }
3099
3100 //=-----------------------------------------------------------------------------
3101 //  Utility Functions
3102 //=-----------------------------------------------------------------------------
3103
3104 fn contains_nodebug_attribute(attributes: &[ast::Attribute]) -> bool {
3105     attributes.iter().any(|attr| {
3106         let meta_item: &ast::MetaItem = &*attr.node.value;
3107         match meta_item.node {
3108             ast::MetaWord(ref value) => value.get() == "no_debug",
3109             _ => false
3110         }
3111     })
3112 }
3113
3114 /// Return codemap::Loc corresponding to the beginning of the span
3115 fn span_start(cx: &CrateContext, span: Span) -> codemap::Loc {
3116     cx.sess().codemap().lookup_char_pos(span.lo)
3117 }
3118
3119 fn size_and_align_of(cx: &CrateContext, llvm_type: Type) -> (u64, u64) {
3120     (machine::llsize_of_alloc(cx, llvm_type), machine::llalign_of_min(cx, llvm_type) as u64)
3121 }
3122
3123 fn bytes_to_bits(bytes: u64) -> u64 {
3124     bytes * 8
3125 }
3126
3127 #[inline]
3128 fn debug_context<'a, 'tcx>(cx: &'a CrateContext<'a, 'tcx>)
3129                            -> &'a CrateDebugContext<'tcx> {
3130     let debug_context: &'a CrateDebugContext<'tcx> = cx.dbg_cx().as_ref().unwrap();
3131     debug_context
3132 }
3133
3134 #[inline]
3135 #[allow(non_snake_case)]
3136 fn DIB(cx: &CrateContext) -> DIBuilderRef {
3137     cx.dbg_cx().as_ref().unwrap().builder
3138 }
3139
3140 fn fn_should_be_ignored(fcx: &FunctionContext) -> bool {
3141     match fcx.debug_context.repr {
3142         DebugInfo(_) => false,
3143         _ => true
3144     }
3145 }
3146
3147 fn assert_type_for_node_id(cx: &CrateContext,
3148                            node_id: ast::NodeId,
3149                            error_reporting_span: Span) {
3150     if !cx.tcx().node_types.borrow().contains_key(&node_id) {
3151         cx.sess().span_bug(error_reporting_span,
3152                            "debuginfo: Could not find type for node id!");
3153     }
3154 }
3155
3156 fn get_namespace_and_span_for_item(cx: &CrateContext, def_id: ast::DefId)
3157                                    -> (DIScope, Span) {
3158     let containing_scope = namespace_for_item(cx, def_id).scope;
3159     let definition_span = if def_id.krate == ast::LOCAL_CRATE {
3160         cx.tcx().map.span(def_id.node)
3161     } else {
3162         // For external items there is no span information
3163         codemap::DUMMY_SP
3164     };
3165
3166     (containing_scope, definition_span)
3167 }
3168
3169 // This procedure builds the *scope map* for a given function, which maps any
3170 // given ast::NodeId in the function's AST to the correct DIScope metadata instance.
3171 //
3172 // This builder procedure walks the AST in execution order and keeps track of
3173 // what belongs to which scope, creating DIScope DIEs along the way, and
3174 // introducing *artificial* lexical scope descriptors where necessary. These
3175 // artificial scopes allow GDB to correctly handle name shadowing.
3176 fn populate_scope_map(cx: &CrateContext,
3177                       args: &[ast::Arg],
3178                       fn_entry_block: &ast::Block,
3179                       fn_metadata: DISubprogram,
3180                       fn_ast_id: ast::NodeId,
3181                       scope_map: &mut NodeMap<DIScope>) {
3182     let def_map = &cx.tcx().def_map;
3183
3184     struct ScopeStackEntry {
3185         scope_metadata: DIScope,
3186         ident: Option<ast::Ident>
3187     }
3188
3189     let mut scope_stack = vec!(ScopeStackEntry { scope_metadata: fn_metadata,
3190                                                  ident: None });
3191     scope_map.insert(fn_ast_id, fn_metadata);
3192
3193     // Push argument identifiers onto the stack so arguments integrate nicely
3194     // with variable shadowing.
3195     for arg in args.iter() {
3196         pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, _, path1| {
3197             scope_stack.push(ScopeStackEntry { scope_metadata: fn_metadata,
3198                                                ident: Some(path1.node) });
3199             scope_map.insert(node_id, fn_metadata);
3200         })
3201     }
3202
3203     // Clang creates a separate scope for function bodies, so let's do this too.
3204     with_new_scope(cx,
3205                    fn_entry_block.span,
3206                    &mut scope_stack,
3207                    scope_map,
3208                    |cx, scope_stack, scope_map| {
3209         walk_block(cx, fn_entry_block, scope_stack, scope_map);
3210     });
3211
3212     // local helper functions for walking the AST.
3213     fn with_new_scope(cx: &CrateContext,
3214                       scope_span: Span,
3215                       scope_stack: &mut Vec<ScopeStackEntry> ,
3216                       scope_map: &mut NodeMap<DIScope>,
3217                       inner_walk: |&CrateContext,
3218                                    &mut Vec<ScopeStackEntry> ,
3219                                    &mut NodeMap<DIScope>|) {
3220         // Create a new lexical scope and push it onto the stack
3221         let loc = cx.sess().codemap().lookup_char_pos(scope_span.lo);
3222         let file_metadata = file_metadata(cx, loc.file.name.as_slice());
3223         let parent_scope = scope_stack.last().unwrap().scope_metadata;
3224
3225         let scope_metadata = unsafe {
3226             llvm::LLVMDIBuilderCreateLexicalBlock(
3227                 DIB(cx),
3228                 parent_scope,
3229                 file_metadata,
3230                 loc.line as c_uint,
3231                 loc.col.to_uint() as c_uint)
3232         };
3233
3234         scope_stack.push(ScopeStackEntry { scope_metadata: scope_metadata,
3235                                            ident: None });
3236
3237         inner_walk(cx, scope_stack, scope_map);
3238
3239         // pop artificial scopes
3240         while scope_stack.last().unwrap().ident.is_some() {
3241             scope_stack.pop();
3242         }
3243
3244         if scope_stack.last().unwrap().scope_metadata != scope_metadata {
3245             cx.sess().span_bug(scope_span, "debuginfo: Inconsistency in scope management.");
3246         }
3247
3248         scope_stack.pop();
3249     }
3250
3251     fn walk_block(cx: &CrateContext,
3252                   block: &ast::Block,
3253                   scope_stack: &mut Vec<ScopeStackEntry> ,
3254                   scope_map: &mut NodeMap<DIScope>) {
3255         scope_map.insert(block.id, scope_stack.last().unwrap().scope_metadata);
3256
3257         // The interesting things here are statements and the concluding expression.
3258         for statement in block.stmts.iter() {
3259             scope_map.insert(ast_util::stmt_id(&**statement),
3260                              scope_stack.last().unwrap().scope_metadata);
3261
3262             match statement.node {
3263                 ast::StmtDecl(ref decl, _) =>
3264                     walk_decl(cx, &**decl, scope_stack, scope_map),
3265                 ast::StmtExpr(ref exp, _) |
3266                 ast::StmtSemi(ref exp, _) =>
3267                     walk_expr(cx, &**exp, scope_stack, scope_map),
3268                 ast::StmtMac(..) => () // Ignore macros (which should be expanded anyway).
3269             }
3270         }
3271
3272         for exp in block.expr.iter() {
3273             walk_expr(cx, &**exp, scope_stack, scope_map);
3274         }
3275     }
3276
3277     fn walk_decl(cx: &CrateContext,
3278                  decl: &ast::Decl,
3279                  scope_stack: &mut Vec<ScopeStackEntry> ,
3280                  scope_map: &mut NodeMap<DIScope>) {
3281         match *decl {
3282             codemap::Spanned { node: ast::DeclLocal(ref local), .. } => {
3283                 scope_map.insert(local.id, scope_stack.last().unwrap().scope_metadata);
3284
3285                 walk_pattern(cx, &*local.pat, scope_stack, scope_map);
3286
3287                 for exp in local.init.iter() {
3288                     walk_expr(cx, &**exp, scope_stack, scope_map);
3289                 }
3290             }
3291             _ => ()
3292         }
3293     }
3294
3295     fn walk_pattern(cx: &CrateContext,
3296                     pat: &ast::Pat,
3297                     scope_stack: &mut Vec<ScopeStackEntry> ,
3298                     scope_map: &mut NodeMap<DIScope>) {
3299
3300         let def_map = &cx.tcx().def_map;
3301
3302         // Unfortunately, we cannot just use pat_util::pat_bindings() or
3303         // ast_util::walk_pat() here because we have to visit *all* nodes in
3304         // order to put them into the scope map. The above functions don't do that.
3305         match pat.node {
3306             ast::PatIdent(_, ref path1, ref sub_pat_opt) => {
3307
3308                 // Check if this is a binding. If so we need to put it on the
3309                 // scope stack and maybe introduce an artificial scope
3310                 if pat_util::pat_is_binding(def_map, &*pat) {
3311
3312                     let ident = path1.node;
3313
3314                     // LLVM does not properly generate 'DW_AT_start_scope' fields
3315                     // for variable DIEs. For this reason we have to introduce
3316                     // an artificial scope at bindings whenever a variable with
3317                     // the same name is declared in *any* parent scope.
3318                     //
3319                     // Otherwise the following error occurs:
3320                     //
3321                     // let x = 10;
3322                     //
3323                     // do_something(); // 'gdb print x' correctly prints 10
3324                     //
3325                     // {
3326                     //     do_something(); // 'gdb print x' prints 0, because it
3327                     //                     // already reads the uninitialized 'x'
3328                     //                     // from the next line...
3329                     //     let x = 100;
3330                     //     do_something(); // 'gdb print x' correctly prints 100
3331                     // }
3332
3333                     // Is there already a binding with that name?
3334                     // N.B.: this comparison must be UNhygienic... because
3335                     // gdb knows nothing about the context, so any two
3336                     // variables with the same name will cause the problem.
3337                     let need_new_scope = scope_stack
3338                         .iter()
3339                         .any(|entry| entry.ident.iter().any(|i| i.name == ident.name));
3340
3341                     if need_new_scope {
3342                         // Create a new lexical scope and push it onto the stack
3343                         let loc = cx.sess().codemap().lookup_char_pos(pat.span.lo);
3344                         let file_metadata = file_metadata(cx,
3345                                                           loc.file
3346                                                              .name
3347                                                              .as_slice());
3348                         let parent_scope = scope_stack.last().unwrap().scope_metadata;
3349
3350                         let scope_metadata = unsafe {
3351                             llvm::LLVMDIBuilderCreateLexicalBlock(
3352                                 DIB(cx),
3353                                 parent_scope,
3354                                 file_metadata,
3355                                 loc.line as c_uint,
3356                                 loc.col.to_uint() as c_uint)
3357                         };
3358
3359                         scope_stack.push(ScopeStackEntry {
3360                             scope_metadata: scope_metadata,
3361                             ident: Some(ident)
3362                         });
3363
3364                     } else {
3365                         // Push a new entry anyway so the name can be found
3366                         let prev_metadata = scope_stack.last().unwrap().scope_metadata;
3367                         scope_stack.push(ScopeStackEntry {
3368                             scope_metadata: prev_metadata,
3369                             ident: Some(ident)
3370                         });
3371                     }
3372                 }
3373
3374                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3375
3376                 for sub_pat in sub_pat_opt.iter() {
3377                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3378                 }
3379             }
3380
3381             ast::PatWild(_) => {
3382                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3383             }
3384
3385             ast::PatEnum(_, ref sub_pats_opt) => {
3386                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3387
3388                 for sub_pats in sub_pats_opt.iter() {
3389                     for p in sub_pats.iter() {
3390                         walk_pattern(cx, &**p, scope_stack, scope_map);
3391                     }
3392                 }
3393             }
3394
3395             ast::PatStruct(_, ref field_pats, _) => {
3396                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3397
3398                 for &codemap::Spanned {
3399                     node: ast::FieldPat { pat: ref sub_pat, .. },
3400                     ..
3401                 } in field_pats.iter() {
3402                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3403                 }
3404             }
3405
3406             ast::PatTup(ref sub_pats) => {
3407                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3408
3409                 for sub_pat in sub_pats.iter() {
3410                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3411                 }
3412             }
3413
3414             ast::PatBox(ref sub_pat) | ast::PatRegion(ref sub_pat) => {
3415                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3416                 walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3417             }
3418
3419             ast::PatLit(ref exp) => {
3420                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3421                 walk_expr(cx, &**exp, scope_stack, scope_map);
3422             }
3423
3424             ast::PatRange(ref exp1, ref exp2) => {
3425                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3426                 walk_expr(cx, &**exp1, scope_stack, scope_map);
3427                 walk_expr(cx, &**exp2, scope_stack, scope_map);
3428             }
3429
3430             ast::PatVec(ref front_sub_pats, ref middle_sub_pats, ref back_sub_pats) => {
3431                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3432
3433                 for sub_pat in front_sub_pats.iter() {
3434                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3435                 }
3436
3437                 for sub_pat in middle_sub_pats.iter() {
3438                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3439                 }
3440
3441                 for sub_pat in back_sub_pats.iter() {
3442                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3443                 }
3444             }
3445
3446             ast::PatMac(_) => {
3447                 cx.sess().span_bug(pat.span, "debuginfo::populate_scope_map() - \
3448                                               Found unexpanded macro.");
3449             }
3450         }
3451     }
3452
3453     fn walk_expr(cx: &CrateContext,
3454                  exp: &ast::Expr,
3455                  scope_stack: &mut Vec<ScopeStackEntry> ,
3456                  scope_map: &mut NodeMap<DIScope>) {
3457
3458         scope_map.insert(exp.id, scope_stack.last().unwrap().scope_metadata);
3459
3460         match exp.node {
3461             ast::ExprLit(_)   |
3462             ast::ExprBreak(_) |
3463             ast::ExprAgain(_) |
3464             ast::ExprPath(_)  => {}
3465
3466             ast::ExprCast(ref sub_exp, _)     |
3467             ast::ExprAddrOf(_, ref sub_exp)  |
3468             ast::ExprField(ref sub_exp, _) |
3469             ast::ExprTupField(ref sub_exp, _) |
3470             ast::ExprParen(ref sub_exp) =>
3471                 walk_expr(cx, &**sub_exp, scope_stack, scope_map),
3472
3473             ast::ExprBox(ref place, ref sub_expr) => {
3474                 walk_expr(cx, &**place, scope_stack, scope_map);
3475                 walk_expr(cx, &**sub_expr, scope_stack, scope_map);
3476             }
3477
3478             ast::ExprRet(ref exp_opt) => match *exp_opt {
3479                 Some(ref sub_exp) => walk_expr(cx, &**sub_exp, scope_stack, scope_map),
3480                 None => ()
3481             },
3482
3483             ast::ExprUnary(_, ref sub_exp) => {
3484                 walk_expr(cx, &**sub_exp, scope_stack, scope_map);
3485             }
3486
3487             ast::ExprAssignOp(_, ref lhs, ref rhs) |
3488             ast::ExprIndex(ref lhs, ref rhs)        |
3489             ast::ExprBinary(_, ref lhs, ref rhs)    => {
3490                 walk_expr(cx, &**lhs, scope_stack, scope_map);
3491                 walk_expr(cx, &**rhs, scope_stack, scope_map);
3492             }
3493
3494             ast::ExprSlice(ref base, ref start, ref end, _) => {
3495                 walk_expr(cx, &**base, scope_stack, scope_map);
3496                 start.as_ref().map(|x| walk_expr(cx, &**x, scope_stack, scope_map));
3497                 end.as_ref().map(|x| walk_expr(cx, &**x, scope_stack, scope_map));
3498             }
3499
3500             ast::ExprVec(ref init_expressions) |
3501             ast::ExprTup(ref init_expressions) => {
3502                 for ie in init_expressions.iter() {
3503                     walk_expr(cx, &**ie, scope_stack, scope_map);
3504                 }
3505             }
3506
3507             ast::ExprAssign(ref sub_exp1, ref sub_exp2) |
3508             ast::ExprRepeat(ref sub_exp1, ref sub_exp2) => {
3509                 walk_expr(cx, &**sub_exp1, scope_stack, scope_map);
3510                 walk_expr(cx, &**sub_exp2, scope_stack, scope_map);
3511             }
3512
3513             ast::ExprIf(ref cond_exp, ref then_block, ref opt_else_exp) => {
3514                 walk_expr(cx, &**cond_exp, scope_stack, scope_map);
3515
3516                 with_new_scope(cx,
3517                                then_block.span,
3518                                scope_stack,
3519                                scope_map,
3520                                |cx, scope_stack, scope_map| {
3521                     walk_block(cx, &**then_block, scope_stack, scope_map);
3522                 });
3523
3524                 match *opt_else_exp {
3525                     Some(ref else_exp) =>
3526                         walk_expr(cx, &**else_exp, scope_stack, scope_map),
3527                     _ => ()
3528                 }
3529             }
3530
3531             ast::ExprIfLet(..) => {
3532                 cx.sess().span_bug(exp.span, "debuginfo::populate_scope_map() - \
3533                                               Found unexpanded if-let.");
3534             }
3535
3536             ast::ExprWhile(ref cond_exp, ref loop_body, _) => {
3537                 walk_expr(cx, &**cond_exp, scope_stack, scope_map);
3538
3539                 with_new_scope(cx,
3540                                loop_body.span,
3541                                scope_stack,
3542                                scope_map,
3543                                |cx, scope_stack, scope_map| {
3544                     walk_block(cx, &**loop_body, scope_stack, scope_map);
3545                 })
3546             }
3547
3548             ast::ExprWhileLet(..) => {
3549                 cx.sess().span_bug(exp.span, "debuginfo::populate_scope_map() - \
3550                                               Found unexpanded while-let.");
3551             }
3552
3553             ast::ExprForLoop(ref pattern, ref head, ref body, _) => {
3554                 walk_expr(cx, &**head, scope_stack, scope_map);
3555
3556                 with_new_scope(cx,
3557                                exp.span,
3558                                scope_stack,
3559                                scope_map,
3560                                |cx, scope_stack, scope_map| {
3561                     scope_map.insert(exp.id,
3562                                      scope_stack.last()
3563                                                 .unwrap()
3564                                                 .scope_metadata);
3565                     walk_pattern(cx,
3566                                  &**pattern,
3567                                  scope_stack,
3568                                  scope_map);
3569                     walk_block(cx, &**body, scope_stack, scope_map);
3570                 })
3571             }
3572
3573             ast::ExprMac(_) => {
3574                 cx.sess().span_bug(exp.span, "debuginfo::populate_scope_map() - \
3575                                               Found unexpanded macro.");
3576             }
3577
3578             ast::ExprLoop(ref block, _) |
3579             ast::ExprBlock(ref block)   => {
3580                 with_new_scope(cx,
3581                                block.span,
3582                                scope_stack,
3583                                scope_map,
3584                                |cx, scope_stack, scope_map| {
3585                     walk_block(cx, &**block, scope_stack, scope_map);
3586                 })
3587             }
3588
3589             ast::ExprProc(ref decl, ref block) |
3590             ast::ExprClosure(_, _, ref decl, ref block) => {
3591                 with_new_scope(cx,
3592                                block.span,
3593                                scope_stack,
3594                                scope_map,
3595                                |cx, scope_stack, scope_map| {
3596                     for &ast::Arg { pat: ref pattern, .. } in decl.inputs.iter() {
3597                         walk_pattern(cx, &**pattern, scope_stack, scope_map);
3598                     }
3599
3600                     walk_block(cx, &**block, scope_stack, scope_map);
3601                 })
3602             }
3603
3604             ast::ExprCall(ref fn_exp, ref args) => {
3605                 walk_expr(cx, &**fn_exp, scope_stack, scope_map);
3606
3607                 for arg_exp in args.iter() {
3608                     walk_expr(cx, &**arg_exp, scope_stack, scope_map);
3609                 }
3610             }
3611
3612             ast::ExprMethodCall(_, _, ref args) => {
3613                 for arg_exp in args.iter() {
3614                     walk_expr(cx, &**arg_exp, scope_stack, scope_map);
3615                 }
3616             }
3617
3618             ast::ExprMatch(ref discriminant_exp, ref arms, _) => {
3619                 walk_expr(cx, &**discriminant_exp, scope_stack, scope_map);
3620
3621                 // For each arm we have to first walk the pattern as these might
3622                 // introduce new artificial scopes. It should be sufficient to
3623                 // walk only one pattern per arm, as they all must contain the
3624                 // same binding names.
3625
3626                 for arm_ref in arms.iter() {
3627                     let arm_span = arm_ref.pats[0].span;
3628
3629                     with_new_scope(cx,
3630                                    arm_span,
3631                                    scope_stack,
3632                                    scope_map,
3633                                    |cx, scope_stack, scope_map| {
3634                         for pat in arm_ref.pats.iter() {
3635                             walk_pattern(cx, &**pat, scope_stack, scope_map);
3636                         }
3637
3638                         for guard_exp in arm_ref.guard.iter() {
3639                             walk_expr(cx, &**guard_exp, scope_stack, scope_map)
3640                         }
3641
3642                         walk_expr(cx, &*arm_ref.body, scope_stack, scope_map);
3643                     })
3644                 }
3645             }
3646
3647             ast::ExprStruct(_, ref fields, ref base_exp) => {
3648                 for &ast::Field { expr: ref exp, .. } in fields.iter() {
3649                     walk_expr(cx, &**exp, scope_stack, scope_map);
3650                 }
3651
3652                 match *base_exp {
3653                     Some(ref exp) => walk_expr(cx, &**exp, scope_stack, scope_map),
3654                     None => ()
3655                 }
3656             }
3657
3658             ast::ExprInlineAsm(ast::InlineAsm { ref inputs,
3659                                                 ref outputs,
3660                                                 .. }) => {
3661                 // inputs, outputs: Vec<(String, P<Expr>)>
3662                 for &(_, ref exp) in inputs.iter() {
3663                     walk_expr(cx, &**exp, scope_stack, scope_map);
3664                 }
3665
3666                 for &(_, ref exp, _) in outputs.iter() {
3667                     walk_expr(cx, &**exp, scope_stack, scope_map);
3668                 }
3669             }
3670         }
3671     }
3672 }
3673
3674
3675 //=-----------------------------------------------------------------------------
3676 // Type Names for Debug Info
3677 //=-----------------------------------------------------------------------------
3678
3679 // Compute the name of the type as it should be stored in debuginfo. Does not do
3680 // any caching, i.e. calling the function twice with the same type will also do
3681 // the work twice. The `qualified` parameter only affects the first level of the
3682 // type name, further levels (i.e. type parameters) are always fully qualified.
3683 fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
3684                                          t: Ty<'tcx>,
3685                                          qualified: bool)
3686                                          -> String {
3687     let mut result = String::with_capacity(64);
3688     push_debuginfo_type_name(cx, t, qualified, &mut result);
3689     result
3690 }
3691
3692 // Pushes the name of the type as it should be stored in debuginfo on the
3693 // `output` String. See also compute_debuginfo_type_name().
3694 fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
3695                                       t: Ty<'tcx>,
3696                                       qualified: bool,
3697                                       output: &mut String) {
3698     match t.sty {
3699         ty::ty_bool              => output.push_str("bool"),
3700         ty::ty_char              => output.push_str("char"),
3701         ty::ty_str               => output.push_str("str"),
3702         ty::ty_int(ast::TyI)     => output.push_str("int"),
3703         ty::ty_int(ast::TyI8)    => output.push_str("i8"),
3704         ty::ty_int(ast::TyI16)   => output.push_str("i16"),
3705         ty::ty_int(ast::TyI32)   => output.push_str("i32"),
3706         ty::ty_int(ast::TyI64)   => output.push_str("i64"),
3707         ty::ty_uint(ast::TyU)    => output.push_str("uint"),
3708         ty::ty_uint(ast::TyU8)   => output.push_str("u8"),
3709         ty::ty_uint(ast::TyU16)  => output.push_str("u16"),
3710         ty::ty_uint(ast::TyU32)  => output.push_str("u32"),
3711         ty::ty_uint(ast::TyU64)  => output.push_str("u64"),
3712         ty::ty_float(ast::TyF32) => output.push_str("f32"),
3713         ty::ty_float(ast::TyF64) => output.push_str("f64"),
3714         ty::ty_struct(def_id, ref substs) |
3715         ty::ty_enum(def_id, ref substs) => {
3716             push_item_name(cx, def_id, qualified, output);
3717             push_type_params(cx, substs, output);
3718         },
3719         ty::ty_tup(ref component_types) => {
3720             output.push('(');
3721             for &component_type in component_types.iter() {
3722                 push_debuginfo_type_name(cx, component_type, true, output);
3723                 output.push_str(", ");
3724             }
3725             if !component_types.is_empty() {
3726                 output.pop();
3727                 output.pop();
3728             }
3729             output.push(')');
3730         },
3731         ty::ty_uniq(inner_type) => {
3732             output.push_str("Box<");
3733             push_debuginfo_type_name(cx, inner_type, true, output);
3734             output.push('>');
3735         },
3736         ty::ty_ptr(ty::mt { ty: inner_type, mutbl } ) => {
3737             output.push('*');
3738             match mutbl {
3739                 ast::MutImmutable => output.push_str("const "),
3740                 ast::MutMutable => output.push_str("mut "),
3741             }
3742
3743             push_debuginfo_type_name(cx, inner_type, true, output);
3744         },
3745         ty::ty_rptr(_, ty::mt { ty: inner_type, mutbl }) => {
3746             output.push('&');
3747             if mutbl == ast::MutMutable {
3748                 output.push_str("mut ");
3749             }
3750
3751             push_debuginfo_type_name(cx, inner_type, true, output);
3752         },
3753         ty::ty_vec(inner_type, optional_length) => {
3754             output.push('[');
3755             push_debuginfo_type_name(cx, inner_type, true, output);
3756
3757             match optional_length {
3758                 Some(len) => {
3759                     output.push_str(format!(", ..{}", len).as_slice());
3760                 }
3761                 None => { /* nothing to do */ }
3762             };
3763
3764             output.push(']');
3765         },
3766         ty::ty_trait(ref trait_data) => {
3767             push_item_name(cx, trait_data.principal.def_id, false, output);
3768             push_type_params(cx, &trait_data.principal.substs, output);
3769         },
3770         ty::ty_bare_fn(ty::BareFnTy{ fn_style, abi, ref sig } ) => {
3771             if fn_style == ast::UnsafeFn {
3772                 output.push_str("unsafe ");
3773             }
3774
3775             if abi != ::syntax::abi::Rust {
3776                 output.push_str("extern \"");
3777                 output.push_str(abi.name());
3778                 output.push_str("\" ");
3779             }
3780
3781             output.push_str("fn(");
3782
3783             if sig.inputs.len() > 0 {
3784                 for &parameter_type in sig.inputs.iter() {
3785                     push_debuginfo_type_name(cx, parameter_type, true, output);
3786                     output.push_str(", ");
3787                 }
3788                 output.pop();
3789                 output.pop();
3790             }
3791
3792             if sig.variadic {
3793                 if sig.inputs.len() > 0 {
3794                     output.push_str(", ...");
3795                 } else {
3796                     output.push_str("...");
3797                 }
3798             }
3799
3800             output.push(')');
3801
3802             match sig.output {
3803                 ty::FnConverging(result_type) if ty::type_is_nil(result_type) => {}
3804                 ty::FnConverging(result_type) => {
3805                     output.push_str(" -> ");
3806                     push_debuginfo_type_name(cx, result_type, true, output);
3807                 }
3808                 ty::FnDiverging => {
3809                     output.push_str(" -> !");
3810                 }
3811             }
3812         },
3813         ty::ty_closure(box ty::ClosureTy { fn_style,
3814                                            onceness,
3815                                            store,
3816                                            ref sig,
3817                                            .. // omitting bounds ...
3818                                            }) => {
3819             if fn_style == ast::UnsafeFn {
3820                 output.push_str("unsafe ");
3821             }
3822
3823             if onceness == ast::Once {
3824                 output.push_str("once ");
3825             }
3826
3827             let param_list_closing_char;
3828             match store {
3829                 ty::UniqTraitStore => {
3830                     output.push_str("proc(");
3831                     param_list_closing_char = ')';
3832                 }
3833                 ty::RegionTraitStore(_, ast::MutMutable) => {
3834                     output.push_str("&mut|");
3835                     param_list_closing_char = '|';
3836                 }
3837                 ty::RegionTraitStore(_, ast::MutImmutable) => {
3838                     output.push_str("&|");
3839                     param_list_closing_char = '|';
3840                 }
3841             };
3842
3843             if sig.inputs.len() > 0 {
3844                 for &parameter_type in sig.inputs.iter() {
3845                     push_debuginfo_type_name(cx, parameter_type, true, output);
3846                     output.push_str(", ");
3847                 }
3848                 output.pop();
3849                 output.pop();
3850             }
3851
3852             if sig.variadic {
3853                 if sig.inputs.len() > 0 {
3854                     output.push_str(", ...");
3855                 } else {
3856                     output.push_str("...");
3857                 }
3858             }
3859
3860             output.push(param_list_closing_char);
3861
3862             match sig.output {
3863                 ty::FnConverging(result_type) if ty::type_is_nil(result_type) => {}
3864                 ty::FnConverging(result_type) => {
3865                     output.push_str(" -> ");
3866                     push_debuginfo_type_name(cx, result_type, true, output);
3867                 }
3868                 ty::FnDiverging => {
3869                     output.push_str(" -> !");
3870                 }
3871             }
3872         },
3873         ty::ty_unboxed_closure(..) => {
3874             output.push_str("closure");
3875         }
3876         ty::ty_err      |
3877         ty::ty_infer(_) |
3878         ty::ty_open(_) |
3879         ty::ty_param(_) => {
3880             cx.sess().bug(format!("debuginfo: Trying to create type name for \
3881                 unexpected type: {}", ppaux::ty_to_string(cx.tcx(), t)).as_slice());
3882         }
3883     }
3884
3885     fn push_item_name(cx: &CrateContext,
3886                       def_id: ast::DefId,
3887                       qualified: bool,
3888                       output: &mut String) {
3889         ty::with_path(cx.tcx(), def_id, |mut path| {
3890             if qualified {
3891                 if def_id.krate == ast::LOCAL_CRATE {
3892                     output.push_str(crate_root_namespace(cx));
3893                     output.push_str("::");
3894                 }
3895
3896                 let mut path_element_count = 0u;
3897                 for path_element in path {
3898                     let name = token::get_name(path_element.name());
3899                     output.push_str(name.get());
3900                     output.push_str("::");
3901                     path_element_count += 1;
3902                 }
3903
3904                 if path_element_count == 0 {
3905                     cx.sess().bug("debuginfo: Encountered empty item path!");
3906                 }
3907
3908                 output.pop();
3909                 output.pop();
3910             } else {
3911                 let name = token::get_name(path.last()
3912                                                .expect("debuginfo: Empty item path?")
3913                                                .name());
3914                 output.push_str(name.get());
3915             }
3916         });
3917     }
3918
3919     // Pushes the type parameters in the given `Substs` to the output string.
3920     // This ignores region parameters, since they can't reliably be
3921     // reconstructed for items from non-local crates. For local crates, this
3922     // would be possible but with inlining and LTO we have to use the least
3923     // common denominator - otherwise we would run into conflicts.
3924     fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
3925                                   substs: &subst::Substs<'tcx>,
3926                                   output: &mut String) {
3927         if substs.types.is_empty() {
3928             return;
3929         }
3930
3931         output.push('<');
3932
3933         for &type_parameter in substs.types.iter() {
3934             push_debuginfo_type_name(cx, type_parameter, true, output);
3935             output.push_str(", ");
3936         }
3937
3938         output.pop();
3939         output.pop();
3940
3941         output.push('>');
3942     }
3943 }
3944
3945
3946 //=-----------------------------------------------------------------------------
3947 // Namespace Handling
3948 //=-----------------------------------------------------------------------------
3949
3950 struct NamespaceTreeNode {
3951     name: ast::Name,
3952     scope: DIScope,
3953     parent: Option<Weak<NamespaceTreeNode>>,
3954 }
3955
3956 impl NamespaceTreeNode {
3957     fn mangled_name_of_contained_item(&self, item_name: &str) -> String {
3958         fn fill_nested(node: &NamespaceTreeNode, output: &mut String) {
3959             match node.parent {
3960                 Some(ref parent) => fill_nested(&*parent.upgrade().unwrap(), output),
3961                 None => {}
3962             }
3963             let string = token::get_name(node.name);
3964             output.push_str(format!("{}", string.get().len()).as_slice());
3965             output.push_str(string.get());
3966         }
3967
3968         let mut name = String::from_str("_ZN");
3969         fill_nested(self, &mut name);
3970         name.push_str(format!("{}", item_name.len()).as_slice());
3971         name.push_str(item_name);
3972         name.push('E');
3973         name
3974     }
3975 }
3976
3977 fn crate_root_namespace<'a>(cx: &'a CrateContext) -> &'a str {
3978     cx.link_meta().crate_name.as_slice()
3979 }
3980
3981 fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTreeNode> {
3982     ty::with_path(cx.tcx(), def_id, |path| {
3983         // prepend crate name if not already present
3984         let krate = if def_id.krate == ast::LOCAL_CRATE {
3985             let crate_namespace_ident = token::str_to_ident(crate_root_namespace(cx));
3986             Some(ast_map::PathMod(crate_namespace_ident.name))
3987         } else {
3988             None
3989         };
3990         let mut path = krate.into_iter().chain(path).peekable();
3991
3992         let mut current_key = Vec::new();
3993         let mut parent_node: Option<Rc<NamespaceTreeNode>> = None;
3994
3995         // Create/Lookup namespace for each element of the path.
3996         loop {
3997             // Emulate a for loop so we can use peek below.
3998             let path_element = match path.next() {
3999                 Some(e) => e,
4000                 None => break
4001             };
4002             // Ignore the name of the item (the last path element).
4003             if path.peek().is_none() {
4004                 break;
4005             }
4006
4007             let name = path_element.name();
4008             current_key.push(name);
4009
4010             let existing_node = debug_context(cx).namespace_map.borrow()
4011                                                  .get(&current_key).cloned();
4012             let current_node = match existing_node {
4013                 Some(existing_node) => existing_node,
4014                 None => {
4015                     // create and insert
4016                     let parent_scope = match parent_node {
4017                         Some(ref node) => node.scope,
4018                         None => ptr::null_mut()
4019                     };
4020                     let namespace_name = token::get_name(name);
4021                     let scope = namespace_name.get().with_c_str(|namespace_name| {
4022                         unsafe {
4023                             llvm::LLVMDIBuilderCreateNameSpace(
4024                                 DIB(cx),
4025                                 parent_scope,
4026                                 namespace_name,
4027                                 // cannot reconstruct file ...
4028                                 ptr::null_mut(),
4029                                 // ... or line information, but that's not so important.
4030                                 0)
4031                         }
4032                     });
4033
4034                     let node = Rc::new(NamespaceTreeNode {
4035                         name: name,
4036                         scope: scope,
4037                         parent: parent_node.map(|parent| parent.downgrade()),
4038                     });
4039
4040                     debug_context(cx).namespace_map.borrow_mut()
4041                                      .insert(current_key.clone(), node.clone());
4042
4043                     node
4044                 }
4045             };
4046
4047             parent_node = Some(current_node);
4048         }
4049
4050         match parent_node {
4051             Some(node) => node,
4052             None => {
4053                 cx.sess().bug(format!("debuginfo::namespace_for_item(): \
4054                                        path too short for {}",
4055                                       def_id).as_slice());
4056             }
4057         }
4058     })
4059 }