43 #define DEBUG_TYPE "loop-unroll" 46 STATISTIC(NumCompletelyUnrolled,
"Number of loops completely unrolled");
47 STATISTIC(NumUnrolled,
"Number of loops unrolled (completely or otherwise)");
51 cl::desc(
"Allow runtime unrolled loops to be unrolled " 52 "with epilog instead of prolog."));
56 cl::desc(
"Verify domtree after unrolling"),
57 #ifdef EXPENSIVE_CHECKS
72 if (
auto *V = dyn_cast<MetadataAsValue>(Op))
73 if (
auto *Unwrapped = dyn_cast<ValueAsMetadata>(V->getMetadata())) {
74 Op = Unwrapped->getValue();
88 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
89 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
92 PN->setIncomingBlock(i, cast<BasicBlock>(It->
second));
107 if (!OnlyPred)
return nullptr;
113 << OnlyPred->
getName() <<
"\n");
140 for (
auto *DI : Children)
172 for (
Use &U :
I.operands()) {
173 if (
auto Def = dyn_cast<Instruction>(U)) {
195 assert(OldLoop &&
"Should (at least) be in the loop being unrolled!");
197 Loop *&NewLoop = NewLoops[OldLoop];
201 "Header should be first in RPO");
211 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
247 assert(PreHeader && Header);
249 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
262 if (SE && SimplifyIVs) {
268 while (!DeadInsts.
empty())
270 dyn_cast_or_null<Instruction>(&*DeadInsts.
pop_back_val()))
286 BB->getInstList().erase(Inst);
336 Loop *L,
unsigned Count,
unsigned TripCount,
bool Force,
bool AllowRuntime,
337 bool AllowExpensiveTripCount,
bool PreserveCondBr,
bool PreserveOnlyFirst,
338 unsigned TripMultiple,
unsigned PeelCount,
bool UnrollRemainder,
344 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop preheader-insertion failed.\n");
350 LLVM_DEBUG(
dbgs() <<
" Can't unroll; loop exit-block-insertion failed.\n");
356 LLVM_DEBUG(
dbgs() <<
" Can't unroll; Loop body cannot be cloned.\n");
371 <<
" Can't unroll; loop not terminated by a conditional branch.\n");
375 auto CheckSuccessors = [&](
unsigned S1,
unsigned S2) {
379 if (!CheckSuccessors(0, 1) && !CheckSuccessors(1, 0)) {
380 LLVM_DEBUG(
dbgs() <<
"Can't unroll; only loops with one conditional latch" 381 " exiting the loop can be unrolled\n");
388 dbgs() <<
" Won't unroll loop: address of header block is taken.\n");
394 if (TripMultiple != 1)
395 LLVM_DEBUG(
dbgs() <<
" Trip Multiple = " << TripMultiple <<
"\n");
399 if (TripCount != 0 && Count > TripCount)
403 if (TripCount == 0 && Count < 2 && PeelCount == 0) {
410 assert(TripCount == 0 || TripCount % TripMultiple == 0);
413 bool CompletelyUnroll = Count == TripCount;
416 std::vector<BasicBlock*> OriginalLoopBlocks = L->
getBlocks();
424 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
426 return isa<PHINode>(BB->
begin());
432 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
434 assert((!RuntimeTripCount || !PeelCount) &&
435 "Did not expect runtime trip-count unrolling " 436 "and peeling for the same loop");
440 Peeled =
peelLoop(L, PeelCount, LI, SE, DT, AC, PreserveLCSSA);
446 assert(ExitingBlock &&
"Loop without exiting block?");
457 bool HasConvergent =
false;
458 for (
auto &BB : L->
blocks())
461 HasConvergent |= CS.isConvergent();
462 assert((!HasConvergent || TripMultiple % Count == 0) &&
463 "Unroll count must divide trip multiple if loop contains a " 464 "convergent operation.");
467 bool EpilogProfitability =
471 if (RuntimeTripCount && TripMultiple % Count != 0 &&
473 EpilogProfitability, UnrollRemainder, LI, SE,
474 DT, AC, PreserveLCSSA, RemainderLoop)) {
476 RuntimeTripCount =
false;
479 "generated when assuming runtime trip count\n");
485 unsigned BreakoutTrip = 0;
486 if (TripCount != 0) {
487 BreakoutTrip = TripCount % Count;
491 BreakoutTrip = TripMultiple =
497 if (CompletelyUnroll) {
499 <<
" with trip count " << TripCount <<
"!\n");
504 <<
"completely unrolled loop with " 505 <<
NV(
"UnrollCount", TripCount) <<
" iterations";
507 }
else if (PeelCount) {
509 <<
" with iteration count " << PeelCount <<
"!\n");
514 <<
" peeled loop by " <<
NV(
"PeelCount", PeelCount)
518 auto DiagBuilder = [&]() {
521 return Diag <<
"unrolled loop by a factor of " 522 <<
NV(
"UnrollCount", Count);
527 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
528 LLVM_DEBUG(
dbgs() <<
" with a breakout at trip " << BreakoutTrip);
531 return DiagBuilder() <<
" with a breakout at trip " 532 <<
NV(
"BreakoutTrip", BreakoutTrip);
534 }
else if (TripMultiple != 1) {
535 LLVM_DEBUG(
dbgs() <<
" with " << TripMultiple <<
" trips per branch");
538 return DiagBuilder() <<
" with " <<
NV(
"TripMultiple", TripMultiple)
539 <<
" trips per branch";
541 }
else if (RuntimeTripCount) {
545 [&]() {
return DiagBuilder() <<
" with run-time trip count"; });
567 std::vector<PHINode*> OrigPHINode;
569 OrigPHINode.push_back(cast<PHINode>(
I));
572 std::vector<BasicBlock*> Headers;
573 std::vector<BasicBlock*> Latches;
574 Headers.push_back(Header);
575 Latches.push_back(LatchBlock);
587 std::vector<BasicBlock*> UnrolledLoopBlocks = L->
getBlocks();
594 for (
Loop *SubLoop : *L)
595 LoopsToSimplify.
insert(SubLoop);
600 if (!isa<DbgInfoIntrinsic>(&
I))
602 auto NewDIL = DIL->cloneWithDuplicationFactor(Count);
604 I.setDebugLoc(NewDIL.getValue());
607 <<
"Failed to create new discriminator: " 608 << DIL->getFilename() <<
" Line: " << DIL->getLine());
611 for (
unsigned It = 1; It != Count; ++It) {
612 std::vector<BasicBlock*> NewBlocks;
622 "Header should not be in a sub-loop");
626 LoopsToSimplify.
insert(NewLoops[OldLoop]);
631 for (
PHINode *OrigPHI : OrigPHINode) {
632 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
634 if (
Instruction *InValI = dyn_cast<Instruction>(InVal))
635 if (It > 1 && L->contains(InValI))
636 InVal = LastValueMap[InValI];
637 VMap[OrigPHI] = InVal;
642 LastValueMap[*BB] = New;
645 LastValueMap[
VI->first] =
VI->second;
649 if (L->contains(Succ))
651 for (
PHINode &PHI : Succ->phis()) {
652 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
654 if (It != LastValueMap.
end())
656 PHI.addIncoming(Incoming, New);
662 Headers.push_back(New);
663 if (*BB == LatchBlock)
664 Latches.push_back(New);
666 NewBlocks.push_back(New);
667 UnrolledLoopBlocks.push_back(New);
677 auto BBDomNode = DT->
getNode(*BB);
678 auto BBIDom = BBDomNode->
getIDom();
679 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
681 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
690 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
698 for (
PHINode *PN : OrigPHINode) {
699 if (CompletelyUnroll) {
700 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
703 else if (Count > 1) {
704 Value *InVal = PN->removeIncomingValue(LatchBlock,
false);
707 if (
Instruction *InValI = dyn_cast<Instruction>(InVal)) {
708 if (L->contains(InValI))
709 InVal = LastValueMap[InVal];
711 assert(Latches.back() == LastValueMap[LatchBlock] &&
"bad last latch");
712 PN->addIncoming(InVal, Latches.back());
718 for (
unsigned i = 0, e = Latches.size(); i != e; ++i) {
720 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
723 unsigned j = (i + 1) % e;
725 bool NeedConditional =
true;
727 if (RuntimeTripCount && j != 0) {
728 NeedConditional =
false;
733 if (CompletelyUnroll) {
740 "NeedCondition cannot be modified by both complete " 741 "unrolling and runtime unrolling");
742 NeedConditional = (PreserveCondBr && j && !(PreserveOnlyFirst && i != 0));
743 }
else if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
746 NeedConditional =
false;
749 if (NeedConditional) {
755 if (Dest != LoopExit) {
758 if (Succ == Headers[i])
760 for (
PHINode &Phi : Succ->phis())
761 Phi.removeIncomingValue(BB,
false);
774 if (DT && Count > 1) {
775 for (
auto *BB : OriginalLoopBlocks) {
776 auto *BBDomNode = DT->
getNode(BB);
778 for (
auto *ChildDomNode : BBDomNode->getChildren()) {
779 auto *ChildBB = ChildDomNode->getBlock();
780 if (!L->contains(ChildBB))
784 if (BB == LatchBlock) {
792 NewIDom = Latches.
back();
795 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
807 for (
auto *ChildBB : ChildrenToUpdate)
817 BranchInst *Term = cast<BranchInst>(Latch->getTerminator());
822 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
823 UnrolledLoopBlocks.erase(
std::remove(UnrolledLoopBlocks.begin(),
824 UnrolledLoopBlocks.end(), Dest),
825 UnrolledLoopBlocks.end());
835 NumCompletelyUnrolled += CompletelyUnroll;
840 if (CompletelyUnroll)
851 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
863 if (NeedToFixLCSSA) {
868 Loop *FixLCSSALoop = OuterL;
869 if (!FixLCSSALoop->
contains(LatchLoop))
874 }
else if (PreserveLCSSA) {
876 "Loops should be in LCSSA form after loop-unroll.");
884 for (
Loop *SubLoop : LoopsToSimplify)
unsigned getSmallConstantTripCount(const Loop *L)
Returns the maximum trip count of the loop if it is a single-exit loop and we can compute a small max...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, bool PreserveLCSSA, Loop **ResultLoop=nullptr)
Insert code in the prolog/epilog code when unrolling a loop with a run-time trip-count.
unsigned getSmallConstantTripMultiple(const Loop *L)
Returns the largest constant divisor of the trip count of the loop if it is a single-exit loop and we...
DiagnosticInfoOptimizationBase::Argument NV
uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B)
Return the greatest common divisor of the values using Euclid's algorithm.
iterator erase(iterator where)
static bool needToInsertPhisForLCSSA(Loop *L, std::vector< BasicBlock *> Blocks, LoopInfo *LI)
Check if unrolling created a situation where we need to insert phi nodes to preserve LCSSA form...
This class represents lattice values for constants.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
void push_back(const T &Elt)
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
A cache of @llvm.assume calls within a function.
BasicBlock * foldBlockIntoPredecessor(BasicBlock *BB, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT)
Folds a basic block into its predecessor if it only has one predecessor, and that predecessor only ha...
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...
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
const MDOperand & getOperand(unsigned I) const
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...
LoopUnrollResult UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, bool Force, bool AllowRuntime, bool AllowExpensiveTripCount, bool PreserveCondBr, bool PreserveOnlyFirst, unsigned TripMultiple, unsigned PeelCount, bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, bool PreserveLCSSA, Loop **RemainderLoop=nullptr)
Unroll the given loop by Count.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
iterator begin()
Instruction iterator methods.
static cl::opt< bool > UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden, cl::desc("Allow runtime unrolled loops to be unrolled " "with epilog instead of prolog."))
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
static cl::opt< bool > UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden, cl::desc("Verify domtree after unrolling"), cl::init(false))
amdgpu Simplify well known AMD library false Value Value const Twine & Name
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
A Use represents the edge between a Value definition and its users.
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
void setName(const Twine &Name)
Change the name of the value.
RPOIterator endRPO() const
BlockT * getHeader() const
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
iterator find(const KeyT &Val)
static bool isEpilogProfitable(Loop *L)
The function chooses which type of unroll (epilog or prolog) is more profitabale. ...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
void remapInstruction(Instruction *I, ValueToValueMapTy &VMap)
Convert the instruction operands from referencing the current values into those specified by VMap...
StringRef getString() const
The loop was fully unrolled into straight-line code.
bool isDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
initializer< Ty > init(const Ty &Val)
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
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...
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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.
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
const Instruction & back() const
static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New)
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
The loop was partially unrolled – we still have a loop, but with a smaller trip count.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LoopT * AllocateLoop(ArgsTy &&... Args)
LLVM_NODISCARD T pop_back_val()
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const Loop * addClonedBlockToLoopInfo(BasicBlock *OriginalBB, BasicBlock *ClonedBB, LoopInfo *LI, NewLoopsMap &NewLoops)
Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary and adds a mapping from the o...
Store the result of a depth first search within basic blocks contained by a single loop...
void push_back(pointer val)
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...
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
LoopT * getParentLoop() const
LLVMAttributeRef wrap(Attribute Attr)
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
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...
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
bool isUnconditional() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
succ_range successors(Instruction *I)
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
The loop was not modified.
StringRef - Represent a constant reference to a string, i.e.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
unsigned getNumOperands() const
Return number of MDNode operands.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
iterator_range< block_iterator > blocks() const
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
void forgetTopmostLoop(const Loop *L)
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC)
Perform some cleanup and simplifications on loops after unrolling.