[llvm-shlib] Fix the version naming style of libLLVM for Windows (#85710)
[llvm-project.git] / bolt / lib / Core / BinaryFunction.cpp
blob0ac47a53a446775e536ec6b502601169477b07a4
1 //===- bolt/Core/BinaryFunction.cpp - Low-level function ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the BinaryFunction class.
11 //===----------------------------------------------------------------------===//
13 #include "bolt/Core/BinaryFunction.h"
14 #include "bolt/Core/BinaryBasicBlock.h"
15 #include "bolt/Core/BinaryDomTree.h"
16 #include "bolt/Core/DynoStats.h"
17 #include "bolt/Core/HashUtilities.h"
18 #include "bolt/Core/MCPlusBuilder.h"
19 #include "bolt/Utils/NameResolver.h"
20 #include "bolt/Utils/NameShortener.h"
21 #include "bolt/Utils/Utils.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Demangle/Demangle.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/Regex.h"
41 #include "llvm/Support/Timer.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/xxhash.h"
44 #include <functional>
45 #include <limits>
46 #include <numeric>
47 #include <string>
49 #define DEBUG_TYPE "bolt"
51 using namespace llvm;
52 using namespace bolt;
54 namespace opts {
56 extern cl::OptionCategory BoltCategory;
57 extern cl::OptionCategory BoltOptCategory;
59 extern cl::opt<bool> EnableBAT;
60 extern cl::opt<bool> Instrument;
61 extern cl::opt<bool> StrictMode;
62 extern cl::opt<bool> UpdateDebugSections;
63 extern cl::opt<unsigned> Verbosity;
65 extern bool processAllFunctions();
67 cl::opt<bool> CheckEncoding(
68 "check-encoding",
69 cl::desc("perform verification of LLVM instruction encoding/decoding. "
70 "Every instruction in the input is decoded and re-encoded. "
71 "If the resulting bytes do not match the input, a warning message "
72 "is printed."),
73 cl::Hidden, cl::cat(BoltCategory));
75 static cl::opt<bool> DotToolTipCode(
76 "dot-tooltip-code",
77 cl::desc("add basic block instructions as tool tips on nodes"), cl::Hidden,
78 cl::cat(BoltCategory));
80 cl::opt<JumpTableSupportLevel>
81 JumpTables("jump-tables",
82 cl::desc("jump tables support (default=basic)"),
83 cl::init(JTS_BASIC),
84 cl::values(
85 clEnumValN(JTS_NONE, "none",
86 "do not optimize functions with jump tables"),
87 clEnumValN(JTS_BASIC, "basic",
88 "optimize functions with jump tables"),
89 clEnumValN(JTS_MOVE, "move",
90 "move jump tables to a separate section"),
91 clEnumValN(JTS_SPLIT, "split",
92 "split jump tables section into hot and cold based on "
93 "function execution frequency"),
94 clEnumValN(JTS_AGGRESSIVE, "aggressive",
95 "aggressively split jump tables section based on usage "
96 "of the tables")),
97 cl::ZeroOrMore,
98 cl::cat(BoltOptCategory));
100 static cl::opt<bool> NoScan(
101 "no-scan",
102 cl::desc(
103 "do not scan cold functions for external references (may result in "
104 "slower binary)"),
105 cl::Hidden, cl::cat(BoltOptCategory));
107 cl::opt<bool>
108 PreserveBlocksAlignment("preserve-blocks-alignment",
109 cl::desc("try to preserve basic block alignment"),
110 cl::cat(BoltOptCategory));
112 static cl::opt<bool> PrintOutputAddressRange(
113 "print-output-address-range",
114 cl::desc(
115 "print output address range for each basic block in the function when"
116 "BinaryFunction::print is called"),
117 cl::Hidden, cl::cat(BoltOptCategory));
119 cl::opt<bool>
120 PrintDynoStats("dyno-stats",
121 cl::desc("print execution info based on profile"),
122 cl::cat(BoltCategory));
124 static cl::opt<bool>
125 PrintDynoStatsOnly("print-dyno-stats-only",
126 cl::desc("while printing functions output dyno-stats and skip instructions"),
127 cl::init(false),
128 cl::Hidden,
129 cl::cat(BoltCategory));
131 static cl::list<std::string>
132 PrintOnly("print-only",
133 cl::CommaSeparated,
134 cl::desc("list of functions to print"),
135 cl::value_desc("func1,func2,func3,..."),
136 cl::Hidden,
137 cl::cat(BoltCategory));
139 cl::opt<bool>
140 TimeBuild("time-build",
141 cl::desc("print time spent constructing binary functions"),
142 cl::Hidden, cl::cat(BoltCategory));
144 cl::opt<bool>
145 TrapOnAVX512("trap-avx512",
146 cl::desc("in relocation mode trap upon entry to any function that uses "
147 "AVX-512 instructions"),
148 cl::init(false),
149 cl::ZeroOrMore,
150 cl::Hidden,
151 cl::cat(BoltCategory));
153 bool shouldPrint(const BinaryFunction &Function) {
154 if (Function.isIgnored())
155 return false;
157 if (PrintOnly.empty())
158 return true;
160 for (std::string &Name : opts::PrintOnly) {
161 if (Function.hasNameRegex(Name)) {
162 return true;
166 return false;
169 } // namespace opts
171 namespace llvm {
172 namespace bolt {
174 template <typename R> static bool emptyRange(const R &Range) {
175 return Range.begin() == Range.end();
178 /// Gets debug line information for the instruction located at the given
179 /// address in the original binary. The SMLoc's pointer is used
180 /// to point to this information, which is represented by a
181 /// DebugLineTableRowRef. The returned pointer is null if no debug line
182 /// information for this instruction was found.
183 static SMLoc findDebugLineInformationForInstructionAt(
184 uint64_t Address, DWARFUnit *Unit,
185 const DWARFDebugLine::LineTable *LineTable) {
186 // We use the pointer in SMLoc to store an instance of DebugLineTableRowRef,
187 // which occupies 64 bits. Thus, we can only proceed if the struct fits into
188 // the pointer itself.
189 static_assert(
190 sizeof(decltype(SMLoc().getPointer())) >= sizeof(DebugLineTableRowRef),
191 "Cannot fit instruction debug line information into SMLoc's pointer");
193 SMLoc NullResult = DebugLineTableRowRef::NULL_ROW.toSMLoc();
194 uint32_t RowIndex = LineTable->lookupAddress(
195 {Address, object::SectionedAddress::UndefSection});
196 if (RowIndex == LineTable->UnknownRowIndex)
197 return NullResult;
199 assert(RowIndex < LineTable->Rows.size() &&
200 "Line Table lookup returned invalid index.");
202 decltype(SMLoc().getPointer()) Ptr;
203 DebugLineTableRowRef *InstructionLocation =
204 reinterpret_cast<DebugLineTableRowRef *>(&Ptr);
206 InstructionLocation->DwCompileUnitIndex = Unit->getOffset();
207 InstructionLocation->RowIndex = RowIndex + 1;
209 return SMLoc::getFromPointer(Ptr);
212 static std::string buildSectionName(StringRef Prefix, StringRef Name,
213 const BinaryContext &BC) {
214 if (BC.isELF())
215 return (Prefix + Name).str();
216 static NameShortener NS;
217 return (Prefix + Twine(NS.getID(Name))).str();
220 static raw_ostream &operator<<(raw_ostream &OS,
221 const BinaryFunction::State State) {
222 switch (State) {
223 case BinaryFunction::State::Empty: OS << "empty"; break;
224 case BinaryFunction::State::Disassembled: OS << "disassembled"; break;
225 case BinaryFunction::State::CFG: OS << "CFG constructed"; break;
226 case BinaryFunction::State::CFG_Finalized: OS << "CFG finalized"; break;
227 case BinaryFunction::State::EmittedCFG: OS << "emitted with CFG"; break;
228 case BinaryFunction::State::Emitted: OS << "emitted"; break;
231 return OS;
234 std::string BinaryFunction::buildCodeSectionName(StringRef Name,
235 const BinaryContext &BC) {
236 return buildSectionName(BC.isELF() ? ".local.text." : ".l.text.", Name, BC);
239 std::string BinaryFunction::buildColdCodeSectionName(StringRef Name,
240 const BinaryContext &BC) {
241 return buildSectionName(BC.isELF() ? ".local.cold.text." : ".l.c.text.", Name,
242 BC);
245 uint64_t BinaryFunction::Count = 0;
247 std::optional<StringRef>
248 BinaryFunction::hasNameRegex(const StringRef Name) const {
249 const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
250 Regex MatchName(RegexName);
251 return forEachName(
252 [&MatchName](StringRef Name) { return MatchName.match(Name); });
255 std::optional<StringRef>
256 BinaryFunction::hasRestoredNameRegex(const StringRef Name) const {
257 const std::string RegexName = (Twine("^") + StringRef(Name) + "$").str();
258 Regex MatchName(RegexName);
259 return forEachName([&MatchName](StringRef Name) {
260 return MatchName.match(NameResolver::restore(Name));
264 std::string BinaryFunction::getDemangledName() const {
265 StringRef MangledName = NameResolver::restore(getOneName());
266 return demangle(MangledName.str());
269 BinaryBasicBlock *
270 BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset) {
271 if (Offset > Size)
272 return nullptr;
274 if (BasicBlockOffsets.empty())
275 return nullptr;
278 * This is commented out because it makes BOLT too slow.
279 * assert(std::is_sorted(BasicBlockOffsets.begin(),
280 * BasicBlockOffsets.end(),
281 * CompareBasicBlockOffsets())));
283 auto I =
284 llvm::upper_bound(BasicBlockOffsets, BasicBlockOffset(Offset, nullptr),
285 CompareBasicBlockOffsets());
286 assert(I != BasicBlockOffsets.begin() && "first basic block not at offset 0");
287 --I;
288 BinaryBasicBlock *BB = I->second;
289 return (Offset < BB->getOffset() + BB->getOriginalSize()) ? BB : nullptr;
292 void BinaryFunction::markUnreachableBlocks() {
293 std::stack<BinaryBasicBlock *> Stack;
295 for (BinaryBasicBlock &BB : blocks())
296 BB.markValid(false);
298 // Add all entries and landing pads as roots.
299 for (BinaryBasicBlock *BB : BasicBlocks) {
300 if (isEntryPoint(*BB) || BB->isLandingPad()) {
301 Stack.push(BB);
302 BB->markValid(true);
303 continue;
305 // FIXME:
306 // Also mark BBs with indirect jumps as reachable, since we do not
307 // support removing unused jump tables yet (GH-issue20).
308 for (const MCInst &Inst : *BB) {
309 if (BC.MIB->getJumpTable(Inst)) {
310 Stack.push(BB);
311 BB->markValid(true);
312 break;
317 // Determine reachable BBs from the entry point
318 while (!Stack.empty()) {
319 BinaryBasicBlock *BB = Stack.top();
320 Stack.pop();
321 for (BinaryBasicBlock *Succ : BB->successors()) {
322 if (Succ->isValid())
323 continue;
324 Succ->markValid(true);
325 Stack.push(Succ);
330 // Any unnecessary fallthrough jumps revealed after calling eraseInvalidBBs
331 // will be cleaned up by fixBranches().
332 std::pair<unsigned, uint64_t>
333 BinaryFunction::eraseInvalidBBs(const MCCodeEmitter *Emitter) {
334 DenseSet<const BinaryBasicBlock *> InvalidBBs;
335 unsigned Count = 0;
336 uint64_t Bytes = 0;
337 for (BinaryBasicBlock *const BB : BasicBlocks) {
338 if (!BB->isValid()) {
339 assert(!isEntryPoint(*BB) && "all entry blocks must be valid");
340 InvalidBBs.insert(BB);
341 ++Count;
342 Bytes += BC.computeCodeSize(BB->begin(), BB->end(), Emitter);
346 Layout.eraseBasicBlocks(InvalidBBs);
348 BasicBlockListType NewBasicBlocks;
349 for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
350 BinaryBasicBlock *BB = *I;
351 if (InvalidBBs.contains(BB)) {
352 // Make sure the block is removed from the list of predecessors.
353 BB->removeAllSuccessors();
354 DeletedBasicBlocks.push_back(BB);
355 } else {
356 NewBasicBlocks.push_back(BB);
359 BasicBlocks = std::move(NewBasicBlocks);
361 assert(BasicBlocks.size() == Layout.block_size());
363 // Update CFG state if needed
364 if (Count > 0)
365 recomputeLandingPads();
367 return std::make_pair(Count, Bytes);
370 bool BinaryFunction::isForwardCall(const MCSymbol *CalleeSymbol) const {
371 // This function should work properly before and after function reordering.
372 // In order to accomplish this, we use the function index (if it is valid).
373 // If the function indices are not valid, we fall back to the original
374 // addresses. This should be ok because the functions without valid indices
375 // should have been ordered with a stable sort.
376 const BinaryFunction *CalleeBF = BC.getFunctionForSymbol(CalleeSymbol);
377 if (CalleeBF) {
378 if (CalleeBF->isInjected())
379 return true;
381 if (hasValidIndex() && CalleeBF->hasValidIndex()) {
382 return getIndex() < CalleeBF->getIndex();
383 } else if (hasValidIndex() && !CalleeBF->hasValidIndex()) {
384 return true;
385 } else if (!hasValidIndex() && CalleeBF->hasValidIndex()) {
386 return false;
387 } else {
388 return getAddress() < CalleeBF->getAddress();
390 } else {
391 // Absolute symbol.
392 ErrorOr<uint64_t> CalleeAddressOrError = BC.getSymbolValue(*CalleeSymbol);
393 assert(CalleeAddressOrError && "unregistered symbol found");
394 return *CalleeAddressOrError > getAddress();
398 void BinaryFunction::dump() const {
399 // getDynoStats calls FunctionLayout::updateLayoutIndices and
400 // BasicBlock::analyzeBranch. The former cannot be const, but should be
401 // removed, the latter should be made const, but seems to require refactoring.
402 // Forcing all callers to have a non-const reference to BinaryFunction to call
403 // dump non-const however is not ideal either. Adding this const_cast is right
404 // now the best solution. It is safe, because BinaryFunction itself is not
405 // modified. Only BinaryBasicBlocks are actually modified (if it all) and we
406 // have mutable pointers to those regardless whether this function is
407 // const-qualified or not.
408 const_cast<BinaryFunction &>(*this).print(dbgs(), "");
411 void BinaryFunction::print(raw_ostream &OS, std::string Annotation) {
412 if (!opts::shouldPrint(*this))
413 return;
415 StringRef SectionName =
416 OriginSection ? OriginSection->getName() : "<no origin section>";
417 OS << "Binary Function \"" << *this << "\" " << Annotation << " {";
418 std::vector<StringRef> AllNames = getNames();
419 if (AllNames.size() > 1) {
420 OS << "\n All names : ";
421 const char *Sep = "";
422 for (const StringRef &Name : AllNames) {
423 OS << Sep << Name;
424 Sep = "\n ";
427 OS << "\n Number : " << FunctionNumber;
428 OS << "\n State : " << CurrentState;
429 OS << "\n Address : 0x" << Twine::utohexstr(Address);
430 OS << "\n Size : 0x" << Twine::utohexstr(Size);
431 OS << "\n MaxSize : 0x" << Twine::utohexstr(MaxSize);
432 OS << "\n Offset : 0x" << Twine::utohexstr(getFileOffset());
433 OS << "\n Section : " << SectionName;
434 OS << "\n Orc Section : " << getCodeSectionName();
435 OS << "\n LSDA : 0x" << Twine::utohexstr(getLSDAAddress());
436 OS << "\n IsSimple : " << IsSimple;
437 OS << "\n IsMultiEntry: " << isMultiEntry();
438 OS << "\n IsSplit : " << isSplit();
439 OS << "\n BB Count : " << size();
441 if (HasUnknownControlFlow)
442 OS << "\n Unknown CF : true";
443 if (getPersonalityFunction())
444 OS << "\n Personality : " << getPersonalityFunction()->getName();
445 if (IsFragment)
446 OS << "\n IsFragment : true";
447 if (isFolded())
448 OS << "\n FoldedInto : " << *getFoldedIntoFunction();
449 for (BinaryFunction *ParentFragment : ParentFragments)
450 OS << "\n Parent : " << *ParentFragment;
451 if (!Fragments.empty()) {
452 OS << "\n Fragments : ";
453 ListSeparator LS;
454 for (BinaryFunction *Frag : Fragments)
455 OS << LS << *Frag;
457 if (hasCFG())
458 OS << "\n Hash : " << Twine::utohexstr(computeHash());
459 if (isMultiEntry()) {
460 OS << "\n Secondary Entry Points : ";
461 ListSeparator LS;
462 for (const auto &KV : SecondaryEntryPoints)
463 OS << LS << KV.second->getName();
465 if (FrameInstructions.size())
466 OS << "\n CFI Instrs : " << FrameInstructions.size();
467 if (!Layout.block_empty()) {
468 OS << "\n BB Layout : ";
469 ListSeparator LS;
470 for (const BinaryBasicBlock *BB : Layout.blocks())
471 OS << LS << BB->getName();
473 if (getImageAddress())
474 OS << "\n Image : 0x" << Twine::utohexstr(getImageAddress());
475 if (ExecutionCount != COUNT_NO_PROFILE) {
476 OS << "\n Exec Count : " << ExecutionCount;
477 OS << "\n Branch Count: " << RawBranchCount;
478 OS << "\n Profile Acc : " << format("%.1f%%", ProfileMatchRatio * 100.0f);
481 if (opts::PrintDynoStats && !getLayout().block_empty()) {
482 OS << '\n';
483 DynoStats dynoStats = getDynoStats(*this);
484 OS << dynoStats;
487 OS << "\n}\n";
489 if (opts::PrintDynoStatsOnly || !BC.InstPrinter)
490 return;
492 // Offset of the instruction in function.
493 uint64_t Offset = 0;
495 if (BasicBlocks.empty() && !Instructions.empty()) {
496 // Print before CFG was built.
497 for (const std::pair<const uint32_t, MCInst> &II : Instructions) {
498 Offset = II.first;
500 // Print label if exists at this offset.
501 auto LI = Labels.find(Offset);
502 if (LI != Labels.end()) {
503 if (const MCSymbol *EntrySymbol =
504 getSecondaryEntryPointSymbol(LI->second))
505 OS << EntrySymbol->getName() << " (Entry Point):\n";
506 OS << LI->second->getName() << ":\n";
509 BC.printInstruction(OS, II.second, Offset, this);
513 StringRef SplitPointMsg = "";
514 for (const FunctionFragment &FF : Layout.fragments()) {
515 OS << SplitPointMsg;
516 SplitPointMsg = "------- HOT-COLD SPLIT POINT -------\n\n";
517 for (const BinaryBasicBlock *BB : FF) {
518 OS << BB->getName() << " (" << BB->size()
519 << " instructions, align : " << BB->getAlignment() << ")\n";
521 if (opts::PrintOutputAddressRange)
522 OS << formatv(" Output Address Range: [{0:x}, {1:x}) ({2} bytes)\n",
523 BB->getOutputAddressRange().first,
524 BB->getOutputAddressRange().second, BB->getOutputSize());
526 if (isEntryPoint(*BB)) {
527 if (MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB))
528 OS << " Secondary Entry Point: " << EntrySymbol->getName() << '\n';
529 else
530 OS << " Entry Point\n";
533 if (BB->isLandingPad())
534 OS << " Landing Pad\n";
536 uint64_t BBExecCount = BB->getExecutionCount();
537 if (hasValidProfile()) {
538 OS << " Exec Count : ";
539 if (BB->getExecutionCount() != BinaryBasicBlock::COUNT_NO_PROFILE)
540 OS << BBExecCount << '\n';
541 else
542 OS << "<unknown>\n";
544 if (BB->getCFIState() >= 0)
545 OS << " CFI State : " << BB->getCFIState() << '\n';
546 if (opts::EnableBAT) {
547 OS << " Input offset: 0x" << Twine::utohexstr(BB->getInputOffset())
548 << "\n";
550 if (!BB->pred_empty()) {
551 OS << " Predecessors: ";
552 ListSeparator LS;
553 for (BinaryBasicBlock *Pred : BB->predecessors())
554 OS << LS << Pred->getName();
555 OS << '\n';
557 if (!BB->throw_empty()) {
558 OS << " Throwers: ";
559 ListSeparator LS;
560 for (BinaryBasicBlock *Throw : BB->throwers())
561 OS << LS << Throw->getName();
562 OS << '\n';
565 Offset = alignTo(Offset, BB->getAlignment());
567 // Note: offsets are imprecise since this is happening prior to
568 // relaxation.
569 Offset = BC.printInstructions(OS, BB->begin(), BB->end(), Offset, this);
571 if (!BB->succ_empty()) {
572 OS << " Successors: ";
573 // For more than 2 successors, sort them based on frequency.
574 std::vector<uint64_t> Indices(BB->succ_size());
575 std::iota(Indices.begin(), Indices.end(), 0);
576 if (BB->succ_size() > 2 && BB->getKnownExecutionCount()) {
577 llvm::stable_sort(Indices, [&](const uint64_t A, const uint64_t B) {
578 return BB->BranchInfo[B] < BB->BranchInfo[A];
581 ListSeparator LS;
582 for (unsigned I = 0; I < Indices.size(); ++I) {
583 BinaryBasicBlock *Succ = BB->Successors[Indices[I]];
584 const BinaryBasicBlock::BinaryBranchInfo &BI =
585 BB->BranchInfo[Indices[I]];
586 OS << LS << Succ->getName();
587 if (ExecutionCount != COUNT_NO_PROFILE &&
588 BI.MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
589 OS << " (mispreds: " << BI.MispredictedCount
590 << ", count: " << BI.Count << ")";
591 } else if (ExecutionCount != COUNT_NO_PROFILE &&
592 BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
593 OS << " (inferred count: " << BI.Count << ")";
596 OS << '\n';
599 if (!BB->lp_empty()) {
600 OS << " Landing Pads: ";
601 ListSeparator LS;
602 for (BinaryBasicBlock *LP : BB->landing_pads()) {
603 OS << LS << LP->getName();
604 if (ExecutionCount != COUNT_NO_PROFILE) {
605 OS << " (count: " << LP->getExecutionCount() << ")";
608 OS << '\n';
611 // In CFG_Finalized state we can miscalculate CFI state at exit.
612 if (CurrentState == State::CFG) {
613 const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
614 if (CFIStateAtExit >= 0)
615 OS << " CFI State: " << CFIStateAtExit << '\n';
618 OS << '\n';
622 // Dump new exception ranges for the function.
623 if (!CallSites.empty()) {
624 OS << "EH table:\n";
625 for (const FunctionFragment &FF : getLayout().fragments()) {
626 for (const auto &FCSI : getCallSites(FF.getFragmentNum())) {
627 const CallSite &CSI = FCSI.second;
628 OS << " [" << *CSI.Start << ", " << *CSI.End << ") landing pad : ";
629 if (CSI.LP)
630 OS << *CSI.LP;
631 else
632 OS << "0";
633 OS << ", action : " << CSI.Action << '\n';
636 OS << '\n';
639 // Print all jump tables.
640 for (const std::pair<const uint64_t, JumpTable *> &JTI : JumpTables)
641 JTI.second->print(OS);
643 OS << "DWARF CFI Instructions:\n";
644 if (OffsetToCFI.size()) {
645 // Pre-buildCFG information
646 for (const std::pair<const uint32_t, uint32_t> &Elmt : OffsetToCFI) {
647 OS << format(" %08x:\t", Elmt.first);
648 assert(Elmt.second < FrameInstructions.size() && "Incorrect CFI offset");
649 BinaryContext::printCFI(OS, FrameInstructions[Elmt.second]);
650 OS << "\n";
652 } else {
653 // Post-buildCFG information
654 for (uint32_t I = 0, E = FrameInstructions.size(); I != E; ++I) {
655 const MCCFIInstruction &CFI = FrameInstructions[I];
656 OS << format(" %d:\t", I);
657 BinaryContext::printCFI(OS, CFI);
658 OS << "\n";
661 if (FrameInstructions.empty())
662 OS << " <empty>\n";
664 OS << "End of Function \"" << *this << "\"\n\n";
667 void BinaryFunction::printRelocations(raw_ostream &OS, uint64_t Offset,
668 uint64_t Size) const {
669 const char *Sep = " # Relocs: ";
671 auto RI = Relocations.lower_bound(Offset);
672 while (RI != Relocations.end() && RI->first < Offset + Size) {
673 OS << Sep << "(R: " << RI->second << ")";
674 Sep = ", ";
675 ++RI;
679 static std::string mutateDWARFExpressionTargetReg(const MCCFIInstruction &Instr,
680 MCPhysReg NewReg) {
681 StringRef ExprBytes = Instr.getValues();
682 assert(ExprBytes.size() > 1 && "DWARF expression CFI is too short");
683 uint8_t Opcode = ExprBytes[0];
684 assert((Opcode == dwarf::DW_CFA_expression ||
685 Opcode == dwarf::DW_CFA_val_expression) &&
686 "invalid DWARF expression CFI");
687 (void)Opcode;
688 const uint8_t *const Start =
689 reinterpret_cast<const uint8_t *>(ExprBytes.drop_front(1).data());
690 const uint8_t *const End =
691 reinterpret_cast<const uint8_t *>(Start + ExprBytes.size() - 1);
692 unsigned Size = 0;
693 decodeULEB128(Start, &Size, End);
694 assert(Size > 0 && "Invalid reg encoding for DWARF expression CFI");
695 SmallString<8> Tmp;
696 raw_svector_ostream OSE(Tmp);
697 encodeULEB128(NewReg, OSE);
698 return Twine(ExprBytes.slice(0, 1))
699 .concat(OSE.str())
700 .concat(ExprBytes.drop_front(1 + Size))
701 .str();
704 void BinaryFunction::mutateCFIRegisterFor(const MCInst &Instr,
705 MCPhysReg NewReg) {
706 const MCCFIInstruction *OldCFI = getCFIFor(Instr);
707 assert(OldCFI && "invalid CFI instr");
708 switch (OldCFI->getOperation()) {
709 default:
710 llvm_unreachable("Unexpected instruction");
711 case MCCFIInstruction::OpDefCfa:
712 setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, NewReg,
713 OldCFI->getOffset()));
714 break;
715 case MCCFIInstruction::OpDefCfaRegister:
716 setCFIFor(Instr, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg));
717 break;
718 case MCCFIInstruction::OpOffset:
719 setCFIFor(Instr, MCCFIInstruction::createOffset(nullptr, NewReg,
720 OldCFI->getOffset()));
721 break;
722 case MCCFIInstruction::OpRegister:
723 setCFIFor(Instr, MCCFIInstruction::createRegister(nullptr, NewReg,
724 OldCFI->getRegister2()));
725 break;
726 case MCCFIInstruction::OpSameValue:
727 setCFIFor(Instr, MCCFIInstruction::createSameValue(nullptr, NewReg));
728 break;
729 case MCCFIInstruction::OpEscape:
730 setCFIFor(Instr,
731 MCCFIInstruction::createEscape(
732 nullptr,
733 StringRef(mutateDWARFExpressionTargetReg(*OldCFI, NewReg))));
734 break;
735 case MCCFIInstruction::OpRestore:
736 setCFIFor(Instr, MCCFIInstruction::createRestore(nullptr, NewReg));
737 break;
738 case MCCFIInstruction::OpUndefined:
739 setCFIFor(Instr, MCCFIInstruction::createUndefined(nullptr, NewReg));
740 break;
744 const MCCFIInstruction *BinaryFunction::mutateCFIOffsetFor(const MCInst &Instr,
745 int64_t NewOffset) {
746 const MCCFIInstruction *OldCFI = getCFIFor(Instr);
747 assert(OldCFI && "invalid CFI instr");
748 switch (OldCFI->getOperation()) {
749 default:
750 llvm_unreachable("Unexpected instruction");
751 case MCCFIInstruction::OpDefCfaOffset:
752 setCFIFor(Instr, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset));
753 break;
754 case MCCFIInstruction::OpAdjustCfaOffset:
755 setCFIFor(Instr,
756 MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset));
757 break;
758 case MCCFIInstruction::OpDefCfa:
759 setCFIFor(Instr, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI->getRegister(),
760 NewOffset));
761 break;
762 case MCCFIInstruction::OpOffset:
763 setCFIFor(Instr, MCCFIInstruction::createOffset(
764 nullptr, OldCFI->getRegister(), NewOffset));
765 break;
767 return getCFIFor(Instr);
770 IndirectBranchType
771 BinaryFunction::processIndirectBranch(MCInst &Instruction, unsigned Size,
772 uint64_t Offset,
773 uint64_t &TargetAddress) {
774 const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
776 // The instruction referencing memory used by the branch instruction.
777 // It could be the branch instruction itself or one of the instructions
778 // setting the value of the register used by the branch.
779 MCInst *MemLocInstr;
781 // Address of the table referenced by MemLocInstr. Could be either an
782 // array of function pointers, or a jump table.
783 uint64_t ArrayStart = 0;
785 unsigned BaseRegNum, IndexRegNum;
786 int64_t DispValue;
787 const MCExpr *DispExpr;
789 // In AArch, identify the instruction adding the PC-relative offset to
790 // jump table entries to correctly decode it.
791 MCInst *PCRelBaseInstr;
792 uint64_t PCRelAddr = 0;
794 auto Begin = Instructions.begin();
795 if (BC.isAArch64()) {
796 PreserveNops = BC.HasRelocations;
797 // Start at the last label as an approximation of the current basic block.
798 // This is a heuristic, since the full set of labels have yet to be
799 // determined
800 for (const uint32_t Offset :
801 llvm::make_first_range(llvm::reverse(Labels))) {
802 auto II = Instructions.find(Offset);
803 if (II != Instructions.end()) {
804 Begin = II;
805 break;
810 IndirectBranchType BranchType = BC.MIB->analyzeIndirectBranch(
811 Instruction, Begin, Instructions.end(), PtrSize, MemLocInstr, BaseRegNum,
812 IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
814 if (BranchType == IndirectBranchType::UNKNOWN && !MemLocInstr)
815 return BranchType;
817 if (MemLocInstr != &Instruction)
818 IndexRegNum = BC.MIB->getNoRegister();
820 if (BC.isAArch64()) {
821 const MCSymbol *Sym = BC.MIB->getTargetSymbol(*PCRelBaseInstr, 1);
822 assert(Sym && "Symbol extraction failed");
823 ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*Sym);
824 if (SymValueOrError) {
825 PCRelAddr = *SymValueOrError;
826 } else {
827 for (std::pair<const uint32_t, MCSymbol *> &Elmt : Labels) {
828 if (Elmt.second == Sym) {
829 PCRelAddr = Elmt.first + getAddress();
830 break;
834 uint64_t InstrAddr = 0;
835 for (auto II = Instructions.rbegin(); II != Instructions.rend(); ++II) {
836 if (&II->second == PCRelBaseInstr) {
837 InstrAddr = II->first + getAddress();
838 break;
841 assert(InstrAddr != 0 && "instruction not found");
842 // We do this to avoid spurious references to code locations outside this
843 // function (for example, if the indirect jump lives in the last basic
844 // block of the function, it will create a reference to the next function).
845 // This replaces a symbol reference with an immediate.
846 BC.MIB->replaceMemOperandDisp(*PCRelBaseInstr,
847 MCOperand::createImm(PCRelAddr - InstrAddr));
848 // FIXME: Disable full jump table processing for AArch64 until we have a
849 // proper way of determining the jump table limits.
850 return IndirectBranchType::UNKNOWN;
853 // RIP-relative addressing should be converted to symbol form by now
854 // in processed instructions (but not in jump).
855 if (DispExpr) {
856 const MCSymbol *TargetSym;
857 uint64_t TargetOffset;
858 std::tie(TargetSym, TargetOffset) = BC.MIB->getTargetSymbolInfo(DispExpr);
859 ErrorOr<uint64_t> SymValueOrError = BC.getSymbolValue(*TargetSym);
860 assert(SymValueOrError && "global symbol needs a value");
861 ArrayStart = *SymValueOrError + TargetOffset;
862 BaseRegNum = BC.MIB->getNoRegister();
863 if (BC.isAArch64()) {
864 ArrayStart &= ~0xFFFULL;
865 ArrayStart += DispValue & 0xFFFULL;
867 } else {
868 ArrayStart = static_cast<uint64_t>(DispValue);
871 if (BaseRegNum == BC.MRI->getProgramCounter())
872 ArrayStart += getAddress() + Offset + Size;
874 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addressed memory is 0x"
875 << Twine::utohexstr(ArrayStart) << '\n');
877 ErrorOr<BinarySection &> Section = BC.getSectionForAddress(ArrayStart);
878 if (!Section) {
879 // No section - possibly an absolute address. Since we don't allow
880 // internal function addresses to escape the function scope - we
881 // consider it a tail call.
882 if (opts::Verbosity >= 1) {
883 errs() << "BOLT-WARNING: no section for address 0x"
884 << Twine::utohexstr(ArrayStart) << " referenced from function "
885 << *this << '\n';
887 return IndirectBranchType::POSSIBLE_TAIL_CALL;
889 if (Section->isVirtual()) {
890 // The contents are filled at runtime.
891 return IndirectBranchType::POSSIBLE_TAIL_CALL;
894 if (BranchType == IndirectBranchType::POSSIBLE_FIXED_BRANCH) {
895 ErrorOr<uint64_t> Value = BC.getPointerAtAddress(ArrayStart);
896 if (!Value)
897 return IndirectBranchType::UNKNOWN;
899 if (BC.getSectionForAddress(ArrayStart)->isWritable())
900 return IndirectBranchType::UNKNOWN;
902 outs() << "BOLT-INFO: fixed indirect branch detected in " << *this
903 << " at 0x" << Twine::utohexstr(getAddress() + Offset)
904 << " referencing data at 0x" << Twine::utohexstr(ArrayStart)
905 << " the destination value is 0x" << Twine::utohexstr(*Value)
906 << '\n';
908 TargetAddress = *Value;
909 return BranchType;
912 // Check if there's already a jump table registered at this address.
913 MemoryContentsType MemType;
914 if (JumpTable *JT = BC.getJumpTableContainingAddress(ArrayStart)) {
915 switch (JT->Type) {
916 case JumpTable::JTT_NORMAL:
917 MemType = MemoryContentsType::POSSIBLE_JUMP_TABLE;
918 break;
919 case JumpTable::JTT_PIC:
920 MemType = MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
921 break;
923 } else {
924 MemType = BC.analyzeMemoryAt(ArrayStart, *this);
927 // Check that jump table type in instruction pattern matches memory contents.
928 JumpTable::JumpTableType JTType;
929 if (BranchType == IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE) {
930 if (MemType != MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
931 return IndirectBranchType::UNKNOWN;
932 JTType = JumpTable::JTT_PIC;
933 } else {
934 if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE)
935 return IndirectBranchType::UNKNOWN;
937 if (MemType == MemoryContentsType::UNKNOWN)
938 return IndirectBranchType::POSSIBLE_TAIL_CALL;
940 BranchType = IndirectBranchType::POSSIBLE_JUMP_TABLE;
941 JTType = JumpTable::JTT_NORMAL;
944 // Convert the instruction into jump table branch.
945 const MCSymbol *JTLabel = BC.getOrCreateJumpTable(*this, ArrayStart, JTType);
946 BC.MIB->replaceMemOperandDisp(*MemLocInstr, JTLabel, BC.Ctx.get());
947 BC.MIB->setJumpTable(Instruction, ArrayStart, IndexRegNum);
949 JTSites.emplace_back(Offset, ArrayStart);
951 return BranchType;
954 MCSymbol *BinaryFunction::getOrCreateLocalLabel(uint64_t Address,
955 bool CreatePastEnd) {
956 const uint64_t Offset = Address - getAddress();
958 if ((Offset == getSize()) && CreatePastEnd)
959 return getFunctionEndLabel();
961 auto LI = Labels.find(Offset);
962 if (LI != Labels.end())
963 return LI->second;
965 // For AArch64, check if this address is part of a constant island.
966 if (BC.isAArch64()) {
967 if (MCSymbol *IslandSym = getOrCreateIslandAccess(Address))
968 return IslandSym;
971 MCSymbol *Label = BC.Ctx->createNamedTempSymbol();
972 Labels[Offset] = Label;
974 return Label;
977 ErrorOr<ArrayRef<uint8_t>> BinaryFunction::getData() const {
978 BinarySection &Section = *getOriginSection();
979 assert(Section.containsRange(getAddress(), getMaxSize()) &&
980 "wrong section for function");
982 if (!Section.isText() || Section.isVirtual() || !Section.getSize())
983 return std::make_error_code(std::errc::bad_address);
985 StringRef SectionContents = Section.getContents();
987 assert(SectionContents.size() == Section.getSize() &&
988 "section size mismatch");
990 // Function offset from the section start.
991 uint64_t Offset = getAddress() - Section.getAddress();
992 auto *Bytes = reinterpret_cast<const uint8_t *>(SectionContents.data());
993 return ArrayRef<uint8_t>(Bytes + Offset, getMaxSize());
996 size_t BinaryFunction::getSizeOfDataInCodeAt(uint64_t Offset) const {
997 if (!Islands)
998 return 0;
1000 if (!llvm::is_contained(Islands->DataOffsets, Offset))
1001 return 0;
1003 auto Iter = Islands->CodeOffsets.upper_bound(Offset);
1004 if (Iter != Islands->CodeOffsets.end())
1005 return *Iter - Offset;
1006 return getSize() - Offset;
1009 bool BinaryFunction::isZeroPaddingAt(uint64_t Offset) const {
1010 ArrayRef<uint8_t> FunctionData = *getData();
1011 uint64_t EndOfCode = getSize();
1012 if (Islands) {
1013 auto Iter = Islands->DataOffsets.upper_bound(Offset);
1014 if (Iter != Islands->DataOffsets.end())
1015 EndOfCode = *Iter;
1017 for (uint64_t I = Offset; I < EndOfCode; ++I)
1018 if (FunctionData[I] != 0)
1019 return false;
1021 return true;
1024 void BinaryFunction::handlePCRelOperand(MCInst &Instruction, uint64_t Address,
1025 uint64_t Size) {
1026 auto &MIB = BC.MIB;
1027 uint64_t TargetAddress = 0;
1028 if (!MIB->evaluateMemOperandTarget(Instruction, TargetAddress, Address,
1029 Size)) {
1030 errs() << "BOLT-ERROR: PC-relative operand can't be evaluated:\n";
1031 BC.InstPrinter->printInst(&Instruction, 0, "", *BC.STI, errs());
1032 errs() << '\n';
1033 Instruction.dump_pretty(errs(), BC.InstPrinter.get());
1034 errs() << '\n';
1035 errs() << "BOLT-ERROR: cannot handle PC-relative operand at 0x"
1036 << Twine::utohexstr(Address) << ". Skipping function " << *this
1037 << ".\n";
1038 if (BC.HasRelocations)
1039 exit(1);
1040 IsSimple = false;
1041 return;
1043 if (TargetAddress == 0 && opts::Verbosity >= 1) {
1044 outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this
1045 << '\n';
1048 const MCSymbol *TargetSymbol;
1049 uint64_t TargetOffset;
1050 std::tie(TargetSymbol, TargetOffset) =
1051 BC.handleAddressRef(TargetAddress, *this, /*IsPCRel*/ true);
1053 bool ReplaceSuccess = MIB->replaceMemOperandDisp(
1054 Instruction, TargetSymbol, static_cast<int64_t>(TargetOffset), &*BC.Ctx);
1055 (void)ReplaceSuccess;
1056 assert(ReplaceSuccess && "Failed to replace mem operand with symbol+off.");
1059 MCSymbol *BinaryFunction::handleExternalReference(MCInst &Instruction,
1060 uint64_t Size,
1061 uint64_t Offset,
1062 uint64_t TargetAddress,
1063 bool &IsCall) {
1064 auto &MIB = BC.MIB;
1066 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1067 BC.addInterproceduralReference(this, TargetAddress);
1068 if (opts::Verbosity >= 2 && !IsCall && Size == 2 && !BC.HasRelocations) {
1069 errs() << "BOLT-WARNING: relaxed tail call detected at 0x"
1070 << Twine::utohexstr(AbsoluteInstrAddr) << " in function " << *this
1071 << ". Code size will be increased.\n";
1074 assert(!MIB->isTailCall(Instruction) &&
1075 "synthetic tail call instruction found");
1077 // This is a call regardless of the opcode.
1078 // Assign proper opcode for tail calls, so that they could be
1079 // treated as calls.
1080 if (!IsCall) {
1081 if (!MIB->convertJmpToTailCall(Instruction)) {
1082 assert(MIB->isConditionalBranch(Instruction) &&
1083 "unknown tail call instruction");
1084 if (opts::Verbosity >= 2) {
1085 errs() << "BOLT-WARNING: conditional tail call detected in "
1086 << "function " << *this << " at 0x"
1087 << Twine::utohexstr(AbsoluteInstrAddr) << ".\n";
1090 IsCall = true;
1093 if (opts::Verbosity >= 2 && TargetAddress == 0) {
1094 // We actually see calls to address 0 in presence of weak
1095 // symbols originating from libraries. This code is never meant
1096 // to be executed.
1097 outs() << "BOLT-INFO: Function " << *this
1098 << " has a call to address zero.\n";
1101 return BC.getOrCreateGlobalSymbol(TargetAddress, "FUNCat");
1104 void BinaryFunction::handleIndirectBranch(MCInst &Instruction, uint64_t Size,
1105 uint64_t Offset) {
1106 auto &MIB = BC.MIB;
1107 uint64_t IndirectTarget = 0;
1108 IndirectBranchType Result =
1109 processIndirectBranch(Instruction, Size, Offset, IndirectTarget);
1110 switch (Result) {
1111 default:
1112 llvm_unreachable("unexpected result");
1113 case IndirectBranchType::POSSIBLE_TAIL_CALL: {
1114 bool Result = MIB->convertJmpToTailCall(Instruction);
1115 (void)Result;
1116 assert(Result);
1117 break;
1119 case IndirectBranchType::POSSIBLE_JUMP_TABLE:
1120 case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE:
1121 if (opts::JumpTables == JTS_NONE)
1122 IsSimple = false;
1123 break;
1124 case IndirectBranchType::POSSIBLE_FIXED_BRANCH: {
1125 if (containsAddress(IndirectTarget)) {
1126 const MCSymbol *TargetSymbol = getOrCreateLocalLabel(IndirectTarget);
1127 Instruction.clear();
1128 MIB->createUncondBranch(Instruction, TargetSymbol, BC.Ctx.get());
1129 TakenBranches.emplace_back(Offset, IndirectTarget - getAddress());
1130 addEntryPointAtOffset(IndirectTarget - getAddress());
1131 } else {
1132 MIB->convertJmpToTailCall(Instruction);
1133 BC.addInterproceduralReference(this, IndirectTarget);
1135 break;
1137 case IndirectBranchType::UNKNOWN:
1138 // Keep processing. We'll do more checks and fixes in
1139 // postProcessIndirectBranches().
1140 UnknownIndirectBranchOffsets.emplace(Offset);
1141 break;
1145 void BinaryFunction::handleAArch64IndirectCall(MCInst &Instruction,
1146 const uint64_t Offset) {
1147 auto &MIB = BC.MIB;
1148 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1149 MCInst *TargetHiBits, *TargetLowBits;
1150 uint64_t TargetAddress, Count;
1151 Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1152 AbsoluteInstrAddr, Instruction, TargetHiBits,
1153 TargetLowBits, TargetAddress);
1154 if (Count) {
1155 MIB->addAnnotation(Instruction, "AArch64Veneer", true);
1156 --Count;
1157 for (auto It = std::prev(Instructions.end()); Count != 0;
1158 It = std::prev(It), --Count) {
1159 MIB->addAnnotation(It->second, "AArch64Veneer", true);
1162 BC.addAdrpAddRelocAArch64(*this, *TargetLowBits, *TargetHiBits,
1163 TargetAddress);
1167 bool BinaryFunction::disassemble() {
1168 NamedRegionTimer T("disassemble", "Disassemble function", "buildfuncs",
1169 "Build Binary Functions", opts::TimeBuild);
1170 ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1171 assert(ErrorOrFunctionData && "function data is not available");
1172 ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1173 assert(FunctionData.size() == getMaxSize() &&
1174 "function size does not match raw data size");
1176 auto &Ctx = BC.Ctx;
1177 auto &MIB = BC.MIB;
1179 BC.SymbolicDisAsm->setSymbolizer(MIB->createTargetSymbolizer(*this));
1181 // Insert a label at the beginning of the function. This will be our first
1182 // basic block.
1183 Labels[0] = Ctx->createNamedTempSymbol("BB0");
1185 // Map offsets in the function to a label that should always point to the
1186 // corresponding instruction. This is used for labels that shouldn't point to
1187 // the start of a basic block but always to a specific instruction. This is
1188 // used, for example, on RISC-V where %pcrel_lo relocations point to the
1189 // corresponding %pcrel_hi.
1190 LabelsMapType InstructionLabels;
1192 uint64_t Size = 0; // instruction size
1193 for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1194 MCInst Instruction;
1195 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1197 // Check for data inside code and ignore it
1198 if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1199 Size = DataInCodeSize;
1200 continue;
1203 if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size,
1204 FunctionData.slice(Offset),
1205 AbsoluteInstrAddr, nulls())) {
1206 // Functions with "soft" boundaries, e.g. coming from assembly source,
1207 // can have 0-byte padding at the end.
1208 if (isZeroPaddingAt(Offset))
1209 break;
1211 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1212 << Twine::utohexstr(Offset) << " (address 0x"
1213 << Twine::utohexstr(AbsoluteInstrAddr) << ") in function " << *this
1214 << '\n';
1215 // Some AVX-512 instructions could not be disassembled at all.
1216 if (BC.HasRelocations && opts::TrapOnAVX512 && BC.isX86()) {
1217 setTrapOnEntry();
1218 BC.TrappedFunctions.push_back(this);
1219 } else {
1220 setIgnored();
1223 break;
1226 // Check integrity of LLVM assembler/disassembler.
1227 if (opts::CheckEncoding && !BC.MIB->isBranch(Instruction) &&
1228 !BC.MIB->isCall(Instruction) && !BC.MIB->isNoop(Instruction)) {
1229 if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) {
1230 errs() << "BOLT-WARNING: mismatching LLVM encoding detected in "
1231 << "function " << *this << " for instruction :\n";
1232 BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr);
1233 errs() << '\n';
1237 // Special handling for AVX-512 instructions.
1238 if (MIB->hasEVEXEncoding(Instruction)) {
1239 if (BC.HasRelocations && opts::TrapOnAVX512) {
1240 setTrapOnEntry();
1241 BC.TrappedFunctions.push_back(this);
1242 break;
1245 if (!BC.validateInstructionEncoding(FunctionData.slice(Offset, Size))) {
1246 errs() << "BOLT-WARNING: internal assembler/disassembler error "
1247 "detected for AVX512 instruction:\n";
1248 BC.printInstruction(errs(), Instruction, AbsoluteInstrAddr);
1249 errs() << " in function " << *this << '\n';
1250 setIgnored();
1251 break;
1255 if (MIB->isBranch(Instruction) || MIB->isCall(Instruction)) {
1256 uint64_t TargetAddress = 0;
1257 if (MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1258 TargetAddress)) {
1259 // Check if the target is within the same function. Otherwise it's
1260 // a call, possibly a tail call.
1262 // If the target *is* the function address it could be either a branch
1263 // or a recursive call.
1264 bool IsCall = MIB->isCall(Instruction);
1265 const bool IsCondBranch = MIB->isConditionalBranch(Instruction);
1266 MCSymbol *TargetSymbol = nullptr;
1268 if (BC.MIB->isUnsupportedBranch(Instruction)) {
1269 setIgnored();
1270 if (BinaryFunction *TargetFunc =
1271 BC.getBinaryFunctionContainingAddress(TargetAddress))
1272 TargetFunc->setIgnored();
1275 if (IsCall && containsAddress(TargetAddress)) {
1276 if (TargetAddress == getAddress()) {
1277 // Recursive call.
1278 TargetSymbol = getSymbol();
1279 } else {
1280 if (BC.isX86()) {
1281 // Dangerous old-style x86 PIC code. We may need to freeze this
1282 // function, so preserve the function as is for now.
1283 PreserveNops = true;
1284 } else {
1285 errs() << "BOLT-WARNING: internal call detected at 0x"
1286 << Twine::utohexstr(AbsoluteInstrAddr) << " in function "
1287 << *this << ". Skipping.\n";
1288 IsSimple = false;
1293 if (!TargetSymbol) {
1294 // Create either local label or external symbol.
1295 if (containsAddress(TargetAddress)) {
1296 TargetSymbol = getOrCreateLocalLabel(TargetAddress);
1297 } else {
1298 if (TargetAddress == getAddress() + getSize() &&
1299 TargetAddress < getAddress() + getMaxSize() &&
1300 !(BC.isAArch64() &&
1301 BC.handleAArch64Veneer(TargetAddress, /*MatchOnly*/ true))) {
1302 // Result of __builtin_unreachable().
1303 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump past end detected at 0x"
1304 << Twine::utohexstr(AbsoluteInstrAddr)
1305 << " in function " << *this
1306 << " : replacing with nop.\n");
1307 BC.MIB->createNoop(Instruction);
1308 if (IsCondBranch) {
1309 // Register branch offset for profile validation.
1310 IgnoredBranches.emplace_back(Offset, Offset + Size);
1312 goto add_instruction;
1314 // May update Instruction and IsCall
1315 TargetSymbol = handleExternalReference(Instruction, Size, Offset,
1316 TargetAddress, IsCall);
1320 if (!IsCall) {
1321 // Add taken branch info.
1322 TakenBranches.emplace_back(Offset, TargetAddress - getAddress());
1324 BC.MIB->replaceBranchTarget(Instruction, TargetSymbol, &*Ctx);
1326 // Mark CTC.
1327 if (IsCondBranch && IsCall)
1328 MIB->setConditionalTailCall(Instruction, TargetAddress);
1329 } else {
1330 // Could not evaluate branch. Should be an indirect call or an
1331 // indirect branch. Bail out on the latter case.
1332 if (MIB->isIndirectBranch(Instruction))
1333 handleIndirectBranch(Instruction, Size, Offset);
1334 // Indirect call. We only need to fix it if the operand is RIP-relative.
1335 if (IsSimple && MIB->hasPCRelOperand(Instruction))
1336 handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1338 if (BC.isAArch64())
1339 handleAArch64IndirectCall(Instruction, Offset);
1341 } else if (BC.isAArch64() || BC.isRISCV()) {
1342 // Check if there's a relocation associated with this instruction.
1343 bool UsedReloc = false;
1344 for (auto Itr = Relocations.lower_bound(Offset),
1345 ItrE = Relocations.lower_bound(Offset + Size);
1346 Itr != ItrE; ++Itr) {
1347 const Relocation &Relocation = Itr->second;
1348 MCSymbol *Symbol = Relocation.Symbol;
1350 if (Relocation::isInstructionReference(Relocation.Type)) {
1351 uint64_t RefOffset = Relocation.Value - getAddress();
1352 LabelsMapType::iterator LI = InstructionLabels.find(RefOffset);
1354 if (LI == InstructionLabels.end()) {
1355 Symbol = BC.Ctx->createNamedTempSymbol();
1356 InstructionLabels.emplace(RefOffset, Symbol);
1357 } else {
1358 Symbol = LI->second;
1362 int64_t Value = Relocation.Value;
1363 const bool Result = BC.MIB->replaceImmWithSymbolRef(
1364 Instruction, Symbol, Relocation.Addend, Ctx.get(), Value,
1365 Relocation.Type);
1366 (void)Result;
1367 assert(Result && "cannot replace immediate with relocation");
1369 // For aarch64, if we replaced an immediate with a symbol from a
1370 // relocation, we mark it so we do not try to further process a
1371 // pc-relative operand. All we need is the symbol.
1372 UsedReloc = true;
1375 if (!BC.isRISCV() && MIB->hasPCRelOperand(Instruction) && !UsedReloc)
1376 handlePCRelOperand(Instruction, AbsoluteInstrAddr, Size);
1379 add_instruction:
1380 if (getDWARFLineTable()) {
1381 Instruction.setLoc(findDebugLineInformationForInstructionAt(
1382 AbsoluteInstrAddr, getDWARFUnit(), getDWARFLineTable()));
1385 // Record offset of the instruction for profile matching.
1386 if (BC.keepOffsetForInstruction(Instruction))
1387 MIB->setOffset(Instruction, static_cast<uint32_t>(Offset));
1389 if (BC.isX86() && BC.MIB->isNoop(Instruction)) {
1390 // NOTE: disassembly loses the correct size information for noops on x86.
1391 // E.g. nopw 0x0(%rax,%rax,1) is 9 bytes, but re-encoded it's only
1392 // 5 bytes. Preserve the size info using annotations.
1393 MIB->setSize(Instruction, Size);
1396 addInstruction(Offset, std::move(Instruction));
1399 for (auto [Offset, Label] : InstructionLabels) {
1400 InstrMapType::iterator II = Instructions.find(Offset);
1401 assert(II != Instructions.end() && "reference to non-existing instruction");
1403 BC.MIB->setLabel(II->second, Label);
1406 // Reset symbolizer for the disassembler.
1407 BC.SymbolicDisAsm->setSymbolizer(nullptr);
1409 if (uint64_t Offset = getFirstInstructionOffset())
1410 Labels[Offset] = BC.Ctx->createNamedTempSymbol();
1412 clearList(Relocations);
1414 if (!IsSimple) {
1415 clearList(Instructions);
1416 return false;
1419 updateState(State::Disassembled);
1421 return true;
1424 bool BinaryFunction::scanExternalRefs() {
1425 bool Success = true;
1426 bool DisassemblyFailed = false;
1428 // Ignore pseudo functions.
1429 if (isPseudo())
1430 return Success;
1432 if (opts::NoScan) {
1433 clearList(Relocations);
1434 clearList(ExternallyReferencedOffsets);
1436 return false;
1439 // List of external references for this function.
1440 std::vector<Relocation> FunctionRelocations;
1442 static BinaryContext::IndependentCodeEmitter Emitter =
1443 BC.createIndependentMCCodeEmitter();
1445 ErrorOr<ArrayRef<uint8_t>> ErrorOrFunctionData = getData();
1446 assert(ErrorOrFunctionData && "function data is not available");
1447 ArrayRef<uint8_t> FunctionData = *ErrorOrFunctionData;
1448 assert(FunctionData.size() == getMaxSize() &&
1449 "function size does not match raw data size");
1451 BC.SymbolicDisAsm->setSymbolizer(
1452 BC.MIB->createTargetSymbolizer(*this, /*CreateSymbols*/ false));
1454 // Disassemble contents of the function. Detect code entry points and create
1455 // relocations for references to code that will be moved.
1456 uint64_t Size = 0; // instruction size
1457 for (uint64_t Offset = 0; Offset < getSize(); Offset += Size) {
1458 // Check for data inside code and ignore it
1459 if (const size_t DataInCodeSize = getSizeOfDataInCodeAt(Offset)) {
1460 Size = DataInCodeSize;
1461 continue;
1464 const uint64_t AbsoluteInstrAddr = getAddress() + Offset;
1465 MCInst Instruction;
1466 if (!BC.SymbolicDisAsm->getInstruction(Instruction, Size,
1467 FunctionData.slice(Offset),
1468 AbsoluteInstrAddr, nulls())) {
1469 if (opts::Verbosity >= 1 && !isZeroPaddingAt(Offset)) {
1470 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1471 << Twine::utohexstr(Offset) << " (address 0x"
1472 << Twine::utohexstr(AbsoluteInstrAddr) << ") in function "
1473 << *this << '\n';
1475 Success = false;
1476 DisassemblyFailed = true;
1477 break;
1480 // Return true if we can skip handling the Target function reference.
1481 auto ignoreFunctionRef = [&](const BinaryFunction &Target) {
1482 if (&Target == this)
1483 return true;
1485 // Note that later we may decide not to emit Target function. In that
1486 // case, we conservatively create references that will be ignored or
1487 // resolved to the same function.
1488 if (!BC.shouldEmit(Target))
1489 return true;
1491 return false;
1494 // Return true if we can ignore reference to the symbol.
1495 auto ignoreReference = [&](const MCSymbol *TargetSymbol) {
1496 if (!TargetSymbol)
1497 return true;
1499 if (BC.forceSymbolRelocations(TargetSymbol->getName()))
1500 return false;
1502 BinaryFunction *TargetFunction = BC.getFunctionForSymbol(TargetSymbol);
1503 if (!TargetFunction)
1504 return true;
1506 return ignoreFunctionRef(*TargetFunction);
1509 // Handle calls and branches separately as symbolization doesn't work for
1510 // them yet.
1511 MCSymbol *BranchTargetSymbol = nullptr;
1512 if (BC.MIB->isCall(Instruction) || BC.MIB->isBranch(Instruction)) {
1513 uint64_t TargetAddress = 0;
1514 BC.MIB->evaluateBranch(Instruction, AbsoluteInstrAddr, Size,
1515 TargetAddress);
1517 // Create an entry point at reference address if needed.
1518 BinaryFunction *TargetFunction =
1519 BC.getBinaryFunctionContainingAddress(TargetAddress);
1521 if (!TargetFunction || ignoreFunctionRef(*TargetFunction))
1522 continue;
1524 const uint64_t FunctionOffset =
1525 TargetAddress - TargetFunction->getAddress();
1526 BranchTargetSymbol =
1527 FunctionOffset ? TargetFunction->addEntryPointAtOffset(FunctionOffset)
1528 : TargetFunction->getSymbol();
1531 // Can't find more references. Not creating relocations since we are not
1532 // moving code.
1533 if (!BC.HasRelocations)
1534 continue;
1536 if (BranchTargetSymbol) {
1537 BC.MIB->replaceBranchTarget(Instruction, BranchTargetSymbol,
1538 Emitter.LocalCtx.get());
1539 } else if (!llvm::any_of(Instruction,
1540 [](const MCOperand &Op) { return Op.isExpr(); })) {
1541 // Skip assembly if the instruction may not have any symbolic operands.
1542 continue;
1545 // Emit the instruction using temp emitter and generate relocations.
1546 SmallString<256> Code;
1547 SmallVector<MCFixup, 4> Fixups;
1548 Emitter.MCE->encodeInstruction(Instruction, Code, Fixups, *BC.STI);
1550 // Create relocation for every fixup.
1551 for (const MCFixup &Fixup : Fixups) {
1552 std::optional<Relocation> Rel = BC.MIB->createRelocation(Fixup, *BC.MAB);
1553 if (!Rel) {
1554 Success = false;
1555 continue;
1558 if (ignoreReference(Rel->Symbol))
1559 continue;
1561 if (Relocation::getSizeForType(Rel->Type) < 4) {
1562 // If the instruction uses a short form, then we might not be able
1563 // to handle the rewrite without relaxation, and hence cannot reliably
1564 // create an external reference relocation.
1565 Success = false;
1566 continue;
1568 Rel->Offset += getAddress() - getOriginSection()->getAddress() + Offset;
1569 FunctionRelocations.push_back(*Rel);
1572 if (!Success)
1573 break;
1576 // Reset symbolizer for the disassembler.
1577 BC.SymbolicDisAsm->setSymbolizer(nullptr);
1579 // Add relocations unless disassembly failed for this function.
1580 if (!DisassemblyFailed)
1581 for (Relocation &Rel : FunctionRelocations)
1582 getOriginSection()->addPendingRelocation(Rel);
1584 // Inform BinaryContext that this function symbols will not be defined and
1585 // relocations should not be created against them.
1586 if (BC.HasRelocations) {
1587 for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
1588 BC.UndefinedSymbols.insert(LI.second);
1589 for (MCSymbol *const EndLabel : FunctionEndLabels)
1590 if (EndLabel)
1591 BC.UndefinedSymbols.insert(EndLabel);
1594 clearList(Relocations);
1595 clearList(ExternallyReferencedOffsets);
1597 if (Success && BC.HasRelocations)
1598 HasExternalRefRelocations = true;
1600 if (opts::Verbosity >= 1 && !Success)
1601 outs() << "BOLT-INFO: failed to scan refs for " << *this << '\n';
1603 return Success;
1606 void BinaryFunction::postProcessEntryPoints() {
1607 if (!isSimple())
1608 return;
1610 for (auto &KV : Labels) {
1611 MCSymbol *Label = KV.second;
1612 if (!getSecondaryEntryPointSymbol(Label))
1613 continue;
1615 // In non-relocation mode there's potentially an external undetectable
1616 // reference to the entry point and hence we cannot move this entry
1617 // point. Optimizing without moving could be difficult.
1618 if (!BC.HasRelocations)
1619 setSimple(false);
1621 const uint32_t Offset = KV.first;
1623 // If we are at Offset 0 and there is no instruction associated with it,
1624 // this means this is an empty function. Just ignore. If we find an
1625 // instruction at this offset, this entry point is valid.
1626 if (!Offset || getInstructionAtOffset(Offset))
1627 continue;
1629 // On AArch64 there are legitimate reasons to have references past the
1630 // end of the function, e.g. jump tables.
1631 if (BC.isAArch64() && Offset == getSize())
1632 continue;
1634 errs() << "BOLT-WARNING: reference in the middle of instruction "
1635 "detected in function "
1636 << *this << " at offset 0x" << Twine::utohexstr(Offset) << '\n';
1637 if (BC.HasRelocations)
1638 setIgnored();
1639 setSimple(false);
1640 return;
1644 void BinaryFunction::postProcessJumpTables() {
1645 // Create labels for all entries.
1646 for (auto &JTI : JumpTables) {
1647 JumpTable &JT = *JTI.second;
1648 if (JT.Type == JumpTable::JTT_PIC && opts::JumpTables == JTS_BASIC) {
1649 opts::JumpTables = JTS_MOVE;
1650 outs() << "BOLT-INFO: forcing -jump-tables=move as PIC jump table was "
1651 "detected in function "
1652 << *this << '\n';
1654 const uint64_t BDSize =
1655 BC.getBinaryDataAtAddress(JT.getAddress())->getSize();
1656 if (!BDSize) {
1657 BC.setBinaryDataSize(JT.getAddress(), JT.getSize());
1658 } else {
1659 assert(BDSize >= JT.getSize() &&
1660 "jump table cannot be larger than the containing object");
1662 if (!JT.Entries.empty())
1663 continue;
1665 bool HasOneParent = (JT.Parents.size() == 1);
1666 for (uint64_t EntryAddress : JT.EntriesAsAddress) {
1667 // builtin_unreachable does not belong to any function
1668 // Need to handle separately
1669 bool IsBuiltinUnreachable =
1670 llvm::any_of(JT.Parents, [&](const BinaryFunction *Parent) {
1671 return EntryAddress == Parent->getAddress() + Parent->getSize();
1673 if (IsBuiltinUnreachable) {
1674 MCSymbol *Label = getOrCreateLocalLabel(EntryAddress, true);
1675 JT.Entries.push_back(Label);
1676 continue;
1678 // Create a local label for targets that cannot be reached by other
1679 // fragments. Otherwise, create a secondary entry point in the target
1680 // function.
1681 BinaryFunction *TargetBF =
1682 BC.getBinaryFunctionContainingAddress(EntryAddress);
1683 MCSymbol *Label;
1684 if (HasOneParent && TargetBF == this) {
1685 Label = getOrCreateLocalLabel(EntryAddress, true);
1686 } else {
1687 const uint64_t Offset = EntryAddress - TargetBF->getAddress();
1688 Label = Offset ? TargetBF->addEntryPointAtOffset(Offset)
1689 : TargetBF->getSymbol();
1691 JT.Entries.push_back(Label);
1695 // Add TakenBranches from JumpTables.
1697 // We want to do it after initial processing since we don't know jump tables'
1698 // boundaries until we process them all.
1699 for (auto &JTSite : JTSites) {
1700 const uint64_t JTSiteOffset = JTSite.first;
1701 const uint64_t JTAddress = JTSite.second;
1702 const JumpTable *JT = getJumpTableContainingAddress(JTAddress);
1703 assert(JT && "cannot find jump table for address");
1705 uint64_t EntryOffset = JTAddress - JT->getAddress();
1706 while (EntryOffset < JT->getSize()) {
1707 uint64_t EntryAddress = JT->EntriesAsAddress[EntryOffset / JT->EntrySize];
1708 uint64_t TargetOffset = EntryAddress - getAddress();
1709 if (TargetOffset < getSize()) {
1710 TakenBranches.emplace_back(JTSiteOffset, TargetOffset);
1712 if (opts::StrictMode)
1713 registerReferencedOffset(TargetOffset);
1716 EntryOffset += JT->EntrySize;
1718 // A label at the next entry means the end of this jump table.
1719 if (JT->Labels.count(EntryOffset))
1720 break;
1723 clearList(JTSites);
1725 // Conservatively populate all possible destinations for unknown indirect
1726 // branches.
1727 if (opts::StrictMode && hasInternalReference()) {
1728 for (uint64_t Offset : UnknownIndirectBranchOffsets) {
1729 for (uint64_t PossibleDestination : ExternallyReferencedOffsets) {
1730 // Ignore __builtin_unreachable().
1731 if (PossibleDestination == getSize())
1732 continue;
1733 TakenBranches.emplace_back(Offset, PossibleDestination);
1738 // Remove duplicates branches. We can get a bunch of them from jump tables.
1739 // Without doing jump table value profiling we don't have use for extra
1740 // (duplicate) branches.
1741 llvm::sort(TakenBranches);
1742 auto NewEnd = std::unique(TakenBranches.begin(), TakenBranches.end());
1743 TakenBranches.erase(NewEnd, TakenBranches.end());
1746 bool BinaryFunction::validateExternallyReferencedOffsets() {
1747 SmallPtrSet<MCSymbol *, 4> JTTargets;
1748 for (const JumpTable *JT : llvm::make_second_range(JumpTables))
1749 JTTargets.insert(JT->Entries.begin(), JT->Entries.end());
1751 bool HasUnclaimedReference = false;
1752 for (uint64_t Destination : ExternallyReferencedOffsets) {
1753 // Ignore __builtin_unreachable().
1754 if (Destination == getSize())
1755 continue;
1756 // Ignore constant islands
1757 if (isInConstantIsland(Destination + getAddress()))
1758 continue;
1760 if (BinaryBasicBlock *BB = getBasicBlockAtOffset(Destination)) {
1761 // Check if the externally referenced offset is a recognized jump table
1762 // target.
1763 if (JTTargets.contains(BB->getLabel()))
1764 continue;
1766 if (opts::Verbosity >= 1) {
1767 errs() << "BOLT-WARNING: unclaimed data to code reference (possibly "
1768 << "an unrecognized jump table entry) to " << BB->getName()
1769 << " in " << *this << "\n";
1771 auto L = BC.scopeLock();
1772 addEntryPoint(*BB);
1773 } else {
1774 errs() << "BOLT-WARNING: unknown data to code reference to offset "
1775 << Twine::utohexstr(Destination) << " in " << *this << "\n";
1776 setIgnored();
1778 HasUnclaimedReference = true;
1780 return !HasUnclaimedReference;
1783 bool BinaryFunction::postProcessIndirectBranches(
1784 MCPlusBuilder::AllocatorIdTy AllocId) {
1785 auto addUnknownControlFlow = [&](BinaryBasicBlock &BB) {
1786 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding unknown control flow in " << *this
1787 << " for " << BB.getName() << "\n");
1788 HasUnknownControlFlow = true;
1789 BB.removeAllSuccessors();
1790 for (uint64_t PossibleDestination : ExternallyReferencedOffsets)
1791 if (BinaryBasicBlock *SuccBB = getBasicBlockAtOffset(PossibleDestination))
1792 BB.addSuccessor(SuccBB);
1795 uint64_t NumIndirectJumps = 0;
1796 MCInst *LastIndirectJump = nullptr;
1797 BinaryBasicBlock *LastIndirectJumpBB = nullptr;
1798 uint64_t LastJT = 0;
1799 uint16_t LastJTIndexReg = BC.MIB->getNoRegister();
1800 for (BinaryBasicBlock &BB : blocks()) {
1801 for (BinaryBasicBlock::iterator II = BB.begin(); II != BB.end(); ++II) {
1802 MCInst &Instr = *II;
1803 if (!BC.MIB->isIndirectBranch(Instr))
1804 continue;
1806 // If there's an indirect branch in a single-block function -
1807 // it must be a tail call.
1808 if (BasicBlocks.size() == 1) {
1809 BC.MIB->convertJmpToTailCall(Instr);
1810 return true;
1813 ++NumIndirectJumps;
1815 if (opts::StrictMode && !hasInternalReference()) {
1816 BC.MIB->convertJmpToTailCall(Instr);
1817 break;
1820 // Validate the tail call or jump table assumptions now that we know
1821 // basic block boundaries.
1822 if (BC.MIB->isTailCall(Instr) || BC.MIB->getJumpTable(Instr)) {
1823 const unsigned PtrSize = BC.AsmInfo->getCodePointerSize();
1824 MCInst *MemLocInstr;
1825 unsigned BaseRegNum, IndexRegNum;
1826 int64_t DispValue;
1827 const MCExpr *DispExpr;
1828 MCInst *PCRelBaseInstr;
1829 IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
1830 Instr, BB.begin(), II, PtrSize, MemLocInstr, BaseRegNum,
1831 IndexRegNum, DispValue, DispExpr, PCRelBaseInstr);
1832 if (Type != IndirectBranchType::UNKNOWN || MemLocInstr != nullptr)
1833 continue;
1835 if (!opts::StrictMode)
1836 return false;
1838 if (BC.MIB->isTailCall(Instr)) {
1839 BC.MIB->convertTailCallToJmp(Instr);
1840 } else {
1841 LastIndirectJump = &Instr;
1842 LastIndirectJumpBB = &BB;
1843 LastJT = BC.MIB->getJumpTable(Instr);
1844 LastJTIndexReg = BC.MIB->getJumpTableIndexReg(Instr);
1845 BC.MIB->unsetJumpTable(Instr);
1847 JumpTable *JT = BC.getJumpTableContainingAddress(LastJT);
1848 if (JT->Type == JumpTable::JTT_NORMAL) {
1849 // Invalidating the jump table may also invalidate other jump table
1850 // boundaries. Until we have/need a support for this, mark the
1851 // function as non-simple.
1852 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: rejected jump table reference"
1853 << JT->getName() << " in " << *this << '\n');
1854 return false;
1858 addUnknownControlFlow(BB);
1859 continue;
1862 // If this block contains an epilogue code and has an indirect branch,
1863 // then most likely it's a tail call. Otherwise, we cannot tell for sure
1864 // what it is and conservatively reject the function's CFG.
1865 bool IsEpilogue = llvm::any_of(BB, [&](const MCInst &Instr) {
1866 return BC.MIB->isLeave(Instr) || BC.MIB->isPop(Instr);
1868 if (IsEpilogue) {
1869 BC.MIB->convertJmpToTailCall(Instr);
1870 BB.removeAllSuccessors();
1871 continue;
1874 if (opts::Verbosity >= 2) {
1875 outs() << "BOLT-INFO: rejected potential indirect tail call in "
1876 << "function " << *this << " in basic block " << BB.getName()
1877 << ".\n";
1878 LLVM_DEBUG(BC.printInstructions(dbgs(), BB.begin(), BB.end(),
1879 BB.getOffset(), this, true));
1882 if (!opts::StrictMode)
1883 return false;
1885 addUnknownControlFlow(BB);
1889 if (HasInternalLabelReference)
1890 return false;
1892 // If there's only one jump table, and one indirect jump, and no other
1893 // references, then we should be able to derive the jump table even if we
1894 // fail to match the pattern.
1895 if (HasUnknownControlFlow && NumIndirectJumps == 1 &&
1896 JumpTables.size() == 1 && LastIndirectJump &&
1897 !BC.getJumpTableContainingAddress(LastJT)->IsSplit) {
1898 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: unsetting unknown control flow in "
1899 << *this << '\n');
1900 BC.MIB->setJumpTable(*LastIndirectJump, LastJT, LastJTIndexReg, AllocId);
1901 HasUnknownControlFlow = false;
1903 LastIndirectJumpBB->updateJumpTableSuccessors();
1906 // Validate that all data references to function offsets are claimed by
1907 // recognized jump tables. Register externally referenced blocks as entry
1908 // points.
1909 if (!opts::StrictMode && hasInternalReference()) {
1910 if (!validateExternallyReferencedOffsets())
1911 return false;
1914 if (HasUnknownControlFlow && !BC.HasRelocations)
1915 return false;
1917 return true;
1920 void BinaryFunction::recomputeLandingPads() {
1921 updateBBIndices(0);
1923 for (BinaryBasicBlock *BB : BasicBlocks) {
1924 BB->LandingPads.clear();
1925 BB->Throwers.clear();
1928 for (BinaryBasicBlock *BB : BasicBlocks) {
1929 std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
1930 for (MCInst &Instr : *BB) {
1931 if (!BC.MIB->isInvoke(Instr))
1932 continue;
1934 const std::optional<MCPlus::MCLandingPad> EHInfo =
1935 BC.MIB->getEHInfo(Instr);
1936 if (!EHInfo || !EHInfo->first)
1937 continue;
1939 BinaryBasicBlock *LPBlock = getBasicBlockForLabel(EHInfo->first);
1940 if (!BBLandingPads.count(LPBlock)) {
1941 BBLandingPads.insert(LPBlock);
1942 BB->LandingPads.emplace_back(LPBlock);
1943 LPBlock->Throwers.emplace_back(BB);
1949 bool BinaryFunction::buildCFG(MCPlusBuilder::AllocatorIdTy AllocatorId) {
1950 auto &MIB = BC.MIB;
1952 if (!isSimple()) {
1953 assert(!BC.HasRelocations &&
1954 "cannot process file with non-simple function in relocs mode");
1955 return false;
1958 if (CurrentState != State::Disassembled)
1959 return false;
1961 assert(BasicBlocks.empty() && "basic block list should be empty");
1962 assert((Labels.find(getFirstInstructionOffset()) != Labels.end()) &&
1963 "first instruction should always have a label");
1965 // Create basic blocks in the original layout order:
1967 // * Every instruction with associated label marks
1968 // the beginning of a basic block.
1969 // * Conditional instruction marks the end of a basic block,
1970 // except when the following instruction is an
1971 // unconditional branch, and the unconditional branch is not
1972 // a destination of another branch. In the latter case, the
1973 // basic block will consist of a single unconditional branch
1974 // (missed "double-jump" optimization).
1976 // Created basic blocks are sorted in layout order since they are
1977 // created in the same order as instructions, and instructions are
1978 // sorted by offsets.
1979 BinaryBasicBlock *InsertBB = nullptr;
1980 BinaryBasicBlock *PrevBB = nullptr;
1981 bool IsLastInstrNop = false;
1982 // Offset of the last non-nop instruction.
1983 uint64_t LastInstrOffset = 0;
1985 auto addCFIPlaceholders = [this](uint64_t CFIOffset,
1986 BinaryBasicBlock *InsertBB) {
1987 for (auto FI = OffsetToCFI.lower_bound(CFIOffset),
1988 FE = OffsetToCFI.upper_bound(CFIOffset);
1989 FI != FE; ++FI) {
1990 addCFIPseudo(InsertBB, InsertBB->end(), FI->second);
1994 // For profiling purposes we need to save the offset of the last instruction
1995 // in the basic block.
1996 // NOTE: nops always have an Offset annotation. Annotate the last non-nop as
1997 // older profiles ignored nops.
1998 auto updateOffset = [&](uint64_t Offset) {
1999 assert(PrevBB && PrevBB != InsertBB && "invalid previous block");
2000 MCInst *LastNonNop = nullptr;
2001 for (BinaryBasicBlock::reverse_iterator RII = PrevBB->getLastNonPseudo(),
2002 E = PrevBB->rend();
2003 RII != E; ++RII) {
2004 if (!BC.MIB->isPseudo(*RII) && !BC.MIB->isNoop(*RII)) {
2005 LastNonNop = &*RII;
2006 break;
2009 if (LastNonNop && !MIB->getOffset(*LastNonNop))
2010 MIB->setOffset(*LastNonNop, static_cast<uint32_t>(Offset));
2013 for (auto I = Instructions.begin(), E = Instructions.end(); I != E; ++I) {
2014 const uint32_t Offset = I->first;
2015 MCInst &Instr = I->second;
2017 auto LI = Labels.find(Offset);
2018 if (LI != Labels.end()) {
2019 // Always create new BB at branch destination.
2020 PrevBB = InsertBB ? InsertBB : PrevBB;
2021 InsertBB = addBasicBlockAt(LI->first, LI->second);
2022 if (opts::PreserveBlocksAlignment && IsLastInstrNop)
2023 InsertBB->setDerivedAlignment();
2025 if (PrevBB)
2026 updateOffset(LastInstrOffset);
2029 // Mark all nops with Offset for profile tracking purposes.
2030 if (MIB->isNoop(Instr) && !MIB->getOffset(Instr)) {
2031 // If "Offset" annotation is not present, set it and mark the nop for
2032 // deletion.
2033 MIB->setOffset(Instr, static_cast<uint32_t>(Offset));
2034 // Annotate ordinary nops, so we can safely delete them if required.
2035 MIB->addAnnotation(Instr, "NOP", static_cast<uint32_t>(1), AllocatorId);
2038 if (!InsertBB) {
2039 // It must be a fallthrough or unreachable code. Create a new block unless
2040 // we see an unconditional branch following a conditional one. The latter
2041 // should not be a conditional tail call.
2042 assert(PrevBB && "no previous basic block for a fall through");
2043 MCInst *PrevInstr = PrevBB->getLastNonPseudoInstr();
2044 assert(PrevInstr && "no previous instruction for a fall through");
2045 if (MIB->isUnconditionalBranch(Instr) &&
2046 !MIB->isIndirectBranch(*PrevInstr) &&
2047 !MIB->isUnconditionalBranch(*PrevInstr) &&
2048 !MIB->getConditionalTailCall(*PrevInstr) &&
2049 !MIB->isReturn(*PrevInstr)) {
2050 // Temporarily restore inserter basic block.
2051 InsertBB = PrevBB;
2052 } else {
2053 MCSymbol *Label;
2055 auto L = BC.scopeLock();
2056 Label = BC.Ctx->createNamedTempSymbol("FT");
2058 InsertBB = addBasicBlockAt(Offset, Label);
2059 if (opts::PreserveBlocksAlignment && IsLastInstrNop)
2060 InsertBB->setDerivedAlignment();
2061 updateOffset(LastInstrOffset);
2064 if (Offset == getFirstInstructionOffset()) {
2065 // Add associated CFI pseudos in the first offset
2066 addCFIPlaceholders(Offset, InsertBB);
2069 const bool IsBlockEnd = MIB->isTerminator(Instr);
2070 IsLastInstrNop = MIB->isNoop(Instr);
2071 if (!IsLastInstrNop)
2072 LastInstrOffset = Offset;
2073 InsertBB->addInstruction(std::move(Instr));
2075 // Add associated CFI instrs. We always add the CFI instruction that is
2076 // located immediately after this instruction, since the next CFI
2077 // instruction reflects the change in state caused by this instruction.
2078 auto NextInstr = std::next(I);
2079 uint64_t CFIOffset;
2080 if (NextInstr != E)
2081 CFIOffset = NextInstr->first;
2082 else
2083 CFIOffset = getSize();
2085 // Note: this potentially invalidates instruction pointers/iterators.
2086 addCFIPlaceholders(CFIOffset, InsertBB);
2088 if (IsBlockEnd) {
2089 PrevBB = InsertBB;
2090 InsertBB = nullptr;
2094 if (BasicBlocks.empty()) {
2095 setSimple(false);
2096 return false;
2099 // Intermediate dump.
2100 LLVM_DEBUG(print(dbgs(), "after creating basic blocks"));
2102 // TODO: handle properly calls to no-return functions,
2103 // e.g. exit(3), etc. Otherwise we'll see a false fall-through
2104 // blocks.
2106 for (std::pair<uint32_t, uint32_t> &Branch : TakenBranches) {
2107 LLVM_DEBUG(dbgs() << "registering branch [0x"
2108 << Twine::utohexstr(Branch.first) << "] -> [0x"
2109 << Twine::utohexstr(Branch.second) << "]\n");
2110 BinaryBasicBlock *FromBB = getBasicBlockContainingOffset(Branch.first);
2111 BinaryBasicBlock *ToBB = getBasicBlockAtOffset(Branch.second);
2112 if (!FromBB || !ToBB) {
2113 if (!FromBB)
2114 errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2115 if (!ToBB)
2116 errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2117 BC.exitWithBugReport("disassembly failed - inconsistent branch found.",
2118 *this);
2121 FromBB->addSuccessor(ToBB);
2124 // Add fall-through branches.
2125 PrevBB = nullptr;
2126 bool IsPrevFT = false; // Is previous block a fall-through.
2127 for (BinaryBasicBlock *BB : BasicBlocks) {
2128 if (IsPrevFT)
2129 PrevBB->addSuccessor(BB);
2131 if (BB->empty()) {
2132 IsPrevFT = true;
2133 PrevBB = BB;
2134 continue;
2137 MCInst *LastInstr = BB->getLastNonPseudoInstr();
2138 assert(LastInstr &&
2139 "should have non-pseudo instruction in non-empty block");
2141 if (BB->succ_size() == 0) {
2142 // Since there's no existing successors, we know the last instruction is
2143 // not a conditional branch. Thus if it's a terminator, it shouldn't be a
2144 // fall-through.
2146 // Conditional tail call is a special case since we don't add a taken
2147 // branch successor for it.
2148 IsPrevFT = !MIB->isTerminator(*LastInstr) ||
2149 MIB->getConditionalTailCall(*LastInstr);
2150 } else if (BB->succ_size() == 1) {
2151 IsPrevFT = MIB->isConditionalBranch(*LastInstr);
2152 } else {
2153 IsPrevFT = false;
2156 PrevBB = BB;
2159 // Assign landing pads and throwers info.
2160 recomputeLandingPads();
2162 // Assign CFI information to each BB entry.
2163 annotateCFIState();
2165 // Annotate invoke instructions with GNU_args_size data.
2166 propagateGnuArgsSizeInfo(AllocatorId);
2168 // Set the basic block layout to the original order and set end offsets.
2169 PrevBB = nullptr;
2170 for (BinaryBasicBlock *BB : BasicBlocks) {
2171 Layout.addBasicBlock(BB);
2172 if (PrevBB)
2173 PrevBB->setEndOffset(BB->getOffset());
2174 PrevBB = BB;
2176 PrevBB->setEndOffset(getSize());
2178 Layout.updateLayoutIndices();
2180 normalizeCFIState();
2182 // Clean-up memory taken by intermediate structures.
2184 // NB: don't clear Labels list as we may need them if we mark the function
2185 // as non-simple later in the process of discovering extra entry points.
2186 clearList(Instructions);
2187 clearList(OffsetToCFI);
2188 clearList(TakenBranches);
2190 // Update the state.
2191 CurrentState = State::CFG;
2193 // Make any necessary adjustments for indirect branches.
2194 if (!postProcessIndirectBranches(AllocatorId)) {
2195 if (opts::Verbosity) {
2196 errs() << "BOLT-WARNING: failed to post-process indirect branches for "
2197 << *this << '\n';
2199 // In relocation mode we want to keep processing the function but avoid
2200 // optimizing it.
2201 setSimple(false);
2204 clearList(ExternallyReferencedOffsets);
2205 clearList(UnknownIndirectBranchOffsets);
2207 return true;
2210 void BinaryFunction::postProcessCFG() {
2211 if (isSimple() && !BasicBlocks.empty()) {
2212 // Convert conditional tail call branches to conditional branches that jump
2213 // to a tail call.
2214 removeConditionalTailCalls();
2216 postProcessProfile();
2218 // Eliminate inconsistencies between branch instructions and CFG.
2219 postProcessBranches();
2222 calculateMacroOpFusionStats();
2224 // The final cleanup of intermediate structures.
2225 clearList(IgnoredBranches);
2227 // Remove "Offset" annotations, unless we need an address-translation table
2228 // later. This has no cost, since annotations are allocated by a bumpptr
2229 // allocator and won't be released anyway until late in the pipeline.
2230 if (!requiresAddressTranslation() && !opts::Instrument) {
2231 for (BinaryBasicBlock &BB : blocks())
2232 for (MCInst &Inst : BB)
2233 BC.MIB->clearOffset(Inst);
2236 assert((!isSimple() || validateCFG()) &&
2237 "invalid CFG detected after post-processing");
2240 void BinaryFunction::calculateMacroOpFusionStats() {
2241 if (!getBinaryContext().isX86())
2242 return;
2243 for (const BinaryBasicBlock &BB : blocks()) {
2244 auto II = BB.getMacroOpFusionPair();
2245 if (II == BB.end())
2246 continue;
2248 // Check offset of the second instruction.
2249 // FIXME: arch-specific.
2250 const uint32_t Offset = BC.MIB->getOffsetWithDefault(*std::next(II), 0);
2251 if (!Offset || (getAddress() + Offset) % 64)
2252 continue;
2254 LLVM_DEBUG(dbgs() << "\nmissed macro-op fusion at address 0x"
2255 << Twine::utohexstr(getAddress() + Offset)
2256 << " in function " << *this << "; executed "
2257 << BB.getKnownExecutionCount() << " times.\n");
2258 ++BC.Stats.MissedMacroFusionPairs;
2259 BC.Stats.MissedMacroFusionExecCount += BB.getKnownExecutionCount();
2263 void BinaryFunction::removeTagsFromProfile() {
2264 for (BinaryBasicBlock *BB : BasicBlocks) {
2265 if (BB->ExecutionCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2266 BB->ExecutionCount = 0;
2267 for (BinaryBasicBlock::BinaryBranchInfo &BI : BB->branch_info()) {
2268 if (BI.Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
2269 BI.MispredictedCount != BinaryBasicBlock::COUNT_NO_PROFILE)
2270 continue;
2271 BI.Count = 0;
2272 BI.MispredictedCount = 0;
2277 void BinaryFunction::removeConditionalTailCalls() {
2278 // Blocks to be appended at the end.
2279 std::vector<std::unique_ptr<BinaryBasicBlock>> NewBlocks;
2281 for (auto BBI = begin(); BBI != end(); ++BBI) {
2282 BinaryBasicBlock &BB = *BBI;
2283 MCInst *CTCInstr = BB.getLastNonPseudoInstr();
2284 if (!CTCInstr)
2285 continue;
2287 std::optional<uint64_t> TargetAddressOrNone =
2288 BC.MIB->getConditionalTailCall(*CTCInstr);
2289 if (!TargetAddressOrNone)
2290 continue;
2292 // Gather all necessary information about CTC instruction before
2293 // annotations are destroyed.
2294 const int32_t CFIStateBeforeCTC = BB.getCFIStateAtInstr(CTCInstr);
2295 uint64_t CTCTakenCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2296 uint64_t CTCMispredCount = BinaryBasicBlock::COUNT_NO_PROFILE;
2297 if (hasValidProfile()) {
2298 CTCTakenCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2299 *CTCInstr, "CTCTakenCount");
2300 CTCMispredCount = BC.MIB->getAnnotationWithDefault<uint64_t>(
2301 *CTCInstr, "CTCMispredCount");
2304 // Assert that the tail call does not throw.
2305 assert(!BC.MIB->getEHInfo(*CTCInstr) &&
2306 "found tail call with associated landing pad");
2308 // Create a basic block with an unconditional tail call instruction using
2309 // the same destination.
2310 const MCSymbol *CTCTargetLabel = BC.MIB->getTargetSymbol(*CTCInstr);
2311 assert(CTCTargetLabel && "symbol expected for conditional tail call");
2312 MCInst TailCallInstr;
2313 BC.MIB->createTailCall(TailCallInstr, CTCTargetLabel, BC.Ctx.get());
2315 // Move offset from CTCInstr to TailCallInstr.
2316 if (const std::optional<uint32_t> Offset = BC.MIB->getOffset(*CTCInstr)) {
2317 BC.MIB->setOffset(TailCallInstr, *Offset);
2318 BC.MIB->clearOffset(*CTCInstr);
2321 // Link new BBs to the original input offset of the BB where the CTC
2322 // is, so we can map samples recorded in new BBs back to the original BB
2323 // seem in the input binary (if using BAT)
2324 std::unique_ptr<BinaryBasicBlock> TailCallBB =
2325 createBasicBlock(BC.Ctx->createNamedTempSymbol("TC"));
2326 TailCallBB->setOffset(BB.getInputOffset());
2327 TailCallBB->addInstruction(TailCallInstr);
2328 TailCallBB->setCFIState(CFIStateBeforeCTC);
2330 // Add CFG edge with profile info from BB to TailCallBB.
2331 BB.addSuccessor(TailCallBB.get(), CTCTakenCount, CTCMispredCount);
2333 // Add execution count for the block.
2334 TailCallBB->setExecutionCount(CTCTakenCount);
2336 BC.MIB->convertTailCallToJmp(*CTCInstr);
2338 BC.MIB->replaceBranchTarget(*CTCInstr, TailCallBB->getLabel(),
2339 BC.Ctx.get());
2341 // Add basic block to the list that will be added to the end.
2342 NewBlocks.emplace_back(std::move(TailCallBB));
2344 // Swap edges as the TailCallBB corresponds to the taken branch.
2345 BB.swapConditionalSuccessors();
2347 // This branch is no longer a conditional tail call.
2348 BC.MIB->unsetConditionalTailCall(*CTCInstr);
2351 insertBasicBlocks(std::prev(end()), std::move(NewBlocks),
2352 /* UpdateLayout */ true,
2353 /* UpdateCFIState */ false);
2356 uint64_t BinaryFunction::getFunctionScore() const {
2357 if (FunctionScore != -1)
2358 return FunctionScore;
2360 if (!isSimple() || !hasValidProfile()) {
2361 FunctionScore = 0;
2362 return FunctionScore;
2365 uint64_t TotalScore = 0ULL;
2366 for (const BinaryBasicBlock &BB : blocks()) {
2367 uint64_t BBExecCount = BB.getExecutionCount();
2368 if (BBExecCount == BinaryBasicBlock::COUNT_NO_PROFILE)
2369 continue;
2370 TotalScore += BBExecCount * BB.getNumNonPseudos();
2372 FunctionScore = TotalScore;
2373 return FunctionScore;
2376 void BinaryFunction::annotateCFIState() {
2377 assert(CurrentState == State::Disassembled && "unexpected function state");
2378 assert(!BasicBlocks.empty() && "basic block list should not be empty");
2380 // This is an index of the last processed CFI in FDE CFI program.
2381 uint32_t State = 0;
2383 // This is an index of RememberState CFI reflecting effective state right
2384 // after execution of RestoreState CFI.
2386 // It differs from State iff the CFI at (State-1)
2387 // was RestoreState (modulo GNU_args_size CFIs, which are ignored).
2389 // This allows us to generate shorter replay sequences when producing new
2390 // CFI programs.
2391 uint32_t EffectiveState = 0;
2393 // For tracking RememberState/RestoreState sequences.
2394 std::stack<uint32_t> StateStack;
2396 for (BinaryBasicBlock *BB : BasicBlocks) {
2397 BB->setCFIState(EffectiveState);
2399 for (const MCInst &Instr : *BB) {
2400 const MCCFIInstruction *CFI = getCFIFor(Instr);
2401 if (!CFI)
2402 continue;
2404 ++State;
2406 switch (CFI->getOperation()) {
2407 case MCCFIInstruction::OpRememberState:
2408 StateStack.push(EffectiveState);
2409 EffectiveState = State;
2410 break;
2411 case MCCFIInstruction::OpRestoreState:
2412 assert(!StateStack.empty() && "corrupt CFI stack");
2413 EffectiveState = StateStack.top();
2414 StateStack.pop();
2415 break;
2416 case MCCFIInstruction::OpGnuArgsSize:
2417 // OpGnuArgsSize CFIs do not affect the CFI state.
2418 break;
2419 default:
2420 // Any other CFI updates the state.
2421 EffectiveState = State;
2422 break;
2427 assert(StateStack.empty() && "corrupt CFI stack");
2430 namespace {
2432 /// Our full interpretation of a DWARF CFI machine state at a given point
2433 struct CFISnapshot {
2434 /// CFA register number and offset defining the canonical frame at this
2435 /// point, or the number of a rule (CFI state) that computes it with a
2436 /// DWARF expression. This number will be negative if it refers to a CFI
2437 /// located in the CIE instead of the FDE.
2438 uint32_t CFAReg;
2439 int32_t CFAOffset;
2440 int32_t CFARule;
2441 /// Mapping of rules (CFI states) that define the location of each
2442 /// register. If absent, no rule defining the location of such register
2443 /// was ever read. This number will be negative if it refers to a CFI
2444 /// located in the CIE instead of the FDE.
2445 DenseMap<int32_t, int32_t> RegRule;
2447 /// References to CIE, FDE and expanded instructions after a restore state
2448 const BinaryFunction::CFIInstrMapType &CIE;
2449 const BinaryFunction::CFIInstrMapType &FDE;
2450 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents;
2452 /// Current FDE CFI number representing the state where the snapshot is at
2453 int32_t CurState;
2455 /// Used when we don't have information about which state/rule to apply
2456 /// to recover the location of either the CFA or a specific register
2457 constexpr static int32_t UNKNOWN = std::numeric_limits<int32_t>::min();
2459 private:
2460 /// Update our snapshot by executing a single CFI
2461 void update(const MCCFIInstruction &Instr, int32_t RuleNumber) {
2462 switch (Instr.getOperation()) {
2463 case MCCFIInstruction::OpSameValue:
2464 case MCCFIInstruction::OpRelOffset:
2465 case MCCFIInstruction::OpOffset:
2466 case MCCFIInstruction::OpRestore:
2467 case MCCFIInstruction::OpUndefined:
2468 case MCCFIInstruction::OpRegister:
2469 RegRule[Instr.getRegister()] = RuleNumber;
2470 break;
2471 case MCCFIInstruction::OpDefCfaRegister:
2472 CFAReg = Instr.getRegister();
2473 CFARule = UNKNOWN;
2475 // This shouldn't happen according to the spec but GNU binutils on RISC-V
2476 // emits a DW_CFA_def_cfa_register in CIE's which leaves the offset
2477 // unspecified. Both readelf and llvm-dwarfdump interpret the offset as 0
2478 // in this case so let's do the same.
2479 if (CFAOffset == UNKNOWN)
2480 CFAOffset = 0;
2481 break;
2482 case MCCFIInstruction::OpDefCfaOffset:
2483 CFAOffset = Instr.getOffset();
2484 CFARule = UNKNOWN;
2485 break;
2486 case MCCFIInstruction::OpDefCfa:
2487 CFAReg = Instr.getRegister();
2488 CFAOffset = Instr.getOffset();
2489 CFARule = UNKNOWN;
2490 break;
2491 case MCCFIInstruction::OpEscape: {
2492 std::optional<uint8_t> Reg =
2493 readDWARFExpressionTargetReg(Instr.getValues());
2494 // Handle DW_CFA_def_cfa_expression
2495 if (!Reg) {
2496 CFARule = RuleNumber;
2497 break;
2499 RegRule[*Reg] = RuleNumber;
2500 break;
2502 case MCCFIInstruction::OpAdjustCfaOffset:
2503 case MCCFIInstruction::OpWindowSave:
2504 case MCCFIInstruction::OpNegateRAState:
2505 case MCCFIInstruction::OpLLVMDefAspaceCfa:
2506 llvm_unreachable("unsupported CFI opcode");
2507 break;
2508 case MCCFIInstruction::OpRememberState:
2509 case MCCFIInstruction::OpRestoreState:
2510 case MCCFIInstruction::OpGnuArgsSize:
2511 // do not affect CFI state
2512 break;
2516 public:
2517 /// Advance state reading FDE CFI instructions up to State number
2518 void advanceTo(int32_t State) {
2519 for (int32_t I = CurState, E = State; I != E; ++I) {
2520 const MCCFIInstruction &Instr = FDE[I];
2521 if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2522 update(Instr, I);
2523 continue;
2525 // If restore state instruction, fetch the equivalent CFIs that have
2526 // the same effect of this restore. This is used to ensure remember-
2527 // restore pairs are completely removed.
2528 auto Iter = FrameRestoreEquivalents.find(I);
2529 if (Iter == FrameRestoreEquivalents.end())
2530 continue;
2531 for (int32_t RuleNumber : Iter->second)
2532 update(FDE[RuleNumber], RuleNumber);
2535 assert(((CFAReg != (uint32_t)UNKNOWN && CFAOffset != UNKNOWN) ||
2536 CFARule != UNKNOWN) &&
2537 "CIE did not define default CFA?");
2539 CurState = State;
2542 /// Interpret all CIE and FDE instructions up until CFI State number and
2543 /// populate this snapshot
2544 CFISnapshot(
2545 const BinaryFunction::CFIInstrMapType &CIE,
2546 const BinaryFunction::CFIInstrMapType &FDE,
2547 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2548 int32_t State)
2549 : CIE(CIE), FDE(FDE), FrameRestoreEquivalents(FrameRestoreEquivalents) {
2550 CFAReg = UNKNOWN;
2551 CFAOffset = UNKNOWN;
2552 CFARule = UNKNOWN;
2553 CurState = 0;
2555 for (int32_t I = 0, E = CIE.size(); I != E; ++I) {
2556 const MCCFIInstruction &Instr = CIE[I];
2557 update(Instr, -I);
2560 advanceTo(State);
2564 /// A CFI snapshot with the capability of checking if incremental additions to
2565 /// it are redundant. This is used to ensure we do not emit two CFI instructions
2566 /// back-to-back that are doing the same state change, or to avoid emitting a
2567 /// CFI at all when the state at that point would not be modified after that CFI
2568 struct CFISnapshotDiff : public CFISnapshot {
2569 bool RestoredCFAReg{false};
2570 bool RestoredCFAOffset{false};
2571 DenseMap<int32_t, bool> RestoredRegs;
2573 CFISnapshotDiff(const CFISnapshot &S) : CFISnapshot(S) {}
2575 CFISnapshotDiff(
2576 const BinaryFunction::CFIInstrMapType &CIE,
2577 const BinaryFunction::CFIInstrMapType &FDE,
2578 const DenseMap<int32_t, SmallVector<int32_t, 4>> &FrameRestoreEquivalents,
2579 int32_t State)
2580 : CFISnapshot(CIE, FDE, FrameRestoreEquivalents, State) {}
2582 /// Return true if applying Instr to this state is redundant and can be
2583 /// dismissed.
2584 bool isRedundant(const MCCFIInstruction &Instr) {
2585 switch (Instr.getOperation()) {
2586 case MCCFIInstruction::OpSameValue:
2587 case MCCFIInstruction::OpRelOffset:
2588 case MCCFIInstruction::OpOffset:
2589 case MCCFIInstruction::OpRestore:
2590 case MCCFIInstruction::OpUndefined:
2591 case MCCFIInstruction::OpRegister:
2592 case MCCFIInstruction::OpEscape: {
2593 uint32_t Reg;
2594 if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2595 Reg = Instr.getRegister();
2596 } else {
2597 std::optional<uint8_t> R =
2598 readDWARFExpressionTargetReg(Instr.getValues());
2599 // Handle DW_CFA_def_cfa_expression
2600 if (!R) {
2601 if (RestoredCFAReg && RestoredCFAOffset)
2602 return true;
2603 RestoredCFAReg = true;
2604 RestoredCFAOffset = true;
2605 return false;
2607 Reg = *R;
2609 if (RestoredRegs[Reg])
2610 return true;
2611 RestoredRegs[Reg] = true;
2612 const int32_t CurRegRule = RegRule.contains(Reg) ? RegRule[Reg] : UNKNOWN;
2613 if (CurRegRule == UNKNOWN) {
2614 if (Instr.getOperation() == MCCFIInstruction::OpRestore ||
2615 Instr.getOperation() == MCCFIInstruction::OpSameValue)
2616 return true;
2617 return false;
2619 const MCCFIInstruction &LastDef =
2620 CurRegRule < 0 ? CIE[-CurRegRule] : FDE[CurRegRule];
2621 return LastDef == Instr;
2623 case MCCFIInstruction::OpDefCfaRegister:
2624 if (RestoredCFAReg)
2625 return true;
2626 RestoredCFAReg = true;
2627 return CFAReg == Instr.getRegister();
2628 case MCCFIInstruction::OpDefCfaOffset:
2629 if (RestoredCFAOffset)
2630 return true;
2631 RestoredCFAOffset = true;
2632 return CFAOffset == Instr.getOffset();
2633 case MCCFIInstruction::OpDefCfa:
2634 if (RestoredCFAReg && RestoredCFAOffset)
2635 return true;
2636 RestoredCFAReg = true;
2637 RestoredCFAOffset = true;
2638 return CFAReg == Instr.getRegister() && CFAOffset == Instr.getOffset();
2639 case MCCFIInstruction::OpAdjustCfaOffset:
2640 case MCCFIInstruction::OpWindowSave:
2641 case MCCFIInstruction::OpNegateRAState:
2642 case MCCFIInstruction::OpLLVMDefAspaceCfa:
2643 llvm_unreachable("unsupported CFI opcode");
2644 return false;
2645 case MCCFIInstruction::OpRememberState:
2646 case MCCFIInstruction::OpRestoreState:
2647 case MCCFIInstruction::OpGnuArgsSize:
2648 // do not affect CFI state
2649 return true;
2651 return false;
2655 } // end anonymous namespace
2657 bool BinaryFunction::replayCFIInstrs(int32_t FromState, int32_t ToState,
2658 BinaryBasicBlock *InBB,
2659 BinaryBasicBlock::iterator InsertIt) {
2660 if (FromState == ToState)
2661 return true;
2662 assert(FromState < ToState && "can only replay CFIs forward");
2664 CFISnapshotDiff CFIDiff(CIEFrameInstructions, FrameInstructions,
2665 FrameRestoreEquivalents, FromState);
2667 std::vector<uint32_t> NewCFIs;
2668 for (int32_t CurState = FromState; CurState < ToState; ++CurState) {
2669 MCCFIInstruction *Instr = &FrameInstructions[CurState];
2670 if (Instr->getOperation() == MCCFIInstruction::OpRestoreState) {
2671 auto Iter = FrameRestoreEquivalents.find(CurState);
2672 assert(Iter != FrameRestoreEquivalents.end());
2673 NewCFIs.insert(NewCFIs.end(), Iter->second.begin(), Iter->second.end());
2674 // RestoreState / Remember will be filtered out later by CFISnapshotDiff,
2675 // so we might as well fall-through here.
2677 NewCFIs.push_back(CurState);
2680 // Replay instructions while avoiding duplicates
2681 for (int32_t State : llvm::reverse(NewCFIs)) {
2682 if (CFIDiff.isRedundant(FrameInstructions[State]))
2683 continue;
2684 InsertIt = addCFIPseudo(InBB, InsertIt, State);
2687 return true;
2690 SmallVector<int32_t, 4>
2691 BinaryFunction::unwindCFIState(int32_t FromState, int32_t ToState,
2692 BinaryBasicBlock *InBB,
2693 BinaryBasicBlock::iterator &InsertIt) {
2694 SmallVector<int32_t, 4> NewStates;
2696 CFISnapshot ToCFITable(CIEFrameInstructions, FrameInstructions,
2697 FrameRestoreEquivalents, ToState);
2698 CFISnapshotDiff FromCFITable(ToCFITable);
2699 FromCFITable.advanceTo(FromState);
2701 auto undoStateDefCfa = [&]() {
2702 if (ToCFITable.CFARule == CFISnapshot::UNKNOWN) {
2703 FrameInstructions.emplace_back(MCCFIInstruction::cfiDefCfa(
2704 nullptr, ToCFITable.CFAReg, ToCFITable.CFAOffset));
2705 if (FromCFITable.isRedundant(FrameInstructions.back())) {
2706 FrameInstructions.pop_back();
2707 return;
2709 NewStates.push_back(FrameInstructions.size() - 1);
2710 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2711 ++InsertIt;
2712 } else if (ToCFITable.CFARule < 0) {
2713 if (FromCFITable.isRedundant(CIEFrameInstructions[-ToCFITable.CFARule]))
2714 return;
2715 NewStates.push_back(FrameInstructions.size());
2716 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2717 ++InsertIt;
2718 FrameInstructions.emplace_back(CIEFrameInstructions[-ToCFITable.CFARule]);
2719 } else if (!FromCFITable.isRedundant(
2720 FrameInstructions[ToCFITable.CFARule])) {
2721 NewStates.push_back(ToCFITable.CFARule);
2722 InsertIt = addCFIPseudo(InBB, InsertIt, ToCFITable.CFARule);
2723 ++InsertIt;
2727 auto undoState = [&](const MCCFIInstruction &Instr) {
2728 switch (Instr.getOperation()) {
2729 case MCCFIInstruction::OpRememberState:
2730 case MCCFIInstruction::OpRestoreState:
2731 break;
2732 case MCCFIInstruction::OpSameValue:
2733 case MCCFIInstruction::OpRelOffset:
2734 case MCCFIInstruction::OpOffset:
2735 case MCCFIInstruction::OpRestore:
2736 case MCCFIInstruction::OpUndefined:
2737 case MCCFIInstruction::OpEscape:
2738 case MCCFIInstruction::OpRegister: {
2739 uint32_t Reg;
2740 if (Instr.getOperation() != MCCFIInstruction::OpEscape) {
2741 Reg = Instr.getRegister();
2742 } else {
2743 std::optional<uint8_t> R =
2744 readDWARFExpressionTargetReg(Instr.getValues());
2745 // Handle DW_CFA_def_cfa_expression
2746 if (!R) {
2747 undoStateDefCfa();
2748 return;
2750 Reg = *R;
2753 if (!ToCFITable.RegRule.contains(Reg)) {
2754 FrameInstructions.emplace_back(
2755 MCCFIInstruction::createRestore(nullptr, Reg));
2756 if (FromCFITable.isRedundant(FrameInstructions.back())) {
2757 FrameInstructions.pop_back();
2758 break;
2760 NewStates.push_back(FrameInstructions.size() - 1);
2761 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size() - 1);
2762 ++InsertIt;
2763 break;
2765 const int32_t Rule = ToCFITable.RegRule[Reg];
2766 if (Rule < 0) {
2767 if (FromCFITable.isRedundant(CIEFrameInstructions[-Rule]))
2768 break;
2769 NewStates.push_back(FrameInstructions.size());
2770 InsertIt = addCFIPseudo(InBB, InsertIt, FrameInstructions.size());
2771 ++InsertIt;
2772 FrameInstructions.emplace_back(CIEFrameInstructions[-Rule]);
2773 break;
2775 if (FromCFITable.isRedundant(FrameInstructions[Rule]))
2776 break;
2777 NewStates.push_back(Rule);
2778 InsertIt = addCFIPseudo(InBB, InsertIt, Rule);
2779 ++InsertIt;
2780 break;
2782 case MCCFIInstruction::OpDefCfaRegister:
2783 case MCCFIInstruction::OpDefCfaOffset:
2784 case MCCFIInstruction::OpDefCfa:
2785 undoStateDefCfa();
2786 break;
2787 case MCCFIInstruction::OpAdjustCfaOffset:
2788 case MCCFIInstruction::OpWindowSave:
2789 case MCCFIInstruction::OpNegateRAState:
2790 case MCCFIInstruction::OpLLVMDefAspaceCfa:
2791 llvm_unreachable("unsupported CFI opcode");
2792 break;
2793 case MCCFIInstruction::OpGnuArgsSize:
2794 // do not affect CFI state
2795 break;
2799 // Undo all modifications from ToState to FromState
2800 for (int32_t I = ToState, E = FromState; I != E; ++I) {
2801 const MCCFIInstruction &Instr = FrameInstructions[I];
2802 if (Instr.getOperation() != MCCFIInstruction::OpRestoreState) {
2803 undoState(Instr);
2804 continue;
2806 auto Iter = FrameRestoreEquivalents.find(I);
2807 if (Iter == FrameRestoreEquivalents.end())
2808 continue;
2809 for (int32_t State : Iter->second)
2810 undoState(FrameInstructions[State]);
2813 return NewStates;
2816 void BinaryFunction::normalizeCFIState() {
2817 // Reordering blocks with remember-restore state instructions can be specially
2818 // tricky. When rewriting the CFI, we omit remember-restore state instructions
2819 // entirely. For restore state, we build a map expanding each restore to the
2820 // equivalent unwindCFIState sequence required at that point to achieve the
2821 // same effect of the restore. All remember state are then just ignored.
2822 std::stack<int32_t> Stack;
2823 for (BinaryBasicBlock *CurBB : Layout.blocks()) {
2824 for (auto II = CurBB->begin(); II != CurBB->end(); ++II) {
2825 if (const MCCFIInstruction *CFI = getCFIFor(*II)) {
2826 if (CFI->getOperation() == MCCFIInstruction::OpRememberState) {
2827 Stack.push(II->getOperand(0).getImm());
2828 continue;
2830 if (CFI->getOperation() == MCCFIInstruction::OpRestoreState) {
2831 const int32_t RememberState = Stack.top();
2832 const int32_t CurState = II->getOperand(0).getImm();
2833 FrameRestoreEquivalents[CurState] =
2834 unwindCFIState(CurState, RememberState, CurBB, II);
2835 Stack.pop();
2842 bool BinaryFunction::finalizeCFIState() {
2843 LLVM_DEBUG(
2844 dbgs() << "Trying to fix CFI states for each BB after reordering.\n");
2845 LLVM_DEBUG(dbgs() << "This is the list of CFI states for each BB of " << *this
2846 << ": ");
2848 const char *Sep = "";
2849 (void)Sep;
2850 for (FunctionFragment &FF : Layout.fragments()) {
2851 // Hot-cold border: at start of each region (with a different FDE) we need
2852 // to reset the CFI state.
2853 int32_t State = 0;
2855 for (BinaryBasicBlock *BB : FF) {
2856 const int32_t CFIStateAtExit = BB->getCFIStateAtExit();
2858 // We need to recover the correct state if it doesn't match expected
2859 // state at BB entry point.
2860 if (BB->getCFIState() < State) {
2861 // In this case, State is currently higher than what this BB expect it
2862 // to be. To solve this, we need to insert CFI instructions to undo
2863 // the effect of all CFI from BB's state to current State.
2864 auto InsertIt = BB->begin();
2865 unwindCFIState(State, BB->getCFIState(), BB, InsertIt);
2866 } else if (BB->getCFIState() > State) {
2867 // If BB's CFI state is greater than State, it means we are behind in
2868 // the state. Just emit all instructions to reach this state at the
2869 // beginning of this BB. If this sequence of instructions involve
2870 // remember state or restore state, bail out.
2871 if (!replayCFIInstrs(State, BB->getCFIState(), BB, BB->begin()))
2872 return false;
2875 State = CFIStateAtExit;
2876 LLVM_DEBUG(dbgs() << Sep << State; Sep = ", ");
2879 LLVM_DEBUG(dbgs() << "\n");
2881 for (BinaryBasicBlock &BB : blocks()) {
2882 for (auto II = BB.begin(); II != BB.end();) {
2883 const MCCFIInstruction *CFI = getCFIFor(*II);
2884 if (CFI && (CFI->getOperation() == MCCFIInstruction::OpRememberState ||
2885 CFI->getOperation() == MCCFIInstruction::OpRestoreState)) {
2886 II = BB.eraseInstruction(II);
2887 } else {
2888 ++II;
2893 return true;
2896 bool BinaryFunction::requiresAddressTranslation() const {
2897 return opts::EnableBAT || hasSDTMarker() || hasPseudoProbe();
2900 bool BinaryFunction::requiresAddressMap() const {
2901 if (isInjected())
2902 return false;
2904 return opts::UpdateDebugSections || isMultiEntry() ||
2905 requiresAddressTranslation();
2908 uint64_t BinaryFunction::getInstructionCount() const {
2909 uint64_t Count = 0;
2910 for (const BinaryBasicBlock &BB : blocks())
2911 Count += BB.getNumNonPseudos();
2912 return Count;
2915 void BinaryFunction::clearDisasmState() {
2916 clearList(Instructions);
2917 clearList(IgnoredBranches);
2918 clearList(TakenBranches);
2920 if (BC.HasRelocations) {
2921 for (std::pair<const uint32_t, MCSymbol *> &LI : Labels)
2922 BC.UndefinedSymbols.insert(LI.second);
2923 for (MCSymbol *const EndLabel : FunctionEndLabels)
2924 if (EndLabel)
2925 BC.UndefinedSymbols.insert(EndLabel);
2929 void BinaryFunction::setTrapOnEntry() {
2930 clearDisasmState();
2932 forEachEntryPoint([&](uint64_t Offset, const MCSymbol *Label) -> bool {
2933 MCInst TrapInstr;
2934 BC.MIB->createTrap(TrapInstr);
2935 addInstruction(Offset, std::move(TrapInstr));
2936 return true;
2939 TrapsOnEntry = true;
2942 void BinaryFunction::setIgnored() {
2943 if (opts::processAllFunctions()) {
2944 // We can accept ignored functions before they've been disassembled.
2945 // In that case, they would still get disassembled and emited, but not
2946 // optimized.
2947 assert(CurrentState == State::Empty &&
2948 "cannot ignore non-empty functions in current mode");
2949 IsIgnored = true;
2950 return;
2953 clearDisasmState();
2955 // Clear CFG state too.
2956 if (hasCFG()) {
2957 releaseCFG();
2959 for (BinaryBasicBlock *BB : BasicBlocks)
2960 delete BB;
2961 clearList(BasicBlocks);
2963 for (BinaryBasicBlock *BB : DeletedBasicBlocks)
2964 delete BB;
2965 clearList(DeletedBasicBlocks);
2967 Layout.clear();
2970 CurrentState = State::Empty;
2972 IsIgnored = true;
2973 IsSimple = false;
2974 LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n');
2977 void BinaryFunction::duplicateConstantIslands() {
2978 assert(Islands && "function expected to have constant islands");
2980 for (BinaryBasicBlock *BB : getLayout().blocks()) {
2981 if (!BB->isCold())
2982 continue;
2984 for (MCInst &Inst : *BB) {
2985 int OpNum = 0;
2986 for (MCOperand &Operand : Inst) {
2987 if (!Operand.isExpr()) {
2988 ++OpNum;
2989 continue;
2991 const MCSymbol *Symbol = BC.MIB->getTargetSymbol(Inst, OpNum);
2992 // Check if this is an island symbol
2993 if (!Islands->Symbols.count(Symbol) &&
2994 !Islands->ProxySymbols.count(Symbol))
2995 continue;
2997 // Create cold symbol, if missing
2998 auto ISym = Islands->ColdSymbols.find(Symbol);
2999 MCSymbol *ColdSymbol;
3000 if (ISym != Islands->ColdSymbols.end()) {
3001 ColdSymbol = ISym->second;
3002 } else {
3003 ColdSymbol = BC.Ctx->getOrCreateSymbol(Symbol->getName() + ".cold");
3004 Islands->ColdSymbols[Symbol] = ColdSymbol;
3005 // Check if this is a proxy island symbol and update owner proxy map
3006 if (Islands->ProxySymbols.count(Symbol)) {
3007 BinaryFunction *Owner = Islands->ProxySymbols[Symbol];
3008 auto IProxiedSym = Owner->Islands->Proxies[this].find(Symbol);
3009 Owner->Islands->ColdProxies[this][IProxiedSym->second] = ColdSymbol;
3013 // Update instruction reference
3014 Operand = MCOperand::createExpr(BC.MIB->getTargetExprFor(
3015 Inst,
3016 MCSymbolRefExpr::create(ColdSymbol, MCSymbolRefExpr::VK_None,
3017 *BC.Ctx),
3018 *BC.Ctx, 0));
3019 ++OpNum;
3025 #ifndef MAX_PATH
3026 #define MAX_PATH 255
3027 #endif
3029 static std::string constructFilename(std::string Filename,
3030 std::string Annotation,
3031 std::string Suffix) {
3032 std::replace(Filename.begin(), Filename.end(), '/', '-');
3033 if (!Annotation.empty())
3034 Annotation.insert(0, "-");
3035 if (Filename.size() + Annotation.size() + Suffix.size() > MAX_PATH) {
3036 assert(Suffix.size() + Annotation.size() <= MAX_PATH);
3037 if (opts::Verbosity >= 1) {
3038 errs() << "BOLT-WARNING: Filename \"" << Filename << Annotation << Suffix
3039 << "\" exceeds the " << MAX_PATH << " size limit, truncating.\n";
3041 Filename.resize(MAX_PATH - (Suffix.size() + Annotation.size()));
3043 Filename += Annotation;
3044 Filename += Suffix;
3045 return Filename;
3048 static std::string formatEscapes(const std::string &Str) {
3049 std::string Result;
3050 for (unsigned I = 0; I < Str.size(); ++I) {
3051 char C = Str[I];
3052 switch (C) {
3053 case '\n':
3054 Result += "&#13;";
3055 break;
3056 case '"':
3057 break;
3058 default:
3059 Result += C;
3060 break;
3063 return Result;
3066 void BinaryFunction::dumpGraph(raw_ostream &OS) const {
3067 OS << "digraph \"" << getPrintName() << "\" {\n"
3068 << "node [fontname=courier, shape=box, style=filled, colorscheme=brbg9]\n";
3069 uint64_t Offset = Address;
3070 for (BinaryBasicBlock *BB : BasicBlocks) {
3071 auto LayoutPos = find(Layout.blocks(), BB);
3072 unsigned LayoutIndex = LayoutPos - Layout.block_begin();
3073 const char *ColdStr = BB->isCold() ? " (cold)" : "";
3074 std::vector<std::string> Attrs;
3075 // Bold box for entry points
3076 if (isEntryPoint(*BB))
3077 Attrs.push_back("penwidth=2");
3078 if (BLI && BLI->getLoopFor(BB)) {
3079 // Distinguish innermost loops
3080 const BinaryLoop *Loop = BLI->getLoopFor(BB);
3081 if (Loop->isInnermost())
3082 Attrs.push_back("fillcolor=6");
3083 else // some outer loop
3084 Attrs.push_back("fillcolor=4");
3085 } else { // non-loopy code
3086 Attrs.push_back("fillcolor=5");
3088 ListSeparator LS;
3089 OS << "\"" << BB->getName() << "\" [";
3090 for (StringRef Attr : Attrs)
3091 OS << LS << Attr;
3092 OS << "]\n";
3093 OS << format("\"%s\" [label=\"%s%s\\n(C:%lu,O:%lu,I:%u,L:%u,CFI:%u)\\n",
3094 BB->getName().data(), BB->getName().data(), ColdStr,
3095 BB->getKnownExecutionCount(), BB->getOffset(), getIndex(BB),
3096 LayoutIndex, BB->getCFIState());
3098 if (opts::DotToolTipCode) {
3099 std::string Str;
3100 raw_string_ostream CS(Str);
3101 Offset = BC.printInstructions(CS, BB->begin(), BB->end(), Offset, this,
3102 /* PrintMCInst = */ false,
3103 /* PrintMemData = */ false,
3104 /* PrintRelocations = */ false,
3105 /* Endl = */ R"(\\l)");
3106 OS << formatEscapes(CS.str()) << '\n';
3108 OS << "\"]\n";
3110 // analyzeBranch is just used to get the names of the branch
3111 // opcodes.
3112 const MCSymbol *TBB = nullptr;
3113 const MCSymbol *FBB = nullptr;
3114 MCInst *CondBranch = nullptr;
3115 MCInst *UncondBranch = nullptr;
3116 const bool Success = BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch);
3118 const MCInst *LastInstr = BB->getLastNonPseudoInstr();
3119 const bool IsJumpTable = LastInstr && BC.MIB->getJumpTable(*LastInstr);
3121 auto BI = BB->branch_info_begin();
3122 for (BinaryBasicBlock *Succ : BB->successors()) {
3123 std::string Branch;
3124 if (Success) {
3125 if (Succ == BB->getConditionalSuccessor(true)) {
3126 Branch = CondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3127 CondBranch->getOpcode()))
3128 : "TB";
3129 } else if (Succ == BB->getConditionalSuccessor(false)) {
3130 Branch = UncondBranch ? std::string(BC.InstPrinter->getOpcodeName(
3131 UncondBranch->getOpcode()))
3132 : "FB";
3133 } else {
3134 Branch = "FT";
3137 if (IsJumpTable)
3138 Branch = "JT";
3139 OS << format("\"%s\" -> \"%s\" [label=\"%s", BB->getName().data(),
3140 Succ->getName().data(), Branch.c_str());
3142 if (BB->getExecutionCount() != COUNT_NO_PROFILE &&
3143 BI->MispredictedCount != BinaryBasicBlock::COUNT_INFERRED) {
3144 OS << "\\n(C:" << BI->Count << ",M:" << BI->MispredictedCount << ")";
3145 } else if (ExecutionCount != COUNT_NO_PROFILE &&
3146 BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE) {
3147 OS << "\\n(IC:" << BI->Count << ")";
3149 OS << "\"]\n";
3151 ++BI;
3153 for (BinaryBasicBlock *LP : BB->landing_pads()) {
3154 OS << format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3155 BB->getName().data(), LP->getName().data());
3158 OS << "}\n";
3161 void BinaryFunction::viewGraph() const {
3162 SmallString<MAX_PATH> Filename;
3163 if (std::error_code EC =
3164 sys::fs::createTemporaryFile("bolt-cfg", "dot", Filename)) {
3165 errs() << "BOLT-ERROR: " << EC.message() << ", unable to create "
3166 << " bolt-cfg-XXXXX.dot temporary file.\n";
3167 return;
3169 dumpGraphToFile(std::string(Filename));
3170 if (DisplayGraph(Filename))
3171 errs() << "BOLT-ERROR: Can't display " << Filename << " with graphviz.\n";
3172 if (std::error_code EC = sys::fs::remove(Filename)) {
3173 errs() << "BOLT-WARNING: " << EC.message() << ", failed to remove "
3174 << Filename << "\n";
3178 void BinaryFunction::dumpGraphForPass(std::string Annotation) const {
3179 if (!opts::shouldPrint(*this))
3180 return;
3182 std::string Filename = constructFilename(getPrintName(), Annotation, ".dot");
3183 if (opts::Verbosity >= 1)
3184 outs() << "BOLT-INFO: dumping CFG to " << Filename << "\n";
3185 dumpGraphToFile(Filename);
3188 void BinaryFunction::dumpGraphToFile(std::string Filename) const {
3189 std::error_code EC;
3190 raw_fd_ostream of(Filename, EC, sys::fs::OF_None);
3191 if (EC) {
3192 if (opts::Verbosity >= 1) {
3193 errs() << "BOLT-WARNING: " << EC.message() << ", unable to open "
3194 << Filename << " for output.\n";
3196 return;
3198 dumpGraph(of);
3201 bool BinaryFunction::validateCFG() const {
3202 // Skip the validation of CFG after it is finalized
3203 if (CurrentState == State::CFG_Finalized)
3204 return true;
3206 bool Valid = true;
3207 for (BinaryBasicBlock *BB : BasicBlocks)
3208 Valid &= BB->validateSuccessorInvariants();
3210 if (!Valid)
3211 return Valid;
3213 // Make sure all blocks in CFG are valid.
3214 auto validateBlock = [this](const BinaryBasicBlock *BB, StringRef Desc) {
3215 if (!BB->isValid()) {
3216 errs() << "BOLT-ERROR: deleted " << Desc << " " << BB->getName()
3217 << " detected in:\n";
3218 this->dump();
3219 return false;
3221 return true;
3223 for (const BinaryBasicBlock *BB : BasicBlocks) {
3224 if (!validateBlock(BB, "block"))
3225 return false;
3226 for (const BinaryBasicBlock *PredBB : BB->predecessors())
3227 if (!validateBlock(PredBB, "predecessor"))
3228 return false;
3229 for (const BinaryBasicBlock *SuccBB : BB->successors())
3230 if (!validateBlock(SuccBB, "successor"))
3231 return false;
3232 for (const BinaryBasicBlock *LP : BB->landing_pads())
3233 if (!validateBlock(LP, "landing pad"))
3234 return false;
3235 for (const BinaryBasicBlock *Thrower : BB->throwers())
3236 if (!validateBlock(Thrower, "thrower"))
3237 return false;
3240 for (const BinaryBasicBlock *BB : BasicBlocks) {
3241 std::unordered_set<const BinaryBasicBlock *> BBLandingPads;
3242 for (const BinaryBasicBlock *LP : BB->landing_pads()) {
3243 if (BBLandingPads.count(LP)) {
3244 errs() << "BOLT-ERROR: duplicate landing pad detected in"
3245 << BB->getName() << " in function " << *this << '\n';
3246 return false;
3248 BBLandingPads.insert(LP);
3251 std::unordered_set<const BinaryBasicBlock *> BBThrowers;
3252 for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3253 if (BBThrowers.count(Thrower)) {
3254 errs() << "BOLT-ERROR: duplicate thrower detected in" << BB->getName()
3255 << " in function " << *this << '\n';
3256 return false;
3258 BBThrowers.insert(Thrower);
3261 for (const BinaryBasicBlock *LPBlock : BB->landing_pads()) {
3262 if (!llvm::is_contained(LPBlock->throwers(), BB)) {
3263 errs() << "BOLT-ERROR: inconsistent landing pad detected in " << *this
3264 << ": " << BB->getName() << " is in LandingPads but not in "
3265 << LPBlock->getName() << " Throwers\n";
3266 return false;
3269 for (const BinaryBasicBlock *Thrower : BB->throwers()) {
3270 if (!llvm::is_contained(Thrower->landing_pads(), BB)) {
3271 errs() << "BOLT-ERROR: inconsistent thrower detected in " << *this
3272 << ": " << BB->getName() << " is in Throwers list but not in "
3273 << Thrower->getName() << " LandingPads\n";
3274 return false;
3279 return Valid;
3282 void BinaryFunction::fixBranches() {
3283 auto &MIB = BC.MIB;
3284 MCContext *Ctx = BC.Ctx.get();
3286 for (BinaryBasicBlock *BB : BasicBlocks) {
3287 const MCSymbol *TBB = nullptr;
3288 const MCSymbol *FBB = nullptr;
3289 MCInst *CondBranch = nullptr;
3290 MCInst *UncondBranch = nullptr;
3291 if (!BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch))
3292 continue;
3294 // We will create unconditional branch with correct destination if needed.
3295 if (UncondBranch)
3296 BB->eraseInstruction(BB->findInstruction(UncondBranch));
3298 // Basic block that follows the current one in the final layout.
3299 const BinaryBasicBlock *const NextBB =
3300 Layout.getBasicBlockAfter(BB, /*IgnoreSplits=*/false);
3302 if (BB->succ_size() == 1) {
3303 // __builtin_unreachable() could create a conditional branch that
3304 // falls-through into the next function - hence the block will have only
3305 // one valid successor. Since behaviour is undefined - we replace
3306 // the conditional branch with an unconditional if required.
3307 if (CondBranch)
3308 BB->eraseInstruction(BB->findInstruction(CondBranch));
3309 if (BB->getSuccessor() == NextBB)
3310 continue;
3311 BB->addBranchInstruction(BB->getSuccessor());
3312 } else if (BB->succ_size() == 2) {
3313 assert(CondBranch && "conditional branch expected");
3314 const BinaryBasicBlock *TSuccessor = BB->getConditionalSuccessor(true);
3315 const BinaryBasicBlock *FSuccessor = BB->getConditionalSuccessor(false);
3317 // Eliminate unnecessary conditional branch.
3318 if (TSuccessor == FSuccessor) {
3319 BB->removeDuplicateConditionalSuccessor(CondBranch);
3320 if (TSuccessor != NextBB)
3321 BB->addBranchInstruction(TSuccessor);
3322 continue;
3325 // Reverse branch condition and swap successors.
3326 auto swapSuccessors = [&]() {
3327 if (MIB->isUnsupportedBranch(*CondBranch))
3328 return false;
3329 std::swap(TSuccessor, FSuccessor);
3330 BB->swapConditionalSuccessors();
3331 auto L = BC.scopeLock();
3332 MIB->reverseBranchCondition(*CondBranch, TSuccessor->getLabel(), Ctx);
3333 return true;
3336 // Check whether the next block is a "taken" target and try to swap it
3337 // with a "fall-through" target.
3338 if (TSuccessor == NextBB && swapSuccessors())
3339 continue;
3341 // Update conditional branch destination if needed.
3342 if (MIB->getTargetSymbol(*CondBranch) != TSuccessor->getLabel()) {
3343 auto L = BC.scopeLock();
3344 MIB->replaceBranchTarget(*CondBranch, TSuccessor->getLabel(), Ctx);
3347 // No need for the unconditional branch.
3348 if (FSuccessor == NextBB)
3349 continue;
3351 if (BC.isX86()) {
3352 // We are going to generate two branches. Check if their targets are in
3353 // the same fragment as this block. If only one target is in the same
3354 // fragment, make it the destination of the conditional branch. There
3355 // is a chance it will be a short branch which takes 4 bytes fewer than
3356 // a long conditional branch. For unconditional branch, the difference
3357 // is 3 bytes.
3358 if (BB->getFragmentNum() != TSuccessor->getFragmentNum() &&
3359 BB->getFragmentNum() == FSuccessor->getFragmentNum())
3360 swapSuccessors();
3363 BB->addBranchInstruction(FSuccessor);
3365 // Cases where the number of successors is 0 (block ends with a
3366 // terminator) or more than 2 (switch table) don't require branch
3367 // instruction adjustments.
3369 assert((!isSimple() || validateCFG()) &&
3370 "Invalid CFG detected after fixing branches");
3373 void BinaryFunction::propagateGnuArgsSizeInfo(
3374 MCPlusBuilder::AllocatorIdTy AllocId) {
3375 assert(CurrentState == State::Disassembled && "unexpected function state");
3377 if (!hasEHRanges() || !usesGnuArgsSize())
3378 return;
3380 // The current value of DW_CFA_GNU_args_size affects all following
3381 // invoke instructions until the next CFI overrides it.
3382 // It is important to iterate basic blocks in the original order when
3383 // assigning the value.
3384 uint64_t CurrentGnuArgsSize = 0;
3385 for (BinaryBasicBlock *BB : BasicBlocks) {
3386 for (auto II = BB->begin(); II != BB->end();) {
3387 MCInst &Instr = *II;
3388 if (BC.MIB->isCFI(Instr)) {
3389 const MCCFIInstruction *CFI = getCFIFor(Instr);
3390 if (CFI->getOperation() == MCCFIInstruction::OpGnuArgsSize) {
3391 CurrentGnuArgsSize = CFI->getOffset();
3392 // Delete DW_CFA_GNU_args_size instructions and only regenerate
3393 // during the final code emission. The information is embedded
3394 // inside call instructions.
3395 II = BB->erasePseudoInstruction(II);
3396 continue;
3398 } else if (BC.MIB->isInvoke(Instr)) {
3399 // Add the value of GNU_args_size as an extra operand to invokes.
3400 BC.MIB->addGnuArgsSize(Instr, CurrentGnuArgsSize);
3402 ++II;
3407 void BinaryFunction::postProcessBranches() {
3408 if (!isSimple())
3409 return;
3410 for (BinaryBasicBlock &BB : blocks()) {
3411 auto LastInstrRI = BB.getLastNonPseudo();
3412 if (BB.succ_size() == 1) {
3413 if (LastInstrRI != BB.rend() &&
3414 BC.MIB->isConditionalBranch(*LastInstrRI)) {
3415 // __builtin_unreachable() could create a conditional branch that
3416 // falls-through into the next function - hence the block will have only
3417 // one valid successor. Such behaviour is undefined and thus we remove
3418 // the conditional branch while leaving a valid successor.
3419 BB.eraseInstruction(std::prev(LastInstrRI.base()));
3420 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: erasing conditional branch in "
3421 << BB.getName() << " in function " << *this << '\n');
3423 } else if (BB.succ_size() == 0) {
3424 // Ignore unreachable basic blocks.
3425 if (BB.pred_size() == 0 || BB.isLandingPad())
3426 continue;
3428 // If it's the basic block that does not end up with a terminator - we
3429 // insert a return instruction unless it's a call instruction.
3430 if (LastInstrRI == BB.rend()) {
3431 LLVM_DEBUG(
3432 dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3433 << BB.getName() << " in function " << *this << '\n');
3434 continue;
3436 if (!BC.MIB->isTerminator(*LastInstrRI) &&
3437 !BC.MIB->isCall(*LastInstrRI)) {
3438 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: adding return to basic block "
3439 << BB.getName() << " in function " << *this << '\n');
3440 MCInst ReturnInstr;
3441 BC.MIB->createReturn(ReturnInstr);
3442 BB.addInstruction(ReturnInstr);
3446 assert(validateCFG() && "invalid CFG");
3449 MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) {
3450 assert(Offset && "cannot add primary entry point");
3451 assert(CurrentState == State::Empty || CurrentState == State::Disassembled);
3453 const uint64_t EntryPointAddress = getAddress() + Offset;
3454 MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress);
3456 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(LocalSymbol);
3457 if (EntrySymbol)
3458 return EntrySymbol;
3460 if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) {
3461 EntrySymbol = EntryBD->getSymbol();
3462 } else {
3463 EntrySymbol = BC.getOrCreateGlobalSymbol(
3464 EntryPointAddress, Twine("__ENTRY_") + getOneName() + "@");
3466 SecondaryEntryPoints[LocalSymbol] = EntrySymbol;
3468 BC.setSymbolToFunctionMap(EntrySymbol, this);
3470 return EntrySymbol;
3473 MCSymbol *BinaryFunction::addEntryPoint(const BinaryBasicBlock &BB) {
3474 assert(CurrentState == State::CFG &&
3475 "basic block can be added as an entry only in a function with CFG");
3477 if (&BB == BasicBlocks.front())
3478 return getSymbol();
3480 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(BB);
3481 if (EntrySymbol)
3482 return EntrySymbol;
3484 EntrySymbol =
3485 BC.Ctx->getOrCreateSymbol("__ENTRY_" + BB.getLabel()->getName());
3487 SecondaryEntryPoints[BB.getLabel()] = EntrySymbol;
3489 BC.setSymbolToFunctionMap(EntrySymbol, this);
3491 return EntrySymbol;
3494 MCSymbol *BinaryFunction::getSymbolForEntryID(uint64_t EntryID) {
3495 if (EntryID == 0)
3496 return getSymbol();
3498 if (!isMultiEntry())
3499 return nullptr;
3501 uint64_t NumEntries = 0;
3502 if (hasCFG()) {
3503 for (BinaryBasicBlock *BB : BasicBlocks) {
3504 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3505 if (!EntrySymbol)
3506 continue;
3507 if (NumEntries == EntryID)
3508 return EntrySymbol;
3509 ++NumEntries;
3511 } else {
3512 for (std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3513 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3514 if (!EntrySymbol)
3515 continue;
3516 if (NumEntries == EntryID)
3517 return EntrySymbol;
3518 ++NumEntries;
3522 return nullptr;
3525 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol *Symbol) const {
3526 if (!isMultiEntry())
3527 return 0;
3529 for (const MCSymbol *FunctionSymbol : getSymbols())
3530 if (FunctionSymbol == Symbol)
3531 return 0;
3533 // Check all secondary entries available as either basic blocks or lables.
3534 uint64_t NumEntries = 0;
3535 for (const BinaryBasicBlock *BB : BasicBlocks) {
3536 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(*BB);
3537 if (!EntrySymbol)
3538 continue;
3539 if (EntrySymbol == Symbol)
3540 return NumEntries;
3541 ++NumEntries;
3543 NumEntries = 0;
3544 for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3545 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3546 if (!EntrySymbol)
3547 continue;
3548 if (EntrySymbol == Symbol)
3549 return NumEntries;
3550 ++NumEntries;
3553 llvm_unreachable("symbol not found");
3556 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback) const {
3557 bool Status = Callback(0, getSymbol());
3558 if (!isMultiEntry())
3559 return Status;
3561 for (const std::pair<const uint32_t, MCSymbol *> &KV : Labels) {
3562 if (!Status)
3563 break;
3565 MCSymbol *EntrySymbol = getSecondaryEntryPointSymbol(KV.second);
3566 if (!EntrySymbol)
3567 continue;
3569 Status = Callback(KV.first, EntrySymbol);
3572 return Status;
3575 BinaryFunction::BasicBlockListType BinaryFunction::dfs() const {
3576 BasicBlockListType DFS;
3577 unsigned Index = 0;
3578 std::stack<BinaryBasicBlock *> Stack;
3580 // Push entry points to the stack in reverse order.
3582 // NB: we rely on the original order of entries to match.
3583 SmallVector<BinaryBasicBlock *> EntryPoints;
3584 llvm::copy_if(BasicBlocks, std::back_inserter(EntryPoints),
3585 [&](const BinaryBasicBlock *const BB) { return isEntryPoint(*BB); });
3586 // Sort entry points by their offset to make sure we got them in the right
3587 // order.
3588 llvm::stable_sort(EntryPoints, [](const BinaryBasicBlock *const A,
3589 const BinaryBasicBlock *const B) {
3590 return A->getOffset() < B->getOffset();
3592 for (BinaryBasicBlock *const BB : reverse(EntryPoints))
3593 Stack.push(BB);
3595 for (BinaryBasicBlock &BB : blocks())
3596 BB.setLayoutIndex(BinaryBasicBlock::InvalidIndex);
3598 while (!Stack.empty()) {
3599 BinaryBasicBlock *BB = Stack.top();
3600 Stack.pop();
3602 if (BB->getLayoutIndex() != BinaryBasicBlock::InvalidIndex)
3603 continue;
3605 BB->setLayoutIndex(Index++);
3606 DFS.push_back(BB);
3608 for (BinaryBasicBlock *SuccBB : BB->landing_pads()) {
3609 Stack.push(SuccBB);
3612 const MCSymbol *TBB = nullptr;
3613 const MCSymbol *FBB = nullptr;
3614 MCInst *CondBranch = nullptr;
3615 MCInst *UncondBranch = nullptr;
3616 if (BB->analyzeBranch(TBB, FBB, CondBranch, UncondBranch) && CondBranch &&
3617 BB->succ_size() == 2) {
3618 if (BC.MIB->getCanonicalBranchCondCode(BC.MIB->getCondCode(
3619 *CondBranch)) == BC.MIB->getCondCode(*CondBranch)) {
3620 Stack.push(BB->getConditionalSuccessor(true));
3621 Stack.push(BB->getConditionalSuccessor(false));
3622 } else {
3623 Stack.push(BB->getConditionalSuccessor(false));
3624 Stack.push(BB->getConditionalSuccessor(true));
3626 } else {
3627 for (BinaryBasicBlock *SuccBB : BB->successors()) {
3628 Stack.push(SuccBB);
3633 return DFS;
3636 size_t BinaryFunction::computeHash(bool UseDFS, HashFunction HashFunction,
3637 OperandHashFuncTy OperandHashFunc) const {
3638 if (size() == 0)
3639 return 0;
3641 assert(hasCFG() && "function is expected to have CFG");
3643 SmallVector<const BinaryBasicBlock *, 0> Order;
3644 if (UseDFS)
3645 llvm::copy(dfs(), std::back_inserter(Order));
3646 else
3647 llvm::copy(Layout.blocks(), std::back_inserter(Order));
3649 // The hash is computed by creating a string of all instruction opcodes and
3650 // possibly their operands and then hashing that string with std::hash.
3651 std::string HashString;
3652 for (const BinaryBasicBlock *BB : Order)
3653 HashString.append(hashBlock(BC, *BB, OperandHashFunc));
3655 switch (HashFunction) {
3656 case HashFunction::StdHash:
3657 return Hash = std::hash<std::string>{}(HashString);
3658 case HashFunction::XXH3:
3659 return Hash = llvm::xxh3_64bits(HashString);
3661 llvm_unreachable("Unhandled HashFunction");
3664 void BinaryFunction::insertBasicBlocks(
3665 BinaryBasicBlock *Start,
3666 std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3667 const bool UpdateLayout, const bool UpdateCFIState,
3668 const bool RecomputeLandingPads) {
3669 const int64_t StartIndex = Start ? getIndex(Start) : -1LL;
3670 const size_t NumNewBlocks = NewBBs.size();
3672 BasicBlocks.insert(BasicBlocks.begin() + (StartIndex + 1), NumNewBlocks,
3673 nullptr);
3675 int64_t I = StartIndex + 1;
3676 for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3677 assert(!BasicBlocks[I]);
3678 BasicBlocks[I++] = BB.release();
3681 if (RecomputeLandingPads)
3682 recomputeLandingPads();
3683 else
3684 updateBBIndices(0);
3686 if (UpdateLayout)
3687 updateLayout(Start, NumNewBlocks);
3689 if (UpdateCFIState)
3690 updateCFIState(Start, NumNewBlocks);
3693 BinaryFunction::iterator BinaryFunction::insertBasicBlocks(
3694 BinaryFunction::iterator StartBB,
3695 std::vector<std::unique_ptr<BinaryBasicBlock>> &&NewBBs,
3696 const bool UpdateLayout, const bool UpdateCFIState,
3697 const bool RecomputeLandingPads) {
3698 const unsigned StartIndex = getIndex(&*StartBB);
3699 const size_t NumNewBlocks = NewBBs.size();
3701 BasicBlocks.insert(BasicBlocks.begin() + StartIndex + 1, NumNewBlocks,
3702 nullptr);
3703 auto RetIter = BasicBlocks.begin() + StartIndex + 1;
3705 unsigned I = StartIndex + 1;
3706 for (std::unique_ptr<BinaryBasicBlock> &BB : NewBBs) {
3707 assert(!BasicBlocks[I]);
3708 BasicBlocks[I++] = BB.release();
3711 if (RecomputeLandingPads)
3712 recomputeLandingPads();
3713 else
3714 updateBBIndices(0);
3716 if (UpdateLayout)
3717 updateLayout(*std::prev(RetIter), NumNewBlocks);
3719 if (UpdateCFIState)
3720 updateCFIState(*std::prev(RetIter), NumNewBlocks);
3722 return RetIter;
3725 void BinaryFunction::updateBBIndices(const unsigned StartIndex) {
3726 for (unsigned I = StartIndex; I < BasicBlocks.size(); ++I)
3727 BasicBlocks[I]->Index = I;
3730 void BinaryFunction::updateCFIState(BinaryBasicBlock *Start,
3731 const unsigned NumNewBlocks) {
3732 const int32_t CFIState = Start->getCFIStateAtExit();
3733 const unsigned StartIndex = getIndex(Start) + 1;
3734 for (unsigned I = 0; I < NumNewBlocks; ++I)
3735 BasicBlocks[StartIndex + I]->setCFIState(CFIState);
3738 void BinaryFunction::updateLayout(BinaryBasicBlock *Start,
3739 const unsigned NumNewBlocks) {
3740 BasicBlockListType::iterator Begin;
3741 BasicBlockListType::iterator End;
3743 // If start not provided copy new blocks from the beginning of BasicBlocks
3744 if (!Start) {
3745 Begin = BasicBlocks.begin();
3746 End = BasicBlocks.begin() + NumNewBlocks;
3747 } else {
3748 unsigned StartIndex = getIndex(Start);
3749 Begin = std::next(BasicBlocks.begin(), StartIndex + 1);
3750 End = std::next(BasicBlocks.begin(), StartIndex + NumNewBlocks + 1);
3753 // Insert new blocks in the layout immediately after Start.
3754 Layout.insertBasicBlocks(Start, {Begin, End});
3755 Layout.updateLayoutIndices();
3758 bool BinaryFunction::checkForAmbiguousJumpTables() {
3759 SmallSet<uint64_t, 4> JumpTables;
3760 for (BinaryBasicBlock *&BB : BasicBlocks) {
3761 for (MCInst &Inst : *BB) {
3762 if (!BC.MIB->isIndirectBranch(Inst))
3763 continue;
3764 uint64_t JTAddress = BC.MIB->getJumpTable(Inst);
3765 if (!JTAddress)
3766 continue;
3767 // This address can be inside another jump table, but we only consider
3768 // it ambiguous when the same start address is used, not the same JT
3769 // object.
3770 if (!JumpTables.count(JTAddress)) {
3771 JumpTables.insert(JTAddress);
3772 continue;
3774 return true;
3777 return false;
3780 void BinaryFunction::disambiguateJumpTables(
3781 MCPlusBuilder::AllocatorIdTy AllocId) {
3782 assert((opts::JumpTables != JTS_BASIC && isSimple()) || !BC.HasRelocations);
3783 SmallPtrSet<JumpTable *, 4> JumpTables;
3784 for (BinaryBasicBlock *&BB : BasicBlocks) {
3785 for (MCInst &Inst : *BB) {
3786 if (!BC.MIB->isIndirectBranch(Inst))
3787 continue;
3788 JumpTable *JT = getJumpTable(Inst);
3789 if (!JT)
3790 continue;
3791 auto Iter = JumpTables.find(JT);
3792 if (Iter == JumpTables.end()) {
3793 JumpTables.insert(JT);
3794 continue;
3796 // This instruction is an indirect jump using a jump table, but it is
3797 // using the same jump table of another jump. Try all our tricks to
3798 // extract the jump table symbol and make it point to a new, duplicated JT
3799 MCPhysReg BaseReg1;
3800 uint64_t Scale;
3801 const MCSymbol *Target;
3802 // In case we match if our first matcher, first instruction is the one to
3803 // patch
3804 MCInst *JTLoadInst = &Inst;
3805 // Try a standard indirect jump matcher, scale 8
3806 std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher =
3807 BC.MIB->matchIndJmp(BC.MIB->matchReg(BaseReg1),
3808 BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3809 /*Offset=*/BC.MIB->matchSymbol(Target));
3810 if (!IndJmpMatcher->match(
3811 *BC.MRI, *BC.MIB,
3812 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3813 BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3814 MCPhysReg BaseReg2;
3815 uint64_t Offset;
3816 // Standard JT matching failed. Trying now:
3817 // movq "jt.2397/1"(,%rax,8), %rax
3818 // jmpq *%rax
3819 std::unique_ptr<MCPlusBuilder::MCInstMatcher> LoadMatcherOwner =
3820 BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg1),
3821 BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3822 /*Offset=*/BC.MIB->matchSymbol(Target));
3823 MCPlusBuilder::MCInstMatcher *LoadMatcher = LoadMatcherOwner.get();
3824 std::unique_ptr<MCPlusBuilder::MCInstMatcher> IndJmpMatcher2 =
3825 BC.MIB->matchIndJmp(std::move(LoadMatcherOwner));
3826 if (!IndJmpMatcher2->match(
3827 *BC.MRI, *BC.MIB,
3828 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3829 BaseReg1 != BC.MIB->getNoRegister() || Scale != 8) {
3830 // JT matching failed. Trying now:
3831 // PIC-style matcher, scale 4
3832 // addq %rdx, %rsi
3833 // addq %rdx, %rdi
3834 // leaq DATAat0x402450(%rip), %r11
3835 // movslq (%r11,%rdx,4), %rcx
3836 // addq %r11, %rcx
3837 // jmpq *%rcx # JUMPTABLE @0x402450
3838 std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICIndJmpMatcher =
3839 BC.MIB->matchIndJmp(BC.MIB->matchAdd(
3840 BC.MIB->matchReg(BaseReg1),
3841 BC.MIB->matchLoad(BC.MIB->matchReg(BaseReg2),
3842 BC.MIB->matchImm(Scale), BC.MIB->matchReg(),
3843 BC.MIB->matchImm(Offset))));
3844 std::unique_ptr<MCPlusBuilder::MCInstMatcher> LEAMatcherOwner =
3845 BC.MIB->matchLoadAddr(BC.MIB->matchSymbol(Target));
3846 MCPlusBuilder::MCInstMatcher *LEAMatcher = LEAMatcherOwner.get();
3847 std::unique_ptr<MCPlusBuilder::MCInstMatcher> PICBaseAddrMatcher =
3848 BC.MIB->matchIndJmp(BC.MIB->matchAdd(std::move(LEAMatcherOwner),
3849 BC.MIB->matchAnyOperand()));
3850 if (!PICIndJmpMatcher->match(
3851 *BC.MRI, *BC.MIB,
3852 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1) ||
3853 Scale != 4 || BaseReg1 != BaseReg2 || Offset != 0 ||
3854 !PICBaseAddrMatcher->match(
3855 *BC.MRI, *BC.MIB,
3856 MutableArrayRef<MCInst>(&*BB->begin(), &Inst + 1), -1)) {
3857 llvm_unreachable("Failed to extract jump table base");
3858 continue;
3860 // Matched PIC, identify the instruction with the reference to the JT
3861 JTLoadInst = LEAMatcher->CurInst;
3862 } else {
3863 // Matched non-PIC
3864 JTLoadInst = LoadMatcher->CurInst;
3868 uint64_t NewJumpTableID = 0;
3869 const MCSymbol *NewJTLabel;
3870 std::tie(NewJumpTableID, NewJTLabel) =
3871 BC.duplicateJumpTable(*this, JT, Target);
3873 auto L = BC.scopeLock();
3874 BC.MIB->replaceMemOperandDisp(*JTLoadInst, NewJTLabel, BC.Ctx.get());
3876 // We use a unique ID with the high bit set as address for this "injected"
3877 // jump table (not originally in the input binary).
3878 BC.MIB->setJumpTable(Inst, NewJumpTableID, 0, AllocId);
3883 bool BinaryFunction::replaceJumpTableEntryIn(BinaryBasicBlock *BB,
3884 BinaryBasicBlock *OldDest,
3885 BinaryBasicBlock *NewDest) {
3886 MCInst *Instr = BB->getLastNonPseudoInstr();
3887 if (!Instr || !BC.MIB->isIndirectBranch(*Instr))
3888 return false;
3889 uint64_t JTAddress = BC.MIB->getJumpTable(*Instr);
3890 assert(JTAddress && "Invalid jump table address");
3891 JumpTable *JT = getJumpTableContainingAddress(JTAddress);
3892 assert(JT && "No jump table structure for this indirect branch");
3893 bool Patched = JT->replaceDestination(JTAddress, OldDest->getLabel(),
3894 NewDest->getLabel());
3895 (void)Patched;
3896 assert(Patched && "Invalid entry to be replaced in jump table");
3897 return true;
3900 BinaryBasicBlock *BinaryFunction::splitEdge(BinaryBasicBlock *From,
3901 BinaryBasicBlock *To) {
3902 // Create intermediate BB
3903 MCSymbol *Tmp;
3905 auto L = BC.scopeLock();
3906 Tmp = BC.Ctx->createNamedTempSymbol("SplitEdge");
3908 // Link new BBs to the original input offset of the From BB, so we can map
3909 // samples recorded in new BBs back to the original BB seem in the input
3910 // binary (if using BAT)
3911 std::unique_ptr<BinaryBasicBlock> NewBB = createBasicBlock(Tmp);
3912 NewBB->setOffset(From->getInputOffset());
3913 BinaryBasicBlock *NewBBPtr = NewBB.get();
3915 // Update "From" BB
3916 auto I = From->succ_begin();
3917 auto BI = From->branch_info_begin();
3918 for (; I != From->succ_end(); ++I) {
3919 if (*I == To)
3920 break;
3921 ++BI;
3923 assert(I != From->succ_end() && "Invalid CFG edge in splitEdge!");
3924 uint64_t OrigCount = BI->Count;
3925 uint64_t OrigMispreds = BI->MispredictedCount;
3926 replaceJumpTableEntryIn(From, To, NewBBPtr);
3927 From->replaceSuccessor(To, NewBBPtr, OrigCount, OrigMispreds);
3929 NewBB->addSuccessor(To, OrigCount, OrigMispreds);
3930 NewBB->setExecutionCount(OrigCount);
3931 NewBB->setIsCold(From->isCold());
3933 // Update CFI and BB layout with new intermediate BB
3934 std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
3935 NewBBs.emplace_back(std::move(NewBB));
3936 insertBasicBlocks(From, std::move(NewBBs), true, true,
3937 /*RecomputeLandingPads=*/false);
3938 return NewBBPtr;
3941 void BinaryFunction::deleteConservativeEdges() {
3942 // Our goal is to aggressively remove edges from the CFG that we believe are
3943 // wrong. This is used for instrumentation, where it is safe to remove
3944 // fallthrough edges because we won't reorder blocks.
3945 for (auto I = BasicBlocks.begin(), E = BasicBlocks.end(); I != E; ++I) {
3946 BinaryBasicBlock *BB = *I;
3947 if (BB->succ_size() != 1 || BB->size() == 0)
3948 continue;
3950 auto NextBB = std::next(I);
3951 MCInst *Last = BB->getLastNonPseudoInstr();
3952 // Fallthrough is a landing pad? Delete this edge (as long as we don't
3953 // have a direct jump to it)
3954 if ((*BB->succ_begin())->isLandingPad() && NextBB != E &&
3955 *BB->succ_begin() == *NextBB && Last && !BC.MIB->isBranch(*Last)) {
3956 BB->removeAllSuccessors();
3957 continue;
3960 // Look for suspicious calls at the end of BB where gcc may optimize it and
3961 // remove the jump to the epilogue when it knows the call won't return.
3962 if (!Last || !BC.MIB->isCall(*Last))
3963 continue;
3965 const MCSymbol *CalleeSymbol = BC.MIB->getTargetSymbol(*Last);
3966 if (!CalleeSymbol)
3967 continue;
3969 StringRef CalleeName = CalleeSymbol->getName();
3970 if (CalleeName != "__cxa_throw@PLT" && CalleeName != "_Unwind_Resume@PLT" &&
3971 CalleeName != "__cxa_rethrow@PLT" && CalleeName != "exit@PLT" &&
3972 CalleeName != "abort@PLT")
3973 continue;
3975 BB->removeAllSuccessors();
3979 bool BinaryFunction::isSymbolValidInScope(const SymbolRef &Symbol,
3980 uint64_t SymbolSize) const {
3981 // If this symbol is in a different section from the one where the
3982 // function symbol is, don't consider it as valid.
3983 if (!getOriginSection()->containsAddress(
3984 cantFail(Symbol.getAddress(), "cannot get symbol address")))
3985 return false;
3987 // Some symbols are tolerated inside function bodies, others are not.
3988 // The real function boundaries may not be known at this point.
3989 if (BC.isMarker(Symbol))
3990 return true;
3992 // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3993 // function.
3994 if (SymbolSize == 0 && containsAddress(cantFail(Symbol.getAddress())))
3995 return true;
3997 if (cantFail(Symbol.getType()) != SymbolRef::ST_Unknown)
3998 return false;
4000 if (cantFail(Symbol.getFlags()) & SymbolRef::SF_Global)
4001 return false;
4003 return true;
4006 void BinaryFunction::adjustExecutionCount(uint64_t Count) {
4007 if (getKnownExecutionCount() == 0 || Count == 0)
4008 return;
4010 if (ExecutionCount < Count)
4011 Count = ExecutionCount;
4013 double AdjustmentRatio = ((double)ExecutionCount - Count) / ExecutionCount;
4014 if (AdjustmentRatio < 0.0)
4015 AdjustmentRatio = 0.0;
4017 for (BinaryBasicBlock &BB : blocks())
4018 BB.adjustExecutionCount(AdjustmentRatio);
4020 ExecutionCount -= Count;
4023 BinaryFunction::~BinaryFunction() {
4024 for (BinaryBasicBlock *BB : BasicBlocks)
4025 delete BB;
4026 for (BinaryBasicBlock *BB : DeletedBasicBlocks)
4027 delete BB;
4030 void BinaryFunction::calculateLoopInfo() {
4031 // Discover loops.
4032 BinaryDominatorTree DomTree;
4033 DomTree.recalculate(*this);
4034 BLI.reset(new BinaryLoopInfo());
4035 BLI->analyze(DomTree);
4037 // Traverse discovered loops and add depth and profile information.
4038 std::stack<BinaryLoop *> St;
4039 for (auto I = BLI->begin(), E = BLI->end(); I != E; ++I) {
4040 St.push(*I);
4041 ++BLI->OuterLoops;
4044 while (!St.empty()) {
4045 BinaryLoop *L = St.top();
4046 St.pop();
4047 ++BLI->TotalLoops;
4048 BLI->MaximumDepth = std::max(L->getLoopDepth(), BLI->MaximumDepth);
4050 // Add nested loops in the stack.
4051 for (BinaryLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4052 St.push(*I);
4054 // Skip if no valid profile is found.
4055 if (!hasValidProfile()) {
4056 L->EntryCount = COUNT_NO_PROFILE;
4057 L->ExitCount = COUNT_NO_PROFILE;
4058 L->TotalBackEdgeCount = COUNT_NO_PROFILE;
4059 continue;
4062 // Compute back edge count.
4063 SmallVector<BinaryBasicBlock *, 1> Latches;
4064 L->getLoopLatches(Latches);
4066 for (BinaryBasicBlock *Latch : Latches) {
4067 auto BI = Latch->branch_info_begin();
4068 for (BinaryBasicBlock *Succ : Latch->successors()) {
4069 if (Succ == L->getHeader()) {
4070 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4071 "profile data not found");
4072 L->TotalBackEdgeCount += BI->Count;
4074 ++BI;
4078 // Compute entry count.
4079 L->EntryCount = L->getHeader()->getExecutionCount() - L->TotalBackEdgeCount;
4081 // Compute exit count.
4082 SmallVector<BinaryLoop::Edge, 1> ExitEdges;
4083 L->getExitEdges(ExitEdges);
4084 for (BinaryLoop::Edge &Exit : ExitEdges) {
4085 const BinaryBasicBlock *Exiting = Exit.first;
4086 const BinaryBasicBlock *ExitTarget = Exit.second;
4087 auto BI = Exiting->branch_info_begin();
4088 for (BinaryBasicBlock *Succ : Exiting->successors()) {
4089 if (Succ == ExitTarget) {
4090 assert(BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE &&
4091 "profile data not found");
4092 L->ExitCount += BI->Count;
4094 ++BI;
4100 void BinaryFunction::updateOutputValues(const BOLTLinker &Linker) {
4101 if (!isEmitted()) {
4102 assert(!isInjected() && "injected function should be emitted");
4103 setOutputAddress(getAddress());
4104 setOutputSize(getSize());
4105 return;
4108 const auto SymbolInfo = Linker.lookupSymbolInfo(getSymbol()->getName());
4109 assert(SymbolInfo && "Cannot find function entry symbol");
4110 setOutputAddress(SymbolInfo->Address);
4111 setOutputSize(SymbolInfo->Size);
4113 if (BC.HasRelocations || isInjected()) {
4114 if (hasConstantIsland()) {
4115 const auto DataAddress =
4116 Linker.lookupSymbol(getFunctionConstantIslandLabel()->getName());
4117 assert(DataAddress && "Cannot find function CI symbol");
4118 setOutputDataAddress(*DataAddress);
4119 for (auto It : Islands->Offsets) {
4120 const uint64_t OldOffset = It.first;
4121 BinaryData *BD = BC.getBinaryDataAtAddress(getAddress() + OldOffset);
4122 if (!BD)
4123 continue;
4125 MCSymbol *Symbol = It.second;
4126 const auto NewAddress = Linker.lookupSymbol(Symbol->getName());
4127 assert(NewAddress && "Cannot find CI symbol");
4128 auto &Section = *getCodeSection();
4129 const auto NewOffset = *NewAddress - Section.getOutputAddress();
4130 BD->setOutputLocation(Section, NewOffset);
4133 if (isSplit()) {
4134 for (FunctionFragment &FF : getLayout().getSplitFragments()) {
4135 ErrorOr<BinarySection &> ColdSection =
4136 getCodeSection(FF.getFragmentNum());
4137 // If fragment is empty, cold section might not exist
4138 if (FF.empty() && ColdSection.getError())
4139 continue;
4141 const MCSymbol *ColdStartSymbol = getSymbol(FF.getFragmentNum());
4142 // If fragment is empty, symbol might have not been emitted
4143 if (FF.empty() && (!ColdStartSymbol || !ColdStartSymbol->isDefined()) &&
4144 !hasConstantIsland())
4145 continue;
4146 assert(ColdStartSymbol && ColdStartSymbol->isDefined() &&
4147 "split function should have defined cold symbol");
4148 const auto ColdStartSymbolInfo =
4149 Linker.lookupSymbolInfo(ColdStartSymbol->getName());
4150 assert(ColdStartSymbolInfo && "Cannot find cold start symbol");
4151 FF.setAddress(ColdStartSymbolInfo->Address);
4152 FF.setImageSize(ColdStartSymbolInfo->Size);
4153 if (hasConstantIsland()) {
4154 const auto DataAddress = Linker.lookupSymbol(
4155 getFunctionColdConstantIslandLabel()->getName());
4156 assert(DataAddress && "Cannot find cold CI symbol");
4157 setOutputColdDataAddress(*DataAddress);
4163 // Update basic block output ranges for the debug info, if we have
4164 // secondary entry points in the symbol table to update or if writing BAT.
4165 if (!requiresAddressMap())
4166 return;
4168 // AArch64 may have functions that only contains a constant island (no code).
4169 if (getLayout().block_empty())
4170 return;
4172 for (FunctionFragment &FF : getLayout().fragments()) {
4173 if (FF.empty())
4174 continue;
4176 const uint64_t FragmentBaseAddress =
4177 getCodeSection(isSimple() ? FF.getFragmentNum() : FragmentNum::main())
4178 ->getOutputAddress();
4180 BinaryBasicBlock *PrevBB = nullptr;
4181 for (BinaryBasicBlock *const BB : FF) {
4182 assert(BB->getLabel()->isDefined() && "symbol should be defined");
4183 if (!BC.HasRelocations) {
4184 if (BB->isSplit())
4185 assert(FragmentBaseAddress == FF.getAddress());
4186 else
4187 assert(FragmentBaseAddress == getOutputAddress());
4188 (void)FragmentBaseAddress;
4191 // Injected functions likely will fail lookup, as they have no
4192 // input range. Just assign the BB the output address of the
4193 // function.
4194 auto MaybeBBAddress = BC.getIOAddressMap().lookup(BB->getLabel());
4195 const uint64_t BBAddress = MaybeBBAddress ? *MaybeBBAddress
4196 : BB->isSplit() ? FF.getAddress()
4197 : getOutputAddress();
4198 BB->setOutputStartAddress(BBAddress);
4200 if (PrevBB) {
4201 assert(PrevBB->getOutputAddressRange().first <= BBAddress &&
4202 "Bad output address for basic block.");
4203 assert((PrevBB->getOutputAddressRange().first != BBAddress ||
4204 !hasInstructions() || !PrevBB->getNumNonPseudos()) &&
4205 "Bad output address for basic block.");
4206 PrevBB->setOutputEndAddress(BBAddress);
4208 PrevBB = BB;
4211 PrevBB->setOutputEndAddress(PrevBB->isSplit()
4212 ? FF.getAddress() + FF.getImageSize()
4213 : getOutputAddress() + getOutputSize());
4216 // Reset output addresses for deleted blocks.
4217 for (BinaryBasicBlock *BB : DeletedBasicBlocks) {
4218 BB->setOutputStartAddress(0);
4219 BB->setOutputEndAddress(0);
4223 DebugAddressRangesVector BinaryFunction::getOutputAddressRanges() const {
4224 DebugAddressRangesVector OutputRanges;
4226 if (isFolded())
4227 return OutputRanges;
4229 if (IsFragment)
4230 return OutputRanges;
4232 OutputRanges.emplace_back(getOutputAddress(),
4233 getOutputAddress() + getOutputSize());
4234 if (isSplit()) {
4235 assert(isEmitted() && "split function should be emitted");
4236 for (const FunctionFragment &FF : getLayout().getSplitFragments())
4237 OutputRanges.emplace_back(FF.getAddress(),
4238 FF.getAddress() + FF.getImageSize());
4241 if (isSimple())
4242 return OutputRanges;
4244 for (BinaryFunction *Frag : Fragments) {
4245 assert(!Frag->isSimple() &&
4246 "fragment of non-simple function should also be non-simple");
4247 OutputRanges.emplace_back(Frag->getOutputAddress(),
4248 Frag->getOutputAddress() + Frag->getOutputSize());
4251 return OutputRanges;
4254 uint64_t BinaryFunction::translateInputToOutputAddress(uint64_t Address) const {
4255 if (isFolded())
4256 return 0;
4258 // If the function hasn't changed return the same address.
4259 if (!isEmitted())
4260 return Address;
4262 if (Address < getAddress())
4263 return 0;
4265 // Check if the address is associated with an instruction that is tracked
4266 // by address translation.
4267 if (auto OutputAddress = BC.getIOAddressMap().lookup(Address))
4268 return *OutputAddress;
4270 // FIXME: #18950828 - we rely on relative offsets inside basic blocks to stay
4271 // intact. Instead we can use pseudo instructions and/or annotations.
4272 const uint64_t Offset = Address - getAddress();
4273 const BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4274 if (!BB) {
4275 // Special case for address immediately past the end of the function.
4276 if (Offset == getSize())
4277 return getOutputAddress() + getOutputSize();
4279 return 0;
4282 return std::min(BB->getOutputAddressRange().first + Offset - BB->getOffset(),
4283 BB->getOutputAddressRange().second);
4286 DebugAddressRangesVector
4287 BinaryFunction::translateInputToOutputRange(DebugAddressRange InRange) const {
4288 DebugAddressRangesVector OutRanges;
4290 // The function was removed from the output. Return an empty range.
4291 if (isFolded())
4292 return OutRanges;
4294 // If the function hasn't changed return the same range.
4295 if (!isEmitted()) {
4296 OutRanges.emplace_back(InRange);
4297 return OutRanges;
4300 if (!containsAddress(InRange.LowPC))
4301 return OutRanges;
4303 // Special case of an empty range [X, X). Some tools expect X to be updated.
4304 if (InRange.LowPC == InRange.HighPC) {
4305 if (uint64_t NewPC = translateInputToOutputAddress(InRange.LowPC))
4306 OutRanges.push_back(DebugAddressRange{NewPC, NewPC});
4307 return OutRanges;
4310 uint64_t InputOffset = InRange.LowPC - getAddress();
4311 const uint64_t InputEndOffset =
4312 std::min(InRange.HighPC - getAddress(), getSize());
4314 auto BBI = llvm::upper_bound(BasicBlockOffsets,
4315 BasicBlockOffset(InputOffset, nullptr),
4316 CompareBasicBlockOffsets());
4317 assert(BBI != BasicBlockOffsets.begin());
4319 // Iterate over blocks in the input order using BasicBlockOffsets.
4320 for (--BBI; InputOffset < InputEndOffset && BBI != BasicBlockOffsets.end();
4321 InputOffset = BBI->second->getEndOffset(), ++BBI) {
4322 const BinaryBasicBlock &BB = *BBI->second;
4323 if (InputOffset < BB.getOffset() || InputOffset >= BB.getEndOffset()) {
4324 LLVM_DEBUG(
4325 dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4326 << *this << " : [0x" << Twine::utohexstr(InRange.LowPC)
4327 << ", 0x" << Twine::utohexstr(InRange.HighPC) << "]\n");
4328 break;
4331 // Skip the block if it wasn't emitted.
4332 if (!BB.getOutputAddressRange().first)
4333 continue;
4335 // Find output address for an instruction with an offset greater or equal
4336 // to /p Offset. The output address should fall within the same basic
4337 // block boundaries.
4338 auto translateBlockOffset = [&](const uint64_t Offset) {
4339 const uint64_t OutAddress = BB.getOutputAddressRange().first + Offset;
4340 return std::min(OutAddress, BB.getOutputAddressRange().second);
4343 uint64_t OutLowPC = BB.getOutputAddressRange().first;
4344 if (InputOffset > BB.getOffset())
4345 OutLowPC = translateBlockOffset(InputOffset - BB.getOffset());
4347 uint64_t OutHighPC = BB.getOutputAddressRange().second;
4348 if (InputEndOffset < BB.getEndOffset()) {
4349 assert(InputEndOffset >= BB.getOffset());
4350 OutHighPC = translateBlockOffset(InputEndOffset - BB.getOffset());
4353 // Check if we can expand the last translated range.
4354 if (!OutRanges.empty() && OutRanges.back().HighPC == OutLowPC)
4355 OutRanges.back().HighPC = std::max(OutRanges.back().HighPC, OutHighPC);
4356 else
4357 OutRanges.emplace_back(OutLowPC, std::max(OutLowPC, OutHighPC));
4360 LLVM_DEBUG({
4361 dbgs() << "BOLT-DEBUG: translated address range " << InRange << " -> ";
4362 for (const DebugAddressRange &R : OutRanges)
4363 dbgs() << R << ' ';
4364 dbgs() << '\n';
4367 return OutRanges;
4370 MCInst *BinaryFunction::getInstructionAtOffset(uint64_t Offset) {
4371 if (CurrentState == State::Disassembled) {
4372 auto II = Instructions.find(Offset);
4373 return (II == Instructions.end()) ? nullptr : &II->second;
4374 } else if (CurrentState == State::CFG) {
4375 BinaryBasicBlock *BB = getBasicBlockContainingOffset(Offset);
4376 if (!BB)
4377 return nullptr;
4379 for (MCInst &Inst : *BB) {
4380 constexpr uint32_t InvalidOffset = std::numeric_limits<uint32_t>::max();
4381 if (Offset == BC.MIB->getOffsetWithDefault(Inst, InvalidOffset))
4382 return &Inst;
4385 if (MCInst *LastInstr = BB->getLastNonPseudoInstr()) {
4386 if (std::optional<uint32_t> Size = BC.MIB->getSize(*LastInstr)) {
4387 if (BB->getEndOffset() - Offset == Size) {
4388 return LastInstr;
4393 return nullptr;
4394 } else {
4395 llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4399 void BinaryFunction::printLoopInfo(raw_ostream &OS) const {
4400 if (!opts::shouldPrint(*this))
4401 return;
4403 OS << "Loop Info for Function \"" << *this << "\"";
4404 if (hasValidProfile())
4405 OS << " (count: " << getExecutionCount() << ")";
4406 OS << "\n";
4408 std::stack<BinaryLoop *> St;
4409 for (BinaryLoop *L : *BLI)
4410 St.push(L);
4411 while (!St.empty()) {
4412 BinaryLoop *L = St.top();
4413 St.pop();
4415 for (BinaryLoop *Inner : *L)
4416 St.push(Inner);
4418 if (!hasValidProfile())
4419 continue;
4421 OS << (L->getLoopDepth() > 1 ? "Nested" : "Outer")
4422 << " loop header: " << L->getHeader()->getName();
4423 OS << "\n";
4424 OS << "Loop basic blocks: ";
4425 ListSeparator LS;
4426 for (BinaryBasicBlock *BB : L->blocks())
4427 OS << LS << BB->getName();
4428 OS << "\n";
4429 if (hasValidProfile()) {
4430 OS << "Total back edge count: " << L->TotalBackEdgeCount << "\n";
4431 OS << "Loop entry count: " << L->EntryCount << "\n";
4432 OS << "Loop exit count: " << L->ExitCount << "\n";
4433 if (L->EntryCount > 0) {
4434 OS << "Average iters per entry: "
4435 << format("%.4lf", (double)L->TotalBackEdgeCount / L->EntryCount)
4436 << "\n";
4439 OS << "----\n";
4442 OS << "Total number of loops: " << BLI->TotalLoops << "\n";
4443 OS << "Number of outer loops: " << BLI->OuterLoops << "\n";
4444 OS << "Maximum nested loop depth: " << BLI->MaximumDepth << "\n\n";
4447 bool BinaryFunction::isAArch64Veneer() const {
4448 if (empty() || hasIslandsInfo())
4449 return false;
4451 BinaryBasicBlock &BB = **BasicBlocks.begin();
4452 for (MCInst &Inst : BB)
4453 if (!BC.MIB->hasAnnotation(Inst, "AArch64Veneer"))
4454 return false;
4456 for (auto I = BasicBlocks.begin() + 1, E = BasicBlocks.end(); I != E; ++I) {
4457 for (MCInst &Inst : **I)
4458 if (!BC.MIB->isNoop(Inst))
4459 return false;
4462 return true;
4465 void BinaryFunction::addRelocation(uint64_t Address, MCSymbol *Symbol,
4466 uint64_t RelType, uint64_t Addend,
4467 uint64_t Value) {
4468 assert(Address >= getAddress() && Address < getAddress() + getMaxSize() &&
4469 "address is outside of the function");
4470 uint64_t Offset = Address - getAddress();
4471 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: addRelocation in "
4472 << formatv("{0}@{1:x} against {2}\n", *this, Offset,
4473 (Symbol ? Symbol->getName() : "<undef>")));
4474 bool IsCI = BC.isAArch64() && isInConstantIsland(Address);
4475 std::map<uint64_t, Relocation> &Rels =
4476 IsCI ? Islands->Relocations : Relocations;
4477 if (BC.MIB->shouldRecordCodeRelocation(RelType))
4478 Rels[Offset] = Relocation{Offset, Symbol, RelType, Addend, Value};
4481 } // namespace bolt
4482 } // namespace llvm