52 #define DEBUG_TYPE "loop-unroll" 54 STATISTIC(NumPeeled,
"Number of loops peeled");
58 cl::desc(
"Max average trip count which will cause loop peeling."));
62 cl::desc(
"Force a peel count regardless of profiling information."));
66 cl::desc(
"Allow peeling of loops with multiple deopt exits."));
129 "Non-loop Phi should not be checked for turning into invariant.");
132 auto I = IterationsToInvariance.
find(Phi);
133 if (I != IterationsToInvariance.
end())
145 else if (
PHINode *IncPhi = dyn_cast<PHINode>(Input)) {
147 if (IncPhi->getParent() != L->
getHeader())
148 return InfiniteIterationsToInvariance;
152 IncPhi, L, BackEdge, IterationsToInvariance);
153 if (InputToInvariance != InfiniteIterationsToInvariance)
154 ToInvariance = InputToInvariance + 1u;
158 if (ToInvariance != InfiniteIterationsToInvariance)
159 IterationsToInvariance[Phi] = ToInvariance;
175 unsigned DesiredPeelCount = 0;
177 for (
auto *BB : L.
blocks()) {
179 if (!BI || BI->isUnconditional())
186 Value *Condition = BI->getCondition();
187 Value *LeftVal, *RightVal;
204 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
205 if (isa<SCEVAddRecExpr>(RightSCEV)) {
226 unsigned NewPeelCount = DesiredPeelCount;
239 auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step,
241 IterVal = NextIterVal;
242 NextIterVal = SE.getAddExpr(IterVal, Step);
246 auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() {
247 return NewPeelCount < MaxPeelCount;
250 while (CanPeelOneMoreIteration() &&
251 SE.isKnownPredicate(Pred, IterVal, RightSCEV))
252 PeelOneMoreIteration();
266 assert(!SE.isKnownPredicate(Pred, IterVal, RightSCEV) &&
267 SE.isKnownPredicate(Pred, NextIterVal, RightSCEV) &&
268 "Expected Pred to go from known to unknown.");
269 if (!CanPeelOneMoreIteration())
271 PeelOneMoreIteration();
274 DesiredPeelCount =
std::max(DesiredPeelCount, NewPeelCount);
277 return DesiredPeelCount;
284 assert(LoopSize > 0 &&
"Zero loop size is not allowed!");
300 <<
" iterations.\n");
310 unsigned AlreadyPeeled = 0;
312 AlreadyPeeled = *Peeled;
323 if (2 * LoopSize <= UP.Threshold && UnrollPeelMaxCount > 0) {
330 unsigned DesiredPeelCount = TargetPeelCount;
332 assert(BackEdge &&
"Loop is not in simplified form?");
333 for (
auto BI = L->
getHeader()->
begin(); isa<PHINode>(&*BI); ++BI) {
334 PHINode *Phi = cast<PHINode>(&*BI);
336 Phi, L, BackEdge, IterationsToInvariance);
337 if (ToInvariance != InfiniteIterationsToInvariance)
338 DesiredPeelCount =
std::max(DesiredPeelCount, ToInvariance);
343 MaxPeelCount = std::min(MaxPeelCount, UP.
Threshold / LoopSize - 1);
345 DesiredPeelCount =
std::max(DesiredPeelCount,
348 if (DesiredPeelCount > 0) {
349 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount);
351 assert(DesiredPeelCount > 0 &&
"Wrong loop size estimation?");
354 <<
" iteration(s) to turn" 355 <<
" some Phis into invariants.\n");
381 LLVM_DEBUG(
dbgs() <<
"Profile-based estimated trip count is " << *PeelCount
386 (LoopSize * (*PeelCount + 1) <= UP.
Threshold)) {
388 <<
" iterations.\n");
392 LLVM_DEBUG(
dbgs() <<
"Requested peel count: " << *PeelCount <<
"\n");
393 LLVM_DEBUG(
dbgs() <<
"Already peel count: " << AlreadyPeeled <<
"\n");
424 uint64_t &FallThroughWeight) {
427 if (!FallThroughWeight)
430 unsigned HeaderIdx = (LatchBR->
getSuccessor(0) == Header ? 0 : 1);
433 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight)
434 : MDB.createBranchWeights(FallThroughWeight, ExitWeight);
435 LatchBR->
setMetadata(LLVMContext::MD_prof, WeightNode);
437 FallThroughWeight > ExitWeight ? FallThroughWeight - ExitWeight : 1;
447 uint64_t &ExitWeight,
448 uint64_t &FallThroughWeight) {
449 uint64_t TrueWeight, FalseWeight;
452 unsigned HeaderIdx = LatchBR->
getSuccessor(0) == Header ? 0 : 1;
453 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
454 FallThroughWeight = HeaderIdx ? FalseWeight : TrueWeight;
465 uint64_t FallThroughWeight) {
468 if (!FallThroughWeight)
473 unsigned HeaderIdx = LatchBR->
getSuccessor(0) == Header ? 0 : 1;
475 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight)
476 : MDB.createBranchWeights(FallThroughWeight, ExitWeight);
477 LatchBR->
setMetadata(LLVMContext::MD_prof, WeightNode);
539 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
541 for (
unsigned idx = 0,
e = LatchBR->getNumSuccessors(); idx <
e; ++idx)
542 if (LatchBR->getSuccessor(idx) == Header) {
558 PHINode *NewPHI = cast<PHINode>(VMap[&*
I]);
559 if (IterNumber == 0) {
564 if (LatchInst && L->
contains(LatchInst))
565 VMap[&*
I] = LVMap[LatchInst];
567 VMap[&*
I] = LatchVal;
569 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
576 for (
auto Edge : ExitEdges)
577 for (
PHINode &PHI : Edge.second->phis()) {
578 Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first);
580 if (LatchInst && L->
contains(LatchInst))
581 LatchVal = VMap[LatchVal];
582 PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first]));
588 LVMap[KV.first] = KV.second;
603 assert(PeelCount > 0 &&
"Attempt to peel out zero iterations?");
604 assert(
canPeel(L) &&
"Attempt to peel a loop which is not peelable?");
636 for (
auto Edge : ExitEdges) {
637 if (ExitIDom.
count(Edge.second))
642 ExitIDom[Edge.second] = BB;
701 NewPreHeader->setName(PreHeader->
getName() +
".peel.newph");
708 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
709 uint64_t ExitWeight = 0, FallThroughWeight = 0;
713 for (
unsigned Iter = 0; Iter < PeelCount; ++Iter) {
718 LoopBlocks, VMap, LVMap, DT, LI);
729 for (
auto Exit : ExitIDom)
731 cast<BasicBlock>(LVMap[Exit.second]));
732 #ifdef EXPENSIVE_CHECKS 737 auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]);
741 LatchBRCopy->setMetadata(LLVMContext::MD_loop,
nullptr);
743 InsertTop = InsertBot;
749 NewBlocks[0]->getIterator(), F->
end());
758 if (LatchInst && L->
contains(LatchInst))
759 NewVal = LVMap[LatchInst];
767 unsigned AlreadyPeeled = 0;
769 AlreadyPeeled = *Peeled;
782 simplifyLoop(L, DT, LI, SE, AC,
nullptr, PreserveLCSSA);
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
static void cloneLoopBlocks(Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, SmallVectorImpl< std::pair< BasicBlock *, BasicBlock *> > &ExitEdges, SmallVectorImpl< BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, LoopInfo *LI)
Clones the body of the loop L, putting it between InsertTop and InsertBot.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static const char * PeeledCountMetaData
const SCEV * getConstant(ConstantInt *V)
This class represents lattice values for constants.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
void push_back(const T &Elt)
The main scalar evolution driver.
static cl::opt< bool > UnrollPeelMultiDeoptExit("unroll-peel-multi-deopt-exit", cl::init(true), cl::Hidden, cl::desc("Allow peeling of loops with multiple deopt exits."))
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
bool isMonotonicPredicate(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred, bool &Increasing)
Return true if, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or...
STATISTIC(NumFunctions, "Total number of functions")
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
iterator begin()
Instruction iterator methods.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
static unsigned calculateIterationsToInvariance(PHINode *Phi, Loop *L, BasicBlock *BackEdge, SmallDenseMap< PHINode *, unsigned > &IterationsToInvariance)
bool match(Val *V, const Pattern &P)
static cl::opt< unsigned > UnrollPeelMaxCount("unroll-peel-max-count", cl::init(7), cl::Hidden, cl::desc("Max average trip count which will cause loop peeling."))
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const Loop * getLoop() const
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void setName(const Twine &Name)
Change the name of the value.
RPOIterator endRPO() const
BlockT * getHeader() const
void computePeelCount(Loop *L, unsigned LoopSize, TargetTransformInfo::UnrollingPreferences &UP, unsigned &TripCount, ScalarEvolution &SE)
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS...
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
This node represents a polynomial recurrence on the trip count of the specified loop.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR, uint64_t ExitWeight, uint64_t FallThroughWeight)
Update the weights of original Latch block after peeling off all iterations.
iterator find(const_arg_type_t< KeyT > Val)
initializer< Ty > init(const Ty &Val)
llvm::Optional< int > getOptionalIntLoopAttribute(Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
LLVM Basic Block Representation.
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop...
Conditional or Unconditional Branch instruction.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
static cl::opt< unsigned > UnrollForcePeelCount("unroll-force-peel-count", cl::init(0), cl::Hidden, cl::desc("Force a peel count regardless of profiling information."))
DomTreeNodeBase * getIDom() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, bool PreserveLCSSA)
Peel off the first PeelCount iterations of loop L.
static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, ScalarEvolution &SE)
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
void splice(iterator where, iplist_impl &L2)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
self_iterator getIterator()
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR, uint64_t &ExitWeight, uint64_t &FallThroughWeight)
Initialize the weights.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void getUniqueNonLatchExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop except successors from Latch block are not considered...
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Iterator for intrusive lists based on ilist_node.
Type * getType() const
Return the LLVM type of this SCEV expression.
Align max(MaybeAlign Lhs, Align Rhs)
static const unsigned InfiniteIterationsToInvariance
bool hasNoSelfWrap() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool isConditional() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Store the result of a depth first search within basic blocks contained by a single loop...
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
LoopT * getParentLoop() const
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
This class represents an analyzed expression in the program.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isEquality() const
Return true if this predicate is either EQ or NE.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR, uint64_t ExitWeight, uint64_t &FallThroughWeight)
Update the branch weights of the latch of a peeled-off loop iteration.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
iterator_range< block_iterator > blocks() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
const BasicBlock * getParent() const
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
void forgetTopmostLoop(const Loop *L)
void remapInstructionsInBlocks(const SmallVectorImpl< BasicBlock *> &Blocks, ValueToValueMapTy &VMap)
Remaps instructions in Blocks using the mapping in VMap.