1 //===- bolt/Core/BinaryFunction.cpp - Low-level function ------------------===//
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 BinaryFunction class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Core/BinaryFunction.h"
14 #include "bolt/Core/BinaryBasicBlock.h"
15 #include "bolt/Core/DynoStats.h"
16 #include "bolt/Core/MCPlusBuilder.h"
17 #include "bolt/Utils/NameResolver.h"
18 #include "bolt/Utils/NameShortener.h"
19 #include "bolt/Utils/Utils.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/edit_distance.h"
23 #include "llvm/Demangle/Demangle.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCAsmLayout.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Object/ObjectFile.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/GraphWriter.h"
36 #include "llvm/Support/LEB128.h"
37 #include "llvm/Support/Regex.h"
38 #include "llvm/Support/Timer.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <functional>
41 #include <limits>
42 #include <numeric>
43 #include <string>
44 
45 #define DEBUG_TYPE "bolt"
46 
47 using namespace llvm;
48 using namespace bolt;
49 
50 namespace opts {
51 
52 extern cl::OptionCategory BoltCategory;
53 extern cl::OptionCategory BoltOptCategory;
54 extern cl::OptionCategory BoltRelocCategory;
55 
56 extern cl::opt<bool> EnableBAT;
57 extern cl::opt<bool> Instrument;
58 extern cl::opt<bool> StrictMode;
59 extern cl::opt<bool> UpdateDebugSections;
60 extern cl::opt<unsigned> Verbosity;
61 
62 extern bool processAllFunctions();
63 
64 cl::opt<bool>
65 CheckEncoding("check-encoding",
66   cl::desc("perform verification of LLVM instruction encoding/decoding. "
67            "Every instruction in the input is decoded and re-encoded. "
68            "If the resulting bytes do not match the input, a warning message "
69            "is printed."),
70   cl::init(false),
71   cl::ZeroOrMore,
72   cl::Hidden,
73   cl::cat(BoltCategory));
74 
75 static cl::opt<bool>
76 DotToolTipCode("dot-tooltip-code",
77   cl::desc("add basic block instructions as tool tips on nodes"),
78   cl::ZeroOrMore,
79   cl::Hidden,
80   cl::cat(BoltCategory));
81 
82 cl::opt<JumpTableSupportLevel>
83 JumpTables("jump-tables",
84   cl::desc("jump tables support (default=basic)"),
85   cl::init(JTS_BASIC),
86   cl::values(
87       clEnumValN(JTS_NONE, "none",
88                  "do not optimize functions with jump tables"),
89       clEnumValN(JTS_BASIC, "basic",
90                  "optimize functions with jump tables"),
91       clEnumValN(JTS_MOVE, "move",
92                  "move jump tables to a separate section"),
93       clEnumValN(JTS_SPLIT, "split",
94                  "split jump tables section into hot and cold based on "
95                  "function execution frequency"),
96       clEnumValN(JTS_AGGRESSIVE, "aggressive",
97                  "aggressively split jump tables section based on usage "
98                  "of the tables")),
99   cl::ZeroOrMore,
100   cl::cat(BoltOptCategory));
101 
102 static cl::opt<bool>
103 NoScan("no-scan",
104   cl::desc("do not scan cold functions for external references (may result in "
105            "slower binary)"),
106   cl::init(false),
107   cl::ZeroOrMore,
108   cl::Hidden,
109   cl::cat(BoltOptCategory));
110 
111 cl::opt<bool>
112 PreserveBlocksAlignment("preserve-blocks-alignment",
113   cl::desc("try to preserve basic block alignment"),
114   cl::init(false),
115   cl::ZeroOrMore,
116   cl::cat(BoltOptCategory));
117 
118 cl::opt<bool>
119 PrintDynoStats("dyno-stats",
120   cl::desc("print execution info based on profile"),
121   cl::cat(BoltCategory));
122 
123 static cl::opt<bool>
124 PrintDynoStatsOnly("print-dyno-stats-only",
125   cl::desc("while printing functions output dyno-stats and skip instructions"),
126   cl::init(false),
127   cl::Hidden,
128   cl::cat(BoltCategory));
129 
130 static cl::list<std::string>
131 PrintOnly("print-only",
132   cl::CommaSeparated,
133   cl::desc("list of functions to print"),
134   cl::value_desc("func1,func2,func3,..."),
135   cl::Hidden,
136   cl::cat(BoltCategory));
137 
138 cl::opt<bool>
139 TimeBuild("time-build",
140   cl::desc("print time spent constructing binary functions"),
141   cl::ZeroOrMore,
142   cl::Hidden,
143   cl::cat(BoltCategory));
144 
145 cl::opt<bool>
146 TrapOnAVX512("trap-avx512",
147   cl::desc("in relocation mode trap upon entry to any function that uses "
148             "AVX-512 instructions"),
149   cl::init(false),
150   cl::ZeroOrMore,
151   cl::Hidden,
152   cl::cat(BoltCategory));
153 
154 bool shouldPrint(const BinaryFunction &Function) {
155   if (Function.isIgnored())
156     return false;
157 
158   if (PrintOnly.empty())
159     return true;
160 
161   for (std::string &Name : opts::PrintOnly) {
162     if (Function.hasNameRegex(Name)) {
163       return true;
164     }
165   }
166 
167   return false;
168 }
169 
170 } // namespace opts
171 
172 namespace llvm {
173 namespace bolt {
174 
175 constexpr unsigned BinaryFunction::MinAlign;
176 
177 namespace {
178 
179 template <typename R> bool emptyRange(const R &Range) {
180   return Range.begin() == Range.end();
181 }
182 
183 /// Gets debug line information for the instruction located at the given
184 /// address in the original binary. The SMLoc's pointer is used
185 /// to point to this information, which is represented by a
186 /// DebugLineTableRowRef. The returned pointer is null if no debug line
187 /// information for this instruction was found.
188 SMLoc findDebugLineInformationForInstructionAt(
189     uint64_t Address, DWARFUnit *Unit,
190     const DWARFDebugLine::LineTable *LineTable) {
191   // We use the pointer in SMLoc to store an instance of DebugLineTableRowRef,
192   // which occupies 64 bits. Thus, we can only proceed if the struct fits into
193   // the pointer itself.
194   assert(sizeof(decltype(SMLoc().getPointer())) >=
195              sizeof(DebugLineTableRowRef) &&
196          "Cannot fit instruction debug line information into SMLoc's pointer");
197 
198   SMLoc NullResult = DebugLineTableRowRef::NULL_ROW.toSMLoc();
199   uint32_t RowIndex = LineTable->lookupAddress(
200       {Address, object::SectionedAddress::UndefSection});
201   if (RowIndex == LineTable->UnknownRowIndex)
202     return NullResult;
203 
204   assert(RowIndex < LineTable->Rows.size() &&
205          "Line Table lookup returned invalid index.");
206 
207   decltype(SMLoc().getPointer()) Ptr;
208   DebugLineTableRowRef *InstructionLocation =
209       reinterpret_cast<DebugLineTableRowRef *>(&Ptr);
210 
211   InstructionLocation->DwCompileUnitIndex = Unit->getOffset();
212   InstructionLocation->RowIndex = RowIndex + 1;
213 
214   return SMLoc::getFromPointer(Ptr);
215 }
216 
217 std::string buildSectionName(StringRef Prefix, StringRef Name,
218                              const BinaryContext &BC) {
219   if (BC.isELF())
220     return (Prefix + Name).str();
221   static NameShortener NS;
222   return (Prefix + Twine(NS.getID(Name))).str();
223 }
224 
225 raw_ostream &operator<<(raw_ostream &OS, const BinaryFunction::State State) {
226   switch (State) {
227   case BinaryFunction::State::Empty:         OS << "empty"; break;
228   case BinaryFunction::State::Disassembled:  OS << "disassembled"; break;
229   case BinaryFunction::State::CFG:           OS << "CFG constructed"; break;
230   case BinaryFunction::State::CFG_Finalized: OS << "CFG finalized"; break;
231   case BinaryFunction::State::EmittedCFG:    OS << "emitted with CFG"; break;
232   case BinaryFunction::State::Emitted:       OS << "emitted"; break;
233   }
234 
235   return OS;
236 }
237 
238 } // namespace
239 
240 std::string BinaryFunction::buildCodeSectionName(StringRef Name,
241                                                  const BinaryContext &BC) {
242   return buildSectionName(BC.isELF() ? ".local.text." : ".l.text.", Name, BC);
243 }
244 
245 std::string BinaryFunction::buildColdCodeSectionName(StringRef Name,
246                                                      const BinaryContext &BC) {
247   return buildSectionName(BC.isELF() ? ".local.cold.text." : ".l.c.text.", Name,
248                           BC);
249 }
250 
251 uint64_t BinaryFunction::Count = 0;
252 
253 Optional<StringRef> BinaryFunction::hasNameRegex(const StringRef Name) const {
254   const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
255   Regex MatchName(RegexName);
256   Optional<StringRef> Match = forEachName(
257       [&MatchName](StringRef Name) { return MatchName.match(Name); });
258 
259   return Match;
260 }
261 
262 Optional<StringRef>
263 BinaryFunction::hasRestoredNameRegex(const StringRef Name) const {
264   const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
265   Regex MatchName(RegexName);
266   Optional<StringRef> Match = forEachName([&MatchName](StringRef Name) {
267     return MatchName.match(NameResolver::restore(Name));
268   });
269 
270   return Match;
271 }
272 
273 std::string BinaryFunction::getDemangledName() const {
274   StringRef MangledName = NameResolver::restore(getOneName());
275   return demangle(MangledName.str());
276 }
277 
278 BinaryBasicBlock *
279 BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset) {
280   if (Offset > Size)
281     return nullptr;
282 
283   if (BasicBlockOffsets.empty())
284     return nullptr;
285 
286   /*
287    * This is commented out because it makes BOLT too slow.
288    * assert(std::is_sorted(BasicBlockOffsets.begin(),
289    *                       BasicBlockOffsets.end(),
290    *                       CompareBasicBlockOffsets())));
291    */
292   auto I = std::upper_bound(BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
293                             BasicBlockOffset(Offset, nullptr),
294                             CompareBasicBlockOffsets());
295   assert(I != BasicBlockOffsets.begin() && "first basic block not at offset 0");
296   --I;
297   BinaryBasicBlock *BB = I->second;
298   return (Offset < BB->getOffset() + BB->getOriginalSize()) ? BB : nullptr;
299 }
300 
301 void BinaryFunction::markUnreachableBlocks() {
302   std::stack<BinaryBasicBlock *> Stack;
303 
304   for (BinaryBasicBlock *BB : layout())
305     BB->markValid(false);
306 
307   // Add all entries and landing pads as roots.
308   for (BinaryBasicBlock *BB : BasicBlocks) {
309     if (isEntryPoint(*BB) || BB->isLandingPad()) {
310       Stack.push(BB);
311       BB->markValid(true);
312       continue;
313     }
314     // FIXME:
315     // Also mark BBs with indirect jumps as reachable, since we do not
316     // support removing unused jump tables yet (GH-issue20).
317     for (const MCInst &Inst : *BB) {
318       if (BC.MIB->getJumpTable(Inst)) {
319         Stack.push(BB);
320         BB->markValid(true);
321         break;
322       }
323     }
324   }
325 
326   // Determine reachable BBs from the entry point
327   while (!Stack.empty()) {
328     BinaryBasicBlock *BB = Stack.top();
329     Stack.pop();
330     for (BinaryBasicBlock *Succ : BB->successors()) {
331       if (Succ->isValid())
332         continue;
333       Succ->markValid(true);
334       Stack.push(Succ);
335     }
336   }
337 }
338 
339 // Any unnecessary fallthrough jumps revealed after calling eraseInvalidBBs
340 // will be cleaned up by fixBranches().
341 std::pair<unsigned, uint64_t> BinaryFunction::eraseInvalidBBs() {
342   BasicBlockOrderType NewLayout;
343   unsigned Count = 0;
344   uint64_t Bytes = 0;
345   for (BinaryBasicBlock *BB : layout()) {
346     if (BB->isValid()) {
347       NewLayout.push_back(BB);
348     } else {
349       assert(!isEntryPoint(*BB) && "all entry blocks must be valid");
350       ++Count;
351       Bytes += BC.computeCodeSize(BB->begin(), BB->end());
352     }
353   }
354   BasicBlocksLayout = std::move(NewLayout);
355 
356   BasicBlockListType NewBasicBlocks;
357   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
358     BinaryBasicBlock *BB = *I;
359     if (BB->isValid()) {
360       NewBasicBlocks.push_back(BB);
361     } else {
362       // Make sure the block is removed from the list of predecessors.
363       BB->removeAllSuccessors();
364       DeletedBasicBlocks.push_back(BB);
365     }
366   }
367   BasicBlocks = std::move(NewBasicBlocks);
368 
369   assert(BasicBlocks.size() == BasicBlocksLayout.size());
370 
371   // Update CFG state if needed
372   if (Count > 0)
373     recomputeLandingPads();
374 
375   return std::make_pair(Count, Bytes);
376 }
377 
378 bool BinaryFunction::isForwardCall(const MCSymbol *CalleeSymbol) const {
379   // This function should work properly before and after function reordering.
380   // In order to accomplish this, we use the function index (if it is valid).
381   // If the function indices are not valid, we fall back to the original
382   // addresses.  This should be ok because the functions without valid indices
383   // should have been ordered with a stable sort.
384   const BinaryFunction *CalleeBF = BC.getFunctionForSymbol(CalleeSymbol);
385   if (CalleeBF) {
386     if (CalleeBF->isInjected())
387       return true;
388 
389     if (hasValidIndex() && CalleeBF->hasValidIndex()) {
390       return getIndex() < CalleeBF->getIndex();
391     } else if (hasValidIndex() && !CalleeBF->hasValidIndex()) {
392       return true;
393     } else if (!hasValidIndex() && CalleeBF->hasValidIndex()) {
394       return false;
395     } else {
396       return getAddress() < CalleeBF->getAddress();
397     }
398   } else {
399     // Absolute symbol.
400     ErrorOr<uint64_t> CalleeAddressOrError = BC.getSymbolValue(*CalleeSymbol);
401     assert(CalleeAddressOrError && "unregistered symbol found");
402     return *CalleeAddressOrError > getAddress();
403   }
404 }
405 
406 void BinaryFunction::dump(bool PrintInstructions) const {
407   print(dbgs(), "", PrintInstructions);
408 }
409 
410 void BinaryFunction::print(raw_ostream &OS, std::string Annotation,
411                            bool PrintInstructions) const {
412   if (!opts::shouldPrint(*this))
413     return;
414 
415   StringRef SectionName =
416       OriginSection ? OriginSection->getName() : "<no origin section>";
417   OS << "Binary Function \"" << *this << "\" " << Annotation << " {";
418   std::vector<StringRef> AllNames = getNames();
419   if (AllNames.size() > 1) {
420     OS << "\n  All names   : ";
421     const char *Sep = "";
422     for (const StringRef &Name : AllNames) {
423       OS << Sep << Name;
424       Sep = "\n                ";
425     }
426   }
427   OS << "\n  Number      : "   << FunctionNumber
428      << "\n  State       : "   << CurrentState
429      << "\n  Address     : 0x" << Twine::utohexstr(Address)
430      << "\n  Size        : 0x" << Twine::utohexstr(Size)
431      << "\n  MaxSize     : 0x" << Twine::utohexstr(MaxSize)
432      << "\n  Offset      : 0x" << Twine::utohexstr(FileOffset)
433      << "\n  Section     : "   << SectionName
434      << "\n  Orc Section : "   << getCodeSectionName()
435      << "\n  LSDA        : 0x" << Twine::utohexstr(getLSDAAddress())
436      << "\n  IsSimple    : "   << IsSimple
437      << "\n  IsMultiEntry: "   << isMultiEntry()
438      << "\n  IsSplit     : "   << isSplit()
439      << "\n  BB Count    : "   << size();
440 
441   if (HasFixedIndirectBranch)
442     OS << "\n  HasFixedIndirectBranch : true";
443   if (HasUnknownControlFlow)
444     OS << "\n  Unknown CF  : true";
445   if (getPersonalityFunction())
446     OS << "\n  Personality : " << getPersonalityFunction()->getName();
447   if (IsFragment)
448     OS << "\n  IsFragment  : true";
449   if (isFolded())
450     OS << "\n  FoldedInto  : " << *getFoldedIntoFunction();
451   for (BinaryFunction *ParentFragment : ParentFragments)
452     OS << "\n  Parent      : " << *ParentFragment;
453   if (!Fragments.empty()) {
454     OS << "\n  Fragments   : ";
455     const char *Sep = "";
456     for (BinaryFunction *Frag : Fragments) {
457       OS << Sep << *Frag;
458       Sep = ", ";
459     }
460   }
461   if (hasCFG())
462     OS << "\n  Hash        : " << Twine::utohexstr(computeHash());
463   if (isMultiEntry()) {
464     OS << "\n  Secondary Entry Points : ";
465     const char *Sep = "";
466     for (const auto &KV : SecondaryEntryPoints) {
467       OS << Sep << KV.second->getName();
468       Sep = ", ";
469     }
470   }
471   if (FrameInstructions.size())
472     OS << "\n  CFI Instrs  : " << FrameInstructions.size();
473   if (BasicBlocksLayout.size()) {
474     OS << "\n  BB Layout   : ";
475     const char *Sep = "";
476     for (BinaryBasicBlock *BB : BasicBlocksLayout) {
477       OS << Sep << BB->getName();
478       Sep = ", ";
479     }
480   }
481   if (ImageAddress)
482     OS << "\n  Image       : 0x" << Twine::utohexstr(ImageAddress);
483   if (ExecutionCount != COUNT_NO_PROFILE) {
484     OS << "\n  Exec Count  : " << ExecutionCount;
485     OS << "\n  Profile Acc : " << format("%.1f%%", ProfileMatchRatio * 100.0f);
486   }
487 
488   if (opts::PrintDynoStats && !BasicBlocksLayout.empty()) {
489     OS << '\n';
490     DynoStats dynoStats = getDynoStats(*this);
491     OS << dynoStats;
492   }
493 
494   OS << "\n}\n";
495 
496   if (opts::PrintDynoStatsOnly || !PrintInstructions || !BC.InstPrinter)
497     return;
498 
499   // Offset of the instruction in function.
500   uint64_t Offset = 0;
501 
502   if (BasicBlocks.empty() && !Instructions.empty()) {
503     // Print before CFG was built.
504     for (const std::pair<const uint32_t, MCInst> &II : Instructions) {
505       Offset = II.first;
506 
507       // Print label if exists at this offset.
508       auto LI = Labels.find(Offset);
509       if (LI != Labels.end()) {
510         if (const MCSymbol *EntrySymbol =
511                 getSecondaryEntryPointSymbol(LI->second))
512           OS << EntrySymbol->getName() << " (Entry Point):\n";
513         OS << LI->second->getName() << ":\n";
514       }
515 
516       BC.printInstruction(OS, II.second, Offset, this);
517     }
518   }
519 
520   for (uint32_t I = 0, E = BasicBlocksLayout.size(); I != E; ++I) {
521     BinaryBasicBlock *BB = BasicBlocksLayout[I];
522     if (I != 0 && BB->isCold() != BasicBlocksLayout[I - 1]->isCold())
523       OS << "-------   HOT-COLD SPLIT POINT   -------\n\n";
524 
525     OS << BB->getName() << " (" << BB->size()
526        << " instructions, align : " << BB->getAlignment() << ")\n";
527 
528     if (isEntryPoint(*BB)) {
529       if (MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB))
530         OS << "  Secondary Entry Point: " << EntrySymbol->getName() << '\n';
531       else
532         OS << "  Entry Point\n";
533     }
534 
535     if (BB->isLandingPad())
536       OS << "  Landing Pad\n";
537 
538     uint64_t BBExecCount = BB->getExecutionCount();
539     if (hasValidProfile()) {
540       OS << "  Exec Count : ";
541       if (BB->getExecutionCount() != BinaryBasicBlock::COUNT_NO_PROFILE)
542         OS << BBExecCount << '\n';
543       else
544         OS << "<unknown>\n";
545     }
546     if (BB->getCFIState() >= 0)
547       OS << "  CFI State : " << BB->getCFIState() << '\n';
548     if (opts::EnableBAT) {
549       OS << "  Input offset: " << Twine::utohexstr(BB->getInputOffset())
550          << "\n";
551     }
552     if (!BB->pred_empty()) {
553       OS << "  Predecessors: ";
554       const char *Sep = "";
555       for (BinaryBasicBlock *Pred : BB->predecessors()) {
556         OS << Sep << Pred->getName();
557         Sep = ", ";
558       }
559       OS << '\n';
560     }
561     if (!BB->throw_empty()) {
562       OS << "  Throwers: ";
563       const char *Sep = "";
564       for (BinaryBasicBlock *Throw : BB->throwers()) {
565         OS << Sep << Throw->getName();
566         Sep = ", ";
567       }
568       OS << '\n';
569     }
570 
571     Offset = alignTo(Offset, BB->getAlignment());
572 
573     // Note: offsets are imprecise since this is happening prior to relaxation.
574     Offset = BC.printInstructions(OS, BB->begin(), BB->end(), Offset, this);
575 
576     if (!BB->succ_empty()) {
577       OS << "  Successors: ";
578       // For more than 2 successors, sort them based on frequency.
579       std::vector<uint64_t> Indices(BB->succ_size());
580       std::iota(Indices.begin(), Indices.end(), 0);
581       if (BB->succ_size() > 2 && BB->getKnownExecutionCount()) {
582         std::stable_sort(Indices.begin(), Indices.end(),
583                          [&](const uint64_t A, const uint64_t B) {
584                            return BB->BranchInfo[B] < BB->BranchInfo[A];
585                          });
586       }
587       const char *Sep = "";
588       for (unsigned I = 0; I < Indices.size(); ++I) {
589         BinaryBasicBlock *Succ = BB->Successors[Indices[I]];
590         BinaryBasicBlock::BinaryBranchInfo &BI = BB->BranchInfo[Indices[I]];
591         OS << Sep << Succ->getName();
592         if (ExecutionCount != COUNT_NO_PROFILE &&
593             BI.MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
594           OS << " (mispreds: " << BI.MispredictedCount
595              << ", count: " << BI.Count << ")";
596         } else if (ExecutionCount != COUNT_NO_PROFILE &&
597                    BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
598           OS << " (inferred count: " << BI.Count << ")";
599         }
600         Sep = ", ";
601       }
602       OS << '\n';
603     }
604 
605     if (!BB->lp_empty()) {
606       OS << "  Landing Pads: ";
607       const char *Sep = "";
608       for (BinaryBasicBlock *LP : BB->landing_pads()) {
609         OS << Sep << LP->getName();
610         if (ExecutionCount != COUNT_NO_PROFILE) {
611           OS << " (count: " << LP->getExecutionCount() << ")";
612         }
613         Sep = ", ";
614       }
615       OS << '\n';
616     }
617 
618     // In CFG_Finalized state we can miscalculate CFI state at exit.
619     if (CurrentState == State::CFG) {
620       const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
621       if (CFIStateAtExit >= 0)
622         OS << "  CFI State: " << CFIStateAtExit << '\n';
623     }
624 
625     OS << '\n';
626   }
627 
628   // Dump new exception ranges for the function.
629   if (!CallSites.empty()) {
630     OS << "EH table:\n";
631     for (const CallSite &CSI : CallSites) {
632       OS << "  [" << *CSI.Start << ", " << *CSI.End << ") landing pad : ";
633       if (CSI.LP)
634         OS << *CSI.LP;
635       else
636         OS << "0";
637       OS << ", action : " << CSI.Action << '\n';
638     }
639     OS << '\n';
640   }
641 
642   // Print all jump tables.
643   for (const std::pair<const uint64_t, JumpTable *> &JTI : JumpTables)
644     JTI.second->print(OS);
645 
646   OS << "DWARF CFI Instructions:\n";
647   if (OffsetToCFI.size()) {
648     // Pre-buildCFG information
649     for (const std::pair<const uint32_t, uint32_t> &Elmt : OffsetToCFI) {
650       OS << format("    %08x:\t", Elmt.first);
651       assert(Elmt.second < FrameInstructions.size() && "Incorrect CFI offset");
652       BinaryContext::printCFI(OS, FrameInstructions[Elmt.second]);
653       OS << "\n";
654     }
655   } else {
656     // Post-buildCFG information
657     for (uint32_t I = 0, E = FrameInstructions.size(); I != E; ++I) {
658       const MCCFIInstruction &CFI = FrameInstructions[I];
659       OS << format("    %d:\t", I);
660       BinaryContext::printCFI(OS, CFI);
661       OS << "\n";
662     }
663   }
664   if (FrameInstructions.empty())
665     OS << "    <empty>\n";
666 
667   OS << "End of Function \"" << *this << "\"\n\n";
668 }
669 
670 void BinaryFunction::printRelocations(raw_ostream &OS, uint64_t Offset,
671                                       uint64_t Size) const {
672   const char *Sep = " # Relocs: ";
673 
674   auto RI = Relocations.lower_bound(Offset);
675   while (RI != Relocations.end() && RI->first < Offset + Size) {
676     OS << Sep << "(R: " << RI->second << ")";
677     Sep = ", ";
678     ++RI;
679   }
680 }
681 
682 namespace {
683 std::string mutateDWARFExpressionTargetReg(const MCCFIInstruction &Instr,
684                                            MCPhysReg NewReg) {
685   StringRef ExprBytes = Instr.getValues();
686   assert(ExprBytes.size() > 1 && "DWARF expression CFI is too short");
687   uint8_t Opcode = ExprBytes[0];
688   assert((Opcode == dwarf::DW_CFA_expression ||
689           Opcode == dwarf::DW_CFA_val_expression) &&
690          "invalid DWARF expression CFI");
691   (void)Opcode;
692   const uint8_t *const Start =
693       reinterpret_cast<const uint8_t *>(ExprBytes.drop_front(1).data());
694   const uint8_t *const End =
695       reinterpret_cast<const uint8_t *>(Start + ExprBytes.size() - 1);
696   unsigned Size = 0;
697   decodeULEB128(Start, &Size, End);
698   assert(Size > 0 && "Invalid reg encoding for DWARF expression CFI");
699   SmallString<8> Tmp;
700   raw_svector_ostream OSE(Tmp);
701   encodeULEB128(NewReg, OSE);
702   return Twine(ExprBytes.slice(0, 1))
703       .concat(OSE.str())
704       .concat(ExprBytes.drop_front(1 + Size))
705       .str();
706 }
707 } // namespace
708 
709 void BinaryFunction::mutateCFIRegisterFor(const MCInst &Instr,
710                                           MCPhysReg NewReg) {
711   const MCCFIInstruction *OldCFI = getCFIFor(Instr);
712   assert(OldCFI && "invalid CFI instr");
713   switch (OldCFI->getOperation()) {
714   default:
715     llvm_unreachable("Unexpected instruction");
716   case MCCFIInstruction::OpDefCfa:
717     setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, NewReg,
718                                                  OldCFI->getOffset()));
719     break;
720   case MCCFIInstruction::OpDefCfaRegister:
721     setCFIFor(Instr, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg));
722     break;
723   case MCCFIInstruction::OpOffset:
724     setCFIFor(Instr, MCCFIInstruction::createOffset(nullptr, NewReg,
725                                                     OldCFI->getOffset()));
726     break;
727   case MCCFIInstruction::OpRegister:
728     setCFIFor(Instr, MCCFIInstruction::createRegister(nullptr, NewReg,
729                                                       OldCFI->getRegister2()));
730     break;
731   case MCCFIInstruction::OpSameValue:
732     setCFIFor(Instr, MCCFIInstruction::createSameValue(nullptr, NewReg));
733     break;
734   case MCCFIInstruction::OpEscape:
735     setCFIFor(Instr,
736               MCCFIInstruction::createEscape(
737                   nullptr,
738                   StringRef(mutateDWARFExpressionTargetReg(*OldCFI, NewReg))));
739     break;
740   case MCCFIInstruction::OpRestore:
741     setCFIFor(Instr, MCCFIInstruction::createRestore(nullptr, NewReg));
742     break;
743   case MCCFIInstruction::OpUndefined:
744     setCFIFor(Instr, MCCFIInstruction::createUndefined(nullptr, NewReg));
745     break;
746   }
747 }
748 
749 const MCCFIInstruction *BinaryFunction::mutateCFIOffsetFor(const MCInst &Instr,
750                                                            int64_t NewOffset) {
751   const MCCFIInstruction *OldCFI = getCFIFor(Instr);
752   assert(OldCFI && "invalid CFI instr");
753   switch (OldCFI->getOperation()) {
754   default:
755     llvm_unreachable("Unexpected instruction");
756   case MCCFIInstruction::OpDefCfaOffset:
757     setCFIFor(Instr, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset));
758     break;
759   case MCCFIInstruction::OpAdjustCfaOffset:
760     setCFIFor(Instr,
761               MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset));
762     break;
763   case MCCFIInstruction::OpDefCfa:
764     setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI->getRegister(),
765                                                  NewOffset));
766     break;
767   case MCCFIInstruction::OpOffset:
768     setCFIFor(Instr, MCCFIInstruction::createOffset(
769                          nullptr, OldCFI->getRegister(), NewOffset));
770     break;
771   }
772   return getCFIFor(Instr);
773 }
774 
775 IndirectBranchType
776 BinaryFunction::processIndirectBranch(MCInst &Instruction, unsigned Size,
777                                       uint64_t Offset,
778                                       uint64_t &TargetAddress) {
779   const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
780 
781   // The instruction referencing memory used by the branch instruction.
782   // It could be the branch instruction itself or one of the instructions
783   // setting the value of the register used by the branch.
784   MCInst *MemLocInstr;
785 
786   // Address of the table referenced by MemLocInstr. Could be either an
787   // array of function pointers, or a jump table.
788   uint64_t ArrayStart = 0;
789 
790   unsigned BaseRegNum, IndexRegNum;
791   int64_t DispValue;
792   const MCExpr *DispExpr;
793 
794   // In AArch, identify the instruction adding the PC-relative offset to
795   // jump table entries to correctly decode it.
796   MCInst *PCRelBaseInstr;
797   uint64_t PCRelAddr = 0;
798 
799   auto Begin = Instructions.begin();
800   if (BC.isAArch64()) {
801     PreserveNops = BC.HasRelocations;
802     // Start at the last label as an approximation of the current basic block.
803     // This is a heuristic, since the full set of labels have yet to be
804     // determined
805     for (auto LI = Labels.rbegin(); LI != Labels.rend(); ++LI) {
806       auto II = Instructions.find(LI->first);
807       if (II != Instructions.end()) {
808         Begin = II;
809         break;
810       }
811     }
812   }
813 
814   IndirectBranchType BranchType = BC.MIB->analyzeIndirectBranch(
815       Instruction, Begin, Instructions.end(), PtrSize, MemLocInstr, BaseRegNum,
816       IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
817 
818   if (BranchType == IndirectBranchType::UNKNOWN && !MemLocInstr)
819     return BranchType;
820 
821   if (MemLocInstr != &Instruction)
822     IndexRegNum = BC.MIB->getNoRegister();
823 
824   if (BC.isAArch64()) {
825     const MCSymbol *Sym = BC.MIB->getTargetSymbol(*PCRelBaseInstr, 1);
826     assert(Sym && "Symbol extraction failed");
827     ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*Sym);
828     if (SymValueOrError) {
829       PCRelAddr = *SymValueOrError;
830     } else {
831       for (std::pair<const uint32_t, MCSymbol *> &Elmt : Labels) {
832         if (Elmt.second == Sym) {
833           PCRelAddr = Elmt.first + getAddress();
834           break;
835         }
836       }
837     }
838     uint64_t InstrAddr = 0;
839     for (auto II = Instructions.rbegin(); II != Instructions.rend(); ++II) {
840       if (&II->second == PCRelBaseInstr) {
841         InstrAddr = II->first + getAddress();
842         break;
843       }
844     }
845     assert(InstrAddr != 0 && "instruction not found");
846     // We do this to avoid spurious references to code locations outside this
847     // function (for example, if the indirect jump lives in the last basic
848     // block of the function, it will create a reference to the next function).
849     // This replaces a symbol reference with an immediate.
850     BC.MIB->replaceMemOperandDisp(*PCRelBaseInstr,
851                                   MCOperand::createImm(PCRelAddr - InstrAddr));
852     // FIXME: Disable full jump table processing for AArch64 until we have a
853     // proper way of determining the jump table limits.
854     return IndirectBranchType::UNKNOWN;
855   }
856 
857   // RIP-relative addressing should be converted to symbol form by now
858   // in processed instructions (but not in jump).
859   if (DispExpr) {
860     const MCSymbol *TargetSym;
861     uint64_t TargetOffset;
862     std::tie(TargetSym, TargetOffset) = BC.MIB->getTargetSymbolInfo(DispExpr);
863     ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*TargetSym);
864     assert(SymValueOrError && "global symbol needs a value");
865     ArrayStart = *SymValueOrError + TargetOffset;
866     BaseRegNum = BC.MIB->getNoRegister();
867     if (BC.isAArch64()) {
868       ArrayStart &= ~0xFFFULL;
869       ArrayStart += DispValue & 0xFFFULL;
870     }
871   } else {
872     ArrayStart = static_cast<uint64_t>(DispValue);
873   }
874 
875   if (BaseRegNum == BC.MRI->getProgramCounter())
876     ArrayStart += getAddress() + Offset + Size;
877 
878   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addressed memory is 0x"
879                     << Twine::utohexstr(ArrayStart) << '\n');
880 
881   ErrorOr<BinarySection &> Section = BC.getSectionForAddress(ArrayStart);
882   if (!Section) {
883     // No section - possibly an absolute address. Since we don't allow
884     // internal function addresses to escape the function scope - we
885     // consider it a tail call.
886     if (opts::Verbosity >= 1) {
887       errs() << "BOLT-WARNING: no section for address 0x"
888              << Twine::utohexstr(ArrayStart) << " referenced from function "
889              << *this << '\n';
890     }
891     return IndirectBranchType::POSSIBLE_TAIL_CALL;
892   }
893   if (Section->isVirtual()) {
894     // The contents are filled at runtime.
895     return IndirectBranchType::POSSIBLE_TAIL_CALL;
896   }
897 
898   if (BranchType == IndirectBranchType::POSSIBLE_FIXED_BRANCH) {
899     ErrorOr<uint64_t> Value = BC.getPointerAtAddress(ArrayStart);
900     if (!Value)
901       return IndirectBranchType::UNKNOWN;
902 
903     if (!BC.getSectionForAddress(ArrayStart)->isReadOnly())
904       return IndirectBranchType::UNKNOWN;
905 
906     outs() << "BOLT-INFO: fixed indirect branch detected in " << *this
907            << " at 0x" << Twine::utohexstr(getAddress() + Offset)
908            << " referencing data at 0x" << Twine::utohexstr(ArrayStart)
909            << " the destination value is 0x" << Twine::utohexstr(*Value)
910            << '\n';
911 
912     TargetAddress = *Value;
913     return BranchType;
914   }
915 
916   // Check if there's already a jump table registered at this address.
917   MemoryContentsType MemType;
918   if (JumpTable *JT = BC.getJumpTableContainingAddress(ArrayStart)) {
919     switch (JT->Type) {
920     case JumpTable::JTT_NORMAL:
921       MemType = MemoryContentsType::POSSIBLE_JUMP_TABLE;
922       break;
923     case JumpTable::JTT_PIC:
924       MemType = MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
925       break;
926     }
927   } else {
928     MemType = BC.analyzeMemoryAt(ArrayStart, *this);
929   }
930 
931   // Check that jump table type in instruction pattern matches memory contents.
932   JumpTable::JumpTableType JTType;
933   if (BranchType == IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE) {
934     if (MemType != MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
935       return IndirectBranchType::UNKNOWN;
936     JTType = JumpTable::JTT_PIC;
937   } else {
938     if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
939       return IndirectBranchType::UNKNOWN;
940 
941     if (MemType == MemoryContentsType::UNKNOWN)
942       return IndirectBranchType::POSSIBLE_TAIL_CALL;
943 
944     BranchType = IndirectBranchType::POSSIBLE_JUMP_TABLE;
945     JTType = JumpTable::JTT_NORMAL;
946   }
947 
948   // Convert the instruction into jump table branch.
949   const MCSymbol *JTLabel = BC.getOrCreateJumpTable(*this, ArrayStart, JTType);
950   BC.MIB->replaceMemOperandDisp(*MemLocInstr, JTLabel, BC.Ctx.get());
951   BC.MIB->setJumpTable(Instruction, ArrayStart, IndexRegNum);
952 
953   JTSites.emplace_back(Offset, ArrayStart);
954 
955   return BranchType;
956 }
957 
958 MCSymbol *BinaryFunction::getOrCreateLocalLabel(uint64_t Address,
959                                                 bool CreatePastEnd) {
960   const uint64_t Offset = Address - getAddress();
961 
962   if ((Offset == getSize()) && CreatePastEnd)
963     return getFunctionEndLabel();
964 
965   auto LI = Labels.find(Offset);
966   if (LI != Labels.end())
967     return LI->second;
968 
969   // For AArch64, check if this address is part of a constant island.
970   if (BC.isAArch64()) {
971     if (MCSymbol *IslandSym = getOrCreateIslandAccess(Address))
972       return IslandSym;
973   }
974 
975   MCSymbol *Label = BC.Ctx->createNamedTempSymbol();
976   Labels[Offset] = Label;
977 
978   return Label;
979 }
980 
981 ErrorOr<ArrayRef<uint8_t>> BinaryFunction::getData() const {
982   BinarySection &Section = *getOriginSection();
983   assert(Section.containsRange(getAddress(), getMaxSize()) &&
984          "wrong section for function");
985 
986   if (!Section.isText() || Section.isVirtual() || !Section.getSize())
987     return std::make_error_code(std::errc::bad_address);
988 
989   StringRef SectionContents = Section.getContents();
990 
991   assert(SectionContents.size() == Section.getSize() &&
992          "section size mismatch");
993 
994   // Function offset from the section start.
995   uint64_t Offset = getAddress() - Section.getAddress();
996   auto *Bytes = reinterpret_cast<const uint8_t *>(SectionContents.data());
997   return ArrayRef<uint8_t>(Bytes + Offset, getMaxSize());
998 }
999 
1000 size_t BinaryFunction::getSizeOfDataInCodeAt(uint64_t Offset) const {
1001   if (!Islands)
1002     return 0;
1003 
1004   if (Islands->DataOffsets.find(Offset) == Islands->DataOffsets.end())
1005     return 0;
1006 
1007   auto Iter = Islands->CodeOffsets.upper_bound(Offset);
1008   if (Iter != Islands->CodeOffsets.end())
1009     return *Iter - Offset;
1010   return getSize() - Offset;
1011 }
1012 
1013 bool BinaryFunction::isZeroPaddingAt(uint64_t Offset) const {
1014   ArrayRef<uint8_t> FunctionData = *getData();
1015   uint64_t EndOfCode = getSize();
1016   if (Islands) {
1017     auto Iter = Islands->DataOffsets.upper_bound(Offset);
1018     if (Iter != Islands->DataOffsets.end())
1019       EndOfCode = *Iter;
1020   }
1021   for (uint64_t I = Offset; I < EndOfCode; ++I)
1022     if (FunctionData[I] != 0)
1023       return false;
1024 
1025   return true;
1026 }
1027 
1028 bool BinaryFunction::disassemble() {
1029   NamedRegionTimer T("disassemble", "Disassemble function", "buildfuncs",
1030                      "Build Binary Functions", opts::TimeBuild);
1031   ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1032   assert(ErrorOrFunctionData && "function data is not available");
1033   ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1034   assert(FunctionData.size() == getMaxSize() &&
1035          "function size does not match raw data size");
1036 
1037   auto &Ctx = BC.Ctx;
1038   auto &MIB = BC.MIB;
1039 
1040   // Insert a label at the beginning of the function. This will be our first
1041   // basic block.
1042   Labels[0] = Ctx->createNamedTempSymbol("BB0");
1043 
1044   auto handlePCRelOperand = [&](MCInst &Instruction, uint64_t Address,
1045                                 uint64_t Size) {
1046     uint64_t TargetAddress = 0;
1047     if (!MIB->evaluateMemOperandTarget(Instruction, TargetAddress, Address,
1048                                        Size)) {
1049       errs() << "BOLT-ERROR: PC-relative operand can't be evaluated:\n";
1050       BC.InstPrinter->printInst(&Instruction, 0, "", *BC.STI, errs());
1051       errs() << '\n';
1052       Instruction.dump_pretty(errs(), BC.InstPrinter.get());
1053       errs() << '\n';
1054       errs() << "BOLT-ERROR: cannot handle PC-relative operand at 0x"
1055              << Twine::utohexstr(Address) << ". Skipping function " << *this
1056              << ".\n";
1057       if (BC.HasRelocations)
1058         exit(1);
1059       IsSimple = false;
1060       return;
1061     }
1062     if (TargetAddress == 0 && opts::Verbosity >= 1) {
1063       outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this
1064              << '\n';
1065     }
1066 
1067     const MCSymbol *TargetSymbol;
1068     uint64_t TargetOffset;
1069     std::tie(TargetSymbol, TargetOffset) =
1070         BC.handleAddressRef(TargetAddress, *this, /*IsPCRel*/ true);
1071     const MCExpr *Expr = MCSymbolRefExpr::create(
1072         TargetSymbol, MCSymbolRefExpr::VK_None, *BC.Ctx);
1073     if (TargetOffset) {
1074       const MCConstantExpr *Offset =
1075           MCConstantExpr::create(TargetOffset, *BC.Ctx);
1076       Expr = MCBinaryExpr::createAdd(Expr, Offset, *BC.Ctx);
1077     }
1078     MIB->replaceMemOperandDisp(Instruction,
1079                                MCOperand::createExpr(BC.MIB->getTargetExprFor(
1080                                    Instruction, Expr, *BC.Ctx, 0)));
1081   };
1082 
1083   // Used to fix the target of linker-generated AArch64 stubs with no relocation
1084   // info
1085   auto fixStubTarget = [&](MCInst &LoadLowBits, MCInst &LoadHiBits,
1086                            uint64_t Target) {
1087     const MCSymbol *TargetSymbol;
1088     uint64_t Addend = 0;
1089     std::tie(TargetSymbol, Addend) = BC.handleAddressRef(Target, *this, true);
1090 
1091     int64_t Val;
1092     MIB->replaceImmWithSymbolRef(LoadHiBits, TargetSymbol, Addend, Ctx.get(),
1093                                  Val, ELF::R_AARCH64_ADR_PREL_PG_HI21);
1094     MIB->replaceImmWithSymbolRef(LoadLowBits, TargetSymbol, Addend, Ctx.get(),
1095                                  Val, ELF::R_AARCH64_ADD_ABS_LO12_NC);
1096   };
1097 
1098   auto handleExternalReference = [&](MCInst &Instruction, uint64_t Size,
1099                                      uint64_t Offset, uint64_t TargetAddress,
1100                                      bool &IsCall) -> MCSymbol * {
1101     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1102     MCSymbol *TargetSymbol = nullptr;
1103     InterproceduralReferences.insert(TargetAddress);
1104     if (opts::Verbosity >= 2 && !IsCall && Size == 2 && !BC.HasRelocations) {
1105       errs() << "BOLT-WARNING: relaxed tail call detected at 0x"
1106              << Twine::utohexstr(AbsoluteInstrAddr) << " in function " << *this
1107              << ". Code size will be increased.\n";
1108     }
1109 
1110     assert(!MIB->isTailCall(Instruction) &&
1111            "synthetic tail call instruction found");
1112 
1113     // This is a call regardless of the opcode.
1114     // Assign proper opcode for tail calls, so that they could be
1115     // treated as calls.
1116     if (!IsCall) {
1117       if (!MIB->convertJmpToTailCall(Instruction)) {
1118         assert(MIB->isConditionalBranch(Instruction) &&
1119                "unknown tail call instruction");
1120         if (opts::Verbosity >= 2) {
1121           errs() << "BOLT-WARNING: conditional tail call detected in "
1122                  << "function " << *this << " at 0x"
1123                  << Twine::utohexstr(AbsoluteInstrAddr) << ".\n";
1124         }
1125       }
1126       IsCall = true;
1127     }
1128 
1129     TargetSymbol = BC.getOrCreateGlobalSymbol(TargetAddress, "FUNCat");
1130     if (opts::Verbosity >= 2 && TargetAddress == 0) {
1131       // We actually see calls to address 0 in presence of weak
1132       // symbols originating from libraries. This code is never meant
1133       // to be executed.
1134       outs() << "BOLT-INFO: Function " << *this
1135              << " has a call to address zero.\n";
1136     }
1137 
1138     return TargetSymbol;
1139   };
1140 
1141   auto handleIndirectBranch = [&](MCInst &Instruction, uint64_t Size,
1142                                   uint64_t Offset) {
1143     uint64_t IndirectTarget = 0;
1144     IndirectBranchType Result =
1145         processIndirectBranch(Instruction, Size, Offset, IndirectTarget);
1146     switch (Result) {
1147     default:
1148       llvm_unreachable("unexpected result");
1149     case IndirectBranchType::POSSIBLE_TAIL_CALL: {
1150       bool Result = MIB->convertJmpToTailCall(Instruction);
1151       (void)Result;
1152       assert(Result);
1153       break;
1154     }
1155     case IndirectBranchType::POSSIBLE_JUMP_TABLE:
1156     case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE:
1157       if (opts::JumpTables == JTS_NONE)
1158         IsSimple = false;
1159       break;
1160     case IndirectBranchType::POSSIBLE_FIXED_BRANCH: {
1161       if (containsAddress(IndirectTarget)) {
1162         const MCSymbol *TargetSymbol = getOrCreateLocalLabel(IndirectTarget);
1163         Instruction.clear();
1164         MIB->createUncondBranch(Instruction, TargetSymbol, BC.Ctx.get());
1165         TakenBranches.emplace_back(Offset, IndirectTarget - getAddress());
1166         HasFixedIndirectBranch = true;
1167       } else {
1168         MIB->convertJmpToTailCall(Instruction);
1169         InterproceduralReferences.insert(IndirectTarget);
1170       }
1171       break;
1172     }
1173     case IndirectBranchType::UNKNOWN:
1174       // Keep processing. We'll do more checks and fixes in
1175       // postProcessIndirectBranches().
1176       UnknownIndirectBranchOffsets.emplace(Offset);
1177       break;
1178     }
1179   };
1180 
1181   // Check for linker veneers, which lack relocations and need manual
1182   // adjustments.
1183   auto handleAArch64IndirectCall = [&](MCInst &Instruction, uint64_t Offset) {
1184     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1185     MCInst *TargetHiBits, *TargetLowBits;
1186     uint64_t TargetAddress;
1187     if (MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1188                                AbsoluteInstrAddr, Instruction, TargetHiBits,
1189                                TargetLowBits, TargetAddress)) {
1190       MIB->addAnnotation(Instruction, "AArch64Veneer", true);
1191 
1192       uint8_t Counter = 0;
1193       for (auto It = std::prev(Instructions.end()); Counter != 2;
1194            --It, ++Counter) {
1195         MIB->addAnnotation(It->second, "AArch64Veneer", true);
1196       }
1197 
1198       fixStubTarget(*TargetLowBits, *TargetHiBits, TargetAddress);
1199     }
1200   };
1201 
1202   uint64_t Size = 0; // instruction size
1203   for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1204     MCInst Instruction;
1205     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1206 
1207     // Check for data inside code and ignore it
1208     if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1209       Size = DataInCodeSize;
1210       continue;
1211     }
1212 
1213     if (!BC.DisAsm->getInstruction(Instruction, Size,
1214                                    FunctionData.slice(Offset),
1215                                    AbsoluteInstrAddr, nulls())) {
1216       // Functions with "soft" boundaries, e.g. coming from assembly source,
1217       // can have 0-byte padding at the end.
1218       if (isZeroPaddingAt(Offset))
1219         break;
1220 
1221       errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1222              << Twine::utohexstr(Offset) << " (address 0x"
1223              << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " << *this
1224              << '\n';
1225       // Some AVX-512 instructions could not be disassembled at all.
1226       if (BC.HasRelocations && opts::TrapOnAVX512 && BC.isX86()) {
1227         setTrapOnEntry();
1228         BC.TrappedFunctions.push_back(this);
1229       } else {
1230         setIgnored();
1231       }
1232 
1233       break;
1234     }
1235 
1236     // Check integrity of LLVM assembler/disassembler.
1237     if (opts::CheckEncoding && !BC.MIB->isBranch(Instruction) &&
1238         !BC.MIB->isCall(Instruction) && !BC.MIB->isNoop(Instruction)) {
1239       if (!BC.validateEncoding(Instruction, FunctionData.slice(Offset, Size))) {
1240         errs() << "BOLT-WARNING: mismatching LLVM encoding detected in "
1241                << "function " << *this << " for instruction :\n";
1242         BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr);
1243         errs() << '\n';
1244       }
1245     }
1246 
1247     // Special handling for AVX-512 instructions.
1248     if (MIB->hasEVEXEncoding(Instruction)) {
1249       if (BC.HasRelocations && opts::TrapOnAVX512) {
1250         setTrapOnEntry();
1251         BC.TrappedFunctions.push_back(this);
1252         break;
1253       }
1254 
1255       // Check if our disassembly is correct and matches the assembler output.
1256       if (!BC.validateEncoding(Instruction, FunctionData.slice(Offset, Size))) {
1257         if (opts::Verbosity >= 1) {
1258           errs() << "BOLT-WARNING: internal assembler/disassembler error "
1259                     "detected for AVX512 instruction:\n";
1260           BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr);
1261           errs() << " in function " << *this << '\n';
1262         }
1263 
1264         setIgnored();
1265         break;
1266       }
1267     }
1268 
1269     if (MIB->isBranch(Instruction) || MIB->isCall(Instruction)) {
1270       uint64_t TargetAddress = 0;
1271       if (MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1272                               TargetAddress)) {
1273         // Check if the target is within the same function. Otherwise it's
1274         // a call, possibly a tail call.
1275         //
1276         // If the target *is* the function address it could be either a branch
1277         // or a recursive call.
1278         bool IsCall = MIB->isCall(Instruction);
1279         const bool IsCondBranch = MIB->isConditionalBranch(Instruction);
1280         MCSymbol *TargetSymbol = nullptr;
1281 
1282         if (BC.MIB->isUnsupportedBranch(Instruction.getOpcode())) {
1283           setIgnored();
1284           if (BinaryFunction *TargetFunc =
1285                   BC.getBinaryFunctionContainingAddress(TargetAddress))
1286             TargetFunc->setIgnored();
1287         }
1288 
1289         if (IsCall && containsAddress(TargetAddress)) {
1290           if (TargetAddress == getAddress()) {
1291             // Recursive call.
1292             TargetSymbol = getSymbol();
1293           } else {
1294             if (BC.isX86()) {
1295               // Dangerous old-style x86 PIC code. We may need to freeze this
1296               // function, so preserve the function as is for now.
1297               PreserveNops = true;
1298             } else {
1299               errs() << "BOLT-WARNING: internal call detected at 0x"
1300                      << Twine::utohexstr(AbsoluteInstrAddr) << " in function "
1301                      << *this << ". Skipping.\n";
1302               IsSimple = false;
1303             }
1304           }
1305         }
1306 
1307         if (!TargetSymbol) {
1308           // Create either local label or external symbol.
1309           if (containsAddress(TargetAddress)) {
1310             TargetSymbol = getOrCreateLocalLabel(TargetAddress);
1311           } else {
1312             if (TargetAddress == getAddress() + getSize() &&
1313                 TargetAddress < getAddress() + getMaxSize()) {
1314               // Result of __builtin_unreachable().
1315               LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump past end detected at 0x"
1316                                 << Twine::utohexstr(AbsoluteInstrAddr)
1317                                 << " in function " << *this
1318                                 << " : replacing with nop.\n");
1319               BC.MIB->createNoop(Instruction);
1320               if (IsCondBranch) {
1321                 // Register branch offset for profile validation.
1322                 IgnoredBranches.emplace_back(Offset, Offset + Size);
1323               }
1324               goto add_instruction;
1325             }
1326             // May update Instruction and IsCall
1327             TargetSymbol = handleExternalReference(Instruction, Size, Offset,
1328                                                    TargetAddress, IsCall);
1329           }
1330         }
1331 
1332         if (!IsCall) {
1333           // Add taken branch info.
1334           TakenBranches.emplace_back(Offset, TargetAddress - getAddress());
1335         }
1336         BC.MIB->replaceBranchTarget(Instruction, TargetSymbol, &*Ctx);
1337 
1338         // Mark CTC.
1339         if (IsCondBranch && IsCall)
1340           MIB->setConditionalTailCall(Instruction, TargetAddress);
1341       } else {
1342         // Could not evaluate branch. Should be an indirect call or an
1343         // indirect branch. Bail out on the latter case.
1344         if (MIB->isIndirectBranch(Instruction))
1345           handleIndirectBranch(Instruction, Size, Offset);
1346         // Indirect call. We only need to fix it if the operand is RIP-relative.
1347         if (IsSimple && MIB->hasPCRelOperand(Instruction))
1348           handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1349 
1350         if (BC.isAArch64())
1351           handleAArch64IndirectCall(Instruction, Offset);
1352       }
1353     } else {
1354       // Check if there's a relocation associated with this instruction.
1355       bool UsedReloc = false;
1356       for (auto Itr = Relocations.lower_bound(Offset),
1357                 ItrE = Relocations.lower_bound(Offset + Size);
1358            Itr != ItrE; ++Itr) {
1359         const Relocation &Relocation = Itr->second;
1360         uint64_t SymbolValue = Relocation.Value - Relocation.Addend;
1361         if (Relocation.isPCRelative())
1362           SymbolValue += getAddress() + Relocation.Offset;
1363 
1364         // Process reference to the symbol.
1365         if (BC.isX86())
1366           BC.handleAddressRef(SymbolValue, *this, Relocation.isPCRelative());
1367 
1368         if (BC.isAArch64() || !Relocation.isPCRelative()) {
1369           int64_t Value = Relocation.Value;
1370           const bool Result = BC.MIB->replaceImmWithSymbolRef(
1371               Instruction, Relocation.Symbol, Relocation.Addend, Ctx.get(),
1372               Value, Relocation.Type);
1373           (void)Result;
1374           assert(Result && "cannot replace immediate with relocation");
1375 
1376           if (BC.isX86()) {
1377             // Make sure we replaced the correct immediate (instruction
1378             // can have multiple immediate operands).
1379             assert(
1380                 truncateToSize(static_cast<uint64_t>(Value),
1381                                Relocation::getSizeForType(Relocation.Type)) ==
1382                     truncateToSize(Relocation.Value, Relocation::getSizeForType(
1383                                                          Relocation.Type)) &&
1384                 "immediate value mismatch in function");
1385           } else if (BC.isAArch64()) {
1386             // For aarch, if we replaced an immediate with a symbol from a
1387             // relocation, we mark it so we do not try to further process a
1388             // pc-relative operand. All we need is the symbol.
1389             UsedReloc = true;
1390           }
1391         } else {
1392           // Check if the relocation matches memop's Disp.
1393           uint64_t TargetAddress;
1394           if (!BC.MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1395                                                 AbsoluteInstrAddr, Size)) {
1396             errs() << "BOLT-ERROR: PC-relative operand can't be evaluated\n";
1397             exit(1);
1398           }
1399           assert(TargetAddress == Relocation.Value + AbsoluteInstrAddr + Size &&
1400                  "Immediate value mismatch detected.");
1401 
1402           const MCExpr *Expr = MCSymbolRefExpr::create(
1403               Relocation.Symbol, MCSymbolRefExpr::VK_None, *BC.Ctx);
1404           // Real addend for pc-relative targets is adjusted with a delta
1405           // from relocation placement to the next instruction.
1406           const uint64_t TargetAddend =
1407               Relocation.Addend + Offset + Size - Relocation.Offset;
1408           if (TargetAddend) {
1409             const MCConstantExpr *Offset =
1410                 MCConstantExpr::create(TargetAddend, *BC.Ctx);
1411             Expr = MCBinaryExpr::createAdd(Expr, Offset, *BC.Ctx);
1412           }
1413           BC.MIB->replaceMemOperandDisp(
1414               Instruction, MCOperand::createExpr(BC.MIB->getTargetExprFor(
1415                                Instruction, Expr, *BC.Ctx, 0)));
1416           UsedReloc = true;
1417         }
1418       }
1419 
1420       if (MIB->hasPCRelOperand(Instruction) && !UsedReloc)
1421         handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1422     }
1423 
1424 add_instruction:
1425     if (getDWARFLineTable()) {
1426       Instruction.setLoc(findDebugLineInformationForInstructionAt(
1427           AbsoluteInstrAddr, getDWARFUnit(), getDWARFLineTable()));
1428     }
1429 
1430     // Record offset of the instruction for profile matching.
1431     if (BC.keepOffsetForInstruction(Instruction))
1432       MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
1433 
1434     if (BC.MIB->isNoop(Instruction)) {
1435       // NOTE: disassembly loses the correct size information for noops.
1436       //       E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
1437       //       5 bytes. Preserve the size info using annotations.
1438       MIB->addAnnotation(Instruction, "Size", static_cast<uint32_t>(Size));
1439     }
1440 
1441     addInstruction(Offset, std::move(Instruction));
1442   }
1443 
1444   clearList(Relocations);
1445 
1446   if (!IsSimple) {
1447     clearList(Instructions);
1448     return false;
1449   }
1450 
1451   updateState(State::Disassembled);
1452 
1453   return true;
1454 }
1455 
1456 bool BinaryFunction::scanExternalRefs() {
1457   bool Success = true;
1458   bool DisassemblyFailed = false;
1459 
1460   // Ignore pseudo functions.
1461   if (isPseudo())
1462     return Success;
1463 
1464   if (opts::NoScan) {
1465     clearList(Relocations);
1466     clearList(ExternallyReferencedOffsets);
1467 
1468     return false;
1469   }
1470 
1471   // List of external references for this function.
1472   std::vector<Relocation> FunctionRelocations;
1473 
1474   static BinaryContext::IndependentCodeEmitter Emitter =
1475       BC.createIndependentMCCodeEmitter();
1476 
1477   ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1478   assert(ErrorOrFunctionData && "function data is not available");
1479   ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1480   assert(FunctionData.size() == getMaxSize() &&
1481          "function size does not match raw data size");
1482 
1483   uint64_t Size = 0; // instruction size
1484   for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1485     // Check for data inside code and ignore it
1486     if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1487       Size = DataInCodeSize;
1488       continue;
1489     }
1490 
1491     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1492     MCInst Instruction;
1493     if (!BC.DisAsm->getInstruction(Instruction, Size,
1494                                    FunctionData.slice(Offset),
1495                                    AbsoluteInstrAddr, nulls())) {
1496       if (opts::Verbosity >= 1 && !isZeroPaddingAt(Offset)) {
1497         errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1498                << Twine::utohexstr(Offset) << " (address 0x"
1499                << Twine::utohexstr(AbsoluteInstrAddr) << ") in function "
1500                << *this << '\n';
1501       }
1502       Success = false;
1503       DisassemblyFailed = true;
1504       break;
1505     }
1506 
1507     // Return true if we can skip handling the Target function reference.
1508     auto ignoreFunctionRef = [&](const BinaryFunction &Target) {
1509       if (&Target == this)
1510         return true;
1511 
1512       // Note that later we may decide not to emit Target function. In that
1513       // case, we conservatively create references that will be ignored or
1514       // resolved to the same function.
1515       if (!BC.shouldEmit(Target))
1516         return true;
1517 
1518       return false;
1519     };
1520 
1521     // Return true if we can ignore reference to the symbol.
1522     auto ignoreReference = [&](const MCSymbol *TargetSymbol) {
1523       if (!TargetSymbol)
1524         return true;
1525 
1526       if (BC.forceSymbolRelocations(TargetSymbol->getName()))
1527         return false;
1528 
1529       BinaryFunction *TargetFunction = BC.getFunctionForSymbol(TargetSymbol);
1530       if (!TargetFunction)
1531         return true;
1532 
1533       return ignoreFunctionRef(*TargetFunction);
1534     };
1535 
1536     // Detect if the instruction references an address.
1537     // Without relocations, we can only trust PC-relative address modes.
1538     uint64_t TargetAddress = 0;
1539     bool IsPCRel = false;
1540     bool IsBranch = false;
1541     if (BC.MIB->hasPCRelOperand(Instruction)) {
1542       if (BC.MIB->evaluateMemOperandTarget(Instruction, TargetAddress,
1543                                            AbsoluteInstrAddr, Size)) {
1544         IsPCRel = true;
1545       }
1546     } else if (BC.MIB->isCall(Instruction) || BC.MIB->isBranch(Instruction)) {
1547       if (BC.MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1548                                  TargetAddress)) {
1549         IsBranch = true;
1550       }
1551     }
1552 
1553     MCSymbol *TargetSymbol = nullptr;
1554 
1555     // Create an entry point at reference address if needed.
1556     BinaryFunction *TargetFunction =
1557         BC.getBinaryFunctionContainingAddress(TargetAddress);
1558     if (TargetFunction && !ignoreFunctionRef(*TargetFunction)) {
1559       const uint64_t FunctionOffset =
1560           TargetAddress - TargetFunction->getAddress();
1561       TargetSymbol = FunctionOffset
1562                          ? TargetFunction->addEntryPointAtOffset(FunctionOffset)
1563                          : TargetFunction->getSymbol();
1564     }
1565 
1566     // Can't find more references and not creating relocations.
1567     if (!BC.HasRelocations)
1568       continue;
1569 
1570     // Create a relocation against the TargetSymbol as the symbol might get
1571     // moved.
1572     if (TargetSymbol) {
1573       if (IsBranch) {
1574         BC.MIB->replaceBranchTarget(Instruction, TargetSymbol,
1575                                     Emitter.LocalCtx.get());
1576       } else if (IsPCRel) {
1577         const MCExpr *Expr = MCSymbolRefExpr::create(
1578             TargetSymbol, MCSymbolRefExpr::VK_None, *Emitter.LocalCtx.get());
1579         BC.MIB->replaceMemOperandDisp(
1580             Instruction, MCOperand::createExpr(BC.MIB->getTargetExprFor(
1581                              Instruction, Expr, *Emitter.LocalCtx.get(), 0)));
1582       }
1583     }
1584 
1585     // Create more relocations based on input file relocations.
1586     bool HasRel = false;
1587     for (auto Itr = Relocations.lower_bound(Offset),
1588               ItrE = Relocations.lower_bound(Offset + Size);
1589          Itr != ItrE; ++Itr) {
1590       Relocation &Relocation = Itr->second;
1591       if (Relocation.isPCRelative() && BC.isX86())
1592         continue;
1593       if (ignoreReference(Relocation.Symbol))
1594         continue;
1595 
1596       int64_t Value = Relocation.Value;
1597       const bool Result = BC.MIB->replaceImmWithSymbolRef(
1598           Instruction, Relocation.Symbol, Relocation.Addend,
1599           Emitter.LocalCtx.get(), Value, Relocation.Type);
1600       (void)Result;
1601       assert(Result && "cannot replace immediate with relocation");
1602 
1603       HasRel = true;
1604     }
1605 
1606     if (!TargetSymbol && !HasRel)
1607       continue;
1608 
1609     // Emit the instruction using temp emitter and generate relocations.
1610     SmallString<256> Code;
1611     SmallVector<MCFixup, 4> Fixups;
1612     raw_svector_ostream VecOS(Code);
1613     Emitter.MCE->encodeInstruction(Instruction, VecOS, Fixups, *BC.STI);
1614 
1615     // Create relocation for every fixup.
1616     for (const MCFixup &Fixup : Fixups) {
1617       Optional<Relocation> Rel = BC.MIB->createRelocation(Fixup, *BC.MAB);
1618       if (!Rel) {
1619         Success = false;
1620         continue;
1621       }
1622 
1623       if (Relocation::getSizeForType(Rel->Type) < 4) {
1624         // If the instruction uses a short form, then we might not be able
1625         // to handle the rewrite without relaxation, and hence cannot reliably
1626         // create an external reference relocation.
1627         Success = false;
1628         continue;
1629       }
1630       Rel->Offset += getAddress() - getOriginSection()->getAddress() + Offset;
1631       FunctionRelocations.push_back(*Rel);
1632     }
1633 
1634     if (!Success)
1635       break;
1636   }
1637 
1638   // Add relocations unless disassembly failed for this function.
1639   if (!DisassemblyFailed)
1640     for (Relocation &Rel : FunctionRelocations)
1641       getOriginSection()->addPendingRelocation(Rel);
1642 
1643   // Inform BinaryContext that this function symbols will not be defined and
1644   // relocations should not be created against them.
1645   if (BC.HasRelocations) {
1646     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
1647       BC.UndefinedSymbols.insert(LI.second);
1648     if (FunctionEndLabel)
1649       BC.UndefinedSymbols.insert(FunctionEndLabel);
1650   }
1651 
1652   clearList(Relocations);
1653   clearList(ExternallyReferencedOffsets);
1654 
1655   if (Success && BC.HasRelocations)
1656     HasExternalRefRelocations = true;
1657 
1658   if (opts::Verbosity >= 1 && !Success)
1659     outs() << "BOLT-INFO: failed to scan refs for  " << *this << '\n';
1660 
1661   return Success;
1662 }
1663 
1664 void BinaryFunction::postProcessEntryPoints() {
1665   if (!isSimple())
1666     return;
1667 
1668   for (auto &KV : Labels) {
1669     MCSymbol *Label = KV.second;
1670     if (!getSecondaryEntryPointSymbol(Label))
1671       continue;
1672 
1673     // In non-relocation mode there's potentially an external undetectable
1674     // reference to the entry point and hence we cannot move this entry
1675     // point. Optimizing without moving could be difficult.
1676     if (!BC.HasRelocations)
1677       setSimple(false);
1678 
1679     const uint32_t Offset = KV.first;
1680 
1681     // If we are at Offset 0 and there is no instruction associated with it,
1682     // this means this is an empty function. Just ignore. If we find an
1683     // instruction at this offset, this entry point is valid.
1684     if (!Offset || getInstructionAtOffset(Offset))
1685       continue;
1686 
1687     // On AArch64 there are legitimate reasons to have references past the
1688     // end of the function, e.g. jump tables.
1689     if (BC.isAArch64() && Offset == getSize())
1690       continue;
1691 
1692     errs() << "BOLT-WARNING: reference in the middle of instruction "
1693               "detected in function "
1694            << *this << " at offset 0x" << Twine::utohexstr(Offset) << '\n';
1695     if (BC.HasRelocations)
1696       setIgnored();
1697     setSimple(false);
1698     return;
1699   }
1700 }
1701 
1702 void BinaryFunction::postProcessJumpTables() {
1703   // Create labels for all entries.
1704   for (auto &JTI : JumpTables) {
1705     JumpTable &JT = *JTI.second;
1706     if (JT.Type == JumpTable::JTT_PIC && opts::JumpTables == JTS_BASIC) {
1707       opts::JumpTables = JTS_MOVE;
1708       outs() << "BOLT-INFO: forcing -jump-tables=move as PIC jump table was "
1709                 "detected in function "
1710              << *this << '\n';
1711     }
1712     for (unsigned I = 0; I < JT.OffsetEntries.size(); ++I) {
1713       MCSymbol *Label =
1714           getOrCreateLocalLabel(getAddress() + JT.OffsetEntries[I],
1715                                 /*CreatePastEnd*/ true);
1716       JT.Entries.push_back(Label);
1717     }
1718 
1719     const uint64_t BDSize =
1720         BC.getBinaryDataAtAddress(JT.getAddress())->getSize();
1721     if (!BDSize) {
1722       BC.setBinaryDataSize(JT.getAddress(), JT.getSize());
1723     } else {
1724       assert(BDSize >= JT.getSize() &&
1725              "jump table cannot be larger than the containing object");
1726     }
1727   }
1728 
1729   // Add TakenBranches from JumpTables.
1730   //
1731   // We want to do it after initial processing since we don't know jump tables'
1732   // boundaries until we process them all.
1733   for (auto &JTSite : JTSites) {
1734     const uint64_t JTSiteOffset = JTSite.first;
1735     const uint64_t JTAddress = JTSite.second;
1736     const JumpTable *JT = getJumpTableContainingAddress(JTAddress);
1737     assert(JT && "cannot find jump table for address");
1738 
1739     uint64_t EntryOffset = JTAddress - JT->getAddress();
1740     while (EntryOffset < JT->getSize()) {
1741       uint64_t TargetOffset = JT->OffsetEntries[EntryOffset / JT->EntrySize];
1742       if (TargetOffset < getSize()) {
1743         TakenBranches.emplace_back(JTSiteOffset, TargetOffset);
1744 
1745         if (opts::StrictMode)
1746           registerReferencedOffset(TargetOffset);
1747       }
1748 
1749       EntryOffset += JT->EntrySize;
1750 
1751       // A label at the next entry means the end of this jump table.
1752       if (JT->Labels.count(EntryOffset))
1753         break;
1754     }
1755   }
1756   clearList(JTSites);
1757 
1758   // Free memory used by jump table offsets.
1759   for (auto &JTI : JumpTables) {
1760     JumpTable &JT = *JTI.second;
1761     clearList(JT.OffsetEntries);
1762   }
1763 
1764   // Conservatively populate all possible destinations for unknown indirect
1765   // branches.
1766   if (opts::StrictMode && hasInternalReference()) {
1767     for (uint64_t Offset : UnknownIndirectBranchOffsets) {
1768       for (uint64_t PossibleDestination : ExternallyReferencedOffsets) {
1769         // Ignore __builtin_unreachable().
1770         if (PossibleDestination == getSize())
1771           continue;
1772         TakenBranches.emplace_back(Offset, PossibleDestination);
1773       }
1774     }
1775   }
1776 
1777   // Remove duplicates branches. We can get a bunch of them from jump tables.
1778   // Without doing jump table value profiling we don't have use for extra
1779   // (duplicate) branches.
1780   std::sort(TakenBranches.begin(), TakenBranches.end());
1781   auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end());
1782   TakenBranches.erase(NewEnd, TakenBranches.end());
1783 }
1784 
1785 bool BinaryFunction::postProcessIndirectBranches(
1786     MCPlusBuilder::AllocatorIdTy AllocId) {
1787   auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) {
1788     HasUnknownControlFlow = true;
1789     BB.removeAllSuccessors();
1790     for (uint64_t PossibleDestination : ExternallyReferencedOffsets)
1791       if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination))
1792         BB.addSuccessor(SuccBB);
1793   };
1794 
1795   uint64_t NumIndirectJumps = 0;
1796   MCInst *LastIndirectJump = nullptr;
1797   BinaryBasicBlock *LastIndirectJumpBB = nullptr;
1798   uint64_t LastJT = 0;
1799   uint16_t LastJTIndexReg = BC.MIB->getNoRegister();
1800   for (BinaryBasicBlock *BB : layout()) {
1801     for (MCInst &Instr : *BB) {
1802       if (!BC.MIB->isIndirectBranch(Instr))
1803         continue;
1804 
1805       // If there's an indirect branch in a single-block function -
1806       // it must be a tail call.
1807       if (layout_size() == 1) {
1808         BC.MIB->convertJmpToTailCall(Instr);
1809         return true;
1810       }
1811 
1812       ++NumIndirectJumps;
1813 
1814       if (opts::StrictMode && !hasInternalReference()) {
1815         BC.MIB->convertJmpToTailCall(Instr);
1816         break;
1817       }
1818 
1819       // Validate the tail call or jump table assumptions now that we know
1820       // basic block boundaries.
1821       if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) {
1822         const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
1823         MCInst *MemLocInstr;
1824         unsigned BaseRegNum, IndexRegNum;
1825         int64_t DispValue;
1826         const MCExpr *DispExpr;
1827         MCInst *PCRelBaseInstr;
1828         IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
1829             Instr, BB->begin(), BB->end(), PtrSize, MemLocInstr, BaseRegNum,
1830             IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
1831         if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr)
1832           continue;
1833 
1834         if (!opts::StrictMode)
1835           return false;
1836 
1837         if (BC.MIB->isTailCall(Instr)) {
1838           BC.MIB->convertTailCallToJmp(Instr);
1839         } else {
1840           LastIndirectJump = &Instr;
1841           LastIndirectJumpBB = BB;
1842           LastJT = BC.MIB->getJumpTable(Instr);
1843           LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr);
1844           BC.MIB->unsetJumpTable(Instr);
1845 
1846           JumpTable *JT = BC.getJumpTableContainingAddress(LastJT);
1847           if (JT->Type == JumpTable::JTT_NORMAL) {
1848             // Invalidating the jump table may also invalidate other jump table
1849             // boundaries. Until we have/need a support for this, mark the
1850             // function as non-simple.
1851             LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference"
1852                               << JT->getName() << " in " << *this << '\n');
1853             return false;
1854           }
1855         }
1856 
1857         addUnknownControlFlow(*BB);
1858         continue;
1859       }
1860 
1861       // If this block contains an epilogue code and has an indirect branch,
1862       // then most likely it's a tail call. Otherwise, we cannot tell for sure
1863       // what it is and conservatively reject the function's CFG.
1864       bool IsEpilogue = false;
1865       for (const MCInst &Instr : *BB) {
1866         if (BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr)) {
1867           IsEpilogue = true;
1868           break;
1869         }
1870       }
1871       if (IsEpilogue) {
1872         BC.MIB->convertJmpToTailCall(Instr);
1873         BB->removeAllSuccessors();
1874         continue;
1875       }
1876 
1877       if (opts::Verbosity >= 2) {
1878         outs() << "BOLT-INFO: rejected potential indirect tail call in "
1879                << "function " << *this << " in basic block " << BB->getName()
1880                << ".\n";
1881         LLVM_DEBUG(BC.printInstructions(dbgs(), BB->begin(), BB->end(),
1882                                         BB->getOffset(), this, true));
1883       }
1884 
1885       if (!opts::StrictMode)
1886         return false;
1887 
1888       addUnknownControlFlow(*BB);
1889     }
1890   }
1891 
1892   if (HasInternalLabelReference)
1893     return false;
1894 
1895   // If there's only one jump table, and one indirect jump, and no other
1896   // references, then we should be able to derive the jump table even if we
1897   // fail to match the pattern.
1898   if (HasUnknownControlFlow && NumIndirectJumps == 1 &&
1899       JumpTables.size() == 1 && LastIndirectJump) {
1900     BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId);
1901     HasUnknownControlFlow = false;
1902 
1903     LastIndirectJumpBB->updateJumpTableSuccessors();
1904   }
1905 
1906   if (HasFixedIndirectBranch)
1907     return false;
1908 
1909   if (HasUnknownControlFlow && !BC.HasRelocations)
1910     return false;
1911 
1912   return true;
1913 }
1914 
1915 void BinaryFunction::recomputeLandingPads() {
1916   updateBBIndices(0);
1917 
1918   for (BinaryBasicBlock *BB : BasicBlocks) {
1919     BB->LandingPads.clear();
1920     BB->Throwers.clear();
1921   }
1922 
1923   for (BinaryBasicBlock *BB : BasicBlocks) {
1924     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
1925     for (MCInst &Instr : *BB) {
1926       if (!BC.MIB->isInvoke(Instr))
1927         continue;
1928 
1929       const Optional<MCPlus::MCLandingPad> EHInfo = BC.MIB->getEHInfo(Instr);
1930       if (!EHInfo || !EHInfo->first)
1931         continue;
1932 
1933       BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
1934       if (!BBLandingPads.count(LPBlock)) {
1935         BBLandingPads.insert(LPBlock);
1936         BB->LandingPads.emplace_back(LPBlock);
1937         LPBlock->Throwers.emplace_back(BB);
1938       }
1939     }
1940   }
1941 }
1942 
1943 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
1944   auto &MIB = BC.MIB;
1945 
1946   if (!isSimple()) {
1947     assert(!BC.HasRelocations &&
1948            "cannot process file with non-simple function in relocs mode");
1949     return false;
1950   }
1951 
1952   if (CurrentState != State::Disassembled)
1953     return false;
1954 
1955   assert(BasicBlocks.empty() && "basic block list should be empty");
1956   assert((Labels.find(0) != Labels.end()) &&
1957          "first instruction should always have a label");
1958 
1959   // Create basic blocks in the original layout order:
1960   //
1961   //  * Every instruction with associated label marks
1962   //    the beginning of a basic block.
1963   //  * Conditional instruction marks the end of a basic block,
1964   //    except when the following instruction is an
1965   //    unconditional branch, and the unconditional branch is not
1966   //    a destination of another branch. In the latter case, the
1967   //    basic block will consist of a single unconditional branch
1968   //    (missed "double-jump" optimization).
1969   //
1970   // Created basic blocks are sorted in layout order since they are
1971   // created in the same order as instructions, and instructions are
1972   // sorted by offsets.
1973   BinaryBasicBlock *InsertBB = nullptr;
1974   BinaryBasicBlock *PrevBB = nullptr;
1975   bool IsLastInstrNop = false;
1976   // Offset of the last non-nop instruction.
1977   uint64_t LastInstrOffset = 0;
1978 
1979   auto addCFIPlaceholders = [this](uint64_t CFIOffset,
1980                                    BinaryBasicBlock *InsertBB) {
1981     for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
1982               FE = OffsetToCFI.upper_bound(CFIOffset);
1983          FI != FE; ++FI) {
1984       addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
1985     }
1986   };
1987 
1988   // For profiling purposes we need to save the offset of the last instruction
1989   // in the basic block.
1990   // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
1991   //       older profiles ignored nops.
1992   auto updateOffset = [&](uint64_t Offset) {
1993     assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
1994     MCInst *LastNonNop = nullptr;
1995     for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
1996                                             E = PrevBB->rend();
1997          RII != E; ++RII) {
1998       if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
1999         LastNonNop = &*RII;
2000         break;
2001       }
2002     }
2003     if (LastNonNop && !MIB->getOffset(*LastNonNop))
2004       MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset), AllocatorId);
2005   };
2006 
2007   for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
2008     const uint32_t Offset = I->first;
2009     MCInst &Instr = I->second;
2010 
2011     auto LI = Labels.find(Offset);
2012     if (LI != Labels.end()) {
2013       // Always create new BB at branch destination.
2014       PrevBB = InsertBB ? InsertBB : PrevBB;
2015       InsertBB = addBasicBlock(LI->first, LI->second,
2016                                opts::PreserveBlocksAlignment && IsLastInstrNop);
2017       if (PrevBB)
2018         updateOffset(LastInstrOffset);
2019     }
2020 
2021     const uint64_t InstrInputAddr = I->first + Address;
2022     bool IsSDTMarker =
2023         MIB->isNoop(Instr) && BC.SDTMarkers.count(InstrInputAddr);
2024     bool IsLKMarker = BC.LKMarkers.count(InstrInputAddr);
2025     // Mark all nops with Offset for profile tracking purposes.
2026     if (MIB->isNoop(Instr) || IsLKMarker) {
2027       if (!MIB->getOffset(Instr))
2028         MIB->setOffset(Instr, static_cast<uint32_t>(Offset), AllocatorId);
2029       if (IsSDTMarker || IsLKMarker)
2030         HasSDTMarker = true;
2031       else
2032         // Annotate ordinary nops, so we can safely delete them if required.
2033         MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
2034     }
2035 
2036     if (!InsertBB) {
2037       // It must be a fallthrough or unreachable code. Create a new block unless
2038       // we see an unconditional branch following a conditional one. The latter
2039       // should not be a conditional tail call.
2040       assert(PrevBB && "no previous basic block for a fall through");
2041       MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
2042       assert(PrevInstr && "no previous instruction for a fall through");
2043       if (MIB->isUnconditionalBranch(Instr) &&
2044           !MIB->isUnconditionalBranch(*PrevInstr) &&
2045           !MIB->getConditionalTailCall(*PrevInstr) &&
2046           !MIB->isReturn(*PrevInstr)) {
2047         // Temporarily restore inserter basic block.
2048         InsertBB = PrevBB;
2049       } else {
2050         MCSymbol *Label;
2051         {
2052           auto L = BC.scopeLock();
2053           Label = BC.Ctx->createNamedTempSymbol("FT");
2054         }
2055         InsertBB = addBasicBlock(
2056             Offset, Label, opts::PreserveBlocksAlignment && IsLastInstrNop);
2057         updateOffset(LastInstrOffset);
2058       }
2059     }
2060     if (Offset == 0) {
2061       // Add associated CFI pseudos in the first offset (0)
2062       addCFIPlaceholders(0, InsertBB);
2063     }
2064 
2065     const bool IsBlockEnd = MIB->isTerminator(Instr);
2066     IsLastInstrNop = MIB->isNoop(Instr);
2067     if (!IsLastInstrNop)
2068       LastInstrOffset = Offset;
2069     InsertBB->addInstruction(std::move(Instr));
2070 
2071     // Add associated CFI instrs. We always add the CFI instruction that is
2072     // located immediately after this instruction, since the next CFI
2073     // instruction reflects the change in state caused by this instruction.
2074     auto NextInstr = std::next(I);
2075     uint64_t CFIOffset;
2076     if (NextInstr != E)
2077       CFIOffset = NextInstr->first;
2078     else
2079       CFIOffset = getSize();
2080 
2081     // Note: this potentially invalidates instruction pointers/iterators.
2082     addCFIPlaceholders(CFIOffset, InsertBB);
2083 
2084     if (IsBlockEnd) {
2085       PrevBB = InsertBB;
2086       InsertBB = nullptr;
2087     }
2088   }
2089 
2090   if (BasicBlocks.empty()) {
2091     setSimple(false);
2092     return false;
2093   }
2094 
2095   // Intermediate dump.
2096   LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2097 
2098   // TODO: handle properly calls to no-return functions,
2099   // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2100   // blocks.
2101 
2102   for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2103     LLVM_DEBUG(dbgs() << "registering branch [0x"
2104                       << Twine::utohexstr(Branch.first) << "] -> [0x"
2105                       << Twine::utohexstr(Branch.second) << "]\n");
2106     BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2107     BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2108     if (!FromBB || !ToBB) {
2109       if (!FromBB)
2110         errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2111       if (!ToBB)
2112         errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2113       BC.exitWithBugReport("disassembly failed - inconsistent branch found.",
2114                            *this);
2115     }
2116 
2117     FromBB->addSuccessor(ToBB);
2118   }
2119 
2120   // Add fall-through branches.
2121   PrevBB = nullptr;
2122   bool IsPrevFT = false; // Is previous block a fall-through.
2123   for (BinaryBasicBlock *BB : BasicBlocks) {
2124     if (IsPrevFT)
2125       PrevBB->addSuccessor(BB);
2126 
2127     if (BB->empty()) {
2128       IsPrevFT = true;
2129       PrevBB = BB;
2130       continue;
2131     }
2132 
2133     MCInst *LastInstr = BB->getLastNonPseudoInstr();
2134     assert(LastInstr &&
2135            "should have non-pseudo instruction in non-empty block");
2136 
2137     if (BB->succ_size() == 0) {
2138       // Since there's no existing successors, we know the last instruction is
2139       // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2140       // fall-through.
2141       //
2142       // Conditional tail call is a special case since we don't add a taken
2143       // branch successor for it.
2144       IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2145                  MIB->getConditionalTailCall(*LastInstr);
2146     } else if (BB->succ_size() == 1) {
2147       IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2148     } else {
2149       IsPrevFT = false;
2150     }
2151 
2152     PrevBB = BB;
2153   }
2154 
2155   // Assign landing pads and throwers info.
2156   recomputeLandingPads();
2157 
2158   // Assign CFI information to each BB entry.
2159   annotateCFIState();
2160 
2161   // Annotate invoke instructions with GNU_args_size data.
2162   propagateGnuArgsSizeInfo(AllocatorId);
2163 
2164   // Set the basic block layout to the original order and set end offsets.
2165   PrevBB = nullptr;
2166   for (BinaryBasicBlock *BB : BasicBlocks) {
2167     BasicBlocksLayout.emplace_back(BB);
2168     if (PrevBB)
2169       PrevBB->setEndOffset(BB->getOffset());
2170     PrevBB = BB;
2171   }
2172   PrevBB->setEndOffset(getSize());
2173 
2174   updateLayoutIndices();
2175 
2176   normalizeCFIState();
2177 
2178   // Clean-up memory taken by intermediate structures.
2179   //
2180   // NB: don't clear Labels list as we may need them if we mark the function
2181   //     as non-simple later in the process of discovering extra entry points.
2182   clearList(Instructions);
2183   clearList(OffsetToCFI);
2184   clearList(TakenBranches);
2185 
2186   // Update the state.
2187   CurrentState = State::CFG;
2188 
2189   // Make any necessary adjustments for indirect branches.
2190   if (!postProcessIndirectBranches(AllocatorId)) {
2191     if (opts::Verbosity) {
2192       errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2193              << *this << '\n';
2194     }
2195     // In relocation mode we want to keep processing the function but avoid
2196     // optimizing it.
2197     setSimple(false);
2198   }
2199 
2200   clearList(ExternallyReferencedOffsets);
2201   clearList(UnknownIndirectBranchOffsets);
2202 
2203   return true;
2204 }
2205 
2206 void BinaryFunction::postProcessCFG() {
2207   if (isSimple() && !BasicBlocks.empty()) {
2208     // Convert conditional tail call branches to conditional branches that jump
2209     // to a tail call.
2210     removeConditionalTailCalls();
2211 
2212     postProcessProfile();
2213 
2214     // Eliminate inconsistencies between branch instructions and CFG.
2215     postProcessBranches();
2216   }
2217 
2218   calculateMacroOpFusionStats();
2219 
2220   // The final cleanup of intermediate structures.
2221   clearList(IgnoredBranches);
2222 
2223   // Remove "Offset" annotations, unless we need an address-translation table
2224   // later. This has no cost, since annotations are allocated by a bumpptr
2225   // allocator and won't be released anyway until late in the pipeline.
2226   if (!requiresAddressTranslation() && !opts::Instrument) {
2227     for (BinaryBasicBlock *BB : layout())
2228       for (MCInst &Inst : *BB)
2229         BC.MIB->clearOffset(Inst);
2230   }
2231 
2232   assert((!isSimple() || validateCFG()) &&
2233          "invalid CFG detected after post-processing");
2234 }
2235 
2236 void BinaryFunction::calculateMacroOpFusionStats() {
2237   if (!getBinaryContext().isX86())
2238     return;
2239   for (BinaryBasicBlock *BB : layout()) {
2240     auto II = BB->getMacroOpFusionPair();
2241     if (II == BB->end())
2242       continue;
2243 
2244     // Check offset of the second instruction.
2245     // FIXME: arch-specific.
2246     const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0);
2247     if (!Offset || (getAddress() + Offset) % 64)
2248       continue;
2249 
2250     LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x"
2251                       << Twine::utohexstr(getAddress() + Offset)
2252                       << " in function " << *this << "; executed "
2253                       << BB->getKnownExecutionCount() << " times.\n");
2254     ++BC.MissedMacroFusionPairs;
2255     BC.MissedMacroFusionExecCount += BB->getKnownExecutionCount();
2256   }
2257 }
2258 
2259 void BinaryFunction::removeTagsFromProfile() {
2260   for (BinaryBasicBlock *BB : BasicBlocks) {
2261     if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2262       BB->ExecutionCount = 0;
2263     for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2264       if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2265           BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2266         continue;
2267       BI.Count = 0;
2268       BI.MispredictedCount = 0;
2269     }
2270   }
2271 }
2272 
2273 void BinaryFunction::removeConditionalTailCalls() {
2274   // Blocks to be appended at the end.
2275   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2276 
2277   for (auto BBI = begin(); BBI != end(); ++BBI) {
2278     BinaryBasicBlock &BB = *BBI;
2279     MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2280     if (!CTCInstr)
2281       continue;
2282 
2283     Optional<uint64_t> TargetAddressOrNone =
2284         BC.MIB->getConditionalTailCall(*CTCInstr);
2285     if (!TargetAddressOrNone)
2286       continue;
2287 
2288     // Gather all necessary information about CTC instruction before
2289     // annotations are destroyed.
2290     const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2291     uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2292     uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2293     if (hasValidProfile()) {
2294       CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2295           *CTCInstr, "CTCTakenCount");
2296       CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2297           *CTCInstr, "CTCMispredCount");
2298     }
2299 
2300     // Assert that the tail call does not throw.
2301     assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2302            "found tail call with associated landing pad");
2303 
2304     // Create a basic block with an unconditional tail call instruction using
2305     // the same destination.
2306     const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2307     assert(CTCTargetLabel && "symbol expected for conditional tail call");
2308     MCInst TailCallInstr;
2309     BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
2310     // Link new BBs to the original input offset of the BB where the CTC
2311     // is, so we can map samples recorded in new BBs back to the original BB
2312     // seem in the input binary (if using BAT)
2313     std::unique_ptr<BinaryBasicBlock> TailCallBB = createBasicBlock(
2314         BB.getInputOffset(), BC.Ctx->createNamedTempSymbol("TC"));
2315     TailCallBB->addInstruction(TailCallInstr);
2316     TailCallBB->setCFIState(CFIStateBeforeCTC);
2317 
2318     // Add CFG edge with profile info from BB to TailCallBB.
2319     BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2320 
2321     // Add execution count for the block.
2322     TailCallBB->setExecutionCount(CTCTakenCount);
2323 
2324     BC.MIB->convertTailCallToJmp(*CTCInstr);
2325 
2326     BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2327                                 BC.Ctx.get());
2328 
2329     // Add basic block to the list that will be added to the end.
2330     NewBlocks.emplace_back(std::move(TailCallBB));
2331 
2332     // Swap edges as the TailCallBB corresponds to the taken branch.
2333     BB.swapConditionalSuccessors();
2334 
2335     // This branch is no longer a conditional tail call.
2336     BC.MIB->unsetConditionalTailCall(*CTCInstr);
2337   }
2338 
2339   insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2340                     /* UpdateLayout */ true,
2341                     /* UpdateCFIState */ false);
2342 }
2343 
2344 uint64_t BinaryFunction::getFunctionScore() const {
2345   if (FunctionScore != -1)
2346     return FunctionScore;
2347 
2348   if (!isSimple() || !hasValidProfile()) {
2349     FunctionScore = 0;
2350     return FunctionScore;
2351   }
2352 
2353   uint64_t TotalScore = 0ULL;
2354   for (BinaryBasicBlock *BB : layout()) {
2355     uint64_t BBExecCount = BB->getExecutionCount();
2356     if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2357       continue;
2358     TotalScore += BBExecCount;
2359   }
2360   FunctionScore = TotalScore;
2361   return FunctionScore;
2362 }
2363 
2364 void BinaryFunction::annotateCFIState() {
2365   assert(CurrentState == State::Disassembled && "unexpected function state");
2366   assert(!BasicBlocks.empty() && "basic block list should not be empty");
2367 
2368   // This is an index of the last processed CFI in FDE CFI program.
2369   uint32_t State = 0;
2370 
2371   // This is an index of RememberState CFI reflecting effective state right
2372   // after execution of RestoreState CFI.
2373   //
2374   // It differs from State iff the CFI at (State-1)
2375   // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2376   //
2377   // This allows us to generate shorter replay sequences when producing new
2378   // CFI programs.
2379   uint32_t EffectiveState = 0;
2380 
2381   // For tracking RememberState/RestoreState sequences.
2382   std::stack<uint32_t> StateStack;
2383 
2384   for (BinaryBasicBlock *BB : BasicBlocks) {
2385     BB->setCFIState(EffectiveState);
2386 
2387     for (const MCInst &Instr : *BB) {
2388       const MCCFIInstruction *CFI = getCFIFor(Instr);
2389       if (!CFI)
2390         continue;
2391 
2392       ++State;
2393 
2394       switch (CFI->getOperation()) {
2395       case MCCFIInstruction::OpRememberState:
2396         StateStack.push(EffectiveState);
2397         EffectiveState = State;
2398         break;
2399       case MCCFIInstruction::OpRestoreState:
2400         assert(!StateStack.empty() && "corrupt CFI stack");
2401         EffectiveState = StateStack.top();
2402         StateStack.pop();
2403         break;
2404       case MCCFIInstruction::OpGnuArgsSize:
2405         // OpGnuArgsSize CFIs do not affect the CFI state.
2406         break;
2407       default:
2408         // Any other CFI updates the state.
2409         EffectiveState = State;
2410         break;
2411       }
2412     }
2413   }
2414 
2415   assert(StateStack.empty() && "corrupt CFI stack");
2416 }
2417 
2418 namespace {
2419 
2420 /// Our full interpretation of a DWARF CFI machine state at a given point
2421 struct CFISnapshot {
2422   /// CFA register number and offset defining the canonical frame at this
2423   /// point, or the number of a rule (CFI state) that computes it with a
2424   /// DWARF expression. This number will be negative if it refers to a CFI
2425   /// located in the CIE instead of the FDE.
2426   uint32_t CFAReg;
2427   int32_t CFAOffset;
2428   int32_t CFARule;
2429   /// Mapping of rules (CFI states) that define the location of each
2430   /// register. If absent, no rule defining the location of such register
2431   /// was ever read. This number will be negative if it refers to a CFI
2432   /// located in the CIE instead of the FDE.
2433   DenseMap<int32_t, int32_t> RegRule;
2434 
2435   /// References to CIE, FDE and expanded instructions after a restore state
2436   const BinaryFunction::CFIInstrMapType &CIE;
2437   const BinaryFunction::CFIInstrMapType &FDE;
2438   const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2439 
2440   /// Current FDE CFI number representing the state where the snapshot is at
2441   int32_t CurState;
2442 
2443   /// Used when we don't have information about which state/rule to apply
2444   /// to recover the location of either the CFA or a specific register
2445   constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2446 
2447 private:
2448   /// Update our snapshot by executing a single CFI
2449   void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2450     switch (Instr.getOperation()) {
2451     case MCCFIInstruction::OpSameValue:
2452     case MCCFIInstruction::OpRelOffset:
2453     case MCCFIInstruction::OpOffset:
2454     case MCCFIInstruction::OpRestore:
2455     case MCCFIInstruction::OpUndefined:
2456     case MCCFIInstruction::OpRegister:
2457       RegRule[Instr.getRegister()] = RuleNumber;
2458       break;
2459     case MCCFIInstruction::OpDefCfaRegister:
2460       CFAReg = Instr.getRegister();
2461       CFARule = UNKNOWN;
2462       break;
2463     case MCCFIInstruction::OpDefCfaOffset:
2464       CFAOffset = Instr.getOffset();
2465       CFARule = UNKNOWN;
2466       break;
2467     case MCCFIInstruction::OpDefCfa:
2468       CFAReg = Instr.getRegister();
2469       CFAOffset = Instr.getOffset();
2470       CFARule = UNKNOWN;
2471       break;
2472     case MCCFIInstruction::OpEscape: {
2473       Optional<uint8_t> Reg = readDWARFExpressionTargetReg(Instr.getValues());
2474       // Handle DW_CFA_def_cfa_expression
2475       if (!Reg) {
2476         CFARule = RuleNumber;
2477         break;
2478       }
2479       RegRule[*Reg] = RuleNumber;
2480       break;
2481     }
2482     case MCCFIInstruction::OpAdjustCfaOffset:
2483     case MCCFIInstruction::OpWindowSave:
2484     case MCCFIInstruction::OpNegateRAState:
2485     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2486       llvm_unreachable("unsupported CFI opcode");
2487       break;
2488     case MCCFIInstruction::OpRememberState:
2489     case MCCFIInstruction::OpRestoreState:
2490     case MCCFIInstruction::OpGnuArgsSize:
2491       // do not affect CFI state
2492       break;
2493     }
2494   }
2495 
2496 public:
2497   /// Advance state reading FDE CFI instructions up to State number
2498   void advanceTo(int32_t State) {
2499     for (int32_t I = CurState, E = State; I != E; ++I) {
2500       const MCCFIInstruction &Instr = FDE[I];
2501       if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2502         update(Instr, I);
2503         continue;
2504       }
2505       // If restore state instruction, fetch the equivalent CFIs that have
2506       // the same effect of this restore. This is used to ensure remember-
2507       // restore pairs are completely removed.
2508       auto Iter = FrameRestoreEquivalents.find(I);
2509       if (Iter == FrameRestoreEquivalents.end())
2510         continue;
2511       for (int32_t RuleNumber : Iter->second)
2512         update(FDE[RuleNumber], RuleNumber);
2513     }
2514 
2515     assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2516             CFARule != UNKNOWN) &&
2517            "CIE did not define default CFA?");
2518 
2519     CurState = State;
2520   }
2521 
2522   /// Interpret all CIE and FDE instructions up until CFI State number and
2523   /// populate this snapshot
2524   CFISnapshot(
2525       const BinaryFunction::CFIInstrMapType &CIE,
2526       const BinaryFunction::CFIInstrMapType &FDE,
2527       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2528       int32_t State)
2529       : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2530     CFAReg = UNKNOWN;
2531     CFAOffset = UNKNOWN;
2532     CFARule = UNKNOWN;
2533     CurState = 0;
2534 
2535     for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2536       const MCCFIInstruction &Instr = CIE[I];
2537       update(Instr, -I);
2538     }
2539 
2540     advanceTo(State);
2541   }
2542 };
2543 
2544 /// A CFI snapshot with the capability of checking if incremental additions to
2545 /// it are redundant. This is used to ensure we do not emit two CFI instructions
2546 /// back-to-back that are doing the same state change, or to avoid emitting a
2547 /// CFI at all when the state at that point would not be modified after that CFI
2548 struct CFISnapshotDiff : public CFISnapshot {
2549   bool RestoredCFAReg{false};
2550   bool RestoredCFAOffset{false};
2551   DenseMap<int32_t, bool> RestoredRegs;
2552 
2553   CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2554 
2555   CFISnapshotDiff(
2556       const BinaryFunction::CFIInstrMapType &CIE,
2557       const BinaryFunction::CFIInstrMapType &FDE,
2558       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2559       int32_t State)
2560       : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2561 
2562   /// Return true if applying Instr to this state is redundant and can be
2563   /// dismissed.
2564   bool isRedundant(const MCCFIInstruction &Instr) {
2565     switch (Instr.getOperation()) {
2566     case MCCFIInstruction::OpSameValue:
2567     case MCCFIInstruction::OpRelOffset:
2568     case MCCFIInstruction::OpOffset:
2569     case MCCFIInstruction::OpRestore:
2570     case MCCFIInstruction::OpUndefined:
2571     case MCCFIInstruction::OpRegister:
2572     case MCCFIInstruction::OpEscape: {
2573       uint32_t Reg;
2574       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2575         Reg = Instr.getRegister();
2576       } else {
2577         Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2578         // Handle DW_CFA_def_cfa_expression
2579         if (!R) {
2580           if (RestoredCFAReg && RestoredCFAOffset)
2581             return true;
2582           RestoredCFAReg = true;
2583           RestoredCFAOffset = true;
2584           return false;
2585         }
2586         Reg = *R;
2587       }
2588       if (RestoredRegs[Reg])
2589         return true;
2590       RestoredRegs[Reg] = true;
2591       const int32_t CurRegRule =
2592           RegRule.find(Reg) != RegRule.end() ? RegRule[Reg] : UNKNOWN;
2593       if (CurRegRule == UNKNOWN) {
2594         if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2595             Instr.getOperation() == MCCFIInstruction::OpSameValue)
2596           return true;
2597         return false;
2598       }
2599       const MCCFIInstruction &LastDef =
2600           CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2601       return LastDef == Instr;
2602     }
2603     case MCCFIInstruction::OpDefCfaRegister:
2604       if (RestoredCFAReg)
2605         return true;
2606       RestoredCFAReg = true;
2607       return CFAReg == Instr.getRegister();
2608     case MCCFIInstruction::OpDefCfaOffset:
2609       if (RestoredCFAOffset)
2610         return true;
2611       RestoredCFAOffset = true;
2612       return CFAOffset == Instr.getOffset();
2613     case MCCFIInstruction::OpDefCfa:
2614       if (RestoredCFAReg && RestoredCFAOffset)
2615         return true;
2616       RestoredCFAReg = true;
2617       RestoredCFAOffset = true;
2618       return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2619     case MCCFIInstruction::OpAdjustCfaOffset:
2620     case MCCFIInstruction::OpWindowSave:
2621     case MCCFIInstruction::OpNegateRAState:
2622     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2623       llvm_unreachable("unsupported CFI opcode");
2624       return false;
2625     case MCCFIInstruction::OpRememberState:
2626     case MCCFIInstruction::OpRestoreState:
2627     case MCCFIInstruction::OpGnuArgsSize:
2628       // do not affect CFI state
2629       return true;
2630     }
2631     return false;
2632   }
2633 };
2634 
2635 } // end anonymous namespace
2636 
2637 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2638                                      BinaryBasicBlock *InBB,
2639                                      BinaryBasicBlock::iterator InsertIt) {
2640   if (FromState == ToState)
2641     return true;
2642   assert(FromState < ToState && "can only replay CFIs forward");
2643 
2644   CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2645                           FrameRestoreEquivalents, FromState);
2646 
2647   std::vector<uint32_t> NewCFIs;
2648   for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2649     MCCFIInstruction *Instr = &FrameInstructions[CurState];
2650     if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2651       auto Iter = FrameRestoreEquivalents.find(CurState);
2652       assert(Iter != FrameRestoreEquivalents.end());
2653       NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2654       // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2655       // so we might as well fall-through here.
2656     }
2657     NewCFIs.push_back(CurState);
2658     continue;
2659   }
2660 
2661   // Replay instructions while avoiding duplicates
2662   for (auto I = NewCFIs.rbegin(), E = NewCFIs.rend(); I != E; ++I) {
2663     if (CFIDiff.isRedundant(FrameInstructions[*I]))
2664       continue;
2665     InsertIt = addCFIPseudo(InBB, InsertIt, *I);
2666   }
2667 
2668   return true;
2669 }
2670 
2671 SmallVector<int32_t, 4>
2672 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2673                                BinaryBasicBlock *InBB,
2674                                BinaryBasicBlock::iterator &InsertIt) {
2675   SmallVector<int32_t, 4> NewStates;
2676 
2677   CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2678                          FrameRestoreEquivalents, ToState);
2679   CFISnapshotDiff FromCFITable(ToCFITable);
2680   FromCFITable.advanceTo(FromState);
2681 
2682   auto undoStateDefCfa = [&]() {
2683     if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2684       FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2685           nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2686       if (FromCFITable.isRedundant(FrameInstructions.back())) {
2687         FrameInstructions.pop_back();
2688         return;
2689       }
2690       NewStates.push_back(FrameInstructions.size() - 1);
2691       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2692       ++InsertIt;
2693     } else if (ToCFITable.CFARule < 0) {
2694       if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2695         return;
2696       NewStates.push_back(FrameInstructions.size());
2697       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2698       ++InsertIt;
2699       FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2700     } else if (!FromCFITable.isRedundant(
2701                    FrameInstructions[ToCFITable.CFARule])) {
2702       NewStates.push_back(ToCFITable.CFARule);
2703       InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2704       ++InsertIt;
2705     }
2706   };
2707 
2708   auto undoState = [&](const MCCFIInstruction &Instr) {
2709     switch (Instr.getOperation()) {
2710     case MCCFIInstruction::OpRememberState:
2711     case MCCFIInstruction::OpRestoreState:
2712       break;
2713     case MCCFIInstruction::OpSameValue:
2714     case MCCFIInstruction::OpRelOffset:
2715     case MCCFIInstruction::OpOffset:
2716     case MCCFIInstruction::OpRestore:
2717     case MCCFIInstruction::OpUndefined:
2718     case MCCFIInstruction::OpEscape:
2719     case MCCFIInstruction::OpRegister: {
2720       uint32_t Reg;
2721       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2722         Reg = Instr.getRegister();
2723       } else {
2724         Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2725         // Handle DW_CFA_def_cfa_expression
2726         if (!R) {
2727           undoStateDefCfa();
2728           return;
2729         }
2730         Reg = *R;
2731       }
2732 
2733       if (ToCFITable.RegRule.find(Reg) == ToCFITable.RegRule.end()) {
2734         FrameInstructions.emplace_back(
2735             MCCFIInstruction::createRestore(nullptr, Reg));
2736         if (FromCFITable.isRedundant(FrameInstructions.back())) {
2737           FrameInstructions.pop_back();
2738           break;
2739         }
2740         NewStates.push_back(FrameInstructions.size() - 1);
2741         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2742         ++InsertIt;
2743         break;
2744       }
2745       const int32_t Rule = ToCFITable.RegRule[Reg];
2746       if (Rule < 0) {
2747         if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2748           break;
2749         NewStates.push_back(FrameInstructions.size());
2750         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2751         ++InsertIt;
2752         FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2753         break;
2754       }
2755       if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2756         break;
2757       NewStates.push_back(Rule);
2758       InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2759       ++InsertIt;
2760       break;
2761     }
2762     case MCCFIInstruction::OpDefCfaRegister:
2763     case MCCFIInstruction::OpDefCfaOffset:
2764     case MCCFIInstruction::OpDefCfa:
2765       undoStateDefCfa();
2766       break;
2767     case MCCFIInstruction::OpAdjustCfaOffset:
2768     case MCCFIInstruction::OpWindowSave:
2769     case MCCFIInstruction::OpNegateRAState:
2770     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2771       llvm_unreachable("unsupported CFI opcode");
2772       break;
2773     case MCCFIInstruction::OpGnuArgsSize:
2774       // do not affect CFI state
2775       break;
2776     }
2777   };
2778 
2779   // Undo all modifications from ToState to FromState
2780   for (int32_t I = ToState, E = FromState; I != E; ++I) {
2781     const MCCFIInstruction &Instr = FrameInstructions[I];
2782     if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2783       undoState(Instr);
2784       continue;
2785     }
2786     auto Iter = FrameRestoreEquivalents.find(I);
2787     if (Iter == FrameRestoreEquivalents.end())
2788       continue;
2789     for (int32_t State : Iter->second)
2790       undoState(FrameInstructions[State]);
2791   }
2792 
2793   return NewStates;
2794 }
2795 
2796 void BinaryFunction::normalizeCFIState() {
2797   // Reordering blocks with remember-restore state instructions can be specially
2798   // tricky. When rewriting the CFI, we omit remember-restore state instructions
2799   // entirely. For restore state, we build a map expanding each restore to the
2800   // equivalent unwindCFIState sequence required at that point to achieve the
2801   // same effect of the restore. All remember state are then just ignored.
2802   std::stack<int32_t> Stack;
2803   for (BinaryBasicBlock *CurBB : BasicBlocksLayout) {
2804     for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2805       if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2806         if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2807           Stack.push(II->getOperand(0).getImm());
2808           continue;
2809         }
2810         if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2811           const int32_t RememberState = Stack.top();
2812           const int32_t CurState = II->getOperand(0).getImm();
2813           FrameRestoreEquivalents[CurState] =
2814               unwindCFIState(CurState, RememberState, CurBB, II);
2815           Stack.pop();
2816         }
2817       }
2818     }
2819   }
2820 }
2821 
2822 bool BinaryFunction::finalizeCFIState() {
2823   LLVM_DEBUG(
2824       dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2825   LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2826                     << ": ");
2827 
2828   int32_t State = 0;
2829   bool SeenCold = false;
2830   const char *Sep = "";
2831   (void)Sep;
2832   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
2833     const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2834 
2835     // Hot-cold border: check if this is the first BB to be allocated in a cold
2836     // region (with a different FDE). If yes, we need to reset the CFI state.
2837     if (!SeenCold && BB->isCold()) {
2838       State = 0;
2839       SeenCold = true;
2840     }
2841 
2842     // We need to recover the correct state if it doesn't match expected
2843     // state at BB entry point.
2844     if (BB->getCFIState() < State) {
2845       // In this case, State is currently higher than what this BB expect it
2846       // to be. To solve this, we need to insert CFI instructions to undo
2847       // the effect of all CFI from BB's state to current State.
2848       auto InsertIt = BB->begin();
2849       unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2850     } else if (BB->getCFIState() > State) {
2851       // If BB's CFI state is greater than State, it means we are behind in the
2852       // state. Just emit all instructions to reach this state at the
2853       // beginning of this BB. If this sequence of instructions involve
2854       // remember state or restore state, bail out.
2855       if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2856         return false;
2857     }
2858 
2859     State = CFIStateAtExit;
2860     LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2861   }
2862   LLVM_DEBUG(dbgs() << "\n");
2863 
2864   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
2865     for (auto II = BB->begin(); II != BB->end();) {
2866       const MCCFIInstruction *CFI = getCFIFor(*II);
2867       if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2868                   CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2869         II = BB->eraseInstruction(II);
2870       } else {
2871         ++II;
2872       }
2873     }
2874   }
2875 
2876   return true;
2877 }
2878 
2879 bool BinaryFunction::requiresAddressTranslation() const {
2880   return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2881 }
2882 
2883 uint64_t BinaryFunction::getInstructionCount() const {
2884   uint64_t Count = 0;
2885   for (BinaryBasicBlock *const &Block : BasicBlocksLayout)
2886     Count += Block->getNumNonPseudos();
2887   return Count;
2888 }
2889 
2890 bool BinaryFunction::hasLayoutChanged() const { return ModifiedLayout; }
2891 
2892 uint64_t BinaryFunction::getEditDistance() const {
2893   return ComputeEditDistance<BinaryBasicBlock *>(BasicBlocksPreviousLayout,
2894                                                  BasicBlocksLayout);
2895 }
2896 
2897 void BinaryFunction::clearDisasmState() {
2898   clearList(Instructions);
2899   clearList(IgnoredBranches);
2900   clearList(TakenBranches);
2901   clearList(InterproceduralReferences);
2902 
2903   if (BC.HasRelocations) {
2904     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
2905       BC.UndefinedSymbols.insert(LI.second);
2906     if (FunctionEndLabel)
2907       BC.UndefinedSymbols.insert(FunctionEndLabel);
2908   }
2909 }
2910 
2911 void BinaryFunction::setTrapOnEntry() {
2912   clearDisasmState();
2913 
2914   auto addTrapAtOffset = [&](uint64_t Offset) {
2915     MCInst TrapInstr;
2916     BC.MIB->createTrap(TrapInstr);
2917     addInstruction(Offset, std::move(TrapInstr));
2918   };
2919 
2920   addTrapAtOffset(0);
2921   for (const std::pair<const uint32_t, MCSymbol *> &KV : getLabels())
2922     if (getSecondaryEntryPointSymbol(KV.second))
2923       addTrapAtOffset(KV.first);
2924 
2925   TrapsOnEntry = true;
2926 }
2927 
2928 void BinaryFunction::setIgnored() {
2929   if (opts::processAllFunctions()) {
2930     // We can accept ignored functions before they've been disassembled.
2931     // In that case, they would still get disassembled and emited, but not
2932     // optimized.
2933     assert(CurrentState == State::Empty &&
2934            "cannot ignore non-empty functions in current mode");
2935     IsIgnored = true;
2936     return;
2937   }
2938 
2939   clearDisasmState();
2940 
2941   // Clear CFG state too.
2942   if (hasCFG()) {
2943     releaseCFG();
2944 
2945     for (BinaryBasicBlock *BB : BasicBlocks)
2946       delete BB;
2947     clearList(BasicBlocks);
2948 
2949     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
2950       delete BB;
2951     clearList(DeletedBasicBlocks);
2952 
2953     clearList(BasicBlocksLayout);
2954     clearList(BasicBlocksPreviousLayout);
2955   }
2956 
2957   CurrentState = State::Empty;
2958 
2959   IsIgnored = true;
2960   IsSimple = false;
2961   LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
2962 }
2963 
2964 void BinaryFunction::duplicateConstantIslands() {
2965   assert(Islands && "function expected to have constant islands");
2966 
2967   for (BinaryBasicBlock *BB : layout()) {
2968     if (!BB->isCold())
2969       continue;
2970 
2971     for (MCInst &Inst : *BB) {
2972       int OpNum = 0;
2973       for (MCOperand &Operand : Inst) {
2974         if (!Operand.isExpr()) {
2975           ++OpNum;
2976           continue;
2977         }
2978         const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
2979         // Check if this is an island symbol
2980         if (!Islands->Symbols.count(Symbol) &&
2981             !Islands->ProxySymbols.count(Symbol))
2982           continue;
2983 
2984         // Create cold symbol, if missing
2985         auto ISym = Islands->ColdSymbols.find(Symbol);
2986         MCSymbol *ColdSymbol;
2987         if (ISym != Islands->ColdSymbols.end()) {
2988           ColdSymbol = ISym->second;
2989         } else {
2990           ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
2991           Islands->ColdSymbols[Symbol] = ColdSymbol;
2992           // Check if this is a proxy island symbol and update owner proxy map
2993           if (Islands->ProxySymbols.count(Symbol)) {
2994             BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
2995             auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
2996             Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
2997           }
2998         }
2999 
3000         // Update instruction reference
3001         Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
3002             Inst,
3003             MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
3004                                     *BC.Ctx),
3005             *BC.Ctx, 0));
3006         ++OpNum;
3007       }
3008     }
3009   }
3010 }
3011 
3012 namespace {
3013 
3014 #ifndef MAX_PATH
3015 #define MAX_PATH 255
3016 #endif
3017 
3018 std::string constructFilename(std::string Filename, std::string Annotation,
3019                               std::string Suffix) {
3020   std::replace(Filename.begin(), Filename.end(), '/', '-');
3021   if (!Annotation.empty())
3022     Annotation.insert(0, "-");
3023   if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
3024     assert(Suffix.size() + Annotation.size() <= MAX_PATH);
3025     if (opts::Verbosity >= 1) {
3026       errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix
3027              << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n";
3028     }
3029     Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
3030   }
3031   Filename += Annotation;
3032   Filename += Suffix;
3033   return Filename;
3034 }
3035 
3036 std::string formatEscapes(const std::string &Str) {
3037   std::string Result;
3038   for (unsigned I = 0; I < Str.size(); ++I) {
3039     char C = Str[I];
3040     switch (C) {
3041     case '\n':
3042       Result += "&#13;";
3043       break;
3044     case '"':
3045       break;
3046     default:
3047       Result += C;
3048       break;
3049     }
3050   }
3051   return Result;
3052 }
3053 
3054 } // namespace
3055 
3056 void BinaryFunction::dumpGraph(raw_ostream &OS) const {
3057   OS << "strict digraph \"" << getPrintName() << "\" {\n";
3058   uint64_t Offset = Address;
3059   for (BinaryBasicBlock *BB : BasicBlocks) {
3060     auto LayoutPos =
3061         std::find(BasicBlocksLayout.begin(), BasicBlocksLayout.end(), BB);
3062     unsigned Layout = LayoutPos - BasicBlocksLayout.begin();
3063     const char *ColdStr = BB->isCold() ? " (cold)" : "";
3064     OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u:CFI:%u)\"]\n",
3065                  BB->getName().data(), BB->getName().data(), ColdStr,
3066                  (BB->ExecutionCount != BinaryBasicBlock::COUNT_NO_PROFILE
3067                       ? BB->ExecutionCount
3068                       : 0),
3069                  BB->getOffset(), getIndex(BB), Layout, BB->getCFIState());
3070     OS << format("\"%s\" [shape=box]\n", BB->getName().data());
3071     if (opts::DotToolTipCode) {
3072       std::string Str;
3073       raw_string_ostream CS(Str);
3074       Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this);
3075       const std::string Code = formatEscapes(CS.str());
3076       OS << format("\"%s\" [tooltip=\"%s\"]\n", BB->getName().data(),
3077                    Code.c_str());
3078     }
3079 
3080     // analyzeBranch is just used to get the names of the branch
3081     // opcodes.
3082     const MCSymbol *TBB = nullptr;
3083     const MCSymbol *FBB = nullptr;
3084     MCInst *CondBranch = nullptr;
3085     MCInst *UncondBranch = nullptr;
3086     const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3087 
3088     const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3089     const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3090 
3091     auto BI = BB->branch_info_begin();
3092     for (BinaryBasicBlock *Succ : BB->successors()) {
3093       std::string Branch;
3094       if (Success) {
3095         if (Succ == BB->getConditionalSuccessor(true)) {
3096           Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3097                                     CondBranch->getOpcode()))
3098                               : "TB";
3099         } else if (Succ == BB->getConditionalSuccessor(false)) {
3100           Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3101                                       UncondBranch->getOpcode()))
3102                                 : "FB";
3103         } else {
3104           Branch = "FT";
3105         }
3106       }
3107       if (IsJumpTable)
3108         Branch = "JT";
3109       OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
3110                    Succ->getName().data(), Branch.c_str());
3111 
3112       if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3113           BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3114         OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3115       } else if (ExecutionCount != COUNT_NO_PROFILE &&
3116                  BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3117         OS << "\\n(IC:" << BI->Count << ")";
3118       }
3119       OS << "\"]\n";
3120 
3121       ++BI;
3122     }
3123     for (BinaryBasicBlock *LP : BB->landing_pads()) {
3124       OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3125                    BB->getName().data(), LP->getName().data());
3126     }
3127   }
3128   OS << "}\n";
3129 }
3130 
3131 void BinaryFunction::viewGraph() const {
3132   SmallString<MAX_PATH> Filename;
3133   if (std::error_code EC =
3134           sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
3135     errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3136            << " bolt-cfg-XXXXX.dot temporary file.\n";
3137     return;
3138   }
3139   dumpGraphToFile(std::string(Filename));
3140   if (DisplayGraph(Filename))
3141     errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n";
3142   if (std::error_code EC = sys::fs::remove(Filename)) {
3143     errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3144            << Filename << "\n";
3145   }
3146 }
3147 
3148 void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3149   std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3150   outs() << "BOLT-DEBUG: Dumping CFG to " << Filename << "\n";
3151   dumpGraphToFile(Filename);
3152 }
3153 
3154 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3155   std::error_code EC;
3156   raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3157   if (EC) {
3158     if (opts::Verbosity >= 1) {
3159       errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3160              << Filename << " for output.\n";
3161     }
3162     return;
3163   }
3164   dumpGraph(of);
3165 }
3166 
3167 bool BinaryFunction::validateCFG() const {
3168   bool Valid = true;
3169   for (BinaryBasicBlock *BB : BasicBlocks)
3170     Valid &= BB->validateSuccessorInvariants();
3171 
3172   if (!Valid)
3173     return Valid;
3174 
3175   // Make sure all blocks in CFG are valid.
3176   auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3177     if (!BB->isValid()) {
3178       errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3179              << " detected in:\n";
3180       this->dump();
3181       return false;
3182     }
3183     return true;
3184   };
3185   for (const BinaryBasicBlock *BB : BasicBlocks) {
3186     if (!validateBlock(BB, "block"))
3187       return false;
3188     for (const BinaryBasicBlock *PredBB : BB->predecessors())
3189       if (!validateBlock(PredBB, "predecessor"))
3190         return false;
3191     for (const BinaryBasicBlock *SuccBB : BB->successors())
3192       if (!validateBlock(SuccBB, "successor"))
3193         return false;
3194     for (const BinaryBasicBlock *LP : BB->landing_pads())
3195       if (!validateBlock(LP, "landing pad"))
3196         return false;
3197     for (const BinaryBasicBlock *Thrower : BB->throwers())
3198       if (!validateBlock(Thrower, "thrower"))
3199         return false;
3200   }
3201 
3202   for (const BinaryBasicBlock *BB : BasicBlocks) {
3203     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3204     for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3205       if (BBLandingPads.count(LP)) {
3206         errs() << "BOLT-ERROR: duplicate landing pad detected in"
3207                << BB->getName() << " in function " << *this << '\n';
3208         return false;
3209       }
3210       BBLandingPads.insert(LP);
3211     }
3212 
3213     std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3214     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3215       if (BBThrowers.count(Thrower)) {
3216         errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3217                << " in function " << *this << '\n';
3218         return false;
3219       }
3220       BBThrowers.insert(Thrower);
3221     }
3222 
3223     for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3224       if (std::find(LPBlock->throw_begin(), LPBlock->throw_end(), BB) ==
3225           LPBlock->throw_end()) {
3226         errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3227                << ": " << BB->getName() << " is in LandingPads but not in "
3228                << LPBlock->getName() << " Throwers\n";
3229         return false;
3230       }
3231     }
3232     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3233       if (std::find(Thrower->lp_begin(), Thrower->lp_end(), BB) ==
3234           Thrower->lp_end()) {
3235         errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3236                << ": " << BB->getName() << " is in Throwers list but not in "
3237                << Thrower->getName() << " LandingPads\n";
3238         return false;
3239       }
3240     }
3241   }
3242 
3243   return Valid;
3244 }
3245 
3246 void BinaryFunction::fixBranches() {
3247   auto &MIB = BC.MIB;
3248   MCContext *Ctx = BC.Ctx.get();
3249 
3250   for (unsigned I = 0, E = BasicBlocksLayout.size(); I != E; ++I) {
3251     BinaryBasicBlock *BB = BasicBlocksLayout[I];
3252     const MCSymbol *TBB = nullptr;
3253     const MCSymbol *FBB = nullptr;
3254     MCInst *CondBranch = nullptr;
3255     MCInst *UncondBranch = nullptr;
3256     if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3257       continue;
3258 
3259     // We will create unconditional branch with correct destination if needed.
3260     if (UncondBranch)
3261       BB->eraseInstruction(BB->findInstruction(UncondBranch));
3262 
3263     // Basic block that follows the current one in the final layout.
3264     const BinaryBasicBlock *NextBB = nullptr;
3265     if (I + 1 != E && BB->isCold() == BasicBlocksLayout[I + 1]->isCold())
3266       NextBB = BasicBlocksLayout[I + 1];
3267 
3268     if (BB->succ_size() == 1) {
3269       // __builtin_unreachable() could create a conditional branch that
3270       // falls-through into the next function - hence the block will have only
3271       // one valid successor. Since behaviour is undefined - we replace
3272       // the conditional branch with an unconditional if required.
3273       if (CondBranch)
3274         BB->eraseInstruction(BB->findInstruction(CondBranch));
3275       if (BB->getSuccessor() == NextBB)
3276         continue;
3277       BB->addBranchInstruction(BB->getSuccessor());
3278     } else if (BB->succ_size() == 2) {
3279       assert(CondBranch && "conditional branch expected");
3280       const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3281       const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3282       // Check whether we support reversing this branch direction
3283       const bool IsSupported =
3284           !MIB->isUnsupportedBranch(CondBranch->getOpcode());
3285       if (NextBB && NextBB == TSuccessor && IsSupported) {
3286         std::swap(TSuccessor, FSuccessor);
3287         {
3288           auto L = BC.scopeLock();
3289           MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3290         }
3291         BB->swapConditionalSuccessors();
3292       } else {
3293         auto L = BC.scopeLock();
3294         MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3295       }
3296       if (TSuccessor == FSuccessor)
3297         BB->removeDuplicateConditionalSuccessor(CondBranch);
3298       if (!NextBB ||
3299           ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) {
3300         // If one of the branches is guaranteed to be "long" while the other
3301         // could be "short", then prioritize short for "taken". This will
3302         // generate a sequence 1 byte shorter on x86.
3303         if (IsSupported && BC.isX86() &&
3304             TSuccessor->isCold() != FSuccessor->isCold() &&
3305             BB->isCold() != TSuccessor->isCold()) {
3306           std::swap(TSuccessor, FSuccessor);
3307           {
3308             auto L = BC.scopeLock();
3309             MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(),
3310                                         Ctx);
3311           }
3312           BB->swapConditionalSuccessors();
3313         }
3314         BB->addBranchInstruction(FSuccessor);
3315       }
3316     }
3317     // Cases where the number of successors is 0 (block ends with a
3318     // terminator) or more than 2 (switch table) don't require branch
3319     // instruction adjustments.
3320   }
3321   assert((!isSimple() || validateCFG()) &&
3322          "Invalid CFG detected after fixing branches");
3323 }
3324 
3325 void BinaryFunction::propagateGnuArgsSizeInfo(
3326     MCPlusBuilder::AllocatorIdTy AllocId) {
3327   assert(CurrentState == State::Disassembled && "unexpected function state");
3328 
3329   if (!hasEHRanges() || !usesGnuArgsSize())
3330     return;
3331 
3332   // The current value of DW_CFA_GNU_args_size affects all following
3333   // invoke instructions until the next CFI overrides it.
3334   // It is important to iterate basic blocks in the original order when
3335   // assigning the value.
3336   uint64_t CurrentGnuArgsSize = 0;
3337   for (BinaryBasicBlock *BB : BasicBlocks) {
3338     for (auto II = BB->begin(); II != BB->end();) {
3339       MCInst &Instr = *II;
3340       if (BC.MIB->isCFI(Instr)) {
3341         const MCCFIInstruction *CFI = getCFIFor(Instr);
3342         if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3343           CurrentGnuArgsSize = CFI->getOffset();
3344           // Delete DW_CFA_GNU_args_size instructions and only regenerate
3345           // during the final code emission. The information is embedded
3346           // inside call instructions.
3347           II = BB->erasePseudoInstruction(II);
3348           continue;
3349         }
3350       } else if (BC.MIB->isInvoke(Instr)) {
3351         // Add the value of GNU_args_size as an extra operand to invokes.
3352         BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId);
3353       }
3354       ++II;
3355     }
3356   }
3357 }
3358 
3359 void BinaryFunction::postProcessBranches() {
3360   if (!isSimple())
3361     return;
3362   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
3363     auto LastInstrRI = BB->getLastNonPseudo();
3364     if (BB->succ_size() == 1) {
3365       if (LastInstrRI != BB->rend() &&
3366           BC.MIB->isConditionalBranch(*LastInstrRI)) {
3367         // __builtin_unreachable() could create a conditional branch that
3368         // falls-through into the next function - hence the block will have only
3369         // one valid successor. Such behaviour is undefined and thus we remove
3370         // the conditional branch while leaving a valid successor.
3371         BB->eraseInstruction(std::prev(LastInstrRI.base()));
3372         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3373                           << BB->getName() << " in function " << *this << '\n');
3374       }
3375     } else if (BB->succ_size() == 0) {
3376       // Ignore unreachable basic blocks.
3377       if (BB->pred_size() == 0 || BB->isLandingPad())
3378         continue;
3379 
3380       // If it's the basic block that does not end up with a terminator - we
3381       // insert a return instruction unless it's a call instruction.
3382       if (LastInstrRI == BB->rend()) {
3383         LLVM_DEBUG(
3384             dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3385                    << BB->getName() << " in function " << *this << '\n');
3386         continue;
3387       }
3388       if (!BC.MIB->isTerminator(*LastInstrRI) &&
3389           !BC.MIB->isCall(*LastInstrRI)) {
3390         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3391                           << BB->getName() << " in function " << *this << '\n');
3392         MCInst ReturnInstr;
3393         BC.MIB->createReturn(ReturnInstr);
3394         BB->addInstruction(ReturnInstr);
3395       }
3396     }
3397   }
3398   assert(validateCFG() && "invalid CFG");
3399 }
3400 
3401 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3402   assert(Offset && "cannot add primary entry point");
3403   assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3404 
3405   const uint64_t EntryPointAddress = getAddress() + Offset;
3406   MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3407 
3408   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3409   if (EntrySymbol)
3410     return EntrySymbol;
3411 
3412   if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3413     EntrySymbol = EntryBD->getSymbol();
3414   } else {
3415     EntrySymbol = BC.getOrCreateGlobalSymbol(
3416         EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3417   }
3418   SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3419 
3420   BC.setSymbolToFunctionMap(EntrySymbol, this);
3421 
3422   return EntrySymbol;
3423 }
3424 
3425 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3426   assert(CurrentState == State::CFG &&
3427          "basic block can be added as an entry only in a function with CFG");
3428 
3429   if (&BB == BasicBlocks.front())
3430     return getSymbol();
3431 
3432   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3433   if (EntrySymbol)
3434     return EntrySymbol;
3435 
3436   EntrySymbol =
3437       BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3438 
3439   SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3440 
3441   BC.setSymbolToFunctionMap(EntrySymbol, this);
3442 
3443   return EntrySymbol;
3444 }
3445 
3446 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3447   if (EntryID == 0)
3448     return getSymbol();
3449 
3450   if (!isMultiEntry())
3451     return nullptr;
3452 
3453   uint64_t NumEntries = 0;
3454   if (hasCFG()) {
3455     for (BinaryBasicBlock *BB : BasicBlocks) {
3456       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3457       if (!EntrySymbol)
3458         continue;
3459       if (NumEntries == EntryID)
3460         return EntrySymbol;
3461       ++NumEntries;
3462     }
3463   } else {
3464     for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3465       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3466       if (!EntrySymbol)
3467         continue;
3468       if (NumEntries == EntryID)
3469         return EntrySymbol;
3470       ++NumEntries;
3471     }
3472   }
3473 
3474   return nullptr;
3475 }
3476 
3477 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3478   if (!isMultiEntry())
3479     return 0;
3480 
3481   for (const MCSymbol *FunctionSymbol : getSymbols())
3482     if (FunctionSymbol == Symbol)
3483       return 0;
3484 
3485   // Check all secondary entries available as either basic blocks or lables.
3486   uint64_t NumEntries = 0;
3487   for (const BinaryBasicBlock *BB : BasicBlocks) {
3488     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3489     if (!EntrySymbol)
3490       continue;
3491     if (EntrySymbol == Symbol)
3492       return NumEntries;
3493     ++NumEntries;
3494   }
3495   NumEntries = 0;
3496   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3497     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3498     if (!EntrySymbol)
3499       continue;
3500     if (EntrySymbol == Symbol)
3501       return NumEntries;
3502     ++NumEntries;
3503   }
3504 
3505   llvm_unreachable("symbol not found");
3506 }
3507 
3508 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3509   bool Status = Callback(0, getSymbol());
3510   if (!isMultiEntry())
3511     return Status;
3512 
3513   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3514     if (!Status)
3515       break;
3516 
3517     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3518     if (!EntrySymbol)
3519       continue;
3520 
3521     Status = Callback(KV.first, EntrySymbol);
3522   }
3523 
3524   return Status;
3525 }
3526 
3527 BinaryFunction::BasicBlockOrderType BinaryFunction::dfs() const {
3528   BasicBlockOrderType DFS;
3529   unsigned Index = 0;
3530   std::stack<BinaryBasicBlock *> Stack;
3531 
3532   // Push entry points to the stack in reverse order.
3533   //
3534   // NB: we rely on the original order of entries to match.
3535   for (auto BBI = layout_rbegin(); BBI != layout_rend(); ++BBI) {
3536     BinaryBasicBlock *BB = *BBI;
3537     if (isEntryPoint(*BB))
3538       Stack.push(BB);
3539     BB->setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3540   }
3541 
3542   while (!Stack.empty()) {
3543     BinaryBasicBlock *BB = Stack.top();
3544     Stack.pop();
3545 
3546     if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3547       continue;
3548 
3549     BB->setLayoutIndex(Index++);
3550     DFS.push_back(BB);
3551 
3552     for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3553       Stack.push(SuccBB);
3554     }
3555 
3556     const MCSymbol *TBB = nullptr;
3557     const MCSymbol *FBB = nullptr;
3558     MCInst *CondBranch = nullptr;
3559     MCInst *UncondBranch = nullptr;
3560     if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3561         BB->succ_size() == 2) {
3562       if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3563               *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3564         Stack.push(BB->getConditionalSuccessor(true));
3565         Stack.push(BB->getConditionalSuccessor(false));
3566       } else {
3567         Stack.push(BB->getConditionalSuccessor(false));
3568         Stack.push(BB->getConditionalSuccessor(true));
3569       }
3570     } else {
3571       for (BinaryBasicBlock *SuccBB : BB->successors()) {
3572         Stack.push(SuccBB);
3573       }
3574     }
3575   }
3576 
3577   return DFS;
3578 }
3579 
3580 size_t BinaryFunction::computeHash(bool UseDFS,
3581                                    OperandHashFuncTy OperandHashFunc) const {
3582   if (size() == 0)
3583     return 0;
3584 
3585   assert(hasCFG() && "function is expected to have CFG");
3586 
3587   const BasicBlockOrderType &Order = UseDFS ? dfs() : BasicBlocksLayout;
3588 
3589   // The hash is computed by creating a string of all instruction opcodes and
3590   // possibly their operands and then hashing that string with std::hash.
3591   std::string HashString;
3592   for (const BinaryBasicBlock *BB : Order) {
3593     for (const MCInst &Inst : *BB) {
3594       unsigned Opcode = Inst.getOpcode();
3595 
3596       if (BC.MIB->isPseudo(Inst))
3597         continue;
3598 
3599       // Ignore unconditional jumps since we check CFG consistency by processing
3600       // basic blocks in order and do not rely on branches to be in-sync with
3601       // CFG. Note that we still use condition code of conditional jumps.
3602       if (BC.MIB->isUnconditionalBranch(Inst))
3603         continue;
3604 
3605       if (Opcode == 0)
3606         HashString.push_back(0);
3607 
3608       while (Opcode) {
3609         uint8_t LSB = Opcode & 0xff;
3610         HashString.push_back(LSB);
3611         Opcode = Opcode >> 8;
3612       }
3613 
3614       for (const MCOperand &Op : MCPlus::primeOperands(Inst))
3615         HashString.append(OperandHashFunc(Op));
3616     }
3617   }
3618 
3619   return Hash = std::hash<std::string>{}(HashString);
3620 }
3621 
3622 void BinaryFunction::insertBasicBlocks(
3623     BinaryBasicBlock *Start,
3624     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3625     const bool UpdateLayout, const bool UpdateCFIState,
3626     const bool RecomputeLandingPads) {
3627   const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3628   const size_t NumNewBlocks = NewBBs.size();
3629 
3630   BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3631                      nullptr);
3632 
3633   int64_t I = StartIndex + 1;
3634   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3635     assert(!BasicBlocks[I]);
3636     BasicBlocks[I++] = BB.release();
3637   }
3638 
3639   if (RecomputeLandingPads)
3640     recomputeLandingPads();
3641   else
3642     updateBBIndices(0);
3643 
3644   if (UpdateLayout)
3645     updateLayout(Start, NumNewBlocks);
3646 
3647   if (UpdateCFIState)
3648     updateCFIState(Start, NumNewBlocks);
3649 }
3650 
3651 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3652     BinaryFunction::iterator StartBB,
3653     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3654     const bool UpdateLayout, const bool UpdateCFIState,
3655     const bool RecomputeLandingPads) {
3656   const unsigned StartIndex = getIndex(&*StartBB);
3657   const size_t NumNewBlocks = NewBBs.size();
3658 
3659   BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3660                      nullptr);
3661   auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3662 
3663   unsigned I = StartIndex + 1;
3664   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3665     assert(!BasicBlocks[I]);
3666     BasicBlocks[I++] = BB.release();
3667   }
3668 
3669   if (RecomputeLandingPads)
3670     recomputeLandingPads();
3671   else
3672     updateBBIndices(0);
3673 
3674   if (UpdateLayout)
3675     updateLayout(*std::prev(RetIter), NumNewBlocks);
3676 
3677   if (UpdateCFIState)
3678     updateCFIState(*std::prev(RetIter), NumNewBlocks);
3679 
3680   return RetIter;
3681 }
3682 
3683 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3684   for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3685     BasicBlocks[I]->Index = I;
3686 }
3687 
3688 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3689                                     const unsigned NumNewBlocks) {
3690   const int32_t CFIState = Start->getCFIStateAtExit();
3691   const unsigned StartIndex = getIndex(Start) + 1;
3692   for (unsigned I = 0; I < NumNewBlocks; ++I)
3693     BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3694 }
3695 
3696 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3697                                   const unsigned NumNewBlocks) {
3698   // If start not provided insert new blocks at the beginning
3699   if (!Start) {
3700     BasicBlocksLayout.insert(layout_begin(), BasicBlocks.begin(),
3701                              BasicBlocks.begin() + NumNewBlocks);
3702     updateLayoutIndices();
3703     return;
3704   }
3705 
3706   // Insert new blocks in the layout immediately after Start.
3707   auto Pos = std::find(layout_begin(), layout_end(), Start);
3708   assert(Pos != layout_end());
3709   BasicBlockListType::iterator Begin =
3710       std::next(BasicBlocks.begin(), getIndex(Start) + 1);
3711   BasicBlockListType::iterator End =
3712       std::next(BasicBlocks.begin(), getIndex(Start) + NumNewBlocks + 1);
3713   BasicBlocksLayout.insert(Pos + 1, Begin, End);
3714   updateLayoutIndices();
3715 }
3716 
3717 bool BinaryFunction::checkForAmbiguousJumpTables() {
3718   SmallSet<uint64_t, 4> JumpTables;
3719   for (BinaryBasicBlock *&BB : BasicBlocks) {
3720     for (MCInst &Inst : *BB) {
3721       if (!BC.MIB->isIndirectBranch(Inst))
3722         continue;
3723       uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3724       if (!JTAddress)
3725         continue;
3726       // This address can be inside another jump table, but we only consider
3727       // it ambiguous when the same start address is used, not the same JT
3728       // object.
3729       if (!JumpTables.count(JTAddress)) {
3730         JumpTables.insert(JTAddress);
3731         continue;
3732       }
3733       return true;
3734     }
3735   }
3736   return false;
3737 }
3738 
3739 void BinaryFunction::disambiguateJumpTables(
3740     MCPlusBuilder::AllocatorIdTy AllocId) {
3741   assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3742   SmallPtrSet<JumpTable *, 4> JumpTables;
3743   for (BinaryBasicBlock *&BB : BasicBlocks) {
3744     for (MCInst &Inst : *BB) {
3745       if (!BC.MIB->isIndirectBranch(Inst))
3746         continue;
3747       JumpTable *JT = getJumpTable(Inst);
3748       if (!JT)
3749         continue;
3750       auto Iter = JumpTables.find(JT);
3751       if (Iter == JumpTables.end()) {
3752         JumpTables.insert(JT);
3753         continue;
3754       }
3755       // This instruction is an indirect jump using a jump table, but it is
3756       // using the same jump table of another jump. Try all our tricks to
3757       // extract the jump table symbol and make it point to a new, duplicated JT
3758       MCPhysReg BaseReg1;
3759       uint64_t Scale;
3760       const MCSymbol *Target;
3761       // In case we match if our first matcher, first instruction is the one to
3762       // patch
3763       MCInst *JTLoadInst = &Inst;
3764       // Try a standard indirect jump matcher, scale 8
3765       std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3766           BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3767                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3768                               /*Offset=*/BC.MIB->matchSymbol(Target));
3769       if (!IndJmpMatcher->match(
3770               *BC.MRI, *BC.MIB,
3771               MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3772           BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3773         MCPhysReg BaseReg2;
3774         uint64_t Offset;
3775         // Standard JT matching failed. Trying now:
3776         //     movq  "jt.2397/1"(,%rax,8), %rax
3777         //     jmpq  *%rax
3778         std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3779             BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3780                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3781                               /*Offset=*/BC.MIB->matchSymbol(Target));
3782         MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3783         std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3784             BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3785         if (!IndJmpMatcher2->match(
3786                 *BC.MRI, *BC.MIB,
3787                 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3788             BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3789           // JT matching failed. Trying now:
3790           // PIC-style matcher, scale 4
3791           //    addq    %rdx, %rsi
3792           //    addq    %rdx, %rdi
3793           //    leaq    DATAat0x402450(%rip), %r11
3794           //    movslq  (%r11,%rdx,4), %rcx
3795           //    addq    %r11, %rcx
3796           //    jmpq    *%rcx # JUMPTABLE @0x402450
3797           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3798               BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3799                   BC.MIB->matchReg(BaseReg1),
3800                   BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3801                                     BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3802                                     BC.MIB->matchImm(Offset))));
3803           std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3804               BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3805           MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3806           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3807               BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3808                                                    BC.MIB->matchAnyOperand()));
3809           if (!PICIndJmpMatcher->match(
3810                   *BC.MRI, *BC.MIB,
3811                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3812               Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3813               !PICBaseAddrMatcher->match(
3814                   *BC.MRI, *BC.MIB,
3815                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3816             llvm_unreachable("Failed to extract jump table base");
3817             continue;
3818           }
3819           // Matched PIC, identify the instruction with the reference to the JT
3820           JTLoadInst = LEAMatcher->CurInst;
3821         } else {
3822           // Matched non-PIC
3823           JTLoadInst = LoadMatcher->CurInst;
3824         }
3825       }
3826 
3827       uint64_t NewJumpTableID = 0;
3828       const MCSymbol *NewJTLabel;
3829       std::tie(NewJumpTableID, NewJTLabel) =
3830           BC.duplicateJumpTable(*this, JT, Target);
3831       {
3832         auto L = BC.scopeLock();
3833         BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3834       }
3835       // We use a unique ID with the high bit set as address for this "injected"
3836       // jump table (not originally in the input binary).
3837       BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3838     }
3839   }
3840 }
3841 
3842 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3843                                              BinaryBasicBlock *OldDest,
3844                                              BinaryBasicBlock *NewDest) {
3845   MCInst *Instr = BB->getLastNonPseudoInstr();
3846   if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3847     return false;
3848   uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3849   assert(JTAddress && "Invalid jump table address");
3850   JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3851   assert(JT && "No jump table structure for this indirect branch");
3852   bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3853                                         NewDest->getLabel());
3854   (void)Patched;
3855   assert(Patched && "Invalid entry to be replaced in jump table");
3856   return true;
3857 }
3858 
3859 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3860                                             BinaryBasicBlock *To) {
3861   // Create intermediate BB
3862   MCSymbol *Tmp;
3863   {
3864     auto L = BC.scopeLock();
3865     Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3866   }
3867   // Link new BBs to the original input offset of the From BB, so we can map
3868   // samples recorded in new BBs back to the original BB seem in the input
3869   // binary (if using BAT)
3870   std::unique_ptr<BinaryBasicBlock> NewBB =
3871       createBasicBlock(From->getInputOffset(), Tmp);
3872   BinaryBasicBlock *NewBBPtr = NewBB.get();
3873 
3874   // Update "From" BB
3875   auto I = From->succ_begin();
3876   auto BI = From->branch_info_begin();
3877   for (; I != From->succ_end(); ++I) {
3878     if (*I == To)
3879       break;
3880     ++BI;
3881   }
3882   assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3883   uint64_t OrigCount = BI->Count;
3884   uint64_t OrigMispreds = BI->MispredictedCount;
3885   replaceJumpTableEntryIn(From, To, NewBBPtr);
3886   From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3887 
3888   NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3889   NewBB->setExecutionCount(OrigCount);
3890   NewBB->setIsCold(From->isCold());
3891 
3892   // Update CFI and BB layout with new intermediate BB
3893   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3894   NewBBs.emplace_back(std::move(NewBB));
3895   insertBasicBlocks(From, std::move(NewBBs), true, true,
3896                     /*RecomputeLandingPads=*/false);
3897   return NewBBPtr;
3898 }
3899 
3900 void BinaryFunction::deleteConservativeEdges() {
3901   // Our goal is to aggressively remove edges from the CFG that we believe are
3902   // wrong. This is used for instrumentation, where it is safe to remove
3903   // fallthrough edges because we won't reorder blocks.
3904   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3905     BinaryBasicBlock *BB = *I;
3906     if (BB->succ_size() != 1 || BB->size() == 0)
3907       continue;
3908 
3909     auto NextBB = std::next(I);
3910     MCInst *Last = BB->getLastNonPseudoInstr();
3911     // Fallthrough is a landing pad? Delete this edge (as long as we don't
3912     // have a direct jump to it)
3913     if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3914         *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3915       BB->removeAllSuccessors();
3916       continue;
3917     }
3918 
3919     // Look for suspicious calls at the end of BB where gcc may optimize it and
3920     // remove the jump to the epilogue when it knows the call won't return.
3921     if (!Last || !BC.MIB->isCall(*Last))
3922       continue;
3923 
3924     const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3925     if (!CalleeSymbol)
3926       continue;
3927 
3928     StringRef CalleeName = CalleeSymbol->getName();
3929     if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3930         CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3931         CalleeName != "abort@PLT")
3932       continue;
3933 
3934     BB->removeAllSuccessors();
3935   }
3936 }
3937 
3938 bool BinaryFunction::isDataMarker(const SymbolRef &Symbol,
3939                                   uint64_t SymbolSize) const {
3940   // For aarch64, the ABI defines mapping symbols so we identify data in the
3941   // code section (see IHI0056B). $d identifies a symbol starting data contents.
3942   if (BC.isAArch64() && Symbol.getType() &&
3943       cantFail(Symbol.getType()) == SymbolRef::ST_Unknown && SymbolSize == 0 &&
3944       Symbol.getName() &&
3945       (cantFail(Symbol.getName()) == "$d" ||
3946        cantFail(Symbol.getName()).startswith("$d.")))
3947     return true;
3948   return false;
3949 }
3950 
3951 bool BinaryFunction::isCodeMarker(const SymbolRef &Symbol,
3952                                   uint64_t SymbolSize) const {
3953   // For aarch64, the ABI defines mapping symbols so we identify data in the
3954   // code section (see IHI0056B). $x identifies a symbol starting code or the
3955   // end of a data chunk inside code.
3956   if (BC.isAArch64() && Symbol.getType() &&
3957       cantFail(Symbol.getType()) == SymbolRef::ST_Unknown && SymbolSize == 0 &&
3958       Symbol.getName() &&
3959       (cantFail(Symbol.getName()) == "$x" ||
3960        cantFail(Symbol.getName()).startswith("$x.")))
3961     return true;
3962   return false;
3963 }
3964 
3965 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3966                                           uint64_t SymbolSize) const {
3967   // If this symbol is in a different section from the one where the
3968   // function symbol is, don't consider it as valid.
3969   if (!getOriginSection()->containsAddress(
3970           cantFail(Symbol.getAddress(), "cannot get symbol address")))
3971     return false;
3972 
3973   // Some symbols are tolerated inside function bodies, others are not.
3974   // The real function boundaries may not be known at this point.
3975   if (isDataMarker(Symbol, SymbolSize) || isCodeMarker(Symbol, SymbolSize))
3976     return true;
3977 
3978   // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3979   // function.
3980   if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3981     return true;
3982 
3983   if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3984     return false;
3985 
3986   if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
3987     return false;
3988 
3989   return true;
3990 }
3991 
3992 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
3993   if (getKnownExecutionCount() == 0 || Count == 0)
3994     return;
3995 
3996   if (ExecutionCount < Count)
3997     Count = ExecutionCount;
3998 
3999   double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
4000   if (AdjustmentRatio < 0.0)
4001     AdjustmentRatio = 0.0;
4002 
4003   for (BinaryBasicBlock *&BB : layout())
4004     BB->adjustExecutionCount(AdjustmentRatio);
4005 
4006   ExecutionCount -= Count;
4007 }
4008 
4009 BinaryFunction::~BinaryFunction() {
4010   for (BinaryBasicBlock *BB : BasicBlocks)
4011     delete BB;
4012   for (BinaryBasicBlock *BB : DeletedBasicBlocks)
4013     delete BB;
4014 }
4015 
4016 void BinaryFunction::calculateLoopInfo() {
4017   // Discover loops.
4018   BinaryDominatorTree DomTree;
4019   DomTree.recalculate(*this);
4020   BLI.reset(new BinaryLoopInfo());
4021   BLI->analyze(DomTree);
4022 
4023   // Traverse discovered loops and add depth and profile information.
4024   std::stack<BinaryLoop *> St;
4025   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
4026     St.push(*I);
4027     ++BLI->OuterLoops;
4028   }
4029 
4030   while (!St.empty()) {
4031     BinaryLoop *L = St.top();
4032     St.pop();
4033     ++BLI->TotalLoops;
4034     BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
4035 
4036     // Add nested loops in the stack.
4037     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4038       St.push(*I);
4039 
4040     // Skip if no valid profile is found.
4041     if (!hasValidProfile()) {
4042       L->EntryCount = COUNT_NO_PROFILE;
4043       L->ExitCount = COUNT_NO_PROFILE;
4044       L->TotalBackEdgeCount = COUNT_NO_PROFILE;
4045       continue;
4046     }
4047 
4048     // Compute back edge count.
4049     SmallVector<BinaryBasicBlock *, 1> Latches;
4050     L->getLoopLatches(Latches);
4051 
4052     for (BinaryBasicBlock *Latch : Latches) {
4053       auto BI = Latch->branch_info_begin();
4054       for (BinaryBasicBlock *Succ : Latch->successors()) {
4055         if (Succ == L->getHeader()) {
4056           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4057                  "profile data not found");
4058           L->TotalBackEdgeCount += BI->Count;
4059         }
4060         ++BI;
4061       }
4062     }
4063 
4064     // Compute entry count.
4065     L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4066 
4067     // Compute exit count.
4068     SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4069     L->getExitEdges(ExitEdges);
4070     for (BinaryLoop::Edge &Exit : ExitEdges) {
4071       const BinaryBasicBlock *Exiting = Exit.first;
4072       const BinaryBasicBlock *ExitTarget = Exit.second;
4073       auto BI = Exiting->branch_info_begin();
4074       for (BinaryBasicBlock *Succ : Exiting->successors()) {
4075         if (Succ == ExitTarget) {
4076           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4077                  "profile data not found");
4078           L->ExitCount += BI->Count;
4079         }
4080         ++BI;
4081       }
4082     }
4083   }
4084 }
4085 
4086 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) {
4087   if (!isEmitted()) {
4088     assert(!isInjected() && "injected function should be emitted");
4089     setOutputAddress(getAddress());
4090     setOutputSize(getSize());
4091     return;
4092   }
4093 
4094   const uint64_t BaseAddress = getCodeSection()->getOutputAddress();
4095   ErrorOr<BinarySection &> ColdSection = getColdCodeSection();
4096   const uint64_t ColdBaseAddress =
4097       isSplit() ? ColdSection->getOutputAddress() : 0;
4098   if (BC.HasRelocations || isInjected()) {
4099     const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol());
4100     const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel());
4101     setOutputAddress(BaseAddress + StartOffset);
4102     setOutputSize(EndOffset - StartOffset);
4103     if (hasConstantIsland()) {
4104       const uint64_t DataOffset =
4105           Layout.getSymbolOffset(*getFunctionConstantIslandLabel());
4106       setOutputDataAddress(BaseAddress + DataOffset);
4107     }
4108     if (isSplit()) {
4109       const MCSymbol *ColdStartSymbol = getColdSymbol();
4110       assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4111              "split function should have defined cold symbol");
4112       const MCSymbol *ColdEndSymbol = getFunctionColdEndLabel();
4113       assert(ColdEndSymbol && ColdEndSymbol->isDefined() &&
4114              "split function should have defined cold end symbol");
4115       const uint64_t ColdStartOffset = Layout.getSymbolOffset(*ColdStartSymbol);
4116       const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol);
4117       cold().setAddress(ColdBaseAddress + ColdStartOffset);
4118       cold().setImageSize(ColdEndOffset - ColdStartOffset);
4119       if (hasConstantIsland()) {
4120         const uint64_t DataOffset =
4121             Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel());
4122         setOutputColdDataAddress(ColdBaseAddress + DataOffset);
4123       }
4124     }
4125   } else {
4126     setOutputAddress(getAddress());
4127     setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel()));
4128   }
4129 
4130   // Update basic block output ranges for the debug info, if we have
4131   // secondary entry points in the symbol table to update or if writing BAT.
4132   if (!opts::UpdateDebugSections && !isMultiEntry() &&
4133       !requiresAddressTranslation())
4134     return;
4135 
4136   // Output ranges should match the input if the body hasn't changed.
4137   if (!isSimple() && !BC.HasRelocations)
4138     return;
4139 
4140   // AArch64 may have functions that only contains a constant island (no code).
4141   if (layout_begin() == layout_end())
4142     return;
4143 
4144   BinaryBasicBlock *PrevBB = nullptr;
4145   for (auto BBI = layout_begin(), BBE = layout_end(); BBI != BBE; ++BBI) {
4146     BinaryBasicBlock *BB = *BBI;
4147     assert(BB->getLabel()->isDefined() && "symbol should be defined");
4148     const uint64_t BBBaseAddress = BB->isCold() ? ColdBaseAddress : BaseAddress;
4149     if (!BC.HasRelocations) {
4150       if (BB->isCold()) {
4151         assert(BBBaseAddress == cold().getAddress());
4152       } else {
4153         assert(BBBaseAddress == getOutputAddress());
4154       }
4155     }
4156     const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel());
4157     const uint64_t BBAddress = BBBaseAddress + BBOffset;
4158     BB->setOutputStartAddress(BBAddress);
4159 
4160     if (PrevBB) {
4161       uint64_t PrevBBEndAddress = BBAddress;
4162       if (BB->isCold() != PrevBB->isCold())
4163         PrevBBEndAddress = getOutputAddress() + getOutputSize();
4164       PrevBB->setOutputEndAddress(PrevBBEndAddress);
4165     }
4166     PrevBB = BB;
4167 
4168     BB->updateOutputValues(Layout);
4169   }
4170   PrevBB->setOutputEndAddress(PrevBB->isCold()
4171                                   ? cold().getAddress() + cold().getImageSize()
4172                                   : getOutputAddress() + getOutputSize());
4173 }
4174 
4175 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4176   DebugAddressRangesVector OutputRanges;
4177 
4178   if (isFolded())
4179     return OutputRanges;
4180 
4181   if (IsFragment)
4182     return OutputRanges;
4183 
4184   OutputRanges.emplace_back(getOutputAddress(),
4185                             getOutputAddress() + getOutputSize());
4186   if (isSplit()) {
4187     assert(isEmitted() && "split function should be emitted");
4188     OutputRanges.emplace_back(cold().getAddress(),
4189                               cold().getAddress() + cold().getImageSize());
4190   }
4191 
4192   if (isSimple())
4193     return OutputRanges;
4194 
4195   for (BinaryFunction *Frag : Fragments) {
4196     assert(!Frag->isSimple() &&
4197            "fragment of non-simple function should also be non-simple");
4198     OutputRanges.emplace_back(Frag->getOutputAddress(),
4199                               Frag->getOutputAddress() + Frag->getOutputSize());
4200   }
4201 
4202   return OutputRanges;
4203 }
4204 
4205 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4206   if (isFolded())
4207     return 0;
4208 
4209   // If the function hasn't changed return the same address.
4210   if (!isEmitted())
4211     return Address;
4212 
4213   if (Address < getAddress())
4214     return 0;
4215 
4216   // Check if the address is associated with an instruction that is tracked
4217   // by address translation.
4218   auto KV = InputOffsetToAddressMap.find(Address - getAddress());
4219   if (KV != InputOffsetToAddressMap.end())
4220     return KV->second;
4221 
4222   // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4223   //        intact. Instead we can use pseudo instructions and/or annotations.
4224   const uint64_t Offset = Address - getAddress();
4225   const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4226   if (!BB) {
4227     // Special case for address immediately past the end of the function.
4228     if (Offset == getSize())
4229       return getOutputAddress() + getOutputSize();
4230 
4231     return 0;
4232   }
4233 
4234   return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4235                   BB->getOutputAddressRange().second);
4236 }
4237 
4238 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges(
4239     const DWARFAddressRangesVector &InputRanges) const {
4240   DebugAddressRangesVector OutputRanges;
4241 
4242   if (isFolded())
4243     return OutputRanges;
4244 
4245   // If the function hasn't changed return the same ranges.
4246   if (!isEmitted()) {
4247     OutputRanges.resize(InputRanges.size());
4248     std::transform(InputRanges.begin(), InputRanges.end(), OutputRanges.begin(),
4249                    [](const DWARFAddressRange &Range) {
4250                      return DebugAddressRange(Range.LowPC, Range.HighPC);
4251                    });
4252     return OutputRanges;
4253   }
4254 
4255   // Even though we will merge ranges in a post-processing pass, we attempt to
4256   // merge them in a main processing loop as it improves the processing time.
4257   uint64_t PrevEndAddress = 0;
4258   for (const DWARFAddressRange &Range : InputRanges) {
4259     if (!containsAddress(Range.LowPC)) {
4260       LLVM_DEBUG(
4261           dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4262                  << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x"
4263                  << Twine::utohexstr(Range.HighPC) << "]\n");
4264       PrevEndAddress = 0;
4265       continue;
4266     }
4267     uint64_t InputOffset = Range.LowPC - getAddress();
4268     const uint64_t InputEndOffset =
4269         std::min(Range.HighPC - getAddress(), getSize());
4270 
4271     auto BBI = std::upper_bound(
4272         BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
4273         BasicBlockOffset(InputOffset, nullptr), CompareBasicBlockOffsets());
4274     --BBI;
4275     do {
4276       const BinaryBasicBlock *BB = BBI->second;
4277       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4278         LLVM_DEBUG(
4279             dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4280                    << *this << " : [0x" << Twine::utohexstr(Range.LowPC)
4281                    << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n");
4282         PrevEndAddress = 0;
4283         break;
4284       }
4285 
4286       // Skip the range if the block was deleted.
4287       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4288         const uint64_t StartAddress =
4289             OutputStart + InputOffset - BB->getOffset();
4290         uint64_t EndAddress = BB->getOutputAddressRange().second;
4291         if (InputEndOffset < BB->getEndOffset())
4292           EndAddress = StartAddress + InputEndOffset - InputOffset;
4293 
4294         if (StartAddress == PrevEndAddress) {
4295           OutputRanges.back().HighPC =
4296               std::max(OutputRanges.back().HighPC, EndAddress);
4297         } else {
4298           OutputRanges.emplace_back(StartAddress,
4299                                     std::max(StartAddress, EndAddress));
4300         }
4301         PrevEndAddress = OutputRanges.back().HighPC;
4302       }
4303 
4304       InputOffset = BB->getEndOffset();
4305       ++BBI;
4306     } while (InputOffset < InputEndOffset);
4307   }
4308 
4309   // Post-processing pass to sort and merge ranges.
4310   std::sort(OutputRanges.begin(), OutputRanges.end());
4311   DebugAddressRangesVector MergedRanges;
4312   PrevEndAddress = 0;
4313   for (const DebugAddressRange &Range : OutputRanges) {
4314     if (Range.LowPC <= PrevEndAddress) {
4315       MergedRanges.back().HighPC =
4316           std::max(MergedRanges.back().HighPC, Range.HighPC);
4317     } else {
4318       MergedRanges.emplace_back(Range.LowPC, Range.HighPC);
4319     }
4320     PrevEndAddress = MergedRanges.back().HighPC;
4321   }
4322 
4323   return MergedRanges;
4324 }
4325 
4326 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4327   if (CurrentState == State::Disassembled) {
4328     auto II = Instructions.find(Offset);
4329     return (II == Instructions.end()) ? nullptr : &II->second;
4330   } else if (CurrentState == State::CFG) {
4331     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4332     if (!BB)
4333       return nullptr;
4334 
4335     for (MCInst &Inst : *BB) {
4336       constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4337       if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4338         return &Inst;
4339     }
4340 
4341     if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4342       const uint32_t Size =
4343           BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size");
4344       if (BB->getEndOffset() - Offset == Size)
4345         return LastInstr;
4346     }
4347 
4348     return nullptr;
4349   } else {
4350     llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4351   }
4352 }
4353 
4354 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList(
4355     const DebugLocationsVector &InputLL) const {
4356   DebugLocationsVector OutputLL;
4357 
4358   if (isFolded())
4359     return OutputLL;
4360 
4361   // If the function hasn't changed - there's nothing to update.
4362   if (!isEmitted())
4363     return InputLL;
4364 
4365   uint64_t PrevEndAddress = 0;
4366   SmallVectorImpl<uint8_t> *PrevExpr = nullptr;
4367   for (const DebugLocationEntry &Entry : InputLL) {
4368     const uint64_t Start = Entry.LowPC;
4369     const uint64_t End = Entry.HighPC;
4370     if (!containsAddress(Start)) {
4371       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4372                            "for "
4373                         << *this << " : [0x" << Twine::utohexstr(Start)
4374                         << ", 0x" << Twine::utohexstr(End) << "]\n");
4375       continue;
4376     }
4377     uint64_t InputOffset = Start - getAddress();
4378     const uint64_t InputEndOffset = std::min(End - getAddress(), getSize());
4379     auto BBI = std::upper_bound(
4380         BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
4381         BasicBlockOffset(InputOffset, nullptr), CompareBasicBlockOffsets());
4382     --BBI;
4383     do {
4384       const BinaryBasicBlock *BB = BBI->second;
4385       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4386         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4387                              "for "
4388                           << *this << " : [0x" << Twine::utohexstr(Start)
4389                           << ", 0x" << Twine::utohexstr(End) << "]\n");
4390         PrevEndAddress = 0;
4391         break;
4392       }
4393 
4394       // Skip the range if the block was deleted.
4395       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4396         const uint64_t StartAddress =
4397             OutputStart + InputOffset - BB->getOffset();
4398         uint64_t EndAddress = BB->getOutputAddressRange().second;
4399         if (InputEndOffset < BB->getEndOffset())
4400           EndAddress = StartAddress + InputEndOffset - InputOffset;
4401 
4402         if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) {
4403           OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress);
4404         } else {
4405           OutputLL.emplace_back(DebugLocationEntry{
4406               StartAddress, std::max(StartAddress, EndAddress), Entry.Expr});
4407         }
4408         PrevEndAddress = OutputLL.back().HighPC;
4409         PrevExpr = &OutputLL.back().Expr;
4410       }
4411 
4412       ++BBI;
4413       InputOffset = BB->getEndOffset();
4414     } while (InputOffset < InputEndOffset);
4415   }
4416 
4417   // Sort and merge adjacent entries with identical location.
4418   std::stable_sort(
4419       OutputLL.begin(), OutputLL.end(),
4420       [](const DebugLocationEntry &A, const DebugLocationEntry &B) {
4421         return A.LowPC < B.LowPC;
4422       });
4423   DebugLocationsVector MergedLL;
4424   PrevEndAddress = 0;
4425   PrevExpr = nullptr;
4426   for (const DebugLocationEntry &Entry : OutputLL) {
4427     if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) {
4428       MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC);
4429     } else {
4430       const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress);
4431       const uint64_t End = std::max(Begin, Entry.HighPC);
4432       MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr});
4433     }
4434     PrevEndAddress = MergedLL.back().HighPC;
4435     PrevExpr = &MergedLL.back().Expr;
4436   }
4437 
4438   return MergedLL;
4439 }
4440 
4441 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4442   OS << "Loop Info for Function \"" << *this << "\"";
4443   if (hasValidProfile())
4444     OS << " (count: " << getExecutionCount() << ")";
4445   OS << "\n";
4446 
4447   std::stack<BinaryLoop *> St;
4448   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I)
4449     St.push(*I);
4450   while (!St.empty()) {
4451     BinaryLoop *L = St.top();
4452     St.pop();
4453 
4454     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4455       St.push(*I);
4456 
4457     if (!hasValidProfile())
4458       continue;
4459 
4460     OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4461        << " loop header: " << L->getHeader()->getName();
4462     OS << "\n";
4463     OS << "Loop basic blocks: ";
4464     const char *Sep = "";
4465     for (auto BI = L->block_begin(), BE = L->block_end(); BI != BE; ++BI) {
4466       OS << Sep << (*BI)->getName();
4467       Sep = ", ";
4468     }
4469     OS << "\n";
4470     if (hasValidProfile()) {
4471       OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4472       OS << "Loop entry count: " << L->EntryCount << "\n";
4473       OS << "Loop exit count: " << L->ExitCount << "\n";
4474       if (L->EntryCount > 0) {
4475         OS << "Average iters per entry: "
4476            << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4477            << "\n";
4478       }
4479     }
4480     OS << "----\n";
4481   }
4482 
4483   OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4484   OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4485   OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4486 }
4487 
4488 bool BinaryFunction::isAArch64Veneer() const {
4489   if (BasicBlocks.size() != 1)
4490     return false;
4491 
4492   BinaryBasicBlock &BB = **BasicBlocks.begin();
4493   if (BB.size() != 3)
4494     return false;
4495 
4496   for (MCInst &Inst : BB)
4497     if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4498       return false;
4499 
4500   return true;
4501 }
4502 
4503 } // namespace bolt
4504 } // namespace llvm
4505