1 //===- bolt/Core/BinaryFunction.cpp - Low-level function ------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
49 #define DEBUG_TYPE "bolt"
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(
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 "
73 cl::Hidden
, cl::cat(BoltCategory
));
75 static cl::opt
<bool> DotToolTipCode(
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)"),
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 "
98 cl::cat(BoltOptCategory
));
100 static cl::opt
<bool> NoScan(
103 "do not scan cold functions for external references (may result in "
105 cl::Hidden
, cl::cat(BoltOptCategory
));
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",
115 "print output address range for each basic block in the function when"
116 "BinaryFunction::print is called"),
117 cl::Hidden
, cl::cat(BoltOptCategory
));
120 PrintDynoStats("dyno-stats",
121 cl::desc("print execution info based on profile"),
122 cl::cat(BoltCategory
));
125 PrintDynoStatsOnly("print-dyno-stats-only",
126 cl::desc("while printing functions output dyno-stats and skip instructions"),
129 cl::cat(BoltCategory
));
131 static cl::list
<std::string
>
132 PrintOnly("print-only",
134 cl::desc("list of functions to print"),
135 cl::value_desc("func1,func2,func3,..."),
137 cl::cat(BoltCategory
));
140 TimeBuild("time-build",
141 cl::desc("print time spent constructing binary functions"),
142 cl::Hidden
, cl::cat(BoltCategory
));
145 TrapOnAVX512("trap-avx512",
146 cl::desc("in relocation mode trap upon entry to any function that uses "
147 "AVX-512 instructions"),
151 cl::cat(BoltCategory
));
153 bool shouldPrint(const BinaryFunction
&Function
) {
154 if (Function
.isIgnored())
157 if (PrintOnly
.empty())
160 for (std::string
&Name
: opts::PrintOnly
) {
161 if (Function
.hasNameRegex(Name
)) {
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.
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
)
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
) {
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
) {
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;
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
,
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
);
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());
270 BinaryFunction::getBasicBlockContainingOffset(uint64_t Offset
) {
274 if (BasicBlockOffsets
.empty())
278 * This is commented out because it makes BOLT too slow.
279 * assert(std::is_sorted(BasicBlockOffsets.begin(),
280 * BasicBlockOffsets.end(),
281 * CompareBasicBlockOffsets())));
284 llvm::upper_bound(BasicBlockOffsets
, BasicBlockOffset(Offset
, nullptr),
285 CompareBasicBlockOffsets());
286 assert(I
!= BasicBlockOffsets
.begin() && "first basic block not at offset 0");
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())
298 // Add all entries and landing pads as roots.
299 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
300 if (isEntryPoint(*BB
) || BB
->isLandingPad()) {
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
)) {
317 // Determine reachable BBs from the entry point
318 while (!Stack
.empty()) {
319 BinaryBasicBlock
*BB
= Stack
.top();
321 for (BinaryBasicBlock
*Succ
: BB
->successors()) {
324 Succ
->markValid(true);
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
;
337 for (BinaryBasicBlock
*const BB
: BasicBlocks
) {
338 if (!BB
->isValid()) {
339 assert(!isEntryPoint(*BB
) && "all entry blocks must be valid");
340 InvalidBBs
.insert(BB
);
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
);
356 NewBasicBlocks
.push_back(BB
);
359 BasicBlocks
= std::move(NewBasicBlocks
);
361 assert(BasicBlocks
.size() == Layout
.block_size());
363 // Update CFG state if needed
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
);
378 if (CalleeBF
->isInjected())
381 if (hasValidIndex() && CalleeBF
->hasValidIndex()) {
382 return getIndex() < CalleeBF
->getIndex();
383 } else if (hasValidIndex() && !CalleeBF
->hasValidIndex()) {
385 } else if (!hasValidIndex() && CalleeBF
->hasValidIndex()) {
388 return getAddress() < CalleeBF
->getAddress();
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))
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
) {
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();
446 OS
<< "\n IsFragment : true";
448 OS
<< "\n FoldedInto : " << *getFoldedIntoFunction();
449 for (BinaryFunction
*ParentFragment
: ParentFragments
)
450 OS
<< "\n Parent : " << *ParentFragment
;
451 if (!Fragments
.empty()) {
452 OS
<< "\n Fragments : ";
454 for (BinaryFunction
*Frag
: Fragments
)
458 OS
<< "\n Hash : " << Twine::utohexstr(computeHash());
459 if (isMultiEntry()) {
460 OS
<< "\n Secondary Entry Points : ";
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 : ";
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()) {
483 DynoStats dynoStats
= getDynoStats(*this);
489 if (opts::PrintDynoStatsOnly
|| !BC
.InstPrinter
)
492 // Offset of the instruction in function.
495 if (BasicBlocks
.empty() && !Instructions
.empty()) {
496 // Print before CFG was built.
497 for (const std::pair
<const uint32_t, MCInst
> &II
: Instructions
) {
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()) {
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';
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';
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())
550 if (!BB
->pred_empty()) {
551 OS
<< " Predecessors: ";
553 for (BinaryBasicBlock
*Pred
: BB
->predecessors())
554 OS
<< LS
<< Pred
->getName();
557 if (!BB
->throw_empty()) {
560 for (BinaryBasicBlock
*Throw
: BB
->throwers())
561 OS
<< LS
<< Throw
->getName();
565 Offset
= alignTo(Offset
, BB
->getAlignment());
567 // Note: offsets are imprecise since this is happening prior to
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
];
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
<< ")";
599 if (!BB
->lp_empty()) {
600 OS
<< " Landing Pads: ";
602 for (BinaryBasicBlock
*LP
: BB
->landing_pads()) {
603 OS
<< LS
<< LP
->getName();
604 if (ExecutionCount
!= COUNT_NO_PROFILE
) {
605 OS
<< " (count: " << LP
->getExecutionCount() << ")";
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';
622 // Dump new exception ranges for the function.
623 if (!CallSites
.empty()) {
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 : ";
633 OS
<< ", action : " << CSI
.Action
<< '\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
]);
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
);
661 if (FrameInstructions
.empty())
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
<< ")";
679 static std::string
mutateDWARFExpressionTargetReg(const MCCFIInstruction
&Instr
,
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");
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);
693 decodeULEB128(Start
, &Size
, End
);
694 assert(Size
> 0 && "Invalid reg encoding for DWARF expression CFI");
696 raw_svector_ostream
OSE(Tmp
);
697 encodeULEB128(NewReg
, OSE
);
698 return Twine(ExprBytes
.slice(0, 1))
700 .concat(ExprBytes
.drop_front(1 + Size
))
704 void BinaryFunction::mutateCFIRegisterFor(const MCInst
&Instr
,
706 const MCCFIInstruction
*OldCFI
= getCFIFor(Instr
);
707 assert(OldCFI
&& "invalid CFI instr");
708 switch (OldCFI
->getOperation()) {
710 llvm_unreachable("Unexpected instruction");
711 case MCCFIInstruction::OpDefCfa
:
712 setCFIFor(Instr
, MCCFIInstruction::cfiDefCfa(nullptr, NewReg
,
713 OldCFI
->getOffset()));
715 case MCCFIInstruction::OpDefCfaRegister
:
716 setCFIFor(Instr
, MCCFIInstruction::createDefCfaRegister(nullptr, NewReg
));
718 case MCCFIInstruction::OpOffset
:
719 setCFIFor(Instr
, MCCFIInstruction::createOffset(nullptr, NewReg
,
720 OldCFI
->getOffset()));
722 case MCCFIInstruction::OpRegister
:
723 setCFIFor(Instr
, MCCFIInstruction::createRegister(nullptr, NewReg
,
724 OldCFI
->getRegister2()));
726 case MCCFIInstruction::OpSameValue
:
727 setCFIFor(Instr
, MCCFIInstruction::createSameValue(nullptr, NewReg
));
729 case MCCFIInstruction::OpEscape
:
731 MCCFIInstruction::createEscape(
733 StringRef(mutateDWARFExpressionTargetReg(*OldCFI
, NewReg
))));
735 case MCCFIInstruction::OpRestore
:
736 setCFIFor(Instr
, MCCFIInstruction::createRestore(nullptr, NewReg
));
738 case MCCFIInstruction::OpUndefined
:
739 setCFIFor(Instr
, MCCFIInstruction::createUndefined(nullptr, NewReg
));
744 const MCCFIInstruction
*BinaryFunction::mutateCFIOffsetFor(const MCInst
&Instr
,
746 const MCCFIInstruction
*OldCFI
= getCFIFor(Instr
);
747 assert(OldCFI
&& "invalid CFI instr");
748 switch (OldCFI
->getOperation()) {
750 llvm_unreachable("Unexpected instruction");
751 case MCCFIInstruction::OpDefCfaOffset
:
752 setCFIFor(Instr
, MCCFIInstruction::cfiDefCfaOffset(nullptr, NewOffset
));
754 case MCCFIInstruction::OpAdjustCfaOffset
:
756 MCCFIInstruction::createAdjustCfaOffset(nullptr, NewOffset
));
758 case MCCFIInstruction::OpDefCfa
:
759 setCFIFor(Instr
, MCCFIInstruction::cfiDefCfa(nullptr, OldCFI
->getRegister(),
762 case MCCFIInstruction::OpOffset
:
763 setCFIFor(Instr
, MCCFIInstruction::createOffset(
764 nullptr, OldCFI
->getRegister(), NewOffset
));
767 return getCFIFor(Instr
);
771 BinaryFunction::processIndirectBranch(MCInst
&Instruction
, unsigned Size
,
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.
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
;
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
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()) {
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
)
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
;
827 for (std::pair
<const uint32_t, MCSymbol
*> &Elmt
: Labels
) {
828 if (Elmt
.second
== Sym
) {
829 PCRelAddr
= Elmt
.first
+ getAddress();
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();
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).
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
;
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
);
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 "
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
);
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
)
908 TargetAddress
= *Value
;
912 // Check if there's already a jump table registered at this address.
913 MemoryContentsType MemType
;
914 if (JumpTable
*JT
= BC
.getJumpTableContainingAddress(ArrayStart
)) {
916 case JumpTable::JTT_NORMAL
:
917 MemType
= MemoryContentsType::POSSIBLE_JUMP_TABLE
;
919 case JumpTable::JTT_PIC
:
920 MemType
= MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE
;
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
;
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
);
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())
965 // For AArch64, check if this address is part of a constant island.
966 if (BC
.isAArch64()) {
967 if (MCSymbol
*IslandSym
= getOrCreateIslandAccess(Address
))
971 MCSymbol
*Label
= BC
.Ctx
->createNamedTempSymbol();
972 Labels
[Offset
] = 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 {
1000 if (!llvm::is_contained(Islands
->DataOffsets
, Offset
))
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();
1013 auto Iter
= Islands
->DataOffsets
.upper_bound(Offset
);
1014 if (Iter
!= Islands
->DataOffsets
.end())
1017 for (uint64_t I
= Offset
; I
< EndOfCode
; ++I
)
1018 if (FunctionData
[I
] != 0)
1024 void BinaryFunction::handlePCRelOperand(MCInst
&Instruction
, uint64_t Address
,
1027 uint64_t TargetAddress
= 0;
1028 if (!MIB
->evaluateMemOperandTarget(Instruction
, TargetAddress
, Address
,
1030 errs() << "BOLT-ERROR: PC-relative operand can't be evaluated:\n";
1031 BC
.InstPrinter
->printInst(&Instruction
, 0, "", *BC
.STI
, errs());
1033 Instruction
.dump_pretty(errs(), BC
.InstPrinter
.get());
1035 errs() << "BOLT-ERROR: cannot handle PC-relative operand at 0x"
1036 << Twine::utohexstr(Address
) << ". Skipping function " << *this
1038 if (BC
.HasRelocations
)
1043 if (TargetAddress
== 0 && opts::Verbosity
>= 1) {
1044 outs() << "BOLT-INFO: PC-relative operand is zero in function " << *this
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
,
1062 uint64_t TargetAddress
,
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.
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";
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
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
,
1107 uint64_t IndirectTarget
= 0;
1108 IndirectBranchType Result
=
1109 processIndirectBranch(Instruction
, Size
, Offset
, IndirectTarget
);
1112 llvm_unreachable("unexpected result");
1113 case IndirectBranchType::POSSIBLE_TAIL_CALL
: {
1114 bool Result
= MIB
->convertJmpToTailCall(Instruction
);
1119 case IndirectBranchType::POSSIBLE_JUMP_TABLE
:
1120 case IndirectBranchType::POSSIBLE_PIC_JUMP_TABLE
:
1121 if (opts::JumpTables
== JTS_NONE
)
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());
1132 MIB
->convertJmpToTailCall(Instruction
);
1133 BC
.addInterproceduralReference(this, IndirectTarget
);
1137 case IndirectBranchType::UNKNOWN
:
1138 // Keep processing. We'll do more checks and fixes in
1139 // postProcessIndirectBranches().
1140 UnknownIndirectBranchOffsets
.emplace(Offset
);
1145 void BinaryFunction::handleAArch64IndirectCall(MCInst
&Instruction
,
1146 const uint64_t Offset
) {
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
);
1155 MIB
->addAnnotation(Instruction
, "AArch64Veneer", true);
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
,
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");
1179 BC
.SymbolicDisAsm
->setSymbolizer(MIB
->createTargetSymbolizer(*this));
1181 // Insert a label at the beginning of the function. This will be our first
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
) {
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
;
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
))
1211 errs() << "BOLT-WARNING: unable to disassemble instruction at offset 0x"
1212 << Twine::utohexstr(Offset
) << " (address 0x"
1213 << Twine::utohexstr(AbsoluteInstrAddr
) << ") in function " << *this
1215 // Some AVX-512 instructions could not be disassembled at all.
1216 if (BC
.HasRelocations
&& opts::TrapOnAVX512
&& BC
.isX86()) {
1218 BC
.TrappedFunctions
.push_back(this);
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
);
1237 // Special handling for AVX-512 instructions.
1238 if (MIB
->hasEVEXEncoding(Instruction
)) {
1239 if (BC
.HasRelocations
&& opts::TrapOnAVX512
) {
1241 BC
.TrappedFunctions
.push_back(this);
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';
1255 if (MIB
->isBranch(Instruction
) || MIB
->isCall(Instruction
)) {
1256 uint64_t TargetAddress
= 0;
1257 if (MIB
->evaluateBranch(Instruction
, AbsoluteInstrAddr
, Size
,
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
)) {
1270 if (BinaryFunction
*TargetFunc
=
1271 BC
.getBinaryFunctionContainingAddress(TargetAddress
))
1272 TargetFunc
->setIgnored();
1275 if (IsCall
&& containsAddress(TargetAddress
)) {
1276 if (TargetAddress
== getAddress()) {
1278 TargetSymbol
= getSymbol();
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;
1285 errs() << "BOLT-WARNING: internal call detected at 0x"
1286 << Twine::utohexstr(AbsoluteInstrAddr
) << " in function "
1287 << *this << ". Skipping.\n";
1293 if (!TargetSymbol
) {
1294 // Create either local label or external symbol.
1295 if (containsAddress(TargetAddress
)) {
1296 TargetSymbol
= getOrCreateLocalLabel(TargetAddress
);
1298 if (TargetAddress
== getAddress() + getSize() &&
1299 TargetAddress
< getAddress() + getMaxSize() &&
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
);
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
);
1321 // Add taken branch info.
1322 TakenBranches
.emplace_back(Offset
, TargetAddress
- getAddress());
1324 BC
.MIB
->replaceBranchTarget(Instruction
, TargetSymbol
, &*Ctx
);
1327 if (IsCondBranch
&& IsCall
)
1328 MIB
->setConditionalTailCall(Instruction
, TargetAddress
);
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
);
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
);
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
,
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.
1375 if (!BC
.isRISCV() && MIB
->hasPCRelOperand(Instruction
) && !UsedReloc
)
1376 handlePCRelOperand(Instruction
, AbsoluteInstrAddr
, Size
);
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
);
1415 clearList(Instructions
);
1419 updateState(State::Disassembled
);
1424 bool BinaryFunction::scanExternalRefs() {
1425 bool Success
= true;
1426 bool DisassemblyFailed
= false;
1428 // Ignore pseudo functions.
1433 clearList(Relocations
);
1434 clearList(ExternallyReferencedOffsets
);
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
;
1464 const uint64_t AbsoluteInstrAddr
= getAddress() + Offset
;
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 "
1476 DisassemblyFailed
= true;
1480 // Return true if we can skip handling the Target function reference.
1481 auto ignoreFunctionRef
= [&](const BinaryFunction
&Target
) {
1482 if (&Target
== this)
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
))
1494 // Return true if we can ignore reference to the symbol.
1495 auto ignoreReference
= [&](const MCSymbol
*TargetSymbol
) {
1499 if (BC
.forceSymbolRelocations(TargetSymbol
->getName()))
1502 BinaryFunction
*TargetFunction
= BC
.getFunctionForSymbol(TargetSymbol
);
1503 if (!TargetFunction
)
1506 return ignoreFunctionRef(*TargetFunction
);
1509 // Handle calls and branches separately as symbolization doesn't work for
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
,
1517 // Create an entry point at reference address if needed.
1518 BinaryFunction
*TargetFunction
=
1519 BC
.getBinaryFunctionContainingAddress(TargetAddress
);
1521 if (!TargetFunction
|| ignoreFunctionRef(*TargetFunction
))
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
1533 if (!BC
.HasRelocations
)
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.
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
);
1558 if (ignoreReference(Rel
->Symbol
))
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.
1568 Rel
->Offset
+= getAddress() - getOriginSection()->getAddress() + Offset
;
1569 FunctionRelocations
.push_back(*Rel
);
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
)
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';
1606 void BinaryFunction::postProcessEntryPoints() {
1610 for (auto &KV
: Labels
) {
1611 MCSymbol
*Label
= KV
.second
;
1612 if (!getSecondaryEntryPointSymbol(Label
))
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
)
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
))
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())
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
)
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 "
1654 const uint64_t BDSize
=
1655 BC
.getBinaryDataAtAddress(JT
.getAddress())->getSize();
1657 BC
.setBinaryDataSize(JT
.getAddress(), JT
.getSize());
1659 assert(BDSize
>= JT
.getSize() &&
1660 "jump table cannot be larger than the containing object");
1662 if (!JT
.Entries
.empty())
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
);
1678 // Create a local label for targets that cannot be reached by other
1679 // fragments. Otherwise, create a secondary entry point in the target
1681 BinaryFunction
*TargetBF
=
1682 BC
.getBinaryFunctionContainingAddress(EntryAddress
);
1684 if (HasOneParent
&& TargetBF
== this) {
1685 Label
= getOrCreateLocalLabel(EntryAddress
, true);
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
))
1725 // Conservatively populate all possible destinations for unknown indirect
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())
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())
1756 // Ignore constant islands
1757 if (isInConstantIsland(Destination
+ getAddress()))
1760 if (BinaryBasicBlock
*BB
= getBasicBlockAtOffset(Destination
)) {
1761 // Check if the externally referenced offset is a recognized jump table
1763 if (JTTargets
.contains(BB
->getLabel()))
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();
1774 errs() << "BOLT-WARNING: unknown data to code reference to offset "
1775 << Twine::utohexstr(Destination
) << " in " << *this << "\n";
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
))
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
);
1815 if (opts::StrictMode
&& !hasInternalReference()) {
1816 BC
.MIB
->convertJmpToTailCall(Instr
);
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
;
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)
1835 if (!opts::StrictMode
)
1838 if (BC
.MIB
->isTailCall(Instr
)) {
1839 BC
.MIB
->convertTailCallToJmp(Instr
);
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');
1858 addUnknownControlFlow(BB
);
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
);
1869 BC
.MIB
->convertJmpToTailCall(Instr
);
1870 BB
.removeAllSuccessors();
1874 if (opts::Verbosity
>= 2) {
1875 outs() << "BOLT-INFO: rejected potential indirect tail call in "
1876 << "function " << *this << " in basic block " << BB
.getName()
1878 LLVM_DEBUG(BC
.printInstructions(dbgs(), BB
.begin(), BB
.end(),
1879 BB
.getOffset(), this, true));
1882 if (!opts::StrictMode
)
1885 addUnknownControlFlow(BB
);
1889 if (HasInternalLabelReference
)
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 "
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
1909 if (!opts::StrictMode
&& hasInternalReference()) {
1910 if (!validateExternallyReferencedOffsets())
1914 if (HasUnknownControlFlow
&& !BC
.HasRelocations
)
1920 void BinaryFunction::recomputeLandingPads() {
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
))
1934 const std::optional
<MCPlus::MCLandingPad
> EHInfo
=
1935 BC
.MIB
->getEHInfo(Instr
);
1936 if (!EHInfo
|| !EHInfo
->first
)
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
) {
1953 assert(!BC
.HasRelocations
&&
1954 "cannot process file with non-simple function in relocs mode");
1958 if (CurrentState
!= State::Disassembled
)
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
);
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(),
2004 if (!BC
.MIB
->isPseudo(*RII
) && !BC
.MIB
->isNoop(*RII
)) {
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();
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
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
);
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.
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
);
2081 CFIOffset
= NextInstr
->first
;
2083 CFIOffset
= getSize();
2085 // Note: this potentially invalidates instruction pointers/iterators.
2086 addCFIPlaceholders(CFIOffset
, InsertBB
);
2094 if (BasicBlocks
.empty()) {
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
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
) {
2114 errs() << "BOLT-ERROR: cannot find BB containing the branch.\n";
2116 errs() << "BOLT-ERROR: cannot find BB containing branch destination.\n";
2117 BC
.exitWithBugReport("disassembly failed - inconsistent branch found.",
2121 FromBB
->addSuccessor(ToBB
);
2124 // Add fall-through branches.
2126 bool IsPrevFT
= false; // Is previous block a fall-through.
2127 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
2129 PrevBB
->addSuccessor(BB
);
2137 MCInst
*LastInstr
= BB
->getLastNonPseudoInstr();
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
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
);
2159 // Assign landing pads and throwers info.
2160 recomputeLandingPads();
2162 // Assign CFI information to each BB entry.
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.
2170 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
2171 Layout
.addBasicBlock(BB
);
2173 PrevBB
->setEndOffset(BB
->getOffset());
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 "
2199 // In relocation mode we want to keep processing the function but avoid
2204 clearList(ExternallyReferencedOffsets
);
2205 clearList(UnknownIndirectBranchOffsets
);
2210 void BinaryFunction::postProcessCFG() {
2211 if (isSimple() && !BasicBlocks
.empty()) {
2212 // Convert conditional tail call branches to conditional branches that jump
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())
2243 for (const BinaryBasicBlock
&BB
: blocks()) {
2244 auto II
= BB
.getMacroOpFusionPair();
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)
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
)
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();
2287 std::optional
<uint64_t> TargetAddressOrNone
=
2288 BC
.MIB
->getConditionalTailCall(*CTCInstr
);
2289 if (!TargetAddressOrNone
)
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(),
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()) {
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
)
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.
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
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
);
2406 switch (CFI
->getOperation()) {
2407 case MCCFIInstruction::OpRememberState
:
2408 StateStack
.push(EffectiveState
);
2409 EffectiveState
= State
;
2411 case MCCFIInstruction::OpRestoreState
:
2412 assert(!StateStack
.empty() && "corrupt CFI stack");
2413 EffectiveState
= StateStack
.top();
2416 case MCCFIInstruction::OpGnuArgsSize
:
2417 // OpGnuArgsSize CFIs do not affect the CFI state.
2420 // Any other CFI updates the state.
2421 EffectiveState
= State
;
2427 assert(StateStack
.empty() && "corrupt CFI stack");
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.
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
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();
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
;
2471 case MCCFIInstruction::OpDefCfaRegister
:
2472 CFAReg
= Instr
.getRegister();
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
)
2482 case MCCFIInstruction::OpDefCfaOffset
:
2483 CFAOffset
= Instr
.getOffset();
2486 case MCCFIInstruction::OpDefCfa
:
2487 CFAReg
= Instr
.getRegister();
2488 CFAOffset
= Instr
.getOffset();
2491 case MCCFIInstruction::OpEscape
: {
2492 std::optional
<uint8_t> Reg
=
2493 readDWARFExpressionTargetReg(Instr
.getValues());
2494 // Handle DW_CFA_def_cfa_expression
2496 CFARule
= RuleNumber
;
2499 RegRule
[*Reg
] = RuleNumber
;
2502 case MCCFIInstruction::OpAdjustCfaOffset
:
2503 case MCCFIInstruction::OpWindowSave
:
2504 case MCCFIInstruction::OpNegateRAState
:
2505 case MCCFIInstruction::OpLLVMDefAspaceCfa
:
2506 llvm_unreachable("unsupported CFI opcode");
2508 case MCCFIInstruction::OpRememberState
:
2509 case MCCFIInstruction::OpRestoreState
:
2510 case MCCFIInstruction::OpGnuArgsSize
:
2511 // do not affect CFI state
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
) {
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())
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?");
2542 /// Interpret all CIE and FDE instructions up until CFI State number and
2543 /// populate this snapshot
2545 const BinaryFunction::CFIInstrMapType
&CIE
,
2546 const BinaryFunction::CFIInstrMapType
&FDE
,
2547 const DenseMap
<int32_t, SmallVector
<int32_t, 4>> &FrameRestoreEquivalents
,
2549 : CIE(CIE
), FDE(FDE
), FrameRestoreEquivalents(FrameRestoreEquivalents
) {
2551 CFAOffset
= UNKNOWN
;
2555 for (int32_t I
= 0, E
= CIE
.size(); I
!= E
; ++I
) {
2556 const MCCFIInstruction
&Instr
= CIE
[I
];
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
) {}
2576 const BinaryFunction::CFIInstrMapType
&CIE
,
2577 const BinaryFunction::CFIInstrMapType
&FDE
,
2578 const DenseMap
<int32_t, SmallVector
<int32_t, 4>> &FrameRestoreEquivalents
,
2580 : CFISnapshot(CIE
, FDE
, FrameRestoreEquivalents
, State
) {}
2582 /// Return true if applying Instr to this state is redundant and can be
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
: {
2594 if (Instr
.getOperation() != MCCFIInstruction::OpEscape
) {
2595 Reg
= Instr
.getRegister();
2597 std::optional
<uint8_t> R
=
2598 readDWARFExpressionTargetReg(Instr
.getValues());
2599 // Handle DW_CFA_def_cfa_expression
2601 if (RestoredCFAReg
&& RestoredCFAOffset
)
2603 RestoredCFAReg
= true;
2604 RestoredCFAOffset
= true;
2609 if (RestoredRegs
[Reg
])
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
)
2619 const MCCFIInstruction
&LastDef
=
2620 CurRegRule
< 0 ? CIE
[-CurRegRule
] : FDE
[CurRegRule
];
2621 return LastDef
== Instr
;
2623 case MCCFIInstruction::OpDefCfaRegister
:
2626 RestoredCFAReg
= true;
2627 return CFAReg
== Instr
.getRegister();
2628 case MCCFIInstruction::OpDefCfaOffset
:
2629 if (RestoredCFAOffset
)
2631 RestoredCFAOffset
= true;
2632 return CFAOffset
== Instr
.getOffset();
2633 case MCCFIInstruction::OpDefCfa
:
2634 if (RestoredCFAReg
&& RestoredCFAOffset
)
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");
2645 case MCCFIInstruction::OpRememberState
:
2646 case MCCFIInstruction::OpRestoreState
:
2647 case MCCFIInstruction::OpGnuArgsSize
:
2648 // do not affect CFI state
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
)
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
]))
2684 InsertIt
= addCFIPseudo(InBB
, InsertIt
, State
);
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();
2709 NewStates
.push_back(FrameInstructions
.size() - 1);
2710 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size() - 1);
2712 } else if (ToCFITable
.CFARule
< 0) {
2713 if (FromCFITable
.isRedundant(CIEFrameInstructions
[-ToCFITable
.CFARule
]))
2715 NewStates
.push_back(FrameInstructions
.size());
2716 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size());
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
);
2727 auto undoState
= [&](const MCCFIInstruction
&Instr
) {
2728 switch (Instr
.getOperation()) {
2729 case MCCFIInstruction::OpRememberState
:
2730 case MCCFIInstruction::OpRestoreState
:
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
: {
2740 if (Instr
.getOperation() != MCCFIInstruction::OpEscape
) {
2741 Reg
= Instr
.getRegister();
2743 std::optional
<uint8_t> R
=
2744 readDWARFExpressionTargetReg(Instr
.getValues());
2745 // Handle DW_CFA_def_cfa_expression
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();
2760 NewStates
.push_back(FrameInstructions
.size() - 1);
2761 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size() - 1);
2765 const int32_t Rule
= ToCFITable
.RegRule
[Reg
];
2767 if (FromCFITable
.isRedundant(CIEFrameInstructions
[-Rule
]))
2769 NewStates
.push_back(FrameInstructions
.size());
2770 InsertIt
= addCFIPseudo(InBB
, InsertIt
, FrameInstructions
.size());
2772 FrameInstructions
.emplace_back(CIEFrameInstructions
[-Rule
]);
2775 if (FromCFITable
.isRedundant(FrameInstructions
[Rule
]))
2777 NewStates
.push_back(Rule
);
2778 InsertIt
= addCFIPseudo(InBB
, InsertIt
, Rule
);
2782 case MCCFIInstruction::OpDefCfaRegister
:
2783 case MCCFIInstruction::OpDefCfaOffset
:
2784 case MCCFIInstruction::OpDefCfa
:
2787 case MCCFIInstruction::OpAdjustCfaOffset
:
2788 case MCCFIInstruction::OpWindowSave
:
2789 case MCCFIInstruction::OpNegateRAState
:
2790 case MCCFIInstruction::OpLLVMDefAspaceCfa
:
2791 llvm_unreachable("unsupported CFI opcode");
2793 case MCCFIInstruction::OpGnuArgsSize
:
2794 // do not affect CFI state
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
) {
2806 auto Iter
= FrameRestoreEquivalents
.find(I
);
2807 if (Iter
== FrameRestoreEquivalents
.end())
2809 for (int32_t State
: Iter
->second
)
2810 undoState(FrameInstructions
[State
]);
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());
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
);
2842 bool BinaryFunction::finalizeCFIState() {
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
2848 const char *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.
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()))
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
);
2896 bool BinaryFunction::requiresAddressTranslation() const {
2897 return opts::EnableBAT
|| hasSDTMarker() || hasPseudoProbe();
2900 bool BinaryFunction::requiresAddressMap() const {
2904 return opts::UpdateDebugSections
|| isMultiEntry() ||
2905 requiresAddressTranslation();
2908 uint64_t BinaryFunction::getInstructionCount() const {
2910 for (const BinaryBasicBlock
&BB
: blocks())
2911 Count
+= BB
.getNumNonPseudos();
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
)
2925 BC
.UndefinedSymbols
.insert(EndLabel
);
2929 void BinaryFunction::setTrapOnEntry() {
2932 forEachEntryPoint([&](uint64_t Offset
, const MCSymbol
*Label
) -> bool {
2934 BC
.MIB
->createTrap(TrapInstr
);
2935 addInstruction(Offset
, std::move(TrapInstr
));
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
2947 assert(CurrentState
== State::Empty
&&
2948 "cannot ignore non-empty functions in current mode");
2955 // Clear CFG state too.
2959 for (BinaryBasicBlock
*BB
: BasicBlocks
)
2961 clearList(BasicBlocks
);
2963 for (BinaryBasicBlock
*BB
: DeletedBasicBlocks
)
2965 clearList(DeletedBasicBlocks
);
2970 CurrentState
= State::Empty
;
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()) {
2984 for (MCInst
&Inst
: *BB
) {
2986 for (MCOperand
&Operand
: Inst
) {
2987 if (!Operand
.isExpr()) {
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
))
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
;
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(
3016 MCSymbolRefExpr::create(ColdSymbol
, MCSymbolRefExpr::VK_None
,
3026 #define MAX_PATH 255
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
;
3048 static std::string
formatEscapes(const std::string
&Str
) {
3050 for (unsigned I
= 0; I
< Str
.size(); ++I
) {
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");
3089 OS
<< "\"" << BB
->getName() << "\" [";
3090 for (StringRef Attr
: Attrs
)
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
) {
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';
3110 // analyzeBranch is just used to get the names of the branch
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()) {
3125 if (Succ
== BB
->getConditionalSuccessor(true)) {
3126 Branch
= CondBranch
? std::string(BC
.InstPrinter
->getOpcodeName(
3127 CondBranch
->getOpcode()))
3129 } else if (Succ
== BB
->getConditionalSuccessor(false)) {
3130 Branch
= UncondBranch
? std::string(BC
.InstPrinter
->getOpcodeName(
3131 UncondBranch
->getOpcode()))
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
<< ")";
3153 for (BinaryBasicBlock
*LP
: BB
->landing_pads()) {
3154 OS
<< format("\"%s\" -> \"%s\" [constraint=false style=dashed]\n",
3155 BB
->getName().data(), LP
->getName().data());
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";
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))
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 {
3190 raw_fd_ostream
of(Filename
, EC
, sys::fs::OF_None
);
3192 if (opts::Verbosity
>= 1) {
3193 errs() << "BOLT-WARNING: " << EC
.message() << ", unable to open "
3194 << Filename
<< " for output.\n";
3201 bool BinaryFunction::validateCFG() const {
3202 // Skip the validation of CFG after it is finalized
3203 if (CurrentState
== State::CFG_Finalized
)
3207 for (BinaryBasicBlock
*BB
: BasicBlocks
)
3208 Valid
&= BB
->validateSuccessorInvariants();
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";
3223 for (const BinaryBasicBlock
*BB
: BasicBlocks
) {
3224 if (!validateBlock(BB
, "block"))
3226 for (const BinaryBasicBlock
*PredBB
: BB
->predecessors())
3227 if (!validateBlock(PredBB
, "predecessor"))
3229 for (const BinaryBasicBlock
*SuccBB
: BB
->successors())
3230 if (!validateBlock(SuccBB
, "successor"))
3232 for (const BinaryBasicBlock
*LP
: BB
->landing_pads())
3233 if (!validateBlock(LP
, "landing pad"))
3235 for (const BinaryBasicBlock
*Thrower
: BB
->throwers())
3236 if (!validateBlock(Thrower
, "thrower"))
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';
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';
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";
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";
3282 void BinaryFunction::fixBranches() {
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
))
3294 // We will create unconditional branch with correct destination if needed.
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.
3308 BB
->eraseInstruction(BB
->findInstruction(CondBranch
));
3309 if (BB
->getSuccessor() == NextBB
)
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
);
3325 // Reverse branch condition and swap successors.
3326 auto swapSuccessors
= [&]() {
3327 if (MIB
->isUnsupportedBranch(*CondBranch
))
3329 std::swap(TSuccessor
, FSuccessor
);
3330 BB
->swapConditionalSuccessors();
3331 auto L
= BC
.scopeLock();
3332 MIB
->reverseBranchCondition(*CondBranch
, TSuccessor
->getLabel(), Ctx
);
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())
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
)
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
3358 if (BB
->getFragmentNum() != TSuccessor
->getFragmentNum() &&
3359 BB
->getFragmentNum() == FSuccessor
->getFragmentNum())
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())
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
);
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
);
3407 void BinaryFunction::postProcessBranches() {
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())
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()) {
3432 dbgs() << "BOLT-DEBUG: at least one instruction expected in BB "
3433 << BB
.getName() << " in function " << *this << '\n');
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');
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
);
3460 if (BinaryData
*EntryBD
= BC
.getBinaryDataAtAddress(EntryPointAddress
)) {
3461 EntrySymbol
= EntryBD
->getSymbol();
3463 EntrySymbol
= BC
.getOrCreateGlobalSymbol(
3464 EntryPointAddress
, Twine("__ENTRY_") + getOneName() + "@");
3466 SecondaryEntryPoints
[LocalSymbol
] = EntrySymbol
;
3468 BC
.setSymbolToFunctionMap(EntrySymbol
, this);
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())
3480 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(BB
);
3485 BC
.Ctx
->getOrCreateSymbol("__ENTRY_" + BB
.getLabel()->getName());
3487 SecondaryEntryPoints
[BB
.getLabel()] = EntrySymbol
;
3489 BC
.setSymbolToFunctionMap(EntrySymbol
, this);
3494 MCSymbol
*BinaryFunction::getSymbolForEntryID(uint64_t EntryID
) {
3498 if (!isMultiEntry())
3501 uint64_t NumEntries
= 0;
3503 for (BinaryBasicBlock
*BB
: BasicBlocks
) {
3504 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(*BB
);
3507 if (NumEntries
== EntryID
)
3512 for (std::pair
<const uint32_t, MCSymbol
*> &KV
: Labels
) {
3513 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(KV
.second
);
3516 if (NumEntries
== EntryID
)
3525 uint64_t BinaryFunction::getEntryIDForSymbol(const MCSymbol
*Symbol
) const {
3526 if (!isMultiEntry())
3529 for (const MCSymbol
*FunctionSymbol
: getSymbols())
3530 if (FunctionSymbol
== Symbol
)
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
);
3539 if (EntrySymbol
== Symbol
)
3544 for (const std::pair
<const uint32_t, MCSymbol
*> &KV
: Labels
) {
3545 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(KV
.second
);
3548 if (EntrySymbol
== Symbol
)
3553 llvm_unreachable("symbol not found");
3556 bool BinaryFunction::forEachEntryPoint(EntryPointCallbackTy Callback
) const {
3557 bool Status
= Callback(0, getSymbol());
3558 if (!isMultiEntry())
3561 for (const std::pair
<const uint32_t, MCSymbol
*> &KV
: Labels
) {
3565 MCSymbol
*EntrySymbol
= getSecondaryEntryPointSymbol(KV
.second
);
3569 Status
= Callback(KV
.first
, EntrySymbol
);
3575 BinaryFunction::BasicBlockListType
BinaryFunction::dfs() const {
3576 BasicBlockListType DFS
;
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
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
))
3595 for (BinaryBasicBlock
&BB
: blocks())
3596 BB
.setLayoutIndex(BinaryBasicBlock::InvalidIndex
);
3598 while (!Stack
.empty()) {
3599 BinaryBasicBlock
*BB
= Stack
.top();
3602 if (BB
->getLayoutIndex() != BinaryBasicBlock::InvalidIndex
)
3605 BB
->setLayoutIndex(Index
++);
3608 for (BinaryBasicBlock
*SuccBB
: BB
->landing_pads()) {
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));
3623 Stack
.push(BB
->getConditionalSuccessor(false));
3624 Stack
.push(BB
->getConditionalSuccessor(true));
3627 for (BinaryBasicBlock
*SuccBB
: BB
->successors()) {
3636 size_t BinaryFunction::computeHash(bool UseDFS
, HashFunction HashFunction
,
3637 OperandHashFuncTy OperandHashFunc
) const {
3641 assert(hasCFG() && "function is expected to have CFG");
3643 SmallVector
<const BinaryBasicBlock
*, 0> Order
;
3645 llvm::copy(dfs(), std::back_inserter(Order
));
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
,
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();
3687 updateLayout(Start
, NumNewBlocks
);
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
,
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();
3717 updateLayout(*std::prev(RetIter
), NumNewBlocks
);
3720 updateCFIState(*std::prev(RetIter
), NumNewBlocks
);
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
3745 Begin
= BasicBlocks
.begin();
3746 End
= BasicBlocks
.begin() + NumNewBlocks
;
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
))
3764 uint64_t JTAddress
= BC
.MIB
->getJumpTable(Inst
);
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
3770 if (!JumpTables
.count(JTAddress
)) {
3771 JumpTables
.insert(JTAddress
);
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
))
3788 JumpTable
*JT
= getJumpTable(Inst
);
3791 auto Iter
= JumpTables
.find(JT
);
3792 if (Iter
== JumpTables
.end()) {
3793 JumpTables
.insert(JT
);
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
3801 const MCSymbol
*Target
;
3802 // In case we match if our first matcher, first instruction is the one to
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(
3812 MutableArrayRef
<MCInst
>(&*BB
->begin(), &Inst
+ 1), -1) ||
3813 BaseReg1
!= BC
.MIB
->getNoRegister() || Scale
!= 8) {
3816 // Standard JT matching failed. Trying now:
3817 // movq "jt.2397/1"(,%rax,8), %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(
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
3834 // leaq DATAat0x402450(%rip), %r11
3835 // movslq (%r11,%rdx,4), %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(
3852 MutableArrayRef
<MCInst
>(&*BB
->begin(), &Inst
+ 1), -1) ||
3853 Scale
!= 4 || BaseReg1
!= BaseReg2
|| Offset
!= 0 ||
3854 !PICBaseAddrMatcher
->match(
3856 MutableArrayRef
<MCInst
>(&*BB
->begin(), &Inst
+ 1), -1)) {
3857 llvm_unreachable("Failed to extract jump table base");
3860 // Matched PIC, identify the instruction with the reference to the JT
3861 JTLoadInst
= LEAMatcher
->CurInst
;
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
))
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());
3896 assert(Patched
&& "Invalid entry to be replaced in jump table");
3900 BinaryBasicBlock
*BinaryFunction::splitEdge(BinaryBasicBlock
*From
,
3901 BinaryBasicBlock
*To
) {
3902 // Create intermediate BB
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();
3916 auto I
= From
->succ_begin();
3917 auto BI
= From
->branch_info_begin();
3918 for (; I
!= From
->succ_end(); ++I
) {
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);
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)
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();
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
))
3965 const MCSymbol
*CalleeSymbol
= BC
.MIB
->getTargetSymbol(*Last
);
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")
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")))
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
))
3992 // It's okay to have a zero-sized symbol in the middle of non-zero-sized
3994 if (SymbolSize
== 0 && containsAddress(cantFail(Symbol
.getAddress())))
3997 if (cantFail(Symbol
.getType()) != SymbolRef::ST_Unknown
)
4000 if (cantFail(Symbol
.getFlags()) & SymbolRef::SF_Global
)
4006 void BinaryFunction::adjustExecutionCount(uint64_t Count
) {
4007 if (getKnownExecutionCount() == 0 || Count
== 0)
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
)
4026 for (BinaryBasicBlock
*BB
: DeletedBasicBlocks
)
4030 void BinaryFunction::calculateLoopInfo() {
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
) {
4044 while (!St
.empty()) {
4045 BinaryLoop
*L
= St
.top();
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
)
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
;
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
;
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
;
4100 void BinaryFunction::updateOutputValues(const BOLTLinker
&Linker
) {
4102 assert(!isInjected() && "injected function should be emitted");
4103 setOutputAddress(getAddress());
4104 setOutputSize(getSize());
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
);
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
);
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())
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())
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())
4168 // AArch64 may have functions that only contains a constant island (no code).
4169 if (getLayout().block_empty())
4172 for (FunctionFragment
&FF
: getLayout().fragments()) {
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
) {
4185 assert(FragmentBaseAddress
== FF
.getAddress());
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
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
);
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
);
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
;
4227 return OutputRanges
;
4230 return OutputRanges
;
4232 OutputRanges
.emplace_back(getOutputAddress(),
4233 getOutputAddress() + getOutputSize());
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());
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 {
4258 // If the function hasn't changed return the same address.
4262 if (Address
< getAddress())
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
);
4275 // Special case for address immediately past the end of the function.
4276 if (Offset
== getSize())
4277 return getOutputAddress() + getOutputSize();
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.
4294 // If the function hasn't changed return the same range.
4296 OutRanges
.emplace_back(InRange
);
4300 if (!containsAddress(InRange
.LowPC
))
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
});
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()) {
4325 dbgs() << "BOLT-DEBUG: invalid debug address range detected for "
4326 << *this << " : [0x" << Twine::utohexstr(InRange
.LowPC
)
4327 << ", 0x" << Twine::utohexstr(InRange
.HighPC
) << "]\n");
4331 // Skip the block if it wasn't emitted.
4332 if (!BB
.getOutputAddressRange().first
)
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
);
4357 OutRanges
.emplace_back(OutLowPC
, std::max(OutLowPC
, OutHighPC
));
4361 dbgs() << "BOLT-DEBUG: translated address range " << InRange
<< " -> ";
4362 for (const DebugAddressRange
&R
: 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
);
4379 for (MCInst
&Inst
: *BB
) {
4380 constexpr uint32_t InvalidOffset
= std::numeric_limits
<uint32_t>::max();
4381 if (Offset
== BC
.MIB
->getOffsetWithDefault(Inst
, InvalidOffset
))
4385 if (MCInst
*LastInstr
= BB
->getLastNonPseudoInstr()) {
4386 if (std::optional
<uint32_t> Size
= BC
.MIB
->getSize(*LastInstr
)) {
4387 if (BB
->getEndOffset() - Offset
== Size
) {
4395 llvm_unreachable("invalid CFG state to use getInstructionAtOffset()");
4399 void BinaryFunction::printLoopInfo(raw_ostream
&OS
) const {
4400 if (!opts::shouldPrint(*this))
4403 OS
<< "Loop Info for Function \"" << *this << "\"";
4404 if (hasValidProfile())
4405 OS
<< " (count: " << getExecutionCount() << ")";
4408 std::stack
<BinaryLoop
*> St
;
4409 for (BinaryLoop
*L
: *BLI
)
4411 while (!St
.empty()) {
4412 BinaryLoop
*L
= St
.top();
4415 for (BinaryLoop
*Inner
: *L
)
4418 if (!hasValidProfile())
4421 OS
<< (L
->getLoopDepth() > 1 ? "Nested" : "Outer")
4422 << " loop header: " << L
->getHeader()->getName();
4424 OS
<< "Loop basic blocks: ";
4426 for (BinaryBasicBlock
*BB
: L
->blocks())
4427 OS
<< LS
<< BB
->getName();
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
)
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())
4451 BinaryBasicBlock
&BB
= **BasicBlocks
.begin();
4452 for (MCInst
&Inst
: BB
)
4453 if (!BC
.MIB
->hasAnnotation(Inst
, "AArch64Veneer"))
4456 for (auto I
= BasicBlocks
.begin() + 1, E
= BasicBlocks
.end(); I
!= E
; ++I
) {
4457 for (MCInst
&Inst
: **I
)
4458 if (!BC
.MIB
->isNoop(Inst
))
4465 void BinaryFunction::addRelocation(uint64_t Address
, MCSymbol
*Symbol
,
4466 uint64_t RelType
, uint64_t Addend
,
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
};