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
+20
View File
@@ -6,6 +6,8 @@
#include "common/vlog.h"
#include "toolchain/base/kind_switch.h"
#include "toolchain/base/pretty_stack_trace_function.h"
#include "toolchain/sem_ir/diagnostic_loc_converter.h"
#include "toolchain/sem_ir/file.h"
#include "toolchain/sem_ir/generic.h"
@@ -55,7 +57,25 @@ auto FunctionContext::TryToReuseBlock(SemIR::InstBlockId block_id,
}
auto FunctionContext::LowerBlockContents(SemIR::InstBlockId block_id) -> void {
auto inst_id_for_stack_trace = SemIR::InstId::None;
// On crash, report the instruction we were lowering.
PrettyStackTraceFunction stack_trace_entry([&](llvm::raw_ostream& output) {
SemIR::DiagnosticLocConverter converter(
file_context_->context().tree_and_subtrees_getters(), &sem_ir());
auto converted = converter.Convert(SemIR::LocId(inst_id_for_stack_trace),
/*token_only=*/false);
converted.loc.FormatLocation(output);
// TODO: Format SemIR for the instruction we were lowering?
output << "Lowering "
<< sem_ir().insts().Get(inst_id_for_stack_trace).kind().ir_name()
<< "\n";
// Crash output has a tab indent; try to indent slightly past that.
converted.loc.FormatSnippet(output, /*indent=*/10);
});
for (auto inst_id : sem_ir().inst_blocks().Get(block_id)) {
inst_id_for_stack_trace = inst_id;
LowerInst(inst_id);
}
}