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