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