43 #define DEBUG_TYPE "early-ifcvt" 49 cl::desc(
"Maximum number of instructions per speculated block."));
55 STATISTIC(NumDiamondsSeen,
"Number of diamonds");
56 STATISTIC(NumDiamondsConv,
"Number of diamonds converted");
57 STATISTIC(NumTrianglesSeen,
"Number of triangles");
58 STATISTIC(NumTrianglesConv,
"Number of triangles converted");
102 bool isTriangle()
const {
return TBB == Tail || FBB ==
Tail; }
115 int CondCycles, TCycles, FCycles;
118 : PHI(phi), TReg(0), FReg(0), CondCycles(0), TCycles(0), FCycles(0) {}
158 bool findInsertionPoint();
161 void replacePHIInstrs();
164 void rewritePHIOperands();
172 LiveRegUnits.
clear();
174 ClobberedRegUnits.
clear();
214 if (
I->isDebugInstr())
238 bool DontMoveAcrossStore =
true;
239 if (!
I->isSafeToMove(
nullptr, DontMoveAcrossStore)) {
245 if (!InstrDependenciesAllowIfConv(&(*
I)))
255 bool SSAIfConv::InstrDependenciesAllowIfConv(
MachineInstr *
I) {
257 if (MO.isRegMask()) {
268 ClobberedRegUnits.
set(*Units);
273 if (!DefMI || DefMI->
getParent() != Head)
275 if (InsertAfter.
insert(DefMI).second)
279 LLVM_DEBUG(
dbgs() <<
"Can't insert instructions below terminator.\n");
302 unsigned InstrCount = 0;
331 if (!InstrDependenciesAllowIfConv(&(*I)))
339 auto Condition = Cond;
340 if (ReversePredicate)
362 bool SSAIfConv::findInsertionPoint() {
365 LiveRegUnits.
clear();
373 if (InsertAfter.
count(&*I)) {
389 LiveRegUnits.
erase(*Units);
395 while (!Reads.
empty())
398 if (ClobberedRegUnits.
test(*Units))
399 LiveRegUnits.
insert(*Units);
402 if (I != FirstTerm && I->isTerminator())
407 if (!LiveRegUnits.
empty()) {
409 dbgs() <<
"Would clobber";
411 i = LiveRegUnits.
begin(),
e = LiveRegUnits.
end(); i !=
e; ++i)
413 dbgs() <<
" live before " << *
I;
434 TBB = FBB = Tail =
nullptr;
489 LLVM_DEBUG(
dbgs() <<
"AnalyzeBranch didn't find conditional branch.\n");
496 LLVM_DEBUG(
dbgs() <<
"AnalyzeBranch found an unconditional branch.\n");
502 FBB = TBB == Succ0 ? Succ1 : Succ0;
509 I !=
E && I->isPHI(); ++
I) {
511 PHIInfo &PI = PHIs.
back();
513 for (
unsigned i = 1; i != PI.PHI->getNumOperands(); i += 2) {
514 if (PI.PHI->getOperand(i+1).getMBB() == TPred)
515 PI.TReg = PI.PHI->getOperand(i).getReg();
516 if (PI.PHI->getOperand(i+1).getMBB() == FPred)
517 PI.FReg = PI.PHI->getOperand(i).getReg();
524 PI.CondCycles, PI.TCycles, PI.FCycles)) {
532 ClobberedRegUnits.
reset();
534 if (TBB != Tail && !canPredicateInstrs(TBB))
536 if (FBB != Tail && !canPredicateInstrs(FBB))
539 if (TBB != Tail && !canSpeculateInstrs(TBB))
541 if (FBB != Tail && !canSpeculateInstrs(FBB))
547 if (!findInsertionPoint())
560 void SSAIfConv::replacePHIInstrs() {
563 assert(FirstTerm != Head->
end() &&
"No terminators");
564 DebugLoc HeadDL = FirstTerm->getDebugLoc();
567 for (
unsigned i = 0,
e = PHIs.
size(); i !=
e; ++i) {
568 PHIInfo &PI = PHIs[i];
570 Register DstReg = PI.PHI->getOperand(0).getReg();
571 TII->
insertSelect(*Head, FirstTerm, HeadDL, DstReg, Cond, PI.TReg, PI.FReg);
573 PI.PHI->eraseFromParent();
581 void SSAIfConv::rewritePHIOperands() {
583 assert(FirstTerm != Head->
end() &&
"No terminators");
584 DebugLoc HeadDL = FirstTerm->getDebugLoc();
587 for (
unsigned i = 0,
e = PHIs.
size(); i !=
e; ++i) {
588 PHIInfo &PI = PHIs[i];
592 if (PI.TReg == PI.FReg) {
597 Register PHIDst = PI.PHI->getOperand(0).getReg();
600 DstReg, Cond, PI.TReg, PI.FReg);
605 for (
unsigned i = PI.PHI->getNumOperands(); i != 1; i -= 2) {
607 if (MBB == getTPred()) {
608 PI.PHI->getOperand(i-1).setMBB(Head);
609 PI.PHI->getOperand(i-2).setReg(DstReg);
610 }
else if (MBB == getFPred()) {
611 PI.PHI->RemoveOperand(i-1);
612 PI.PHI->RemoveOperand(i-2);
626 assert(Head && Tail && TBB && FBB &&
"Call canConvertIf first.");
637 PredicateBlock(TBB,
false);
642 PredicateBlock(FBB,
true);
646 bool ExtraPreds = Tail->
pred_size() != 2;
648 rewritePHIOperands();
690 TII->
insertBranch(*Head, Tail,
nullptr, EmptyCond, HeadDL);
717 StringRef getPassName()
const override {
return "Early If-Conversion"; }
721 void invalidateTraces();
722 bool shouldConvertIf();
730 "Early If Converter",
false,
false)
737 void EarlyIfConverter::getAnalysisUsage(
AnalysisUsage &AU)
const {
756 for (
auto B : Removed) {
758 assert(Node != HeadNode &&
"Cannot erase the head node");
774 for (
auto B : Removed)
780 void EarlyIfConverter::invalidateTraces() {
781 Traces->verifyAnalysis();
782 Traces->invalidate(IfConv.Head);
783 Traces->invalidate(IfConv.Tail);
784 Traces->invalidate(IfConv.TBB);
785 Traces->invalidate(IfConv.FBB);
786 Traces->verifyAnalysis();
791 if (Delta < 0 && Cyc + Delta > Cyc)
799 bool EarlyIfConverter::shouldConvertIf() {
814 unsigned CritLimit = SchedModel.MispredictPenalty/2;
820 if (IfConv.TBB != IfConv.Tail)
824 <<
", minimal critical path " << MinCrit <<
'\n');
825 if (ResLength > MinCrit + CritLimit) {
834 unsigned BranchDepth =
841 for (
unsigned i = 0,
e = IfConv.PHIs.size(); i !=
e; ++i) {
842 SSAIfConv::PHIInfo &PI = IfConv.PHIs[i];
848 unsigned CondDepth =
adjCycles(BranchDepth, PI.CondCycles);
849 if (CondDepth > MaxDepth) {
850 unsigned Extra = CondDepth -
MaxDepth;
852 if (Extra > CritLimit) {
860 if (TDepth > MaxDepth) {
863 if (Extra > CritLimit) {
871 if (FDepth > MaxDepth) {
874 if (Extra > CritLimit) {
886 bool Changed =
false;
887 while (IfConv.canConvertIf(MBB) && shouldConvertIf()) {
891 IfConv.convertIf(RemovedBlocks);
893 updateDomTree(DomTree, IfConv, RemovedBlocks);
894 updateLoops(
Loops, RemovedBlocks);
900 LLVM_DEBUG(
dbgs() <<
"********** EARLY IF-CONVERSION **********\n" 901 <<
"********** Function: " << MF.
getName() <<
'\n');
914 DomTree = &getAnalysis<MachineDominatorTree>();
915 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
916 Traces = &getAnalysis<MachineTraceMetrics>();
919 bool Changed =
false;
920 IfConv.runOnMachineFunction(MF);
927 if (tryConvertIf(DomNode->getBlock()))
953 StringRef getPassName()
const override {
return "Early If-predicator"; }
957 bool shouldConvertIf();
962 #define DEBUG_TYPE "early-if-predicator" 974 void EarlyIfPredicator::getAnalysisUsage(
AnalysisUsage &AU)
const {
984 bool EarlyIfPredicator::shouldConvertIf() {
985 auto TrueProbability = MBPI->getEdgeProbability(IfConv.Head, IfConv.TBB);
986 if (IfConv.isTriangle()) {
988 (IfConv.TBB == IfConv.Tail) ? *IfConv.FBB : *IfConv.TBB;
990 unsigned ExtraPredCost = 0;
993 unsigned NumCycles = SchedModel.computeInstrLatency(&I,
false);
995 Cycles += NumCycles - 1;
1002 unsigned TExtra = 0;
1003 unsigned FExtra = 0;
1004 unsigned TCycle = 0;
1005 unsigned FCycle = 0;
1007 unsigned NumCycles = SchedModel.computeInstrLatency(&I,
false);
1009 TCycle += NumCycles - 1;
1013 unsigned NumCycles = SchedModel.computeInstrLatency(&I,
false);
1015 FCycle += NumCycles - 1;
1019 FCycle, FExtra, TrueProbability);
1025 bool Changed =
false;
1026 while (IfConv.canConvertIf(MBB,
true) && shouldConvertIf()) {
1029 IfConv.convertIf(RemovedBlocks,
true);
1031 updateDomTree(DomTree, IfConv, RemovedBlocks);
1032 updateLoops(
Loops, RemovedBlocks);
1038 LLVM_DEBUG(
dbgs() <<
"********** EARLY IF-PREDICATOR **********\n" 1039 <<
"********** Function: " << MF.
getName() <<
'\n');
1047 SchedModel.init(&STI);
1048 DomTree = &getAnalysis<MachineDominatorTree>();
1049 Loops = getAnalysisIfAvailable<MachineLoopInfo>();
1050 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1052 bool Changed =
false;
1053 IfConv.runOnMachineFunction(MF);
1060 if (tryConvertIf(DomNode->getBlock()))
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
static cl::opt< bool > Stress("stress-early-ifcvt", cl::Hidden, cl::desc("Turn all knobs to 11"))
virtual bool canInsertSelect(const MachineBasicBlock &MBB, ArrayRef< MachineOperand > Cond, unsigned TrueReg, unsigned FalseReg, int &CondCycles, int &TrueCycles, int &FalseCycles) const
Return true if it is possible to insert a select instruction that chooses between TrueReg and FalseRe...
MachineDomTreeNode * getNode(MachineBasicBlock *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
virtual void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, unsigned DstReg, ArrayRef< MachineOperand > Cond, unsigned TrueReg, unsigned FalseReg) const
Insert a select instruction into MBB before I that will copy TrueReg to DstReg when Cond is true...
This class represents lattice values for constants.
std::pair< iterator, bool > insert(const ValueT &Val)
insert - Attempts to insert a new element.
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
unsigned Depth
Earliest issue cycle as determined by data dependencies and instruction latencies from the beginning ...
void push_back(const T &Elt)
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
bool test(unsigned Idx) const
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.
char & EarlyIfConverterID
EarlyIfConverter - This pass performs if-conversion on SSA form by inserting cmov instructions...
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A trace ensemble is a collection of traces selected using the same strategy, for example 'minimum res...
static unsigned InstrCount
iterator_range< mop_iterator > operands()
void eraseNode(MachineBasicBlock *BB)
eraseNode - Removes a node from the dominator tree.
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
unsigned getNumRegUnits() const
Return the number of (native) register units in the target.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
virtual bool enableEarlyIfConversion() const
Enable the use of the early if conversion pass.
#define INITIALIZE_PASS_DEPENDENCY(depName)
void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Provide an instruction scheduling machine model to CodeGen passes.
const HexagonInstrInfo * TII
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
void removeBlock(MachineBasicBlock *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
char & EarlyIfPredicatorID
EarlyIfPredicator - This pass performs if-conversion on SSA form by predicating if/else block and ins...
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
Select the trace through a block that has the fewest instructions.
INITIALIZE_PASS_BEGIN(EarlyIfConverter, DEBUG_TYPE, "Early If Converter", false, false) INITIALIZE_PASS_END(EarlyIfConverter
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const std::vector< DomTreeNodeBase * > & getChildren() const
virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const
Return true if it's profitable to predicate instructions with accumulated instruction latency of "Num...
virtual const TargetInstrInfo * getInstrInfo() const
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
iterator erase(iterator I)
erase - Erases an existing element identified by a valid iterator.
TargetInstrInfo - Interface to description of machine instruction set.
bool empty() const
empty - Returns true if the set is empty.
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
unsigned const MachineRegisterInfo * MRI
virtual unsigned getPredicationCost(const MachineInstr &MI) const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
unsigned getCriticalPath() const
Return the length of the (data dependency) critical path through the trace.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
InstrCycles getInstrCycles(const MachineInstr &MI) const
Return the depth and height of MI.
Represent the analysis usage information of a pass.
iterator_range< po_iterator< T > > post_order(const T &G)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool livein_empty() const
void setUniverse(unsigned U)
setUniverse - Set the universe size which determines the largest key the set can hold.
succ_iterator succ_begin()
virtual bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Pred) const
Convert the instruction into a predicated instruction.
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...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A trace represents a plausible sequence of executed basic blocks that passes through the current basi...
const_iterator end() const
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
bool isDebugInstr() const
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
static unsigned adjCycles(unsigned Cyc, int Delta)
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.
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_t getNumChildren() const
MachineInstrBuilder MachineInstrBuilder & DefMI
const_iterator begin() const
LLVM_NODISCARD T pop_back_val()
unsigned pred_size() 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 Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static cl::opt< unsigned > BlockInstrLimit("early-ifcvt-limit", cl::init(30), cl::Hidden, cl::desc("Maximum number of instructions per speculated block."))
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
virtual bool isPredicable(const MachineInstr &MI) const
Return true if the specified instruction can be predicated.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
unsigned succ_size() const
const MachineBasicBlock * getParent() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
TargetSubtargetInfo - Generic base class for all target subtargets.
Representation of each machine instruction.
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 '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Tail - This calling convention attemps to make calls as fast as possible while guaranteeing that tail...
A set of register units used to track register liveness.
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
void changeImmediateDominator(MachineBasicBlock *N, MachineBasicBlock *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
void clear()
clear - Clears the set.
unsigned getPHIDepth(const MachineInstr &PHI) const
Return the Depth of a PHI instruction in a trace center block successor.
virtual bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const
Reverses the branch condition of the specified condition list, returning false on success and true if...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
unsigned getResourceLength(ArrayRef< const MachineBasicBlock *> Extrablocks=None, ArrayRef< const MCSchedClassDesc *> ExtraInstrs=None, ArrayRef< const MCSchedClassDesc *> RemoveInstrs=None) const
Return the resource length of the trace.
StringRef - Represent a constant reference to a string, i.e.
unsigned getInstrSlack(const MachineInstr &MI) const
Return the slack of MI.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
Machine model for scheduling, bundling, and heuristics.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
Wrapper class representing virtual and physical registers.