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