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