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     std::for_each(BF->Fragments.begin(), BF->Fragments.end(), addToWorklist);
722     std::for_each(BF->ParentFragments.begin(), BF->ParentFragments.end(),
723                   addToWorklist);
724   }
725   if (!FragmentsToSkip.empty())
726     errs() << "BOLT-WARNING: skipped " << FragmentsToSkip.size() << " function"
727            << (FragmentsToSkip.size() == 1 ? "" : "s")
728            << " due to cold fragments\n";
729   FragmentsToSkip.clear();
730 }
731 
732 MCSymbol *BinaryContext::getOrCreateGlobalSymbol(uint64_t Address, Twine Prefix,
733                                                  uint64_t Size,
734                                                  uint16_t Alignment,
735                                                  unsigned Flags) {
736   auto Itr = BinaryDataMap.find(Address);
737   if (Itr != BinaryDataMap.end()) {
738     assert(Itr->second->getSize() == Size || !Size);
739     return Itr->second->getSymbol();
740   }
741 
742   std::string Name = (Prefix + "0x" + Twine::utohexstr(Address)).str();
743   assert(!GlobalSymbols.count(Name) && "created name is not unique");
744   return registerNameAtAddress(Name, Address, Size, Alignment, Flags);
745 }
746 
747 MCSymbol *BinaryContext::getOrCreateUndefinedGlobalSymbol(StringRef Name) {
748   return Ctx->getOrCreateSymbol(Name);
749 }
750 
751 BinaryFunction *BinaryContext::createBinaryFunction(
752     const std::string &Name, BinarySection &Section, uint64_t Address,
753     uint64_t Size, uint64_t SymbolSize, uint16_t Alignment) {
754   auto Result = BinaryFunctions.emplace(
755       Address, BinaryFunction(Name, Section, Address, Size, *this));
756   assert(Result.second == true && "unexpected duplicate function");
757   BinaryFunction *BF = &Result.first->second;
758   registerNameAtAddress(Name, Address, SymbolSize ? SymbolSize : Size,
759                         Alignment);
760   setSymbolToFunctionMap(BF->getSymbol(), BF);
761   return BF;
762 }
763 
764 const MCSymbol *
765 BinaryContext::getOrCreateJumpTable(BinaryFunction &Function, uint64_t Address,
766                                     JumpTable::JumpTableType Type) {
767   if (JumpTable *JT = getJumpTableContainingAddress(Address)) {
768     assert(JT->Type == Type && "jump table types have to match");
769     assert(JT->Parent == &Function &&
770            "cannot re-use jump table of a different function");
771     assert(Address == JT->getAddress() && "unexpected non-empty jump table");
772 
773     return JT->getFirstLabel();
774   }
775 
776   // Re-use the existing symbol if possible.
777   MCSymbol *JTLabel = nullptr;
778   if (BinaryData *Object = getBinaryDataAtAddress(Address)) {
779     if (!isInternalSymbolName(Object->getSymbol()->getName()))
780       JTLabel = Object->getSymbol();
781   }
782 
783   const uint64_t EntrySize = getJumpTableEntrySize(Type);
784   if (!JTLabel) {
785     const std::string JumpTableName = generateJumpTableName(Function, Address);
786     JTLabel = registerNameAtAddress(JumpTableName, Address, 0, EntrySize);
787   }
788 
789   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: creating jump table " << JTLabel->getName()
790                     << " in function " << Function << '\n');
791 
792   JumpTable *JT = new JumpTable(*JTLabel, Address, EntrySize, Type,
793                                 JumpTable::LabelMapType{{0, JTLabel}}, Function,
794                                 *getSectionForAddress(Address));
795   JumpTables.emplace(Address, JT);
796 
797   // Duplicate the entry for the parent function for easy access.
798   Function.JumpTables.emplace(Address, JT);
799 
800   return JTLabel;
801 }
802 
803 std::pair<uint64_t, const MCSymbol *>
804 BinaryContext::duplicateJumpTable(BinaryFunction &Function, JumpTable *JT,
805                                   const MCSymbol *OldLabel) {
806   auto L = scopeLock();
807   unsigned Offset = 0;
808   bool Found = false;
809   for (std::pair<const unsigned, MCSymbol *> Elmt : JT->Labels) {
810     if (Elmt.second != OldLabel)
811       continue;
812     Offset = Elmt.first;
813     Found = true;
814     break;
815   }
816   assert(Found && "Label not found");
817   (void)Found;
818   MCSymbol *NewLabel = Ctx->createNamedTempSymbol("duplicatedJT");
819   JumpTable *NewJT =
820       new JumpTable(*NewLabel, JT->getAddress(), JT->EntrySize, JT->Type,
821                     JumpTable::LabelMapType{{Offset, NewLabel}}, Function,
822                     *getSectionForAddress(JT->getAddress()));
823   NewJT->Entries = JT->Entries;
824   NewJT->Counts = JT->Counts;
825   uint64_t JumpTableID = ++DuplicatedJumpTables;
826   // Invert it to differentiate from regular jump tables whose IDs are their
827   // addresses in the input binary memory space
828   JumpTableID = ~JumpTableID;
829   JumpTables.emplace(JumpTableID, NewJT);
830   Function.JumpTables.emplace(JumpTableID, NewJT);
831   return std::make_pair(JumpTableID, NewLabel);
832 }
833 
834 std::string BinaryContext::generateJumpTableName(const BinaryFunction &BF,
835                                                  uint64_t Address) {
836   size_t Id;
837   uint64_t Offset = 0;
838   if (const JumpTable *JT = BF.getJumpTableContainingAddress(Address)) {
839     Offset = Address - JT->getAddress();
840     auto Itr = JT->Labels.find(Offset);
841     if (Itr != JT->Labels.end())
842       return std::string(Itr->second->getName());
843     Id = JumpTableIds.at(JT->getAddress());
844   } else {
845     Id = JumpTableIds[Address] = BF.JumpTables.size();
846   }
847   return ("JUMP_TABLE/" + BF.getOneName().str() + "." + std::to_string(Id) +
848           (Offset ? ("." + std::to_string(Offset)) : ""));
849 }
850 
851 bool BinaryContext::hasValidCodePadding(const BinaryFunction &BF) {
852   // FIXME: aarch64 support is missing.
853   if (!isX86())
854     return true;
855 
856   if (BF.getSize() == BF.getMaxSize())
857     return true;
858 
859   ErrorOr<ArrayRef<unsigned char>> FunctionData = BF.getData();
860   assert(FunctionData && "cannot get function as data");
861 
862   uint64_t Offset = BF.getSize();
863   MCInst Instr;
864   uint64_t InstrSize = 0;
865   uint64_t InstrAddress = BF.getAddress() + Offset;
866   using std::placeholders::_1;
867 
868   // Skip instructions that satisfy the predicate condition.
869   auto skipInstructions = [&](std::function<bool(const MCInst &)> Predicate) {
870     const uint64_t StartOffset = Offset;
871     for (; Offset < BF.getMaxSize();
872          Offset += InstrSize, InstrAddress += InstrSize) {
873       if (!DisAsm->getInstruction(Instr, InstrSize, FunctionData->slice(Offset),
874                                   InstrAddress, nulls()))
875         break;
876       if (!Predicate(Instr))
877         break;
878     }
879 
880     return Offset - StartOffset;
881   };
882 
883   // Skip a sequence of zero bytes.
884   auto skipZeros = [&]() {
885     const uint64_t StartOffset = Offset;
886     for (; Offset < BF.getMaxSize(); ++Offset)
887       if ((*FunctionData)[Offset] != 0)
888         break;
889 
890     return Offset - StartOffset;
891   };
892 
893   // Accept the whole padding area filled with breakpoints.
894   auto isBreakpoint = std::bind(&MCPlusBuilder::isBreakpoint, MIB.get(), _1);
895   if (skipInstructions(isBreakpoint) && Offset == BF.getMaxSize())
896     return true;
897 
898   auto isNoop = std::bind(&MCPlusBuilder::isNoop, MIB.get(), _1);
899 
900   // Some functions have a jump to the next function or to the padding area
901   // inserted after the body.
902   auto isSkipJump = [&](const MCInst &Instr) {
903     uint64_t TargetAddress = 0;
904     if (MIB->isUnconditionalBranch(Instr) &&
905         MIB->evaluateBranch(Instr, InstrAddress, InstrSize, TargetAddress)) {
906       if (TargetAddress >= InstrAddress + InstrSize &&
907           TargetAddress <= BF.getAddress() + BF.getMaxSize()) {
908         return true;
909       }
910     }
911     return false;
912   };
913 
914   // Skip over nops, jumps, and zero padding. Allow interleaving (this happens).
915   while (skipInstructions(isNoop) || skipInstructions(isSkipJump) ||
916          skipZeros())
917     ;
918 
919   if (Offset == BF.getMaxSize())
920     return true;
921 
922   if (opts::Verbosity >= 1) {
923     errs() << "BOLT-WARNING: bad padding at address 0x"
924            << Twine::utohexstr(BF.getAddress() + BF.getSize())
925            << " starting at offset " << (Offset - BF.getSize())
926            << " in function " << BF << '\n'
927            << FunctionData->slice(BF.getSize(), BF.getMaxSize() - BF.getSize())
928            << '\n';
929   }
930 
931   return false;
932 }
933 
934 void BinaryContext::adjustCodePadding() {
935   for (auto &BFI : BinaryFunctions) {
936     BinaryFunction &BF = BFI.second;
937     if (!shouldEmit(BF))
938       continue;
939 
940     if (!hasValidCodePadding(BF)) {
941       if (HasRelocations) {
942         if (opts::Verbosity >= 1) {
943           outs() << "BOLT-INFO: function " << BF
944                  << " has invalid padding. Ignoring the function.\n";
945         }
946         BF.setIgnored();
947       } else {
948         BF.setMaxSize(BF.getSize());
949       }
950     }
951   }
952 }
953 
954 MCSymbol *BinaryContext::registerNameAtAddress(StringRef Name, uint64_t Address,
955                                                uint64_t Size,
956                                                uint16_t Alignment,
957                                                unsigned Flags) {
958   // Register the name with MCContext.
959   MCSymbol *Symbol = Ctx->getOrCreateSymbol(Name);
960 
961   auto GAI = BinaryDataMap.find(Address);
962   BinaryData *BD;
963   if (GAI == BinaryDataMap.end()) {
964     ErrorOr<BinarySection &> SectionOrErr = getSectionForAddress(Address);
965     BinarySection &Section =
966         SectionOrErr ? SectionOrErr.get() : absoluteSection();
967     BD = new BinaryData(*Symbol, Address, Size, Alignment ? Alignment : 1,
968                         Section, Flags);
969     GAI = BinaryDataMap.emplace(Address, BD).first;
970     GlobalSymbols[Name] = BD;
971     updateObjectNesting(GAI);
972   } else {
973     BD = GAI->second;
974     if (!BD->hasName(Name)) {
975       GlobalSymbols[Name] = BD;
976       BD->Symbols.push_back(Symbol);
977     }
978   }
979 
980   return Symbol;
981 }
982 
983 const BinaryData *
984 BinaryContext::getBinaryDataContainingAddressImpl(uint64_t Address) const {
985   auto NI = BinaryDataMap.lower_bound(Address);
986   auto End = BinaryDataMap.end();
987   if ((NI != End && Address == NI->first) ||
988       ((NI != BinaryDataMap.begin()) && (NI-- != BinaryDataMap.begin()))) {
989     if (NI->second->containsAddress(Address))
990       return NI->second;
991 
992     // If this is a sub-symbol, see if a parent data contains the address.
993     const BinaryData *BD = NI->second->getParent();
994     while (BD) {
995       if (BD->containsAddress(Address))
996         return BD;
997       BD = BD->getParent();
998     }
999   }
1000   return nullptr;
1001 }
1002 
1003 bool BinaryContext::setBinaryDataSize(uint64_t Address, uint64_t Size) {
1004   auto NI = BinaryDataMap.find(Address);
1005   assert(NI != BinaryDataMap.end());
1006   if (NI == BinaryDataMap.end())
1007     return false;
1008   // TODO: it's possible that a jump table starts at the same address
1009   // as a larger blob of private data.  When we set the size of the
1010   // jump table, it might be smaller than the total blob size.  In this
1011   // case we just leave the original size since (currently) it won't really
1012   // affect anything.
1013   assert((!NI->second->Size || NI->second->Size == Size ||
1014           (NI->second->isJumpTable() && NI->second->Size > Size)) &&
1015          "can't change the size of a symbol that has already had its "
1016          "size set");
1017   if (!NI->second->Size) {
1018     NI->second->Size = Size;
1019     updateObjectNesting(NI);
1020     return true;
1021   }
1022   return false;
1023 }
1024 
1025 void BinaryContext::generateSymbolHashes() {
1026   auto isPadding = [](const BinaryData &BD) {
1027     StringRef Contents = BD.getSection().getContents();
1028     StringRef SymData = Contents.substr(BD.getOffset(), BD.getSize());
1029     return (BD.getName().startswith("HOLEat") ||
1030             SymData.find_first_not_of(0) == StringRef::npos);
1031   };
1032 
1033   uint64_t NumCollisions = 0;
1034   for (auto &Entry : BinaryDataMap) {
1035     BinaryData &BD = *Entry.second;
1036     StringRef Name = BD.getName();
1037 
1038     if (!isInternalSymbolName(Name))
1039       continue;
1040 
1041     // First check if a non-anonymous alias exists and move it to the front.
1042     if (BD.getSymbols().size() > 1) {
1043       auto Itr = std::find_if(BD.getSymbols().begin(), BD.getSymbols().end(),
1044                               [&](const MCSymbol *Symbol) {
1045                                 return !isInternalSymbolName(Symbol->getName());
1046                               });
1047       if (Itr != BD.getSymbols().end()) {
1048         size_t Idx = std::distance(BD.getSymbols().begin(), Itr);
1049         std::swap(BD.getSymbols()[0], BD.getSymbols()[Idx]);
1050         continue;
1051       }
1052     }
1053 
1054     // We have to skip 0 size symbols since they will all collide.
1055     if (BD.getSize() == 0) {
1056       continue;
1057     }
1058 
1059     const uint64_t Hash = BD.getSection().hash(BD);
1060     const size_t Idx = Name.find("0x");
1061     std::string NewName =
1062         (Twine(Name.substr(0, Idx)) + "_" + Twine::utohexstr(Hash)).str();
1063     if (getBinaryDataByName(NewName)) {
1064       // Ignore collisions for symbols that appear to be padding
1065       // (i.e. all zeros or a "hole")
1066       if (!isPadding(BD)) {
1067         if (opts::Verbosity) {
1068           errs() << "BOLT-WARNING: collision detected when hashing " << BD
1069                  << " with new name (" << NewName << "), skipping.\n";
1070         }
1071         ++NumCollisions;
1072       }
1073       continue;
1074     }
1075     BD.Symbols.insert(BD.Symbols.begin(), Ctx->getOrCreateSymbol(NewName));
1076     GlobalSymbols[NewName] = &BD;
1077   }
1078   if (NumCollisions) {
1079     errs() << "BOLT-WARNING: " << NumCollisions
1080            << " collisions detected while hashing binary objects";
1081     if (!opts::Verbosity)
1082       errs() << ". Use -v=1 to see the list.";
1083     errs() << '\n';
1084   }
1085 }
1086 
1087 bool BinaryContext::registerFragment(BinaryFunction &TargetFunction,
1088                                      BinaryFunction &Function) const {
1089   if (!isPotentialFragmentByName(TargetFunction, Function))
1090     return false;
1091   assert(TargetFunction.isFragment() && "TargetFunction must be a fragment");
1092   if (TargetFunction.isParentFragment(&Function))
1093     return true;
1094   TargetFunction.addParentFragment(Function);
1095   Function.addFragment(TargetFunction);
1096   if (!HasRelocations) {
1097     TargetFunction.setSimple(false);
1098     Function.setSimple(false);
1099   }
1100   if (opts::Verbosity >= 1) {
1101     outs() << "BOLT-INFO: marking " << TargetFunction << " as a fragment of "
1102            << Function << '\n';
1103   }
1104   return true;
1105 }
1106 
1107 void BinaryContext::processInterproceduralReferences(BinaryFunction &Function) {
1108   for (uint64_t Address : Function.InterproceduralReferences) {
1109     if (!Address)
1110       continue;
1111 
1112     BinaryFunction *TargetFunction =
1113         getBinaryFunctionContainingAddress(Address);
1114     if (&Function == TargetFunction)
1115       continue;
1116 
1117     if (TargetFunction) {
1118       if (TargetFunction->IsFragment &&
1119           !registerFragment(*TargetFunction, Function)) {
1120         errs() << "BOLT-WARNING: interprocedural reference between unrelated "
1121                   "fragments: "
1122                << Function.getPrintName() << " and "
1123                << TargetFunction->getPrintName() << '\n';
1124       }
1125       if (uint64_t Offset = Address - TargetFunction->getAddress())
1126         TargetFunction->addEntryPointAtOffset(Offset);
1127 
1128       continue;
1129     }
1130 
1131     // Check if address falls in function padding space - this could be
1132     // unmarked data in code. In this case adjust the padding space size.
1133     ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1134     assert(Section && "cannot get section for referenced address");
1135 
1136     if (!Section->isText())
1137       continue;
1138 
1139     // PLT requires special handling and could be ignored in this context.
1140     StringRef SectionName = Section->getName();
1141     if (SectionName == ".plt" || SectionName == ".plt.got")
1142       continue;
1143 
1144     if (opts::processAllFunctions()) {
1145       errs() << "BOLT-ERROR: cannot process binaries with unmarked "
1146              << "object in code at address 0x" << Twine::utohexstr(Address)
1147              << " belonging to section " << SectionName << " in current mode\n";
1148       exit(1);
1149     }
1150 
1151     TargetFunction = getBinaryFunctionContainingAddress(Address,
1152                                                         /*CheckPastEnd=*/false,
1153                                                         /*UseMaxSize=*/true);
1154     // We are not going to overwrite non-simple functions, but for simple
1155     // ones - adjust the padding size.
1156     if (TargetFunction && TargetFunction->isSimple()) {
1157       errs() << "BOLT-WARNING: function " << *TargetFunction
1158              << " has an object detected in a padding region at address 0x"
1159              << Twine::utohexstr(Address) << '\n';
1160       TargetFunction->setMaxSize(TargetFunction->getSize());
1161     }
1162   }
1163 
1164   clearList(Function.InterproceduralReferences);
1165 }
1166 
1167 void BinaryContext::postProcessSymbolTable() {
1168   fixBinaryDataHoles();
1169   bool Valid = true;
1170   for (auto &Entry : BinaryDataMap) {
1171     BinaryData *BD = Entry.second;
1172     if ((BD->getName().startswith("SYMBOLat") ||
1173          BD->getName().startswith("DATAat")) &&
1174         !BD->getParent() && !BD->getSize() && !BD->isAbsolute() &&
1175         BD->getSection()) {
1176       errs() << "BOLT-WARNING: zero-sized top level symbol: " << *BD << "\n";
1177       Valid = false;
1178     }
1179   }
1180   assert(Valid);
1181   (void)Valid;
1182   generateSymbolHashes();
1183 }
1184 
1185 void BinaryContext::foldFunction(BinaryFunction &ChildBF,
1186                                  BinaryFunction &ParentBF) {
1187   assert(!ChildBF.isMultiEntry() && !ParentBF.isMultiEntry() &&
1188          "cannot merge functions with multiple entry points");
1189 
1190   std::unique_lock<std::shared_timed_mutex> WriteCtxLock(CtxMutex,
1191                                                          std::defer_lock);
1192   std::unique_lock<std::shared_timed_mutex> WriteSymbolMapLock(
1193       SymbolToFunctionMapMutex, std::defer_lock);
1194 
1195   const StringRef ChildName = ChildBF.getOneName();
1196 
1197   // Move symbols over and update bookkeeping info.
1198   for (MCSymbol *Symbol : ChildBF.getSymbols()) {
1199     ParentBF.getSymbols().push_back(Symbol);
1200     WriteSymbolMapLock.lock();
1201     SymbolToFunctionMap[Symbol] = &ParentBF;
1202     WriteSymbolMapLock.unlock();
1203     // NB: there's no need to update BinaryDataMap and GlobalSymbols.
1204   }
1205   ChildBF.getSymbols().clear();
1206 
1207   // Move other names the child function is known under.
1208   std::move(ChildBF.Aliases.begin(), ChildBF.Aliases.end(),
1209             std::back_inserter(ParentBF.Aliases));
1210   ChildBF.Aliases.clear();
1211 
1212   if (HasRelocations) {
1213     // Merge execution counts of ChildBF into those of ParentBF.
1214     // Without relocations, we cannot reliably merge profiles as both functions
1215     // continue to exist and either one can be executed.
1216     ChildBF.mergeProfileDataInto(ParentBF);
1217 
1218     std::shared_lock<std::shared_timed_mutex> ReadBfsLock(BinaryFunctionsMutex,
1219                                                           std::defer_lock);
1220     std::unique_lock<std::shared_timed_mutex> WriteBfsLock(BinaryFunctionsMutex,
1221                                                            std::defer_lock);
1222     // Remove ChildBF from the global set of functions in relocs mode.
1223     ReadBfsLock.lock();
1224     auto FI = BinaryFunctions.find(ChildBF.getAddress());
1225     ReadBfsLock.unlock();
1226 
1227     assert(FI != BinaryFunctions.end() && "function not found");
1228     assert(&ChildBF == &FI->second && "function mismatch");
1229 
1230     WriteBfsLock.lock();
1231     ChildBF.clearDisasmState();
1232     FI = BinaryFunctions.erase(FI);
1233     WriteBfsLock.unlock();
1234 
1235   } else {
1236     // In non-relocation mode we keep the function, but rename it.
1237     std::string NewName = "__ICF_" + ChildName.str();
1238 
1239     WriteCtxLock.lock();
1240     ChildBF.getSymbols().push_back(Ctx->getOrCreateSymbol(NewName));
1241     WriteCtxLock.unlock();
1242 
1243     ChildBF.setFolded(&ParentBF);
1244   }
1245 }
1246 
1247 void BinaryContext::fixBinaryDataHoles() {
1248   assert(validateObjectNesting() && "object nesting inconsitency detected");
1249 
1250   for (BinarySection &Section : allocatableSections()) {
1251     std::vector<std::pair<uint64_t, uint64_t>> Holes;
1252 
1253     auto isNotHole = [&Section](const binary_data_iterator &Itr) {
1254       BinaryData *BD = Itr->second;
1255       bool isHole = (!BD->getParent() && !BD->getSize() && BD->isObject() &&
1256                      (BD->getName().startswith("SYMBOLat0x") ||
1257                       BD->getName().startswith("DATAat0x") ||
1258                       BD->getName().startswith("ANONYMOUS")));
1259       return !isHole && BD->getSection() == Section && !BD->getParent();
1260     };
1261 
1262     auto BDStart = BinaryDataMap.begin();
1263     auto BDEnd = BinaryDataMap.end();
1264     auto Itr = FilteredBinaryDataIterator(isNotHole, BDStart, BDEnd);
1265     auto End = FilteredBinaryDataIterator(isNotHole, BDEnd, BDEnd);
1266 
1267     uint64_t EndAddress = Section.getAddress();
1268 
1269     while (Itr != End) {
1270       if (Itr->second->getAddress() > EndAddress) {
1271         uint64_t Gap = Itr->second->getAddress() - EndAddress;
1272         Holes.emplace_back(EndAddress, Gap);
1273       }
1274       EndAddress = Itr->second->getEndAddress();
1275       ++Itr;
1276     }
1277 
1278     if (EndAddress < Section.getEndAddress())
1279       Holes.emplace_back(EndAddress, Section.getEndAddress() - EndAddress);
1280 
1281     // If there is already a symbol at the start of the hole, grow that symbol
1282     // to cover the rest.  Otherwise, create a new symbol to cover the hole.
1283     for (std::pair<uint64_t, uint64_t> &Hole : Holes) {
1284       BinaryData *BD = getBinaryDataAtAddress(Hole.first);
1285       if (BD) {
1286         // BD->getSection() can be != Section if there are sections that
1287         // overlap.  In this case it is probably safe to just skip the holes
1288         // since the overlapping section will not(?) have any symbols in it.
1289         if (BD->getSection() == Section)
1290           setBinaryDataSize(Hole.first, Hole.second);
1291       } else {
1292         getOrCreateGlobalSymbol(Hole.first, "HOLEat", Hole.second, 1);
1293       }
1294     }
1295   }
1296 
1297   assert(validateObjectNesting() && "object nesting inconsitency detected");
1298   assert(validateHoles() && "top level hole detected in object map");
1299 }
1300 
1301 void BinaryContext::printGlobalSymbols(raw_ostream &OS) const {
1302   const BinarySection *CurrentSection = nullptr;
1303   bool FirstSection = true;
1304 
1305   for (auto &Entry : BinaryDataMap) {
1306     const BinaryData *BD = Entry.second;
1307     const BinarySection &Section = BD->getSection();
1308     if (FirstSection || Section != *CurrentSection) {
1309       uint64_t Address, Size;
1310       StringRef Name = Section.getName();
1311       if (Section) {
1312         Address = Section.getAddress();
1313         Size = Section.getSize();
1314       } else {
1315         Address = BD->getAddress();
1316         Size = BD->getSize();
1317       }
1318       OS << "BOLT-INFO: Section " << Name << ", "
1319          << "0x" + Twine::utohexstr(Address) << ":"
1320          << "0x" + Twine::utohexstr(Address + Size) << "/" << Size << "\n";
1321       CurrentSection = &Section;
1322       FirstSection = false;
1323     }
1324 
1325     OS << "BOLT-INFO: ";
1326     const BinaryData *P = BD->getParent();
1327     while (P) {
1328       OS << "  ";
1329       P = P->getParent();
1330     }
1331     OS << *BD << "\n";
1332   }
1333 }
1334 
1335 Expected<unsigned> BinaryContext::getDwarfFile(
1336     StringRef Directory, StringRef FileName, unsigned FileNumber,
1337     Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source,
1338     unsigned CUID, unsigned DWARFVersion) {
1339   DwarfLineTable &Table = DwarfLineTablesCUMap[CUID];
1340   return Table.tryGetFile(Directory, FileName, Checksum, Source, DWARFVersion,
1341                           FileNumber);
1342 }
1343 
1344 unsigned BinaryContext::addDebugFilenameToUnit(const uint32_t DestCUID,
1345                                                const uint32_t SrcCUID,
1346                                                unsigned FileIndex) {
1347   DWARFCompileUnit *SrcUnit = DwCtx->getCompileUnitForOffset(SrcCUID);
1348   const DWARFDebugLine::LineTable *LineTable =
1349       DwCtx->getLineTableForUnit(SrcUnit);
1350   const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1351       LineTable->Prologue.FileNames;
1352   // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1353   // means empty dir.
1354   assert(FileIndex > 0 && FileIndex <= FileNames.size() &&
1355          "FileIndex out of range for the compilation unit.");
1356   StringRef Dir = "";
1357   if (FileNames[FileIndex - 1].DirIdx != 0) {
1358     if (Optional<const char *> DirName = dwarf::toString(
1359             LineTable->Prologue
1360                 .IncludeDirectories[FileNames[FileIndex - 1].DirIdx - 1])) {
1361       Dir = *DirName;
1362     }
1363   }
1364   StringRef FileName = "";
1365   if (Optional<const char *> FName =
1366           dwarf::toString(FileNames[FileIndex - 1].Name))
1367     FileName = *FName;
1368   assert(FileName != "");
1369   DWARFCompileUnit *DstUnit = DwCtx->getCompileUnitForOffset(DestCUID);
1370   return cantFail(getDwarfFile(Dir, FileName, 0, None, None, DestCUID,
1371                                DstUnit->getVersion()));
1372 }
1373 
1374 std::vector<BinaryFunction *> BinaryContext::getSortedFunctions() {
1375   std::vector<BinaryFunction *> SortedFunctions(BinaryFunctions.size());
1376   std::transform(BinaryFunctions.begin(), BinaryFunctions.end(),
1377                  SortedFunctions.begin(),
1378                  [](std::pair<const uint64_t, BinaryFunction> &BFI) {
1379                    return &BFI.second;
1380                  });
1381 
1382   std::stable_sort(SortedFunctions.begin(), SortedFunctions.end(),
1383                    [](const BinaryFunction *A, const BinaryFunction *B) {
1384                      if (A->hasValidIndex() && B->hasValidIndex()) {
1385                        return A->getIndex() < B->getIndex();
1386                      }
1387                      return A->hasValidIndex();
1388                    });
1389   return SortedFunctions;
1390 }
1391 
1392 std::vector<BinaryFunction *> BinaryContext::getAllBinaryFunctions() {
1393   std::vector<BinaryFunction *> AllFunctions;
1394   AllFunctions.reserve(BinaryFunctions.size() + InjectedBinaryFunctions.size());
1395   std::transform(BinaryFunctions.begin(), BinaryFunctions.end(),
1396                  std::back_inserter(AllFunctions),
1397                  [](std::pair<const uint64_t, BinaryFunction> &BFI) {
1398                    return &BFI.second;
1399                  });
1400   std::copy(InjectedBinaryFunctions.begin(), InjectedBinaryFunctions.end(),
1401             std::back_inserter(AllFunctions));
1402 
1403   return AllFunctions;
1404 }
1405 
1406 Optional<DWARFUnit *> BinaryContext::getDWOCU(uint64_t DWOId) {
1407   auto Iter = DWOCUs.find(DWOId);
1408   if (Iter == DWOCUs.end())
1409     return None;
1410 
1411   return Iter->second;
1412 }
1413 
1414 DWARFContext *BinaryContext::getDWOContext() {
1415   if (DWOCUs.empty())
1416     return nullptr;
1417   return &DWOCUs.begin()->second->getContext();
1418 }
1419 
1420 /// Handles DWO sections that can either be in .o, .dwo or .dwp files.
1421 void BinaryContext::preprocessDWODebugInfo() {
1422   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1423     DWARFUnit *const DwarfUnit = CU.get();
1424     if (llvm::Optional<uint64_t> DWOId = DwarfUnit->getDWOId()) {
1425       DWARFUnit *DWOCU = DwarfUnit->getNonSkeletonUnitDIE(false).getDwarfUnit();
1426       if (!DWOCU->isDWOUnit()) {
1427         std::string DWOName = dwarf::toString(
1428             DwarfUnit->getUnitDIE().find(
1429                 {dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
1430             "");
1431         outs() << "BOLT-WARNING: Debug Fission: DWO debug information for "
1432                << DWOName
1433                << " was not retrieved and won't be updated. Please check "
1434                   "relative path.\n";
1435         continue;
1436       }
1437       DWOCUs[*DWOId] = DWOCU;
1438     }
1439   }
1440 }
1441 
1442 void BinaryContext::preprocessDebugInfo() {
1443   struct CURange {
1444     uint64_t LowPC;
1445     uint64_t HighPC;
1446     DWARFUnit *Unit;
1447 
1448     bool operator<(const CURange &Other) const { return LowPC < Other.LowPC; }
1449   };
1450 
1451   // Building a map of address ranges to CUs similar to .debug_aranges and use
1452   // it to assign CU to functions.
1453   std::vector<CURange> AllRanges;
1454   AllRanges.reserve(DwCtx->getNumCompileUnits());
1455   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1456     Expected<DWARFAddressRangesVector> RangesOrError =
1457         CU->getUnitDIE().getAddressRanges();
1458     if (!RangesOrError) {
1459       consumeError(RangesOrError.takeError());
1460       continue;
1461     }
1462     for (DWARFAddressRange &Range : *RangesOrError) {
1463       // Parts of the debug info could be invalidated due to corresponding code
1464       // being removed from the binary by the linker. Hence we check if the
1465       // address is a valid one.
1466       if (containsAddress(Range.LowPC))
1467         AllRanges.emplace_back(CURange{Range.LowPC, Range.HighPC, CU.get()});
1468     }
1469 
1470     ContainsDwarf5 |= CU->getVersion() >= 5;
1471     ContainsDwarfLegacy |= CU->getVersion() < 5;
1472   }
1473 
1474   if (ContainsDwarf5 && ContainsDwarfLegacy)
1475     llvm::errs() << "BOLT-WARNING: BOLT does not support mix mode binary with "
1476                     "DWARF5 and DWARF{2,3,4}.\n";
1477 
1478   std::sort(AllRanges.begin(), AllRanges.end());
1479   for (auto &KV : BinaryFunctions) {
1480     const uint64_t FunctionAddress = KV.first;
1481     BinaryFunction &Function = KV.second;
1482 
1483     auto It = std::partition_point(
1484         AllRanges.begin(), AllRanges.end(),
1485         [=](CURange R) { return R.HighPC <= FunctionAddress; });
1486     if (It != AllRanges.end() && It->LowPC <= FunctionAddress) {
1487       Function.setDWARFUnit(It->Unit);
1488     }
1489   }
1490 
1491   // Discover units with debug info that needs to be updated.
1492   for (const auto &KV : BinaryFunctions) {
1493     const BinaryFunction &BF = KV.second;
1494     if (shouldEmit(BF) && BF.getDWARFUnit())
1495       ProcessedCUs.insert(BF.getDWARFUnit());
1496   }
1497 
1498   // Clear debug info for functions from units that we are not going to process.
1499   for (auto &KV : BinaryFunctions) {
1500     BinaryFunction &BF = KV.second;
1501     if (BF.getDWARFUnit() && !ProcessedCUs.count(BF.getDWARFUnit()))
1502       BF.setDWARFUnit(nullptr);
1503   }
1504 
1505   if (opts::Verbosity >= 1) {
1506     outs() << "BOLT-INFO: " << ProcessedCUs.size() << " out of "
1507            << DwCtx->getNumCompileUnits() << " CUs will be updated\n";
1508   }
1509 
1510   preprocessDWODebugInfo();
1511 
1512   // Populate MCContext with DWARF files from all units.
1513   StringRef GlobalPrefix = AsmInfo->getPrivateGlobalPrefix();
1514   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1515     const uint64_t CUID = CU->getOffset();
1516     DwarfLineTable &BinaryLineTable = getDwarfLineTable(CUID);
1517     BinaryLineTable.setLabel(Ctx->getOrCreateSymbol(
1518         GlobalPrefix + "line_table_start" + Twine(CUID)));
1519 
1520     if (!ProcessedCUs.count(CU.get()))
1521       continue;
1522 
1523     const DWARFDebugLine::LineTable *LineTable =
1524         DwCtx->getLineTableForUnit(CU.get());
1525     const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1526         LineTable->Prologue.FileNames;
1527 
1528     uint16_t DwarfVersion = LineTable->Prologue.getVersion();
1529     if (DwarfVersion >= 5) {
1530       Optional<MD5::MD5Result> Checksum = None;
1531       if (LineTable->Prologue.ContentTypes.HasMD5)
1532         Checksum = LineTable->Prologue.FileNames[0].Checksum;
1533       Optional<const char *> Name =
1534           dwarf::toString(CU->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1535       if (Optional<uint64_t> DWOID = CU->getDWOId()) {
1536         auto Iter = DWOCUs.find(*DWOID);
1537         assert(Iter != DWOCUs.end() && "DWO CU was not found.");
1538         Name = dwarf::toString(
1539             Iter->second->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1540       }
1541       BinaryLineTable.setRootFile(CU->getCompilationDir(), *Name, Checksum,
1542                                   None);
1543     }
1544 
1545     BinaryLineTable.setDwarfVersion(DwarfVersion);
1546 
1547     // Assign a unique label to every line table, one per CU.
1548     // Make sure empty debug line tables are registered too.
1549     if (FileNames.empty()) {
1550       cantFail(
1551           getDwarfFile("", "<unknown>", 0, None, None, CUID, DwarfVersion));
1552       continue;
1553     }
1554     const uint32_t Offset = DwarfVersion < 5 ? 1 : 0;
1555     for (size_t I = 0, Size = FileNames.size(); I != Size; ++I) {
1556       // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1557       // means empty dir.
1558       StringRef Dir = "";
1559       if (FileNames[I].DirIdx != 0 || DwarfVersion >= 5)
1560         if (Optional<const char *> DirName = dwarf::toString(
1561                 LineTable->Prologue
1562                     .IncludeDirectories[FileNames[I].DirIdx - Offset]))
1563           Dir = *DirName;
1564       StringRef FileName = "";
1565       if (Optional<const char *> FName = dwarf::toString(FileNames[I].Name))
1566         FileName = *FName;
1567       assert(FileName != "");
1568       Optional<MD5::MD5Result> Checksum = None;
1569       if (DwarfVersion >= 5 && LineTable->Prologue.ContentTypes.HasMD5)
1570         Checksum = LineTable->Prologue.FileNames[I].Checksum;
1571       cantFail(
1572           getDwarfFile(Dir, FileName, 0, Checksum, None, CUID, DwarfVersion));
1573     }
1574   }
1575 }
1576 
1577 bool BinaryContext::shouldEmit(const BinaryFunction &Function) const {
1578   if (Function.isPseudo())
1579     return false;
1580 
1581   if (opts::processAllFunctions())
1582     return true;
1583 
1584   if (Function.isIgnored())
1585     return false;
1586 
1587   // In relocation mode we will emit non-simple functions with CFG.
1588   // If the function does not have a CFG it should be marked as ignored.
1589   return HasRelocations || Function.isSimple();
1590 }
1591 
1592 void BinaryContext::printCFI(raw_ostream &OS, const MCCFIInstruction &Inst) {
1593   uint32_t Operation = Inst.getOperation();
1594   switch (Operation) {
1595   case MCCFIInstruction::OpSameValue:
1596     OS << "OpSameValue Reg" << Inst.getRegister();
1597     break;
1598   case MCCFIInstruction::OpRememberState:
1599     OS << "OpRememberState";
1600     break;
1601   case MCCFIInstruction::OpRestoreState:
1602     OS << "OpRestoreState";
1603     break;
1604   case MCCFIInstruction::OpOffset:
1605     OS << "OpOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1606     break;
1607   case MCCFIInstruction::OpDefCfaRegister:
1608     OS << "OpDefCfaRegister Reg" << Inst.getRegister();
1609     break;
1610   case MCCFIInstruction::OpDefCfaOffset:
1611     OS << "OpDefCfaOffset " << Inst.getOffset();
1612     break;
1613   case MCCFIInstruction::OpDefCfa:
1614     OS << "OpDefCfa Reg" << Inst.getRegister() << " " << Inst.getOffset();
1615     break;
1616   case MCCFIInstruction::OpRelOffset:
1617     OS << "OpRelOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1618     break;
1619   case MCCFIInstruction::OpAdjustCfaOffset:
1620     OS << "OfAdjustCfaOffset " << Inst.getOffset();
1621     break;
1622   case MCCFIInstruction::OpEscape:
1623     OS << "OpEscape";
1624     break;
1625   case MCCFIInstruction::OpRestore:
1626     OS << "OpRestore Reg" << Inst.getRegister();
1627     break;
1628   case MCCFIInstruction::OpUndefined:
1629     OS << "OpUndefined Reg" << Inst.getRegister();
1630     break;
1631   case MCCFIInstruction::OpRegister:
1632     OS << "OpRegister Reg" << Inst.getRegister() << " Reg"
1633        << Inst.getRegister2();
1634     break;
1635   case MCCFIInstruction::OpWindowSave:
1636     OS << "OpWindowSave";
1637     break;
1638   case MCCFIInstruction::OpGnuArgsSize:
1639     OS << "OpGnuArgsSize";
1640     break;
1641   default:
1642     OS << "Op#" << Operation;
1643     break;
1644   }
1645 }
1646 
1647 MarkerSymType BinaryContext::getMarkerType(const SymbolRef &Symbol) const {
1648   // For aarch64, the ABI defines mapping symbols so we identify data in the
1649   // code section (see IHI0056B). $x identifies a symbol starting code or the
1650   // end of a data chunk inside code, $d indentifies start of data.
1651   if (!isAArch64() || ELFSymbolRef(Symbol).getSize())
1652     return MarkerSymType::NONE;
1653 
1654   Expected<StringRef> NameOrError = Symbol.getName();
1655   Expected<object::SymbolRef::Type> TypeOrError = Symbol.getType();
1656 
1657   if (!TypeOrError || !NameOrError)
1658     return MarkerSymType::NONE;
1659 
1660   if (*TypeOrError != SymbolRef::ST_Unknown)
1661     return MarkerSymType::NONE;
1662 
1663   if (*NameOrError == "$x" || NameOrError->startswith("$x."))
1664     return MarkerSymType::CODE;
1665 
1666   if (*NameOrError == "$d" || NameOrError->startswith("$d."))
1667     return MarkerSymType::DATA;
1668 
1669   return MarkerSymType::NONE;
1670 }
1671 
1672 bool BinaryContext::isMarker(const SymbolRef &Symbol) const {
1673   return getMarkerType(Symbol) != MarkerSymType::NONE;
1674 }
1675 
1676 void BinaryContext::printInstruction(raw_ostream &OS, const MCInst &Instruction,
1677                                      uint64_t Offset,
1678                                      const BinaryFunction *Function,
1679                                      bool PrintMCInst, bool PrintMemData,
1680                                      bool PrintRelocations,
1681                                      StringRef Endl) const {
1682   if (MIB->isEHLabel(Instruction)) {
1683     OS << "  EH_LABEL: " << *MIB->getTargetSymbol(Instruction) << Endl;
1684     return;
1685   }
1686   OS << format("    %08" PRIx64 ": ", Offset);
1687   if (MIB->isCFI(Instruction)) {
1688     uint32_t Offset = Instruction.getOperand(0).getImm();
1689     OS << "\t!CFI\t$" << Offset << "\t; ";
1690     if (Function)
1691       printCFI(OS, *Function->getCFIFor(Instruction));
1692     OS << Endl;
1693     return;
1694   }
1695   InstPrinter->printInst(&Instruction, 0, "", *STI, OS);
1696   if (MIB->isCall(Instruction)) {
1697     if (MIB->isTailCall(Instruction))
1698       OS << " # TAILCALL ";
1699     if (MIB->isInvoke(Instruction)) {
1700       const Optional<MCPlus::MCLandingPad> EHInfo = MIB->getEHInfo(Instruction);
1701       OS << " # handler: ";
1702       if (EHInfo->first)
1703         OS << *EHInfo->first;
1704       else
1705         OS << '0';
1706       OS << "; action: " << EHInfo->second;
1707       const int64_t GnuArgsSize = MIB->getGnuArgsSize(Instruction);
1708       if (GnuArgsSize >= 0)
1709         OS << "; GNU_args_size = " << GnuArgsSize;
1710     }
1711   } else if (MIB->isIndirectBranch(Instruction)) {
1712     if (uint64_t JTAddress = MIB->getJumpTable(Instruction)) {
1713       OS << " # JUMPTABLE @0x" << Twine::utohexstr(JTAddress);
1714     } else {
1715       OS << " # UNKNOWN CONTROL FLOW";
1716     }
1717   }
1718   if (Optional<uint32_t> Offset = MIB->getOffset(Instruction))
1719     OS << " # Offset: " << *Offset;
1720 
1721   MIB->printAnnotations(Instruction, OS);
1722 
1723   if (opts::PrintDebugInfo) {
1724     DebugLineTableRowRef RowRef =
1725         DebugLineTableRowRef::fromSMLoc(Instruction.getLoc());
1726     if (RowRef != DebugLineTableRowRef::NULL_ROW) {
1727       const DWARFDebugLine::LineTable *LineTable;
1728       if (Function && Function->getDWARFUnit() &&
1729           Function->getDWARFUnit()->getOffset() == RowRef.DwCompileUnitIndex) {
1730         LineTable = Function->getDWARFLineTable();
1731       } else {
1732         LineTable = DwCtx->getLineTableForUnit(
1733             DwCtx->getCompileUnitForOffset(RowRef.DwCompileUnitIndex));
1734       }
1735       assert(LineTable &&
1736              "line table expected for instruction with debug info");
1737 
1738       const DWARFDebugLine::Row &Row = LineTable->Rows[RowRef.RowIndex - 1];
1739       StringRef FileName = "";
1740       if (Optional<const char *> FName =
1741               dwarf::toString(LineTable->Prologue.FileNames[Row.File - 1].Name))
1742         FileName = *FName;
1743       OS << " # debug line " << FileName << ":" << Row.Line;
1744       if (Row.Column)
1745         OS << ":" << Row.Column;
1746       if (Row.Discriminator)
1747         OS << " discriminator:" << Row.Discriminator;
1748     }
1749   }
1750 
1751   if ((opts::PrintRelocations || PrintRelocations) && Function) {
1752     const uint64_t Size = computeCodeSize(&Instruction, &Instruction + 1);
1753     Function->printRelocations(OS, Offset, Size);
1754   }
1755 
1756   OS << Endl;
1757 
1758   if (PrintMCInst) {
1759     Instruction.dump_pretty(OS, InstPrinter.get());
1760     OS << Endl;
1761   }
1762 }
1763 
1764 Optional<uint64_t>
1765 BinaryContext::getBaseAddressForMapping(uint64_t MMapAddress,
1766                                         uint64_t FileOffset) const {
1767   // Find a segment with a matching file offset.
1768   for (auto &KV : SegmentMapInfo) {
1769     const SegmentInfo &SegInfo = KV.second;
1770     if (alignDown(SegInfo.FileOffset, SegInfo.Alignment) == FileOffset) {
1771       // Use segment's aligned memory offset to calculate the base address.
1772       const uint64_t MemOffset = alignDown(SegInfo.Address, SegInfo.Alignment);
1773       return MMapAddress - MemOffset;
1774     }
1775   }
1776 
1777   return NoneType();
1778 }
1779 
1780 ErrorOr<BinarySection &> BinaryContext::getSectionForAddress(uint64_t Address) {
1781   auto SI = AddressToSection.upper_bound(Address);
1782   if (SI != AddressToSection.begin()) {
1783     --SI;
1784     uint64_t UpperBound = SI->first + SI->second->getSize();
1785     if (!SI->second->getSize())
1786       UpperBound += 1;
1787     if (UpperBound > Address)
1788       return *SI->second;
1789   }
1790   return std::make_error_code(std::errc::bad_address);
1791 }
1792 
1793 ErrorOr<StringRef>
1794 BinaryContext::getSectionNameForAddress(uint64_t Address) const {
1795   if (ErrorOr<const BinarySection &> Section = getSectionForAddress(Address))
1796     return Section->getName();
1797   return std::make_error_code(std::errc::bad_address);
1798 }
1799 
1800 BinarySection &BinaryContext::registerSection(BinarySection *Section) {
1801   auto Res = Sections.insert(Section);
1802   (void)Res;
1803   assert(Res.second && "can't register the same section twice.");
1804 
1805   // Only register allocatable sections in the AddressToSection map.
1806   if (Section->isAllocatable() && Section->getAddress())
1807     AddressToSection.insert(std::make_pair(Section->getAddress(), Section));
1808   NameToSection.insert(
1809       std::make_pair(std::string(Section->getName()), Section));
1810   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: registering " << *Section << "\n");
1811   return *Section;
1812 }
1813 
1814 BinarySection &BinaryContext::registerSection(SectionRef Section) {
1815   return registerSection(new BinarySection(*this, Section));
1816 }
1817 
1818 BinarySection &
1819 BinaryContext::registerSection(StringRef SectionName,
1820                                const BinarySection &OriginalSection) {
1821   return registerSection(
1822       new BinarySection(*this, SectionName, OriginalSection));
1823 }
1824 
1825 BinarySection &
1826 BinaryContext::registerOrUpdateSection(StringRef Name, unsigned ELFType,
1827                                        unsigned ELFFlags, uint8_t *Data,
1828                                        uint64_t Size, unsigned Alignment) {
1829   auto NamedSections = getSectionByName(Name);
1830   if (NamedSections.begin() != NamedSections.end()) {
1831     assert(std::next(NamedSections.begin()) == NamedSections.end() &&
1832            "can only update unique sections");
1833     BinarySection *Section = NamedSections.begin()->second;
1834 
1835     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: updating " << *Section << " -> ");
1836     const bool Flag = Section->isAllocatable();
1837     (void)Flag;
1838     Section->update(Data, Size, Alignment, ELFType, ELFFlags);
1839     LLVM_DEBUG(dbgs() << *Section << "\n");
1840     // FIXME: Fix section flags/attributes for MachO.
1841     if (isELF())
1842       assert(Flag == Section->isAllocatable() &&
1843              "can't change section allocation status");
1844     return *Section;
1845   }
1846 
1847   return registerSection(
1848       new BinarySection(*this, Name, Data, Size, Alignment, ELFType, ELFFlags));
1849 }
1850 
1851 bool BinaryContext::deregisterSection(BinarySection &Section) {
1852   BinarySection *SectionPtr = &Section;
1853   auto Itr = Sections.find(SectionPtr);
1854   if (Itr != Sections.end()) {
1855     auto Range = AddressToSection.equal_range(SectionPtr->getAddress());
1856     while (Range.first != Range.second) {
1857       if (Range.first->second == SectionPtr) {
1858         AddressToSection.erase(Range.first);
1859         break;
1860       }
1861       ++Range.first;
1862     }
1863 
1864     auto NameRange =
1865         NameToSection.equal_range(std::string(SectionPtr->getName()));
1866     while (NameRange.first != NameRange.second) {
1867       if (NameRange.first->second == SectionPtr) {
1868         NameToSection.erase(NameRange.first);
1869         break;
1870       }
1871       ++NameRange.first;
1872     }
1873 
1874     Sections.erase(Itr);
1875     delete SectionPtr;
1876     return true;
1877   }
1878   return false;
1879 }
1880 
1881 void BinaryContext::printSections(raw_ostream &OS) const {
1882   for (BinarySection *const &Section : Sections)
1883     OS << "BOLT-INFO: " << *Section << "\n";
1884 }
1885 
1886 BinarySection &BinaryContext::absoluteSection() {
1887   if (ErrorOr<BinarySection &> Section = getUniqueSectionByName("<absolute>"))
1888     return *Section;
1889   return registerOrUpdateSection("<absolute>", ELF::SHT_NULL, 0u);
1890 }
1891 
1892 ErrorOr<uint64_t> BinaryContext::getUnsignedValueAtAddress(uint64_t Address,
1893                                                            size_t Size) const {
1894   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
1895   if (!Section)
1896     return std::make_error_code(std::errc::bad_address);
1897 
1898   if (Section->isVirtual())
1899     return 0;
1900 
1901   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
1902                    AsmInfo->getCodePointerSize());
1903   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
1904   return DE.getUnsigned(&ValueOffset, Size);
1905 }
1906 
1907 ErrorOr<uint64_t> BinaryContext::getSignedValueAtAddress(uint64_t Address,
1908                                                          size_t Size) const {
1909   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
1910   if (!Section)
1911     return std::make_error_code(std::errc::bad_address);
1912 
1913   if (Section->isVirtual())
1914     return 0;
1915 
1916   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
1917                    AsmInfo->getCodePointerSize());
1918   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
1919   return DE.getSigned(&ValueOffset, Size);
1920 }
1921 
1922 void BinaryContext::addRelocation(uint64_t Address, MCSymbol *Symbol,
1923                                   uint64_t Type, uint64_t Addend,
1924                                   uint64_t Value) {
1925   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1926   assert(Section && "cannot find section for address");
1927   Section->addRelocation(Address - Section->getAddress(), Symbol, Type, Addend,
1928                          Value);
1929 }
1930 
1931 void BinaryContext::addDynamicRelocation(uint64_t Address, MCSymbol *Symbol,
1932                                          uint64_t Type, uint64_t Addend,
1933                                          uint64_t Value) {
1934   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1935   assert(Section && "cannot find section for address");
1936   Section->addDynamicRelocation(Address - Section->getAddress(), Symbol, Type,
1937                                 Addend, Value);
1938 }
1939 
1940 bool BinaryContext::removeRelocationAt(uint64_t Address) {
1941   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1942   assert(Section && "cannot find section for address");
1943   return Section->removeRelocationAt(Address - Section->getAddress());
1944 }
1945 
1946 const Relocation *BinaryContext::getRelocationAt(uint64_t Address) {
1947   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1948   if (!Section)
1949     return nullptr;
1950 
1951   return Section->getRelocationAt(Address - Section->getAddress());
1952 }
1953 
1954 const Relocation *BinaryContext::getDynamicRelocationAt(uint64_t Address) {
1955   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1956   if (!Section)
1957     return nullptr;
1958 
1959   return Section->getDynamicRelocationAt(Address - Section->getAddress());
1960 }
1961 
1962 void BinaryContext::markAmbiguousRelocations(BinaryData &BD,
1963                                              const uint64_t Address) {
1964   auto setImmovable = [&](BinaryData &BD) {
1965     BinaryData *Root = BD.getAtomicRoot();
1966     LLVM_DEBUG(if (Root->isMoveable()) {
1967       dbgs() << "BOLT-DEBUG: setting " << *Root << " as immovable "
1968              << "due to ambiguous relocation referencing 0x"
1969              << Twine::utohexstr(Address) << '\n';
1970     });
1971     Root->setIsMoveable(false);
1972   };
1973 
1974   if (Address == BD.getAddress()) {
1975     setImmovable(BD);
1976 
1977     // Set previous symbol as immovable
1978     BinaryData *Prev = getBinaryDataContainingAddress(Address - 1);
1979     if (Prev && Prev->getEndAddress() == BD.getAddress())
1980       setImmovable(*Prev);
1981   }
1982 
1983   if (Address == BD.getEndAddress()) {
1984     setImmovable(BD);
1985 
1986     // Set next symbol as immovable
1987     BinaryData *Next = getBinaryDataContainingAddress(BD.getEndAddress());
1988     if (Next && Next->getAddress() == BD.getEndAddress())
1989       setImmovable(*Next);
1990   }
1991 }
1992 
1993 BinaryFunction *BinaryContext::getFunctionForSymbol(const MCSymbol *Symbol,
1994                                                     uint64_t *EntryDesc) {
1995   std::shared_lock<std::shared_timed_mutex> Lock(SymbolToFunctionMapMutex);
1996   auto BFI = SymbolToFunctionMap.find(Symbol);
1997   if (BFI == SymbolToFunctionMap.end())
1998     return nullptr;
1999 
2000   BinaryFunction *BF = BFI->second;
2001   if (EntryDesc)
2002     *EntryDesc = BF->getEntryIDForSymbol(Symbol);
2003 
2004   return BF;
2005 }
2006 
2007 void BinaryContext::exitWithBugReport(StringRef Message,
2008                                       const BinaryFunction &Function) const {
2009   errs() << "=======================================\n";
2010   errs() << "BOLT is unable to proceed because it couldn't properly understand "
2011             "this function.\n";
2012   errs() << "If you are running the most recent version of BOLT, you may "
2013             "want to "
2014             "report this and paste this dump.\nPlease check that there is no "
2015             "sensitive contents being shared in this dump.\n";
2016   errs() << "\nOffending function: " << Function.getPrintName() << "\n\n";
2017   ScopedPrinter SP(errs());
2018   SP.printBinaryBlock("Function contents", *Function.getData());
2019   errs() << "\n";
2020   Function.dump();
2021   errs() << "ERROR: " << Message;
2022   errs() << "\n=======================================\n";
2023   exit(1);
2024 }
2025 
2026 BinaryFunction *
2027 BinaryContext::createInjectedBinaryFunction(const std::string &Name,
2028                                             bool IsSimple) {
2029   InjectedBinaryFunctions.push_back(new BinaryFunction(Name, *this, IsSimple));
2030   BinaryFunction *BF = InjectedBinaryFunctions.back();
2031   setSymbolToFunctionMap(BF->getSymbol(), BF);
2032   BF->CurrentState = BinaryFunction::State::CFG;
2033   return BF;
2034 }
2035 
2036 std::pair<size_t, size_t>
2037 BinaryContext::calculateEmittedSize(BinaryFunction &BF, bool FixBranches) {
2038   // Adjust branch instruction to match the current layout.
2039   if (FixBranches)
2040     BF.fixBranches();
2041 
2042   // Create local MC context to isolate the effect of ephemeral code emission.
2043   IndependentCodeEmitter MCEInstance = createIndependentMCCodeEmitter();
2044   MCContext *LocalCtx = MCEInstance.LocalCtx.get();
2045   MCAsmBackend *MAB =
2046       TheTarget->createMCAsmBackend(*STI, *MRI, MCTargetOptions());
2047 
2048   SmallString<256> Code;
2049   raw_svector_ostream VecOS(Code);
2050 
2051   std::unique_ptr<MCObjectWriter> OW = MAB->createObjectWriter(VecOS);
2052   std::unique_ptr<MCStreamer> Streamer(TheTarget->createMCObjectStreamer(
2053       *TheTriple, *LocalCtx, std::unique_ptr<MCAsmBackend>(MAB), std::move(OW),
2054       std::unique_ptr<MCCodeEmitter>(MCEInstance.MCE.release()), *STI,
2055       /*RelaxAll=*/false,
2056       /*IncrementalLinkerCompatible=*/false,
2057       /*DWARFMustBeAtTheEnd=*/false));
2058 
2059   Streamer->initSections(false, *STI);
2060 
2061   MCSection *Section = MCEInstance.LocalMOFI->getTextSection();
2062   Section->setHasInstructions(true);
2063 
2064   // Create symbols in the LocalCtx so that they get destroyed with it.
2065   MCSymbol *StartLabel = LocalCtx->createTempSymbol();
2066   MCSymbol *EndLabel = LocalCtx->createTempSymbol();
2067   MCSymbol *ColdStartLabel = LocalCtx->createTempSymbol();
2068   MCSymbol *ColdEndLabel = LocalCtx->createTempSymbol();
2069 
2070   Streamer->switchSection(Section);
2071   Streamer->emitLabel(StartLabel);
2072   emitFunctionBody(*Streamer, BF, /*EmitColdPart=*/false,
2073                    /*EmitCodeOnly=*/true);
2074   Streamer->emitLabel(EndLabel);
2075 
2076   if (BF.isSplit()) {
2077     MCSectionELF *ColdSection =
2078         LocalCtx->getELFSection(BF.getColdCodeSectionName(), ELF::SHT_PROGBITS,
2079                                 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC);
2080     ColdSection->setHasInstructions(true);
2081 
2082     Streamer->switchSection(ColdSection);
2083     Streamer->emitLabel(ColdStartLabel);
2084     emitFunctionBody(*Streamer, BF, /*EmitColdPart=*/true,
2085                      /*EmitCodeOnly=*/true);
2086     Streamer->emitLabel(ColdEndLabel);
2087     // To avoid calling MCObjectStreamer::flushPendingLabels() which is private
2088     Streamer->emitBytes(StringRef(""));
2089     Streamer->switchSection(Section);
2090   }
2091 
2092   // To avoid calling MCObjectStreamer::flushPendingLabels() which is private or
2093   // MCStreamer::Finish(), which does more than we want
2094   Streamer->emitBytes(StringRef(""));
2095 
2096   MCAssembler &Assembler =
2097       static_cast<MCObjectStreamer *>(Streamer.get())->getAssembler();
2098   MCAsmLayout Layout(Assembler);
2099   Assembler.layout(Layout);
2100 
2101   const uint64_t HotSize =
2102       Layout.getSymbolOffset(*EndLabel) - Layout.getSymbolOffset(*StartLabel);
2103   const uint64_t ColdSize = BF.isSplit()
2104                                 ? Layout.getSymbolOffset(*ColdEndLabel) -
2105                                       Layout.getSymbolOffset(*ColdStartLabel)
2106                                 : 0ULL;
2107 
2108   // Clean-up the effect of the code emission.
2109   for (const MCSymbol &Symbol : Assembler.symbols()) {
2110     MCSymbol *MutableSymbol = const_cast<MCSymbol *>(&Symbol);
2111     MutableSymbol->setUndefined();
2112     MutableSymbol->setIsRegistered(false);
2113   }
2114 
2115   return std::make_pair(HotSize, ColdSize);
2116 }
2117 
2118 bool BinaryContext::validateEncoding(const MCInst &Inst,
2119                                      ArrayRef<uint8_t> InputEncoding) const {
2120   SmallString<256> Code;
2121   SmallVector<MCFixup, 4> Fixups;
2122   raw_svector_ostream VecOS(Code);
2123 
2124   MCE->encodeInstruction(Inst, VecOS, Fixups, *STI);
2125   auto EncodedData = ArrayRef<uint8_t>((uint8_t *)Code.data(), Code.size());
2126   if (InputEncoding != EncodedData) {
2127     if (opts::Verbosity > 1) {
2128       errs() << "BOLT-WARNING: mismatched encoding detected\n"
2129              << "      input: " << InputEncoding << '\n'
2130              << "     output: " << EncodedData << '\n';
2131     }
2132     return false;
2133   }
2134 
2135   return true;
2136 }
2137 
2138 uint64_t BinaryContext::getHotThreshold() const {
2139   static uint64_t Threshold = 0;
2140   if (Threshold == 0) {
2141     Threshold = std::max(
2142         (uint64_t)opts::ExecutionCountThreshold,
2143         NumProfiledFuncs ? SumExecutionCount / (2 * NumProfiledFuncs) : 1);
2144   }
2145   return Threshold;
2146 }
2147 
2148 BinaryFunction *BinaryContext::getBinaryFunctionContainingAddress(
2149     uint64_t Address, bool CheckPastEnd, bool UseMaxSize) {
2150   auto FI = BinaryFunctions.upper_bound(Address);
2151   if (FI == BinaryFunctions.begin())
2152     return nullptr;
2153   --FI;
2154 
2155   const uint64_t UsedSize =
2156       UseMaxSize ? FI->second.getMaxSize() : FI->second.getSize();
2157 
2158   if (Address >= FI->first + UsedSize + (CheckPastEnd ? 1 : 0))
2159     return nullptr;
2160 
2161   return &FI->second;
2162 }
2163 
2164 BinaryFunction *BinaryContext::getBinaryFunctionAtAddress(uint64_t Address) {
2165   // First, try to find a function starting at the given address. If the
2166   // function was folded, this will get us the original folded function if it
2167   // wasn't removed from the list, e.g. in non-relocation mode.
2168   auto BFI = BinaryFunctions.find(Address);
2169   if (BFI != BinaryFunctions.end())
2170     return &BFI->second;
2171 
2172   // We might have folded the function matching the object at the given
2173   // address. In such case, we look for a function matching the symbol
2174   // registered at the original address. The new function (the one that the
2175   // original was folded into) will hold the symbol.
2176   if (const BinaryData *BD = getBinaryDataAtAddress(Address)) {
2177     uint64_t EntryID = 0;
2178     BinaryFunction *BF = getFunctionForSymbol(BD->getSymbol(), &EntryID);
2179     if (BF && EntryID == 0)
2180       return BF;
2181   }
2182   return nullptr;
2183 }
2184 
2185 DebugAddressRangesVector BinaryContext::translateModuleAddressRanges(
2186     const DWARFAddressRangesVector &InputRanges) const {
2187   DebugAddressRangesVector OutputRanges;
2188 
2189   for (const DWARFAddressRange Range : InputRanges) {
2190     auto BFI = BinaryFunctions.lower_bound(Range.LowPC);
2191     while (BFI != BinaryFunctions.end()) {
2192       const BinaryFunction &Function = BFI->second;
2193       if (Function.getAddress() >= Range.HighPC)
2194         break;
2195       const DebugAddressRangesVector FunctionRanges =
2196           Function.getOutputAddressRanges();
2197       std::move(std::begin(FunctionRanges), std::end(FunctionRanges),
2198                 std::back_inserter(OutputRanges));
2199       std::advance(BFI, 1);
2200     }
2201   }
2202 
2203   return OutputRanges;
2204 }
2205 
2206 } // namespace bolt
2207 } // namespace llvm
2208