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