xref: /llvm-project/bolt/lib/Core/BinaryFunction.cpp (revision a9cd49d50e88aa142e6d57de90321d8810e1027f)
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/MCStreamer.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     // re-populate successors based on the jump table.
1879     std::set<const MCSymbol *> JTLabels;
1880     LastIndirectJumpBB->removeAllSuccessors();
1881     const JumpTable *JT = getJumpTableContainingAddress(LastJT);
1882     for (const MCSymbol *Label : JT->Entries)
1883       JTLabels.emplace(Label);
1884     for (const MCSymbol *Label : JTLabels) {
1885       BinaryBasicBlock *BB = getBasicBlockForLabel(Label);
1886       // Ignore __builtin_unreachable()
1887       if (!BB) {
1888         assert(Label == getFunctionEndLabel() && "if no BB found, must be end");
1889         continue;
1890       }
1891       LastIndirectJumpBB->addSuccessor(BB);
1892     }
1893   }
1894 
1895   if (HasFixedIndirectBranch)
1896     return false;
1897 
1898   if (HasUnknownControlFlow && !BC.HasRelocations)
1899     return false;
1900 
1901   return true;
1902 }
1903 
1904 void BinaryFunction::recomputeLandingPads() {
1905   updateBBIndices(0);
1906 
1907   for (BinaryBasicBlock *BB : BasicBlocks) {
1908     BB->LandingPads.clear();
1909     BB->Throwers.clear();
1910   }
1911 
1912   for (BinaryBasicBlock *BB : BasicBlocks) {
1913     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
1914     for (MCInst &Instr : *BB) {
1915       if (!BC.MIB->isInvoke(Instr))
1916         continue;
1917 
1918       const Optional<MCPlus::MCLandingPad> EHInfo = BC.MIB->getEHInfo(Instr);
1919       if (!EHInfo || !EHInfo->first)
1920         continue;
1921 
1922       BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
1923       if (!BBLandingPads.count(LPBlock)) {
1924         BBLandingPads.insert(LPBlock);
1925         BB->LandingPads.emplace_back(LPBlock);
1926         LPBlock->Throwers.emplace_back(BB);
1927       }
1928     }
1929   }
1930 }
1931 
1932 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
1933   auto &MIB = BC.MIB;
1934 
1935   if (!isSimple()) {
1936     assert(!BC.HasRelocations &&
1937            "cannot process file with non-simple function in relocs mode");
1938     return false;
1939   }
1940 
1941   if (CurrentState != State::Disassembled)
1942     return false;
1943 
1944   assert(BasicBlocks.empty() && "basic block list should be empty");
1945   assert((Labels.find(0) != Labels.end()) &&
1946          "first instruction should always have a label");
1947 
1948   // Create basic blocks in the original layout order:
1949   //
1950   //  * Every instruction with associated label marks
1951   //    the beginning of a basic block.
1952   //  * Conditional instruction marks the end of a basic block,
1953   //    except when the following instruction is an
1954   //    unconditional branch, and the unconditional branch is not
1955   //    a destination of another branch. In the latter case, the
1956   //    basic block will consist of a single unconditional branch
1957   //    (missed "double-jump" optimization).
1958   //
1959   // Created basic blocks are sorted in layout order since they are
1960   // created in the same order as instructions, and instructions are
1961   // sorted by offsets.
1962   BinaryBasicBlock *InsertBB = nullptr;
1963   BinaryBasicBlock *PrevBB = nullptr;
1964   bool IsLastInstrNop = false;
1965   // Offset of the last non-nop instruction.
1966   uint64_t LastInstrOffset = 0;
1967 
1968   auto addCFIPlaceholders = [this](uint64_t CFIOffset,
1969                                    BinaryBasicBlock *InsertBB) {
1970     for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
1971               FE = OffsetToCFI.upper_bound(CFIOffset);
1972          FI != FE; ++FI) {
1973       addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
1974     }
1975   };
1976 
1977   // For profiling purposes we need to save the offset of the last instruction
1978   // in the basic block.
1979   // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
1980   //       older profiles ignored nops.
1981   auto updateOffset = [&](uint64_t Offset) {
1982     assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
1983     MCInst *LastNonNop = nullptr;
1984     for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
1985                                             E = PrevBB->rend();
1986          RII != E; ++RII) {
1987       if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
1988         LastNonNop = &*RII;
1989         break;
1990       }
1991     }
1992     if (LastNonNop && !MIB->getOffset(*LastNonNop))
1993       MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset), AllocatorId);
1994   };
1995 
1996   for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
1997     const uint32_t Offset = I->first;
1998     MCInst &Instr = I->second;
1999 
2000     auto LI = Labels.find(Offset);
2001     if (LI != Labels.end()) {
2002       // Always create new BB at branch destination.
2003       PrevBB = InsertBB ? InsertBB : PrevBB;
2004       InsertBB = addBasicBlock(LI->first, LI->second,
2005                                opts::PreserveBlocksAlignment && IsLastInstrNop);
2006       if (PrevBB)
2007         updateOffset(LastInstrOffset);
2008     }
2009 
2010     const uint64_t InstrInputAddr = I->first + Address;
2011     bool IsSDTMarker =
2012         MIB->isNoop(Instr) && BC.SDTMarkers.count(InstrInputAddr);
2013     bool IsLKMarker = BC.LKMarkers.count(InstrInputAddr);
2014     // Mark all nops with Offset for profile tracking purposes.
2015     if (MIB->isNoop(Instr) || IsLKMarker) {
2016       if (!MIB->getOffset(Instr))
2017         MIB->setOffset(Instr, static_cast<uint32_t>(Offset), AllocatorId);
2018       if (IsSDTMarker || IsLKMarker)
2019         HasSDTMarker = true;
2020       else
2021         // Annotate ordinary nops, so we can safely delete them if required.
2022         MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
2023     }
2024 
2025     if (!InsertBB) {
2026       // It must be a fallthrough or unreachable code. Create a new block unless
2027       // we see an unconditional branch following a conditional one. The latter
2028       // should not be a conditional tail call.
2029       assert(PrevBB && "no previous basic block for a fall through");
2030       MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
2031       assert(PrevInstr && "no previous instruction for a fall through");
2032       if (MIB->isUnconditionalBranch(Instr) &&
2033           !MIB->isUnconditionalBranch(*PrevInstr) &&
2034           !MIB->getConditionalTailCall(*PrevInstr)) {
2035         // Temporarily restore inserter basic block.
2036         InsertBB = PrevBB;
2037       } else {
2038         MCSymbol *Label;
2039         {
2040           auto L = BC.scopeLock();
2041           Label = BC.Ctx->createNamedTempSymbol("FT");
2042         }
2043         InsertBB = addBasicBlock(
2044             Offset, Label, opts::PreserveBlocksAlignment && IsLastInstrNop);
2045         updateOffset(LastInstrOffset);
2046       }
2047     }
2048     if (Offset == 0) {
2049       // Add associated CFI pseudos in the first offset (0)
2050       addCFIPlaceholders(0, InsertBB);
2051     }
2052 
2053     const bool IsBlockEnd = MIB->isTerminator(Instr);
2054     IsLastInstrNop = MIB->isNoop(Instr);
2055     if (!IsLastInstrNop)
2056       LastInstrOffset = Offset;
2057     InsertBB->addInstruction(std::move(Instr));
2058 
2059     // Add associated CFI instrs. We always add the CFI instruction that is
2060     // located immediately after this instruction, since the next CFI
2061     // instruction reflects the change in state caused by this instruction.
2062     auto NextInstr = std::next(I);
2063     uint64_t CFIOffset;
2064     if (NextInstr != E)
2065       CFIOffset = NextInstr->first;
2066     else
2067       CFIOffset = getSize();
2068 
2069     // Note: this potentially invalidates instruction pointers/iterators.
2070     addCFIPlaceholders(CFIOffset, InsertBB);
2071 
2072     if (IsBlockEnd) {
2073       PrevBB = InsertBB;
2074       InsertBB = nullptr;
2075     }
2076   }
2077 
2078   if (BasicBlocks.empty()) {
2079     setSimple(false);
2080     return false;
2081   }
2082 
2083   // Intermediate dump.
2084   LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2085 
2086   // TODO: handle properly calls to no-return functions,
2087   // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2088   // blocks.
2089 
2090   for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2091     LLVM_DEBUG(dbgs() << "registering branch [0x"
2092                       << Twine::utohexstr(Branch.first) << "] -> [0x"
2093                       << Twine::utohexstr(Branch.second) << "]\n");
2094     BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2095     BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2096     if (!FromBB || !ToBB) {
2097       if (!FromBB)
2098         errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2099       if (!ToBB)
2100         errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2101       BC.exitWithBugReport("disassembly failed - inconsistent branch found.",
2102                            *this);
2103     }
2104 
2105     FromBB->addSuccessor(ToBB);
2106   }
2107 
2108   // Add fall-through branches.
2109   PrevBB = nullptr;
2110   bool IsPrevFT = false; // Is previous block a fall-through.
2111   for (BinaryBasicBlock *BB : BasicBlocks) {
2112     if (IsPrevFT)
2113       PrevBB->addSuccessor(BB);
2114 
2115     if (BB->empty()) {
2116       IsPrevFT = true;
2117       PrevBB = BB;
2118       continue;
2119     }
2120 
2121     MCInst *LastInstr = BB->getLastNonPseudoInstr();
2122     assert(LastInstr &&
2123            "should have non-pseudo instruction in non-empty block");
2124 
2125     if (BB->succ_size() == 0) {
2126       // Since there's no existing successors, we know the last instruction is
2127       // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2128       // fall-through.
2129       //
2130       // Conditional tail call is a special case since we don't add a taken
2131       // branch successor for it.
2132       IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2133                  MIB->getConditionalTailCall(*LastInstr);
2134     } else if (BB->succ_size() == 1) {
2135       IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2136     } else {
2137       IsPrevFT = false;
2138     }
2139 
2140     PrevBB = BB;
2141   }
2142 
2143   // Assign landing pads and throwers info.
2144   recomputeLandingPads();
2145 
2146   // Assign CFI information to each BB entry.
2147   annotateCFIState();
2148 
2149   // Annotate invoke instructions with GNU_args_size data.
2150   propagateGnuArgsSizeInfo(AllocatorId);
2151 
2152   // Set the basic block layout to the original order and set end offsets.
2153   PrevBB = nullptr;
2154   for (BinaryBasicBlock *BB : BasicBlocks) {
2155     BasicBlocksLayout.emplace_back(BB);
2156     if (PrevBB)
2157       PrevBB->setEndOffset(BB->getOffset());
2158     PrevBB = BB;
2159   }
2160   PrevBB->setEndOffset(getSize());
2161 
2162   updateLayoutIndices();
2163 
2164   normalizeCFIState();
2165 
2166   // Clean-up memory taken by intermediate structures.
2167   //
2168   // NB: don't clear Labels list as we may need them if we mark the function
2169   //     as non-simple later in the process of discovering extra entry points.
2170   clearList(Instructions);
2171   clearList(OffsetToCFI);
2172   clearList(TakenBranches);
2173 
2174   // Update the state.
2175   CurrentState = State::CFG;
2176 
2177   // Make any necessary adjustments for indirect branches.
2178   if (!postProcessIndirectBranches(AllocatorId)) {
2179     if (opts::Verbosity) {
2180       errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2181              << *this << '\n';
2182     }
2183     // In relocation mode we want to keep processing the function but avoid
2184     // optimizing it.
2185     setSimple(false);
2186   }
2187 
2188   clearList(ExternallyReferencedOffsets);
2189   clearList(UnknownIndirectBranchOffsets);
2190 
2191   return true;
2192 }
2193 
2194 void BinaryFunction::postProcessCFG() {
2195   if (isSimple() && !BasicBlocks.empty()) {
2196     // Convert conditional tail call branches to conditional branches that jump
2197     // to a tail call.
2198     removeConditionalTailCalls();
2199 
2200     postProcessProfile();
2201 
2202     // Eliminate inconsistencies between branch instructions and CFG.
2203     postProcessBranches();
2204   }
2205 
2206   calculateMacroOpFusionStats();
2207 
2208   // The final cleanup of intermediate structures.
2209   clearList(IgnoredBranches);
2210 
2211   // Remove "Offset" annotations, unless we need an address-translation table
2212   // later. This has no cost, since annotations are allocated by a bumpptr
2213   // allocator and won't be released anyway until late in the pipeline.
2214   if (!requiresAddressTranslation() && !opts::Instrument) {
2215     for (BinaryBasicBlock *BB : layout())
2216       for (MCInst &Inst : *BB)
2217         BC.MIB->clearOffset(Inst);
2218   }
2219 
2220   assert((!isSimple() || validateCFG()) &&
2221          "invalid CFG detected after post-processing");
2222 }
2223 
2224 void BinaryFunction::calculateMacroOpFusionStats() {
2225   if (!getBinaryContext().isX86())
2226     return;
2227   for (BinaryBasicBlock *BB : layout()) {
2228     auto II = BB->getMacroOpFusionPair();
2229     if (II == BB->end())
2230       continue;
2231 
2232     // Check offset of the second instruction.
2233     // FIXME: arch-specific.
2234     const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0);
2235     if (!Offset || (getAddress() + Offset) % 64)
2236       continue;
2237 
2238     LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x"
2239                       << Twine::utohexstr(getAddress() + Offset)
2240                       << " in function " << *this << "; executed "
2241                       << BB->getKnownExecutionCount() << " times.\n");
2242     ++BC.MissedMacroFusionPairs;
2243     BC.MissedMacroFusionExecCount += BB->getKnownExecutionCount();
2244   }
2245 }
2246 
2247 void BinaryFunction::removeTagsFromProfile() {
2248   for (BinaryBasicBlock *BB : BasicBlocks) {
2249     if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2250       BB->ExecutionCount = 0;
2251     for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2252       if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2253           BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2254         continue;
2255       BI.Count = 0;
2256       BI.MispredictedCount = 0;
2257     }
2258   }
2259 }
2260 
2261 void BinaryFunction::removeConditionalTailCalls() {
2262   // Blocks to be appended at the end.
2263   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2264 
2265   for (auto BBI = begin(); BBI != end(); ++BBI) {
2266     BinaryBasicBlock &BB = *BBI;
2267     MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2268     if (!CTCInstr)
2269       continue;
2270 
2271     Optional<uint64_t> TargetAddressOrNone =
2272         BC.MIB->getConditionalTailCall(*CTCInstr);
2273     if (!TargetAddressOrNone)
2274       continue;
2275 
2276     // Gather all necessary information about CTC instruction before
2277     // annotations are destroyed.
2278     const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2279     uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2280     uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2281     if (hasValidProfile()) {
2282       CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2283           *CTCInstr, "CTCTakenCount");
2284       CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2285           *CTCInstr, "CTCMispredCount");
2286     }
2287 
2288     // Assert that the tail call does not throw.
2289     assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2290            "found tail call with associated landing pad");
2291 
2292     // Create a basic block with an unconditional tail call instruction using
2293     // the same destination.
2294     const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2295     assert(CTCTargetLabel && "symbol expected for conditional tail call");
2296     MCInst TailCallInstr;
2297     BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
2298     // Link new BBs to the original input offset of the BB where the CTC
2299     // is, so we can map samples recorded in new BBs back to the original BB
2300     // seem in the input binary (if using BAT)
2301     std::unique_ptr<BinaryBasicBlock> TailCallBB = createBasicBlock(
2302         BB.getInputOffset(), BC.Ctx->createNamedTempSymbol("TC"));
2303     TailCallBB->addInstruction(TailCallInstr);
2304     TailCallBB->setCFIState(CFIStateBeforeCTC);
2305 
2306     // Add CFG edge with profile info from BB to TailCallBB.
2307     BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2308 
2309     // Add execution count for the block.
2310     TailCallBB->setExecutionCount(CTCTakenCount);
2311 
2312     BC.MIB->convertTailCallToJmp(*CTCInstr);
2313 
2314     BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2315                                 BC.Ctx.get());
2316 
2317     // Add basic block to the list that will be added to the end.
2318     NewBlocks.emplace_back(std::move(TailCallBB));
2319 
2320     // Swap edges as the TailCallBB corresponds to the taken branch.
2321     BB.swapConditionalSuccessors();
2322 
2323     // This branch is no longer a conditional tail call.
2324     BC.MIB->unsetConditionalTailCall(*CTCInstr);
2325   }
2326 
2327   insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2328                     /* UpdateLayout */ true,
2329                     /* UpdateCFIState */ false);
2330 }
2331 
2332 uint64_t BinaryFunction::getFunctionScore() const {
2333   if (FunctionScore != -1)
2334     return FunctionScore;
2335 
2336   if (!isSimple() || !hasValidProfile()) {
2337     FunctionScore = 0;
2338     return FunctionScore;
2339   }
2340 
2341   uint64_t TotalScore = 0ULL;
2342   for (BinaryBasicBlock *BB : layout()) {
2343     uint64_t BBExecCount = BB->getExecutionCount();
2344     if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2345       continue;
2346     TotalScore += BBExecCount;
2347   }
2348   FunctionScore = TotalScore;
2349   return FunctionScore;
2350 }
2351 
2352 void BinaryFunction::annotateCFIState() {
2353   assert(CurrentState == State::Disassembled && "unexpected function state");
2354   assert(!BasicBlocks.empty() && "basic block list should not be empty");
2355 
2356   // This is an index of the last processed CFI in FDE CFI program.
2357   uint32_t State = 0;
2358 
2359   // This is an index of RememberState CFI reflecting effective state right
2360   // after execution of RestoreState CFI.
2361   //
2362   // It differs from State iff the CFI at (State-1)
2363   // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2364   //
2365   // This allows us to generate shorter replay sequences when producing new
2366   // CFI programs.
2367   uint32_t EffectiveState = 0;
2368 
2369   // For tracking RememberState/RestoreState sequences.
2370   std::stack<uint32_t> StateStack;
2371 
2372   for (BinaryBasicBlock *BB : BasicBlocks) {
2373     BB->setCFIState(EffectiveState);
2374 
2375     for (const MCInst &Instr : *BB) {
2376       const MCCFIInstruction *CFI = getCFIFor(Instr);
2377       if (!CFI)
2378         continue;
2379 
2380       ++State;
2381 
2382       switch (CFI->getOperation()) {
2383       case MCCFIInstruction::OpRememberState:
2384         StateStack.push(EffectiveState);
2385         EffectiveState = State;
2386         break;
2387       case MCCFIInstruction::OpRestoreState:
2388         assert(!StateStack.empty() && "corrupt CFI stack");
2389         EffectiveState = StateStack.top();
2390         StateStack.pop();
2391         break;
2392       case MCCFIInstruction::OpGnuArgsSize:
2393         // OpGnuArgsSize CFIs do not affect the CFI state.
2394         break;
2395       default:
2396         // Any other CFI updates the state.
2397         EffectiveState = State;
2398         break;
2399       }
2400     }
2401   }
2402 
2403   assert(StateStack.empty() && "corrupt CFI stack");
2404 }
2405 
2406 namespace {
2407 
2408 /// Our full interpretation of a DWARF CFI machine state at a given point
2409 struct CFISnapshot {
2410   /// CFA register number and offset defining the canonical frame at this
2411   /// point, or the number of a rule (CFI state) that computes it with a
2412   /// DWARF expression. This number will be negative if it refers to a CFI
2413   /// located in the CIE instead of the FDE.
2414   uint32_t CFAReg;
2415   int32_t CFAOffset;
2416   int32_t CFARule;
2417   /// Mapping of rules (CFI states) that define the location of each
2418   /// register. If absent, no rule defining the location of such register
2419   /// was ever read. This number will be negative if it refers to a CFI
2420   /// located in the CIE instead of the FDE.
2421   DenseMap<int32_t, int32_t> RegRule;
2422 
2423   /// References to CIE, FDE and expanded instructions after a restore state
2424   const BinaryFunction::CFIInstrMapType &CIE;
2425   const BinaryFunction::CFIInstrMapType &FDE;
2426   const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2427 
2428   /// Current FDE CFI number representing the state where the snapshot is at
2429   int32_t CurState;
2430 
2431   /// Used when we don't have information about which state/rule to apply
2432   /// to recover the location of either the CFA or a specific register
2433   constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2434 
2435 private:
2436   /// Update our snapshot by executing a single CFI
2437   void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2438     switch (Instr.getOperation()) {
2439     case MCCFIInstruction::OpSameValue:
2440     case MCCFIInstruction::OpRelOffset:
2441     case MCCFIInstruction::OpOffset:
2442     case MCCFIInstruction::OpRestore:
2443     case MCCFIInstruction::OpUndefined:
2444     case MCCFIInstruction::OpRegister:
2445       RegRule[Instr.getRegister()] = RuleNumber;
2446       break;
2447     case MCCFIInstruction::OpDefCfaRegister:
2448       CFAReg = Instr.getRegister();
2449       CFARule = UNKNOWN;
2450       break;
2451     case MCCFIInstruction::OpDefCfaOffset:
2452       CFAOffset = Instr.getOffset();
2453       CFARule = UNKNOWN;
2454       break;
2455     case MCCFIInstruction::OpDefCfa:
2456       CFAReg = Instr.getRegister();
2457       CFAOffset = Instr.getOffset();
2458       CFARule = UNKNOWN;
2459       break;
2460     case MCCFIInstruction::OpEscape: {
2461       Optional<uint8_t> Reg = readDWARFExpressionTargetReg(Instr.getValues());
2462       // Handle DW_CFA_def_cfa_expression
2463       if (!Reg) {
2464         CFARule = RuleNumber;
2465         break;
2466       }
2467       RegRule[*Reg] = RuleNumber;
2468       break;
2469     }
2470     case MCCFIInstruction::OpAdjustCfaOffset:
2471     case MCCFIInstruction::OpWindowSave:
2472     case MCCFIInstruction::OpNegateRAState:
2473     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2474       llvm_unreachable("unsupported CFI opcode");
2475       break;
2476     case MCCFIInstruction::OpRememberState:
2477     case MCCFIInstruction::OpRestoreState:
2478     case MCCFIInstruction::OpGnuArgsSize:
2479       // do not affect CFI state
2480       break;
2481     }
2482   }
2483 
2484 public:
2485   /// Advance state reading FDE CFI instructions up to State number
2486   void advanceTo(int32_t State) {
2487     for (int32_t I = CurState, E = State; I != E; ++I) {
2488       const MCCFIInstruction &Instr = FDE[I];
2489       if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2490         update(Instr, I);
2491         continue;
2492       }
2493       // If restore state instruction, fetch the equivalent CFIs that have
2494       // the same effect of this restore. This is used to ensure remember-
2495       // restore pairs are completely removed.
2496       auto Iter = FrameRestoreEquivalents.find(I);
2497       if (Iter == FrameRestoreEquivalents.end())
2498         continue;
2499       for (int32_t RuleNumber : Iter->second)
2500         update(FDE[RuleNumber], RuleNumber);
2501     }
2502 
2503     assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2504             CFARule != UNKNOWN) &&
2505            "CIE did not define default CFA?");
2506 
2507     CurState = State;
2508   }
2509 
2510   /// Interpret all CIE and FDE instructions up until CFI State number and
2511   /// populate this snapshot
2512   CFISnapshot(
2513       const BinaryFunction::CFIInstrMapType &CIE,
2514       const BinaryFunction::CFIInstrMapType &FDE,
2515       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2516       int32_t State)
2517       : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2518     CFAReg = UNKNOWN;
2519     CFAOffset = UNKNOWN;
2520     CFARule = UNKNOWN;
2521     CurState = 0;
2522 
2523     for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2524       const MCCFIInstruction &Instr = CIE[I];
2525       update(Instr, -I);
2526     }
2527 
2528     advanceTo(State);
2529   }
2530 };
2531 
2532 /// A CFI snapshot with the capability of checking if incremental additions to
2533 /// it are redundant. This is used to ensure we do not emit two CFI instructions
2534 /// back-to-back that are doing the same state change, or to avoid emitting a
2535 /// CFI at all when the state at that point would not be modified after that CFI
2536 struct CFISnapshotDiff : public CFISnapshot {
2537   bool RestoredCFAReg{false};
2538   bool RestoredCFAOffset{false};
2539   DenseMap<int32_t, bool> RestoredRegs;
2540 
2541   CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2542 
2543   CFISnapshotDiff(
2544       const BinaryFunction::CFIInstrMapType &CIE,
2545       const BinaryFunction::CFIInstrMapType &FDE,
2546       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2547       int32_t State)
2548       : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2549 
2550   /// Return true if applying Instr to this state is redundant and can be
2551   /// dismissed.
2552   bool isRedundant(const MCCFIInstruction &Instr) {
2553     switch (Instr.getOperation()) {
2554     case MCCFIInstruction::OpSameValue:
2555     case MCCFIInstruction::OpRelOffset:
2556     case MCCFIInstruction::OpOffset:
2557     case MCCFIInstruction::OpRestore:
2558     case MCCFIInstruction::OpUndefined:
2559     case MCCFIInstruction::OpRegister:
2560     case MCCFIInstruction::OpEscape: {
2561       uint32_t Reg;
2562       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2563         Reg = Instr.getRegister();
2564       } else {
2565         Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2566         // Handle DW_CFA_def_cfa_expression
2567         if (!R) {
2568           if (RestoredCFAReg && RestoredCFAOffset)
2569             return true;
2570           RestoredCFAReg = true;
2571           RestoredCFAOffset = true;
2572           return false;
2573         }
2574         Reg = *R;
2575       }
2576       if (RestoredRegs[Reg])
2577         return true;
2578       RestoredRegs[Reg] = true;
2579       const int32_t CurRegRule =
2580           RegRule.find(Reg) != RegRule.end() ? RegRule[Reg] : UNKNOWN;
2581       if (CurRegRule == UNKNOWN) {
2582         if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2583             Instr.getOperation() == MCCFIInstruction::OpSameValue)
2584           return true;
2585         return false;
2586       }
2587       const MCCFIInstruction &LastDef =
2588           CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2589       return LastDef == Instr;
2590     }
2591     case MCCFIInstruction::OpDefCfaRegister:
2592       if (RestoredCFAReg)
2593         return true;
2594       RestoredCFAReg = true;
2595       return CFAReg == Instr.getRegister();
2596     case MCCFIInstruction::OpDefCfaOffset:
2597       if (RestoredCFAOffset)
2598         return true;
2599       RestoredCFAOffset = true;
2600       return CFAOffset == Instr.getOffset();
2601     case MCCFIInstruction::OpDefCfa:
2602       if (RestoredCFAReg && RestoredCFAOffset)
2603         return true;
2604       RestoredCFAReg = true;
2605       RestoredCFAOffset = true;
2606       return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2607     case MCCFIInstruction::OpAdjustCfaOffset:
2608     case MCCFIInstruction::OpWindowSave:
2609     case MCCFIInstruction::OpNegateRAState:
2610     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2611       llvm_unreachable("unsupported CFI opcode");
2612       return false;
2613     case MCCFIInstruction::OpRememberState:
2614     case MCCFIInstruction::OpRestoreState:
2615     case MCCFIInstruction::OpGnuArgsSize:
2616       // do not affect CFI state
2617       return true;
2618     }
2619     return false;
2620   }
2621 };
2622 
2623 } // end anonymous namespace
2624 
2625 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2626                                      BinaryBasicBlock *InBB,
2627                                      BinaryBasicBlock::iterator InsertIt) {
2628   if (FromState == ToState)
2629     return true;
2630   assert(FromState < ToState && "can only replay CFIs forward");
2631 
2632   CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2633                           FrameRestoreEquivalents, FromState);
2634 
2635   std::vector<uint32_t> NewCFIs;
2636   for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2637     MCCFIInstruction *Instr = &FrameInstructions[CurState];
2638     if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2639       auto Iter = FrameRestoreEquivalents.find(CurState);
2640       assert(Iter != FrameRestoreEquivalents.end());
2641       NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2642       // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2643       // so we might as well fall-through here.
2644     }
2645     NewCFIs.push_back(CurState);
2646     continue;
2647   }
2648 
2649   // Replay instructions while avoiding duplicates
2650   for (auto I = NewCFIs.rbegin(), E = NewCFIs.rend(); I != E; ++I) {
2651     if (CFIDiff.isRedundant(FrameInstructions[*I]))
2652       continue;
2653     InsertIt = addCFIPseudo(InBB, InsertIt, *I);
2654   }
2655 
2656   return true;
2657 }
2658 
2659 SmallVector<int32_t, 4>
2660 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2661                                BinaryBasicBlock *InBB,
2662                                BinaryBasicBlock::iterator &InsertIt) {
2663   SmallVector<int32_t, 4> NewStates;
2664 
2665   CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2666                          FrameRestoreEquivalents, ToState);
2667   CFISnapshotDiff FromCFITable(ToCFITable);
2668   FromCFITable.advanceTo(FromState);
2669 
2670   auto undoStateDefCfa = [&]() {
2671     if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2672       FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2673           nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2674       if (FromCFITable.isRedundant(FrameInstructions.back())) {
2675         FrameInstructions.pop_back();
2676         return;
2677       }
2678       NewStates.push_back(FrameInstructions.size() - 1);
2679       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2680       ++InsertIt;
2681     } else if (ToCFITable.CFARule < 0) {
2682       if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2683         return;
2684       NewStates.push_back(FrameInstructions.size());
2685       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2686       ++InsertIt;
2687       FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2688     } else if (!FromCFITable.isRedundant(
2689                    FrameInstructions[ToCFITable.CFARule])) {
2690       NewStates.push_back(ToCFITable.CFARule);
2691       InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2692       ++InsertIt;
2693     }
2694   };
2695 
2696   auto undoState = [&](const MCCFIInstruction &Instr) {
2697     switch (Instr.getOperation()) {
2698     case MCCFIInstruction::OpRememberState:
2699     case MCCFIInstruction::OpRestoreState:
2700       break;
2701     case MCCFIInstruction::OpSameValue:
2702     case MCCFIInstruction::OpRelOffset:
2703     case MCCFIInstruction::OpOffset:
2704     case MCCFIInstruction::OpRestore:
2705     case MCCFIInstruction::OpUndefined:
2706     case MCCFIInstruction::OpEscape:
2707     case MCCFIInstruction::OpRegister: {
2708       uint32_t Reg;
2709       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2710         Reg = Instr.getRegister();
2711       } else {
2712         Optional<uint8_t> R = readDWARFExpressionTargetReg(Instr.getValues());
2713         // Handle DW_CFA_def_cfa_expression
2714         if (!R) {
2715           undoStateDefCfa();
2716           return;
2717         }
2718         Reg = *R;
2719       }
2720 
2721       if (ToCFITable.RegRule.find(Reg) == ToCFITable.RegRule.end()) {
2722         FrameInstructions.emplace_back(
2723             MCCFIInstruction::createRestore(nullptr, Reg));
2724         if (FromCFITable.isRedundant(FrameInstructions.back())) {
2725           FrameInstructions.pop_back();
2726           break;
2727         }
2728         NewStates.push_back(FrameInstructions.size() - 1);
2729         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2730         ++InsertIt;
2731         break;
2732       }
2733       const int32_t Rule = ToCFITable.RegRule[Reg];
2734       if (Rule < 0) {
2735         if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2736           break;
2737         NewStates.push_back(FrameInstructions.size());
2738         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2739         ++InsertIt;
2740         FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2741         break;
2742       }
2743       if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2744         break;
2745       NewStates.push_back(Rule);
2746       InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2747       ++InsertIt;
2748       break;
2749     }
2750     case MCCFIInstruction::OpDefCfaRegister:
2751     case MCCFIInstruction::OpDefCfaOffset:
2752     case MCCFIInstruction::OpDefCfa:
2753       undoStateDefCfa();
2754       break;
2755     case MCCFIInstruction::OpAdjustCfaOffset:
2756     case MCCFIInstruction::OpWindowSave:
2757     case MCCFIInstruction::OpNegateRAState:
2758     case MCCFIInstruction::OpLLVMDefAspaceCfa:
2759       llvm_unreachable("unsupported CFI opcode");
2760       break;
2761     case MCCFIInstruction::OpGnuArgsSize:
2762       // do not affect CFI state
2763       break;
2764     }
2765   };
2766 
2767   // Undo all modifications from ToState to FromState
2768   for (int32_t I = ToState, E = FromState; I != E; ++I) {
2769     const MCCFIInstruction &Instr = FrameInstructions[I];
2770     if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2771       undoState(Instr);
2772       continue;
2773     }
2774     auto Iter = FrameRestoreEquivalents.find(I);
2775     if (Iter == FrameRestoreEquivalents.end())
2776       continue;
2777     for (int32_t State : Iter->second)
2778       undoState(FrameInstructions[State]);
2779   }
2780 
2781   return NewStates;
2782 }
2783 
2784 void BinaryFunction::normalizeCFIState() {
2785   // Reordering blocks with remember-restore state instructions can be specially
2786   // tricky. When rewriting the CFI, we omit remember-restore state instructions
2787   // entirely. For restore state, we build a map expanding each restore to the
2788   // equivalent unwindCFIState sequence required at that point to achieve the
2789   // same effect of the restore. All remember state are then just ignored.
2790   std::stack<int32_t> Stack;
2791   for (BinaryBasicBlock *CurBB : BasicBlocksLayout) {
2792     for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2793       if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2794         if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2795           Stack.push(II->getOperand(0).getImm());
2796           continue;
2797         }
2798         if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2799           const int32_t RememberState = Stack.top();
2800           const int32_t CurState = II->getOperand(0).getImm();
2801           FrameRestoreEquivalents[CurState] =
2802               unwindCFIState(CurState, RememberState, CurBB, II);
2803           Stack.pop();
2804         }
2805       }
2806     }
2807   }
2808 }
2809 
2810 bool BinaryFunction::finalizeCFIState() {
2811   LLVM_DEBUG(
2812       dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2813   LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2814                     << ": ");
2815 
2816   int32_t State = 0;
2817   bool SeenCold = false;
2818   const char *Sep = "";
2819   (void)Sep;
2820   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
2821     const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2822 
2823     // Hot-cold border: check if this is the first BB to be allocated in a cold
2824     // region (with a different FDE). If yes, we need to reset the CFI state.
2825     if (!SeenCold && BB->isCold()) {
2826       State = 0;
2827       SeenCold = true;
2828     }
2829 
2830     // We need to recover the correct state if it doesn't match expected
2831     // state at BB entry point.
2832     if (BB->getCFIState() < State) {
2833       // In this case, State is currently higher than what this BB expect it
2834       // to be. To solve this, we need to insert CFI instructions to undo
2835       // the effect of all CFI from BB's state to current State.
2836       auto InsertIt = BB->begin();
2837       unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2838     } else if (BB->getCFIState() > State) {
2839       // If BB's CFI state is greater than State, it means we are behind in the
2840       // state. Just emit all instructions to reach this state at the
2841       // beginning of this BB. If this sequence of instructions involve
2842       // remember state or restore state, bail out.
2843       if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2844         return false;
2845     }
2846 
2847     State = CFIStateAtExit;
2848     LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2849   }
2850   LLVM_DEBUG(dbgs() << "\n");
2851 
2852   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
2853     for (auto II = BB->begin(); II != BB->end();) {
2854       const MCCFIInstruction *CFI = getCFIFor(*II);
2855       if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2856                   CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2857         II = BB->eraseInstruction(II);
2858       } else {
2859         ++II;
2860       }
2861     }
2862   }
2863 
2864   return true;
2865 }
2866 
2867 bool BinaryFunction::requiresAddressTranslation() const {
2868   return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2869 }
2870 
2871 uint64_t BinaryFunction::getInstructionCount() const {
2872   uint64_t Count = 0;
2873   for (BinaryBasicBlock *const &Block : BasicBlocksLayout)
2874     Count += Block->getNumNonPseudos();
2875   return Count;
2876 }
2877 
2878 bool BinaryFunction::hasLayoutChanged() const { return ModifiedLayout; }
2879 
2880 uint64_t BinaryFunction::getEditDistance() const {
2881   return ComputeEditDistance<BinaryBasicBlock *>(BasicBlocksPreviousLayout,
2882                                                  BasicBlocksLayout);
2883 }
2884 
2885 void BinaryFunction::clearDisasmState() {
2886   clearList(Instructions);
2887   clearList(IgnoredBranches);
2888   clearList(TakenBranches);
2889   clearList(InterproceduralReferences);
2890 
2891   if (BC.HasRelocations) {
2892     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
2893       BC.UndefinedSymbols.insert(LI.second);
2894     if (FunctionEndLabel)
2895       BC.UndefinedSymbols.insert(FunctionEndLabel);
2896   }
2897 }
2898 
2899 void BinaryFunction::setTrapOnEntry() {
2900   clearDisasmState();
2901 
2902   auto addTrapAtOffset = [&](uint64_t Offset) {
2903     MCInst TrapInstr;
2904     BC.MIB->createTrap(TrapInstr);
2905     addInstruction(Offset, std::move(TrapInstr));
2906   };
2907 
2908   addTrapAtOffset(0);
2909   for (const std::pair<const uint32_t, MCSymbol *> &KV : getLabels())
2910     if (getSecondaryEntryPointSymbol(KV.second))
2911       addTrapAtOffset(KV.first);
2912 
2913   TrapsOnEntry = true;
2914 }
2915 
2916 void BinaryFunction::setIgnored() {
2917   if (opts::processAllFunctions()) {
2918     // We can accept ignored functions before they've been disassembled.
2919     // In that case, they would still get disassembled and emited, but not
2920     // optimized.
2921     assert(CurrentState == State::Empty &&
2922            "cannot ignore non-empty functions in current mode");
2923     IsIgnored = true;
2924     return;
2925   }
2926 
2927   clearDisasmState();
2928 
2929   // Clear CFG state too.
2930   if (hasCFG()) {
2931     releaseCFG();
2932 
2933     for (BinaryBasicBlock *BB : BasicBlocks)
2934       delete BB;
2935     clearList(BasicBlocks);
2936 
2937     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
2938       delete BB;
2939     clearList(DeletedBasicBlocks);
2940 
2941     clearList(BasicBlocksLayout);
2942     clearList(BasicBlocksPreviousLayout);
2943   }
2944 
2945   CurrentState = State::Empty;
2946 
2947   IsIgnored = true;
2948   IsSimple = false;
2949   LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
2950 }
2951 
2952 void BinaryFunction::duplicateConstantIslands() {
2953   assert(Islands && "function expected to have constant islands");
2954 
2955   for (BinaryBasicBlock *BB : layout()) {
2956     if (!BB->isCold())
2957       continue;
2958 
2959     for (MCInst &Inst : *BB) {
2960       int OpNum = 0;
2961       for (MCOperand &Operand : Inst) {
2962         if (!Operand.isExpr()) {
2963           ++OpNum;
2964           continue;
2965         }
2966         const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
2967         // Check if this is an island symbol
2968         if (!Islands->Symbols.count(Symbol) &&
2969             !Islands->ProxySymbols.count(Symbol))
2970           continue;
2971 
2972         // Create cold symbol, if missing
2973         auto ISym = Islands->ColdSymbols.find(Symbol);
2974         MCSymbol *ColdSymbol;
2975         if (ISym != Islands->ColdSymbols.end()) {
2976           ColdSymbol = ISym->second;
2977         } else {
2978           ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
2979           Islands->ColdSymbols[Symbol] = ColdSymbol;
2980           // Check if this is a proxy island symbol and update owner proxy map
2981           if (Islands->ProxySymbols.count(Symbol)) {
2982             BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
2983             auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
2984             Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
2985           }
2986         }
2987 
2988         // Update instruction reference
2989         Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
2990             Inst,
2991             MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
2992                                     *BC.Ctx),
2993             *BC.Ctx, 0));
2994         ++OpNum;
2995       }
2996     }
2997   }
2998 }
2999 
3000 namespace {
3001 
3002 #ifndef MAX_PATH
3003 #define MAX_PATH 255
3004 #endif
3005 
3006 std::string constructFilename(std::string Filename, std::string Annotation,
3007                               std::string Suffix) {
3008   std::replace(Filename.begin(), Filename.end(), '/', '-');
3009   if (!Annotation.empty())
3010     Annotation.insert(0, "-");
3011   if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
3012     assert(Suffix.size() + Annotation.size() <= MAX_PATH);
3013     if (opts::Verbosity >= 1) {
3014       errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix
3015              << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n";
3016     }
3017     Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
3018   }
3019   Filename += Annotation;
3020   Filename += Suffix;
3021   return Filename;
3022 }
3023 
3024 std::string formatEscapes(const std::string &Str) {
3025   std::string Result;
3026   for (unsigned I = 0; I < Str.size(); ++I) {
3027     char C = Str[I];
3028     switch (C) {
3029     case '\n':
3030       Result += "&#13;";
3031       break;
3032     case '"':
3033       break;
3034     default:
3035       Result += C;
3036       break;
3037     }
3038   }
3039   return Result;
3040 }
3041 
3042 } // namespace
3043 
3044 void BinaryFunction::dumpGraph(raw_ostream &OS) const {
3045   OS << "strict digraph \"" << getPrintName() << "\" {\n";
3046   uint64_t Offset = Address;
3047   for (BinaryBasicBlock *BB : BasicBlocks) {
3048     auto LayoutPos =
3049         std::find(BasicBlocksLayout.begin(), BasicBlocksLayout.end(), BB);
3050     unsigned Layout = LayoutPos - BasicBlocksLayout.begin();
3051     const char *ColdStr = BB->isCold() ? " (cold)" : "";
3052     OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u:CFI:%u)\"]\n",
3053                  BB->getName().data(), BB->getName().data(), ColdStr,
3054                  (BB->ExecutionCount != BinaryBasicBlock::COUNT_NO_PROFILE
3055                       ? BB->ExecutionCount
3056                       : 0),
3057                  BB->getOffset(), getIndex(BB), Layout, BB->getCFIState());
3058     OS << format("\"%s\" [shape=box]\n", BB->getName().data());
3059     if (opts::DotToolTipCode) {
3060       std::string Str;
3061       raw_string_ostream CS(Str);
3062       Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this);
3063       const std::string Code = formatEscapes(CS.str());
3064       OS << format("\"%s\" [tooltip=\"%s\"]\n", BB->getName().data(),
3065                    Code.c_str());
3066     }
3067 
3068     // analyzeBranch is just used to get the names of the branch
3069     // opcodes.
3070     const MCSymbol *TBB = nullptr;
3071     const MCSymbol *FBB = nullptr;
3072     MCInst *CondBranch = nullptr;
3073     MCInst *UncondBranch = nullptr;
3074     const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3075 
3076     const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3077     const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3078 
3079     auto BI = BB->branch_info_begin();
3080     for (BinaryBasicBlock *Succ : BB->successors()) {
3081       std::string Branch;
3082       if (Success) {
3083         if (Succ == BB->getConditionalSuccessor(true)) {
3084           Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3085                                     CondBranch->getOpcode()))
3086                               : "TB";
3087         } else if (Succ == BB->getConditionalSuccessor(false)) {
3088           Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3089                                       UncondBranch->getOpcode()))
3090                                 : "FB";
3091         } else {
3092           Branch = "FT";
3093         }
3094       }
3095       if (IsJumpTable)
3096         Branch = "JT";
3097       OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
3098                    Succ->getName().data(), Branch.c_str());
3099 
3100       if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3101           BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3102         OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3103       } else if (ExecutionCount != COUNT_NO_PROFILE &&
3104                  BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3105         OS << "\\n(IC:" << BI->Count << ")";
3106       }
3107       OS << "\"]\n";
3108 
3109       ++BI;
3110     }
3111     for (BinaryBasicBlock *LP : BB->landing_pads()) {
3112       OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3113                    BB->getName().data(), LP->getName().data());
3114     }
3115   }
3116   OS << "}\n";
3117 }
3118 
3119 void BinaryFunction::viewGraph() const {
3120   SmallString<MAX_PATH> Filename;
3121   if (std::error_code EC =
3122           sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
3123     errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3124            << " bolt-cfg-XXXXX.dot temporary file.\n";
3125     return;
3126   }
3127   dumpGraphToFile(std::string(Filename));
3128   if (DisplayGraph(Filename))
3129     errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n";
3130   if (std::error_code EC = sys::fs::remove(Filename)) {
3131     errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3132            << Filename << "\n";
3133   }
3134 }
3135 
3136 void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3137   std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3138   outs() << "BOLT-DEBUG: Dumping CFG to " << Filename << "\n";
3139   dumpGraphToFile(Filename);
3140 }
3141 
3142 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3143   std::error_code EC;
3144   raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3145   if (EC) {
3146     if (opts::Verbosity >= 1) {
3147       errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3148              << Filename << " for output.\n";
3149     }
3150     return;
3151   }
3152   dumpGraph(of);
3153 }
3154 
3155 bool BinaryFunction::validateCFG() const {
3156   bool Valid = true;
3157   for (BinaryBasicBlock *BB : BasicBlocks)
3158     Valid &= BB->validateSuccessorInvariants();
3159 
3160   if (!Valid)
3161     return Valid;
3162 
3163   // Make sure all blocks in CFG are valid.
3164   auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3165     if (!BB->isValid()) {
3166       errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3167              << " detected in:\n";
3168       this->dump();
3169       return false;
3170     }
3171     return true;
3172   };
3173   for (const BinaryBasicBlock *BB : BasicBlocks) {
3174     if (!validateBlock(BB, "block"))
3175       return false;
3176     for (const BinaryBasicBlock *PredBB : BB->predecessors())
3177       if (!validateBlock(PredBB, "predecessor"))
3178         return false;
3179     for (const BinaryBasicBlock *SuccBB : BB->successors())
3180       if (!validateBlock(SuccBB, "successor"))
3181         return false;
3182     for (const BinaryBasicBlock *LP : BB->landing_pads())
3183       if (!validateBlock(LP, "landing pad"))
3184         return false;
3185     for (const BinaryBasicBlock *Thrower : BB->throwers())
3186       if (!validateBlock(Thrower, "thrower"))
3187         return false;
3188   }
3189 
3190   for (const BinaryBasicBlock *BB : BasicBlocks) {
3191     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3192     for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3193       if (BBLandingPads.count(LP)) {
3194         errs() << "BOLT-ERROR: duplicate landing pad detected in"
3195                << BB->getName() << " in function " << *this << '\n';
3196         return false;
3197       }
3198       BBLandingPads.insert(LP);
3199     }
3200 
3201     std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3202     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3203       if (BBThrowers.count(Thrower)) {
3204         errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3205                << " in function " << *this << '\n';
3206         return false;
3207       }
3208       BBThrowers.insert(Thrower);
3209     }
3210 
3211     for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3212       if (std::find(LPBlock->throw_begin(), LPBlock->throw_end(), BB) ==
3213           LPBlock->throw_end()) {
3214         errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3215                << ": " << BB->getName() << " is in LandingPads but not in "
3216                << LPBlock->getName() << " Throwers\n";
3217         return false;
3218       }
3219     }
3220     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3221       if (std::find(Thrower->lp_begin(), Thrower->lp_end(), BB) ==
3222           Thrower->lp_end()) {
3223         errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3224                << ": " << BB->getName() << " is in Throwers list but not in "
3225                << Thrower->getName() << " LandingPads\n";
3226         return false;
3227       }
3228     }
3229   }
3230 
3231   return Valid;
3232 }
3233 
3234 void BinaryFunction::fixBranches() {
3235   auto &MIB = BC.MIB;
3236   MCContext *Ctx = BC.Ctx.get();
3237 
3238   for (unsigned I = 0, E = BasicBlocksLayout.size(); I != E; ++I) {
3239     BinaryBasicBlock *BB = BasicBlocksLayout[I];
3240     const MCSymbol *TBB = nullptr;
3241     const MCSymbol *FBB = nullptr;
3242     MCInst *CondBranch = nullptr;
3243     MCInst *UncondBranch = nullptr;
3244     if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3245       continue;
3246 
3247     // We will create unconditional branch with correct destination if needed.
3248     if (UncondBranch)
3249       BB->eraseInstruction(BB->findInstruction(UncondBranch));
3250 
3251     // Basic block that follows the current one in the final layout.
3252     const BinaryBasicBlock *NextBB = nullptr;
3253     if (I + 1 != E && BB->isCold() == BasicBlocksLayout[I + 1]->isCold())
3254       NextBB = BasicBlocksLayout[I + 1];
3255 
3256     if (BB->succ_size() == 1) {
3257       // __builtin_unreachable() could create a conditional branch that
3258       // falls-through into the next function - hence the block will have only
3259       // one valid successor. Since behaviour is undefined - we replace
3260       // the conditional branch with an unconditional if required.
3261       if (CondBranch)
3262         BB->eraseInstruction(BB->findInstruction(CondBranch));
3263       if (BB->getSuccessor() == NextBB)
3264         continue;
3265       BB->addBranchInstruction(BB->getSuccessor());
3266     } else if (BB->succ_size() == 2) {
3267       assert(CondBranch && "conditional branch expected");
3268       const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3269       const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3270       // Check whether we support reversing this branch direction
3271       const bool IsSupported =
3272           !MIB->isUnsupportedBranch(CondBranch->getOpcode());
3273       if (NextBB && NextBB == TSuccessor && IsSupported) {
3274         std::swap(TSuccessor, FSuccessor);
3275         {
3276           auto L = BC.scopeLock();
3277           MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3278         }
3279         BB->swapConditionalSuccessors();
3280       } else {
3281         auto L = BC.scopeLock();
3282         MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3283       }
3284       if (TSuccessor == FSuccessor)
3285         BB->removeDuplicateConditionalSuccessor(CondBranch);
3286       if (!NextBB ||
3287           ((NextBB != TSuccessor || !IsSupported) && NextBB != FSuccessor)) {
3288         // If one of the branches is guaranteed to be "long" while the other
3289         // could be "short", then prioritize short for "taken". This will
3290         // generate a sequence 1 byte shorter on x86.
3291         if (IsSupported && BC.isX86() &&
3292             TSuccessor->isCold() != FSuccessor->isCold() &&
3293             BB->isCold() != TSuccessor->isCold()) {
3294           std::swap(TSuccessor, FSuccessor);
3295           {
3296             auto L = BC.scopeLock();
3297             MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(),
3298                                         Ctx);
3299           }
3300           BB->swapConditionalSuccessors();
3301         }
3302         BB->addBranchInstruction(FSuccessor);
3303       }
3304     }
3305     // Cases where the number of successors is 0 (block ends with a
3306     // terminator) or more than 2 (switch table) don't require branch
3307     // instruction adjustments.
3308   }
3309   assert((!isSimple() || validateCFG()) &&
3310          "Invalid CFG detected after fixing branches");
3311 }
3312 
3313 void BinaryFunction::propagateGnuArgsSizeInfo(
3314     MCPlusBuilder::AllocatorIdTy AllocId) {
3315   assert(CurrentState == State::Disassembled && "unexpected function state");
3316 
3317   if (!hasEHRanges() || !usesGnuArgsSize())
3318     return;
3319 
3320   // The current value of DW_CFA_GNU_args_size affects all following
3321   // invoke instructions until the next CFI overrides it.
3322   // It is important to iterate basic blocks in the original order when
3323   // assigning the value.
3324   uint64_t CurrentGnuArgsSize = 0;
3325   for (BinaryBasicBlock *BB : BasicBlocks) {
3326     for (auto II = BB->begin(); II != BB->end();) {
3327       MCInst &Instr = *II;
3328       if (BC.MIB->isCFI(Instr)) {
3329         const MCCFIInstruction *CFI = getCFIFor(Instr);
3330         if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3331           CurrentGnuArgsSize = CFI->getOffset();
3332           // Delete DW_CFA_GNU_args_size instructions and only regenerate
3333           // during the final code emission. The information is embedded
3334           // inside call instructions.
3335           II = BB->erasePseudoInstruction(II);
3336           continue;
3337         }
3338       } else if (BC.MIB->isInvoke(Instr)) {
3339         // Add the value of GNU_args_size as an extra operand to invokes.
3340         BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize, AllocId);
3341       }
3342       ++II;
3343     }
3344   }
3345 }
3346 
3347 void BinaryFunction::postProcessBranches() {
3348   if (!isSimple())
3349     return;
3350   for (BinaryBasicBlock *BB : BasicBlocksLayout) {
3351     auto LastInstrRI = BB->getLastNonPseudo();
3352     if (BB->succ_size() == 1) {
3353       if (LastInstrRI != BB->rend() &&
3354           BC.MIB->isConditionalBranch(*LastInstrRI)) {
3355         // __builtin_unreachable() could create a conditional branch that
3356         // falls-through into the next function - hence the block will have only
3357         // one valid successor. Such behaviour is undefined and thus we remove
3358         // the conditional branch while leaving a valid successor.
3359         BB->eraseInstruction(std::prev(LastInstrRI.base()));
3360         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3361                           << BB->getName() << " in function " << *this << '\n');
3362       }
3363     } else if (BB->succ_size() == 0) {
3364       // Ignore unreachable basic blocks.
3365       if (BB->pred_size() == 0 || BB->isLandingPad())
3366         continue;
3367 
3368       // If it's the basic block that does not end up with a terminator - we
3369       // insert a return instruction unless it's a call instruction.
3370       if (LastInstrRI == BB->rend()) {
3371         LLVM_DEBUG(
3372             dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3373                    << BB->getName() << " in function " << *this << '\n');
3374         continue;
3375       }
3376       if (!BC.MIB->isTerminator(*LastInstrRI) &&
3377           !BC.MIB->isCall(*LastInstrRI)) {
3378         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3379                           << BB->getName() << " in function " << *this << '\n');
3380         MCInst ReturnInstr;
3381         BC.MIB->createReturn(ReturnInstr);
3382         BB->addInstruction(ReturnInstr);
3383       }
3384     }
3385   }
3386   assert(validateCFG() && "invalid CFG");
3387 }
3388 
3389 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3390   assert(Offset && "cannot add primary entry point");
3391   assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3392 
3393   const uint64_t EntryPointAddress = getAddress() + Offset;
3394   MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3395 
3396   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3397   if (EntrySymbol)
3398     return EntrySymbol;
3399 
3400   if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3401     EntrySymbol = EntryBD->getSymbol();
3402   } else {
3403     EntrySymbol = BC.getOrCreateGlobalSymbol(
3404         EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3405   }
3406   SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3407 
3408   BC.setSymbolToFunctionMap(EntrySymbol, this);
3409 
3410   return EntrySymbol;
3411 }
3412 
3413 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3414   assert(CurrentState == State::CFG &&
3415          "basic block can be added as an entry only in a function with CFG");
3416 
3417   if (&BB == BasicBlocks.front())
3418     return getSymbol();
3419 
3420   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3421   if (EntrySymbol)
3422     return EntrySymbol;
3423 
3424   EntrySymbol =
3425       BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3426 
3427   SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3428 
3429   BC.setSymbolToFunctionMap(EntrySymbol, this);
3430 
3431   return EntrySymbol;
3432 }
3433 
3434 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3435   if (EntryID == 0)
3436     return getSymbol();
3437 
3438   if (!isMultiEntry())
3439     return nullptr;
3440 
3441   uint64_t NumEntries = 0;
3442   if (hasCFG()) {
3443     for (BinaryBasicBlock *BB : BasicBlocks) {
3444       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3445       if (!EntrySymbol)
3446         continue;
3447       if (NumEntries == EntryID)
3448         return EntrySymbol;
3449       ++NumEntries;
3450     }
3451   } else {
3452     for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3453       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3454       if (!EntrySymbol)
3455         continue;
3456       if (NumEntries == EntryID)
3457         return EntrySymbol;
3458       ++NumEntries;
3459     }
3460   }
3461 
3462   return nullptr;
3463 }
3464 
3465 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3466   if (!isMultiEntry())
3467     return 0;
3468 
3469   for (const MCSymbol *FunctionSymbol : getSymbols())
3470     if (FunctionSymbol == Symbol)
3471       return 0;
3472 
3473   // Check all secondary entries available as either basic blocks or lables.
3474   uint64_t NumEntries = 0;
3475   for (const BinaryBasicBlock *BB : BasicBlocks) {
3476     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3477     if (!EntrySymbol)
3478       continue;
3479     if (EntrySymbol == Symbol)
3480       return NumEntries;
3481     ++NumEntries;
3482   }
3483   NumEntries = 0;
3484   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3485     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3486     if (!EntrySymbol)
3487       continue;
3488     if (EntrySymbol == Symbol)
3489       return NumEntries;
3490     ++NumEntries;
3491   }
3492 
3493   llvm_unreachable("symbol not found");
3494 }
3495 
3496 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3497   bool Status = Callback(0, getSymbol());
3498   if (!isMultiEntry())
3499     return Status;
3500 
3501   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3502     if (!Status)
3503       break;
3504 
3505     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3506     if (!EntrySymbol)
3507       continue;
3508 
3509     Status = Callback(KV.first, EntrySymbol);
3510   }
3511 
3512   return Status;
3513 }
3514 
3515 BinaryFunction::BasicBlockOrderType BinaryFunction::dfs() const {
3516   BasicBlockOrderType DFS;
3517   unsigned Index = 0;
3518   std::stack<BinaryBasicBlock *> Stack;
3519 
3520   // Push entry points to the stack in reverse order.
3521   //
3522   // NB: we rely on the original order of entries to match.
3523   for (auto BBI = layout_rbegin(); BBI != layout_rend(); ++BBI) {
3524     BinaryBasicBlock *BB = *BBI;
3525     if (isEntryPoint(*BB))
3526       Stack.push(BB);
3527     BB->setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3528   }
3529 
3530   while (!Stack.empty()) {
3531     BinaryBasicBlock *BB = Stack.top();
3532     Stack.pop();
3533 
3534     if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3535       continue;
3536 
3537     BB->setLayoutIndex(Index++);
3538     DFS.push_back(BB);
3539 
3540     for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3541       Stack.push(SuccBB);
3542     }
3543 
3544     const MCSymbol *TBB = nullptr;
3545     const MCSymbol *FBB = nullptr;
3546     MCInst *CondBranch = nullptr;
3547     MCInst *UncondBranch = nullptr;
3548     if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3549         BB->succ_size() == 2) {
3550       if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3551               *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3552         Stack.push(BB->getConditionalSuccessor(true));
3553         Stack.push(BB->getConditionalSuccessor(false));
3554       } else {
3555         Stack.push(BB->getConditionalSuccessor(false));
3556         Stack.push(BB->getConditionalSuccessor(true));
3557       }
3558     } else {
3559       for (BinaryBasicBlock *SuccBB : BB->successors()) {
3560         Stack.push(SuccBB);
3561       }
3562     }
3563   }
3564 
3565   return DFS;
3566 }
3567 
3568 size_t BinaryFunction::computeHash(bool UseDFS,
3569                                    OperandHashFuncTy OperandHashFunc) const {
3570   if (size() == 0)
3571     return 0;
3572 
3573   assert(hasCFG() && "function is expected to have CFG");
3574 
3575   const BasicBlockOrderType &Order = UseDFS ? dfs() : BasicBlocksLayout;
3576 
3577   // The hash is computed by creating a string of all instruction opcodes and
3578   // possibly their operands and then hashing that string with std::hash.
3579   std::string HashString;
3580   for (const BinaryBasicBlock *BB : Order) {
3581     for (const MCInst &Inst : *BB) {
3582       unsigned Opcode = Inst.getOpcode();
3583 
3584       if (BC.MIB->isPseudo(Inst))
3585         continue;
3586 
3587       // Ignore unconditional jumps since we check CFG consistency by processing
3588       // basic blocks in order and do not rely on branches to be in-sync with
3589       // CFG. Note that we still use condition code of conditional jumps.
3590       if (BC.MIB->isUnconditionalBranch(Inst))
3591         continue;
3592 
3593       if (Opcode == 0)
3594         HashString.push_back(0);
3595 
3596       while (Opcode) {
3597         uint8_t LSB = Opcode & 0xff;
3598         HashString.push_back(LSB);
3599         Opcode = Opcode >> 8;
3600       }
3601 
3602       for (unsigned I = 0, E = MCPlus::getNumPrimeOperands(Inst); I != E; ++I)
3603         HashString.append(OperandHashFunc(Inst.getOperand(I)));
3604     }
3605   }
3606 
3607   return Hash = std::hash<std::string>{}(HashString);
3608 }
3609 
3610 void BinaryFunction::insertBasicBlocks(
3611     BinaryBasicBlock *Start,
3612     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3613     const bool UpdateLayout, const bool UpdateCFIState,
3614     const bool RecomputeLandingPads) {
3615   const auto StartIndex = Start ? getIndex(Start) : -1;
3616   const size_t NumNewBlocks = NewBBs.size();
3617 
3618   BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3619                      nullptr);
3620 
3621   auto I = StartIndex + 1;
3622   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3623     assert(!BasicBlocks[I]);
3624     BasicBlocks[I++] = BB.release();
3625   }
3626 
3627   if (RecomputeLandingPads)
3628     recomputeLandingPads();
3629   else
3630     updateBBIndices(0);
3631 
3632   if (UpdateLayout)
3633     updateLayout(Start, NumNewBlocks);
3634 
3635   if (UpdateCFIState)
3636     updateCFIState(Start, NumNewBlocks);
3637 }
3638 
3639 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3640     BinaryFunction::iterator StartBB,
3641     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3642     const bool UpdateLayout, const bool UpdateCFIState,
3643     const bool RecomputeLandingPads) {
3644   const unsigned StartIndex = getIndex(&*StartBB);
3645   const size_t NumNewBlocks = NewBBs.size();
3646 
3647   BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3648                      nullptr);
3649   auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3650 
3651   unsigned I = StartIndex + 1;
3652   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3653     assert(!BasicBlocks[I]);
3654     BasicBlocks[I++] = BB.release();
3655   }
3656 
3657   if (RecomputeLandingPads)
3658     recomputeLandingPads();
3659   else
3660     updateBBIndices(0);
3661 
3662   if (UpdateLayout)
3663     updateLayout(*std::prev(RetIter), NumNewBlocks);
3664 
3665   if (UpdateCFIState)
3666     updateCFIState(*std::prev(RetIter), NumNewBlocks);
3667 
3668   return RetIter;
3669 }
3670 
3671 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3672   for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3673     BasicBlocks[I]->Index = I;
3674 }
3675 
3676 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3677                                     const unsigned NumNewBlocks) {
3678   const int32_t CFIState = Start->getCFIStateAtExit();
3679   const unsigned StartIndex = getIndex(Start) + 1;
3680   for (unsigned I = 0; I < NumNewBlocks; ++I)
3681     BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3682 }
3683 
3684 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3685                                   const unsigned NumNewBlocks) {
3686   // If start not provided insert new blocks at the beginning
3687   if (!Start) {
3688     BasicBlocksLayout.insert(layout_begin(), BasicBlocks.begin(),
3689                              BasicBlocks.begin() + NumNewBlocks);
3690     updateLayoutIndices();
3691     return;
3692   }
3693 
3694   // Insert new blocks in the layout immediately after Start.
3695   auto Pos = std::find(layout_begin(), layout_end(), Start);
3696   assert(Pos != layout_end());
3697   BasicBlockListType::iterator Begin =
3698       std::next(BasicBlocks.begin(), getIndex(Start) + 1);
3699   BasicBlockListType::iterator End =
3700       std::next(BasicBlocks.begin(), getIndex(Start) + NumNewBlocks + 1);
3701   BasicBlocksLayout.insert(Pos + 1, Begin, End);
3702   updateLayoutIndices();
3703 }
3704 
3705 bool BinaryFunction::checkForAmbiguousJumpTables() {
3706   SmallSet<uint64_t, 4> JumpTables;
3707   for (BinaryBasicBlock *&BB : BasicBlocks) {
3708     for (MCInst &Inst : *BB) {
3709       if (!BC.MIB->isIndirectBranch(Inst))
3710         continue;
3711       uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3712       if (!JTAddress)
3713         continue;
3714       // This address can be inside another jump table, but we only consider
3715       // it ambiguous when the same start address is used, not the same JT
3716       // object.
3717       if (!JumpTables.count(JTAddress)) {
3718         JumpTables.insert(JTAddress);
3719         continue;
3720       }
3721       return true;
3722     }
3723   }
3724   return false;
3725 }
3726 
3727 void BinaryFunction::disambiguateJumpTables(
3728     MCPlusBuilder::AllocatorIdTy AllocId) {
3729   assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3730   SmallPtrSet<JumpTable *, 4> JumpTables;
3731   for (BinaryBasicBlock *&BB : BasicBlocks) {
3732     for (MCInst &Inst : *BB) {
3733       if (!BC.MIB->isIndirectBranch(Inst))
3734         continue;
3735       JumpTable *JT = getJumpTable(Inst);
3736       if (!JT)
3737         continue;
3738       auto Iter = JumpTables.find(JT);
3739       if (Iter == JumpTables.end()) {
3740         JumpTables.insert(JT);
3741         continue;
3742       }
3743       // This instruction is an indirect jump using a jump table, but it is
3744       // using the same jump table of another jump. Try all our tricks to
3745       // extract the jump table symbol and make it point to a new, duplicated JT
3746       MCPhysReg BaseReg1;
3747       uint64_t Scale;
3748       const MCSymbol *Target;
3749       // In case we match if our first matcher, first instruction is the one to
3750       // patch
3751       MCInst *JTLoadInst = &Inst;
3752       // Try a standard indirect jump matcher, scale 8
3753       std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3754           BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3755                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3756                               /*Offset=*/BC.MIB->matchSymbol(Target));
3757       if (!IndJmpMatcher->match(
3758               *BC.MRI, *BC.MIB,
3759               MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3760           BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3761         MCPhysReg BaseReg2;
3762         uint64_t Offset;
3763         // Standard JT matching failed. Trying now:
3764         //     movq  "jt.2397/1"(,%rax,8), %rax
3765         //     jmpq  *%rax
3766         std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3767             BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3768                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3769                               /*Offset=*/BC.MIB->matchSymbol(Target));
3770         MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3771         std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3772             BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3773         if (!IndJmpMatcher2->match(
3774                 *BC.MRI, *BC.MIB,
3775                 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3776             BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3777           // JT matching failed. Trying now:
3778           // PIC-style matcher, scale 4
3779           //    addq    %rdx, %rsi
3780           //    addq    %rdx, %rdi
3781           //    leaq    DATAat0x402450(%rip), %r11
3782           //    movslq  (%r11,%rdx,4), %rcx
3783           //    addq    %r11, %rcx
3784           //    jmpq    *%rcx # JUMPTABLE @0x402450
3785           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3786               BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3787                   BC.MIB->matchReg(BaseReg1),
3788                   BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3789                                     BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3790                                     BC.MIB->matchImm(Offset))));
3791           std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3792               BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3793           MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3794           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3795               BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3796                                                    BC.MIB->matchAnyOperand()));
3797           if (!PICIndJmpMatcher->match(
3798                   *BC.MRI, *BC.MIB,
3799                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3800               Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3801               !PICBaseAddrMatcher->match(
3802                   *BC.MRI, *BC.MIB,
3803                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3804             llvm_unreachable("Failed to extract jump table base");
3805             continue;
3806           }
3807           // Matched PIC, identify the instruction with the reference to the JT
3808           JTLoadInst = LEAMatcher->CurInst;
3809         } else {
3810           // Matched non-PIC
3811           JTLoadInst = LoadMatcher->CurInst;
3812         }
3813       }
3814 
3815       uint64_t NewJumpTableID = 0;
3816       const MCSymbol *NewJTLabel;
3817       std::tie(NewJumpTableID, NewJTLabel) =
3818           BC.duplicateJumpTable(*this, JT, Target);
3819       {
3820         auto L = BC.scopeLock();
3821         BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3822       }
3823       // We use a unique ID with the high bit set as address for this "injected"
3824       // jump table (not originally in the input binary).
3825       BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3826     }
3827   }
3828 }
3829 
3830 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3831                                              BinaryBasicBlock *OldDest,
3832                                              BinaryBasicBlock *NewDest) {
3833   MCInst *Instr = BB->getLastNonPseudoInstr();
3834   if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3835     return false;
3836   uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3837   assert(JTAddress && "Invalid jump table address");
3838   JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3839   assert(JT && "No jump table structure for this indirect branch");
3840   bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3841                                         NewDest->getLabel());
3842   (void)Patched;
3843   assert(Patched && "Invalid entry to be replaced in jump table");
3844   return true;
3845 }
3846 
3847 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3848                                             BinaryBasicBlock *To) {
3849   // Create intermediate BB
3850   MCSymbol *Tmp;
3851   {
3852     auto L = BC.scopeLock();
3853     Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3854   }
3855   // Link new BBs to the original input offset of the From BB, so we can map
3856   // samples recorded in new BBs back to the original BB seem in the input
3857   // binary (if using BAT)
3858   std::unique_ptr<BinaryBasicBlock> NewBB =
3859       createBasicBlock(From->getInputOffset(), Tmp);
3860   BinaryBasicBlock *NewBBPtr = NewBB.get();
3861 
3862   // Update "From" BB
3863   auto I = From->succ_begin();
3864   auto BI = From->branch_info_begin();
3865   for (; I != From->succ_end(); ++I) {
3866     if (*I == To)
3867       break;
3868     ++BI;
3869   }
3870   assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3871   uint64_t OrigCount = BI->Count;
3872   uint64_t OrigMispreds = BI->MispredictedCount;
3873   replaceJumpTableEntryIn(From, To, NewBBPtr);
3874   From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3875 
3876   NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3877   NewBB->setExecutionCount(OrigCount);
3878   NewBB->setIsCold(From->isCold());
3879 
3880   // Update CFI and BB layout with new intermediate BB
3881   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3882   NewBBs.emplace_back(std::move(NewBB));
3883   insertBasicBlocks(From, std::move(NewBBs), true, true,
3884                     /*RecomputeLandingPads=*/false);
3885   return NewBBPtr;
3886 }
3887 
3888 void BinaryFunction::deleteConservativeEdges() {
3889   // Our goal is to aggressively remove edges from the CFG that we believe are
3890   // wrong. This is used for instrumentation, where it is safe to remove
3891   // fallthrough edges because we won't reorder blocks.
3892   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3893     BinaryBasicBlock *BB = *I;
3894     if (BB->succ_size() != 1 || BB->size() == 0)
3895       continue;
3896 
3897     auto NextBB = std::next(I);
3898     MCInst *Last = BB->getLastNonPseudoInstr();
3899     // Fallthrough is a landing pad? Delete this edge (as long as we don't
3900     // have a direct jump to it)
3901     if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3902         *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3903       BB->removeAllSuccessors();
3904       continue;
3905     }
3906 
3907     // Look for suspicious calls at the end of BB where gcc may optimize it and
3908     // remove the jump to the epilogue when it knows the call won't return.
3909     if (!Last || !BC.MIB->isCall(*Last))
3910       continue;
3911 
3912     const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3913     if (!CalleeSymbol)
3914       continue;
3915 
3916     StringRef CalleeName = CalleeSymbol->getName();
3917     if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3918         CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3919         CalleeName != "abort@PLT")
3920       continue;
3921 
3922     BB->removeAllSuccessors();
3923   }
3924 }
3925 
3926 bool BinaryFunction::isDataMarker(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). $d identifies a symbol starting data contents.
3930   if (BC.isAArch64() && Symbol.getType() &&
3931       cantFail(Symbol.getType()) == SymbolRef::ST_Unknown && SymbolSize == 0 &&
3932       Symbol.getName() &&
3933       (cantFail(Symbol.getName()) == "$d" ||
3934        cantFail(Symbol.getName()).startswith("$d.")))
3935     return true;
3936   return false;
3937 }
3938 
3939 bool BinaryFunction::isCodeMarker(const SymbolRef &Symbol,
3940                                   uint64_t SymbolSize) const {
3941   // For aarch64, the ABI defines mapping symbols so we identify data in the
3942   // code section (see IHI0056B). $x identifies a symbol starting code or the
3943   // end of a data chunk inside code.
3944   if (BC.isAArch64() && Symbol.getType() &&
3945       cantFail(Symbol.getType()) == SymbolRef::ST_Unknown && SymbolSize == 0 &&
3946       Symbol.getName() &&
3947       (cantFail(Symbol.getName()) == "$x" ||
3948        cantFail(Symbol.getName()).startswith("$x.")))
3949     return true;
3950   return false;
3951 }
3952 
3953 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3954                                           uint64_t SymbolSize) const {
3955   // If this symbol is in a different section from the one where the
3956   // function symbol is, don't consider it as valid.
3957   if (!getOriginSection()->containsAddress(
3958           cantFail(Symbol.getAddress(), "cannot get symbol address")))
3959     return false;
3960 
3961   // Some symbols are tolerated inside function bodies, others are not.
3962   // The real function boundaries may not be known at this point.
3963   if (isDataMarker(Symbol, SymbolSize) || isCodeMarker(Symbol, SymbolSize))
3964     return true;
3965 
3966   // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3967   // function.
3968   if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3969     return true;
3970 
3971   if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3972     return false;
3973 
3974   if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
3975     return false;
3976 
3977   return true;
3978 }
3979 
3980 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
3981   if (getKnownExecutionCount() == 0 || Count == 0)
3982     return;
3983 
3984   if (ExecutionCount < Count)
3985     Count = ExecutionCount;
3986 
3987   double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
3988   if (AdjustmentRatio < 0.0)
3989     AdjustmentRatio = 0.0;
3990 
3991   for (BinaryBasicBlock *&BB : layout())
3992     BB->adjustExecutionCount(AdjustmentRatio);
3993 
3994   ExecutionCount -= Count;
3995 }
3996 
3997 BinaryFunction::~BinaryFunction() {
3998   for (BinaryBasicBlock *BB : BasicBlocks)
3999     delete BB;
4000   for (BinaryBasicBlock *BB : DeletedBasicBlocks)
4001     delete BB;
4002 }
4003 
4004 void BinaryFunction::calculateLoopInfo() {
4005   // Discover loops.
4006   BinaryDominatorTree DomTree;
4007   DomTree.recalculate(*this);
4008   BLI.reset(new BinaryLoopInfo());
4009   BLI->analyze(DomTree);
4010 
4011   // Traverse discovered loops and add depth and profile information.
4012   std::stack<BinaryLoop *> St;
4013   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
4014     St.push(*I);
4015     ++BLI->OuterLoops;
4016   }
4017 
4018   while (!St.empty()) {
4019     BinaryLoop *L = St.top();
4020     St.pop();
4021     ++BLI->TotalLoops;
4022     BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
4023 
4024     // Add nested loops in the stack.
4025     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4026       St.push(*I);
4027 
4028     // Skip if no valid profile is found.
4029     if (!hasValidProfile()) {
4030       L->EntryCount = COUNT_NO_PROFILE;
4031       L->ExitCount = COUNT_NO_PROFILE;
4032       L->TotalBackEdgeCount = COUNT_NO_PROFILE;
4033       continue;
4034     }
4035 
4036     // Compute back edge count.
4037     SmallVector<BinaryBasicBlock *, 1> Latches;
4038     L->getLoopLatches(Latches);
4039 
4040     for (BinaryBasicBlock *Latch : Latches) {
4041       auto BI = Latch->branch_info_begin();
4042       for (BinaryBasicBlock *Succ : Latch->successors()) {
4043         if (Succ == L->getHeader()) {
4044           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4045                  "profile data not found");
4046           L->TotalBackEdgeCount += BI->Count;
4047         }
4048         ++BI;
4049       }
4050     }
4051 
4052     // Compute entry count.
4053     L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4054 
4055     // Compute exit count.
4056     SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4057     L->getExitEdges(ExitEdges);
4058     for (BinaryLoop::Edge &Exit : ExitEdges) {
4059       const BinaryBasicBlock *Exiting = Exit.first;
4060       const BinaryBasicBlock *ExitTarget = Exit.second;
4061       auto BI = Exiting->branch_info_begin();
4062       for (BinaryBasicBlock *Succ : Exiting->successors()) {
4063         if (Succ == ExitTarget) {
4064           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4065                  "profile data not found");
4066           L->ExitCount += BI->Count;
4067         }
4068         ++BI;
4069       }
4070     }
4071   }
4072 }
4073 
4074 void BinaryFunction::updateOutputValues(const MCAsmLayout &Layout) {
4075   if (!isEmitted()) {
4076     assert(!isInjected() && "injected function should be emitted");
4077     setOutputAddress(getAddress());
4078     setOutputSize(getSize());
4079     return;
4080   }
4081 
4082   const uint64_t BaseAddress = getCodeSection()->getOutputAddress();
4083   ErrorOr<BinarySection &> ColdSection = getColdCodeSection();
4084   const uint64_t ColdBaseAddress =
4085       isSplit() ? ColdSection->getOutputAddress() : 0;
4086   if (BC.HasRelocations || isInjected()) {
4087     const uint64_t StartOffset = Layout.getSymbolOffset(*getSymbol());
4088     const uint64_t EndOffset = Layout.getSymbolOffset(*getFunctionEndLabel());
4089     setOutputAddress(BaseAddress + StartOffset);
4090     setOutputSize(EndOffset - StartOffset);
4091     if (hasConstantIsland()) {
4092       const uint64_t DataOffset =
4093           Layout.getSymbolOffset(*getFunctionConstantIslandLabel());
4094       setOutputDataAddress(BaseAddress + DataOffset);
4095     }
4096     if (isSplit()) {
4097       const MCSymbol *ColdStartSymbol = getColdSymbol();
4098       assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4099              "split function should have defined cold symbol");
4100       const MCSymbol *ColdEndSymbol = getFunctionColdEndLabel();
4101       assert(ColdEndSymbol && ColdEndSymbol->isDefined() &&
4102              "split function should have defined cold end symbol");
4103       const uint64_t ColdStartOffset = Layout.getSymbolOffset(*ColdStartSymbol);
4104       const uint64_t ColdEndOffset = Layout.getSymbolOffset(*ColdEndSymbol);
4105       cold().setAddress(ColdBaseAddress + ColdStartOffset);
4106       cold().setImageSize(ColdEndOffset - ColdStartOffset);
4107       if (hasConstantIsland()) {
4108         const uint64_t DataOffset =
4109             Layout.getSymbolOffset(*getFunctionColdConstantIslandLabel());
4110         setOutputColdDataAddress(ColdBaseAddress + DataOffset);
4111       }
4112     }
4113   } else {
4114     setOutputAddress(getAddress());
4115     setOutputSize(Layout.getSymbolOffset(*getFunctionEndLabel()));
4116   }
4117 
4118   // Update basic block output ranges for the debug info, if we have
4119   // secondary entry points in the symbol table to update or if writing BAT.
4120   if (!opts::UpdateDebugSections && !isMultiEntry() &&
4121       !requiresAddressTranslation())
4122     return;
4123 
4124   // Output ranges should match the input if the body hasn't changed.
4125   if (!isSimple() && !BC.HasRelocations)
4126     return;
4127 
4128   // AArch64 may have functions that only contains a constant island (no code).
4129   if (layout_begin() == layout_end())
4130     return;
4131 
4132   BinaryBasicBlock *PrevBB = nullptr;
4133   for (auto BBI = layout_begin(), BBE = layout_end(); BBI != BBE; ++BBI) {
4134     BinaryBasicBlock *BB = *BBI;
4135     assert(BB->getLabel()->isDefined() && "symbol should be defined");
4136     const uint64_t BBBaseAddress = BB->isCold() ? ColdBaseAddress : BaseAddress;
4137     if (!BC.HasRelocations) {
4138       if (BB->isCold()) {
4139         assert(BBBaseAddress == cold().getAddress());
4140       } else {
4141         assert(BBBaseAddress == getOutputAddress());
4142       }
4143     }
4144     const uint64_t BBOffset = Layout.getSymbolOffset(*BB->getLabel());
4145     const uint64_t BBAddress = BBBaseAddress + BBOffset;
4146     BB->setOutputStartAddress(BBAddress);
4147 
4148     if (PrevBB) {
4149       uint64_t PrevBBEndAddress = BBAddress;
4150       if (BB->isCold() != PrevBB->isCold())
4151         PrevBBEndAddress = getOutputAddress() + getOutputSize();
4152       PrevBB->setOutputEndAddress(PrevBBEndAddress);
4153     }
4154     PrevBB = BB;
4155 
4156     BB->updateOutputValues(Layout);
4157   }
4158   PrevBB->setOutputEndAddress(PrevBB->isCold()
4159                                   ? cold().getAddress() + cold().getImageSize()
4160                                   : getOutputAddress() + getOutputSize());
4161 }
4162 
4163 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4164   DebugAddressRangesVector OutputRanges;
4165 
4166   if (isFolded())
4167     return OutputRanges;
4168 
4169   if (IsFragment)
4170     return OutputRanges;
4171 
4172   OutputRanges.emplace_back(getOutputAddress(),
4173                             getOutputAddress() + getOutputSize());
4174   if (isSplit()) {
4175     assert(isEmitted() && "split function should be emitted");
4176     OutputRanges.emplace_back(cold().getAddress(),
4177                               cold().getAddress() + cold().getImageSize());
4178   }
4179 
4180   if (isSimple())
4181     return OutputRanges;
4182 
4183   for (BinaryFunction *Frag : Fragments) {
4184     assert(!Frag->isSimple() &&
4185            "fragment of non-simple function should also be non-simple");
4186     OutputRanges.emplace_back(Frag->getOutputAddress(),
4187                               Frag->getOutputAddress() + Frag->getOutputSize());
4188   }
4189 
4190   return OutputRanges;
4191 }
4192 
4193 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4194   if (isFolded())
4195     return 0;
4196 
4197   // If the function hasn't changed return the same address.
4198   if (!isEmitted())
4199     return Address;
4200 
4201   if (Address < getAddress())
4202     return 0;
4203 
4204   // Check if the address is associated with an instruction that is tracked
4205   // by address translation.
4206   auto KV = InputOffsetToAddressMap.find(Address - getAddress());
4207   if (KV != InputOffsetToAddressMap.end())
4208     return KV->second;
4209 
4210   // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4211   //        intact. Instead we can use pseudo instructions and/or annotations.
4212   const uint64_t Offset = Address - getAddress();
4213   const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4214   if (!BB) {
4215     // Special case for address immediately past the end of the function.
4216     if (Offset == getSize())
4217       return getOutputAddress() + getOutputSize();
4218 
4219     return 0;
4220   }
4221 
4222   return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4223                   BB->getOutputAddressRange().second);
4224 }
4225 
4226 DebugAddressRangesVector BinaryFunction::translateInputToOutputRanges(
4227     const DWARFAddressRangesVector &InputRanges) const {
4228   DebugAddressRangesVector OutputRanges;
4229 
4230   if (isFolded())
4231     return OutputRanges;
4232 
4233   // If the function hasn't changed return the same ranges.
4234   if (!isEmitted()) {
4235     OutputRanges.resize(InputRanges.size());
4236     std::transform(InputRanges.begin(), InputRanges.end(), OutputRanges.begin(),
4237                    [](const DWARFAddressRange &Range) {
4238                      return DebugAddressRange(Range.LowPC, Range.HighPC);
4239                    });
4240     return OutputRanges;
4241   }
4242 
4243   // Even though we will merge ranges in a post-processing pass, we attempt to
4244   // merge them in a main processing loop as it improves the processing time.
4245   uint64_t PrevEndAddress = 0;
4246   for (const DWARFAddressRange &Range : InputRanges) {
4247     if (!containsAddress(Range.LowPC)) {
4248       LLVM_DEBUG(
4249           dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4250                  << *this << " : [0x" << Twine::utohexstr(Range.LowPC) << ", 0x"
4251                  << Twine::utohexstr(Range.HighPC) << "]\n");
4252       PrevEndAddress = 0;
4253       continue;
4254     }
4255     uint64_t InputOffset = Range.LowPC - getAddress();
4256     const uint64_t InputEndOffset =
4257         std::min(Range.HighPC - getAddress(), getSize());
4258 
4259     auto BBI = std::upper_bound(
4260         BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
4261         BasicBlockOffset(InputOffset, nullptr), CompareBasicBlockOffsets());
4262     --BBI;
4263     do {
4264       const BinaryBasicBlock *BB = BBI->second;
4265       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4266         LLVM_DEBUG(
4267             dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4268                    << *this << " : [0x" << Twine::utohexstr(Range.LowPC)
4269                    << ", 0x" << Twine::utohexstr(Range.HighPC) << "]\n");
4270         PrevEndAddress = 0;
4271         break;
4272       }
4273 
4274       // Skip the range if the block was deleted.
4275       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4276         const uint64_t StartAddress =
4277             OutputStart + InputOffset - BB->getOffset();
4278         uint64_t EndAddress = BB->getOutputAddressRange().second;
4279         if (InputEndOffset < BB->getEndOffset())
4280           EndAddress = StartAddress + InputEndOffset - InputOffset;
4281 
4282         if (StartAddress == PrevEndAddress) {
4283           OutputRanges.back().HighPC =
4284               std::max(OutputRanges.back().HighPC, EndAddress);
4285         } else {
4286           OutputRanges.emplace_back(StartAddress,
4287                                     std::max(StartAddress, EndAddress));
4288         }
4289         PrevEndAddress = OutputRanges.back().HighPC;
4290       }
4291 
4292       InputOffset = BB->getEndOffset();
4293       ++BBI;
4294     } while (InputOffset < InputEndOffset);
4295   }
4296 
4297   // Post-processing pass to sort and merge ranges.
4298   std::sort(OutputRanges.begin(), OutputRanges.end());
4299   DebugAddressRangesVector MergedRanges;
4300   PrevEndAddress = 0;
4301   for (const DebugAddressRange &Range : OutputRanges) {
4302     if (Range.LowPC <= PrevEndAddress) {
4303       MergedRanges.back().HighPC =
4304           std::max(MergedRanges.back().HighPC, Range.HighPC);
4305     } else {
4306       MergedRanges.emplace_back(Range.LowPC, Range.HighPC);
4307     }
4308     PrevEndAddress = MergedRanges.back().HighPC;
4309   }
4310 
4311   return MergedRanges;
4312 }
4313 
4314 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4315   if (CurrentState == State::Disassembled) {
4316     auto II = Instructions.find(Offset);
4317     return (II == Instructions.end()) ? nullptr : &II->second;
4318   } else if (CurrentState == State::CFG) {
4319     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4320     if (!BB)
4321       return nullptr;
4322 
4323     for (MCInst &Inst : *BB) {
4324       constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4325       if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4326         return &Inst;
4327     }
4328 
4329     if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4330       const uint32_t Size =
4331           BC.MIB->getAnnotationWithDefault<uint32_t>(*LastInstr, "Size");
4332       if (BB->getEndOffset() - Offset == Size)
4333         return LastInstr;
4334     }
4335 
4336     return nullptr;
4337   } else {
4338     llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4339   }
4340 }
4341 
4342 DebugLocationsVector BinaryFunction::translateInputToOutputLocationList(
4343     const DebugLocationsVector &InputLL) const {
4344   DebugLocationsVector OutputLL;
4345 
4346   if (isFolded())
4347     return OutputLL;
4348 
4349   // If the function hasn't changed - there's nothing to update.
4350   if (!isEmitted())
4351     return InputLL;
4352 
4353   uint64_t PrevEndAddress = 0;
4354   SmallVectorImpl<uint8_t> *PrevExpr = nullptr;
4355   for (const DebugLocationEntry &Entry : InputLL) {
4356     const uint64_t Start = Entry.LowPC;
4357     const uint64_t End = Entry.HighPC;
4358     if (!containsAddress(Start)) {
4359       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4360                            "for "
4361                         << *this << " : [0x" << Twine::utohexstr(Start)
4362                         << ", 0x" << Twine::utohexstr(End) << "]\n");
4363       continue;
4364     }
4365     uint64_t InputOffset = Start - getAddress();
4366     const uint64_t InputEndOffset = std::min(End - getAddress(), getSize());
4367     auto BBI = std::upper_bound(
4368         BasicBlockOffsets.begin(), BasicBlockOffsets.end(),
4369         BasicBlockOffset(InputOffset, nullptr), CompareBasicBlockOffsets());
4370     --BBI;
4371     do {
4372       const BinaryBasicBlock *BB = BBI->second;
4373       if (InputOffset < BB->getOffset() || InputOffset >= BB->getEndOffset()) {
4374         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: invalid debug address range detected "
4375                              "for "
4376                           << *this << " : [0x" << Twine::utohexstr(Start)
4377                           << ", 0x" << Twine::utohexstr(End) << "]\n");
4378         PrevEndAddress = 0;
4379         break;
4380       }
4381 
4382       // Skip the range if the block was deleted.
4383       if (const uint64_t OutputStart = BB->getOutputAddressRange().first) {
4384         const uint64_t StartAddress =
4385             OutputStart + InputOffset - BB->getOffset();
4386         uint64_t EndAddress = BB->getOutputAddressRange().second;
4387         if (InputEndOffset < BB->getEndOffset())
4388           EndAddress = StartAddress + InputEndOffset - InputOffset;
4389 
4390         if (StartAddress == PrevEndAddress && Entry.Expr == *PrevExpr) {
4391           OutputLL.back().HighPC = std::max(OutputLL.back().HighPC, EndAddress);
4392         } else {
4393           OutputLL.emplace_back(DebugLocationEntry{
4394               StartAddress, std::max(StartAddress, EndAddress), Entry.Expr});
4395         }
4396         PrevEndAddress = OutputLL.back().HighPC;
4397         PrevExpr = &OutputLL.back().Expr;
4398       }
4399 
4400       ++BBI;
4401       InputOffset = BB->getEndOffset();
4402     } while (InputOffset < InputEndOffset);
4403   }
4404 
4405   // Sort and merge adjacent entries with identical location.
4406   std::stable_sort(
4407       OutputLL.begin(), OutputLL.end(),
4408       [](const DebugLocationEntry &A, const DebugLocationEntry &B) {
4409         return A.LowPC < B.LowPC;
4410       });
4411   DebugLocationsVector MergedLL;
4412   PrevEndAddress = 0;
4413   PrevExpr = nullptr;
4414   for (const DebugLocationEntry &Entry : OutputLL) {
4415     if (Entry.LowPC <= PrevEndAddress && *PrevExpr == Entry.Expr) {
4416       MergedLL.back().HighPC = std::max(Entry.HighPC, MergedLL.back().HighPC);
4417     } else {
4418       const uint64_t Begin = std::max(Entry.LowPC, PrevEndAddress);
4419       const uint64_t End = std::max(Begin, Entry.HighPC);
4420       MergedLL.emplace_back(DebugLocationEntry{Begin, End, Entry.Expr});
4421     }
4422     PrevEndAddress = MergedLL.back().HighPC;
4423     PrevExpr = &MergedLL.back().Expr;
4424   }
4425 
4426   return MergedLL;
4427 }
4428 
4429 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4430   OS << "Loop Info for Function \"" << *this << "\"";
4431   if (hasValidProfile())
4432     OS << " (count: " << getExecutionCount() << ")";
4433   OS << "\n";
4434 
4435   std::stack<BinaryLoop *> St;
4436   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I)
4437     St.push(*I);
4438   while (!St.empty()) {
4439     BinaryLoop *L = St.top();
4440     St.pop();
4441 
4442     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4443       St.push(*I);
4444 
4445     if (!hasValidProfile())
4446       continue;
4447 
4448     OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4449        << " loop header: " << L->getHeader()->getName();
4450     OS << "\n";
4451     OS << "Loop basic blocks: ";
4452     const char *Sep = "";
4453     for (auto BI = L->block_begin(), BE = L->block_end(); BI != BE; ++BI) {
4454       OS << Sep << (*BI)->getName();
4455       Sep = ", ";
4456     }
4457     OS << "\n";
4458     if (hasValidProfile()) {
4459       OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4460       OS << "Loop entry count: " << L->EntryCount << "\n";
4461       OS << "Loop exit count: " << L->ExitCount << "\n";
4462       if (L->EntryCount > 0) {
4463         OS << "Average iters per entry: "
4464            << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4465            << "\n";
4466       }
4467     }
4468     OS << "----\n";
4469   }
4470 
4471   OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4472   OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4473   OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4474 }
4475 
4476 bool BinaryFunction::isAArch64Veneer() const {
4477   if (BasicBlocks.size() != 1)
4478     return false;
4479 
4480   BinaryBasicBlock &BB = **BasicBlocks.begin();
4481   if (BB.size() != 3)
4482     return false;
4483 
4484   for (MCInst &Inst : BB)
4485     if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4486       return false;
4487 
4488   return true;
4489 }
4490 
4491 } // namespace bolt
4492 } // namespace llvm
4493