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