[LoopReroll] Alter the data structures used during reroll validation.
[oota-llvm.git] / lib / Transforms / Scalar / LoopRerollPass.cpp
1 //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements a simple loop reroller.
11 //
12 //===----------------------------------------------------------------------===//
13
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/ValueTracking.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Analysis/TargetLibraryInfo.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/LoopUtils.h"
37
38 using namespace llvm;
39
40 #define DEBUG_TYPE "loop-reroll"
41
42 STATISTIC(NumRerolledLoops, "Number of rerolled loops");
43
44 static cl::opt<unsigned>
45 MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
46   cl::desc("The maximum increment for loop rerolling"));
47
48 // This loop re-rolling transformation aims to transform loops like this:
49 //
50 // int foo(int a);
51 // void bar(int *x) {
52 //   for (int i = 0; i < 500; i += 3) {
53 //     foo(i);
54 //     foo(i+1);
55 //     foo(i+2);
56 //   }
57 // }
58 //
59 // into a loop like this:
60 //
61 // void bar(int *x) {
62 //   for (int i = 0; i < 500; ++i)
63 //     foo(i);
64 // }
65 //
66 // It does this by looking for loops that, besides the latch code, are composed
67 // of isomorphic DAGs of instructions, with each DAG rooted at some increment
68 // to the induction variable, and where each DAG is isomorphic to the DAG
69 // rooted at the induction variable (excepting the sub-DAGs which root the
70 // other induction-variable increments). In other words, we're looking for loop
71 // bodies of the form:
72 //
73 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
74 // f(%iv)
75 // %iv.1 = add %iv, 1                <-- a root increment
76 // f(%iv.1)
77 // %iv.2 = add %iv, 2                <-- a root increment
78 // f(%iv.2)
79 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
80 // f(%iv.scale_m_1)
81 // ...
82 // %iv.next = add %iv, scale
83 // %cmp = icmp(%iv, ...)
84 // br %cmp, header, exit
85 //
86 // where each f(i) is a set of instructions that, collectively, are a function
87 // only of i (and other loop-invariant values).
88 //
89 // As a special case, we can also reroll loops like this:
90 //
91 // int foo(int);
92 // void bar(int *x) {
93 //   for (int i = 0; i < 500; ++i) {
94 //     x[3*i] = foo(0);
95 //     x[3*i+1] = foo(0);
96 //     x[3*i+2] = foo(0);
97 //   }
98 // }
99 //
100 // into this:
101 //
102 // void bar(int *x) {
103 //   for (int i = 0; i < 1500; ++i)
104 //     x[i] = foo(0);
105 // }
106 //
107 // in which case, we're looking for inputs like this:
108 //
109 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
110 // %scaled.iv = mul %iv, scale
111 // f(%scaled.iv)
112 // %scaled.iv.1 = add %scaled.iv, 1
113 // f(%scaled.iv.1)
114 // %scaled.iv.2 = add %scaled.iv, 2
115 // f(%scaled.iv.2)
116 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
117 // f(%scaled.iv.scale_m_1)
118 // ...
119 // %iv.next = add %iv, 1
120 // %cmp = icmp(%iv, ...)
121 // br %cmp, header, exit
122
123 namespace {
124   enum IterationLimits {
125     /// The maximum number of iterations that we'll try and reroll. This
126     /// has to be less than 25 in order to fit into a SmallBitVector.
127     IL_MaxRerollIterations = 16,
128     /// The bitvector index used by loop induction variables and other
129     /// instructions that belong to no one particular iteration.
130     IL_LoopIncIdx,
131     IL_End
132   };
133
134   class LoopReroll : public LoopPass {
135   public:
136     static char ID; // Pass ID, replacement for typeid
137     LoopReroll() : LoopPass(ID) {
138       initializeLoopRerollPass(*PassRegistry::getPassRegistry());
139     }
140
141     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
142
143     void getAnalysisUsage(AnalysisUsage &AU) const override {
144       AU.addRequired<AliasAnalysis>();
145       AU.addRequired<LoopInfoWrapperPass>();
146       AU.addPreserved<LoopInfoWrapperPass>();
147       AU.addRequired<DominatorTreeWrapperPass>();
148       AU.addPreserved<DominatorTreeWrapperPass>();
149       AU.addRequired<ScalarEvolution>();
150       AU.addRequired<TargetLibraryInfoWrapperPass>();
151     }
152
153   protected:
154     AliasAnalysis *AA;
155     LoopInfo *LI;
156     ScalarEvolution *SE;
157     const DataLayout *DL;
158     TargetLibraryInfo *TLI;
159     DominatorTree *DT;
160
161     typedef SmallVector<Instruction *, 16> SmallInstructionVector;
162     typedef SmallSet<Instruction *, 16>   SmallInstructionSet;
163
164     // A chain of isomorphic instructions, indentified by a single-use PHI,
165     // representing a reduction. Only the last value may be used outside the
166     // loop.
167     struct SimpleLoopReduction {
168       SimpleLoopReduction(Instruction *P, Loop *L)
169         : Valid(false), Instructions(1, P) {
170         assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
171         add(L);
172       }
173
174       bool valid() const {
175         return Valid;
176       }
177
178       Instruction *getPHI() const {
179         assert(Valid && "Using invalid reduction");
180         return Instructions.front();
181       }
182
183       Instruction *getReducedValue() const {
184         assert(Valid && "Using invalid reduction");
185         return Instructions.back();
186       }
187
188       Instruction *get(size_t i) const {
189         assert(Valid && "Using invalid reduction");
190         return Instructions[i+1];
191       }
192
193       Instruction *operator [] (size_t i) const { return get(i); }
194
195       // The size, ignoring the initial PHI.
196       size_t size() const {
197         assert(Valid && "Using invalid reduction");
198         return Instructions.size()-1;
199       }
200
201       typedef SmallInstructionVector::iterator iterator;
202       typedef SmallInstructionVector::const_iterator const_iterator;
203
204       iterator begin() {
205         assert(Valid && "Using invalid reduction");
206         return std::next(Instructions.begin());
207       }
208
209       const_iterator begin() const {
210         assert(Valid && "Using invalid reduction");
211         return std::next(Instructions.begin());
212       }
213
214       iterator end() { return Instructions.end(); }
215       const_iterator end() const { return Instructions.end(); }
216
217     protected:
218       bool Valid;
219       SmallInstructionVector Instructions;
220
221       void add(Loop *L);
222     };
223
224     // The set of all reductions, and state tracking of possible reductions
225     // during loop instruction processing.
226     struct ReductionTracker {
227       typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
228
229       // Add a new possible reduction.
230       void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
231
232       // Setup to track possible reductions corresponding to the provided
233       // rerolling scale. Only reductions with a number of non-PHI instructions
234       // that is divisible by the scale are considered. Three instructions sets
235       // are filled in:
236       //   - A set of all possible instructions in eligible reductions.
237       //   - A set of all PHIs in eligible reductions
238       //   - A set of all reduced values (last instructions) in eligible
239       //     reductions.
240       void restrictToScale(uint64_t Scale,
241                            SmallInstructionSet &PossibleRedSet,
242                            SmallInstructionSet &PossibleRedPHISet,
243                            SmallInstructionSet &PossibleRedLastSet) {
244         PossibleRedIdx.clear();
245         PossibleRedIter.clear();
246         Reds.clear();
247
248         for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
249           if (PossibleReds[i].size() % Scale == 0) {
250             PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
251             PossibleRedPHISet.insert(PossibleReds[i].getPHI());
252
253             PossibleRedSet.insert(PossibleReds[i].getPHI());
254             PossibleRedIdx[PossibleReds[i].getPHI()] = i;
255             for (Instruction *J : PossibleReds[i]) {
256               PossibleRedSet.insert(J);
257               PossibleRedIdx[J] = i;
258             }
259           }
260       }
261
262       // The functions below are used while processing the loop instructions.
263
264       // Are the two instructions both from reductions, and furthermore, from
265       // the same reduction?
266       bool isPairInSame(Instruction *J1, Instruction *J2) {
267         DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
268         if (J1I != PossibleRedIdx.end()) {
269           DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
270           if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
271             return true;
272         }
273
274         return false;
275       }
276
277       // The two provided instructions, the first from the base iteration, and
278       // the second from iteration i, form a matched pair. If these are part of
279       // a reduction, record that fact.
280       void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
281         if (PossibleRedIdx.count(J1)) {
282           assert(PossibleRedIdx.count(J2) &&
283                  "Recording reduction vs. non-reduction instruction?");
284
285           PossibleRedIter[J1] = 0;
286           PossibleRedIter[J2] = i;
287
288           int Idx = PossibleRedIdx[J1];
289           assert(Idx == PossibleRedIdx[J2] &&
290                  "Recording pair from different reductions?");
291           Reds.insert(Idx);
292         }
293       }
294
295       // The functions below can be called after we've finished processing all
296       // instructions in the loop, and we know which reductions were selected.
297
298       // Is the provided instruction the PHI of a reduction selected for
299       // rerolling?
300       bool isSelectedPHI(Instruction *J) {
301         if (!isa<PHINode>(J))
302           return false;
303
304         for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
305              RI != RIE; ++RI) {
306           int i = *RI;
307           if (cast<Instruction>(J) == PossibleReds[i].getPHI())
308             return true;
309         }
310
311         return false;
312       }
313
314       bool validateSelected();
315       void replaceSelected();
316
317     protected:
318       // The vector of all possible reductions (for any scale).
319       SmallReductionVector PossibleReds;
320
321       DenseMap<Instruction *, int> PossibleRedIdx;
322       DenseMap<Instruction *, int> PossibleRedIter;
323       DenseSet<int> Reds;
324     };
325
326     // The set of all DAG roots, and state tracking of all roots
327     // for a particular induction variable.
328     struct DAGRootTracker {
329       DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
330                      ScalarEvolution *SE, AliasAnalysis *AA,
331                      TargetLibraryInfo *TLI, const DataLayout *DL)
332         : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI),
333           DL(DL), IV(IV) {
334       }
335
336       /// Stage 1: Find all the DAG roots for the induction variable.
337       bool findRoots();
338       /// Stage 2: Validate if the found roots are valid.
339       bool validate(ReductionTracker &Reductions);
340       /// Stage 3: Assuming validate() returned true, perform the
341       /// replacement.
342       /// @param IterCount The maximum iteration count of L.
343       void replace(const SCEV *IterCount);
344
345     protected:
346       typedef MapVector<Instruction*, SmallBitVector> UsesTy;
347
348       bool findScaleFromMul();
349       bool collectAllRoots();
350
351       bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
352       void collectInLoopUserSet(const SmallInstructionVector &Roots,
353                                 const SmallInstructionSet &Exclude,
354                                 const SmallInstructionSet &Final,
355                                 DenseSet<Instruction *> &Users);
356       void collectInLoopUserSet(Instruction *Root,
357                                 const SmallInstructionSet &Exclude,
358                                 const SmallInstructionSet &Final,
359                                 DenseSet<Instruction *> &Users);
360
361       UsesTy::iterator nextInstr(int Val, UsesTy &In, UsesTy::iterator I);
362
363       LoopReroll *Parent;
364
365       // Members of Parent, replicated here for brevity.
366       Loop *L;
367       ScalarEvolution *SE;
368       AliasAnalysis *AA;
369       TargetLibraryInfo *TLI;
370       const DataLayout *DL;
371
372       // The loop induction variable.
373       Instruction *IV;
374       // Loop step amount.
375       uint64_t Inc;
376       // Loop reroll count; if Inc == 1, this records the scaling applied
377       // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
378       // If Inc is not 1, Scale = Inc.
379       uint64_t Scale;
380       // If Scale != Inc, then RealIV is IV after its multiplication.
381       Instruction *RealIV;
382       // The roots themselves.
383       SmallInstructionVector Roots;
384       // All increment instructions for IV.
385       SmallInstructionVector LoopIncs;
386       // Map of all instructions in the loop (in order) to the iterations
387       // they are used in (or specially, IL_LoopIncIdx for instructions
388       // used in the loop increment mechanism).
389       UsesTy Uses;
390     };
391
392     void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
393     void collectPossibleReductions(Loop *L,
394            ReductionTracker &Reductions);
395     bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
396                 ReductionTracker &Reductions);
397   };
398 }
399
400 char LoopReroll::ID = 0;
401 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
402 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
403 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
404 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
405 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
406 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
407 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
408
409 Pass *llvm::createLoopRerollPass() {
410   return new LoopReroll;
411 }
412
413 // Returns true if the provided instruction is used outside the given loop.
414 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
415 // non-loop blocks to be outside the loop.
416 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
417   for (User *U : I->users()) {
418     if (!L->contains(cast<Instruction>(U)))
419       return true;
420   }
421   return false;
422 }
423
424 // Collect the list of loop induction variables with respect to which it might
425 // be possible to reroll the loop.
426 void LoopReroll::collectPossibleIVs(Loop *L,
427                                     SmallInstructionVector &PossibleIVs) {
428   BasicBlock *Header = L->getHeader();
429   for (BasicBlock::iterator I = Header->begin(),
430        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
431     if (!isa<PHINode>(I))
432       continue;
433     if (!I->getType()->isIntegerTy())
434       continue;
435
436     if (const SCEVAddRecExpr *PHISCEV =
437         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
438       if (PHISCEV->getLoop() != L)
439         continue;
440       if (!PHISCEV->isAffine())
441         continue;
442       if (const SCEVConstant *IncSCEV =
443           dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
444         if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
445           continue;
446         if (IncSCEV->getValue()->uge(MaxInc))
447           continue;
448
449         DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
450               *PHISCEV << "\n");
451         PossibleIVs.push_back(I);
452       }
453     }
454   }
455 }
456
457 // Add the remainder of the reduction-variable chain to the instruction vector
458 // (the initial PHINode has already been added). If successful, the object is
459 // marked as valid.
460 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
461   assert(!Valid && "Cannot add to an already-valid chain");
462
463   // The reduction variable must be a chain of single-use instructions
464   // (including the PHI), except for the last value (which is used by the PHI
465   // and also outside the loop).
466   Instruction *C = Instructions.front();
467
468   do {
469     C = cast<Instruction>(*C->user_begin());
470     if (C->hasOneUse()) {
471       if (!C->isBinaryOp())
472         return;
473
474       if (!(isa<PHINode>(Instructions.back()) ||
475             C->isSameOperationAs(Instructions.back())))
476         return;
477
478       Instructions.push_back(C);
479     }
480   } while (C->hasOneUse());
481
482   if (Instructions.size() < 2 ||
483       !C->isSameOperationAs(Instructions.back()) ||
484       C->use_empty())
485     return;
486
487   // C is now the (potential) last instruction in the reduction chain.
488   for (User *U : C->users()) {
489     // The only in-loop user can be the initial PHI.
490     if (L->contains(cast<Instruction>(U)))
491       if (cast<Instruction>(U) != Instructions.front())
492         return;
493   }
494
495   Instructions.push_back(C);
496   Valid = true;
497 }
498
499 // Collect the vector of possible reduction variables.
500 void LoopReroll::collectPossibleReductions(Loop *L,
501   ReductionTracker &Reductions) {
502   BasicBlock *Header = L->getHeader();
503   for (BasicBlock::iterator I = Header->begin(),
504        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
505     if (!isa<PHINode>(I))
506       continue;
507     if (!I->getType()->isSingleValueType())
508       continue;
509
510     SimpleLoopReduction SLR(I, L);
511     if (!SLR.valid())
512       continue;
513
514     DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
515           SLR.size() << " chained instructions)\n");
516     Reductions.addSLR(SLR);
517   }
518 }
519
520 // Collect the set of all users of the provided root instruction. This set of
521 // users contains not only the direct users of the root instruction, but also
522 // all users of those users, and so on. There are two exceptions:
523 //
524 //   1. Instructions in the set of excluded instructions are never added to the
525 //   use set (even if they are users). This is used, for example, to exclude
526 //   including root increments in the use set of the primary IV.
527 //
528 //   2. Instructions in the set of final instructions are added to the use set
529 //   if they are users, but their users are not added. This is used, for
530 //   example, to prevent a reduction update from forcing all later reduction
531 //   updates into the use set.
532 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
533   Instruction *Root, const SmallInstructionSet &Exclude,
534   const SmallInstructionSet &Final,
535   DenseSet<Instruction *> &Users) {
536   SmallInstructionVector Queue(1, Root);
537   while (!Queue.empty()) {
538     Instruction *I = Queue.pop_back_val();
539     if (!Users.insert(I).second)
540       continue;
541
542     if (!Final.count(I))
543       for (Use &U : I->uses()) {
544         Instruction *User = cast<Instruction>(U.getUser());
545         if (PHINode *PN = dyn_cast<PHINode>(User)) {
546           // Ignore "wrap-around" uses to PHIs of this loop's header.
547           if (PN->getIncomingBlock(U) == L->getHeader())
548             continue;
549         }
550
551         if (L->contains(User) && !Exclude.count(User)) {
552           Queue.push_back(User);
553         }
554       }
555
556     // We also want to collect single-user "feeder" values.
557     for (User::op_iterator OI = I->op_begin(),
558          OIE = I->op_end(); OI != OIE; ++OI) {
559       if (Instruction *Op = dyn_cast<Instruction>(*OI))
560         if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
561             !Final.count(Op))
562           Queue.push_back(Op);
563     }
564   }
565 }
566
567 // Collect all of the users of all of the provided root instructions (combined
568 // into a single set).
569 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
570   const SmallInstructionVector &Roots,
571   const SmallInstructionSet &Exclude,
572   const SmallInstructionSet &Final,
573   DenseSet<Instruction *> &Users) {
574   for (SmallInstructionVector::const_iterator I = Roots.begin(),
575        IE = Roots.end(); I != IE; ++I)
576     collectInLoopUserSet(*I, Exclude, Final, Users);
577 }
578
579 static bool isSimpleLoadStore(Instruction *I) {
580   if (LoadInst *LI = dyn_cast<LoadInst>(I))
581     return LI->isSimple();
582   if (StoreInst *SI = dyn_cast<StoreInst>(I))
583     return SI->isSimple();
584   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
585     return !MI->isVolatile();
586   return false;
587 }
588
589 bool LoopReroll::DAGRootTracker::findRoots() {
590
591   const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
592   Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
593     getValue()->getZExtValue();
594
595   // The effective induction variable, IV, is normally also the real induction
596   // variable. When we're dealing with a loop like:
597   //   for (int i = 0; i < 500; ++i)
598   //     x[3*i] = ...;
599   //     x[3*i+1] = ...;
600   //     x[3*i+2] = ...;
601   // then the real IV is still i, but the effective IV is (3*i).
602   Scale = Inc;
603   RealIV = IV;
604   if (Inc == 1 && !findScaleFromMul())
605     return false;
606
607   // The set of increment instructions for each increment value.
608   if (!collectAllRoots())
609     return false;
610
611   if (Roots.size() > IL_MaxRerollIterations) {
612     DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
613           << "#Found=" << Roots.size() << ", #Max=" << IL_MaxRerollIterations
614           << "\n");
615     return false;
616   }
617
618   return true;
619 }
620
621 // Recognize loops that are setup like this:
622 //
623 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
624 // %scaled.iv = mul %iv, scale
625 // f(%scaled.iv)
626 // %scaled.iv.1 = add %scaled.iv, 1
627 // f(%scaled.iv.1)
628 // %scaled.iv.2 = add %scaled.iv, 2
629 // f(%scaled.iv.2)
630 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
631 // f(%scaled.iv.scale_m_1)
632 // ...
633 // %iv.next = add %iv, 1
634 // %cmp = icmp(%iv, ...)
635 // br %cmp, header, exit
636 //
637 // and, if found, set IV = %scaled.iv, and add %iv.next to LoopIncs.
638 bool LoopReroll::DAGRootTracker::findScaleFromMul() {
639
640   // This is a special case: here we're looking for all uses (except for
641   // the increment) to be multiplied by a common factor. The increment must
642   // be by one. This is to capture loops like:
643   //   for (int i = 0; i < 500; ++i) {
644   //     foo(3*i); foo(3*i+1); foo(3*i+2);
645   //   }
646   if (RealIV->getNumUses() != 2)
647     return false;
648   const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
649   Instruction *User1 = cast<Instruction>(*RealIV->user_begin()),
650               *User2 = cast<Instruction>(*std::next(RealIV->user_begin()));
651   if (!SE->isSCEVable(User1->getType()) || !SE->isSCEVable(User2->getType()))
652     return false;
653   const SCEVAddRecExpr *User1SCEV =
654                          dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User1)),
655                        *User2SCEV =
656                          dyn_cast<SCEVAddRecExpr>(SE->getSCEV(User2));
657   if (!User1SCEV || !User1SCEV->isAffine() ||
658       !User2SCEV || !User2SCEV->isAffine())
659     return false;
660
661   // We assume below that User1 is the scale multiply and User2 is the
662   // increment. If this can't be true, then swap them.
663   if (User1SCEV == RealIVSCEV->getPostIncExpr(*SE)) {
664     std::swap(User1, User2);
665     std::swap(User1SCEV, User2SCEV);
666   }
667
668   if (User2SCEV != RealIVSCEV->getPostIncExpr(*SE))
669     return false;
670   assert(User2SCEV->getStepRecurrence(*SE)->isOne() &&
671          "Invalid non-unit step for multiplicative scaling");
672   LoopIncs.push_back(User2);
673
674   if (const SCEVConstant *MulScale =
675       dyn_cast<SCEVConstant>(User1SCEV->getStepRecurrence(*SE))) {
676     // Make sure that both the start and step have the same multiplier.
677     if (RealIVSCEV->getStart()->getType() != MulScale->getType())
678       return false;
679     if (SE->getMulExpr(RealIVSCEV->getStart(), MulScale) !=
680         User1SCEV->getStart())
681       return false;
682
683     ConstantInt *MulScaleCI = MulScale->getValue();
684     if (!MulScaleCI->uge(2) || MulScaleCI->uge(MaxInc))
685       return false;
686     Scale = MulScaleCI->getZExtValue();
687     IV = User1;
688   } else
689     return false;
690
691   DEBUG(dbgs() << "LRR: Found possible scaling " << *User1 << "\n");
692
693   assert(Scale <= MaxInc && "Scale is too large");
694   assert(Scale > 1 && "Scale must be at least 2");
695
696   return true;
697 }
698
699 // Collect all root increments with respect to the provided induction variable
700 // (normally the PHI, but sometimes a multiply). A root increment is an
701 // instruction, normally an add, with a positive constant less than Scale. In a
702 // rerollable loop, each of these increments is the root of an instruction
703 // graph isomorphic to the others. Also, we collect the final induction
704 // increment (the increment equal to the Scale), and its users in LoopIncs.
705 bool LoopReroll::DAGRootTracker::collectAllRoots() {
706   Roots.resize(Scale-1);
707   
708   for (User *U : IV->users()) {
709     Instruction *UI = cast<Instruction>(U);
710     if (!SE->isSCEVable(UI->getType()))
711       continue;
712     if (UI->getType() != IV->getType())
713       continue;
714     if (!L->contains(UI))
715       continue;
716     if (hasUsesOutsideLoop(UI, L))
717       continue;
718
719     if (const SCEVConstant *Diff = dyn_cast<SCEVConstant>(SE->getMinusSCEV(
720           SE->getSCEV(UI), SE->getSCEV(IV)))) {
721       uint64_t Idx = Diff->getValue()->getValue().getZExtValue();
722       if (Idx > 0 && Idx < Scale) {
723         if (Roots[Idx-1])
724           // No duplicates allowed.
725           return false;
726         Roots[Idx-1] = UI;
727       } else if (Idx == Scale && Inc > 1) {
728         LoopIncs.push_back(UI);
729       }
730     }
731   }
732
733   for (unsigned i = 0; i < Scale-1; ++i) {
734     if (!Roots[i])
735       return false;
736   }
737
738   return true;
739 }
740
741 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
742   // Populate the MapVector with all instructions in the block, in order first,
743   // so we can iterate over the contents later in perfect order.
744   for (auto &I : *L->getHeader()) {
745     Uses[&I].resize(IL_End);
746   }
747
748   SmallInstructionSet Exclude;
749   Exclude.insert(Roots.begin(), Roots.end());
750   Exclude.insert(LoopIncs.begin(), LoopIncs.end());
751
752   DenseSet<Instruction*> VBase;
753   collectInLoopUserSet(IV, Exclude, PossibleRedSet, VBase);
754   for (auto *I : VBase) {
755     Uses[I].set(0);
756   }
757
758   unsigned Idx = 1;
759   for (auto *Root : Roots) {
760     DenseSet<Instruction*> V;
761     collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
762
763     // While we're here, check the use sets are the same size.
764     if (V.size() != VBase.size()) {
765       DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
766       return false;
767     }
768
769     for (auto *I : V) {
770       Uses[I].set(Idx);
771     }
772     ++Idx;
773   }
774
775   // Make sure the loop increments are also accounted for.
776   Exclude.clear();
777   Exclude.insert(Roots.begin(), Roots.end());
778
779   DenseSet<Instruction*> V;
780   collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
781   for (auto *I : V) {
782     Uses[I].set(IL_LoopIncIdx);
783   }
784   if (IV != RealIV)
785     Uses[RealIV].set(IL_LoopIncIdx);
786
787   return true;
788
789 }
790
791 LoopReroll::DAGRootTracker::UsesTy::iterator
792 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
793                                       UsesTy::iterator I) {
794   while (I != In.end() && I->second.test(Val) == 0)
795     ++I;
796   return I;
797 }
798
799 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
800   // We now need to check for equivalence of the use graph of each root with
801   // that of the primary induction variable (excluding the roots). Our goal
802   // here is not to solve the full graph isomorphism problem, but rather to
803   // catch common cases without a lot of work. As a result, we will assume
804   // that the relative order of the instructions in each unrolled iteration
805   // is the same (although we will not make an assumption about how the
806   // different iterations are intermixed). Note that while the order must be
807   // the same, the instructions may not be in the same basic block.
808
809   // An array of just the possible reductions for this scale factor. When we
810   // collect the set of all users of some root instructions, these reduction
811   // instructions are treated as 'final' (their uses are not considered).
812   // This is important because we don't want the root use set to search down
813   // the reduction chain.
814   SmallInstructionSet PossibleRedSet;
815   SmallInstructionSet PossibleRedLastSet;
816   SmallInstructionSet PossibleRedPHISet;
817   Reductions.restrictToScale(Scale, PossibleRedSet,
818                              PossibleRedPHISet, PossibleRedLastSet);
819
820   // Populate "Uses" with where each instruction is used.
821   if (!collectUsedInstructions(PossibleRedSet))
822     return false;
823
824   // Make sure we mark the reduction PHIs as used in all iterations.
825   for (auto *I : PossibleRedPHISet) {
826     Uses[I].set(IL_LoopIncIdx);
827   }
828
829   // Make sure all instructions in the loop are in one and only one
830   // set.
831   for (auto &KV : Uses) {
832     if (KV.second.count() != 1) {
833       DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
834             << *KV.first << " (#uses=" << KV.second.count() << ")\n");
835       return false;
836     }
837   }
838
839   DEBUG(
840     for (auto &KV : Uses) {
841       dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
842     }
843     );
844
845   for (unsigned Iter = 1; Iter < Scale; ++Iter) {
846     // In addition to regular aliasing information, we need to look for
847     // instructions from later (future) iterations that have side effects
848     // preventing us from reordering them past other instructions with side
849     // effects.
850     bool FutureSideEffects = false;
851     AliasSetTracker AST(*AA);
852     // The map between instructions in f(%iv.(i+1)) and f(%iv).
853     DenseMap<Value *, Value *> BaseMap;
854
855     // Compare iteration Iter to the base.
856     auto BaseIt = nextInstr(0, Uses, Uses.begin());
857     auto RootIt = nextInstr(Iter, Uses, Uses.begin());
858     auto LastRootIt = Uses.begin();
859
860     while (BaseIt != Uses.end() && RootIt != Uses.end()) {
861       Instruction *BaseInst = BaseIt->first;
862       Instruction *RootInst = RootIt->first;
863
864       // Skip over the IV or root instructions; only match their users.
865       bool Continue = false;
866       if (BaseInst == RealIV || BaseInst == IV) {
867         BaseIt = nextInstr(0, Uses, ++BaseIt);
868         Continue = true;
869       }
870       if (std::find(Roots.begin(), Roots.end(), RootInst) != Roots.end()) {
871         LastRootIt = RootIt;
872         RootIt = nextInstr(Iter, Uses, ++RootIt);
873         Continue = true;
874       }
875       if (Continue) continue;
876
877       // All instructions between the last root and this root
878       // belong to some other iteration. If they belong to a 
879       // future iteration, then they're dangerous to alias with.
880       for (; LastRootIt != RootIt; ++LastRootIt) {
881         Instruction *I = LastRootIt->first;
882         if (LastRootIt->second.find_first() < (int)Iter)
883           continue;
884         if (I->mayWriteToMemory())
885           AST.add(I);
886         // Note: This is specifically guarded by a check on isa<PHINode>,
887         // which while a valid (somewhat arbitrary) micro-optimization, is
888         // needed because otherwise isSafeToSpeculativelyExecute returns
889         // false on PHI nodes.
890         if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
891             !isSafeToSpeculativelyExecute(I, DL))
892           // Intervening instructions cause side effects.
893           FutureSideEffects = true;
894       }
895
896       if (!BaseInst->isSameOperationAs(RootInst)) {
897         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
898               " vs. " << *RootInst << "\n");
899         return false;
900       }
901
902       // Make sure that this instruction, which is in the use set of this
903       // root instruction, does not also belong to the base set or the set of
904       // some other root instruction.
905       if (RootIt->second.count() > 1) {
906         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
907                         " vs. " << *RootInst << " (prev. case overlap)\n");
908         return false;
909       }
910
911       // Make sure that we don't alias with any instruction in the alias set
912       // tracker. If we do, then we depend on a future iteration, and we
913       // can't reroll.
914       if (RootInst->mayReadFromMemory())
915         for (auto &K : AST) {
916           if (K.aliasesUnknownInst(RootInst, *AA)) {
917             DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
918                             " vs. " << *RootInst << " (depends on future store)\n");
919             return false;
920           }
921         }
922
923       // If we've past an instruction from a future iteration that may have
924       // side effects, and this instruction might also, then we can't reorder
925       // them, and this matching fails. As an exception, we allow the alias
926       // set tracker to handle regular (simple) load/store dependencies.
927       if (FutureSideEffects &&
928             ((!isSimpleLoadStore(BaseInst) &&
929               !isSafeToSpeculativelyExecute(BaseInst, DL)) ||
930              (!isSimpleLoadStore(RootInst) &&
931               !isSafeToSpeculativelyExecute(RootInst, DL)))) {
932         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
933                         " vs. " << *RootInst <<
934                         " (side effects prevent reordering)\n");
935         return false;
936       }
937
938       // For instructions that are part of a reduction, if the operation is
939       // associative, then don't bother matching the operands (because we
940       // already know that the instructions are isomorphic, and the order
941       // within the iteration does not matter). For non-associative reductions,
942       // we do need to match the operands, because we need to reject
943       // out-of-order instructions within an iteration!
944       // For example (assume floating-point addition), we need to reject this:
945       //   x += a[i]; x += b[i];
946       //   x += a[i+1]; x += b[i+1];
947       //   x += b[i+2]; x += a[i+2];
948       bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
949
950       if (!(InReduction && BaseInst->isAssociative())) {
951         bool Swapped = false, SomeOpMatched = false;
952         for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
953           Value *Op2 = RootInst->getOperand(j);
954
955           // If this is part of a reduction (and the operation is not
956           // associatve), then we match all operands, but not those that are
957           // part of the reduction.
958           if (InReduction)
959             if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
960               if (Reductions.isPairInSame(RootInst, Op2I))
961                 continue;
962
963           DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
964           if (BMI != BaseMap.end())
965             Op2 = BMI->second;
966           else if (Roots[Iter-1] == (Instruction*) Op2)
967             Op2 = IV;
968
969           if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
970             // If we've not already decided to swap the matched operands, and
971             // we've not already matched our first operand (note that we could
972             // have skipped matching the first operand because it is part of a
973             // reduction above), and the instruction is commutative, then try
974             // the swapped match.
975             if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
976                 BaseInst->getOperand(!j) == Op2) {
977               Swapped = true;
978             } else {
979               DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
980                     << " vs. " << *RootInst << " (operand " << j << ")\n");
981               return false;
982             }
983           }
984
985           SomeOpMatched = true;
986         }
987       }
988
989       if ((!PossibleRedLastSet.count(BaseInst) &&
990            hasUsesOutsideLoop(BaseInst, L)) ||
991           (!PossibleRedLastSet.count(RootInst) &&
992            hasUsesOutsideLoop(RootInst, L))) {
993         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
994                         " vs. " << *RootInst << " (uses outside loop)\n");
995         return false;
996       }
997
998       Reductions.recordPair(BaseInst, RootInst, Iter);
999       BaseMap.insert(std::make_pair(RootInst, BaseInst));
1000
1001       LastRootIt = RootIt;
1002       BaseIt = nextInstr(0, Uses, ++BaseIt);
1003       RootIt = nextInstr(Iter, Uses, ++RootIt);
1004     }
1005     assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1006             "Mismatched set sizes!");
1007   }
1008
1009   DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1010                   *RealIV << "\n");
1011
1012   return true;
1013 }
1014
1015 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1016   BasicBlock *Header = L->getHeader();
1017   // Remove instructions associated with non-base iterations.
1018   for (BasicBlock::reverse_iterator J = Header->rbegin();
1019        J != Header->rend();) {
1020     unsigned I = Uses[&*J].find_first();
1021     if (I > 0 && I < IL_LoopIncIdx) {
1022       Instruction *D = &*J;
1023       DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1024       D->eraseFromParent();
1025       continue;
1026     }
1027
1028     ++J;
1029   }
1030
1031   // Insert the new induction variable.
1032   const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(RealIV));
1033   const SCEV *Start = RealIVSCEV->getStart();
1034   if (Inc == 1)
1035     Start = SE->getMulExpr(Start,
1036                            SE->getConstant(Start->getType(), Scale));
1037   const SCEVAddRecExpr *H =
1038     cast<SCEVAddRecExpr>(SE->getAddRecExpr(Start,
1039                            SE->getConstant(RealIVSCEV->getType(), 1),
1040                            L, SCEV::FlagAnyWrap));
1041   { // Limit the lifetime of SCEVExpander.
1042     SCEVExpander Expander(*SE, "reroll");
1043     Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1044
1045     for (auto &KV : Uses) {
1046       if (KV.second.find_first() == 0)
1047         KV.first->replaceUsesOfWith(IV, NewIV);
1048     }
1049
1050     if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1051       // FIXME: Why do we need this check?
1052       if (Uses[BI].find_first() == IL_LoopIncIdx) {
1053         const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1054         if (Inc == 1)
1055           ICSCEV =
1056             SE->getMulExpr(ICSCEV, SE->getConstant(ICSCEV->getType(), Scale));
1057         // Iteration count SCEV minus 1
1058         const SCEV *ICMinus1SCEV =
1059           SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
1060
1061         Value *ICMinus1; // Iteration count minus 1
1062         if (isa<SCEVConstant>(ICMinus1SCEV)) {
1063           ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1064         } else {
1065           BasicBlock *Preheader = L->getLoopPreheader();
1066           if (!Preheader)
1067             Preheader = InsertPreheaderForLoop(L, Parent);
1068
1069           ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1070                                             Preheader->getTerminator());
1071         }
1072
1073         Value *Cond =
1074             new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
1075         BI->setCondition(Cond);
1076
1077         if (BI->getSuccessor(1) != Header)
1078           BI->swapSuccessors();
1079       }
1080     }
1081   }
1082
1083   SimplifyInstructionsInBlock(Header, DL, TLI);
1084   DeleteDeadPHIs(Header, TLI);
1085 }
1086
1087 // Validate the selected reductions. All iterations must have an isomorphic
1088 // part of the reduction chain and, for non-associative reductions, the chain
1089 // entries must appear in order.
1090 bool LoopReroll::ReductionTracker::validateSelected() {
1091   // For a non-associative reduction, the chain entries must appear in order.
1092   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1093        RI != RIE; ++RI) {
1094     int i = *RI;
1095     int PrevIter = 0, BaseCount = 0, Count = 0;
1096     for (Instruction *J : PossibleReds[i]) {
1097       // Note that all instructions in the chain must have been found because
1098       // all instructions in the function must have been assigned to some
1099       // iteration.
1100       int Iter = PossibleRedIter[J];
1101       if (Iter != PrevIter && Iter != PrevIter + 1 &&
1102           !PossibleReds[i].getReducedValue()->isAssociative()) {
1103         DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
1104                         J << "\n");
1105         return false;
1106       }
1107
1108       if (Iter != PrevIter) {
1109         if (Count != BaseCount) {
1110           DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1111                 " reduction use count " << Count <<
1112                 " is not equal to the base use count " <<
1113                 BaseCount << "\n");
1114           return false;
1115         }
1116
1117         Count = 0;
1118       }
1119
1120       ++Count;
1121       if (Iter == 0)
1122         ++BaseCount;
1123
1124       PrevIter = Iter;
1125     }
1126   }
1127
1128   return true;
1129 }
1130
1131 // For all selected reductions, remove all parts except those in the first
1132 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1133 // of the first-iteration reduced value (in other words, reroll the selected
1134 // reductions).
1135 void LoopReroll::ReductionTracker::replaceSelected() {
1136   // Fixup reductions to refer to the last instruction associated with the
1137   // first iteration (not the last).
1138   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1139        RI != RIE; ++RI) {
1140     int i = *RI;
1141     int j = 0;
1142     for (int e = PossibleReds[i].size(); j != e; ++j)
1143       if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1144         --j;
1145         break;
1146       }
1147
1148     // Replace users with the new end-of-chain value.
1149     SmallInstructionVector Users;
1150     for (User *U : PossibleReds[i].getReducedValue()->users()) {
1151       Users.push_back(cast<Instruction>(U));
1152     }
1153
1154     for (SmallInstructionVector::iterator J = Users.begin(),
1155          JE = Users.end(); J != JE; ++J)
1156       (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1157                               PossibleReds[i][j]);
1158   }
1159 }
1160
1161 // Reroll the provided loop with respect to the provided induction variable.
1162 // Generally, we're looking for a loop like this:
1163 //
1164 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1165 // f(%iv)
1166 // %iv.1 = add %iv, 1                <-- a root increment
1167 // f(%iv.1)
1168 // %iv.2 = add %iv, 2                <-- a root increment
1169 // f(%iv.2)
1170 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
1171 // f(%iv.scale_m_1)
1172 // ...
1173 // %iv.next = add %iv, scale
1174 // %cmp = icmp(%iv, ...)
1175 // br %cmp, header, exit
1176 //
1177 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1178 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1179 // be intermixed with eachother. The restriction imposed by this algorithm is
1180 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1181 // etc. be the same.
1182 //
1183 // First, we collect the use set of %iv, excluding the other increment roots.
1184 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1185 // times, having collected the use set of f(%iv.(i+1)), during which we:
1186 //   - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1187 //     the next unmatched instruction in f(%iv.(i+1)).
1188 //   - Ensure that both matched instructions don't have any external users
1189 //     (with the exception of last-in-chain reduction instructions).
1190 //   - Track the (aliasing) write set, and other side effects, of all
1191 //     instructions that belong to future iterations that come before the matched
1192 //     instructions. If the matched instructions read from that write set, then
1193 //     f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1194 //     f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1195 //     if any of these future instructions had side effects (could not be
1196 //     speculatively executed), and so do the matched instructions, when we
1197 //     cannot reorder those side-effect-producing instructions, and rerolling
1198 //     fails.
1199 //
1200 // Finally, we make sure that all loop instructions are either loop increment
1201 // roots, belong to simple latch code, parts of validated reductions, part of
1202 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1203 // have been validated), then we reroll the loop.
1204 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1205                         const SCEV *IterCount,
1206                         ReductionTracker &Reductions) {
1207   DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DL);
1208
1209   if (!DAGRoots.findRoots())
1210     return false;
1211   DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
1212                   *IV << "\n");
1213   
1214   if (!DAGRoots.validate(Reductions))
1215     return false;
1216   if (!Reductions.validateSelected())
1217     return false;
1218   // At this point, we've validated the rerolling, and we're committed to
1219   // making changes!
1220
1221   Reductions.replaceSelected();
1222   DAGRoots.replace(IterCount);
1223
1224   ++NumRerolledLoops;
1225   return true;
1226 }
1227
1228 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1229   if (skipOptnoneFunction(L))
1230     return false;
1231
1232   AA = &getAnalysis<AliasAnalysis>();
1233   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1234   SE = &getAnalysis<ScalarEvolution>();
1235   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1236   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1237   DL = DLP ? &DLP->getDataLayout() : nullptr;
1238   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1239
1240   BasicBlock *Header = L->getHeader();
1241   DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1242         "] Loop %" << Header->getName() << " (" <<
1243         L->getNumBlocks() << " block(s))\n");
1244
1245   bool Changed = false;
1246
1247   // For now, we'll handle only single BB loops.
1248   if (L->getNumBlocks() > 1)
1249     return Changed;
1250
1251   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1252     return Changed;
1253
1254   const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1255   const SCEV *IterCount =
1256     SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1257   DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1258
1259   // First, we need to find the induction variable with respect to which we can
1260   // reroll (there may be several possible options).
1261   SmallInstructionVector PossibleIVs;
1262   collectPossibleIVs(L, PossibleIVs);
1263
1264   if (PossibleIVs.empty()) {
1265     DEBUG(dbgs() << "LRR: No possible IVs found\n");
1266     return Changed;
1267   }
1268
1269   ReductionTracker Reductions;
1270   collectPossibleReductions(L, Reductions);
1271
1272   // For each possible IV, collect the associated possible set of 'root' nodes
1273   // (i+1, i+2, etc.).
1274   for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1275        IE = PossibleIVs.end(); I != IE; ++I)
1276     if (reroll(*I, L, Header, IterCount, Reductions)) {
1277       Changed = true;
1278       break;
1279     }
1280
1281   return Changed;
1282 }