xref: /llvm-project/bolt/lib/Core/BinaryFunction.cpp (revision ef232a7e3486b9494c087ad25830f00bc15d739a)
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"
163e3a926bSspupyrev #include "bolt/Core/HashUtilities.h"
17a34c753fSRafael Auler #include "bolt/Core/MCPlusBuilder.h"
18a34c753fSRafael Auler #include "bolt/Utils/NameResolver.h"
19a34c753fSRafael Auler #include "bolt/Utils/NameShortener.h"
20a34c753fSRafael Auler #include "bolt/Utils/Utils.h"
215d8247d4SAmir Ayupov #include "llvm/ADT/STLExtras.h"
22a34c753fSRafael Auler #include "llvm/ADT/SmallSet.h"
23f7581a39SAmir Ayupov #include "llvm/ADT/StringExtras.h"
24a34c753fSRafael Auler #include "llvm/ADT/StringRef.h"
25ae585be1SRafael Auler #include "llvm/Demangle/Demangle.h"
26a34c753fSRafael Auler #include "llvm/MC/MCAsmInfo.h"
27a34c753fSRafael Auler #include "llvm/MC/MCContext.h"
28a34c753fSRafael Auler #include "llvm/MC/MCDisassembler/MCDisassembler.h"
29a34c753fSRafael Auler #include "llvm/MC/MCExpr.h"
30a34c753fSRafael Auler #include "llvm/MC/MCInst.h"
31a34c753fSRafael Auler #include "llvm/MC/MCInstPrinter.h"
3257f7c7d9Sserge-sans-paille #include "llvm/MC/MCRegisterInfo.h"
33a191ea7dSFabian Parzefall #include "llvm/MC/MCSymbol.h"
34a34c753fSRafael Auler #include "llvm/Object/ObjectFile.h"
35a34c753fSRafael Auler #include "llvm/Support/CommandLine.h"
36a34c753fSRafael Auler #include "llvm/Support/Debug.h"
37fd38366eSAmir Ayupov #include "llvm/Support/GenericDomTreeConstruction.h"
38fd38366eSAmir Ayupov #include "llvm/Support/GenericLoopInfoImpl.h"
39a34c753fSRafael Auler #include "llvm/Support/GraphWriter.h"
40a34c753fSRafael Auler #include "llvm/Support/LEB128.h"
41a34c753fSRafael Auler #include "llvm/Support/Regex.h"
42a34c753fSRafael Auler #include "llvm/Support/Timer.h"
43a34c753fSRafael Auler #include "llvm/Support/raw_ostream.h"
44e7dd596cSspupyrev #include "llvm/Support/xxhash.h"
45a34c753fSRafael Auler #include <functional>
46a34c753fSRafael Auler #include <limits>
47a34c753fSRafael Auler #include <numeric>
48b23fe108SNikita Popov #include <stack>
49a34c753fSRafael Auler #include <string>
50a34c753fSRafael Auler 
51a34c753fSRafael Auler #define DEBUG_TYPE "bolt"
52a34c753fSRafael Auler 
53a34c753fSRafael Auler using namespace llvm;
54a34c753fSRafael Auler using namespace bolt;
55a34c753fSRafael Auler 
56a34c753fSRafael Auler namespace opts {
57a34c753fSRafael Auler 
58a34c753fSRafael Auler extern cl::OptionCategory BoltCategory;
59a34c753fSRafael Auler extern cl::OptionCategory BoltOptCategory;
60a34c753fSRafael Auler 
61a34c753fSRafael Auler extern cl::opt<bool> EnableBAT;
62a34c753fSRafael Auler extern cl::opt<bool> Instrument;
63a34c753fSRafael Auler extern cl::opt<bool> StrictMode;
64a34c753fSRafael Auler extern cl::opt<bool> UpdateDebugSections;
65a34c753fSRafael Auler extern cl::opt<unsigned> Verbosity;
66a34c753fSRafael Auler 
67a34c753fSRafael Auler extern bool processAllFunctions();
68a34c753fSRafael Auler 
69b92436efSFangrui Song cl::opt<bool> CheckEncoding(
70b92436efSFangrui Song     "check-encoding",
71a34c753fSRafael Auler     cl::desc("perform verification of LLVM instruction encoding/decoding. "
72a34c753fSRafael Auler              "Every instruction in the input is decoded and re-encoded. "
73a34c753fSRafael Auler              "If the resulting bytes do not match the input, a warning message "
74a34c753fSRafael Auler              "is printed."),
75b92436efSFangrui Song     cl::Hidden, cl::cat(BoltCategory));
76a34c753fSRafael Auler 
77b92436efSFangrui Song static cl::opt<bool> DotToolTipCode(
78b92436efSFangrui Song     "dot-tooltip-code",
79b92436efSFangrui Song     cl::desc("add basic block instructions as tool tips on nodes"), 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 
102b92436efSFangrui Song static cl::opt<bool> NoScan(
103b92436efSFangrui Song     "no-scan",
104b92436efSFangrui Song     cl::desc(
105b92436efSFangrui Song         "do not scan cold functions for external references (may result in "
106a34c753fSRafael Auler         "slower binary)"),
107b92436efSFangrui Song     cl::Hidden, cl::cat(BoltOptCategory));
108a34c753fSRafael Auler 
109a34c753fSRafael Auler cl::opt<bool>
110a34c753fSRafael Auler     PreserveBlocksAlignment("preserve-blocks-alignment",
111a34c753fSRafael Auler                             cl::desc("try to preserve basic block alignment"),
112a34c753fSRafael Auler                             cl::cat(BoltOptCategory));
113a34c753fSRafael Auler 
114d333c0e0SShatianWang static cl::opt<bool> PrintOutputAddressRange(
115d333c0e0SShatianWang     "print-output-address-range",
116d333c0e0SShatianWang     cl::desc(
117d333c0e0SShatianWang         "print output address range for each basic block in the function when"
118d333c0e0SShatianWang         "BinaryFunction::print is called"),
119d333c0e0SShatianWang     cl::Hidden, cl::cat(BoltOptCategory));
120d333c0e0SShatianWang 
121a34c753fSRafael Auler cl::opt<bool>
122a34c753fSRafael Auler PrintDynoStats("dyno-stats",
123a34c753fSRafael Auler   cl::desc("print execution info based on profile"),
124a34c753fSRafael Auler   cl::cat(BoltCategory));
125a34c753fSRafael Auler 
126a34c753fSRafael Auler static cl::opt<bool>
127a34c753fSRafael Auler PrintDynoStatsOnly("print-dyno-stats-only",
128a34c753fSRafael Auler   cl::desc("while printing functions output dyno-stats and skip instructions"),
129a34c753fSRafael Auler   cl::init(false),
130a34c753fSRafael Auler   cl::Hidden,
131a34c753fSRafael Auler   cl::cat(BoltCategory));
132a34c753fSRafael Auler 
133a34c753fSRafael Auler static cl::list<std::string>
134a34c753fSRafael Auler PrintOnly("print-only",
135a34c753fSRafael Auler   cl::CommaSeparated,
136a34c753fSRafael Auler   cl::desc("list of functions to print"),
137a34c753fSRafael Auler   cl::value_desc("func1,func2,func3,..."),
138a34c753fSRafael Auler   cl::Hidden,
139a34c753fSRafael Auler   cl::cat(BoltCategory));
140a34c753fSRafael Auler 
141a34c753fSRafael Auler cl::opt<bool>
142a34c753fSRafael Auler     TimeBuild("time-build",
143a34c753fSRafael Auler               cl::desc("print time spent constructing binary functions"),
144b92436efSFangrui Song               cl::Hidden, cl::cat(BoltCategory));
145a34c753fSRafael Auler 
146a34c753fSRafael Auler cl::opt<bool>
147a34c753fSRafael Auler TrapOnAVX512("trap-avx512",
148a34c753fSRafael Auler   cl::desc("in relocation mode trap upon entry to any function that uses "
149a34c753fSRafael Auler             "AVX-512 instructions"),
150a34c753fSRafael Auler   cl::init(false),
151a34c753fSRafael Auler   cl::ZeroOrMore,
152a34c753fSRafael Auler   cl::Hidden,
153a34c753fSRafael Auler   cl::cat(BoltCategory));
154a34c753fSRafael Auler 
155a34c753fSRafael Auler bool shouldPrint(const BinaryFunction &Function) {
156a34c753fSRafael Auler   if (Function.isIgnored())
157a34c753fSRafael Auler     return false;
158a34c753fSRafael Auler 
159a34c753fSRafael Auler   if (PrintOnly.empty())
160a34c753fSRafael Auler     return true;
161a34c753fSRafael Auler 
162a34c753fSRafael Auler   for (std::string &Name : opts::PrintOnly) {
163a34c753fSRafael Auler     if (Function.hasNameRegex(Name)) {
164a34c753fSRafael Auler       return true;
165a34c753fSRafael Auler     }
166a34c753fSRafael Auler   }
167a34c753fSRafael Auler 
1684db0cc4cSMaksim Panchenko   std::optional<StringRef> Origin = Function.getOriginSectionName();
1694db0cc4cSMaksim Panchenko   if (Origin && llvm::any_of(opts::PrintOnly, [&](const std::string &Name) {
1704db0cc4cSMaksim Panchenko         return Name == *Origin;
1714db0cc4cSMaksim Panchenko       }))
1724db0cc4cSMaksim Panchenko     return true;
1734db0cc4cSMaksim Panchenko 
174a34c753fSRafael Auler   return false;
175a34c753fSRafael Auler }
176a34c753fSRafael Auler 
177a34c753fSRafael Auler } // namespace opts
178a34c753fSRafael Auler 
179a34c753fSRafael Auler namespace llvm {
180a34c753fSRafael Auler namespace bolt {
181a34c753fSRafael Auler 
182be2f67c4SAmir Ayupov template <typename R> static bool emptyRange(const R &Range) {
183a34c753fSRafael Auler   return Range.begin() == Range.end();
184a34c753fSRafael Auler }
185a34c753fSRafael Auler 
186a34c753fSRafael Auler /// Gets debug line information for the instruction located at the given
187a34c753fSRafael Auler /// address in the original binary. The SMLoc's pointer is used
188a34c753fSRafael Auler /// to point to this information, which is represented by a
189a34c753fSRafael Auler /// DebugLineTableRowRef. The returned pointer is null if no debug line
190a34c753fSRafael Auler /// information for this instruction was found.
191be2f67c4SAmir Ayupov static SMLoc findDebugLineInformationForInstructionAt(
19240c2e0faSMaksim Panchenko     uint64_t Address, DWARFUnit *Unit,
19340c2e0faSMaksim Panchenko     const DWARFDebugLine::LineTable *LineTable) {
194a34c753fSRafael Auler   // We use the pointer in SMLoc to store an instance of DebugLineTableRowRef,
195a34c753fSRafael Auler   // which occupies 64 bits. Thus, we can only proceed if the struct fits into
196a34c753fSRafael Auler   // the pointer itself.
197363be89cSKazu Hirata   static_assert(
198363be89cSKazu Hirata       sizeof(decltype(SMLoc().getPointer())) >= sizeof(DebugLineTableRowRef),
199a34c753fSRafael Auler       "Cannot fit instruction debug line information into SMLoc's pointer");
200a34c753fSRafael Auler 
201a34c753fSRafael Auler   SMLoc NullResult = DebugLineTableRowRef::NULL_ROW.toSMLoc();
202a34c753fSRafael Auler   uint32_t RowIndex = LineTable->lookupAddress(
203a34c753fSRafael Auler       {Address, object::SectionedAddress::UndefSection});
204a34c753fSRafael Auler   if (RowIndex == LineTable->UnknownRowIndex)
205a34c753fSRafael Auler     return NullResult;
206a34c753fSRafael Auler 
207a34c753fSRafael Auler   assert(RowIndex < LineTable->Rows.size() &&
208a34c753fSRafael Auler          "Line Table lookup returned invalid index.");
209a34c753fSRafael Auler 
210a34c753fSRafael Auler   decltype(SMLoc().getPointer()) Ptr;
211a34c753fSRafael Auler   DebugLineTableRowRef *InstructionLocation =
212a34c753fSRafael Auler       reinterpret_cast<DebugLineTableRowRef *>(&Ptr);
213a34c753fSRafael Auler 
214a34c753fSRafael Auler   InstructionLocation->DwCompileUnitIndex = Unit->getOffset();
215a34c753fSRafael Auler   InstructionLocation->RowIndex = RowIndex + 1;
216a34c753fSRafael Auler 
217a34c753fSRafael Auler   return SMLoc::getFromPointer(Ptr);
218a34c753fSRafael Auler }
219a34c753fSRafael Auler 
220be2f67c4SAmir Ayupov static std::string buildSectionName(StringRef Prefix, StringRef Name,
221a34c753fSRafael Auler                                     const BinaryContext &BC) {
222a34c753fSRafael Auler   if (BC.isELF())
223a34c753fSRafael Auler     return (Prefix + Name).str();
224a34c753fSRafael Auler   static NameShortener NS;
225a34c753fSRafael Auler   return (Prefix + Twine(NS.getID(Name))).str();
226a34c753fSRafael Auler }
227a34c753fSRafael Auler 
228be2f67c4SAmir Ayupov static raw_ostream &operator<<(raw_ostream &OS,
229be2f67c4SAmir Ayupov                                const BinaryFunction::State State) {
23040c2e0faSMaksim Panchenko   switch (State) {
23140c2e0faSMaksim Panchenko   case BinaryFunction::State::Empty:         OS << "empty"; break;
23240c2e0faSMaksim Panchenko   case BinaryFunction::State::Disassembled:  OS << "disassembled"; break;
23340c2e0faSMaksim Panchenko   case BinaryFunction::State::CFG:           OS << "CFG constructed"; break;
23440c2e0faSMaksim Panchenko   case BinaryFunction::State::CFG_Finalized: OS << "CFG finalized"; break;
23540c2e0faSMaksim Panchenko   case BinaryFunction::State::EmittedCFG:    OS << "emitted with CFG"; break;
23640c2e0faSMaksim Panchenko   case BinaryFunction::State::Emitted:       OS << "emitted"; break;
23740c2e0faSMaksim Panchenko   }
23840c2e0faSMaksim Panchenko 
23940c2e0faSMaksim Panchenko   return OS;
24040c2e0faSMaksim Panchenko }
24140c2e0faSMaksim Panchenko 
242a34c753fSRafael Auler std::string BinaryFunction::buildCodeSectionName(StringRef Name,
243a34c753fSRafael Auler                                                  const BinaryContext &BC) {
244a34c753fSRafael Auler   return buildSectionName(BC.isELF() ? ".local.text." : ".l.text.", Name, BC);
245a34c753fSRafael Auler }
246a34c753fSRafael Auler 
247a34c753fSRafael Auler std::string BinaryFunction::buildColdCodeSectionName(StringRef Name,
248a34c753fSRafael Auler                                                      const BinaryContext &BC) {
249a34c753fSRafael Auler   return buildSectionName(BC.isELF() ? ".local.cold.text." : ".l.c.text.", Name,
250a34c753fSRafael Auler                           BC);
251a34c753fSRafael Auler }
252a34c753fSRafael Auler 
253a34c753fSRafael Auler uint64_t BinaryFunction::Count = 0;
254a34c753fSRafael Auler 
25572528ee4SAmir Ayupov std::optional<StringRef>
25672528ee4SAmir Ayupov BinaryFunction::hasNameRegex(const StringRef Name) const {
257a34c753fSRafael Auler   const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
258a34c753fSRafael Auler   Regex MatchName(RegexName);
25972528ee4SAmir Ayupov   return forEachName(
260a34c753fSRafael Auler       [&MatchName](StringRef Name) { return MatchName.match(Name); });
261a34c753fSRafael Auler }
262a34c753fSRafael Auler 
26372528ee4SAmir Ayupov std::optional<StringRef>
264a34c753fSRafael Auler BinaryFunction::hasRestoredNameRegex(const StringRef Name) const {
265a34c753fSRafael Auler   const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
266a34c753fSRafael Auler   Regex MatchName(RegexName);
26772528ee4SAmir Ayupov   return forEachName([&MatchName](StringRef Name) {
268a34c753fSRafael Auler     return MatchName.match(NameResolver::restore(Name));
269a34c753fSRafael Auler   });
270a34c753fSRafael Auler }
271a34c753fSRafael Auler 
272a34c753fSRafael Auler std::string BinaryFunction::getDemangledName() const {
273a34c753fSRafael Auler   StringRef MangledName = NameResolver::restore(getOneName());
274ae585be1SRafael Auler   return demangle(MangledName.str());
275a34c753fSRafael Auler }
276a34c753fSRafael Auler 
277a34c753fSRafael Auler BinaryBasicBlock *
278a34c753fSRafael Auler BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset) {
279a34c753fSRafael Auler   if (Offset > Size)
280a34c753fSRafael Auler     return nullptr;
281a34c753fSRafael Auler 
282a34c753fSRafael Auler   if (BasicBlockOffsets.empty())
283a34c753fSRafael Auler     return nullptr;
284a34c753fSRafael Auler 
285a34c753fSRafael Auler   /*
286a34c753fSRafael Auler    * This is commented out because it makes BOLT too slow.
287a34c753fSRafael Auler    * assert(std::is_sorted(BasicBlockOffsets.begin(),
288a34c753fSRafael Auler    *                       BasicBlockOffsets.end(),
289a34c753fSRafael Auler    *                       CompareBasicBlockOffsets())));
290a34c753fSRafael Auler    */
291d2c87699SAmir Ayupov   auto I =
292d2c87699SAmir Ayupov       llvm::upper_bound(BasicBlockOffsets, BasicBlockOffset(Offset, nullptr),
293a34c753fSRafael Auler                         CompareBasicBlockOffsets());
294a34c753fSRafael Auler   assert(I != BasicBlockOffsets.begin() && "first basic block not at offset 0");
295a34c753fSRafael Auler   --I;
296a34c753fSRafael Auler   BinaryBasicBlock *BB = I->second;
297a34c753fSRafael Auler   return (Offset < BB->getOffset() + BB->getOriginalSize()) ? BB : nullptr;
298a34c753fSRafael Auler }
299a34c753fSRafael Auler 
300a34c753fSRafael Auler void BinaryFunction::markUnreachableBlocks() {
301a34c753fSRafael Auler   std::stack<BinaryBasicBlock *> Stack;
302a34c753fSRafael Auler 
303d55dfeafSFabian Parzefall   for (BinaryBasicBlock &BB : blocks())
304d55dfeafSFabian Parzefall     BB.markValid(false);
305a34c753fSRafael Auler 
306a34c753fSRafael Auler   // Add all entries and landing pads as roots.
307a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
308a34c753fSRafael Auler     if (isEntryPoint(*BB) || BB->isLandingPad()) {
309a34c753fSRafael Auler       Stack.push(BB);
310a34c753fSRafael Auler       BB->markValid(true);
311a34c753fSRafael Auler       continue;
312a34c753fSRafael Auler     }
313a34c753fSRafael Auler     // FIXME:
314a34c753fSRafael Auler     // Also mark BBs with indirect jumps as reachable, since we do not
315933df2a4SMaksim Panchenko     // support removing unused jump tables yet (GH-issue20).
316a34c753fSRafael Auler     for (const MCInst &Inst : *BB) {
317a34c753fSRafael Auler       if (BC.MIB->getJumpTable(Inst)) {
318a34c753fSRafael Auler         Stack.push(BB);
319a34c753fSRafael Auler         BB->markValid(true);
320a34c753fSRafael Auler         break;
321a34c753fSRafael Auler       }
322a34c753fSRafael Auler     }
323a34c753fSRafael Auler   }
324a34c753fSRafael Auler 
325a34c753fSRafael Auler   // Determine reachable BBs from the entry point
326a34c753fSRafael Auler   while (!Stack.empty()) {
327a34c753fSRafael Auler     BinaryBasicBlock *BB = Stack.top();
328a34c753fSRafael Auler     Stack.pop();
329a34c753fSRafael Auler     for (BinaryBasicBlock *Succ : BB->successors()) {
330a34c753fSRafael Auler       if (Succ->isValid())
331a34c753fSRafael Auler         continue;
332a34c753fSRafael Auler       Succ->markValid(true);
333a34c753fSRafael Auler       Stack.push(Succ);
334a34c753fSRafael Auler     }
335a34c753fSRafael Auler   }
336a34c753fSRafael Auler }
337a34c753fSRafael Auler 
338a34c753fSRafael Auler // Any unnecessary fallthrough jumps revealed after calling eraseInvalidBBs
339a34c753fSRafael Auler // will be cleaned up by fixBranches().
340c6c04a83SVladislav Khmelevsky std::pair<unsigned, uint64_t>
341c6c04a83SVladislav Khmelevsky BinaryFunction::eraseInvalidBBs(const MCCodeEmitter *Emitter) {
3428477bc67SFabian Parzefall   DenseSet<const BinaryBasicBlock *> InvalidBBs;
343a34c753fSRafael Auler   unsigned Count = 0;
344a34c753fSRafael Auler   uint64_t Bytes = 0;
3458477bc67SFabian Parzefall   for (BinaryBasicBlock *const BB : BasicBlocks) {
3468477bc67SFabian Parzefall     if (!BB->isValid()) {
347a34c753fSRafael Auler       assert(!isEntryPoint(*BB) && "all entry blocks must be valid");
3488477bc67SFabian Parzefall       InvalidBBs.insert(BB);
349a34c753fSRafael Auler       ++Count;
350c6c04a83SVladislav Khmelevsky       Bytes += BC.computeCodeSize(BB->begin(), BB->end(), Emitter);
351a34c753fSRafael Auler     }
352a34c753fSRafael Auler   }
3538477bc67SFabian Parzefall 
3548477bc67SFabian Parzefall   Layout.eraseBasicBlocks(InvalidBBs);
355a34c753fSRafael Auler 
356a34c753fSRafael Auler   BasicBlockListType NewBasicBlocks;
357a34c753fSRafael Auler   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
358a34c753fSRafael Auler     BinaryBasicBlock *BB = *I;
3598477bc67SFabian Parzefall     if (InvalidBBs.contains(BB)) {
360a34c753fSRafael Auler       // Make sure the block is removed from the list of predecessors.
361a34c753fSRafael Auler       BB->removeAllSuccessors();
362a34c753fSRafael Auler       DeletedBasicBlocks.push_back(BB);
3638477bc67SFabian Parzefall     } else {
3648477bc67SFabian Parzefall       NewBasicBlocks.push_back(BB);
365a34c753fSRafael Auler     }
366a34c753fSRafael Auler   }
367a34c753fSRafael Auler   BasicBlocks = std::move(NewBasicBlocks);
368a34c753fSRafael Auler 
3698477bc67SFabian Parzefall   assert(BasicBlocks.size() == Layout.block_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;
3884d2bc0adSEnna1     return compareBinaryFunctionByIndex(this, CalleeBF);
389a34c753fSRafael Auler   } else {
390a34c753fSRafael Auler     // Absolute symbol.
391a34c753fSRafael Auler     ErrorOr<uint64_t> CalleeAddressOrError = BC.getSymbolValue(*CalleeSymbol);
392a34c753fSRafael Auler     assert(CalleeAddressOrError && "unregistered symbol found");
393a34c753fSRafael Auler     return *CalleeAddressOrError > getAddress();
394a34c753fSRafael Auler   }
395a34c753fSRafael Auler }
396a34c753fSRafael Auler 
397be9d3edeSMaksim Panchenko void BinaryFunction::dump() const {
398d5c03defSFabian Parzefall   // getDynoStats calls FunctionLayout::updateLayoutIndices and
399d5c03defSFabian Parzefall   // BasicBlock::analyzeBranch. The former cannot be const, but should be
400d5c03defSFabian Parzefall   // removed, the latter should be made const, but seems to require refactoring.
401d5c03defSFabian Parzefall   // Forcing all callers to have a non-const reference to BinaryFunction to call
402d5c03defSFabian Parzefall   // dump non-const however is not ideal either. Adding this const_cast is right
403d5c03defSFabian Parzefall   // now the best solution. It is safe, because BinaryFunction itself is not
404d5c03defSFabian Parzefall   // modified. Only BinaryBasicBlocks are actually modified (if it all) and we
405d5c03defSFabian Parzefall   // have mutable pointers to those regardless whether this function is
406d5c03defSFabian Parzefall   // const-qualified or not.
407be9d3edeSMaksim Panchenko   const_cast<BinaryFunction &>(*this).print(dbgs(), "");
408a34c753fSRafael Auler }
409a34c753fSRafael Auler 
410be9d3edeSMaksim Panchenko void BinaryFunction::print(raw_ostream &OS, std::string Annotation) {
411a34c753fSRafael Auler   if (!opts::shouldPrint(*this))
412a34c753fSRafael Auler     return;
413a34c753fSRafael Auler 
414a34c753fSRafael Auler   StringRef SectionName =
415a34c753fSRafael Auler       OriginSection ? OriginSection->getName() : "<no origin section>";
416a34c753fSRafael Auler   OS << "Binary Function \"" << *this << "\" " << Annotation << " {";
417a34c753fSRafael Auler   std::vector<StringRef> AllNames = getNames();
418a34c753fSRafael Auler   if (AllNames.size() > 1) {
419a34c753fSRafael Auler     OS << "\n  All names   : ";
420a34c753fSRafael Auler     const char *Sep = "";
421253b8f0aSAmir Ayupov     for (const StringRef &Name : AllNames) {
422a34c753fSRafael Auler       OS << Sep << Name;
423a34c753fSRafael Auler       Sep = "\n                ";
424a34c753fSRafael Auler     }
425a34c753fSRafael Auler   }
4269b6e7861SFabian Parzefall   OS << "\n  Number      : " << FunctionNumber;
4279b6e7861SFabian Parzefall   OS << "\n  State       : " << CurrentState;
4289b6e7861SFabian Parzefall   OS << "\n  Address     : 0x" << Twine::utohexstr(Address);
4299b6e7861SFabian Parzefall   OS << "\n  Size        : 0x" << Twine::utohexstr(Size);
4309b6e7861SFabian Parzefall   OS << "\n  MaxSize     : 0x" << Twine::utohexstr(MaxSize);
4319b6e7861SFabian Parzefall   OS << "\n  Offset      : 0x" << Twine::utohexstr(getFileOffset());
4329b6e7861SFabian Parzefall   OS << "\n  Section     : " << SectionName;
4339b6e7861SFabian Parzefall   OS << "\n  Orc Section : " << getCodeSectionName();
4349b6e7861SFabian Parzefall   OS << "\n  LSDA        : 0x" << Twine::utohexstr(getLSDAAddress());
4359b6e7861SFabian Parzefall   OS << "\n  IsSimple    : " << IsSimple;
4369b6e7861SFabian Parzefall   OS << "\n  IsMultiEntry: " << isMultiEntry();
4379b6e7861SFabian Parzefall   OS << "\n  IsSplit     : " << isSplit();
4389b6e7861SFabian Parzefall   OS << "\n  BB Count    : " << size();
439a34c753fSRafael Auler 
44040c2e0faSMaksim Panchenko   if (HasUnknownControlFlow)
441a34c753fSRafael Auler     OS << "\n  Unknown CF  : true";
44240c2e0faSMaksim Panchenko   if (getPersonalityFunction())
443a34c753fSRafael Auler     OS << "\n  Personality : " << getPersonalityFunction()->getName();
44440c2e0faSMaksim Panchenko   if (IsFragment)
445a34c753fSRafael Auler     OS << "\n  IsFragment  : true";
44640c2e0faSMaksim Panchenko   if (isFolded())
447a34c753fSRafael Auler     OS << "\n  FoldedInto  : " << *getFoldedIntoFunction();
44840c2e0faSMaksim Panchenko   for (BinaryFunction *ParentFragment : ParentFragments)
449a34c753fSRafael Auler     OS << "\n  Parent      : " << *ParentFragment;
450a34c753fSRafael Auler   if (!Fragments.empty()) {
451a34c753fSRafael Auler     OS << "\n  Fragments   : ";
452f7581a39SAmir Ayupov     ListSeparator LS;
453f7581a39SAmir Ayupov     for (BinaryFunction *Frag : Fragments)
454f7581a39SAmir Ayupov       OS << LS << *Frag;
455a34c753fSRafael Auler   }
45640c2e0faSMaksim Panchenko   if (hasCFG())
457a34c753fSRafael Auler     OS << "\n  Hash        : " << Twine::utohexstr(computeHash());
458a34c753fSRafael Auler   if (isMultiEntry()) {
459a34c753fSRafael Auler     OS << "\n  Secondary Entry Points : ";
460f7581a39SAmir Ayupov     ListSeparator LS;
461f7581a39SAmir Ayupov     for (const auto &KV : SecondaryEntryPoints)
462f7581a39SAmir Ayupov       OS << LS << KV.second->getName();
463a34c753fSRafael Auler   }
46440c2e0faSMaksim Panchenko   if (FrameInstructions.size())
465a34c753fSRafael Auler     OS << "\n  CFI Instrs  : " << FrameInstructions.size();
4668477bc67SFabian Parzefall   if (!Layout.block_empty()) {
467a34c753fSRafael Auler     OS << "\n  BB Layout   : ";
468f7581a39SAmir Ayupov     ListSeparator LS;
4698477bc67SFabian Parzefall     for (const BinaryBasicBlock *BB : Layout.blocks())
470f7581a39SAmir Ayupov       OS << LS << BB->getName();
471a34c753fSRafael Auler   }
4729b6e7861SFabian Parzefall   if (getImageAddress())
4739b6e7861SFabian Parzefall     OS << "\n  Image       : 0x" << Twine::utohexstr(getImageAddress());
474a34c753fSRafael Auler   if (ExecutionCount != COUNT_NO_PROFILE) {
475a34c753fSRafael Auler     OS << "\n  Exec Count  : " << ExecutionCount;
47692758a99Sspupyrev     OS << "\n  Branch Count: " << RawBranchCount;
477a34c753fSRafael Auler     OS << "\n  Profile Acc : " << format("%.1f%%", ProfileMatchRatio * 100.0f);
478a34c753fSRafael Auler   }
479a34c753fSRafael Auler 
4808477bc67SFabian Parzefall   if (opts::PrintDynoStats && !getLayout().block_empty()) {
481a34c753fSRafael Auler     OS << '\n';
482a34c753fSRafael Auler     DynoStats dynoStats = getDynoStats(*this);
483a34c753fSRafael Auler     OS << dynoStats;
484a34c753fSRafael Auler   }
485a34c753fSRafael Auler 
486a34c753fSRafael Auler   OS << "\n}\n";
487a34c753fSRafael Auler 
488be9d3edeSMaksim Panchenko   if (opts::PrintDynoStatsOnly || !BC.InstPrinter)
489a34c753fSRafael Auler     return;
490a34c753fSRafael Auler 
491a34c753fSRafael Auler   // Offset of the instruction in function.
492a34c753fSRafael Auler   uint64_t Offset = 0;
493a34c753fSRafael Auler 
494a34c753fSRafael Auler   if (BasicBlocks.empty() && !Instructions.empty()) {
495a34c753fSRafael Auler     // Print before CFG was built.
496a34c753fSRafael Auler     for (const std::pair<const uint32_t, MCInst> &II : Instructions) {
497a34c753fSRafael Auler       Offset = II.first;
498a34c753fSRafael Auler 
499a34c753fSRafael Auler       // Print label if exists at this offset.
500a34c753fSRafael Auler       auto LI = Labels.find(Offset);
501a34c753fSRafael Auler       if (LI != Labels.end()) {
502a34c753fSRafael Auler         if (const MCSymbol *EntrySymbol =
503a34c753fSRafael Auler                 getSecondaryEntryPointSymbol(LI->second))
504a34c753fSRafael Auler           OS << EntrySymbol->getName() << " (Entry Point):\n";
505a34c753fSRafael Auler         OS << LI->second->getName() << ":\n";
506a34c753fSRafael Auler       }
507a34c753fSRafael Auler 
508a34c753fSRafael Auler       BC.printInstruction(OS, II.second, Offset, this);
509a34c753fSRafael Auler     }
510a34c753fSRafael Auler   }
511a34c753fSRafael Auler 
5128477bc67SFabian Parzefall   StringRef SplitPointMsg = "";
51307f63b0aSFabian Parzefall   for (const FunctionFragment &FF : Layout.fragments()) {
5148477bc67SFabian Parzefall     OS << SplitPointMsg;
5158477bc67SFabian Parzefall     SplitPointMsg = "-------   HOT-COLD SPLIT POINT   -------\n\n";
5160f8412c1SFabian Parzefall     for (const BinaryBasicBlock *BB : FF) {
51740c2e0faSMaksim Panchenko       OS << BB->getName() << " (" << BB->size()
51840c2e0faSMaksim Panchenko          << " instructions, align : " << BB->getAlignment() << ")\n";
519a34c753fSRafael Auler 
520d333c0e0SShatianWang       if (opts::PrintOutputAddressRange)
521d333c0e0SShatianWang         OS << formatv("  Output Address Range: [{0:x}, {1:x}) ({2} bytes)\n",
522d333c0e0SShatianWang                       BB->getOutputAddressRange().first,
523d333c0e0SShatianWang                       BB->getOutputAddressRange().second, BB->getOutputSize());
524d333c0e0SShatianWang 
525a34c753fSRafael Auler       if (isEntryPoint(*BB)) {
526a34c753fSRafael Auler         if (MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB))
527a34c753fSRafael Auler           OS << "  Secondary Entry Point: " << EntrySymbol->getName() << '\n';
528a34c753fSRafael Auler         else
529a34c753fSRafael Auler           OS << "  Entry Point\n";
530a34c753fSRafael Auler       }
531a34c753fSRafael Auler 
532a34c753fSRafael Auler       if (BB->isLandingPad())
533a34c753fSRafael Auler         OS << "  Landing Pad\n";
534a34c753fSRafael Auler 
535a34c753fSRafael Auler       uint64_t BBExecCount = BB->getExecutionCount();
536a34c753fSRafael Auler       if (hasValidProfile()) {
537a34c753fSRafael Auler         OS << "  Exec Count : ";
538a34c753fSRafael Auler         if (BB->getExecutionCount() != BinaryBasicBlock::COUNT_NO_PROFILE)
539a34c753fSRafael Auler           OS << BBExecCount << '\n';
540a34c753fSRafael Auler         else
541a34c753fSRafael Auler           OS << "<unknown>\n";
542a34c753fSRafael Auler       }
543ca06b610SMaksim Panchenko       if (hasCFI())
544a34c753fSRafael Auler         OS << "  CFI State : " << BB->getCFIState() << '\n';
545a34c753fSRafael Auler       if (opts::EnableBAT) {
5467f031d1cSmaksfb         OS << "  Input offset: 0x" << Twine::utohexstr(BB->getInputOffset())
547a34c753fSRafael Auler            << "\n";
548a34c753fSRafael Auler       }
549a34c753fSRafael Auler       if (!BB->pred_empty()) {
550a34c753fSRafael Auler         OS << "  Predecessors: ";
551f7581a39SAmir Ayupov         ListSeparator LS;
552f7581a39SAmir Ayupov         for (BinaryBasicBlock *Pred : BB->predecessors())
553f7581a39SAmir Ayupov           OS << LS << Pred->getName();
554a34c753fSRafael Auler         OS << '\n';
555a34c753fSRafael Auler       }
556a34c753fSRafael Auler       if (!BB->throw_empty()) {
557a34c753fSRafael Auler         OS << "  Throwers: ";
558f7581a39SAmir Ayupov         ListSeparator LS;
559f7581a39SAmir Ayupov         for (BinaryBasicBlock *Throw : BB->throwers())
560f7581a39SAmir Ayupov           OS << LS << Throw->getName();
561a34c753fSRafael Auler         OS << '\n';
562a34c753fSRafael Auler       }
563a34c753fSRafael Auler 
564a34c753fSRafael Auler       Offset = alignTo(Offset, BB->getAlignment());
565a34c753fSRafael Auler 
5668477bc67SFabian Parzefall       // Note: offsets are imprecise since this is happening prior to
5678477bc67SFabian Parzefall       // relaxation.
568a34c753fSRafael Auler       Offset = BC.printInstructions(OS, BB->begin(), BB->end(), Offset, this);
569a34c753fSRafael Auler 
570a34c753fSRafael Auler       if (!BB->succ_empty()) {
571a34c753fSRafael Auler         OS << "  Successors: ";
572a34c753fSRafael Auler         // For more than 2 successors, sort them based on frequency.
573a34c753fSRafael Auler         std::vector<uint64_t> Indices(BB->succ_size());
574a34c753fSRafael Auler         std::iota(Indices.begin(), Indices.end(), 0);
575a34c753fSRafael Auler         if (BB->succ_size() > 2 && BB->getKnownExecutionCount()) {
576d2c87699SAmir Ayupov           llvm::stable_sort(Indices, [&](const uint64_t A, const uint64_t B) {
577a34c753fSRafael Auler             return BB->BranchInfo[B] < BB->BranchInfo[A];
578a34c753fSRafael Auler           });
579a34c753fSRafael Auler         }
580f7581a39SAmir Ayupov         ListSeparator LS;
581a34c753fSRafael Auler         for (unsigned I = 0; I < Indices.size(); ++I) {
582a34c753fSRafael Auler           BinaryBasicBlock *Succ = BB->Successors[Indices[I]];
5838477bc67SFabian Parzefall           const BinaryBasicBlock::BinaryBranchInfo &BI =
5848477bc67SFabian Parzefall               BB->BranchInfo[Indices[I]];
585f7581a39SAmir Ayupov           OS << LS << Succ->getName();
586a34c753fSRafael Auler           if (ExecutionCount != COUNT_NO_PROFILE &&
587a34c753fSRafael Auler               BI.MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
588a34c753fSRafael Auler             OS << " (mispreds: " << BI.MispredictedCount
589a34c753fSRafael Auler                << ", count: " << BI.Count << ")";
590a34c753fSRafael Auler           } else if (ExecutionCount != COUNT_NO_PROFILE &&
591a34c753fSRafael Auler                      BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
592a34c753fSRafael Auler             OS << " (inferred count: " << BI.Count << ")";
593a34c753fSRafael Auler           }
594a34c753fSRafael Auler         }
595a34c753fSRafael Auler         OS << '\n';
596a34c753fSRafael Auler       }
597a34c753fSRafael Auler 
598a34c753fSRafael Auler       if (!BB->lp_empty()) {
599a34c753fSRafael Auler         OS << "  Landing Pads: ";
600f7581a39SAmir Ayupov         ListSeparator LS;
601a34c753fSRafael Auler         for (BinaryBasicBlock *LP : BB->landing_pads()) {
602f7581a39SAmir Ayupov           OS << LS << LP->getName();
603a34c753fSRafael Auler           if (ExecutionCount != COUNT_NO_PROFILE) {
604a34c753fSRafael Auler             OS << " (count: " << LP->getExecutionCount() << ")";
605a34c753fSRafael Auler           }
606a34c753fSRafael Auler         }
607a34c753fSRafael Auler         OS << '\n';
608a34c753fSRafael Auler       }
609a34c753fSRafael Auler 
610a34c753fSRafael Auler       // In CFG_Finalized state we can miscalculate CFI state at exit.
611ca06b610SMaksim Panchenko       if (CurrentState == State::CFG && hasCFI()) {
612a34c753fSRafael Auler         const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
613a34c753fSRafael Auler         if (CFIStateAtExit >= 0)
614a34c753fSRafael Auler           OS << "  CFI State: " << CFIStateAtExit << '\n';
615a34c753fSRafael Auler       }
616a34c753fSRafael Auler 
617a34c753fSRafael Auler       OS << '\n';
618a34c753fSRafael Auler     }
6198477bc67SFabian Parzefall   }
620a34c753fSRafael Auler 
621a34c753fSRafael Auler   // Dump new exception ranges for the function.
622a34c753fSRafael Auler   if (!CallSites.empty()) {
623a34c753fSRafael Auler     OS << "EH table:\n";
6243ac46f37SFabian Parzefall     for (const FunctionFragment &FF : getLayout().fragments()) {
6253ac46f37SFabian Parzefall       for (const auto &FCSI : getCallSites(FF.getFragmentNum())) {
6263ac46f37SFabian Parzefall         const CallSite &CSI = FCSI.second;
627a34c753fSRafael Auler         OS << "  [" << *CSI.Start << ", " << *CSI.End << ") landing pad : ";
628a34c753fSRafael Auler         if (CSI.LP)
629a34c753fSRafael Auler           OS << *CSI.LP;
630a34c753fSRafael Auler         else
631a34c753fSRafael Auler           OS << "0";
632a34c753fSRafael Auler         OS << ", action : " << CSI.Action << '\n';
633a34c753fSRafael Auler       }
6343ac46f37SFabian Parzefall     }
635a34c753fSRafael Auler     OS << '\n';
636a34c753fSRafael Auler   }
637a34c753fSRafael Auler 
638a34c753fSRafael Auler   // Print all jump tables.
6393652483cSRafael Auler   for (const std::pair<const uint64_t, JumpTable *> &JTI : JumpTables)
640a34c753fSRafael Auler     JTI.second->print(OS);
641a34c753fSRafael Auler 
642a34c753fSRafael Auler   OS << "DWARF CFI Instructions:\n";
643a34c753fSRafael Auler   if (OffsetToCFI.size()) {
644a34c753fSRafael Auler     // Pre-buildCFG information
645a34c753fSRafael Auler     for (const std::pair<const uint32_t, uint32_t> &Elmt : OffsetToCFI) {
646a34c753fSRafael Auler       OS << format("    %08x:\t", Elmt.first);
647a34c753fSRafael Auler       assert(Elmt.second < FrameInstructions.size() && "Incorrect CFI offset");
648a34c753fSRafael Auler       BinaryContext::printCFI(OS, FrameInstructions[Elmt.second]);
649a34c753fSRafael Auler       OS << "\n";
650a34c753fSRafael Auler     }
651a34c753fSRafael Auler   } else {
652a34c753fSRafael Auler     // Post-buildCFG information
653a34c753fSRafael Auler     for (uint32_t I = 0, E = FrameInstructions.size(); I != E; ++I) {
654a34c753fSRafael Auler       const MCCFIInstruction &CFI = FrameInstructions[I];
655a34c753fSRafael Auler       OS << format("    %d:\t", I);
656a34c753fSRafael Auler       BinaryContext::printCFI(OS, CFI);
657a34c753fSRafael Auler       OS << "\n";
658a34c753fSRafael Auler     }
659a34c753fSRafael Auler   }
660a34c753fSRafael Auler   if (FrameInstructions.empty())
661a34c753fSRafael Auler     OS << "    <empty>\n";
662a34c753fSRafael Auler 
663a34c753fSRafael Auler   OS << "End of Function \"" << *this << "\"\n\n";
664a34c753fSRafael Auler }
665a34c753fSRafael Auler 
66640c2e0faSMaksim Panchenko void BinaryFunction::printRelocations(raw_ostream &OS, uint64_t Offset,
667a34c753fSRafael Auler                                       uint64_t Size) const {
668a34c753fSRafael Auler   const char *Sep = " # Relocs: ";
669a34c753fSRafael Auler 
670a34c753fSRafael Auler   auto RI = Relocations.lower_bound(Offset);
671a34c753fSRafael Auler   while (RI != Relocations.end() && RI->first < Offset + Size) {
672a34c753fSRafael Auler     OS << Sep << "(R: " << RI->second << ")";
673a34c753fSRafael Auler     Sep = ", ";
674a34c753fSRafael Auler     ++RI;
675a34c753fSRafael Auler   }
676a34c753fSRafael Auler }
677a34c753fSRafael Auler 
678be2f67c4SAmir Ayupov static std::string mutateDWARFExpressionTargetReg(const MCCFIInstruction &Instr,
679a34c753fSRafael Auler                                                   MCPhysReg NewReg) {
680a34c753fSRafael Auler   StringRef ExprBytes = Instr.getValues();
681a34c753fSRafael Auler   assert(ExprBytes.size() > 1 && "DWARF expression CFI is too short");
682a34c753fSRafael Auler   uint8_t Opcode = ExprBytes[0];
683a34c753fSRafael Auler   assert((Opcode == dwarf::DW_CFA_expression ||
684a34c753fSRafael Auler           Opcode == dwarf::DW_CFA_val_expression) &&
685a34c753fSRafael Auler          "invalid DWARF expression CFI");
686139744acSAmir Ayupov   (void)Opcode;
687a34c753fSRafael Auler   const uint8_t *const Start =
688a34c753fSRafael Auler       reinterpret_cast<const uint8_t *>(ExprBytes.drop_front(1).data());
689a34c753fSRafael Auler   const uint8_t *const End =
690a34c753fSRafael Auler       reinterpret_cast<const uint8_t *>(Start + ExprBytes.size() - 1);
691a34c753fSRafael Auler   unsigned Size = 0;
692a34c753fSRafael Auler   decodeULEB128(Start, &Size, End);
693a34c753fSRafael Auler   assert(Size > 0 && "Invalid reg encoding for DWARF expression CFI");
694a34c753fSRafael Auler   SmallString<8> Tmp;
695a34c753fSRafael Auler   raw_svector_ostream OSE(Tmp);
696a34c753fSRafael Auler   encodeULEB128(NewReg, OSE);
697a34c753fSRafael Auler   return Twine(ExprBytes.slice(0, 1))
698a34c753fSRafael Auler       .concat(OSE.str())
699a34c753fSRafael Auler       .concat(ExprBytes.drop_front(1 + Size))
700a34c753fSRafael Auler       .str();
701a34c753fSRafael Auler }
702a34c753fSRafael Auler 
703a34c753fSRafael Auler void BinaryFunction::mutateCFIRegisterFor(const MCInst &Instr,
704a34c753fSRafael Auler                                           MCPhysReg NewReg) {
705a34c753fSRafael Auler   const MCCFIInstruction *OldCFI = getCFIFor(Instr);
706a34c753fSRafael Auler   assert(OldCFI && "invalid CFI instr");
707a34c753fSRafael Auler   switch (OldCFI->getOperation()) {
708a34c753fSRafael Auler   default:
709a34c753fSRafael Auler     llvm_unreachable("Unexpected instruction");
710a34c753fSRafael Auler   case MCCFIInstruction::OpDefCfa:
711a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, NewReg,
712a34c753fSRafael Auler                                                  OldCFI->getOffset()));
713a34c753fSRafael Auler     break;
714a34c753fSRafael Auler   case MCCFIInstruction::OpDefCfaRegister:
715a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg));
716a34c753fSRafael Auler     break;
717a34c753fSRafael Auler   case MCCFIInstruction::OpOffset:
718a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::createOffset(nullptr, NewReg,
719a34c753fSRafael Auler                                                     OldCFI->getOffset()));
720a34c753fSRafael Auler     break;
721a34c753fSRafael Auler   case MCCFIInstruction::OpRegister:
722a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::createRegister(nullptr, NewReg,
723a34c753fSRafael Auler                                                       OldCFI->getRegister2()));
724a34c753fSRafael Auler     break;
725a34c753fSRafael Auler   case MCCFIInstruction::OpSameValue:
726a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::createSameValue(nullptr, NewReg));
727a34c753fSRafael Auler     break;
728a34c753fSRafael Auler   case MCCFIInstruction::OpEscape:
729a34c753fSRafael Auler     setCFIFor(Instr,
730a34c753fSRafael Auler               MCCFIInstruction::createEscape(
731a34c753fSRafael Auler                   nullptr,
732a34c753fSRafael Auler                   StringRef(mutateDWARFExpressionTargetReg(*OldCFI, NewReg))));
733a34c753fSRafael Auler     break;
734a34c753fSRafael Auler   case MCCFIInstruction::OpRestore:
735a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::createRestore(nullptr, NewReg));
736a34c753fSRafael Auler     break;
737a34c753fSRafael Auler   case MCCFIInstruction::OpUndefined:
738a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::createUndefined(nullptr, NewReg));
739a34c753fSRafael Auler     break;
740a34c753fSRafael Auler   }
741a34c753fSRafael Auler }
742a34c753fSRafael Auler 
743a34c753fSRafael Auler const MCCFIInstruction *BinaryFunction::mutateCFIOffsetFor(const MCInst &Instr,
744a34c753fSRafael Auler                                                            int64_t NewOffset) {
745a34c753fSRafael Auler   const MCCFIInstruction *OldCFI = getCFIFor(Instr);
746a34c753fSRafael Auler   assert(OldCFI && "invalid CFI instr");
747a34c753fSRafael Auler   switch (OldCFI->getOperation()) {
748a34c753fSRafael Auler   default:
749a34c753fSRafael Auler     llvm_unreachable("Unexpected instruction");
750a34c753fSRafael Auler   case MCCFIInstruction::OpDefCfaOffset:
751a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset));
752a34c753fSRafael Auler     break;
753a34c753fSRafael Auler   case MCCFIInstruction::OpAdjustCfaOffset:
754a34c753fSRafael Auler     setCFIFor(Instr,
755a34c753fSRafael Auler               MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset));
756a34c753fSRafael Auler     break;
757a34c753fSRafael Auler   case MCCFIInstruction::OpDefCfa:
758a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI->getRegister(),
759a34c753fSRafael Auler                                                  NewOffset));
760a34c753fSRafael Auler     break;
761a34c753fSRafael Auler   case MCCFIInstruction::OpOffset:
762a34c753fSRafael Auler     setCFIFor(Instr, MCCFIInstruction::createOffset(
763a34c753fSRafael Auler                          nullptr, OldCFI->getRegister(), NewOffset));
764a34c753fSRafael Auler     break;
765a34c753fSRafael Auler   }
766a34c753fSRafael Auler   return getCFIFor(Instr);
767a34c753fSRafael Auler }
768a34c753fSRafael Auler 
769a34c753fSRafael Auler IndirectBranchType
77040c2e0faSMaksim Panchenko BinaryFunction::processIndirectBranch(MCInst &Instruction, unsigned Size,
771a34c753fSRafael Auler                                       uint64_t Offset,
772a34c753fSRafael Auler                                       uint64_t &TargetAddress) {
773a34c753fSRafael Auler   const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
774a34c753fSRafael Auler 
775a34c753fSRafael Auler   // The instruction referencing memory used by the branch instruction.
776a34c753fSRafael Auler   // It could be the branch instruction itself or one of the instructions
777a34c753fSRafael Auler   // setting the value of the register used by the branch.
778a34c753fSRafael Auler   MCInst *MemLocInstr;
779a34c753fSRafael Auler 
7803023b15fSAmir Ayupov   // The instruction loading the fixed PIC jump table entry value.
7813023b15fSAmir Ayupov   MCInst *FixedEntryLoadInstr;
7823023b15fSAmir Ayupov 
783a34c753fSRafael Auler   // Address of the table referenced by MemLocInstr. Could be either an
784a34c753fSRafael Auler   // array of function pointers, or a jump table.
785a34c753fSRafael Auler   uint64_t ArrayStart = 0;
786a34c753fSRafael Auler 
787a34c753fSRafael Auler   unsigned BaseRegNum, IndexRegNum;
788a34c753fSRafael Auler   int64_t DispValue;
789a34c753fSRafael Auler   const MCExpr *DispExpr;
790a34c753fSRafael Auler 
791a34c753fSRafael Auler   // In AArch, identify the instruction adding the PC-relative offset to
792a34c753fSRafael Auler   // jump table entries to correctly decode it.
793a34c753fSRafael Auler   MCInst *PCRelBaseInstr;
794a34c753fSRafael Auler   uint64_t PCRelAddr = 0;
795a34c753fSRafael Auler 
796a34c753fSRafael Auler   auto Begin = Instructions.begin();
797a34c753fSRafael Auler   if (BC.isAArch64()) {
798a34c753fSRafael Auler     // Start at the last label as an approximation of the current basic block.
799a34c753fSRafael Auler     // This is a heuristic, since the full set of labels have yet to be
800a34c753fSRafael Auler     // determined
801f40d25ddSAmir Ayupov     for (const uint32_t Offset :
802f40d25ddSAmir Ayupov          llvm::make_first_range(llvm::reverse(Labels))) {
803f40d25ddSAmir Ayupov       auto II = Instructions.find(Offset);
804a34c753fSRafael Auler       if (II != Instructions.end()) {
805a34c753fSRafael Auler         Begin = II;
806a34c753fSRafael Auler         break;
807a34c753fSRafael Auler       }
808a34c753fSRafael Auler     }
809a34c753fSRafael Auler   }
810a34c753fSRafael Auler 
81140c2e0faSMaksim Panchenko   IndirectBranchType BranchType = BC.MIB->analyzeIndirectBranch(
81240c2e0faSMaksim Panchenko       Instruction, Begin, Instructions.end(), PtrSize, MemLocInstr, BaseRegNum,
8133023b15fSAmir Ayupov       IndexRegNum, DispValue, DispExpr, PCRelBaseInstr, FixedEntryLoadInstr);
814a34c753fSRafael Auler 
815a34c753fSRafael Auler   if (BranchType == IndirectBranchType::UNKNOWN && !MemLocInstr)
816a34c753fSRafael Auler     return BranchType;
817a34c753fSRafael Auler 
818a34c753fSRafael Auler   if (MemLocInstr != &Instruction)
819a34c753fSRafael Auler     IndexRegNum = BC.MIB->getNoRegister();
820a34c753fSRafael Auler 
821a34c753fSRafael Auler   if (BC.isAArch64()) {
822a34c753fSRafael Auler     const MCSymbol *Sym = BC.MIB->getTargetSymbol(*PCRelBaseInstr, 1);
823a34c753fSRafael Auler     assert(Sym && "Symbol extraction failed");
824a34c753fSRafael Auler     ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*Sym);
825a34c753fSRafael Auler     if (SymValueOrError) {
826a34c753fSRafael Auler       PCRelAddr = *SymValueOrError;
827a34c753fSRafael Auler     } else {
828a34c753fSRafael Auler       for (std::pair<const uint32_t, MCSymbol *> &Elmt : Labels) {
829a34c753fSRafael Auler         if (Elmt.second == Sym) {
830a34c753fSRafael Auler           PCRelAddr = Elmt.first + getAddress();
831a34c753fSRafael Auler           break;
832a34c753fSRafael Auler         }
833a34c753fSRafael Auler       }
834a34c753fSRafael Auler     }
835a34c753fSRafael Auler     uint64_t InstrAddr = 0;
836a34c753fSRafael Auler     for (auto II = Instructions.rbegin(); II != Instructions.rend(); ++II) {
837a34c753fSRafael Auler       if (&II->second == PCRelBaseInstr) {
838a34c753fSRafael Auler         InstrAddr = II->first + getAddress();
839a34c753fSRafael Auler         break;
840a34c753fSRafael Auler       }
841a34c753fSRafael Auler     }
842a34c753fSRafael Auler     assert(InstrAddr != 0 && "instruction not found");
843a34c753fSRafael Auler     // We do this to avoid spurious references to code locations outside this
844a34c753fSRafael Auler     // function (for example, if the indirect jump lives in the last basic
845a34c753fSRafael Auler     // block of the function, it will create a reference to the next function).
846a34c753fSRafael Auler     // This replaces a symbol reference with an immediate.
847a34c753fSRafael Auler     BC.MIB->replaceMemOperandDisp(*PCRelBaseInstr,
848a34c753fSRafael Auler                                   MCOperand::createImm(PCRelAddr - InstrAddr));
849a34c753fSRafael Auler     // FIXME: Disable full jump table processing for AArch64 until we have a
850a34c753fSRafael Auler     // proper way of determining the jump table limits.
851a34c753fSRafael Auler     return IndirectBranchType::UNKNOWN;
852a34c753fSRafael Auler   }
853a34c753fSRafael Auler 
854f2394905SAmir Ayupov   auto getExprValue = [&](const MCExpr *Expr) {
855f2394905SAmir Ayupov     const MCSymbol *TargetSym;
856f2394905SAmir Ayupov     uint64_t TargetOffset;
857f2394905SAmir Ayupov     std::tie(TargetSym, TargetOffset) = BC.MIB->getTargetSymbolInfo(Expr);
858f2394905SAmir Ayupov     ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*TargetSym);
859f2394905SAmir Ayupov     assert(SymValueOrError && "Global symbol needs a value");
860f2394905SAmir Ayupov     return *SymValueOrError + TargetOffset;
861f2394905SAmir Ayupov   };
862f2394905SAmir Ayupov 
863a34c753fSRafael Auler   // RIP-relative addressing should be converted to symbol form by now
864a34c753fSRafael Auler   // in processed instructions (but not in jump).
865a34c753fSRafael Auler   if (DispExpr) {
866f2394905SAmir Ayupov     ArrayStart = getExprValue(DispExpr);
867a34c753fSRafael Auler     BaseRegNum = BC.MIB->getNoRegister();
868a34c753fSRafael Auler     if (BC.isAArch64()) {
869a34c753fSRafael Auler       ArrayStart &= ~0xFFFULL;
870a34c753fSRafael Auler       ArrayStart += DispValue & 0xFFFULL;
871a34c753fSRafael Auler     }
872a34c753fSRafael Auler   } else {
873a34c753fSRafael Auler     ArrayStart = static_cast<uint64_t>(DispValue);
874a34c753fSRafael Auler   }
875a34c753fSRafael Auler 
876a34c753fSRafael Auler   if (BaseRegNum == BC.MRI->getProgramCounter())
877a34c753fSRafael Auler     ArrayStart += getAddress() + Offset + Size;
878a34c753fSRafael Auler 
8793023b15fSAmir Ayupov   if (FixedEntryLoadInstr) {
8803023b15fSAmir Ayupov     assert(BranchType == IndirectBranchType::POSSIBLE_PIC_FIXED_BRANCH &&
8813023b15fSAmir Ayupov            "Invalid IndirectBranch type");
8823023b15fSAmir Ayupov     MCInst::iterator FixedEntryDispOperand =
8833023b15fSAmir Ayupov         BC.MIB->getMemOperandDisp(*FixedEntryLoadInstr);
8843023b15fSAmir Ayupov     assert(FixedEntryDispOperand != FixedEntryLoadInstr->end() &&
8853023b15fSAmir Ayupov            "Invalid memory instruction");
8863023b15fSAmir Ayupov     const MCExpr *FixedEntryDispExpr = FixedEntryDispOperand->getExpr();
8873023b15fSAmir Ayupov     const uint64_t EntryAddress = getExprValue(FixedEntryDispExpr);
8883023b15fSAmir Ayupov     uint64_t EntrySize = BC.getJumpTableEntrySize(JumpTable::JTT_PIC);
8893023b15fSAmir Ayupov     ErrorOr<int64_t> Value =
8903023b15fSAmir Ayupov         BC.getSignedValueAtAddress(EntryAddress, EntrySize);
8913023b15fSAmir Ayupov     if (!Value)
8923023b15fSAmir Ayupov       return IndirectBranchType::UNKNOWN;
8933023b15fSAmir Ayupov 
8943023b15fSAmir Ayupov     BC.outs() << "BOLT-INFO: fixed PIC indirect branch detected in " << *this
8953023b15fSAmir Ayupov               << " at 0x" << Twine::utohexstr(getAddress() + Offset)
8963023b15fSAmir Ayupov               << " referencing data at 0x" << Twine::utohexstr(EntryAddress)
8973023b15fSAmir Ayupov               << " the destination value is 0x"
8983023b15fSAmir Ayupov               << Twine::utohexstr(ArrayStart + *Value) << '\n';
8993023b15fSAmir Ayupov 
9003023b15fSAmir Ayupov     TargetAddress = ArrayStart + *Value;
9013023b15fSAmir Ayupov 
9023023b15fSAmir Ayupov     // Remove spurious JumpTable at EntryAddress caused by PIC reference from
9033023b15fSAmir Ayupov     // the load instruction.
9043023b15fSAmir Ayupov     BC.deleteJumpTable(EntryAddress);
9053023b15fSAmir Ayupov 
9063023b15fSAmir Ayupov     // Replace FixedEntryDispExpr used in target address calculation with outer
9073023b15fSAmir Ayupov     // jump table reference.
9083023b15fSAmir Ayupov     JumpTable *JT = BC.getJumpTableContainingAddress(ArrayStart);
9093023b15fSAmir Ayupov     assert(JT && "Must have a containing jump table for PIC fixed branch");
9103023b15fSAmir Ayupov     BC.MIB->replaceMemOperandDisp(*FixedEntryLoadInstr, JT->getFirstLabel(),
9113023b15fSAmir Ayupov                                   EntryAddress - ArrayStart, &*BC.Ctx);
9123023b15fSAmir Ayupov 
9133023b15fSAmir Ayupov     return BranchType;
9143023b15fSAmir Ayupov   }
9153023b15fSAmir Ayupov 
916a34c753fSRafael Auler   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addressed memory is 0x"
917a34c753fSRafael Auler                     << Twine::utohexstr(ArrayStart) << '\n');
918a34c753fSRafael Auler 
919a34c753fSRafael Auler   ErrorOr<BinarySection &> Section = BC.getSectionForAddress(ArrayStart);
920a34c753fSRafael Auler   if (!Section) {
921a34c753fSRafael Auler     // No section - possibly an absolute address. Since we don't allow
922a34c753fSRafael Auler     // internal function addresses to escape the function scope - we
923a34c753fSRafael Auler     // consider it a tail call.
924a34c753fSRafael Auler     if (opts::Verbosity >= 1) {
92552cf0711SAmir Ayupov       BC.errs() << "BOLT-WARNING: no section for address 0x"
926a34c753fSRafael Auler                 << Twine::utohexstr(ArrayStart) << " referenced from function "
927a34c753fSRafael Auler                 << *this << '\n';
928a34c753fSRafael Auler     }
929a34c753fSRafael Auler     return IndirectBranchType::POSSIBLE_TAIL_CALL;
930a34c753fSRafael Auler   }
931a34c753fSRafael Auler   if (Section->isVirtual()) {
932a34c753fSRafael Auler     // The contents are filled at runtime.
933a34c753fSRafael Auler     return IndirectBranchType::POSSIBLE_TAIL_CALL;
934a34c753fSRafael Auler   }
935a34c753fSRafael Auler 
936a34c753fSRafael Auler   if (BranchType == IndirectBranchType::POSSIBLE_FIXED_BRANCH) {
937a34c753fSRafael Auler     ErrorOr<uint64_t> Value = BC.getPointerAtAddress(ArrayStart);
938a34c753fSRafael Auler     if (!Value)
939a34c753fSRafael Auler       return IndirectBranchType::UNKNOWN;
940a34c753fSRafael Auler 
94169a9bbf1SAmir Ayupov     if (BC.getSectionForAddress(ArrayStart)->isWritable())
942a34c753fSRafael Auler       return IndirectBranchType::UNKNOWN;
943a34c753fSRafael Auler 
94452cf0711SAmir Ayupov     BC.outs() << "BOLT-INFO: fixed indirect branch detected in " << *this
945a34c753fSRafael Auler               << " at 0x" << Twine::utohexstr(getAddress() + Offset)
946a34c753fSRafael Auler               << " referencing data at 0x" << Twine::utohexstr(ArrayStart)
947a34c753fSRafael Auler               << " the destination value is 0x" << Twine::utohexstr(*Value)
948a34c753fSRafael Auler               << '\n';
949a34c753fSRafael Auler 
950a34c753fSRafael Auler     TargetAddress = *Value;
951a34c753fSRafael Auler     return BranchType;
952a34c753fSRafael Auler   }
953a34c753fSRafael Auler 
954a34c753fSRafael Auler   // Check if there's already a jump table registered at this address.
955a34c753fSRafael Auler   MemoryContentsType MemType;
956a34c753fSRafael Auler   if (JumpTable *JT = BC.getJumpTableContainingAddress(ArrayStart)) {
957a34c753fSRafael Auler     switch (JT->Type) {
958a34c753fSRafael Auler     case JumpTable::JTT_NORMAL:
959a34c753fSRafael Auler       MemType = MemoryContentsType::POSSIBLE_JUMP_TABLE;
960a34c753fSRafael Auler       break;
961a34c753fSRafael Auler     case JumpTable::JTT_PIC:
962a34c753fSRafael Auler       MemType = MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
963a34c753fSRafael Auler       break;
964a34c753fSRafael Auler     }
965a34c753fSRafael Auler   } else {
966a34c753fSRafael Auler     MemType = BC.analyzeMemoryAt(ArrayStart, *this);
967a34c753fSRafael Auler   }
968a34c753fSRafael Auler 
969a34c753fSRafael Auler   // Check that jump table type in instruction pattern matches memory contents.
970a34c753fSRafael Auler   JumpTable::JumpTableType JTType;
971a34c753fSRafael Auler   if (BranchType == IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE) {
972a34c753fSRafael Auler     if (MemType != MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
973a34c753fSRafael Auler       return IndirectBranchType::UNKNOWN;
974a34c753fSRafael Auler     JTType = JumpTable::JTT_PIC;
975a34c753fSRafael Auler   } else {
976a34c753fSRafael Auler     if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
977a34c753fSRafael Auler       return IndirectBranchType::UNKNOWN;
978a34c753fSRafael Auler 
979a34c753fSRafael Auler     if (MemType == MemoryContentsType::UNKNOWN)
980a34c753fSRafael Auler       return IndirectBranchType::POSSIBLE_TAIL_CALL;
981a34c753fSRafael Auler 
982a34c753fSRafael Auler     BranchType = IndirectBranchType::POSSIBLE_JUMP_TABLE;
983a34c753fSRafael Auler     JTType = JumpTable::JTT_NORMAL;
984a34c753fSRafael Auler   }
985a34c753fSRafael Auler 
986a34c753fSRafael Auler   // Convert the instruction into jump table branch.
987a34c753fSRafael Auler   const MCSymbol *JTLabel = BC.getOrCreateJumpTable(*this, ArrayStart, JTType);
988a34c753fSRafael Auler   BC.MIB->replaceMemOperandDisp(*MemLocInstr, JTLabel, BC.Ctx.get());
989a34c753fSRafael Auler   BC.MIB->setJumpTable(Instruction, ArrayStart, IndexRegNum);
990a34c753fSRafael Auler 
991a34c753fSRafael Auler   JTSites.emplace_back(Offset, ArrayStart);
992a34c753fSRafael Auler 
993a34c753fSRafael Auler   return BranchType;
994a34c753fSRafael Auler }
995a34c753fSRafael Auler 
996a34c753fSRafael Auler MCSymbol *BinaryFunction::getOrCreateLocalLabel(uint64_t Address,
997a34c753fSRafael Auler                                                 bool CreatePastEnd) {
998a34c753fSRafael Auler   const uint64_t Offset = Address - getAddress();
999a34c753fSRafael Auler 
1000a34c753fSRafael Auler   if ((Offset == getSize()) && CreatePastEnd)
1001a34c753fSRafael Auler     return getFunctionEndLabel();
1002a34c753fSRafael Auler 
1003a34c753fSRafael Auler   auto LI = Labels.find(Offset);
1004a34c753fSRafael Auler   if (LI != Labels.end())
1005a34c753fSRafael Auler     return LI->second;
1006a34c753fSRafael Auler 
1007a34c753fSRafael Auler   // For AArch64, check if this address is part of a constant island.
1008a34c753fSRafael Auler   if (BC.isAArch64()) {
10093652483cSRafael Auler     if (MCSymbol *IslandSym = getOrCreateIslandAccess(Address))
1010a34c753fSRafael Auler       return IslandSym;
1011a34c753fSRafael Auler   }
1012a34c753fSRafael Auler 
1013a34c753fSRafael Auler   MCSymbol *Label = BC.Ctx->createNamedTempSymbol();
1014a34c753fSRafael Auler   Labels[Offset] = Label;
1015a34c753fSRafael Auler 
1016a34c753fSRafael Auler   return Label;
1017a34c753fSRafael Auler }
1018a34c753fSRafael Auler 
1019a34c753fSRafael Auler ErrorOr<ArrayRef<uint8_t>> BinaryFunction::getData() const {
1020a34c753fSRafael Auler   BinarySection &Section = *getOriginSection();
1021a34c753fSRafael Auler   assert(Section.containsRange(getAddress(), getMaxSize()) &&
1022a34c753fSRafael Auler          "wrong section for function");
1023a34c753fSRafael Auler 
10243652483cSRafael Auler   if (!Section.isText() || Section.isVirtual() || !Section.getSize())
1025a34c753fSRafael Auler     return std::make_error_code(std::errc::bad_address);
1026a34c753fSRafael Auler 
1027a34c753fSRafael Auler   StringRef SectionContents = Section.getContents();
1028a34c753fSRafael Auler 
1029a34c753fSRafael Auler   assert(SectionContents.size() == Section.getSize() &&
1030a34c753fSRafael Auler          "section size mismatch");
1031a34c753fSRafael Auler 
1032a34c753fSRafael Auler   // Function offset from the section start.
1033a34c753fSRafael Auler   uint64_t Offset = getAddress() - Section.getAddress();
1034a34c753fSRafael Auler   auto *Bytes = reinterpret_cast<const uint8_t *>(SectionContents.data());
1035a34c753fSRafael Auler   return ArrayRef<uint8_t>(Bytes + Offset, getMaxSize());
1036a34c753fSRafael Auler }
1037a34c753fSRafael Auler 
1038a34c753fSRafael Auler size_t BinaryFunction::getSizeOfDataInCodeAt(uint64_t Offset) const {
1039a34c753fSRafael Auler   if (!Islands)
1040a34c753fSRafael Auler     return 0;
1041a34c753fSRafael Auler 
10422eae9d8eSAmir Ayupov   if (!llvm::is_contained(Islands->DataOffsets, Offset))
1043a34c753fSRafael Auler     return 0;
1044a34c753fSRafael Auler 
1045a34c753fSRafael Auler   auto Iter = Islands->CodeOffsets.upper_bound(Offset);
10463652483cSRafael Auler   if (Iter != Islands->CodeOffsets.end())
1047a34c753fSRafael Auler     return *Iter - Offset;
1048a34c753fSRafael Auler   return getSize() - Offset;
1049a34c753fSRafael Auler }
1050a34c753fSRafael Auler 
1051a34c753fSRafael Auler bool BinaryFunction::isZeroPaddingAt(uint64_t Offset) const {
1052a34c753fSRafael Auler   ArrayRef<uint8_t> FunctionData = *getData();
1053a34c753fSRafael Auler   uint64_t EndOfCode = getSize();
1054a34c753fSRafael Auler   if (Islands) {
1055a34c753fSRafael Auler     auto Iter = Islands->DataOffsets.upper_bound(Offset);
1056a34c753fSRafael Auler     if (Iter != Islands->DataOffsets.end())
1057a34c753fSRafael Auler       EndOfCode = *Iter;
1058a34c753fSRafael Auler   }
10593652483cSRafael Auler   for (uint64_t I = Offset; I < EndOfCode; ++I)
10603652483cSRafael Auler     if (FunctionData[I] != 0)
1061a34c753fSRafael Auler       return false;
1062a34c753fSRafael Auler 
1063a34c753fSRafael Auler   return true;
1064a34c753fSRafael Auler }
1065a34c753fSRafael Auler 
106613d60ce2SAmir Ayupov Error BinaryFunction::handlePCRelOperand(MCInst &Instruction, uint64_t Address,
106740c2e0faSMaksim Panchenko                                          uint64_t Size) {
10686cd475f8SAmir Ayupov   auto &MIB = BC.MIB;
1069a34c753fSRafael Auler   uint64_t TargetAddress = 0;
1070a34c753fSRafael Auler   if (!MIB->evaluateMemOperandTarget(Instruction, TargetAddress, Address,
1071a34c753fSRafael Auler                                      Size)) {
107213d60ce2SAmir Ayupov     std::string Msg;
107313d60ce2SAmir Ayupov     raw_string_ostream SS(Msg);
107413d60ce2SAmir Ayupov     SS << "BOLT-ERROR: PC-relative operand can't be evaluated:\n";
107513d60ce2SAmir Ayupov     BC.InstPrinter->printInst(&Instruction, 0, "", *BC.STI, SS);
107613d60ce2SAmir Ayupov     SS << '\n';
107713d60ce2SAmir Ayupov     Instruction.dump_pretty(SS, BC.InstPrinter.get());
107813d60ce2SAmir Ayupov     SS << '\n';
107913d60ce2SAmir Ayupov     SS << "BOLT-ERROR: cannot handle PC-relative operand at 0x"
108013d60ce2SAmir Ayupov        << Twine::utohexstr(Address) << ". Skipping function " << *this << ".\n";
1081a34c753fSRafael Auler     if (BC.HasRelocations)
108213d60ce2SAmir Ayupov       return createFatalBOLTError(Msg);
1083a34c753fSRafael Auler     IsSimple = false;
108413d60ce2SAmir Ayupov     return createNonFatalBOLTError(Msg);
1085a34c753fSRafael Auler   }
1086a34c753fSRafael Auler   if (TargetAddress == 0 && opts::Verbosity >= 1) {
108752cf0711SAmir Ayupov     BC.outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this
1088a34c753fSRafael Auler               << '\n';
1089a34c753fSRafael Auler   }
1090a34c753fSRafael Auler 
1091a34c753fSRafael Auler   const MCSymbol *TargetSymbol;
1092a34c753fSRafael Auler   uint64_t TargetOffset;
1093a34c753fSRafael Auler   std::tie(TargetSymbol, TargetOffset) =
1094a34c753fSRafael Auler       BC.handleAddressRef(TargetAddress, *this, /*IsPCRel*/ true);
10958d1fc45dSRafael Auler 
10968d1fc45dSRafael Auler   bool ReplaceSuccess = MIB->replaceMemOperandDisp(
10978d1fc45dSRafael Auler       Instruction, TargetSymbol, static_cast<int64_t>(TargetOffset), &*BC.Ctx);
10988d1fc45dSRafael Auler   (void)ReplaceSuccess;
10998d1fc45dSRafael Auler   assert(ReplaceSuccess && "Failed to replace mem operand with symbol+off.");
110013d60ce2SAmir Ayupov   return Error::success();
11016cd475f8SAmir Ayupov }
11026cd475f8SAmir Ayupov 
1103ec1fbf22SAmir Ayupov MCSymbol *BinaryFunction::handleExternalReference(MCInst &Instruction,
1104ec1fbf22SAmir Ayupov                                                   uint64_t Size,
1105ec1fbf22SAmir Ayupov                                                   uint64_t Offset,
1106ec1fbf22SAmir Ayupov                                                   uint64_t TargetAddress,
1107ec1fbf22SAmir Ayupov                                                   bool &IsCall) {
11086cd475f8SAmir Ayupov   auto &MIB = BC.MIB;
11096cd475f8SAmir Ayupov 
1110a34c753fSRafael Auler   const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
111135efe1d8SVladislav Khmelevsky   BC.addInterproceduralReference(this, TargetAddress);
1112a34c753fSRafael Auler   if (opts::Verbosity >= 2 && !IsCall && Size == 2 && !BC.HasRelocations) {
111352cf0711SAmir Ayupov     BC.errs() << "BOLT-WARNING: relaxed tail call detected at 0x"
1114a34c753fSRafael Auler               << Twine::utohexstr(AbsoluteInstrAddr) << " in function " << *this
1115a34c753fSRafael Auler               << ". Code size will be increased.\n";
1116a34c753fSRafael Auler   }
1117a34c753fSRafael Auler 
1118a34c753fSRafael Auler   assert(!MIB->isTailCall(Instruction) &&
1119a34c753fSRafael Auler          "synthetic tail call instruction found");
1120a34c753fSRafael Auler 
1121a34c753fSRafael Auler   // This is a call regardless of the opcode.
1122a34c753fSRafael Auler   // Assign proper opcode for tail calls, so that they could be
1123a34c753fSRafael Auler   // treated as calls.
1124a34c753fSRafael Auler   if (!IsCall) {
1125a34c753fSRafael Auler     if (!MIB->convertJmpToTailCall(Instruction)) {
1126139744acSAmir Ayupov       assert(MIB->isConditionalBranch(Instruction) &&
1127139744acSAmir Ayupov              "unknown tail call instruction");
1128a34c753fSRafael Auler       if (opts::Verbosity >= 2) {
112952cf0711SAmir Ayupov         BC.errs() << "BOLT-WARNING: conditional tail call detected in "
1130a34c753fSRafael Auler                   << "function " << *this << " at 0x"
1131a34c753fSRafael Auler                   << Twine::utohexstr(AbsoluteInstrAddr) << ".\n";
1132a34c753fSRafael Auler       }
1133a34c753fSRafael Auler     }
1134a34c753fSRafael Auler     IsCall = true;
1135a34c753fSRafael Auler   }
1136a34c753fSRafael Auler 
1137a34c753fSRafael Auler   if (opts::Verbosity >= 2 && TargetAddress == 0) {
1138a34c753fSRafael Auler     // We actually see calls to address 0 in presence of weak
1139a34c753fSRafael Auler     // symbols originating from libraries. This code is never meant
1140a34c753fSRafael Auler     // to be executed.
114152cf0711SAmir Ayupov     BC.outs() << "BOLT-INFO: Function " << *this
1142a34c753fSRafael Auler               << " has a call to address zero.\n";
1143a34c753fSRafael Auler   }
1144a34c753fSRafael Auler 
1145ec1fbf22SAmir Ayupov   return BC.getOrCreateGlobalSymbol(TargetAddress, "FUNCat");
1146ec1fbf22SAmir Ayupov }
1147ec1fbf22SAmir Ayupov 
1148c844850bSAmir Ayupov void BinaryFunction::handleIndirectBranch(MCInst &Instruction, uint64_t Size,
1149a34c753fSRafael Auler                                           uint64_t Offset) {
1150c844850bSAmir Ayupov   auto &MIB = BC.MIB;
1151a34c753fSRafael Auler   uint64_t IndirectTarget = 0;
1152a34c753fSRafael Auler   IndirectBranchType Result =
1153a34c753fSRafael Auler       processIndirectBranch(Instruction, Size, Offset, IndirectTarget);
1154a34c753fSRafael Auler   switch (Result) {
1155a34c753fSRafael Auler   default:
1156a34c753fSRafael Auler     llvm_unreachable("unexpected result");
1157a34c753fSRafael Auler   case IndirectBranchType::POSSIBLE_TAIL_CALL: {
1158a34c753fSRafael Auler     bool Result = MIB->convertJmpToTailCall(Instruction);
1159a34c753fSRafael Auler     (void)Result;
1160a34c753fSRafael Auler     assert(Result);
1161a34c753fSRafael Auler     break;
1162a34c753fSRafael Auler   }
1163a34c753fSRafael Auler   case IndirectBranchType::POSSIBLE_JUMP_TABLE:
1164a34c753fSRafael Auler   case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE:
11653023b15fSAmir Ayupov   case IndirectBranchType::POSSIBLE_PIC_FIXED_BRANCH:
1166a34c753fSRafael Auler     if (opts::JumpTables == JTS_NONE)
1167a34c753fSRafael Auler       IsSimple = false;
1168a34c753fSRafael Auler     break;
1169a34c753fSRafael Auler   case IndirectBranchType::POSSIBLE_FIXED_BRANCH: {
1170a34c753fSRafael Auler     if (containsAddress(IndirectTarget)) {
1171a34c753fSRafael Auler       const MCSymbol *TargetSymbol = getOrCreateLocalLabel(IndirectTarget);
1172a34c753fSRafael Auler       Instruction.clear();
1173a34c753fSRafael Auler       MIB->createUncondBranch(Instruction, TargetSymbol, BC.Ctx.get());
1174a34c753fSRafael Auler       TakenBranches.emplace_back(Offset, IndirectTarget - getAddress());
11755b595406SVladislav Khmelevsky       addEntryPointAtOffset(IndirectTarget - getAddress());
1176a34c753fSRafael Auler     } else {
1177a34c753fSRafael Auler       MIB->convertJmpToTailCall(Instruction);
117835efe1d8SVladislav Khmelevsky       BC.addInterproceduralReference(this, IndirectTarget);
1179a34c753fSRafael Auler     }
1180a34c753fSRafael Auler     break;
1181a34c753fSRafael Auler   }
1182a34c753fSRafael Auler   case IndirectBranchType::UNKNOWN:
1183a34c753fSRafael Auler     // Keep processing. We'll do more checks and fixes in
1184a34c753fSRafael Auler     // postProcessIndirectBranches().
1185a34c753fSRafael Auler     UnknownIndirectBranchOffsets.emplace(Offset);
1186a34c753fSRafael Auler     break;
1187a34c753fSRafael Auler   }
1188c844850bSAmir Ayupov }
1189c844850bSAmir Ayupov 
119037cbbea6SAmir Ayupov void BinaryFunction::handleAArch64IndirectCall(MCInst &Instruction,
119137cbbea6SAmir Ayupov                                                const uint64_t Offset) {
1192c844850bSAmir Ayupov   auto &MIB = BC.MIB;
1193a34c753fSRafael Auler   const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1194a34c753fSRafael Auler   MCInst *TargetHiBits, *TargetLowBits;
119535efe1d8SVladislav Khmelevsky   uint64_t TargetAddress, Count;
119635efe1d8SVladislav Khmelevsky   Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1197a34c753fSRafael Auler                                  AbsoluteInstrAddr, Instruction, TargetHiBits,
119835efe1d8SVladislav Khmelevsky                                  TargetLowBits, TargetAddress);
119935efe1d8SVladislav Khmelevsky   if (Count) {
1200a34c753fSRafael Auler     MIB->addAnnotation(Instruction, "AArch64Veneer", true);
120135efe1d8SVladislav Khmelevsky     --Count;
120235efe1d8SVladislav Khmelevsky     for (auto It = std::prev(Instructions.end()); Count != 0;
120335efe1d8SVladislav Khmelevsky          It = std::prev(It), --Count) {
1204a34c753fSRafael Auler       MIB->addAnnotation(It->second, "AArch64Veneer", true);
1205a34c753fSRafael Auler     }
1206a34c753fSRafael Auler 
120735efe1d8SVladislav Khmelevsky     BC.addAdrpAddRelocAArch64(*this, *TargetLowBits, *TargetHiBits,
120835efe1d8SVladislav Khmelevsky                               TargetAddress);
1209a34c753fSRafael Auler   }
121037cbbea6SAmir Ayupov }
121137cbbea6SAmir Ayupov 
1212db29f20fSAmir Ayupov std::optional<MCInst>
1213db29f20fSAmir Ayupov BinaryFunction::disassembleInstructionAtOffset(uint64_t Offset) const {
1214db29f20fSAmir Ayupov   assert(CurrentState == State::Empty && "Function should not be disassembled");
1215db29f20fSAmir Ayupov   assert(Offset < MaxSize && "Invalid offset");
1216db29f20fSAmir Ayupov   ErrorOr<ArrayRef<unsigned char>> FunctionData = getData();
1217db29f20fSAmir Ayupov   assert(FunctionData && "Cannot get function as data");
1218db29f20fSAmir Ayupov   MCInst Instr;
1219db29f20fSAmir Ayupov   uint64_t InstrSize = 0;
1220db29f20fSAmir Ayupov   const uint64_t InstrAddress = getAddress() + Offset;
1221db29f20fSAmir Ayupov   if (BC.DisAsm->getInstruction(Instr, InstrSize, FunctionData->slice(Offset),
1222db29f20fSAmir Ayupov                                 InstrAddress, nulls()))
1223db29f20fSAmir Ayupov     return Instr;
1224db29f20fSAmir Ayupov   return std::nullopt;
1225db29f20fSAmir Ayupov }
1226db29f20fSAmir Ayupov 
122713d60ce2SAmir Ayupov Error BinaryFunction::disassemble() {
122837cbbea6SAmir Ayupov   NamedRegionTimer T("disassemble", "Disassemble function", "buildfuncs",
122937cbbea6SAmir Ayupov                      "Build Binary Functions", opts::TimeBuild);
123037cbbea6SAmir Ayupov   ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
123137cbbea6SAmir Ayupov   assert(ErrorOrFunctionData && "function data is not available");
123237cbbea6SAmir Ayupov   ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
123337cbbea6SAmir Ayupov   assert(FunctionData.size() == getMaxSize() &&
123437cbbea6SAmir Ayupov          "function size does not match raw data size");
123537cbbea6SAmir Ayupov 
123637cbbea6SAmir Ayupov   auto &Ctx = BC.Ctx;
123737cbbea6SAmir Ayupov   auto &MIB = BC.MIB;
123837cbbea6SAmir Ayupov 
123937cbbea6SAmir Ayupov   BC.SymbolicDisAsm->setSymbolizer(MIB->createTargetSymbolizer(*this));
124037cbbea6SAmir Ayupov 
124137cbbea6SAmir Ayupov   // Insert a label at the beginning of the function. This will be our first
124237cbbea6SAmir Ayupov   // basic block.
124337cbbea6SAmir Ayupov   Labels[0] = Ctx->createNamedTempSymbol("BB0");
1244a34c753fSRafael Auler 
1245ff5e2babSJob Noorman   // Map offsets in the function to a label that should always point to the
1246ff5e2babSJob Noorman   // corresponding instruction. This is used for labels that shouldn't point to
1247ff5e2babSJob Noorman   // the start of a basic block but always to a specific instruction. This is
1248ff5e2babSJob Noorman   // used, for example, on RISC-V where %pcrel_lo relocations point to the
1249ff5e2babSJob Noorman   // corresponding %pcrel_hi.
1250ff5e2babSJob Noorman   LabelsMapType InstructionLabels;
1251ff5e2babSJob Noorman 
1252a34c753fSRafael Auler   uint64_t Size = 0; // instruction size
1253a34c753fSRafael Auler   for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1254a34c753fSRafael Auler     MCInst Instruction;
1255a34c753fSRafael Auler     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1256a34c753fSRafael Auler 
1257a34c753fSRafael Auler     // Check for data inside code and ignore it
1258a34c753fSRafael Auler     if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1259a34c753fSRafael Auler       Size = DataInCodeSize;
1260a34c753fSRafael Auler       continue;
1261a34c753fSRafael Auler     }
1262a34c753fSRafael Auler 
1263e290133cSMaksim Panchenko     if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size,
1264a34c753fSRafael Auler                                            FunctionData.slice(Offset),
126540c2e0faSMaksim Panchenko                                            AbsoluteInstrAddr, nulls())) {
1266a34c753fSRafael Auler       // Functions with "soft" boundaries, e.g. coming from assembly source,
1267a34c753fSRafael Auler       // can have 0-byte padding at the end.
1268a34c753fSRafael Auler       if (isZeroPaddingAt(Offset))
1269a34c753fSRafael Auler         break;
1270a34c753fSRafael Auler 
127152cf0711SAmir Ayupov       BC.errs()
127252cf0711SAmir Ayupov           << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1273a34c753fSRafael Auler           << Twine::utohexstr(Offset) << " (address 0x"
127440c2e0faSMaksim Panchenko           << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " << *this
127540c2e0faSMaksim Panchenko           << '\n';
1276a34c753fSRafael Auler       // Some AVX-512 instructions could not be disassembled at all.
1277a34c753fSRafael Auler       if (BC.HasRelocations && opts::TrapOnAVX512 && BC.isX86()) {
1278a34c753fSRafael Auler         setTrapOnEntry();
1279a34c753fSRafael Auler         BC.TrappedFunctions.push_back(this);
1280a34c753fSRafael Auler       } else {
1281a34c753fSRafael Auler         setIgnored();
1282a34c753fSRafael Auler       }
1283a34c753fSRafael Auler 
1284a34c753fSRafael Auler       break;
1285a34c753fSRafael Auler     }
1286a34c753fSRafael Auler 
1287a34c753fSRafael Auler     // Check integrity of LLVM assembler/disassembler.
1288a34c753fSRafael Auler     if (opts::CheckEncoding && !BC.MIB->isBranch(Instruction) &&
1289a34c753fSRafael Auler         !BC.MIB->isCall(Instruction) && !BC.MIB->isNoop(Instruction)) {
1290bcc4c909SMaksim Panchenko       if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) {
129152cf0711SAmir Ayupov         BC.errs() << "BOLT-WARNING: mismatching LLVM encoding detected in "
1292a34c753fSRafael Auler                   << "function " << *this << " for instruction :\n";
129352cf0711SAmir Ayupov         BC.printInstruction(BC.errs(), Instruction, AbsoluteInstrAddr);
129452cf0711SAmir Ayupov         BC.errs() << '\n';
1295a34c753fSRafael Auler       }
1296a34c753fSRafael Auler     }
1297a34c753fSRafael Auler 
1298a34c753fSRafael Auler     // Special handling for AVX-512 instructions.
1299a34c753fSRafael Auler     if (MIB->hasEVEXEncoding(Instruction)) {
1300a34c753fSRafael Auler       if (BC.HasRelocations && opts::TrapOnAVX512) {
1301a34c753fSRafael Auler         setTrapOnEntry();
1302a34c753fSRafael Auler         BC.TrappedFunctions.push_back(this);
1303a34c753fSRafael Auler         break;
1304a34c753fSRafael Auler       }
1305a34c753fSRafael Auler 
1306bcc4c909SMaksim Panchenko       if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) {
130752cf0711SAmir Ayupov         BC.errs() << "BOLT-WARNING: internal assembler/disassembler error "
1308a34c753fSRafael Auler                      "detected for AVX512 instruction:\n";
130952cf0711SAmir Ayupov         BC.printInstruction(BC.errs(), Instruction, AbsoluteInstrAddr);
131052cf0711SAmir Ayupov         BC.errs() << " in function " << *this << '\n';
1311a34c753fSRafael Auler         setIgnored();
1312a34c753fSRafael Auler         break;
1313a34c753fSRafael Auler       }
1314a34c753fSRafael Auler     }
1315a34c753fSRafael Auler 
13166c5b62b8SNathan Sidwell     bool IsUnsupported = BC.MIB->isUnsupportedInstruction(Instruction);
13176c5b62b8SNathan Sidwell     if (IsUnsupported)
13186c5b62b8SNathan Sidwell       setIgnored();
13196c5b62b8SNathan Sidwell 
1320a34c753fSRafael Auler     if (MIB->isBranch(Instruction) || MIB->isCall(Instruction)) {
1321a34c753fSRafael Auler       uint64_t TargetAddress = 0;
1322a34c753fSRafael Auler       if (MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1323a34c753fSRafael Auler                               TargetAddress)) {
1324a34c753fSRafael Auler         // Check if the target is within the same function. Otherwise it's
1325a34c753fSRafael Auler         // a call, possibly a tail call.
1326a34c753fSRafael Auler         //
1327a34c753fSRafael Auler         // If the target *is* the function address it could be either a branch
1328a34c753fSRafael Auler         // or a recursive call.
1329a34c753fSRafael Auler         bool IsCall = MIB->isCall(Instruction);
1330a34c753fSRafael Auler         const bool IsCondBranch = MIB->isConditionalBranch(Instruction);
1331a34c753fSRafael Auler         MCSymbol *TargetSymbol = nullptr;
1332a34c753fSRafael Auler 
13336c5b62b8SNathan Sidwell         if (IsUnsupported)
13346c5b62b8SNathan Sidwell           if (auto *TargetFunc =
1335a34c753fSRafael Auler                   BC.getBinaryFunctionContainingAddress(TargetAddress))
1336a34c753fSRafael Auler             TargetFunc->setIgnored();
1337a34c753fSRafael Auler 
1338abd69b36SMaksim Panchenko         if (IsCall && TargetAddress == getAddress()) {
1339abd69b36SMaksim Panchenko           // A recursive call. Calls to internal blocks are handled by
1340abd69b36SMaksim Panchenko           // ValidateInternalCalls pass.
1341a34c753fSRafael Auler           TargetSymbol = getSymbol();
1342a34c753fSRafael Auler         }
1343a34c753fSRafael Auler 
1344a34c753fSRafael Auler         if (!TargetSymbol) {
1345a34c753fSRafael Auler           // Create either local label or external symbol.
1346a34c753fSRafael Auler           if (containsAddress(TargetAddress)) {
1347a34c753fSRafael Auler             TargetSymbol = getOrCreateLocalLabel(TargetAddress);
1348a34c753fSRafael Auler           } else {
1349a34c753fSRafael Auler             if (TargetAddress == getAddress() + getSize() &&
135035efe1d8SVladislav Khmelevsky                 TargetAddress < getAddress() + getMaxSize() &&
135135efe1d8SVladislav Khmelevsky                 !(BC.isAArch64() &&
135235efe1d8SVladislav Khmelevsky                   BC.handleAArch64Veneer(TargetAddress, /*MatchOnly*/ true))) {
1353a34c753fSRafael Auler               // Result of __builtin_unreachable().
1354a34c753fSRafael Auler               LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump past end detected at 0x"
1355a34c753fSRafael Auler                                 << Twine::utohexstr(AbsoluteInstrAddr)
1356a34c753fSRafael Auler                                 << " in function " << *this
1357a34c753fSRafael Auler                                 << " : replacing with nop.\n");
1358a34c753fSRafael Auler               BC.MIB->createNoop(Instruction);
1359a34c753fSRafael Auler               if (IsCondBranch) {
1360a34c753fSRafael Auler                 // Register branch offset for profile validation.
1361a34c753fSRafael Auler                 IgnoredBranches.emplace_back(Offset, Offset + Size);
1362a34c753fSRafael Auler               }
1363a34c753fSRafael Auler               goto add_instruction;
1364a34c753fSRafael Auler             }
1365a34c753fSRafael Auler             // May update Instruction and IsCall
1366a34c753fSRafael Auler             TargetSymbol = handleExternalReference(Instruction, Size, Offset,
1367a34c753fSRafael Auler                                                    TargetAddress, IsCall);
1368a34c753fSRafael Auler           }
1369a34c753fSRafael Auler         }
1370a34c753fSRafael Auler 
1371a34c753fSRafael Auler         if (!IsCall) {
1372a34c753fSRafael Auler           // Add taken branch info.
1373a34c753fSRafael Auler           TakenBranches.emplace_back(Offset, TargetAddress - getAddress());
1374a34c753fSRafael Auler         }
1375a34c753fSRafael Auler         BC.MIB->replaceBranchTarget(Instruction, TargetSymbol, &*Ctx);
1376a34c753fSRafael Auler 
1377a34c753fSRafael Auler         // Mark CTC.
13783652483cSRafael Auler         if (IsCondBranch && IsCall)
1379a34c753fSRafael Auler           MIB->setConditionalTailCall(Instruction, TargetAddress);
1380a34c753fSRafael Auler       } else {
1381a34c753fSRafael Auler         // Could not evaluate branch. Should be an indirect call or an
1382a34c753fSRafael Auler         // indirect branch. Bail out on the latter case.
1383a34c753fSRafael Auler         if (MIB->isIndirectBranch(Instruction))
1384a34c753fSRafael Auler           handleIndirectBranch(Instruction, Size, Offset);
1385a34c753fSRafael Auler         // Indirect call. We only need to fix it if the operand is RIP-relative.
138613d60ce2SAmir Ayupov         if (IsSimple && MIB->hasPCRelOperand(Instruction)) {
138713d60ce2SAmir Ayupov           if (auto NewE = handleErrors(
138813d60ce2SAmir Ayupov                   handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size),
138913d60ce2SAmir Ayupov                   [&](const BOLTError &E) -> Error {
139013d60ce2SAmir Ayupov                     if (E.isFatal())
139113d60ce2SAmir Ayupov                       return Error(std::make_unique<BOLTError>(std::move(E)));
139213d60ce2SAmir Ayupov                     if (!E.getMessage().empty())
139352cf0711SAmir Ayupov                       E.log(BC.errs());
139413d60ce2SAmir Ayupov                     return Error::success();
139513d60ce2SAmir Ayupov                   })) {
139613d60ce2SAmir Ayupov             return Error(std::move(NewE));
139713d60ce2SAmir Ayupov           }
139813d60ce2SAmir Ayupov         }
1399a34c753fSRafael Auler 
1400a34c753fSRafael Auler         if (BC.isAArch64())
1401a34c753fSRafael Auler           handleAArch64IndirectCall(Instruction, Offset);
1402a34c753fSRafael Auler       }
1403f8730293SJob Noorman     } else if (BC.isAArch64() || BC.isRISCV()) {
14044101aa13SMaksim Panchenko       // Check if there's a relocation associated with this instruction.
14054101aa13SMaksim Panchenko       bool UsedReloc = false;
14064101aa13SMaksim Panchenko       for (auto Itr = Relocations.lower_bound(Offset),
14074101aa13SMaksim Panchenko                 ItrE = Relocations.lower_bound(Offset + Size);
14084101aa13SMaksim Panchenko            Itr != ItrE; ++Itr) {
14094101aa13SMaksim Panchenko         const Relocation &Relocation = Itr->second;
1410ff5e2babSJob Noorman         MCSymbol *Symbol = Relocation.Symbol;
1411ff5e2babSJob Noorman 
1412ff5e2babSJob Noorman         if (Relocation::isInstructionReference(Relocation.Type)) {
1413ff5e2babSJob Noorman           uint64_t RefOffset = Relocation.Value - getAddress();
1414ff5e2babSJob Noorman           LabelsMapType::iterator LI = InstructionLabels.find(RefOffset);
1415ff5e2babSJob Noorman 
1416ff5e2babSJob Noorman           if (LI == InstructionLabels.end()) {
1417ff5e2babSJob Noorman             Symbol = BC.Ctx->createNamedTempSymbol();
1418ff5e2babSJob Noorman             InstructionLabels.emplace(RefOffset, Symbol);
1419ff5e2babSJob Noorman           } else {
1420ff5e2babSJob Noorman             Symbol = LI->second;
1421ff5e2babSJob Noorman           }
1422ff5e2babSJob Noorman         }
1423ff5e2babSJob Noorman 
14244101aa13SMaksim Panchenko         int64_t Value = Relocation.Value;
14254101aa13SMaksim Panchenko         const bool Result = BC.MIB->replaceImmWithSymbolRef(
1426ff5e2babSJob Noorman             Instruction, Symbol, Relocation.Addend, Ctx.get(), Value,
1427e290133cSMaksim Panchenko             Relocation.Type);
14284101aa13SMaksim Panchenko         (void)Result;
14294101aa13SMaksim Panchenko         assert(Result && "cannot replace immediate with relocation");
14304101aa13SMaksim Panchenko 
1431e290133cSMaksim Panchenko         // For aarch64, if we replaced an immediate with a symbol from a
14324101aa13SMaksim Panchenko         // relocation, we mark it so we do not try to further process a
14334101aa13SMaksim Panchenko         // pc-relative operand. All we need is the symbol.
14344101aa13SMaksim Panchenko         UsedReloc = true;
14354101aa13SMaksim Panchenko       }
14364101aa13SMaksim Panchenko 
143713d60ce2SAmir Ayupov       if (!BC.isRISCV() && MIB->hasPCRelOperand(Instruction) && !UsedReloc) {
143813d60ce2SAmir Ayupov         if (auto NewE = handleErrors(
143913d60ce2SAmir Ayupov                 handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size),
144013d60ce2SAmir Ayupov                 [&](const BOLTError &E) -> Error {
144113d60ce2SAmir Ayupov                   if (E.isFatal())
144213d60ce2SAmir Ayupov                     return Error(std::make_unique<BOLTError>(std::move(E)));
144313d60ce2SAmir Ayupov                   if (!E.getMessage().empty())
144452cf0711SAmir Ayupov                     E.log(BC.errs());
144513d60ce2SAmir Ayupov                   return Error::success();
144613d60ce2SAmir Ayupov                 }))
144713d60ce2SAmir Ayupov           return Error(std::move(NewE));
144813d60ce2SAmir Ayupov       }
14493652483cSRafael Auler     }
1450a34c753fSRafael Auler 
1451a34c753fSRafael Auler add_instruction:
1452a34c753fSRafael Auler     if (getDWARFLineTable()) {
145340c2e0faSMaksim Panchenko       Instruction.setLoc(findDebugLineInformationForInstructionAt(
145440c2e0faSMaksim Panchenko           AbsoluteInstrAddr, getDWARFUnit(), getDWARFLineTable()));
1455a34c753fSRafael Auler     }
1456a34c753fSRafael Auler 
1457a34c753fSRafael Auler     // Record offset of the instruction for profile matching.
14583652483cSRafael Auler     if (BC.keepOffsetForInstruction(Instruction))
1459a9cd49d5SAmir Ayupov       MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
1460a34c753fSRafael Auler 
1461838331a0SVladislav Khmelevsky     if (BC.isX86() && BC.MIB->isNoop(Instruction)) {
1462838331a0SVladislav Khmelevsky       // NOTE: disassembly loses the correct size information for noops on x86.
146308f56926SVladislav Khmelevsky       //       E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
146408f56926SVladislav Khmelevsky       //       5 bytes. Preserve the size info using annotations.
14652db9b6a9SMaksim Panchenko       MIB->setSize(Instruction, Size);
146608f56926SVladislav Khmelevsky     }
146708f56926SVladislav Khmelevsky 
1468a34c753fSRafael Auler     addInstruction(Offset, std::move(Instruction));
1469a34c753fSRafael Auler   }
1470a34c753fSRafael Auler 
1471ff5e2babSJob Noorman   for (auto [Offset, Label] : InstructionLabels) {
1472ff5e2babSJob Noorman     InstrMapType::iterator II = Instructions.find(Offset);
1473ff5e2babSJob Noorman     assert(II != Instructions.end() && "reference to non-existing instruction");
1474ff5e2babSJob Noorman 
14757c206c78SMaksim Panchenko     BC.MIB->setInstLabel(II->second, Label);
1476ff5e2babSJob Noorman   }
1477ff5e2babSJob Noorman 
1478e290133cSMaksim Panchenko   // Reset symbolizer for the disassembler.
1479e290133cSMaksim Panchenko   BC.SymbolicDisAsm->setSymbolizer(nullptr);
1480e290133cSMaksim Panchenko 
14810b7e8bafSDenis Revunov   if (uint64_t Offset = getFirstInstructionOffset())
14820b7e8bafSDenis Revunov     Labels[Offset] = BC.Ctx->createNamedTempSymbol();
14830b7e8bafSDenis Revunov 
1484a34c753fSRafael Auler   clearList(Relocations);
1485a34c753fSRafael Auler 
1486a34c753fSRafael Auler   if (!IsSimple) {
1487a34c753fSRafael Auler     clearList(Instructions);
148813d60ce2SAmir Ayupov     return createNonFatalBOLTError("");
1489a34c753fSRafael Auler   }
1490a34c753fSRafael Auler 
1491a34c753fSRafael Auler   updateState(State::Disassembled);
1492a34c753fSRafael Auler 
149313d60ce2SAmir Ayupov   return Error::success();
1494a34c753fSRafael Auler }
1495a34c753fSRafael Auler 
1496d7d564b2SMaksim Panchenko MCSymbol *BinaryFunction::registerBranch(uint64_t Src, uint64_t Dst) {
1497d7d564b2SMaksim Panchenko   assert(CurrentState == State::Disassembled &&
1498d7d564b2SMaksim Panchenko          "Cannot register branch unless function is in disassembled state.");
1499d7d564b2SMaksim Panchenko   assert(containsAddress(Src) && containsAddress(Dst) &&
1500d7d564b2SMaksim Panchenko          "Cannot register external branch.");
1501d7d564b2SMaksim Panchenko   MCSymbol *Target = getOrCreateLocalLabel(Dst);
1502d7d564b2SMaksim Panchenko   TakenBranches.emplace_back(Src - getAddress(), Dst - getAddress());
1503d7d564b2SMaksim Panchenko   return Target;
1504d7d564b2SMaksim Panchenko }
1505d7d564b2SMaksim Panchenko 
15063c357a49SAlexander Yermolovich void BinaryFunction::analyzeInstructionForFuncReference(const MCInst &Inst) {
15073c357a49SAlexander Yermolovich   for (const MCOperand &Op : MCPlus::primeOperands(Inst)) {
15083c357a49SAlexander Yermolovich     if (!Op.isExpr())
15093c357a49SAlexander Yermolovich       continue;
15103c357a49SAlexander Yermolovich     const MCExpr &Expr = *Op.getExpr();
15113c357a49SAlexander Yermolovich     if (Expr.getKind() != MCExpr::SymbolRef)
15123c357a49SAlexander Yermolovich       continue;
15133c357a49SAlexander Yermolovich     const MCSymbol &Symbol = cast<MCSymbolRefExpr>(Expr).getSymbol();
15143c357a49SAlexander Yermolovich     // Set HasAddressTaken for a function regardless of the ICF level.
15153c357a49SAlexander Yermolovich     if (BinaryFunction *BF = BC.getFunctionForSymbol(&Symbol))
15163c357a49SAlexander Yermolovich       BF->setHasAddressTaken(true);
15173c357a49SAlexander Yermolovich   }
15183c357a49SAlexander Yermolovich }
15193c357a49SAlexander Yermolovich 
1520a34c753fSRafael Auler bool BinaryFunction::scanExternalRefs() {
1521a34c753fSRafael Auler   bool Success = true;
1522a34c753fSRafael Auler   bool DisassemblyFailed = false;
1523a34c753fSRafael Auler 
1524a34c753fSRafael Auler   // Ignore pseudo functions.
1525a34c753fSRafael Auler   if (isPseudo())
1526a34c753fSRafael Auler     return Success;
1527a34c753fSRafael Auler 
1528a34c753fSRafael Auler   if (opts::NoScan) {
1529a34c753fSRafael Auler     clearList(Relocations);
1530a34c753fSRafael Auler     clearList(ExternallyReferencedOffsets);
1531a34c753fSRafael Auler 
1532a34c753fSRafael Auler     return false;
1533a34c753fSRafael Auler   }
1534a34c753fSRafael Auler 
1535a34c753fSRafael Auler   // List of external references for this function.
1536a34c753fSRafael Auler   std::vector<Relocation> FunctionRelocations;
1537a34c753fSRafael Auler 
1538a34c753fSRafael Auler   static BinaryContext::IndependentCodeEmitter Emitter =
1539a34c753fSRafael Auler       BC.createIndependentMCCodeEmitter();
1540a34c753fSRafael Auler 
1541a34c753fSRafael Auler   ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1542a34c753fSRafael Auler   assert(ErrorOrFunctionData && "function data is not available");
1543a34c753fSRafael Auler   ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1544a34c753fSRafael Auler   assert(FunctionData.size() == getMaxSize() &&
1545a34c753fSRafael Auler          "function size does not match raw data size");
1546a34c753fSRafael Auler 
154743f56a2fSMaksim Panchenko   BC.SymbolicDisAsm->setSymbolizer(
154843f56a2fSMaksim Panchenko       BC.MIB->createTargetSymbolizer(*this, /*CreateSymbols*/ false));
154943f56a2fSMaksim Panchenko 
155043f56a2fSMaksim Panchenko   // Disassemble contents of the function. Detect code entry points and create
155143f56a2fSMaksim Panchenko   // relocations for references to code that will be moved.
1552a34c753fSRafael Auler   uint64_t Size = 0; // instruction size
1553a34c753fSRafael Auler   for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1554a34c753fSRafael Auler     // Check for data inside code and ignore it
1555a34c753fSRafael Auler     if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1556a34c753fSRafael Auler       Size = DataInCodeSize;
1557a34c753fSRafael Auler       continue;
1558a34c753fSRafael Auler     }
1559a34c753fSRafael Auler 
1560a34c753fSRafael Auler     const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1561a34c753fSRafael Auler     MCInst Instruction;
156243f56a2fSMaksim Panchenko     if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size,
1563a34c753fSRafael Auler                                            FunctionData.slice(Offset),
156440c2e0faSMaksim Panchenko                                            AbsoluteInstrAddr, nulls())) {
1565a34c753fSRafael Auler       if (opts::Verbosity >= 1 && !isZeroPaddingAt(Offset)) {
156652cf0711SAmir Ayupov         BC.errs()
156752cf0711SAmir Ayupov             << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1568a34c753fSRafael Auler             << Twine::utohexstr(Offset) << " (address 0x"
156952cf0711SAmir Ayupov             << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " << *this
157052cf0711SAmir Ayupov             << '\n';
1571a34c753fSRafael Auler       }
1572a34c753fSRafael Auler       Success = false;
1573a34c753fSRafael Auler       DisassemblyFailed = true;
1574a34c753fSRafael Auler       break;
1575a34c753fSRafael Auler     }
1576a34c753fSRafael Auler 
1577a34c753fSRafael Auler     // Return true if we can skip handling the Target function reference.
1578a34c753fSRafael Auler     auto ignoreFunctionRef = [&](const BinaryFunction &Target) {
1579a34c753fSRafael Auler       if (&Target == this)
1580a34c753fSRafael Auler         return true;
1581a34c753fSRafael Auler 
1582a34c753fSRafael Auler       // Note that later we may decide not to emit Target function. In that
1583a34c753fSRafael Auler       // case, we conservatively create references that will be ignored or
1584a34c753fSRafael Auler       // resolved to the same function.
1585a34c753fSRafael Auler       if (!BC.shouldEmit(Target))
1586a34c753fSRafael Auler         return true;
1587a34c753fSRafael Auler 
1588a34c753fSRafael Auler       return false;
1589a34c753fSRafael Auler     };
1590a34c753fSRafael Auler 
1591a34c753fSRafael Auler     // Return true if we can ignore reference to the symbol.
1592a34c753fSRafael Auler     auto ignoreReference = [&](const MCSymbol *TargetSymbol) {
1593a34c753fSRafael Auler       if (!TargetSymbol)
1594a34c753fSRafael Auler         return true;
1595a34c753fSRafael Auler 
1596a34c753fSRafael Auler       if (BC.forceSymbolRelocations(TargetSymbol->getName()))
1597a34c753fSRafael Auler         return false;
1598a34c753fSRafael Auler 
1599a34c753fSRafael Auler       BinaryFunction *TargetFunction = BC.getFunctionForSymbol(TargetSymbol);
1600a34c753fSRafael Auler       if (!TargetFunction)
1601a34c753fSRafael Auler         return true;
1602a34c753fSRafael Auler 
1603a34c753fSRafael Auler       return ignoreFunctionRef(*TargetFunction);
1604a34c753fSRafael Auler     };
1605a34c753fSRafael Auler 
160643f56a2fSMaksim Panchenko     // Handle calls and branches separately as symbolization doesn't work for
160743f56a2fSMaksim Panchenko     // them yet.
160843f56a2fSMaksim Panchenko     MCSymbol *BranchTargetSymbol = nullptr;
160943f56a2fSMaksim Panchenko     if (BC.MIB->isCall(Instruction) || BC.MIB->isBranch(Instruction)) {
1610a34c753fSRafael Auler       uint64_t TargetAddress = 0;
161143f56a2fSMaksim Panchenko       BC.MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1612cdef841fSAmir Ayupov                              TargetAddress);
1613a34c753fSRafael Auler 
1614a34c753fSRafael Auler       // Create an entry point at reference address if needed.
1615a34c753fSRafael Auler       BinaryFunction *TargetFunction =
1616a34c753fSRafael Auler           BC.getBinaryFunctionContainingAddress(TargetAddress);
161743f56a2fSMaksim Panchenko 
161843f56a2fSMaksim Panchenko       if (!TargetFunction || ignoreFunctionRef(*TargetFunction))
161943f56a2fSMaksim Panchenko         continue;
162043f56a2fSMaksim Panchenko 
1621a34c753fSRafael Auler       const uint64_t FunctionOffset =
1622a34c753fSRafael Auler           TargetAddress - TargetFunction->getAddress();
162343f56a2fSMaksim Panchenko       BranchTargetSymbol =
162443f56a2fSMaksim Panchenko           FunctionOffset ? TargetFunction->addEntryPointAtOffset(FunctionOffset)
1625a34c753fSRafael Auler                          : TargetFunction->getSymbol();
1626a34c753fSRafael Auler     }
1627a34c753fSRafael Auler 
162843f56a2fSMaksim Panchenko     // Can't find more references. Not creating relocations since we are not
162943f56a2fSMaksim Panchenko     // moving code.
1630a34c753fSRafael Auler     if (!BC.HasRelocations)
1631a34c753fSRafael Auler       continue;
1632a34c753fSRafael Auler 
163343f56a2fSMaksim Panchenko     if (BranchTargetSymbol) {
163443f56a2fSMaksim Panchenko       BC.MIB->replaceBranchTarget(Instruction, BranchTargetSymbol,
1635a34c753fSRafael Auler                                   Emitter.LocalCtx.get());
163643f56a2fSMaksim Panchenko     } else if (!llvm::any_of(Instruction,
163743f56a2fSMaksim Panchenko                              [](const MCOperand &Op) { return Op.isExpr(); })) {
163843f56a2fSMaksim Panchenko       // Skip assembly if the instruction may not have any symbolic operands.
16394101aa13SMaksim Panchenko       continue;
16403c357a49SAlexander Yermolovich     } else {
16413c357a49SAlexander Yermolovich       analyzeInstructionForFuncReference(Instruction);
1642a34c753fSRafael Auler     }
1643a34c753fSRafael Auler 
1644a34c753fSRafael Auler     // Emit the instruction using temp emitter and generate relocations.
1645a34c753fSRafael Auler     SmallString<256> Code;
1646a34c753fSRafael Auler     SmallVector<MCFixup, 4> Fixups;
16470c049ea6SAlexis Engelke     Emitter.MCE->encodeInstruction(Instruction, Code, Fixups, *BC.STI);
1648a34c753fSRafael Auler 
1649a34c753fSRafael Auler     // Create relocation for every fixup.
1650a34c753fSRafael Auler     for (const MCFixup &Fixup : Fixups) {
16512563fd63SAmir Ayupov       std::optional<Relocation> Rel = BC.MIB->createRelocation(Fixup, *BC.MAB);
1652a34c753fSRafael Auler       if (!Rel) {
1653a34c753fSRafael Auler         Success = false;
1654a34c753fSRafael Auler         continue;
1655a34c753fSRafael Auler       }
1656a34c753fSRafael Auler 
165743f56a2fSMaksim Panchenko       if (ignoreReference(Rel->Symbol))
165843f56a2fSMaksim Panchenko         continue;
165943f56a2fSMaksim Panchenko 
1660a34c753fSRafael Auler       if (Relocation::getSizeForType(Rel->Type) < 4) {
1661a34c753fSRafael Auler         // If the instruction uses a short form, then we might not be able
1662a34c753fSRafael Auler         // to handle the rewrite without relaxation, and hence cannot reliably
1663a34c753fSRafael Auler         // create an external reference relocation.
1664a34c753fSRafael Auler         Success = false;
1665a34c753fSRafael Auler         continue;
1666a34c753fSRafael Auler       }
1667a34c753fSRafael Auler       Rel->Offset += getAddress() - getOriginSection()->getAddress() + Offset;
1668a34c753fSRafael Auler       FunctionRelocations.push_back(*Rel);
1669a34c753fSRafael Auler     }
1670a34c753fSRafael Auler 
1671a34c753fSRafael Auler     if (!Success)
1672a34c753fSRafael Auler       break;
1673a34c753fSRafael Auler   }
1674a34c753fSRafael Auler 
167543f56a2fSMaksim Panchenko   // Reset symbolizer for the disassembler.
167643f56a2fSMaksim Panchenko   BC.SymbolicDisAsm->setSymbolizer(nullptr);
167743f56a2fSMaksim Panchenko 
1678a34c753fSRafael Auler   // Add relocations unless disassembly failed for this function.
16793652483cSRafael Auler   if (!DisassemblyFailed)
16803652483cSRafael Auler     for (Relocation &Rel : FunctionRelocations)
1681a34c753fSRafael Auler       getOriginSection()->addPendingRelocation(Rel);
1682a34c753fSRafael Auler 
1683a34c753fSRafael Auler   // Inform BinaryContext that this function symbols will not be defined and
1684a34c753fSRafael Auler   // relocations should not be created against them.
1685a34c753fSRafael Auler   if (BC.HasRelocations) {
16863652483cSRafael Auler     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
1687a34c753fSRafael Auler       BC.UndefinedSymbols.insert(LI.second);
1688a191ea7dSFabian Parzefall     for (MCSymbol *const EndLabel : FunctionEndLabels)
1689a191ea7dSFabian Parzefall       if (EndLabel)
1690a191ea7dSFabian Parzefall         BC.UndefinedSymbols.insert(EndLabel);
1691a34c753fSRafael Auler   }
1692a34c753fSRafael Auler 
1693a34c753fSRafael Auler   clearList(Relocations);
1694a34c753fSRafael Auler   clearList(ExternallyReferencedOffsets);
1695a34c753fSRafael Auler 
16963652483cSRafael Auler   if (Success && BC.HasRelocations)
1697a34c753fSRafael Auler     HasExternalRefRelocations = true;
1698a34c753fSRafael Auler 
16993652483cSRafael Auler   if (opts::Verbosity >= 1 && !Success)
170052cf0711SAmir Ayupov     BC.outs() << "BOLT-INFO: failed to scan refs for  " << *this << '\n';
1701a34c753fSRafael Auler 
1702a34c753fSRafael Auler   return Success;
1703a34c753fSRafael Auler }
1704a34c753fSRafael Auler 
1705a34c753fSRafael Auler void BinaryFunction::postProcessEntryPoints() {
1706a34c753fSRafael Auler   if (!isSimple())
1707a34c753fSRafael Auler     return;
1708a34c753fSRafael Auler 
1709a34c753fSRafael Auler   for (auto &KV : Labels) {
1710a34c753fSRafael Auler     MCSymbol *Label = KV.second;
1711a34c753fSRafael Auler     if (!getSecondaryEntryPointSymbol(Label))
1712a34c753fSRafael Auler       continue;
1713a34c753fSRafael Auler 
1714a34c753fSRafael Auler     // In non-relocation mode there's potentially an external undetectable
1715a34c753fSRafael Auler     // reference to the entry point and hence we cannot move this entry
1716a34c753fSRafael Auler     // point. Optimizing without moving could be difficult.
1717935b946bSAmir Ayupov     // In BAT mode, register any known entry points for CFG construction.
1718935b946bSAmir Ayupov     if (!BC.HasRelocations && !BC.HasBATSection)
1719a34c753fSRafael Auler       setSimple(false);
1720a34c753fSRafael Auler 
1721a34c753fSRafael Auler     const uint32_t Offset = KV.first;
1722a34c753fSRafael Auler 
1723a34c753fSRafael Auler     // If we are at Offset 0 and there is no instruction associated with it,
1724a34c753fSRafael Auler     // this means this is an empty function. Just ignore. If we find an
1725a34c753fSRafael Auler     // instruction at this offset, this entry point is valid.
17263652483cSRafael Auler     if (!Offset || getInstructionAtOffset(Offset))
1727a34c753fSRafael Auler       continue;
1728a34c753fSRafael Auler 
1729a34c753fSRafael Auler     // On AArch64 there are legitimate reasons to have references past the
1730a34c753fSRafael Auler     // end of the function, e.g. jump tables.
17313652483cSRafael Auler     if (BC.isAArch64() && Offset == getSize())
1732a34c753fSRafael Auler       continue;
1733a34c753fSRafael Auler 
173452cf0711SAmir Ayupov     BC.errs() << "BOLT-WARNING: reference in the middle of instruction "
173540c2e0faSMaksim Panchenko                  "detected in function "
173640c2e0faSMaksim Panchenko               << *this << " at offset 0x" << Twine::utohexstr(Offset) << '\n';
17373652483cSRafael Auler     if (BC.HasRelocations)
1738a34c753fSRafael Auler       setIgnored();
1739a34c753fSRafael Auler     setSimple(false);
1740a34c753fSRafael Auler     return;
1741a34c753fSRafael Auler   }
1742a34c753fSRafael Auler }
1743a34c753fSRafael Auler 
1744a34c753fSRafael Auler void BinaryFunction::postProcessJumpTables() {
1745a34c753fSRafael Auler   // Create labels for all entries.
1746a34c753fSRafael Auler   for (auto &JTI : JumpTables) {
1747a34c753fSRafael Auler     JumpTable &JT = *JTI.second;
1748a34c753fSRafael Auler     if (JT.Type == JumpTable::JTT_PIC && opts::JumpTables == JTS_BASIC) {
1749a34c753fSRafael Auler       opts::JumpTables = JTS_MOVE;
175052cf0711SAmir Ayupov       BC.outs() << "BOLT-INFO: forcing -jump-tables=move as PIC jump table was "
175140c2e0faSMaksim Panchenko                    "detected in function "
175240c2e0faSMaksim Panchenko                 << *this << '\n';
1753a34c753fSRafael Auler     }
1754a34c753fSRafael Auler     const uint64_t BDSize =
1755a34c753fSRafael Auler         BC.getBinaryDataAtAddress(JT.getAddress())->getSize();
1756a34c753fSRafael Auler     if (!BDSize) {
1757a34c753fSRafael Auler       BC.setBinaryDataSize(JT.getAddress(), JT.getSize());
1758a34c753fSRafael Auler     } else {
1759a34c753fSRafael Auler       assert(BDSize >= JT.getSize() &&
1760a34c753fSRafael Auler              "jump table cannot be larger than the containing object");
1761a34c753fSRafael Auler     }
176259a27170SAmir Ayupov     if (!JT.Entries.empty())
176359a27170SAmir Ayupov       continue;
176459a27170SAmir Ayupov 
176559a27170SAmir Ayupov     bool HasOneParent = (JT.Parents.size() == 1);
176659a27170SAmir Ayupov     for (uint64_t EntryAddress : JT.EntriesAsAddress) {
176759a27170SAmir Ayupov       // builtin_unreachable does not belong to any function
176859a27170SAmir Ayupov       // Need to handle separately
176959a27170SAmir Ayupov       bool IsBuiltinUnreachable =
177059a27170SAmir Ayupov           llvm::any_of(JT.Parents, [&](const BinaryFunction *Parent) {
177159a27170SAmir Ayupov             return EntryAddress == Parent->getAddress() + Parent->getSize();
177259a27170SAmir Ayupov           });
177359a27170SAmir Ayupov       if (IsBuiltinUnreachable) {
177459a27170SAmir Ayupov         MCSymbol *Label = getOrCreateLocalLabel(EntryAddress, true);
177559a27170SAmir Ayupov         JT.Entries.push_back(Label);
177659a27170SAmir Ayupov         continue;
177759a27170SAmir Ayupov       }
1778b6fbb64dSMaksim Panchenko       // Create a local label for targets that cannot be reached by other
1779b6fbb64dSMaksim Panchenko       // fragments. Otherwise, create a secondary entry point in the target
1780b6fbb64dSMaksim Panchenko       // function.
178159a27170SAmir Ayupov       BinaryFunction *TargetBF =
178259a27170SAmir Ayupov           BC.getBinaryFunctionContainingAddress(EntryAddress);
1783b6fbb64dSMaksim Panchenko       MCSymbol *Label;
1784b6fbb64dSMaksim Panchenko       if (HasOneParent && TargetBF == this) {
1785b6fbb64dSMaksim Panchenko         Label = getOrCreateLocalLabel(EntryAddress, true);
1786b6fbb64dSMaksim Panchenko       } else {
1787b6fbb64dSMaksim Panchenko         const uint64_t Offset = EntryAddress - TargetBF->getAddress();
1788b6fbb64dSMaksim Panchenko         Label = Offset ? TargetBF->addEntryPointAtOffset(Offset)
1789b6fbb64dSMaksim Panchenko                        : TargetBF->getSymbol();
179059a27170SAmir Ayupov       }
1791b6fbb64dSMaksim Panchenko       JT.Entries.push_back(Label);
179259a27170SAmir Ayupov     }
1793a34c753fSRafael Auler   }
1794a34c753fSRafael Auler 
1795a34c753fSRafael Auler   // Add TakenBranches from JumpTables.
1796a34c753fSRafael Auler   //
1797a34c753fSRafael Auler   // We want to do it after initial processing since we don't know jump tables'
1798a34c753fSRafael Auler   // boundaries until we process them all.
1799a34c753fSRafael Auler   for (auto &JTSite : JTSites) {
1800a34c753fSRafael Auler     const uint64_t JTSiteOffset = JTSite.first;
1801a34c753fSRafael Auler     const uint64_t JTAddress = JTSite.second;
1802a34c753fSRafael Auler     const JumpTable *JT = getJumpTableContainingAddress(JTAddress);
1803a34c753fSRafael Auler     assert(JT && "cannot find jump table for address");
1804a34c753fSRafael Auler 
1805a34c753fSRafael Auler     uint64_t EntryOffset = JTAddress - JT->getAddress();
1806a34c753fSRafael Auler     while (EntryOffset < JT->getSize()) {
180705523dc3SHuan Nguyen       uint64_t EntryAddress = JT->EntriesAsAddress[EntryOffset / JT->EntrySize];
180805523dc3SHuan Nguyen       uint64_t TargetOffset = EntryAddress - getAddress();
1809a34c753fSRafael Auler       if (TargetOffset < getSize()) {
1810a34c753fSRafael Auler         TakenBranches.emplace_back(JTSiteOffset, TargetOffset);
1811a34c753fSRafael Auler 
1812a34c753fSRafael Auler         if (opts::StrictMode)
1813a34c753fSRafael Auler           registerReferencedOffset(TargetOffset);
1814a34c753fSRafael Auler       }
1815a34c753fSRafael Auler 
1816a34c753fSRafael Auler       EntryOffset += JT->EntrySize;
1817a34c753fSRafael Auler 
1818a34c753fSRafael Auler       // A label at the next entry means the end of this jump table.
1819a34c753fSRafael Auler       if (JT->Labels.count(EntryOffset))
1820a34c753fSRafael Auler         break;
1821a34c753fSRafael Auler     }
1822a34c753fSRafael Auler   }
1823a34c753fSRafael Auler   clearList(JTSites);
1824a34c753fSRafael Auler 
1825a34c753fSRafael Auler   // Conservatively populate all possible destinations for unknown indirect
1826a34c753fSRafael Auler   // branches.
1827a34c753fSRafael Auler   if (opts::StrictMode && hasInternalReference()) {
1828a34c753fSRafael Auler     for (uint64_t Offset : UnknownIndirectBranchOffsets) {
1829a34c753fSRafael Auler       for (uint64_t PossibleDestination : ExternallyReferencedOffsets) {
1830a34c753fSRafael Auler         // Ignore __builtin_unreachable().
1831a34c753fSRafael Auler         if (PossibleDestination == getSize())
1832a34c753fSRafael Auler           continue;
1833a34c753fSRafael Auler         TakenBranches.emplace_back(Offset, PossibleDestination);
1834a34c753fSRafael Auler       }
1835a34c753fSRafael Auler     }
1836a34c753fSRafael Auler   }
1837a34c753fSRafael Auler }
1838a34c753fSRafael Auler 
1839e002523bSAmir Ayupov bool BinaryFunction::validateExternallyReferencedOffsets() {
1840e002523bSAmir Ayupov   SmallPtrSet<MCSymbol *, 4> JTTargets;
1841e002523bSAmir Ayupov   for (const JumpTable *JT : llvm::make_second_range(JumpTables))
1842e002523bSAmir Ayupov     JTTargets.insert(JT->Entries.begin(), JT->Entries.end());
1843e002523bSAmir Ayupov 
1844e002523bSAmir Ayupov   bool HasUnclaimedReference = false;
1845e002523bSAmir Ayupov   for (uint64_t Destination : ExternallyReferencedOffsets) {
1846e002523bSAmir Ayupov     // Ignore __builtin_unreachable().
1847e002523bSAmir Ayupov     if (Destination == getSize())
1848e002523bSAmir Ayupov       continue;
1849e002523bSAmir Ayupov     // Ignore constant islands
1850e002523bSAmir Ayupov     if (isInConstantIsland(Destination + getAddress()))
1851e002523bSAmir Ayupov       continue;
1852e002523bSAmir Ayupov 
1853e002523bSAmir Ayupov     if (BinaryBasicBlock *BB = getBasicBlockAtOffset(Destination)) {
1854e002523bSAmir Ayupov       // Check if the externally referenced offset is a recognized jump table
1855e002523bSAmir Ayupov       // target.
1856e002523bSAmir Ayupov       if (JTTargets.contains(BB->getLabel()))
1857e002523bSAmir Ayupov         continue;
1858e002523bSAmir Ayupov 
1859e002523bSAmir Ayupov       if (opts::Verbosity >= 1) {
186052cf0711SAmir Ayupov         BC.errs() << "BOLT-WARNING: unclaimed data to code reference (possibly "
1861e002523bSAmir Ayupov                   << "an unrecognized jump table entry) to " << BB->getName()
1862e002523bSAmir Ayupov                   << " in " << *this << "\n";
1863e002523bSAmir Ayupov       }
1864e002523bSAmir Ayupov       auto L = BC.scopeLock();
1865e002523bSAmir Ayupov       addEntryPoint(*BB);
1866e002523bSAmir Ayupov     } else {
186752cf0711SAmir Ayupov       BC.errs() << "BOLT-WARNING: unknown data to code reference to offset "
1868e002523bSAmir Ayupov                 << Twine::utohexstr(Destination) << " in " << *this << "\n";
1869e002523bSAmir Ayupov       setIgnored();
1870e002523bSAmir Ayupov     }
1871e002523bSAmir Ayupov     HasUnclaimedReference = true;
1872e002523bSAmir Ayupov   }
1873e002523bSAmir Ayupov   return !HasUnclaimedReference;
1874e002523bSAmir Ayupov }
1875e002523bSAmir Ayupov 
1876a34c753fSRafael Auler bool BinaryFunction::postProcessIndirectBranches(
1877a34c753fSRafael Auler     MCPlusBuilder::AllocatorIdTy AllocId) {
1878a34c753fSRafael Auler   auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) {
18791c286acfSAmir Ayupov     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding unknown control flow in " << *this
18801c286acfSAmir Ayupov                       << " for " << BB.getName() << "\n");
1881a34c753fSRafael Auler     HasUnknownControlFlow = true;
1882a34c753fSRafael Auler     BB.removeAllSuccessors();
18833652483cSRafael Auler     for (uint64_t PossibleDestination : ExternallyReferencedOffsets)
1884a34c753fSRafael Auler       if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination))
1885a34c753fSRafael Auler         BB.addSuccessor(SuccBB);
1886a34c753fSRafael Auler   };
1887a34c753fSRafael Auler 
1888a34c753fSRafael Auler   uint64_t NumIndirectJumps = 0;
1889a34c753fSRafael Auler   MCInst *LastIndirectJump = nullptr;
1890a34c753fSRafael Auler   BinaryBasicBlock *LastIndirectJumpBB = nullptr;
1891a34c753fSRafael Auler   uint64_t LastJT = 0;
1892a34c753fSRafael Auler   uint16_t LastJTIndexReg = BC.MIB->getNoRegister();
1893d55dfeafSFabian Parzefall   for (BinaryBasicBlock &BB : blocks()) {
18947fa33773SJob Noorman     for (BinaryBasicBlock::iterator II = BB.begin(); II != BB.end(); ++II) {
18957fa33773SJob Noorman       MCInst &Instr = *II;
1896a34c753fSRafael Auler       if (!BC.MIB->isIndirectBranch(Instr))
1897a34c753fSRafael Auler         continue;
1898a34c753fSRafael Auler 
1899a34c753fSRafael Auler       // If there's an indirect branch in a single-block function -
1900a34c753fSRafael Auler       // it must be a tail call.
1901d55dfeafSFabian Parzefall       if (BasicBlocks.size() == 1) {
1902a34c753fSRafael Auler         BC.MIB->convertJmpToTailCall(Instr);
1903a34c753fSRafael Auler         return true;
1904a34c753fSRafael Auler       }
1905a34c753fSRafael Auler 
1906a34c753fSRafael Auler       ++NumIndirectJumps;
1907a34c753fSRafael Auler 
1908a34c753fSRafael Auler       if (opts::StrictMode && !hasInternalReference()) {
1909a34c753fSRafael Auler         BC.MIB->convertJmpToTailCall(Instr);
1910a34c753fSRafael Auler         break;
1911a34c753fSRafael Auler       }
1912a34c753fSRafael Auler 
1913a34c753fSRafael Auler       // Validate the tail call or jump table assumptions now that we know
1914a34c753fSRafael Auler       // basic block boundaries.
1915a34c753fSRafael Auler       if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) {
1916a34c753fSRafael Auler         const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
1917a34c753fSRafael Auler         MCInst *MemLocInstr;
1918a34c753fSRafael Auler         unsigned BaseRegNum, IndexRegNum;
1919a34c753fSRafael Auler         int64_t DispValue;
1920a34c753fSRafael Auler         const MCExpr *DispExpr;
1921a34c753fSRafael Auler         MCInst *PCRelBaseInstr;
19223023b15fSAmir Ayupov         MCInst *FixedEntryLoadInstr;
1923a34c753fSRafael Auler         IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
19247fa33773SJob Noorman             Instr, BB.begin(), II, PtrSize, MemLocInstr, BaseRegNum,
19253023b15fSAmir Ayupov             IndexRegNum, DispValue, DispExpr, PCRelBaseInstr,
19263023b15fSAmir Ayupov             FixedEntryLoadInstr);
1927a34c753fSRafael Auler         if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr)
1928a34c753fSRafael Auler           continue;
1929a34c753fSRafael Auler 
1930a34c753fSRafael Auler         if (!opts::StrictMode)
1931a34c753fSRafael Auler           return false;
1932a34c753fSRafael Auler 
1933a34c753fSRafael Auler         if (BC.MIB->isTailCall(Instr)) {
1934a34c753fSRafael Auler           BC.MIB->convertTailCallToJmp(Instr);
1935a34c753fSRafael Auler         } else {
1936a34c753fSRafael Auler           LastIndirectJump = &Instr;
1937d55dfeafSFabian Parzefall           LastIndirectJumpBB = &BB;
1938a34c753fSRafael Auler           LastJT = BC.MIB->getJumpTable(Instr);
1939a34c753fSRafael Auler           LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr);
1940a34c753fSRafael Auler           BC.MIB->unsetJumpTable(Instr);
1941a34c753fSRafael Auler 
1942a34c753fSRafael Auler           JumpTable *JT = BC.getJumpTableContainingAddress(LastJT);
1943a34c753fSRafael Auler           if (JT->Type == JumpTable::JTT_NORMAL) {
1944a34c753fSRafael Auler             // Invalidating the jump table may also invalidate other jump table
1945a34c753fSRafael Auler             // boundaries. Until we have/need a support for this, mark the
1946a34c753fSRafael Auler             // function as non-simple.
1947a34c753fSRafael Auler             LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference"
1948a34c753fSRafael Auler                               << JT->getName() << " in " << *this << '\n');
1949a34c753fSRafael Auler             return false;
1950a34c753fSRafael Auler           }
1951a34c753fSRafael Auler         }
1952a34c753fSRafael Auler 
1953d55dfeafSFabian Parzefall         addUnknownControlFlow(BB);
1954a34c753fSRafael Auler         continue;
1955a34c753fSRafael Auler       }
1956a34c753fSRafael Auler 
1957a34c753fSRafael Auler       // If this block contains an epilogue code and has an indirect branch,
1958a34c753fSRafael Auler       // then most likely it's a tail call. Otherwise, we cannot tell for sure
1959a34c753fSRafael Auler       // what it is and conservatively reject the function's CFG.
1960f119a248SAmir Ayupov       bool IsEpilogue = llvm::any_of(BB, [&](const MCInst &Instr) {
1961f119a248SAmir Ayupov         return BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr);
1962f119a248SAmir Ayupov       });
1963a34c753fSRafael Auler       if (IsEpilogue) {
1964a34c753fSRafael Auler         BC.MIB->convertJmpToTailCall(Instr);
1965d55dfeafSFabian Parzefall         BB.removeAllSuccessors();
1966a34c753fSRafael Auler         continue;
1967a34c753fSRafael Auler       }
1968a34c753fSRafael Auler 
1969a34c753fSRafael Auler       if (opts::Verbosity >= 2) {
197052cf0711SAmir Ayupov         BC.outs() << "BOLT-INFO: rejected potential indirect tail call in "
1971d55dfeafSFabian Parzefall                   << "function " << *this << " in basic block " << BB.getName()
197240c2e0faSMaksim Panchenko                   << ".\n";
1973d55dfeafSFabian Parzefall         LLVM_DEBUG(BC.printInstructions(dbgs(), BB.begin(), BB.end(),
1974d55dfeafSFabian Parzefall                                         BB.getOffset(), this, true));
1975a34c753fSRafael Auler       }
1976a34c753fSRafael Auler 
1977a34c753fSRafael Auler       if (!opts::StrictMode)
1978a34c753fSRafael Auler         return false;
1979a34c753fSRafael Auler 
1980d55dfeafSFabian Parzefall       addUnknownControlFlow(BB);
1981a34c753fSRafael Auler     }
1982a34c753fSRafael Auler   }
1983a34c753fSRafael Auler 
1984a34c753fSRafael Auler   if (HasInternalLabelReference)
1985a34c753fSRafael Auler     return false;
1986a34c753fSRafael Auler 
1987a34c753fSRafael Auler   // If there's only one jump table, and one indirect jump, and no other
1988a34c753fSRafael Auler   // references, then we should be able to derive the jump table even if we
1989a34c753fSRafael Auler   // fail to match the pattern.
1990a34c753fSRafael Auler   if (HasUnknownControlFlow && NumIndirectJumps == 1 &&
19911c286acfSAmir Ayupov       JumpTables.size() == 1 && LastIndirectJump &&
19921c286acfSAmir Ayupov       !BC.getJumpTableContainingAddress(LastJT)->IsSplit) {
19931c286acfSAmir Ayupov     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: unsetting unknown control flow in "
19941c286acfSAmir Ayupov                       << *this << '\n');
1995a34c753fSRafael Auler     BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId);
1996a34c753fSRafael Auler     HasUnknownControlFlow = false;
1997a34c753fSRafael Auler 
19985a343994SMaksim Panchenko     LastIndirectJumpBB->updateJumpTableSuccessors();
1999a34c753fSRafael Auler   }
2000a34c753fSRafael Auler 
2001e002523bSAmir Ayupov   // Validate that all data references to function offsets are claimed by
2002e002523bSAmir Ayupov   // recognized jump tables. Register externally referenced blocks as entry
2003e002523bSAmir Ayupov   // points.
2004e002523bSAmir Ayupov   if (!opts::StrictMode && hasInternalReference()) {
2005e002523bSAmir Ayupov     if (!validateExternallyReferencedOffsets())
2006e002523bSAmir Ayupov       return false;
2007e002523bSAmir Ayupov   }
2008e002523bSAmir Ayupov 
2009a34c753fSRafael Auler   if (HasUnknownControlFlow && !BC.HasRelocations)
2010a34c753fSRafael Auler     return false;
2011a34c753fSRafael Auler 
2012a34c753fSRafael Auler   return true;
2013a34c753fSRafael Auler }
2014a34c753fSRafael Auler 
2015a34c753fSRafael Auler void BinaryFunction::recomputeLandingPads() {
2016a34c753fSRafael Auler   updateBBIndices(0);
2017a34c753fSRafael Auler 
2018a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
2019a34c753fSRafael Auler     BB->LandingPads.clear();
2020a34c753fSRafael Auler     BB->Throwers.clear();
2021a34c753fSRafael Auler   }
2022a34c753fSRafael Auler 
2023a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
2024a34c753fSRafael Auler     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
2025a34c753fSRafael Auler     for (MCInst &Instr : *BB) {
2026a34c753fSRafael Auler       if (!BC.MIB->isInvoke(Instr))
2027a34c753fSRafael Auler         continue;
2028a34c753fSRafael Auler 
20292563fd63SAmir Ayupov       const std::optional<MCPlus::MCLandingPad> EHInfo =
20302563fd63SAmir Ayupov           BC.MIB->getEHInfo(Instr);
2031a34c753fSRafael Auler       if (!EHInfo || !EHInfo->first)
2032a34c753fSRafael Auler         continue;
2033a34c753fSRafael Auler 
2034a34c753fSRafael Auler       BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
2035a34c753fSRafael Auler       if (!BBLandingPads.count(LPBlock)) {
2036a34c753fSRafael Auler         BBLandingPads.insert(LPBlock);
2037a34c753fSRafael Auler         BB->LandingPads.emplace_back(LPBlock);
2038a34c753fSRafael Auler         LPBlock->Throwers.emplace_back(BB);
2039a34c753fSRafael Auler       }
2040a34c753fSRafael Auler     }
2041a34c753fSRafael Auler   }
2042a34c753fSRafael Auler }
2043a34c753fSRafael Auler 
204413d60ce2SAmir Ayupov Error BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
2045a34c753fSRafael Auler   auto &MIB = BC.MIB;
2046a34c753fSRafael Auler 
2047a34c753fSRafael Auler   if (!isSimple()) {
2048a34c753fSRafael Auler     assert(!BC.HasRelocations &&
2049a34c753fSRafael Auler            "cannot process file with non-simple function in relocs mode");
205013d60ce2SAmir Ayupov     return createNonFatalBOLTError("");
2051a34c753fSRafael Auler   }
2052a34c753fSRafael Auler 
2053a34c753fSRafael Auler   if (CurrentState != State::Disassembled)
205413d60ce2SAmir Ayupov     return createNonFatalBOLTError("");
2055a34c753fSRafael Auler 
2056a34c753fSRafael Auler   assert(BasicBlocks.empty() && "basic block list should be empty");
20570b7e8bafSDenis Revunov   assert((Labels.find(getFirstInstructionOffset()) != Labels.end()) &&
2058a34c753fSRafael Auler          "first instruction should always have a label");
2059a34c753fSRafael Auler 
2060a34c753fSRafael Auler   // Create basic blocks in the original layout order:
2061a34c753fSRafael Auler   //
2062a34c753fSRafael Auler   //  * Every instruction with associated label marks
2063a34c753fSRafael Auler   //    the beginning of a basic block.
2064a34c753fSRafael Auler   //  * Conditional instruction marks the end of a basic block,
2065a34c753fSRafael Auler   //    except when the following instruction is an
2066a34c753fSRafael Auler   //    unconditional branch, and the unconditional branch is not
2067a34c753fSRafael Auler   //    a destination of another branch. In the latter case, the
2068a34c753fSRafael Auler   //    basic block will consist of a single unconditional branch
2069a34c753fSRafael Auler   //    (missed "double-jump" optimization).
2070a34c753fSRafael Auler   //
2071a34c753fSRafael Auler   // Created basic blocks are sorted in layout order since they are
2072a34c753fSRafael Auler   // created in the same order as instructions, and instructions are
2073a34c753fSRafael Auler   // sorted by offsets.
2074a34c753fSRafael Auler   BinaryBasicBlock *InsertBB = nullptr;
2075a34c753fSRafael Auler   BinaryBasicBlock *PrevBB = nullptr;
2076a34c753fSRafael Auler   bool IsLastInstrNop = false;
2077ccb99dd1SMaksim Panchenko   // Offset of the last non-nop instruction.
2078a34c753fSRafael Auler   uint64_t LastInstrOffset = 0;
2079a34c753fSRafael Auler 
208040c2e0faSMaksim Panchenko   auto addCFIPlaceholders = [this](uint64_t CFIOffset,
208140c2e0faSMaksim Panchenko                                    BinaryBasicBlock *InsertBB) {
2082a34c753fSRafael Auler     for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
2083a34c753fSRafael Auler               FE = OffsetToCFI.upper_bound(CFIOffset);
2084a34c753fSRafael Auler          FI != FE; ++FI) {
2085a34c753fSRafael Auler       addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
2086a34c753fSRafael Auler     }
2087a34c753fSRafael Auler   };
2088a34c753fSRafael Auler 
2089a34c753fSRafael Auler   // For profiling purposes we need to save the offset of the last instruction
2090ccb99dd1SMaksim Panchenko   // in the basic block.
2091ccb99dd1SMaksim Panchenko   // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
2092ccb99dd1SMaksim Panchenko   //       older profiles ignored nops.
2093a34c753fSRafael Auler   auto updateOffset = [&](uint64_t Offset) {
2094a34c753fSRafael Auler     assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
2095ccb99dd1SMaksim Panchenko     MCInst *LastNonNop = nullptr;
2096ccb99dd1SMaksim Panchenko     for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
2097ccb99dd1SMaksim Panchenko                                             E = PrevBB->rend();
2098ccb99dd1SMaksim Panchenko          RII != E; ++RII) {
2099ccb99dd1SMaksim Panchenko       if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
2100ccb99dd1SMaksim Panchenko         LastNonNop = &*RII;
2101ccb99dd1SMaksim Panchenko         break;
2102ccb99dd1SMaksim Panchenko       }
2103ccb99dd1SMaksim Panchenko     }
2104a9cd49d5SAmir Ayupov     if (LastNonNop && !MIB->getOffset(*LastNonNop))
210574e0a26fSmaksfb       MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset));
2106a34c753fSRafael Auler   };
2107a34c753fSRafael Auler 
2108a34c753fSRafael Auler   for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
2109a34c753fSRafael Auler     const uint32_t Offset = I->first;
2110a34c753fSRafael Auler     MCInst &Instr = I->second;
2111a34c753fSRafael Auler 
2112a34c753fSRafael Auler     auto LI = Labels.find(Offset);
2113a34c753fSRafael Auler     if (LI != Labels.end()) {
2114a34c753fSRafael Auler       // Always create new BB at branch destination.
2115ccb99dd1SMaksim Panchenko       PrevBB = InsertBB ? InsertBB : PrevBB;
21168228c703SMaksim Panchenko       InsertBB = addBasicBlockAt(LI->first, LI->second);
21178228c703SMaksim Panchenko       if (opts::PreserveBlocksAlignment && IsLastInstrNop)
21188228c703SMaksim Panchenko         InsertBB->setDerivedAlignment();
21198228c703SMaksim Panchenko 
2120a34c753fSRafael Auler       if (PrevBB)
2121a34c753fSRafael Auler         updateOffset(LastInstrOffset);
2122a34c753fSRafael Auler     }
2123a34c753fSRafael Auler 
2124ccb99dd1SMaksim Panchenko     // Mark all nops with Offset for profile tracking purposes.
212538639a81SMaksim Panchenko     if (MIB->isNoop(Instr) && !MIB->getOffset(Instr)) {
212698e2d630SMaksim Panchenko       // If "Offset" annotation is not present, set it and mark the nop for
212798e2d630SMaksim Panchenko       // deletion.
212874e0a26fSmaksfb       MIB->setOffset(Instr, static_cast<uint32_t>(Offset));
2129ccb99dd1SMaksim Panchenko       // Annotate ordinary nops, so we can safely delete them if required.
213038639a81SMaksim Panchenko       MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
2131a34c753fSRafael Auler     }
2132a34c753fSRafael Auler 
2133a34c753fSRafael Auler     if (!InsertBB) {
2134a34c753fSRafael Auler       // It must be a fallthrough or unreachable code. Create a new block unless
2135a34c753fSRafael Auler       // we see an unconditional branch following a conditional one. The latter
2136a34c753fSRafael Auler       // should not be a conditional tail call.
2137a34c753fSRafael Auler       assert(PrevBB && "no previous basic block for a fall through");
2138a34c753fSRafael Auler       MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
2139a34c753fSRafael Auler       assert(PrevInstr && "no previous instruction for a fall through");
2140a34c753fSRafael Auler       if (MIB->isUnconditionalBranch(Instr) &&
2141b87bf744SRafael Auler           !MIB->isIndirectBranch(*PrevInstr) &&
2142a34c753fSRafael Auler           !MIB->isUnconditionalBranch(*PrevInstr) &&
2143bb8e7ebaSVladislav Khmelevsky           !MIB->getConditionalTailCall(*PrevInstr) &&
2144bb8e7ebaSVladislav Khmelevsky           !MIB->isReturn(*PrevInstr)) {
2145a34c753fSRafael Auler         // Temporarily restore inserter basic block.
2146a34c753fSRafael Auler         InsertBB = PrevBB;
2147a34c753fSRafael Auler       } else {
2148a34c753fSRafael Auler         MCSymbol *Label;
2149a34c753fSRafael Auler         {
2150a34c753fSRafael Auler           auto L = BC.scopeLock();
2151a34c753fSRafael Auler           Label = BC.Ctx->createNamedTempSymbol("FT");
2152a34c753fSRafael Auler         }
21538228c703SMaksim Panchenko         InsertBB = addBasicBlockAt(Offset, Label);
21548228c703SMaksim Panchenko         if (opts::PreserveBlocksAlignment && IsLastInstrNop)
21558228c703SMaksim Panchenko           InsertBB->setDerivedAlignment();
2156a34c753fSRafael Auler         updateOffset(LastInstrOffset);
2157a34c753fSRafael Auler       }
2158a34c753fSRafael Auler     }
21590b7e8bafSDenis Revunov     if (Offset == getFirstInstructionOffset()) {
21600b7e8bafSDenis Revunov       // Add associated CFI pseudos in the first offset
21610b7e8bafSDenis Revunov       addCFIPlaceholders(Offset, InsertBB);
2162a34c753fSRafael Auler     }
2163a34c753fSRafael Auler 
2164a34c753fSRafael Auler     const bool IsBlockEnd = MIB->isTerminator(Instr);
2165a34c753fSRafael Auler     IsLastInstrNop = MIB->isNoop(Instr);
2166ccb99dd1SMaksim Panchenko     if (!IsLastInstrNop)
2167a34c753fSRafael Auler       LastInstrOffset = Offset;
2168a34c753fSRafael Auler     InsertBB->addInstruction(std::move(Instr));
2169a34c753fSRafael Auler 
2170a34c753fSRafael Auler     // Add associated CFI instrs. We always add the CFI instruction that is
2171a34c753fSRafael Auler     // located immediately after this instruction, since the next CFI
2172a34c753fSRafael Auler     // instruction reflects the change in state caused by this instruction.
2173a34c753fSRafael Auler     auto NextInstr = std::next(I);
2174a34c753fSRafael Auler     uint64_t CFIOffset;
2175a34c753fSRafael Auler     if (NextInstr != E)
2176a34c753fSRafael Auler       CFIOffset = NextInstr->first;
2177a34c753fSRafael Auler     else
2178a34c753fSRafael Auler       CFIOffset = getSize();
2179a34c753fSRafael Auler 
2180a34c753fSRafael Auler     // Note: this potentially invalidates instruction pointers/iterators.
2181a34c753fSRafael Auler     addCFIPlaceholders(CFIOffset, InsertBB);
2182a34c753fSRafael Auler 
2183a34c753fSRafael Auler     if (IsBlockEnd) {
2184a34c753fSRafael Auler       PrevBB = InsertBB;
2185a34c753fSRafael Auler       InsertBB = nullptr;
2186a34c753fSRafael Auler     }
2187a34c753fSRafael Auler   }
2188a34c753fSRafael Auler 
2189a34c753fSRafael Auler   if (BasicBlocks.empty()) {
2190a34c753fSRafael Auler     setSimple(false);
219113d60ce2SAmir Ayupov     return createNonFatalBOLTError("");
2192a34c753fSRafael Auler   }
2193a34c753fSRafael Auler 
2194a34c753fSRafael Auler   // Intermediate dump.
2195a34c753fSRafael Auler   LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2196a34c753fSRafael Auler 
2197a34c753fSRafael Auler   // TODO: handle properly calls to no-return functions,
2198a34c753fSRafael Auler   // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2199a34c753fSRafael Auler   // blocks.
2200a34c753fSRafael Auler 
22013f2a9e59SMaksim Panchenko   // Remove duplicates branches. We can get a bunch of them from jump tables.
22023f2a9e59SMaksim Panchenko   // Without doing jump table value profiling we don't have a use for extra
22033f2a9e59SMaksim Panchenko   // (duplicate) branches.
22043f2a9e59SMaksim Panchenko   llvm::sort(TakenBranches);
22053f2a9e59SMaksim Panchenko   auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end());
22063f2a9e59SMaksim Panchenko   TakenBranches.erase(NewEnd, TakenBranches.end());
22073f2a9e59SMaksim Panchenko 
2208a34c753fSRafael Auler   for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2209a34c753fSRafael Auler     LLVM_DEBUG(dbgs() << "registering branch [0x"
2210a34c753fSRafael Auler                       << Twine::utohexstr(Branch.first) << "] -> [0x"
2211a34c753fSRafael Auler                       << Twine::utohexstr(Branch.second) << "]\n");
2212a34c753fSRafael Auler     BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2213a34c753fSRafael Auler     BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2214a34c753fSRafael Auler     if (!FromBB || !ToBB) {
2215a34c753fSRafael Auler       if (!FromBB)
221652cf0711SAmir Ayupov         BC.errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2217a34c753fSRafael Auler       if (!ToBB)
221852cf0711SAmir Ayupov         BC.errs()
221952cf0711SAmir Ayupov             << "BOLT-ERROR: cannot find BB containing branch destination.\n";
222052cf0711SAmir Ayupov       return createFatalBOLTError(BC.generateBugReportMessage(
222152cf0711SAmir Ayupov           "disassembly failed - inconsistent branch found.", *this));
2222a34c753fSRafael Auler     }
2223a34c753fSRafael Auler 
2224a34c753fSRafael Auler     FromBB->addSuccessor(ToBB);
2225a34c753fSRafael Auler   }
2226a34c753fSRafael Auler 
2227a34c753fSRafael Auler   // Add fall-through branches.
2228a34c753fSRafael Auler   PrevBB = nullptr;
2229a34c753fSRafael Auler   bool IsPrevFT = false; // Is previous block a fall-through.
2230a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
22313652483cSRafael Auler     if (IsPrevFT)
2232a34c753fSRafael Auler       PrevBB->addSuccessor(BB);
22333652483cSRafael Auler 
2234a34c753fSRafael Auler     if (BB->empty()) {
2235a34c753fSRafael Auler       IsPrevFT = true;
2236a34c753fSRafael Auler       PrevBB = BB;
2237a34c753fSRafael Auler       continue;
2238a34c753fSRafael Auler     }
2239a34c753fSRafael Auler 
2240a34c753fSRafael Auler     MCInst *LastInstr = BB->getLastNonPseudoInstr();
2241a34c753fSRafael Auler     assert(LastInstr &&
2242a34c753fSRafael Auler            "should have non-pseudo instruction in non-empty block");
2243a34c753fSRafael Auler 
2244a34c753fSRafael Auler     if (BB->succ_size() == 0) {
2245a34c753fSRafael Auler       // Since there's no existing successors, we know the last instruction is
2246a34c753fSRafael Auler       // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2247a34c753fSRafael Auler       // fall-through.
2248a34c753fSRafael Auler       //
2249a34c753fSRafael Auler       // Conditional tail call is a special case since we don't add a taken
2250a34c753fSRafael Auler       // branch successor for it.
2251a34c753fSRafael Auler       IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2252a34c753fSRafael Auler                  MIB->getConditionalTailCall(*LastInstr);
2253a34c753fSRafael Auler     } else if (BB->succ_size() == 1) {
2254a34c753fSRafael Auler       IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2255a34c753fSRafael Auler     } else {
2256a34c753fSRafael Auler       IsPrevFT = false;
2257a34c753fSRafael Auler     }
2258a34c753fSRafael Auler 
2259a34c753fSRafael Auler     PrevBB = BB;
2260a34c753fSRafael Auler   }
2261a34c753fSRafael Auler 
2262a34c753fSRafael Auler   // Assign landing pads and throwers info.
2263a34c753fSRafael Auler   recomputeLandingPads();
2264a34c753fSRafael Auler 
2265a34c753fSRafael Auler   // Assign CFI information to each BB entry.
2266a34c753fSRafael Auler   annotateCFIState();
2267a34c753fSRafael Auler 
2268a34c753fSRafael Auler   // Annotate invoke instructions with GNU_args_size data.
2269a34c753fSRafael Auler   propagateGnuArgsSizeInfo(AllocatorId);
2270a34c753fSRafael Auler 
2271a34c753fSRafael Auler   // Set the basic block layout to the original order and set end offsets.
2272a34c753fSRafael Auler   PrevBB = nullptr;
2273a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
22748477bc67SFabian Parzefall     Layout.addBasicBlock(BB);
2275a34c753fSRafael Auler     if (PrevBB)
2276a34c753fSRafael Auler       PrevBB->setEndOffset(BB->getOffset());
2277a34c753fSRafael Auler     PrevBB = BB;
2278a34c753fSRafael Auler   }
2279a34c753fSRafael Auler   PrevBB->setEndOffset(getSize());
2280a34c753fSRafael Auler 
22818477bc67SFabian Parzefall   Layout.updateLayoutIndices();
2282a34c753fSRafael Auler 
2283a34c753fSRafael Auler   normalizeCFIState();
2284a34c753fSRafael Auler 
2285a34c753fSRafael Auler   // Clean-up memory taken by intermediate structures.
2286a34c753fSRafael Auler   //
2287a34c753fSRafael Auler   // NB: don't clear Labels list as we may need them if we mark the function
2288a34c753fSRafael Auler   //     as non-simple later in the process of discovering extra entry points.
2289a34c753fSRafael Auler   clearList(Instructions);
2290a34c753fSRafael Auler   clearList(OffsetToCFI);
2291a34c753fSRafael Auler   clearList(TakenBranches);
2292a34c753fSRafael Auler 
2293a34c753fSRafael Auler   // Update the state.
2294a34c753fSRafael Auler   CurrentState = State::CFG;
2295a34c753fSRafael Auler 
2296a34c753fSRafael Auler   // Make any necessary adjustments for indirect branches.
2297a34c753fSRafael Auler   if (!postProcessIndirectBranches(AllocatorId)) {
2298a34c753fSRafael Auler     if (opts::Verbosity) {
229952cf0711SAmir Ayupov       BC.errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2300a34c753fSRafael Auler                 << *this << '\n';
2301a34c753fSRafael Auler     }
2302*ef232a7eSMaksim Panchenko 
2303*ef232a7eSMaksim Panchenko     if (BC.isAArch64())
2304*ef232a7eSMaksim Panchenko       PreserveNops = BC.HasRelocations;
2305*ef232a7eSMaksim Panchenko 
2306a34c753fSRafael Auler     // In relocation mode we want to keep processing the function but avoid
2307a34c753fSRafael Auler     // optimizing it.
2308a34c753fSRafael Auler     setSimple(false);
2309a34c753fSRafael Auler   }
2310a34c753fSRafael Auler 
2311a34c753fSRafael Auler   clearList(ExternallyReferencedOffsets);
2312a34c753fSRafael Auler   clearList(UnknownIndirectBranchOffsets);
2313a34c753fSRafael Auler 
231413d60ce2SAmir Ayupov   return Error::success();
2315a34c753fSRafael Auler }
2316a34c753fSRafael Auler 
2317a34c753fSRafael Auler void BinaryFunction::postProcessCFG() {
2318a34c753fSRafael Auler   if (isSimple() && !BasicBlocks.empty()) {
2319a34c753fSRafael Auler     // Convert conditional tail call branches to conditional branches that jump
2320a34c753fSRafael Auler     // to a tail call.
2321a34c753fSRafael Auler     removeConditionalTailCalls();
2322a34c753fSRafael Auler 
2323a34c753fSRafael Auler     postProcessProfile();
2324a34c753fSRafael Auler 
2325a34c753fSRafael Auler     // Eliminate inconsistencies between branch instructions and CFG.
2326a34c753fSRafael Auler     postProcessBranches();
2327a34c753fSRafael Auler   }
2328a34c753fSRafael Auler 
2329a34c753fSRafael Auler   // The final cleanup of intermediate structures.
2330a34c753fSRafael Auler   clearList(IgnoredBranches);
2331a34c753fSRafael Auler 
2332a34c753fSRafael Auler   // Remove "Offset" annotations, unless we need an address-translation table
2333a34c753fSRafael Auler   // later. This has no cost, since annotations are allocated by a bumpptr
2334a34c753fSRafael Auler   // allocator and won't be released anyway until late in the pipeline.
23353652483cSRafael Auler   if (!requiresAddressTranslation() && !opts::Instrument) {
2336d55dfeafSFabian Parzefall     for (BinaryBasicBlock &BB : blocks())
2337d55dfeafSFabian Parzefall       for (MCInst &Inst : BB)
2338a9cd49d5SAmir Ayupov         BC.MIB->clearOffset(Inst);
23393652483cSRafael Auler   }
2340a34c753fSRafael Auler 
2341a34c753fSRafael Auler   assert((!isSimple() || validateCFG()) &&
2342a34c753fSRafael Auler          "invalid CFG detected after post-processing");
2343a34c753fSRafael Auler }
2344a34c753fSRafael Auler 
2345a34c753fSRafael Auler void BinaryFunction::removeTagsFromProfile() {
2346a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
2347a34c753fSRafael Auler     if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2348a34c753fSRafael Auler       BB->ExecutionCount = 0;
2349a34c753fSRafael Auler     for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2350a34c753fSRafael Auler       if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2351a34c753fSRafael Auler           BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2352a34c753fSRafael Auler         continue;
2353a34c753fSRafael Auler       BI.Count = 0;
2354a34c753fSRafael Auler       BI.MispredictedCount = 0;
2355a34c753fSRafael Auler     }
2356a34c753fSRafael Auler   }
2357a34c753fSRafael Auler }
2358a34c753fSRafael Auler 
2359a34c753fSRafael Auler void BinaryFunction::removeConditionalTailCalls() {
2360a34c753fSRafael Auler   // Blocks to be appended at the end.
2361a34c753fSRafael Auler   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2362a34c753fSRafael Auler 
2363a34c753fSRafael Auler   for (auto BBI = begin(); BBI != end(); ++BBI) {
2364a34c753fSRafael Auler     BinaryBasicBlock &BB = *BBI;
2365a34c753fSRafael Auler     MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2366a34c753fSRafael Auler     if (!CTCInstr)
2367a34c753fSRafael Auler       continue;
2368a34c753fSRafael Auler 
23692563fd63SAmir Ayupov     std::optional<uint64_t> TargetAddressOrNone =
2370a34c753fSRafael Auler         BC.MIB->getConditionalTailCall(*CTCInstr);
2371a34c753fSRafael Auler     if (!TargetAddressOrNone)
2372a34c753fSRafael Auler       continue;
2373a34c753fSRafael Auler 
2374a34c753fSRafael Auler     // Gather all necessary information about CTC instruction before
2375a34c753fSRafael Auler     // annotations are destroyed.
2376a34c753fSRafael Auler     const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2377a34c753fSRafael Auler     uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2378a34c753fSRafael Auler     uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2379a34c753fSRafael Auler     if (hasValidProfile()) {
238040c2e0faSMaksim Panchenko       CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
238140c2e0faSMaksim Panchenko           *CTCInstr, "CTCTakenCount");
238240c2e0faSMaksim Panchenko       CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
238340c2e0faSMaksim Panchenko           *CTCInstr, "CTCMispredCount");
2384a34c753fSRafael Auler     }
2385a34c753fSRafael Auler 
2386a34c753fSRafael Auler     // Assert that the tail call does not throw.
2387a34c753fSRafael Auler     assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2388a34c753fSRafael Auler            "found tail call with associated landing pad");
2389a34c753fSRafael Auler 
2390a34c753fSRafael Auler     // Create a basic block with an unconditional tail call instruction using
2391a34c753fSRafael Auler     // the same destination.
2392a34c753fSRafael Auler     const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2393a34c753fSRafael Auler     assert(CTCTargetLabel && "symbol expected for conditional tail call");
2394a34c753fSRafael Auler     MCInst TailCallInstr;
2395a34c753fSRafael Auler     BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
239674e0a26fSmaksfb 
239774e0a26fSmaksfb     // Move offset from CTCInstr to TailCallInstr.
239874e0a26fSmaksfb     if (const std::optional<uint32_t> Offset = BC.MIB->getOffset(*CTCInstr)) {
239974e0a26fSmaksfb       BC.MIB->setOffset(TailCallInstr, *Offset);
240074e0a26fSmaksfb       BC.MIB->clearOffset(*CTCInstr);
240174e0a26fSmaksfb     }
240274e0a26fSmaksfb 
2403a34c753fSRafael Auler     // Link new BBs to the original input offset of the BB where the CTC
2404a34c753fSRafael Auler     // is, so we can map samples recorded in new BBs back to the original BB
2405a34c753fSRafael Auler     // seem in the input binary (if using BAT)
24068228c703SMaksim Panchenko     std::unique_ptr<BinaryBasicBlock> TailCallBB =
24078228c703SMaksim Panchenko         createBasicBlock(BC.Ctx->createNamedTempSymbol("TC"));
24088228c703SMaksim Panchenko     TailCallBB->setOffset(BB.getInputOffset());
2409a34c753fSRafael Auler     TailCallBB->addInstruction(TailCallInstr);
2410a34c753fSRafael Auler     TailCallBB->setCFIState(CFIStateBeforeCTC);
2411a34c753fSRafael Auler 
2412a34c753fSRafael Auler     // Add CFG edge with profile info from BB to TailCallBB.
2413a34c753fSRafael Auler     BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2414a34c753fSRafael Auler 
2415a34c753fSRafael Auler     // Add execution count for the block.
2416a34c753fSRafael Auler     TailCallBB->setExecutionCount(CTCTakenCount);
2417a34c753fSRafael Auler 
2418a34c753fSRafael Auler     BC.MIB->convertTailCallToJmp(*CTCInstr);
2419a34c753fSRafael Auler 
2420a34c753fSRafael Auler     BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2421a34c753fSRafael Auler                                 BC.Ctx.get());
2422a34c753fSRafael Auler 
2423a34c753fSRafael Auler     // Add basic block to the list that will be added to the end.
2424a34c753fSRafael Auler     NewBlocks.emplace_back(std::move(TailCallBB));
2425a34c753fSRafael Auler 
2426a34c753fSRafael Auler     // Swap edges as the TailCallBB corresponds to the taken branch.
2427a34c753fSRafael Auler     BB.swapConditionalSuccessors();
2428a34c753fSRafael Auler 
2429a34c753fSRafael Auler     // This branch is no longer a conditional tail call.
2430a34c753fSRafael Auler     BC.MIB->unsetConditionalTailCall(*CTCInstr);
2431a34c753fSRafael Auler   }
2432a34c753fSRafael Auler 
243340c2e0faSMaksim Panchenko   insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2434a34c753fSRafael Auler                     /* UpdateLayout */ true,
2435a34c753fSRafael Auler                     /* UpdateCFIState */ false);
2436a34c753fSRafael Auler }
2437a34c753fSRafael Auler 
2438a34c753fSRafael Auler uint64_t BinaryFunction::getFunctionScore() const {
2439a34c753fSRafael Auler   if (FunctionScore != -1)
2440a34c753fSRafael Auler     return FunctionScore;
2441a34c753fSRafael Auler 
2442a34c753fSRafael Auler   if (!isSimple() || !hasValidProfile()) {
2443a34c753fSRafael Auler     FunctionScore = 0;
2444a34c753fSRafael Auler     return FunctionScore;
2445a34c753fSRafael Auler   }
2446a34c753fSRafael Auler 
2447a34c753fSRafael Auler   uint64_t TotalScore = 0ULL;
2448d55dfeafSFabian Parzefall   for (const BinaryBasicBlock &BB : blocks()) {
2449d55dfeafSFabian Parzefall     uint64_t BBExecCount = BB.getExecutionCount();
2450a34c753fSRafael Auler     if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2451a34c753fSRafael Auler       continue;
2452d55dfeafSFabian Parzefall     TotalScore += BBExecCount * BB.getNumNonPseudos();
2453a34c753fSRafael Auler   }
2454a34c753fSRafael Auler   FunctionScore = TotalScore;
2455a34c753fSRafael Auler   return FunctionScore;
2456a34c753fSRafael Auler }
2457a34c753fSRafael Auler 
2458a34c753fSRafael Auler void BinaryFunction::annotateCFIState() {
2459a34c753fSRafael Auler   assert(CurrentState == State::Disassembled && "unexpected function state");
2460a34c753fSRafael Auler   assert(!BasicBlocks.empty() && "basic block list should not be empty");
2461a34c753fSRafael Auler 
2462a34c753fSRafael Auler   // This is an index of the last processed CFI in FDE CFI program.
2463a34c753fSRafael Auler   uint32_t State = 0;
2464a34c753fSRafael Auler 
2465a34c753fSRafael Auler   // This is an index of RememberState CFI reflecting effective state right
2466a34c753fSRafael Auler   // after execution of RestoreState CFI.
2467a34c753fSRafael Auler   //
2468a34c753fSRafael Auler   // It differs from State iff the CFI at (State-1)
2469a34c753fSRafael Auler   // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2470a34c753fSRafael Auler   //
2471a34c753fSRafael Auler   // This allows us to generate shorter replay sequences when producing new
2472a34c753fSRafael Auler   // CFI programs.
2473a34c753fSRafael Auler   uint32_t EffectiveState = 0;
2474a34c753fSRafael Auler 
2475a34c753fSRafael Auler   // For tracking RememberState/RestoreState sequences.
2476a34c753fSRafael Auler   std::stack<uint32_t> StateStack;
2477a34c753fSRafael Auler 
2478a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
2479a34c753fSRafael Auler     BB->setCFIState(EffectiveState);
2480a34c753fSRafael Auler 
2481a34c753fSRafael Auler     for (const MCInst &Instr : *BB) {
2482a34c753fSRafael Auler       const MCCFIInstruction *CFI = getCFIFor(Instr);
2483a34c753fSRafael Auler       if (!CFI)
2484a34c753fSRafael Auler         continue;
2485a34c753fSRafael Auler 
2486a34c753fSRafael Auler       ++State;
2487a34c753fSRafael Auler 
2488a34c753fSRafael Auler       switch (CFI->getOperation()) {
2489a34c753fSRafael Auler       case MCCFIInstruction::OpRememberState:
2490a34c753fSRafael Auler         StateStack.push(EffectiveState);
2491a34c753fSRafael Auler         EffectiveState = State;
2492a34c753fSRafael Auler         break;
2493a34c753fSRafael Auler       case MCCFIInstruction::OpRestoreState:
2494a34c753fSRafael Auler         assert(!StateStack.empty() && "corrupt CFI stack");
2495a34c753fSRafael Auler         EffectiveState = StateStack.top();
2496a34c753fSRafael Auler         StateStack.pop();
2497a34c753fSRafael Auler         break;
2498a34c753fSRafael Auler       case MCCFIInstruction::OpGnuArgsSize:
2499a34c753fSRafael Auler         // OpGnuArgsSize CFIs do not affect the CFI state.
2500a34c753fSRafael Auler         break;
2501a34c753fSRafael Auler       default:
2502a34c753fSRafael Auler         // Any other CFI updates the state.
2503a34c753fSRafael Auler         EffectiveState = State;
2504a34c753fSRafael Auler         break;
2505a34c753fSRafael Auler       }
2506a34c753fSRafael Auler     }
2507a34c753fSRafael Auler   }
2508a34c753fSRafael Auler 
25098f305068SMaksim Panchenko   if (opts::Verbosity >= 1 && !StateStack.empty()) {
2510f83a89c1SAmir Ayupov     BC.errs() << "BOLT-WARNING: non-empty CFI stack at the end of " << *this
2511f83a89c1SAmir Ayupov               << '\n';
2512f83a89c1SAmir Ayupov   }
2513a34c753fSRafael Auler }
2514a34c753fSRafael Auler 
2515a34c753fSRafael Auler namespace {
2516a34c753fSRafael Auler 
2517a34c753fSRafael Auler /// Our full interpretation of a DWARF CFI machine state at a given point
2518a34c753fSRafael Auler struct CFISnapshot {
2519a34c753fSRafael Auler   /// CFA register number and offset defining the canonical frame at this
2520a34c753fSRafael Auler   /// point, or the number of a rule (CFI state) that computes it with a
2521a34c753fSRafael Auler   /// DWARF expression. This number will be negative if it refers to a CFI
2522a34c753fSRafael Auler   /// located in the CIE instead of the FDE.
2523a34c753fSRafael Auler   uint32_t CFAReg;
2524a34c753fSRafael Auler   int32_t CFAOffset;
2525a34c753fSRafael Auler   int32_t CFARule;
2526a34c753fSRafael Auler   /// Mapping of rules (CFI states) that define the location of each
2527a34c753fSRafael Auler   /// register. If absent, no rule defining the location of such register
2528a34c753fSRafael Auler   /// was ever read. This number will be negative if it refers to a CFI
2529a34c753fSRafael Auler   /// located in the CIE instead of the FDE.
2530a34c753fSRafael Auler   DenseMap<int32_t, int32_t> RegRule;
2531a34c753fSRafael Auler 
2532a34c753fSRafael Auler   /// References to CIE, FDE and expanded instructions after a restore state
2533ebe51c4dSMaksim Panchenko   const BinaryFunction::CFIInstrMapType &CIE;
2534ebe51c4dSMaksim Panchenko   const BinaryFunction::CFIInstrMapType &FDE;
2535a34c753fSRafael Auler   const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2536a34c753fSRafael Auler 
2537a34c753fSRafael Auler   /// Current FDE CFI number representing the state where the snapshot is at
2538a34c753fSRafael Auler   int32_t CurState;
2539a34c753fSRafael Auler 
2540a34c753fSRafael Auler   /// Used when we don't have information about which state/rule to apply
2541a34c753fSRafael Auler   /// to recover the location of either the CFA or a specific register
2542a34c753fSRafael Auler   constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2543a34c753fSRafael Auler 
2544a34c753fSRafael Auler private:
2545a34c753fSRafael Auler   /// Update our snapshot by executing a single CFI
2546a34c753fSRafael Auler   void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2547a34c753fSRafael Auler     switch (Instr.getOperation()) {
2548a34c753fSRafael Auler     case MCCFIInstruction::OpSameValue:
2549a34c753fSRafael Auler     case MCCFIInstruction::OpRelOffset:
2550a34c753fSRafael Auler     case MCCFIInstruction::OpOffset:
2551a34c753fSRafael Auler     case MCCFIInstruction::OpRestore:
2552a34c753fSRafael Auler     case MCCFIInstruction::OpUndefined:
2553a34c753fSRafael Auler     case MCCFIInstruction::OpRegister:
2554a34c753fSRafael Auler       RegRule[Instr.getRegister()] = RuleNumber;
2555a34c753fSRafael Auler       break;
2556a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfaRegister:
2557a34c753fSRafael Auler       CFAReg = Instr.getRegister();
2558a34c753fSRafael Auler       CFARule = UNKNOWN;
25596795bfceSJob Noorman 
25606795bfceSJob Noorman       // This shouldn't happen according to the spec but GNU binutils on RISC-V
25616795bfceSJob Noorman       // emits a DW_CFA_def_cfa_register in CIE's which leaves the offset
25626795bfceSJob Noorman       // unspecified. Both readelf and llvm-dwarfdump interpret the offset as 0
25636795bfceSJob Noorman       // in this case so let's do the same.
25646795bfceSJob Noorman       if (CFAOffset == UNKNOWN)
25656795bfceSJob Noorman         CFAOffset = 0;
2566a34c753fSRafael Auler       break;
2567a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfaOffset:
2568a34c753fSRafael Auler       CFAOffset = Instr.getOffset();
2569a34c753fSRafael Auler       CFARule = UNKNOWN;
2570a34c753fSRafael Auler       break;
2571a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfa:
2572a34c753fSRafael Auler       CFAReg = Instr.getRegister();
2573a34c753fSRafael Auler       CFAOffset = Instr.getOffset();
2574a34c753fSRafael Auler       CFARule = UNKNOWN;
2575a34c753fSRafael Auler       break;
2576a34c753fSRafael Auler     case MCCFIInstruction::OpEscape: {
257776cfea0cSAmir Ayupov       std::optional<uint8_t> Reg =
257876cfea0cSAmir Ayupov           readDWARFExpressionTargetReg(Instr.getValues());
2579a34c753fSRafael Auler       // Handle DW_CFA_def_cfa_expression
2580a34c753fSRafael Auler       if (!Reg) {
2581a34c753fSRafael Auler         CFARule = RuleNumber;
2582a34c753fSRafael Auler         break;
2583a34c753fSRafael Auler       }
2584a34c753fSRafael Auler       RegRule[*Reg] = RuleNumber;
2585a34c753fSRafael Auler       break;
2586a34c753fSRafael Auler     }
2587a34c753fSRafael Auler     case MCCFIInstruction::OpAdjustCfaOffset:
2588a34c753fSRafael Auler     case MCCFIInstruction::OpWindowSave:
2589a34c753fSRafael Auler     case MCCFIInstruction::OpNegateRAState:
259041baa69aSKazu Hirata     case MCCFIInstruction::OpNegateRAStateWithPC:
2591a34c753fSRafael Auler     case MCCFIInstruction::OpLLVMDefAspaceCfa:
25922718654cSFangrui Song     case MCCFIInstruction::OpLabel:
259374003f11SDaniel Sanders     case MCCFIInstruction::OpValOffset:
2594a34c753fSRafael Auler       llvm_unreachable("unsupported CFI opcode");
2595a34c753fSRafael Auler       break;
2596a34c753fSRafael Auler     case MCCFIInstruction::OpRememberState:
2597a34c753fSRafael Auler     case MCCFIInstruction::OpRestoreState:
2598a34c753fSRafael Auler     case MCCFIInstruction::OpGnuArgsSize:
2599a34c753fSRafael Auler       // do not affect CFI state
2600a34c753fSRafael Auler       break;
2601a34c753fSRafael Auler     }
2602a34c753fSRafael Auler   }
2603a34c753fSRafael Auler 
2604a34c753fSRafael Auler public:
2605a34c753fSRafael Auler   /// Advance state reading FDE CFI instructions up to State number
2606a34c753fSRafael Auler   void advanceTo(int32_t State) {
2607a34c753fSRafael Auler     for (int32_t I = CurState, E = State; I != E; ++I) {
2608a34c753fSRafael Auler       const MCCFIInstruction &Instr = FDE[I];
2609a34c753fSRafael Auler       if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2610a34c753fSRafael Auler         update(Instr, I);
2611a34c753fSRafael Auler         continue;
2612a34c753fSRafael Auler       }
2613a34c753fSRafael Auler       // If restore state instruction, fetch the equivalent CFIs that have
2614a34c753fSRafael Auler       // the same effect of this restore. This is used to ensure remember-
2615a34c753fSRafael Auler       // restore pairs are completely removed.
2616a34c753fSRafael Auler       auto Iter = FrameRestoreEquivalents.find(I);
2617a34c753fSRafael Auler       if (Iter == FrameRestoreEquivalents.end())
2618a34c753fSRafael Auler         continue;
26193652483cSRafael Auler       for (int32_t RuleNumber : Iter->second)
2620a34c753fSRafael Auler         update(FDE[RuleNumber], RuleNumber);
2621a34c753fSRafael Auler     }
2622a34c753fSRafael Auler 
2623a34c753fSRafael Auler     assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2624a34c753fSRafael Auler             CFARule != UNKNOWN) &&
2625a34c753fSRafael Auler            "CIE did not define default CFA?");
2626a34c753fSRafael Auler 
2627a34c753fSRafael Auler     CurState = State;
2628a34c753fSRafael Auler   }
2629a34c753fSRafael Auler 
2630a34c753fSRafael Auler   /// Interpret all CIE and FDE instructions up until CFI State number and
2631a34c753fSRafael Auler   /// populate this snapshot
2632a34c753fSRafael Auler   CFISnapshot(
2633ebe51c4dSMaksim Panchenko       const BinaryFunction::CFIInstrMapType &CIE,
2634ebe51c4dSMaksim Panchenko       const BinaryFunction::CFIInstrMapType &FDE,
2635a34c753fSRafael Auler       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2636a34c753fSRafael Auler       int32_t State)
2637a34c753fSRafael Auler       : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2638a34c753fSRafael Auler     CFAReg = UNKNOWN;
2639a34c753fSRafael Auler     CFAOffset = UNKNOWN;
2640a34c753fSRafael Auler     CFARule = UNKNOWN;
2641a34c753fSRafael Auler     CurState = 0;
2642a34c753fSRafael Auler 
2643a34c753fSRafael Auler     for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2644a34c753fSRafael Auler       const MCCFIInstruction &Instr = CIE[I];
2645a34c753fSRafael Auler       update(Instr, -I);
2646a34c753fSRafael Auler     }
2647a34c753fSRafael Auler 
2648a34c753fSRafael Auler     advanceTo(State);
2649a34c753fSRafael Auler   }
2650a34c753fSRafael Auler };
2651a34c753fSRafael Auler 
2652a34c753fSRafael Auler /// A CFI snapshot with the capability of checking if incremental additions to
2653a34c753fSRafael Auler /// it are redundant. This is used to ensure we do not emit two CFI instructions
2654a34c753fSRafael Auler /// back-to-back that are doing the same state change, or to avoid emitting a
2655a34c753fSRafael Auler /// CFI at all when the state at that point would not be modified after that CFI
2656a34c753fSRafael Auler struct CFISnapshotDiff : public CFISnapshot {
2657a34c753fSRafael Auler   bool RestoredCFAReg{false};
2658a34c753fSRafael Auler   bool RestoredCFAOffset{false};
2659a34c753fSRafael Auler   DenseMap<int32_t, bool> RestoredRegs;
2660a34c753fSRafael Auler 
2661a34c753fSRafael Auler   CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2662a34c753fSRafael Auler 
2663a34c753fSRafael Auler   CFISnapshotDiff(
2664ebe51c4dSMaksim Panchenko       const BinaryFunction::CFIInstrMapType &CIE,
2665ebe51c4dSMaksim Panchenko       const BinaryFunction::CFIInstrMapType &FDE,
2666a34c753fSRafael Auler       const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2667a34c753fSRafael Auler       int32_t State)
2668a34c753fSRafael Auler       : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2669a34c753fSRafael Auler 
2670a34c753fSRafael Auler   /// Return true if applying Instr to this state is redundant and can be
2671a34c753fSRafael Auler   /// dismissed.
2672a34c753fSRafael Auler   bool isRedundant(const MCCFIInstruction &Instr) {
2673a34c753fSRafael Auler     switch (Instr.getOperation()) {
2674a34c753fSRafael Auler     case MCCFIInstruction::OpSameValue:
2675a34c753fSRafael Auler     case MCCFIInstruction::OpRelOffset:
2676a34c753fSRafael Auler     case MCCFIInstruction::OpOffset:
2677a34c753fSRafael Auler     case MCCFIInstruction::OpRestore:
2678a34c753fSRafael Auler     case MCCFIInstruction::OpUndefined:
2679a34c753fSRafael Auler     case MCCFIInstruction::OpRegister:
2680a34c753fSRafael Auler     case MCCFIInstruction::OpEscape: {
2681a34c753fSRafael Auler       uint32_t Reg;
2682a34c753fSRafael Auler       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2683a34c753fSRafael Auler         Reg = Instr.getRegister();
2684a34c753fSRafael Auler       } else {
268576cfea0cSAmir Ayupov         std::optional<uint8_t> R =
268676cfea0cSAmir Ayupov             readDWARFExpressionTargetReg(Instr.getValues());
2687a34c753fSRafael Auler         // Handle DW_CFA_def_cfa_expression
2688a34c753fSRafael Auler         if (!R) {
2689a34c753fSRafael Auler           if (RestoredCFAReg && RestoredCFAOffset)
2690a34c753fSRafael Auler             return true;
2691a34c753fSRafael Auler           RestoredCFAReg = true;
2692a34c753fSRafael Auler           RestoredCFAOffset = true;
2693a34c753fSRafael Auler           return false;
2694a34c753fSRafael Auler         }
2695a34c753fSRafael Auler         Reg = *R;
2696a34c753fSRafael Auler       }
2697a34c753fSRafael Auler       if (RestoredRegs[Reg])
2698a34c753fSRafael Auler         return true;
2699a34c753fSRafael Auler       RestoredRegs[Reg] = true;
27004e585e51SKazu Hirata       const int32_t CurRegRule = RegRule.contains(Reg) ? RegRule[Reg] : UNKNOWN;
2701a34c753fSRafael Auler       if (CurRegRule == UNKNOWN) {
2702a34c753fSRafael Auler         if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2703a34c753fSRafael Auler             Instr.getOperation() == MCCFIInstruction::OpSameValue)
2704a34c753fSRafael Auler           return true;
2705a34c753fSRafael Auler         return false;
2706a34c753fSRafael Auler       }
2707a34c753fSRafael Auler       const MCCFIInstruction &LastDef =
2708a34c753fSRafael Auler           CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2709a34c753fSRafael Auler       return LastDef == Instr;
2710a34c753fSRafael Auler     }
2711a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfaRegister:
2712a34c753fSRafael Auler       if (RestoredCFAReg)
2713a34c753fSRafael Auler         return true;
2714a34c753fSRafael Auler       RestoredCFAReg = true;
2715a34c753fSRafael Auler       return CFAReg == Instr.getRegister();
2716a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfaOffset:
2717a34c753fSRafael Auler       if (RestoredCFAOffset)
2718a34c753fSRafael Auler         return true;
2719a34c753fSRafael Auler       RestoredCFAOffset = true;
2720a34c753fSRafael Auler       return CFAOffset == Instr.getOffset();
2721a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfa:
2722a34c753fSRafael Auler       if (RestoredCFAReg && RestoredCFAOffset)
2723a34c753fSRafael Auler         return true;
2724a34c753fSRafael Auler       RestoredCFAReg = true;
2725a34c753fSRafael Auler       RestoredCFAOffset = true;
2726a34c753fSRafael Auler       return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2727a34c753fSRafael Auler     case MCCFIInstruction::OpAdjustCfaOffset:
2728a34c753fSRafael Auler     case MCCFIInstruction::OpWindowSave:
2729a34c753fSRafael Auler     case MCCFIInstruction::OpNegateRAState:
273041baa69aSKazu Hirata     case MCCFIInstruction::OpNegateRAStateWithPC:
2731a34c753fSRafael Auler     case MCCFIInstruction::OpLLVMDefAspaceCfa:
27322718654cSFangrui Song     case MCCFIInstruction::OpLabel:
273374003f11SDaniel Sanders     case MCCFIInstruction::OpValOffset:
2734a34c753fSRafael Auler       llvm_unreachable("unsupported CFI opcode");
2735a34c753fSRafael Auler       return false;
2736a34c753fSRafael Auler     case MCCFIInstruction::OpRememberState:
2737a34c753fSRafael Auler     case MCCFIInstruction::OpRestoreState:
2738a34c753fSRafael Auler     case MCCFIInstruction::OpGnuArgsSize:
2739a34c753fSRafael Auler       // do not affect CFI state
2740a34c753fSRafael Auler       return true;
2741a34c753fSRafael Auler     }
2742a34c753fSRafael Auler     return false;
2743a34c753fSRafael Auler   }
2744a34c753fSRafael Auler };
2745a34c753fSRafael Auler 
2746a34c753fSRafael Auler } // end anonymous namespace
2747a34c753fSRafael Auler 
2748a34c753fSRafael Auler bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2749a34c753fSRafael Auler                                      BinaryBasicBlock *InBB,
2750a34c753fSRafael Auler                                      BinaryBasicBlock::iterator InsertIt) {
2751a34c753fSRafael Auler   if (FromState == ToState)
2752a34c753fSRafael Auler     return true;
2753a34c753fSRafael Auler   assert(FromState < ToState && "can only replay CFIs forward");
2754a34c753fSRafael Auler 
2755a34c753fSRafael Auler   CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2756a34c753fSRafael Auler                           FrameRestoreEquivalents, FromState);
2757a34c753fSRafael Auler 
2758a34c753fSRafael Auler   std::vector<uint32_t> NewCFIs;
2759a34c753fSRafael Auler   for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2760a34c753fSRafael Auler     MCCFIInstruction *Instr = &FrameInstructions[CurState];
2761a34c753fSRafael Auler     if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2762a34c753fSRafael Auler       auto Iter = FrameRestoreEquivalents.find(CurState);
2763a34c753fSRafael Auler       assert(Iter != FrameRestoreEquivalents.end());
276440c2e0faSMaksim Panchenko       NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2765a34c753fSRafael Auler       // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2766a34c753fSRafael Auler       // so we might as well fall-through here.
2767a34c753fSRafael Auler     }
2768a34c753fSRafael Auler     NewCFIs.push_back(CurState);
2769a34c753fSRafael Auler   }
2770a34c753fSRafael Auler 
2771a34c753fSRafael Auler   // Replay instructions while avoiding duplicates
2772f40d25ddSAmir Ayupov   for (int32_t State : llvm::reverse(NewCFIs)) {
2773f40d25ddSAmir Ayupov     if (CFIDiff.isRedundant(FrameInstructions[State]))
2774a34c753fSRafael Auler       continue;
2775f40d25ddSAmir Ayupov     InsertIt = addCFIPseudo(InBB, InsertIt, State);
2776a34c753fSRafael Auler   }
2777a34c753fSRafael Auler 
2778a34c753fSRafael Auler   return true;
2779a34c753fSRafael Auler }
2780a34c753fSRafael Auler 
2781a34c753fSRafael Auler SmallVector<int32_t, 4>
2782a34c753fSRafael Auler BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2783a34c753fSRafael Auler                                BinaryBasicBlock *InBB,
2784a34c753fSRafael Auler                                BinaryBasicBlock::iterator &InsertIt) {
2785a34c753fSRafael Auler   SmallVector<int32_t, 4> NewStates;
2786a34c753fSRafael Auler 
2787a34c753fSRafael Auler   CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2788a34c753fSRafael Auler                          FrameRestoreEquivalents, ToState);
2789a34c753fSRafael Auler   CFISnapshotDiff FromCFITable(ToCFITable);
2790a34c753fSRafael Auler   FromCFITable.advanceTo(FromState);
2791a34c753fSRafael Auler 
2792a34c753fSRafael Auler   auto undoStateDefCfa = [&]() {
2793a34c753fSRafael Auler     if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2794a34c753fSRafael Auler       FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2795a34c753fSRafael Auler           nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2796a34c753fSRafael Auler       if (FromCFITable.isRedundant(FrameInstructions.back())) {
2797a34c753fSRafael Auler         FrameInstructions.pop_back();
2798a34c753fSRafael Auler         return;
2799a34c753fSRafael Auler       }
2800a34c753fSRafael Auler       NewStates.push_back(FrameInstructions.size() - 1);
2801a34c753fSRafael Auler       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2802a34c753fSRafael Auler       ++InsertIt;
2803a34c753fSRafael Auler     } else if (ToCFITable.CFARule < 0) {
2804a34c753fSRafael Auler       if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2805a34c753fSRafael Auler         return;
2806a34c753fSRafael Auler       NewStates.push_back(FrameInstructions.size());
2807a34c753fSRafael Auler       InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2808a34c753fSRafael Auler       ++InsertIt;
2809a34c753fSRafael Auler       FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2810a34c753fSRafael Auler     } else if (!FromCFITable.isRedundant(
2811a34c753fSRafael Auler                    FrameInstructions[ToCFITable.CFARule])) {
2812a34c753fSRafael Auler       NewStates.push_back(ToCFITable.CFARule);
2813a34c753fSRafael Auler       InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2814a34c753fSRafael Auler       ++InsertIt;
2815a34c753fSRafael Auler     }
2816a34c753fSRafael Auler   };
2817a34c753fSRafael Auler 
2818a34c753fSRafael Auler   auto undoState = [&](const MCCFIInstruction &Instr) {
2819a34c753fSRafael Auler     switch (Instr.getOperation()) {
2820a34c753fSRafael Auler     case MCCFIInstruction::OpRememberState:
2821a34c753fSRafael Auler     case MCCFIInstruction::OpRestoreState:
2822a34c753fSRafael Auler       break;
2823a34c753fSRafael Auler     case MCCFIInstruction::OpSameValue:
2824a34c753fSRafael Auler     case MCCFIInstruction::OpRelOffset:
2825a34c753fSRafael Auler     case MCCFIInstruction::OpOffset:
2826a34c753fSRafael Auler     case MCCFIInstruction::OpRestore:
2827a34c753fSRafael Auler     case MCCFIInstruction::OpUndefined:
2828a34c753fSRafael Auler     case MCCFIInstruction::OpEscape:
2829a34c753fSRafael Auler     case MCCFIInstruction::OpRegister: {
2830a34c753fSRafael Auler       uint32_t Reg;
2831a34c753fSRafael Auler       if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2832a34c753fSRafael Auler         Reg = Instr.getRegister();
2833a34c753fSRafael Auler       } else {
283476cfea0cSAmir Ayupov         std::optional<uint8_t> R =
283576cfea0cSAmir Ayupov             readDWARFExpressionTargetReg(Instr.getValues());
2836a34c753fSRafael Auler         // Handle DW_CFA_def_cfa_expression
2837a34c753fSRafael Auler         if (!R) {
2838a34c753fSRafael Auler           undoStateDefCfa();
2839a34c753fSRafael Auler           return;
2840a34c753fSRafael Auler         }
2841a34c753fSRafael Auler         Reg = *R;
2842a34c753fSRafael Auler       }
2843a34c753fSRafael Auler 
28444e585e51SKazu Hirata       if (!ToCFITable.RegRule.contains(Reg)) {
2845a34c753fSRafael Auler         FrameInstructions.emplace_back(
2846a34c753fSRafael Auler             MCCFIInstruction::createRestore(nullptr, Reg));
2847a34c753fSRafael Auler         if (FromCFITable.isRedundant(FrameInstructions.back())) {
2848a34c753fSRafael Auler           FrameInstructions.pop_back();
2849a34c753fSRafael Auler           break;
2850a34c753fSRafael Auler         }
2851a34c753fSRafael Auler         NewStates.push_back(FrameInstructions.size() - 1);
2852a34c753fSRafael Auler         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2853a34c753fSRafael Auler         ++InsertIt;
2854a34c753fSRafael Auler         break;
2855a34c753fSRafael Auler       }
2856a34c753fSRafael Auler       const int32_t Rule = ToCFITable.RegRule[Reg];
2857a34c753fSRafael Auler       if (Rule < 0) {
2858a34c753fSRafael Auler         if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2859a34c753fSRafael Auler           break;
2860a34c753fSRafael Auler         NewStates.push_back(FrameInstructions.size());
2861a34c753fSRafael Auler         InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2862a34c753fSRafael Auler         ++InsertIt;
2863a34c753fSRafael Auler         FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2864a34c753fSRafael Auler         break;
2865a34c753fSRafael Auler       }
2866a34c753fSRafael Auler       if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2867a34c753fSRafael Auler         break;
2868a34c753fSRafael Auler       NewStates.push_back(Rule);
2869a34c753fSRafael Auler       InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2870a34c753fSRafael Auler       ++InsertIt;
2871a34c753fSRafael Auler       break;
2872a34c753fSRafael Auler     }
2873a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfaRegister:
2874a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfaOffset:
2875a34c753fSRafael Auler     case MCCFIInstruction::OpDefCfa:
2876a34c753fSRafael Auler       undoStateDefCfa();
2877a34c753fSRafael Auler       break;
2878a34c753fSRafael Auler     case MCCFIInstruction::OpAdjustCfaOffset:
2879a34c753fSRafael Auler     case MCCFIInstruction::OpWindowSave:
2880a34c753fSRafael Auler     case MCCFIInstruction::OpNegateRAState:
288141baa69aSKazu Hirata     case MCCFIInstruction::OpNegateRAStateWithPC:
2882a34c753fSRafael Auler     case MCCFIInstruction::OpLLVMDefAspaceCfa:
28832718654cSFangrui Song     case MCCFIInstruction::OpLabel:
288474003f11SDaniel Sanders     case MCCFIInstruction::OpValOffset:
2885a34c753fSRafael Auler       llvm_unreachable("unsupported CFI opcode");
2886a34c753fSRafael Auler       break;
2887a34c753fSRafael Auler     case MCCFIInstruction::OpGnuArgsSize:
2888a34c753fSRafael Auler       // do not affect CFI state
2889a34c753fSRafael Auler       break;
2890a34c753fSRafael Auler     }
2891a34c753fSRafael Auler   };
2892a34c753fSRafael Auler 
2893a34c753fSRafael Auler   // Undo all modifications from ToState to FromState
2894a34c753fSRafael Auler   for (int32_t I = ToState, E = FromState; I != E; ++I) {
2895a34c753fSRafael Auler     const MCCFIInstruction &Instr = FrameInstructions[I];
2896a34c753fSRafael Auler     if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2897a34c753fSRafael Auler       undoState(Instr);
2898a34c753fSRafael Auler       continue;
2899a34c753fSRafael Auler     }
2900a34c753fSRafael Auler     auto Iter = FrameRestoreEquivalents.find(I);
2901a34c753fSRafael Auler     if (Iter == FrameRestoreEquivalents.end())
2902a34c753fSRafael Auler       continue;
2903a34c753fSRafael Auler     for (int32_t State : Iter->second)
2904a34c753fSRafael Auler       undoState(FrameInstructions[State]);
2905a34c753fSRafael Auler   }
2906a34c753fSRafael Auler 
2907a34c753fSRafael Auler   return NewStates;
2908a34c753fSRafael Auler }
2909a34c753fSRafael Auler 
2910a34c753fSRafael Auler void BinaryFunction::normalizeCFIState() {
2911a34c753fSRafael Auler   // Reordering blocks with remember-restore state instructions can be specially
2912a34c753fSRafael Auler   // tricky. When rewriting the CFI, we omit remember-restore state instructions
2913a34c753fSRafael Auler   // entirely. For restore state, we build a map expanding each restore to the
2914a34c753fSRafael Auler   // equivalent unwindCFIState sequence required at that point to achieve the
2915a34c753fSRafael Auler   // same effect of the restore. All remember state are then just ignored.
2916a34c753fSRafael Auler   std::stack<int32_t> Stack;
29178477bc67SFabian Parzefall   for (BinaryBasicBlock *CurBB : Layout.blocks()) {
2918a34c753fSRafael Auler     for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2919a34c753fSRafael Auler       if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2920a34c753fSRafael Auler         if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2921a34c753fSRafael Auler           Stack.push(II->getOperand(0).getImm());
2922a34c753fSRafael Auler           continue;
2923a34c753fSRafael Auler         }
2924a34c753fSRafael Auler         if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2925a34c753fSRafael Auler           const int32_t RememberState = Stack.top();
2926a34c753fSRafael Auler           const int32_t CurState = II->getOperand(0).getImm();
2927a34c753fSRafael Auler           FrameRestoreEquivalents[CurState] =
2928a34c753fSRafael Auler               unwindCFIState(CurState, RememberState, CurBB, II);
2929a34c753fSRafael Auler           Stack.pop();
2930a34c753fSRafael Auler         }
2931a34c753fSRafael Auler       }
2932a34c753fSRafael Auler     }
2933a34c753fSRafael Auler   }
2934a34c753fSRafael Auler }
2935a34c753fSRafael Auler 
2936a34c753fSRafael Auler bool BinaryFunction::finalizeCFIState() {
2937a34c753fSRafael Auler   LLVM_DEBUG(
2938a34c753fSRafael Auler       dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2939a34c753fSRafael Auler   LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2940a34c753fSRafael Auler                     << ": ");
2941a34c753fSRafael Auler 
2942a34c753fSRafael Auler   const char *Sep = "";
2943a34c753fSRafael Auler   (void)Sep;
294407f63b0aSFabian Parzefall   for (FunctionFragment &FF : Layout.fragments()) {
29458477bc67SFabian Parzefall     // Hot-cold border: at start of each region (with a different FDE) we need
29468477bc67SFabian Parzefall     // to reset the CFI state.
29478477bc67SFabian Parzefall     int32_t State = 0;
2948a34c753fSRafael Auler 
29490f8412c1SFabian Parzefall     for (BinaryBasicBlock *BB : FF) {
29508477bc67SFabian Parzefall       const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2951a34c753fSRafael Auler 
2952a34c753fSRafael Auler       // We need to recover the correct state if it doesn't match expected
2953a34c753fSRafael Auler       // state at BB entry point.
2954a34c753fSRafael Auler       if (BB->getCFIState() < State) {
2955a34c753fSRafael Auler         // In this case, State is currently higher than what this BB expect it
2956a34c753fSRafael Auler         // to be. To solve this, we need to insert CFI instructions to undo
2957a34c753fSRafael Auler         // the effect of all CFI from BB's state to current State.
2958a34c753fSRafael Auler         auto InsertIt = BB->begin();
2959a34c753fSRafael Auler         unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2960a34c753fSRafael Auler       } else if (BB->getCFIState() > State) {
29618477bc67SFabian Parzefall         // If BB's CFI state is greater than State, it means we are behind in
29628477bc67SFabian Parzefall         // the state. Just emit all instructions to reach this state at the
2963a34c753fSRafael Auler         // beginning of this BB. If this sequence of instructions involve
2964a34c753fSRafael Auler         // remember state or restore state, bail out.
2965a34c753fSRafael Auler         if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2966a34c753fSRafael Auler           return false;
2967a34c753fSRafael Auler       }
2968a34c753fSRafael Auler 
2969a34c753fSRafael Auler       State = CFIStateAtExit;
2970a34c753fSRafael Auler       LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2971a34c753fSRafael Auler     }
29728477bc67SFabian Parzefall   }
2973a34c753fSRafael Auler   LLVM_DEBUG(dbgs() << "\n");
2974a34c753fSRafael Auler 
2975d55dfeafSFabian Parzefall   for (BinaryBasicBlock &BB : blocks()) {
2976d55dfeafSFabian Parzefall     for (auto II = BB.begin(); II != BB.end();) {
2977a34c753fSRafael Auler       const MCCFIInstruction *CFI = getCFIFor(*II);
297840c2e0faSMaksim Panchenko       if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2979a34c753fSRafael Auler                   CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2980d55dfeafSFabian Parzefall         II = BB.eraseInstruction(II);
2981a34c753fSRafael Auler       } else {
2982a34c753fSRafael Auler         ++II;
2983a34c753fSRafael Auler       }
2984a34c753fSRafael Auler     }
2985a34c753fSRafael Auler   }
2986a34c753fSRafael Auler 
2987a34c753fSRafael Auler   return true;
2988a34c753fSRafael Auler }
2989a34c753fSRafael Auler 
2990a34c753fSRafael Auler bool BinaryFunction::requiresAddressTranslation() const {
2991a34c753fSRafael Auler   return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2992a34c753fSRafael Auler }
2993a34c753fSRafael Auler 
299423c8d382SJob Noorman bool BinaryFunction::requiresAddressMap() const {
299523c8d382SJob Noorman   if (isInjected())
299623c8d382SJob Noorman     return false;
299723c8d382SJob Noorman 
299823c8d382SJob Noorman   return opts::UpdateDebugSections || isMultiEntry() ||
299923c8d382SJob Noorman          requiresAddressTranslation();
300023c8d382SJob Noorman }
300123c8d382SJob Noorman 
3002a34c753fSRafael Auler uint64_t BinaryFunction::getInstructionCount() const {
3003a34c753fSRafael Auler   uint64_t Count = 0;
3004d55dfeafSFabian Parzefall   for (const BinaryBasicBlock &BB : blocks())
3005d55dfeafSFabian Parzefall     Count += BB.getNumNonPseudos();
3006a34c753fSRafael Auler   return Count;
3007a34c753fSRafael Auler }
3008a34c753fSRafael Auler 
3009a34c753fSRafael Auler void BinaryFunction::clearDisasmState() {
3010a34c753fSRafael Auler   clearList(Instructions);
3011a34c753fSRafael Auler   clearList(IgnoredBranches);
3012a34c753fSRafael Auler   clearList(TakenBranches);
3013a34c753fSRafael Auler 
3014a34c753fSRafael Auler   if (BC.HasRelocations) {
30153652483cSRafael Auler     for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
3016a34c753fSRafael Auler       BC.UndefinedSymbols.insert(LI.second);
3017a191ea7dSFabian Parzefall     for (MCSymbol *const EndLabel : FunctionEndLabels)
3018a191ea7dSFabian Parzefall       if (EndLabel)
3019a191ea7dSFabian Parzefall         BC.UndefinedSymbols.insert(EndLabel);
3020a34c753fSRafael Auler   }
3021a34c753fSRafael Auler }
3022a34c753fSRafael Auler 
3023a34c753fSRafael Auler void BinaryFunction::setTrapOnEntry() {
3024a34c753fSRafael Auler   clearDisasmState();
3025a34c753fSRafael Auler 
3026d77f96a9SAmir Ayupov   forEachEntryPoint([&](uint64_t Offset, const MCSymbol *Label) -> bool {
3027a34c753fSRafael Auler     MCInst TrapInstr;
3028a34c753fSRafael Auler     BC.MIB->createTrap(TrapInstr);
3029a34c753fSRafael Auler     addInstruction(Offset, std::move(TrapInstr));
3030d77f96a9SAmir Ayupov     return true;
3031d77f96a9SAmir Ayupov   });
3032a34c753fSRafael Auler 
3033a34c753fSRafael Auler   TrapsOnEntry = true;
3034a34c753fSRafael Auler }
3035a34c753fSRafael Auler 
3036a34c753fSRafael Auler void BinaryFunction::setIgnored() {
3037a34c753fSRafael Auler   if (opts::processAllFunctions()) {
3038a34c753fSRafael Auler     // We can accept ignored functions before they've been disassembled.
3039a34c753fSRafael Auler     // In that case, they would still get disassembled and emited, but not
3040a34c753fSRafael Auler     // optimized.
3041a34c753fSRafael Auler     assert(CurrentState == State::Empty &&
3042a34c753fSRafael Auler            "cannot ignore non-empty functions in current mode");
3043a34c753fSRafael Auler     IsIgnored = true;
3044a34c753fSRafael Auler     return;
3045a34c753fSRafael Auler   }
3046a34c753fSRafael Auler 
3047a34c753fSRafael Auler   clearDisasmState();
3048a34c753fSRafael Auler 
3049a34c753fSRafael Auler   // Clear CFG state too.
3050a34c753fSRafael Auler   if (hasCFG()) {
3051a34c753fSRafael Auler     releaseCFG();
3052a34c753fSRafael Auler 
30533652483cSRafael Auler     for (BinaryBasicBlock *BB : BasicBlocks)
3054a34c753fSRafael Auler       delete BB;
3055a34c753fSRafael Auler     clearList(BasicBlocks);
3056a34c753fSRafael Auler 
30573652483cSRafael Auler     for (BinaryBasicBlock *BB : DeletedBasicBlocks)
3058a34c753fSRafael Auler       delete BB;
3059a34c753fSRafael Auler     clearList(DeletedBasicBlocks);
3060a34c753fSRafael Auler 
30618477bc67SFabian Parzefall     Layout.clear();
3062a34c753fSRafael Auler   }
3063a34c753fSRafael Auler 
3064a34c753fSRafael Auler   CurrentState = State::Empty;
3065a34c753fSRafael Auler 
3066a34c753fSRafael Auler   IsIgnored = true;
3067a34c753fSRafael Auler   IsSimple = false;
3068a34c753fSRafael Auler   LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
3069a34c753fSRafael Auler }
3070a34c753fSRafael Auler 
3071a34c753fSRafael Auler void BinaryFunction::duplicateConstantIslands() {
3072a34c753fSRafael Auler   assert(Islands && "function expected to have constant islands");
3073a34c753fSRafael Auler 
30748477bc67SFabian Parzefall   for (BinaryBasicBlock *BB : getLayout().blocks()) {
3075a34c753fSRafael Auler     if (!BB->isCold())
3076a34c753fSRafael Auler       continue;
3077a34c753fSRafael Auler 
3078a34c753fSRafael Auler     for (MCInst &Inst : *BB) {
3079a34c753fSRafael Auler       int OpNum = 0;
3080a34c753fSRafael Auler       for (MCOperand &Operand : Inst) {
3081a34c753fSRafael Auler         if (!Operand.isExpr()) {
3082a34c753fSRafael Auler           ++OpNum;
3083a34c753fSRafael Auler           continue;
3084a34c753fSRafael Auler         }
3085a34c753fSRafael Auler         const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
3086a34c753fSRafael Auler         // Check if this is an island symbol
3087a34c753fSRafael Auler         if (!Islands->Symbols.count(Symbol) &&
3088a34c753fSRafael Auler             !Islands->ProxySymbols.count(Symbol))
3089a34c753fSRafael Auler           continue;
3090a34c753fSRafael Auler 
3091a34c753fSRafael Auler         // Create cold symbol, if missing
3092a34c753fSRafael Auler         auto ISym = Islands->ColdSymbols.find(Symbol);
3093a34c753fSRafael Auler         MCSymbol *ColdSymbol;
3094a34c753fSRafael Auler         if (ISym != Islands->ColdSymbols.end()) {
3095a34c753fSRafael Auler           ColdSymbol = ISym->second;
3096a34c753fSRafael Auler         } else {
3097a34c753fSRafael Auler           ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
3098a34c753fSRafael Auler           Islands->ColdSymbols[Symbol] = ColdSymbol;
3099a34c753fSRafael Auler           // Check if this is a proxy island symbol and update owner proxy map
3100a34c753fSRafael Auler           if (Islands->ProxySymbols.count(Symbol)) {
3101a34c753fSRafael Auler             BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
3102a34c753fSRafael Auler             auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
3103a34c753fSRafael Auler             Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
3104a34c753fSRafael Auler           }
3105a34c753fSRafael Auler         }
3106a34c753fSRafael Auler 
3107a34c753fSRafael Auler         // Update instruction reference
3108a34c753fSRafael Auler         Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
3109a34c753fSRafael Auler             Inst,
3110a34c753fSRafael Auler             MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
3111a34c753fSRafael Auler                                     *BC.Ctx),
3112a34c753fSRafael Auler             *BC.Ctx, 0));
3113a34c753fSRafael Auler         ++OpNum;
3114a34c753fSRafael Auler       }
3115a34c753fSRafael Auler     }
3116a34c753fSRafael Auler   }
3117a34c753fSRafael Auler }
3118a34c753fSRafael Auler 
3119a34c753fSRafael Auler #ifndef MAX_PATH
3120a34c753fSRafael Auler #define MAX_PATH 255
3121a34c753fSRafael Auler #endif
3122a34c753fSRafael Auler 
3123be2f67c4SAmir Ayupov static std::string constructFilename(std::string Filename,
3124be2f67c4SAmir Ayupov                                      std::string Annotation,
3125a34c753fSRafael Auler                                      std::string Suffix) {
3126a34c753fSRafael Auler   std::replace(Filename.begin(), Filename.end(), '/', '-');
31273652483cSRafael Auler   if (!Annotation.empty())
3128a34c753fSRafael Auler     Annotation.insert(0, "-");
3129a34c753fSRafael Auler   if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
3130a34c753fSRafael Auler     assert(Suffix.size() + Annotation.size() <= MAX_PATH);
3131a34c753fSRafael Auler     Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
3132a34c753fSRafael Auler   }
3133a34c753fSRafael Auler   Filename += Annotation;
3134a34c753fSRafael Auler   Filename += Suffix;
3135a34c753fSRafael Auler   return Filename;
3136a34c753fSRafael Auler }
3137a34c753fSRafael Auler 
3138be2f67c4SAmir Ayupov static std::string formatEscapes(const std::string &Str) {
3139a34c753fSRafael Auler   std::string Result;
3140a34c753fSRafael Auler   for (unsigned I = 0; I < Str.size(); ++I) {
3141a34c753fSRafael Auler     char C = Str[I];
3142a34c753fSRafael Auler     switch (C) {
3143a34c753fSRafael Auler     case '\n':
3144a34c753fSRafael Auler       Result += "&#13;";
3145a34c753fSRafael Auler       break;
3146a34c753fSRafael Auler     case '"':
3147a34c753fSRafael Auler       break;
3148a34c753fSRafael Auler     default:
3149a34c753fSRafael Auler       Result += C;
3150a34c753fSRafael Auler       break;
3151a34c753fSRafael Auler     }
3152a34c753fSRafael Auler   }
3153a34c753fSRafael Auler   return Result;
3154a34c753fSRafael Auler }
3155a34c753fSRafael Auler 
3156a34c753fSRafael Auler void BinaryFunction::dumpGraph(raw_ostream &OS) const {
31576333e5ddSAmir Ayupov   OS << "digraph \"" << getPrintName() << "\" {\n"
31586333e5ddSAmir Ayupov      << "node [fontname=courier, shape=box, style=filled, colorscheme=brbg9]\n";
3159a34c753fSRafael Auler   uint64_t Offset = Address;
3160a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
31618477bc67SFabian Parzefall     auto LayoutPos = find(Layout.blocks(), BB);
31628477bc67SFabian Parzefall     unsigned LayoutIndex = LayoutPos - Layout.block_begin();
3163a34c753fSRafael Auler     const char *ColdStr = BB->isCold() ? " (cold)" : "";
31646333e5ddSAmir Ayupov     std::vector<std::string> Attrs;
31656333e5ddSAmir Ayupov     // Bold box for entry points
31666333e5ddSAmir Ayupov     if (isEntryPoint(*BB))
31676333e5ddSAmir Ayupov       Attrs.push_back("penwidth=2");
31686333e5ddSAmir Ayupov     if (BLI && BLI->getLoopFor(BB)) {
31696333e5ddSAmir Ayupov       // Distinguish innermost loops
31706333e5ddSAmir Ayupov       const BinaryLoop *Loop = BLI->getLoopFor(BB);
31716333e5ddSAmir Ayupov       if (Loop->isInnermost())
31726333e5ddSAmir Ayupov         Attrs.push_back("fillcolor=6");
31736333e5ddSAmir Ayupov       else // some outer loop
31746333e5ddSAmir Ayupov         Attrs.push_back("fillcolor=4");
31756333e5ddSAmir Ayupov     } else { // non-loopy code
31766333e5ddSAmir Ayupov       Attrs.push_back("fillcolor=5");
31776333e5ddSAmir Ayupov     }
31786333e5ddSAmir Ayupov     ListSeparator LS;
31796333e5ddSAmir Ayupov     OS << "\"" << BB->getName() << "\" [";
31806333e5ddSAmir Ayupov     for (StringRef Attr : Attrs)
31816333e5ddSAmir Ayupov       OS << LS << Attr;
31826333e5ddSAmir Ayupov     OS << "]\n";
3183cc23c64fSAmir Ayupov     OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u,CFI:%u)\\n",
3184cc23c64fSAmir Ayupov                  BB->getName().data(), BB->getName().data(), ColdStr,
3185cc23c64fSAmir Ayupov                  BB->getKnownExecutionCount(), BB->getOffset(), getIndex(BB),
31868477bc67SFabian Parzefall                  LayoutIndex, BB->getCFIState());
3187cc23c64fSAmir Ayupov 
3188a34c753fSRafael Auler     if (opts::DotToolTipCode) {
3189a34c753fSRafael Auler       std::string Str;
3190a34c753fSRafael Auler       raw_string_ostream CS(Str);
3191cc23c64fSAmir Ayupov       Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this,
3192cc23c64fSAmir Ayupov                                     /* PrintMCInst = */ false,
3193cc23c64fSAmir Ayupov                                     /* PrintMemData = */ false,
3194cc23c64fSAmir Ayupov                                     /* PrintRelocations = */ false,
3195cc23c64fSAmir Ayupov                                     /* Endl = */ R"(\\l)");
3196cc23c64fSAmir Ayupov       OS << formatEscapes(CS.str()) << '\n';
3197a34c753fSRafael Auler     }
3198cc23c64fSAmir Ayupov     OS << "\"]\n";
3199a34c753fSRafael Auler 
3200a34c753fSRafael Auler     // analyzeBranch is just used to get the names of the branch
3201a34c753fSRafael Auler     // opcodes.
3202a34c753fSRafael Auler     const MCSymbol *TBB = nullptr;
3203a34c753fSRafael Auler     const MCSymbol *FBB = nullptr;
3204a34c753fSRafael Auler     MCInst *CondBranch = nullptr;
3205a34c753fSRafael Auler     MCInst *UncondBranch = nullptr;
320640c2e0faSMaksim Panchenko     const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3207a34c753fSRafael Auler 
3208a34c753fSRafael Auler     const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3209a34c753fSRafael Auler     const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3210a34c753fSRafael Auler 
3211a34c753fSRafael Auler     auto BI = BB->branch_info_begin();
3212a34c753fSRafael Auler     for (BinaryBasicBlock *Succ : BB->successors()) {
3213a34c753fSRafael Auler       std::string Branch;
3214a34c753fSRafael Auler       if (Success) {
3215a34c753fSRafael Auler         if (Succ == BB->getConditionalSuccessor(true)) {
3216a34c753fSRafael Auler           Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3217a34c753fSRafael Auler                                     CondBranch->getOpcode()))
3218a34c753fSRafael Auler                               : "TB";
3219a34c753fSRafael Auler         } else if (Succ == BB->getConditionalSuccessor(false)) {
3220a34c753fSRafael Auler           Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3221a34c753fSRafael Auler                                       UncondBranch->getOpcode()))
3222a34c753fSRafael Auler                                 : "FB";
3223a34c753fSRafael Auler         } else {
3224a34c753fSRafael Auler           Branch = "FT";
3225a34c753fSRafael Auler         }
3226a34c753fSRafael Auler       }
32273652483cSRafael Auler       if (IsJumpTable)
3228a34c753fSRafael Auler         Branch = "JT";
322940c2e0faSMaksim Panchenko       OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
323040c2e0faSMaksim Panchenko                    Succ->getName().data(), Branch.c_str());
3231a34c753fSRafael Auler 
3232a34c753fSRafael Auler       if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3233a34c753fSRafael Auler           BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3234a34c753fSRafael Auler         OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3235a34c753fSRafael Auler       } else if (ExecutionCount != COUNT_NO_PROFILE &&
3236a34c753fSRafael Auler                  BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3237a34c753fSRafael Auler         OS << "\\n(IC:" << BI->Count << ")";
3238a34c753fSRafael Auler       }
3239a34c753fSRafael Auler       OS << "\"]\n";
3240a34c753fSRafael Auler 
3241a34c753fSRafael Auler       ++BI;
3242a34c753fSRafael Auler     }
3243a34c753fSRafael Auler     for (BinaryBasicBlock *LP : BB->landing_pads()) {
3244a34c753fSRafael Auler       OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
324540c2e0faSMaksim Panchenko                    BB->getName().data(), LP->getName().data());
3246a34c753fSRafael Auler     }
3247a34c753fSRafael Auler   }
3248a34c753fSRafael Auler   OS << "}\n";
3249a34c753fSRafael Auler }
3250a34c753fSRafael Auler 
3251a34c753fSRafael Auler void BinaryFunction::viewGraph() const {
3252a34c753fSRafael Auler   SmallString<MAX_PATH> Filename;
3253a34c753fSRafael Auler   if (std::error_code EC =
3254a34c753fSRafael Auler           sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
325552cf0711SAmir Ayupov     BC.errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3256a34c753fSRafael Auler               << " bolt-cfg-XXXXX.dot temporary file.\n";
3257a34c753fSRafael Auler     return;
3258a34c753fSRafael Auler   }
3259a34c753fSRafael Auler   dumpGraphToFile(std::string(Filename));
32603652483cSRafael Auler   if (DisplayGraph(Filename))
326152cf0711SAmir Ayupov     BC.errs() << "BOLT-ERROR: Can't display " << Filename
326252cf0711SAmir Ayupov               << " with graphviz.\n";
3263a34c753fSRafael Auler   if (std::error_code EC = sys::fs::remove(Filename)) {
326452cf0711SAmir Ayupov     BC.errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3265a34c753fSRafael Auler               << Filename << "\n";
3266a34c753fSRafael Auler   }
3267a34c753fSRafael Auler }
3268a34c753fSRafael Auler 
3269a34c753fSRafael Auler void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3270798e92c6SAmir Ayupov   if (!opts::shouldPrint(*this))
3271798e92c6SAmir Ayupov     return;
3272798e92c6SAmir Ayupov 
3273a34c753fSRafael Auler   std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3274798e92c6SAmir Ayupov   if (opts::Verbosity >= 1)
327552cf0711SAmir Ayupov     BC.outs() << "BOLT-INFO: dumping CFG to " << Filename << "\n";
3276a34c753fSRafael Auler   dumpGraphToFile(Filename);
3277a34c753fSRafael Auler }
3278a34c753fSRafael Auler 
3279a34c753fSRafael Auler void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3280a34c753fSRafael Auler   std::error_code EC;
3281a34c753fSRafael Auler   raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3282a34c753fSRafael Auler   if (EC) {
3283a34c753fSRafael Auler     if (opts::Verbosity >= 1) {
328452cf0711SAmir Ayupov       BC.errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3285a34c753fSRafael Auler                 << Filename << " for output.\n";
3286a34c753fSRafael Auler     }
3287a34c753fSRafael Auler     return;
3288a34c753fSRafael Auler   }
3289a34c753fSRafael Auler   dumpGraph(of);
3290a34c753fSRafael Auler }
3291a34c753fSRafael Auler 
3292a34c753fSRafael Auler bool BinaryFunction::validateCFG() const {
329316fd8799Szhoujiapeng   // Skip the validation of CFG after it is finalized
329416fd8799Szhoujiapeng   if (CurrentState == State::CFG_Finalized)
329516fd8799Szhoujiapeng     return true;
329616fd8799Szhoujiapeng 
32973652483cSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks)
3298725014d8SNathan Sidwell     if (!BB->validateSuccessorInvariants())
3299725014d8SNathan Sidwell       return false;
3300a34c753fSRafael Auler 
3301a34c753fSRafael Auler   // Make sure all blocks in CFG are valid.
3302a34c753fSRafael Auler   auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3303a34c753fSRafael Auler     if (!BB->isValid()) {
330452cf0711SAmir Ayupov       BC.errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3305a34c753fSRafael Auler                 << " detected in:\n";
3306a34c753fSRafael Auler       this->dump();
3307a34c753fSRafael Auler       return false;
3308a34c753fSRafael Auler     }
3309a34c753fSRafael Auler     return true;
3310a34c753fSRafael Auler   };
3311a34c753fSRafael Auler   for (const BinaryBasicBlock *BB : BasicBlocks) {
3312a34c753fSRafael Auler     if (!validateBlock(BB, "block"))
3313a34c753fSRafael Auler       return false;
3314a34c753fSRafael Auler     for (const BinaryBasicBlock *PredBB : BB->predecessors())
3315a34c753fSRafael Auler       if (!validateBlock(PredBB, "predecessor"))
3316a34c753fSRafael Auler         return false;
3317a34c753fSRafael Auler     for (const BinaryBasicBlock *SuccBB : BB->successors())
3318a34c753fSRafael Auler       if (!validateBlock(SuccBB, "successor"))
3319a34c753fSRafael Auler         return false;
3320a34c753fSRafael Auler     for (const BinaryBasicBlock *LP : BB->landing_pads())
3321a34c753fSRafael Auler       if (!validateBlock(LP, "landing pad"))
3322a34c753fSRafael Auler         return false;
3323a34c753fSRafael Auler     for (const BinaryBasicBlock *Thrower : BB->throwers())
3324a34c753fSRafael Auler       if (!validateBlock(Thrower, "thrower"))
3325a34c753fSRafael Auler         return false;
3326a34c753fSRafael Auler   }
3327a34c753fSRafael Auler 
3328a34c753fSRafael Auler   for (const BinaryBasicBlock *BB : BasicBlocks) {
3329a34c753fSRafael Auler     std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3330a34c753fSRafael Auler     for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3331a34c753fSRafael Auler       if (BBLandingPads.count(LP)) {
333252cf0711SAmir Ayupov         BC.errs() << "BOLT-ERROR: duplicate landing pad detected in"
3333a34c753fSRafael Auler                   << BB->getName() << " in function " << *this << '\n';
3334a34c753fSRafael Auler         return false;
3335a34c753fSRafael Auler       }
3336a34c753fSRafael Auler       BBLandingPads.insert(LP);
3337a34c753fSRafael Auler     }
3338a34c753fSRafael Auler 
3339a34c753fSRafael Auler     std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3340a34c753fSRafael Auler     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3341a34c753fSRafael Auler       if (BBThrowers.count(Thrower)) {
334252cf0711SAmir Ayupov         BC.errs() << "BOLT-ERROR: duplicate thrower detected in"
334352cf0711SAmir Ayupov                   << BB->getName() << " in function " << *this << '\n';
3344a34c753fSRafael Auler         return false;
3345a34c753fSRafael Auler       }
3346a34c753fSRafael Auler       BBThrowers.insert(Thrower);
3347a34c753fSRafael Auler     }
3348a34c753fSRafael Auler 
3349a34c753fSRafael Auler     for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3350d2c87699SAmir Ayupov       if (!llvm::is_contained(LPBlock->throwers(), BB)) {
335152cf0711SAmir Ayupov         BC.errs() << "BOLT-ERROR: inconsistent landing pad detected in "
335252cf0711SAmir Ayupov                   << *this << ": " << BB->getName()
335352cf0711SAmir Ayupov                   << " is in LandingPads but not in " << LPBlock->getName()
335452cf0711SAmir Ayupov                   << " Throwers\n";
3355a34c753fSRafael Auler         return false;
3356a34c753fSRafael Auler       }
3357a34c753fSRafael Auler     }
3358a34c753fSRafael Auler     for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3359d2c87699SAmir Ayupov       if (!llvm::is_contained(Thrower->landing_pads(), BB)) {
336052cf0711SAmir Ayupov         BC.errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
336140c2e0faSMaksim Panchenko                   << ": " << BB->getName() << " is in Throwers list but not in "
336240c2e0faSMaksim Panchenko                   << Thrower->getName() << " LandingPads\n";
3363a34c753fSRafael Auler         return false;
3364a34c753fSRafael Auler       }
3365a34c753fSRafael Auler     }
3366a34c753fSRafael Auler   }
3367a34c753fSRafael Auler 
3368725014d8SNathan Sidwell   return true;
3369a34c753fSRafael Auler }
3370a34c753fSRafael Auler 
3371a34c753fSRafael Auler void BinaryFunction::fixBranches() {
3372a34c753fSRafael Auler   auto &MIB = BC.MIB;
3373a34c753fSRafael Auler   MCContext *Ctx = BC.Ctx.get();
3374a34c753fSRafael Auler 
33758477bc67SFabian Parzefall   for (BinaryBasicBlock *BB : BasicBlocks) {
3376a34c753fSRafael Auler     const MCSymbol *TBB = nullptr;
3377a34c753fSRafael Auler     const MCSymbol *FBB = nullptr;
3378a34c753fSRafael Auler     MCInst *CondBranch = nullptr;
3379a34c753fSRafael Auler     MCInst *UncondBranch = nullptr;
3380a34c753fSRafael Auler     if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3381a34c753fSRafael Auler       continue;
3382a34c753fSRafael Auler 
3383a34c753fSRafael Auler     // We will create unconditional branch with correct destination if needed.
3384a34c753fSRafael Auler     if (UncondBranch)
3385a34c753fSRafael Auler       BB->eraseInstruction(BB->findInstruction(UncondBranch));
3386a34c753fSRafael Auler 
3387a34c753fSRafael Auler     // Basic block that follows the current one in the final layout.
33884bcbbe1fSMaksim Panchenko     const BinaryBasicBlock *const NextBB =
33898477bc67SFabian Parzefall         Layout.getBasicBlockAfter(BB, /*IgnoreSplits=*/false);
3390a34c753fSRafael Auler 
3391a34c753fSRafael Auler     if (BB->succ_size() == 1) {
3392a34c753fSRafael Auler       // __builtin_unreachable() could create a conditional branch that
3393a34c753fSRafael Auler       // falls-through into the next function - hence the block will have only
3394a34c753fSRafael Auler       // one valid successor. Since behaviour is undefined - we replace
3395a34c753fSRafael Auler       // the conditional branch with an unconditional if required.
3396a34c753fSRafael Auler       if (CondBranch)
3397a34c753fSRafael Auler         BB->eraseInstruction(BB->findInstruction(CondBranch));
3398a34c753fSRafael Auler       if (BB->getSuccessor() == NextBB)
3399a34c753fSRafael Auler         continue;
3400a34c753fSRafael Auler       BB->addBranchInstruction(BB->getSuccessor());
3401a34c753fSRafael Auler     } else if (BB->succ_size() == 2) {
3402a34c753fSRafael Auler       assert(CondBranch && "conditional branch expected");
3403a34c753fSRafael Auler       const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3404a34c753fSRafael Auler       const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
34054bcbbe1fSMaksim Panchenko 
34064bcbbe1fSMaksim Panchenko       // Eliminate unnecessary conditional branch.
34074bcbbe1fSMaksim Panchenko       if (TSuccessor == FSuccessor) {
34086b1cf004SMaksim Panchenko         // FIXME: at the moment, we cannot safely remove static key branches.
34096b1cf004SMaksim Panchenko         if (MIB->isDynamicBranch(*CondBranch)) {
34106b1cf004SMaksim Panchenko           if (opts::Verbosity) {
34116b1cf004SMaksim Panchenko             BC.outs()
34126b1cf004SMaksim Panchenko                 << "BOLT-INFO: unable to remove redundant dynamic branch in "
34136b1cf004SMaksim Panchenko                 << *this << '\n';
34146b1cf004SMaksim Panchenko           }
34156b1cf004SMaksim Panchenko           continue;
34166b1cf004SMaksim Panchenko         }
34176b1cf004SMaksim Panchenko 
34184bcbbe1fSMaksim Panchenko         BB->removeDuplicateConditionalSuccessor(CondBranch);
34194bcbbe1fSMaksim Panchenko         if (TSuccessor != NextBB)
34204bcbbe1fSMaksim Panchenko           BB->addBranchInstruction(TSuccessor);
34214bcbbe1fSMaksim Panchenko         continue;
34224bcbbe1fSMaksim Panchenko       }
34234bcbbe1fSMaksim Panchenko 
34244bcbbe1fSMaksim Panchenko       // Reverse branch condition and swap successors.
34254bcbbe1fSMaksim Panchenko       auto swapSuccessors = [&]() {
342676fdc2e5SNathan Sidwell         if (!MIB->isReversibleBranch(*CondBranch)) {
34276b1cf004SMaksim Panchenko           if (opts::Verbosity) {
34286b1cf004SMaksim Panchenko             BC.outs() << "BOLT-INFO: unable to swap successors in " << *this
34296b1cf004SMaksim Panchenko                       << '\n';
34306b1cf004SMaksim Panchenko           }
34314bcbbe1fSMaksim Panchenko           return false;
34326b1cf004SMaksim Panchenko         }
3433a34c753fSRafael Auler         std::swap(TSuccessor, FSuccessor);
34344bcbbe1fSMaksim Panchenko         BB->swapConditionalSuccessors();
3435a34c753fSRafael Auler         auto L = BC.scopeLock();
3436a34c753fSRafael Auler         MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
34374bcbbe1fSMaksim Panchenko         return true;
34384bcbbe1fSMaksim Panchenko       };
34394bcbbe1fSMaksim Panchenko 
34404bcbbe1fSMaksim Panchenko       // Check whether the next block is a "taken" target and try to swap it
34414bcbbe1fSMaksim Panchenko       // with a "fall-through" target.
34424bcbbe1fSMaksim Panchenko       if (TSuccessor == NextBB && swapSuccessors())
34434bcbbe1fSMaksim Panchenko         continue;
34444bcbbe1fSMaksim Panchenko 
34454bcbbe1fSMaksim Panchenko       // Update conditional branch destination if needed.
34464bcbbe1fSMaksim Panchenko       if (MIB->getTargetSymbol(*CondBranch) != TSuccessor->getLabel()) {
3447a34c753fSRafael Auler         auto L = BC.scopeLock();
3448a34c753fSRafael Auler         MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3449a34c753fSRafael Auler       }
34504bcbbe1fSMaksim Panchenko 
34514bcbbe1fSMaksim Panchenko       // No need for the unconditional branch.
34524bcbbe1fSMaksim Panchenko       if (FSuccessor == NextBB)
34534bcbbe1fSMaksim Panchenko         continue;
34544bcbbe1fSMaksim Panchenko 
34554bcbbe1fSMaksim Panchenko       if (BC.isX86()) {
34564bcbbe1fSMaksim Panchenko         // We are going to generate two branches. Check if their targets are in
34574bcbbe1fSMaksim Panchenko         // the same fragment as this block. If only one target is in the same
34584bcbbe1fSMaksim Panchenko         // fragment, make it the destination of the conditional branch. There
34594f308129SMaksim Panchenko         // is a chance it will be a short branch which takes 4 bytes fewer than
34604bcbbe1fSMaksim Panchenko         // a long conditional branch. For unconditional branch, the difference
34614f308129SMaksim Panchenko         // is 3 bytes.
34624bcbbe1fSMaksim Panchenko         if (BB->getFragmentNum() != TSuccessor->getFragmentNum() &&
34634bcbbe1fSMaksim Panchenko             BB->getFragmentNum() == FSuccessor->getFragmentNum())
34644bcbbe1fSMaksim Panchenko           swapSuccessors();
3465a34c753fSRafael Auler       }
34664bcbbe1fSMaksim Panchenko 
3467a34c753fSRafael Auler       BB->addBranchInstruction(FSuccessor);
3468a34c753fSRafael Auler     }
3469a34c753fSRafael Auler     // Cases where the number of successors is 0 (block ends with a
3470a34c753fSRafael Auler     // terminator) or more than 2 (switch table) don't require branch
3471a34c753fSRafael Auler     // instruction adjustments.
3472a34c753fSRafael Auler   }
347340c2e0faSMaksim Panchenko   assert((!isSimple() || validateCFG()) &&
347440c2e0faSMaksim Panchenko          "Invalid CFG detected after fixing branches");
3475a34c753fSRafael Auler }
3476a34c753fSRafael Auler 
3477a34c753fSRafael Auler void BinaryFunction::propagateGnuArgsSizeInfo(
3478a34c753fSRafael Auler     MCPlusBuilder::AllocatorIdTy AllocId) {
3479a34c753fSRafael Auler   assert(CurrentState == State::Disassembled && "unexpected function state");
3480a34c753fSRafael Auler 
3481a34c753fSRafael Auler   if (!hasEHRanges() || !usesGnuArgsSize())
3482a34c753fSRafael Auler     return;
3483a34c753fSRafael Auler 
3484a34c753fSRafael Auler   // The current value of DW_CFA_GNU_args_size affects all following
3485a34c753fSRafael Auler   // invoke instructions until the next CFI overrides it.
3486a34c753fSRafael Auler   // It is important to iterate basic blocks in the original order when
3487a34c753fSRafael Auler   // assigning the value.
3488a34c753fSRafael Auler   uint64_t CurrentGnuArgsSize = 0;
3489a34c753fSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks) {
3490a34c753fSRafael Auler     for (auto II = BB->begin(); II != BB->end();) {
3491a34c753fSRafael Auler       MCInst &Instr = *II;
3492a34c753fSRafael Auler       if (BC.MIB->isCFI(Instr)) {
3493a34c753fSRafael Auler         const MCCFIInstruction *CFI = getCFIFor(Instr);
3494a34c753fSRafael Auler         if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3495a34c753fSRafael Auler           CurrentGnuArgsSize = CFI->getOffset();
3496a34c753fSRafael Auler           // Delete DW_CFA_GNU_args_size instructions and only regenerate
3497a34c753fSRafael Auler           // during the final code emission. The information is embedded
3498a34c753fSRafael Auler           // inside call instructions.
3499a34c753fSRafael Auler           II = BB->erasePseudoInstruction(II);
3500a34c753fSRafael Auler           continue;
3501a34c753fSRafael Auler         }
3502a34c753fSRafael Auler       } else if (BC.MIB->isInvoke(Instr)) {
3503a34c753fSRafael Auler         // Add the value of GNU_args_size as an extra operand to invokes.
350474e0a26fSmaksfb         BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize);
3505a34c753fSRafael Auler       }
3506a34c753fSRafael Auler       ++II;
3507a34c753fSRafael Auler     }
3508a34c753fSRafael Auler   }
3509a34c753fSRafael Auler }
3510a34c753fSRafael Auler 
3511a34c753fSRafael Auler void BinaryFunction::postProcessBranches() {
3512a34c753fSRafael Auler   if (!isSimple())
3513a34c753fSRafael Auler     return;
3514d55dfeafSFabian Parzefall   for (BinaryBasicBlock &BB : blocks()) {
3515d55dfeafSFabian Parzefall     auto LastInstrRI = BB.getLastNonPseudo();
3516d55dfeafSFabian Parzefall     if (BB.succ_size() == 1) {
3517d55dfeafSFabian Parzefall       if (LastInstrRI != BB.rend() &&
3518a34c753fSRafael Auler           BC.MIB->isConditionalBranch(*LastInstrRI)) {
3519a34c753fSRafael Auler         // __builtin_unreachable() could create a conditional branch that
3520a34c753fSRafael Auler         // falls-through into the next function - hence the block will have only
3521a34c753fSRafael Auler         // one valid successor. Such behaviour is undefined and thus we remove
3522a34c753fSRafael Auler         // the conditional branch while leaving a valid successor.
3523d55dfeafSFabian Parzefall         BB.eraseInstruction(std::prev(LastInstrRI.base()));
3524a34c753fSRafael Auler         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3525d55dfeafSFabian Parzefall                           << BB.getName() << " in function " << *this << '\n');
3526a34c753fSRafael Auler       }
3527d55dfeafSFabian Parzefall     } else if (BB.succ_size() == 0) {
3528a34c753fSRafael Auler       // Ignore unreachable basic blocks.
3529d55dfeafSFabian Parzefall       if (BB.pred_size() == 0 || BB.isLandingPad())
3530a34c753fSRafael Auler         continue;
3531a34c753fSRafael Auler 
3532a34c753fSRafael Auler       // If it's the basic block that does not end up with a terminator - we
3533a34c753fSRafael Auler       // insert a return instruction unless it's a call instruction.
3534d55dfeafSFabian Parzefall       if (LastInstrRI == BB.rend()) {
3535a34c753fSRafael Auler         LLVM_DEBUG(
3536a34c753fSRafael Auler             dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3537d55dfeafSFabian Parzefall                    << BB.getName() << " in function " << *this << '\n');
3538a34c753fSRafael Auler         continue;
3539a34c753fSRafael Auler       }
3540a34c753fSRafael Auler       if (!BC.MIB->isTerminator(*LastInstrRI) &&
3541a34c753fSRafael Auler           !BC.MIB->isCall(*LastInstrRI)) {
3542a34c753fSRafael Auler         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3543d55dfeafSFabian Parzefall                           << BB.getName() << " in function " << *this << '\n');
3544a34c753fSRafael Auler         MCInst ReturnInstr;
3545a34c753fSRafael Auler         BC.MIB->createReturn(ReturnInstr);
3546d55dfeafSFabian Parzefall         BB.addInstruction(ReturnInstr);
3547a34c753fSRafael Auler       }
3548a34c753fSRafael Auler     }
3549a34c753fSRafael Auler   }
3550a34c753fSRafael Auler   assert(validateCFG() && "invalid CFG");
3551a34c753fSRafael Auler }
3552a34c753fSRafael Auler 
3553a34c753fSRafael Auler MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3554a34c753fSRafael Auler   assert(Offset && "cannot add primary entry point");
3555a34c753fSRafael Auler   assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3556a34c753fSRafael Auler 
3557a34c753fSRafael Auler   const uint64_t EntryPointAddress = getAddress() + Offset;
3558a34c753fSRafael Auler   MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3559a34c753fSRafael Auler 
3560a34c753fSRafael Auler   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3561a34c753fSRafael Auler   if (EntrySymbol)
3562a34c753fSRafael Auler     return EntrySymbol;
3563a34c753fSRafael Auler 
3564a34c753fSRafael Auler   if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3565a34c753fSRafael Auler     EntrySymbol = EntryBD->getSymbol();
3566a34c753fSRafael Auler   } else {
356740c2e0faSMaksim Panchenko     EntrySymbol = BC.getOrCreateGlobalSymbol(
356840c2e0faSMaksim Panchenko         EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3569a34c753fSRafael Auler   }
3570a34c753fSRafael Auler   SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3571a34c753fSRafael Auler 
3572a34c753fSRafael Auler   BC.setSymbolToFunctionMap(EntrySymbol, this);
3573a34c753fSRafael Auler 
3574a34c753fSRafael Auler   return EntrySymbol;
3575a34c753fSRafael Auler }
3576a34c753fSRafael Auler 
3577a34c753fSRafael Auler MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3578a34c753fSRafael Auler   assert(CurrentState == State::CFG &&
3579a34c753fSRafael Auler          "basic block can be added as an entry only in a function with CFG");
3580a34c753fSRafael Auler 
3581a34c753fSRafael Auler   if (&BB == BasicBlocks.front())
3582a34c753fSRafael Auler     return getSymbol();
3583a34c753fSRafael Auler 
3584a34c753fSRafael Auler   MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3585a34c753fSRafael Auler   if (EntrySymbol)
3586a34c753fSRafael Auler     return EntrySymbol;
3587a34c753fSRafael Auler 
3588a34c753fSRafael Auler   EntrySymbol =
3589a34c753fSRafael Auler       BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3590a34c753fSRafael Auler 
3591a34c753fSRafael Auler   SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3592a34c753fSRafael Auler 
3593a34c753fSRafael Auler   BC.setSymbolToFunctionMap(EntrySymbol, this);
3594a34c753fSRafael Auler 
3595a34c753fSRafael Auler   return EntrySymbol;
3596a34c753fSRafael Auler }
3597a34c753fSRafael Auler 
3598a34c753fSRafael Auler MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3599a34c753fSRafael Auler   if (EntryID == 0)
3600a34c753fSRafael Auler     return getSymbol();
3601a34c753fSRafael Auler 
3602a34c753fSRafael Auler   if (!isMultiEntry())
3603a34c753fSRafael Auler     return nullptr;
3604a34c753fSRafael Auler 
3605d8fe2e4bSAmir Ayupov   uint64_t NumEntries = 1;
3606a34c753fSRafael Auler   if (hasCFG()) {
3607a34c753fSRafael Auler     for (BinaryBasicBlock *BB : BasicBlocks) {
3608a34c753fSRafael Auler       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3609a34c753fSRafael Auler       if (!EntrySymbol)
3610a34c753fSRafael Auler         continue;
3611a34c753fSRafael Auler       if (NumEntries == EntryID)
3612a34c753fSRafael Auler         return EntrySymbol;
3613a34c753fSRafael Auler       ++NumEntries;
3614a34c753fSRafael Auler     }
3615a34c753fSRafael Auler   } else {
3616a34c753fSRafael Auler     for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3617a34c753fSRafael Auler       MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3618a34c753fSRafael Auler       if (!EntrySymbol)
3619a34c753fSRafael Auler         continue;
3620a34c753fSRafael Auler       if (NumEntries == EntryID)
3621a34c753fSRafael Auler         return EntrySymbol;
3622a34c753fSRafael Auler       ++NumEntries;
3623a34c753fSRafael Auler     }
3624a34c753fSRafael Auler   }
3625a34c753fSRafael Auler 
3626a34c753fSRafael Auler   return nullptr;
3627a34c753fSRafael Auler }
3628a34c753fSRafael Auler 
3629a34c753fSRafael Auler uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3630a34c753fSRafael Auler   if (!isMultiEntry())
3631a34c753fSRafael Auler     return 0;
3632a34c753fSRafael Auler 
3633a34c753fSRafael Auler   for (const MCSymbol *FunctionSymbol : getSymbols())
3634a34c753fSRafael Auler     if (FunctionSymbol == Symbol)
3635a34c753fSRafael Auler       return 0;
3636a34c753fSRafael Auler 
3637a34c753fSRafael Auler   // Check all secondary entries available as either basic blocks or lables.
3638d8fe2e4bSAmir Ayupov   uint64_t NumEntries = 1;
3639a34c753fSRafael Auler   for (const BinaryBasicBlock *BB : BasicBlocks) {
3640a34c753fSRafael Auler     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3641a34c753fSRafael Auler     if (!EntrySymbol)
3642a34c753fSRafael Auler       continue;
3643a34c753fSRafael Auler     if (EntrySymbol == Symbol)
3644a34c753fSRafael Auler       return NumEntries;
3645a34c753fSRafael Auler     ++NumEntries;
3646a34c753fSRafael Auler   }
3647d8fe2e4bSAmir Ayupov   NumEntries = 1;
3648a34c753fSRafael Auler   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3649a34c753fSRafael Auler     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3650a34c753fSRafael Auler     if (!EntrySymbol)
3651a34c753fSRafael Auler       continue;
3652a34c753fSRafael Auler     if (EntrySymbol == Symbol)
3653a34c753fSRafael Auler       return NumEntries;
3654a34c753fSRafael Auler     ++NumEntries;
3655a34c753fSRafael Auler   }
3656a34c753fSRafael Auler 
3657a34c753fSRafael Auler   llvm_unreachable("symbol not found");
3658a34c753fSRafael Auler }
3659a34c753fSRafael Auler 
3660a34c753fSRafael Auler bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3661a34c753fSRafael Auler   bool Status = Callback(0, getSymbol());
3662a34c753fSRafael Auler   if (!isMultiEntry())
3663a34c753fSRafael Auler     return Status;
3664a34c753fSRafael Auler 
3665a34c753fSRafael Auler   for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3666a34c753fSRafael Auler     if (!Status)
3667a34c753fSRafael Auler       break;
3668a34c753fSRafael Auler 
3669a34c753fSRafael Auler     MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3670a34c753fSRafael Auler     if (!EntrySymbol)
3671a34c753fSRafael Auler       continue;
3672a34c753fSRafael Auler 
3673a34c753fSRafael Auler     Status = Callback(KV.first, EntrySymbol);
3674a34c753fSRafael Auler   }
3675a34c753fSRafael Auler 
3676a34c753fSRafael Auler   return Status;
3677a34c753fSRafael Auler }
3678a34c753fSRafael Auler 
3679d55dfeafSFabian Parzefall BinaryFunction::BasicBlockListType BinaryFunction::dfs() const {
3680d55dfeafSFabian Parzefall   BasicBlockListType DFS;
3681a34c753fSRafael Auler   std::stack<BinaryBasicBlock *> Stack;
36824be3083bSshaw young   std::set<BinaryBasicBlock *> Visited;
3683a34c753fSRafael Auler 
3684a34c753fSRafael Auler   // Push entry points to the stack in reverse order.
3685a34c753fSRafael Auler   //
3686a34c753fSRafael Auler   // NB: we rely on the original order of entries to match.
3687d55dfeafSFabian Parzefall   SmallVector<BinaryBasicBlock *> EntryPoints;
3688d55dfeafSFabian Parzefall   llvm::copy_if(BasicBlocks, std::back_inserter(EntryPoints),
3689d55dfeafSFabian Parzefall           [&](const BinaryBasicBlock *const BB) { return isEntryPoint(*BB); });
3690d55dfeafSFabian Parzefall   // Sort entry points by their offset to make sure we got them in the right
3691d55dfeafSFabian Parzefall   // order.
3692d55dfeafSFabian Parzefall   llvm::stable_sort(EntryPoints, [](const BinaryBasicBlock *const A,
3693d55dfeafSFabian Parzefall                               const BinaryBasicBlock *const B) {
3694d55dfeafSFabian Parzefall     return A->getOffset() < B->getOffset();
3695d55dfeafSFabian Parzefall   });
3696d55dfeafSFabian Parzefall   for (BinaryBasicBlock *const BB : reverse(EntryPoints))
3697a34c753fSRafael Auler     Stack.push(BB);
3698d55dfeafSFabian Parzefall 
3699a34c753fSRafael Auler   while (!Stack.empty()) {
3700a34c753fSRafael Auler     BinaryBasicBlock *BB = Stack.top();
3701a34c753fSRafael Auler     Stack.pop();
3702a34c753fSRafael Auler 
37037928e14fSKazu Hirata     if (!Visited.insert(BB).second)
3704a34c753fSRafael Auler       continue;
3705a34c753fSRafael Auler     DFS.push_back(BB);
3706a34c753fSRafael Auler 
3707a34c753fSRafael Auler     for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3708a34c753fSRafael Auler       Stack.push(SuccBB);
3709a34c753fSRafael Auler     }
3710a34c753fSRafael Auler 
3711a34c753fSRafael Auler     const MCSymbol *TBB = nullptr;
3712a34c753fSRafael Auler     const MCSymbol *FBB = nullptr;
3713a34c753fSRafael Auler     MCInst *CondBranch = nullptr;
3714a34c753fSRafael Auler     MCInst *UncondBranch = nullptr;
371540c2e0faSMaksim Panchenko     if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
371640c2e0faSMaksim Panchenko         BB->succ_size() == 2) {
3717a34c753fSRafael Auler       if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3718a34c753fSRafael Auler               *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3719a34c753fSRafael Auler         Stack.push(BB->getConditionalSuccessor(true));
3720a34c753fSRafael Auler         Stack.push(BB->getConditionalSuccessor(false));
3721a34c753fSRafael Auler       } else {
3722a34c753fSRafael Auler         Stack.push(BB->getConditionalSuccessor(false));
3723a34c753fSRafael Auler         Stack.push(BB->getConditionalSuccessor(true));
3724a34c753fSRafael Auler       }
3725a34c753fSRafael Auler     } else {
3726a34c753fSRafael Auler       for (BinaryBasicBlock *SuccBB : BB->successors()) {
3727a34c753fSRafael Auler         Stack.push(SuccBB);
3728a34c753fSRafael Auler       }
3729a34c753fSRafael Auler     }
3730a34c753fSRafael Auler   }
3731a34c753fSRafael Auler 
3732a34c753fSRafael Auler   return DFS;
3733a34c753fSRafael Auler }
3734a34c753fSRafael Auler 
3735b039ccc6SAmir Ayupov size_t BinaryFunction::computeHash(bool UseDFS, HashFunction HashFunction,
3736a34c753fSRafael Auler                                    OperandHashFuncTy OperandHashFunc) const {
3737720cade2SAmir Ayupov   LLVM_DEBUG({
3738720cade2SAmir Ayupov     dbgs() << "BOLT-DEBUG: computeHash " << getPrintName() << ' '
3739720cade2SAmir Ayupov            << (UseDFS ? "dfs" : "bin") << " order "
3740720cade2SAmir Ayupov            << (HashFunction == HashFunction::StdHash ? "std::hash" : "xxh3")
3741720cade2SAmir Ayupov            << '\n';
3742720cade2SAmir Ayupov   });
3743720cade2SAmir Ayupov 
3744a34c753fSRafael Auler   if (size() == 0)
3745a34c753fSRafael Auler     return 0;
3746a34c753fSRafael Auler 
3747a34c753fSRafael Auler   assert(hasCFG() && "function is expected to have CFG");
3748a34c753fSRafael Auler 
3749d5c03defSFabian Parzefall   SmallVector<const BinaryBasicBlock *, 0> Order;
37508477bc67SFabian Parzefall   if (UseDFS)
3751d5c03defSFabian Parzefall     llvm::copy(dfs(), std::back_inserter(Order));
37528477bc67SFabian Parzefall   else
37538477bc67SFabian Parzefall     llvm::copy(Layout.blocks(), std::back_inserter(Order));
3754a34c753fSRafael Auler 
3755a34c753fSRafael Auler   // The hash is computed by creating a string of all instruction opcodes and
3756a34c753fSRafael Auler   // possibly their operands and then hashing that string with std::hash.
3757a34c753fSRafael Auler   std::string HashString;
37583e3a926bSspupyrev   for (const BinaryBasicBlock *BB : Order)
37593e3a926bSspupyrev     HashString.append(hashBlock(BC, *BB, OperandHashFunc));
3760a34c753fSRafael Auler 
3761b039ccc6SAmir Ayupov   switch (HashFunction) {
3762b039ccc6SAmir Ayupov   case HashFunction::StdHash:
3763b039ccc6SAmir Ayupov     return Hash = std::hash<std::string>{}(HashString);
3764b039ccc6SAmir Ayupov   case HashFunction::XXH3:
3765e7dd596cSspupyrev     return Hash = llvm::xxh3_64bits(HashString);
3766a34c753fSRafael Auler   }
3767b039ccc6SAmir Ayupov   llvm_unreachable("Unhandled HashFunction");
3768b039ccc6SAmir Ayupov }
3769a34c753fSRafael Auler 
3770a34c753fSRafael Auler void BinaryFunction::insertBasicBlocks(
3771a34c753fSRafael Auler     BinaryBasicBlock *Start,
3772a34c753fSRafael Auler     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
377340c2e0faSMaksim Panchenko     const bool UpdateLayout, const bool UpdateCFIState,
3774a34c753fSRafael Auler     const bool RecomputeLandingPads) {
3775f18fcdabSAmir Ayupov   const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3776a34c753fSRafael Auler   const size_t NumNewBlocks = NewBBs.size();
3777a34c753fSRafael Auler 
377840c2e0faSMaksim Panchenko   BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3779a34c753fSRafael Auler                      nullptr);
3780a34c753fSRafael Auler 
3781f18fcdabSAmir Ayupov   int64_t I = StartIndex + 1;
3782a34c753fSRafael Auler   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3783a34c753fSRafael Auler     assert(!BasicBlocks[I]);
3784a34c753fSRafael Auler     BasicBlocks[I++] = BB.release();
3785a34c753fSRafael Auler   }
3786a34c753fSRafael Auler 
37873652483cSRafael Auler   if (RecomputeLandingPads)
3788a34c753fSRafael Auler     recomputeLandingPads();
37893652483cSRafael Auler   else
3790a34c753fSRafael Auler     updateBBIndices(0);
3791a34c753fSRafael Auler 
37923652483cSRafael Auler   if (UpdateLayout)
3793a34c753fSRafael Auler     updateLayout(Start, NumNewBlocks);
3794a34c753fSRafael Auler 
37953652483cSRafael Auler   if (UpdateCFIState)
3796a34c753fSRafael Auler     updateCFIState(Start, NumNewBlocks);
3797a34c753fSRafael Auler }
3798a34c753fSRafael Auler 
3799a34c753fSRafael Auler BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3800a34c753fSRafael Auler     BinaryFunction::iterator StartBB,
3801a34c753fSRafael Auler     std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
380240c2e0faSMaksim Panchenko     const bool UpdateLayout, const bool UpdateCFIState,
3803a34c753fSRafael Auler     const bool RecomputeLandingPads) {
3804a34c753fSRafael Auler   const unsigned StartIndex = getIndex(&*StartBB);
3805a34c753fSRafael Auler   const size_t NumNewBlocks = NewBBs.size();
3806a34c753fSRafael Auler 
3807a34c753fSRafael Auler   BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3808a34c753fSRafael Auler                      nullptr);
3809a34c753fSRafael Auler   auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3810a34c753fSRafael Auler 
3811a34c753fSRafael Auler   unsigned I = StartIndex + 1;
3812a34c753fSRafael Auler   for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3813a34c753fSRafael Auler     assert(!BasicBlocks[I]);
3814a34c753fSRafael Auler     BasicBlocks[I++] = BB.release();
3815a34c753fSRafael Auler   }
3816a34c753fSRafael Auler 
38173652483cSRafael Auler   if (RecomputeLandingPads)
3818a34c753fSRafael Auler     recomputeLandingPads();
38193652483cSRafael Auler   else
3820a34c753fSRafael Auler     updateBBIndices(0);
3821a34c753fSRafael Auler 
38223652483cSRafael Auler   if (UpdateLayout)
3823a34c753fSRafael Auler     updateLayout(*std::prev(RetIter), NumNewBlocks);
3824a34c753fSRafael Auler 
38253652483cSRafael Auler   if (UpdateCFIState)
3826a34c753fSRafael Auler     updateCFIState(*std::prev(RetIter), NumNewBlocks);
3827a34c753fSRafael Auler 
3828a34c753fSRafael Auler   return RetIter;
3829a34c753fSRafael Auler }
3830a34c753fSRafael Auler 
3831a34c753fSRafael Auler void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
38323652483cSRafael Auler   for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3833a34c753fSRafael Auler     BasicBlocks[I]->Index = I;
3834a34c753fSRafael Auler }
3835a34c753fSRafael Auler 
3836a34c753fSRafael Auler void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3837a34c753fSRafael Auler                                     const unsigned NumNewBlocks) {
3838a34c753fSRafael Auler   const int32_t CFIState = Start->getCFIStateAtExit();
3839a34c753fSRafael Auler   const unsigned StartIndex = getIndex(Start) + 1;
38403652483cSRafael Auler   for (unsigned I = 0; I < NumNewBlocks; ++I)
3841a34c753fSRafael Auler     BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3842a34c753fSRafael Auler }
3843a34c753fSRafael Auler 
3844a34c753fSRafael Auler void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3845a34c753fSRafael Auler                                   const unsigned NumNewBlocks) {
38468477bc67SFabian Parzefall   BasicBlockListType::iterator Begin;
38478477bc67SFabian Parzefall   BasicBlockListType::iterator End;
38488477bc67SFabian Parzefall 
38498477bc67SFabian Parzefall   // If start not provided copy new blocks from the beginning of BasicBlocks
3850a34c753fSRafael Auler   if (!Start) {
38518477bc67SFabian Parzefall     Begin = BasicBlocks.begin();
38528477bc67SFabian Parzefall     End = BasicBlocks.begin() + NumNewBlocks;
38538477bc67SFabian Parzefall   } else {
38548477bc67SFabian Parzefall     unsigned StartIndex = getIndex(Start);
38558477bc67SFabian Parzefall     Begin = std::next(BasicBlocks.begin(), StartIndex + 1);
38568477bc67SFabian Parzefall     End = std::next(BasicBlocks.begin(), StartIndex + NumNewBlocks + 1);
3857a34c753fSRafael Auler   }
3858a34c753fSRafael Auler 
3859a34c753fSRafael Auler   // Insert new blocks in the layout immediately after Start.
38608477bc67SFabian Parzefall   Layout.insertBasicBlocks(Start, {Begin, End});
38618477bc67SFabian Parzefall   Layout.updateLayoutIndices();
3862a34c753fSRafael Auler }
3863a34c753fSRafael Auler 
3864a34c753fSRafael Auler bool BinaryFunction::checkForAmbiguousJumpTables() {
3865a34c753fSRafael Auler   SmallSet<uint64_t, 4> JumpTables;
3866a34c753fSRafael Auler   for (BinaryBasicBlock *&BB : BasicBlocks) {
3867a34c753fSRafael Auler     for (MCInst &Inst : *BB) {
3868a34c753fSRafael Auler       if (!BC.MIB->isIndirectBranch(Inst))
3869a34c753fSRafael Auler         continue;
3870a34c753fSRafael Auler       uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3871a34c753fSRafael Auler       if (!JTAddress)
3872a34c753fSRafael Auler         continue;
3873a34c753fSRafael Auler       // This address can be inside another jump table, but we only consider
3874a34c753fSRafael Auler       // it ambiguous when the same start address is used, not the same JT
3875a34c753fSRafael Auler       // object.
3876a34c753fSRafael Auler       if (!JumpTables.count(JTAddress)) {
3877a34c753fSRafael Auler         JumpTables.insert(JTAddress);
3878a34c753fSRafael Auler         continue;
3879a34c753fSRafael Auler       }
3880a34c753fSRafael Auler       return true;
3881a34c753fSRafael Auler     }
3882a34c753fSRafael Auler   }
3883a34c753fSRafael Auler   return false;
3884a34c753fSRafael Auler }
3885a34c753fSRafael Auler 
3886a34c753fSRafael Auler void BinaryFunction::disambiguateJumpTables(
3887a34c753fSRafael Auler     MCPlusBuilder::AllocatorIdTy AllocId) {
3888a34c753fSRafael Auler   assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3889a34c753fSRafael Auler   SmallPtrSet<JumpTable *, 4> JumpTables;
3890a34c753fSRafael Auler   for (BinaryBasicBlock *&BB : BasicBlocks) {
3891a34c753fSRafael Auler     for (MCInst &Inst : *BB) {
3892a34c753fSRafael Auler       if (!BC.MIB->isIndirectBranch(Inst))
3893a34c753fSRafael Auler         continue;
3894a34c753fSRafael Auler       JumpTable *JT = getJumpTable(Inst);
3895a34c753fSRafael Auler       if (!JT)
3896a34c753fSRafael Auler         continue;
38977928e14fSKazu Hirata       if (JumpTables.insert(JT).second)
3898a34c753fSRafael Auler         continue;
3899a34c753fSRafael Auler       // This instruction is an indirect jump using a jump table, but it is
3900a34c753fSRafael Auler       // using the same jump table of another jump. Try all our tricks to
3901a34c753fSRafael Auler       // extract the jump table symbol and make it point to a new, duplicated JT
3902a34c753fSRafael Auler       MCPhysReg BaseReg1;
3903a34c753fSRafael Auler       uint64_t Scale;
3904a34c753fSRafael Auler       const MCSymbol *Target;
3905a34c753fSRafael Auler       // In case we match if our first matcher, first instruction is the one to
3906a34c753fSRafael Auler       // patch
3907a34c753fSRafael Auler       MCInst *JTLoadInst = &Inst;
3908a34c753fSRafael Auler       // Try a standard indirect jump matcher, scale 8
3909a34c753fSRafael Auler       std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3910a34c753fSRafael Auler           BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3911a34c753fSRafael Auler                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3912a34c753fSRafael Auler                               /*Offset=*/BC.MIB->matchSymbol(Target));
3913a34c753fSRafael Auler       if (!IndJmpMatcher->match(
3914a34c753fSRafael Auler               *BC.MRI, *BC.MIB,
3915a34c753fSRafael Auler               MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
391640c2e0faSMaksim Panchenko           BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3917a34c753fSRafael Auler         MCPhysReg BaseReg2;
3918a34c753fSRafael Auler         uint64_t Offset;
3919a34c753fSRafael Auler         // Standard JT matching failed. Trying now:
3920a34c753fSRafael Auler         //     movq  "jt.2397/1"(,%rax,8), %rax
3921a34c753fSRafael Auler         //     jmpq  *%rax
3922a34c753fSRafael Auler         std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3923a34c753fSRafael Auler             BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3924a34c753fSRafael Auler                               BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3925a34c753fSRafael Auler                               /*Offset=*/BC.MIB->matchSymbol(Target));
3926a34c753fSRafael Auler         MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3927a34c753fSRafael Auler         std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3928a34c753fSRafael Auler             BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3929a34c753fSRafael Auler         if (!IndJmpMatcher2->match(
3930a34c753fSRafael Auler                 *BC.MRI, *BC.MIB,
3931a34c753fSRafael Auler                 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3932a34c753fSRafael Auler             BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3933a34c753fSRafael Auler           // JT matching failed. Trying now:
3934a34c753fSRafael Auler           // PIC-style matcher, scale 4
3935a34c753fSRafael Auler           //    addq    %rdx, %rsi
3936a34c753fSRafael Auler           //    addq    %rdx, %rdi
3937a34c753fSRafael Auler           //    leaq    DATAat0x402450(%rip), %r11
3938a34c753fSRafael Auler           //    movslq  (%r11,%rdx,4), %rcx
3939a34c753fSRafael Auler           //    addq    %r11, %rcx
3940a34c753fSRafael Auler           //    jmpq    *%rcx # JUMPTABLE @0x402450
3941a34c753fSRafael Auler           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3942a34c753fSRafael Auler               BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3943a34c753fSRafael Auler                   BC.MIB->matchReg(BaseReg1),
3944a34c753fSRafael Auler                   BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3945a34c753fSRafael Auler                                     BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3946a34c753fSRafael Auler                                     BC.MIB->matchImm(Offset))));
3947a34c753fSRafael Auler           std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3948a34c753fSRafael Auler               BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3949a34c753fSRafael Auler           MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3950a34c753fSRafael Auler           std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3951a34c753fSRafael Auler               BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3952a34c753fSRafael Auler                                                    BC.MIB->matchAnyOperand()));
3953a34c753fSRafael Auler           if (!PICIndJmpMatcher->match(
3954a34c753fSRafael Auler                   *BC.MRI, *BC.MIB,
3955a34c753fSRafael Auler                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3956a34c753fSRafael Auler               Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3957a34c753fSRafael Auler               !PICBaseAddrMatcher->match(
3958a34c753fSRafael Auler                   *BC.MRI, *BC.MIB,
3959a34c753fSRafael Auler                   MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3960a34c753fSRafael Auler             llvm_unreachable("Failed to extract jump table base");
3961a34c753fSRafael Auler             continue;
3962a34c753fSRafael Auler           }
3963a34c753fSRafael Auler           // Matched PIC, identify the instruction with the reference to the JT
3964a34c753fSRafael Auler           JTLoadInst = LEAMatcher->CurInst;
3965a34c753fSRafael Auler         } else {
3966a34c753fSRafael Auler           // Matched non-PIC
3967a34c753fSRafael Auler           JTLoadInst = LoadMatcher->CurInst;
3968a34c753fSRafael Auler         }
3969a34c753fSRafael Auler       }
3970a34c753fSRafael Auler 
3971a34c753fSRafael Auler       uint64_t NewJumpTableID = 0;
3972a34c753fSRafael Auler       const MCSymbol *NewJTLabel;
3973a34c753fSRafael Auler       std::tie(NewJumpTableID, NewJTLabel) =
3974a34c753fSRafael Auler           BC.duplicateJumpTable(*this, JT, Target);
3975a34c753fSRafael Auler       {
3976a34c753fSRafael Auler         auto L = BC.scopeLock();
3977a34c753fSRafael Auler         BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3978a34c753fSRafael Auler       }
3979a34c753fSRafael Auler       // We use a unique ID with the high bit set as address for this "injected"
3980a34c753fSRafael Auler       // jump table (not originally in the input binary).
3981a34c753fSRafael Auler       BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3982a34c753fSRafael Auler     }
3983a34c753fSRafael Auler   }
3984a34c753fSRafael Auler }
3985a34c753fSRafael Auler 
3986a34c753fSRafael Auler bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3987a34c753fSRafael Auler                                              BinaryBasicBlock *OldDest,
3988a34c753fSRafael Auler                                              BinaryBasicBlock *NewDest) {
3989a34c753fSRafael Auler   MCInst *Instr = BB->getLastNonPseudoInstr();
3990a34c753fSRafael Auler   if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3991a34c753fSRafael Auler     return false;
3992a34c753fSRafael Auler   uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3993a34c753fSRafael Auler   assert(JTAddress && "Invalid jump table address");
3994a34c753fSRafael Auler   JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3995a34c753fSRafael Auler   assert(JT && "No jump table structure for this indirect branch");
3996a34c753fSRafael Auler   bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3997a34c753fSRafael Auler                                         NewDest->getLabel());
3998a34c753fSRafael Auler   (void)Patched;
3999a34c753fSRafael Auler   assert(Patched && "Invalid entry to be replaced in jump table");
4000a34c753fSRafael Auler   return true;
4001a34c753fSRafael Auler }
4002a34c753fSRafael Auler 
4003a34c753fSRafael Auler BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
4004a34c753fSRafael Auler                                             BinaryBasicBlock *To) {
4005a34c753fSRafael Auler   // Create intermediate BB
4006a34c753fSRafael Auler   MCSymbol *Tmp;
4007a34c753fSRafael Auler   {
4008a34c753fSRafael Auler     auto L = BC.scopeLock();
4009a34c753fSRafael Auler     Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
4010a34c753fSRafael Auler   }
4011a34c753fSRafael Auler   // Link new BBs to the original input offset of the From BB, so we can map
4012a34c753fSRafael Auler   // samples recorded in new BBs back to the original BB seem in the input
4013a34c753fSRafael Auler   // binary (if using BAT)
40148228c703SMaksim Panchenko   std::unique_ptr<BinaryBasicBlock> NewBB = createBasicBlock(Tmp);
40158228c703SMaksim Panchenko   NewBB->setOffset(From->getInputOffset());
4016a34c753fSRafael Auler   BinaryBasicBlock *NewBBPtr = NewBB.get();
4017a34c753fSRafael Auler 
4018a34c753fSRafael Auler   // Update "From" BB
4019a34c753fSRafael Auler   auto I = From->succ_begin();
4020a34c753fSRafael Auler   auto BI = From->branch_info_begin();
4021a34c753fSRafael Auler   for (; I != From->succ_end(); ++I) {
4022a34c753fSRafael Auler     if (*I == To)
4023a34c753fSRafael Auler       break;
4024a34c753fSRafael Auler     ++BI;
4025a34c753fSRafael Auler   }
4026a34c753fSRafael Auler   assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
4027a34c753fSRafael Auler   uint64_t OrigCount = BI->Count;
4028a34c753fSRafael Auler   uint64_t OrigMispreds = BI->MispredictedCount;
4029a34c753fSRafael Auler   replaceJumpTableEntryIn(From, To, NewBBPtr);
4030a34c753fSRafael Auler   From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
4031a34c753fSRafael Auler 
4032a34c753fSRafael Auler   NewBB->addSuccessor(To, OrigCount, OrigMispreds);
4033a34c753fSRafael Auler   NewBB->setExecutionCount(OrigCount);
4034a34c753fSRafael Auler   NewBB->setIsCold(From->isCold());
4035a34c753fSRafael Auler 
4036a34c753fSRafael Auler   // Update CFI and BB layout with new intermediate BB
4037a34c753fSRafael Auler   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
4038a34c753fSRafael Auler   NewBBs.emplace_back(std::move(NewBB));
4039a34c753fSRafael Auler   insertBasicBlocks(From, std::move(NewBBs), true, true,
4040a34c753fSRafael Auler                     /*RecomputeLandingPads=*/false);
4041a34c753fSRafael Auler   return NewBBPtr;
4042a34c753fSRafael Auler }
4043a34c753fSRafael Auler 
4044a34c753fSRafael Auler void BinaryFunction::deleteConservativeEdges() {
4045a34c753fSRafael Auler   // Our goal is to aggressively remove edges from the CFG that we believe are
4046a34c753fSRafael Auler   // wrong. This is used for instrumentation, where it is safe to remove
4047a34c753fSRafael Auler   // fallthrough edges because we won't reorder blocks.
4048a34c753fSRafael Auler   for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
4049a34c753fSRafael Auler     BinaryBasicBlock *BB = *I;
4050a34c753fSRafael Auler     if (BB->succ_size() != 1 || BB->size() == 0)
4051a34c753fSRafael Auler       continue;
4052a34c753fSRafael Auler 
4053a34c753fSRafael Auler     auto NextBB = std::next(I);
4054a34c753fSRafael Auler     MCInst *Last = BB->getLastNonPseudoInstr();
4055a34c753fSRafael Auler     // Fallthrough is a landing pad? Delete this edge (as long as we don't
4056a34c753fSRafael Auler     // have a direct jump to it)
4057a34c753fSRafael Auler     if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
4058a34c753fSRafael Auler         *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
4059a34c753fSRafael Auler       BB->removeAllSuccessors();
4060a34c753fSRafael Auler       continue;
4061a34c753fSRafael Auler     }
4062a34c753fSRafael Auler 
4063a34c753fSRafael Auler     // Look for suspicious calls at the end of BB where gcc may optimize it and
4064a34c753fSRafael Auler     // remove the jump to the epilogue when it knows the call won't return.
4065a34c753fSRafael Auler     if (!Last || !BC.MIB->isCall(*Last))
4066a34c753fSRafael Auler       continue;
4067a34c753fSRafael Auler 
4068a34c753fSRafael Auler     const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
4069a34c753fSRafael Auler     if (!CalleeSymbol)
4070a34c753fSRafael Auler       continue;
4071a34c753fSRafael Auler 
4072a34c753fSRafael Auler     StringRef CalleeName = CalleeSymbol->getName();
407340c2e0faSMaksim Panchenko     if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
407440c2e0faSMaksim Panchenko         CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
4075a34c753fSRafael Auler         CalleeName != "abort@PLT")
4076a34c753fSRafael Auler       continue;
4077a34c753fSRafael Auler 
4078a34c753fSRafael Auler     BB->removeAllSuccessors();
4079a34c753fSRafael Auler   }
4080a34c753fSRafael Auler }
4081a34c753fSRafael Auler 
4082a34c753fSRafael Auler bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
4083a34c753fSRafael Auler                                           uint64_t SymbolSize) const {
4084a34c753fSRafael Auler   // If this symbol is in a different section from the one where the
4085a34c753fSRafael Auler   // function symbol is, don't consider it as valid.
4086a34c753fSRafael Auler   if (!getOriginSection()->containsAddress(
4087a34c753fSRafael Auler           cantFail(Symbol.getAddress(), "cannot get symbol address")))
4088a34c753fSRafael Auler     return false;
4089a34c753fSRafael Auler 
4090a34c753fSRafael Auler   // Some symbols are tolerated inside function bodies, others are not.
4091a34c753fSRafael Auler   // The real function boundaries may not be known at this point.
40928579db96SDenis Revunov   if (BC.isMarker(Symbol))
4093a34c753fSRafael Auler     return true;
4094a34c753fSRafael Auler 
4095a34c753fSRafael Auler   // It's okay to have a zero-sized symbol in the middle of non-zero-sized
4096a34c753fSRafael Auler   // function.
4097a34c753fSRafael Auler   if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
4098a34c753fSRafael Auler     return true;
4099a34c753fSRafael Auler 
4100a34c753fSRafael Auler   if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
4101a34c753fSRafael Auler     return false;
4102a34c753fSRafael Auler 
4103a34c753fSRafael Auler   if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
4104a34c753fSRafael Auler     return false;
4105a34c753fSRafael Auler 
4106a34c753fSRafael Auler   return true;
4107a34c753fSRafael Auler }
4108a34c753fSRafael Auler 
4109a34c753fSRafael Auler void BinaryFunction::adjustExecutionCount(uint64_t Count) {
4110a34c753fSRafael Auler   if (getKnownExecutionCount() == 0 || Count == 0)
4111a34c753fSRafael Auler     return;
4112a34c753fSRafael Auler 
4113a34c753fSRafael Auler   if (ExecutionCount < Count)
4114a34c753fSRafael Auler     Count = ExecutionCount;
4115a34c753fSRafael Auler 
4116a34c753fSRafael Auler   double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
4117a34c753fSRafael Auler   if (AdjustmentRatio < 0.0)
4118a34c753fSRafael Auler     AdjustmentRatio = 0.0;
4119a34c753fSRafael Auler 
4120d55dfeafSFabian Parzefall   for (BinaryBasicBlock &BB : blocks())
4121d55dfeafSFabian Parzefall     BB.adjustExecutionCount(AdjustmentRatio);
4122a34c753fSRafael Auler 
4123a34c753fSRafael Auler   ExecutionCount -= Count;
4124a34c753fSRafael Auler }
4125a34c753fSRafael Auler 
4126a34c753fSRafael Auler BinaryFunction::~BinaryFunction() {
41273652483cSRafael Auler   for (BinaryBasicBlock *BB : BasicBlocks)
4128a34c753fSRafael Auler     delete BB;
41293652483cSRafael Auler   for (BinaryBasicBlock *BB : DeletedBasicBlocks)
4130a34c753fSRafael Auler     delete BB;
4131a34c753fSRafael Auler }
4132a34c753fSRafael Auler 
4133d12e45adSAmir Ayupov void BinaryFunction::constructDomTree() {
4134d12e45adSAmir Ayupov   BDT.reset(new BinaryDominatorTree);
4135d12e45adSAmir Ayupov   BDT->recalculate(*this);
4136d12e45adSAmir Ayupov }
4137d12e45adSAmir Ayupov 
4138a34c753fSRafael Auler void BinaryFunction::calculateLoopInfo() {
4139d12e45adSAmir Ayupov   if (!hasDomTree())
4140d12e45adSAmir Ayupov     constructDomTree();
4141a34c753fSRafael Auler   // Discover loops.
4142a34c753fSRafael Auler   BLI.reset(new BinaryLoopInfo());
4143d12e45adSAmir Ayupov   BLI->analyze(getDomTree());
4144a34c753fSRafael Auler 
4145a34c753fSRafael Auler   // Traverse discovered loops and add depth and profile information.
4146a34c753fSRafael Auler   std::stack<BinaryLoop *> St;
4147a34c753fSRafael Auler   for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
4148a34c753fSRafael Auler     St.push(*I);
4149a34c753fSRafael Auler     ++BLI->OuterLoops;
4150a34c753fSRafael Auler   }
4151a34c753fSRafael Auler 
4152a34c753fSRafael Auler   while (!St.empty()) {
4153a34c753fSRafael Auler     BinaryLoop *L = St.top();
4154a34c753fSRafael Auler     St.pop();
4155a34c753fSRafael Auler     ++BLI->TotalLoops;
4156a34c753fSRafael Auler     BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
4157a34c753fSRafael Auler 
4158a34c753fSRafael Auler     // Add nested loops in the stack.
41593652483cSRafael Auler     for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4160a34c753fSRafael Auler       St.push(*I);
4161a34c753fSRafael Auler 
4162a34c753fSRafael Auler     // Skip if no valid profile is found.
4163a34c753fSRafael Auler     if (!hasValidProfile()) {
4164a34c753fSRafael Auler       L->EntryCount = COUNT_NO_PROFILE;
4165a34c753fSRafael Auler       L->ExitCount = COUNT_NO_PROFILE;
4166a34c753fSRafael Auler       L->TotalBackEdgeCount = COUNT_NO_PROFILE;
4167a34c753fSRafael Auler       continue;
4168a34c753fSRafael Auler     }
4169a34c753fSRafael Auler 
4170a34c753fSRafael Auler     // Compute back edge count.
4171a34c753fSRafael Auler     SmallVector<BinaryBasicBlock *, 1> Latches;
4172a34c753fSRafael Auler     L->getLoopLatches(Latches);
4173a34c753fSRafael Auler 
4174a34c753fSRafael Auler     for (BinaryBasicBlock *Latch : Latches) {
4175a34c753fSRafael Auler       auto BI = Latch->branch_info_begin();
4176a34c753fSRafael Auler       for (BinaryBasicBlock *Succ : Latch->successors()) {
4177a34c753fSRafael Auler         if (Succ == L->getHeader()) {
4178a34c753fSRafael Auler           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4179a34c753fSRafael Auler                  "profile data not found");
4180a34c753fSRafael Auler           L->TotalBackEdgeCount += BI->Count;
4181a34c753fSRafael Auler         }
4182a34c753fSRafael Auler         ++BI;
4183a34c753fSRafael Auler       }
4184a34c753fSRafael Auler     }
4185a34c753fSRafael Auler 
4186a34c753fSRafael Auler     // Compute entry count.
4187a34c753fSRafael Auler     L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4188a34c753fSRafael Auler 
4189a34c753fSRafael Auler     // Compute exit count.
4190a34c753fSRafael Auler     SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4191a34c753fSRafael Auler     L->getExitEdges(ExitEdges);
4192a34c753fSRafael Auler     for (BinaryLoop::Edge &Exit : ExitEdges) {
4193a34c753fSRafael Auler       const BinaryBasicBlock *Exiting = Exit.first;
4194a34c753fSRafael Auler       const BinaryBasicBlock *ExitTarget = Exit.second;
4195a34c753fSRafael Auler       auto BI = Exiting->branch_info_begin();
4196a34c753fSRafael Auler       for (BinaryBasicBlock *Succ : Exiting->successors()) {
4197a34c753fSRafael Auler         if (Succ == ExitTarget) {
4198a34c753fSRafael Auler           assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4199a34c753fSRafael Auler                  "profile data not found");
4200a34c753fSRafael Auler           L->ExitCount += BI->Count;
4201a34c753fSRafael Auler         }
4202a34c753fSRafael Auler         ++BI;
4203a34c753fSRafael Auler       }
4204a34c753fSRafael Auler     }
4205a34c753fSRafael Auler   }
4206a34c753fSRafael Auler }
4207a34c753fSRafael Auler 
4208475a93a0SJob Noorman void BinaryFunction::updateOutputValues(const BOLTLinker &Linker) {
4209a34c753fSRafael Auler   if (!isEmitted()) {
4210a34c753fSRafael Auler     assert(!isInjected() && "injected function should be emitted");
4211a34c753fSRafael Auler     setOutputAddress(getAddress());
4212a34c753fSRafael Auler     setOutputSize(getSize());
4213a34c753fSRafael Auler     return;
4214a34c753fSRafael Auler   }
4215a34c753fSRafael Auler 
4216475a93a0SJob Noorman   const auto SymbolInfo = Linker.lookupSymbolInfo(getSymbol()->getName());
4217475a93a0SJob Noorman   assert(SymbolInfo && "Cannot find function entry symbol");
4218475a93a0SJob Noorman   setOutputAddress(SymbolInfo->Address);
4219475a93a0SJob Noorman   setOutputSize(SymbolInfo->Size);
4220475a93a0SJob Noorman 
4221a34c753fSRafael Auler   if (BC.HasRelocations || isInjected()) {
4222a34c753fSRafael Auler     if (hasConstantIsland()) {
4223475a93a0SJob Noorman       const auto DataAddress =
4224475a93a0SJob Noorman           Linker.lookupSymbol(getFunctionConstantIslandLabel()->getName());
4225475a93a0SJob Noorman       assert(DataAddress && "Cannot find function CI symbol");
4226475a93a0SJob Noorman       setOutputDataAddress(*DataAddress);
42277117af52SVladislav Khmelevsky       for (auto It : Islands->Offsets) {
42287117af52SVladislav Khmelevsky         const uint64_t OldOffset = It.first;
42297117af52SVladislav Khmelevsky         BinaryData *BD = BC.getBinaryDataAtAddress(getAddress() + OldOffset);
42307117af52SVladislav Khmelevsky         if (!BD)
42317117af52SVladislav Khmelevsky           continue;
42327117af52SVladislav Khmelevsky 
42337117af52SVladislav Khmelevsky         MCSymbol *Symbol = It.second;
4234475a93a0SJob Noorman         const auto NewAddress = Linker.lookupSymbol(Symbol->getName());
4235475a93a0SJob Noorman         assert(NewAddress && "Cannot find CI symbol");
4236475a93a0SJob Noorman         auto &Section = *getCodeSection();
4237475a93a0SJob Noorman         const auto NewOffset = *NewAddress - Section.getOutputAddress();
4238475a93a0SJob Noorman         BD->setOutputLocation(Section, NewOffset);
42397117af52SVladislav Khmelevsky       }
4240a34c753fSRafael Auler     }
4241a34c753fSRafael Auler     if (isSplit()) {
42429b6e7861SFabian Parzefall       for (FunctionFragment &FF : getLayout().getSplitFragments()) {
42430f74d191SFabian Parzefall         ErrorOr<BinarySection &> ColdSection =
42440f74d191SFabian Parzefall             getCodeSection(FF.getFragmentNum());
42450f74d191SFabian Parzefall         // If fragment is empty, cold section might not exist
42460f74d191SFabian Parzefall         if (FF.empty() && ColdSection.getError())
42470f74d191SFabian Parzefall           continue;
42480f74d191SFabian Parzefall 
42490f74d191SFabian Parzefall         const MCSymbol *ColdStartSymbol = getSymbol(FF.getFragmentNum());
42500f74d191SFabian Parzefall         // If fragment is empty, symbol might have not been emitted
42510f74d191SFabian Parzefall         if (FF.empty() && (!ColdStartSymbol || !ColdStartSymbol->isDefined()) &&
42520f74d191SFabian Parzefall             !hasConstantIsland())
42530f74d191SFabian Parzefall           continue;
4254a34c753fSRafael Auler         assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4255a34c753fSRafael Auler                "split function should have defined cold symbol");
4256475a93a0SJob Noorman         const auto ColdStartSymbolInfo =
4257475a93a0SJob Noorman             Linker.lookupSymbolInfo(ColdStartSymbol->getName());
4258475a93a0SJob Noorman         assert(ColdStartSymbolInfo && "Cannot find cold start symbol");
4259475a93a0SJob Noorman         FF.setAddress(ColdStartSymbolInfo->Address);
4260475a93a0SJob Noorman         FF.setImageSize(ColdStartSymbolInfo->Size);
4261a34c753fSRafael Auler         if (hasConstantIsland()) {
4262475a93a0SJob Noorman           const auto DataAddress = Linker.lookupSymbol(
4263475a93a0SJob Noorman               getFunctionColdConstantIslandLabel()->getName());
4264475a93a0SJob Noorman           assert(DataAddress && "Cannot find cold CI symbol");
4265475a93a0SJob Noorman           setOutputColdDataAddress(*DataAddress);
4266a34c753fSRafael Auler         }
4267a34c753fSRafael Auler       }
42680f74d191SFabian Parzefall     }
4269a34c753fSRafael Auler   }
4270a34c753fSRafael Auler 
4271a34c753fSRafael Auler   // Update basic block output ranges for the debug info, if we have
4272a34c753fSRafael Auler   // secondary entry points in the symbol table to update or if writing BAT.
4273475a93a0SJob Noorman   if (!requiresAddressMap())
4274a34c753fSRafael Auler     return;
4275a34c753fSRafael Auler 
4276a34c753fSRafael Auler   // AArch64 may have functions that only contains a constant island (no code).
42778477bc67SFabian Parzefall   if (getLayout().block_empty())
4278a34c753fSRafael Auler     return;
4279a34c753fSRafael Auler 
428007f63b0aSFabian Parzefall   for (FunctionFragment &FF : getLayout().fragments()) {
42819b6e7861SFabian Parzefall     if (FF.empty())
42829b6e7861SFabian Parzefall       continue;
42839b6e7861SFabian Parzefall 
42840f74d191SFabian Parzefall     const uint64_t FragmentBaseAddress =
42850f74d191SFabian Parzefall         getCodeSection(isSimple() ? FF.getFragmentNum() : FragmentNum::main())
42860f74d191SFabian Parzefall             ->getOutputAddress();
42879b6e7861SFabian Parzefall 
42889b6e7861SFabian Parzefall     BinaryBasicBlock *PrevBB = nullptr;
42890f74d191SFabian Parzefall     for (BinaryBasicBlock *const BB : FF) {
4290a34c753fSRafael Auler       assert(BB->getLabel()->isDefined() && "symbol should be defined");
4291a34c753fSRafael Auler       if (!BC.HasRelocations) {
42929b6e7861SFabian Parzefall         if (BB->isSplit())
42939b6e7861SFabian Parzefall           assert(FragmentBaseAddress == FF.getAddress());
42949b6e7861SFabian Parzefall         else
42950f74d191SFabian Parzefall           assert(FragmentBaseAddress == getOutputAddress());
4296ff22d125SKazu Hirata         (void)FragmentBaseAddress;
4297a34c753fSRafael Auler       }
42989b6e7861SFabian Parzefall 
4299b59cf211SRafael Auler       // Injected functions likely will fail lookup, as they have no
4300b59cf211SRafael Auler       // input range. Just assign the BB the output address of the
4301b59cf211SRafael Auler       // function.
43028244ff67Smaksfb       auto MaybeBBAddress = BC.getIOAddressMap().lookup(BB->getLabel());
4303b59cf211SRafael Auler       const uint64_t BBAddress = MaybeBBAddress  ? *MaybeBBAddress
4304b59cf211SRafael Auler                                  : BB->isSplit() ? FF.getAddress()
4305b59cf211SRafael Auler                                                  : getOutputAddress();
4306a34c753fSRafael Auler       BB->setOutputStartAddress(BBAddress);
4307a34c753fSRafael Auler 
43088244ff67Smaksfb       if (PrevBB) {
43098244ff67Smaksfb         assert(PrevBB->getOutputAddressRange().first <= BBAddress &&
43108244ff67Smaksfb                "Bad output address for basic block.");
43118244ff67Smaksfb         assert((PrevBB->getOutputAddressRange().first != BBAddress ||
4312254ccb95SMaksim Panchenko                 !hasInstructions() || !PrevBB->getNumNonPseudos()) &&
43138244ff67Smaksfb                "Bad output address for basic block.");
43149b6e7861SFabian Parzefall         PrevBB->setOutputEndAddress(BBAddress);
43158244ff67Smaksfb       }
4316a34c753fSRafael Auler       PrevBB = BB;
4317a34c753fSRafael Auler     }
43189b6e7861SFabian Parzefall 
43196304e382SFabian Parzefall     PrevBB->setOutputEndAddress(PrevBB->isSplit()
43209b6e7861SFabian Parzefall                                     ? FF.getAddress() + FF.getImageSize()
43216304e382SFabian Parzefall                                     : getOutputAddress() + getOutputSize());
43227e254818SFabian Parzefall   }
4323f4834255SMaksim Panchenko 
4324f4834255SMaksim Panchenko   // Reset output addresses for deleted blocks.
4325f4834255SMaksim Panchenko   for (BinaryBasicBlock *BB : DeletedBasicBlocks) {
4326f4834255SMaksim Panchenko     BB->setOutputStartAddress(0);
4327f4834255SMaksim Panchenko     BB->setOutputEndAddress(0);
4328f4834255SMaksim Panchenko   }
43299b6e7861SFabian Parzefall }
4330a34c753fSRafael Auler 
4331a34c753fSRafael Auler DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4332a34c753fSRafael Auler   DebugAddressRangesVector OutputRanges;
4333a34c753fSRafael Auler 
4334a34c753fSRafael Auler   if (isFolded())
4335a34c753fSRafael Auler     return OutputRanges;
4336a34c753fSRafael Auler 
4337a34c753fSRafael Auler   if (IsFragment)
4338a34c753fSRafael Auler     return OutputRanges;
4339a34c753fSRafael Auler 
4340a34c753fSRafael Auler   OutputRanges.emplace_back(getOutputAddress(),
4341a34c753fSRafael Auler                             getOutputAddress() + getOutputSize());
4342a34c753fSRafael Auler   if (isSplit()) {
4343a34c753fSRafael Auler     assert(isEmitted() && "split function should be emitted");
43449b6e7861SFabian Parzefall     for (const FunctionFragment &FF : getLayout().getSplitFragments())
43459b6e7861SFabian Parzefall       OutputRanges.emplace_back(FF.getAddress(),
43469b6e7861SFabian Parzefall                                 FF.getAddress() + FF.getImageSize());
4347a34c753fSRafael Auler   }
4348a34c753fSRafael Auler 
4349a34c753fSRafael Auler   if (isSimple())
4350a34c753fSRafael Auler     return OutputRanges;
4351a34c753fSRafael Auler 
4352a34c753fSRafael Auler   for (BinaryFunction *Frag : Fragments) {
4353a34c753fSRafael Auler     assert(!Frag->isSimple() &&
4354a34c753fSRafael Auler            "fragment of non-simple function should also be non-simple");
4355a34c753fSRafael Auler     OutputRanges.emplace_back(Frag->getOutputAddress(),
4356a34c753fSRafael Auler                               Frag->getOutputAddress() + Frag->getOutputSize());
4357a34c753fSRafael Auler   }
4358a34c753fSRafael Auler 
4359a34c753fSRafael Auler   return OutputRanges;
4360a34c753fSRafael Auler }
4361a34c753fSRafael Auler 
4362a34c753fSRafael Auler uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4363a34c753fSRafael Auler   if (isFolded())
4364a34c753fSRafael Auler     return 0;
4365a34c753fSRafael Auler 
4366a34c753fSRafael Auler   // If the function hasn't changed return the same address.
4367a34c753fSRafael Auler   if (!isEmitted())
4368a34c753fSRafael Auler     return Address;
4369a34c753fSRafael Auler 
4370a34c753fSRafael Auler   if (Address < getAddress())
4371a34c753fSRafael Auler     return 0;
4372a34c753fSRafael Auler 
4373a34c753fSRafael Auler   // Check if the address is associated with an instruction that is tracked
4374a34c753fSRafael Auler   // by address translation.
437523c8d382SJob Noorman   if (auto OutputAddress = BC.getIOAddressMap().lookup(Address))
437623c8d382SJob Noorman     return *OutputAddress;
4377a34c753fSRafael Auler 
4378a34c753fSRafael Auler   // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4379a34c753fSRafael Auler   //        intact. Instead we can use pseudo instructions and/or annotations.
4380a34c753fSRafael Auler   const uint64_t Offset = Address - getAddress();
4381a34c753fSRafael Auler   const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4382a34c753fSRafael Auler   if (!BB) {
4383a34c753fSRafael Auler     // Special case for address immediately past the end of the function.
4384a34c753fSRafael Auler     if (Offset == getSize())
4385a34c753fSRafael Auler       return getOutputAddress() + getOutputSize();
4386a34c753fSRafael Auler 
4387a34c753fSRafael Auler     return 0;
4388a34c753fSRafael Auler   }
4389a34c753fSRafael Auler 
4390a34c753fSRafael Auler   return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4391a34c753fSRafael Auler                   BB->getOutputAddressRange().second);
4392a34c753fSRafael Auler }
4393a34c753fSRafael Auler 
43946e26246cSmaksfb DebugAddressRangesVector
43956e26246cSmaksfb BinaryFunction::translateInputToOutputRange(DebugAddressRange InRange) const {
43966e26246cSmaksfb   DebugAddressRangesVector OutRanges;
4397a34c753fSRafael Auler 
43986e26246cSmaksfb   // The function was removed from the output. Return an empty range.
4399a34c753fSRafael Auler   if (isFolded())
44006e26246cSmaksfb     return OutRanges;
4401a34c753fSRafael Auler 
44026e26246cSmaksfb   // If the function hasn't changed return the same range.
4403a34c753fSRafael Auler   if (!isEmitted()) {
44046e26246cSmaksfb     OutRanges.emplace_back(InRange);
44056e26246cSmaksfb     return OutRanges;
4406a34c753fSRafael Auler   }
4407a34c753fSRafael Auler 
44086e26246cSmaksfb   if (!containsAddress(InRange.LowPC))
44096e26246cSmaksfb     return OutRanges;
44106e26246cSmaksfb 
44116e26246cSmaksfb   // Special case of an empty range [X, X). Some tools expect X to be updated.
44126e26246cSmaksfb   if (InRange.LowPC == InRange.HighPC) {
44136e26246cSmaksfb     if (uint64_t NewPC = translateInputToOutputAddress(InRange.LowPC))
44146e26246cSmaksfb       OutRanges.push_back(DebugAddressRange{NewPC, NewPC});
44156e26246cSmaksfb     return OutRanges;
4416a34c753fSRafael Auler   }
44176e26246cSmaksfb 
44186e26246cSmaksfb   uint64_t InputOffset = InRange.LowPC - getAddress();
4419a34c753fSRafael Auler   const uint64_t InputEndOffset =
44206e26246cSmaksfb       std::min(InRange.HighPC - getAddress(), getSize());
4421a34c753fSRafael Auler 
4422d2c87699SAmir Ayupov   auto BBI = llvm::upper_bound(BasicBlockOffsets,
4423d2c87699SAmir Ayupov                                BasicBlockOffset(InputOffset, nullptr),
4424d2c87699SAmir Ayupov                                CompareBasicBlockOffsets());
44256e26246cSmaksfb   assert(BBI != BasicBlockOffsets.begin());
44266e26246cSmaksfb 
44276e26246cSmaksfb   // Iterate over blocks in the input order using BasicBlockOffsets.
44286e26246cSmaksfb   for (--BBI; InputOffset < InputEndOffset && BBI != BasicBlockOffsets.end();
44296e26246cSmaksfb        InputOffset = BBI->second->getEndOffset(), ++BBI) {
44306e26246cSmaksfb     const BinaryBasicBlock &BB = *BBI->second;
44316e26246cSmaksfb     if (InputOffset < BB.getOffset() || InputOffset >= BB.getEndOffset()) {
4432a34c753fSRafael Auler       LLVM_DEBUG(
4433a34c753fSRafael Auler           dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
44346e26246cSmaksfb                  << *this << " : [0x" << Twine::utohexstr(InRange.LowPC)
44356e26246cSmaksfb                  << ", 0x" << Twine::utohexstr(InRange.HighPC) << "]\n");
4436a34c753fSRafael Auler       break;
4437a34c753fSRafael Auler     }
4438a34c753fSRafael Auler 
44396e26246cSmaksfb     // Skip the block if it wasn't emitted.
44406e26246cSmaksfb     if (!BB.getOutputAddressRange().first)
44416e26246cSmaksfb       continue;
4442a34c753fSRafael Auler 
44436e26246cSmaksfb     // Find output address for an instruction with an offset greater or equal
44446e26246cSmaksfb     // to /p Offset. The output address should fall within the same basic
44456e26246cSmaksfb     // block boundaries.
44466e26246cSmaksfb     auto translateBlockOffset = [&](const uint64_t Offset) {
44476e26246cSmaksfb       const uint64_t OutAddress = BB.getOutputAddressRange().first + Offset;
444811f52f78SMaksim Panchenko       return std::min(OutAddress, BB.getOutputAddressRange().second);
44496e26246cSmaksfb     };
44506e26246cSmaksfb 
44516e26246cSmaksfb     uint64_t OutLowPC = BB.getOutputAddressRange().first;
44526e26246cSmaksfb     if (InputOffset > BB.getOffset())
44536e26246cSmaksfb       OutLowPC = translateBlockOffset(InputOffset - BB.getOffset());
44546e26246cSmaksfb 
44556e26246cSmaksfb     uint64_t OutHighPC = BB.getOutputAddressRange().second;
44566e26246cSmaksfb     if (InputEndOffset < BB.getEndOffset()) {
44576e26246cSmaksfb       assert(InputEndOffset >= BB.getOffset());
44586e26246cSmaksfb       OutHighPC = translateBlockOffset(InputEndOffset - BB.getOffset());
4459a34c753fSRafael Auler     }
4460a34c753fSRafael Auler 
44616e26246cSmaksfb     // Check if we can expand the last translated range.
44626e26246cSmaksfb     if (!OutRanges.empty() && OutRanges.back().HighPC == OutLowPC)
44636e26246cSmaksfb       OutRanges.back().HighPC = std::max(OutRanges.back().HighPC, OutHighPC);
44646e26246cSmaksfb     else
44656e26246cSmaksfb       OutRanges.emplace_back(OutLowPC, std::max(OutLowPC, OutHighPC));
4466a34c753fSRafael Auler   }
4467a34c753fSRafael Auler 
44686e26246cSmaksfb   LLVM_DEBUG({
44696e26246cSmaksfb     dbgs() << "BOLT-DEBUG: translated address range " << InRange << " -> ";
44706e26246cSmaksfb     for (const DebugAddressRange &R : OutRanges)
44716e26246cSmaksfb       dbgs() << R << ' ';
44726e26246cSmaksfb     dbgs() << '\n';
44736e26246cSmaksfb   });
4474a34c753fSRafael Auler 
44756e26246cSmaksfb   return OutRanges;
4476a34c753fSRafael Auler }
4477a34c753fSRafael Auler 
4478a34c753fSRafael Auler MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4479a34c753fSRafael Auler   if (CurrentState == State::Disassembled) {
4480a34c753fSRafael Auler     auto II = Instructions.find(Offset);
4481a34c753fSRafael Auler     return (II == Instructions.end()) ? nullptr : &II->second;
4482a34c753fSRafael Auler   } else if (CurrentState == State::CFG) {
4483a34c753fSRafael Auler     BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4484a34c753fSRafael Auler     if (!BB)
4485a34c753fSRafael Auler       return nullptr;
4486a34c753fSRafael Auler 
4487a34c753fSRafael Auler     for (MCInst &Inst : *BB) {
4488a34c753fSRafael Auler       constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4489a9cd49d5SAmir Ayupov       if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4490a34c753fSRafael Auler         return &Inst;
4491a34c753fSRafael Auler     }
4492a34c753fSRafael Auler 
4493ccb99dd1SMaksim Panchenko     if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
44942db9b6a9SMaksim Panchenko       if (std::optional<uint32_t> Size = BC.MIB->getSize(*LastInstr)) {
44952db9b6a9SMaksim Panchenko         if (BB->getEndOffset() - Offset == Size) {
4496ccb99dd1SMaksim Panchenko           return LastInstr;
4497ccb99dd1SMaksim Panchenko         }
44982db9b6a9SMaksim Panchenko       }
44992db9b6a9SMaksim Panchenko     }
4500ccb99dd1SMaksim Panchenko 
4501a34c753fSRafael Auler     return nullptr;
4502a34c753fSRafael Auler   } else {
4503a34c753fSRafael Auler     llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4504a34c753fSRafael Auler   }
4505a34c753fSRafael Auler }
4506a34c753fSRafael Auler 
4507d16b21b1SMaksim Panchenko MCInst *BinaryFunction::getInstructionContainingOffset(uint64_t Offset) {
4508d16b21b1SMaksim Panchenko   assert(CurrentState == State::Disassembled && "Wrong function state");
4509d16b21b1SMaksim Panchenko 
4510d16b21b1SMaksim Panchenko   if (Offset > Size)
4511d16b21b1SMaksim Panchenko     return nullptr;
4512d16b21b1SMaksim Panchenko 
4513d16b21b1SMaksim Panchenko   auto II = Instructions.upper_bound(Offset);
4514d16b21b1SMaksim Panchenko   assert(II != Instructions.begin() && "First instruction not at offset 0");
4515d16b21b1SMaksim Panchenko   --II;
4516d16b21b1SMaksim Panchenko   return &II->second;
4517d16b21b1SMaksim Panchenko }
4518d16b21b1SMaksim Panchenko 
4519a34c753fSRafael Auler void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4520798e92c6SAmir Ayupov   if (!opts::shouldPrint(*this))
4521798e92c6SAmir Ayupov     return;
4522798e92c6SAmir Ayupov 
4523a34c753fSRafael Auler   OS << "Loop Info for Function \"" << *this << "\"";
45243652483cSRafael Auler   if (hasValidProfile())
4525a34c753fSRafael Auler     OS << " (count: " << getExecutionCount() << ")";
4526a34c753fSRafael Auler   OS << "\n";
4527a34c753fSRafael Auler 
4528a34c753fSRafael Auler   std::stack<BinaryLoop *> St;
4529a0c7ca8aSKazu Hirata   for (BinaryLoop *L : *BLI)
4530a0c7ca8aSKazu Hirata     St.push(L);
4531a34c753fSRafael Auler   while (!St.empty()) {
4532a34c753fSRafael Auler     BinaryLoop *L = St.top();
4533a34c753fSRafael Auler     St.pop();
4534a34c753fSRafael Auler 
4535a0c7ca8aSKazu Hirata     for (BinaryLoop *Inner : *L)
4536a0c7ca8aSKazu Hirata       St.push(Inner);
4537a34c753fSRafael Auler 
4538a34c753fSRafael Auler     if (!hasValidProfile())
4539a34c753fSRafael Auler       continue;
4540a34c753fSRafael Auler 
454140c2e0faSMaksim Panchenko     OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
454240c2e0faSMaksim Panchenko        << " loop header: " << L->getHeader()->getName();
4543a34c753fSRafael Auler     OS << "\n";
4544a34c753fSRafael Auler     OS << "Loop basic blocks: ";
4545f7581a39SAmir Ayupov     ListSeparator LS;
4546f7581a39SAmir Ayupov     for (BinaryBasicBlock *BB : L->blocks())
4547f7581a39SAmir Ayupov       OS << LS << BB->getName();
4548a34c753fSRafael Auler     OS << "\n";
4549a34c753fSRafael Auler     if (hasValidProfile()) {
4550a34c753fSRafael Auler       OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4551a34c753fSRafael Auler       OS << "Loop entry count: " << L->EntryCount << "\n";
4552a34c753fSRafael Auler       OS << "Loop exit count: " << L->ExitCount << "\n";
4553a34c753fSRafael Auler       if (L->EntryCount > 0) {
4554a34c753fSRafael Auler         OS << "Average iters per entry: "
4555a34c753fSRafael Auler            << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4556a34c753fSRafael Auler            << "\n";
4557a34c753fSRafael Auler       }
4558a34c753fSRafael Auler     }
4559a34c753fSRafael Auler     OS << "----\n";
4560a34c753fSRafael Auler   }
4561a34c753fSRafael Auler 
4562a34c753fSRafael Auler   OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4563a34c753fSRafael Auler   OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4564a34c753fSRafael Auler   OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4565a34c753fSRafael Auler }
4566a34c753fSRafael Auler 
4567a34c753fSRafael Auler bool BinaryFunction::isAArch64Veneer() const {
4568d0e29e87SDenis Revunov   if (empty() || hasIslandsInfo())
4569a34c753fSRafael Auler     return false;
4570a34c753fSRafael Auler 
4571a34c753fSRafael Auler   BinaryBasicBlock &BB = **BasicBlocks.begin();
45723652483cSRafael Auler   for (MCInst &Inst : BB)
4573a34c753fSRafael Auler     if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4574a34c753fSRafael Auler       return false;
4575a34c753fSRafael Auler 
457635efe1d8SVladislav Khmelevsky   for (auto I = BasicBlocks.begin() + 1, E = BasicBlocks.end(); I != E; ++I) {
457735efe1d8SVladislav Khmelevsky     for (MCInst &Inst : **I)
457835efe1d8SVladislav Khmelevsky       if (!BC.MIB->isNoop(Inst))
457935efe1d8SVladislav Khmelevsky         return false;
458035efe1d8SVladislav Khmelevsky   }
458135efe1d8SVladislav Khmelevsky 
4582a34c753fSRafael Auler   return true;
4583a34c753fSRafael Auler }
4584a34c753fSRafael Auler 
4585edda8577SAmir Ayupov void BinaryFunction::addRelocation(uint64_t Address, MCSymbol *Symbol,
4586edda8577SAmir Ayupov                                    uint64_t RelType, uint64_t Addend,
4587edda8577SAmir Ayupov                                    uint64_t Value) {
4588edda8577SAmir Ayupov   assert(Address >= getAddress() && Address < getAddress() + getMaxSize() &&
4589edda8577SAmir Ayupov          "address is outside of the function");
4590edda8577SAmir Ayupov   uint64_t Offset = Address - getAddress();
4591edda8577SAmir Ayupov   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addRelocation in "
4592713b2853SAmir Ayupov                     << formatv("{0}@{1:x} against {2}\n", *this, Offset,
4593ff5e2babSJob Noorman                                (Symbol ? Symbol->getName() : "<undef>")));
4594edda8577SAmir Ayupov   bool IsCI = BC.isAArch64() && isInConstantIsland(Address);
4595edda8577SAmir Ayupov   std::map<uint64_t, Relocation> &Rels =
4596edda8577SAmir Ayupov       IsCI ? Islands->Relocations : Relocations;
4597edda8577SAmir Ayupov   if (BC.MIB->shouldRecordCodeRelocation(RelType))
4598edda8577SAmir Ayupov     Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
4599edda8577SAmir Ayupov }
4600edda8577SAmir Ayupov 
4601a34c753fSRafael Auler } // namespace bolt
4602a34c753fSRafael Auler } // namespace llvm
4603