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