23#include "llvm/Config/llvm-config.h"
40#define DEBUG_TYPE "branch-relaxation"
43STATISTIC(NumConditionalRelaxed,
"Number of conditional branches relaxed");
44STATISTIC(NumUnconditionalRelaxed,
"Number of unconditional branches relaxed");
46#define BRANCH_RELAX_NAME "Branch relaxation pass"
50class BranchRelaxation {
73 const Align Alignment =
MBB.getAlignment();
74 const Align ParentAlign =
MBB.getParent()->getAlignment();
75 if (Alignment <= ParentAlign)
90 RelaxedUnconditionals;
91 std::unique_ptr<RegScavenger> RS;
99 bool relaxBranchInstructions();
142char BranchRelaxationLegacy::ID = 0;
150void BranchRelaxation::
verify() {
152 unsigned PrevNum = MF->begin()->getNumber();
154 const unsigned Num =
MBB.getNumber();
155 assert(!Num || BlockInfo[PrevNum].postOffset(
MBB) <= BlockInfo[Num].
Offset);
162 J !=
MBB.end(); J = std::next(J)) {
164 if (!
MI.isConditionalBranch() && !
MI.isUnconditionalBranch())
166 if (
MI.getOpcode() == TargetOpcode::FAULTING_OP)
169 assert(isBlockInRange(
MI, *DestBB) ||
170 RelaxedUnconditionals.contains({&MBB, DestBB}));
176#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
179 for (
auto &
MBB : *MF) {
189void BranchRelaxation::scanFunction() {
191 BlockInfo.resize(MF->getNumBlockIDs());
193 TrampolineInsertionPoint =
nullptr;
194 RelaxedUnconditionals.clear();
201 for (MachineBasicBlock &
MBB : *MF) {
205 TrampolineInsertionPoint = &
MBB;
209 adjustBlockOffsets(*MF->begin());
211 if (TrampolineInsertionPoint ==
nullptr) {
212 LLVM_DEBUG(
dbgs() <<
" No suitable trampoline insertion point found in "
213 << MF->getName() <<
".\n");
219BranchRelaxation::computeBlockSize(
const MachineBasicBlock &
MBB)
const {
221 for (
const MachineInstr &
MI :
MBB)
229unsigned BranchRelaxation::getInstrOffset(
const MachineInstr &
MI)
const {
230 const MachineBasicBlock *
MBB =
MI.getParent();
239 assert(
I !=
MBB->
end() &&
"Didn't find MI in its own basic block?");
246void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
247 adjustBlockOffsets(Start, MF->end());
250void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start,
252 unsigned PrevNum =
Start.getNumber();
258 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(
MBB);
266BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigBB) {
273BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigMBB,
274 const BasicBlock *BB) {
276 MachineBasicBlock *NewBB = MF->CreateMachineBasicBlock(BB);
285 BlockInfo.insert(BlockInfo.begin() + NewBB->
getNumber(), BasicBlockInfo());
290 adjustBlockOffsets(OrigMBB, std::next(NewBB->
getIterator()));
299BranchRelaxation::splitBlockBeforeInstr(MachineInstr &
MI,
300 MachineBasicBlock *DestBB) {
301 MachineBasicBlock *OrigBB =
MI.getParent();
304 MachineBasicBlock *NewBB =
314 NewBB->
splice(NewBB->
end(), OrigBB,
MI.getIterator(), OrigBB->
end());
320 TII->insertUnconditionalBranch(*OrigBB, NewBB,
DebugLoc());
323 BlockInfo.insert(BlockInfo.begin() + NewBB->
getNumber(), BasicBlockInfo());
338 BlockInfo[OrigBB->
getNumber()].Size = computeBlockSize(*OrigBB);
342 BlockInfo[NewBB->
getNumber()].Size = computeBlockSize(*NewBB);
345 adjustBlockOffsets(*OrigBB, std::next(NewBB->
getIterator()));
348 if (
TRI->trackLivenessAfterRegAlloc(*MF))
358bool BranchRelaxation::isBlockInRange(
const MachineInstr &
MI,
359 const MachineBasicBlock &DestBB)
const {
360 int64_t BrOffset = getInstrOffset(
MI);
361 int64_t DestOffset = BlockInfo[DestBB.
getNumber()].Offset;
363 const MachineBasicBlock *SrcBB =
MI.getParent();
365 if (
TII->isBranchOffsetInRange(
MI.getOpcode(),
368 : DestOffset - BrOffset))
374 << DestOffset <<
" offset " << DestOffset - BrOffset <<
'\t'
383bool BranchRelaxation::fixupConditionalBranch(MachineInstr &
MI) {
385 MachineBasicBlock *
MBB =
MI.getParent();
386 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
387 MachineBasicBlock *NewBB =
nullptr;
390 auto insertUncondBranch = [&](MachineBasicBlock *
MBB,
391 MachineBasicBlock *DestBB) {
394 TII->insertUnconditionalBranch(*
MBB, DestBB,
DL, &NewBrSize);
397 auto insertBranch = [&](MachineBasicBlock *
MBB, MachineBasicBlock *
TBB,
398 MachineBasicBlock *FBB,
399 SmallVectorImpl<MachineOperand> &
Cond) {
405 auto removeBranch = [&](MachineBasicBlock *
MBB) {
409 BBSize -= RemovedSize;
414 assert(NewBB !=
nullptr &&
"can't update liveness for nullptr");
417 if (
TRI->trackLivenessAfterRegAlloc(*MF))
422 assert(!
Fail &&
"branches to be relaxed must be analyzable");
437 TrampolineInsertionPoint !=
nullptr) {
442 if (isBlockInRange(
MI, *NewBB)) {
446 insertUncondBranch(NewBB,
TBB);
454 insertBranch(
MBB, NewBB, FBB,
Cond);
456 TrampolineInsertionPoint = NewBB;
462 dbgs() <<
" Trampoline insertion point out of range for Bcc from "
480 if (FBB && isBlockInRange(
MI, *FBB)) {
489 "its destination with "
508 insertUncondBranch(
MBB,
TBB);
513 NewBB = createNewBlockAfter(*
MBB);
515 insertUncondBranch(NewBB, FBB);
528 <<
", invert condition and change dest. to "
539 <<
" Insert a new BB after " <<
MBB->
back());
555 NewBB = createNewBlockAfter(*
MBB);
556 insertUncondBranch(NewBB,
TBB);
560 <<
" Keep the exiting condition.\n"
562 <<
" In the new BB: Insert B to "
571 insertBranch(
MBB, NewBB, FBB,
Cond);
577bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &
MI) {
578 MachineBasicBlock *
MBB =
MI.getParent();
579 unsigned OldBrSize =
TII->getInstSizeInBytes(
MI);
580 MachineBasicBlock *DestBB =
TII->getBranchDestBlock(
MI);
582 int64_t DestOffset = BlockInfo[DestBB->
getNumber()].Offset;
583 int64_t SrcOffset = getInstrOffset(
MI);
588 : DestOffset - SrcOffset));
592 MachineBasicBlock *BranchBB =
MBB;
597 BranchBB = createNewBlockAfter(*
MBB);
601 for (
const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
608 if (TrampolineInsertionPoint ==
MBB)
609 TrampolineInsertionPoint = BranchBB;
613 MI.eraseFromParent();
618 MachineBasicBlock *RestoreBB =
624 TII->insertIndirectBranch(*BranchBB, *DestBB, *RestoreBB,
DL,
627 : DestOffset - SrcOffset,
632 BlockInfo[BranchBB->
getNumber()].Size = computeBlockSize(*BranchBB);
636 if (!RestoreBB->
empty()) {
641 MachineBasicBlock *NewBB = createNewBlockAfter(*TrampolineInsertionPoint);
642 TII->insertUnconditionalBranch(*NewBB, DestBB,
DebugLoc());
643 BlockInfo[NewBB->
getNumber()].Size = computeBlockSize(*NewBB);
644 adjustBlockOffsets(*TrampolineInsertionPoint,
648 TrampolineInsertionPoint = NewBB;
664 MachineBasicBlock *PrevBB = &*std::prev(DestBB->
getIterator());
669 TII->insertUnconditionalBranch(*PrevBB, FT,
DebugLoc());
670 BlockInfo[PrevBB->
getNumber()].Size = computeBlockSize(*PrevBB);
677 if (
TRI->trackLivenessAfterRegAlloc(*MF))
680 BlockInfo[RestoreBB->
getNumber()].Size = computeBlockSize(*RestoreBB);
682 adjustBlockOffsets(*PrevBB, DestBB->
getIterator());
688 RelaxedUnconditionals.insert({BranchBB, RestoreBB});
691 MF->erase(RestoreBB);
692 RelaxedUnconditionals.insert({BranchBB, DestBB});
698bool BranchRelaxation::relaxBranchInstructions() {
703 for (MachineBasicBlock &
MBB : *MF) {
714 if (
Last->isUnconditionalBranch()) {
717 if (MachineBasicBlock *DestBB =
TII->getBranchDestBlock(*
Last)) {
719 !RelaxedUnconditionals.contains({&MBB, DestBB})) {
720 fixupUnconditionalBranch(*
Last);
721 ++NumUnconditionalRelaxed;
732 MachineInstr &
MI = *J;
734 if (!
MI.isConditionalBranch())
737 if (
MI.getOpcode() == TargetOpcode::FAULTING_OP)
742 MachineBasicBlock *DestBB =
TII->getBranchDestBlock(
MI);
743 if (!isBlockInRange(
MI, *DestBB)) {
749 splitBlockBeforeInstr(*
Next, DestBB);
751 fixupConditionalBranch(
MI);
752 ++NumConditionalRelaxed;
767 adjustBlockOffsets(MF->front());
786 TII = ST.getInstrInfo();
789 TRI = ST.getRegisterInfo();
790 if (
TRI->trackLivenessAfterRegAlloc(*MF))
795 MF->RenumberBlocks();
801 LLVM_DEBUG(
dbgs() <<
" Basic blocks before relaxation\n"; dumpBBs(););
803 bool MadeChange =
false;
804 while (relaxBranchInstructions())
810 LLVM_DEBUG(
dbgs() <<
" Basic blocks after relaxation\n\n"; dumpBBs());
813 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)
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
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.
LLVM_ABI 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.
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.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
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.
LLVM_ABI void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
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