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