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