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