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