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