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