]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/debuginfo/mod.rs
move job of creating local-def-ids to ast-map (with a few stragglers)
[rust.git] / src / librustc_trans / trans / 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, assert_type_for_node_id, contains_nodebug_attribute,
18                   create_DIArray, is_node_local_to_unit};
19 use self::namespace::{namespace_for_item, NamespaceTreeNode};
20 use self::type_names::compute_debuginfo_type_name;
21 use self::metadata::{type_metadata, diverging_type_metadata};
22 use self::metadata::{file_metadata, scope_metadata, TypeMap, compile_unit_metadata};
23 use self::source_loc::InternalDebugLocation;
24
25 use llvm;
26 use llvm::{ModuleRef, ContextRef, ValueRef};
27 use llvm::debuginfo::{DIFile, DIType, DIScope, DIBuilderRef, DISubprogram, DIArray,
28                       DIDescriptor, FlagPrototyped};
29 use middle::def_id::DefId;
30 use middle::infer::normalize_associated_type;
31 use middle::subst::{self, Substs};
32 use rustc_front;
33 use rustc_front::hir;
34
35 use trans::common::{NodeIdAndSpan, CrateContext, FunctionContext, Block};
36 use trans;
37 use trans::{monomorphize, type_of};
38 use middle::ty::{self, Ty};
39 use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
40 use util::nodemap::{NodeMap, FnvHashMap, FnvHashSet};
41 use rustc::front::map as hir_map;
42
43 use libc::c_uint;
44 use std::cell::{Cell, RefCell};
45 use std::ffi::CString;
46 use std::ptr;
47 use std::rc::Rc;
48
49 use syntax::codemap::{Span, Pos};
50 use syntax::{abi, ast, codemap};
51 use syntax::attr::IntType;
52 use syntax::parse::token::{self, special_idents};
53
54 pub mod gdb;
55 mod utils;
56 mod namespace;
57 mod type_names;
58 mod metadata;
59 mod create_scope_map;
60 mod source_loc;
61
62 pub use self::source_loc::set_source_location;
63 pub use self::source_loc::clear_source_location;
64 pub use self::source_loc::start_emitting_source_locations;
65 pub use self::source_loc::get_cleanup_debug_loc_for_ast_node;
66 pub use self::source_loc::with_source_location_override;
67 pub use self::metadata::create_match_binding_metadata;
68 pub use self::metadata::create_argument_metadata;
69 pub use self::metadata::create_captured_var_metadata;
70 pub use self::metadata::create_global_var_metadata;
71 pub use self::metadata::create_local_var_metadata;
72
73 #[allow(non_upper_case_globals)]
74 const DW_TAG_auto_variable: c_uint = 0x100;
75 #[allow(non_upper_case_globals)]
76 const DW_TAG_arg_variable: c_uint = 0x101;
77
78 /// A context object for maintaining all state needed by the debuginfo module.
79 pub struct CrateDebugContext<'tcx> {
80     llcontext: ContextRef,
81     builder: DIBuilderRef,
82     current_debug_location: Cell<InternalDebugLocation>,
83     created_files: RefCell<FnvHashMap<String, DIFile>>,
84     created_enum_disr_types: RefCell<FnvHashMap<(DefId, IntType), DIType>>,
85
86     type_map: RefCell<TypeMap<'tcx>>,
87     namespace_map: RefCell<FnvHashMap<Vec<ast::Name>, Rc<NamespaceTreeNode>>>,
88
89     // This collection is used to assert that composite types (structs, enums,
90     // ...) have their members only set once:
91     composite_types_completed: RefCell<FnvHashSet<DIType>>,
92 }
93
94 impl<'tcx> CrateDebugContext<'tcx> {
95     pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
96         debug!("CrateDebugContext::new");
97         let builder = unsafe { llvm::LLVMDIBuilderCreate(llmod) };
98         // DIBuilder inherits context from the module, so we'd better use the same one
99         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
100         return CrateDebugContext {
101             llcontext: llcontext,
102             builder: builder,
103             current_debug_location: Cell::new(InternalDebugLocation::UnknownLocation),
104             created_files: RefCell::new(FnvHashMap()),
105             created_enum_disr_types: RefCell::new(FnvHashMap()),
106             type_map: RefCell::new(TypeMap::new()),
107             namespace_map: RefCell::new(FnvHashMap()),
108             composite_types_completed: RefCell::new(FnvHashSet()),
109         };
110     }
111 }
112
113 pub enum FunctionDebugContext {
114     RegularContext(Box<FunctionDebugContextData>),
115     DebugInfoDisabled,
116     FunctionWithoutDebugInfo,
117 }
118
119 impl FunctionDebugContext {
120     fn get_ref<'a>(&'a self,
121                    cx: &CrateContext,
122                    span: Span)
123                    -> &'a FunctionDebugContextData {
124         match *self {
125             FunctionDebugContext::RegularContext(box ref data) => data,
126             FunctionDebugContext::DebugInfoDisabled => {
127                 cx.sess().span_bug(span,
128                                    FunctionDebugContext::debuginfo_disabled_message());
129             }
130             FunctionDebugContext::FunctionWithoutDebugInfo => {
131                 cx.sess().span_bug(span,
132                                    FunctionDebugContext::should_be_ignored_message());
133             }
134         }
135     }
136
137     fn debuginfo_disabled_message() -> &'static str {
138         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
139     }
140
141     fn should_be_ignored_message() -> &'static str {
142         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
143          ignored by debug info!"
144     }
145 }
146
147 struct FunctionDebugContextData {
148     scope_map: RefCell<NodeMap<DIScope>>,
149     fn_metadata: DISubprogram,
150     argument_counter: Cell<usize>,
151     source_locations_enabled: Cell<bool>,
152     source_location_override: Cell<bool>,
153 }
154
155 pub enum VariableAccess<'a> {
156     // The llptr given is an alloca containing the variable's value
157     DirectVariable { alloca: ValueRef },
158     // The llptr given is an alloca containing the start of some pointer chain
159     // leading to the variable's content.
160     IndirectVariable { alloca: ValueRef, address_operations: &'a [i64] }
161 }
162
163 pub enum VariableKind {
164     ArgumentVariable(usize /*index*/),
165     LocalVariable,
166     CapturedVariable,
167 }
168
169 /// Create any deferred debug metadata nodes
170 pub fn finalize(cx: &CrateContext) {
171     if cx.dbg_cx().is_none() {
172         return;
173     }
174
175     debug!("finalize");
176     let _ = compile_unit_metadata(cx);
177
178     if gdb::needs_gdb_debug_scripts_section(cx) {
179         // Add a .debug_gdb_scripts section to this compile-unit. This will
180         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
181         // which activates the Rust pretty printers for binary this section is
182         // contained in.
183         gdb::get_or_insert_gdb_debug_scripts_section_global(cx);
184     }
185
186     unsafe {
187         llvm::LLVMDIBuilderFinalize(DIB(cx));
188         llvm::LLVMDIBuilderDispose(DIB(cx));
189         // Debuginfo generation in LLVM by default uses a higher
190         // version of dwarf than OS X currently understands. We can
191         // instruct LLVM to emit an older version of dwarf, however,
192         // for OS X to understand. For more info see #11352
193         // This can be overridden using --llvm-opts -dwarf-version,N.
194         // Android has the same issue (#22398)
195         if cx.sess().target.target.options.is_like_osx ||
196            cx.sess().target.target.options.is_like_android {
197             llvm::LLVMRustAddModuleFlag(cx.llmod(),
198                                         "Dwarf Version\0".as_ptr() as *const _,
199                                         2)
200         }
201
202         // Prevent bitcode readers from deleting the debug info.
203         let ptr = "Debug Info Version\0".as_ptr();
204         llvm::LLVMRustAddModuleFlag(cx.llmod(), ptr as *const _,
205                                     llvm::LLVMRustDebugMetadataVersion());
206     };
207 }
208
209 /// Creates the function-specific debug context.
210 ///
211 /// Returns the FunctionDebugContext for the function which holds state needed
212 /// for debug info creation. The function may also return another variant of the
213 /// FunctionDebugContext enum which indicates why no debuginfo should be created
214 /// for the function.
215 pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
216                                                fn_ast_id: ast::NodeId,
217                                                param_substs: &Substs<'tcx>,
218                                                llfn: ValueRef) -> FunctionDebugContext {
219     if cx.sess().opts.debuginfo == NoDebugInfo {
220         return FunctionDebugContext::DebugInfoDisabled;
221     }
222
223     // Clear the debug location so we don't assign them in the function prelude.
224     // Do this here already, in case we do an early exit from this function.
225     source_loc::set_debug_location(cx, InternalDebugLocation::UnknownLocation);
226
227     if fn_ast_id == ast::DUMMY_NODE_ID {
228         // This is a function not linked to any source location, so don't
229         // generate debuginfo for it.
230         return FunctionDebugContext::FunctionWithoutDebugInfo;
231     }
232
233     let empty_generics = rustc_front::util::empty_generics();
234
235     let fnitem = cx.tcx().map.get(fn_ast_id);
236
237     let (name, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
238         hir_map::NodeItem(ref item) => {
239             if contains_nodebug_attribute(&item.attrs) {
240                 return FunctionDebugContext::FunctionWithoutDebugInfo;
241             }
242
243             match item.node {
244                 hir::ItemFn(ref fn_decl, _, _, _, ref generics, ref top_level_block) => {
245                     (item.name, fn_decl, generics, top_level_block, item.span, true)
246                 }
247                 _ => {
248                     cx.sess().span_bug(item.span,
249                         "create_function_debug_context: item bound to non-function");
250                 }
251             }
252         }
253         hir_map::NodeImplItem(impl_item) => {
254             match impl_item.node {
255                 hir::MethodImplItem(ref sig, ref body) => {
256                     if contains_nodebug_attribute(&impl_item.attrs) {
257                         return FunctionDebugContext::FunctionWithoutDebugInfo;
258                     }
259
260                     (impl_item.name,
261                      &sig.decl,
262                      &sig.generics,
263                      body,
264                      impl_item.span,
265                      true)
266                 }
267                 _ => {
268                     cx.sess().span_bug(impl_item.span,
269                                        "create_function_debug_context() \
270                                         called on non-method impl item?!")
271                 }
272             }
273         }
274         hir_map::NodeExpr(ref expr) => {
275             match expr.node {
276                 hir::ExprClosure(_, ref fn_decl, ref top_level_block) => {
277                     let name = format!("fn{}", token::gensym("fn"));
278                     let name = token::intern(&name[..]);
279                     (name, fn_decl,
280                         // This is not quite right. It should actually inherit
281                         // the generics of the enclosing function.
282                         &empty_generics,
283                         top_level_block,
284                         expr.span,
285                         // Don't try to lookup the item path:
286                         false)
287                 }
288                 _ => cx.sess().span_bug(expr.span,
289                         "create_function_debug_context: expected an expr_fn_block here")
290             }
291         }
292         hir_map::NodeTraitItem(trait_item) => {
293             match trait_item.node {
294                 hir::MethodTraitItem(ref sig, Some(ref body)) => {
295                     if contains_nodebug_attribute(&trait_item.attrs) {
296                         return FunctionDebugContext::FunctionWithoutDebugInfo;
297                     }
298
299                     (trait_item.name,
300                      &sig.decl,
301                      &sig.generics,
302                      body,
303                      trait_item.span,
304                      true)
305                 }
306                 _ => {
307                     cx.sess()
308                       .bug(&format!("create_function_debug_context: \
309                                     unexpected sort of node: {:?}",
310                                     fnitem))
311                 }
312             }
313         }
314         hir_map::NodeForeignItem(..) |
315         hir_map::NodeVariant(..) |
316         hir_map::NodeStructCtor(..) => {
317             return FunctionDebugContext::FunctionWithoutDebugInfo;
318         }
319         _ => cx.sess().bug(&format!("create_function_debug_context: \
320                                     unexpected sort of node: {:?}",
321                                    fnitem))
322     };
323
324     // This can be the case for functions inlined from another crate
325     if span == codemap::DUMMY_SP {
326         return FunctionDebugContext::FunctionWithoutDebugInfo;
327     }
328
329     let loc = span_start(cx, span);
330     let file_metadata = file_metadata(cx, &loc.file.name);
331
332     let function_type_metadata = unsafe {
333         let fn_signature = get_function_signature(cx,
334                                                   fn_ast_id,
335                                                   param_substs,
336                                                   span);
337         llvm::LLVMDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
338     };
339
340     // Get_template_parameters() will append a `<...>` clause to the function
341     // name if necessary.
342     let mut function_name = name.to_string();
343     let template_parameters = get_template_parameters(cx,
344                                                       generics,
345                                                       param_substs,
346                                                       file_metadata,
347                                                       &mut function_name);
348
349     // There is no hir_map::Path for hir::ExprClosure-type functions. For now,
350     // just don't put them into a namespace. In the future this could be improved
351     // somehow (storing a path in the hir_map, or construct a path using the
352     // enclosing function).
353     let (linkage_name, containing_scope) = if has_path {
354         let fn_ast_def_id = cx.tcx().map.local_def_id(fn_ast_id);
355         let namespace_node = namespace_for_item(cx, fn_ast_def_id);
356         let linkage_name = namespace_node.mangled_name_of_contained_item(
357             &function_name[..]);
358         let containing_scope = namespace_node.scope;
359         (linkage_name, containing_scope)
360     } else {
361         (function_name.clone(), file_metadata)
362     };
363
364     // Clang sets this parameter to the opening brace of the function's block,
365     // so let's do this too.
366     let scope_line = span_start(cx, top_level_block.span).line;
367
368     let is_local_to_unit = is_node_local_to_unit(cx, fn_ast_id);
369
370     let function_name = CString::new(function_name).unwrap();
371     let linkage_name = CString::new(linkage_name).unwrap();
372     let fn_metadata = unsafe {
373         llvm::LLVMDIBuilderCreateFunction(
374             DIB(cx),
375             containing_scope,
376             function_name.as_ptr(),
377             linkage_name.as_ptr(),
378             file_metadata,
379             loc.line as c_uint,
380             function_type_metadata,
381             is_local_to_unit,
382             true,
383             scope_line as c_uint,
384             FlagPrototyped as c_uint,
385             cx.sess().opts.optimize != config::No,
386             llfn,
387             template_parameters,
388             ptr::null_mut())
389     };
390
391     let scope_map = create_scope_map::create_scope_map(cx,
392                                                        &fn_decl.inputs,
393                                                        &*top_level_block,
394                                                        fn_metadata,
395                                                        fn_ast_id);
396
397     // Initialize fn debug context (including scope map and namespace map)
398     let fn_debug_context = box FunctionDebugContextData {
399         scope_map: RefCell::new(scope_map),
400         fn_metadata: fn_metadata,
401         argument_counter: Cell::new(1),
402         source_locations_enabled: Cell::new(false),
403         source_location_override: Cell::new(false),
404     };
405
406
407
408     return FunctionDebugContext::RegularContext(fn_debug_context);
409
410     fn get_function_signature<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
411                                         fn_ast_id: ast::NodeId,
412                                         param_substs: &Substs<'tcx>,
413                                         error_reporting_span: Span) -> DIArray {
414         if cx.sess().opts.debuginfo == LimitedDebugInfo {
415             return create_DIArray(DIB(cx), &[]);
416         }
417
418         // Return type -- llvm::DIBuilder wants this at index 0
419         assert_type_for_node_id(cx, fn_ast_id, error_reporting_span);
420         let fn_type = cx.tcx().node_id_to_type(fn_ast_id);
421
422         let (sig, abi) = match fn_type.sty {
423             ty::TyBareFn(_, ref barefnty) => {
424                 (cx.tcx().erase_late_bound_regions(&barefnty.sig), barefnty.abi)
425             }
426             ty::TyClosure(def_id, ref substs) => {
427                 let closure_type = cx.tcx().closure_type(def_id, substs);
428                 (cx.tcx().erase_late_bound_regions(&closure_type.sig), closure_type.abi)
429             }
430
431             _ => cx.sess().bug("get_function_metdata: Expected a function type!")
432         };
433         let sig = monomorphize::apply_param_substs(cx.tcx(), param_substs, &sig);
434
435         let mut signature = Vec::with_capacity(sig.inputs.len() + 1);
436
437         // Return type -- llvm::DIBuilder wants this at index 0
438         signature.push(match sig.output {
439             ty::FnConverging(ret_ty) => match ret_ty.sty {
440                 ty::TyTuple(ref tys) if tys.is_empty() => ptr::null_mut(),
441                 _ => type_metadata(cx, ret_ty, codemap::DUMMY_SP)
442             },
443             ty::FnDiverging => diverging_type_metadata(cx)
444         });
445
446         let inputs = &if abi == abi::RustCall {
447             type_of::untuple_arguments(cx, &sig.inputs)
448         } else {
449             sig.inputs
450         };
451
452         // Arguments types
453         for &argument_type in inputs {
454             signature.push(type_metadata(cx, argument_type, codemap::DUMMY_SP));
455         }
456
457         return create_DIArray(DIB(cx), &signature[..]);
458     }
459
460     fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
461                                          generics: &hir::Generics,
462                                          param_substs: &Substs<'tcx>,
463                                          file_metadata: DIFile,
464                                          name_to_append_suffix_to: &mut String)
465                                          -> DIArray
466     {
467         let self_type = param_substs.self_ty();
468         let self_type = normalize_associated_type(cx.tcx(), &self_type);
469
470         // Only true for static default methods:
471         let has_self_type = self_type.is_some();
472
473         if !generics.is_type_parameterized() && !has_self_type {
474             return create_DIArray(DIB(cx), &[]);
475         }
476
477         name_to_append_suffix_to.push('<');
478
479         // The list to be filled with template parameters:
480         let mut template_params: Vec<DIDescriptor> =
481             Vec::with_capacity(generics.ty_params.len() + 1);
482
483         // Handle self type
484         if has_self_type {
485             let actual_self_type = self_type.unwrap();
486             // Add self type name to <...> clause of function name
487             let actual_self_type_name = compute_debuginfo_type_name(
488                 cx,
489                 actual_self_type,
490                 true);
491
492             name_to_append_suffix_to.push_str(&actual_self_type_name[..]);
493
494             if generics.is_type_parameterized() {
495                 name_to_append_suffix_to.push_str(",");
496             }
497
498             // Only create type information if full debuginfo is enabled
499             if cx.sess().opts.debuginfo == FullDebugInfo {
500                 let actual_self_type_metadata = type_metadata(cx,
501                                                               actual_self_type,
502                                                               codemap::DUMMY_SP);
503
504                 let name = special_idents::type_self.name.as_str();
505
506                 let name = CString::new(name.as_bytes()).unwrap();
507                 let param_metadata = unsafe {
508                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
509                         DIB(cx),
510                         ptr::null_mut(),
511                         name.as_ptr(),
512                         actual_self_type_metadata,
513                         file_metadata,
514                         0,
515                         0)
516                 };
517
518                 template_params.push(param_metadata);
519             }
520         }
521
522         // Handle other generic parameters
523         let actual_types = param_substs.types.get_slice(subst::FnSpace);
524         for (index, &hir::TyParam{ name, .. }) in generics.ty_params.iter().enumerate() {
525             let actual_type = actual_types[index];
526             // Add actual type name to <...> clause of function name
527             let actual_type_name = compute_debuginfo_type_name(cx,
528                                                                actual_type,
529                                                                true);
530             name_to_append_suffix_to.push_str(&actual_type_name[..]);
531
532             if index != generics.ty_params.len() - 1 {
533                 name_to_append_suffix_to.push_str(",");
534             }
535
536             // Again, only create type information if full debuginfo is enabled
537             if cx.sess().opts.debuginfo == FullDebugInfo {
538                 let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
539                 let name = CString::new(name.as_str().as_bytes()).unwrap();
540                 let param_metadata = unsafe {
541                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
542                         DIB(cx),
543                         ptr::null_mut(),
544                         name.as_ptr(),
545                         actual_type_metadata,
546                         file_metadata,
547                         0,
548                         0)
549                 };
550                 template_params.push(param_metadata);
551             }
552         }
553
554         name_to_append_suffix_to.push('>');
555
556         return create_DIArray(DIB(cx), &template_params[..]);
557     }
558 }
559
560 fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
561                              variable_name: ast::Name,
562                              variable_type: Ty<'tcx>,
563                              scope_metadata: DIScope,
564                              variable_access: VariableAccess,
565                              variable_kind: VariableKind,
566                              span: Span) {
567     let cx: &CrateContext = bcx.ccx();
568
569     let filename = span_start(cx, span).file.name.clone();
570     let file_metadata = file_metadata(cx, &filename[..]);
571
572     let loc = span_start(cx, span);
573     let type_metadata = type_metadata(cx, variable_type, span);
574
575     let (argument_index, dwarf_tag) = match variable_kind {
576         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
577         LocalVariable    |
578         CapturedVariable => (0, DW_TAG_auto_variable)
579     };
580
581     let name = CString::new(variable_name.as_str().as_bytes()).unwrap();
582     match (variable_access, &[][..]) {
583         (DirectVariable { alloca }, address_operations) |
584         (IndirectVariable {alloca, address_operations}, _) => {
585             let metadata = unsafe {
586                 llvm::LLVMDIBuilderCreateVariable(
587                     DIB(cx),
588                     dwarf_tag,
589                     scope_metadata,
590                     name.as_ptr(),
591                     file_metadata,
592                     loc.line as c_uint,
593                     type_metadata,
594                     cx.sess().opts.optimize != config::No,
595                     0,
596                     address_operations.as_ptr(),
597                     address_operations.len() as c_uint,
598                     argument_index)
599             };
600             source_loc::set_debug_location(cx, InternalDebugLocation::new(scope_metadata,
601                                                                           loc.line,
602                                                                           loc.col.to_usize()));
603             unsafe {
604                 let debug_loc = llvm::LLVMGetCurrentDebugLocation(cx.raw_builder());
605                 let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd(
606                     DIB(cx),
607                     alloca,
608                     metadata,
609                     address_operations.as_ptr(),
610                     address_operations.len() as c_uint,
611                     debug_loc,
612                     bcx.llbb);
613
614                 llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr);
615             }
616         }
617     }
618
619     match variable_kind {
620         ArgumentVariable(_) | CapturedVariable => {
621             assert!(!bcx.fcx
622                         .debug_context
623                         .get_ref(cx, span)
624                         .source_locations_enabled
625                         .get());
626             source_loc::set_debug_location(cx, InternalDebugLocation::UnknownLocation);
627         }
628         _ => { /* nothing to do */ }
629     }
630 }
631
632 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
633 pub enum DebugLoc {
634     At(ast::NodeId, Span),
635     None
636 }
637
638 impl DebugLoc {
639     pub fn apply(&self, fcx: &FunctionContext) {
640         match *self {
641             DebugLoc::At(node_id, span) => {
642                 source_loc::set_source_location(fcx, node_id, span);
643             }
644             DebugLoc::None => {
645                 source_loc::clear_source_location(fcx);
646             }
647         }
648     }
649 }
650
651 pub trait ToDebugLoc {
652     fn debug_loc(&self) -> DebugLoc;
653 }
654
655 impl ToDebugLoc for hir::Expr {
656     fn debug_loc(&self) -> DebugLoc {
657         DebugLoc::At(self.id, self.span)
658     }
659 }
660
661 impl ToDebugLoc for NodeIdAndSpan {
662     fn debug_loc(&self) -> DebugLoc {
663         DebugLoc::At(self.id, self.span)
664     }
665 }
666
667 impl ToDebugLoc for Option<NodeIdAndSpan> {
668     fn debug_loc(&self) -> DebugLoc {
669         match *self {
670             Some(NodeIdAndSpan { id, span }) => DebugLoc::At(id, span),
671             None => DebugLoc::None
672         }
673     }
674 }