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.
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.
11 // See doc.rs for documentation.
14 use self::VariableAccess::*;
15 use self::VariableKind::*;
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};
25 use llvm::{ModuleRef, ContextRef, ValueRef};
26 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilderRef, DISubprogram, DIArray,
28 use rustc::hir::def_id::DefId;
29 use rustc::hir::map::DefPathData;
30 use rustc::ty::subst::Substs;
34 use common::{NodeIdAndSpan, CrateContext, FunctionContext, Block, BlockAndBuilder};
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};
42 use std::cell::{Cell, RefCell};
43 use std::ffi::CString;
46 use syntax_pos::{self, Span, Pos};
48 use syntax::attr::IntType;
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;
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;
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>>,
81 type_map: RefCell<TypeMap<'tcx>>,
82 namespace_map: RefCell<DefIdMap<DIScope>>,
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>>,
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 {
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()),
108 pub enum FunctionDebugContext {
109 RegularContext(Box<FunctionDebugContextData>),
111 FunctionWithoutDebugInfo,
114 impl FunctionDebugContext {
115 fn get_ref<'a>(&'a self,
117 -> &'a FunctionDebugContextData {
119 FunctionDebugContext::RegularContext(box ref data) => data,
120 FunctionDebugContext::DebugInfoDisabled => {
123 FunctionDebugContext::debuginfo_disabled_message());
125 FunctionDebugContext::FunctionWithoutDebugInfo => {
128 FunctionDebugContext::should_be_ignored_message());
133 fn debuginfo_disabled_message() -> &'static str {
134 "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
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!"
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>,
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] }
159 pub enum VariableKind {
160 ArgumentVariable(usize /*index*/),
165 /// Create any deferred debug metadata nodes
166 pub fn finalize(cx: &CrateContext) {
167 if cx.dbg_cx().is_none() {
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
178 gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
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 _,
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 _,
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());
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;
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
223 /// Creates the function-specific debug context.
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>,
233 llfn: ValueRef) -> FunctionDebugContext {
234 if cx.sess().opts.debuginfo == NoDebugInfo {
235 return FunctionDebugContext::DebugInfoDisabled;
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);
242 let instance = inline::maybe_inline_instance(cx, instance);
243 let (containing_scope, span) = get_containing_scope_and_span(cx, instance);
245 // This can be the case for functions inlined from another crate
246 if span == syntax_pos::DUMMY_SP {
247 return FunctionDebugContext::FunctionWithoutDebugInfo;
250 let loc = span_start(cx, span);
251 let file_metadata = file_metadata(cx, &loc.file.name, &loc.file.abs_path);
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)
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);
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,
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..]);
280 let scope_line = span_start(cx, span).line;
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));
285 let function_name = CString::new(name).unwrap();
286 let linkage_name = CString::new(linkage_name).unwrap();
288 let fn_metadata = unsafe {
289 llvm::LLVMRustDIBuilderCreateFunction(
292 function_name.as_ptr(),
293 linkage_name.as_ptr(),
296 function_type_metadata,
299 scope_line as c_uint,
300 FlagPrototyped as c_uint,
301 cx.sess().opts.optimize != config::OptLevel::No,
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),
316 return FunctionDebugContext::RegularContext(fn_debug_context);
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), &[]);
325 let mut signature = Vec::with_capacity(sig.inputs.len() + 1);
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)
333 ty::FnDiverging => diverging_type_metadata(cx)
336 let inputs = if abi == Abi::RustCall {
337 &sig.inputs[..sig.inputs.len()-1]
343 for &argument_type in inputs {
344 signature.push(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP));
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));
355 return create_DIArray(DIB(cx), &signature[..]);
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)
365 let actual_types = param_substs.types.as_slice();
367 if actual_types.is_empty() {
368 return create_DIArray(DIB(cx), &[]);
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,
378 name_to_append_suffix_to.push_str(&actual_type_name[..]);
380 if i != actual_types.len() - 1 {
381 name_to_append_suffix_to.push_str(",");
384 name_to_append_suffix_to.push('>');
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();
393 llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
397 actual_type_metadata,
407 return create_DIArray(DIB(cx), &template_params[..]);
410 fn get_containing_scope_and_span<'ccx, 'tcx>(cx: &CrateContext<'ccx, 'tcx>,
411 instance: Instance<'tcx>)
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(),
424 Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
426 // For trait method impls we still use the "parallel namespace"
432 let containing_scope = self_type.unwrap_or_else(|| {
433 namespace::item_namespace(cx, DefId {
434 krate: instance.def.krate,
436 .def_key(instance.def)
438 .expect("get_containing_scope_and_span: missing parent?")
442 // Try to get some span information, if we have an inlined item.
443 let definition_span = cx.tcx()
445 .def_id_span(instance.def, syntax_pos::DUMMY_SP);
447 (containing_scope, definition_span)
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,
463 *data.scope_map.borrow_mut() = scope_map;
465 FunctionDebugContext::DebugInfoDisabled |
466 FunctionDebugContext::FunctionWithoutDebugInfo => {}
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,
477 let cx: &CrateContext = bcx.ccx();
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);
483 let loc = span_start(cx, span);
484 let type_metadata = type_metadata(cx, variable_type, span);
486 let (argument_index, dwarf_tag) = match variable_kind {
487 ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
489 CapturedVariable => (0, DW_TAG_auto_variable)
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(
505 cx.sess().opts.optimize != config::OptLevel::No,
507 address_operations.as_ptr(),
508 address_operations.len() as c_uint,
511 source_loc::set_debug_location(cx, None,
512 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
514 let debug_loc = llvm::LLVMGetCurrentDebugLocation(cx.raw_builder());
515 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
519 address_operations.as_ptr(),
520 address_operations.len() as c_uint,
524 llvm::LLVMSetInstDebugLocation(::build::B(bcx).llbuilder, instr);
529 match variable_kind {
530 ArgumentVariable(_) | CapturedVariable => {
534 .source_locations_enabled
536 source_loc::set_debug_location(cx, None, UnknownLocation);
538 _ => { /* nothing to do */ }
542 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
544 At(ast::NodeId, Span),
545 ScopeAt(DIScope, Span),
550 pub fn apply(self, fcx: &FunctionContext) {
551 source_loc::set_source_location(fcx, None, self);
554 pub fn apply_to_bcx(self, bcx: &BlockAndBuilder) {
555 source_loc::set_source_location(bcx.fcx(), Some(bcx), self);
559 pub trait ToDebugLoc {
560 fn debug_loc(&self) -> DebugLoc;
563 impl ToDebugLoc for hir::Expr {
564 fn debug_loc(&self) -> DebugLoc {
565 DebugLoc::At(self.id, self.span)
569 impl ToDebugLoc for NodeIdAndSpan {
570 fn debug_loc(&self) -> DebugLoc {
571 DebugLoc::At(self.id, self.span)
575 impl ToDebugLoc for Option<NodeIdAndSpan> {
576 fn debug_loc(&self) -> DebugLoc {
578 Some(NodeIdAndSpan { id, span }) => DebugLoc::At(id, span),
579 None => DebugLoc::None