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