]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/debuginfo/mod.rs
Remove unused code from remaining compiler crates
[rust.git] / compiler / rustc_codegen_llvm / src / debuginfo / mod.rs
1 // See doc.rs for documentation.
2 mod doc;
3
4 use rustc_codegen_ssa::mir::debuginfo::VariableKind::*;
5
6 use self::metadata::{file_metadata, type_metadata, TypeMap, UNKNOWN_LINE_NUMBER};
7 use self::namespace::mangled_name_of_instance;
8 use self::type_names::compute_debuginfo_type_name;
9 use self::utils::{create_DIArray, is_node_local_to_unit, DIB};
10
11 use crate::abi::FnAbi;
12 use crate::builder::Builder;
13 use crate::common::CodegenCx;
14 use crate::llvm;
15 use crate::llvm::debuginfo::{
16     DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DISPFlags, DIScope, DIType, DIVariable,
17 };
18 use crate::value::Value;
19
20 use rustc_codegen_ssa::debuginfo::type_names;
21 use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind};
22 use rustc_codegen_ssa::traits::*;
23 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
24 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE};
25 use rustc_index::vec::IndexVec;
26 use rustc_middle::mir;
27 use rustc_middle::ty::layout::HasTyCtxt;
28 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
29 use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TypeFoldable};
30 use rustc_session::config::{self, DebugInfo};
31 use rustc_span::symbol::Symbol;
32 use rustc_span::{self, BytePos, Span};
33 use rustc_target::abi::{LayoutOf, Primitive, Size};
34
35 use libc::c_uint;
36 use smallvec::SmallVec;
37 use std::cell::RefCell;
38 use tracing::debug;
39
40 mod create_scope_map;
41 pub mod gdb;
42 pub mod metadata;
43 mod namespace;
44 mod source_loc;
45 mod utils;
46
47 pub use self::create_scope_map::compute_mir_scopes;
48 pub use self::metadata::create_global_var_metadata;
49 pub use self::metadata::extend_scope_to_file;
50
51 #[allow(non_upper_case_globals)]
52 const DW_TAG_auto_variable: c_uint = 0x100;
53 #[allow(non_upper_case_globals)]
54 const DW_TAG_arg_variable: c_uint = 0x101;
55
56 /// A context object for maintaining all state needed by the debuginfo module.
57 pub struct CrateDebugContext<'a, 'tcx> {
58     llcontext: &'a llvm::Context,
59     llmod: &'a llvm::Module,
60     builder: &'a mut DIBuilder<'a>,
61     created_files: RefCell<FxHashMap<(Option<String>, Option<String>), &'a DIFile>>,
62     created_enum_disr_types: RefCell<FxHashMap<(DefId, Primitive), &'a DIType>>,
63
64     type_map: RefCell<TypeMap<'a, 'tcx>>,
65     namespace_map: RefCell<DefIdMap<&'a DIScope>>,
66
67     // This collection is used to assert that composite types (structs, enums,
68     // ...) have their members only set once:
69     composite_types_completed: RefCell<FxHashSet<&'a DIType>>,
70 }
71
72 impl Drop for CrateDebugContext<'a, 'tcx> {
73     fn drop(&mut self) {
74         unsafe {
75             llvm::LLVMRustDIBuilderDispose(&mut *(self.builder as *mut _));
76         }
77     }
78 }
79
80 impl<'a, 'tcx> CrateDebugContext<'a, 'tcx> {
81     pub fn new(llmod: &'a llvm::Module) -> Self {
82         debug!("CrateDebugContext::new");
83         let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
84         // DIBuilder inherits context from the module, so we'd better use the same one
85         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
86         CrateDebugContext {
87             llcontext,
88             llmod,
89             builder,
90             created_files: Default::default(),
91             created_enum_disr_types: Default::default(),
92             type_map: Default::default(),
93             namespace_map: RefCell::new(Default::default()),
94             composite_types_completed: Default::default(),
95         }
96     }
97 }
98
99 /// Creates any deferred debug metadata nodes
100 pub fn finalize(cx: &CodegenCx<'_, '_>) {
101     if cx.dbg_cx.is_none() {
102         return;
103     }
104
105     debug!("finalize");
106
107     if gdb::needs_gdb_debug_scripts_section(cx) {
108         // Add a .debug_gdb_scripts section to this compile-unit. This will
109         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
110         // which activates the Rust pretty printers for binary this section is
111         // contained in.
112         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
113     }
114
115     unsafe {
116         llvm::LLVMRustDIBuilderFinalize(DIB(cx));
117         // Debuginfo generation in LLVM by default uses a higher
118         // version of dwarf than macOS currently understands. We can
119         // instruct LLVM to emit an older version of dwarf, however,
120         // for macOS to understand. For more info see #11352
121         // This can be overridden using --llvm-opts -dwarf-version,N.
122         // Android has the same issue (#22398)
123         if cx.sess().target.target.options.is_like_osx
124             || cx.sess().target.target.options.is_like_android
125         {
126             llvm::LLVMRustAddModuleFlag(cx.llmod, "Dwarf Version\0".as_ptr().cast(), 2)
127         }
128
129         // Indicate that we want CodeView debug information on MSVC
130         if cx.sess().target.target.options.is_like_msvc {
131             llvm::LLVMRustAddModuleFlag(cx.llmod, "CodeView\0".as_ptr().cast(), 1)
132         }
133
134         // Prevent bitcode readers from deleting the debug info.
135         let ptr = "Debug Info Version\0".as_ptr();
136         llvm::LLVMRustAddModuleFlag(cx.llmod, ptr.cast(), llvm::LLVMRustDebugMetadataVersion());
137     };
138 }
139
140 impl DebugInfoBuilderMethods for Builder<'a, 'll, 'tcx> {
141     // FIXME(eddyb) find a common convention for all of the debuginfo-related
142     // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.).
143     fn dbg_var_addr(
144         &mut self,
145         dbg_var: &'ll DIVariable,
146         scope_metadata: &'ll DIScope,
147         variable_alloca: Self::Value,
148         direct_offset: Size,
149         indirect_offsets: &[Size],
150         span: Span,
151     ) {
152         let cx = self.cx();
153
154         // Convert the direct and indirect offsets to address ops.
155         // FIXME(eddyb) use `const`s instead of getting the values via FFI,
156         // the values should match the ones in the DWARF standard anyway.
157         let op_deref = || unsafe { llvm::LLVMRustDIBuilderCreateOpDeref() };
158         let op_plus_uconst = || unsafe { llvm::LLVMRustDIBuilderCreateOpPlusUconst() };
159         let mut addr_ops = SmallVec::<[_; 8]>::new();
160
161         if direct_offset.bytes() > 0 {
162             addr_ops.push(op_plus_uconst());
163             addr_ops.push(direct_offset.bytes() as i64);
164         }
165         for &offset in indirect_offsets {
166             addr_ops.push(op_deref());
167             if offset.bytes() > 0 {
168                 addr_ops.push(op_plus_uconst());
169                 addr_ops.push(offset.bytes() as i64);
170             }
171         }
172
173         // FIXME(eddyb) maybe this information could be extracted from `dbg_var`,
174         // to avoid having to pass it down in both places?
175         // NB: `var` doesn't seem to know about the column, so that's a limitation.
176         let dbg_loc = cx.create_debug_loc(scope_metadata, span);
177         unsafe {
178             // FIXME(eddyb) replace `llvm.dbg.declare` with `llvm.dbg.addr`.
179             llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
180                 DIB(cx),
181                 variable_alloca,
182                 dbg_var,
183                 addr_ops.as_ptr(),
184                 addr_ops.len() as c_uint,
185                 dbg_loc,
186                 self.llbb(),
187             );
188         }
189     }
190
191     fn set_source_location(&mut self, scope: &'ll DIScope, span: Span) {
192         debug!("set_source_location: {}", self.sess().source_map().span_to_string(span));
193
194         let dbg_loc = self.cx().create_debug_loc(scope, span);
195
196         unsafe {
197             llvm::LLVMSetCurrentDebugLocation(self.llbuilder, dbg_loc);
198         }
199     }
200     fn insert_reference_to_gdb_debug_scripts_section_global(&mut self) {
201         gdb::insert_reference_to_gdb_debug_scripts_section_global(self)
202     }
203
204     fn set_var_name(&mut self, value: &'ll Value, name: &str) {
205         // Avoid wasting time if LLVM value names aren't even enabled.
206         if self.sess().fewer_names() {
207             return;
208         }
209
210         // Only function parameters and instructions are local to a function,
211         // don't change the name of anything else (e.g. globals).
212         let param_or_inst = unsafe {
213             llvm::LLVMIsAArgument(value).is_some() || llvm::LLVMIsAInstruction(value).is_some()
214         };
215         if !param_or_inst {
216             return;
217         }
218
219         // Avoid replacing the name if it already exists.
220         // While we could combine the names somehow, it'd
221         // get noisy quick, and the usefulness is dubious.
222         if llvm::get_value_name(value).is_empty() {
223             llvm::set_value_name(value, name.as_bytes());
224         }
225     }
226 }
227
228 impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> {
229     fn create_function_debug_context(
230         &self,
231         instance: Instance<'tcx>,
232         fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
233         llfn: &'ll Value,
234         mir: &mir::Body<'_>,
235     ) -> Option<FunctionDebugContext<&'ll DIScope>> {
236         if self.sess().opts.debuginfo == DebugInfo::None {
237             return None;
238         }
239
240         let span = mir.span;
241
242         // This can be the case for functions inlined from another crate
243         if span.is_dummy() {
244             // FIXME(simulacrum): Probably can't happen; remove.
245             return None;
246         }
247
248         let def_id = instance.def_id();
249         let containing_scope = get_containing_scope(self, instance);
250         let loc = self.lookup_debug_loc(span.lo());
251         let file_metadata = file_metadata(self, &loc.file, def_id.krate);
252
253         let function_type_metadata = unsafe {
254             let fn_signature = get_function_signature(self, fn_abi);
255             llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(self), fn_signature)
256         };
257
258         // Find the enclosing function, in case this is a closure.
259         let def_key = self.tcx().def_key(def_id);
260         let mut name = def_key.disambiguated_data.data.to_string();
261
262         let enclosing_fn_def_id = self.tcx().closure_base_def_id(def_id);
263
264         // Get_template_parameters() will append a `<...>` clause to the function
265         // name if necessary.
266         let generics = self.tcx().generics_of(enclosing_fn_def_id);
267         let substs = instance.substs.truncate_to(self.tcx(), generics);
268         let template_parameters = get_template_parameters(self, &generics, substs, &mut name);
269
270         let linkage_name = &mangled_name_of_instance(self, instance).name;
271         // Omit the linkage_name if it is the same as subprogram name.
272         let linkage_name = if &name == linkage_name { "" } else { linkage_name };
273
274         // FIXME(eddyb) does this need to be separate from `loc.line` for some reason?
275         let scope_line = loc.line;
276
277         let mut flags = DIFlags::FlagPrototyped;
278
279         if fn_abi.ret.layout.abi.is_uninhabited() {
280             flags |= DIFlags::FlagNoReturn;
281         }
282
283         let mut spflags = DISPFlags::SPFlagDefinition;
284         if is_node_local_to_unit(self, def_id) {
285             spflags |= DISPFlags::SPFlagLocalToUnit;
286         }
287         if self.sess().opts.optimize != config::OptLevel::No {
288             spflags |= DISPFlags::SPFlagOptimized;
289         }
290         if let Some((id, _)) = self.tcx.entry_fn(LOCAL_CRATE) {
291             if id.to_def_id() == def_id {
292                 spflags |= DISPFlags::SPFlagMainSubprogram;
293             }
294         }
295
296         let fn_metadata = unsafe {
297             llvm::LLVMRustDIBuilderCreateFunction(
298                 DIB(self),
299                 containing_scope,
300                 name.as_ptr().cast(),
301                 name.len(),
302                 linkage_name.as_ptr().cast(),
303                 linkage_name.len(),
304                 file_metadata,
305                 loc.line.unwrap_or(UNKNOWN_LINE_NUMBER),
306                 function_type_metadata,
307                 scope_line.unwrap_or(UNKNOWN_LINE_NUMBER),
308                 flags,
309                 spflags,
310                 llfn,
311                 template_parameters,
312                 None,
313             )
314         };
315
316         // Initialize fn debug context (including scopes).
317         // FIXME(eddyb) figure out a way to not need `Option` for `scope_metadata`.
318         let null_scope = DebugScope {
319             scope_metadata: None,
320             file_start_pos: BytePos(0),
321             file_end_pos: BytePos(0),
322         };
323         let mut fn_debug_context = FunctionDebugContext {
324             scopes: IndexVec::from_elem(null_scope, &mir.source_scopes),
325             defining_crate: def_id.krate,
326         };
327
328         // Fill in all the scopes, with the information from the MIR body.
329         compute_mir_scopes(self, mir, fn_metadata, &mut fn_debug_context);
330
331         return Some(fn_debug_context);
332
333         fn get_function_signature<'ll, 'tcx>(
334             cx: &CodegenCx<'ll, 'tcx>,
335             fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
336         ) -> &'ll DIArray {
337             if cx.sess().opts.debuginfo == DebugInfo::Limited {
338                 return create_DIArray(DIB(cx), &[]);
339             }
340
341             let mut signature = Vec::with_capacity(fn_abi.args.len() + 1);
342
343             // Return type -- llvm::DIBuilder wants this at index 0
344             signature.push(if fn_abi.ret.is_ignore() {
345                 None
346             } else {
347                 Some(type_metadata(cx, fn_abi.ret.layout.ty, rustc_span::DUMMY_SP))
348             });
349
350             // Arguments types
351             if cx.sess().target.target.options.is_like_msvc {
352                 // FIXME(#42800):
353                 // There is a bug in MSDIA that leads to a crash when it encounters
354                 // a fixed-size array of `u8` or something zero-sized in a
355                 // function-type (see #40477).
356                 // As a workaround, we replace those fixed-size arrays with a
357                 // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
358                 // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
359                 // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
360                 // This transformed type is wrong, but these function types are
361                 // already inaccurate due to ABI adjustments (see #42800).
362                 signature.extend(fn_abi.args.iter().map(|arg| {
363                     let t = arg.layout.ty;
364                     let t = match t.kind() {
365                         ty::Array(ct, _)
366                             if (*ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() =>
367                         {
368                             cx.tcx.mk_imm_ptr(ct)
369                         }
370                         _ => t,
371                     };
372                     Some(type_metadata(cx, t, rustc_span::DUMMY_SP))
373                 }));
374             } else {
375                 signature.extend(
376                     fn_abi
377                         .args
378                         .iter()
379                         .map(|arg| Some(type_metadata(cx, arg.layout.ty, rustc_span::DUMMY_SP))),
380                 );
381             }
382
383             create_DIArray(DIB(cx), &signature[..])
384         }
385
386         fn get_template_parameters<'ll, 'tcx>(
387             cx: &CodegenCx<'ll, 'tcx>,
388             generics: &ty::Generics,
389             substs: SubstsRef<'tcx>,
390             name_to_append_suffix_to: &mut String,
391         ) -> &'ll DIArray {
392             if substs.types().next().is_none() {
393                 return create_DIArray(DIB(cx), &[]);
394             }
395
396             name_to_append_suffix_to.push('<');
397             for (i, actual_type) in substs.types().enumerate() {
398                 if i != 0 {
399                     name_to_append_suffix_to.push_str(",");
400                 }
401
402                 let actual_type =
403                     cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), actual_type);
404                 // Add actual type name to <...> clause of function name
405                 let actual_type_name = compute_debuginfo_type_name(cx.tcx(), actual_type, true);
406                 name_to_append_suffix_to.push_str(&actual_type_name[..]);
407             }
408             name_to_append_suffix_to.push('>');
409
410             // Again, only create type information if full debuginfo is enabled
411             let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full {
412                 let names = get_parameter_names(cx, generics);
413                 substs
414                     .iter()
415                     .zip(names)
416                     .filter_map(|(kind, name)| {
417                         if let GenericArgKind::Type(ty) = kind.unpack() {
418                             let actual_type =
419                                 cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
420                             let actual_type_metadata =
421                                 type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
422                             let name = name.as_str();
423                             Some(unsafe {
424                                 Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
425                                     DIB(cx),
426                                     None,
427                                     name.as_ptr().cast(),
428                                     name.len(),
429                                     actual_type_metadata,
430                                 ))
431                             })
432                         } else {
433                             None
434                         }
435                     })
436                     .collect()
437             } else {
438                 vec![]
439             };
440
441             create_DIArray(DIB(cx), &template_params[..])
442         }
443
444         fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
445             let mut names = generics
446                 .parent
447                 .map_or(vec![], |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
448             names.extend(generics.params.iter().map(|param| param.name));
449             names
450         }
451
452         fn get_containing_scope<'ll, 'tcx>(
453             cx: &CodegenCx<'ll, 'tcx>,
454             instance: Instance<'tcx>,
455         ) -> &'ll DIScope {
456             // First, let's see if this is a method within an inherent impl. Because
457             // if yes, we want to make the result subroutine DIE a child of the
458             // subroutine's self-type.
459             let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| {
460                 // If the method does *not* belong to a trait, proceed
461                 if cx.tcx.trait_id_of_impl(impl_def_id).is_none() {
462                     let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions(
463                         instance.substs,
464                         ty::ParamEnv::reveal_all(),
465                         &cx.tcx.type_of(impl_def_id),
466                     );
467
468                     // Only "class" methods are generally understood by LLVM,
469                     // so avoid methods on other types (e.g., `<*mut T>::null`).
470                     match impl_self_ty.kind() {
471                         ty::Adt(def, ..) if !def.is_box() => {
472                             // Again, only create type information if full debuginfo is enabled
473                             if cx.sess().opts.debuginfo == DebugInfo::Full
474                                 && !impl_self_ty.needs_subst()
475                             {
476                                 Some(type_metadata(cx, impl_self_ty, rustc_span::DUMMY_SP))
477                             } else {
478                                 Some(namespace::item_namespace(cx, def.did))
479                             }
480                         }
481                         _ => None,
482                     }
483                 } else {
484                     // For trait method impls we still use the "parallel namespace"
485                     // strategy
486                     None
487                 }
488             });
489
490             self_type.unwrap_or_else(|| {
491                 namespace::item_namespace(
492                     cx,
493                     DefId {
494                         krate: instance.def_id().krate,
495                         index: cx
496                             .tcx
497                             .def_key(instance.def_id())
498                             .parent
499                             .expect("get_containing_scope: missing parent?"),
500                     },
501                 )
502             })
503         }
504     }
505
506     fn create_vtable_metadata(&self, ty: Ty<'tcx>, vtable: Self::Value) {
507         metadata::create_vtable_metadata(self, ty, vtable)
508     }
509
510     fn extend_scope_to_file(
511         &self,
512         scope_metadata: &'ll DIScope,
513         file: &rustc_span::SourceFile,
514         defining_crate: CrateNum,
515     ) -> &'ll DILexicalBlock {
516         metadata::extend_scope_to_file(&self, scope_metadata, file, defining_crate)
517     }
518
519     fn debuginfo_finalize(&self) {
520         finalize(self)
521     }
522
523     // FIXME(eddyb) find a common convention for all of the debuginfo-related
524     // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.).
525     fn create_dbg_var(
526         &self,
527         dbg_context: &FunctionDebugContext<&'ll DIScope>,
528         variable_name: Symbol,
529         variable_type: Ty<'tcx>,
530         scope_metadata: &'ll DIScope,
531         variable_kind: VariableKind,
532         span: Span,
533     ) -> &'ll DIVariable {
534         let loc = self.lookup_debug_loc(span.lo());
535         let file_metadata = file_metadata(self, &loc.file, dbg_context.defining_crate);
536
537         let type_metadata = type_metadata(self, variable_type, span);
538
539         let (argument_index, dwarf_tag) = match variable_kind {
540             ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
541             LocalVariable => (0, DW_TAG_auto_variable),
542         };
543         let align = self.align_of(variable_type);
544
545         let name = variable_name.as_str();
546         unsafe {
547             llvm::LLVMRustDIBuilderCreateVariable(
548                 DIB(self),
549                 dwarf_tag,
550                 scope_metadata,
551                 name.as_ptr().cast(),
552                 name.len(),
553                 file_metadata,
554                 loc.line.unwrap_or(UNKNOWN_LINE_NUMBER),
555                 type_metadata,
556                 true,
557                 DIFlags::FlagZero,
558                 argument_index,
559                 align.bytes() as u32,
560             )
561         }
562     }
563 }