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