Improve backtrace for lowering crashes. (#5651)

Factor out the logic for mapping from a `LocId` into a diagnostic
location from check into sem_ir so it can be reused by lowering. Include
the function and instruction being lowered in the pretty stack trace.
Example stack trace:

```carbon
2.      filename: examples/sieve.carbon
3.      core/prelude/types/int.carbon:213:3: lowering function Core.Op(Core.IntLiteral as Core.ImplicitAs(i32))
            fn Op[addr self: Self*](other: Self) = "int.sadd_assign";
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4.      core/prelude/operators/arithmetic.carbon:22:27: lowering call
            fn Op[addr self: Self*](other: Other);
                                    ^~~~~~~~~~~~
```
This commit is contained in:
Richard Smith
2025-06-16 23:21:22 +00:00
committed by GitHub
parent ac56057f08
commit 519e633147
16 changed files with 276 additions and 149 deletions
+8 -10
View File
@@ -13,21 +13,20 @@
namespace Carbon::Lower {
Context::Context(llvm::LLVMContext& llvm_context,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
std::optional<llvm::ArrayRef<Parse::GetTreeAndSubtreesFn>>
tree_and_subtrees_getters_for_debug_info,
llvm::StringRef module_name, llvm::raw_ostream* vlog_stream)
Context::Context(
llvm::LLVMContext& llvm_context,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs, bool want_debug_info,
llvm::ArrayRef<Parse::GetTreeAndSubtreesFn> tree_and_subtrees_getters,
llvm::StringRef module_name, llvm::raw_ostream* vlog_stream)
: llvm_context_(&llvm_context),
llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
file_system_(std::move(fs)),
di_builder_(*llvm_module_),
di_compile_unit_(
tree_and_subtrees_getters_for_debug_info
want_debug_info
? BuildDICompileUnit(module_name, *llvm_module_, di_builder_)
: nullptr),
tree_and_subtrees_getters_for_debug_info_(
tree_and_subtrees_getters_for_debug_info),
tree_and_subtrees_getters_(tree_and_subtrees_getters),
vlog_stream_(vlog_stream) {}
auto Context::GetFileContext(const SemIR::File* file,
@@ -79,8 +78,7 @@ auto Context::BuildDICompileUnit(llvm::StringRef module_name,
auto Context::GetLocForDI(SemIR::AbsoluteNodeId abs_node_id) -> LocForDI {
const auto& tree_and_subtrees =
(*tree_and_subtrees_getters_for_debug_info_)[abs_node_id.check_ir_id()
.index]();
tree_and_subtrees_getters()[abs_node_id.check_ir_id().index]();
const auto& tokens = tree_and_subtrees.tree().tokens();
if (abs_node_id.node_id().has_value()) {