]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/debuginfo/mod.rs
Auto merge of #35174 - arielb1:llvm-type-audit, r=eddyb
[rust.git] / src / librustc_trans / debuginfo / mod.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // See doc.rs for documentation.
12 mod doc;
13
14 use self::VariableAccess::*;
15 use self::VariableKind::*;
16
17 use self::utils::{DIB, span_start, create_DIArray, is_node_local_to_unit};
18 use self::namespace::mangled_name_of_item;
19 use self::type_names::compute_debuginfo_type_name;
20 use self::metadata::{type_metadata, diverging_type_metadata};
21 use self::metadata::{file_metadata, scope_metadata, TypeMap};
22 use self::source_loc::InternalDebugLocation::{self, UnknownLocation};
23
24 use llvm;
25 use llvm::{ModuleRef, ContextRef, ValueRef};
26 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilderRef, DISubprogram, DIArray,
27                       FlagPrototyped};
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::map::DefPathData;
30 use rustc::ty::subst::Substs;
31 use rustc::hir;
32
33 use abi::Abi;
34 use common::{NodeIdAndSpan, CrateContext, FunctionContext, Block, BlockAndBuilder};
35 use inline;
36 use monomorphize::{self, Instance};
37 use rustc::ty::{self, Ty};
38 use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
39 use util::nodemap::{DefIdMap, NodeMap, FnvHashMap, FnvHashSet};
40
41 use libc::c_uint;
42 use std::cell::{Cell, RefCell};
43 use std::ffi::CString;
44 use std::ptr;
45
46 use syntax_pos::{self, Span, Pos};
47 use syntax::ast;
48 use syntax::attr::IntType;
49
50 pub mod gdb;
51 mod utils;
52 mod namespace;
53 mod type_names;
54 pub mod metadata;
55 mod create_scope_map;
56 mod source_loc;
57
58 pub use self::create_scope_map::create_mir_scopes;
59 pub use self::source_loc::start_emitting_source_locations;
60 pub use self::source_loc::get_cleanup_debug_loc_for_ast_node;
61 pub use self::source_loc::with_source_location_override;
62 pub use self::metadata::create_match_binding_metadata;
63 pub use self::metadata::create_argument_metadata;
64 pub use self::metadata::create_captured_var_metadata;
65 pub use self::metadata::create_global_var_metadata;
66 pub use self::metadata::create_local_var_metadata;
67
68 #[allow(non_upper_case_globals)]
69 const DW_TAG_auto_variable: c_uint = 0x100;
70 #[allow(non_upper_case_globals)]
71 const DW_TAG_arg_variable: c_uint = 0x101;
72
73 /// A context object for maintaining all state needed by the debuginfo module.
74 pub struct CrateDebugContext<'tcx> {
75     llcontext: ContextRef,
76     builder: DIBuilderRef,
77     current_debug_location: Cell<InternalDebugLocation>,
78     created_files: RefCell<FnvHashMap<String, DIFile>>,
79     created_enum_disr_types: RefCell<FnvHashMap<(DefId, IntType), DIType>>,
80
81     type_map: RefCell<TypeMap<'tcx>>,
82     namespace_map: RefCell<DefIdMap<DIScope>>,
83
84     // This collection is used to assert that composite types (structs, enums,
85     // ...) have their members only set once:
86     composite_types_completed: RefCell<FnvHashSet<DIType>>,
87 }
88
89 impl<'tcx> CrateDebugContext<'tcx> {
90     pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
91         debug!("CrateDebugContext::new");
92         let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
93         // DIBuilder inherits context from the module, so we'd better use the same one
94         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
95         return CrateDebugContext {
96             llcontext: llcontext,
97             builder: builder,
98             current_debug_location: Cell::new(InternalDebugLocation::UnknownLocation),
99             created_files: RefCell::new(FnvHashMap()),
100             created_enum_disr_types: RefCell::new(FnvHashMap()),
101             type_map: RefCell::new(TypeMap::new()),
102             namespace_map: RefCell::new(DefIdMap()),
103             composite_types_completed: RefCell::new(FnvHashSet()),
104         };
105     }
106 }
107
108 pub enum FunctionDebugContext {
109     RegularContext(Box<FunctionDebugContextData>),
110     DebugInfoDisabled,
111     FunctionWithoutDebugInfo,
112 }
113
114 impl FunctionDebugContext {
115     fn get_ref<'a>(&'a self,
116                    span: Span)
117                    -> &'a FunctionDebugContextData {
118         match *self {
119             FunctionDebugContext::RegularContext(box ref data) => data,
120             FunctionDebugContext::DebugInfoDisabled => {
121                 span_bug!(span,
122                           "{}",
123                           FunctionDebugContext::debuginfo_disabled_message());
124             }
125             FunctionDebugContext::FunctionWithoutDebugInfo => {
126                 span_bug!(span,
127                           "{}",
128                           FunctionDebugContext::should_be_ignored_message());
129             }
130         }
131     }
132
133     fn debuginfo_disabled_message() -> &'static str {
134         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
135     }
136
137     fn should_be_ignored_message() -> &'static str {
138         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
139          ignored by debug info!"
140     }
141 }
142
143 pub struct FunctionDebugContextData {
144     scope_map: RefCell<NodeMap<DIScope>>,
145     fn_metadata: DISubprogram,
146     argument_counter: Cell<usize>,
147     source_locations_enabled: Cell<bool>,
148     source_location_override: Cell<bool>,
149 }
150
151 pub enum VariableAccess<'a> {
152     // The llptr given is an alloca containing the variable's value
153     DirectVariable { alloca: ValueRef },
154     // The llptr given is an alloca containing the start of some pointer chain
155     // leading to the variable's content.
156     IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] }
157 }
158
159 pub enum VariableKind {
160     ArgumentVariable(usize /*index*/),
161     LocalVariable,
162     CapturedVariable,
163 }
164
165 /// Create any deferred debug metadata nodes
166 pub fn finalize(cx: &CrateContext) {
167     if cx.dbg_cx().is_none() {
168         return;
169     }
170
171     debug!("finalize");
172
173     if gdb::needs_gdb_debug_scripts_section(cx) {
174         // Add a .debug_gdb_scripts section to this compile-unit. This will
175         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
176         // which activates the Rust pretty printers for binary this section is
177         // contained in.
178         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
179     }
180
181     unsafe {
182         llvm::LLVMRustDIBuilderFinalize(DIB(cx));
183         llvm::LLVMRustDIBuilderDispose(DIB(cx));
184         // Debuginfo generation in LLVM by default uses a higher
185         // version of dwarf than OS X currently understands. We can
186         // instruct LLVM to emit an older version of dwarf, however,
187         // for OS X to understand. For more info see #11352
188         // This can be overridden using --llvm-opts -dwarf-version,N.
189         // Android has the same issue (#22398)
190         if cx.sess().target.target.options.is_like_osx ||
191            cx.sess().target.target.options.is_like_android {
192             llvm::LLVMRustAddModuleFlag(cx.llmod(),
193                                         "Dwarf Version\0".as_ptr() as *const _,
194                                         2)
195         }
196
197         // Indicate that we want CodeView debug information on MSVC
198         if cx.sess().target.target.options.is_like_msvc {
199             llvm::LLVMRustAddModuleFlag(cx.llmod(),
200                                         "CodeView\0".as_ptr() as *const _,
201                                         1)
202         }
203
204         // Prevent bitcode readers from deleting the debug info.
205         let ptr = "Debug Info Version\0".as_ptr();
206         llvm::LLVMRustAddModuleFlag(cx.llmod(), ptr as *const _,
207                                     llvm::LLVMRustDebugMetadataVersion());
208     };
209 }
210
211 /// Creates a function-specific debug context for a function w/o debuginfo.
212 pub fn empty_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>)
213                                               -> FunctionDebugContext {
214     if cx.sess().opts.debuginfo == NoDebugInfo {
215         return FunctionDebugContext::DebugInfoDisabled;
216     }
217
218     // Clear the debug location so we don't assign them in the function prelude.
219     source_loc::set_debug_location(cx, None, UnknownLocation);
220     FunctionDebugContext::FunctionWithoutDebugInfo
221 }
222
223 /// Creates the function-specific debug context.
224 ///
225 /// Returns the FunctionDebugContext for the function which holds state needed
226 /// for debug info creation. The function may also return another variant of the
227 /// FunctionDebugContext enum which indicates why no debuginfo should be created
228 /// for the function.
229 pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
230                                                instance: Instance<'tcx>,
231                                                sig: &ty::FnSig<'tcx>,
232                                                abi: Abi,
233                                                llfn: ValueRef) -> FunctionDebugContext {
234     if cx.sess().opts.debuginfo == NoDebugInfo {
235         return FunctionDebugContext::DebugInfoDisabled;
236     }
237
238     // Clear the debug location so we don't assign them in the function prelude.
239     // Do this here already, in case we do an early exit from this function.
240     source_loc::set_debug_location(cx, None, UnknownLocation);
241
242     let instance = inline::maybe_inline_instance(cx, instance);
243     let (containing_scope, span) = get_containing_scope_and_span(cx, instance);
244
245     // This can be the case for functions inlined from another crate
246     if span == syntax_pos::DUMMY_SP {
247         return FunctionDebugContext::FunctionWithoutDebugInfo;
248     }
249
250     let loc = span_start(cx, span);
251     let file_metadata = file_metadata(cx, &loc.file.name, &loc.file.abs_path);
252
253     let function_type_metadata = unsafe {
254         let fn_signature = get_function_signature(cx, sig, abi);
255         llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
256     };
257
258     // Find the enclosing function, in case this is a closure.
259     let mut fn_def_id = instance.def;
260     let mut def_key = cx.tcx().def_key(fn_def_id);
261     let mut name = def_key.disambiguated_data.data.to_string();
262     let name_len = name.len();
263     while def_key.disambiguated_data.data == DefPathData::ClosureExpr {
264         fn_def_id.index = def_key.parent.expect("closure without a parent?");
265         def_key = cx.tcx().def_key(fn_def_id);
266     }
267
268     // Get_template_parameters() will append a `<...>` clause to the function
269     // name if necessary.
270     let generics = cx.tcx().lookup_item_type(fn_def_id).generics;
271     let template_parameters = get_template_parameters(cx,
272                                                       &generics,
273                                                       instance.substs,
274                                                       file_metadata,
275                                                       &mut name);
276
277     // Build the linkage_name out of the item path and "template" parameters.
278     let linkage_name = mangled_name_of_item(cx, instance.def, &name[name_len..]);
279
280     let scope_line = span_start(cx, span).line;
281
282     let local_id = cx.tcx().map.as_local_node_id(instance.def);
283     let is_local_to_unit = local_id.map_or(false, |id| is_node_local_to_unit(cx, id));
284
285     let function_name = CString::new(name).unwrap();
286     let linkage_name = CString::new(linkage_name).unwrap();
287
288     let fn_metadata = unsafe {
289         llvm::LLVMRustDIBuilderCreateFunction(
290             DIB(cx),
291             containing_scope,
292             function_name.as_ptr(),
293             linkage_name.as_ptr(),
294             file_metadata,
295             loc.line as c_uint,
296             function_type_metadata,
297             is_local_to_unit,
298             true,
299             scope_line as c_uint,
300             FlagPrototyped as c_uint,
301             cx.sess().opts.optimize != config::OptLevel::No,
302             llfn,
303             template_parameters,
304             ptr::null_mut())
305     };
306
307     // Initialize fn debug context (including scope map and namespace map)
308     let fn_debug_context = box FunctionDebugContextData {
309         scope_map: RefCell::new(NodeMap()),
310         fn_metadata: fn_metadata,
311         argument_counter: Cell::new(1),
312         source_locations_enabled: Cell::new(false),
313         source_location_override: Cell::new(false),
314     };
315
316     return FunctionDebugContext::RegularContext(fn_debug_context);
317
318     fn get_function_signature<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
319                                         sig: &ty::FnSig<'tcx>,
320                                         abi: Abi) -> DIArray {
321         if cx.sess().opts.debuginfo == LimitedDebugInfo {
322             return create_DIArray(DIB(cx), &[]);
323         }
324
325         let mut signature = Vec::with_capacity(sig.inputs.len() + 1);
326
327         // Return type -- llvm::DIBuilder wants this at index 0
328         signature.push(match sig.output {
329             ty::FnConverging(ret_ty) => match ret_ty.sty {
330                 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
331                 _ => type_metadata(cx, ret_ty, syntax_pos::DUMMY_SP)
332             },
333             ty::FnDiverging => diverging_type_metadata(cx)
334         });
335
336         let inputs = if abi == Abi::RustCall {
337             &sig.inputs[..sig.inputs.len()-1]
338         } else {
339             &sig.inputs[..]
340         };
341
342         // Arguments types
343         for &argument_type in inputs {
344             signature.push(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP));
345         }
346
347         if abi == Abi::RustCall && !sig.inputs.is_empty() {
348             if let ty::TyTuple(args) = sig.inputs[sig.inputs.len() - 1].sty {
349                 for &argument_type in args {
350                     signature.push(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP));
351                 }
352             }
353         }
354
355         return create_DIArray(DIB(cx), &signature[..]);
356     }
357
358     fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
359                                          generics: &ty::Generics<'tcx>,
360                                          param_substs: &Substs<'tcx>,
361                                          file_metadata: DIFile,
362                                          name_to_append_suffix_to: &mut String)
363                                          -> DIArray
364     {
365         let actual_types = param_substs.types.as_slice();
366
367         if actual_types.is_empty() {
368             return create_DIArray(DIB(cx), &[]);
369         }
370
371         name_to_append_suffix_to.push('<');
372         for (i, &actual_type) in actual_types.iter().enumerate() {
373             let actual_type = cx.tcx().normalize_associated_type(&actual_type);
374             // Add actual type name to <...> clause of function name
375             let actual_type_name = compute_debuginfo_type_name(cx,
376                                                                actual_type,
377                                                                true);
378             name_to_append_suffix_to.push_str(&actual_type_name[..]);
379
380             if i != actual_types.len() - 1 {
381                 name_to_append_suffix_to.push_str(",");
382             }
383         }
384         name_to_append_suffix_to.push('>');
385
386         // Again, only create type information if full debuginfo is enabled
387         let template_params: Vec<_> = if cx.sess().opts.debuginfo == FullDebugInfo {
388             generics.types.as_slice().iter().enumerate().map(|(i, param)| {
389                 let actual_type = cx.tcx().normalize_associated_type(&actual_types[i]);
390                 let actual_type_metadata = type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
391                 let name = CString::new(param.name.as_str().as_bytes()).unwrap();
392                 unsafe {
393                     llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
394                         DIB(cx),
395                         ptr::null_mut(),
396                         name.as_ptr(),
397                         actual_type_metadata,
398                         file_metadata,
399                         0,
400                         0)
401                 }
402             }).collect()
403         } else {
404             vec![]
405         };
406
407         return create_DIArray(DIB(cx), &template_params[..]);
408     }
409
410     fn get_containing_scope_and_span<'ccx, 'tcx>(cx: &CrateContext<'ccx, 'tcx>,
411                                                  instance: Instance<'tcx>)
412                                                  -> (DIScope, Span) {
413         // First, let's see if this is a method within an inherent impl. Because
414         // if yes, we want to make the result subroutine DIE a child of the
415         // subroutine's self-type.
416         let self_type = cx.tcx().impl_of_method(instance.def).and_then(|impl_def_id| {
417             // If the method does *not* belong to a trait, proceed
418             if cx.tcx().trait_id_of_impl(impl_def_id).is_none() {
419                 let impl_self_ty = cx.tcx().lookup_item_type(impl_def_id).ty;
420                 let impl_self_ty = cx.tcx().erase_regions(&impl_self_ty);
421                 let impl_self_ty = monomorphize::apply_param_substs(cx.tcx(),
422                                                                     instance.substs,
423                                                                     &impl_self_ty);
424                 Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
425             } else {
426                 // For trait method impls we still use the "parallel namespace"
427                 // strategy
428                 None
429             }
430         });
431
432         let containing_scope = self_type.unwrap_or_else(|| {
433             namespace::item_namespace(cx, DefId {
434                 krate: instance.def.krate,
435                 index: cx.tcx()
436                          .def_key(instance.def)
437                          .parent
438                          .expect("get_containing_scope_and_span: missing parent?")
439             })
440         });
441
442         // Try to get some span information, if we have an inlined item.
443         let definition_span = cx.tcx()
444                                 .map
445                                 .def_id_span(instance.def, syntax_pos::DUMMY_SP);
446
447         (containing_scope, definition_span)
448     }
449 }
450
451 /// Computes the scope map for a function given its declaration and body.
452 pub fn fill_scope_map_for_function<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
453                                              fn_decl: &hir::FnDecl,
454                                              top_level_block: &hir::Block,
455                                              fn_ast_id: ast::NodeId) {
456     match fcx.debug_context {
457         FunctionDebugContext::RegularContext(box ref data) => {
458             let scope_map = create_scope_map::create_scope_map(fcx.ccx,
459                                                                &fn_decl.inputs,
460                                                                top_level_block,
461                                                                data.fn_metadata,
462                                                                fn_ast_id);
463             *data.scope_map.borrow_mut() = scope_map;
464         }
465         FunctionDebugContext::DebugInfoDisabled |
466         FunctionDebugContext::FunctionWithoutDebugInfo => {}
467     }
468 }
469
470 pub fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
471                                  variable_name: ast::Name,
472                                  variable_type: Ty<'tcx>,
473                                  scope_metadata: DIScope,
474                                  variable_access: VariableAccess,
475                                  variable_kind: VariableKind,
476                                  span: Span) {
477     let cx: &CrateContext = bcx.ccx();
478
479     let file = span_start(cx, span).file;
480     let filename = file.name.clone();
481     let file_metadata = file_metadata(cx, &filename[..], &file.abs_path);
482
483     let loc = span_start(cx, span);
484     let type_metadata = type_metadata(cx, variable_type, span);
485
486     let (argument_index, dwarf_tag) = match variable_kind {
487         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
488         LocalVariable    |
489         CapturedVariable => (0, DW_TAG_auto_variable)
490     };
491
492     let name = CString::new(variable_name.as_str().as_bytes()).unwrap();
493     match (variable_access, &[][..]) {
494         (DirectVariable { alloca }, address_operations) |
495         (IndirectVariable {alloca, address_operations}, _) => {
496             let metadata = unsafe {
497                 llvm::LLVMRustDIBuilderCreateVariable(
498                     DIB(cx),
499                     dwarf_tag,
500                     scope_metadata,
501                     name.as_ptr(),
502                     file_metadata,
503                     loc.line as c_uint,
504                     type_metadata,
505                     cx.sess().opts.optimize != config::OptLevel::No,
506                     0,
507                     address_operations.as_ptr(),
508                     address_operations.len() as c_uint,
509                     argument_index)
510             };
511             source_loc::set_debug_location(cx, None,
512                 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
513             unsafe {
514                 let debug_loc = llvm::LLVMGetCurrentDebugLocation(cx.raw_builder());
515                 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
516                     DIB(cx),
517                     alloca,
518                     metadata,
519                     address_operations.as_ptr(),
520                     address_operations.len() as c_uint,
521                     debug_loc,
522                     bcx.llbb);
523
524                 llvm::LLVMSetInstDebugLocation(::build::B(bcx).llbuilder, instr);
525             }
526         }
527     }
528
529     match variable_kind {
530         ArgumentVariable(_) | CapturedVariable => {
531             assert!(!bcx.fcx
532                         .debug_context
533                         .get_ref(span)
534                         .source_locations_enabled
535                         .get());
536             source_loc::set_debug_location(cx, None, UnknownLocation);
537         }
538         _ => { /* nothing to do */ }
539     }
540 }
541
542 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
543 pub enum DebugLoc {
544     At(ast::NodeId, Span),
545     ScopeAt(DIScope, Span),
546     None
547 }
548
549 impl DebugLoc {
550     pub fn apply(self, fcx: &FunctionContext) {
551         source_loc::set_source_location(fcx, None, self);
552     }
553
554     pub fn apply_to_bcx(self, bcx: &BlockAndBuilder) {
555         source_loc::set_source_location(bcx.fcx(), Some(bcx), self);
556     }
557 }
558
559 pub trait ToDebugLoc {
560     fn debug_loc(&self) -> DebugLoc;
561 }
562
563 impl ToDebugLoc for hir::Expr {
564     fn debug_loc(&self) -> DebugLoc {
565         DebugLoc::At(self.id, self.span)
566     }
567 }
568
569 impl ToDebugLoc for NodeIdAndSpan {
570     fn debug_loc(&self) -> DebugLoc {
571         DebugLoc::At(self.id, self.span)
572     }
573 }
574
575 impl ToDebugLoc for Option<NodeIdAndSpan> {
576     fn debug_loc(&self) -> DebugLoc {
577         match *self {
578             Some(NodeIdAndSpan { id, span }) => DebugLoc::At(id, span),
579             None => DebugLoc::None
580         }
581     }
582 }