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_instance;
19 use self::type_names::compute_debuginfo_type_name;
20 use self::metadata::{type_metadata, file_metadata, TypeMap};
21 use self::source_loc::InternalDebugLocation::{self, UnknownLocation};
24 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilder, DISubprogram, DIArray, DIFlags};
25 use rustc::hir::CodegenFnAttrFlags;
26 use rustc::hir::def_id::{DefId, CrateNum};
27 use rustc::ty::subst::{Substs, UnpackedKind};
30 use common::CodegenCx;
32 use monomorphize::Instance;
33 use rustc::ty::{self, ParamEnv, Ty, InstanceDef};
35 use rustc::session::config::{self, DebugInfo};
36 use rustc::util::nodemap::{DefIdMap, FxHashMap, FxHashSet};
37 use rustc_data_structures::small_c_str::SmallCStr;
41 use std::cell::{Cell, RefCell};
42 use std::ffi::CString;
44 use syntax_pos::{self, Span, Pos};
46 use syntax::symbol::{Symbol, InternedString};
47 use rustc::ty::layout::{self, LayoutOf};
48 use traits::BuilderMethods;
58 pub use self::create_scope_map::{create_mir_scopes, MirDebugScope};
59 pub use self::source_loc::start_emitting_source_locations;
60 pub use self::metadata::create_global_var_metadata;
61 pub use self::metadata::create_vtable_metadata;
62 pub use self::metadata::extend_scope_to_file;
63 pub use self::source_loc::set_source_location;
65 #[allow(non_upper_case_globals)]
66 const DW_TAG_auto_variable: c_uint = 0x100;
67 #[allow(non_upper_case_globals)]
68 const DW_TAG_arg_variable: c_uint = 0x101;
70 /// A context object for maintaining all state needed by the debuginfo module.
71 pub struct CrateDebugContext<'a, 'tcx> {
72 llcontext: &'a llvm::Context,
73 llmod: &'a llvm::Module,
74 builder: &'a mut DIBuilder<'a>,
75 created_files: RefCell<FxHashMap<(Symbol, Symbol), &'a DIFile>>,
76 created_enum_disr_types: RefCell<FxHashMap<(DefId, layout::Primitive), &'a DIType>>,
78 type_map: RefCell<TypeMap<'a, 'tcx>>,
79 namespace_map: RefCell<DefIdMap<&'a DIScope>>,
81 // This collection is used to assert that composite types (structs, enums,
82 // ...) have their members only set once:
83 composite_types_completed: RefCell<FxHashSet<&'a DIType>>,
86 impl Drop for CrateDebugContext<'a, 'tcx> {
89 llvm::LLVMRustDIBuilderDispose(&mut *(self.builder as *mut _));
94 impl<'a, 'tcx> CrateDebugContext<'a, 'tcx> {
95 pub fn new(llmod: &'a llvm::Module) -> Self {
96 debug!("CrateDebugContext::new");
97 let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
98 // DIBuilder inherits context from the module, so we'd better use the same one
99 let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
104 created_files: Default::default(),
105 created_enum_disr_types: Default::default(),
106 type_map: Default::default(),
107 namespace_map: RefCell::new(DefIdMap()),
108 composite_types_completed: Default::default(),
113 pub enum FunctionDebugContext<'ll> {
114 RegularContext(FunctionDebugContextData<'ll>),
116 FunctionWithoutDebugInfo,
119 impl FunctionDebugContext<'ll> {
120 pub fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData<'ll> {
122 FunctionDebugContext::RegularContext(ref data) => data,
123 FunctionDebugContext::DebugInfoDisabled => {
124 span_bug!(span, "{}", FunctionDebugContext::debuginfo_disabled_message());
126 FunctionDebugContext::FunctionWithoutDebugInfo => {
127 span_bug!(span, "{}", FunctionDebugContext::should_be_ignored_message());
132 fn debuginfo_disabled_message() -> &'static str {
133 "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
136 fn should_be_ignored_message() -> &'static str {
137 "debuginfo: Error trying to access FunctionDebugContext for function that should be \
138 ignored by debug info!"
142 pub struct FunctionDebugContextData<'ll> {
143 fn_metadata: &'ll DISubprogram,
144 source_locations_enabled: Cell<bool>,
145 pub defining_crate: CrateNum,
148 pub enum VariableAccess<'a, 'll> {
149 // The llptr given is an alloca containing the variable's value
150 DirectVariable { alloca: &'ll Value },
151 // The llptr given is an alloca containing the start of some pointer chain
152 // leading to the variable's content.
153 IndirectVariable { alloca: &'ll Value, address_operations: &'a [i64] }
156 pub enum VariableKind {
157 ArgumentVariable(usize /*index*/),
161 /// Create any deferred debug metadata nodes
162 pub fn finalize(cx: &CodegenCx) {
163 if cx.dbg_cx.is_none() {
169 if gdb::needs_gdb_debug_scripts_section(cx) {
170 // Add a .debug_gdb_scripts section to this compile-unit. This will
171 // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
172 // which activates the Rust pretty printers for binary this section is
174 gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
178 llvm::LLVMRustDIBuilderFinalize(DIB(cx));
179 // Debuginfo generation in LLVM by default uses a higher
180 // version of dwarf than macOS currently understands. We can
181 // instruct LLVM to emit an older version of dwarf, however,
182 // for macOS to understand. For more info see #11352
183 // This can be overridden using --llvm-opts -dwarf-version,N.
184 // Android has the same issue (#22398)
185 if cx.sess().target.target.options.is_like_osx ||
186 cx.sess().target.target.options.is_like_android {
187 llvm::LLVMRustAddModuleFlag(cx.llmod,
188 "Dwarf Version\0".as_ptr() as *const _,
192 // Indicate that we want CodeView debug information on MSVC
193 if cx.sess().target.target.options.is_like_msvc {
194 llvm::LLVMRustAddModuleFlag(cx.llmod,
195 "CodeView\0".as_ptr() as *const _,
199 // Prevent bitcode readers from deleting the debug info.
200 let ptr = "Debug Info Version\0".as_ptr();
201 llvm::LLVMRustAddModuleFlag(cx.llmod, ptr as *const _,
202 llvm::LLVMRustDebugMetadataVersion());
206 /// Creates the function-specific debug context.
208 /// Returns the FunctionDebugContext for the function which holds state needed
209 /// for debug info creation. The function may also return another variant of the
210 /// FunctionDebugContext enum which indicates why no debuginfo should be created
211 /// for the function.
212 pub fn create_function_debug_context(
213 cx: &CodegenCx<'ll, 'tcx>,
214 instance: Instance<'tcx>,
215 sig: ty::FnSig<'tcx>,
218 ) -> FunctionDebugContext<'ll> {
219 if cx.sess().opts.debuginfo == DebugInfo::None {
220 return FunctionDebugContext::DebugInfoDisabled;
223 if let InstanceDef::Item(def_id) = instance.def {
224 if cx.tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NO_DEBUG) {
225 return FunctionDebugContext::FunctionWithoutDebugInfo;
231 // This can be the case for functions inlined from another crate
233 // FIXME(simulacrum): Probably can't happen; remove.
234 return FunctionDebugContext::FunctionWithoutDebugInfo;
237 let def_id = instance.def_id();
238 let containing_scope = get_containing_scope(cx, instance);
239 let loc = span_start(cx, span);
240 let file_metadata = file_metadata(cx, &loc.file.name, def_id.krate);
242 let function_type_metadata = unsafe {
243 let fn_signature = get_function_signature(cx, sig);
244 llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
247 // Find the enclosing function, in case this is a closure.
248 let def_key = cx.tcx.def_key(def_id);
249 let mut name = def_key.disambiguated_data.data.to_string();
251 let enclosing_fn_def_id = cx.tcx.closure_base_def_id(def_id);
253 // Get_template_parameters() will append a `<...>` clause to the function
254 // name if necessary.
255 let generics = cx.tcx.generics_of(enclosing_fn_def_id);
256 let substs = instance.substs.truncate_to(cx.tcx, generics);
257 let template_parameters = get_template_parameters(cx,
263 // Get the linkage_name, which is just the symbol name
264 let linkage_name = mangled_name_of_instance(cx, instance);
266 let scope_line = span_start(cx, span).line;
267 let is_local_to_unit = is_node_local_to_unit(cx, def_id);
269 let function_name = CString::new(name).unwrap();
270 let linkage_name = SmallCStr::new(&linkage_name.as_str());
272 let mut flags = DIFlags::FlagPrototyped;
274 let local_id = cx.tcx.hir.as_local_node_id(def_id);
275 if let Some((id, _, _)) = *cx.sess().entry_fn.borrow() {
276 if local_id == Some(id) {
277 flags |= DIFlags::FlagMainSubprogram;
281 if cx.layout_of(sig.output()).abi.is_uninhabited() {
282 flags |= DIFlags::FlagNoReturn;
285 let fn_metadata = unsafe {
286 llvm::LLVMRustDIBuilderCreateFunction(
289 function_name.as_ptr(),
290 linkage_name.as_ptr(),
293 function_type_metadata,
296 scope_line as c_uint,
298 cx.sess().opts.optimize != config::OptLevel::No,
304 // Initialize fn debug context (including scope map and namespace map)
305 let fn_debug_context = FunctionDebugContextData {
307 source_locations_enabled: Cell::new(false),
308 defining_crate: def_id.krate,
311 return FunctionDebugContext::RegularContext(fn_debug_context);
313 fn get_function_signature(
314 cx: &CodegenCx<'ll, 'tcx>,
315 sig: ty::FnSig<'tcx>,
317 if cx.sess().opts.debuginfo == DebugInfo::Limited {
318 return create_DIArray(DIB(cx), &[]);
321 let mut signature = Vec::with_capacity(sig.inputs().len() + 1);
323 // Return type -- llvm::DIBuilder wants this at index 0
324 signature.push(match sig.output().sty {
325 ty::Tuple(ref tys) if tys.is_empty() => None,
326 _ => Some(type_metadata(cx, sig.output(), syntax_pos::DUMMY_SP))
329 let inputs = if sig.abi == Abi::RustCall {
330 &sig.inputs()[..sig.inputs().len() - 1]
336 if cx.sess().target.target.options.is_like_msvc {
338 // There is a bug in MSDIA that leads to a crash when it encounters
339 // a fixed-size array of `u8` or something zero-sized in a
340 // function-type (see #40477).
341 // As a workaround, we replace those fixed-size arrays with a
342 // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
343 // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
344 // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
345 // This transformed type is wrong, but these function types are
346 // already inaccurate due to ABI adjustments (see #42800).
347 signature.extend(inputs.iter().map(|&t| {
348 let t = match t.sty {
350 if (ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() => {
351 cx.tcx.mk_imm_ptr(ct)
355 Some(type_metadata(cx, t, syntax_pos::DUMMY_SP))
358 signature.extend(inputs.iter().map(|t| {
359 Some(type_metadata(cx, t, syntax_pos::DUMMY_SP))
363 if sig.abi == Abi::RustCall && !sig.inputs().is_empty() {
364 if let ty::Tuple(args) = sig.inputs()[sig.inputs().len() - 1].sty {
366 args.iter().map(|argument_type| {
367 Some(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP))
373 create_DIArray(DIB(cx), &signature[..])
376 fn get_template_parameters(
377 cx: &CodegenCx<'ll, 'tcx>,
378 generics: &ty::Generics,
379 substs: &Substs<'tcx>,
380 file_metadata: &'ll DIFile,
381 name_to_append_suffix_to: &mut String,
383 if substs.types().next().is_none() {
384 return create_DIArray(DIB(cx), &[]);
387 name_to_append_suffix_to.push('<');
388 for (i, actual_type) in substs.types().enumerate() {
390 name_to_append_suffix_to.push_str(",");
393 let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), actual_type);
394 // Add actual type name to <...> clause of function name
395 let actual_type_name = compute_debuginfo_type_name(cx,
398 name_to_append_suffix_to.push_str(&actual_type_name[..]);
400 name_to_append_suffix_to.push('>');
402 // Again, only create type information if full debuginfo is enabled
403 let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full {
404 let names = get_parameter_names(cx, generics);
405 substs.iter().zip(names).filter_map(|(kind, name)| {
406 if let UnpackedKind::Type(ty) = kind.unpack() {
407 let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
408 let actual_type_metadata =
409 type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
410 let name = SmallCStr::new(&name.as_str());
412 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
416 actual_type_metadata,
430 create_DIArray(DIB(cx), &template_params[..])
433 fn get_parameter_names(cx: &CodegenCx,
434 generics: &ty::Generics)
435 -> Vec<InternedString> {
436 let mut names = generics.parent.map_or(vec![], |def_id| {
437 get_parameter_names(cx, cx.tcx.generics_of(def_id))
439 names.extend(generics.params.iter().map(|param| param.name));
443 fn get_containing_scope(
444 cx: &CodegenCx<'ll, 'tcx>,
445 instance: Instance<'tcx>,
447 // First, let's see if this is a method within an inherent impl. Because
448 // if yes, we want to make the result subroutine DIE a child of the
449 // subroutine's self-type.
450 let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| {
451 // If the method does *not* belong to a trait, proceed
452 if cx.tcx.trait_id_of_impl(impl_def_id).is_none() {
453 let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions(
455 ty::ParamEnv::reveal_all(),
456 &cx.tcx.type_of(impl_def_id),
459 // Only "class" methods are generally understood by LLVM,
460 // so avoid methods on other types (e.g. `<*mut T>::null`).
461 match impl_self_ty.sty {
462 ty::Adt(def, ..) if !def.is_box() => {
463 Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
468 // For trait method impls we still use the "parallel namespace"
474 self_type.unwrap_or_else(|| {
475 namespace::item_namespace(cx, DefId {
476 krate: instance.def_id().krate,
478 .def_key(instance.def_id())
480 .expect("get_containing_scope: missing parent?")
486 pub fn declare_local(
487 bx: &Builder<'a, 'll, 'tcx>,
488 dbg_context: &FunctionDebugContext<'ll>,
489 variable_name: ast::Name,
490 variable_type: Ty<'tcx>,
491 scope_metadata: &'ll DIScope,
492 variable_access: VariableAccess<'_, 'll>,
493 variable_kind: VariableKind,
496 assert!(!dbg_context.get_ref(span).source_locations_enabled.get());
499 let file = span_start(cx, span).file;
500 let file_metadata = file_metadata(cx,
502 dbg_context.get_ref(span).defining_crate);
504 let loc = span_start(cx, span);
505 let type_metadata = type_metadata(cx, variable_type, span);
507 let (argument_index, dwarf_tag) = match variable_kind {
508 ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
509 LocalVariable => (0, DW_TAG_auto_variable)
511 let align = cx.align_of(variable_type);
513 let name = SmallCStr::new(&variable_name.as_str());
514 match (variable_access, &[][..]) {
515 (DirectVariable { alloca }, address_operations) |
516 (IndirectVariable {alloca, address_operations}, _) => {
517 let metadata = unsafe {
518 llvm::LLVMRustDIBuilderCreateVariable(
526 cx.sess().opts.optimize != config::OptLevel::No,
532 source_loc::set_debug_location(bx,
533 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
535 let debug_loc = llvm::LLVMGetCurrentDebugLocation(bx.llbuilder);
536 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
540 address_operations.as_ptr(),
541 address_operations.len() as c_uint,
545 llvm::LLVMSetInstDebugLocation(bx.llbuilder, instr);
547 source_loc::set_debug_location(bx, UnknownLocation);