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