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