[LoopRerolling] Be more forgiving with instruction order.
[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 static cl::opt<unsigned>
49 NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
50                           cl::Hidden,
51                           cl::desc("The maximum number of failures to tolerate"
52                                    " during fuzzy matching. (default: 400)"));
53
54 // This loop re-rolling transformation aims to transform loops like this:
55 //
56 // int foo(int a);
57 // void bar(int *x) {
58 //   for (int i = 0; i < 500; i += 3) {
59 //     foo(i);
60 //     foo(i+1);
61 //     foo(i+2);
62 //   }
63 // }
64 //
65 // into a loop like this:
66 //
67 // void bar(int *x) {
68 //   for (int i = 0; i < 500; ++i)
69 //     foo(i);
70 // }
71 //
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:
78 //
79 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
80 // f(%iv)
81 // %iv.1 = add %iv, 1                <-- a root increment
82 // f(%iv.1)
83 // %iv.2 = add %iv, 2                <-- a root increment
84 // f(%iv.2)
85 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
86 // f(%iv.scale_m_1)
87 // ...
88 // %iv.next = add %iv, scale
89 // %cmp = icmp(%iv, ...)
90 // br %cmp, header, exit
91 //
92 // where each f(i) is a set of instructions that, collectively, are a function
93 // only of i (and other loop-invariant values).
94 //
95 // As a special case, we can also reroll loops like this:
96 //
97 // int foo(int);
98 // void bar(int *x) {
99 //   for (int i = 0; i < 500; ++i) {
100 //     x[3*i] = foo(0);
101 //     x[3*i+1] = foo(0);
102 //     x[3*i+2] = foo(0);
103 //   }
104 // }
105 //
106 // into this:
107 //
108 // void bar(int *x) {
109 //   for (int i = 0; i < 1500; ++i)
110 //     x[i] = foo(0);
111 // }
112 //
113 // in which case, we're looking for inputs like this:
114 //
115 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
116 // %scaled.iv = mul %iv, scale
117 // f(%scaled.iv)
118 // %scaled.iv.1 = add %scaled.iv, 1
119 // f(%scaled.iv.1)
120 // %scaled.iv.2 = add %scaled.iv, 2
121 // f(%scaled.iv.2)
122 // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
123 // f(%scaled.iv.scale_m_1)
124 // ...
125 // %iv.next = add %iv, 1
126 // %cmp = icmp(%iv, ...)
127 // br %cmp, header, exit
128
129 namespace {
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.
136     IL_All,
137     IL_End
138   };
139
140   class LoopReroll : public LoopPass {
141   public:
142     static char ID; // Pass ID, replacement for typeid
143     LoopReroll() : LoopPass(ID) {
144       initializeLoopRerollPass(*PassRegistry::getPassRegistry());
145     }
146
147     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
148
149     void getAnalysisUsage(AnalysisUsage &AU) const override {
150       AU.addRequired<AliasAnalysis>();
151       AU.addRequired<LoopInfoWrapperPass>();
152       AU.addPreserved<LoopInfoWrapperPass>();
153       AU.addRequired<DominatorTreeWrapperPass>();
154       AU.addPreserved<DominatorTreeWrapperPass>();
155       AU.addRequired<ScalarEvolution>();
156       AU.addRequired<TargetLibraryInfoWrapperPass>();
157     }
158
159   protected:
160     AliasAnalysis *AA;
161     LoopInfo *LI;
162     ScalarEvolution *SE;
163     const DataLayout *DL;
164     TargetLibraryInfo *TLI;
165     DominatorTree *DT;
166
167     typedef SmallVector<Instruction *, 16> SmallInstructionVector;
168     typedef SmallSet<Instruction *, 16>   SmallInstructionSet;
169
170     // A chain of isomorphic instructions, indentified by a single-use PHI,
171     // representing a reduction. Only the last value may be used outside the
172     // loop.
173     struct SimpleLoopReduction {
174       SimpleLoopReduction(Instruction *P, Loop *L)
175         : Valid(false), Instructions(1, P) {
176         assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
177         add(L);
178       }
179
180       bool valid() const {
181         return Valid;
182       }
183
184       Instruction *getPHI() const {
185         assert(Valid && "Using invalid reduction");
186         return Instructions.front();
187       }
188
189       Instruction *getReducedValue() const {
190         assert(Valid && "Using invalid reduction");
191         return Instructions.back();
192       }
193
194       Instruction *get(size_t i) const {
195         assert(Valid && "Using invalid reduction");
196         return Instructions[i+1];
197       }
198
199       Instruction *operator [] (size_t i) const { return get(i); }
200
201       // The size, ignoring the initial PHI.
202       size_t size() const {
203         assert(Valid && "Using invalid reduction");
204         return Instructions.size()-1;
205       }
206
207       typedef SmallInstructionVector::iterator iterator;
208       typedef SmallInstructionVector::const_iterator const_iterator;
209
210       iterator begin() {
211         assert(Valid && "Using invalid reduction");
212         return std::next(Instructions.begin());
213       }
214
215       const_iterator begin() const {
216         assert(Valid && "Using invalid reduction");
217         return std::next(Instructions.begin());
218       }
219
220       iterator end() { return Instructions.end(); }
221       const_iterator end() const { return Instructions.end(); }
222
223     protected:
224       bool Valid;
225       SmallInstructionVector Instructions;
226
227       void add(Loop *L);
228     };
229
230     // The set of all reductions, and state tracking of possible reductions
231     // during loop instruction processing.
232     struct ReductionTracker {
233       typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
234
235       // Add a new possible reduction.
236       void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
237
238       // Setup to track possible reductions corresponding to the provided
239       // rerolling scale. Only reductions with a number of non-PHI instructions
240       // that is divisible by the scale are considered. Three instructions sets
241       // are filled in:
242       //   - A set of all possible instructions in eligible reductions.
243       //   - A set of all PHIs in eligible reductions
244       //   - A set of all reduced values (last instructions) in eligible
245       //     reductions.
246       void restrictToScale(uint64_t Scale,
247                            SmallInstructionSet &PossibleRedSet,
248                            SmallInstructionSet &PossibleRedPHISet,
249                            SmallInstructionSet &PossibleRedLastSet) {
250         PossibleRedIdx.clear();
251         PossibleRedIter.clear();
252         Reds.clear();
253
254         for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
255           if (PossibleReds[i].size() % Scale == 0) {
256             PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
257             PossibleRedPHISet.insert(PossibleReds[i].getPHI());
258
259             PossibleRedSet.insert(PossibleReds[i].getPHI());
260             PossibleRedIdx[PossibleReds[i].getPHI()] = i;
261             for (Instruction *J : PossibleReds[i]) {
262               PossibleRedSet.insert(J);
263               PossibleRedIdx[J] = i;
264             }
265           }
266       }
267
268       // The functions below are used while processing the loop instructions.
269
270       // Are the two instructions both from reductions, and furthermore, from
271       // the same reduction?
272       bool isPairInSame(Instruction *J1, Instruction *J2) {
273         DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
274         if (J1I != PossibleRedIdx.end()) {
275           DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
276           if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
277             return true;
278         }
279
280         return false;
281       }
282
283       // The two provided instructions, the first from the base iteration, and
284       // the second from iteration i, form a matched pair. If these are part of
285       // a reduction, record that fact.
286       void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
287         if (PossibleRedIdx.count(J1)) {
288           assert(PossibleRedIdx.count(J2) &&
289                  "Recording reduction vs. non-reduction instruction?");
290
291           PossibleRedIter[J1] = 0;
292           PossibleRedIter[J2] = i;
293
294           int Idx = PossibleRedIdx[J1];
295           assert(Idx == PossibleRedIdx[J2] &&
296                  "Recording pair from different reductions?");
297           Reds.insert(Idx);
298         }
299       }
300
301       // The functions below can be called after we've finished processing all
302       // instructions in the loop, and we know which reductions were selected.
303
304       // Is the provided instruction the PHI of a reduction selected for
305       // rerolling?
306       bool isSelectedPHI(Instruction *J) {
307         if (!isa<PHINode>(J))
308           return false;
309
310         for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
311              RI != RIE; ++RI) {
312           int i = *RI;
313           if (cast<Instruction>(J) == PossibleReds[i].getPHI())
314             return true;
315         }
316
317         return false;
318       }
319
320       bool validateSelected();
321       void replaceSelected();
322
323     protected:
324       // The vector of all possible reductions (for any scale).
325       SmallReductionVector PossibleReds;
326
327       DenseMap<Instruction *, int> PossibleRedIdx;
328       DenseMap<Instruction *, int> PossibleRedIter;
329       DenseSet<int> Reds;
330     };
331
332     // A DAGRootSet models an induction variable being used in a rerollable
333     // loop. For example,
334     //
335     //   x[i*3+0] = y1
336     //   x[i*3+1] = y2
337     //   x[i*3+2] = y3
338     //
339     //   Base instruction -> i*3               
340     //                    +---+----+
341     //                   /    |     \
342     //               ST[y1]  +1     +2  <-- Roots
343     //                        |      |
344     //                      ST[y2] ST[y3]
345     //
346     // There may be multiple DAGRoots, for example:
347     //
348     //   x[i*2+0] = ...   (1)
349     //   x[i*2+1] = ...   (1)
350     //   x[i*2+4] = ...   (2)
351     //   x[i*2+5] = ...   (2)
352     //   x[(i+1234)*2+5678] = ... (3)
353     //   x[(i+1234)*2+5679] = ... (3)
354     //
355     // The loop will be rerolled by adding a new loop induction variable,
356     // one for the Base instruction in each DAGRootSet.
357     //
358     struct DAGRootSet {
359       Instruction *BaseInst;
360       SmallInstructionVector Roots;
361       // The instructions between IV and BaseInst (but not including BaseInst).
362       SmallInstructionSet SubsumedInsts;
363     };
364
365     // The set of all DAG roots, and state tracking of all roots
366     // for a particular induction variable.
367     struct DAGRootTracker {
368       DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
369                      ScalarEvolution *SE, AliasAnalysis *AA,
370                      TargetLibraryInfo *TLI, const DataLayout *DL)
371         : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI),
372           DL(DL), IV(IV) {
373       }
374
375       /// Stage 1: Find all the DAG roots for the induction variable.
376       bool findRoots();
377       /// Stage 2: Validate if the found roots are valid.
378       bool validate(ReductionTracker &Reductions);
379       /// Stage 3: Assuming validate() returned true, perform the
380       /// replacement.
381       /// @param IterCount The maximum iteration count of L.
382       void replace(const SCEV *IterCount);
383
384     protected:
385       typedef MapVector<Instruction*, SmallBitVector> UsesTy;
386
387       bool findRootsRecursive(Instruction *IVU,
388                               SmallInstructionSet SubsumedInsts);
389       bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
390       bool collectPossibleRoots(Instruction *Base,
391                                 std::map<int64_t,Instruction*> &Roots);
392
393       bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
394       void collectInLoopUserSet(const SmallInstructionVector &Roots,
395                                 const SmallInstructionSet &Exclude,
396                                 const SmallInstructionSet &Final,
397                                 DenseSet<Instruction *> &Users);
398       void collectInLoopUserSet(Instruction *Root,
399                                 const SmallInstructionSet &Exclude,
400                                 const SmallInstructionSet &Final,
401                                 DenseSet<Instruction *> &Users);
402
403       UsesTy::iterator nextInstr(int Val, UsesTy &In,
404                                  const SmallInstructionSet &Exclude,
405                                  UsesTy::iterator *StartI=nullptr);
406       bool isBaseInst(Instruction *I);
407       bool isRootInst(Instruction *I);
408       bool instrDependsOn(Instruction *I,
409                           UsesTy::iterator Start,
410                           UsesTy::iterator End);
411
412       LoopReroll *Parent;
413
414       // Members of Parent, replicated here for brevity.
415       Loop *L;
416       ScalarEvolution *SE;
417       AliasAnalysis *AA;
418       TargetLibraryInfo *TLI;
419       const DataLayout *DL;
420
421       // The loop induction variable.
422       Instruction *IV;
423       // Loop step amount.
424       uint64_t Inc;
425       // Loop reroll count; if Inc == 1, this records the scaling applied
426       // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
427       // If Inc is not 1, Scale = Inc.
428       uint64_t Scale;
429       // The roots themselves.
430       SmallVector<DAGRootSet,16> RootSets;
431       // All increment instructions for IV.
432       SmallInstructionVector LoopIncs;
433       // Map of all instructions in the loop (in order) to the iterations
434       // they are used in (or specially, IL_All for instructions
435       // used in the loop increment mechanism).
436       UsesTy Uses;
437     };
438
439     void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
440     void collectPossibleReductions(Loop *L,
441            ReductionTracker &Reductions);
442     bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
443                 ReductionTracker &Reductions);
444   };
445 }
446
447 char LoopReroll::ID = 0;
448 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
449 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
450 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
451 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
452 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
453 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
454 INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
455
456 Pass *llvm::createLoopRerollPass() {
457   return new LoopReroll;
458 }
459
460 // Returns true if the provided instruction is used outside the given loop.
461 // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
462 // non-loop blocks to be outside the loop.
463 static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
464   for (User *U : I->users()) {
465     if (!L->contains(cast<Instruction>(U)))
466       return true;
467   }
468   return false;
469 }
470
471 // Collect the list of loop induction variables with respect to which it might
472 // be possible to reroll the loop.
473 void LoopReroll::collectPossibleIVs(Loop *L,
474                                     SmallInstructionVector &PossibleIVs) {
475   BasicBlock *Header = L->getHeader();
476   for (BasicBlock::iterator I = Header->begin(),
477        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
478     if (!isa<PHINode>(I))
479       continue;
480     if (!I->getType()->isIntegerTy())
481       continue;
482
483     if (const SCEVAddRecExpr *PHISCEV =
484         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
485       if (PHISCEV->getLoop() != L)
486         continue;
487       if (!PHISCEV->isAffine())
488         continue;
489       if (const SCEVConstant *IncSCEV =
490           dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
491         if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
492           continue;
493         if (IncSCEV->getValue()->uge(MaxInc))
494           continue;
495
496         DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
497               *PHISCEV << "\n");
498         PossibleIVs.push_back(I);
499       }
500     }
501   }
502 }
503
504 // Add the remainder of the reduction-variable chain to the instruction vector
505 // (the initial PHINode has already been added). If successful, the object is
506 // marked as valid.
507 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
508   assert(!Valid && "Cannot add to an already-valid chain");
509
510   // The reduction variable must be a chain of single-use instructions
511   // (including the PHI), except for the last value (which is used by the PHI
512   // and also outside the loop).
513   Instruction *C = Instructions.front();
514
515   do {
516     C = cast<Instruction>(*C->user_begin());
517     if (C->hasOneUse()) {
518       if (!C->isBinaryOp())
519         return;
520
521       if (!(isa<PHINode>(Instructions.back()) ||
522             C->isSameOperationAs(Instructions.back())))
523         return;
524
525       Instructions.push_back(C);
526     }
527   } while (C->hasOneUse());
528
529   if (Instructions.size() < 2 ||
530       !C->isSameOperationAs(Instructions.back()) ||
531       C->use_empty())
532     return;
533
534   // C is now the (potential) last instruction in the reduction chain.
535   for (User *U : C->users()) {
536     // The only in-loop user can be the initial PHI.
537     if (L->contains(cast<Instruction>(U)))
538       if (cast<Instruction>(U) != Instructions.front())
539         return;
540   }
541
542   Instructions.push_back(C);
543   Valid = true;
544 }
545
546 // Collect the vector of possible reduction variables.
547 void LoopReroll::collectPossibleReductions(Loop *L,
548   ReductionTracker &Reductions) {
549   BasicBlock *Header = L->getHeader();
550   for (BasicBlock::iterator I = Header->begin(),
551        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
552     if (!isa<PHINode>(I))
553       continue;
554     if (!I->getType()->isSingleValueType())
555       continue;
556
557     SimpleLoopReduction SLR(I, L);
558     if (!SLR.valid())
559       continue;
560
561     DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
562           SLR.size() << " chained instructions)\n");
563     Reductions.addSLR(SLR);
564   }
565 }
566
567 // Collect the set of all users of the provided root instruction. This set of
568 // users contains not only the direct users of the root instruction, but also
569 // all users of those users, and so on. There are two exceptions:
570 //
571 //   1. Instructions in the set of excluded instructions are never added to the
572 //   use set (even if they are users). This is used, for example, to exclude
573 //   including root increments in the use set of the primary IV.
574 //
575 //   2. Instructions in the set of final instructions are added to the use set
576 //   if they are users, but their users are not added. This is used, for
577 //   example, to prevent a reduction update from forcing all later reduction
578 //   updates into the use set.
579 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
580   Instruction *Root, const SmallInstructionSet &Exclude,
581   const SmallInstructionSet &Final,
582   DenseSet<Instruction *> &Users) {
583   SmallInstructionVector Queue(1, Root);
584   while (!Queue.empty()) {
585     Instruction *I = Queue.pop_back_val();
586     if (!Users.insert(I).second)
587       continue;
588
589     if (!Final.count(I))
590       for (Use &U : I->uses()) {
591         Instruction *User = cast<Instruction>(U.getUser());
592         if (PHINode *PN = dyn_cast<PHINode>(User)) {
593           // Ignore "wrap-around" uses to PHIs of this loop's header.
594           if (PN->getIncomingBlock(U) == L->getHeader())
595             continue;
596         }
597
598         if (L->contains(User) && !Exclude.count(User)) {
599           Queue.push_back(User);
600         }
601       }
602
603     // We also want to collect single-user "feeder" values.
604     for (User::op_iterator OI = I->op_begin(),
605          OIE = I->op_end(); OI != OIE; ++OI) {
606       if (Instruction *Op = dyn_cast<Instruction>(*OI))
607         if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
608             !Final.count(Op))
609           Queue.push_back(Op);
610     }
611   }
612 }
613
614 // Collect all of the users of all of the provided root instructions (combined
615 // into a single set).
616 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
617   const SmallInstructionVector &Roots,
618   const SmallInstructionSet &Exclude,
619   const SmallInstructionSet &Final,
620   DenseSet<Instruction *> &Users) {
621   for (SmallInstructionVector::const_iterator I = Roots.begin(),
622        IE = Roots.end(); I != IE; ++I)
623     collectInLoopUserSet(*I, Exclude, Final, Users);
624 }
625
626 static bool isSimpleLoadStore(Instruction *I) {
627   if (LoadInst *LI = dyn_cast<LoadInst>(I))
628     return LI->isSimple();
629   if (StoreInst *SI = dyn_cast<StoreInst>(I))
630     return SI->isSimple();
631   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
632     return !MI->isVolatile();
633   return false;
634 }
635
636 /// Return true if IVU is a "simple" arithmetic operation.
637 /// This is used for narrowing the search space for DAGRoots; only arithmetic
638 /// and GEPs can be part of a DAGRoot.
639 static bool isSimpleArithmeticOp(User *IVU) {
640   if (Instruction *I = dyn_cast<Instruction>(IVU)) {
641     switch (I->getOpcode()) {
642     default: return false;
643     case Instruction::Add:
644     case Instruction::Sub:
645     case Instruction::Mul:
646     case Instruction::Shl:
647     case Instruction::AShr:
648     case Instruction::LShr:
649     case Instruction::GetElementPtr:
650     case Instruction::Trunc:
651     case Instruction::ZExt:
652     case Instruction::SExt:
653       return true;
654     }
655   }
656   return false;
657 }
658
659 static bool isLoopIncrement(User *U, Instruction *IV) {
660   BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
661   if (!BO || BO->getOpcode() != Instruction::Add)
662     return false;
663
664   for (auto *UU : BO->users()) {
665     PHINode *PN = dyn_cast<PHINode>(UU);
666     if (PN && PN == IV)
667       return true;
668   }
669   return false;
670 }
671
672 bool LoopReroll::DAGRootTracker::
673 collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
674   SmallInstructionVector BaseUsers;
675
676   for (auto *I : Base->users()) {
677     ConstantInt *CI = nullptr;
678
679     if (isLoopIncrement(I, IV)) {
680       LoopIncs.push_back(cast<Instruction>(I));
681       continue;
682     }
683
684     // The root nodes must be either GEPs, ORs or ADDs.
685     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
686       if (BO->getOpcode() == Instruction::Add ||
687           BO->getOpcode() == Instruction::Or)
688         CI = dyn_cast<ConstantInt>(BO->getOperand(1));
689     } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
690       Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
691       CI = dyn_cast<ConstantInt>(LastOperand);
692     }
693
694     if (!CI) {
695       if (Instruction *II = dyn_cast<Instruction>(I)) {
696         BaseUsers.push_back(II);
697         continue;
698       } else {
699         DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
700         return false;
701       }
702     }
703
704     int64_t V = CI->getValue().getSExtValue();
705     if (Roots.find(V) != Roots.end())
706       // No duplicates, please.
707       return false;
708
709     // FIXME: Add support for negative values.
710     if (V < 0) {
711       DEBUG(dbgs() << "LRR: Aborting due to negative value: " << V << "\n");
712       return false;
713     }
714
715     Roots[V] = cast<Instruction>(I);
716   }
717
718   if (Roots.empty())
719     return false;
720   
721   assert(Roots.find(0) == Roots.end() && "Didn't expect a zero index!");
722
723   // If we found non-loop-inc, non-root users of Base, assume they are
724   // for the zeroth root index. This is because "add %a, 0" gets optimized
725   // away.
726   if (BaseUsers.size())
727     Roots[0] = Base;
728
729   // Calculate the number of users of the base, or lowest indexed, iteration.
730   unsigned NumBaseUses = BaseUsers.size();
731   if (NumBaseUses == 0)
732     NumBaseUses = Roots.begin()->second->getNumUses();
733   
734   // Check that every node has the same number of users.
735   for (auto &KV : Roots) {
736     if (KV.first == 0)
737       continue;
738     if (KV.second->getNumUses() != NumBaseUses) {
739       DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
740             << "#Base=" << NumBaseUses << ", #Root=" <<
741             KV.second->getNumUses() << "\n");
742       return false;
743     }
744   }
745
746   return true; 
747 }
748
749 bool LoopReroll::DAGRootTracker::
750 findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
751   // Does the user look like it could be part of a root set?
752   // All its users must be simple arithmetic ops.
753   if (I->getNumUses() > IL_MaxRerollIterations)
754     return false;
755
756   if ((I->getOpcode() == Instruction::Mul ||
757        I->getOpcode() == Instruction::PHI) &&
758       I != IV &&
759       findRootsBase(I, SubsumedInsts))
760     return true;
761
762   SubsumedInsts.insert(I);
763
764   for (User *V : I->users()) {
765     Instruction *I = dyn_cast<Instruction>(V);
766     if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
767       continue;
768
769     if (!I || !isSimpleArithmeticOp(I) ||
770         !findRootsRecursive(I, SubsumedInsts))
771       return false;
772   }
773   return true;
774 }
775
776 bool LoopReroll::DAGRootTracker::
777 findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
778
779   // The base instruction needs to be a multiply so
780   // that we can erase it.
781   if (IVU->getOpcode() != Instruction::Mul &&
782       IVU->getOpcode() != Instruction::PHI)
783     return false;
784
785   std::map<int64_t, Instruction*> V;
786   if (!collectPossibleRoots(IVU, V))
787     return false;
788
789   // If we didn't get a root for index zero, then IVU must be 
790   // subsumed.
791   if (V.find(0) == V.end())
792     SubsumedInsts.insert(IVU);
793
794   // Partition the vector into monotonically increasing indexes.
795   DAGRootSet DRS;
796   DRS.BaseInst = nullptr;
797
798   for (auto &KV : V) {
799     if (!DRS.BaseInst) {
800       DRS.BaseInst = KV.second;
801       DRS.SubsumedInsts = SubsumedInsts;
802     } else if (DRS.Roots.empty()) {
803       DRS.Roots.push_back(KV.second);
804     } else if (V.find(KV.first - 1) != V.end()) {
805       DRS.Roots.push_back(KV.second);
806     } else {
807       // Linear sequence terminated.
808       RootSets.push_back(DRS);
809       DRS.BaseInst = KV.second;
810       DRS.SubsumedInsts = SubsumedInsts;
811       DRS.Roots.clear();
812     }
813   }
814   RootSets.push_back(DRS);
815
816   return true;
817 }
818
819 bool LoopReroll::DAGRootTracker::findRoots() {
820
821   const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
822   Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
823     getValue()->getZExtValue();
824
825   assert(RootSets.empty() && "Unclean state!");
826   if (Inc == 1) {
827     for (auto *IVU : IV->users()) {
828       if (isLoopIncrement(IVU, IV))
829         LoopIncs.push_back(cast<Instruction>(IVU));
830     }
831     if (!findRootsRecursive(IV, SmallInstructionSet()))
832       return false;
833     LoopIncs.push_back(IV);
834   } else {
835     if (!findRootsBase(IV, SmallInstructionSet()))
836       return false;
837   }
838
839   // Ensure all sets have the same size.
840   if (RootSets.empty()) {
841     DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
842     return false;
843   }
844   for (auto &V : RootSets) {
845     if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
846       DEBUG(dbgs()
847             << "LRR: Aborting because not all root sets have the same size\n");
848       return false;
849     }
850   }
851
852   // And ensure all loop iterations are consecutive. We rely on std::map
853   // providing ordered traversal.
854   for (auto &V : RootSets) {
855     const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
856     if (!ADR)
857       return false;
858
859     // Consider a DAGRootSet with N-1 roots (so N different values including
860     //   BaseInst).
861     // Define d = Roots[0] - BaseInst, which should be the same as
862     //   Roots[I] - Roots[I-1] for all I in [1..N).
863     // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
864     //   loop iteration J.
865     //
866     // Now, For the loop iterations to be consecutive:
867     //   D = d * N
868
869     unsigned N = V.Roots.size() + 1;
870     const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
871     const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
872     if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
873       DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
874       return false;
875     }
876   }
877   Scale = RootSets[0].Roots.size() + 1;
878
879   if (Scale > IL_MaxRerollIterations) {
880     DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
881           << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
882           << "\n");
883     return false;
884   }
885
886   DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
887
888   return true;
889 }
890
891 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
892   // Populate the MapVector with all instructions in the block, in order first,
893   // so we can iterate over the contents later in perfect order.
894   for (auto &I : *L->getHeader()) {
895     Uses[&I].resize(IL_End);
896   }
897
898   SmallInstructionSet Exclude;
899   for (auto &DRS : RootSets) {
900     Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
901     Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
902     Exclude.insert(DRS.BaseInst);
903   }
904   Exclude.insert(LoopIncs.begin(), LoopIncs.end());
905
906   for (auto &DRS : RootSets) {
907     DenseSet<Instruction*> VBase;
908     collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
909     for (auto *I : VBase) {
910       Uses[I].set(0);
911     }
912
913     unsigned Idx = 1;
914     for (auto *Root : DRS.Roots) {
915       DenseSet<Instruction*> V;
916       collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
917
918       // While we're here, check the use sets are the same size.
919       if (V.size() != VBase.size()) {
920         DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
921         return false;
922       }
923
924       for (auto *I : V) {
925         Uses[I].set(Idx);
926       }
927       ++Idx;
928     }
929
930     // Make sure our subsumed instructions are remembered too.
931     for (auto *I : DRS.SubsumedInsts) {
932       Uses[I].set(IL_All);
933     }
934   }
935
936   // Make sure the loop increments are also accounted for.
937
938   Exclude.clear();
939   for (auto &DRS : RootSets) {
940     Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
941     Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
942     Exclude.insert(DRS.BaseInst);
943   }
944
945   DenseSet<Instruction*> V;
946   collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
947   for (auto *I : V) {
948     Uses[I].set(IL_All);
949   }
950
951   return true;
952
953 }
954
955 /// Get the next instruction in "In" that is a member of set Val.
956 /// Start searching from StartI, and do not return anything in Exclude.
957 /// If StartI is not given, start from In.begin().
958 LoopReroll::DAGRootTracker::UsesTy::iterator
959 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
960                                       const SmallInstructionSet &Exclude,
961                                       UsesTy::iterator *StartI) {
962   UsesTy::iterator I = StartI ? *StartI : In.begin();
963   while (I != In.end() && (I->second.test(Val) == 0 ||
964                            Exclude.count(I->first) != 0))
965     ++I;
966   return I;
967 }
968
969 bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
970   for (auto &DRS : RootSets) {
971     if (DRS.BaseInst == I)
972       return true;
973   }
974   return false;
975 }
976
977 bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
978   for (auto &DRS : RootSets) {
979     if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
980       return true;
981   }
982   return false;
983 }
984
985 /// Return true if instruction I depends on any instruction between
986 /// Start and End.
987 bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
988                                                 UsesTy::iterator Start,
989                                                 UsesTy::iterator End) {
990   for (auto *U : I->users()) {
991     for (auto It = Start; It != End; ++It)
992       if (U == It->first)
993         return true;
994   }
995   return false;
996 }
997
998 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
999   // We now need to check for equivalence of the use graph of each root with
1000   // that of the primary induction variable (excluding the roots). Our goal
1001   // here is not to solve the full graph isomorphism problem, but rather to
1002   // catch common cases without a lot of work. As a result, we will assume
1003   // that the relative order of the instructions in each unrolled iteration
1004   // is the same (although we will not make an assumption about how the
1005   // different iterations are intermixed). Note that while the order must be
1006   // the same, the instructions may not be in the same basic block.
1007
1008   // An array of just the possible reductions for this scale factor. When we
1009   // collect the set of all users of some root instructions, these reduction
1010   // instructions are treated as 'final' (their uses are not considered).
1011   // This is important because we don't want the root use set to search down
1012   // the reduction chain.
1013   SmallInstructionSet PossibleRedSet;
1014   SmallInstructionSet PossibleRedLastSet;
1015   SmallInstructionSet PossibleRedPHISet;
1016   Reductions.restrictToScale(Scale, PossibleRedSet,
1017                              PossibleRedPHISet, PossibleRedLastSet);
1018
1019   // Populate "Uses" with where each instruction is used.
1020   if (!collectUsedInstructions(PossibleRedSet))
1021     return false;
1022
1023   // Make sure we mark the reduction PHIs as used in all iterations.
1024   for (auto *I : PossibleRedPHISet) {
1025     Uses[I].set(IL_All);
1026   }
1027
1028   // Make sure all instructions in the loop are in one and only one
1029   // set.
1030   for (auto &KV : Uses) {
1031     if (KV.second.count() != 1) {
1032       DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1033             << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1034       return false;
1035     }
1036   }
1037
1038   DEBUG(
1039     for (auto &KV : Uses) {
1040       dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1041     }
1042     );
1043
1044   for (unsigned Iter = 1; Iter < Scale; ++Iter) {
1045     // In addition to regular aliasing information, we need to look for
1046     // instructions from later (future) iterations that have side effects
1047     // preventing us from reordering them past other instructions with side
1048     // effects.
1049     bool FutureSideEffects = false;
1050     AliasSetTracker AST(*AA);
1051     // The map between instructions in f(%iv.(i+1)) and f(%iv).
1052     DenseMap<Value *, Value *> BaseMap;
1053
1054     // Compare iteration Iter to the base.
1055     SmallInstructionSet Visited;
1056     auto BaseIt = nextInstr(0, Uses, Visited);
1057     auto RootIt = nextInstr(Iter, Uses, Visited);
1058     auto LastRootIt = Uses.begin();
1059
1060     while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1061       Instruction *BaseInst = BaseIt->first;
1062       Instruction *RootInst = RootIt->first;
1063
1064       // Skip over the IV or root instructions; only match their users.
1065       bool Continue = false;
1066       if (isBaseInst(BaseInst)) {
1067         Visited.insert(BaseInst);
1068         BaseIt = nextInstr(0, Uses, Visited);
1069         Continue = true;
1070       }
1071       if (isRootInst(RootInst)) {
1072         LastRootIt = RootIt;
1073         Visited.insert(RootInst);
1074         RootIt = nextInstr(Iter, Uses, Visited);
1075         Continue = true;
1076       }
1077       if (Continue) continue;
1078
1079       if (!BaseInst->isSameOperationAs(RootInst)) {
1080         // Last chance saloon. We don't try and solve the full isomorphism
1081         // problem, but try and at least catch the case where two instructions
1082         // *of different types* are round the wrong way. We won't be able to
1083         // efficiently tell, given two ADD instructions, which way around we
1084         // should match them, but given an ADD and a SUB, we can at least infer
1085         // which one is which.
1086         //
1087         // This should allow us to deal with a greater subset of the isomorphism
1088         // problem. It does however change a linear algorithm into a quadratic
1089         // one, so limit the number of probes we do.
1090         auto TryIt = RootIt;
1091         unsigned N = NumToleratedFailedMatches;
1092         while (TryIt != Uses.end() &&
1093                !BaseInst->isSameOperationAs(TryIt->first) &&
1094                N--) {
1095           ++TryIt;
1096           TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1097         }
1098
1099         if (TryIt == Uses.end() || TryIt == RootIt ||
1100             instrDependsOn(TryIt->first, RootIt, TryIt)) {
1101           DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1102                 " vs. " << *RootInst << "\n");
1103           return false;
1104         }
1105         
1106         RootIt = TryIt;
1107         RootInst = TryIt->first;
1108       }
1109
1110       // All instructions between the last root and this root
1111       // may belong to some other iteration. If they belong to a 
1112       // future iteration, then they're dangerous to alias with.
1113       // 
1114       // Note that because we allow a limited amount of flexibility in the order
1115       // that we visit nodes, LastRootIt might be *before* RootIt, in which
1116       // case we've already checked this set of instructions so we shouldn't
1117       // do anything.
1118       for (; LastRootIt < RootIt; ++LastRootIt) {
1119         Instruction *I = LastRootIt->first;
1120         if (LastRootIt->second.find_first() < (int)Iter)
1121           continue;
1122         if (I->mayWriteToMemory())
1123           AST.add(I);
1124         // Note: This is specifically guarded by a check on isa<PHINode>,
1125         // which while a valid (somewhat arbitrary) micro-optimization, is
1126         // needed because otherwise isSafeToSpeculativelyExecute returns
1127         // false on PHI nodes.
1128         if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
1129             !isSafeToSpeculativelyExecute(I, DL))
1130           // Intervening instructions cause side effects.
1131           FutureSideEffects = true;
1132       }
1133
1134       // Make sure that this instruction, which is in the use set of this
1135       // root instruction, does not also belong to the base set or the set of
1136       // some other root instruction.
1137       if (RootIt->second.count() > 1) {
1138         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1139                         " vs. " << *RootInst << " (prev. case overlap)\n");
1140         return false;
1141       }
1142
1143       // Make sure that we don't alias with any instruction in the alias set
1144       // tracker. If we do, then we depend on a future iteration, and we
1145       // can't reroll.
1146       if (RootInst->mayReadFromMemory())
1147         for (auto &K : AST) {
1148           if (K.aliasesUnknownInst(RootInst, *AA)) {
1149             DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1150                             " vs. " << *RootInst << " (depends on future store)\n");
1151             return false;
1152           }
1153         }
1154
1155       // If we've past an instruction from a future iteration that may have
1156       // side effects, and this instruction might also, then we can't reorder
1157       // them, and this matching fails. As an exception, we allow the alias
1158       // set tracker to handle regular (simple) load/store dependencies.
1159       if (FutureSideEffects &&
1160             ((!isSimpleLoadStore(BaseInst) &&
1161               !isSafeToSpeculativelyExecute(BaseInst, DL)) ||
1162              (!isSimpleLoadStore(RootInst) &&
1163               !isSafeToSpeculativelyExecute(RootInst, DL)))) {
1164         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1165                         " vs. " << *RootInst <<
1166                         " (side effects prevent reordering)\n");
1167         return false;
1168       }
1169
1170       // For instructions that are part of a reduction, if the operation is
1171       // associative, then don't bother matching the operands (because we
1172       // already know that the instructions are isomorphic, and the order
1173       // within the iteration does not matter). For non-associative reductions,
1174       // we do need to match the operands, because we need to reject
1175       // out-of-order instructions within an iteration!
1176       // For example (assume floating-point addition), we need to reject this:
1177       //   x += a[i]; x += b[i];
1178       //   x += a[i+1]; x += b[i+1];
1179       //   x += b[i+2]; x += a[i+2];
1180       bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
1181
1182       if (!(InReduction && BaseInst->isAssociative())) {
1183         bool Swapped = false, SomeOpMatched = false;
1184         for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1185           Value *Op2 = RootInst->getOperand(j);
1186
1187           // If this is part of a reduction (and the operation is not
1188           // associatve), then we match all operands, but not those that are
1189           // part of the reduction.
1190           if (InReduction)
1191             if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
1192               if (Reductions.isPairInSame(RootInst, Op2I))
1193                 continue;
1194
1195           DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
1196           if (BMI != BaseMap.end()) {
1197             Op2 = BMI->second;
1198           } else {
1199             for (auto &DRS : RootSets) {
1200               if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1201                 Op2 = DRS.BaseInst;
1202                 break;
1203               }
1204             }
1205           }
1206
1207           if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
1208             // If we've not already decided to swap the matched operands, and
1209             // we've not already matched our first operand (note that we could
1210             // have skipped matching the first operand because it is part of a
1211             // reduction above), and the instruction is commutative, then try
1212             // the swapped match.
1213             if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1214                 BaseInst->getOperand(!j) == Op2) {
1215               Swapped = true;
1216             } else {
1217               DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1218                     << " vs. " << *RootInst << " (operand " << j << ")\n");
1219               return false;
1220             }
1221           }
1222
1223           SomeOpMatched = true;
1224         }
1225       }
1226
1227       if ((!PossibleRedLastSet.count(BaseInst) &&
1228            hasUsesOutsideLoop(BaseInst, L)) ||
1229           (!PossibleRedLastSet.count(RootInst) &&
1230            hasUsesOutsideLoop(RootInst, L))) {
1231         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1232                         " vs. " << *RootInst << " (uses outside loop)\n");
1233         return false;
1234       }
1235
1236       Reductions.recordPair(BaseInst, RootInst, Iter);
1237       BaseMap.insert(std::make_pair(RootInst, BaseInst));
1238
1239       LastRootIt = RootIt;
1240       Visited.insert(BaseInst);
1241       Visited.insert(RootInst);
1242       BaseIt = nextInstr(0, Uses, Visited);
1243       RootIt = nextInstr(Iter, Uses, Visited);
1244     }
1245     assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1246             "Mismatched set sizes!");
1247   }
1248
1249   DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1250                   *IV << "\n");
1251
1252   return true;
1253 }
1254
1255 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1256   BasicBlock *Header = L->getHeader();
1257   // Remove instructions associated with non-base iterations.
1258   for (BasicBlock::reverse_iterator J = Header->rbegin();
1259        J != Header->rend();) {
1260     unsigned I = Uses[&*J].find_first();
1261     if (I > 0 && I < IL_All) {
1262       Instruction *D = &*J;
1263       DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1264       D->eraseFromParent();
1265       continue;
1266     }
1267
1268     ++J;
1269   }
1270
1271   // We need to create a new induction variable for each different BaseInst.
1272   for (auto &DRS : RootSets) {
1273     // Insert the new induction variable.
1274     const SCEVAddRecExpr *RealIVSCEV =
1275       cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1276     const SCEV *Start = RealIVSCEV->getStart();
1277     const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>
1278       (SE->getAddRecExpr(Start,
1279                          SE->getConstant(RealIVSCEV->getType(), 1),
1280                          L, SCEV::FlagAnyWrap));
1281     { // Limit the lifetime of SCEVExpander.
1282       SCEVExpander Expander(*SE, "reroll");
1283       Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
1284
1285       for (auto &KV : Uses) {
1286         if (KV.second.find_first() == 0)
1287           KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV);
1288       }
1289
1290       if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1291         // FIXME: Why do we need this check?
1292         if (Uses[BI].find_first() == IL_All) {
1293           const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1294
1295           // Iteration count SCEV minus 1
1296           const SCEV *ICMinus1SCEV =
1297             SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
1298
1299           Value *ICMinus1; // Iteration count minus 1
1300           if (isa<SCEVConstant>(ICMinus1SCEV)) {
1301             ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1302           } else {
1303             BasicBlock *Preheader = L->getLoopPreheader();
1304             if (!Preheader)
1305               Preheader = InsertPreheaderForLoop(L, Parent);
1306
1307             ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1308                                               Preheader->getTerminator());
1309           }
1310
1311           Value *Cond =
1312             new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
1313           BI->setCondition(Cond);
1314
1315           if (BI->getSuccessor(1) != Header)
1316             BI->swapSuccessors();
1317         }
1318       }
1319     }
1320   }
1321
1322   SimplifyInstructionsInBlock(Header, DL, TLI);
1323   DeleteDeadPHIs(Header, TLI);
1324 }
1325
1326 // Validate the selected reductions. All iterations must have an isomorphic
1327 // part of the reduction chain and, for non-associative reductions, the chain
1328 // entries must appear in order.
1329 bool LoopReroll::ReductionTracker::validateSelected() {
1330   // For a non-associative reduction, the chain entries must appear in order.
1331   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1332        RI != RIE; ++RI) {
1333     int i = *RI;
1334     int PrevIter = 0, BaseCount = 0, Count = 0;
1335     for (Instruction *J : PossibleReds[i]) {
1336       // Note that all instructions in the chain must have been found because
1337       // all instructions in the function must have been assigned to some
1338       // iteration.
1339       int Iter = PossibleRedIter[J];
1340       if (Iter != PrevIter && Iter != PrevIter + 1 &&
1341           !PossibleReds[i].getReducedValue()->isAssociative()) {
1342         DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
1343                         J << "\n");
1344         return false;
1345       }
1346
1347       if (Iter != PrevIter) {
1348         if (Count != BaseCount) {
1349           DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1350                 " reduction use count " << Count <<
1351                 " is not equal to the base use count " <<
1352                 BaseCount << "\n");
1353           return false;
1354         }
1355
1356         Count = 0;
1357       }
1358
1359       ++Count;
1360       if (Iter == 0)
1361         ++BaseCount;
1362
1363       PrevIter = Iter;
1364     }
1365   }
1366
1367   return true;
1368 }
1369
1370 // For all selected reductions, remove all parts except those in the first
1371 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1372 // of the first-iteration reduced value (in other words, reroll the selected
1373 // reductions).
1374 void LoopReroll::ReductionTracker::replaceSelected() {
1375   // Fixup reductions to refer to the last instruction associated with the
1376   // first iteration (not the last).
1377   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1378        RI != RIE; ++RI) {
1379     int i = *RI;
1380     int j = 0;
1381     for (int e = PossibleReds[i].size(); j != e; ++j)
1382       if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1383         --j;
1384         break;
1385       }
1386
1387     // Replace users with the new end-of-chain value.
1388     SmallInstructionVector Users;
1389     for (User *U : PossibleReds[i].getReducedValue()->users()) {
1390       Users.push_back(cast<Instruction>(U));
1391     }
1392
1393     for (SmallInstructionVector::iterator J = Users.begin(),
1394          JE = Users.end(); J != JE; ++J)
1395       (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1396                               PossibleReds[i][j]);
1397   }
1398 }
1399
1400 // Reroll the provided loop with respect to the provided induction variable.
1401 // Generally, we're looking for a loop like this:
1402 //
1403 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1404 // f(%iv)
1405 // %iv.1 = add %iv, 1                <-- a root increment
1406 // f(%iv.1)
1407 // %iv.2 = add %iv, 2                <-- a root increment
1408 // f(%iv.2)
1409 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
1410 // f(%iv.scale_m_1)
1411 // ...
1412 // %iv.next = add %iv, scale
1413 // %cmp = icmp(%iv, ...)
1414 // br %cmp, header, exit
1415 //
1416 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1417 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1418 // be intermixed with eachother. The restriction imposed by this algorithm is
1419 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1420 // etc. be the same.
1421 //
1422 // First, we collect the use set of %iv, excluding the other increment roots.
1423 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1424 // times, having collected the use set of f(%iv.(i+1)), during which we:
1425 //   - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1426 //     the next unmatched instruction in f(%iv.(i+1)).
1427 //   - Ensure that both matched instructions don't have any external users
1428 //     (with the exception of last-in-chain reduction instructions).
1429 //   - Track the (aliasing) write set, and other side effects, of all
1430 //     instructions that belong to future iterations that come before the matched
1431 //     instructions. If the matched instructions read from that write set, then
1432 //     f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1433 //     f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1434 //     if any of these future instructions had side effects (could not be
1435 //     speculatively executed), and so do the matched instructions, when we
1436 //     cannot reorder those side-effect-producing instructions, and rerolling
1437 //     fails.
1438 //
1439 // Finally, we make sure that all loop instructions are either loop increment
1440 // roots, belong to simple latch code, parts of validated reductions, part of
1441 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1442 // have been validated), then we reroll the loop.
1443 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1444                         const SCEV *IterCount,
1445                         ReductionTracker &Reductions) {
1446   DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DL);
1447
1448   if (!DAGRoots.findRoots())
1449     return false;
1450   DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
1451                   *IV << "\n");
1452   
1453   if (!DAGRoots.validate(Reductions))
1454     return false;
1455   if (!Reductions.validateSelected())
1456     return false;
1457   // At this point, we've validated the rerolling, and we're committed to
1458   // making changes!
1459
1460   Reductions.replaceSelected();
1461   DAGRoots.replace(IterCount);
1462
1463   ++NumRerolledLoops;
1464   return true;
1465 }
1466
1467 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1468   if (skipOptnoneFunction(L))
1469     return false;
1470
1471   AA = &getAnalysis<AliasAnalysis>();
1472   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1473   SE = &getAnalysis<ScalarEvolution>();
1474   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1475   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1476   DL = DLP ? &DLP->getDataLayout() : nullptr;
1477   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1478
1479   BasicBlock *Header = L->getHeader();
1480   DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1481         "] Loop %" << Header->getName() << " (" <<
1482         L->getNumBlocks() << " block(s))\n");
1483
1484   bool Changed = false;
1485
1486   // For now, we'll handle only single BB loops.
1487   if (L->getNumBlocks() > 1)
1488     return Changed;
1489
1490   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1491     return Changed;
1492
1493   const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1494   const SCEV *IterCount =
1495     SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
1496   DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1497
1498   // First, we need to find the induction variable with respect to which we can
1499   // reroll (there may be several possible options).
1500   SmallInstructionVector PossibleIVs;
1501   collectPossibleIVs(L, PossibleIVs);
1502
1503   if (PossibleIVs.empty()) {
1504     DEBUG(dbgs() << "LRR: No possible IVs found\n");
1505     return Changed;
1506   }
1507
1508   ReductionTracker Reductions;
1509   collectPossibleReductions(L, Reductions);
1510
1511   // For each possible IV, collect the associated possible set of 'root' nodes
1512   // (i+1, i+2, etc.).
1513   for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1514        IE = PossibleIVs.end(); I != IE; ++I)
1515     if (reroll(*I, L, Header, IterCount, Reductions)) {
1516       Changed = true;
1517       break;
1518     }
1519
1520   return Changed;
1521 }