43 #define DEBUG_TYPE "loop-unroll-and-jam" 45 STATISTIC(NumUnrolledAndJammed,
"Number of loops unroll and jammed");
46 STATISTIC(NumCompletelyUnrolledAndJammed,
"Number of loops unroll and jammed");
73 if (BB == SubLoopPreHeader)
96 for (
auto &Phi : Header->
phis()) {
97 Value *V = Phi.getIncomingValueForBlock(Latch);
102 while (!Worklist.
empty()) {
124 std::vector<Instruction *> Visited;
128 Visited.push_back(I);
173 unsigned TripMultiple,
bool UnrollRemainder,
183 if (TripCount == 0 && Count < 2) {
190 assert(TripCount == 0 || TripCount % TripMultiple == 0);
193 bool CompletelyUnroll = (Count == TripCount);
196 if (TripMultiple == 1 || TripMultiple % Count != 0) {
199 UnrollRemainder, LI, SE, DT, AC,
true)) {
200 LLVM_DEBUG(
dbgs() <<
"Won't unroll-and-jam; remainder loop could not be " 201 "generated when assuming runtime trip count\n");
215 if (CompletelyUnroll) {
217 << Header->
getName() <<
" with trip count " << TripCount
221 <<
"completely unroll and jammed loop with " 222 <<
NV(
"UnrollCount", TripCount) <<
" iterations");
224 auto DiagBuilder = [&]() {
227 return Diag <<
"unroll and jammed loop by a factor of " 228 <<
NV(
"UnrollCount", Count);
233 if (TripMultiple != 1) {
234 LLVM_DEBUG(
dbgs() <<
" with " << TripMultiple <<
" trips per branch");
236 return DiagBuilder() <<
" with " <<
NV(
"TripMultiple", TripMultiple)
237 <<
" trips per branch";
241 ORE->
emit([&]() {
return DiagBuilder() <<
" with run-time trip count"; });
249 assert(Preheader && LatchBlock && Header);
253 bool SubLoopContinueOnTrue = SubLoop->contains(
254 SubLoop->getLoopLatch()->getTerminator()->getSuccessor(0));
267 std::vector<BasicBlock *> ForeBlocksFirst;
268 std::vector<BasicBlock *> ForeBlocksLast;
269 std::vector<BasicBlock *> SubLoopBlocksFirst;
270 std::vector<BasicBlock *> SubLoopBlocksLast;
271 std::vector<BasicBlock *> AftBlocksFirst;
272 std::vector<BasicBlock *> AftBlocksLast;
273 ForeBlocksFirst.push_back(Header);
274 ForeBlocksLast.push_back(SubLoop->getLoopPreheader());
275 SubLoopBlocksFirst.push_back(SubLoop->getHeader());
276 SubLoopBlocksLast.push_back(SubLoop->getExitingBlock());
277 AftBlocksFirst.push_back(SubLoop->getExitBlock());
284 Header, LatchBlock, SubLoop->getLoopPreheader()->
getTerminator(),
299 if (!isa<DbgInfoIntrinsic>(&
I))
301 I.setDebugLoc(DIL->cloneWithDuplicationFactor(Count));
304 for (
unsigned It = 1; It != Count; ++It) {
305 std::vector<BasicBlock *> NewBlocks;
314 if (ForeBlocks.
count(*BB)) {
317 if (*BB == ForeBlocksFirst[0])
318 ForeBlocksFirst.push_back(New);
319 if (*BB == ForeBlocksLast[0])
320 ForeBlocksLast.push_back(New);
321 }
else if (SubLoopBlocks.
count(*BB)) {
322 SubLoop->addBasicBlockToLoop(New, *LI);
324 if (*BB == SubLoopBlocksFirst[0])
325 SubLoopBlocksFirst.push_back(New);
326 if (*BB == SubLoopBlocksLast[0])
327 SubLoopBlocksLast.push_back(New);
328 }
else if (AftBlocks.
count(*BB)) {
331 if (*BB == AftBlocksFirst[0])
332 AftBlocksFirst.push_back(New);
333 if (*BB == AftBlocksLast[0])
334 AftBlocksLast.push_back(New);
340 PrevItValueMap[New] = (It == 1 ? *BB : LastValueMap[*BB]);
341 LastValueMap[*BB] = New;
344 PrevItValueMap[
VI->second] =
345 const_cast<Value *
>(It == 1 ?
VI->first : LastValueMap[
VI->first]);
346 LastValueMap[
VI->first] =
VI->second;
349 NewBlocks.push_back(New);
352 if (*BB == ForeBlocksFirst[0])
354 else if (*BB == SubLoopBlocksFirst[0])
356 else if (*BB == AftBlocksFirst[0])
361 auto BBDomNode = DT->
getNode(*BB);
362 auto BBIDom = BBDomNode->
getIDom();
363 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
365 assert(LastValueMap[cast<Value>(OriginalBBIDom)]);
367 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
375 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
376 if (II->getIntrinsicID() == Intrinsic::assume)
383 for (
PHINode &Phi : ForeBlocksFirst[It]->phis()) {
384 Value *OldValue = Phi.getIncomingValueForBlock(AftBlocksLast[It]);
385 assert(OldValue &&
"should have incoming edge from Aft[It]");
386 Value *NewValue = OldValue;
387 if (
Value *PrevValue = PrevItValueMap[OldValue])
388 NewValue = PrevValue;
390 assert(Phi.getNumOperands() == 2);
391 Phi.setIncomingBlock(0, ForeBlocksLast[It - 1]);
392 Phi.setIncomingValue(0, NewValue);
393 Phi.removeIncomingValue(1);
405 int I = Phi.getBasicBlockIndex(OldBB);
406 Phi.setIncomingBlock(I, NewBB);
415 for (
unsigned b = 0; b < Phi.getNumIncomingValues(); ++b) {
416 if (Phi.getIncomingBlock(b) == OldBB) {
417 Value *OldValue = Phi.getIncomingValue(b);
418 if (
Value *LastValue = LastValueMap[OldValue])
419 Phi.setIncomingValue(b, LastValue);
420 Phi.setIncomingBlock(b, NewBB);
434 updatePHIBlocksAndValues(LoopExit, AftBlocksLast[0], AftBlocksLast.
back(),
439 cast<BranchInst>(ForeBlocksLast.back()->getTerminator());
441 ForeTerm->setSuccessor(0, Dest);
443 if (CompletelyUnroll) {
444 while (
PHINode *Phi = dyn_cast<PHINode>(ForeBlocksFirst[0]->
begin())) {
446 Phi->getParent()->getInstList().erase(Phi);
450 updatePHIBlocksAndValues(ForeBlocksFirst[0], AftBlocksLast[0],
451 AftBlocksLast.back(), LastValueMap);
454 for (
unsigned It = 1; It != Count; It++) {
457 cast<BranchInst>(ForeBlocksLast[It - 1]->getTerminator());
464 cast<BranchInst>(SubLoopBlocksLast.back()->getTerminator());
465 SubTerm->
setSuccessor(!SubLoopContinueOnTrue, SubLoopBlocksFirst[0]);
466 SubTerm->
setSuccessor(SubLoopContinueOnTrue, AftBlocksFirst[0]);
467 updatePHIBlocks(SubLoopBlocksFirst[0], ForeBlocksLast[0],
468 ForeBlocksLast.back());
469 updatePHIBlocks(SubLoopBlocksFirst[0], SubLoopBlocksLast[0],
470 SubLoopBlocksLast.back());
472 for (
unsigned It = 1; It != Count; It++) {
476 cast<BranchInst>(SubLoopBlocksLast[It - 1]->getTerminator());
480 updatePHIBlocks(SubLoopBlocksFirst[It], ForeBlocksLast[It],
481 ForeBlocksLast.back());
482 updatePHIBlocks(SubLoopBlocksFirst[It], SubLoopBlocksLast[It],
483 SubLoopBlocksLast.back());
484 movePHIs(SubLoopBlocksFirst[It], SubLoopBlocksFirst[0]);
488 BranchInst *Term = cast<BranchInst>(AftBlocksLast.back()->getTerminator());
489 if (CompletelyUnroll) {
493 Term->
setSuccessor(!ContinueOnTrue, ForeBlocksFirst[0]);
495 updatePHIBlocks(AftBlocksFirst[0], SubLoopBlocksLast[0],
496 SubLoopBlocksLast.back());
498 for (
unsigned It = 1; It != Count; It++) {
502 cast<BranchInst>(AftBlocksLast[It - 1]->getTerminator());
506 updatePHIBlocks(AftBlocksFirst[It], SubLoopBlocksLast[It],
507 SubLoopBlocksLast.back());
508 movePHIs(AftBlocksFirst[It], AftBlocksFirst[0]);
516 SubLoopBlocksFirst[0]);
518 SubLoopBlocksLast[0], AftBlocksFirst[0]);
521 ForeBlocksLast.back(), SubLoopBlocksFirst[0]);
523 SubLoopBlocksLast.back(), AftBlocksFirst[0]);
529 MergeBlocks.
insert(ForeBlocksLast.begin(), ForeBlocksLast.end());
530 MergeBlocks.
insert(SubLoopBlocksLast.begin(), SubLoopBlocksLast.end());
531 MergeBlocks.
insert(AftBlocksLast.begin(), AftBlocksLast.end());
532 while (!MergeBlocks.
empty()) {
541 MergeBlocks.
erase(Dest);
543 MergeBlocks.
erase(BB);
545 MergeBlocks.
erase(BB);
554 NumCompletelyUnrolledAndJammed += CompletelyUnroll;
555 ++NumUnrolledAndJammed;
560 Loop *OutestLoop = OuterL ? OuterL : (!CompletelyUnroll ? L : SubLoop);
562 if (!CompletelyUnroll)
564 assert(SubLoop->isLoopSimplifyForm());
569 if (CompletelyUnroll)
582 if (
auto *Ld = dyn_cast<LoadInst>(&
I)) {
586 }
else if (
auto *St = dyn_cast<StoreInst>(&
I)) {
590 }
else if (
I.mayReadOrWriteMemory()) {
600 unsigned LoopDepth,
bool InnerLoop,
604 for (
Value *
I : Earlier) {
605 for (
Value *J : Later) {
611 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
619 if (
auto D = DI.
depends(Src, Dst,
true)) {
620 assert(
D->isOrdered() &&
"Expected an output, flow or anti dep.");
628 assert(LoopDepth + 1 <=
D->getLevels());
716 if (SubLoopLatch != SubLoopExit)
733 if (AftBlocks.
size() != 1)
738 if (isa<SCEVCouldNotCompute>(SubLoopBECountSC) ||
760 Header, Latch, AftBlocks, [&AftBlocks, &SubLoop](
Instruction *
I) {
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
DiagnosticInfoOptimizationBase::Argument NV
Compute iterated dominance frontiers using a linear time algorithm.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
static bool getLoadsAndStores(BasicBlockSet &Blocks, SmallVector< Value *, 4 > &MemInstr)
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
unsigned getLoopDepth() const
Return the nesting level of this loop.
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...
static bool processHeaderPhiOperands(BasicBlock *Header, BasicBlock *Latch, BasicBlockSet &AftBlocks, T Visit)
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
DependenceInfo - This class is the main dependence-analysis driver.
static void moveHeaderPhiOperandsToForeBlocks(BasicBlock *Header, BasicBlock *Latch, Instruction *InsertLoc, BasicBlockSet &AftBlocks)
static bool checkDependencies(SmallVector< Value *, 4 > &Earlier, SmallVector< Value *, 4 > &Later, unsigned LoopDepth, bool InnerLoop, DependenceInfo &DI)
iterator begin()
Instruction iterator methods.
The SCEV is loop-invariant.
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...
bool isIntegerTy() const
True if this is an instance of IntegerType.
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
BlockT * getHeader() const
void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
LoopUnrollResult UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount, unsigned TripMultiple, bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, OptimizationRemarkEmitter *ORE)
bool isSafeToUnrollAndJam(Loop *L, ScalarEvolution &SE, DominatorTree &DT, DependenceInfo &DI)
This header provides classes for managing per-loop analyses.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void remapInstruction(Instruction *I, ValueToValueMapTy &VMap)
Convert the instruction operands from referencing the current values into those specified by VMap...
The loop was fully unrolled into straight-line code.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
SmallPtrSet< BasicBlock *, 4 > BasicBlockSet
bool isDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool PossiblyLoopIndependent)
depends - Tests for a dependence between the Src and Dst instructions.
Subclasses of this class are all able to terminate a basic block.
LLVM Basic Block Representation.
LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
Conditional or Unconditional Branch instruction.
DomTreeNodeBase * getIDom() const
LLVM_NODISCARD bool empty() const
static bool partitionOuterLoopBlocks(Loop *L, Loop *SubLoop, BasicBlockSet &ForeBlocks, BasicBlockSet &SubLoopBlocks, BasicBlockSet &AftBlocks, DominatorTree *DT)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
const Instruction & back() const
std::vector< BasicBlock * >::const_reverse_iterator RPOIterator
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
The loop was partially unrolled – we still have a loop, but with a smaller trip count.
bool UnrollRuntimeLoopRemainder(Loop *L, unsigned Count, bool AllowExpensiveTripCount, bool UseEpilogRemainder, bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, bool PreserveLCSSA)
Insert code in the prolog/epilog code when unrolling a loop with a run-time 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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Type * getType() const
Return the LLVM type of this SCEV expression.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Store the result of a depth first search within basic blocks contained by a single loop...
LoopDisposition
An enum describing the relationship between a SCEV and a 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)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
LoopT * getParentLoop() const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
Captures loop safety information.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
void emplace_back(ArgTypes &&... Args)
This class represents an analyzed expression in the program.
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.
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...
block_iterator block_end() const
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool isUnconditional() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
LLVM Value Representation.
The loop was not modified.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
const SCEV * getExitCount(const Loop *L, BasicBlock *ExitingBlock)
Get the expression for the number of loop iterations for which this loop is guaranteed not to exit vi...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
iterator_range< block_iterator > blocks() const
block_iterator block_begin() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
const BasicBlock * getParent() const
LoopUnrollResult
Represents the result of a UnrollLoop invocation.
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
void simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC)
Perform some cleanup and simplifications on loops after unrolling.