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