xref: /llvm-project/bolt/lib/Profile/BoltAddressTranslation.cpp (revision 8901f718ea16ceb82b6f878db53d3bcb46b4d2b2)
1 //===- bolt/Profile/BoltAddressTranslation.cpp ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "bolt/Profile/BoltAddressTranslation.h"
10 #include "bolt/Core/BinaryFunction.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/Support/Errc.h"
13 #include "llvm/Support/Error.h"
14 #include "llvm/Support/LEB128.h"
15 
16 #define DEBUG_TYPE "bolt-bat"
17 
18 namespace llvm {
19 namespace bolt {
20 
21 const char *BoltAddressTranslation::SECTION_NAME = ".note.bolt_bat";
22 
23 void BoltAddressTranslation::writeEntriesForBB(
24     MapTy &Map, const BinaryBasicBlock &BB, uint64_t FuncInputAddress,
25     uint64_t FuncOutputAddress) const {
26   const uint64_t BBOutputOffset =
27       BB.getOutputAddressRange().first - FuncOutputAddress;
28   const uint32_t BBInputOffset = BB.getInputOffset();
29 
30   // Every output BB must track back to an input BB for profile collection
31   // in bolted binaries. If we are missing an offset, it means this block was
32   // created by a pass. We will skip writing any entries for it, and this means
33   // any traffic happening in this block will map to the previous block in the
34   // layout. This covers the case where an input basic block is split into two,
35   // and the second one lacks any offset.
36   if (BBInputOffset == BinaryBasicBlock::INVALID_OFFSET)
37     return;
38 
39   LLVM_DEBUG(dbgs() << "BB " << BB.getName() << "\n");
40   LLVM_DEBUG(dbgs() << "  Key: " << Twine::utohexstr(BBOutputOffset)
41                     << " Val: " << Twine::utohexstr(BBInputOffset) << "\n");
42   // NB: in `writeEntriesForBB` we use the input address because hashes are
43   // saved early in `saveMetadata` before output addresses are assigned.
44   const BBHashMapTy &BBHashMap = getBBHashMap(FuncInputAddress);
45   (void)BBHashMap;
46   LLVM_DEBUG(
47       dbgs() << formatv(" Hash: {0:x}\n", BBHashMap.getBBHash(BBInputOffset)));
48   LLVM_DEBUG(
49       dbgs() << formatv(" Index: {0}\n", BBHashMap.getBBIndex(BBInputOffset)));
50   // In case of conflicts (same Key mapping to different Vals), the last
51   // update takes precedence. Of course it is not ideal to have conflicts and
52   // those happen when we have an empty BB that either contained only
53   // NOPs or a jump to the next block (successor). Either way, the successor
54   // and this deleted block will both share the same output address (the same
55   // key), and we need to map back. We choose here to privilege the successor by
56   // allowing it to overwrite the previously inserted key in the map.
57   Map.emplace(BBOutputOffset, BBInputOffset << 1);
58 
59   const auto &IOAddressMap =
60       BB.getFunction()->getBinaryContext().getIOAddressMap();
61 
62   for (const auto &[InputOffset, Sym] : BB.getLocSyms()) {
63     const auto InputAddress = BB.getFunction()->getAddress() + InputOffset;
64     const auto OutputAddress = IOAddressMap.lookup(InputAddress);
65     assert(OutputAddress && "Unknown instruction address");
66     const auto OutputOffset = *OutputAddress - FuncOutputAddress;
67 
68     // Is this the first instruction in the BB? No need to duplicate the entry.
69     if (OutputOffset == BBOutputOffset)
70       continue;
71 
72     LLVM_DEBUG(dbgs() << "  Key: " << Twine::utohexstr(OutputOffset) << " Val: "
73                       << Twine::utohexstr(InputOffset) << " (branch)\n");
74     Map.emplace(OutputOffset, (InputOffset << 1) | BRANCHENTRY);
75   }
76 }
77 
78 void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) {
79   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Writing BOLT Address Translation Tables\n");
80   for (auto &BFI : BC.getBinaryFunctions()) {
81     const BinaryFunction &Function = BFI.second;
82     const uint64_t InputAddress = Function.getAddress();
83     const uint64_t OutputAddress = Function.getOutputAddress();
84     // We don't need a translation table if the body of the function hasn't
85     // changed
86     if (Function.isIgnored() || (!BC.HasRelocations && !Function.isSimple()))
87       continue;
88 
89     uint32_t NumSecondaryEntryPoints = 0;
90     Function.forEachEntryPoint([&](uint64_t Offset, const MCSymbol *) {
91       if (!Offset)
92         return true;
93       ++NumSecondaryEntryPoints;
94       SecondaryEntryPointsMap[OutputAddress].push_back(Offset);
95       return true;
96     });
97 
98     LLVM_DEBUG(dbgs() << "Function name: " << Function.getPrintName() << "\n");
99     LLVM_DEBUG(dbgs() << " Address reference: 0x"
100                       << Twine::utohexstr(Function.getOutputAddress()) << "\n");
101     LLVM_DEBUG(dbgs() << formatv(" Hash: {0:x}\n", getBFHash(InputAddress)));
102     LLVM_DEBUG(dbgs() << " Secondary Entry Points: " << NumSecondaryEntryPoints
103                       << '\n');
104 
105     MapTy Map;
106     for (const BinaryBasicBlock *const BB :
107          Function.getLayout().getMainFragment())
108       writeEntriesForBB(Map, *BB, InputAddress, OutputAddress);
109     // Add entries for deleted blocks. They are still required for correct BB
110     // mapping of branches modified by SCTC. By convention, they would have the
111     // end of the function as output address.
112     const BBHashMapTy &BBHashMap = getBBHashMap(InputAddress);
113     if (BBHashMap.size() != Function.size()) {
114       const uint64_t EndOffset = Function.getOutputSize();
115       std::unordered_set<uint32_t> MappedInputOffsets;
116       for (const BinaryBasicBlock &BB : Function)
117         MappedInputOffsets.emplace(BB.getInputOffset());
118       for (const auto &[InputOffset, _] : BBHashMap)
119         if (!llvm::is_contained(MappedInputOffsets, InputOffset))
120           Map.emplace(EndOffset, InputOffset << 1);
121     }
122     Maps.emplace(Function.getOutputAddress(), std::move(Map));
123     ReverseMap.emplace(OutputAddress, InputAddress);
124 
125     if (!Function.isSplit())
126       continue;
127 
128     // Split maps
129     LLVM_DEBUG(dbgs() << " Cold part\n");
130     for (const FunctionFragment &FF :
131          Function.getLayout().getSplitFragments()) {
132       ColdPartSource.emplace(FF.getAddress(), Function.getOutputAddress());
133       Map.clear();
134       for (const BinaryBasicBlock *const BB : FF)
135         writeEntriesForBB(Map, *BB, InputAddress, FF.getAddress());
136 
137       Maps.emplace(FF.getAddress(), std::move(Map));
138     }
139   }
140 
141   // Output addresses are delta-encoded
142   uint64_t PrevAddress = 0;
143   writeMaps</*Cold=*/false>(Maps, PrevAddress, OS);
144   writeMaps</*Cold=*/true>(Maps, PrevAddress, OS);
145 
146   BC.outs() << "BOLT-INFO: Wrote " << Maps.size() << " BAT maps\n";
147   BC.outs() << "BOLT-INFO: Wrote " << FuncHashes.getNumFunctions()
148             << " function and " << FuncHashes.getNumBasicBlocks()
149             << " basic block hashes\n";
150 }
151 
152 APInt BoltAddressTranslation::calculateBranchEntriesBitMask(
153     MapTy &Map, size_t EqualElems) const {
154   APInt BitMask(alignTo(EqualElems, 8), 0);
155   size_t Index = 0;
156   for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
157     if (Index == EqualElems)
158       break;
159     const uint32_t OutputOffset = KeyVal.second;
160     if (OutputOffset & BRANCHENTRY)
161       BitMask.setBit(Index);
162     ++Index;
163   }
164   return BitMask;
165 }
166 
167 size_t BoltAddressTranslation::getNumEqualOffsets(const MapTy &Map,
168                                                   uint32_t Skew) const {
169   size_t EqualOffsets = 0;
170   for (const std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
171     const uint32_t OutputOffset = KeyVal.first;
172     const uint32_t InputOffset = KeyVal.second >> 1;
173     if (OutputOffset == InputOffset - Skew)
174       ++EqualOffsets;
175     else
176       break;
177   }
178   return EqualOffsets;
179 }
180 
181 template <bool Cold>
182 void BoltAddressTranslation::writeMaps(std::map<uint64_t, MapTy> &Maps,
183                                        uint64_t &PrevAddress, raw_ostream &OS) {
184   const uint32_t NumFuncs =
185       llvm::count_if(llvm::make_first_range(Maps), [&](const uint64_t Address) {
186         return Cold == ColdPartSource.count(Address);
187       });
188   encodeULEB128(NumFuncs, OS);
189   LLVM_DEBUG(dbgs() << "Writing " << NumFuncs << (Cold ? " cold" : "")
190                     << " functions for BAT.\n");
191   size_t PrevIndex = 0;
192   for (auto &MapEntry : Maps) {
193     const uint64_t Address = MapEntry.first;
194     // Only process cold fragments in cold mode, and vice versa.
195     if (Cold != ColdPartSource.count(Address))
196       continue;
197     // NB: in `writeMaps` we use the input address because hashes are saved
198     // early in `saveMetadata` before output addresses are assigned.
199     const uint64_t HotInputAddress =
200         ReverseMap[Cold ? ColdPartSource[Address] : Address];
201     MapTy &Map = MapEntry.second;
202     const uint32_t NumEntries = Map.size();
203     LLVM_DEBUG(dbgs() << "Writing " << NumEntries << " entries for 0x"
204                       << Twine::utohexstr(Address) << ".\n");
205     encodeULEB128(Address - PrevAddress, OS);
206     PrevAddress = Address;
207     const uint32_t NumSecondaryEntryPoints =
208         SecondaryEntryPointsMap.count(Address)
209             ? SecondaryEntryPointsMap[Address].size()
210             : 0;
211     uint32_t Skew = 0;
212     if (Cold) {
213       auto HotEntryIt = Maps.find(ColdPartSource[Address]);
214       assert(HotEntryIt != Maps.end());
215       size_t HotIndex = std::distance(Maps.begin(), HotEntryIt);
216       encodeULEB128(HotIndex - PrevIndex, OS);
217       PrevIndex = HotIndex;
218       // Skew of all input offsets for cold fragments is simply the first input
219       // offset.
220       Skew = Map.begin()->second >> 1;
221       encodeULEB128(Skew, OS);
222     } else {
223       // Function hash
224       size_t BFHash = getBFHash(HotInputAddress);
225       LLVM_DEBUG(dbgs() << "Hash: " << formatv("{0:x}\n", BFHash));
226       OS.write(reinterpret_cast<char *>(&BFHash), 8);
227       // Number of basic blocks
228       size_t NumBasicBlocks = NumBasicBlocksMap[HotInputAddress];
229       LLVM_DEBUG(dbgs() << "Basic blocks: " << NumBasicBlocks << '\n');
230       encodeULEB128(NumBasicBlocks, OS);
231       // Secondary entry points
232       encodeULEB128(NumSecondaryEntryPoints, OS);
233       LLVM_DEBUG(dbgs() << "Secondary Entry Points: " << NumSecondaryEntryPoints
234                         << '\n');
235     }
236     encodeULEB128(NumEntries, OS);
237     // Encode the number of equal offsets (output = input - skew) in the
238     // beginning of the function. Only encode one offset in these cases.
239     const size_t EqualElems = getNumEqualOffsets(Map, Skew);
240     encodeULEB128(EqualElems, OS);
241     if (EqualElems) {
242       const size_t BranchEntriesBytes = alignTo(EqualElems, 8) / 8;
243       APInt BranchEntries = calculateBranchEntriesBitMask(Map, EqualElems);
244       OS.write(reinterpret_cast<const char *>(BranchEntries.getRawData()),
245                BranchEntriesBytes);
246       LLVM_DEBUG({
247         dbgs() << "BranchEntries: ";
248         SmallString<8> BitMaskStr;
249         BranchEntries.toString(BitMaskStr, 2, false);
250         dbgs() << BitMaskStr << '\n';
251       });
252     }
253     const BBHashMapTy &BBHashMap = getBBHashMap(HotInputAddress);
254     size_t Index = 0;
255     uint64_t InOffset = 0;
256     size_t PrevBBIndex = 0;
257     // Output and Input addresses and delta-encoded
258     for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
259       const uint64_t OutputAddress = KeyVal.first + Address;
260       encodeULEB128(OutputAddress - PrevAddress, OS);
261       PrevAddress = OutputAddress;
262       if (Index++ >= EqualElems)
263         encodeSLEB128(KeyVal.second - InOffset, OS);
264       InOffset = KeyVal.second; // Keeping InOffset as if BRANCHENTRY is encoded
265       if ((InOffset & BRANCHENTRY) == 0) {
266         const bool IsBlock = BBHashMap.isInputBlock(InOffset >> 1);
267         unsigned BBIndex = IsBlock ? BBHashMap.getBBIndex(InOffset >> 1) : 0;
268         size_t BBHash = IsBlock ? BBHashMap.getBBHash(InOffset >> 1) : 0;
269         OS.write(reinterpret_cast<char *>(&BBHash), 8);
270         // Basic block index in the input binary
271         encodeULEB128(BBIndex - PrevBBIndex, OS);
272         PrevBBIndex = BBIndex;
273         LLVM_DEBUG(dbgs() << formatv("{0:x} -> {1:x} {2:x} {3}\n", KeyVal.first,
274                                      InOffset >> 1, BBHash, BBIndex));
275       }
276     }
277     uint32_t PrevOffset = 0;
278     if (!Cold && NumSecondaryEntryPoints) {
279       LLVM_DEBUG(dbgs() << "Secondary entry points: ");
280       // Secondary entry point offsets, delta-encoded
281       for (uint32_t Offset : SecondaryEntryPointsMap[Address]) {
282         encodeULEB128(Offset - PrevOffset, OS);
283         LLVM_DEBUG(dbgs() << formatv("{0:x} ", Offset));
284         PrevOffset = Offset;
285       }
286       LLVM_DEBUG(dbgs() << '\n');
287     }
288   }
289 }
290 
291 std::error_code BoltAddressTranslation::parse(raw_ostream &OS, StringRef Buf) {
292   DataExtractor DE = DataExtractor(Buf, true, 8);
293   uint64_t Offset = 0;
294   if (Buf.size() < 12)
295     return make_error_code(llvm::errc::io_error);
296 
297   const uint32_t NameSz = DE.getU32(&Offset);
298   const uint32_t DescSz = DE.getU32(&Offset);
299   const uint32_t Type = DE.getU32(&Offset);
300 
301   if (Type != BinarySection::NT_BOLT_BAT ||
302       Buf.size() + Offset < alignTo(NameSz, 4) + DescSz)
303     return make_error_code(llvm::errc::io_error);
304 
305   StringRef Name = Buf.slice(Offset, Offset + NameSz);
306   Offset = alignTo(Offset + NameSz, 4);
307   if (!Name.starts_with("BOLT"))
308     return make_error_code(llvm::errc::io_error);
309 
310   Error Err(Error::success());
311   std::vector<uint64_t> HotFuncs;
312   uint64_t PrevAddress = 0;
313   parseMaps</*Cold=*/false>(HotFuncs, PrevAddress, DE, Offset, Err);
314   parseMaps</*Cold=*/true>(HotFuncs, PrevAddress, DE, Offset, Err);
315   OS << "BOLT-INFO: Parsed " << Maps.size() << " BAT entries\n";
316   return errorToErrorCode(std::move(Err));
317 }
318 
319 template <bool Cold>
320 void BoltAddressTranslation::parseMaps(std::vector<uint64_t> &HotFuncs,
321                                        uint64_t &PrevAddress, DataExtractor &DE,
322                                        uint64_t &Offset, Error &Err) {
323   const uint32_t NumFunctions = DE.getULEB128(&Offset, &Err);
324   LLVM_DEBUG(dbgs() << "Parsing " << NumFunctions << (Cold ? " cold" : "")
325                     << " functions\n");
326   size_t HotIndex = 0;
327   for (uint32_t I = 0; I < NumFunctions; ++I) {
328     const uint64_t Address = PrevAddress + DE.getULEB128(&Offset, &Err);
329     uint64_t HotAddress = Cold ? 0 : Address;
330     PrevAddress = Address;
331     uint32_t SecondaryEntryPoints = 0;
332     uint64_t ColdInputSkew = 0;
333     if (Cold) {
334       HotIndex += DE.getULEB128(&Offset, &Err);
335       HotAddress = HotFuncs[HotIndex];
336       ColdPartSource.emplace(Address, HotAddress);
337       ColdInputSkew = DE.getULEB128(&Offset, &Err);
338     } else {
339       HotFuncs.push_back(Address);
340       // Function hash
341       const size_t FuncHash = DE.getU64(&Offset, &Err);
342       FuncHashes.addEntry(Address, FuncHash);
343       LLVM_DEBUG(dbgs() << formatv("{0:x}: hash {1:x}\n", Address, FuncHash));
344       // Number of basic blocks
345       const size_t NumBasicBlocks = DE.getULEB128(&Offset, &Err);
346       NumBasicBlocksMap.emplace(Address, NumBasicBlocks);
347       LLVM_DEBUG(dbgs() << formatv("{0:x}: #bbs {1}, {2} bytes\n", Address,
348                                    NumBasicBlocks,
349                                    getULEB128Size(NumBasicBlocks)));
350       // Secondary entry points
351       SecondaryEntryPoints = DE.getULEB128(&Offset, &Err);
352       LLVM_DEBUG(
353           dbgs() << formatv("{0:x}: secondary entry points {1}, {2} bytes\n",
354                             Address, SecondaryEntryPoints,
355                             getULEB128Size(SecondaryEntryPoints)));
356     }
357     const uint32_t NumEntries = DE.getULEB128(&Offset, &Err);
358     // Equal offsets.
359     const size_t EqualElems = DE.getULEB128(&Offset, &Err);
360     APInt BEBitMask;
361     LLVM_DEBUG(dbgs() << formatv("Equal offsets: {0}, {1} bytes\n", EqualElems,
362                                  getULEB128Size(EqualElems)));
363     if (EqualElems) {
364       const size_t BranchEntriesBytes = alignTo(EqualElems, 8) / 8;
365       BEBitMask = APInt(alignTo(EqualElems, 8), 0);
366       LoadIntFromMemory(
367           BEBitMask,
368           reinterpret_cast<const uint8_t *>(
369               DE.getBytes(&Offset, BranchEntriesBytes, &Err).data()),
370           BranchEntriesBytes);
371       LLVM_DEBUG({
372         dbgs() << "BEBitMask: ";
373         SmallString<8> BitMaskStr;
374         BEBitMask.toString(BitMaskStr, 2, false);
375         dbgs() << BitMaskStr << ", " << BranchEntriesBytes << " bytes\n";
376       });
377     }
378     MapTy Map;
379 
380     LLVM_DEBUG(dbgs() << "Parsing " << NumEntries << " entries for 0x"
381                       << Twine::utohexstr(Address) << "\n");
382     uint64_t InputOffset = 0;
383     size_t BBIndex = 0;
384     for (uint32_t J = 0; J < NumEntries; ++J) {
385       const uint64_t OutputDelta = DE.getULEB128(&Offset, &Err);
386       const uint64_t OutputAddress = PrevAddress + OutputDelta;
387       const uint64_t OutputOffset = OutputAddress - Address;
388       PrevAddress = OutputAddress;
389       int64_t InputDelta = 0;
390       if (J < EqualElems) {
391         InputOffset = ((OutputOffset + ColdInputSkew) << 1) | BEBitMask[J];
392       } else {
393         InputDelta = DE.getSLEB128(&Offset, &Err);
394         InputOffset += InputDelta;
395       }
396       Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset, InputOffset));
397       size_t BBHash = 0;
398       size_t BBIndexDelta = 0;
399       const bool IsBranchEntry = InputOffset & BRANCHENTRY;
400       if (!IsBranchEntry) {
401         BBHash = DE.getU64(&Offset, &Err);
402         BBIndexDelta = DE.getULEB128(&Offset, &Err);
403         BBIndex += BBIndexDelta;
404         // Map basic block hash to hot fragment by input offset
405         getBBHashMap(HotAddress).addEntry(InputOffset >> 1, BBIndex, BBHash);
406       }
407       LLVM_DEBUG({
408         dbgs() << formatv(
409             "{0:x} -> {1:x} ({2}/{3}b -> {4}/{5}b), {6:x}", OutputOffset,
410             InputOffset, OutputDelta, getULEB128Size(OutputDelta), InputDelta,
411             (J < EqualElems) ? 0 : getSLEB128Size(InputDelta), OutputAddress);
412         if (!IsBranchEntry) {
413           dbgs() << formatv(" {0:x} {1}/{2}b", BBHash, BBIndex,
414                             getULEB128Size(BBIndexDelta));
415         }
416         dbgs() << '\n';
417       });
418     }
419     Maps.insert(std::pair<uint64_t, MapTy>(Address, Map));
420     if (!Cold && SecondaryEntryPoints) {
421       uint32_t EntryPointOffset = 0;
422       LLVM_DEBUG(dbgs() << "Secondary entry points: ");
423       for (uint32_t EntryPointId = 0; EntryPointId != SecondaryEntryPoints;
424            ++EntryPointId) {
425         uint32_t OffsetDelta = DE.getULEB128(&Offset, &Err);
426         EntryPointOffset += OffsetDelta;
427         SecondaryEntryPointsMap[Address].push_back(EntryPointOffset);
428         LLVM_DEBUG(dbgs() << formatv("{0:x}/{1}b ", EntryPointOffset,
429                                      getULEB128Size(OffsetDelta)));
430       }
431       LLVM_DEBUG(dbgs() << '\n');
432     }
433   }
434 }
435 
436 void BoltAddressTranslation::dump(raw_ostream &OS) const {
437   const size_t NumTables = Maps.size();
438   OS << "BAT tables for " << NumTables << " functions:\n";
439   for (const auto &MapEntry : Maps) {
440     const uint64_t Address = MapEntry.first;
441     const uint64_t HotAddress = fetchParentAddress(Address);
442     const bool IsHotFunction = HotAddress == 0;
443     OS << "Function Address: 0x" << Twine::utohexstr(Address);
444     if (IsHotFunction)
445       OS << formatv(", hash: {0:x}", getBFHash(Address));
446     OS << "\n";
447     OS << "BB mappings:\n";
448     const BBHashMapTy &BBHashMap =
449         getBBHashMap(HotAddress ? HotAddress : Address);
450     for (const auto &Entry : MapEntry.second) {
451       const bool IsBranch = Entry.second & BRANCHENTRY;
452       const uint32_t Val = Entry.second >> 1; // dropping BRANCHENTRY bit
453       OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
454          << "0x" << Twine::utohexstr(Val);
455       if (IsBranch)
456         OS << " (branch)";
457       else
458         OS << formatv(" hash: {0:x}", BBHashMap.getBBHash(Val));
459       OS << "\n";
460     }
461     if (IsHotFunction) {
462       auto NumBasicBlocksIt = NumBasicBlocksMap.find(Address);
463       assert(NumBasicBlocksIt != NumBasicBlocksMap.end());
464       OS << "NumBlocks: " << NumBasicBlocksIt->second << '\n';
465     }
466     auto SecondaryEntryPointsIt = SecondaryEntryPointsMap.find(Address);
467     if (SecondaryEntryPointsIt != SecondaryEntryPointsMap.end()) {
468       const std::vector<uint32_t> &SecondaryEntryPoints =
469           SecondaryEntryPointsIt->second;
470       OS << SecondaryEntryPoints.size() << " secondary entry points:\n";
471       for (uint32_t EntryPointOffset : SecondaryEntryPoints)
472         OS << formatv("{0:x}\n", EntryPointOffset);
473     }
474     OS << "\n";
475   }
476   const size_t NumColdParts = ColdPartSource.size();
477   if (!NumColdParts)
478     return;
479 
480   OS << NumColdParts << " cold mappings:\n";
481   for (const auto &Entry : ColdPartSource) {
482     OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
483        << Twine::utohexstr(Entry.second) << "\n";
484   }
485   OS << "\n";
486 }
487 
488 uint64_t BoltAddressTranslation::translate(uint64_t FuncAddress,
489                                            uint64_t Offset,
490                                            bool IsBranchSrc) const {
491   auto Iter = Maps.find(FuncAddress);
492   if (Iter == Maps.end())
493     return Offset;
494 
495   const MapTy &Map = Iter->second;
496   auto KeyVal = Map.upper_bound(Offset);
497   if (KeyVal == Map.begin())
498     return Offset;
499 
500   --KeyVal;
501 
502   const uint32_t Val = KeyVal->second >> 1; // dropping BRANCHENTRY bit
503   // Branch source addresses are translated to the first instruction of the
504   // source BB to avoid accounting for modifications BOLT may have made in the
505   // BB regarding deletion/addition of instructions.
506   if (IsBranchSrc)
507     return Val;
508   return Offset - KeyVal->first + Val;
509 }
510 
511 std::optional<BoltAddressTranslation::FallthroughListTy>
512 BoltAddressTranslation::getFallthroughsInTrace(uint64_t FuncAddress,
513                                                uint64_t From,
514                                                uint64_t To) const {
515   SmallVector<std::pair<uint64_t, uint64_t>, 16> Res;
516 
517   // Filter out trivial case
518   if (From >= To)
519     return Res;
520 
521   From -= FuncAddress;
522   To -= FuncAddress;
523 
524   auto Iter = Maps.find(FuncAddress);
525   if (Iter == Maps.end())
526     return std::nullopt;
527 
528   const MapTy &Map = Iter->second;
529   auto FromIter = Map.upper_bound(From);
530   if (FromIter == Map.begin())
531     return Res;
532   // Skip instruction entries, to create fallthroughs we are only interested in
533   // BB boundaries
534   do {
535     if (FromIter == Map.begin())
536       return Res;
537     --FromIter;
538   } while (FromIter->second & BRANCHENTRY);
539 
540   auto ToIter = Map.upper_bound(To);
541   if (ToIter == Map.begin())
542     return Res;
543   --ToIter;
544   if (FromIter->first >= ToIter->first)
545     return Res;
546 
547   for (auto Iter = FromIter; Iter != ToIter;) {
548     const uint32_t Src = Iter->first;
549     if (Iter->second & BRANCHENTRY) {
550       ++Iter;
551       continue;
552     }
553 
554     ++Iter;
555     while (Iter->second & BRANCHENTRY && Iter != ToIter)
556       ++Iter;
557     if (Iter->second & BRANCHENTRY)
558       break;
559     Res.emplace_back(Src, Iter->first);
560   }
561 
562   return Res;
563 }
564 
565 bool BoltAddressTranslation::enabledFor(
566     llvm::object::ELFObjectFileBase *InputFile) const {
567   for (const SectionRef &Section : InputFile->sections()) {
568     Expected<StringRef> SectionNameOrErr = Section.getName();
569     if (Error E = SectionNameOrErr.takeError())
570       continue;
571 
572     if (SectionNameOrErr.get() == SECTION_NAME)
573       return true;
574   }
575   return false;
576 }
577 
578 void BoltAddressTranslation::saveMetadata(BinaryContext &BC) {
579   for (BinaryFunction &BF : llvm::make_second_range(BC.getBinaryFunctions())) {
580     // We don't need a translation table if the body of the function hasn't
581     // changed
582     if (BF.isIgnored() || (!BC.HasRelocations && !BF.isSimple()))
583       continue;
584     // Prepare function and block hashes
585     FuncHashes.addEntry(BF.getAddress(), BF.computeHash());
586     BF.computeBlockHashes();
587     BBHashMapTy &BBHashMap = getBBHashMap(BF.getAddress());
588     // Set BF/BB metadata
589     for (const BinaryBasicBlock &BB : BF)
590       BBHashMap.addEntry(BB.getInputOffset(), BB.getIndex(), BB.getHash());
591     NumBasicBlocksMap.emplace(BF.getAddress(), BF.size());
592   }
593 }
594 
595 unsigned
596 BoltAddressTranslation::getSecondaryEntryPointId(uint64_t Address,
597                                                  uint32_t Offset) const {
598   auto FunctionIt = SecondaryEntryPointsMap.find(Address);
599   if (FunctionIt == SecondaryEntryPointsMap.end())
600     return 0;
601   const std::vector<uint32_t> &Offsets = FunctionIt->second;
602   auto OffsetIt = std::find(Offsets.begin(), Offsets.end(), Offset);
603   if (OffsetIt == Offsets.end())
604     return 0;
605   // Adding one here because main entry point is not stored in BAT, and
606   // enumeration for secondary entry points starts with 1.
607   return OffsetIt - Offsets.begin() + 1;
608 }
609 
610 std::pair<const BinaryFunction *, unsigned>
611 BoltAddressTranslation::translateSymbol(const BinaryContext &BC,
612                                         const MCSymbol &Symbol,
613                                         uint32_t Offset) const {
614   // The symbol could be a secondary entry in a cold fragment.
615   uint64_t SymbolValue = cantFail(errorOrToExpected(BC.getSymbolValue(Symbol)));
616 
617   const BinaryFunction *Callee = BC.getFunctionForSymbol(&Symbol);
618   assert(Callee);
619 
620   // Containing function, not necessarily the same as symbol value.
621   const uint64_t CalleeAddress = Callee->getAddress();
622   const uint32_t OutputOffset = SymbolValue - CalleeAddress;
623 
624   const uint64_t ParentAddress = fetchParentAddress(CalleeAddress);
625   const uint64_t HotAddress = ParentAddress ? ParentAddress : CalleeAddress;
626 
627   const BinaryFunction *ParentBF = BC.getBinaryFunctionAtAddress(HotAddress);
628 
629   const uint32_t InputOffset =
630       translate(CalleeAddress, OutputOffset, /*IsBranchSrc*/ false) + Offset;
631 
632   unsigned SecondaryEntryId{0};
633   if (InputOffset)
634     SecondaryEntryId = getSecondaryEntryPointId(HotAddress, InputOffset);
635 
636   return std::pair(ParentBF, SecondaryEntryId);
637 }
638 
639 } // namespace bolt
640 } // namespace llvm
641