1 //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements a simple loop reroller.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AliasSetTracker.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/ScalarEvolution.h"
22 #include "llvm/Analysis/ScalarEvolutionExpander.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetLibraryInfo.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/LoopUtils.h"
38 #define DEBUG_TYPE "loop-reroll"
40 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
42 static cl::opt<unsigned>
43 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
44 cl::desc("The maximum increment for loop rerolling"));
46 // This loop re-rolling transformation aims to transform loops like this:
50 // for (int i = 0; i < 500; i += 3) {
57 // into a loop like this:
60 // for (int i = 0; i < 500; ++i)
64 // It does this by looking for loops that, besides the latch code, are composed
65 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
66 // to the induction variable, and where each DAG is isomorphic to the DAG
67 // rooted at the induction variable (excepting the sub-DAGs which root the
68 // other induction-variable increments). In other words, we're looking for loop
69 // bodies of the form:
71 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
73 // %iv.1 = add %iv, 1 <-- a root increment
75 // %iv.2 = add %iv, 2 <-- a root increment
77 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
80 // %iv.next = add %iv, scale
81 // %cmp = icmp(%iv, ...)
82 // br %cmp, header, exit
84 // where each f(i) is a set of instructions that, collectively, are a function
85 // only of i (and other loop-invariant values).
87 // As a special case, we can also reroll loops like this:
91 // for (int i = 0; i < 500; ++i) {
100 // void bar(int *x) {
101 // for (int i = 0; i < 1500; ++i)
105 // in which case, we're looking for inputs like this:
107 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
108 // %scaled.iv = mul %iv, scale
110 // %scaled.iv.1 = add %scaled.iv, 1
112 // %scaled.iv.2 = add %scaled.iv, 2
114 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
115 // f(%scaled.iv.scale_m_1)
117 // %iv.next = add %iv, 1
118 // %cmp = icmp(%iv, ...)
119 // br %cmp, header, exit
122 class LoopReroll : public LoopPass {
124 static char ID; // Pass ID, replacement for typeid
125 LoopReroll() : LoopPass(ID) {
126 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
129 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 AU.addRequired<AliasAnalysis>();
133 AU.addRequired<LoopInfo>();
134 AU.addPreserved<LoopInfo>();
135 AU.addRequired<DominatorTreeWrapperPass>();
136 AU.addPreserved<DominatorTreeWrapperPass>();
137 AU.addRequired<ScalarEvolution>();
138 AU.addRequired<TargetLibraryInfo>();
145 const DataLayout *DL;
146 TargetLibraryInfo *TLI;
149 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
150 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
152 // A chain of isomorphic instructions, indentified by a single-use PHI,
153 // representing a reduction. Only the last value may be used outside the
155 struct SimpleLoopReduction {
156 SimpleLoopReduction(Instruction *P, Loop *L)
157 : Valid(false), Instructions(1, P) {
158 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
166 Instruction *getPHI() const {
167 assert(Valid && "Using invalid reduction");
168 return Instructions.front();
171 Instruction *getReducedValue() const {
172 assert(Valid && "Using invalid reduction");
173 return Instructions.back();
176 Instruction *get(size_t i) const {
177 assert(Valid && "Using invalid reduction");
178 return Instructions[i+1];
181 Instruction *operator [] (size_t i) const { return get(i); }
183 // The size, ignoring the initial PHI.
184 size_t size() const {
185 assert(Valid && "Using invalid reduction");
186 return Instructions.size()-1;
189 typedef SmallInstructionVector::iterator iterator;
190 typedef SmallInstructionVector::const_iterator const_iterator;
193 assert(Valid && "Using invalid reduction");
194 return std::next(Instructions.begin());
197 const_iterator begin() const {
198 assert(Valid && "Using invalid reduction");
199 return std::next(Instructions.begin());
202 iterator end() { return Instructions.end(); }
203 const_iterator end() const { return Instructions.end(); }
207 SmallInstructionVector Instructions;
212 // The set of all reductions, and state tracking of possible reductions
213 // during loop instruction processing.
214 struct ReductionTracker {
215 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
217 // Add a new possible reduction.
218 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
220 // Setup to track possible reductions corresponding to the provided
221 // rerolling scale. Only reductions with a number of non-PHI instructions
222 // that is divisible by the scale are considered. Three instructions sets
224 // - A set of all possible instructions in eligible reductions.
225 // - A set of all PHIs in eligible reductions
226 // - A set of all reduced values (last instructions) in eligible
228 void restrictToScale(uint64_t Scale,
229 SmallInstructionSet &PossibleRedSet,
230 SmallInstructionSet &PossibleRedPHISet,
231 SmallInstructionSet &PossibleRedLastSet) {
232 PossibleRedIdx.clear();
233 PossibleRedIter.clear();
236 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
237 if (PossibleReds[i].size() % Scale == 0) {
238 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
239 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
241 PossibleRedSet.insert(PossibleReds[i].getPHI());
242 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
243 for (Instruction *J : PossibleReds[i]) {
244 PossibleRedSet.insert(J);
245 PossibleRedIdx[J] = i;
250 // The functions below are used while processing the loop instructions.
252 // Are the two instructions both from reductions, and furthermore, from
253 // the same reduction?
254 bool isPairInSame(Instruction *J1, Instruction *J2) {
255 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
256 if (J1I != PossibleRedIdx.end()) {
257 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
258 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
265 // The two provided instructions, the first from the base iteration, and
266 // the second from iteration i, form a matched pair. If these are part of
267 // a reduction, record that fact.
268 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
269 if (PossibleRedIdx.count(J1)) {
270 assert(PossibleRedIdx.count(J2) &&
271 "Recording reduction vs. non-reduction instruction?");
273 PossibleRedIter[J1] = 0;
274 PossibleRedIter[J2] = i;
276 int Idx = PossibleRedIdx[J1];
277 assert(Idx == PossibleRedIdx[J2] &&
278 "Recording pair from different reductions?");
283 // The functions below can be called after we've finished processing all
284 // instructions in the loop, and we know which reductions were selected.
286 // Is the provided instruction the PHI of a reduction selected for
288 bool isSelectedPHI(Instruction *J) {
289 if (!isa<PHINode>(J))
292 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
295 if (cast<Instruction>(J) == PossibleReds[i].getPHI())
302 bool validateSelected();
303 void replaceSelected();
306 // The vector of all possible reductions (for any scale).
307 SmallReductionVector PossibleReds;
309 DenseMap<Instruction *, int> PossibleRedIdx;
310 DenseMap<Instruction *, int> PossibleRedIter;
314 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
315 void collectPossibleReductions(Loop *L,
316 ReductionTracker &Reductions);
317 void collectInLoopUserSet(Loop *L,
318 const SmallInstructionVector &Roots,
319 const SmallInstructionSet &Exclude,
320 const SmallInstructionSet &Final,
321 DenseSet<Instruction *> &Users);
322 void collectInLoopUserSet(Loop *L,
324 const SmallInstructionSet &Exclude,
325 const SmallInstructionSet &Final,
326 DenseSet<Instruction *> &Users);
327 bool findScaleFromMul(Instruction *RealIV, uint64_t &Scale,
329 SmallInstructionVector &LoopIncs);
330 bool collectAllRoots(Loop *L, uint64_t Inc, uint64_t Scale, Instruction *IV,
331 SmallVector<SmallInstructionVector, 32> &Roots,
332 SmallInstructionSet &AllRoots,
333 SmallInstructionVector &LoopIncs);
334 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
335 ReductionTracker &Reductions);
339 char LoopReroll::ID = 0;
340 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
341 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
342 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
343 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
344 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
345 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
346 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
348 Pass *llvm::createLoopRerollPass() {
349 return new LoopReroll;
352 // Returns true if the provided instruction is used outside the given loop.
353 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
354 // non-loop blocks to be outside the loop.
355 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
356 for (User *U : I->users())
357 if (!L->contains(cast<Instruction>(U)))
363 // Collect the list of loop induction variables with respect to which it might
364 // be possible to reroll the loop.
365 void LoopReroll::collectPossibleIVs(Loop *L,
366 SmallInstructionVector &PossibleIVs) {
367 BasicBlock *Header = L->getHeader();
368 for (BasicBlock::iterator I = Header->begin(),
369 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
370 if (!isa<PHINode>(I))
372 if (!I->getType()->isIntegerTy())
375 if (const SCEVAddRecExpr *PHISCEV =
376 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
377 if (PHISCEV->getLoop() != L)
379 if (!PHISCEV->isAffine())
381 if (const SCEVConstant *IncSCEV =
382 dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
383 if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
385 if (IncSCEV->getValue()->uge(MaxInc))
388 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
390 PossibleIVs.push_back(I);
396 // Add the remainder of the reduction-variable chain to the instruction vector
397 // (the initial PHINode has already been added). If successful, the object is
399 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
400 assert(!Valid && "Cannot add to an already-valid chain");
402 // The reduction variable must be a chain of single-use instructions
403 // (including the PHI), except for the last value (which is used by the PHI
404 // and also outside the loop).
405 Instruction *C = Instructions.front();
408 C = cast<Instruction>(*C->user_begin());
409 if (C->hasOneUse()) {
410 if (!C->isBinaryOp())
413 if (!(isa<PHINode>(Instructions.back()) ||
414 C->isSameOperationAs(Instructions.back())))
417 Instructions.push_back(C);
419 } while (C->hasOneUse());
421 if (Instructions.size() < 2 ||
422 !C->isSameOperationAs(Instructions.back()) ||
426 // C is now the (potential) last instruction in the reduction chain.
427 for (User *U : C->users())
428 // The only in-loop user can be the initial PHI.
429 if (L->contains(cast<Instruction>(U)))
430 if (cast<Instruction>(U) != Instructions.front())
433 Instructions.push_back(C);
437 // Collect the vector of possible reduction variables.
438 void LoopReroll::collectPossibleReductions(Loop *L,
439 ReductionTracker &Reductions) {
440 BasicBlock *Header = L->getHeader();
441 for (BasicBlock::iterator I = Header->begin(),
442 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
443 if (!isa<PHINode>(I))
445 if (!I->getType()->isSingleValueType())
448 SimpleLoopReduction SLR(I, L);
452 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
453 SLR.size() << " chained instructions)\n");
454 Reductions.addSLR(SLR);
458 // Collect the set of all users of the provided root instruction. This set of
459 // users contains not only the direct users of the root instruction, but also
460 // all users of those users, and so on. There are two exceptions:
462 // 1. Instructions in the set of excluded instructions are never added to the
463 // use set (even if they are users). This is used, for example, to exclude
464 // including root increments in the use set of the primary IV.
466 // 2. Instructions in the set of final instructions are added to the use set
467 // if they are users, but their users are not added. This is used, for
468 // example, to prevent a reduction update from forcing all later reduction
469 // updates into the use set.
470 void LoopReroll::collectInLoopUserSet(Loop *L,
471 Instruction *Root, const SmallInstructionSet &Exclude,
472 const SmallInstructionSet &Final,
473 DenseSet<Instruction *> &Users) {
474 SmallInstructionVector Queue(1, Root);
475 while (!Queue.empty()) {
476 Instruction *I = Queue.pop_back_val();
477 if (!Users.insert(I).second)
481 for (Use &U : I->uses()) {
482 Instruction *User = cast<Instruction>(U.getUser());
483 if (PHINode *PN = dyn_cast<PHINode>(User)) {
484 // Ignore "wrap-around" uses to PHIs of this loop's header.
485 if (PN->getIncomingBlock(U) == L->getHeader())
489 if (L->contains(User) && !Exclude.count(User)) {
490 Queue.push_back(User);
494 // We also want to collect single-user "feeder" values.
495 for (User::op_iterator OI = I->op_begin(),
496 OIE = I->op_end(); OI != OIE; ++OI) {
497 if (Instruction *Op = dyn_cast<Instruction>(*OI))
498 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
505 // Collect all of the users of all of the provided root instructions (combined
506 // into a single set).
507 void LoopReroll::collectInLoopUserSet(Loop *L,
508 const SmallInstructionVector &Roots,
509 const SmallInstructionSet &Exclude,
510 const SmallInstructionSet &Final,
511 DenseSet<Instruction *> &Users) {
512 for (SmallInstructionVector::const_iterator I = Roots.begin(),
513 IE = Roots.end(); I != IE; ++I)
514 collectInLoopUserSet(L, *I, Exclude, Final, Users);
517 static bool isSimpleLoadStore(Instruction *I) {
518 if (LoadInst *LI = dyn_cast<LoadInst>(I))
519 return LI->isSimple();
520 if (StoreInst *SI = dyn_cast<StoreInst>(I))
521 return SI->isSimple();
522 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
523 return !MI->isVolatile();
527 // Recognize loops that are setup like this:
529 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
530 // %scaled.iv = mul %iv, scale
532 // %scaled.iv.1 = add %scaled.iv, 1
534 // %scaled.iv.2 = add %scaled.iv, 2
536 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
537 // f(%scaled.iv.scale_m_1)
539 // %iv.next = add %iv, 1
540 // %cmp = icmp(%iv, ...)
541 // br %cmp, header, exit
543 // and, if found, set IV = %scaled.iv, and add %iv.next to LoopIncs.
544 bool LoopReroll::findScaleFromMul(Instruction *RealIV, uint64_t &Scale,
546 SmallInstructionVector &LoopIncs) {
547 // This is a special case: here we're looking for all uses (except for
548 // the increment) to be multiplied by a common factor. The increment must
549 // be by one. This is to capture loops like:
550 // for (int i = 0; i < 500; ++i) {
551 // foo(3*i); foo(3*i+1); foo(3*i+2);
553 if (RealIV->getNumUses() != 2)
555 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
556 Instruction *User1 = cast<Instruction>(*RealIV->user_begin()),
557 *User2 = cast<Instruction>(*std::next(RealIV->user_begin()));
558 if (!SE->isSCEVable(User1->getType()) || !SE->isSCEVable(User2->getType()))
560 const SCEVAddRecExpr *User1SCEV =
561 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User1)),
563 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User2));
564 if (!User1SCEV || !User1SCEV->isAffine() ||
565 !User2SCEV || !User2SCEV->isAffine())
568 // We assume below that User1 is the scale multiply and User2 is the
569 // increment. If this can't be true, then swap them.
570 if (User1SCEV == RealIVSCEV->getPostIncExpr(*SE)) {
571 std::swap(User1, User2);
572 std::swap(User1SCEV, User2SCEV);
575 if (User2SCEV != RealIVSCEV->getPostIncExpr(*SE))
577 assert(User2SCEV->getStepRecurrence(*SE)->isOne() &&
578 "Invalid non-unit step for multiplicative scaling");
579 LoopIncs.push_back(User2);
581 if (const SCEVConstant *MulScale =
582 dyn_cast<SCEVConstant>(User1SCEV->getStepRecurrence(*SE))) {
583 // Make sure that both the start and step have the same multiplier.
584 if (RealIVSCEV->getStart()->getType() != MulScale->getType())
586 if (SE->getMulExpr(RealIVSCEV->getStart(), MulScale) !=
587 User1SCEV->getStart())
590 ConstantInt *MulScaleCI = MulScale->getValue();
591 if (!MulScaleCI->uge(2) || MulScaleCI->uge(MaxInc))
593 Scale = MulScaleCI->getZExtValue();
598 DEBUG(dbgs() << "LRR: Found possible scaling " << *User1 << "\n");
602 // Collect all root increments with respect to the provided induction variable
603 // (normally the PHI, but sometimes a multiply). A root increment is an
604 // instruction, normally an add, with a positive constant less than Scale. In a
605 // rerollable loop, each of these increments is the root of an instruction
606 // graph isomorphic to the others. Also, we collect the final induction
607 // increment (the increment equal to the Scale), and its users in LoopIncs.
608 bool LoopReroll::collectAllRoots(Loop *L, uint64_t Inc, uint64_t Scale,
610 SmallVector<SmallInstructionVector, 32> &Roots,
611 SmallInstructionSet &AllRoots,
612 SmallInstructionVector &LoopIncs) {
613 for (User *U : IV->users()) {
614 Instruction *UI = cast<Instruction>(U);
615 if (!SE->isSCEVable(UI->getType()))
617 if (UI->getType() != IV->getType())
619 if (!L->contains(UI))
621 if (hasUsesOutsideLoop(UI, L))
624 if (const SCEVConstant *Diff = dyn_cast<SCEVConstant>(SE->getMinusSCEV(
625 SE->getSCEV(UI), SE->getSCEV(IV)))) {
626 uint64_t Idx = Diff->getValue()->getValue().getZExtValue();
627 if (Idx > 0 && Idx < Scale) {
628 Roots[Idx-1].push_back(UI);
630 } else if (Idx == Scale && Inc > 1) {
631 LoopIncs.push_back(UI);
636 if (Roots[0].empty())
639 for (unsigned i = 1; i < Scale-1; ++i)
640 if (Roots[i].size() != Roots[0].size()) {
651 // Validate the selected reductions. All iterations must have an isomorphic
652 // part of the reduction chain and, for non-associative reductions, the chain
653 // entries must appear in order.
654 bool LoopReroll::ReductionTracker::validateSelected() {
655 // For a non-associative reduction, the chain entries must appear in order.
656 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
659 int PrevIter = 0, BaseCount = 0, Count = 0;
660 for (Instruction *J : PossibleReds[i]) {
661 // Note that all instructions in the chain must have been found because
662 // all instructions in the function must have been assigned to some
664 int Iter = PossibleRedIter[J];
665 if (Iter != PrevIter && Iter != PrevIter + 1 &&
666 !PossibleReds[i].getReducedValue()->isAssociative()) {
667 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
672 if (Iter != PrevIter) {
673 if (Count != BaseCount) {
674 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
675 " reduction use count " << Count <<
676 " is not equal to the base use count " <<
695 // For all selected reductions, remove all parts except those in the first
696 // iteration (and the PHI). Replace outside uses of the reduced value with uses
697 // of the first-iteration reduced value (in other words, reroll the selected
699 void LoopReroll::ReductionTracker::replaceSelected() {
700 // Fixup reductions to refer to the last instruction associated with the
701 // first iteration (not the last).
702 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
706 for (int e = PossibleReds[i].size(); j != e; ++j)
707 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
712 // Replace users with the new end-of-chain value.
713 SmallInstructionVector Users;
714 for (User *U : PossibleReds[i].getReducedValue()->users())
715 Users.push_back(cast<Instruction>(U));
717 for (SmallInstructionVector::iterator J = Users.begin(),
718 JE = Users.end(); J != JE; ++J)
719 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
724 // Reroll the provided loop with respect to the provided induction variable.
725 // Generally, we're looking for a loop like this:
727 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
729 // %iv.1 = add %iv, 1 <-- a root increment
731 // %iv.2 = add %iv, 2 <-- a root increment
733 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
736 // %iv.next = add %iv, scale
737 // %cmp = icmp(%iv, ...)
738 // br %cmp, header, exit
740 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
741 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
742 // be intermixed with eachother. The restriction imposed by this algorithm is
743 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
746 // First, we collect the use set of %iv, excluding the other increment roots.
747 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
748 // times, having collected the use set of f(%iv.(i+1)), during which we:
749 // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
750 // the next unmatched instruction in f(%iv.(i+1)).
751 // - Ensure that both matched instructions don't have any external users
752 // (with the exception of last-in-chain reduction instructions).
753 // - Track the (aliasing) write set, and other side effects, of all
754 // instructions that belong to future iterations that come before the matched
755 // instructions. If the matched instructions read from that write set, then
756 // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
757 // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
758 // if any of these future instructions had side effects (could not be
759 // speculatively executed), and so do the matched instructions, when we
760 // cannot reorder those side-effect-producing instructions, and rerolling
763 // Finally, we make sure that all loop instructions are either loop increment
764 // roots, belong to simple latch code, parts of validated reductions, part of
765 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
766 // have been validated), then we reroll the loop.
767 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
768 const SCEV *IterCount,
769 ReductionTracker &Reductions) {
770 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
771 uint64_t Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
772 getValue()->getZExtValue();
773 // The collection of loop increment instructions.
774 SmallInstructionVector LoopIncs;
775 uint64_t Scale = Inc;
777 // The effective induction variable, IV, is normally also the real induction
778 // variable. When we're dealing with a loop like:
779 // for (int i = 0; i < 500; ++i)
783 // then the real IV is still i, but the effective IV is (3*i).
784 Instruction *RealIV = IV;
785 if (Inc == 1 && !findScaleFromMul(RealIV, Scale, IV, LoopIncs))
788 assert(Scale <= MaxInc && "Scale is too large");
789 assert(Scale > 1 && "Scale must be at least 2");
791 // The set of increment instructions for each increment value.
792 SmallVector<SmallInstructionVector, 32> Roots(Scale-1);
793 SmallInstructionSet AllRoots;
794 if (!collectAllRoots(L, Inc, Scale, IV, Roots, AllRoots, LoopIncs))
797 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
800 // An array of just the possible reductions for this scale factor. When we
801 // collect the set of all users of some root instructions, these reduction
802 // instructions are treated as 'final' (their uses are not considered).
803 // This is important because we don't want the root use set to search down
804 // the reduction chain.
805 SmallInstructionSet PossibleRedSet;
806 SmallInstructionSet PossibleRedLastSet, PossibleRedPHISet;
807 Reductions.restrictToScale(Scale, PossibleRedSet, PossibleRedPHISet,
810 // We now need to check for equivalence of the use graph of each root with
811 // that of the primary induction variable (excluding the roots). Our goal
812 // here is not to solve the full graph isomorphism problem, but rather to
813 // catch common cases without a lot of work. As a result, we will assume
814 // that the relative order of the instructions in each unrolled iteration
815 // is the same (although we will not make an assumption about how the
816 // different iterations are intermixed). Note that while the order must be
817 // the same, the instructions may not be in the same basic block.
818 SmallInstructionSet Exclude(AllRoots);
819 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
821 DenseSet<Instruction *> BaseUseSet;
822 collectInLoopUserSet(L, IV, Exclude, PossibleRedSet, BaseUseSet);
824 DenseSet<Instruction *> AllRootUses;
825 std::vector<DenseSet<Instruction *> > RootUseSets(Scale-1);
827 bool MatchFailed = false;
828 for (unsigned i = 0; i < Scale-1 && !MatchFailed; ++i) {
829 DenseSet<Instruction *> &RootUseSet = RootUseSets[i];
830 collectInLoopUserSet(L, Roots[i], SmallInstructionSet(),
831 PossibleRedSet, RootUseSet);
833 DEBUG(dbgs() << "LRR: base use set size: " << BaseUseSet.size() <<
834 " vs. iteration increment " << (i+1) <<
835 " use set size: " << RootUseSet.size() << "\n");
837 if (BaseUseSet.size() != RootUseSet.size()) {
842 // In addition to regular aliasing information, we need to look for
843 // instructions from later (future) iterations that have side effects
844 // preventing us from reordering them past other instructions with side
846 bool FutureSideEffects = false;
847 AliasSetTracker AST(*AA);
849 // The map between instructions in f(%iv.(i+1)) and f(%iv).
850 DenseMap<Value *, Value *> BaseMap;
852 assert(L->getNumBlocks() == 1 && "Cannot handle multi-block loops");
853 for (BasicBlock::iterator J1 = Header->begin(), J2 = Header->begin(),
854 JE = Header->end(); J1 != JE && !MatchFailed; ++J1) {
855 if (cast<Instruction>(J1) == RealIV)
857 if (cast<Instruction>(J1) == IV)
859 if (!BaseUseSet.count(J1))
861 if (PossibleRedPHISet.count(J1)) // Skip reduction PHIs.
864 while (J2 != JE && (!RootUseSet.count(J2) ||
865 std::find(Roots[i].begin(), Roots[i].end(), J2) !=
867 // As we iterate through the instructions, instructions that don't
868 // belong to previous iterations (or the base case), must belong to
869 // future iterations. We want to track the alias set of writes from
870 // previous iterations.
871 if (!isa<PHINode>(J2) && !BaseUseSet.count(J2) &&
872 !AllRootUses.count(J2)) {
873 if (J2->mayWriteToMemory())
876 // Note: This is specifically guarded by a check on isa<PHINode>,
877 // which while a valid (somewhat arbitrary) micro-optimization, is
878 // needed because otherwise isSafeToSpeculativelyExecute returns
879 // false on PHI nodes.
880 if (!isSimpleLoadStore(J2) && !isSafeToSpeculativelyExecute(J2, DL))
881 FutureSideEffects = true;
887 if (!J1->isSameOperationAs(J2)) {
888 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
889 " vs. " << *J2 << "\n");
894 // Make sure that this instruction, which is in the use set of this
895 // root instruction, does not also belong to the base set or the set of
896 // some previous root instruction.
897 if (BaseUseSet.count(J2) || AllRootUses.count(J2)) {
898 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
899 " vs. " << *J2 << " (prev. case overlap)\n");
904 // Make sure that we don't alias with any instruction in the alias set
905 // tracker. If we do, then we depend on a future iteration, and we
907 if (J2->mayReadFromMemory()) {
908 for (AliasSetTracker::iterator K = AST.begin(), KE = AST.end();
909 K != KE && !MatchFailed; ++K) {
910 if (K->aliasesUnknownInst(J2, *AA)) {
911 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
912 " vs. " << *J2 << " (depends on future store)\n");
919 // If we've past an instruction from a future iteration that may have
920 // side effects, and this instruction might also, then we can't reorder
921 // them, and this matching fails. As an exception, we allow the alias
922 // set tracker to handle regular (simple) load/store dependencies.
923 if (FutureSideEffects &&
924 ((!isSimpleLoadStore(J1) &&
925 !isSafeToSpeculativelyExecute(J1, DL)) ||
926 (!isSimpleLoadStore(J2) &&
927 !isSafeToSpeculativelyExecute(J2, DL)))) {
928 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
930 " (side effects prevent reordering)\n");
935 // For instructions that are part of a reduction, if the operation is
936 // associative, then don't bother matching the operands (because we
937 // already know that the instructions are isomorphic, and the order
938 // within the iteration does not matter). For non-associative reductions,
939 // we do need to match the operands, because we need to reject
940 // out-of-order instructions within an iteration!
941 // For example (assume floating-point addition), we need to reject this:
942 // x += a[i]; x += b[i];
943 // x += a[i+1]; x += b[i+1];
944 // x += b[i+2]; x += a[i+2];
945 bool InReduction = Reductions.isPairInSame(J1, J2);
947 if (!(InReduction && J1->isAssociative())) {
948 bool Swapped = false, SomeOpMatched = false;
949 for (unsigned j = 0; j < J1->getNumOperands() && !MatchFailed; ++j) {
950 Value *Op2 = J2->getOperand(j);
952 // If this is part of a reduction (and the operation is not
953 // associatve), then we match all operands, but not those that are
954 // part of the reduction.
956 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
957 if (Reductions.isPairInSame(J2, Op2I))
960 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
961 if (BMI != BaseMap.end())
963 else if (std::find(Roots[i].begin(), Roots[i].end(),
964 (Instruction*) Op2) != Roots[i].end())
967 if (J1->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
968 // If we've not already decided to swap the matched operands, and
969 // we've not already matched our first operand (note that we could
970 // have skipped matching the first operand because it is part of a
971 // reduction above), and the instruction is commutative, then try
972 // the swapped match.
973 if (!Swapped && J1->isCommutative() && !SomeOpMatched &&
974 J1->getOperand(!j) == Op2) {
977 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
978 " vs. " << *J2 << " (operand " << j << ")\n");
984 SomeOpMatched = true;
988 if ((!PossibleRedLastSet.count(J1) && hasUsesOutsideLoop(J1, L)) ||
989 (!PossibleRedLastSet.count(J2) && hasUsesOutsideLoop(J2, L))) {
990 DEBUG(dbgs() << "LRR: iteration root match failed at " << *J1 <<
991 " vs. " << *J2 << " (uses outside loop)\n");
997 BaseMap.insert(std::pair<Value *, Value *>(J2, J1));
999 AllRootUses.insert(J2);
1000 Reductions.recordPair(J1, J2, i+1);
1009 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1012 DenseSet<Instruction *> LoopIncUseSet;
1013 collectInLoopUserSet(L, LoopIncs, SmallInstructionSet(),
1014 SmallInstructionSet(), LoopIncUseSet);
1015 DEBUG(dbgs() << "LRR: Loop increment set size: " <<
1016 LoopIncUseSet.size() << "\n");
1018 // Make sure that all instructions in the loop have been included in some
1020 for (BasicBlock::iterator J = Header->begin(), JE = Header->end();
1022 if (isa<DbgInfoIntrinsic>(J))
1024 if (cast<Instruction>(J) == RealIV)
1026 if (cast<Instruction>(J) == IV)
1028 if (BaseUseSet.count(J) || AllRootUses.count(J) ||
1029 (LoopIncUseSet.count(J) && (J->isTerminator() ||
1030 isSafeToSpeculativelyExecute(J, DL))))
1033 if (AllRoots.count(J))
1036 if (Reductions.isSelectedPHI(J))
1039 DEBUG(dbgs() << "LRR: aborting reroll based on " << *RealIV <<
1040 " unprocessed instruction found: " << *J << "\n");
1048 DEBUG(dbgs() << "LRR: all instructions processed from " <<
1051 if (!Reductions.validateSelected())
1054 // At this point, we've validated the rerolling, and we're committed to
1057 Reductions.replaceSelected();
1059 // Remove instructions associated with non-base iterations.
1060 for (BasicBlock::reverse_iterator J = Header->rbegin();
1061 J != Header->rend();) {
1062 if (AllRootUses.count(&*J)) {
1063 Instruction *D = &*J;
1064 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1065 D->eraseFromParent();
1072 // Insert the new induction variable.
1073 const SCEV *Start = RealIVSCEV->getStart();
1075 Start = SE->getMulExpr(Start,
1076 SE->getConstant(Start->getType(), Scale));
1077 const SCEVAddRecExpr *H =
1078 cast<SCEVAddRecExpr>(SE->getAddRecExpr(Start,
1079 SE->getConstant(RealIVSCEV->getType(), 1),
1080 L, SCEV::FlagAnyWrap));
1081 { // Limit the lifetime of SCEVExpander.
1082 SCEVExpander Expander(*SE, "reroll");
1083 Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1085 for (DenseSet<Instruction *>::iterator J = BaseUseSet.begin(),
1086 JE = BaseUseSet.end(); J != JE; ++J)
1087 (*J)->replaceUsesOfWith(IV, NewIV);
1089 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1090 if (LoopIncUseSet.count(BI)) {
1091 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1094 SE->getMulExpr(ICSCEV, SE->getConstant(ICSCEV->getType(), Scale));
1095 // Iteration count SCEV minus 1
1096 const SCEV *ICMinus1SCEV =
1097 SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
1099 Value *ICMinus1; // Iteration count minus 1
1100 if (isa<SCEVConstant>(ICMinus1SCEV)) {
1101 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1103 BasicBlock *Preheader = L->getLoopPreheader();
1105 Preheader = InsertPreheaderForLoop(L, this);
1107 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1108 Preheader->getTerminator());
1112 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
1113 BI->setCondition(Cond);
1115 if (BI->getSuccessor(1) != Header)
1116 BI->swapSuccessors();
1121 SimplifyInstructionsInBlock(Header, DL, TLI);
1122 DeleteDeadPHIs(Header, TLI);
1127 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1128 if (skipOptnoneFunction(L))
1131 AA = &getAnalysis<AliasAnalysis>();
1132 LI = &getAnalysis<LoopInfo>();
1133 SE = &getAnalysis<ScalarEvolution>();
1134 TLI = &getAnalysis<TargetLibraryInfo>();
1135 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1136 DL = DLP ? &DLP->getDataLayout() : nullptr;
1137 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1139 BasicBlock *Header = L->getHeader();
1140 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1141 "] Loop %" << Header->getName() << " (" <<
1142 L->getNumBlocks() << " block(s))\n");
1144 bool Changed = false;
1146 // For now, we'll handle only single BB loops.
1147 if (L->getNumBlocks() > 1)
1150 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1153 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1154 const SCEV *IterCount =
1155 SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1156 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1158 // First, we need to find the induction variable with respect to which we can
1159 // reroll (there may be several possible options).
1160 SmallInstructionVector PossibleIVs;
1161 collectPossibleIVs(L, PossibleIVs);
1163 if (PossibleIVs.empty()) {
1164 DEBUG(dbgs() << "LRR: No possible IVs found\n");
1168 ReductionTracker Reductions;
1169 collectPossibleReductions(L, Reductions);
1171 // For each possible IV, collect the associated possible set of 'root' nodes
1172 // (i+1, i+2, etc.).
1173 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1174 IE = PossibleIVs.end(); I != IE; ++I)
1175 if (reroll(*I, L, Header, IterCount, Reductions)) {