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