xref: /llvm-project/bolt/lib/Core/BinaryContext.cpp (revision 1e4ee588fbb5047a82dd33c4357fcfdebaf38bab)
1 //===- bolt/Core/BinaryContext.cpp - Low-level context --------------------===//
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 // This file implements the BinaryContext class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Core/BinaryContext.h"
14 #include "bolt/Core/BinaryEmitter.h"
15 #include "bolt/Core/BinaryFunction.h"
16 #include "bolt/Utils/CommandLineOpts.h"
17 #include "bolt/Utils/NameResolver.h"
18 #include "bolt/Utils/Utils.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
24 #include "llvm/MC/MCAsmLayout.h"
25 #include "llvm/MC/MCAssembler.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCObjectStreamer.h"
30 #include "llvm/MC/MCObjectWriter.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSectionELF.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSubtargetInfo.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Error.h"
38 #include "llvm/Support/Regex.h"
39 #include <algorithm>
40 #include <functional>
41 #include <iterator>
42 #include <numeric>
43 #include <unordered_set>
44 
45 using namespace llvm;
46 
47 #undef  DEBUG_TYPE
48 #define DEBUG_TYPE "bolt"
49 
50 namespace opts {
51 
52 cl::opt<bool> NoHugePages("no-huge-pages",
53                           cl::desc("use regular size pages for code alignment"),
54                           cl::Hidden, cl::cat(BoltCategory));
55 
56 static cl::opt<bool>
57 PrintDebugInfo("print-debug-info",
58   cl::desc("print debug info when printing functions"),
59   cl::Hidden,
60   cl::ZeroOrMore,
61   cl::cat(BoltCategory));
62 
63 cl::opt<bool> PrintRelocations(
64     "print-relocations",
65     cl::desc("print relocations when printing functions/objects"), cl::Hidden,
66     cl::cat(BoltCategory));
67 
68 static cl::opt<bool>
69 PrintMemData("print-mem-data",
70   cl::desc("print memory data annotations when printing functions"),
71   cl::Hidden,
72   cl::ZeroOrMore,
73   cl::cat(BoltCategory));
74 
75 } // namespace opts
76 
77 namespace llvm {
78 namespace bolt {
79 
80 BinaryContext::BinaryContext(std::unique_ptr<MCContext> Ctx,
81                              std::unique_ptr<DWARFContext> DwCtx,
82                              std::unique_ptr<Triple> TheTriple,
83                              const Target *TheTarget, std::string TripleName,
84                              std::unique_ptr<MCCodeEmitter> MCE,
85                              std::unique_ptr<MCObjectFileInfo> MOFI,
86                              std::unique_ptr<const MCAsmInfo> AsmInfo,
87                              std::unique_ptr<const MCInstrInfo> MII,
88                              std::unique_ptr<const MCSubtargetInfo> STI,
89                              std::unique_ptr<MCInstPrinter> InstPrinter,
90                              std::unique_ptr<const MCInstrAnalysis> MIA,
91                              std::unique_ptr<MCPlusBuilder> MIB,
92                              std::unique_ptr<const MCRegisterInfo> MRI,
93                              std::unique_ptr<MCDisassembler> DisAsm)
94     : Ctx(std::move(Ctx)), DwCtx(std::move(DwCtx)),
95       TheTriple(std::move(TheTriple)), TheTarget(TheTarget),
96       TripleName(TripleName), MCE(std::move(MCE)), MOFI(std::move(MOFI)),
97       AsmInfo(std::move(AsmInfo)), MII(std::move(MII)), STI(std::move(STI)),
98       InstPrinter(std::move(InstPrinter)), MIA(std::move(MIA)),
99       MIB(std::move(MIB)), MRI(std::move(MRI)), DisAsm(std::move(DisAsm)) {
100   Relocation::Arch = this->TheTriple->getArch();
101   RegularPageSize = isAArch64() ? RegularPageSizeAArch64 : RegularPageSizeX86;
102   PageAlign = opts::NoHugePages ? RegularPageSize : HugePageSize;
103 }
104 
105 BinaryContext::~BinaryContext() {
106   for (BinarySection *Section : Sections)
107     delete Section;
108   for (BinaryFunction *InjectedFunction : InjectedBinaryFunctions)
109     delete InjectedFunction;
110   for (std::pair<const uint64_t, JumpTable *> JTI : JumpTables)
111     delete JTI.second;
112   clearBinaryData();
113 }
114 
115 /// Create BinaryContext for a given architecture \p ArchName and
116 /// triple \p TripleName.
117 Expected<std::unique_ptr<BinaryContext>>
118 BinaryContext::createBinaryContext(const ObjectFile *File, bool IsPIC,
119                                    std::unique_ptr<DWARFContext> DwCtx) {
120   StringRef ArchName = "";
121   StringRef FeaturesStr = "";
122   switch (File->getArch()) {
123   case llvm::Triple::x86_64:
124     ArchName = "x86-64";
125     FeaturesStr = "+nopl";
126     break;
127   case llvm::Triple::aarch64:
128     ArchName = "aarch64";
129     FeaturesStr = "+all";
130     break;
131   case llvm::Triple::riscv64:
132     ArchName = "riscv64";
133     // RV64GC
134     FeaturesStr = "+m,+a,+f,+d,+zicsr,+zifencei,+c";
135     break;
136   default:
137     return createStringError(std::errc::not_supported,
138                              "BOLT-ERROR: Unrecognized machine in ELF file");
139   }
140 
141   auto TheTriple = std::make_unique<Triple>(File->makeTriple());
142   const std::string TripleName = TheTriple->str();
143 
144   std::string Error;
145   const Target *TheTarget =
146       TargetRegistry::lookupTarget(std::string(ArchName), *TheTriple, Error);
147   if (!TheTarget)
148     return createStringError(make_error_code(std::errc::not_supported),
149                              Twine("BOLT-ERROR: ", Error));
150 
151   std::unique_ptr<const MCRegisterInfo> MRI(
152       TheTarget->createMCRegInfo(TripleName));
153   if (!MRI)
154     return createStringError(
155         make_error_code(std::errc::not_supported),
156         Twine("BOLT-ERROR: no register info for target ", TripleName));
157 
158   // Set up disassembler.
159   std::unique_ptr<MCAsmInfo> AsmInfo(
160       TheTarget->createMCAsmInfo(*MRI, TripleName, MCTargetOptions()));
161   if (!AsmInfo)
162     return createStringError(
163         make_error_code(std::errc::not_supported),
164         Twine("BOLT-ERROR: no assembly info for target ", TripleName));
165   // BOLT creates "func@PLT" symbols for PLT entries. In function assembly dump
166   // we want to emit such names as using @PLT without double quotes to convey
167   // variant kind to the assembler. BOLT doesn't rely on the linker so we can
168   // override the default AsmInfo behavior to emit names the way we want.
169   AsmInfo->setAllowAtInName(true);
170 
171   std::unique_ptr<const MCSubtargetInfo> STI(
172       TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
173   if (!STI)
174     return createStringError(
175         make_error_code(std::errc::not_supported),
176         Twine("BOLT-ERROR: no subtarget info for target ", TripleName));
177 
178   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
179   if (!MII)
180     return createStringError(
181         make_error_code(std::errc::not_supported),
182         Twine("BOLT-ERROR: no instruction info for target ", TripleName));
183 
184   std::unique_ptr<MCContext> Ctx(
185       new MCContext(*TheTriple, AsmInfo.get(), MRI.get(), STI.get()));
186   std::unique_ptr<MCObjectFileInfo> MOFI(
187       TheTarget->createMCObjectFileInfo(*Ctx, IsPIC));
188   Ctx->setObjectFileInfo(MOFI.get());
189   // We do not support X86 Large code model. Change this in the future.
190   bool Large = false;
191   if (TheTriple->getArch() == llvm::Triple::aarch64)
192     Large = true;
193   unsigned LSDAEncoding =
194       Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
195   if (IsPIC) {
196     LSDAEncoding = dwarf::DW_EH_PE_pcrel |
197                    (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
198   }
199 
200   std::unique_ptr<MCDisassembler> DisAsm(
201       TheTarget->createMCDisassembler(*STI, *Ctx));
202 
203   if (!DisAsm)
204     return createStringError(
205         make_error_code(std::errc::not_supported),
206         Twine("BOLT-ERROR: no disassembler info for target ", TripleName));
207 
208   std::unique_ptr<const MCInstrAnalysis> MIA(
209       TheTarget->createMCInstrAnalysis(MII.get()));
210   if (!MIA)
211     return createStringError(
212         make_error_code(std::errc::not_supported),
213         Twine("BOLT-ERROR: failed to create instruction analysis for target ",
214               TripleName));
215 
216   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
217   std::unique_ptr<MCInstPrinter> InstructionPrinter(
218       TheTarget->createMCInstPrinter(*TheTriple, AsmPrinterVariant, *AsmInfo,
219                                      *MII, *MRI));
220   if (!InstructionPrinter)
221     return createStringError(
222         make_error_code(std::errc::not_supported),
223         Twine("BOLT-ERROR: no instruction printer for target ", TripleName));
224   InstructionPrinter->setPrintImmHex(true);
225 
226   std::unique_ptr<MCCodeEmitter> MCE(
227       TheTarget->createMCCodeEmitter(*MII, *Ctx));
228 
229   // Make sure we don't miss any output on core dumps.
230   outs().SetUnbuffered();
231   errs().SetUnbuffered();
232   dbgs().SetUnbuffered();
233 
234   auto BC = std::make_unique<BinaryContext>(
235       std::move(Ctx), std::move(DwCtx), std::move(TheTriple), TheTarget,
236       std::string(TripleName), std::move(MCE), std::move(MOFI),
237       std::move(AsmInfo), std::move(MII), std::move(STI),
238       std::move(InstructionPrinter), std::move(MIA), nullptr, std::move(MRI),
239       std::move(DisAsm));
240 
241   BC->LSDAEncoding = LSDAEncoding;
242 
243   BC->MAB = std::unique_ptr<MCAsmBackend>(
244       BC->TheTarget->createMCAsmBackend(*BC->STI, *BC->MRI, MCTargetOptions()));
245 
246   BC->setFilename(File->getFileName());
247 
248   BC->HasFixedLoadAddress = !IsPIC;
249 
250   BC->SymbolicDisAsm = std::unique_ptr<MCDisassembler>(
251       BC->TheTarget->createMCDisassembler(*BC->STI, *BC->Ctx));
252 
253   if (!BC->SymbolicDisAsm)
254     return createStringError(
255         make_error_code(std::errc::not_supported),
256         Twine("BOLT-ERROR: no disassembler info for target ", TripleName));
257 
258   return std::move(BC);
259 }
260 
261 bool BinaryContext::forceSymbolRelocations(StringRef SymbolName) const {
262   if (opts::HotText &&
263       (SymbolName == "__hot_start" || SymbolName == "__hot_end"))
264     return true;
265 
266   if (opts::HotData &&
267       (SymbolName == "__hot_data_start" || SymbolName == "__hot_data_end"))
268     return true;
269 
270   if (SymbolName == "_end")
271     return true;
272 
273   return false;
274 }
275 
276 std::unique_ptr<MCObjectWriter>
277 BinaryContext::createObjectWriter(raw_pwrite_stream &OS) {
278   return MAB->createObjectWriter(OS);
279 }
280 
281 bool BinaryContext::validateObjectNesting() const {
282   auto Itr = BinaryDataMap.begin();
283   auto End = BinaryDataMap.end();
284   bool Valid = true;
285   while (Itr != End) {
286     auto Next = std::next(Itr);
287     while (Next != End &&
288            Itr->second->getSection() == Next->second->getSection() &&
289            Itr->second->containsRange(Next->second->getAddress(),
290                                       Next->second->getSize())) {
291       if (Next->second->Parent != Itr->second) {
292         errs() << "BOLT-WARNING: object nesting incorrect for:\n"
293                << "BOLT-WARNING:  " << *Itr->second << "\n"
294                << "BOLT-WARNING:  " << *Next->second << "\n";
295         Valid = false;
296       }
297       ++Next;
298     }
299     Itr = Next;
300   }
301   return Valid;
302 }
303 
304 bool BinaryContext::validateHoles() const {
305   bool Valid = true;
306   for (BinarySection &Section : sections()) {
307     for (const Relocation &Rel : Section.relocations()) {
308       uint64_t RelAddr = Rel.Offset + Section.getAddress();
309       const BinaryData *BD = getBinaryDataContainingAddress(RelAddr);
310       if (!BD) {
311         errs() << "BOLT-WARNING: no BinaryData found for relocation at address"
312                << " 0x" << Twine::utohexstr(RelAddr) << " in "
313                << Section.getName() << "\n";
314         Valid = false;
315       } else if (!BD->getAtomicRoot()) {
316         errs() << "BOLT-WARNING: no atomic BinaryData found for relocation at "
317                << "address 0x" << Twine::utohexstr(RelAddr) << " in "
318                << Section.getName() << "\n";
319         Valid = false;
320       }
321     }
322   }
323   return Valid;
324 }
325 
326 void BinaryContext::updateObjectNesting(BinaryDataMapType::iterator GAI) {
327   const uint64_t Address = GAI->second->getAddress();
328   const uint64_t Size = GAI->second->getSize();
329 
330   auto fixParents = [&](BinaryDataMapType::iterator Itr,
331                         BinaryData *NewParent) {
332     BinaryData *OldParent = Itr->second->Parent;
333     Itr->second->Parent = NewParent;
334     ++Itr;
335     while (Itr != BinaryDataMap.end() && OldParent &&
336            Itr->second->Parent == OldParent) {
337       Itr->second->Parent = NewParent;
338       ++Itr;
339     }
340   };
341 
342   // Check if the previous symbol contains the newly added symbol.
343   if (GAI != BinaryDataMap.begin()) {
344     BinaryData *Prev = std::prev(GAI)->second;
345     while (Prev) {
346       if (Prev->getSection() == GAI->second->getSection() &&
347           Prev->containsRange(Address, Size)) {
348         fixParents(GAI, Prev);
349       } else {
350         fixParents(GAI, nullptr);
351       }
352       Prev = Prev->Parent;
353     }
354   }
355 
356   // Check if the newly added symbol contains any subsequent symbols.
357   if (Size != 0) {
358     BinaryData *BD = GAI->second->Parent ? GAI->second->Parent : GAI->second;
359     auto Itr = std::next(GAI);
360     while (
361         Itr != BinaryDataMap.end() &&
362         BD->containsRange(Itr->second->getAddress(), Itr->second->getSize())) {
363       Itr->second->Parent = BD;
364       ++Itr;
365     }
366   }
367 }
368 
369 iterator_range<BinaryContext::binary_data_iterator>
370 BinaryContext::getSubBinaryData(BinaryData *BD) {
371   auto Start = std::next(BinaryDataMap.find(BD->getAddress()));
372   auto End = Start;
373   while (End != BinaryDataMap.end() && BD->isAncestorOf(End->second))
374     ++End;
375   return make_range(Start, End);
376 }
377 
378 std::pair<const MCSymbol *, uint64_t>
379 BinaryContext::handleAddressRef(uint64_t Address, BinaryFunction &BF,
380                                 bool IsPCRel) {
381   if (isAArch64()) {
382     // Check if this is an access to a constant island and create bookkeeping
383     // to keep track of it and emit it later as part of this function.
384     if (MCSymbol *IslandSym = BF.getOrCreateIslandAccess(Address))
385       return std::make_pair(IslandSym, 0);
386 
387     // Detect custom code written in assembly that refers to arbitrary
388     // constant islands from other functions. Write this reference so we
389     // can pull this constant island and emit it as part of this function
390     // too.
391     auto IslandIter = AddressToConstantIslandMap.lower_bound(Address);
392 
393     if (IslandIter != AddressToConstantIslandMap.begin() &&
394         (IslandIter == AddressToConstantIslandMap.end() ||
395          IslandIter->first > Address))
396       --IslandIter;
397 
398     if (IslandIter != AddressToConstantIslandMap.end()) {
399       // Fall-back to referencing the original constant island in the presence
400       // of dynamic relocs, as we currently do not support cloning them.
401       // Notice: we might fail to link because of this, if the original constant
402       // island we are referring would be emitted too far away.
403       if (IslandIter->second->hasDynamicRelocationAtIsland()) {
404         MCSymbol *IslandSym =
405             IslandIter->second->getOrCreateIslandAccess(Address);
406         if (IslandSym)
407           return std::make_pair(IslandSym, 0);
408       } else if (MCSymbol *IslandSym =
409                      IslandIter->second->getOrCreateProxyIslandAccess(Address,
410                                                                       BF)) {
411         BF.createIslandDependency(IslandSym, IslandIter->second);
412         return std::make_pair(IslandSym, 0);
413       }
414     }
415   }
416 
417   // Note that the address does not necessarily have to reside inside
418   // a section, it could be an absolute address too.
419   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
420   if (Section && Section->isText()) {
421     if (BF.containsAddress(Address, /*UseMaxSize=*/isAArch64())) {
422       if (Address != BF.getAddress()) {
423         // The address could potentially escape. Mark it as another entry
424         // point into the function.
425         if (opts::Verbosity >= 1) {
426           outs() << "BOLT-INFO: potentially escaped address 0x"
427                  << Twine::utohexstr(Address) << " in function " << BF << '\n';
428         }
429         BF.HasInternalLabelReference = true;
430         return std::make_pair(
431             BF.addEntryPointAtOffset(Address - BF.getAddress()), 0);
432       }
433     } else {
434       addInterproceduralReference(&BF, Address);
435     }
436   }
437 
438   // With relocations, catch jump table references outside of the basic block
439   // containing the indirect jump.
440   if (HasRelocations) {
441     const MemoryContentsType MemType = analyzeMemoryAt(Address, BF);
442     if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE && IsPCRel) {
443       const MCSymbol *Symbol =
444           getOrCreateJumpTable(BF, Address, JumpTable::JTT_PIC);
445 
446       return std::make_pair(Symbol, 0);
447     }
448   }
449 
450   if (BinaryData *BD = getBinaryDataContainingAddress(Address))
451     return std::make_pair(BD->getSymbol(), Address - BD->getAddress());
452 
453   // TODO: use DWARF info to get size/alignment here?
454   MCSymbol *TargetSymbol = getOrCreateGlobalSymbol(Address, "DATAat");
455   LLVM_DEBUG(dbgs() << "Created symbol " << TargetSymbol->getName() << '\n');
456   return std::make_pair(TargetSymbol, 0);
457 }
458 
459 MemoryContentsType BinaryContext::analyzeMemoryAt(uint64_t Address,
460                                                   BinaryFunction &BF) {
461   if (!isX86())
462     return MemoryContentsType::UNKNOWN;
463 
464   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
465   if (!Section) {
466     // No section - possibly an absolute address. Since we don't allow
467     // internal function addresses to escape the function scope - we
468     // consider it a tail call.
469     if (opts::Verbosity > 1) {
470       errs() << "BOLT-WARNING: no section for address 0x"
471              << Twine::utohexstr(Address) << " referenced from function " << BF
472              << '\n';
473     }
474     return MemoryContentsType::UNKNOWN;
475   }
476 
477   if (Section->isVirtual()) {
478     // The contents are filled at runtime.
479     return MemoryContentsType::UNKNOWN;
480   }
481 
482   // No support for jump tables in code yet.
483   if (Section->isText())
484     return MemoryContentsType::UNKNOWN;
485 
486   // Start with checking for PIC jump table. We expect non-PIC jump tables
487   // to have high 32 bits set to 0.
488   if (analyzeJumpTable(Address, JumpTable::JTT_PIC, BF))
489     return MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
490 
491   if (analyzeJumpTable(Address, JumpTable::JTT_NORMAL, BF))
492     return MemoryContentsType::POSSIBLE_JUMP_TABLE;
493 
494   return MemoryContentsType::UNKNOWN;
495 }
496 
497 bool BinaryContext::analyzeJumpTable(const uint64_t Address,
498                                      const JumpTable::JumpTableType Type,
499                                      const BinaryFunction &BF,
500                                      const uint64_t NextJTAddress,
501                                      JumpTable::AddressesType *EntriesAsAddress,
502                                      bool *HasEntryInFragment) const {
503   // Is one of the targets __builtin_unreachable?
504   bool HasUnreachable = false;
505 
506   // Does one of the entries match function start address?
507   bool HasStartAsEntry = false;
508 
509   // Number of targets other than __builtin_unreachable.
510   uint64_t NumRealEntries = 0;
511 
512   auto addEntryAddress = [&](uint64_t EntryAddress) {
513     if (EntriesAsAddress)
514       EntriesAsAddress->emplace_back(EntryAddress);
515   };
516 
517   ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
518   if (!Section)
519     return false;
520 
521   // The upper bound is defined by containing object, section limits, and
522   // the next jump table in memory.
523   uint64_t UpperBound = Section->getEndAddress();
524   const BinaryData *JumpTableBD = getBinaryDataAtAddress(Address);
525   if (JumpTableBD && JumpTableBD->getSize()) {
526     assert(JumpTableBD->getEndAddress() <= UpperBound &&
527            "data object cannot cross a section boundary");
528     UpperBound = JumpTableBD->getEndAddress();
529   }
530   if (NextJTAddress)
531     UpperBound = std::min(NextJTAddress, UpperBound);
532 
533   LLVM_DEBUG({
534     using JTT = JumpTable::JumpTableType;
535     dbgs() << formatv("BOLT-DEBUG: analyzeJumpTable @{0:x} in {1}, JTT={2}\n",
536                       Address, BF.getPrintName(),
537                       Type == JTT::JTT_PIC ? "PIC" : "Normal");
538   });
539   const uint64_t EntrySize = getJumpTableEntrySize(Type);
540   for (uint64_t EntryAddress = Address; EntryAddress <= UpperBound - EntrySize;
541        EntryAddress += EntrySize) {
542     LLVM_DEBUG(dbgs() << "  * Checking 0x" << Twine::utohexstr(EntryAddress)
543                       << " -> ");
544     // Check if there's a proper relocation against the jump table entry.
545     if (HasRelocations) {
546       if (Type == JumpTable::JTT_PIC &&
547           !DataPCRelocations.count(EntryAddress)) {
548         LLVM_DEBUG(
549             dbgs() << "FAIL: JTT_PIC table, no relocation for this address\n");
550         break;
551       }
552       if (Type == JumpTable::JTT_NORMAL && !getRelocationAt(EntryAddress)) {
553         LLVM_DEBUG(
554             dbgs()
555             << "FAIL: JTT_NORMAL table, no relocation for this address\n");
556         break;
557       }
558     }
559 
560     const uint64_t Value =
561         (Type == JumpTable::JTT_PIC)
562             ? Address + *getSignedValueAtAddress(EntryAddress, EntrySize)
563             : *getPointerAtAddress(EntryAddress);
564 
565     // __builtin_unreachable() case.
566     if (Value == BF.getAddress() + BF.getSize()) {
567       addEntryAddress(Value);
568       HasUnreachable = true;
569       LLVM_DEBUG(dbgs() << formatv("OK: {0:x} __builtin_unreachable\n", Value));
570       continue;
571     }
572 
573     // Function start is another special case. It is allowed in the jump table,
574     // but we need at least one another regular entry to distinguish the table
575     // from, e.g. a function pointer array.
576     if (Value == BF.getAddress()) {
577       HasStartAsEntry = true;
578       addEntryAddress(Value);
579       continue;
580     }
581 
582     // Function or one of its fragments.
583     const BinaryFunction *TargetBF = getBinaryFunctionContainingAddress(Value);
584     const bool DoesBelongToFunction =
585         BF.containsAddress(Value) ||
586         (TargetBF && TargetBF->isParentOrChildOf(BF));
587     if (!DoesBelongToFunction) {
588       LLVM_DEBUG({
589         if (!BF.containsAddress(Value)) {
590           dbgs() << "FAIL: function doesn't contain this address\n";
591           if (TargetBF) {
592             dbgs() << "  ! function containing this address: "
593                    << TargetBF->getPrintName() << '\n';
594             if (TargetBF->isFragment()) {
595               dbgs() << "  ! is a fragment";
596               for (BinaryFunction *Parent : TargetBF->ParentFragments)
597                 dbgs() << ", parent: " << Parent->getPrintName();
598               dbgs() << '\n';
599             }
600           }
601         }
602       });
603       break;
604     }
605 
606     // Check there's an instruction at this offset.
607     if (TargetBF->getState() == BinaryFunction::State::Disassembled &&
608         !TargetBF->getInstructionAtOffset(Value - TargetBF->getAddress())) {
609       LLVM_DEBUG(dbgs() << formatv("FAIL: no instruction at {0:x}\n", Value));
610       break;
611     }
612 
613     ++NumRealEntries;
614     LLVM_DEBUG(dbgs() << formatv("OK: {0:x} real entry\n", Value));
615 
616     if (TargetBF != &BF && HasEntryInFragment)
617       *HasEntryInFragment = true;
618     addEntryAddress(Value);
619   }
620 
621   // It's a jump table if the number of real entries is more than 1, or there's
622   // one real entry and one or more special targets. If there are only multiple
623   // special targets, then it's not a jump table.
624   return NumRealEntries + (HasUnreachable || HasStartAsEntry) >= 2;
625 }
626 
627 void BinaryContext::populateJumpTables() {
628   LLVM_DEBUG(dbgs() << "DataPCRelocations: " << DataPCRelocations.size()
629                     << '\n');
630   for (auto JTI = JumpTables.begin(), JTE = JumpTables.end(); JTI != JTE;
631        ++JTI) {
632     JumpTable *JT = JTI->second;
633 
634     bool NonSimpleParent = false;
635     for (BinaryFunction *BF : JT->Parents)
636       NonSimpleParent |= !BF->isSimple();
637     if (NonSimpleParent)
638       continue;
639 
640     uint64_t NextJTAddress = 0;
641     auto NextJTI = std::next(JTI);
642     if (NextJTI != JTE)
643       NextJTAddress = NextJTI->second->getAddress();
644 
645     const bool Success =
646         analyzeJumpTable(JT->getAddress(), JT->Type, *(JT->Parents[0]),
647                          NextJTAddress, &JT->EntriesAsAddress, &JT->IsSplit);
648     if (!Success) {
649       LLVM_DEBUG({
650         dbgs() << "failed to analyze ";
651         JT->print(dbgs());
652         if (NextJTI != JTE) {
653           dbgs() << "next ";
654           NextJTI->second->print(dbgs());
655         }
656       });
657       llvm_unreachable("jump table heuristic failure");
658     }
659     for (BinaryFunction *Frag : JT->Parents) {
660       if (JT->IsSplit)
661         Frag->setHasIndirectTargetToSplitFragment(true);
662       for (uint64_t EntryAddress : JT->EntriesAsAddress)
663         // if target is builtin_unreachable
664         if (EntryAddress == Frag->getAddress() + Frag->getSize()) {
665           Frag->IgnoredBranches.emplace_back(EntryAddress - Frag->getAddress(),
666                                              Frag->getSize());
667         } else if (EntryAddress >= Frag->getAddress() &&
668                    EntryAddress < Frag->getAddress() + Frag->getSize()) {
669           Frag->registerReferencedOffset(EntryAddress - Frag->getAddress());
670         }
671     }
672 
673     // In strict mode, erase PC-relative relocation record. Later we check that
674     // all such records are erased and thus have been accounted for.
675     if (opts::StrictMode && JT->Type == JumpTable::JTT_PIC) {
676       for (uint64_t Address = JT->getAddress();
677            Address < JT->getAddress() + JT->getSize();
678            Address += JT->EntrySize) {
679         DataPCRelocations.erase(DataPCRelocations.find(Address));
680       }
681     }
682 
683     // Mark to skip the function and all its fragments.
684     for (BinaryFunction *Frag : JT->Parents)
685       if (Frag->hasIndirectTargetToSplitFragment())
686         addFragmentsToSkip(Frag);
687   }
688 
689   if (opts::StrictMode && DataPCRelocations.size()) {
690     LLVM_DEBUG({
691       dbgs() << DataPCRelocations.size()
692              << " unclaimed PC-relative relocations left in data:\n";
693       for (uint64_t Reloc : DataPCRelocations)
694         dbgs() << Twine::utohexstr(Reloc) << '\n';
695     });
696     assert(0 && "unclaimed PC-relative relocations left in data\n");
697   }
698   clearList(DataPCRelocations);
699 }
700 
701 void BinaryContext::skipMarkedFragments() {
702   std::vector<BinaryFunction *> FragmentQueue;
703   // Copy the functions to FragmentQueue.
704   FragmentQueue.assign(FragmentsToSkip.begin(), FragmentsToSkip.end());
705   auto addToWorklist = [&](BinaryFunction *Function) -> void {
706     if (FragmentsToSkip.count(Function))
707       return;
708     FragmentQueue.push_back(Function);
709     addFragmentsToSkip(Function);
710   };
711   // Functions containing split jump tables need to be skipped with all
712   // fragments (transitively).
713   for (size_t I = 0; I != FragmentQueue.size(); I++) {
714     BinaryFunction *BF = FragmentQueue[I];
715     assert(FragmentsToSkip.count(BF) &&
716            "internal error in traversing function fragments");
717     if (opts::Verbosity >= 1)
718       errs() << "BOLT-WARNING: Ignoring " << BF->getPrintName() << '\n';
719     BF->setSimple(false);
720     BF->setHasIndirectTargetToSplitFragment(true);
721 
722     llvm::for_each(BF->Fragments, addToWorklist);
723     llvm::for_each(BF->ParentFragments, addToWorklist);
724   }
725   if (!FragmentsToSkip.empty())
726     errs() << "BOLT-WARNING: skipped " << FragmentsToSkip.size() << " function"
727            << (FragmentsToSkip.size() == 1 ? "" : "s")
728            << " due to cold fragments\n";
729 }
730 
731 MCSymbol *BinaryContext::getOrCreateGlobalSymbol(uint64_t Address, Twine Prefix,
732                                                  uint64_t Size,
733                                                  uint16_t Alignment,
734                                                  unsigned Flags) {
735   auto Itr = BinaryDataMap.find(Address);
736   if (Itr != BinaryDataMap.end()) {
737     assert(Itr->second->getSize() == Size || !Size);
738     return Itr->second->getSymbol();
739   }
740 
741   std::string Name = (Prefix + "0x" + Twine::utohexstr(Address)).str();
742   assert(!GlobalSymbols.count(Name) && "created name is not unique");
743   return registerNameAtAddress(Name, Address, Size, Alignment, Flags);
744 }
745 
746 MCSymbol *BinaryContext::getOrCreateUndefinedGlobalSymbol(StringRef Name) {
747   return Ctx->getOrCreateSymbol(Name);
748 }
749 
750 BinaryFunction *BinaryContext::createBinaryFunction(
751     const std::string &Name, BinarySection &Section, uint64_t Address,
752     uint64_t Size, uint64_t SymbolSize, uint16_t Alignment) {
753   auto Result = BinaryFunctions.emplace(
754       Address, BinaryFunction(Name, Section, Address, Size, *this));
755   assert(Result.second == true && "unexpected duplicate function");
756   BinaryFunction *BF = &Result.first->second;
757   registerNameAtAddress(Name, Address, SymbolSize ? SymbolSize : Size,
758                         Alignment);
759   setSymbolToFunctionMap(BF->getSymbol(), BF);
760   return BF;
761 }
762 
763 const MCSymbol *
764 BinaryContext::getOrCreateJumpTable(BinaryFunction &Function, uint64_t Address,
765                                     JumpTable::JumpTableType Type) {
766   // Two fragments of same function access same jump table
767   if (JumpTable *JT = getJumpTableContainingAddress(Address)) {
768     assert(JT->Type == Type && "jump table types have to match");
769     assert(Address == JT->getAddress() && "unexpected non-empty jump table");
770 
771     // Prevent associating a jump table to a specific fragment twice.
772     // This simple check arises from the assumption: no more than 2 fragments.
773     if (JT->Parents.size() == 1 && JT->Parents[0] != &Function) {
774       assert(JT->Parents[0]->isParentOrChildOf(Function) &&
775              "cannot re-use jump table of a different function");
776       // Duplicate the entry for the parent function for easy access
777       JT->Parents.push_back(&Function);
778       if (opts::Verbosity > 2) {
779         outs() << "BOLT-INFO: Multiple fragments access same jump table: "
780                << JT->Parents[0]->getPrintName() << "; "
781                << Function.getPrintName() << "\n";
782         JT->print(outs());
783       }
784       Function.JumpTables.emplace(Address, JT);
785       JT->Parents[0]->setHasIndirectTargetToSplitFragment(true);
786       JT->Parents[1]->setHasIndirectTargetToSplitFragment(true);
787     }
788 
789     bool IsJumpTableParent = false;
790     (void)IsJumpTableParent;
791     for (BinaryFunction *Frag : JT->Parents)
792       if (Frag == &Function)
793         IsJumpTableParent = true;
794     assert(IsJumpTableParent &&
795            "cannot re-use jump table of a different function");
796     return JT->getFirstLabel();
797   }
798 
799   // Re-use the existing symbol if possible.
800   MCSymbol *JTLabel = nullptr;
801   if (BinaryData *Object = getBinaryDataAtAddress(Address)) {
802     if (!isInternalSymbolName(Object->getSymbol()->getName()))
803       JTLabel = Object->getSymbol();
804   }
805 
806   const uint64_t EntrySize = getJumpTableEntrySize(Type);
807   if (!JTLabel) {
808     const std::string JumpTableName = generateJumpTableName(Function, Address);
809     JTLabel = registerNameAtAddress(JumpTableName, Address, 0, EntrySize);
810   }
811 
812   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: creating jump table " << JTLabel->getName()
813                     << " in function " << Function << '\n');
814 
815   JumpTable *JT = new JumpTable(*JTLabel, Address, EntrySize, Type,
816                                 JumpTable::LabelMapType{{0, JTLabel}},
817                                 *getSectionForAddress(Address));
818   JT->Parents.push_back(&Function);
819   if (opts::Verbosity > 2)
820     JT->print(outs());
821   JumpTables.emplace(Address, JT);
822 
823   // Duplicate the entry for the parent function for easy access.
824   Function.JumpTables.emplace(Address, JT);
825   return JTLabel;
826 }
827 
828 std::pair<uint64_t, const MCSymbol *>
829 BinaryContext::duplicateJumpTable(BinaryFunction &Function, JumpTable *JT,
830                                   const MCSymbol *OldLabel) {
831   auto L = scopeLock();
832   unsigned Offset = 0;
833   bool Found = false;
834   for (std::pair<const unsigned, MCSymbol *> Elmt : JT->Labels) {
835     if (Elmt.second != OldLabel)
836       continue;
837     Offset = Elmt.first;
838     Found = true;
839     break;
840   }
841   assert(Found && "Label not found");
842   (void)Found;
843   MCSymbol *NewLabel = Ctx->createNamedTempSymbol("duplicatedJT");
844   JumpTable *NewJT =
845       new JumpTable(*NewLabel, JT->getAddress(), JT->EntrySize, JT->Type,
846                     JumpTable::LabelMapType{{Offset, NewLabel}},
847                     *getSectionForAddress(JT->getAddress()));
848   NewJT->Parents = JT->Parents;
849   NewJT->Entries = JT->Entries;
850   NewJT->Counts = JT->Counts;
851   uint64_t JumpTableID = ++DuplicatedJumpTables;
852   // Invert it to differentiate from regular jump tables whose IDs are their
853   // addresses in the input binary memory space
854   JumpTableID = ~JumpTableID;
855   JumpTables.emplace(JumpTableID, NewJT);
856   Function.JumpTables.emplace(JumpTableID, NewJT);
857   return std::make_pair(JumpTableID, NewLabel);
858 }
859 
860 std::string BinaryContext::generateJumpTableName(const BinaryFunction &BF,
861                                                  uint64_t Address) {
862   size_t Id;
863   uint64_t Offset = 0;
864   if (const JumpTable *JT = BF.getJumpTableContainingAddress(Address)) {
865     Offset = Address - JT->getAddress();
866     auto Itr = JT->Labels.find(Offset);
867     if (Itr != JT->Labels.end())
868       return std::string(Itr->second->getName());
869     Id = JumpTableIds.at(JT->getAddress());
870   } else {
871     Id = JumpTableIds[Address] = BF.JumpTables.size();
872   }
873   return ("JUMP_TABLE/" + BF.getOneName().str() + "." + std::to_string(Id) +
874           (Offset ? ("." + std::to_string(Offset)) : ""));
875 }
876 
877 bool BinaryContext::hasValidCodePadding(const BinaryFunction &BF) {
878   // FIXME: aarch64 support is missing.
879   if (!isX86())
880     return true;
881 
882   if (BF.getSize() == BF.getMaxSize())
883     return true;
884 
885   ErrorOr<ArrayRef<unsigned char>> FunctionData = BF.getData();
886   assert(FunctionData && "cannot get function as data");
887 
888   uint64_t Offset = BF.getSize();
889   MCInst Instr;
890   uint64_t InstrSize = 0;
891   uint64_t InstrAddress = BF.getAddress() + Offset;
892   using std::placeholders::_1;
893 
894   // Skip instructions that satisfy the predicate condition.
895   auto skipInstructions = [&](std::function<bool(const MCInst &)> Predicate) {
896     const uint64_t StartOffset = Offset;
897     for (; Offset < BF.getMaxSize();
898          Offset += InstrSize, InstrAddress += InstrSize) {
899       if (!DisAsm->getInstruction(Instr, InstrSize, FunctionData->slice(Offset),
900                                   InstrAddress, nulls()))
901         break;
902       if (!Predicate(Instr))
903         break;
904     }
905 
906     return Offset - StartOffset;
907   };
908 
909   // Skip a sequence of zero bytes.
910   auto skipZeros = [&]() {
911     const uint64_t StartOffset = Offset;
912     for (; Offset < BF.getMaxSize(); ++Offset)
913       if ((*FunctionData)[Offset] != 0)
914         break;
915 
916     return Offset - StartOffset;
917   };
918 
919   // Accept the whole padding area filled with breakpoints.
920   auto isBreakpoint = std::bind(&MCPlusBuilder::isBreakpoint, MIB.get(), _1);
921   if (skipInstructions(isBreakpoint) && Offset == BF.getMaxSize())
922     return true;
923 
924   auto isNoop = std::bind(&MCPlusBuilder::isNoop, MIB.get(), _1);
925 
926   // Some functions have a jump to the next function or to the padding area
927   // inserted after the body.
928   auto isSkipJump = [&](const MCInst &Instr) {
929     uint64_t TargetAddress = 0;
930     if (MIB->isUnconditionalBranch(Instr) &&
931         MIB->evaluateBranch(Instr, InstrAddress, InstrSize, TargetAddress)) {
932       if (TargetAddress >= InstrAddress + InstrSize &&
933           TargetAddress <= BF.getAddress() + BF.getMaxSize()) {
934         return true;
935       }
936     }
937     return false;
938   };
939 
940   // Skip over nops, jumps, and zero padding. Allow interleaving (this happens).
941   while (skipInstructions(isNoop) || skipInstructions(isSkipJump) ||
942          skipZeros())
943     ;
944 
945   if (Offset == BF.getMaxSize())
946     return true;
947 
948   if (opts::Verbosity >= 1) {
949     errs() << "BOLT-WARNING: bad padding at address 0x"
950            << Twine::utohexstr(BF.getAddress() + BF.getSize())
951            << " starting at offset " << (Offset - BF.getSize())
952            << " in function " << BF << '\n'
953            << FunctionData->slice(BF.getSize(), BF.getMaxSize() - BF.getSize())
954            << '\n';
955   }
956 
957   return false;
958 }
959 
960 void BinaryContext::adjustCodePadding() {
961   for (auto &BFI : BinaryFunctions) {
962     BinaryFunction &BF = BFI.second;
963     if (!shouldEmit(BF))
964       continue;
965 
966     if (!hasValidCodePadding(BF)) {
967       if (HasRelocations) {
968         if (opts::Verbosity >= 1) {
969           outs() << "BOLT-INFO: function " << BF
970                  << " has invalid padding. Ignoring the function.\n";
971         }
972         BF.setIgnored();
973       } else {
974         BF.setMaxSize(BF.getSize());
975       }
976     }
977   }
978 }
979 
980 MCSymbol *BinaryContext::registerNameAtAddress(StringRef Name, uint64_t Address,
981                                                uint64_t Size,
982                                                uint16_t Alignment,
983                                                unsigned Flags) {
984   // Register the name with MCContext.
985   MCSymbol *Symbol = Ctx->getOrCreateSymbol(Name);
986 
987   auto GAI = BinaryDataMap.find(Address);
988   BinaryData *BD;
989   if (GAI == BinaryDataMap.end()) {
990     ErrorOr<BinarySection &> SectionOrErr = getSectionForAddress(Address);
991     BinarySection &Section =
992         SectionOrErr ? SectionOrErr.get() : absoluteSection();
993     BD = new BinaryData(*Symbol, Address, Size, Alignment ? Alignment : 1,
994                         Section, Flags);
995     GAI = BinaryDataMap.emplace(Address, BD).first;
996     GlobalSymbols[Name] = BD;
997     updateObjectNesting(GAI);
998   } else {
999     BD = GAI->second;
1000     if (!BD->hasName(Name)) {
1001       GlobalSymbols[Name] = BD;
1002       BD->Symbols.push_back(Symbol);
1003     }
1004   }
1005 
1006   return Symbol;
1007 }
1008 
1009 const BinaryData *
1010 BinaryContext::getBinaryDataContainingAddressImpl(uint64_t Address) const {
1011   auto NI = BinaryDataMap.lower_bound(Address);
1012   auto End = BinaryDataMap.end();
1013   if ((NI != End && Address == NI->first) ||
1014       ((NI != BinaryDataMap.begin()) && (NI-- != BinaryDataMap.begin()))) {
1015     if (NI->second->containsAddress(Address))
1016       return NI->second;
1017 
1018     // If this is a sub-symbol, see if a parent data contains the address.
1019     const BinaryData *BD = NI->second->getParent();
1020     while (BD) {
1021       if (BD->containsAddress(Address))
1022         return BD;
1023       BD = BD->getParent();
1024     }
1025   }
1026   return nullptr;
1027 }
1028 
1029 bool BinaryContext::setBinaryDataSize(uint64_t Address, uint64_t Size) {
1030   auto NI = BinaryDataMap.find(Address);
1031   assert(NI != BinaryDataMap.end());
1032   if (NI == BinaryDataMap.end())
1033     return false;
1034   // TODO: it's possible that a jump table starts at the same address
1035   // as a larger blob of private data.  When we set the size of the
1036   // jump table, it might be smaller than the total blob size.  In this
1037   // case we just leave the original size since (currently) it won't really
1038   // affect anything.
1039   assert((!NI->second->Size || NI->second->Size == Size ||
1040           (NI->second->isJumpTable() && NI->second->Size > Size)) &&
1041          "can't change the size of a symbol that has already had its "
1042          "size set");
1043   if (!NI->second->Size) {
1044     NI->second->Size = Size;
1045     updateObjectNesting(NI);
1046     return true;
1047   }
1048   return false;
1049 }
1050 
1051 void BinaryContext::generateSymbolHashes() {
1052   auto isPadding = [](const BinaryData &BD) {
1053     StringRef Contents = BD.getSection().getContents();
1054     StringRef SymData = Contents.substr(BD.getOffset(), BD.getSize());
1055     return (BD.getName().startswith("HOLEat") ||
1056             SymData.find_first_not_of(0) == StringRef::npos);
1057   };
1058 
1059   uint64_t NumCollisions = 0;
1060   for (auto &Entry : BinaryDataMap) {
1061     BinaryData &BD = *Entry.second;
1062     StringRef Name = BD.getName();
1063 
1064     if (!isInternalSymbolName(Name))
1065       continue;
1066 
1067     // First check if a non-anonymous alias exists and move it to the front.
1068     if (BD.getSymbols().size() > 1) {
1069       auto Itr = llvm::find_if(BD.getSymbols(), [&](const MCSymbol *Symbol) {
1070         return !isInternalSymbolName(Symbol->getName());
1071       });
1072       if (Itr != BD.getSymbols().end()) {
1073         size_t Idx = std::distance(BD.getSymbols().begin(), Itr);
1074         std::swap(BD.getSymbols()[0], BD.getSymbols()[Idx]);
1075         continue;
1076       }
1077     }
1078 
1079     // We have to skip 0 size symbols since they will all collide.
1080     if (BD.getSize() == 0) {
1081       continue;
1082     }
1083 
1084     const uint64_t Hash = BD.getSection().hash(BD);
1085     const size_t Idx = Name.find("0x");
1086     std::string NewName =
1087         (Twine(Name.substr(0, Idx)) + "_" + Twine::utohexstr(Hash)).str();
1088     if (getBinaryDataByName(NewName)) {
1089       // Ignore collisions for symbols that appear to be padding
1090       // (i.e. all zeros or a "hole")
1091       if (!isPadding(BD)) {
1092         if (opts::Verbosity) {
1093           errs() << "BOLT-WARNING: collision detected when hashing " << BD
1094                  << " with new name (" << NewName << "), skipping.\n";
1095         }
1096         ++NumCollisions;
1097       }
1098       continue;
1099     }
1100     BD.Symbols.insert(BD.Symbols.begin(), Ctx->getOrCreateSymbol(NewName));
1101     GlobalSymbols[NewName] = &BD;
1102   }
1103   if (NumCollisions) {
1104     errs() << "BOLT-WARNING: " << NumCollisions
1105            << " collisions detected while hashing binary objects";
1106     if (!opts::Verbosity)
1107       errs() << ". Use -v=1 to see the list.";
1108     errs() << '\n';
1109   }
1110 }
1111 
1112 bool BinaryContext::registerFragment(BinaryFunction &TargetFunction,
1113                                      BinaryFunction &Function) const {
1114   assert(TargetFunction.isFragment() && "TargetFunction must be a fragment");
1115   if (TargetFunction.isChildOf(Function))
1116     return true;
1117   TargetFunction.addParentFragment(Function);
1118   Function.addFragment(TargetFunction);
1119   if (!HasRelocations) {
1120     TargetFunction.setSimple(false);
1121     Function.setSimple(false);
1122   }
1123   if (opts::Verbosity >= 1) {
1124     outs() << "BOLT-INFO: marking " << TargetFunction << " as a fragment of "
1125            << Function << '\n';
1126   }
1127   return true;
1128 }
1129 
1130 void BinaryContext::addAdrpAddRelocAArch64(BinaryFunction &BF,
1131                                            MCInst &LoadLowBits,
1132                                            MCInst &LoadHiBits,
1133                                            uint64_t Target) {
1134   const MCSymbol *TargetSymbol;
1135   uint64_t Addend = 0;
1136   std::tie(TargetSymbol, Addend) = handleAddressRef(Target, BF,
1137                                                     /*IsPCRel*/ true);
1138   int64_t Val;
1139   MIB->replaceImmWithSymbolRef(LoadHiBits, TargetSymbol, Addend, Ctx.get(), Val,
1140                                ELF::R_AARCH64_ADR_PREL_PG_HI21);
1141   MIB->replaceImmWithSymbolRef(LoadLowBits, TargetSymbol, Addend, Ctx.get(),
1142                                Val, ELF::R_AARCH64_ADD_ABS_LO12_NC);
1143 }
1144 
1145 bool BinaryContext::handleAArch64Veneer(uint64_t Address, bool MatchOnly) {
1146   BinaryFunction *TargetFunction = getBinaryFunctionContainingAddress(Address);
1147   if (TargetFunction)
1148     return false;
1149 
1150   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1151   assert(Section && "cannot get section for referenced address");
1152   if (!Section->isText())
1153     return false;
1154 
1155   bool Ret = false;
1156   StringRef SectionContents = Section->getContents();
1157   uint64_t Offset = Address - Section->getAddress();
1158   const uint64_t MaxSize = SectionContents.size() - Offset;
1159   const uint8_t *Bytes =
1160       reinterpret_cast<const uint8_t *>(SectionContents.data());
1161   ArrayRef<uint8_t> Data(Bytes + Offset, MaxSize);
1162 
1163   auto matchVeneer = [&](BinaryFunction::InstrMapType &Instructions,
1164                          MCInst &Instruction, uint64_t Offset,
1165                          uint64_t AbsoluteInstrAddr,
1166                          uint64_t TotalSize) -> bool {
1167     MCInst *TargetHiBits, *TargetLowBits;
1168     uint64_t TargetAddress, Count;
1169     Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1170                                    AbsoluteInstrAddr, Instruction, TargetHiBits,
1171                                    TargetLowBits, TargetAddress);
1172     if (!Count)
1173       return false;
1174 
1175     if (MatchOnly)
1176       return true;
1177 
1178     // NOTE The target symbol was created during disassemble's
1179     // handleExternalReference
1180     const MCSymbol *VeneerSymbol = getOrCreateGlobalSymbol(Address, "FUNCat");
1181     BinaryFunction *Veneer = createBinaryFunction(VeneerSymbol->getName().str(),
1182                                                   *Section, Address, TotalSize);
1183     addAdrpAddRelocAArch64(*Veneer, *TargetLowBits, *TargetHiBits,
1184                            TargetAddress);
1185     MIB->addAnnotation(Instruction, "AArch64Veneer", true);
1186     Veneer->addInstruction(Offset, std::move(Instruction));
1187     --Count;
1188     for (auto It = Instructions.rbegin(); Count != 0; ++It, --Count) {
1189       MIB->addAnnotation(It->second, "AArch64Veneer", true);
1190       Veneer->addInstruction(It->first, std::move(It->second));
1191     }
1192 
1193     Veneer->getOrCreateLocalLabel(Address);
1194     Veneer->setMaxSize(TotalSize);
1195     Veneer->updateState(BinaryFunction::State::Disassembled);
1196     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: handling veneer function at 0x" << Address
1197                       << "\n");
1198     return true;
1199   };
1200 
1201   uint64_t Size = 0, TotalSize = 0;
1202   BinaryFunction::InstrMapType VeneerInstructions;
1203   for (Offset = 0; Offset < MaxSize; Offset += Size) {
1204     MCInst Instruction;
1205     const uint64_t AbsoluteInstrAddr = Address + Offset;
1206     if (!SymbolicDisAsm->getInstruction(Instruction, Size, Data.slice(Offset),
1207                                         AbsoluteInstrAddr, nulls()))
1208       break;
1209 
1210     TotalSize += Size;
1211     if (MIB->isBranch(Instruction)) {
1212       Ret = matchVeneer(VeneerInstructions, Instruction, Offset,
1213                         AbsoluteInstrAddr, TotalSize);
1214       break;
1215     }
1216 
1217     VeneerInstructions.emplace(Offset, std::move(Instruction));
1218   }
1219 
1220   return Ret;
1221 }
1222 
1223 void BinaryContext::processInterproceduralReferences() {
1224   for (const std::pair<BinaryFunction *, uint64_t> &It :
1225        InterproceduralReferences) {
1226     BinaryFunction &Function = *It.first;
1227     uint64_t Address = It.second;
1228     if (!Address || Function.isIgnored())
1229       continue;
1230 
1231     BinaryFunction *TargetFunction =
1232         getBinaryFunctionContainingAddress(Address);
1233     if (&Function == TargetFunction)
1234       continue;
1235 
1236     if (TargetFunction) {
1237       if (TargetFunction->isFragment() &&
1238           !TargetFunction->isChildOf(Function)) {
1239         errs() << "BOLT-WARNING: interprocedural reference between unrelated "
1240                   "fragments: "
1241                << Function.getPrintName() << " and "
1242                << TargetFunction->getPrintName() << '\n';
1243       }
1244       if (uint64_t Offset = Address - TargetFunction->getAddress())
1245         TargetFunction->addEntryPointAtOffset(Offset);
1246 
1247       continue;
1248     }
1249 
1250     // Check if address falls in function padding space - this could be
1251     // unmarked data in code. In this case adjust the padding space size.
1252     ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1253     assert(Section && "cannot get section for referenced address");
1254 
1255     if (!Section->isText())
1256       continue;
1257 
1258     // PLT requires special handling and could be ignored in this context.
1259     StringRef SectionName = Section->getName();
1260     if (SectionName == ".plt" || SectionName == ".plt.got")
1261       continue;
1262 
1263     // Check if it is aarch64 veneer written at Address
1264     if (isAArch64() && handleAArch64Veneer(Address))
1265       continue;
1266 
1267     if (opts::processAllFunctions()) {
1268       errs() << "BOLT-ERROR: cannot process binaries with unmarked "
1269              << "object in code at address 0x" << Twine::utohexstr(Address)
1270              << " belonging to section " << SectionName << " in current mode\n";
1271       exit(1);
1272     }
1273 
1274     TargetFunction = getBinaryFunctionContainingAddress(Address,
1275                                                         /*CheckPastEnd=*/false,
1276                                                         /*UseMaxSize=*/true);
1277     // We are not going to overwrite non-simple functions, but for simple
1278     // ones - adjust the padding size.
1279     if (TargetFunction && TargetFunction->isSimple()) {
1280       errs() << "BOLT-WARNING: function " << *TargetFunction
1281              << " has an object detected in a padding region at address 0x"
1282              << Twine::utohexstr(Address) << '\n';
1283       TargetFunction->setMaxSize(TargetFunction->getSize());
1284     }
1285   }
1286 
1287   InterproceduralReferences.clear();
1288 }
1289 
1290 void BinaryContext::postProcessSymbolTable() {
1291   fixBinaryDataHoles();
1292   bool Valid = true;
1293   for (auto &Entry : BinaryDataMap) {
1294     BinaryData *BD = Entry.second;
1295     if ((BD->getName().startswith("SYMBOLat") ||
1296          BD->getName().startswith("DATAat")) &&
1297         !BD->getParent() && !BD->getSize() && !BD->isAbsolute() &&
1298         BD->getSection()) {
1299       errs() << "BOLT-WARNING: zero-sized top level symbol: " << *BD << "\n";
1300       Valid = false;
1301     }
1302   }
1303   assert(Valid);
1304   (void)Valid;
1305   generateSymbolHashes();
1306 }
1307 
1308 void BinaryContext::foldFunction(BinaryFunction &ChildBF,
1309                                  BinaryFunction &ParentBF) {
1310   assert(!ChildBF.isMultiEntry() && !ParentBF.isMultiEntry() &&
1311          "cannot merge functions with multiple entry points");
1312 
1313   std::unique_lock<llvm::sys::RWMutex> WriteCtxLock(CtxMutex, std::defer_lock);
1314   std::unique_lock<llvm::sys::RWMutex> WriteSymbolMapLock(
1315       SymbolToFunctionMapMutex, std::defer_lock);
1316 
1317   const StringRef ChildName = ChildBF.getOneName();
1318 
1319   // Move symbols over and update bookkeeping info.
1320   for (MCSymbol *Symbol : ChildBF.getSymbols()) {
1321     ParentBF.getSymbols().push_back(Symbol);
1322     WriteSymbolMapLock.lock();
1323     SymbolToFunctionMap[Symbol] = &ParentBF;
1324     WriteSymbolMapLock.unlock();
1325     // NB: there's no need to update BinaryDataMap and GlobalSymbols.
1326   }
1327   ChildBF.getSymbols().clear();
1328 
1329   // Move other names the child function is known under.
1330   llvm::move(ChildBF.Aliases, std::back_inserter(ParentBF.Aliases));
1331   ChildBF.Aliases.clear();
1332 
1333   if (HasRelocations) {
1334     // Merge execution counts of ChildBF into those of ParentBF.
1335     // Without relocations, we cannot reliably merge profiles as both functions
1336     // continue to exist and either one can be executed.
1337     ChildBF.mergeProfileDataInto(ParentBF);
1338 
1339     std::shared_lock<llvm::sys::RWMutex> ReadBfsLock(BinaryFunctionsMutex,
1340                                                      std::defer_lock);
1341     std::unique_lock<llvm::sys::RWMutex> WriteBfsLock(BinaryFunctionsMutex,
1342                                                       std::defer_lock);
1343     // Remove ChildBF from the global set of functions in relocs mode.
1344     ReadBfsLock.lock();
1345     auto FI = BinaryFunctions.find(ChildBF.getAddress());
1346     ReadBfsLock.unlock();
1347 
1348     assert(FI != BinaryFunctions.end() && "function not found");
1349     assert(&ChildBF == &FI->second && "function mismatch");
1350 
1351     WriteBfsLock.lock();
1352     ChildBF.clearDisasmState();
1353     FI = BinaryFunctions.erase(FI);
1354     WriteBfsLock.unlock();
1355 
1356   } else {
1357     // In non-relocation mode we keep the function, but rename it.
1358     std::string NewName = "__ICF_" + ChildName.str();
1359 
1360     WriteCtxLock.lock();
1361     ChildBF.getSymbols().push_back(Ctx->getOrCreateSymbol(NewName));
1362     WriteCtxLock.unlock();
1363 
1364     ChildBF.setFolded(&ParentBF);
1365   }
1366 
1367   ParentBF.setHasFunctionsFoldedInto();
1368 }
1369 
1370 void BinaryContext::fixBinaryDataHoles() {
1371   assert(validateObjectNesting() && "object nesting inconsitency detected");
1372 
1373   for (BinarySection &Section : allocatableSections()) {
1374     std::vector<std::pair<uint64_t, uint64_t>> Holes;
1375 
1376     auto isNotHole = [&Section](const binary_data_iterator &Itr) {
1377       BinaryData *BD = Itr->second;
1378       bool isHole = (!BD->getParent() && !BD->getSize() && BD->isObject() &&
1379                      (BD->getName().startswith("SYMBOLat0x") ||
1380                       BD->getName().startswith("DATAat0x") ||
1381                       BD->getName().startswith("ANONYMOUS")));
1382       return !isHole && BD->getSection() == Section && !BD->getParent();
1383     };
1384 
1385     auto BDStart = BinaryDataMap.begin();
1386     auto BDEnd = BinaryDataMap.end();
1387     auto Itr = FilteredBinaryDataIterator(isNotHole, BDStart, BDEnd);
1388     auto End = FilteredBinaryDataIterator(isNotHole, BDEnd, BDEnd);
1389 
1390     uint64_t EndAddress = Section.getAddress();
1391 
1392     while (Itr != End) {
1393       if (Itr->second->getAddress() > EndAddress) {
1394         uint64_t Gap = Itr->second->getAddress() - EndAddress;
1395         Holes.emplace_back(EndAddress, Gap);
1396       }
1397       EndAddress = Itr->second->getEndAddress();
1398       ++Itr;
1399     }
1400 
1401     if (EndAddress < Section.getEndAddress())
1402       Holes.emplace_back(EndAddress, Section.getEndAddress() - EndAddress);
1403 
1404     // If there is already a symbol at the start of the hole, grow that symbol
1405     // to cover the rest.  Otherwise, create a new symbol to cover the hole.
1406     for (std::pair<uint64_t, uint64_t> &Hole : Holes) {
1407       BinaryData *BD = getBinaryDataAtAddress(Hole.first);
1408       if (BD) {
1409         // BD->getSection() can be != Section if there are sections that
1410         // overlap.  In this case it is probably safe to just skip the holes
1411         // since the overlapping section will not(?) have any symbols in it.
1412         if (BD->getSection() == Section)
1413           setBinaryDataSize(Hole.first, Hole.second);
1414       } else {
1415         getOrCreateGlobalSymbol(Hole.first, "HOLEat", Hole.second, 1);
1416       }
1417     }
1418   }
1419 
1420   assert(validateObjectNesting() && "object nesting inconsitency detected");
1421   assert(validateHoles() && "top level hole detected in object map");
1422 }
1423 
1424 void BinaryContext::printGlobalSymbols(raw_ostream &OS) const {
1425   const BinarySection *CurrentSection = nullptr;
1426   bool FirstSection = true;
1427 
1428   for (auto &Entry : BinaryDataMap) {
1429     const BinaryData *BD = Entry.second;
1430     const BinarySection &Section = BD->getSection();
1431     if (FirstSection || Section != *CurrentSection) {
1432       uint64_t Address, Size;
1433       StringRef Name = Section.getName();
1434       if (Section) {
1435         Address = Section.getAddress();
1436         Size = Section.getSize();
1437       } else {
1438         Address = BD->getAddress();
1439         Size = BD->getSize();
1440       }
1441       OS << "BOLT-INFO: Section " << Name << ", "
1442          << "0x" + Twine::utohexstr(Address) << ":"
1443          << "0x" + Twine::utohexstr(Address + Size) << "/" << Size << "\n";
1444       CurrentSection = &Section;
1445       FirstSection = false;
1446     }
1447 
1448     OS << "BOLT-INFO: ";
1449     const BinaryData *P = BD->getParent();
1450     while (P) {
1451       OS << "  ";
1452       P = P->getParent();
1453     }
1454     OS << *BD << "\n";
1455   }
1456 }
1457 
1458 Expected<unsigned> BinaryContext::getDwarfFile(
1459     StringRef Directory, StringRef FileName, unsigned FileNumber,
1460     std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1461     unsigned CUID, unsigned DWARFVersion) {
1462   DwarfLineTable &Table = DwarfLineTablesCUMap[CUID];
1463   return Table.tryGetFile(Directory, FileName, Checksum, Source, DWARFVersion,
1464                           FileNumber);
1465 }
1466 
1467 unsigned BinaryContext::addDebugFilenameToUnit(const uint32_t DestCUID,
1468                                                const uint32_t SrcCUID,
1469                                                unsigned FileIndex) {
1470   DWARFCompileUnit *SrcUnit = DwCtx->getCompileUnitForOffset(SrcCUID);
1471   const DWARFDebugLine::LineTable *LineTable =
1472       DwCtx->getLineTableForUnit(SrcUnit);
1473   const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1474       LineTable->Prologue.FileNames;
1475   // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1476   // means empty dir.
1477   assert(FileIndex > 0 && FileIndex <= FileNames.size() &&
1478          "FileIndex out of range for the compilation unit.");
1479   StringRef Dir = "";
1480   if (FileNames[FileIndex - 1].DirIdx != 0) {
1481     if (std::optional<const char *> DirName = dwarf::toString(
1482             LineTable->Prologue
1483                 .IncludeDirectories[FileNames[FileIndex - 1].DirIdx - 1])) {
1484       Dir = *DirName;
1485     }
1486   }
1487   StringRef FileName = "";
1488   if (std::optional<const char *> FName =
1489           dwarf::toString(FileNames[FileIndex - 1].Name))
1490     FileName = *FName;
1491   assert(FileName != "");
1492   DWARFCompileUnit *DstUnit = DwCtx->getCompileUnitForOffset(DestCUID);
1493   return cantFail(getDwarfFile(Dir, FileName, 0, std::nullopt, std::nullopt,
1494                                DestCUID, DstUnit->getVersion()));
1495 }
1496 
1497 std::vector<BinaryFunction *> BinaryContext::getSortedFunctions() {
1498   std::vector<BinaryFunction *> SortedFunctions(BinaryFunctions.size());
1499   llvm::transform(llvm::make_second_range(BinaryFunctions),
1500                   SortedFunctions.begin(),
1501                   [](BinaryFunction &BF) { return &BF; });
1502 
1503   llvm::stable_sort(SortedFunctions,
1504                     [](const BinaryFunction *A, const BinaryFunction *B) {
1505                       if (A->hasValidIndex() && B->hasValidIndex()) {
1506                         return A->getIndex() < B->getIndex();
1507                       }
1508                       return A->hasValidIndex();
1509                     });
1510   return SortedFunctions;
1511 }
1512 
1513 std::vector<BinaryFunction *> BinaryContext::getAllBinaryFunctions() {
1514   std::vector<BinaryFunction *> AllFunctions;
1515   AllFunctions.reserve(BinaryFunctions.size() + InjectedBinaryFunctions.size());
1516   llvm::transform(llvm::make_second_range(BinaryFunctions),
1517                   std::back_inserter(AllFunctions),
1518                   [](BinaryFunction &BF) { return &BF; });
1519   llvm::copy(InjectedBinaryFunctions, std::back_inserter(AllFunctions));
1520 
1521   return AllFunctions;
1522 }
1523 
1524 std::optional<DWARFUnit *> BinaryContext::getDWOCU(uint64_t DWOId) {
1525   auto Iter = DWOCUs.find(DWOId);
1526   if (Iter == DWOCUs.end())
1527     return std::nullopt;
1528 
1529   return Iter->second;
1530 }
1531 
1532 DWARFContext *BinaryContext::getDWOContext() const {
1533   if (DWOCUs.empty())
1534     return nullptr;
1535   return &DWOCUs.begin()->second->getContext();
1536 }
1537 
1538 /// Handles DWO sections that can either be in .o, .dwo or .dwp files.
1539 void BinaryContext::preprocessDWODebugInfo() {
1540   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1541     DWARFUnit *const DwarfUnit = CU.get();
1542     if (std::optional<uint64_t> DWOId = DwarfUnit->getDWOId()) {
1543       DWARFUnit *DWOCU = DwarfUnit->getNonSkeletonUnitDIE(false).getDwarfUnit();
1544       if (!DWOCU->isDWOUnit()) {
1545         std::string DWOName = dwarf::toString(
1546             DwarfUnit->getUnitDIE().find(
1547                 {dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
1548             "");
1549         outs() << "BOLT-WARNING: Debug Fission: DWO debug information for "
1550                << DWOName
1551                << " was not retrieved and won't be updated. Please check "
1552                   "relative path.\n";
1553         continue;
1554       }
1555       DWOCUs[*DWOId] = DWOCU;
1556     }
1557   }
1558   if (!DWOCUs.empty())
1559     outs() << "BOLT-INFO: processing split DWARF\n";
1560 }
1561 
1562 void BinaryContext::preprocessDebugInfo() {
1563   struct CURange {
1564     uint64_t LowPC;
1565     uint64_t HighPC;
1566     DWARFUnit *Unit;
1567 
1568     bool operator<(const CURange &Other) const { return LowPC < Other.LowPC; }
1569   };
1570 
1571   // Building a map of address ranges to CUs similar to .debug_aranges and use
1572   // it to assign CU to functions.
1573   std::vector<CURange> AllRanges;
1574   AllRanges.reserve(DwCtx->getNumCompileUnits());
1575   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1576     Expected<DWARFAddressRangesVector> RangesOrError =
1577         CU->getUnitDIE().getAddressRanges();
1578     if (!RangesOrError) {
1579       consumeError(RangesOrError.takeError());
1580       continue;
1581     }
1582     for (DWARFAddressRange &Range : *RangesOrError) {
1583       // Parts of the debug info could be invalidated due to corresponding code
1584       // being removed from the binary by the linker. Hence we check if the
1585       // address is a valid one.
1586       if (containsAddress(Range.LowPC))
1587         AllRanges.emplace_back(CURange{Range.LowPC, Range.HighPC, CU.get()});
1588     }
1589 
1590     ContainsDwarf5 |= CU->getVersion() >= 5;
1591     ContainsDwarfLegacy |= CU->getVersion() < 5;
1592   }
1593 
1594   llvm::sort(AllRanges);
1595   for (auto &KV : BinaryFunctions) {
1596     const uint64_t FunctionAddress = KV.first;
1597     BinaryFunction &Function = KV.second;
1598 
1599     auto It = llvm::partition_point(
1600         AllRanges, [=](CURange R) { return R.HighPC <= FunctionAddress; });
1601     if (It != AllRanges.end() && It->LowPC <= FunctionAddress)
1602       Function.setDWARFUnit(It->Unit);
1603   }
1604 
1605   // Discover units with debug info that needs to be updated.
1606   for (const auto &KV : BinaryFunctions) {
1607     const BinaryFunction &BF = KV.second;
1608     if (shouldEmit(BF) && BF.getDWARFUnit())
1609       ProcessedCUs.insert(BF.getDWARFUnit());
1610   }
1611 
1612   // Clear debug info for functions from units that we are not going to process.
1613   for (auto &KV : BinaryFunctions) {
1614     BinaryFunction &BF = KV.second;
1615     if (BF.getDWARFUnit() && !ProcessedCUs.count(BF.getDWARFUnit()))
1616       BF.setDWARFUnit(nullptr);
1617   }
1618 
1619   if (opts::Verbosity >= 1) {
1620     outs() << "BOLT-INFO: " << ProcessedCUs.size() << " out of "
1621            << DwCtx->getNumCompileUnits() << " CUs will be updated\n";
1622   }
1623 
1624   preprocessDWODebugInfo();
1625 
1626   // Populate MCContext with DWARF files from all units.
1627   StringRef GlobalPrefix = AsmInfo->getPrivateGlobalPrefix();
1628   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1629     const uint64_t CUID = CU->getOffset();
1630     DwarfLineTable &BinaryLineTable = getDwarfLineTable(CUID);
1631     BinaryLineTable.setLabel(Ctx->getOrCreateSymbol(
1632         GlobalPrefix + "line_table_start" + Twine(CUID)));
1633 
1634     if (!ProcessedCUs.count(CU.get()))
1635       continue;
1636 
1637     const DWARFDebugLine::LineTable *LineTable =
1638         DwCtx->getLineTableForUnit(CU.get());
1639     const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1640         LineTable->Prologue.FileNames;
1641 
1642     uint16_t DwarfVersion = LineTable->Prologue.getVersion();
1643     if (DwarfVersion >= 5) {
1644       std::optional<MD5::MD5Result> Checksum;
1645       if (LineTable->Prologue.ContentTypes.HasMD5)
1646         Checksum = LineTable->Prologue.FileNames[0].Checksum;
1647       std::optional<const char *> Name =
1648           dwarf::toString(CU->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1649       if (std::optional<uint64_t> DWOID = CU->getDWOId()) {
1650         auto Iter = DWOCUs.find(*DWOID);
1651         assert(Iter != DWOCUs.end() && "DWO CU was not found.");
1652         Name = dwarf::toString(
1653             Iter->second->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1654       }
1655       BinaryLineTable.setRootFile(CU->getCompilationDir(), *Name, Checksum,
1656                                   std::nullopt);
1657     }
1658 
1659     BinaryLineTable.setDwarfVersion(DwarfVersion);
1660 
1661     // Assign a unique label to every line table, one per CU.
1662     // Make sure empty debug line tables are registered too.
1663     if (FileNames.empty()) {
1664       cantFail(getDwarfFile("", "<unknown>", 0, std::nullopt, std::nullopt,
1665                             CUID, DwarfVersion));
1666       continue;
1667     }
1668     const uint32_t Offset = DwarfVersion < 5 ? 1 : 0;
1669     for (size_t I = 0, Size = FileNames.size(); I != Size; ++I) {
1670       // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1671       // means empty dir.
1672       StringRef Dir = "";
1673       if (FileNames[I].DirIdx != 0 || DwarfVersion >= 5)
1674         if (std::optional<const char *> DirName = dwarf::toString(
1675                 LineTable->Prologue
1676                     .IncludeDirectories[FileNames[I].DirIdx - Offset]))
1677           Dir = *DirName;
1678       StringRef FileName = "";
1679       if (std::optional<const char *> FName =
1680               dwarf::toString(FileNames[I].Name))
1681         FileName = *FName;
1682       assert(FileName != "");
1683       std::optional<MD5::MD5Result> Checksum;
1684       if (DwarfVersion >= 5 && LineTable->Prologue.ContentTypes.HasMD5)
1685         Checksum = LineTable->Prologue.FileNames[I].Checksum;
1686       cantFail(getDwarfFile(Dir, FileName, 0, Checksum, std::nullopt, CUID,
1687                             DwarfVersion));
1688     }
1689   }
1690 }
1691 
1692 bool BinaryContext::shouldEmit(const BinaryFunction &Function) const {
1693   if (Function.isPseudo())
1694     return false;
1695 
1696   if (opts::processAllFunctions())
1697     return true;
1698 
1699   if (Function.isIgnored())
1700     return false;
1701 
1702   // In relocation mode we will emit non-simple functions with CFG.
1703   // If the function does not have a CFG it should be marked as ignored.
1704   return HasRelocations || Function.isSimple();
1705 }
1706 
1707 void BinaryContext::printCFI(raw_ostream &OS, const MCCFIInstruction &Inst) {
1708   uint32_t Operation = Inst.getOperation();
1709   switch (Operation) {
1710   case MCCFIInstruction::OpSameValue:
1711     OS << "OpSameValue Reg" << Inst.getRegister();
1712     break;
1713   case MCCFIInstruction::OpRememberState:
1714     OS << "OpRememberState";
1715     break;
1716   case MCCFIInstruction::OpRestoreState:
1717     OS << "OpRestoreState";
1718     break;
1719   case MCCFIInstruction::OpOffset:
1720     OS << "OpOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1721     break;
1722   case MCCFIInstruction::OpDefCfaRegister:
1723     OS << "OpDefCfaRegister Reg" << Inst.getRegister();
1724     break;
1725   case MCCFIInstruction::OpDefCfaOffset:
1726     OS << "OpDefCfaOffset " << Inst.getOffset();
1727     break;
1728   case MCCFIInstruction::OpDefCfa:
1729     OS << "OpDefCfa Reg" << Inst.getRegister() << " " << Inst.getOffset();
1730     break;
1731   case MCCFIInstruction::OpRelOffset:
1732     OS << "OpRelOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1733     break;
1734   case MCCFIInstruction::OpAdjustCfaOffset:
1735     OS << "OfAdjustCfaOffset " << Inst.getOffset();
1736     break;
1737   case MCCFIInstruction::OpEscape:
1738     OS << "OpEscape";
1739     break;
1740   case MCCFIInstruction::OpRestore:
1741     OS << "OpRestore Reg" << Inst.getRegister();
1742     break;
1743   case MCCFIInstruction::OpUndefined:
1744     OS << "OpUndefined Reg" << Inst.getRegister();
1745     break;
1746   case MCCFIInstruction::OpRegister:
1747     OS << "OpRegister Reg" << Inst.getRegister() << " Reg"
1748        << Inst.getRegister2();
1749     break;
1750   case MCCFIInstruction::OpWindowSave:
1751     OS << "OpWindowSave";
1752     break;
1753   case MCCFIInstruction::OpGnuArgsSize:
1754     OS << "OpGnuArgsSize";
1755     break;
1756   default:
1757     OS << "Op#" << Operation;
1758     break;
1759   }
1760 }
1761 
1762 MarkerSymType BinaryContext::getMarkerType(const SymbolRef &Symbol) const {
1763   // For aarch64, the ABI defines mapping symbols so we identify data in the
1764   // code section (see IHI0056B). $x identifies a symbol starting code or the
1765   // end of a data chunk inside code, $d indentifies start of data.
1766   if (!isAArch64() || ELFSymbolRef(Symbol).getSize())
1767     return MarkerSymType::NONE;
1768 
1769   Expected<StringRef> NameOrError = Symbol.getName();
1770   Expected<object::SymbolRef::Type> TypeOrError = Symbol.getType();
1771 
1772   if (!TypeOrError || !NameOrError)
1773     return MarkerSymType::NONE;
1774 
1775   if (*TypeOrError != SymbolRef::ST_Unknown)
1776     return MarkerSymType::NONE;
1777 
1778   if (*NameOrError == "$x" || NameOrError->startswith("$x."))
1779     return MarkerSymType::CODE;
1780 
1781   if (*NameOrError == "$d" || NameOrError->startswith("$d."))
1782     return MarkerSymType::DATA;
1783 
1784   return MarkerSymType::NONE;
1785 }
1786 
1787 bool BinaryContext::isMarker(const SymbolRef &Symbol) const {
1788   return getMarkerType(Symbol) != MarkerSymType::NONE;
1789 }
1790 
1791 static void printDebugInfo(raw_ostream &OS, const MCInst &Instruction,
1792                            const BinaryFunction *Function,
1793                            DWARFContext *DwCtx) {
1794   DebugLineTableRowRef RowRef =
1795       DebugLineTableRowRef::fromSMLoc(Instruction.getLoc());
1796   if (RowRef == DebugLineTableRowRef::NULL_ROW)
1797     return;
1798 
1799   const DWARFDebugLine::LineTable *LineTable;
1800   if (Function && Function->getDWARFUnit() &&
1801       Function->getDWARFUnit()->getOffset() == RowRef.DwCompileUnitIndex) {
1802     LineTable = Function->getDWARFLineTable();
1803   } else {
1804     LineTable = DwCtx->getLineTableForUnit(
1805         DwCtx->getCompileUnitForOffset(RowRef.DwCompileUnitIndex));
1806   }
1807   assert(LineTable && "line table expected for instruction with debug info");
1808 
1809   const DWARFDebugLine::Row &Row = LineTable->Rows[RowRef.RowIndex - 1];
1810   StringRef FileName = "";
1811   if (std::optional<const char *> FName =
1812           dwarf::toString(LineTable->Prologue.FileNames[Row.File - 1].Name))
1813     FileName = *FName;
1814   OS << " # debug line " << FileName << ":" << Row.Line;
1815   if (Row.Column)
1816     OS << ":" << Row.Column;
1817   if (Row.Discriminator)
1818     OS << " discriminator:" << Row.Discriminator;
1819 }
1820 
1821 void BinaryContext::printInstruction(raw_ostream &OS, const MCInst &Instruction,
1822                                      uint64_t Offset,
1823                                      const BinaryFunction *Function,
1824                                      bool PrintMCInst, bool PrintMemData,
1825                                      bool PrintRelocations,
1826                                      StringRef Endl) const {
1827   if (MIB->isEHLabel(Instruction)) {
1828     OS << "  EH_LABEL: " << *MIB->getTargetSymbol(Instruction) << Endl;
1829     return;
1830   }
1831   OS << format("    %08" PRIx64 ": ", Offset);
1832   if (MIB->isCFI(Instruction)) {
1833     uint32_t Offset = Instruction.getOperand(0).getImm();
1834     OS << "\t!CFI\t$" << Offset << "\t; ";
1835     if (Function)
1836       printCFI(OS, *Function->getCFIFor(Instruction));
1837     OS << Endl;
1838     return;
1839   }
1840   InstPrinter->printInst(&Instruction, 0, "", *STI, OS);
1841   if (MIB->isCall(Instruction)) {
1842     if (MIB->isTailCall(Instruction))
1843       OS << " # TAILCALL ";
1844     if (MIB->isInvoke(Instruction)) {
1845       const std::optional<MCPlus::MCLandingPad> EHInfo =
1846           MIB->getEHInfo(Instruction);
1847       OS << " # handler: ";
1848       if (EHInfo->first)
1849         OS << *EHInfo->first;
1850       else
1851         OS << '0';
1852       OS << "; action: " << EHInfo->second;
1853       const int64_t GnuArgsSize = MIB->getGnuArgsSize(Instruction);
1854       if (GnuArgsSize >= 0)
1855         OS << "; GNU_args_size = " << GnuArgsSize;
1856     }
1857   } else if (MIB->isIndirectBranch(Instruction)) {
1858     if (uint64_t JTAddress = MIB->getJumpTable(Instruction)) {
1859       OS << " # JUMPTABLE @0x" << Twine::utohexstr(JTAddress);
1860     } else {
1861       OS << " # UNKNOWN CONTROL FLOW";
1862     }
1863   }
1864   if (std::optional<uint32_t> Offset = MIB->getOffset(Instruction))
1865     OS << " # Offset: " << *Offset;
1866 
1867   MIB->printAnnotations(Instruction, OS);
1868 
1869   if (opts::PrintDebugInfo)
1870     printDebugInfo(OS, Instruction, Function, DwCtx.get());
1871 
1872   if ((opts::PrintRelocations || PrintRelocations) && Function) {
1873     const uint64_t Size = computeCodeSize(&Instruction, &Instruction + 1);
1874     Function->printRelocations(OS, Offset, Size);
1875   }
1876 
1877   OS << Endl;
1878 
1879   if (PrintMCInst) {
1880     Instruction.dump_pretty(OS, InstPrinter.get());
1881     OS << Endl;
1882   }
1883 }
1884 
1885 std::optional<uint64_t>
1886 BinaryContext::getBaseAddressForMapping(uint64_t MMapAddress,
1887                                         uint64_t FileOffset) const {
1888   // Find a segment with a matching file offset.
1889   for (auto &KV : SegmentMapInfo) {
1890     const SegmentInfo &SegInfo = KV.second;
1891     if (alignDown(SegInfo.FileOffset, SegInfo.Alignment) == FileOffset) {
1892       // Use segment's aligned memory offset to calculate the base address.
1893       const uint64_t MemOffset = alignDown(SegInfo.Address, SegInfo.Alignment);
1894       return MMapAddress - MemOffset;
1895     }
1896   }
1897 
1898   return std::nullopt;
1899 }
1900 
1901 ErrorOr<BinarySection &> BinaryContext::getSectionForAddress(uint64_t Address) {
1902   auto SI = AddressToSection.upper_bound(Address);
1903   if (SI != AddressToSection.begin()) {
1904     --SI;
1905     uint64_t UpperBound = SI->first + SI->second->getSize();
1906     if (!SI->second->getSize())
1907       UpperBound += 1;
1908     if (UpperBound > Address)
1909       return *SI->second;
1910   }
1911   return std::make_error_code(std::errc::bad_address);
1912 }
1913 
1914 ErrorOr<StringRef>
1915 BinaryContext::getSectionNameForAddress(uint64_t Address) const {
1916   if (ErrorOr<const BinarySection &> Section = getSectionForAddress(Address))
1917     return Section->getName();
1918   return std::make_error_code(std::errc::bad_address);
1919 }
1920 
1921 BinarySection &BinaryContext::registerSection(BinarySection *Section) {
1922   auto Res = Sections.insert(Section);
1923   (void)Res;
1924   assert(Res.second && "can't register the same section twice.");
1925 
1926   // Only register allocatable sections in the AddressToSection map.
1927   if (Section->isAllocatable() && Section->getAddress())
1928     AddressToSection.insert(std::make_pair(Section->getAddress(), Section));
1929   NameToSection.insert(
1930       std::make_pair(std::string(Section->getName()), Section));
1931   if (Section->hasSectionRef())
1932     SectionRefToBinarySection.insert(
1933         std::make_pair(Section->getSectionRef(), Section));
1934 
1935   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: registering " << *Section << "\n");
1936   return *Section;
1937 }
1938 
1939 BinarySection &BinaryContext::registerSection(SectionRef Section) {
1940   return registerSection(new BinarySection(*this, Section));
1941 }
1942 
1943 BinarySection &
1944 BinaryContext::registerSection(const Twine &SectionName,
1945                                const BinarySection &OriginalSection) {
1946   return registerSection(
1947       new BinarySection(*this, SectionName, OriginalSection));
1948 }
1949 
1950 BinarySection &
1951 BinaryContext::registerOrUpdateSection(const Twine &Name, unsigned ELFType,
1952                                        unsigned ELFFlags, uint8_t *Data,
1953                                        uint64_t Size, unsigned Alignment) {
1954   auto NamedSections = getSectionByName(Name);
1955   if (NamedSections.begin() != NamedSections.end()) {
1956     assert(std::next(NamedSections.begin()) == NamedSections.end() &&
1957            "can only update unique sections");
1958     BinarySection *Section = NamedSections.begin()->second;
1959 
1960     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: updating " << *Section << " -> ");
1961     const bool Flag = Section->isAllocatable();
1962     (void)Flag;
1963     Section->update(Data, Size, Alignment, ELFType, ELFFlags);
1964     LLVM_DEBUG(dbgs() << *Section << "\n");
1965     // FIXME: Fix section flags/attributes for MachO.
1966     if (isELF())
1967       assert(Flag == Section->isAllocatable() &&
1968              "can't change section allocation status");
1969     return *Section;
1970   }
1971 
1972   return registerSection(
1973       new BinarySection(*this, Name, Data, Size, Alignment, ELFType, ELFFlags));
1974 }
1975 
1976 void BinaryContext::deregisterSectionName(const BinarySection &Section) {
1977   auto NameRange = NameToSection.equal_range(Section.getName().str());
1978   while (NameRange.first != NameRange.second) {
1979     if (NameRange.first->second == &Section) {
1980       NameToSection.erase(NameRange.first);
1981       break;
1982     }
1983     ++NameRange.first;
1984   }
1985 }
1986 
1987 void BinaryContext::deregisterUnusedSections() {
1988   ErrorOr<BinarySection &> AbsSection = getUniqueSectionByName("<absolute>");
1989   for (auto SI = Sections.begin(); SI != Sections.end();) {
1990     BinarySection *Section = *SI;
1991     // We check getOutputData() instead of getOutputSize() because sometimes
1992     // zero-sized .text.cold sections are allocated.
1993     if (Section->hasSectionRef() || Section->getOutputData() ||
1994         (AbsSection && Section == &AbsSection.get())) {
1995       ++SI;
1996       continue;
1997     }
1998 
1999     LLVM_DEBUG(dbgs() << "LLVM-DEBUG: deregistering " << Section->getName()
2000                       << '\n';);
2001     deregisterSectionName(*Section);
2002     SI = Sections.erase(SI);
2003     delete Section;
2004   }
2005 }
2006 
2007 bool BinaryContext::deregisterSection(BinarySection &Section) {
2008   BinarySection *SectionPtr = &Section;
2009   auto Itr = Sections.find(SectionPtr);
2010   if (Itr != Sections.end()) {
2011     auto Range = AddressToSection.equal_range(SectionPtr->getAddress());
2012     while (Range.first != Range.second) {
2013       if (Range.first->second == SectionPtr) {
2014         AddressToSection.erase(Range.first);
2015         break;
2016       }
2017       ++Range.first;
2018     }
2019 
2020     deregisterSectionName(*SectionPtr);
2021     Sections.erase(Itr);
2022     delete SectionPtr;
2023     return true;
2024   }
2025   return false;
2026 }
2027 
2028 void BinaryContext::renameSection(BinarySection &Section,
2029                                   const Twine &NewName) {
2030   auto Itr = Sections.find(&Section);
2031   assert(Itr != Sections.end() && "Section must exist to be renamed.");
2032   Sections.erase(Itr);
2033 
2034   deregisterSectionName(Section);
2035 
2036   Section.Name = NewName.str();
2037   Section.setOutputName(Section.Name);
2038 
2039   NameToSection.insert(std::make_pair(Section.Name, &Section));
2040 
2041   // Reinsert with the new name.
2042   Sections.insert(&Section);
2043 }
2044 
2045 void BinaryContext::printSections(raw_ostream &OS) const {
2046   for (BinarySection *const &Section : Sections)
2047     OS << "BOLT-INFO: " << *Section << "\n";
2048 }
2049 
2050 BinarySection &BinaryContext::absoluteSection() {
2051   if (ErrorOr<BinarySection &> Section = getUniqueSectionByName("<absolute>"))
2052     return *Section;
2053   return registerOrUpdateSection("<absolute>", ELF::SHT_NULL, 0u);
2054 }
2055 
2056 ErrorOr<uint64_t> BinaryContext::getUnsignedValueAtAddress(uint64_t Address,
2057                                                            size_t Size) const {
2058   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2059   if (!Section)
2060     return std::make_error_code(std::errc::bad_address);
2061 
2062   if (Section->isVirtual())
2063     return 0;
2064 
2065   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
2066                    AsmInfo->getCodePointerSize());
2067   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
2068   return DE.getUnsigned(&ValueOffset, Size);
2069 }
2070 
2071 ErrorOr<uint64_t> BinaryContext::getSignedValueAtAddress(uint64_t Address,
2072                                                          size_t Size) const {
2073   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2074   if (!Section)
2075     return std::make_error_code(std::errc::bad_address);
2076 
2077   if (Section->isVirtual())
2078     return 0;
2079 
2080   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
2081                    AsmInfo->getCodePointerSize());
2082   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
2083   return DE.getSigned(&ValueOffset, Size);
2084 }
2085 
2086 void BinaryContext::addRelocation(uint64_t Address, MCSymbol *Symbol,
2087                                   uint64_t Type, uint64_t Addend,
2088                                   uint64_t Value) {
2089   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2090   assert(Section && "cannot find section for address");
2091   Section->addRelocation(Address - Section->getAddress(), Symbol, Type, Addend,
2092                          Value);
2093 }
2094 
2095 void BinaryContext::addDynamicRelocation(uint64_t Address, MCSymbol *Symbol,
2096                                          uint64_t Type, uint64_t Addend,
2097                                          uint64_t Value) {
2098   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2099   assert(Section && "cannot find section for address");
2100   Section->addDynamicRelocation(Address - Section->getAddress(), Symbol, Type,
2101                                 Addend, Value);
2102 }
2103 
2104 bool BinaryContext::removeRelocationAt(uint64_t Address) {
2105   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2106   assert(Section && "cannot find section for address");
2107   return Section->removeRelocationAt(Address - Section->getAddress());
2108 }
2109 
2110 const Relocation *BinaryContext::getRelocationAt(uint64_t Address) const {
2111   ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2112   if (!Section)
2113     return nullptr;
2114 
2115   return Section->getRelocationAt(Address - Section->getAddress());
2116 }
2117 
2118 const Relocation *
2119 BinaryContext::getDynamicRelocationAt(uint64_t Address) const {
2120   ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2121   if (!Section)
2122     return nullptr;
2123 
2124   return Section->getDynamicRelocationAt(Address - Section->getAddress());
2125 }
2126 
2127 void BinaryContext::markAmbiguousRelocations(BinaryData &BD,
2128                                              const uint64_t Address) {
2129   auto setImmovable = [&](BinaryData &BD) {
2130     BinaryData *Root = BD.getAtomicRoot();
2131     LLVM_DEBUG(if (Root->isMoveable()) {
2132       dbgs() << "BOLT-DEBUG: setting " << *Root << " as immovable "
2133              << "due to ambiguous relocation referencing 0x"
2134              << Twine::utohexstr(Address) << '\n';
2135     });
2136     Root->setIsMoveable(false);
2137   };
2138 
2139   if (Address == BD.getAddress()) {
2140     setImmovable(BD);
2141 
2142     // Set previous symbol as immovable
2143     BinaryData *Prev = getBinaryDataContainingAddress(Address - 1);
2144     if (Prev && Prev->getEndAddress() == BD.getAddress())
2145       setImmovable(*Prev);
2146   }
2147 
2148   if (Address == BD.getEndAddress()) {
2149     setImmovable(BD);
2150 
2151     // Set next symbol as immovable
2152     BinaryData *Next = getBinaryDataContainingAddress(BD.getEndAddress());
2153     if (Next && Next->getAddress() == BD.getEndAddress())
2154       setImmovable(*Next);
2155   }
2156 }
2157 
2158 BinaryFunction *BinaryContext::getFunctionForSymbol(const MCSymbol *Symbol,
2159                                                     uint64_t *EntryDesc) {
2160   std::shared_lock<llvm::sys::RWMutex> Lock(SymbolToFunctionMapMutex);
2161   auto BFI = SymbolToFunctionMap.find(Symbol);
2162   if (BFI == SymbolToFunctionMap.end())
2163     return nullptr;
2164 
2165   BinaryFunction *BF = BFI->second;
2166   if (EntryDesc)
2167     *EntryDesc = BF->getEntryIDForSymbol(Symbol);
2168 
2169   return BF;
2170 }
2171 
2172 void BinaryContext::exitWithBugReport(StringRef Message,
2173                                       const BinaryFunction &Function) const {
2174   errs() << "=======================================\n";
2175   errs() << "BOLT is unable to proceed because it couldn't properly understand "
2176             "this function.\n";
2177   errs() << "If you are running the most recent version of BOLT, you may "
2178             "want to "
2179             "report this and paste this dump.\nPlease check that there is no "
2180             "sensitive contents being shared in this dump.\n";
2181   errs() << "\nOffending function: " << Function.getPrintName() << "\n\n";
2182   ScopedPrinter SP(errs());
2183   SP.printBinaryBlock("Function contents", *Function.getData());
2184   errs() << "\n";
2185   Function.dump();
2186   errs() << "ERROR: " << Message;
2187   errs() << "\n=======================================\n";
2188   exit(1);
2189 }
2190 
2191 BinaryFunction *
2192 BinaryContext::createInjectedBinaryFunction(const std::string &Name,
2193                                             bool IsSimple) {
2194   InjectedBinaryFunctions.push_back(new BinaryFunction(Name, *this, IsSimple));
2195   BinaryFunction *BF = InjectedBinaryFunctions.back();
2196   setSymbolToFunctionMap(BF->getSymbol(), BF);
2197   BF->CurrentState = BinaryFunction::State::CFG;
2198   return BF;
2199 }
2200 
2201 std::pair<size_t, size_t>
2202 BinaryContext::calculateEmittedSize(BinaryFunction &BF, bool FixBranches) {
2203   // Adjust branch instruction to match the current layout.
2204   if (FixBranches)
2205     BF.fixBranches();
2206 
2207   // Create local MC context to isolate the effect of ephemeral code emission.
2208   IndependentCodeEmitter MCEInstance = createIndependentMCCodeEmitter();
2209   MCContext *LocalCtx = MCEInstance.LocalCtx.get();
2210   MCAsmBackend *MAB =
2211       TheTarget->createMCAsmBackend(*STI, *MRI, MCTargetOptions());
2212 
2213   SmallString<256> Code;
2214   raw_svector_ostream VecOS(Code);
2215 
2216   std::unique_ptr<MCObjectWriter> OW = MAB->createObjectWriter(VecOS);
2217   std::unique_ptr<MCStreamer> Streamer(TheTarget->createMCObjectStreamer(
2218       *TheTriple, *LocalCtx, std::unique_ptr<MCAsmBackend>(MAB), std::move(OW),
2219       std::unique_ptr<MCCodeEmitter>(MCEInstance.MCE.release()), *STI,
2220       /*RelaxAll=*/false,
2221       /*IncrementalLinkerCompatible=*/false,
2222       /*DWARFMustBeAtTheEnd=*/false));
2223 
2224   Streamer->initSections(false, *STI);
2225 
2226   MCSection *Section = MCEInstance.LocalMOFI->getTextSection();
2227   Section->setHasInstructions(true);
2228 
2229   // Create symbols in the LocalCtx so that they get destroyed with it.
2230   MCSymbol *StartLabel = LocalCtx->createTempSymbol();
2231   MCSymbol *EndLabel = LocalCtx->createTempSymbol();
2232 
2233   Streamer->switchSection(Section);
2234   Streamer->emitLabel(StartLabel);
2235   emitFunctionBody(*Streamer, BF, BF.getLayout().getMainFragment(),
2236                    /*EmitCodeOnly=*/true);
2237   Streamer->emitLabel(EndLabel);
2238 
2239   using LabelRange = std::pair<const MCSymbol *, const MCSymbol *>;
2240   SmallVector<LabelRange> SplitLabels;
2241   for (FunctionFragment &FF : BF.getLayout().getSplitFragments()) {
2242     MCSymbol *const SplitStartLabel = LocalCtx->createTempSymbol();
2243     MCSymbol *const SplitEndLabel = LocalCtx->createTempSymbol();
2244     SplitLabels.emplace_back(SplitStartLabel, SplitEndLabel);
2245 
2246     MCSectionELF *const SplitSection = LocalCtx->getELFSection(
2247         BF.getCodeSectionName(FF.getFragmentNum()), ELF::SHT_PROGBITS,
2248         ELF::SHF_EXECINSTR | ELF::SHF_ALLOC);
2249     SplitSection->setHasInstructions(true);
2250     Streamer->switchSection(SplitSection);
2251 
2252     Streamer->emitLabel(SplitStartLabel);
2253     emitFunctionBody(*Streamer, BF, FF, /*EmitCodeOnly=*/true);
2254     Streamer->emitLabel(SplitEndLabel);
2255     // To avoid calling MCObjectStreamer::flushPendingLabels() which is
2256     // private
2257     Streamer->emitBytes(StringRef(""));
2258     Streamer->switchSection(Section);
2259   }
2260 
2261   // To avoid calling MCObjectStreamer::flushPendingLabels() which is private or
2262   // MCStreamer::Finish(), which does more than we want
2263   Streamer->emitBytes(StringRef(""));
2264 
2265   MCAssembler &Assembler =
2266       static_cast<MCObjectStreamer *>(Streamer.get())->getAssembler();
2267   MCAsmLayout Layout(Assembler);
2268   Assembler.layout(Layout);
2269 
2270   const uint64_t HotSize =
2271       Layout.getSymbolOffset(*EndLabel) - Layout.getSymbolOffset(*StartLabel);
2272   const uint64_t ColdSize =
2273       std::accumulate(SplitLabels.begin(), SplitLabels.end(), 0ULL,
2274                       [&](const uint64_t Accu, const LabelRange &Labels) {
2275                         return Accu + Layout.getSymbolOffset(*Labels.second) -
2276                                Layout.getSymbolOffset(*Labels.first);
2277                       });
2278 
2279   // Clean-up the effect of the code emission.
2280   for (const MCSymbol &Symbol : Assembler.symbols()) {
2281     MCSymbol *MutableSymbol = const_cast<MCSymbol *>(&Symbol);
2282     MutableSymbol->setUndefined();
2283     MutableSymbol->setIsRegistered(false);
2284   }
2285 
2286   return std::make_pair(HotSize, ColdSize);
2287 }
2288 
2289 bool BinaryContext::validateInstructionEncoding(
2290     ArrayRef<uint8_t> InputSequence) const {
2291   MCInst Inst;
2292   uint64_t InstSize;
2293   DisAsm->getInstruction(Inst, InstSize, InputSequence, 0, nulls());
2294   assert(InstSize == InputSequence.size() &&
2295          "Disassembled instruction size does not match the sequence.");
2296 
2297   SmallString<256> Code;
2298   SmallVector<MCFixup, 4> Fixups;
2299 
2300   MCE->encodeInstruction(Inst, Code, Fixups, *STI);
2301   auto OutputSequence = ArrayRef<uint8_t>((uint8_t *)Code.data(), Code.size());
2302   if (InputSequence != OutputSequence) {
2303     if (opts::Verbosity > 1) {
2304       errs() << "BOLT-WARNING: mismatched encoding detected\n"
2305              << "      input: " << InputSequence << '\n'
2306              << "     output: " << OutputSequence << '\n';
2307     }
2308     return false;
2309   }
2310 
2311   return true;
2312 }
2313 
2314 uint64_t BinaryContext::getHotThreshold() const {
2315   static uint64_t Threshold = 0;
2316   if (Threshold == 0) {
2317     Threshold = std::max(
2318         (uint64_t)opts::ExecutionCountThreshold,
2319         NumProfiledFuncs ? SumExecutionCount / (2 * NumProfiledFuncs) : 1);
2320   }
2321   return Threshold;
2322 }
2323 
2324 BinaryFunction *BinaryContext::getBinaryFunctionContainingAddress(
2325     uint64_t Address, bool CheckPastEnd, bool UseMaxSize) {
2326   auto FI = BinaryFunctions.upper_bound(Address);
2327   if (FI == BinaryFunctions.begin())
2328     return nullptr;
2329   --FI;
2330 
2331   const uint64_t UsedSize =
2332       UseMaxSize ? FI->second.getMaxSize() : FI->second.getSize();
2333 
2334   if (Address >= FI->first + UsedSize + (CheckPastEnd ? 1 : 0))
2335     return nullptr;
2336 
2337   return &FI->second;
2338 }
2339 
2340 BinaryFunction *BinaryContext::getBinaryFunctionAtAddress(uint64_t Address) {
2341   // First, try to find a function starting at the given address. If the
2342   // function was folded, this will get us the original folded function if it
2343   // wasn't removed from the list, e.g. in non-relocation mode.
2344   auto BFI = BinaryFunctions.find(Address);
2345   if (BFI != BinaryFunctions.end())
2346     return &BFI->second;
2347 
2348   // We might have folded the function matching the object at the given
2349   // address. In such case, we look for a function matching the symbol
2350   // registered at the original address. The new function (the one that the
2351   // original was folded into) will hold the symbol.
2352   if (const BinaryData *BD = getBinaryDataAtAddress(Address)) {
2353     uint64_t EntryID = 0;
2354     BinaryFunction *BF = getFunctionForSymbol(BD->getSymbol(), &EntryID);
2355     if (BF && EntryID == 0)
2356       return BF;
2357   }
2358   return nullptr;
2359 }
2360 
2361 DebugAddressRangesVector BinaryContext::translateModuleAddressRanges(
2362     const DWARFAddressRangesVector &InputRanges) const {
2363   DebugAddressRangesVector OutputRanges;
2364 
2365   for (const DWARFAddressRange Range : InputRanges) {
2366     auto BFI = BinaryFunctions.lower_bound(Range.LowPC);
2367     while (BFI != BinaryFunctions.end()) {
2368       const BinaryFunction &Function = BFI->second;
2369       if (Function.getAddress() >= Range.HighPC)
2370         break;
2371       const DebugAddressRangesVector FunctionRanges =
2372           Function.getOutputAddressRanges();
2373       llvm::move(FunctionRanges, std::back_inserter(OutputRanges));
2374       std::advance(BFI, 1);
2375     }
2376   }
2377 
2378   return OutputRanges;
2379 }
2380 
2381 } // namespace bolt
2382 } // namespace llvm
2383