Skip to content

Commit ad00e7e

Browse files
authored
[BOLT] Write and parse BF/BB hashes in BAT
This increases BAT section size to: - large binary: 34832976 bytes (0.90x original), - medium binary: 3586800 bytes (0.60x original), - small binary: 816 bytes (0.57x original). Test Plan: Updated bolt/test/X86/bolt-address-translation.test Reviewers: rafaelauler, dcci, ayermolo, maksfb Reviewed By: rafaelauler Pull Request: #76907
1 parent 1918d4b commit ad00e7e

File tree

4 files changed

+95
-14
lines changed

4 files changed

+95
-14
lines changed

bolt/docs/BAT.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ Hot indices are delta encoded, implicitly starting at zero.
7979
| ------ | ------| ----------- |
8080
| `Address` | Continuous, Delta, ULEB128 | Function address in the output binary |
8181
| `HotIndex` | Delta, ULEB128 | Cold functions only: index of corresponding hot function in hot functions table |
82+
| `FuncHash` | 8b | Hot functions only: function hash for input function |
8283
| `NumEntries` | ULEB128 | Number of address translation entries for a function |
8384
| `EqualElems` | ULEB128 | Hot functions only: number of equal offsets in the beginning of a function |
8485
| `BranchEntries` | Bitmask, `alignTo(EqualElems, 8)` bits | Hot functions only: if `EqualElems` is non-zero, bitmask denoting entries with `BRANCHENTRY` bit |
@@ -94,6 +95,7 @@ entry is encoded. Input offsets implicitly start at zero.
9495
| ------ | ------| ----------- |
9596
| `OutputOffset` | Continuous, Delta, ULEB128 | Function offset in output binary |
9697
| `InputOffset` | Optional, Delta, SLEB128 | Function offset in input binary with `BRANCHENTRY` LSB bit |
98+
| `BBHash` | Optional, 8b | Basic block entries only: basic block hash in input binary |
9799

98100
`BRANCHENTRY` bit denotes whether a given offset pair is a control flow source
99101
(branch or call instruction). If not set, it signifies a control flow target

bolt/include/bolt/Profile/BoltAddressTranslation.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,13 @@ class BoltAddressTranslation {
115115
/// Save function and basic block hashes used for metadata dump.
116116
void saveMetadata(BinaryContext &BC);
117117

118+
/// Returns BB hash by function output address (after BOLT) and basic block
119+
/// input offset.
120+
size_t getBBHash(uint64_t FuncOutputAddress, uint32_t BBInputOffset) const;
121+
122+
/// Returns BF hash by function output address (after BOLT).
123+
size_t getBFHash(uint64_t OutputAddress) const;
124+
118125
private:
119126
/// Helper to update \p Map by inserting one or more BAT entries reflecting
120127
/// \p BB for function located at \p FuncAddress. At least one entry will be
@@ -150,6 +157,9 @@ class BoltAddressTranslation {
150157
/// Links outlined cold bocks to their original function
151158
std::map<uint64_t, uint64_t> ColdPartSource;
152159

160+
/// Links output address of a main fragment back to input address.
161+
std::unordered_map<uint64_t, uint64_t> ReverseMap;
162+
153163
/// Identifies the address of a control-flow changing instructions in a
154164
/// translation map entry
155165
const static uint32_t BRANCHENTRY = 0x1;

bolt/lib/Profile/BoltAddressTranslation.cpp

Lines changed: 77 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ const char *BoltAddressTranslation::SECTION_NAME = ".note.bolt_bat";
2323
void BoltAddressTranslation::writeEntriesForBB(MapTy &Map,
2424
const BinaryBasicBlock &BB,
2525
uint64_t FuncAddress) {
26+
uint64_t HotFuncAddress = ColdPartSource.count(FuncAddress)
27+
? ColdPartSource[FuncAddress]
28+
: FuncAddress;
2629
const uint64_t BBOutputOffset =
2730
BB.getOutputAddressRange().first - FuncAddress;
2831
const uint32_t BBInputOffset = BB.getInputOffset();
@@ -39,6 +42,8 @@ void BoltAddressTranslation::writeEntriesForBB(MapTy &Map,
3942
LLVM_DEBUG(dbgs() << "BB " << BB.getName() << "\n");
4043
LLVM_DEBUG(dbgs() << " Key: " << Twine::utohexstr(BBOutputOffset)
4144
<< " Val: " << Twine::utohexstr(BBInputOffset) << "\n");
45+
LLVM_DEBUG(dbgs() << formatv(" Hash: {0:x}\n",
46+
getBBHash(HotFuncAddress, BBInputOffset)));
4247
// In case of conflicts (same Key mapping to different Vals), the last
4348
// update takes precedence. Of course it is not ideal to have conflicts and
4449
// those happen when we have an empty BB that either contained only
@@ -72,20 +77,28 @@ void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) {
7277
LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Writing BOLT Address Translation Tables\n");
7378
for (auto &BFI : BC.getBinaryFunctions()) {
7479
const BinaryFunction &Function = BFI.second;
80+
const uint64_t InputAddress = Function.getAddress();
81+
const uint64_t OutputAddress = Function.getOutputAddress();
7582
// We don't need a translation table if the body of the function hasn't
7683
// changed
7784
if (Function.isIgnored() || (!BC.HasRelocations && !Function.isSimple()))
7885
continue;
7986

87+
// TBD: handle BAT functions w/multiple entry points.
88+
if (Function.isMultiEntry())
89+
continue;
90+
8091
LLVM_DEBUG(dbgs() << "Function name: " << Function.getPrintName() << "\n");
8192
LLVM_DEBUG(dbgs() << " Address reference: 0x"
8293
<< Twine::utohexstr(Function.getOutputAddress()) << "\n");
94+
LLVM_DEBUG(dbgs() << formatv(" Hash: {0:x}\n", getBFHash(OutputAddress)));
8395

8496
MapTy Map;
8597
for (const BinaryBasicBlock *const BB :
8698
Function.getLayout().getMainFragment())
8799
writeEntriesForBB(Map, *BB, Function.getOutputAddress());
88100
Maps.emplace(Function.getOutputAddress(), std::move(Map));
101+
ReverseMap.emplace(OutputAddress, InputAddress);
89102

90103
if (!Function.isSplit())
91104
continue;
@@ -94,12 +107,12 @@ void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) {
94107
LLVM_DEBUG(dbgs() << " Cold part\n");
95108
for (const FunctionFragment &FF :
96109
Function.getLayout().getSplitFragments()) {
110+
ColdPartSource.emplace(FF.getAddress(), Function.getOutputAddress());
97111
Map.clear();
98112
for (const BinaryBasicBlock *const BB : FF)
99113
writeEntriesForBB(Map, *BB, FF.getAddress());
100114

101115
Maps.emplace(FF.getAddress(), std::move(Map));
102-
ColdPartSource.emplace(FF.getAddress(), Function.getOutputAddress());
103116
}
104117
}
105118

@@ -109,6 +122,11 @@ void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) {
109122
writeMaps</*Cold=*/true>(Maps, PrevAddress, OS);
110123

111124
BC.outs() << "BOLT-INFO: Wrote " << Maps.size() << " BAT maps\n";
125+
const uint64_t NumBBHashes = std::accumulate(
126+
FuncHashes.begin(), FuncHashes.end(), 0ull,
127+
[](size_t Acc, const auto &B) { return Acc + B.second.second.size(); });
128+
BC.outs() << "BOLT-INFO: Wrote " << FuncHashes.size() << " function and "
129+
<< NumBBHashes << " basic block hashes\n";
112130
}
113131

114132
APInt BoltAddressTranslation::calculateBranchEntriesBitMask(MapTy &Map,
@@ -155,6 +173,11 @@ void BoltAddressTranslation::writeMaps(std::map<uint64_t, MapTy> &Maps,
155173
// Only process cold fragments in cold mode, and vice versa.
156174
if (Cold != ColdPartSource.count(Address))
157175
continue;
176+
// NB: here we use the input address because hashes are saved early (in
177+
// `saveMetadata`) before output addresses are assigned.
178+
const uint64_t HotInputAddress =
179+
ReverseMap[Cold ? ColdPartSource[Address] : Address];
180+
std::pair<size_t, BBHashMap> &FuncHashPair = FuncHashes[HotInputAddress];
158181
MapTy &Map = MapEntry.second;
159182
const uint32_t NumEntries = Map.size();
160183
LLVM_DEBUG(dbgs() << "Writing " << NumEntries << " entries for 0x"
@@ -166,6 +189,10 @@ void BoltAddressTranslation::writeMaps(std::map<uint64_t, MapTy> &Maps,
166189
std::distance(ColdPartSource.begin(), ColdPartSource.find(Address));
167190
encodeULEB128(HotIndex - PrevIndex, OS);
168191
PrevIndex = HotIndex;
192+
} else {
193+
// Function hash
194+
LLVM_DEBUG(dbgs() << "Hash: " << formatv("{0:x}\n", FuncHashPair.first));
195+
OS.write(reinterpret_cast<char *>(&FuncHashPair.first), 8);
169196
}
170197
encodeULEB128(NumEntries, OS);
171198
// For hot fragments only: encode the number of equal offsets
@@ -197,6 +224,13 @@ void BoltAddressTranslation::writeMaps(std::map<uint64_t, MapTy> &Maps,
197224
if (Index++ >= EqualElems)
198225
encodeSLEB128(KeyVal.second - InOffset, OS);
199226
InOffset = KeyVal.second; // Keeping InOffset as if BRANCHENTRY is encoded
227+
if ((InOffset & BRANCHENTRY) == 0) {
228+
// Basic block hash
229+
size_t BBHash = FuncHashPair.second[InOffset >> 1];
230+
OS.write(reinterpret_cast<char *>(&BBHash), 8);
231+
LLVM_DEBUG(dbgs() << formatv("{0:x} -> {1:x} {2:x}\n", KeyVal.first,
232+
InOffset >> 1, BBHash));
233+
}
200234
}
201235
}
202236
}
@@ -239,12 +273,18 @@ void BoltAddressTranslation::parseMaps(std::vector<uint64_t> &HotFuncs,
239273
size_t HotIndex = 0;
240274
for (uint32_t I = 0; I < NumFunctions; ++I) {
241275
const uint64_t Address = PrevAddress + DE.getULEB128(&Offset, &Err);
276+
uint64_t HotAddress = Cold ? 0 : Address;
242277
PrevAddress = Address;
243278
if (Cold) {
244279
HotIndex += DE.getULEB128(&Offset, &Err);
245-
ColdPartSource.emplace(Address, HotFuncs[HotIndex]);
280+
HotAddress = HotFuncs[HotIndex];
281+
ColdPartSource.emplace(Address, HotAddress);
246282
} else {
247283
HotFuncs.push_back(Address);
284+
// Function hash
285+
const size_t FuncHash = DE.getU64(&Offset, &Err);
286+
FuncHashes[Address].first = FuncHash;
287+
LLVM_DEBUG(dbgs() << formatv("{0:x}: hash {1:x}\n", Address, FuncHash));
248288
}
249289
const uint32_t NumEntries = DE.getULEB128(&Offset, &Err);
250290
// Equal offsets, hot fragments only.
@@ -288,12 +328,22 @@ void BoltAddressTranslation::parseMaps(std::vector<uint64_t> &HotFuncs,
288328
InputOffset += InputDelta;
289329
}
290330
Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset, InputOffset));
291-
LLVM_DEBUG(
292-
dbgs() << formatv("{0:x} -> {1:x} ({2}/{3}b -> {4}/{5}b), {6:x}\n",
293-
OutputOffset, InputOffset, OutputDelta,
294-
getULEB128Size(OutputDelta), InputDelta,
295-
(J < EqualElems) ? 0 : getSLEB128Size(InputDelta),
296-
OutputAddress));
331+
size_t BBHash = 0;
332+
const bool IsBranchEntry = InputOffset & BRANCHENTRY;
333+
if (!IsBranchEntry) {
334+
BBHash = DE.getU64(&Offset, &Err);
335+
// Map basic block hash to hot fragment by input offset
336+
FuncHashes[HotAddress].second.emplace(InputOffset >> 1, BBHash);
337+
}
338+
LLVM_DEBUG({
339+
dbgs() << formatv(
340+
"{0:x} -> {1:x} ({2}/{3}b -> {4}/{5}b), {6:x}", OutputOffset,
341+
InputOffset, OutputDelta, getULEB128Size(OutputDelta), InputDelta,
342+
(J < EqualElems) ? 0 : getSLEB128Size(InputDelta), OutputAddress);
343+
if (BBHash)
344+
dbgs() << formatv(" {0:x}", BBHash);
345+
dbgs() << '\n';
346+
});
297347
}
298348
Maps.insert(std::pair<uint64_t, MapTy>(Address, Map));
299349
}
@@ -303,7 +353,12 @@ void BoltAddressTranslation::dump(raw_ostream &OS) {
303353
const size_t NumTables = Maps.size();
304354
OS << "BAT tables for " << NumTables << " functions:\n";
305355
for (const auto &MapEntry : Maps) {
306-
OS << "Function Address: 0x" << Twine::utohexstr(MapEntry.first) << "\n";
356+
const uint64_t Address = MapEntry.first;
357+
const uint64_t HotAddress = fetchParentAddress(Address);
358+
OS << "Function Address: 0x" << Twine::utohexstr(Address);
359+
if (HotAddress == 0)
360+
OS << formatv(", hash: {0:x}", getBFHash(Address));
361+
OS << "\n";
307362
OS << "BB mappings:\n";
308363
for (const auto &Entry : MapEntry.second) {
309364
const bool IsBranch = Entry.second & BRANCHENTRY;
@@ -312,6 +367,9 @@ void BoltAddressTranslation::dump(raw_ostream &OS) {
312367
<< "0x" << Twine::utohexstr(Val);
313368
if (IsBranch)
314369
OS << " (branch)";
370+
else
371+
OS << formatv(" hash: {0:x}",
372+
getBBHash(HotAddress ? HotAddress : Address, Val));
315373
OS << "\n";
316374
}
317375
OS << "\n";
@@ -439,5 +497,15 @@ void BoltAddressTranslation::saveMetadata(BinaryContext &BC) {
439497
BB.getHash());
440498
}
441499
}
500+
501+
size_t BoltAddressTranslation::getBBHash(uint64_t FuncOutputAddress,
502+
uint32_t BBInputOffset) const {
503+
return FuncHashes.at(FuncOutputAddress).second.at(BBInputOffset);
504+
}
505+
506+
size_t BoltAddressTranslation::getBFHash(uint64_t OutputAddress) const {
507+
return FuncHashes.at(OutputAddress).first;
508+
}
509+
442510
} // namespace bolt
443511
} // namespace llvm

bolt/test/X86/bolt-address-translation.test

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,21 +36,22 @@
3636
#
3737
# CHECK: BOLT: 3 out of 7 functions were overwritten.
3838
# CHECK: BOLT-INFO: Wrote 6 BAT maps
39-
# CHECK: BOLT-INFO: BAT section size (bytes): 336
39+
# CHECK: BOLT-INFO: Wrote 3 function and 58 basic block hashes
40+
# CHECK: BOLT-INFO: BAT section size (bytes): 816
4041
#
4142
# usqrt mappings (hot part). We match against any key (left side containing
4243
# the bolted binary offsets) because BOLT may change where it puts instructions
4344
# depending on whether it is relaxing a branch or not. But the original input
4445
# binary offsets (right side) should be the same because these addresses are
4546
# hardcoded in the blarge.yaml file.
4647
#
47-
# CHECK-BAT-DUMP: Function Address: 0x401170
48+
# CHECK-BAT-DUMP: Function Address: 0x401170, hash: 0xace6cbc638b31983
4849
# CHECK-BAT-DUMP-NEXT: BB mappings:
49-
# CHECK-BAT-DUMP-NEXT: 0x0 -> 0x0
50+
# CHECK-BAT-DUMP-NEXT: 0x0 -> 0x0 hash: 0x36007ba1d80c0000
5051
# CHECK-BAT-DUMP-NEXT: 0x8 -> 0x8 (branch)
51-
# CHECK-BAT-DUMP-NEXT: 0x{{.*}} -> 0x39
52+
# CHECK-BAT-DUMP-NEXT: 0x{{.*}} -> 0x39 hash: 0x5c06705524800039
5253
# CHECK-BAT-DUMP-NEXT: 0x{{.*}} -> 0x3d (branch)
53-
# CHECK-BAT-DUMP-NEXT: 0x{{.*}} -> 0x10
54+
# CHECK-BAT-DUMP-NEXT: 0x{{.*}} -> 0x10 hash: 0xd70d7a64320e0010
5455
# CHECK-BAT-DUMP-NEXT: 0x{{.*}} -> 0x30 (branch)
5556
#
5657
# CHECK-BAT-DUMP: 3 cold mappings

0 commit comments

Comments
 (0)