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