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