21#include "llvm/Config/llvm-config.h"
38#define DEBUG_TYPE "branch-relaxation"
41STATISTIC(NumConditionalRelaxed,
"Number of conditional branches relaxed");
42STATISTIC(NumUnconditionalRelaxed,
"Number of unconditional branches relaxed");
44#define BRANCH_RELAX_NAME "Branch relaxation pass"
48class BranchRelaxation {
71 const Align Alignment =
MBB.getAlignment();
72 const Align ParentAlign =
MBB.getParent()->getAlignment();
73 if (Alignment <= ParentAlign)
88 RelaxedUnconditionals;
89 std::unique_ptr<RegScavenger> RS;
97 bool relaxBranchInstructions();
138char BranchRelaxationLegacy::ID = 0;
146void BranchRelaxation::
verify() {
148 unsigned PrevNum = MF->begin()->getNumber();
150 const unsigned Num =
MBB.getNumber();
151 assert(!Num || BlockInfo[PrevNum].postOffset(
MBB) <= BlockInfo[Num].
Offset);
158 J !=
MBB.end(); J = std::next(J)) {
160 if (!
MI.isConditionalBranch() && !
MI.isUnconditionalBranch())
162 if (
MI.getOpcode() == TargetOpcode::FAULTING_OP)
165 assert(isBlockInRange(
MI, *DestBB) ||
166 RelaxedUnconditionals.contains({&MBB, DestBB}));
172#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
175 for (
auto &
MBB : *MF) {
185void BranchRelaxation::scanFunction() {
187 BlockInfo.resize(MF->getNumBlockIDs());
189 TrampolineInsertionPoint =
nullptr;
190 RelaxedUnconditionals.clear();
197 for (MachineBasicBlock &
MBB : *MF) {
201 TrampolineInsertionPoint = &
MBB;
205 adjustBlockOffsets(*MF->begin());
207 if (TrampolineInsertionPoint ==
nullptr) {
208 LLVM_DEBUG(
dbgs() <<
" No suitable trampoline insertion point found in "
209 << MF->getName() <<
".\n");
215BranchRelaxation::computeBlockSize(
const MachineBasicBlock &
MBB)
const {
217 for (
const MachineInstr &
MI :
MBB)
225unsigned BranchRelaxation::getInstrOffset(
const MachineInstr &
MI)
const {
226 const MachineBasicBlock *
MBB =
MI.getParent();
235 assert(
I !=
MBB->
end() &&
"Didn't find MI in its own basic block?");
242void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
243 adjustBlockOffsets(Start, MF->end());
246void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start,
248 unsigned PrevNum =
Start.getNumber();
254 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(
MBB);
262BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigBB) {
269BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigMBB,
270 const BasicBlock *BB) {
272 MachineBasicBlock *NewBB = MF->CreateMachineBasicBlock(BB);
281 BlockInfo.insert(BlockInfo.begin() + NewBB->
getNumber(), BasicBlockInfo());
290BranchRelaxation::splitBlockBeforeInstr(MachineInstr &
MI,
291 MachineBasicBlock *DestBB) {
292 MachineBasicBlock *OrigBB =
MI.getParent();
295 MachineBasicBlock *NewBB =
305 NewBB->
splice(NewBB->
end(), OrigBB,
MI.getIterator(), OrigBB->
end());
311 TII->insertUnconditionalBranch(*OrigBB, NewBB,
DebugLoc());
314 BlockInfo.insert(BlockInfo.begin() + NewBB->
getNumber(), BasicBlockInfo());
329 BlockInfo[OrigBB->
getNumber()].Size = computeBlockSize(*OrigBB);
333 BlockInfo[NewBB->
getNumber()].Size = computeBlockSize(*NewBB);
336 adjustBlockOffsets(*OrigBB, std::next(NewBB->
getIterator()));
339 if (
TRI->trackLivenessAfterRegAlloc(*MF))
349bool BranchRelaxation::isBlockInRange(
const MachineInstr &
MI,
350 const MachineBasicBlock &DestBB)
const {
351 int64_t BrOffset = getInstrOffset(
MI);
352 int64_t DestOffset = BlockInfo[DestBB.
getNumber()].Offset;
354 const MachineBasicBlock *SrcBB =
MI.getParent();
356 if (
TII->isBranchOffsetInRange(
MI.getOpcode(),
359 : DestOffset - BrOffset))
365 << DestOffset <<
" offset " << DestOffset - BrOffset <<
'\t'
374bool BranchRelaxation::fixupConditionalBranch(MachineInstr &
MI) {
376 MachineBasicBlock *
MBB =
MI.getParent();
377 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
378 MachineBasicBlock *NewBB =
nullptr;
381 auto insertUncondBranch = [&](MachineBasicBlock *
MBB,
382 MachineBasicBlock *DestBB) {
385 TII->insertUnconditionalBranch(*
MBB, DestBB,
DL, &NewBrSize);
388 auto insertBranch = [&](MachineBasicBlock *
MBB, MachineBasicBlock *
TBB,
389 MachineBasicBlock *FBB,
390 SmallVectorImpl<MachineOperand> &
Cond) {
396 auto removeBranch = [&](MachineBasicBlock *
MBB) {
400 BBSize -= RemovedSize;
404 auto updateOffsetAndLiveness = [&](MachineBasicBlock *NewBB) {
405 assert(NewBB !=
nullptr &&
"can't populate offset for nullptr");
410 adjustBlockOffsets(*std::prev(NewBB->
getIterator()),
414 if (
TRI->trackLivenessAfterRegAlloc(*MF))
419 assert(!
Fail &&
"branches to be relaxed must be analyzable");
434 TrampolineInsertionPoint !=
nullptr) {
439 if (isBlockInRange(
MI, *NewBB)) {
443 insertUncondBranch(NewBB,
TBB);
451 insertBranch(
MBB, NewBB, FBB,
Cond);
453 TrampolineInsertionPoint = NewBB;
454 updateOffsetAndLiveness(NewBB);
459 dbgs() <<
" Trampoline insertion point out of range for Bcc from "
477 if (FBB && isBlockInRange(
MI, *FBB)) {
486 "its destination with "
505 insertUncondBranch(
MBB,
TBB);
510 NewBB = createNewBlockAfter(*
MBB);
512 insertUncondBranch(NewBB, FBB);
517 updateOffsetAndLiveness(NewBB);
525 <<
", invert condition and change dest. to "
536 <<
" Insert a new BB after " <<
MBB->
back());
552 NewBB = createNewBlockAfter(*
MBB);
553 insertUncondBranch(NewBB,
TBB);
557 <<
" Keep the exiting condition.\n"
559 <<
" In the new BB: Insert B to "
568 insertBranch(
MBB, NewBB, FBB,
Cond);
570 updateOffsetAndLiveness(NewBB);
574bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &
MI) {
575 MachineBasicBlock *
MBB =
MI.getParent();
576 unsigned OldBrSize =
TII->getInstSizeInBytes(
MI);
577 MachineBasicBlock *DestBB =
TII->getBranchDestBlock(
MI);
579 int64_t DestOffset = BlockInfo[DestBB->
getNumber()].Offset;
580 int64_t SrcOffset = getInstrOffset(
MI);
585 : DestOffset - SrcOffset));
589 MachineBasicBlock *BranchBB =
MBB;
594 BranchBB = createNewBlockAfter(*
MBB);
598 for (
const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
605 if (TrampolineInsertionPoint ==
MBB)
606 TrampolineInsertionPoint = BranchBB;
610 MI.eraseFromParent();
615 MachineBasicBlock *RestoreBB =
621 TII->insertIndirectBranch(*BranchBB, *DestBB, *RestoreBB,
DL,
624 : DestOffset - SrcOffset,
629 BlockInfo[BranchBB->
getNumber()].Size = computeBlockSize(*BranchBB);
633 if (!RestoreBB->
empty()) {
638 MachineBasicBlock *NewBB = createNewBlockAfter(*TrampolineInsertionPoint);
639 TII->insertUnconditionalBranch(*NewBB, DestBB,
DebugLoc());
640 BlockInfo[NewBB->
getNumber()].Size = computeBlockSize(*NewBB);
641 adjustBlockOffsets(*TrampolineInsertionPoint,
645 TrampolineInsertionPoint = NewBB;
661 MachineBasicBlock *PrevBB = &*std::prev(DestBB->
getIterator());
666 TII->insertUnconditionalBranch(*PrevBB, FT,
DebugLoc());
667 BlockInfo[PrevBB->
getNumber()].Size = computeBlockSize(*PrevBB);
674 if (
TRI->trackLivenessAfterRegAlloc(*MF))
677 BlockInfo[RestoreBB->
getNumber()].Size = computeBlockSize(*RestoreBB);
679 adjustBlockOffsets(*PrevBB, DestBB->
getIterator());
685 RelaxedUnconditionals.insert({BranchBB, RestoreBB});
688 MF->erase(RestoreBB);
689 RelaxedUnconditionals.insert({BranchBB, DestBB});
695bool BranchRelaxation::relaxBranchInstructions() {
700 for (MachineBasicBlock &
MBB : *MF) {
711 if (
Last->isUnconditionalBranch()) {
714 if (MachineBasicBlock *DestBB =
TII->getBranchDestBlock(*
Last)) {
716 !RelaxedUnconditionals.contains({&MBB, DestBB})) {
717 fixupUnconditionalBranch(*
Last);
718 ++NumUnconditionalRelaxed;
729 MachineInstr &
MI = *J;
731 if (!
MI.isConditionalBranch())
734 if (
MI.getOpcode() == TargetOpcode::FAULTING_OP)
739 MachineBasicBlock *DestBB =
TII->getBranchDestBlock(
MI);
740 if (!isBlockInRange(
MI, *DestBB)) {
746 splitBlockBeforeInstr(*
Next, DestBB);
748 fixupConditionalBranch(
MI);
749 ++NumConditionalRelaxed;
764 adjustBlockOffsets(MF->front());
784 TII = ST.getInstrInfo();
787 TRI = ST.getRegisterInfo();
788 if (
TRI->trackLivenessAfterRegAlloc(*MF))
793 MF->RenumberBlocks();
799 LLVM_DEBUG(
dbgs() <<
" Basic blocks before relaxation\n"; dumpBBs(););
801 bool MadeChange =
false;
802 while (relaxBranchInstructions())
808 LLVM_DEBUG(
dbgs() <<
" Basic blocks after relaxation\n\n"; dumpBBs());
811 RelaxedUnconditionals.clear();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static cl::opt< bool > BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true), cl::desc("Relax out of range conditional branches"))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define BRANCH_RELAX_NAME
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
const HexagonInstrInfo * TII
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
This file declares the machine register scavenger class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
LLVM Basic Block Representation.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
bool isTailCall(const MachineInstr &MI) const override
A set of physical registers with utility functions to track liveness when walking backward/forward th...
void setIsEndSection(bool V=true)
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineBasicBlock * getLogicalFallThrough()
Return the fallthrough block if the block can implicitly transfer control to it's successor,...
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
LLVM_ABI void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
LLVM_ABI bool isEntryBlock() const
Returns true if this is the entry block of the function.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
LLVM_ABI iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
bool isBeginSection() const
Returns true if this block begins any section.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
bool isEndSection() const
Returns true if this block ends any section.
MachineInstrBundleIterator< MachineInstr > iterator
void setIsBeginSection(bool V=true)
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
BasicBlockListType::iterator iterator
Representation of each machine instruction.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Implements a dense probed hash-table based set with some number of buckets stored inline.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
uint64_t getMaxCodeSize() const
Returns the maximum code size possible under the code model.
const Target & getTarget() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
self_iterator getIterator()
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & BranchRelaxationPassID
BranchRelaxation - This pass replaces branches that need to jump further than is supported by a branc...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
FunctionAddr VTableAddr Next
void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This struct is a compact representation of a valid (non-zero power of two) alignment.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
BasicBlockInfo - Information about the offset and size of a single basic block.
unsigned Size
Size - Size of the basic block in bytes.
unsigned Offset
Offset - Distance from the beginning of the function to the beginning of this basic block.
LLVM_ABI static const MBBSectionID ColdSectionID