]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/debuginfo/mod.rs
042e72e921ecead4e02951a41c7f3747db5e0966
[rust.git] / src / librustc_codegen_llvm / debuginfo / mod.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // See doc.rs for documentation.
12 mod doc;
13
14 use self::VariableAccess::*;
15 use self::VariableKind::*;
16
17 use self::utils::{DIB, span_start, create_DIArray, is_node_local_to_unit};
18 use self::namespace::mangled_name_of_instance;
19 use self::type_names::compute_debuginfo_type_name;
20 use self::metadata::{type_metadata, file_metadata, TypeMap};
21 use self::source_loc::InternalDebugLocation::{self, UnknownLocation};
22
23 use llvm;
24 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilder, DISubprogram, DIArray, DIFlags};
25 use rustc::hir::CodegenFnAttrFlags;
26 use rustc::hir::def_id::{DefId, CrateNum};
27 use rustc::ty::subst::{Substs, UnpackedKind};
28
29 use abi::Abi;
30 use common::CodegenCx;
31 use builder::Builder;
32 use monomorphize::Instance;
33 use rustc::ty::{self, ParamEnv, Ty, InstanceDef};
34 use rustc::mir;
35 use rustc::session::config::{self, DebugInfo};
36 use rustc::util::nodemap::{DefIdMap, FxHashMap, FxHashSet};
37 use rustc_data_structures::small_c_str::SmallCStr;
38 use value::Value;
39
40 use libc::c_uint;
41 use std::cell::{Cell, RefCell};
42 use std::ffi::CString;
43
44 use syntax_pos::{self, Span, Pos};
45 use syntax::ast;
46 use syntax::symbol::{Symbol, InternedString};
47 use rustc::ty::layout::{self, LayoutOf};
48
49 pub mod gdb;
50 mod utils;
51 mod namespace;
52 mod type_names;
53 pub mod metadata;
54 mod create_scope_map;
55 mod source_loc;
56
57 pub use self::create_scope_map::{create_mir_scopes, MirDebugScope};
58 pub use self::source_loc::start_emitting_source_locations;
59 pub use self::metadata::create_global_var_metadata;
60 pub use self::metadata::create_vtable_metadata;
61 pub use self::metadata::extend_scope_to_file;
62 pub use self::source_loc::set_source_location;
63
64 #[allow(non_upper_case_globals)]
65 const DW_TAG_auto_variable: c_uint = 0x100;
66 #[allow(non_upper_case_globals)]
67 const DW_TAG_arg_variable: c_uint = 0x101;
68
69 /// A context object for maintaining all state needed by the debuginfo module.
70 pub struct CrateDebugContext<'a, 'tcx> {
71     llcontext: &'a llvm::Context,
72     llmod: &'a llvm::Module,
73     builder: &'a mut DIBuilder<'a>,
74     created_files: RefCell<FxHashMap<(Symbol, Symbol), &'a DIFile>>,
75     created_enum_disr_types: RefCell<FxHashMap<(DefId, layout::Primitive), &'a DIType>>,
76
77     type_map: RefCell<TypeMap<'a, 'tcx>>,
78     namespace_map: RefCell<DefIdMap<&'a DIScope>>,
79
80     // This collection is used to assert that composite types (structs, enums,
81     // ...) have their members only set once:
82     composite_types_completed: RefCell<FxHashSet<&'a DIType>>,
83 }
84
85 impl Drop for CrateDebugContext<'a, 'tcx> {
86     fn drop(&mut self) {
87         unsafe {
88             llvm::LLVMRustDIBuilderDispose(&mut *(self.builder as *mut _));
89         }
90     }
91 }
92
93 impl<'a, 'tcx> CrateDebugContext<'a, 'tcx> {
94     pub fn new(llmod: &'a llvm::Module) -> Self {
95         debug!("CrateDebugContext::new");
96         let builder = unsafe { llvm::LLVMRustDIBuilderCreate(llmod) };
97         // DIBuilder inherits context from the module, so we'd better use the same one
98         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
99         CrateDebugContext {
100             llcontext,
101             llmod,
102             builder,
103             created_files: Default::default(),
104             created_enum_disr_types: Default::default(),
105             type_map: Default::default(),
106             namespace_map: RefCell::new(DefIdMap()),
107             composite_types_completed: Default::default(),
108         }
109     }
110 }
111
112 pub enum FunctionDebugContext<'ll> {
113     RegularContext(FunctionDebugContextData<'ll>),
114     DebugInfoDisabled,
115     FunctionWithoutDebugInfo,
116 }
117
118 impl FunctionDebugContext<'ll> {
119     pub fn get_ref<'a>(&'a self, span: Span) -> &'a FunctionDebugContextData<'ll> {
120         match *self {
121             FunctionDebugContext::RegularContext(ref data) => data,
122             FunctionDebugContext::DebugInfoDisabled => {
123                 span_bug!(span, "{}", FunctionDebugContext::debuginfo_disabled_message());
124             }
125             FunctionDebugContext::FunctionWithoutDebugInfo => {
126                 span_bug!(span, "{}", FunctionDebugContext::should_be_ignored_message());
127             }
128         }
129     }
130
131     fn debuginfo_disabled_message() -> &'static str {
132         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
133     }
134
135     fn should_be_ignored_message() -> &'static str {
136         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
137          ignored by debug info!"
138     }
139 }
140
141 pub struct FunctionDebugContextData<'ll> {
142     fn_metadata: &'ll DISubprogram,
143     source_locations_enabled: Cell<bool>,
144     pub defining_crate: CrateNum,
145 }
146
147 pub enum VariableAccess<'a, 'll> {
148     // The llptr given is an alloca containing the variable's value
149     DirectVariable { alloca: &'ll Value },
150     // The llptr given is an alloca containing the start of some pointer chain
151     // leading to the variable's content.
152     IndirectVariable { alloca: &'ll Value, address_operations: &'a [i64] }
153 }
154
155 pub enum VariableKind {
156     ArgumentVariable(usize /*index*/),
157     LocalVariable,
158 }
159
160 /// Create any deferred debug metadata nodes
161 pub fn finalize(cx: &CodegenCx) {
162     if cx.dbg_cx.is_none() {
163         return;
164     }
165
166     debug!("finalize");
167
168     if gdb::needs_gdb_debug_scripts_section(cx) {
169         // Add a .debug_gdb_scripts section to this compile-unit. This will
170         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
171         // which activates the Rust pretty printers for binary this section is
172         // contained in.
173         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
174     }
175
176     unsafe {
177         llvm::LLVMRustDIBuilderFinalize(DIB(cx));
178         // Debuginfo generation in LLVM by default uses a higher
179         // version of dwarf than macOS currently understands. We can
180         // instruct LLVM to emit an older version of dwarf, however,
181         // for macOS to understand. For more info see #11352
182         // This can be overridden using --llvm-opts -dwarf-version,N.
183         // Android has the same issue (#22398)
184         if cx.sess().target.target.options.is_like_osx ||
185            cx.sess().target.target.options.is_like_android {
186             llvm::LLVMRustAddModuleFlag(cx.llmod,
187                                         "Dwarf Version\0".as_ptr() as *const _,
188                                         2)
189         }
190
191         // Indicate that we want CodeView debug information on MSVC
192         if cx.sess().target.target.options.is_like_msvc {
193             llvm::LLVMRustAddModuleFlag(cx.llmod,
194                                         "CodeView\0".as_ptr() as *const _,
195                                         1)
196         }
197
198         // Prevent bitcode readers from deleting the debug info.
199         let ptr = "Debug Info Version\0".as_ptr();
200         llvm::LLVMRustAddModuleFlag(cx.llmod, ptr as *const _,
201                                     llvm::LLVMRustDebugMetadataVersion());
202     };
203 }
204
205 /// Creates the function-specific debug context.
206 ///
207 /// Returns the FunctionDebugContext for the function which holds state needed
208 /// for debug info creation. The function may also return another variant of the
209 /// FunctionDebugContext enum which indicates why no debuginfo should be created
210 /// for the function.
211 pub fn create_function_debug_context(
212     cx: &CodegenCx<'ll, 'tcx>,
213     instance: Instance<'tcx>,
214     sig: ty::FnSig<'tcx>,
215     llfn: &'ll Value,
216     mir: &mir::Mir,
217 ) -> FunctionDebugContext<'ll> {
218     if cx.sess().opts.debuginfo == DebugInfo::None {
219         return FunctionDebugContext::DebugInfoDisabled;
220     }
221
222     if let InstanceDef::Item(def_id) = instance.def {
223         if cx.tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NO_DEBUG) {
224             return FunctionDebugContext::FunctionWithoutDebugInfo;
225         }
226     }
227
228     let span = mir.span;
229
230     // This can be the case for functions inlined from another crate
231     if span.is_dummy() {
232         // FIXME(simulacrum): Probably can't happen; remove.
233         return FunctionDebugContext::FunctionWithoutDebugInfo;
234     }
235
236     let def_id = instance.def_id();
237     let containing_scope = get_containing_scope(cx, instance);
238     let loc = span_start(cx, span);
239     let file_metadata = file_metadata(cx, &loc.file.name, def_id.krate);
240
241     let function_type_metadata = unsafe {
242         let fn_signature = get_function_signature(cx, sig);
243         llvm::LLVMRustDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
244     };
245
246     // Find the enclosing function, in case this is a closure.
247     let def_key = cx.tcx.def_key(def_id);
248     let mut name = def_key.disambiguated_data.data.to_string();
249
250     let enclosing_fn_def_id = cx.tcx.closure_base_def_id(def_id);
251
252     // Get_template_parameters() will append a `<...>` clause to the function
253     // name if necessary.
254     let generics = cx.tcx.generics_of(enclosing_fn_def_id);
255     let substs = instance.substs.truncate_to(cx.tcx, generics);
256     let template_parameters = get_template_parameters(cx,
257                                                       &generics,
258                                                       substs,
259                                                       file_metadata,
260                                                       &mut name);
261
262     // Get the linkage_name, which is just the symbol name
263     let linkage_name = mangled_name_of_instance(cx, instance);
264
265     let scope_line = span_start(cx, span).line;
266     let is_local_to_unit = is_node_local_to_unit(cx, def_id);
267
268     let function_name = CString::new(name).unwrap();
269     let linkage_name = SmallCStr::new(&linkage_name.as_str());
270
271     let mut flags = DIFlags::FlagPrototyped;
272
273     let local_id = cx.tcx.hir.as_local_node_id(def_id);
274     if let Some((id, _, _)) = *cx.sess().entry_fn.borrow() {
275         if local_id == Some(id) {
276             flags |= DIFlags::FlagMainSubprogram;
277         }
278     }
279
280     if cx.layout_of(sig.output()).abi.is_uninhabited() {
281         flags |= DIFlags::FlagNoReturn;
282     }
283
284     let fn_metadata = unsafe {
285         llvm::LLVMRustDIBuilderCreateFunction(
286             DIB(cx),
287             containing_scope,
288             function_name.as_ptr(),
289             linkage_name.as_ptr(),
290             file_metadata,
291             loc.line as c_uint,
292             function_type_metadata,
293             is_local_to_unit,
294             true,
295             scope_line as c_uint,
296             flags,
297             cx.sess().opts.optimize != config::OptLevel::No,
298             llfn,
299             template_parameters,
300             None)
301     };
302
303     // Initialize fn debug context (including scope map and namespace map)
304     let fn_debug_context = FunctionDebugContextData {
305         fn_metadata,
306         source_locations_enabled: Cell::new(false),
307         defining_crate: def_id.krate,
308     };
309
310     return FunctionDebugContext::RegularContext(fn_debug_context);
311
312     fn get_function_signature(
313         cx: &CodegenCx<'ll, 'tcx>,
314         sig: ty::FnSig<'tcx>,
315     ) -> &'ll DIArray {
316         if cx.sess().opts.debuginfo == DebugInfo::Limited {
317             return create_DIArray(DIB(cx), &[]);
318         }
319
320         let mut signature = Vec::with_capacity(sig.inputs().len() + 1);
321
322         // Return type -- llvm::DIBuilder wants this at index 0
323         signature.push(match sig.output().sty {
324             ty::Tuple(ref tys) if tys.is_empty() => None,
325             _ => Some(type_metadata(cx, sig.output(), syntax_pos::DUMMY_SP))
326         });
327
328         let inputs = if sig.abi == Abi::RustCall {
329             &sig.inputs()[..sig.inputs().len() - 1]
330         } else {
331             sig.inputs()
332         };
333
334         // Arguments types
335         if cx.sess().target.target.options.is_like_msvc {
336             // FIXME(#42800):
337             // There is a bug in MSDIA that leads to a crash when it encounters
338             // a fixed-size array of `u8` or something zero-sized in a
339             // function-type (see #40477).
340             // As a workaround, we replace those fixed-size arrays with a
341             // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
342             // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
343             // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
344             // This transformed type is wrong, but these function types are
345             // already inaccurate due to ABI adjustments (see #42800).
346             signature.extend(inputs.iter().map(|&t| {
347                 let t = match t.sty {
348                     ty::Array(ct, _)
349                         if (ct == cx.tcx.types.u8) || cx.layout_of(ct).is_zst() => {
350                         cx.tcx.mk_imm_ptr(ct)
351                     }
352                     _ => t
353                 };
354                 Some(type_metadata(cx, t, syntax_pos::DUMMY_SP))
355             }));
356         } else {
357             signature.extend(inputs.iter().map(|t| {
358                 Some(type_metadata(cx, t, syntax_pos::DUMMY_SP))
359             }));
360         }
361
362         if sig.abi == Abi::RustCall && !sig.inputs().is_empty() {
363             if let ty::Tuple(args) = sig.inputs()[sig.inputs().len() - 1].sty {
364                 signature.extend(
365                     args.iter().map(|argument_type| {
366                         Some(type_metadata(cx, argument_type, syntax_pos::DUMMY_SP))
367                     })
368                 );
369             }
370         }
371
372         create_DIArray(DIB(cx), &signature[..])
373     }
374
375     fn get_template_parameters(
376         cx: &CodegenCx<'ll, 'tcx>,
377         generics: &ty::Generics,
378         substs: &Substs<'tcx>,
379         file_metadata: &'ll DIFile,
380         name_to_append_suffix_to: &mut String,
381     ) -> &'ll DIArray {
382         if substs.types().next().is_none() {
383             return create_DIArray(DIB(cx), &[]);
384         }
385
386         name_to_append_suffix_to.push('<');
387         for (i, actual_type) in substs.types().enumerate() {
388             if i != 0 {
389                 name_to_append_suffix_to.push_str(",");
390             }
391
392             let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), actual_type);
393             // Add actual type name to <...> clause of function name
394             let actual_type_name = compute_debuginfo_type_name(cx,
395                                                                actual_type,
396                                                                true);
397             name_to_append_suffix_to.push_str(&actual_type_name[..]);
398         }
399         name_to_append_suffix_to.push('>');
400
401         // Again, only create type information if full debuginfo is enabled
402         let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full {
403             let names = get_parameter_names(cx, generics);
404             substs.iter().zip(names).filter_map(|(kind, name)| {
405                 if let UnpackedKind::Type(ty) = kind.unpack() {
406                     let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
407                     let actual_type_metadata =
408                         type_metadata(cx, actual_type, syntax_pos::DUMMY_SP);
409                     let name = SmallCStr::new(&name.as_str());
410                     Some(unsafe {
411                         Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
412                             DIB(cx),
413                             None,
414                             name.as_ptr(),
415                             actual_type_metadata,
416                             file_metadata,
417                             0,
418                             0,
419                         ))
420                     })
421                 } else {
422                     None
423                 }
424             }).collect()
425         } else {
426             vec![]
427         };
428
429         create_DIArray(DIB(cx), &template_params[..])
430     }
431
432     fn get_parameter_names(cx: &CodegenCx,
433                            generics: &ty::Generics)
434                            -> Vec<InternedString> {
435         let mut names = generics.parent.map_or(vec![], |def_id| {
436             get_parameter_names(cx, cx.tcx.generics_of(def_id))
437         });
438         names.extend(generics.params.iter().map(|param| param.name));
439         names
440     }
441
442     fn get_containing_scope(
443         cx: &CodegenCx<'ll, 'tcx>,
444         instance: Instance<'tcx>,
445     ) -> &'ll DIScope {
446         // First, let's see if this is a method within an inherent impl. Because
447         // if yes, we want to make the result subroutine DIE a child of the
448         // subroutine's self-type.
449         let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| {
450             // If the method does *not* belong to a trait, proceed
451             if cx.tcx.trait_id_of_impl(impl_def_id).is_none() {
452                 let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions(
453                     instance.substs,
454                     ty::ParamEnv::reveal_all(),
455                     &cx.tcx.type_of(impl_def_id),
456                 );
457
458                 // Only "class" methods are generally understood by LLVM,
459                 // so avoid methods on other types (e.g. `<*mut T>::null`).
460                 match impl_self_ty.sty {
461                     ty::Adt(def, ..) if !def.is_box() => {
462                         Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP))
463                     }
464                     _ => None
465                 }
466             } else {
467                 // For trait method impls we still use the "parallel namespace"
468                 // strategy
469                 None
470             }
471         });
472
473         self_type.unwrap_or_else(|| {
474             namespace::item_namespace(cx, DefId {
475                 krate: instance.def_id().krate,
476                 index: cx.tcx
477                          .def_key(instance.def_id())
478                          .parent
479                          .expect("get_containing_scope: missing parent?")
480             })
481         })
482     }
483 }
484
485 pub fn declare_local(
486     bx: &Builder<'a, 'll, 'tcx>,
487     dbg_context: &FunctionDebugContext<'ll>,
488     variable_name: ast::Name,
489     variable_type: Ty<'tcx>,
490     scope_metadata: &'ll DIScope,
491     variable_access: VariableAccess<'_, 'll>,
492     variable_kind: VariableKind,
493     span: Span,
494 ) {
495     assert!(!dbg_context.get_ref(span).source_locations_enabled.get());
496     let cx = bx.cx;
497
498     let file = span_start(cx, span).file;
499     let file_metadata = file_metadata(cx,
500                                       &file.name,
501                                       dbg_context.get_ref(span).defining_crate);
502
503     let loc = span_start(cx, span);
504     let type_metadata = type_metadata(cx, variable_type, span);
505
506     let (argument_index, dwarf_tag) = match variable_kind {
507         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
508         LocalVariable => (0, DW_TAG_auto_variable)
509     };
510     let align = cx.align_of(variable_type);
511
512     let name = SmallCStr::new(&variable_name.as_str());
513     match (variable_access, &[][..]) {
514         (DirectVariable { alloca }, address_operations) |
515         (IndirectVariable {alloca, address_operations}, _) => {
516             let metadata = unsafe {
517                 llvm::LLVMRustDIBuilderCreateVariable(
518                     DIB(cx),
519                     dwarf_tag,
520                     scope_metadata,
521                     name.as_ptr(),
522                     file_metadata,
523                     loc.line as c_uint,
524                     type_metadata,
525                     cx.sess().opts.optimize != config::OptLevel::No,
526                     DIFlags::FlagZero,
527                     argument_index,
528                     align.abi() as u32,
529                 )
530             };
531             source_loc::set_debug_location(bx,
532                 InternalDebugLocation::new(scope_metadata, loc.line, loc.col.to_usize()));
533             unsafe {
534                 let debug_loc = llvm::LLVMGetCurrentDebugLocation(bx.llbuilder);
535                 let instr = llvm::LLVMRustDIBuilderInsertDeclareAtEnd(
536                     DIB(cx),
537                     alloca,
538                     metadata,
539                     address_operations.as_ptr(),
540                     address_operations.len() as c_uint,
541                     debug_loc,
542                     bx.llbb());
543
544                 llvm::LLVMSetInstDebugLocation(bx.llbuilder, instr);
545             }
546             source_loc::set_debug_location(bx, UnknownLocation);
547         }
548     }
549 }