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