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