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
+9 -2
View File
@@ -8,14 +8,21 @@
namespace Carbon::SemIR {
// Notes an import on the diagnostic. For `Cpp` imports, returns true. Otherwise
// updates cursors to point at the imported IR and returns false.
// Follows an imported instruction location to find the sequence of import
// locations and the ultimately imported location.
static auto FollowImportRef(
llvm::SmallVector<AbsoluteNodeId>& absolute_node_ids,
const File*& cursor_ir, InstId& cursor_inst_id,
ImportIRInstId import_ir_inst_id) -> bool {
auto import_ir_inst = cursor_ir->import_ir_insts().Get(import_ir_inst_id);
if (import_ir_inst.ir_id() == ImportIRId::Cpp) {
CARBON_CHECK(cursor_ir->import_cpps().size() > 0);
// TODO: Decompose the Clang source location to determine which C++ import
// made this location available, and use the location of that import instead
// of arbitrarily using the first C++ import.
absolute_node_ids.push_back(
AbsoluteNodeId(cursor_ir->check_ir_id(),
cursor_ir->import_cpps().values().begin()->node_id));
absolute_node_ids.push_back(
AbsoluteNodeId(import_ir_inst.clang_source_loc_id()));
return true;