47 #define DEBUG_TYPE "tailduplication"
49 STATISTIC(NumTails,
"Number of tails duplicated");
50 STATISTIC(NumTailDups,
"Number of tail duplicated blocks");
52 "Number of instructions added due to tail duplication");
54 "Number of instructions removed due to tail duplication");
55 STATISTIC(NumDeadBlocks,
"Number of dead blocks removed");
56 STATISTIC(NumAddedPHIs,
"Number of phis added");
65 "tail-dup-indirect-size",
66 cl::desc(
"Maximum instructions to consider tail duplicating blocks that "
67 "end with indirect branches."),
cl::init(20),
72 cl::desc(
"Verify sanity of PHI instructions during taildup"),
80 bool LayoutModeIn,
unsigned TailDupSizeIn) {
87 TailDupSize = TailDupSizeIn;
89 assert(MBPI !=
nullptr &&
"Machine Branch Probability Info required");
91 LayoutMode = LayoutModeIn;
92 PreRegAlloc = MRI->
isSSA();
101 while (MI != MBB->
end()) {
106 for (
unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
108 if (PHIBB == PredBB) {
115 dbgs() <<
" missing input from predecessor BB#"
116 << PredBB->getNumber() <<
'\n';
121 for (
unsigned i = 1, e = MI->getNumOperands(); i != e; i += 2) {
123 if (CheckExtra && !Preds.count(PHIBB)) {
124 dbgs() <<
"Warning: malformed PHI in BB#" << MBB->
getNumber() <<
": "
126 dbgs() <<
" extra input from predecessor BB#" << PHIBB->
getNumber()
160 if (!tailDuplicate(IsSimple, MBB, ForcedLayoutPred, TDBBs, Copies))
173 updateSuccessorsPHIs(MBB, isDead, TDBBs, Succs);
177 NumTailDupRemoved += MBB->
size();
178 removeDeadBlock(MBB, RemovalCallback);
183 if (!SSAUpdateVRs.
empty()) {
184 for (
unsigned i = 0, e = SSAUpdateVRs.
size(); i != e; ++i) {
185 unsigned VReg = SSAUpdateVRs[i];
199 SSAUpdateVals.
find(VReg);
200 for (
unsigned j = 0, ee = LI->second.
size(); j != ee; ++j) {
202 unsigned SrcReg = LI->second[j].second;
226 SSAUpdateVRs.
clear();
227 SSAUpdateVals.
clear();
232 for (
unsigned i = 0, e = Copies.
size(); i != e; ++i) {
247 NumAddedPHIs += NewPHIs.
size();
250 *DuplicatedPreds = std::move(TDBBs);
259 bool MadeChange =
false;
262 DEBUG(
dbgs() <<
"\n*** Before tail-duplicating\n");
289 if (
UseMI.isDebugValue())
291 if (
UseMI.getParent() != BB)
309 for (
const auto &
MI : BB) {
312 for (
unsigned i = 1, e =
MI.getNumOperands(); i != e; i += 2) {
313 unsigned SrcReg =
MI.getOperand(i).getReg();
314 UsedByPhi->
insert(SrcReg);
320 void TailDuplicator::addSSAUpdateEntry(
unsigned OrigReg,
unsigned NewReg,
323 SSAUpdateVals.
find(OrigReg);
324 if (LI != SSAUpdateVals.
end())
325 LI->second.push_back(std::make_pair(BB, NewReg));
328 Vals.push_back(std::make_pair(BB, NewReg));
329 SSAUpdateVals.
insert(std::make_pair(OrigReg, Vals));
336 void TailDuplicator::processPHI(
343 assert(SrcOpIdx &&
"Unable to find matching PHI source?");
347 LocalVRMap.
insert(std::make_pair(DefReg, RegSubRegPair(SrcReg, SrcSubReg)));
352 Copies.push_back(std::make_pair(NewDef, RegSubRegPair(SrcReg, SrcSubReg)));
354 addSSAUpdateEntry(DefReg, NewDef, PredBB);
368 void TailDuplicator::duplicateInstruction(
385 LocalVRMap.
insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
387 addSSAUpdateEntry(Reg, NewReg, PredBB);
389 auto VI = LocalVRMap.
find(Reg);
390 if (
VI != LocalVRMap.
end()) {
397 if (
VI->second.SubReg != 0) {
425 if (NewRC ==
nullptr)
429 TII->
get(TargetOpcode::COPY), NewReg)
430 .addReg(
VI->second.Reg, 0,
VI->second.SubReg);
432 LocalVRMap.
insert(std::make_pair(Reg, RegSubRegPair(NewReg, 0)));
452 void TailDuplicator::updateSuccessorsPHIs(
464 if (MO.
getMBB() == FromBB) {
472 unsigned Reg = MO0.
getReg();
479 if (MO.
getMBB() == FromBB) {
491 SSAUpdateVals.
find(Reg);
492 if (LI != SSAUpdateVals.
end()) {
494 for (
unsigned j = 0, ee = LI->second.
size(); j != ee; ++j) {
503 unsigned SrcReg = LI->second[j].second;
509 MIB.addReg(SrcReg).addMBB(SrcBB);
514 for (
unsigned j = 0, ee = TDBBs.
size(); j != ee; ++j) {
521 MIB.addReg(Reg).addMBB(SrcBB);
549 unsigned MaxDuplicateCount;
550 if (TailDupSize == 0 &&
553 MaxDuplicateCount = 1;
554 else if (TailDupSize == 0)
557 MaxDuplicateCount = TailDupSize;
565 if (TII->
analyzeBranch(TailBB, PredTBB, PredFBB, PredCond) &&
575 bool HasIndirectbr =
false;
579 if (HasIndirectbr && PreRegAlloc)
604 if (PreRegAlloc && MI.
isCall())
610 if (InstrCount > MaxDuplicateCount)
623 for (
auto SB : TailBB.successors()) {
624 for (
auto &
I : *
SB) {
635 if (HasIndirectbr && PreRegAlloc)
644 return canCompletelyDuplicateBB(TailBB);
654 if (I == TailBB->
end())
656 return I->isUnconditionalBranch();
678 if (!PredCond.
empty())
684 bool TailDuplicator::duplicateSimpleBB(
692 bool Changed =
false;
706 DEBUG(
dbgs() <<
"\nTail-duplicating into PredBB: " << *PredBB
707 <<
"From simple Succ: " << *TailBB);
713 if (PredCond.
empty())
723 if (PredFBB == TailBB)
725 if (PredTBB == TailBB)
729 if (PredTBB == PredFBB) {
735 if (PredFBB == NextBB)
737 if (PredTBB == NextBB && PredFBB ==
nullptr)
768 if (!PredCond.
empty())
793 return duplicateSimpleBB(TailBB, TDBBs, UsedByPhi, Copies);
798 bool Changed =
false;
802 assert(TailBB != PredBB &&
803 "Single-block loop should have been rejected earlier!");
809 bool IsLayoutSuccessor =
false;
810 if (ForcedLayoutPred)
811 IsLayoutSuccessor = (ForcedLayoutPred == PredBB);
813 IsLayoutSuccessor =
true;
814 if (IsLayoutSuccessor)
817 DEBUG(
dbgs() <<
"\nTail-duplicating into PredBB: " << *PredBB
818 <<
"From Succ: " << *TailBB);
837 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi,
true);
841 duplicateInstruction(MI, TailBB, PredBB, LocalVRMap, UsedByPhi);
844 appendCopies(PredBB, CopyInfos, Copies);
851 NumTailDupAdded += TailBB->
size() - 1;
856 "TailDuplicate called on block with multiple successors!");
877 !TII->
analyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond) &&
879 (!PriorTBB || PriorTBB == TailBB) &&
882 DEBUG(
dbgs() <<
"\nMerging into block: " << *PrevBB
883 <<
"From MBB: " << *TailBB);
893 while (I != TailBB->
end() && I->isPHI()) {
897 processPHI(MI, TailBB, PrevBB, LocalVRMap, CopyInfos, UsedByPhi,
true);
901 while (I != TailBB->
end()) {
905 assert(!MI->
isBundle() &&
"Not expecting bundles before regalloc!");
906 duplicateInstruction(MI, TailBB, PrevBB, LocalVRMap, UsedByPhi);
909 appendCopies(PrevBB, CopyInfos, Copies);
956 while (I != TailBB->
end() && I->isPHI()) {
960 processPHI(MI, TailBB, PredBB, LocalVRMap, CopyInfos, UsedByPhi,
false);
962 appendCopies(PredBB, CopyInfos, Copies);
975 for (
auto &CI : CopyInfos) {
977 .
addReg(CI.second.Reg, 0, CI.second.SubReg);
984 void TailDuplicator::removeDeadBlock(
988 DEBUG(
dbgs() <<
"\nRemoving MBB: " << *MBB);
991 (*RemovalCallback)(MBB);
bool shouldTailDuplicate(bool IsSimple, MachineBasicBlock &TailBB)
Determine if it is profitable to duplicate this block.
unsigned succ_size() const
void push_back(const T &Elt)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
virtual MachineInstr * duplicate(MachineInstr &Orig, MachineFunction &MF) const
Create a duplicate of the Orig instruction in MF.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
instr_iterator instr_begin()
static cl::opt< unsigned > TailDuplicateSize("tail-dup-size", cl::desc("Maximum instructions to consider tail duplicating"), cl::init(2), cl::Hidden)
instr_iterator instr_end()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
STATISTIC(NumFunctions,"Total number of functions")
MachineBasicBlock * getMBB() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
unsigned createVirtualRegister(const TargetRegisterClass *RegClass)
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator getFirstNonDebugInstr()
Returns an iterator to the first non-debug instruction in the basic block, or end().
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Describe properties that are true of each instruction in the target description file.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
static void VerifyPHIs(MachineFunction &MF, bool CheckExtra)
An efficient, type-erasing, non-owning reference to a callable.
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
void RewriteUse(MachineOperand &U)
RewriteUse - Rewrite a use of the symbolic value.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
static unsigned InstrCount
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
MachineSSAUpdater - This class updates SSA form for a set of virtual registers defined in multiple bl...
iterator_range< succ_iterator > successors()
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
static use_iterator use_end()
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
static bool bothUsedInPHI(const MachineBasicBlock &A, const SmallPtrSet< MachineBasicBlock *, 8 > &SuccsB)
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
Reg
All possible values of the reg field in the ModR/M byte.
LLVM_NODISCARD bool empty() const
unsigned getNumOperands() const
Access to explicit operands of the instruction.
bool tailDuplicateBlocks()
Look for small blocks that are unconditionally branched to and do not fall through.
void RemoveOperand(unsigned i)
Erase an operand from an instruction, leaving it with one fewer operand than it started with...
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
virtual const TargetRegisterClass * getMatchingSuperRegClass(const TargetRegisterClass *A, const TargetRegisterClass *B, unsigned Idx) const
Return a subclass of the specified register class A so that each register in it has a sub-register of...
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void Initialize(unsigned V)
Initialize - Reset this object to get ready for a new set of SSA updates.
bool isConvergent(QueryType Type=AnyInBundle) const
Return true if this instruction is convergent.
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
const MachineBasicBlock * getParent() const
iterator find(const_arg_type_t< KeyT > Val)
bool isDebugValue() const
static bool isSimpleBB(MachineBasicBlock *TailBB)
True if this BB has only one unconditional jump.
INITIALIZE_PASS(HexagonEarlyIfConversion,"hexagon-eif","Hexagon early if conversion", false, false) bool HexagonEarlyIfConversion MachineBasicBlock * SB
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
bool isReturn(QueryType Type=AnyInBundle) const
unsigned const MachineRegisterInfo * MRI
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
MachineInstrBuilder & UseMI
const MachineOperand & getOperand(unsigned i) const
std::pair< iterator, bool > insert(const ValueT &V)
bool canTailDuplicate(MachineBasicBlock *TailBB, MachineBasicBlock *PredBB)
Returns true if TailBB can successfully be duplicated into PredBB.
bool isIndirectBranch(QueryType Type=AnyInBundle) const
Return true if this is an indirect branch, such as a branch through a register.
void setMBB(MachineBasicBlock *MBB)
self_iterator getIterator()
iterator_range< pred_iterator > predecessors()
void initMF(MachineFunction &MF, const MachineBranchProbabilityInfo *MBPI, bool LayoutMode, unsigned TailDupSize=0)
Prepare to run on a specific machine function.
succ_iterator succ_begin()
unsigned getSubReg() const
iterator_range< use_instr_iterator > use_instructions(unsigned Reg) const
bool isNotDuplicable(QueryType Type=AnyInBundle) const
Return true if this instruction cannot be safely duplicated.
pred_iterator pred_begin()
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
void setIsKill(bool Val=true)
A SetVector that performs no allocations if smaller than a certain size.
bool hasEHPadSuccessor() const
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
static bool isDefLiveOut(unsigned Reg, MachineBasicBlock *BB, const MachineRegisterInfo *MRI)
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
static unsigned getPHISrcRegOpIdx(MachineInstr *MI, MachineBasicBlock *SrcBB)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const TargetRegisterClass * getRegClassConstraint(unsigned OpIdx, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Compute the static register class constraint for operand OpIdx.
static cl::opt< unsigned > TailDupLimit("tail-dup-limit", cl::init(~0U), cl::Hidden)
void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
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 '...
static cl::opt< unsigned > TailDupIndirectBranchSize("tail-dup-indirect-size", cl::desc("Maximum instructions to consider tail duplicating blocks that ""end with indirect branches."), cl::init(20), cl::Hidden)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
use_iterator use_begin(unsigned RegNo) const
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
void setReg(unsigned Reg)
Change the register this operand corresponds to.
bool isCall(QueryType Type=AnyInBundle) const
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void setSubReg(unsigned subReg)
void AddAvailableValue(MachineBasicBlock *BB, unsigned V)
AddAvailableValue - Indicate that a rewritten value is available at the end of the specified block wi...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
Instructions::iterator instr_iterator
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void setRegClass(unsigned Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
MachineModuleInfo & getMMI() const
unsigned composeSubRegIndices(unsigned a, unsigned b) const
Return the subregister index you get from composing two subregister indices.
bool tailDuplicateAndUpdate(bool IsSimple, MachineBasicBlock *MBB, MachineBasicBlock *ForcedLayoutPred, SmallVectorImpl< MachineBasicBlock * > *DuplicatedPreds=nullptr, function_ref< void(MachineBasicBlock *)> *RemovalCallback=nullptr)
Tail duplicate a single basic block into its predecessors, and then clean up.
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
static void getRegsUsedByPHIs(const MachineBasicBlock &BB, DenseSet< unsigned > *UsedByPhi)
static cl::opt< bool > TailDupVerify("tail-dup-verify", cl::desc("Verify sanity of PHI instructions during taildup"), cl::init(false), cl::Hidden)
unsigned pred_size() const
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.