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/MapVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallBitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AliasSetTracker.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionExpander.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/LoopUtils.h"
40 #define DEBUG_TYPE "loop-reroll"
42 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
44 static cl::opt<unsigned>
45 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
46 cl::desc("The maximum increment for loop rerolling"));
48 static cl::opt<unsigned>
49 NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
51 cl::desc("The maximum number of failures to tolerate"
52 " during fuzzy matching. (default: 400)"));
54 // This loop re-rolling transformation aims to transform loops like this:
58 // for (int i = 0; i < 500; i += 3) {
65 // into a loop like this:
68 // for (int i = 0; i < 500; ++i)
72 // It does this by looking for loops that, besides the latch code, are composed
73 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
74 // to the induction variable, and where each DAG is isomorphic to the DAG
75 // rooted at the induction variable (excepting the sub-DAGs which root the
76 // other induction-variable increments). In other words, we're looking for loop
77 // bodies of the form:
79 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
81 // %iv.1 = add %iv, 1 <-- a root increment
83 // %iv.2 = add %iv, 2 <-- a root increment
85 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
88 // %iv.next = add %iv, scale
89 // %cmp = icmp(%iv, ...)
90 // br %cmp, header, exit
92 // where each f(i) is a set of instructions that, collectively, are a function
93 // only of i (and other loop-invariant values).
95 // As a special case, we can also reroll loops like this:
99 // for (int i = 0; i < 500; ++i) {
101 // x[3*i+1] = foo(0);
102 // x[3*i+2] = foo(0);
108 // void bar(int *x) {
109 // for (int i = 0; i < 1500; ++i)
113 // in which case, we're looking for inputs like this:
115 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
116 // %scaled.iv = mul %iv, scale
118 // %scaled.iv.1 = add %scaled.iv, 1
120 // %scaled.iv.2 = add %scaled.iv, 2
122 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
123 // f(%scaled.iv.scale_m_1)
125 // %iv.next = add %iv, 1
126 // %cmp = icmp(%iv, ...)
127 // br %cmp, header, exit
130 enum IterationLimits {
131 /// The maximum number of iterations that we'll try and reroll. This
132 /// has to be less than 25 in order to fit into a SmallBitVector.
133 IL_MaxRerollIterations = 16,
134 /// The bitvector index used by loop induction variables and other
135 /// instructions that belong to all iterations.
140 class LoopReroll : public LoopPass {
142 static char ID; // Pass ID, replacement for typeid
143 LoopReroll() : LoopPass(ID) {
144 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
147 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
149 void getAnalysisUsage(AnalysisUsage &AU) const override {
150 AU.addRequired<AAResultsWrapperPass>();
151 AU.addRequired<LoopInfoWrapperPass>();
152 AU.addPreserved<LoopInfoWrapperPass>();
153 AU.addRequired<DominatorTreeWrapperPass>();
154 AU.addPreserved<DominatorTreeWrapperPass>();
155 AU.addRequired<ScalarEvolutionWrapperPass>();
156 AU.addRequired<TargetLibraryInfoWrapperPass>();
163 TargetLibraryInfo *TLI;
166 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
167 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
169 // Map between induction variable and its increment
170 DenseMap<Instruction *, int64_t> IVToIncMap;
172 // A chain of isomorphic instructions, identified by a single-use PHI
173 // representing a reduction. Only the last value may be used outside the
175 struct SimpleLoopReduction {
176 SimpleLoopReduction(Instruction *P, Loop *L)
177 : Valid(false), Instructions(1, P) {
178 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
186 Instruction *getPHI() const {
187 assert(Valid && "Using invalid reduction");
188 return Instructions.front();
191 Instruction *getReducedValue() const {
192 assert(Valid && "Using invalid reduction");
193 return Instructions.back();
196 Instruction *get(size_t i) const {
197 assert(Valid && "Using invalid reduction");
198 return Instructions[i+1];
201 Instruction *operator [] (size_t i) const { return get(i); }
203 // The size, ignoring the initial PHI.
204 size_t size() const {
205 assert(Valid && "Using invalid reduction");
206 return Instructions.size()-1;
209 typedef SmallInstructionVector::iterator iterator;
210 typedef SmallInstructionVector::const_iterator const_iterator;
213 assert(Valid && "Using invalid reduction");
214 return std::next(Instructions.begin());
217 const_iterator begin() const {
218 assert(Valid && "Using invalid reduction");
219 return std::next(Instructions.begin());
222 iterator end() { return Instructions.end(); }
223 const_iterator end() const { return Instructions.end(); }
227 SmallInstructionVector Instructions;
232 // The set of all reductions, and state tracking of possible reductions
233 // during loop instruction processing.
234 struct ReductionTracker {
235 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
237 // Add a new possible reduction.
238 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
240 // Setup to track possible reductions corresponding to the provided
241 // rerolling scale. Only reductions with a number of non-PHI instructions
242 // that is divisible by the scale are considered. Three instructions sets
244 // - A set of all possible instructions in eligible reductions.
245 // - A set of all PHIs in eligible reductions
246 // - A set of all reduced values (last instructions) in eligible
248 void restrictToScale(uint64_t Scale,
249 SmallInstructionSet &PossibleRedSet,
250 SmallInstructionSet &PossibleRedPHISet,
251 SmallInstructionSet &PossibleRedLastSet) {
252 PossibleRedIdx.clear();
253 PossibleRedIter.clear();
256 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
257 if (PossibleReds[i].size() % Scale == 0) {
258 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
259 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
261 PossibleRedSet.insert(PossibleReds[i].getPHI());
262 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
263 for (Instruction *J : PossibleReds[i]) {
264 PossibleRedSet.insert(J);
265 PossibleRedIdx[J] = i;
270 // The functions below are used while processing the loop instructions.
272 // Are the two instructions both from reductions, and furthermore, from
273 // the same reduction?
274 bool isPairInSame(Instruction *J1, Instruction *J2) {
275 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
276 if (J1I != PossibleRedIdx.end()) {
277 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
278 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
285 // The two provided instructions, the first from the base iteration, and
286 // the second from iteration i, form a matched pair. If these are part of
287 // a reduction, record that fact.
288 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
289 if (PossibleRedIdx.count(J1)) {
290 assert(PossibleRedIdx.count(J2) &&
291 "Recording reduction vs. non-reduction instruction?");
293 PossibleRedIter[J1] = 0;
294 PossibleRedIter[J2] = i;
296 int Idx = PossibleRedIdx[J1];
297 assert(Idx == PossibleRedIdx[J2] &&
298 "Recording pair from different reductions?");
303 // The functions below can be called after we've finished processing all
304 // instructions in the loop, and we know which reductions were selected.
306 // Is the provided instruction the PHI of a reduction selected for
308 bool isSelectedPHI(Instruction *J) {
309 if (!isa<PHINode>(J))
312 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
315 if (cast<Instruction>(J) == PossibleReds[i].getPHI())
322 bool validateSelected();
323 void replaceSelected();
326 // The vector of all possible reductions (for any scale).
327 SmallReductionVector PossibleReds;
329 DenseMap<Instruction *, int> PossibleRedIdx;
330 DenseMap<Instruction *, int> PossibleRedIter;
334 // A DAGRootSet models an induction variable being used in a rerollable
335 // loop. For example,
341 // Base instruction -> i*3
344 // ST[y1] +1 +2 <-- Roots
348 // There may be multiple DAGRoots, for example:
350 // x[i*2+0] = ... (1)
351 // x[i*2+1] = ... (1)
352 // x[i*2+4] = ... (2)
353 // x[i*2+5] = ... (2)
354 // x[(i+1234)*2+5678] = ... (3)
355 // x[(i+1234)*2+5679] = ... (3)
357 // The loop will be rerolled by adding a new loop induction variable,
358 // one for the Base instruction in each DAGRootSet.
361 Instruction *BaseInst;
362 SmallInstructionVector Roots;
363 // The instructions between IV and BaseInst (but not including BaseInst).
364 SmallInstructionSet SubsumedInsts;
367 // The set of all DAG roots, and state tracking of all roots
368 // for a particular induction variable.
369 struct DAGRootTracker {
370 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
371 ScalarEvolution *SE, AliasAnalysis *AA,
372 TargetLibraryInfo *TLI,
373 DenseMap<Instruction *, int64_t> &IncrMap)
374 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), IV(IV),
375 IVToIncMap(IncrMap) {}
377 /// Stage 1: Find all the DAG roots for the induction variable.
379 /// Stage 2: Validate if the found roots are valid.
380 bool validate(ReductionTracker &Reductions);
381 /// Stage 3: Assuming validate() returned true, perform the
383 /// @param IterCount The maximum iteration count of L.
384 void replace(const SCEV *IterCount);
387 typedef MapVector<Instruction*, SmallBitVector> UsesTy;
389 bool findRootsRecursive(Instruction *IVU,
390 SmallInstructionSet SubsumedInsts);
391 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
392 bool collectPossibleRoots(Instruction *Base,
393 std::map<int64_t,Instruction*> &Roots);
395 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
396 void collectInLoopUserSet(const SmallInstructionVector &Roots,
397 const SmallInstructionSet &Exclude,
398 const SmallInstructionSet &Final,
399 DenseSet<Instruction *> &Users);
400 void collectInLoopUserSet(Instruction *Root,
401 const SmallInstructionSet &Exclude,
402 const SmallInstructionSet &Final,
403 DenseSet<Instruction *> &Users);
405 UsesTy::iterator nextInstr(int Val, UsesTy &In,
406 const SmallInstructionSet &Exclude,
407 UsesTy::iterator *StartI=nullptr);
408 bool isBaseInst(Instruction *I);
409 bool isRootInst(Instruction *I);
410 bool instrDependsOn(Instruction *I,
411 UsesTy::iterator Start,
412 UsesTy::iterator End);
416 // Members of Parent, replicated here for brevity.
420 TargetLibraryInfo *TLI;
422 // The loop induction variable.
426 // Loop reroll count; if Inc == 1, this records the scaling applied
427 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
428 // If Inc is not 1, Scale = Inc.
430 // The roots themselves.
431 SmallVector<DAGRootSet,16> RootSets;
432 // All increment instructions for IV.
433 SmallInstructionVector LoopIncs;
434 // Map of all instructions in the loop (in order) to the iterations
435 // they are used in (or specially, IL_All for instructions
436 // used in the loop increment mechanism).
438 // Map between induction variable and its increment
439 DenseMap<Instruction *, int64_t> &IVToIncMap;
442 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
443 void collectPossibleReductions(Loop *L,
444 ReductionTracker &Reductions);
445 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
446 ReductionTracker &Reductions);
450 char LoopReroll::ID = 0;
451 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
452 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
453 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
454 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
455 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
456 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
457 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
459 Pass *llvm::createLoopRerollPass() {
460 return new LoopReroll;
463 // Returns true if the provided instruction is used outside the given loop.
464 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
465 // non-loop blocks to be outside the loop.
466 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
467 for (User *U : I->users()) {
468 if (!L->contains(cast<Instruction>(U)))
474 // Collect the list of loop induction variables with respect to which it might
475 // be possible to reroll the loop.
476 void LoopReroll::collectPossibleIVs(Loop *L,
477 SmallInstructionVector &PossibleIVs) {
478 BasicBlock *Header = L->getHeader();
479 for (BasicBlock::iterator I = Header->begin(),
480 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
481 if (!isa<PHINode>(I))
483 if (!I->getType()->isIntegerTy())
486 if (const SCEVAddRecExpr *PHISCEV =
487 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
488 if (PHISCEV->getLoop() != L)
490 if (!PHISCEV->isAffine())
492 if (const SCEVConstant *IncSCEV =
493 dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
494 const APInt &AInt = IncSCEV->getValue()->getValue().abs();
495 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
497 IVToIncMap[I] = IncSCEV->getValue()->getSExtValue();
498 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
500 PossibleIVs.push_back(I);
506 // Add the remainder of the reduction-variable chain to the instruction vector
507 // (the initial PHINode has already been added). If successful, the object is
509 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
510 assert(!Valid && "Cannot add to an already-valid chain");
512 // The reduction variable must be a chain of single-use instructions
513 // (including the PHI), except for the last value (which is used by the PHI
514 // and also outside the loop).
515 Instruction *C = Instructions.front();
520 C = cast<Instruction>(*C->user_begin());
521 if (C->hasOneUse()) {
522 if (!C->isBinaryOp())
525 if (!(isa<PHINode>(Instructions.back()) ||
526 C->isSameOperationAs(Instructions.back())))
529 Instructions.push_back(C);
531 } while (C->hasOneUse());
533 if (Instructions.size() < 2 ||
534 !C->isSameOperationAs(Instructions.back()) ||
538 // C is now the (potential) last instruction in the reduction chain.
539 for (User *U : C->users()) {
540 // The only in-loop user can be the initial PHI.
541 if (L->contains(cast<Instruction>(U)))
542 if (cast<Instruction>(U) != Instructions.front())
546 Instructions.push_back(C);
550 // Collect the vector of possible reduction variables.
551 void LoopReroll::collectPossibleReductions(Loop *L,
552 ReductionTracker &Reductions) {
553 BasicBlock *Header = L->getHeader();
554 for (BasicBlock::iterator I = Header->begin(),
555 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
556 if (!isa<PHINode>(I))
558 if (!I->getType()->isSingleValueType())
561 SimpleLoopReduction SLR(I, L);
565 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
566 SLR.size() << " chained instructions)\n");
567 Reductions.addSLR(SLR);
571 // Collect the set of all users of the provided root instruction. This set of
572 // users contains not only the direct users of the root instruction, but also
573 // all users of those users, and so on. There are two exceptions:
575 // 1. Instructions in the set of excluded instructions are never added to the
576 // use set (even if they are users). This is used, for example, to exclude
577 // including root increments in the use set of the primary IV.
579 // 2. Instructions in the set of final instructions are added to the use set
580 // if they are users, but their users are not added. This is used, for
581 // example, to prevent a reduction update from forcing all later reduction
582 // updates into the use set.
583 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
584 Instruction *Root, const SmallInstructionSet &Exclude,
585 const SmallInstructionSet &Final,
586 DenseSet<Instruction *> &Users) {
587 SmallInstructionVector Queue(1, Root);
588 while (!Queue.empty()) {
589 Instruction *I = Queue.pop_back_val();
590 if (!Users.insert(I).second)
594 for (Use &U : I->uses()) {
595 Instruction *User = cast<Instruction>(U.getUser());
596 if (PHINode *PN = dyn_cast<PHINode>(User)) {
597 // Ignore "wrap-around" uses to PHIs of this loop's header.
598 if (PN->getIncomingBlock(U) == L->getHeader())
602 if (L->contains(User) && !Exclude.count(User)) {
603 Queue.push_back(User);
607 // We also want to collect single-user "feeder" values.
608 for (User::op_iterator OI = I->op_begin(),
609 OIE = I->op_end(); OI != OIE; ++OI) {
610 if (Instruction *Op = dyn_cast<Instruction>(*OI))
611 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
618 // Collect all of the users of all of the provided root instructions (combined
619 // into a single set).
620 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
621 const SmallInstructionVector &Roots,
622 const SmallInstructionSet &Exclude,
623 const SmallInstructionSet &Final,
624 DenseSet<Instruction *> &Users) {
625 for (SmallInstructionVector::const_iterator I = Roots.begin(),
626 IE = Roots.end(); I != IE; ++I)
627 collectInLoopUserSet(*I, Exclude, Final, Users);
630 static bool isSimpleLoadStore(Instruction *I) {
631 if (LoadInst *LI = dyn_cast<LoadInst>(I))
632 return LI->isSimple();
633 if (StoreInst *SI = dyn_cast<StoreInst>(I))
634 return SI->isSimple();
635 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
636 return !MI->isVolatile();
640 /// Return true if IVU is a "simple" arithmetic operation.
641 /// This is used for narrowing the search space for DAGRoots; only arithmetic
642 /// and GEPs can be part of a DAGRoot.
643 static bool isSimpleArithmeticOp(User *IVU) {
644 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
645 switch (I->getOpcode()) {
646 default: return false;
647 case Instruction::Add:
648 case Instruction::Sub:
649 case Instruction::Mul:
650 case Instruction::Shl:
651 case Instruction::AShr:
652 case Instruction::LShr:
653 case Instruction::GetElementPtr:
654 case Instruction::Trunc:
655 case Instruction::ZExt:
656 case Instruction::SExt:
663 static bool isLoopIncrement(User *U, Instruction *IV) {
664 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
665 if (!BO || BO->getOpcode() != Instruction::Add)
668 for (auto *UU : BO->users()) {
669 PHINode *PN = dyn_cast<PHINode>(UU);
676 bool LoopReroll::DAGRootTracker::
677 collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
678 SmallInstructionVector BaseUsers;
680 for (auto *I : Base->users()) {
681 ConstantInt *CI = nullptr;
683 if (isLoopIncrement(I, IV)) {
684 LoopIncs.push_back(cast<Instruction>(I));
688 // The root nodes must be either GEPs, ORs or ADDs.
689 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
690 if (BO->getOpcode() == Instruction::Add ||
691 BO->getOpcode() == Instruction::Or)
692 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
693 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
694 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
695 CI = dyn_cast<ConstantInt>(LastOperand);
699 if (Instruction *II = dyn_cast<Instruction>(I)) {
700 BaseUsers.push_back(II);
703 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
708 int64_t V = std::abs(CI->getValue().getSExtValue());
709 if (Roots.find(V) != Roots.end())
710 // No duplicates, please.
713 Roots[V] = cast<Instruction>(I);
719 // If we found non-loop-inc, non-root users of Base, assume they are
720 // for the zeroth root index. This is because "add %a, 0" gets optimized
722 if (BaseUsers.size()) {
723 if (Roots.find(0) != Roots.end()) {
724 DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
730 // Calculate the number of users of the base, or lowest indexed, iteration.
731 unsigned NumBaseUses = BaseUsers.size();
732 if (NumBaseUses == 0)
733 NumBaseUses = Roots.begin()->second->getNumUses();
735 // Check that every node has the same number of users.
736 for (auto &KV : Roots) {
739 if (KV.second->getNumUses() != NumBaseUses) {
740 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
741 << "#Base=" << NumBaseUses << ", #Root=" <<
742 KV.second->getNumUses() << "\n");
750 bool LoopReroll::DAGRootTracker::
751 findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
752 // Does the user look like it could be part of a root set?
753 // All its users must be simple arithmetic ops.
754 if (I->getNumUses() > IL_MaxRerollIterations)
757 if ((I->getOpcode() == Instruction::Mul ||
758 I->getOpcode() == Instruction::PHI) &&
760 findRootsBase(I, SubsumedInsts))
763 SubsumedInsts.insert(I);
765 for (User *V : I->users()) {
766 Instruction *I = dyn_cast<Instruction>(V);
767 if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
770 if (!I || !isSimpleArithmeticOp(I) ||
771 !findRootsRecursive(I, SubsumedInsts))
777 bool LoopReroll::DAGRootTracker::
778 findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
780 // The base instruction needs to be a multiply so
781 // that we can erase it.
782 if (IVU->getOpcode() != Instruction::Mul &&
783 IVU->getOpcode() != Instruction::PHI)
786 std::map<int64_t, Instruction*> V;
787 if (!collectPossibleRoots(IVU, V))
790 // If we didn't get a root for index zero, then IVU must be
792 if (V.find(0) == V.end())
793 SubsumedInsts.insert(IVU);
795 // Partition the vector into monotonically increasing indexes.
797 DRS.BaseInst = nullptr;
801 DRS.BaseInst = KV.second;
802 DRS.SubsumedInsts = SubsumedInsts;
803 } else if (DRS.Roots.empty()) {
804 DRS.Roots.push_back(KV.second);
805 } else if (V.find(KV.first - 1) != V.end()) {
806 DRS.Roots.push_back(KV.second);
808 // Linear sequence terminated.
809 RootSets.push_back(DRS);
810 DRS.BaseInst = KV.second;
811 DRS.SubsumedInsts = SubsumedInsts;
815 RootSets.push_back(DRS);
820 bool LoopReroll::DAGRootTracker::findRoots() {
821 Inc = IVToIncMap[IV];
823 assert(RootSets.empty() && "Unclean state!");
824 if (std::abs(Inc) == 1) {
825 for (auto *IVU : IV->users()) {
826 if (isLoopIncrement(IVU, IV))
827 LoopIncs.push_back(cast<Instruction>(IVU));
829 if (!findRootsRecursive(IV, SmallInstructionSet()))
831 LoopIncs.push_back(IV);
833 if (!findRootsBase(IV, SmallInstructionSet()))
837 // Ensure all sets have the same size.
838 if (RootSets.empty()) {
839 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
842 for (auto &V : RootSets) {
843 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
845 << "LRR: Aborting because not all root sets have the same size\n");
850 // And ensure all loop iterations are consecutive. We rely on std::map
851 // providing ordered traversal.
852 for (auto &V : RootSets) {
853 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
857 // Consider a DAGRootSet with N-1 roots (so N different values including
859 // Define d = Roots[0] - BaseInst, which should be the same as
860 // Roots[I] - Roots[I-1] for all I in [1..N).
861 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
864 // Now, For the loop iterations to be consecutive:
867 unsigned N = V.Roots.size() + 1;
868 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
869 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
870 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
871 DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
875 Scale = RootSets[0].Roots.size() + 1;
877 if (Scale > IL_MaxRerollIterations) {
878 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
879 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
884 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
889 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
890 // Populate the MapVector with all instructions in the block, in order first,
891 // so we can iterate over the contents later in perfect order.
892 for (auto &I : *L->getHeader()) {
893 Uses[&I].resize(IL_End);
896 SmallInstructionSet Exclude;
897 for (auto &DRS : RootSets) {
898 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
899 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
900 Exclude.insert(DRS.BaseInst);
902 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
904 for (auto &DRS : RootSets) {
905 DenseSet<Instruction*> VBase;
906 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
907 for (auto *I : VBase) {
912 for (auto *Root : DRS.Roots) {
913 DenseSet<Instruction*> V;
914 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
916 // While we're here, check the use sets are the same size.
917 if (V.size() != VBase.size()) {
918 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
928 // Make sure our subsumed instructions are remembered too.
929 for (auto *I : DRS.SubsumedInsts) {
934 // Make sure the loop increments are also accounted for.
937 for (auto &DRS : RootSets) {
938 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
939 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
940 Exclude.insert(DRS.BaseInst);
943 DenseSet<Instruction*> V;
944 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
953 /// Get the next instruction in "In" that is a member of set Val.
954 /// Start searching from StartI, and do not return anything in Exclude.
955 /// If StartI is not given, start from In.begin().
956 LoopReroll::DAGRootTracker::UsesTy::iterator
957 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
958 const SmallInstructionSet &Exclude,
959 UsesTy::iterator *StartI) {
960 UsesTy::iterator I = StartI ? *StartI : In.begin();
961 while (I != In.end() && (I->second.test(Val) == 0 ||
962 Exclude.count(I->first) != 0))
967 bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
968 for (auto &DRS : RootSets) {
969 if (DRS.BaseInst == I)
975 bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
976 for (auto &DRS : RootSets) {
977 if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
983 /// Return true if instruction I depends on any instruction between
985 bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
986 UsesTy::iterator Start,
987 UsesTy::iterator End) {
988 for (auto *U : I->users()) {
989 for (auto It = Start; It != End; ++It)
996 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
997 // We now need to check for equivalence of the use graph of each root with
998 // that of the primary induction variable (excluding the roots). Our goal
999 // here is not to solve the full graph isomorphism problem, but rather to
1000 // catch common cases without a lot of work. As a result, we will assume
1001 // that the relative order of the instructions in each unrolled iteration
1002 // is the same (although we will not make an assumption about how the
1003 // different iterations are intermixed). Note that while the order must be
1004 // the same, the instructions may not be in the same basic block.
1006 // An array of just the possible reductions for this scale factor. When we
1007 // collect the set of all users of some root instructions, these reduction
1008 // instructions are treated as 'final' (their uses are not considered).
1009 // This is important because we don't want the root use set to search down
1010 // the reduction chain.
1011 SmallInstructionSet PossibleRedSet;
1012 SmallInstructionSet PossibleRedLastSet;
1013 SmallInstructionSet PossibleRedPHISet;
1014 Reductions.restrictToScale(Scale, PossibleRedSet,
1015 PossibleRedPHISet, PossibleRedLastSet);
1017 // Populate "Uses" with where each instruction is used.
1018 if (!collectUsedInstructions(PossibleRedSet))
1021 // Make sure we mark the reduction PHIs as used in all iterations.
1022 for (auto *I : PossibleRedPHISet) {
1023 Uses[I].set(IL_All);
1026 // Make sure all instructions in the loop are in one and only one
1028 for (auto &KV : Uses) {
1029 if (KV.second.count() != 1) {
1030 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1031 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1037 for (auto &KV : Uses) {
1038 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1042 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
1043 // In addition to regular aliasing information, we need to look for
1044 // instructions from later (future) iterations that have side effects
1045 // preventing us from reordering them past other instructions with side
1047 bool FutureSideEffects = false;
1048 AliasSetTracker AST(*AA);
1049 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1050 DenseMap<Value *, Value *> BaseMap;
1052 // Compare iteration Iter to the base.
1053 SmallInstructionSet Visited;
1054 auto BaseIt = nextInstr(0, Uses, Visited);
1055 auto RootIt = nextInstr(Iter, Uses, Visited);
1056 auto LastRootIt = Uses.begin();
1058 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1059 Instruction *BaseInst = BaseIt->first;
1060 Instruction *RootInst = RootIt->first;
1062 // Skip over the IV or root instructions; only match their users.
1063 bool Continue = false;
1064 if (isBaseInst(BaseInst)) {
1065 Visited.insert(BaseInst);
1066 BaseIt = nextInstr(0, Uses, Visited);
1069 if (isRootInst(RootInst)) {
1070 LastRootIt = RootIt;
1071 Visited.insert(RootInst);
1072 RootIt = nextInstr(Iter, Uses, Visited);
1075 if (Continue) continue;
1077 if (!BaseInst->isSameOperationAs(RootInst)) {
1078 // Last chance saloon. We don't try and solve the full isomorphism
1079 // problem, but try and at least catch the case where two instructions
1080 // *of different types* are round the wrong way. We won't be able to
1081 // efficiently tell, given two ADD instructions, which way around we
1082 // should match them, but given an ADD and a SUB, we can at least infer
1083 // which one is which.
1085 // This should allow us to deal with a greater subset of the isomorphism
1086 // problem. It does however change a linear algorithm into a quadratic
1087 // one, so limit the number of probes we do.
1088 auto TryIt = RootIt;
1089 unsigned N = NumToleratedFailedMatches;
1090 while (TryIt != Uses.end() &&
1091 !BaseInst->isSameOperationAs(TryIt->first) &&
1094 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1097 if (TryIt == Uses.end() || TryIt == RootIt ||
1098 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1099 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1100 " vs. " << *RootInst << "\n");
1105 RootInst = TryIt->first;
1108 // All instructions between the last root and this root
1109 // may belong to some other iteration. If they belong to a
1110 // future iteration, then they're dangerous to alias with.
1112 // Note that because we allow a limited amount of flexibility in the order
1113 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1114 // case we've already checked this set of instructions so we shouldn't
1116 for (; LastRootIt < RootIt; ++LastRootIt) {
1117 Instruction *I = LastRootIt->first;
1118 if (LastRootIt->second.find_first() < (int)Iter)
1120 if (I->mayWriteToMemory())
1122 // Note: This is specifically guarded by a check on isa<PHINode>,
1123 // which while a valid (somewhat arbitrary) micro-optimization, is
1124 // needed because otherwise isSafeToSpeculativelyExecute returns
1125 // false on PHI nodes.
1126 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
1127 !isSafeToSpeculativelyExecute(I))
1128 // Intervening instructions cause side effects.
1129 FutureSideEffects = true;
1132 // Make sure that this instruction, which is in the use set of this
1133 // root instruction, does not also belong to the base set or the set of
1134 // some other root instruction.
1135 if (RootIt->second.count() > 1) {
1136 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1137 " vs. " << *RootInst << " (prev. case overlap)\n");
1141 // Make sure that we don't alias with any instruction in the alias set
1142 // tracker. If we do, then we depend on a future iteration, and we
1144 if (RootInst->mayReadFromMemory())
1145 for (auto &K : AST) {
1146 if (K.aliasesUnknownInst(RootInst, *AA)) {
1147 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1148 " vs. " << *RootInst << " (depends on future store)\n");
1153 // If we've past an instruction from a future iteration that may have
1154 // side effects, and this instruction might also, then we can't reorder
1155 // them, and this matching fails. As an exception, we allow the alias
1156 // set tracker to handle regular (simple) load/store dependencies.
1157 if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
1158 !isSafeToSpeculativelyExecute(BaseInst)) ||
1159 (!isSimpleLoadStore(RootInst) &&
1160 !isSafeToSpeculativelyExecute(RootInst)))) {
1161 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1162 " vs. " << *RootInst <<
1163 " (side effects prevent reordering)\n");
1167 // For instructions that are part of a reduction, if the operation is
1168 // associative, then don't bother matching the operands (because we
1169 // already know that the instructions are isomorphic, and the order
1170 // within the iteration does not matter). For non-associative reductions,
1171 // we do need to match the operands, because we need to reject
1172 // out-of-order instructions within an iteration!
1173 // For example (assume floating-point addition), we need to reject this:
1174 // x += a[i]; x += b[i];
1175 // x += a[i+1]; x += b[i+1];
1176 // x += b[i+2]; x += a[i+2];
1177 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
1179 if (!(InReduction && BaseInst->isAssociative())) {
1180 bool Swapped = false, SomeOpMatched = false;
1181 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1182 Value *Op2 = RootInst->getOperand(j);
1184 // If this is part of a reduction (and the operation is not
1185 // associatve), then we match all operands, but not those that are
1186 // part of the reduction.
1188 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
1189 if (Reductions.isPairInSame(RootInst, Op2I))
1192 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
1193 if (BMI != BaseMap.end()) {
1196 for (auto &DRS : RootSets) {
1197 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1204 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
1205 // If we've not already decided to swap the matched operands, and
1206 // we've not already matched our first operand (note that we could
1207 // have skipped matching the first operand because it is part of a
1208 // reduction above), and the instruction is commutative, then try
1209 // the swapped match.
1210 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1211 BaseInst->getOperand(!j) == Op2) {
1214 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1215 << " vs. " << *RootInst << " (operand " << j << ")\n");
1220 SomeOpMatched = true;
1224 if ((!PossibleRedLastSet.count(BaseInst) &&
1225 hasUsesOutsideLoop(BaseInst, L)) ||
1226 (!PossibleRedLastSet.count(RootInst) &&
1227 hasUsesOutsideLoop(RootInst, L))) {
1228 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1229 " vs. " << *RootInst << " (uses outside loop)\n");
1233 Reductions.recordPair(BaseInst, RootInst, Iter);
1234 BaseMap.insert(std::make_pair(RootInst, BaseInst));
1236 LastRootIt = RootIt;
1237 Visited.insert(BaseInst);
1238 Visited.insert(RootInst);
1239 BaseIt = nextInstr(0, Uses, Visited);
1240 RootIt = nextInstr(Iter, Uses, Visited);
1242 assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1243 "Mismatched set sizes!");
1246 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1252 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1253 BasicBlock *Header = L->getHeader();
1254 // Remove instructions associated with non-base iterations.
1255 for (BasicBlock::reverse_iterator J = Header->rbegin();
1256 J != Header->rend();) {
1257 unsigned I = Uses[&*J].find_first();
1258 if (I > 0 && I < IL_All) {
1259 Instruction *D = &*J;
1260 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1261 D->eraseFromParent();
1267 bool Negative = IVToIncMap[IV] < 0;
1268 const DataLayout &DL = Header->getModule()->getDataLayout();
1270 // We need to create a new induction variable for each different BaseInst.
1271 for (auto &DRS : RootSets) {
1272 // Insert the new induction variable.
1273 const SCEVAddRecExpr *RealIVSCEV =
1274 cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1275 const SCEV *Start = RealIVSCEV->getStart();
1276 const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>(SE->getAddRecExpr(
1277 Start, SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1), L,
1278 SCEV::FlagAnyWrap));
1279 { // Limit the lifetime of SCEVExpander.
1280 SCEVExpander Expander(*SE, DL, "reroll");
1281 Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1283 for (auto &KV : Uses) {
1284 if (KV.second.find_first() == 0)
1285 KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV);
1288 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1289 // FIXME: Why do we need this check?
1290 if (Uses[BI].find_first() == IL_All) {
1291 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1293 // Iteration count SCEV minus 1
1294 const SCEV *ICMinus1SCEV = SE->getMinusSCEV(
1295 ICSCEV, SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1));
1297 Value *ICMinus1; // Iteration count minus 1
1298 if (isa<SCEVConstant>(ICMinus1SCEV)) {
1299 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1301 BasicBlock *Preheader = L->getLoopPreheader();
1303 Preheader = InsertPreheaderForLoop(L, Parent);
1305 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1306 Preheader->getTerminator());
1310 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
1311 BI->setCondition(Cond);
1313 if (BI->getSuccessor(1) != Header)
1314 BI->swapSuccessors();
1320 SimplifyInstructionsInBlock(Header, TLI);
1321 DeleteDeadPHIs(Header, TLI);
1324 // Validate the selected reductions. All iterations must have an isomorphic
1325 // part of the reduction chain and, for non-associative reductions, the chain
1326 // entries must appear in order.
1327 bool LoopReroll::ReductionTracker::validateSelected() {
1328 // For a non-associative reduction, the chain entries must appear in order.
1329 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1332 int PrevIter = 0, BaseCount = 0, Count = 0;
1333 for (Instruction *J : PossibleReds[i]) {
1334 // Note that all instructions in the chain must have been found because
1335 // all instructions in the function must have been assigned to some
1337 int Iter = PossibleRedIter[J];
1338 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1339 !PossibleReds[i].getReducedValue()->isAssociative()) {
1340 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
1345 if (Iter != PrevIter) {
1346 if (Count != BaseCount) {
1347 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1348 " reduction use count " << Count <<
1349 " is not equal to the base use count " <<
1368 // For all selected reductions, remove all parts except those in the first
1369 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1370 // of the first-iteration reduced value (in other words, reroll the selected
1372 void LoopReroll::ReductionTracker::replaceSelected() {
1373 // Fixup reductions to refer to the last instruction associated with the
1374 // first iteration (not the last).
1375 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1379 for (int e = PossibleReds[i].size(); j != e; ++j)
1380 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1385 // Replace users with the new end-of-chain value.
1386 SmallInstructionVector Users;
1387 for (User *U : PossibleReds[i].getReducedValue()->users()) {
1388 Users.push_back(cast<Instruction>(U));
1391 for (SmallInstructionVector::iterator J = Users.begin(),
1392 JE = Users.end(); J != JE; ++J)
1393 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1394 PossibleReds[i][j]);
1398 // Reroll the provided loop with respect to the provided induction variable.
1399 // Generally, we're looking for a loop like this:
1401 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1403 // %iv.1 = add %iv, 1 <-- a root increment
1405 // %iv.2 = add %iv, 2 <-- a root increment
1407 // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1410 // %iv.next = add %iv, scale
1411 // %cmp = icmp(%iv, ...)
1412 // br %cmp, header, exit
1414 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1415 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1416 // be intermixed with eachother. The restriction imposed by this algorithm is
1417 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1418 // etc. be the same.
1420 // First, we collect the use set of %iv, excluding the other increment roots.
1421 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1422 // times, having collected the use set of f(%iv.(i+1)), during which we:
1423 // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1424 // the next unmatched instruction in f(%iv.(i+1)).
1425 // - Ensure that both matched instructions don't have any external users
1426 // (with the exception of last-in-chain reduction instructions).
1427 // - Track the (aliasing) write set, and other side effects, of all
1428 // instructions that belong to future iterations that come before the matched
1429 // instructions. If the matched instructions read from that write set, then
1430 // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1431 // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1432 // if any of these future instructions had side effects (could not be
1433 // speculatively executed), and so do the matched instructions, when we
1434 // cannot reorder those side-effect-producing instructions, and rerolling
1437 // Finally, we make sure that all loop instructions are either loop increment
1438 // roots, belong to simple latch code, parts of validated reductions, part of
1439 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1440 // have been validated), then we reroll the loop.
1441 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1442 const SCEV *IterCount,
1443 ReductionTracker &Reductions) {
1444 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, IVToIncMap);
1446 if (!DAGRoots.findRoots())
1448 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
1451 if (!DAGRoots.validate(Reductions))
1453 if (!Reductions.validateSelected())
1455 // At this point, we've validated the rerolling, and we're committed to
1458 Reductions.replaceSelected();
1459 DAGRoots.replace(IterCount);
1465 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1466 if (skipOptnoneFunction(L))
1469 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1470 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1471 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1472 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1473 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1475 BasicBlock *Header = L->getHeader();
1476 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1477 "] Loop %" << Header->getName() << " (" <<
1478 L->getNumBlocks() << " block(s))\n");
1480 bool Changed = false;
1482 // For now, we'll handle only single BB loops.
1483 if (L->getNumBlocks() > 1)
1486 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1489 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1490 const SCEV *IterCount =
1491 SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1492 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1494 // First, we need to find the induction variable with respect to which we can
1495 // reroll (there may be several possible options).
1496 SmallInstructionVector PossibleIVs;
1498 collectPossibleIVs(L, PossibleIVs);
1500 if (PossibleIVs.empty()) {
1501 DEBUG(dbgs() << "LRR: No possible IVs found\n");
1505 ReductionTracker Reductions;
1506 collectPossibleReductions(L, Reductions);
1508 // For each possible IV, collect the associated possible set of 'root' nodes
1509 // (i+1, i+2, etc.).
1510 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1511 IE = PossibleIVs.end(); I != IE; ++I)
1512 if (reroll(*I, L, Header, IterCount, Reductions)) {