[BOLT] Debug info addresses inside a basic block land on the wrong instruction when an instruction before them changes size
Description
--update-debug-sections translates an address inside a basic block by its offset from the block start, clamped to the block end. When BOLT re-encodes an earlier instruction of the block shorter (dropped prefixes, shorter immediates) or removes it (NOPs), every later address lands mid-instruction or past the block. This affects low_pc/high_pc/ranges of scopes, location-list bounds and DW_AT_call_return_pc.
updated please see a comment below
Environment:
- BOLT:
llvm-boltbuilt frombd6adfedc776c07caf158e59367d9c246c933510 - Compilers:
clang++ 23.0.0git - Others: binutils 2.46 (
ld,objdump),gdb 16.3.
Reproducer
// lib.cpp
__thread int tv;
volatile int sink;
__attribute__((noinline)) int boom(int n) {
int *volatile p = nullptr;
sink = *p + n; // intentional crash
return sink;
}
static inline __attribute__((always_inline)) int scale(int x) {
return x * sink;
}
__attribute__((noinline)) int use_tls(int n) {
int t = tv + n;
int r = boom(scale(t));
return r + 1;
}
// main.cpp
int use_tls(int n);
int main(int argc, char **) { return use_tls(argc); }
clang++ -O2 -gdwarf-5 -gz=none -fPIC -shared lib.cpp -o libt.so -Wl,--emit-relocs
clang++ -O2 -g main.cpp -o main -L. -lt
mkdir -p bolt && llvm-bolt libt.so -o bolt/libt.so --update-debug-sections
BOLT drops the data16 (0x66) and rex.W (0x48) padding prefixes of the TLS general-dynamic sequence, so use_tls, a single block, shrinks by 4 bytes before scale and the call:
objdump -d --no-show-raw-insn --disassemble=_Z7use_tlsi libt.so
objdump -d --no-show-raw-insn --disassemble=_Z7use_tlsi bolt/libt.so
# libt.so # bolt/libt.so
1143: data16 lea 0x2e8d(%rip),%rdi 4000df: lea -0x3fc10e(%rip),%rdi # -1 byte
114b: data16 data16 rex.W call __tls_get_addr 4000e6: call __tls_get_addr # -3 bytes
1153: add (%rax),%ebx 4000eb: add (%rax),%ebx
1155: mov 0x2e5c(%rip),%rax # scale 4000ed: mov -0x3fc13c(%rip),%rax
115c: imul (%rax),%ebx 4000f4: imul (%rax),%ebx
115f: mov %ebx,%edi # scale end 4000f7: mov %ebx,%edi
1161: call boom 4000f9: call boom
1166: inc %eax # return 4000fe: inc %eax
Result
# libt.so
llvm-dwarfdump --name=scale --name=t --name=r -c libt.so
llvm-dwarfdump --debug-info libt.so | grep call_return_pc
# bolt/libt.so
llvm-dwarfdump --name=scale --name=t --name=r -c bolt/libt.so
llvm-dwarfdump --debug-info bolt/libt.so | grep call_return_pc
| DIE | input | bolt/libt.so |
correct |
|---|---|---|---|
scale [low_pc, high_pc) |
[0x1155, 0x115f) |
[0x4000f1, 0x4000fb): mid-movq, mid-call |
[0x4000ed, 0x4000f7) |
boom call site DW_AT_call_return_pc |
0x1166 |
0x400102: past ret |
0x4000fe |
location of t |
[0x1155, 0x115f) |
[0x4000f1, 0x4000fb) |
[0x4000ed, 0x4000f7) |
location of r |
[0x1166, 0x1168) |
[0x400102, 0x400102): empty |
[0x4000fe, 0x400100) |
llvm-dwarfdump --verify does not flag these addresses (it reports the same two .debug_str_offsets errors as for the input).
# libt.so
LD_LIBRARY_PATH=. gdb -q -batch ./main -ex run -ex 'bt 1'
LD_LIBRARY_PATH=. gdb -q -batch ./main -ex 'set breakpoint pending on' -ex 'break scale' -ex run -ex 'x/i $pc'
# bolt/libt.so
LD_LIBRARY_PATH=bolt gdb -q -batch ./main -ex run -ex 'bt 1'
LD_LIBRARY_PATH=bolt gdb -q -batch ./main -ex 'set breakpoint pending on' -ex 'break scale' -ex run -ex 'x/i $pc'
libt.so |
bolt/libt.so |
|
|---|---|---|
bt 1 |
boom (n=n@entry=0) |
boom (n=0): no call site at the return address, entry value lost |
break scale |
Breakpoint 1, scale (x=1) |
SIGSEGV in use_tls: the int3 went into the movq displacement |
The same happens on AArch64 when BOLT removes a NOP in the middle of a block: with __asm__ volatile("nop"); before the call in use_tls (built natively, or cross-compiled with --target=aarch64-linux-gnu -nostdlib -fuse-ld=lld), DW_AT_call_return_pc points one instruction past the return address. The patch fixes it too.
Cause
BOLT records exact output addresses only for basic block starts and a few control-flow instructions. Any other address is translated by its offset from the block start (BinaryFunction.cpp:4669-4682 and translateInputToOutputRange()), which breaks once an earlier instruction in the block is shrunk (x86) or removed (NOPs, any target).
Proposed fix
Keep each instruction's input offset in a new annotation. At emission, label only instructions whose offset in the block changed, add them to the address map, and use the map in translateInputToOutputRange() too.
diff --git a/bolt/include/bolt/Core/BinaryFunction.h b/bolt/include/bolt/Core/BinaryFunction.h
--- a/bolt/include/bolt/Core/BinaryFunction.h
+++ b/bolt/include/bolt/Core/BinaryFunction.h
@@ -259,6 +259,10 @@ private:
/// Size of the function in the output file.
uint64_t OutputSize{0};
+ /// Labels of instructions moved within their block, for debug info.
+ using DebugLocSymsTy = std::vector<std::pair<uint32_t, const MCSymbol *>>;
+ DebugLocSymsTy DebugLocSyms;
+
/// Maximum size this function is allowed to have.
uint64_t MaxSize{std::numeric_limits<uint64_t>::max()};
@@ -1167,6 +1171,9 @@ public:
uint64_t getOutputSize() const { return OutputSize; }
+ DebugLocSymsTy &getDebugLocSyms() { return DebugLocSyms; }
+ const DebugLocSymsTy &getDebugLocSyms() const { return DebugLocSyms; }
+
/// Does this function have a valid streaming order index?
bool hasValidIndex() const { return Index != -1U; }
diff --git a/bolt/include/bolt/Core/MCPlus.h b/bolt/include/bolt/Core/MCPlus.h
--- a/bolt/include/bolt/Core/MCPlus.h
+++ b/bolt/include/bolt/Core/MCPlus.h
@@ -77,6 +77,7 @@ public:
kRememberState, /// Inst has rememberState CFI.
kRestoreState, /// Inst has restoreState CFI.
kNegateState, /// Inst has OpNegateRAState CFI.
+ kInputOffset, /// Offset in the input function, for debug info.
kGeneric, /// First generic annotation.
};
diff --git a/bolt/include/bolt/Core/MCPlusBuilder.h b/bolt/include/bolt/Core/MCPlusBuilder.h
--- a/bolt/include/bolt/Core/MCPlusBuilder.h
+++ b/bolt/include/bolt/Core/MCPlusBuilder.h
@@ -1462,6 +1462,12 @@ public:
/// Remove offset annotation.
bool clearOffset(MCInst &Inst) const;
+ /// Return the input offset of \p Inst, kept for debug info.
+ std::optional<uint32_t> getInputOffset(const MCInst &Inst) const;
+
+ /// Set the input offset of \p Inst.
+ void setInputOffset(MCInst &Inst, uint32_t Offset) const;
+
/// Return the label of \p Inst, if available.
MCSymbol *getInstLabel(const MCInst &Inst) const;
diff --git a/bolt/lib/Core/AddressMap.cpp b/bolt/lib/Core/AddressMap.cpp
--- a/bolt/lib/Core/AddressMap.cpp
+++ b/bolt/lib/Core/AddressMap.cpp
@@ -59,6 +59,17 @@ void AddressMap::emit(MCStreamer &Streamer, BinaryContext &BC) {
emitAddress(Streamer, BFAddress + Offset, Symbol);
}
}
+
+ // Emitted last, as parse() keeps the first entry per address.
+ Streamer.switchSection(BC.getDataSection(AddressSectionName));
+ for (auto &[BFAddress, BF] : BC.getBinaryFunctions()) {
+ if (!BF.requiresAddressMap())
+ continue;
+
+ for (auto [Offset, Symbol] : BF.getDebugLocSyms())
+ emitAddress(Streamer, BFAddress + Offset, Symbol);
+ BF.getDebugLocSyms().clear();
+ }
}
std::optional<AddressMap> AddressMap::parse(BinaryContext &BC) {
diff --git a/bolt/lib/Core/BinaryEmitter.cpp b/bolt/lib/Core/BinaryEmitter.cpp
--- a/bolt/lib/Core/BinaryEmitter.cpp
+++ b/bolt/lib/Core/BinaryEmitter.cpp
@@ -458,6 +458,8 @@ void BinaryEmitter::emitFunctionBody(BinaryFunction &BF, FunctionFragment &FF,
}
SMLoc LastLocSeen;
+ // Offset in the emitted block.
+ uint64_t OutputOffset = 0;
for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
MCInst &Instr = *I;
@@ -489,6 +491,18 @@ void BinaryEmitter::emitFunctionBody(BinaryFunction &BF, FunctionFragment &FF,
BB->getLocSyms().emplace_back(Offset, InstrLabel);
}
+ // Label instructions moved within their block, for debug info.
+ if (opts::UpdateDebugSections) {
+ std::optional<uint32_t> Offset = BC.MIB->getInputOffset(Instr);
+ if (Offset && (*Offset != BB->getInputOffset() + OutputOffset ||
+ OutputOffset >= BB->getOriginalSize())) {
+ if (!InstrLabel)
+ InstrLabel = BC.Ctx->createTempSymbol();
+ BF.getDebugLocSyms().emplace_back(*Offset, InstrLabel);
+ }
+ OutputOffset += BC.computeInstructionSize(Instr);
+ }
+
if (InstrLabel)
Streamer.emitLabel(InstrLabel);
}
diff --git a/bolt/lib/Core/BinaryFunction.cpp b/bolt/lib/Core/BinaryFunction.cpp
--- a/bolt/lib/Core/BinaryFunction.cpp
+++ b/bolt/lib/Core/BinaryFunction.cpp
@@ -1554,6 +1554,10 @@ add_instruction:
if (BC.keepOffsetForInstruction(Instruction))
MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
+ // Debug info may point at any instruction.
+ if (opts::UpdateDebugSections && !getDWARFUnits().empty())
+ MIB->setInputOffset(Instruction, static_cast<uint32_t>(Offset));
+
if (BC.isX86() && BC.MIB->isNoop(Instruction)) {
// NOTE: disassembly loses the correct size information for noops on x86.
// E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
@@ -4735,8 +4739,14 @@ BinaryFunction::translateInputToOutputRange(DebugAddressRange InRange) const {
// to /p Offset. The output address should fall within the same basic
// block boundaries.
auto translateBlockOffset = [&](const uint64_t Offset) {
- const uint64_t OutAddress = BB.getOutputAddressRange().first + Offset;
- return std::min(OutAddress, BB.getOutputAddressRange().second);
+ const auto [OutStart, OutEnd] = BB.getOutputAddressRange();
+ if (BC.hasIOAddressMap()) {
+ if (std::optional<uint64_t> OutAddress = BC.getIOAddressMap().lookup(
+ getAddress() + BB.getOffset() + Offset))
+ if (*OutAddress >= OutStart && *OutAddress <= OutEnd)
+ return *OutAddress;
+ }
+ return std::min(OutStart + Offset, OutEnd);
};
uint64_t OutLowPC = BB.getOutputAddressRange().first;
diff --git a/bolt/lib/Core/MCPlusBuilder.cpp b/bolt/lib/Core/MCPlusBuilder.cpp
--- a/bolt/lib/Core/MCPlusBuilder.cpp
+++ b/bolt/lib/Core/MCPlusBuilder.cpp
@@ -336,6 +336,19 @@ bool MCPlusBuilder::clearOffset(MCInst &Inst) const {
return true;
}
+std::optional<uint32_t>
+MCPlusBuilder::getInputOffset(const MCInst &Inst) const {
+ std::optional<int64_t> Value =
+ getAnnotationOpValue(Inst, MCAnnotation::kInputOffset);
+ if (!Value)
+ return std::nullopt;
+ return static_cast<uint32_t>(*Value);
+}
+
+void MCPlusBuilder::setInputOffset(MCInst &Inst, uint32_t Offset) const {
+ setAnnotationOpValue(Inst, MCAnnotation::kInputOffset, Offset);
+}
+
MCSymbol *MCPlusBuilder::getInstLabel(const MCInst &Inst) const {
if (std::optional<int64_t> Label =
getAnnotationOpValue(Inst, MCAnnotation::kLabel))
[!NOTE] Not covered: an address of a deleted or replaced instruction itself, when an earlier instruction in the same block also changed size. It keeps the block-offset translation.
Tested: with the patch, all four DIEs get the "correct" values and gdb shows boom (n=n@entry=0) and hits the breakpoint. .text is byte-identical to unpatched, and ninja check-bolt passes (645/0, as before).
@llvm/issue-subscribers-bolt
Author: Sebastian (not4juu)
--update-debug-sections translates an address inside a basic block by its offset from the block start, clamped to the block end. When BOLT re-encodes an earlier instruction of the block shorter (dropped prefixes, shorter immediates) or removes it (NOPs), every later address lands mid-instruction or past the block. This affects low_pc/high_pc/ranges of scopes, location-list bounds and DW_AT_call_return_pc.
Environment:
- BOLT:
llvm-boltbuilt frombd6adfedc776c07caf158e59367d9c246c933510 - Compilers:
clang++ 23.0.0git - Others: binutils 2.46 (
ld,objdump),gdb 16.3.
Reproducer
// lib.cpp
__thread int tv;
volatile int sink;
__attribute__((noinline)) int boom(int n) {
int *volatile p = nullptr;
sink = *p + n; // intentional crash
return sink;
}
static inline __attribute__((always_inline)) int scale(int x) {
return x * sink;
}
__attribute__((noinline)) int use_tls(int n) {
int t = tv + n;
int r = boom(scale(t));
return r + 1;
}
// main.cpp
int use_tls(int n);
int main(int argc, char **) { return use_tls(argc); }
clang++ -O2 -gdwarf-5 -gz=none -fPIC -shared lib.cpp -o libt.so -Wl,--emit-relocs
clang++ -O2 -g main.cpp -o main -L. -lt
mkdir -p bolt && llvm-bolt libt.so -o bolt/libt.so --update-debug-sections
BOLT drops the data16 (0x66) and rex.W (0x48) padding prefixes of the TLS general-dynamic sequence, so use_tls, a single block, shrinks by 4 bytes before scale and the call:
objdump -d --no-show-raw-insn --disassemble=_Z7use_tlsi libt.so
objdump -d --no-show-raw-insn --disassemble=_Z7use_tlsi bolt/libt.so
# libt.so # bolt/libt.so
1143: data16 lea 0x2e8d(%rip),%rdi 4000df: lea -0x3fc10e(%rip),%rdi # -1 byte
114b: data16 data16 rex.W call __tls_get_addr 4000e6: call __tls_get_addr # -3 bytes
1153: add (%rax),%ebx 4000eb: add (%rax),%ebx
1155: mov 0x2e5c(%rip),%rax # scale 4000ed: mov -0x3fc13c(%rip),%rax
115c: imul (%rax),%ebx 4000f4: imul (%rax),%ebx
115f: mov %ebx,%edi # scale end 4000f7: mov %ebx,%edi
1161: call boom 4000f9: call boom
1166: inc %eax # return 4000fe: inc %eax
Result
# libt.so
llvm-dwarfdump --name=scale --name=t --name=r -c libt.so
llvm-dwarfdump --debug-info libt.so | grep call_return_pc
# bolt/libt.so
llvm-dwarfdump --name=scale --name=t --name=r -c bolt/libt.so
llvm-dwarfdump --debug-info bolt/libt.so | grep call_return_pc
| DIE | input | bolt/libt.so |
correct |
|---|---|---|---|
scale [low_pc, high_pc) |
[0x1155, 0x115f) |
[0x4000f1, 0x4000fb): mid-movq, mid-call |
[0x4000ed, 0x4000f7) |
boom call site DW_AT_call_return_pc |
0x1166 |
0x400102: past ret |
0x4000fe |
location of t |
[0x1155, 0x115f) |
[0x4000f1, 0x4000fb) |
[0x4000ed, 0x4000f7) |
location of r |
[0x1166, 0x1168) |
[0x400102, 0x400102): empty |
[0x4000fe, 0x400100) |
llvm-dwarfdump --verify does not flag these addresses (it reports the same two .debug_str_offsets errors as for the input).
# libt.so
LD_LIBRARY_PATH=. gdb -q -batch ./main -ex run -ex 'bt 1'
LD_LIBRARY_PATH=. gdb -q -batch ./main -ex 'set breakpoint pending on' -ex 'break scale' -ex run -ex 'x/i $pc'
# bolt/libt.so
LD_LIBRARY_PATH=bolt gdb -q -batch ./main -ex run -ex 'bt 1'
LD_LIBRARY_PATH=bolt gdb -q -batch ./main -ex 'set breakpoint pending on' -ex 'break scale' -ex run -ex 'x/i $pc'
libt.so |
bolt/libt.so |
|
|---|---|---|
bt 1 |
boom (n=n@<!-- -->entry=0) |
boom (n=0): no call site at the return address, entry value lost |
break scale |
Breakpoint 1, scale (x=1) |
SIGSEGV in use_tls: the int3 went into the movq displacement |
The same happens on AArch64 when BOLT removes a NOP in the middle of a block: with __asm__ volatile("nop"); before the call in use_tls (built natively, or cross-compiled with --target=aarch64-linux-gnu -nostdlib -fuse-ld=lld), DW_AT_call_return_pc points one instruction past the return address. The patch fixes it too.
Cause
BOLT records exact output addresses only for basic block starts and a few control-flow instructions. Any other address is translated by its offset from the block start (BinaryFunction.cpp:4669-4682 and translateInputToOutputRange()), which breaks once an earlier instruction in the block is shrunk (x86) or removed (NOPs, any target).
Proposed fix
Keep each instruction's input offset in a new annotation. At emission, label only instructions whose offset in the block changed, add them to the address map, and use the map in translateInputToOutputRange() too.
diff --git a/bolt/include/bolt/Core/BinaryFunction.h b/bolt/include/bolt/Core/BinaryFunction.h
--- a/bolt/include/bolt/Core/BinaryFunction.h
+++ b/bolt/include/bolt/Core/BinaryFunction.h
@@ -259,6 +259,10 @@ private:
/// Size of the function in the output file.
uint64_t OutputSize{0};
+ /// Labels of instructions moved within their block, for debug info.
+ using DebugLocSymsTy = std::vector<std::pair<uint32_t, const MCSymbol *>>;
+ DebugLocSymsTy DebugLocSyms;
+
/// Maximum size this function is allowed to have.
uint64_t MaxSize{std::numeric_limits<uint64_t>::max()};
@@ -1167,6 +1171,9 @@ public:
uint64_t getOutputSize() const { return OutputSize; }
+ DebugLocSymsTy &getDebugLocSyms() { return DebugLocSyms; }
+ const DebugLocSymsTy &getDebugLocSyms() const { return DebugLocSyms; }
+
/// Does this function have a valid streaming order index?
bool hasValidIndex() const { return Index != -1U; }
diff --git a/bolt/include/bolt/Core/MCPlus.h b/bolt/include/bolt/Core/MCPlus.h
--- a/bolt/include/bolt/Core/MCPlus.h
+++ b/bolt/include/bolt/Core/MCPlus.h
@@ -77,6 +77,7 @@ public:
kRememberState, /// Inst has rememberState CFI.
kRestoreState, /// Inst has restoreState CFI.
kNegateState, /// Inst has OpNegateRAState CFI.
+ kInputOffset, /// Offset in the input function, for debug info.
kGeneric, /// First generic annotation.
};
diff --git a/bolt/include/bolt/Core/MCPlusBuilder.h b/bolt/include/bolt/Core/MCPlusBuilder.h
--- a/bolt/include/bolt/Core/MCPlusBuilder.h
+++ b/bolt/include/bolt/Core/MCPlusBuilder.h
@@ -1462,6 +1462,12 @@ public:
/// Remove offset annotation.
bool clearOffset(MCInst &Inst) const;
+ /// Return the input offset of \p Inst, kept for debug info.
+ std::optional<uint32_t> getInputOffset(const MCInst &Inst) const;
+
+ /// Set the input offset of \p Inst.
+ void setInputOffset(MCInst &Inst, uint32_t Offset) const;
+
/// Return the label of \p Inst, if available.
MCSymbol *getInstLabel(const MCInst &Inst) const;
diff --git a/bolt/lib/Core/AddressMap.cpp b/bolt/lib/Core/AddressMap.cpp
--- a/bolt/lib/Core/AddressMap.cpp
+++ b/bolt/lib/Core/AddressMap.cpp
@@ -59,6 +59,17 @@ void AddressMap::emit(MCStreamer &Streamer, BinaryContext &BC) {
emitAddress(Streamer, BFAddress + Offset, Symbol);
}
}
+
+ // Emitted last, as parse() keeps the first entry per address.
+ Streamer.switchSection(BC.getDataSection(AddressSectionName));
+ for (auto &[BFAddress, BF] : BC.getBinaryFunctions()) {
+ if (!BF.requiresAddressMap())
+ continue;
+
+ for (auto [Offset, Symbol] : BF.getDebugLocSyms())
+ emitAddress(Streamer, BFAddress + Offset, Symbol);
+ BF.getDebugLocSyms().clear();
+ }
}
std::optional<AddressMap> AddressMap::parse(BinaryContext &BC) {
diff --git a/bolt/lib/Core/BinaryEmitter.cpp b/bolt/lib/Core/BinaryEmitter.cpp
--- a/bolt/lib/Core/BinaryEmitter.cpp
+++ b/bolt/lib/Core/BinaryEmitter.cpp
@@ -458,6 +458,8 @@ void BinaryEmitter::emitFunctionBody(BinaryFunction &BF, FunctionFragment &FF,
}
SMLoc LastLocSeen;
+ // Offset in the emitted block.
+ uint64_t OutputOffset = 0;
for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
MCInst &Instr = *I;
@@ -489,6 +491,18 @@ void BinaryEmitter::emitFunctionBody(BinaryFunction &BF, FunctionFragment &FF,
BB->getLocSyms().emplace_back(Offset, InstrLabel);
}
+ // Label instructions moved within their block, for debug info.
+ if (opts::UpdateDebugSections) {
+ std::optional<uint32_t> Offset = BC.MIB->getInputOffset(Instr);
+ if (Offset && (*Offset != BB->getInputOffset() + OutputOffset ||
+ OutputOffset >= BB->getOriginalSize())) {
+ if (!InstrLabel)
+ InstrLabel = BC.Ctx->createTempSymbol();
+ BF.getDebugLocSyms().emplace_back(*Offset, InstrLabel);
+ }
+ OutputOffset += BC.computeInstructionSize(Instr);
+ }
+
if (InstrLabel)
Streamer.emitLabel(InstrLabel);
}
diff --git a/bolt/lib/Core/BinaryFunction.cpp b/bolt/lib/Core/BinaryFunction.cpp
--- a/bolt/lib/Core/BinaryFunction.cpp
+++ b/bolt/lib/Core/BinaryFunction.cpp
@@ -1554,6 +1554,10 @@ add_instruction:
if (BC.keepOffsetForInstruction(Instruction))
MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
+ // Debug info may point at any instruction.
+ if (opts::UpdateDebugSections && !getDWARFUnits().empty())
+ MIB->setInputOffset(Instruction, static_cast<uint32_t>(Offset));
+
if (BC.isX86() && BC.MIB->isNoop(Instruction)) {
// NOTE: disassembly loses the correct size information for noops on x86.
// E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
@@ -4735,8 +4739,14 @@ BinaryFunction::translateInputToOutputRange(DebugAddressRange InRange) const {
// to /p Offset. The output address should fall within the same basic
// block boundaries.
auto translateBlockOffset = [&](const uint64_t Offset) {
- const uint64_t OutAddress = BB.getOutputAddressRange().first + Offset;
- return std::min(OutAddress, BB.getOutputAddressRange().second);
+ const auto [OutStart, OutEnd] = BB.getOutputAddressRange();
+ if (BC.hasIOAddressMap()) {
+ if (std::optional<uint64_t> OutAddress = BC.getIOAddressMap().lookup(
+ getAddress() + BB.getOffset() + Offset))
+ if (*OutAddress >= OutStart && *OutAddress <= OutEnd)
+ return *OutAddress;
+ }
+ return std::min(OutStart + Offset, OutEnd);
};
uint64_t OutLowPC = BB.getOutputAddressRange().first;
diff --git a/bolt/lib/Core/MCPlusBuilder.cpp b/bolt/lib/Core/MCPlusBuilder.cpp
--- a/bolt/lib/Core/MCPlusBuilder.cpp
+++ b/bolt/lib/Core/MCPlusBuilder.cpp
@@ -336,6 +336,19 @@ bool MCPlusBuilder::clearOffset(MCInst &Inst) const {
return true;
}
+std::optional<uint32_t>
+MCPlusBuilder::getInputOffset(const MCInst &Inst) const {
+ std::optional<int64_t> Value =
+ getAnnotationOpValue(Inst, MCAnnotation::kInputOffset);
+ if (!Value)
+ return std::nullopt;
+ return static_cast<uint32_t>(*Value);
+}
+
+void MCPlusBuilder::setInputOffset(MCInst &Inst, uint32_t Offset) const {
+ setAnnotationOpValue(Inst, MCAnnotation::kInputOffset, Offset);
+}
+
MCSymbol *MCPlusBuilder::getInstLabel(const MCInst &Inst) const {
if (std::optional<int64_t> Label =
getAnnotationOpValue(Inst, MCAnnotation::kLabel))
> [!NOTE] > Not covered: an address of a deleted or replaced instruction itself, when an earlier instruction in the same block also changed size. It keeps the block-offset translation.
Tested: with the patch, all four DIEs get the "correct" values and gdb shows boom (n=n@<!-- -->entry=0) and hits the breakpoint. .text is byte-identical to unpatched, and ninja check-bolt passes (645/0, as before).
Important - addresses at a re-emitted branch and inside an instruction
The patch above translates an address inside a block exactly only when an input instruction starts there. Two cases still fall back to the block offset:
- The address of a branch BOLT re-emits. The block-ending
jmpis a new instruction without the input offset, so aDW_AT_call_return_pcor a location-list end equal to its address lands past thejmp. - An address inside an instruction. Any debug address that is not an instruction start, for example a location ending on the last byte of a call, lands past the instruction after an earlier instruction of the block shrank, or when the instruction itself shrank (
call __tls_get_addr, 8 → 5 bytes).
Case 1: re-emitted branch
// lib.cpp
#include <cstdio>
__thread int tv;
volatile int sink;
char buf[32];
__attribute__((noinline)) long step(long v, int k) { return v * k + sink; }
// The return PC of snprintf is the jump back.
__attribute__((noinline)) int report(int x) {
if (__builtin_expect(x < 0, 0))
snprintf(buf, sizeof buf, "%d", tv);
return step(sink, 7) + 1;
}
clang++ 23.0.0git, GNU ld 2.46
clang++ -O2 -gdwarf-5 -gz=none -fPIC -shared lib.cpp -o libt.so -Wl,--emit-relocs
mkdir -p bolt && llvm-bolt libt.so -o bolt/libt.so --update-debug-sections
llvm-dwarfdump --debug-info libt.so | grep -A1 snprintf | grep call_return_pc
llvm-dwarfdump --debug-info bolt/libt.so | grep -A1 snprintf | grep call_return_pc
objdump -d --no-show-raw-insn --disassemble=_Z6reporti libt.so
objdump -d --no-show-raw-insn --disassemble=_Z6reporti bolt/libt.so
# libt.so # bolt/libt.so
116d: data16 lea 0x2e63(%rip),%rdi 4000f3: lea -0x3fc122(%rip),%rdi # -1 byte
1175: data16 data16 rex.W call __tls_get_addr 4000fa: call __tls_get_addr # -3 bytes
... ...
1194: call snprintf 400116: call snprintf
1199: jmp report+0x5 40011b: jmp report+0x5
40011d: nop (padding)
| DIE | input | with the patch above / baseline | correct |
|---|---|---|---|
snprintf call site DW_AT_call_return_pc |
0x1199 |
0x40011d: past the jmp |
0x40011b |
The call to snprintf is left without a call site at its real return address, so debuggers cannot find it when resolving entry values or tail-call frames.
Case 2: address inside an instruction
Clang ends locations on instruction starts and does not show this, but a BOLT lit test can cover it with assembly whose location ends on the last byte of a call. GCC (g++ 14.2.0) emits such locations:
// lib.cpp
__thread int tv;
volatile int sink;
__attribute__((noinline)) long step(long v, int k) { return v * k + sink; }
__attribute__((noinline)) long chain(int n) {
long off = tv + n;
off = step(off, 3);
off = step(off, 5);
return off + 1;
}
g++ -O2 -gdwarf-5 -gz=none -fPIC -shared lib.cpp -o libt.so -Wl,--emit-relocs
mkdir -p bolt && llvm-bolt libt.so -o bolt/libt.so --update-debug-sections
llvm-dwarfdump --name=off -c libt.so
llvm-dwarfdump --name=off -c bolt/libt.so
objdump -d --no-show-raw-insn --disassemble=_Z5chaini libt.so
objdump -d --no-show-raw-insn --disassemble=_Z5chaini bolt/libt.so
off entry |
input | with the patch above | correct |
|---|---|---|---|
| 1st | [0x1143, 0x1152): last byte of call __tls_get_addr |
[0x4000d9, 0x4000e8): mid-mov |
[0x4000d9, 0x4000e4) |
| 2nd | [0x115d, 0x1161): last byte of call step |
[0x4000ef, 0x4000f7): mid-mov |
[0x4000ef, 0x4000f3) |
3rd and 4th (RAX) |
[0x116a, 0x116e), [0x116f, 0x1174) |
[0x4000fc, 0x400106): merged |
[0x4000fc, 0x400100), [0x400101, 0x400106) |
NOTE On the baseline the entries are also 4 bytes off at their starts, for example the 2nd is
[0x4000f3, 0x4000f7).
Proposed fix
Keep DebugLocSyms sorted instead of clearing them, and give an address the shift of the closest labeled instruction at or before it; an address inside an instruction that shrank stays on its last byte.
[!IMPORTANT] This diff applies on top of the patch above, not instead of it.
diff --git a/bolt/include/bolt/Core/BinaryFunction.h b/bolt/include/bolt/Core/BinaryFunction.h
--- a/bolt/include/bolt/Core/BinaryFunction.h
+++ b/bolt/include/bolt/Core/BinaryFunction.h
@@ -2598,6 +2598,10 @@
/// removed.
uint64_t translateInputToOutputAddress(uint64_t Address) const;
+ /// Translate input \p Offset in the function, within the block \p BB.
+ uint64_t translateOffsetInBlock(const BinaryBasicBlock &BB,
+ uint64_t Offset) const;
+
/// Translate a contiguous range of addresses in the input binary into a set
/// of ranges in the output binary.
DebugAddressRangesVector
diff --git a/bolt/lib/Core/AddressMap.cpp b/bolt/lib/Core/AddressMap.cpp
--- a/bolt/lib/Core/AddressMap.cpp
+++ b/bolt/lib/Core/AddressMap.cpp
@@ -68,7 +68,7 @@
for (auto [Offset, Symbol] : BF.getDebugLocSyms())
emitAddress(Streamer, BFAddress + Offset, Symbol);
- BF.getDebugLocSyms().clear();
+ llvm::sort(BF.getDebugLocSyms());
}
}
diff --git a/bolt/lib/Core/BinaryFunction.cpp b/bolt/lib/Core/BinaryFunction.cpp
--- a/bolt/lib/Core/BinaryFunction.cpp
+++ b/bolt/lib/Core/BinaryFunction.cpp
@@ -4682,8 +4682,37 @@
return 0;
}
- return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
- BB->getOutputAddressRange().second);
+ return translateOffsetInBlock(*BB, Offset);
+}
+
+uint64_t BinaryFunction::translateOffsetInBlock(const BinaryBasicBlock &BB,
+ uint64_t Offset) const {
+ const auto [OutStart, OutEnd] = BB.getOutputAddressRange();
+ auto translate = [&](uint32_t InputOffset) -> std::optional<uint64_t> {
+ std::optional<uint64_t> OutAddress;
+ if (InputOffset >= BB.getOffset() && InputOffset < BB.getEndOffset() &&
+ BC.hasIOAddressMap())
+ OutAddress = BC.getIOAddressMap().lookup(getAddress() + InputOffset);
+ if (OutAddress && *OutAddress >= OutStart && *OutAddress <= OutEnd)
+ return OutAddress;
+ return std::nullopt;
+ };
+
+ // Keep the shift of the closest moved instruction at or before Offset, up to
+ // the next moved one.
+ uint64_t Start = BB.getOffset(), OutAddress = OutStart, End = OutEnd;
+ auto It = llvm::partition_point(
+ DebugLocSyms, [&](const auto &Sym) { return Sym.first <= Offset; });
+ if (It != DebugLocSyms.end())
+ End = translate(It->first).value_or(OutEnd);
+ if (It != DebugLocSyms.begin())
+ if (std::optional<uint64_t> Prev = translate(std::prev(It)->first)) {
+ Start = std::prev(It)->first;
+ OutAddress = *Prev;
+ }
+ // An address inside an instruction that shrank stays inside it.
+ OutAddress += Offset - Start;
+ return OutAddress > End ? std::max(End, OutStart + 1) - 1 : OutAddress;
}
DebugAddressRangesVector
@@ -4739,14 +4768,7 @@
// to /p Offset. The output address should fall within the same basic
// block boundaries.
auto translateBlockOffset = [&](const uint64_t Offset) {
- const auto [OutStart, OutEnd] = BB.getOutputAddressRange();
- if (BC.hasIOAddressMap()) {
- if (std::optional<uint64_t> OutAddress = BC.getIOAddressMap().lookup(
- getAddress() + BB.getOffset() + Offset))
- if (*OutAddress >= OutStart && *OutAddress <= OutEnd)
- return *OutAddress;
- }
- return std::min(OutStart + Offset, OutEnd);
+ return translateOffsetInBlock(BB, BB.getOffset() + Offset);
};
uint64_t OutLowPC = BB.getOutputAddressRange().first;
Tested: with both patches, all cases above get the correct values, and check-bolt, check-large-bolt and check-large-bolt-arm show no new failures.