Skip to main content

rustc_codegen_llvm/debuginfo/
mod.rs

1#![doc = "# Debug Info Module\n\nThis module serves the purpose of generating debug symbols. We use LLVM\'s\n[source level debugging](https://llvm.org/docs/SourceLevelDebugging.html)\nfeatures for generating the debug information. The general principle is\nthis:\n\nGiven the right metadata in the LLVM IR, the LLVM code generator is able to\ncreate DWARF debug symbols for the given code. The\n[metadata](https://llvm.org/docs/LangRef.html#metadata-type) is structured\nmuch like DWARF *debugging information entries* (DIE), representing type\ninformation such as datatype layout, function signatures, block layout,\nvariable location and scope information, etc. It is the purpose of this\nmodule to generate correct metadata and insert it into the LLVM IR.\n\nAs the exact format of metadata trees may change between different LLVM\nversions, we now use LLVM\n[DIBuilder](https://llvm.org/docs/doxygen/html/classllvm_1_1DIBuilder.html)\nto create metadata where possible. This will hopefully ease the adaptation of\nthis module to future LLVM versions.\n\nThe public API of the module is a set of functions that will insert the\ncorrect metadata into the LLVM IR when called with the right parameters.\nThe module is thus driven from an outside client with functions like\n`debuginfo::create_local_var_metadata(bx: block, local: &ast::local)`.\n\nInternally the module will try to reuse already created metadata by\nutilizing a cache. The way to get a shared metadata node when needed is\nthus to just call the corresponding function in this module:\n```ignore (illustrative)\nlet file_metadata = file_metadata(cx, file);\n```\nThe function will take care of probing the cache for an existing node for\nthat exact file path.\n\nAll private state used by the module is stored within either the\nCodegenUnitDebugContext struct (owned by the CodegenCx) or the\nFunctionDebugContext (owned by the FunctionCx).\n\nThis file consists of three conceptual sections:\n1. The public interface of the module\n2. Module-internal metadata creation functions\n3. Minor utility functions\n\n\n## Recursive Types\n\nSome kinds of types, such as structs and enums can be recursive. That means\nthat the type definition of some type X refers to some other type which in\nturn (transitively) refers to X. This introduces cycles into the type\nreferral graph. A naive algorithm doing an on-demand, depth-first traversal\nof this graph when describing types, can get trapped in an endless loop\nwhen it reaches such a cycle.\n\nFor example, the following simple type for a singly-linked list...\n\n```\nstruct List {\n    value: i32,\n    tail: Option<Box<List>>,\n}\n```\n\nwill generate the following callstack with a naive DFS algorithm:\n\n```ignore (illustrative)\ndescribe(t = List)\n  describe(t = i32)\n  describe(t = Option<Box<List>>)\n    describe(t = Box<List>)\n      describe(t = List) // at the beginning again...\n      ...\n```\n\nTo break cycles like these, we use \"stubs\". That is, when\nthe algorithm encounters a possibly recursive type (any struct or enum), it\nimmediately creates a type description node and inserts it into the cache\n*before* describing the members of the type. This type description is just\na stub (as type members are not described and added to it yet) but it\nallows the algorithm to already refer to the type. After the stub is\ninserted into the cache, the algorithm continues as before. If it now\nencounters a recursive reference, it will hit the cache and does not try to\ndescribe the type anew. This behavior is encapsulated in the\n`type_map::build_type_with_children()` function.\n\n\n## Source Locations and Line Information\n\nIn addition to data type descriptions the debugging information must also\nallow mapping machine code locations back to source code locations in order\nto be useful. This functionality is also handled in this module. The\nfollowing functions allow controlling source mappings:\n\n+ `set_source_location()`\n+ `clear_source_location()`\n+ `start_emitting_source_locations()`\n\n`set_source_location()` allows setting the current source location. All IR\ninstructions created after a call to this function will be linked to the\ngiven source location, until another location is specified with\n`set_source_location()` or the source location is cleared with\n`clear_source_location()`. In the latter case, subsequent IR instructions\nwill not be linked to any source location. As you can see, this is a\nstateful API (mimicking the one in LLVM), so be careful with source\nlocations set by previous calls. It\'s probably best to not rely on any\nspecific state being present at a given point in code.\n\nOne topic that deserves some extra attention is *function prologues*. At\nthe beginning of a function\'s machine code there are typically a few\ninstructions for loading argument values into allocas and checking if\nthere\'s enough stack space for the function to execute. This *prologue* is\nnot visible in the source code and LLVM puts a special PROLOGUE END marker\ninto the line table at the first non-prologue instruction of the function.\nIn order to find out where the prologue ends, LLVM looks for the first\ninstruction in the function body that is linked to a source location. So,\nwhen generating prologue instructions we have to make sure that we don\'t\nemit source location information until the \'real\' function body begins. For\nthis reason, source location emission is disabled by default for any new\nfunction being codegened and is only activated after a call to the third\nfunction from the list above, `start_emitting_source_locations()`. This\nfunction should be called right before regularly starting to codegen the\ntop-level block of the given function.\n\nThere is one exception to the above rule: `llvm.dbg.declare` instruction\nmust be linked to the source location of the variable being declared. For\nfunction parameters these `llvm.dbg.declare` instructions typically occur\nin the middle of the prologue, however, they are ignored by LLVM\'s prologue\ndetection. The `create_argument_metadata()` and related functions take care\nof linking the `llvm.dbg.declare` instructions to the correct source\nlocations even while source location emission is still disabled, so there\nis no need to do anything special with source location handling here.\n"include_str!("doc.md")]
2
3use std::cell::{OnceCell, RefCell};
4use std::ops::Range;
5use std::sync::Arc;
6use std::{iter, ptr};
7
8use libc::c_uint;
9use metadata::create_subroutine_type;
10use rustc_abi::Size;
11use rustc_codegen_ssa::debuginfo::type_names;
12use rustc_codegen_ssa::mir::debuginfo::VariableKind;
13use rustc_codegen_ssa::mir::debuginfo::VariableKind::*;
14use rustc_codegen_ssa::traits::*;
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::unord::UnordMap;
17use rustc_hir::def_id::{DefId, DefIdMap};
18use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
19use rustc_middle::ty::{self, GenericArgs, Instance, Ty, TypeVisitableExt, Unnormalized};
20use rustc_session::Session;
21use rustc_session::config::{self, DebugInfo};
22use rustc_span::{
23    BytePos, Pos, SourceFile, SourceFileAndLine, SourceFileHash, Span, StableSourceFileId, Symbol,
24};
25use rustc_target::callconv::FnAbi;
26use rustc_target::spec::DebuginfoKind;
27use smallvec::SmallVec;
28use tracing::debug;
29
30pub(crate) use self::di_builder::DIBuilderExt;
31pub(crate) use self::metadata::build_global_var_di_node;
32use self::metadata::{
33    UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER, file_metadata, spanned_type_di_node, type_di_node,
34};
35use self::namespace::mangled_name_of_instance;
36use self::utils::{DIB, create_DIArray, debug_context, is_node_local_to_unit};
37use crate::builder::Builder;
38use crate::common::CodegenCx;
39use crate::debuginfo::di_builder::DIBuilderBox;
40use crate::llvm::debuginfo::{
41    DIArray, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DISubprogram,
42    DITemplateTypeParameter, DIType, DIVariable,
43};
44use crate::llvm::{self, Value};
45
46mod di_builder;
47mod dwarf_const;
48mod gdb;
49pub(crate) mod metadata;
50mod namespace;
51mod utils;
52
53/// A context object for maintaining all state needed by the debuginfo module.
54pub(crate) struct CodegenUnitDebugContext<'ll, 'tcx> {
55    builder: DIBuilderBox<'ll>,
56    created_files: RefCell<UnordMap<Option<(StableSourceFileId, SourceFileHash)>, &'ll DIFile>>,
57    type_map: metadata::TypeMap<'ll, 'tcx>,
58    adt_stack: RefCell<Vec<(DefId, GenericArgs<'tcx>)>>,
59    namespace_map: RefCell<DefIdMap<&'ll DIScope>>,
60    recursion_marker_type: OnceCell<&'ll DIType>,
61
62    /// A cache that lets different functions (within this CGU) that contain the same inlined
63    /// callee share a single `DISubprogram`.
64    inlined_function_scopes: RefCell<FxHashMap<Instance<'tcx>, &'ll DIScope>>,
65
66    /// Used alongside `inlined_function_scopes` to ensure that each `(subprogram, arg_index)` pair
67    /// has just one `DILocalVariable`, which LLVM requires.
68    ///
69    /// Consider the following example.
70    /// ```ignore (incomplete)
71    /// #[inline] fn callee(x: &[u8]) { ... }
72    /// fn f1(s: &[u8]) { callee(s) }
73    /// fn f2(s: &mut [u8]) { callee(&*s) }
74    /// fn f3(p: *const [u8]) { callee(unsafe { &*p }) }
75    /// ```
76    /// The `ReferencePropagation` pass eliminates reborrows, and we end up with a MIR local in
77    /// each of `f1`, `f2`, and `f3` that `callee`'s parameter debuginfo points to. But each of
78    /// those MIR locals has a different type: `&[u8]`, `&mut [u8]`, and `*const [u8]`. Naively, we
79    /// would end up with three distinct `DILocalVariable` entries, each one claiming to be param 1
80    /// of `callee`, identical except for their type. LLVM's debug verifier doesn't like this.
81    ///
82    /// With `params_seen`, we create a `DILocalVariable` for `f1` and then `f2` and `f3` reuse it.
83    /// (Though it's not guaranteed `f1` will come first.) That means they get a slightly wrong
84    /// type in the debugger (e.g. `&[u8]` instead of `&mut [u8]` in `f2`).
85    params_seen: RefCell<FxHashMap<(&'ll DISubprogram, usize), &'ll DIVariable>>,
86}
87
88impl<'ll, 'tcx> CodegenUnitDebugContext<'ll, 'tcx> {
89    pub(crate) fn new(llmod: llvm::Module<'ll>, sess: &Session) -> Self {
90        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5989b83b125120725b75332ca63d15fe93c912dd/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs:90",
                        "rustc_codegen_llvm::debuginfo", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5989b83b125120725b75332ca63d15fe93c912dd/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(90u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("CodegenUnitDebugContext::new")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("CodegenUnitDebugContext::new");
91
92        match sess.target.debuginfo_kind {
93            DebuginfoKind::Dwarf | DebuginfoKind::DwarfDsym => {
94                // Debuginfo generation in LLVM by default uses a higher
95                // version of dwarf than macOS currently understands. We can
96                // instruct LLVM to emit an older version of dwarf, however,
97                // for macOS to understand. For more info see #11352
98                // This can be overridden using --llvm-opts -dwarf-version,N.
99                // Android has the same issue (#22398)
100                llvm::add_module_flag_u32(
101                    llmod,
102                    // In the case where multiple CGUs with different dwarf version
103                    // values are being merged together, such as with cross-crate
104                    // LTO, then we want to use the highest version of dwarf
105                    // we can. This matches Clang's behavior as well.
106                    llvm::ModuleFlagMergeBehavior::Max,
107                    "Dwarf Version",
108                    sess.dwarf_version(),
109                );
110            }
111            DebuginfoKind::Pdb => {
112                // Indicate that we want CodeView debug information
113                llvm::add_module_flag_u32(
114                    llmod,
115                    llvm::ModuleFlagMergeBehavior::Warning,
116                    "CodeView",
117                    1,
118                );
119            }
120        }
121
122        // Prevent bitcode readers from deleting the debug info.
123        llvm::add_module_flag_u32(
124            llmod,
125            llvm::ModuleFlagMergeBehavior::Warning,
126            "Debug Info Version",
127            unsafe { llvm::LLVMRustDebugMetadataVersion() },
128        );
129
130        let builder = DIBuilderBox::new(llmod);
131        // DIBuilder inherits context from the module, so we'd better use the same one
132        CodegenUnitDebugContext {
133            builder,
134            created_files: Default::default(),
135            type_map: Default::default(),
136            adt_stack: Default::default(),
137            namespace_map: Default::default(),
138            recursion_marker_type: OnceCell::new(),
139            inlined_function_scopes: Default::default(),
140            params_seen: Default::default(),
141        }
142    }
143
144    pub(crate) fn finalize(&self) {
145        unsafe { llvm::LLVMDIBuilderFinalize(self.builder.as_ref()) };
146    }
147}
148
149impl<'ll> Builder<'_, 'll, '_> {
150    pub(crate) fn get_dbg_loc(&self) -> Option<&'ll DILocation> {
151        unsafe { llvm::LLVMGetCurrentDebugLocation2(self.llbuilder()) }
152    }
153}
154
155impl<'ll, 'tcx> DebugInfoBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
156    fn dbg_scope_fn(
157        &mut self,
158        instance: Instance<'tcx>,
159        fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
160        maybe_definition_llfn: Option<Value<'ll>>,
161    ) -> &'ll DIScope {
162        let tcx = self.tcx;
163
164        // If `maybe_definition_llfn` is `None` then it's an inlined callee. Reuse the previously
165        // generated scope for that callee, if there is one.
166        if maybe_definition_llfn.is_none()
167            && let Some(scope) = debug_context(self).inlined_function_scopes.borrow().get(&instance)
168        {
169            return scope;
170        }
171
172        let def_id = instance.def_id();
173        let (containing_scope, is_method) = get_containing_scope(self, instance);
174        let span = tcx.def_span(def_id);
175        let loc = self.lookup_debug_loc(span.lo());
176        let file_metadata = file_metadata(self, &loc.file);
177
178        let function_type_metadata =
179            create_subroutine_type(self, &get_function_signature(self, fn_abi, span));
180
181        let mut name = String::with_capacity(64);
182        type_names::push_item_name(tcx, def_id, false, &mut name);
183
184        // Find the enclosing function, in case this is a closure.
185        let enclosing_fn_def_id = tcx.typeck_root_def_id(def_id);
186
187        // We look up the generics of the enclosing function and truncate the args
188        // to their length in order to cut off extra stuff that might be in there for
189        // closures or coroutines.
190        let generics = tcx.generics_of(enclosing_fn_def_id);
191        let args = instance.args.truncate_to(tcx, generics);
192
193        type_names::push_generic_args(
194            tcx,
195            tcx.normalize_erasing_regions(self.typing_env(), Unnormalized::new_wip(args)),
196            &mut name,
197        );
198
199        let template_parameters = get_template_parameters(self, generics, args);
200
201        let linkage_name = &mangled_name_of_instance(self, instance).name;
202        // Omit the linkage_name if it is the same as subprogram name.
203        let linkage_name = if &name == linkage_name { "" } else { linkage_name };
204
205        // FIXME(eddyb) does this need to be separate from `loc.line` for some reason?
206        let scope_line = loc.line;
207
208        let mut flags = DIFlags::FlagPrototyped;
209
210        if fn_abi.ret.layout.is_uninhabited() {
211            flags |= DIFlags::FlagNoReturn;
212        }
213
214        let mut spflags = DISPFlags::SPFlagDefinition;
215        if is_node_local_to_unit(self, def_id) {
216            spflags |= DISPFlags::SPFlagLocalToUnit;
217        }
218        if self.sess().opts.optimize != config::OptLevel::No {
219            spflags |= DISPFlags::SPFlagOptimized;
220        }
221        if let Some((id, _)) = tcx.entry_fn(()) {
222            if id == def_id {
223                spflags |= DISPFlags::SPFlagMainSubprogram;
224            }
225        }
226
227        // When we're adding a method to a type DIE, we only want a DW_AT_declaration there, because
228        // LLVM LTO can't unify type definitions when a child DIE is a full subprogram definition.
229        // When we use this `decl` below, the subprogram definition gets created at the CU level
230        // with a DW_AT_specification pointing back to the type's declaration.
231        let decl = is_method.then(|| unsafe {
232            llvm::LLVMRustDIBuilderCreateMethod(
233                DIB(self),
234                containing_scope,
235                name.as_ptr(),
236                name.len(),
237                linkage_name.as_ptr(),
238                linkage_name.len(),
239                file_metadata,
240                loc.line,
241                function_type_metadata,
242                flags,
243                spflags & !DISPFlags::SPFlagDefinition,
244                template_parameters,
245            )
246        });
247
248        let scope = unsafe {
249            llvm::LLVMRustDIBuilderCreateFunction(
250                DIB(self),
251                containing_scope,
252                name.as_ptr(),
253                name.len(),
254                linkage_name.as_ptr(),
255                linkage_name.len(),
256                file_metadata,
257                loc.line,
258                function_type_metadata,
259                scope_line,
260                flags,
261                spflags,
262                maybe_definition_llfn,
263                template_parameters,
264                decl,
265            )
266        };
267        if maybe_definition_llfn.is_none() {
268            debug_context(self).inlined_function_scopes.borrow_mut().insert(instance, scope);
269        }
270        return scope;
271
272        fn get_function_signature<'ll, 'tcx>(
273            cx: &CodegenCx<'ll, 'tcx>,
274            fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
275            span: Span,
276        ) -> Vec<Option<&'ll llvm::Metadata>> {
277            if cx.sess().opts.debuginfo != DebugInfo::Full {
278                return ::alloc::vec::Vec::new()vec![];
279            }
280
281            let mut signature = Vec::with_capacity(fn_abi.args.len() + 1);
282
283            // Return type -- llvm::DIBuilder wants this at index 0
284            signature.push(if fn_abi.ret.layout.ty.is_unit() {
285                None
286            } else {
287                Some(spanned_type_di_node(cx, fn_abi.ret.layout.ty, span))
288            });
289
290            // Arguments types
291            if cx.sess().target.is_like_msvc {
292                // FIXME(#42800):
293                // There is a bug in MSDIA that leads to a crash when it encounters
294                // a fixed-size array of `u8` or something zero-sized in a
295                // function-type (see #40477).
296                // As a workaround, we replace those fixed-size arrays with a
297                // pointer-type. So a function `fn foo(a: u8, b: [u8; 4])` would
298                // appear as `fn foo(a: u8, b: *const u8)` in debuginfo,
299                // and a function `fn bar(x: [(); 7])` as `fn bar(x: *const ())`.
300                // This transformed type is wrong, but these function types are
301                // already inaccurate due to ABI adjustments (see #42800).
302                signature.extend(fn_abi.args.iter().map(|arg| {
303                    let t = arg.layout.ty;
304                    let t = match t.kind() {
305                        ty::Array(ct, _)
306                            if (*ct == cx.tcx.types.u8) || cx.layout_of(*ct).is_zst() =>
307                        {
308                            Ty::new_imm_ptr(cx.tcx, *ct)
309                        }
310                        _ => t,
311                    };
312                    Some(spanned_type_di_node(cx, t, span))
313                }));
314            } else {
315                signature.extend(
316                    fn_abi
317                        .args
318                        .iter()
319                        .map(|arg| Some(spanned_type_di_node(cx, arg.layout.ty, span))),
320                );
321            }
322
323            signature
324        }
325
326        fn get_template_parameters<'ll, 'tcx>(
327            cx: &CodegenCx<'ll, 'tcx>,
328            generics: &ty::Generics,
329            args: GenericArgs<'tcx>,
330        ) -> &'ll DIArray {
331            if args.terms().next().is_none() {
332                return create_DIArray(DIB(cx), &[]);
333            }
334
335            // Again, only create type information if full debuginfo is enabled
336            let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full {
337                let names = get_parameter_names(cx, generics);
338                iter::zip(args, names)
339                    .filter_map(|(kind, name)| {
340                        // FIXME: debug info for consts (using `createTemplateValueParameter`?)
341                        kind.as_type().map(|ty| {
342                            let actual_type = cx.tcx.normalize_erasing_regions(
343                                cx.typing_env(),
344                                Unnormalized::new_wip(ty),
345                            );
346                            let actual_type_metadata = type_di_node(cx, actual_type);
347                            Some(cx.create_template_type_parameter(
348                                name.as_str(),
349                                actual_type_metadata,
350                            ))
351                        })
352                    })
353                    .collect()
354            } else {
355                ::alloc::vec::Vec::new()vec![]
356            };
357
358            create_DIArray(DIB(cx), &template_params)
359        }
360
361        fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
362            let mut names = generics.parent.map_or_else(Vec::new, |def_id| {
363                get_parameter_names(cx, cx.tcx.generics_of(def_id))
364            });
365            names.extend(generics.own_params.iter().map(|param| param.name));
366            names
367        }
368
369        /// Returns a scope, plus `true` if that's a type scope for "class" methods,
370        /// otherwise `false` for plain namespace scopes.
371        fn get_containing_scope<'ll, 'tcx>(
372            cx: &CodegenCx<'ll, 'tcx>,
373            instance: Instance<'tcx>,
374        ) -> (&'ll DIScope, bool) {
375            // First, let's see if this is a method within an inherent impl. Because
376            // if yes, we want to make the result subroutine DIE a child of the
377            // subroutine's self-type.
378            // For trait method impls we still use the "parallel namespace"
379            // strategy
380            if let Some(imp_def_id) = cx.tcx.inherent_impl_of_assoc(instance.def_id()) {
381                let impl_self_ty = cx.tcx.instantiate_and_normalize_erasing_regions(
382                    instance.args,
383                    cx.typing_env(),
384                    cx.tcx.type_of(imp_def_id),
385                );
386
387                // Only "class" methods are generally understood by LLVM,
388                // so avoid methods on other types (e.g., `<*mut T>::null`).
389                if let ty::Adt(def, ..) = impl_self_ty.kind()
390                    && !def.is_box()
391                {
392                    // Again, only create type information if full debuginfo is enabled
393                    if cx.sess().opts.debuginfo == DebugInfo::Full && !impl_self_ty.has_param() {
394                        return (type_di_node(cx, impl_self_ty), true);
395                    } else {
396                        return (namespace::item_namespace(cx, def.did()), false);
397                    }
398                }
399            }
400
401            let scope = namespace::item_namespace(
402                cx,
403                DefId {
404                    krate: instance.def_id().krate,
405                    index: cx
406                        .tcx
407                        .def_key(instance.def_id())
408                        .parent
409                        .expect("get_containing_scope: missing parent?"),
410                },
411            );
412            (scope, false)
413        }
414    }
415
416    fn dbg_create_lexical_block(
417        &mut self,
418        pos: BytePos,
419        parent_scope: &'ll DIScope,
420    ) -> &'ll DIScope {
421        let loc = self.lookup_debug_loc(pos);
422        let file_metadata = file_metadata(self, &loc.file);
423        unsafe {
424            llvm::LLVMDIBuilderCreateLexicalBlock(
425                DIB(self),
426                parent_scope,
427                file_metadata,
428                loc.line,
429                loc.col,
430            )
431        }
432    }
433
434    fn dbg_location_clone_with_discriminator(
435        &mut self,
436        loc: &'ll DILocation,
437        discriminator: u32,
438    ) -> Option<&'ll DILocation> {
439        unsafe { llvm::LLVMRustDILocationCloneWithBaseDiscriminator(loc, discriminator) }
440    }
441
442    fn dbg_loc(
443        &mut self,
444        scope: &'ll DIScope,
445        inlined_at: Option<&'ll DILocation>,
446        span: Span,
447    ) -> &'ll DILocation {
448        let (line, col) = if span.is_dummy() {
449            (0, 0)
450        } else {
451            let DebugLoc { line, col, .. } = self.lookup_debug_loc(span.lo());
452            (line, col)
453        };
454
455        unsafe { llvm::LLVMDIBuilderCreateDebugLocation(self.llcx, line, col, scope, inlined_at) }
456    }
457
458    fn extend_scope_to_file(
459        &mut self,
460        scope_metadata: &'ll DIScope,
461        file: &rustc_span::SourceFile,
462    ) -> &'ll DILexicalBlock {
463        metadata::extend_scope_to_file(self, scope_metadata, file)
464    }
465
466    // FIXME(eddyb) find a common convention for all of the debuginfo-related
467    // names (choose between `dbg`, `debug`, `debuginfo`, `debug_info` etc.).
468    fn create_dbg_var(
469        &mut self,
470        variable_name: Symbol,
471        variable_type: Ty<'tcx>,
472        scope_metadata: &'ll DIScope,
473        variable_kind: VariableKind,
474        span: Span,
475    ) -> &'ll DIVariable {
476        let mut opt_subprogram = None;
477        match variable_kind {
478            ArgumentVariable(arg_index) => {
479                // `scope_metadata` must be a local scope. The `params_seen` key must be a
480                // `DISubprogram`.
481                let subprogram = unsafe { llvm::LLVMRustGetDISubprogram(scope_metadata) };
482                if let Some(var) =
483                    debug_context(self).params_seen.borrow().get(&(subprogram, arg_index))
484                {
485                    return var;
486                }
487                opt_subprogram = Some(subprogram);
488            }
489            LocalVariable => {}
490        }
491
492        let loc = self.lookup_debug_loc(span.lo());
493        let file_metadata = file_metadata(self, &loc.file);
494
495        let type_metadata = spanned_type_di_node(self, variable_type, span);
496
497        let align = self.align_of(variable_type);
498
499        let name = variable_name.as_str();
500
501        match variable_kind {
502            ArgumentVariable(arg_index) => {
503                let var = unsafe {
504                    llvm::LLVMDIBuilderCreateParameterVariable(
505                        DIB(self),
506                        scope_metadata,
507                        name.as_ptr(),
508                        name.len(),
509                        arg_index as c_uint,
510                        file_metadata,
511                        loc.line,
512                        type_metadata,
513                        llvm::Bool::TRUE, // (preserve descriptor during optimizations)
514                        DIFlags::FlagZero,
515                    )
516                };
517                debug_context(self)
518                    .params_seen
519                    .borrow_mut()
520                    .insert((opt_subprogram.unwrap(), arg_index), var);
521                var
522            }
523            LocalVariable => unsafe {
524                llvm::LLVMDIBuilderCreateAutoVariable(
525                    DIB(self),
526                    scope_metadata,
527                    name.as_ptr(),
528                    name.len(),
529                    file_metadata,
530                    loc.line,
531                    type_metadata,
532                    llvm::Bool::TRUE, // (preserve descriptor during optimizations)
533                    DIFlags::FlagZero,
534                    align.bits() as u32,
535                )
536            },
537        }
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 dbg_var_addr(
543        &mut self,
544        dbg_var: &'ll DIVariable,
545        dbg_loc: &'ll DILocation,
546        variable_alloca: Self::Value,
547        direct_offset: Size,
548        indirect_offsets: &[Size],
549        fragment: &Option<Range<Size>>,
550    ) {
551        use dwarf_const::{DW_OP_LLVM_fragment, DW_OP_deref, DW_OP_plus_uconst};
552
553        // Convert the direct and indirect offsets and fragment byte range to address ops.
554        let mut addr_ops = SmallVec::<[u64; 8]>::new();
555
556        if direct_offset.bytes() > 0 {
557            addr_ops.push(DW_OP_plus_uconst);
558            addr_ops.push(direct_offset.bytes());
559        }
560        for &offset in indirect_offsets {
561            addr_ops.push(DW_OP_deref);
562            if offset.bytes() > 0 {
563                addr_ops.push(DW_OP_plus_uconst);
564                addr_ops.push(offset.bytes());
565            }
566        }
567        if let Some(fragment) = fragment {
568            // `DW_OP_LLVM_fragment` takes as arguments the fragment's
569            // offset and size, both of them in bits.
570            addr_ops.push(DW_OP_LLVM_fragment);
571            addr_ops.push(fragment.start.bits());
572            addr_ops.push((fragment.end - fragment.start).bits());
573        }
574
575        let di_builder = DIB(self.cx());
576        let addr_expr = di_builder.create_expression(&addr_ops);
577        unsafe {
578            llvm::LLVMDIBuilderInsertDeclareRecordAtEnd(
579                di_builder,
580                variable_alloca,
581                dbg_var,
582                addr_expr,
583                dbg_loc,
584                self.llbb(),
585            )
586        };
587    }
588
589    fn dbg_var_value(
590        &mut self,
591        dbg_var: &'ll DIVariable,
592        dbg_loc: &'ll DILocation,
593        value: Self::Value,
594        direct_offset: Size,
595        indirect_offsets: &[Size],
596        fragment: &Option<Range<Size>>,
597    ) {
598        use dwarf_const::{DW_OP_LLVM_fragment, DW_OP_deref, DW_OP_plus_uconst, DW_OP_stack_value};
599
600        // Convert the direct and indirect offsets and fragment byte range to address ops.
601        let mut addr_ops = SmallVec::<[u64; 8]>::new();
602
603        if direct_offset.bytes() > 0 {
604            addr_ops.push(DW_OP_plus_uconst);
605            addr_ops.push(direct_offset.bytes());
606            addr_ops.push(DW_OP_stack_value);
607        }
608        for &offset in indirect_offsets {
609            addr_ops.push(DW_OP_deref);
610            if offset.bytes() > 0 {
611                addr_ops.push(DW_OP_plus_uconst);
612                addr_ops.push(offset.bytes());
613            }
614        }
615        if let Some(fragment) = fragment {
616            // `DW_OP_LLVM_fragment` takes as arguments the fragment's
617            // offset and size, both of them in bits.
618            addr_ops.push(DW_OP_LLVM_fragment);
619            addr_ops.push(fragment.start.bits());
620            addr_ops.push((fragment.end - fragment.start).bits());
621        }
622
623        let di_builder = DIB(self.cx());
624        let addr_expr = unsafe {
625            llvm::LLVMDIBuilderCreateExpression(di_builder, addr_ops.as_ptr(), addr_ops.len())
626        };
627        unsafe {
628            llvm::LLVMDIBuilderInsertDbgValueRecordAtEnd(
629                di_builder,
630                value,
631                dbg_var,
632                addr_expr,
633                dbg_loc,
634                self.llbb(),
635            );
636        }
637    }
638
639    fn set_dbg_loc(&mut self, dbg_loc: &'ll DILocation) {
640        unsafe {
641            llvm::LLVMSetCurrentDebugLocation2(self.llbuilder(), dbg_loc);
642        }
643    }
644
645    fn clear_dbg_loc(&mut self) {
646        unsafe {
647            llvm::LLVMSetCurrentDebugLocation2(self.llbuilder(), ptr::null());
648        }
649    }
650
651    fn insert_reference_to_gdb_debug_scripts_section_global(&mut self) {
652        gdb::insert_reference_to_gdb_debug_scripts_section_global(self)
653    }
654
655    fn set_var_name(&mut self, value: Value<'ll>, name: &str) {
656        // Avoid wasting time if LLVM value names aren't even enabled.
657        if self.sess().fewer_names() {
658            return;
659        }
660
661        // Only function parameters and instructions are local to a function,
662        // don't change the name of anything else (e.g. globals).
663        let param_or_inst = unsafe {
664            llvm::LLVMIsAArgument(value).is_some() || llvm::LLVMIsAInstruction(value).is_some()
665        };
666        if !param_or_inst {
667            return;
668        }
669
670        // Avoid replacing the name if it already exists.
671        // While we could combine the names somehow, it'd
672        // get noisy quick, and the usefulness is dubious.
673        if llvm::get_value_name(value).is_empty() {
674            llvm::set_value_name(value, name.as_bytes());
675        }
676    }
677
678    /// Annotate move/copy operations with debug info for profiling.
679    ///
680    /// This creates a temporary debug scope that makes the move/copy appear as an inlined call to
681    /// `compiler_move<T, SIZE>()` or `compiler_copy<T, SIZE>()`. The provided closure is executed
682    /// with this temporary debug location active.
683    ///
684    /// The `instance` parameter should be the monomorphized instance of the `compiler_move` or
685    /// `compiler_copy` function with the actual type and size.
686    fn with_move_annotation<R>(
687        &mut self,
688        instance: ty::Instance<'tcx>,
689        f: impl FnOnce(&mut Self) -> R,
690    ) -> R {
691        // Save the current debug location
692        let saved_loc = self.get_dbg_loc();
693
694        // Create a DIScope for the compiler_move/compiler_copy function
695        // We use the function's FnAbi for debug info generation
696        let fn_abi = self
697            .cx()
698            .tcx
699            .fn_abi_of_instance(
700                self.cx().typing_env().as_query_input((instance, ty::List::empty())),
701            )
702            .unwrap();
703
704        let di_scope = self.dbg_scope_fn(instance, fn_abi, None);
705
706        // Create an inlined debug location:
707        // - scope: the compiler_move/compiler_copy function
708        // - inlined_at: the current location (where the move/copy actually occurs)
709        // - span: use the function's definition span
710        let fn_span = self.cx().tcx.def_span(instance.def_id());
711        let inlined_loc = self.dbg_loc(di_scope, saved_loc, fn_span);
712
713        // Set the temporary debug location
714        self.set_dbg_loc(inlined_loc);
715
716        // Execute the closure (which will generate the memcpy)
717        let result = f(self);
718
719        // Restore the original debug location
720        if let Some(loc) = saved_loc {
721            self.set_dbg_loc(loc);
722        } else {
723            self.clear_dbg_loc();
724        }
725
726        result
727    }
728}
729
730/// A source code location used to generate debug information.
731// FIXME(eddyb) rename this to better indicate it's a duplicate of
732// `rustc_span::Loc` rather than `DILocation`, perhaps by making
733// `lookup_char_pos` return the right information instead.
734struct DebugLoc {
735    /// Information about the original source file.
736    file: Arc<SourceFile>,
737    /// The (1-based) line number.
738    line: u32,
739    /// The (1-based) column number.
740    col: u32,
741}
742
743impl<'ll> CodegenCx<'ll, '_> {
744    /// Looks up debug source information about a `BytePos`.
745    // FIXME(eddyb) rename this to better indicate it's a duplicate of
746    // `lookup_char_pos` rather than `dbg_loc`, perhaps by making
747    // `lookup_char_pos` return the right information instead.
748    fn lookup_debug_loc(&self, pos: BytePos) -> DebugLoc {
749        let (file, line, col) = match self.sess().source_map().lookup_line(pos) {
750            Ok(SourceFileAndLine { sf: file, line }) => {
751                let line_pos = file.lines()[line];
752
753                // Use 1-based indexing.
754                let line = (line + 1) as u32;
755                let col = (file.relative_position(pos) - line_pos).to_u32() + 1;
756
757                (file, line, col)
758            }
759            Err(file) => (file, UNKNOWN_LINE_NUMBER, UNKNOWN_COLUMN_NUMBER),
760        };
761
762        // For MSVC, omit the column number.
763        // Otherwise, emit it. This mimics clang behaviour.
764        // See discussion in https://github.com/rust-lang/rust/issues/42921
765        if self.sess().target.is_like_msvc {
766            DebugLoc { file, line, col: UNKNOWN_COLUMN_NUMBER }
767        } else {
768            DebugLoc { file, line, col }
769        }
770    }
771
772    fn create_template_type_parameter(
773        &self,
774        name: &str,
775        actual_type_metadata: &'ll DIType,
776    ) -> &'ll DITemplateTypeParameter {
777        unsafe {
778            llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
779                DIB(self),
780                None,
781                name.as_ptr(),
782                name.len(),
783                actual_type_metadata,
784            )
785        }
786    }
787
788    /// Creates any deferred debug metadata nodes
789    pub(crate) fn debuginfo_finalize(&self) {
790        if let Some(dbg_cx) = &self.dbg_cx {
791            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5989b83b125120725b75332ca63d15fe93c912dd/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs:791",
                        "rustc_codegen_llvm::debuginfo", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5989b83b125120725b75332ca63d15fe93c912dd/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(791u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::debuginfo"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("finalize")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("finalize");
792
793            if gdb::needs_gdb_debug_scripts_section(self) {
794                // Add a .debug_gdb_scripts section to this compile-unit. This will
795                // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
796                // which activates the Rust pretty printers for binary this section is
797                // contained in.
798                gdb::get_or_insert_gdb_debug_scripts_section_global(self);
799            }
800
801            dbg_cx.finalize();
802        }
803    }
804}
805
806impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
807    fn create_vtable_debuginfo(
808        &self,
809        ty: Ty<'tcx>,
810        trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
811        vtable: Self::Value,
812    ) {
813        metadata::create_vtable_di_node(self, ty, trait_ref, vtable)
814    }
815}