xref: /llvm-project/bolt/lib/Core/BinaryContext.cpp (revision 83ea7ce3a132001dfd7665c7eb50ef44cfd79802)
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     // This simple check arises from the assumption: no more than 2 fragments.
843     if (JT->Parents.size() == 1 && JT->Parents[0] != &Function) {
844       assert(areRelatedFragments(JT->Parents[0], &Function) &&
845              "cannot re-use jump table of a different function");
846       // Duplicate the entry for the parent function for easy access
847       JT->Parents.push_back(&Function);
848       if (opts::Verbosity > 2) {
849         this->outs() << "BOLT-INFO: Multiple fragments access same jump table: "
850                      << JT->Parents[0]->getPrintName() << "; "
851                      << Function.getPrintName() << "\n";
852         JT->print(this->outs());
853       }
854       Function.JumpTables.emplace(Address, JT);
855       JT->Parents[0]->setHasIndirectTargetToSplitFragment(true);
856       JT->Parents[1]->setHasIndirectTargetToSplitFragment(true);
857     }
858 
859     bool IsJumpTableParent = false;
860     (void)IsJumpTableParent;
861     for (BinaryFunction *Frag : JT->Parents)
862       if (Frag == &Function)
863         IsJumpTableParent = true;
864     assert(IsJumpTableParent &&
865            "cannot re-use jump table of a different function");
866     return JT->getFirstLabel();
867   }
868 
869   // Re-use the existing symbol if possible.
870   MCSymbol *JTLabel = nullptr;
871   if (BinaryData *Object = getBinaryDataAtAddress(Address)) {
872     if (!isInternalSymbolName(Object->getSymbol()->getName()))
873       JTLabel = Object->getSymbol();
874   }
875 
876   const uint64_t EntrySize = getJumpTableEntrySize(Type);
877   if (!JTLabel) {
878     const std::string JumpTableName = generateJumpTableName(Function, Address);
879     JTLabel = registerNameAtAddress(JumpTableName, Address, 0, EntrySize);
880   }
881 
882   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: creating jump table " << JTLabel->getName()
883                     << " in function " << Function << '\n');
884 
885   JumpTable *JT = new JumpTable(*JTLabel, Address, EntrySize, Type,
886                                 JumpTable::LabelMapType{{0, JTLabel}},
887                                 *getSectionForAddress(Address));
888   JT->Parents.push_back(&Function);
889   if (opts::Verbosity > 2)
890     JT->print(this->outs());
891   JumpTables.emplace(Address, JT);
892 
893   // Duplicate the entry for the parent function for easy access.
894   Function.JumpTables.emplace(Address, JT);
895   return JTLabel;
896 }
897 
898 std::pair<uint64_t, const MCSymbol *>
899 BinaryContext::duplicateJumpTable(BinaryFunction &Function, JumpTable *JT,
900                                   const MCSymbol *OldLabel) {
901   auto L = scopeLock();
902   unsigned Offset = 0;
903   bool Found = false;
904   for (std::pair<const unsigned, MCSymbol *> Elmt : JT->Labels) {
905     if (Elmt.second != OldLabel)
906       continue;
907     Offset = Elmt.first;
908     Found = true;
909     break;
910   }
911   assert(Found && "Label not found");
912   (void)Found;
913   MCSymbol *NewLabel = Ctx->createNamedTempSymbol("duplicatedJT");
914   JumpTable *NewJT =
915       new JumpTable(*NewLabel, JT->getAddress(), JT->EntrySize, JT->Type,
916                     JumpTable::LabelMapType{{Offset, NewLabel}},
917                     *getSectionForAddress(JT->getAddress()));
918   NewJT->Parents = JT->Parents;
919   NewJT->Entries = JT->Entries;
920   NewJT->Counts = JT->Counts;
921   uint64_t JumpTableID = ++DuplicatedJumpTables;
922   // Invert it to differentiate from regular jump tables whose IDs are their
923   // addresses in the input binary memory space
924   JumpTableID = ~JumpTableID;
925   JumpTables.emplace(JumpTableID, NewJT);
926   Function.JumpTables.emplace(JumpTableID, NewJT);
927   return std::make_pair(JumpTableID, NewLabel);
928 }
929 
930 std::string BinaryContext::generateJumpTableName(const BinaryFunction &BF,
931                                                  uint64_t Address) {
932   size_t Id;
933   uint64_t Offset = 0;
934   if (const JumpTable *JT = BF.getJumpTableContainingAddress(Address)) {
935     Offset = Address - JT->getAddress();
936     auto JTLabelsIt = JT->Labels.find(Offset);
937     if (JTLabelsIt != JT->Labels.end())
938       return std::string(JTLabelsIt->second->getName());
939 
940     auto JTIdsIt = JumpTableIds.find(JT->getAddress());
941     assert(JTIdsIt != JumpTableIds.end());
942     Id = JTIdsIt->second;
943   } else {
944     Id = JumpTableIds[Address] = BF.JumpTables.size();
945   }
946   return ("JUMP_TABLE/" + BF.getOneName().str() + "." + std::to_string(Id) +
947           (Offset ? ("." + std::to_string(Offset)) : ""));
948 }
949 
950 bool BinaryContext::hasValidCodePadding(const BinaryFunction &BF) {
951   // FIXME: aarch64 support is missing.
952   if (!isX86())
953     return true;
954 
955   if (BF.getSize() == BF.getMaxSize())
956     return true;
957 
958   ErrorOr<ArrayRef<unsigned char>> FunctionData = BF.getData();
959   assert(FunctionData && "cannot get function as data");
960 
961   uint64_t Offset = BF.getSize();
962   MCInst Instr;
963   uint64_t InstrSize = 0;
964   uint64_t InstrAddress = BF.getAddress() + Offset;
965   using std::placeholders::_1;
966 
967   // Skip instructions that satisfy the predicate condition.
968   auto skipInstructions = [&](std::function<bool(const MCInst &)> Predicate) {
969     const uint64_t StartOffset = Offset;
970     for (; Offset < BF.getMaxSize();
971          Offset += InstrSize, InstrAddress += InstrSize) {
972       if (!DisAsm->getInstruction(Instr, InstrSize, FunctionData->slice(Offset),
973                                   InstrAddress, nulls()))
974         break;
975       if (!Predicate(Instr))
976         break;
977     }
978 
979     return Offset - StartOffset;
980   };
981 
982   // Skip a sequence of zero bytes.
983   auto skipZeros = [&]() {
984     const uint64_t StartOffset = Offset;
985     for (; Offset < BF.getMaxSize(); ++Offset)
986       if ((*FunctionData)[Offset] != 0)
987         break;
988 
989     return Offset - StartOffset;
990   };
991 
992   // Accept the whole padding area filled with breakpoints.
993   auto isBreakpoint = std::bind(&MCPlusBuilder::isBreakpoint, MIB.get(), _1);
994   if (skipInstructions(isBreakpoint) && Offset == BF.getMaxSize())
995     return true;
996 
997   auto isNoop = std::bind(&MCPlusBuilder::isNoop, MIB.get(), _1);
998 
999   // Some functions have a jump to the next function or to the padding area
1000   // inserted after the body.
1001   auto isSkipJump = [&](const MCInst &Instr) {
1002     uint64_t TargetAddress = 0;
1003     if (MIB->isUnconditionalBranch(Instr) &&
1004         MIB->evaluateBranch(Instr, InstrAddress, InstrSize, TargetAddress)) {
1005       if (TargetAddress >= InstrAddress + InstrSize &&
1006           TargetAddress <= BF.getAddress() + BF.getMaxSize()) {
1007         return true;
1008       }
1009     }
1010     return false;
1011   };
1012 
1013   // Skip over nops, jumps, and zero padding. Allow interleaving (this happens).
1014   while (skipInstructions(isNoop) || skipInstructions(isSkipJump) ||
1015          skipZeros())
1016     ;
1017 
1018   if (Offset == BF.getMaxSize())
1019     return true;
1020 
1021   if (opts::Verbosity >= 1) {
1022     this->errs() << "BOLT-WARNING: bad padding at address 0x"
1023                  << Twine::utohexstr(BF.getAddress() + BF.getSize())
1024                  << " starting at offset " << (Offset - BF.getSize())
1025                  << " in function " << BF << '\n'
1026                  << FunctionData->slice(BF.getSize(),
1027                                         BF.getMaxSize() - BF.getSize())
1028                  << '\n';
1029   }
1030 
1031   return false;
1032 }
1033 
1034 void BinaryContext::adjustCodePadding() {
1035   for (auto &BFI : BinaryFunctions) {
1036     BinaryFunction &BF = BFI.second;
1037     if (!shouldEmit(BF))
1038       continue;
1039 
1040     if (!hasValidCodePadding(BF)) {
1041       if (HasRelocations) {
1042         if (opts::Verbosity >= 1) {
1043           this->outs() << "BOLT-INFO: function " << BF
1044                        << " has invalid padding. Ignoring the function.\n";
1045         }
1046         BF.setIgnored();
1047       } else {
1048         BF.setMaxSize(BF.getSize());
1049       }
1050     }
1051   }
1052 }
1053 
1054 MCSymbol *BinaryContext::registerNameAtAddress(StringRef Name, uint64_t Address,
1055                                                uint64_t Size,
1056                                                uint16_t Alignment,
1057                                                unsigned Flags) {
1058   // Register the name with MCContext.
1059   MCSymbol *Symbol = Ctx->getOrCreateSymbol(Name);
1060 
1061   auto GAI = BinaryDataMap.find(Address);
1062   BinaryData *BD;
1063   if (GAI == BinaryDataMap.end()) {
1064     ErrorOr<BinarySection &> SectionOrErr = getSectionForAddress(Address);
1065     BinarySection &Section =
1066         SectionOrErr ? SectionOrErr.get() : absoluteSection();
1067     BD = new BinaryData(*Symbol, Address, Size, Alignment ? Alignment : 1,
1068                         Section, Flags);
1069     GAI = BinaryDataMap.emplace(Address, BD).first;
1070     GlobalSymbols[Name] = BD;
1071     updateObjectNesting(GAI);
1072   } else {
1073     BD = GAI->second;
1074     if (!BD->hasName(Name)) {
1075       GlobalSymbols[Name] = BD;
1076       BD->Symbols.push_back(Symbol);
1077     }
1078   }
1079 
1080   return Symbol;
1081 }
1082 
1083 const BinaryData *
1084 BinaryContext::getBinaryDataContainingAddressImpl(uint64_t Address) const {
1085   auto NI = BinaryDataMap.lower_bound(Address);
1086   auto End = BinaryDataMap.end();
1087   if ((NI != End && Address == NI->first) ||
1088       ((NI != BinaryDataMap.begin()) && (NI-- != BinaryDataMap.begin()))) {
1089     if (NI->second->containsAddress(Address))
1090       return NI->second;
1091 
1092     // If this is a sub-symbol, see if a parent data contains the address.
1093     const BinaryData *BD = NI->second->getParent();
1094     while (BD) {
1095       if (BD->containsAddress(Address))
1096         return BD;
1097       BD = BD->getParent();
1098     }
1099   }
1100   return nullptr;
1101 }
1102 
1103 BinaryData *BinaryContext::getGOTSymbol() {
1104   // First tries to find a global symbol with that name
1105   BinaryData *GOTSymBD = getBinaryDataByName("_GLOBAL_OFFSET_TABLE_");
1106   if (GOTSymBD)
1107     return GOTSymBD;
1108 
1109   // This symbol might be hidden from run-time link, so fetch the local
1110   // definition if available.
1111   GOTSymBD = getBinaryDataByName("_GLOBAL_OFFSET_TABLE_/1");
1112   if (!GOTSymBD)
1113     return nullptr;
1114 
1115   // If the local symbol is not unique, fail
1116   unsigned Index = 2;
1117   SmallString<30> Storage;
1118   while (const BinaryData *BD =
1119              getBinaryDataByName(Twine("_GLOBAL_OFFSET_TABLE_/")
1120                                      .concat(Twine(Index++))
1121                                      .toStringRef(Storage)))
1122     if (BD->getAddress() != GOTSymBD->getAddress())
1123       return nullptr;
1124 
1125   return GOTSymBD;
1126 }
1127 
1128 bool BinaryContext::setBinaryDataSize(uint64_t Address, uint64_t Size) {
1129   auto NI = BinaryDataMap.find(Address);
1130   assert(NI != BinaryDataMap.end());
1131   if (NI == BinaryDataMap.end())
1132     return false;
1133   // TODO: it's possible that a jump table starts at the same address
1134   // as a larger blob of private data.  When we set the size of the
1135   // jump table, it might be smaller than the total blob size.  In this
1136   // case we just leave the original size since (currently) it won't really
1137   // affect anything.
1138   assert((!NI->second->Size || NI->second->Size == Size ||
1139           (NI->second->isJumpTable() && NI->second->Size > Size)) &&
1140          "can't change the size of a symbol that has already had its "
1141          "size set");
1142   if (!NI->second->Size) {
1143     NI->second->Size = Size;
1144     updateObjectNesting(NI);
1145     return true;
1146   }
1147   return false;
1148 }
1149 
1150 void BinaryContext::generateSymbolHashes() {
1151   auto isPadding = [](const BinaryData &BD) {
1152     StringRef Contents = BD.getSection().getContents();
1153     StringRef SymData = Contents.substr(BD.getOffset(), BD.getSize());
1154     return (BD.getName().starts_with("HOLEat") ||
1155             SymData.find_first_not_of(0) == StringRef::npos);
1156   };
1157 
1158   uint64_t NumCollisions = 0;
1159   for (auto &Entry : BinaryDataMap) {
1160     BinaryData &BD = *Entry.second;
1161     StringRef Name = BD.getName();
1162 
1163     if (!isInternalSymbolName(Name))
1164       continue;
1165 
1166     // First check if a non-anonymous alias exists and move it to the front.
1167     if (BD.getSymbols().size() > 1) {
1168       auto Itr = llvm::find_if(BD.getSymbols(), [&](const MCSymbol *Symbol) {
1169         return !isInternalSymbolName(Symbol->getName());
1170       });
1171       if (Itr != BD.getSymbols().end()) {
1172         size_t Idx = std::distance(BD.getSymbols().begin(), Itr);
1173         std::swap(BD.getSymbols()[0], BD.getSymbols()[Idx]);
1174         continue;
1175       }
1176     }
1177 
1178     // We have to skip 0 size symbols since they will all collide.
1179     if (BD.getSize() == 0) {
1180       continue;
1181     }
1182 
1183     const uint64_t Hash = BD.getSection().hash(BD);
1184     const size_t Idx = Name.find("0x");
1185     std::string NewName =
1186         (Twine(Name.substr(0, Idx)) + "_" + Twine::utohexstr(Hash)).str();
1187     if (getBinaryDataByName(NewName)) {
1188       // Ignore collisions for symbols that appear to be padding
1189       // (i.e. all zeros or a "hole")
1190       if (!isPadding(BD)) {
1191         if (opts::Verbosity) {
1192           this->errs() << "BOLT-WARNING: collision detected when hashing " << BD
1193                        << " with new name (" << NewName << "), skipping.\n";
1194         }
1195         ++NumCollisions;
1196       }
1197       continue;
1198     }
1199     BD.Symbols.insert(BD.Symbols.begin(), Ctx->getOrCreateSymbol(NewName));
1200     GlobalSymbols[NewName] = &BD;
1201   }
1202   if (NumCollisions) {
1203     this->errs() << "BOLT-WARNING: " << NumCollisions
1204                  << " collisions detected while hashing binary objects";
1205     if (!opts::Verbosity)
1206       this->errs() << ". Use -v=1 to see the list.";
1207     this->errs() << '\n';
1208   }
1209 }
1210 
1211 bool BinaryContext::registerFragment(BinaryFunction &TargetFunction,
1212                                      BinaryFunction &Function) {
1213   assert(TargetFunction.isFragment() && "TargetFunction must be a fragment");
1214   if (TargetFunction.isChildOf(Function))
1215     return true;
1216   TargetFunction.addParentFragment(Function);
1217   Function.addFragment(TargetFunction);
1218   FragmentClasses.unionSets(&TargetFunction, &Function);
1219   if (!HasRelocations) {
1220     TargetFunction.setSimple(false);
1221     Function.setSimple(false);
1222   }
1223   if (opts::Verbosity >= 1) {
1224     this->outs() << "BOLT-INFO: marking " << TargetFunction
1225                  << " as a fragment of " << Function << '\n';
1226   }
1227   return true;
1228 }
1229 
1230 void BinaryContext::addAdrpAddRelocAArch64(BinaryFunction &BF,
1231                                            MCInst &LoadLowBits,
1232                                            MCInst &LoadHiBits,
1233                                            uint64_t Target) {
1234   const MCSymbol *TargetSymbol;
1235   uint64_t Addend = 0;
1236   std::tie(TargetSymbol, Addend) = handleAddressRef(Target, BF,
1237                                                     /*IsPCRel*/ true);
1238   int64_t Val;
1239   MIB->replaceImmWithSymbolRef(LoadHiBits, TargetSymbol, Addend, Ctx.get(), Val,
1240                                ELF::R_AARCH64_ADR_PREL_PG_HI21);
1241   MIB->replaceImmWithSymbolRef(LoadLowBits, TargetSymbol, Addend, Ctx.get(),
1242                                Val, ELF::R_AARCH64_ADD_ABS_LO12_NC);
1243 }
1244 
1245 bool BinaryContext::handleAArch64Veneer(uint64_t Address, bool MatchOnly) {
1246   BinaryFunction *TargetFunction = getBinaryFunctionContainingAddress(Address);
1247   if (TargetFunction)
1248     return false;
1249 
1250   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1251   assert(Section && "cannot get section for referenced address");
1252   if (!Section->isText())
1253     return false;
1254 
1255   bool Ret = false;
1256   StringRef SectionContents = Section->getContents();
1257   uint64_t Offset = Address - Section->getAddress();
1258   const uint64_t MaxSize = SectionContents.size() - Offset;
1259   const uint8_t *Bytes =
1260       reinterpret_cast<const uint8_t *>(SectionContents.data());
1261   ArrayRef<uint8_t> Data(Bytes + Offset, MaxSize);
1262 
1263   auto matchVeneer = [&](BinaryFunction::InstrMapType &Instructions,
1264                          MCInst &Instruction, uint64_t Offset,
1265                          uint64_t AbsoluteInstrAddr,
1266                          uint64_t TotalSize) -> bool {
1267     MCInst *TargetHiBits, *TargetLowBits;
1268     uint64_t TargetAddress, Count;
1269     Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1270                                    AbsoluteInstrAddr, Instruction, TargetHiBits,
1271                                    TargetLowBits, TargetAddress);
1272     if (!Count)
1273       return false;
1274 
1275     if (MatchOnly)
1276       return true;
1277 
1278     // NOTE The target symbol was created during disassemble's
1279     // handleExternalReference
1280     const MCSymbol *VeneerSymbol = getOrCreateGlobalSymbol(Address, "FUNCat");
1281     BinaryFunction *Veneer = createBinaryFunction(VeneerSymbol->getName().str(),
1282                                                   *Section, Address, TotalSize);
1283     addAdrpAddRelocAArch64(*Veneer, *TargetLowBits, *TargetHiBits,
1284                            TargetAddress);
1285     MIB->addAnnotation(Instruction, "AArch64Veneer", true);
1286     Veneer->addInstruction(Offset, std::move(Instruction));
1287     --Count;
1288     for (auto It = Instructions.rbegin(); Count != 0; ++It, --Count) {
1289       MIB->addAnnotation(It->second, "AArch64Veneer", true);
1290       Veneer->addInstruction(It->first, std::move(It->second));
1291     }
1292 
1293     Veneer->getOrCreateLocalLabel(Address);
1294     Veneer->setMaxSize(TotalSize);
1295     Veneer->updateState(BinaryFunction::State::Disassembled);
1296     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: handling veneer function at 0x" << Address
1297                       << "\n");
1298     return true;
1299   };
1300 
1301   uint64_t Size = 0, TotalSize = 0;
1302   BinaryFunction::InstrMapType VeneerInstructions;
1303   for (Offset = 0; Offset < MaxSize; Offset += Size) {
1304     MCInst Instruction;
1305     const uint64_t AbsoluteInstrAddr = Address + Offset;
1306     if (!SymbolicDisAsm->getInstruction(Instruction, Size, Data.slice(Offset),
1307                                         AbsoluteInstrAddr, nulls()))
1308       break;
1309 
1310     TotalSize += Size;
1311     if (MIB->isBranch(Instruction)) {
1312       Ret = matchVeneer(VeneerInstructions, Instruction, Offset,
1313                         AbsoluteInstrAddr, TotalSize);
1314       break;
1315     }
1316 
1317     VeneerInstructions.emplace(Offset, std::move(Instruction));
1318   }
1319 
1320   return Ret;
1321 }
1322 
1323 void BinaryContext::processInterproceduralReferences() {
1324   for (const std::pair<BinaryFunction *, uint64_t> &It :
1325        InterproceduralReferences) {
1326     BinaryFunction &Function = *It.first;
1327     uint64_t Address = It.second;
1328     // Process interprocedural references from ignored functions in BAT mode
1329     // (non-simple in non-relocation mode) to properly register entry points
1330     if (!Address || (Function.isIgnored() && !HasBATSection))
1331       continue;
1332 
1333     BinaryFunction *TargetFunction =
1334         getBinaryFunctionContainingAddress(Address);
1335     if (&Function == TargetFunction)
1336       continue;
1337 
1338     if (TargetFunction) {
1339       if (TargetFunction->isFragment() &&
1340           !areRelatedFragments(TargetFunction, &Function)) {
1341         this->errs()
1342             << "BOLT-WARNING: interprocedural reference between unrelated "
1343                "fragments: "
1344             << Function.getPrintName() << " and "
1345             << TargetFunction->getPrintName() << '\n';
1346       }
1347       if (uint64_t Offset = Address - TargetFunction->getAddress())
1348         TargetFunction->addEntryPointAtOffset(Offset);
1349 
1350       continue;
1351     }
1352 
1353     // Check if address falls in function padding space - this could be
1354     // unmarked data in code. In this case adjust the padding space size.
1355     ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1356     assert(Section && "cannot get section for referenced address");
1357 
1358     if (!Section->isText())
1359       continue;
1360 
1361     // PLT requires special handling and could be ignored in this context.
1362     StringRef SectionName = Section->getName();
1363     if (SectionName == ".plt" || SectionName == ".plt.got")
1364       continue;
1365 
1366     // Check if it is aarch64 veneer written at Address
1367     if (isAArch64() && handleAArch64Veneer(Address))
1368       continue;
1369 
1370     if (opts::processAllFunctions()) {
1371       this->errs() << "BOLT-ERROR: cannot process binaries with unmarked "
1372                    << "object in code at address 0x"
1373                    << Twine::utohexstr(Address) << " belonging to section "
1374                    << SectionName << " in current mode\n";
1375       exit(1);
1376     }
1377 
1378     TargetFunction = getBinaryFunctionContainingAddress(Address,
1379                                                         /*CheckPastEnd=*/false,
1380                                                         /*UseMaxSize=*/true);
1381     // We are not going to overwrite non-simple functions, but for simple
1382     // ones - adjust the padding size.
1383     if (TargetFunction && TargetFunction->isSimple()) {
1384       this->errs()
1385           << "BOLT-WARNING: function " << *TargetFunction
1386           << " has an object detected in a padding region at address 0x"
1387           << Twine::utohexstr(Address) << '\n';
1388       TargetFunction->setMaxSize(TargetFunction->getSize());
1389     }
1390   }
1391 
1392   InterproceduralReferences.clear();
1393 }
1394 
1395 void BinaryContext::postProcessSymbolTable() {
1396   fixBinaryDataHoles();
1397   bool Valid = true;
1398   for (auto &Entry : BinaryDataMap) {
1399     BinaryData *BD = Entry.second;
1400     if ((BD->getName().starts_with("SYMBOLat") ||
1401          BD->getName().starts_with("DATAat")) &&
1402         !BD->getParent() && !BD->getSize() && !BD->isAbsolute() &&
1403         BD->getSection()) {
1404       this->errs() << "BOLT-WARNING: zero-sized top level symbol: " << *BD
1405                    << "\n";
1406       Valid = false;
1407     }
1408   }
1409   assert(Valid);
1410   (void)Valid;
1411   generateSymbolHashes();
1412 }
1413 
1414 void BinaryContext::foldFunction(BinaryFunction &ChildBF,
1415                                  BinaryFunction &ParentBF) {
1416   assert(!ChildBF.isMultiEntry() && !ParentBF.isMultiEntry() &&
1417          "cannot merge functions with multiple entry points");
1418 
1419   std::unique_lock<llvm::sys::RWMutex> WriteCtxLock(CtxMutex, std::defer_lock);
1420   std::unique_lock<llvm::sys::RWMutex> WriteSymbolMapLock(
1421       SymbolToFunctionMapMutex, std::defer_lock);
1422 
1423   const StringRef ChildName = ChildBF.getOneName();
1424 
1425   // Move symbols over and update bookkeeping info.
1426   for (MCSymbol *Symbol : ChildBF.getSymbols()) {
1427     ParentBF.getSymbols().push_back(Symbol);
1428     WriteSymbolMapLock.lock();
1429     SymbolToFunctionMap[Symbol] = &ParentBF;
1430     WriteSymbolMapLock.unlock();
1431     // NB: there's no need to update BinaryDataMap and GlobalSymbols.
1432   }
1433   ChildBF.getSymbols().clear();
1434 
1435   // Move other names the child function is known under.
1436   llvm::move(ChildBF.Aliases, std::back_inserter(ParentBF.Aliases));
1437   ChildBF.Aliases.clear();
1438 
1439   if (HasRelocations) {
1440     // Merge execution counts of ChildBF into those of ParentBF.
1441     // Without relocations, we cannot reliably merge profiles as both functions
1442     // continue to exist and either one can be executed.
1443     ChildBF.mergeProfileDataInto(ParentBF);
1444 
1445     std::shared_lock<llvm::sys::RWMutex> ReadBfsLock(BinaryFunctionsMutex,
1446                                                      std::defer_lock);
1447     std::unique_lock<llvm::sys::RWMutex> WriteBfsLock(BinaryFunctionsMutex,
1448                                                       std::defer_lock);
1449     // Remove ChildBF from the global set of functions in relocs mode.
1450     ReadBfsLock.lock();
1451     auto FI = BinaryFunctions.find(ChildBF.getAddress());
1452     ReadBfsLock.unlock();
1453 
1454     assert(FI != BinaryFunctions.end() && "function not found");
1455     assert(&ChildBF == &FI->second && "function mismatch");
1456 
1457     WriteBfsLock.lock();
1458     ChildBF.clearDisasmState();
1459     FI = BinaryFunctions.erase(FI);
1460     WriteBfsLock.unlock();
1461 
1462   } else {
1463     // In non-relocation mode we keep the function, but rename it.
1464     std::string NewName = "__ICF_" + ChildName.str();
1465 
1466     WriteCtxLock.lock();
1467     ChildBF.getSymbols().push_back(Ctx->getOrCreateSymbol(NewName));
1468     WriteCtxLock.unlock();
1469 
1470     ChildBF.setFolded(&ParentBF);
1471   }
1472 
1473   ParentBF.setHasFunctionsFoldedInto();
1474 }
1475 
1476 void BinaryContext::fixBinaryDataHoles() {
1477   assert(validateObjectNesting() && "object nesting inconsistency detected");
1478 
1479   for (BinarySection &Section : allocatableSections()) {
1480     std::vector<std::pair<uint64_t, uint64_t>> Holes;
1481 
1482     auto isNotHole = [&Section](const binary_data_iterator &Itr) {
1483       BinaryData *BD = Itr->second;
1484       bool isHole = (!BD->getParent() && !BD->getSize() && BD->isObject() &&
1485                      (BD->getName().starts_with("SYMBOLat0x") ||
1486                       BD->getName().starts_with("DATAat0x") ||
1487                       BD->getName().starts_with("ANONYMOUS")));
1488       return !isHole && BD->getSection() == Section && !BD->getParent();
1489     };
1490 
1491     auto BDStart = BinaryDataMap.begin();
1492     auto BDEnd = BinaryDataMap.end();
1493     auto Itr = FilteredBinaryDataIterator(isNotHole, BDStart, BDEnd);
1494     auto End = FilteredBinaryDataIterator(isNotHole, BDEnd, BDEnd);
1495 
1496     uint64_t EndAddress = Section.getAddress();
1497 
1498     while (Itr != End) {
1499       if (Itr->second->getAddress() > EndAddress) {
1500         uint64_t Gap = Itr->second->getAddress() - EndAddress;
1501         Holes.emplace_back(EndAddress, Gap);
1502       }
1503       EndAddress = Itr->second->getEndAddress();
1504       ++Itr;
1505     }
1506 
1507     if (EndAddress < Section.getEndAddress())
1508       Holes.emplace_back(EndAddress, Section.getEndAddress() - EndAddress);
1509 
1510     // If there is already a symbol at the start of the hole, grow that symbol
1511     // to cover the rest.  Otherwise, create a new symbol to cover the hole.
1512     for (std::pair<uint64_t, uint64_t> &Hole : Holes) {
1513       BinaryData *BD = getBinaryDataAtAddress(Hole.first);
1514       if (BD) {
1515         // BD->getSection() can be != Section if there are sections that
1516         // overlap.  In this case it is probably safe to just skip the holes
1517         // since the overlapping section will not(?) have any symbols in it.
1518         if (BD->getSection() == Section)
1519           setBinaryDataSize(Hole.first, Hole.second);
1520       } else {
1521         getOrCreateGlobalSymbol(Hole.first, "HOLEat", Hole.second, 1);
1522       }
1523     }
1524   }
1525 
1526   assert(validateObjectNesting() && "object nesting inconsistency detected");
1527   assert(validateHoles() && "top level hole detected in object map");
1528 }
1529 
1530 void BinaryContext::printGlobalSymbols(raw_ostream &OS) const {
1531   const BinarySection *CurrentSection = nullptr;
1532   bool FirstSection = true;
1533 
1534   for (auto &Entry : BinaryDataMap) {
1535     const BinaryData *BD = Entry.second;
1536     const BinarySection &Section = BD->getSection();
1537     if (FirstSection || Section != *CurrentSection) {
1538       uint64_t Address, Size;
1539       StringRef Name = Section.getName();
1540       if (Section) {
1541         Address = Section.getAddress();
1542         Size = Section.getSize();
1543       } else {
1544         Address = BD->getAddress();
1545         Size = BD->getSize();
1546       }
1547       OS << "BOLT-INFO: Section " << Name << ", "
1548          << "0x" + Twine::utohexstr(Address) << ":"
1549          << "0x" + Twine::utohexstr(Address + Size) << "/" << Size << "\n";
1550       CurrentSection = &Section;
1551       FirstSection = false;
1552     }
1553 
1554     OS << "BOLT-INFO: ";
1555     const BinaryData *P = BD->getParent();
1556     while (P) {
1557       OS << "  ";
1558       P = P->getParent();
1559     }
1560     OS << *BD << "\n";
1561   }
1562 }
1563 
1564 Expected<unsigned> BinaryContext::getDwarfFile(
1565     StringRef Directory, StringRef FileName, unsigned FileNumber,
1566     std::optional<MD5::MD5Result> Checksum, std::optional<StringRef> Source,
1567     unsigned CUID, unsigned DWARFVersion) {
1568   DwarfLineTable &Table = DwarfLineTablesCUMap[CUID];
1569   return Table.tryGetFile(Directory, FileName, Checksum, Source, DWARFVersion,
1570                           FileNumber);
1571 }
1572 
1573 unsigned BinaryContext::addDebugFilenameToUnit(const uint32_t DestCUID,
1574                                                const uint32_t SrcCUID,
1575                                                unsigned FileIndex) {
1576   DWARFCompileUnit *SrcUnit = DwCtx->getCompileUnitForOffset(SrcCUID);
1577   const DWARFDebugLine::LineTable *LineTable =
1578       DwCtx->getLineTableForUnit(SrcUnit);
1579   const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1580       LineTable->Prologue.FileNames;
1581   // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1582   // means empty dir.
1583   assert(FileIndex > 0 && FileIndex <= FileNames.size() &&
1584          "FileIndex out of range for the compilation unit.");
1585   StringRef Dir = "";
1586   if (FileNames[FileIndex - 1].DirIdx != 0) {
1587     if (std::optional<const char *> DirName = dwarf::toString(
1588             LineTable->Prologue
1589                 .IncludeDirectories[FileNames[FileIndex - 1].DirIdx - 1])) {
1590       Dir = *DirName;
1591     }
1592   }
1593   StringRef FileName = "";
1594   if (std::optional<const char *> FName =
1595           dwarf::toString(FileNames[FileIndex - 1].Name))
1596     FileName = *FName;
1597   assert(FileName != "");
1598   DWARFCompileUnit *DstUnit = DwCtx->getCompileUnitForOffset(DestCUID);
1599   return cantFail(getDwarfFile(Dir, FileName, 0, std::nullopt, std::nullopt,
1600                                DestCUID, DstUnit->getVersion()));
1601 }
1602 
1603 std::vector<BinaryFunction *> BinaryContext::getSortedFunctions() {
1604   std::vector<BinaryFunction *> SortedFunctions(BinaryFunctions.size());
1605   llvm::transform(llvm::make_second_range(BinaryFunctions),
1606                   SortedFunctions.begin(),
1607                   [](BinaryFunction &BF) { return &BF; });
1608 
1609   llvm::stable_sort(SortedFunctions,
1610                     [](const BinaryFunction *A, const BinaryFunction *B) {
1611                       if (A->hasValidIndex() && B->hasValidIndex()) {
1612                         return A->getIndex() < B->getIndex();
1613                       }
1614                       return A->hasValidIndex();
1615                     });
1616   return SortedFunctions;
1617 }
1618 
1619 std::vector<BinaryFunction *> BinaryContext::getAllBinaryFunctions() {
1620   std::vector<BinaryFunction *> AllFunctions;
1621   AllFunctions.reserve(BinaryFunctions.size() + InjectedBinaryFunctions.size());
1622   llvm::transform(llvm::make_second_range(BinaryFunctions),
1623                   std::back_inserter(AllFunctions),
1624                   [](BinaryFunction &BF) { return &BF; });
1625   llvm::copy(InjectedBinaryFunctions, std::back_inserter(AllFunctions));
1626 
1627   return AllFunctions;
1628 }
1629 
1630 std::optional<DWARFUnit *> BinaryContext::getDWOCU(uint64_t DWOId) {
1631   auto Iter = DWOCUs.find(DWOId);
1632   if (Iter == DWOCUs.end())
1633     return std::nullopt;
1634 
1635   return Iter->second;
1636 }
1637 
1638 DWARFContext *BinaryContext::getDWOContext() const {
1639   if (DWOCUs.empty())
1640     return nullptr;
1641   return &DWOCUs.begin()->second->getContext();
1642 }
1643 
1644 /// Handles DWO sections that can either be in .o, .dwo or .dwp files.
1645 void BinaryContext::preprocessDWODebugInfo() {
1646   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1647     DWARFUnit *const DwarfUnit = CU.get();
1648     if (std::optional<uint64_t> DWOId = DwarfUnit->getDWOId()) {
1649       std::string DWOName = dwarf::toString(
1650           DwarfUnit->getUnitDIE().find(
1651               {dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
1652           "");
1653       SmallString<16> AbsolutePath;
1654       if (!opts::CompDirOverride.empty()) {
1655         sys::path::append(AbsolutePath, opts::CompDirOverride);
1656         sys::path::append(AbsolutePath, DWOName);
1657       }
1658       DWARFUnit *DWOCU =
1659           DwarfUnit->getNonSkeletonUnitDIE(false, AbsolutePath).getDwarfUnit();
1660       if (!DWOCU->isDWOUnit()) {
1661         this->outs()
1662             << "BOLT-WARNING: Debug Fission: DWO debug information for "
1663             << DWOName
1664             << " was not retrieved and won't be updated. Please check "
1665                "relative path.\n";
1666         continue;
1667       }
1668       DWOCUs[*DWOId] = DWOCU;
1669     }
1670   }
1671   if (!DWOCUs.empty())
1672     this->outs() << "BOLT-INFO: processing split DWARF\n";
1673 }
1674 
1675 void BinaryContext::preprocessDebugInfo() {
1676   struct CURange {
1677     uint64_t LowPC;
1678     uint64_t HighPC;
1679     DWARFUnit *Unit;
1680 
1681     bool operator<(const CURange &Other) const { return LowPC < Other.LowPC; }
1682   };
1683 
1684   // Building a map of address ranges to CUs similar to .debug_aranges and use
1685   // it to assign CU to functions.
1686   std::vector<CURange> AllRanges;
1687   AllRanges.reserve(DwCtx->getNumCompileUnits());
1688   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1689     Expected<DWARFAddressRangesVector> RangesOrError =
1690         CU->getUnitDIE().getAddressRanges();
1691     if (!RangesOrError) {
1692       consumeError(RangesOrError.takeError());
1693       continue;
1694     }
1695     for (DWARFAddressRange &Range : *RangesOrError) {
1696       // Parts of the debug info could be invalidated due to corresponding code
1697       // being removed from the binary by the linker. Hence we check if the
1698       // address is a valid one.
1699       if (containsAddress(Range.LowPC))
1700         AllRanges.emplace_back(CURange{Range.LowPC, Range.HighPC, CU.get()});
1701     }
1702 
1703     ContainsDwarf5 |= CU->getVersion() >= 5;
1704     ContainsDwarfLegacy |= CU->getVersion() < 5;
1705   }
1706 
1707   llvm::sort(AllRanges);
1708   for (auto &KV : BinaryFunctions) {
1709     const uint64_t FunctionAddress = KV.first;
1710     BinaryFunction &Function = KV.second;
1711 
1712     auto It = llvm::partition_point(
1713         AllRanges, [=](CURange R) { return R.HighPC <= FunctionAddress; });
1714     if (It != AllRanges.end() && It->LowPC <= FunctionAddress)
1715       Function.setDWARFUnit(It->Unit);
1716   }
1717 
1718   // Discover units with debug info that needs to be updated.
1719   for (const auto &KV : BinaryFunctions) {
1720     const BinaryFunction &BF = KV.second;
1721     if (shouldEmit(BF) && BF.getDWARFUnit())
1722       ProcessedCUs.insert(BF.getDWARFUnit());
1723   }
1724 
1725   // Clear debug info for functions from units that we are not going to process.
1726   for (auto &KV : BinaryFunctions) {
1727     BinaryFunction &BF = KV.second;
1728     if (BF.getDWARFUnit() && !ProcessedCUs.count(BF.getDWARFUnit()))
1729       BF.setDWARFUnit(nullptr);
1730   }
1731 
1732   if (opts::Verbosity >= 1) {
1733     this->outs() << "BOLT-INFO: " << ProcessedCUs.size() << " out of "
1734                  << DwCtx->getNumCompileUnits() << " CUs will be updated\n";
1735   }
1736 
1737   preprocessDWODebugInfo();
1738 
1739   // Populate MCContext with DWARF files from all units.
1740   StringRef GlobalPrefix = AsmInfo->getPrivateGlobalPrefix();
1741   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1742     const uint64_t CUID = CU->getOffset();
1743     DwarfLineTable &BinaryLineTable = getDwarfLineTable(CUID);
1744     BinaryLineTable.setLabel(Ctx->getOrCreateSymbol(
1745         GlobalPrefix + "line_table_start" + Twine(CUID)));
1746 
1747     if (!ProcessedCUs.count(CU.get()))
1748       continue;
1749 
1750     const DWARFDebugLine::LineTable *LineTable =
1751         DwCtx->getLineTableForUnit(CU.get());
1752     const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1753         LineTable->Prologue.FileNames;
1754 
1755     uint16_t DwarfVersion = LineTable->Prologue.getVersion();
1756     if (DwarfVersion >= 5) {
1757       std::optional<MD5::MD5Result> Checksum;
1758       if (LineTable->Prologue.ContentTypes.HasMD5)
1759         Checksum = LineTable->Prologue.FileNames[0].Checksum;
1760       std::optional<const char *> Name =
1761           dwarf::toString(CU->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1762       if (std::optional<uint64_t> DWOID = CU->getDWOId()) {
1763         auto Iter = DWOCUs.find(*DWOID);
1764         assert(Iter != DWOCUs.end() && "DWO CU was not found.");
1765         Name = dwarf::toString(
1766             Iter->second->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1767       }
1768       BinaryLineTable.setRootFile(CU->getCompilationDir(), *Name, Checksum,
1769                                   std::nullopt);
1770     }
1771 
1772     BinaryLineTable.setDwarfVersion(DwarfVersion);
1773 
1774     // Assign a unique label to every line table, one per CU.
1775     // Make sure empty debug line tables are registered too.
1776     if (FileNames.empty()) {
1777       cantFail(getDwarfFile("", "<unknown>", 0, std::nullopt, std::nullopt,
1778                             CUID, DwarfVersion));
1779       continue;
1780     }
1781     const uint32_t Offset = DwarfVersion < 5 ? 1 : 0;
1782     for (size_t I = 0, Size = FileNames.size(); I != Size; ++I) {
1783       // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1784       // means empty dir.
1785       StringRef Dir = "";
1786       if (FileNames[I].DirIdx != 0 || DwarfVersion >= 5)
1787         if (std::optional<const char *> DirName = dwarf::toString(
1788                 LineTable->Prologue
1789                     .IncludeDirectories[FileNames[I].DirIdx - Offset]))
1790           Dir = *DirName;
1791       StringRef FileName = "";
1792       if (std::optional<const char *> FName =
1793               dwarf::toString(FileNames[I].Name))
1794         FileName = *FName;
1795       assert(FileName != "");
1796       std::optional<MD5::MD5Result> Checksum;
1797       if (DwarfVersion >= 5 && LineTable->Prologue.ContentTypes.HasMD5)
1798         Checksum = LineTable->Prologue.FileNames[I].Checksum;
1799       cantFail(getDwarfFile(Dir, FileName, 0, Checksum, std::nullopt, CUID,
1800                             DwarfVersion));
1801     }
1802   }
1803 }
1804 
1805 bool BinaryContext::shouldEmit(const BinaryFunction &Function) const {
1806   if (Function.isPseudo())
1807     return false;
1808 
1809   if (opts::processAllFunctions())
1810     return true;
1811 
1812   if (Function.isIgnored())
1813     return false;
1814 
1815   // In relocation mode we will emit non-simple functions with CFG.
1816   // If the function does not have a CFG it should be marked as ignored.
1817   return HasRelocations || Function.isSimple();
1818 }
1819 
1820 void BinaryContext::dump(const MCInst &Inst) const {
1821   if (LLVM_UNLIKELY(!InstPrinter)) {
1822     dbgs() << "Cannot dump for InstPrinter is not initialized.\n";
1823     return;
1824   }
1825   InstPrinter->printInst(&Inst, 0, "", *STI, dbgs());
1826   dbgs() << "\n";
1827 }
1828 
1829 void BinaryContext::printCFI(raw_ostream &OS, const MCCFIInstruction &Inst) {
1830   uint32_t Operation = Inst.getOperation();
1831   switch (Operation) {
1832   case MCCFIInstruction::OpSameValue:
1833     OS << "OpSameValue Reg" << Inst.getRegister();
1834     break;
1835   case MCCFIInstruction::OpRememberState:
1836     OS << "OpRememberState";
1837     break;
1838   case MCCFIInstruction::OpRestoreState:
1839     OS << "OpRestoreState";
1840     break;
1841   case MCCFIInstruction::OpOffset:
1842     OS << "OpOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1843     break;
1844   case MCCFIInstruction::OpDefCfaRegister:
1845     OS << "OpDefCfaRegister Reg" << Inst.getRegister();
1846     break;
1847   case MCCFIInstruction::OpDefCfaOffset:
1848     OS << "OpDefCfaOffset " << Inst.getOffset();
1849     break;
1850   case MCCFIInstruction::OpDefCfa:
1851     OS << "OpDefCfa Reg" << Inst.getRegister() << " " << Inst.getOffset();
1852     break;
1853   case MCCFIInstruction::OpRelOffset:
1854     OS << "OpRelOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1855     break;
1856   case MCCFIInstruction::OpAdjustCfaOffset:
1857     OS << "OfAdjustCfaOffset " << Inst.getOffset();
1858     break;
1859   case MCCFIInstruction::OpEscape:
1860     OS << "OpEscape";
1861     break;
1862   case MCCFIInstruction::OpRestore:
1863     OS << "OpRestore Reg" << Inst.getRegister();
1864     break;
1865   case MCCFIInstruction::OpUndefined:
1866     OS << "OpUndefined Reg" << Inst.getRegister();
1867     break;
1868   case MCCFIInstruction::OpRegister:
1869     OS << "OpRegister Reg" << Inst.getRegister() << " Reg"
1870        << Inst.getRegister2();
1871     break;
1872   case MCCFIInstruction::OpWindowSave:
1873     OS << "OpWindowSave";
1874     break;
1875   case MCCFIInstruction::OpGnuArgsSize:
1876     OS << "OpGnuArgsSize";
1877     break;
1878   default:
1879     OS << "Op#" << Operation;
1880     break;
1881   }
1882 }
1883 
1884 MarkerSymType BinaryContext::getMarkerType(const SymbolRef &Symbol) const {
1885   // For aarch64 and riscv, the ABI defines mapping symbols so we identify data
1886   // in the code section (see IHI0056B). $x identifies a symbol starting code or
1887   // the end of a data chunk inside code, $d identifies start of data.
1888   if (isX86() || ELFSymbolRef(Symbol).getSize())
1889     return MarkerSymType::NONE;
1890 
1891   Expected<StringRef> NameOrError = Symbol.getName();
1892   Expected<object::SymbolRef::Type> TypeOrError = Symbol.getType();
1893 
1894   if (!TypeOrError || !NameOrError)
1895     return MarkerSymType::NONE;
1896 
1897   if (*TypeOrError != SymbolRef::ST_Unknown)
1898     return MarkerSymType::NONE;
1899 
1900   if (*NameOrError == "$x" || NameOrError->starts_with("$x."))
1901     return MarkerSymType::CODE;
1902 
1903   // $x<ISA>
1904   if (isRISCV() && NameOrError->starts_with("$x"))
1905     return MarkerSymType::CODE;
1906 
1907   if (*NameOrError == "$d" || NameOrError->starts_with("$d."))
1908     return MarkerSymType::DATA;
1909 
1910   return MarkerSymType::NONE;
1911 }
1912 
1913 bool BinaryContext::isMarker(const SymbolRef &Symbol) const {
1914   return getMarkerType(Symbol) != MarkerSymType::NONE;
1915 }
1916 
1917 static void printDebugInfo(raw_ostream &OS, const MCInst &Instruction,
1918                            const BinaryFunction *Function,
1919                            DWARFContext *DwCtx) {
1920   DebugLineTableRowRef RowRef =
1921       DebugLineTableRowRef::fromSMLoc(Instruction.getLoc());
1922   if (RowRef == DebugLineTableRowRef::NULL_ROW)
1923     return;
1924 
1925   const DWARFDebugLine::LineTable *LineTable;
1926   if (Function && Function->getDWARFUnit() &&
1927       Function->getDWARFUnit()->getOffset() == RowRef.DwCompileUnitIndex) {
1928     LineTable = Function->getDWARFLineTable();
1929   } else {
1930     LineTable = DwCtx->getLineTableForUnit(
1931         DwCtx->getCompileUnitForOffset(RowRef.DwCompileUnitIndex));
1932   }
1933   assert(LineTable && "line table expected for instruction with debug info");
1934 
1935   const DWARFDebugLine::Row &Row = LineTable->Rows[RowRef.RowIndex - 1];
1936   StringRef FileName = "";
1937   if (std::optional<const char *> FName =
1938           dwarf::toString(LineTable->Prologue.FileNames[Row.File - 1].Name))
1939     FileName = *FName;
1940   OS << " # debug line " << FileName << ":" << Row.Line;
1941   if (Row.Column)
1942     OS << ":" << Row.Column;
1943   if (Row.Discriminator)
1944     OS << " discriminator:" << Row.Discriminator;
1945 }
1946 
1947 void BinaryContext::printInstruction(raw_ostream &OS, const MCInst &Instruction,
1948                                      uint64_t Offset,
1949                                      const BinaryFunction *Function,
1950                                      bool PrintMCInst, bool PrintMemData,
1951                                      bool PrintRelocations,
1952                                      StringRef Endl) const {
1953   OS << format("    %08" PRIx64 ": ", Offset);
1954   if (MIB->isCFI(Instruction)) {
1955     uint32_t Offset = Instruction.getOperand(0).getImm();
1956     OS << "\t!CFI\t$" << Offset << "\t; ";
1957     if (Function)
1958       printCFI(OS, *Function->getCFIFor(Instruction));
1959     OS << Endl;
1960     return;
1961   }
1962   if (std::optional<uint32_t> DynamicID =
1963           MIB->getDynamicBranchID(Instruction)) {
1964     OS << "\tjit\t" << MIB->getTargetSymbol(Instruction)->getName()
1965        << " # ID: " << DynamicID;
1966   } else {
1967     InstPrinter->printInst(&Instruction, 0, "", *STI, OS);
1968   }
1969   if (MIB->isCall(Instruction)) {
1970     if (MIB->isTailCall(Instruction))
1971       OS << " # TAILCALL ";
1972     if (MIB->isInvoke(Instruction)) {
1973       const std::optional<MCPlus::MCLandingPad> EHInfo =
1974           MIB->getEHInfo(Instruction);
1975       OS << " # handler: ";
1976       if (EHInfo->first)
1977         OS << *EHInfo->first;
1978       else
1979         OS << '0';
1980       OS << "; action: " << EHInfo->second;
1981       const int64_t GnuArgsSize = MIB->getGnuArgsSize(Instruction);
1982       if (GnuArgsSize >= 0)
1983         OS << "; GNU_args_size = " << GnuArgsSize;
1984     }
1985   } else if (MIB->isIndirectBranch(Instruction)) {
1986     if (uint64_t JTAddress = MIB->getJumpTable(Instruction)) {
1987       OS << " # JUMPTABLE @0x" << Twine::utohexstr(JTAddress);
1988     } else {
1989       OS << " # UNKNOWN CONTROL FLOW";
1990     }
1991   }
1992   if (std::optional<uint32_t> Offset = MIB->getOffset(Instruction))
1993     OS << " # Offset: " << *Offset;
1994   if (std::optional<uint32_t> Size = MIB->getSize(Instruction))
1995     OS << " # Size: " << *Size;
1996   if (MCSymbol *Label = MIB->getInstLabel(Instruction))
1997     OS << " # Label: " << *Label;
1998 
1999   MIB->printAnnotations(Instruction, OS);
2000 
2001   if (opts::PrintDebugInfo)
2002     printDebugInfo(OS, Instruction, Function, DwCtx.get());
2003 
2004   if ((opts::PrintRelocations || PrintRelocations) && Function) {
2005     const uint64_t Size = computeCodeSize(&Instruction, &Instruction + 1);
2006     Function->printRelocations(OS, Offset, Size);
2007   }
2008 
2009   OS << Endl;
2010 
2011   if (PrintMCInst) {
2012     Instruction.dump_pretty(OS, InstPrinter.get());
2013     OS << Endl;
2014   }
2015 }
2016 
2017 std::optional<uint64_t>
2018 BinaryContext::getBaseAddressForMapping(uint64_t MMapAddress,
2019                                         uint64_t FileOffset) const {
2020   // Find a segment with a matching file offset.
2021   for (auto &KV : SegmentMapInfo) {
2022     const SegmentInfo &SegInfo = KV.second;
2023     // FileOffset is got from perf event,
2024     // and it is equal to alignDown(SegInfo.FileOffset, pagesize).
2025     // If the pagesize is not equal to SegInfo.Alignment.
2026     // FileOffset and SegInfo.FileOffset should be aligned first,
2027     // and then judge whether they are equal.
2028     if (alignDown(SegInfo.FileOffset, SegInfo.Alignment) ==
2029         alignDown(FileOffset, SegInfo.Alignment)) {
2030       // The function's offset from base address in VAS is aligned by pagesize
2031       // instead of SegInfo.Alignment. Pagesize can't be got from perf events.
2032       // However, The ELF document says that SegInfo.FileOffset should equal
2033       // to SegInfo.Address, modulo the pagesize.
2034       // Reference: https://refspecs.linuxfoundation.org/elf/elf.pdf
2035 
2036       // So alignDown(SegInfo.Address, pagesize) can be calculated by:
2037       // alignDown(SegInfo.Address, pagesize)
2038       //   = SegInfo.Address - (SegInfo.Address % pagesize)
2039       //   = SegInfo.Address - (SegInfo.FileOffset % pagesize)
2040       //   = SegInfo.Address - SegInfo.FileOffset +
2041       //     alignDown(SegInfo.FileOffset, pagesize)
2042       //   = SegInfo.Address - SegInfo.FileOffset + FileOffset
2043       return MMapAddress - (SegInfo.Address - SegInfo.FileOffset + FileOffset);
2044     }
2045   }
2046 
2047   return std::nullopt;
2048 }
2049 
2050 ErrorOr<BinarySection &> BinaryContext::getSectionForAddress(uint64_t Address) {
2051   auto SI = AddressToSection.upper_bound(Address);
2052   if (SI != AddressToSection.begin()) {
2053     --SI;
2054     uint64_t UpperBound = SI->first + SI->second->getSize();
2055     if (!SI->second->getSize())
2056       UpperBound += 1;
2057     if (UpperBound > Address)
2058       return *SI->second;
2059   }
2060   return std::make_error_code(std::errc::bad_address);
2061 }
2062 
2063 ErrorOr<StringRef>
2064 BinaryContext::getSectionNameForAddress(uint64_t Address) const {
2065   if (ErrorOr<const BinarySection &> Section = getSectionForAddress(Address))
2066     return Section->getName();
2067   return std::make_error_code(std::errc::bad_address);
2068 }
2069 
2070 BinarySection &BinaryContext::registerSection(BinarySection *Section) {
2071   auto Res = Sections.insert(Section);
2072   (void)Res;
2073   assert(Res.second && "can't register the same section twice.");
2074 
2075   // Only register allocatable sections in the AddressToSection map.
2076   if (Section->isAllocatable() && Section->getAddress())
2077     AddressToSection.insert(std::make_pair(Section->getAddress(), Section));
2078   NameToSection.insert(
2079       std::make_pair(std::string(Section->getName()), Section));
2080   if (Section->hasSectionRef())
2081     SectionRefToBinarySection.insert(
2082         std::make_pair(Section->getSectionRef(), Section));
2083 
2084   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: registering " << *Section << "\n");
2085   return *Section;
2086 }
2087 
2088 BinarySection &BinaryContext::registerSection(SectionRef Section) {
2089   return registerSection(new BinarySection(*this, Section));
2090 }
2091 
2092 BinarySection &
2093 BinaryContext::registerSection(const Twine &SectionName,
2094                                const BinarySection &OriginalSection) {
2095   return registerSection(
2096       new BinarySection(*this, SectionName, OriginalSection));
2097 }
2098 
2099 BinarySection &
2100 BinaryContext::registerOrUpdateSection(const Twine &Name, unsigned ELFType,
2101                                        unsigned ELFFlags, uint8_t *Data,
2102                                        uint64_t Size, unsigned Alignment) {
2103   auto NamedSections = getSectionByName(Name);
2104   if (NamedSections.begin() != NamedSections.end()) {
2105     assert(std::next(NamedSections.begin()) == NamedSections.end() &&
2106            "can only update unique sections");
2107     BinarySection *Section = NamedSections.begin()->second;
2108 
2109     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: updating " << *Section << " -> ");
2110     const bool Flag = Section->isAllocatable();
2111     (void)Flag;
2112     Section->update(Data, Size, Alignment, ELFType, ELFFlags);
2113     LLVM_DEBUG(dbgs() << *Section << "\n");
2114     // FIXME: Fix section flags/attributes for MachO.
2115     if (isELF())
2116       assert(Flag == Section->isAllocatable() &&
2117              "can't change section allocation status");
2118     return *Section;
2119   }
2120 
2121   return registerSection(
2122       new BinarySection(*this, Name, Data, Size, Alignment, ELFType, ELFFlags));
2123 }
2124 
2125 void BinaryContext::deregisterSectionName(const BinarySection &Section) {
2126   auto NameRange = NameToSection.equal_range(Section.getName().str());
2127   while (NameRange.first != NameRange.second) {
2128     if (NameRange.first->second == &Section) {
2129       NameToSection.erase(NameRange.first);
2130       break;
2131     }
2132     ++NameRange.first;
2133   }
2134 }
2135 
2136 void BinaryContext::deregisterUnusedSections() {
2137   ErrorOr<BinarySection &> AbsSection = getUniqueSectionByName("<absolute>");
2138   for (auto SI = Sections.begin(); SI != Sections.end();) {
2139     BinarySection *Section = *SI;
2140     // We check getOutputData() instead of getOutputSize() because sometimes
2141     // zero-sized .text.cold sections are allocated.
2142     if (Section->hasSectionRef() || Section->getOutputData() ||
2143         (AbsSection && Section == &AbsSection.get())) {
2144       ++SI;
2145       continue;
2146     }
2147 
2148     LLVM_DEBUG(dbgs() << "LLVM-DEBUG: deregistering " << Section->getName()
2149                       << '\n';);
2150     deregisterSectionName(*Section);
2151     SI = Sections.erase(SI);
2152     delete Section;
2153   }
2154 }
2155 
2156 bool BinaryContext::deregisterSection(BinarySection &Section) {
2157   BinarySection *SectionPtr = &Section;
2158   auto Itr = Sections.find(SectionPtr);
2159   if (Itr != Sections.end()) {
2160     auto Range = AddressToSection.equal_range(SectionPtr->getAddress());
2161     while (Range.first != Range.second) {
2162       if (Range.first->second == SectionPtr) {
2163         AddressToSection.erase(Range.first);
2164         break;
2165       }
2166       ++Range.first;
2167     }
2168 
2169     deregisterSectionName(*SectionPtr);
2170     Sections.erase(Itr);
2171     delete SectionPtr;
2172     return true;
2173   }
2174   return false;
2175 }
2176 
2177 void BinaryContext::renameSection(BinarySection &Section,
2178                                   const Twine &NewName) {
2179   auto Itr = Sections.find(&Section);
2180   assert(Itr != Sections.end() && "Section must exist to be renamed.");
2181   Sections.erase(Itr);
2182 
2183   deregisterSectionName(Section);
2184 
2185   Section.Name = NewName.str();
2186   Section.setOutputName(Section.Name);
2187 
2188   NameToSection.insert(std::make_pair(Section.Name, &Section));
2189 
2190   // Reinsert with the new name.
2191   Sections.insert(&Section);
2192 }
2193 
2194 void BinaryContext::printSections(raw_ostream &OS) const {
2195   for (BinarySection *const &Section : Sections)
2196     OS << "BOLT-INFO: " << *Section << "\n";
2197 }
2198 
2199 BinarySection &BinaryContext::absoluteSection() {
2200   if (ErrorOr<BinarySection &> Section = getUniqueSectionByName("<absolute>"))
2201     return *Section;
2202   return registerOrUpdateSection("<absolute>", ELF::SHT_NULL, 0u);
2203 }
2204 
2205 ErrorOr<uint64_t> BinaryContext::getUnsignedValueAtAddress(uint64_t Address,
2206                                                            size_t Size) const {
2207   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2208   if (!Section)
2209     return std::make_error_code(std::errc::bad_address);
2210 
2211   if (Section->isVirtual())
2212     return 0;
2213 
2214   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
2215                    AsmInfo->getCodePointerSize());
2216   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
2217   return DE.getUnsigned(&ValueOffset, Size);
2218 }
2219 
2220 ErrorOr<int64_t> BinaryContext::getSignedValueAtAddress(uint64_t Address,
2221                                                         size_t Size) const {
2222   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2223   if (!Section)
2224     return std::make_error_code(std::errc::bad_address);
2225 
2226   if (Section->isVirtual())
2227     return 0;
2228 
2229   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
2230                    AsmInfo->getCodePointerSize());
2231   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
2232   return DE.getSigned(&ValueOffset, Size);
2233 }
2234 
2235 void BinaryContext::addRelocation(uint64_t Address, MCSymbol *Symbol,
2236                                   uint64_t Type, uint64_t Addend,
2237                                   uint64_t Value) {
2238   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2239   assert(Section && "cannot find section for address");
2240   Section->addRelocation(Address - Section->getAddress(), Symbol, Type, Addend,
2241                          Value);
2242 }
2243 
2244 void BinaryContext::addDynamicRelocation(uint64_t Address, MCSymbol *Symbol,
2245                                          uint64_t Type, uint64_t Addend,
2246                                          uint64_t Value) {
2247   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2248   assert(Section && "cannot find section for address");
2249   Section->addDynamicRelocation(Address - Section->getAddress(), Symbol, Type,
2250                                 Addend, Value);
2251 }
2252 
2253 bool BinaryContext::removeRelocationAt(uint64_t Address) {
2254   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2255   assert(Section && "cannot find section for address");
2256   return Section->removeRelocationAt(Address - Section->getAddress());
2257 }
2258 
2259 const Relocation *BinaryContext::getRelocationAt(uint64_t Address) const {
2260   ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2261   if (!Section)
2262     return nullptr;
2263 
2264   return Section->getRelocationAt(Address - Section->getAddress());
2265 }
2266 
2267 const Relocation *
2268 BinaryContext::getDynamicRelocationAt(uint64_t Address) const {
2269   ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2270   if (!Section)
2271     return nullptr;
2272 
2273   return Section->getDynamicRelocationAt(Address - Section->getAddress());
2274 }
2275 
2276 void BinaryContext::markAmbiguousRelocations(BinaryData &BD,
2277                                              const uint64_t Address) {
2278   auto setImmovable = [&](BinaryData &BD) {
2279     BinaryData *Root = BD.getAtomicRoot();
2280     LLVM_DEBUG(if (Root->isMoveable()) {
2281       dbgs() << "BOLT-DEBUG: setting " << *Root << " as immovable "
2282              << "due to ambiguous relocation referencing 0x"
2283              << Twine::utohexstr(Address) << '\n';
2284     });
2285     Root->setIsMoveable(false);
2286   };
2287 
2288   if (Address == BD.getAddress()) {
2289     setImmovable(BD);
2290 
2291     // Set previous symbol as immovable
2292     BinaryData *Prev = getBinaryDataContainingAddress(Address - 1);
2293     if (Prev && Prev->getEndAddress() == BD.getAddress())
2294       setImmovable(*Prev);
2295   }
2296 
2297   if (Address == BD.getEndAddress()) {
2298     setImmovable(BD);
2299 
2300     // Set next symbol as immovable
2301     BinaryData *Next = getBinaryDataContainingAddress(BD.getEndAddress());
2302     if (Next && Next->getAddress() == BD.getEndAddress())
2303       setImmovable(*Next);
2304   }
2305 }
2306 
2307 BinaryFunction *BinaryContext::getFunctionForSymbol(const MCSymbol *Symbol,
2308                                                     uint64_t *EntryDesc) {
2309   std::shared_lock<llvm::sys::RWMutex> Lock(SymbolToFunctionMapMutex);
2310   auto BFI = SymbolToFunctionMap.find(Symbol);
2311   if (BFI == SymbolToFunctionMap.end())
2312     return nullptr;
2313 
2314   BinaryFunction *BF = BFI->second;
2315   if (EntryDesc)
2316     *EntryDesc = BF->getEntryIDForSymbol(Symbol);
2317 
2318   return BF;
2319 }
2320 
2321 std::string
2322 BinaryContext::generateBugReportMessage(StringRef Message,
2323                                         const BinaryFunction &Function) const {
2324   std::string Msg;
2325   raw_string_ostream SS(Msg);
2326   SS << "=======================================\n";
2327   SS << "BOLT is unable to proceed because it couldn't properly understand "
2328         "this function.\n";
2329   SS << "If you are running the most recent version of BOLT, you may "
2330         "want to "
2331         "report this and paste this dump.\nPlease check that there is no "
2332         "sensitive contents being shared in this dump.\n";
2333   SS << "\nOffending function: " << Function.getPrintName() << "\n\n";
2334   ScopedPrinter SP(SS);
2335   SP.printBinaryBlock("Function contents", *Function.getData());
2336   SS << "\n";
2337   const_cast<BinaryFunction &>(Function).print(SS, "");
2338   SS << "ERROR: " << Message;
2339   SS << "\n=======================================\n";
2340   return Msg;
2341 }
2342 
2343 BinaryFunction *
2344 BinaryContext::createInjectedBinaryFunction(const std::string &Name,
2345                                             bool IsSimple) {
2346   InjectedBinaryFunctions.push_back(new BinaryFunction(Name, *this, IsSimple));
2347   BinaryFunction *BF = InjectedBinaryFunctions.back();
2348   setSymbolToFunctionMap(BF->getSymbol(), BF);
2349   BF->CurrentState = BinaryFunction::State::CFG;
2350   return BF;
2351 }
2352 
2353 std::pair<size_t, size_t>
2354 BinaryContext::calculateEmittedSize(BinaryFunction &BF, bool FixBranches) {
2355   // Adjust branch instruction to match the current layout.
2356   if (FixBranches)
2357     BF.fixBranches();
2358 
2359   // Create local MC context to isolate the effect of ephemeral code emission.
2360   IndependentCodeEmitter MCEInstance = createIndependentMCCodeEmitter();
2361   MCContext *LocalCtx = MCEInstance.LocalCtx.get();
2362   MCAsmBackend *MAB =
2363       TheTarget->createMCAsmBackend(*STI, *MRI, MCTargetOptions());
2364 
2365   SmallString<256> Code;
2366   raw_svector_ostream VecOS(Code);
2367 
2368   std::unique_ptr<MCObjectWriter> OW = MAB->createObjectWriter(VecOS);
2369   std::unique_ptr<MCStreamer> Streamer(TheTarget->createMCObjectStreamer(
2370       *TheTriple, *LocalCtx, std::unique_ptr<MCAsmBackend>(MAB), std::move(OW),
2371       std::unique_ptr<MCCodeEmitter>(MCEInstance.MCE.release()), *STI));
2372 
2373   Streamer->initSections(false, *STI);
2374 
2375   MCSection *Section = MCEInstance.LocalMOFI->getTextSection();
2376   Section->setHasInstructions(true);
2377 
2378   // Create symbols in the LocalCtx so that they get destroyed with it.
2379   MCSymbol *StartLabel = LocalCtx->createTempSymbol();
2380   MCSymbol *EndLabel = LocalCtx->createTempSymbol();
2381 
2382   Streamer->switchSection(Section);
2383   Streamer->emitLabel(StartLabel);
2384   emitFunctionBody(*Streamer, BF, BF.getLayout().getMainFragment(),
2385                    /*EmitCodeOnly=*/true);
2386   Streamer->emitLabel(EndLabel);
2387 
2388   using LabelRange = std::pair<const MCSymbol *, const MCSymbol *>;
2389   SmallVector<LabelRange> SplitLabels;
2390   for (FunctionFragment &FF : BF.getLayout().getSplitFragments()) {
2391     MCSymbol *const SplitStartLabel = LocalCtx->createTempSymbol();
2392     MCSymbol *const SplitEndLabel = LocalCtx->createTempSymbol();
2393     SplitLabels.emplace_back(SplitStartLabel, SplitEndLabel);
2394 
2395     MCSectionELF *const SplitSection = LocalCtx->getELFSection(
2396         BF.getCodeSectionName(FF.getFragmentNum()), ELF::SHT_PROGBITS,
2397         ELF::SHF_EXECINSTR | ELF::SHF_ALLOC);
2398     SplitSection->setHasInstructions(true);
2399     Streamer->switchSection(SplitSection);
2400 
2401     Streamer->emitLabel(SplitStartLabel);
2402     emitFunctionBody(*Streamer, BF, FF, /*EmitCodeOnly=*/true);
2403     Streamer->emitLabel(SplitEndLabel);
2404   }
2405 
2406   MCAssembler &Assembler =
2407       static_cast<MCObjectStreamer *>(Streamer.get())->getAssembler();
2408   Assembler.layout();
2409 
2410   // Obtain fragment sizes.
2411   std::vector<uint64_t> FragmentSizes;
2412   // Main fragment size.
2413   const uint64_t HotSize = Assembler.getSymbolOffset(*EndLabel) -
2414                            Assembler.getSymbolOffset(*StartLabel);
2415   FragmentSizes.push_back(HotSize);
2416   // Split fragment sizes.
2417   uint64_t ColdSize = 0;
2418   for (const auto &Labels : SplitLabels) {
2419     uint64_t Size = Assembler.getSymbolOffset(*Labels.second) -
2420                     Assembler.getSymbolOffset(*Labels.first);
2421     FragmentSizes.push_back(Size);
2422     ColdSize += Size;
2423   }
2424 
2425   // Populate new start and end offsets of each basic block.
2426   uint64_t FragmentIndex = 0;
2427   for (FunctionFragment &FF : BF.getLayout().fragments()) {
2428     BinaryBasicBlock *PrevBB = nullptr;
2429     for (BinaryBasicBlock *BB : FF) {
2430       const uint64_t BBStartOffset =
2431           Assembler.getSymbolOffset(*(BB->getLabel()));
2432       BB->setOutputStartAddress(BBStartOffset);
2433       if (PrevBB)
2434         PrevBB->setOutputEndAddress(BBStartOffset);
2435       PrevBB = BB;
2436     }
2437     if (PrevBB)
2438       PrevBB->setOutputEndAddress(FragmentSizes[FragmentIndex]);
2439     FragmentIndex++;
2440   }
2441 
2442   // Clean-up the effect of the code emission.
2443   for (const MCSymbol &Symbol : Assembler.symbols()) {
2444     MCSymbol *MutableSymbol = const_cast<MCSymbol *>(&Symbol);
2445     MutableSymbol->setUndefined();
2446     MutableSymbol->setIsRegistered(false);
2447   }
2448 
2449   return std::make_pair(HotSize, ColdSize);
2450 }
2451 
2452 bool BinaryContext::validateInstructionEncoding(
2453     ArrayRef<uint8_t> InputSequence) const {
2454   MCInst Inst;
2455   uint64_t InstSize;
2456   DisAsm->getInstruction(Inst, InstSize, InputSequence, 0, nulls());
2457   assert(InstSize == InputSequence.size() &&
2458          "Disassembled instruction size does not match the sequence.");
2459 
2460   SmallString<256> Code;
2461   SmallVector<MCFixup, 4> Fixups;
2462 
2463   MCE->encodeInstruction(Inst, Code, Fixups, *STI);
2464   auto OutputSequence = ArrayRef<uint8_t>((uint8_t *)Code.data(), Code.size());
2465   if (InputSequence != OutputSequence) {
2466     if (opts::Verbosity > 1) {
2467       this->errs() << "BOLT-WARNING: mismatched encoding detected\n"
2468                    << "      input: " << InputSequence << '\n'
2469                    << "     output: " << OutputSequence << '\n';
2470     }
2471     return false;
2472   }
2473 
2474   return true;
2475 }
2476 
2477 uint64_t BinaryContext::getHotThreshold() const {
2478   static uint64_t Threshold = 0;
2479   if (Threshold == 0) {
2480     Threshold = std::max(
2481         (uint64_t)opts::ExecutionCountThreshold,
2482         NumProfiledFuncs ? SumExecutionCount / (2 * NumProfiledFuncs) : 1);
2483   }
2484   return Threshold;
2485 }
2486 
2487 BinaryFunction *BinaryContext::getBinaryFunctionContainingAddress(
2488     uint64_t Address, bool CheckPastEnd, bool UseMaxSize) {
2489   auto FI = BinaryFunctions.upper_bound(Address);
2490   if (FI == BinaryFunctions.begin())
2491     return nullptr;
2492   --FI;
2493 
2494   const uint64_t UsedSize =
2495       UseMaxSize ? FI->second.getMaxSize() : FI->second.getSize();
2496 
2497   if (Address >= FI->first + UsedSize + (CheckPastEnd ? 1 : 0))
2498     return nullptr;
2499 
2500   return &FI->second;
2501 }
2502 
2503 BinaryFunction *BinaryContext::getBinaryFunctionAtAddress(uint64_t Address) {
2504   // First, try to find a function starting at the given address. If the
2505   // function was folded, this will get us the original folded function if it
2506   // wasn't removed from the list, e.g. in non-relocation mode.
2507   auto BFI = BinaryFunctions.find(Address);
2508   if (BFI != BinaryFunctions.end())
2509     return &BFI->second;
2510 
2511   // We might have folded the function matching the object at the given
2512   // address. In such case, we look for a function matching the symbol
2513   // registered at the original address. The new function (the one that the
2514   // original was folded into) will hold the symbol.
2515   if (const BinaryData *BD = getBinaryDataAtAddress(Address)) {
2516     uint64_t EntryID = 0;
2517     BinaryFunction *BF = getFunctionForSymbol(BD->getSymbol(), &EntryID);
2518     if (BF && EntryID == 0)
2519       return BF;
2520   }
2521   return nullptr;
2522 }
2523 
2524 /// Deregister JumpTable registered at a given \p Address and delete it.
2525 void BinaryContext::deleteJumpTable(uint64_t Address) {
2526   assert(JumpTables.count(Address) && "Must have a jump table at address");
2527   JumpTable *JT = JumpTables.at(Address);
2528   for (BinaryFunction *Parent : JT->Parents)
2529     Parent->JumpTables.erase(Address);
2530   JumpTables.erase(Address);
2531   delete JT;
2532 }
2533 
2534 DebugAddressRangesVector BinaryContext::translateModuleAddressRanges(
2535     const DWARFAddressRangesVector &InputRanges) const {
2536   DebugAddressRangesVector OutputRanges;
2537 
2538   for (const DWARFAddressRange Range : InputRanges) {
2539     auto BFI = BinaryFunctions.lower_bound(Range.LowPC);
2540     while (BFI != BinaryFunctions.end()) {
2541       const BinaryFunction &Function = BFI->second;
2542       if (Function.getAddress() >= Range.HighPC)
2543         break;
2544       const DebugAddressRangesVector FunctionRanges =
2545           Function.getOutputAddressRanges();
2546       llvm::move(FunctionRanges, std::back_inserter(OutputRanges));
2547       std::advance(BFI, 1);
2548     }
2549   }
2550 
2551   return OutputRanges;
2552 }
2553 
2554 } // namespace bolt
2555 } // namespace llvm
2556