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