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