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/BitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AliasSetTracker.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionExpander.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Transforms/Utils/LoopUtils.h"
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.
132     IL_MaxRerollIterations = 32,
133     /// The bitvector index used by loop induction variables and other
134     /// instructions that belong to all iterations.
135     IL_All,
136     IL_End
137   };
138 
139   class LoopReroll : public LoopPass {
140   public:
141     static char ID; // Pass ID, replacement for typeid
142     LoopReroll() : LoopPass(ID) {
143       initializeLoopRerollPass(*PassRegistry::getPassRegistry());
144     }
145 
146     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
147 
148     void getAnalysisUsage(AnalysisUsage &AU) const override {
149       AU.addRequired<TargetLibraryInfoWrapperPass>();
150       getLoopAnalysisUsage(AU);
151     }
152 
153   protected:
154     AliasAnalysis *AA;
155     LoopInfo *LI;
156     ScalarEvolution *SE;
157     TargetLibraryInfo *TLI;
158     DominatorTree *DT;
159     bool PreserveLCSSA;
160 
161     typedef SmallVector<Instruction *, 16> SmallInstructionVector;
162     typedef SmallSet<Instruction *, 16>   SmallInstructionSet;
163 
164     // Map between induction variable and its increment
165     DenseMap<Instruction *, int64_t> IVToIncMap;
166     // For loop with multiple induction variable, remember the one used only to
167     // control the loop.
168     Instruction *LoopControlIV;
169 
170     // A chain of isomorphic instructions, identified 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       bool validateSelected();
305       void replaceSelected();
306 
307     protected:
308       // The vector of all possible reductions (for any scale).
309       SmallReductionVector PossibleReds;
310 
311       DenseMap<Instruction *, int> PossibleRedIdx;
312       DenseMap<Instruction *, int> PossibleRedIter;
313       DenseSet<int> Reds;
314     };
315 
316     // A DAGRootSet models an induction variable being used in a rerollable
317     // loop. For example,
318     //
319     //   x[i*3+0] = y1
320     //   x[i*3+1] = y2
321     //   x[i*3+2] = y3
322     //
323     //   Base instruction -> i*3
324     //                    +---+----+
325     //                   /    |     \
326     //               ST[y1]  +1     +2  <-- Roots
327     //                        |      |
328     //                      ST[y2] ST[y3]
329     //
330     // There may be multiple DAGRoots, for example:
331     //
332     //   x[i*2+0] = ...   (1)
333     //   x[i*2+1] = ...   (1)
334     //   x[i*2+4] = ...   (2)
335     //   x[i*2+5] = ...   (2)
336     //   x[(i+1234)*2+5678] = ... (3)
337     //   x[(i+1234)*2+5679] = ... (3)
338     //
339     // The loop will be rerolled by adding a new loop induction variable,
340     // one for the Base instruction in each DAGRootSet.
341     //
342     struct DAGRootSet {
343       Instruction *BaseInst;
344       SmallInstructionVector Roots;
345       // The instructions between IV and BaseInst (but not including BaseInst).
346       SmallInstructionSet SubsumedInsts;
347     };
348 
349     // The set of all DAG roots, and state tracking of all roots
350     // for a particular induction variable.
351     struct DAGRootTracker {
352       DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
353                      ScalarEvolution *SE, AliasAnalysis *AA,
354                      TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
355                      bool PreserveLCSSA,
356                      DenseMap<Instruction *, int64_t> &IncrMap,
357                      Instruction *LoopCtrlIV)
358           : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
359             PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
360             LoopControlIV(LoopCtrlIV) {}
361 
362       /// Stage 1: Find all the DAG roots for the induction variable.
363       bool findRoots();
364       /// Stage 2: Validate if the found roots are valid.
365       bool validate(ReductionTracker &Reductions);
366       /// Stage 3: Assuming validate() returned true, perform the
367       /// replacement.
368       /// @param IterCount The maximum iteration count of L.
369       void replace(const SCEV *IterCount);
370 
371     protected:
372       typedef MapVector<Instruction*, BitVector> UsesTy;
373 
374       bool findRootsRecursive(Instruction *IVU,
375                               SmallInstructionSet SubsumedInsts);
376       bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
377       bool collectPossibleRoots(Instruction *Base,
378                                 std::map<int64_t,Instruction*> &Roots);
379 
380       bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
381       void collectInLoopUserSet(const SmallInstructionVector &Roots,
382                                 const SmallInstructionSet &Exclude,
383                                 const SmallInstructionSet &Final,
384                                 DenseSet<Instruction *> &Users);
385       void collectInLoopUserSet(Instruction *Root,
386                                 const SmallInstructionSet &Exclude,
387                                 const SmallInstructionSet &Final,
388                                 DenseSet<Instruction *> &Users);
389 
390       UsesTy::iterator nextInstr(int Val, UsesTy &In,
391                                  const SmallInstructionSet &Exclude,
392                                  UsesTy::iterator *StartI=nullptr);
393       bool isBaseInst(Instruction *I);
394       bool isRootInst(Instruction *I);
395       bool instrDependsOn(Instruction *I,
396                           UsesTy::iterator Start,
397                           UsesTy::iterator End);
398       void replaceIV(Instruction *Inst, Instruction *IV, const SCEV *IterCount);
399       void updateNonLoopCtrlIncr();
400 
401       LoopReroll *Parent;
402 
403       // Members of Parent, replicated here for brevity.
404       Loop *L;
405       ScalarEvolution *SE;
406       AliasAnalysis *AA;
407       TargetLibraryInfo *TLI;
408       DominatorTree *DT;
409       LoopInfo *LI;
410       bool PreserveLCSSA;
411 
412       // The loop induction variable.
413       Instruction *IV;
414       // Loop step amount.
415       int64_t Inc;
416       // Loop reroll count; if Inc == 1, this records the scaling applied
417       // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
418       // If Inc is not 1, Scale = Inc.
419       uint64_t Scale;
420       // The roots themselves.
421       SmallVector<DAGRootSet,16> RootSets;
422       // All increment instructions for IV.
423       SmallInstructionVector LoopIncs;
424       // Map of all instructions in the loop (in order) to the iterations
425       // they are used in (or specially, IL_All for instructions
426       // used in the loop increment mechanism).
427       UsesTy Uses;
428       // Map between induction variable and its increment
429       DenseMap<Instruction *, int64_t> &IVToIncMap;
430       Instruction *LoopControlIV;
431     };
432 
433     // Check if it is a compare-like instruction whose user is a branch
434     bool isCompareUsedByBranch(Instruction *I) {
435       auto *TI = I->getParent()->getTerminator();
436       if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
437         return false;
438       return I->hasOneUse() && TI->getOperand(0) == I;
439     };
440 
441     bool isLoopControlIV(Loop *L, Instruction *IV);
442     void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
443     void collectPossibleReductions(Loop *L,
444            ReductionTracker &Reductions);
445     bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
446                 ReductionTracker &Reductions);
447   };
448 }
449 
450 char LoopReroll::ID = 0;
451 INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
452 INITIALIZE_PASS_DEPENDENCY(LoopPass)
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 static const SCEVConstant *getIncrmentFactorSCEV(ScalarEvolution *SE,
472                                                  const SCEV *SCEVExpr,
473                                                  Instruction &IV) {
474   const SCEVMulExpr *MulSCEV = dyn_cast<SCEVMulExpr>(SCEVExpr);
475 
476   // If StepRecurrence of a SCEVExpr is a constant (c1 * c2, c2 = sizeof(ptr)),
477   // Return c1.
478   if (!MulSCEV && IV.getType()->isPointerTy())
479     if (const SCEVConstant *IncSCEV = dyn_cast<SCEVConstant>(SCEVExpr)) {
480       const PointerType *PTy = cast<PointerType>(IV.getType());
481       Type *ElTy = PTy->getElementType();
482       const SCEV *SizeOfExpr =
483           SE->getSizeOfExpr(SE->getEffectiveSCEVType(IV.getType()), ElTy);
484       if (IncSCEV->getValue()->getValue().isNegative()) {
485         const SCEV *NewSCEV =
486             SE->getUDivExpr(SE->getNegativeSCEV(SCEVExpr), SizeOfExpr);
487         return dyn_cast<SCEVConstant>(SE->getNegativeSCEV(NewSCEV));
488       } else {
489         return dyn_cast<SCEVConstant>(SE->getUDivExpr(SCEVExpr, SizeOfExpr));
490       }
491     }
492 
493   if (!MulSCEV)
494     return nullptr;
495 
496   // If StepRecurrence of a SCEVExpr is a c * sizeof(x), where c is constant,
497   // Return c.
498   const SCEVConstant *CIncSCEV = nullptr;
499   for (const SCEV *Operand : MulSCEV->operands()) {
500     if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Operand)) {
501       CIncSCEV = Constant;
502     } else if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Operand)) {
503       Type *AllocTy;
504       if (!Unknown->isSizeOf(AllocTy))
505         break;
506     } else {
507       return nullptr;
508     }
509   }
510   return CIncSCEV;
511 }
512 
513 // Check if an IV is only used to control the loop. There are two cases:
514 // 1. It only has one use which is loop increment, and the increment is only
515 // used by comparison and the PHI (could has sext with nsw in between), and the
516 // comparison is only used by branch.
517 // 2. It is used by loop increment and the comparison, the loop increment is
518 // only used by the PHI, and the comparison is used only by the branch.
519 bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
520   unsigned IVUses = IV->getNumUses();
521   if (IVUses != 2 && IVUses != 1)
522     return false;
523 
524   for (auto *User : IV->users()) {
525     int32_t IncOrCmpUses = User->getNumUses();
526     bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
527 
528     // User can only have one or two uses.
529     if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
530       return false;
531 
532     // Case 1
533     if (IVUses == 1) {
534       // The only user must be the loop increment.
535       // The loop increment must have two uses.
536       if (IsCompInst || IncOrCmpUses != 2)
537         return false;
538     }
539 
540     // Case 2
541     if (IVUses == 2 && IncOrCmpUses != 1)
542       return false;
543 
544     // The users of the IV must be a binary operation or a comparison
545     if (auto *BO = dyn_cast<BinaryOperator>(User)) {
546       if (BO->getOpcode() == Instruction::Add) {
547         // Loop Increment
548         // User of Loop Increment should be either PHI or CMP
549         for (auto *UU : User->users()) {
550           if (PHINode *PN = dyn_cast<PHINode>(UU)) {
551             if (PN != IV)
552               return false;
553           }
554           // Must be a CMP or an ext (of a value with nsw) then CMP
555           else {
556             Instruction *UUser = dyn_cast<Instruction>(UU);
557             // Skip SExt if we are extending an nsw value
558             // TODO: Allow ZExt too
559             if (BO->hasNoSignedWrap() && UUser && UUser->getNumUses() == 1 &&
560                 isa<SExtInst>(UUser))
561               UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
562             if (!isCompareUsedByBranch(UUser))
563               return false;
564           }
565         }
566       } else
567         return false;
568       // Compare : can only have one use, and must be branch
569     } else if (!IsCompInst)
570       return false;
571   }
572   return true;
573 }
574 
575 // Collect the list of loop induction variables with respect to which it might
576 // be possible to reroll the loop.
577 void LoopReroll::collectPossibleIVs(Loop *L,
578                                     SmallInstructionVector &PossibleIVs) {
579   BasicBlock *Header = L->getHeader();
580   for (BasicBlock::iterator I = Header->begin(),
581        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
582     if (!isa<PHINode>(I))
583       continue;
584     if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
585       continue;
586 
587     if (const SCEVAddRecExpr *PHISCEV =
588             dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
589       if (PHISCEV->getLoop() != L)
590         continue;
591       if (!PHISCEV->isAffine())
592         continue;
593       const SCEVConstant *IncSCEV = nullptr;
594       if (I->getType()->isPointerTy())
595         IncSCEV =
596             getIncrmentFactorSCEV(SE, PHISCEV->getStepRecurrence(*SE), *I);
597       else
598         IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
599       if (IncSCEV) {
600         const APInt &AInt = IncSCEV->getValue()->getValue().abs();
601         if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
602           continue;
603         IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
604         DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
605                      << "\n");
606 
607         if (isLoopControlIV(L, &*I)) {
608           assert(!LoopControlIV && "Found two loop control only IV");
609           LoopControlIV = &(*I);
610           DEBUG(dbgs() << "LRR: Possible loop control only IV: " << *I << " = "
611                        << *PHISCEV << "\n");
612         } else
613           PossibleIVs.push_back(&*I);
614       }
615     }
616   }
617 }
618 
619 // Add the remainder of the reduction-variable chain to the instruction vector
620 // (the initial PHINode has already been added). If successful, the object is
621 // marked as valid.
622 void LoopReroll::SimpleLoopReduction::add(Loop *L) {
623   assert(!Valid && "Cannot add to an already-valid chain");
624 
625   // The reduction variable must be a chain of single-use instructions
626   // (including the PHI), except for the last value (which is used by the PHI
627   // and also outside the loop).
628   Instruction *C = Instructions.front();
629   if (C->user_empty())
630     return;
631 
632   do {
633     C = cast<Instruction>(*C->user_begin());
634     if (C->hasOneUse()) {
635       if (!C->isBinaryOp())
636         return;
637 
638       if (!(isa<PHINode>(Instructions.back()) ||
639             C->isSameOperationAs(Instructions.back())))
640         return;
641 
642       Instructions.push_back(C);
643     }
644   } while (C->hasOneUse());
645 
646   if (Instructions.size() < 2 ||
647       !C->isSameOperationAs(Instructions.back()) ||
648       C->use_empty())
649     return;
650 
651   // C is now the (potential) last instruction in the reduction chain.
652   for (User *U : C->users()) {
653     // The only in-loop user can be the initial PHI.
654     if (L->contains(cast<Instruction>(U)))
655       if (cast<Instruction>(U) != Instructions.front())
656         return;
657   }
658 
659   Instructions.push_back(C);
660   Valid = true;
661 }
662 
663 // Collect the vector of possible reduction variables.
664 void LoopReroll::collectPossibleReductions(Loop *L,
665   ReductionTracker &Reductions) {
666   BasicBlock *Header = L->getHeader();
667   for (BasicBlock::iterator I = Header->begin(),
668        IE = Header->getFirstInsertionPt(); I != IE; ++I) {
669     if (!isa<PHINode>(I))
670       continue;
671     if (!I->getType()->isSingleValueType())
672       continue;
673 
674     SimpleLoopReduction SLR(&*I, L);
675     if (!SLR.valid())
676       continue;
677 
678     DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
679           SLR.size() << " chained instructions)\n");
680     Reductions.addSLR(SLR);
681   }
682 }
683 
684 // Collect the set of all users of the provided root instruction. This set of
685 // users contains not only the direct users of the root instruction, but also
686 // all users of those users, and so on. There are two exceptions:
687 //
688 //   1. Instructions in the set of excluded instructions are never added to the
689 //   use set (even if they are users). This is used, for example, to exclude
690 //   including root increments in the use set of the primary IV.
691 //
692 //   2. Instructions in the set of final instructions are added to the use set
693 //   if they are users, but their users are not added. This is used, for
694 //   example, to prevent a reduction update from forcing all later reduction
695 //   updates into the use set.
696 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
697   Instruction *Root, const SmallInstructionSet &Exclude,
698   const SmallInstructionSet &Final,
699   DenseSet<Instruction *> &Users) {
700   SmallInstructionVector Queue(1, Root);
701   while (!Queue.empty()) {
702     Instruction *I = Queue.pop_back_val();
703     if (!Users.insert(I).second)
704       continue;
705 
706     if (!Final.count(I))
707       for (Use &U : I->uses()) {
708         Instruction *User = cast<Instruction>(U.getUser());
709         if (PHINode *PN = dyn_cast<PHINode>(User)) {
710           // Ignore "wrap-around" uses to PHIs of this loop's header.
711           if (PN->getIncomingBlock(U) == L->getHeader())
712             continue;
713         }
714 
715         if (L->contains(User) && !Exclude.count(User)) {
716           Queue.push_back(User);
717         }
718       }
719 
720     // We also want to collect single-user "feeder" values.
721     for (User::op_iterator OI = I->op_begin(),
722          OIE = I->op_end(); OI != OIE; ++OI) {
723       if (Instruction *Op = dyn_cast<Instruction>(*OI))
724         if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
725             !Final.count(Op))
726           Queue.push_back(Op);
727     }
728   }
729 }
730 
731 // Collect all of the users of all of the provided root instructions (combined
732 // into a single set).
733 void LoopReroll::DAGRootTracker::collectInLoopUserSet(
734   const SmallInstructionVector &Roots,
735   const SmallInstructionSet &Exclude,
736   const SmallInstructionSet &Final,
737   DenseSet<Instruction *> &Users) {
738   for (SmallInstructionVector::const_iterator I = Roots.begin(),
739        IE = Roots.end(); I != IE; ++I)
740     collectInLoopUserSet(*I, Exclude, Final, Users);
741 }
742 
743 static bool isSimpleLoadStore(Instruction *I) {
744   if (LoadInst *LI = dyn_cast<LoadInst>(I))
745     return LI->isSimple();
746   if (StoreInst *SI = dyn_cast<StoreInst>(I))
747     return SI->isSimple();
748   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
749     return !MI->isVolatile();
750   return false;
751 }
752 
753 /// Return true if IVU is a "simple" arithmetic operation.
754 /// This is used for narrowing the search space for DAGRoots; only arithmetic
755 /// and GEPs can be part of a DAGRoot.
756 static bool isSimpleArithmeticOp(User *IVU) {
757   if (Instruction *I = dyn_cast<Instruction>(IVU)) {
758     switch (I->getOpcode()) {
759     default: return false;
760     case Instruction::Add:
761     case Instruction::Sub:
762     case Instruction::Mul:
763     case Instruction::Shl:
764     case Instruction::AShr:
765     case Instruction::LShr:
766     case Instruction::GetElementPtr:
767     case Instruction::Trunc:
768     case Instruction::ZExt:
769     case Instruction::SExt:
770       return true;
771     }
772   }
773   return false;
774 }
775 
776 static bool isLoopIncrement(User *U, Instruction *IV) {
777   BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
778 
779   if ((BO && BO->getOpcode() != Instruction::Add) ||
780       (!BO && !isa<GetElementPtrInst>(U)))
781     return false;
782 
783   for (auto *UU : U->users()) {
784     PHINode *PN = dyn_cast<PHINode>(UU);
785     if (PN && PN == IV)
786       return true;
787   }
788   return false;
789 }
790 
791 bool LoopReroll::DAGRootTracker::
792 collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
793   SmallInstructionVector BaseUsers;
794 
795   for (auto *I : Base->users()) {
796     ConstantInt *CI = nullptr;
797 
798     if (isLoopIncrement(I, IV)) {
799       LoopIncs.push_back(cast<Instruction>(I));
800       continue;
801     }
802 
803     // The root nodes must be either GEPs, ORs or ADDs.
804     if (auto *BO = dyn_cast<BinaryOperator>(I)) {
805       if (BO->getOpcode() == Instruction::Add ||
806           BO->getOpcode() == Instruction::Or)
807         CI = dyn_cast<ConstantInt>(BO->getOperand(1));
808     } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
809       Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
810       CI = dyn_cast<ConstantInt>(LastOperand);
811     }
812 
813     if (!CI) {
814       if (Instruction *II = dyn_cast<Instruction>(I)) {
815         BaseUsers.push_back(II);
816         continue;
817       } else {
818         DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
819         return false;
820       }
821     }
822 
823     int64_t V = std::abs(CI->getValue().getSExtValue());
824     if (Roots.find(V) != Roots.end())
825       // No duplicates, please.
826       return false;
827 
828     Roots[V] = cast<Instruction>(I);
829   }
830 
831   if (Roots.empty())
832     return false;
833 
834   // If we found non-loop-inc, non-root users of Base, assume they are
835   // for the zeroth root index. This is because "add %a, 0" gets optimized
836   // away.
837   if (BaseUsers.size()) {
838     if (Roots.find(0) != Roots.end()) {
839       DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
840       return false;
841     }
842     Roots[0] = Base;
843   }
844 
845   // Calculate the number of users of the base, or lowest indexed, iteration.
846   unsigned NumBaseUses = BaseUsers.size();
847   if (NumBaseUses == 0)
848     NumBaseUses = Roots.begin()->second->getNumUses();
849 
850   // Check that every node has the same number of users.
851   for (auto &KV : Roots) {
852     if (KV.first == 0)
853       continue;
854     if (KV.second->getNumUses() != NumBaseUses) {
855       DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
856             << "#Base=" << NumBaseUses << ", #Root=" <<
857             KV.second->getNumUses() << "\n");
858       return false;
859     }
860   }
861 
862   return true;
863 }
864 
865 bool LoopReroll::DAGRootTracker::
866 findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
867   // Does the user look like it could be part of a root set?
868   // All its users must be simple arithmetic ops.
869   if (I->getNumUses() > IL_MaxRerollIterations)
870     return false;
871 
872   if ((I->getOpcode() == Instruction::Mul ||
873        I->getOpcode() == Instruction::PHI) &&
874       I != IV &&
875       findRootsBase(I, SubsumedInsts))
876     return true;
877 
878   SubsumedInsts.insert(I);
879 
880   for (User *V : I->users()) {
881     Instruction *I = dyn_cast<Instruction>(V);
882     if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
883       continue;
884 
885     if (!I || !isSimpleArithmeticOp(I) ||
886         !findRootsRecursive(I, SubsumedInsts))
887       return false;
888   }
889   return true;
890 }
891 
892 bool LoopReroll::DAGRootTracker::
893 findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
894 
895   // The base instruction needs to be a multiply so
896   // that we can erase it.
897   if (IVU->getOpcode() != Instruction::Mul &&
898       IVU->getOpcode() != Instruction::PHI)
899     return false;
900 
901   std::map<int64_t, Instruction*> V;
902   if (!collectPossibleRoots(IVU, V))
903     return false;
904 
905   // If we didn't get a root for index zero, then IVU must be
906   // subsumed.
907   if (V.find(0) == V.end())
908     SubsumedInsts.insert(IVU);
909 
910   // Partition the vector into monotonically increasing indexes.
911   DAGRootSet DRS;
912   DRS.BaseInst = nullptr;
913 
914   for (auto &KV : V) {
915     if (!DRS.BaseInst) {
916       DRS.BaseInst = KV.second;
917       DRS.SubsumedInsts = SubsumedInsts;
918     } else if (DRS.Roots.empty()) {
919       DRS.Roots.push_back(KV.second);
920     } else if (V.find(KV.first - 1) != V.end()) {
921       DRS.Roots.push_back(KV.second);
922     } else {
923       // Linear sequence terminated.
924       RootSets.push_back(DRS);
925       DRS.BaseInst = KV.second;
926       DRS.SubsumedInsts = SubsumedInsts;
927       DRS.Roots.clear();
928     }
929   }
930   RootSets.push_back(DRS);
931 
932   return true;
933 }
934 
935 bool LoopReroll::DAGRootTracker::findRoots() {
936   Inc = IVToIncMap[IV];
937 
938   assert(RootSets.empty() && "Unclean state!");
939   if (std::abs(Inc) == 1) {
940     for (auto *IVU : IV->users()) {
941       if (isLoopIncrement(IVU, IV))
942         LoopIncs.push_back(cast<Instruction>(IVU));
943     }
944     if (!findRootsRecursive(IV, SmallInstructionSet()))
945       return false;
946     LoopIncs.push_back(IV);
947   } else {
948     if (!findRootsBase(IV, SmallInstructionSet()))
949       return false;
950   }
951 
952   // Ensure all sets have the same size.
953   if (RootSets.empty()) {
954     DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
955     return false;
956   }
957   for (auto &V : RootSets) {
958     if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
959       DEBUG(dbgs()
960             << "LRR: Aborting because not all root sets have the same size\n");
961       return false;
962     }
963   }
964 
965   // And ensure all loop iterations are consecutive. We rely on std::map
966   // providing ordered traversal.
967   for (auto &V : RootSets) {
968     const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
969     if (!ADR)
970       return false;
971 
972     // Consider a DAGRootSet with N-1 roots (so N different values including
973     //   BaseInst).
974     // Define d = Roots[0] - BaseInst, which should be the same as
975     //   Roots[I] - Roots[I-1] for all I in [1..N).
976     // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
977     //   loop iteration J.
978     //
979     // Now, For the loop iterations to be consecutive:
980     //   D = d * N
981 
982     unsigned N = V.Roots.size() + 1;
983     const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
984     const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
985     if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
986       DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
987       return false;
988     }
989   }
990   Scale = RootSets[0].Roots.size() + 1;
991 
992   if (Scale > IL_MaxRerollIterations) {
993     DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
994           << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
995           << "\n");
996     return false;
997   }
998 
999   DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
1000 
1001   return true;
1002 }
1003 
1004 bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
1005   // Populate the MapVector with all instructions in the block, in order first,
1006   // so we can iterate over the contents later in perfect order.
1007   for (auto &I : *L->getHeader()) {
1008     Uses[&I].resize(IL_End);
1009   }
1010 
1011   SmallInstructionSet Exclude;
1012   for (auto &DRS : RootSets) {
1013     Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1014     Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1015     Exclude.insert(DRS.BaseInst);
1016   }
1017   Exclude.insert(LoopIncs.begin(), LoopIncs.end());
1018 
1019   for (auto &DRS : RootSets) {
1020     DenseSet<Instruction*> VBase;
1021     collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
1022     for (auto *I : VBase) {
1023       Uses[I].set(0);
1024     }
1025 
1026     unsigned Idx = 1;
1027     for (auto *Root : DRS.Roots) {
1028       DenseSet<Instruction*> V;
1029       collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
1030 
1031       // While we're here, check the use sets are the same size.
1032       if (V.size() != VBase.size()) {
1033         DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
1034         return false;
1035       }
1036 
1037       for (auto *I : V) {
1038         Uses[I].set(Idx);
1039       }
1040       ++Idx;
1041     }
1042 
1043     // Make sure our subsumed instructions are remembered too.
1044     for (auto *I : DRS.SubsumedInsts) {
1045       Uses[I].set(IL_All);
1046     }
1047   }
1048 
1049   // Make sure the loop increments are also accounted for.
1050 
1051   Exclude.clear();
1052   for (auto &DRS : RootSets) {
1053     Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1054     Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1055     Exclude.insert(DRS.BaseInst);
1056   }
1057 
1058   DenseSet<Instruction*> V;
1059   collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
1060   for (auto *I : V) {
1061     Uses[I].set(IL_All);
1062   }
1063 
1064   return true;
1065 
1066 }
1067 
1068 /// Get the next instruction in "In" that is a member of set Val.
1069 /// Start searching from StartI, and do not return anything in Exclude.
1070 /// If StartI is not given, start from In.begin().
1071 LoopReroll::DAGRootTracker::UsesTy::iterator
1072 LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
1073                                       const SmallInstructionSet &Exclude,
1074                                       UsesTy::iterator *StartI) {
1075   UsesTy::iterator I = StartI ? *StartI : In.begin();
1076   while (I != In.end() && (I->second.test(Val) == 0 ||
1077                            Exclude.count(I->first) != 0))
1078     ++I;
1079   return I;
1080 }
1081 
1082 bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1083   for (auto &DRS : RootSets) {
1084     if (DRS.BaseInst == I)
1085       return true;
1086   }
1087   return false;
1088 }
1089 
1090 bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1091   for (auto &DRS : RootSets) {
1092     if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
1093       return true;
1094   }
1095   return false;
1096 }
1097 
1098 /// Return true if instruction I depends on any instruction between
1099 /// Start and End.
1100 bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1101                                                 UsesTy::iterator Start,
1102                                                 UsesTy::iterator End) {
1103   for (auto *U : I->users()) {
1104     for (auto It = Start; It != End; ++It)
1105       if (U == It->first)
1106         return true;
1107   }
1108   return false;
1109 }
1110 
1111 static bool isIgnorableInst(const Instruction *I) {
1112   if (isa<DbgInfoIntrinsic>(I))
1113     return true;
1114   const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1115   if (!II)
1116     return false;
1117   switch (II->getIntrinsicID()) {
1118     default:
1119       return false;
1120     case llvm::Intrinsic::annotation:
1121     case Intrinsic::ptr_annotation:
1122     case Intrinsic::var_annotation:
1123     // TODO: the following intrinsics may also be whitelisted:
1124     //   lifetime_start, lifetime_end, invariant_start, invariant_end
1125       return true;
1126   }
1127   return false;
1128 }
1129 
1130 bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
1131   // We now need to check for equivalence of the use graph of each root with
1132   // that of the primary induction variable (excluding the roots). Our goal
1133   // here is not to solve the full graph isomorphism problem, but rather to
1134   // catch common cases without a lot of work. As a result, we will assume
1135   // that the relative order of the instructions in each unrolled iteration
1136   // is the same (although we will not make an assumption about how the
1137   // different iterations are intermixed). Note that while the order must be
1138   // the same, the instructions may not be in the same basic block.
1139 
1140   // An array of just the possible reductions for this scale factor. When we
1141   // collect the set of all users of some root instructions, these reduction
1142   // instructions are treated as 'final' (their uses are not considered).
1143   // This is important because we don't want the root use set to search down
1144   // the reduction chain.
1145   SmallInstructionSet PossibleRedSet;
1146   SmallInstructionSet PossibleRedLastSet;
1147   SmallInstructionSet PossibleRedPHISet;
1148   Reductions.restrictToScale(Scale, PossibleRedSet,
1149                              PossibleRedPHISet, PossibleRedLastSet);
1150 
1151   // Populate "Uses" with where each instruction is used.
1152   if (!collectUsedInstructions(PossibleRedSet))
1153     return false;
1154 
1155   // Make sure we mark the reduction PHIs as used in all iterations.
1156   for (auto *I : PossibleRedPHISet) {
1157     Uses[I].set(IL_All);
1158   }
1159 
1160   // Make sure we mark loop-control-only PHIs as used in all iterations. See
1161   // comment above LoopReroll::isLoopControlIV for more information.
1162   BasicBlock *Header = L->getHeader();
1163   if (LoopControlIV && LoopControlIV != IV) {
1164     for (auto *U : LoopControlIV->users()) {
1165       Instruction *IVUser = dyn_cast<Instruction>(U);
1166       // IVUser could be loop increment or compare
1167       Uses[IVUser].set(IL_All);
1168       for (auto *UU : IVUser->users()) {
1169         Instruction *UUser = dyn_cast<Instruction>(UU);
1170         // UUser could be compare, PHI or branch
1171         Uses[UUser].set(IL_All);
1172         // Skip SExt
1173         if (isa<SExtInst>(UUser)) {
1174           UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
1175           Uses[UUser].set(IL_All);
1176         }
1177         // Is UUser a compare instruction?
1178         if (UU->hasOneUse()) {
1179           Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
1180           if (BI == cast<BranchInst>(Header->getTerminator()))
1181             Uses[BI].set(IL_All);
1182         }
1183       }
1184     }
1185   }
1186 
1187   // Make sure all instructions in the loop are in one and only one
1188   // set.
1189   for (auto &KV : Uses) {
1190     if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
1191       DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1192             << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1193       return false;
1194     }
1195   }
1196 
1197   DEBUG(
1198     for (auto &KV : Uses) {
1199       dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1200     }
1201     );
1202 
1203   for (unsigned Iter = 1; Iter < Scale; ++Iter) {
1204     // In addition to regular aliasing information, we need to look for
1205     // instructions from later (future) iterations that have side effects
1206     // preventing us from reordering them past other instructions with side
1207     // effects.
1208     bool FutureSideEffects = false;
1209     AliasSetTracker AST(*AA);
1210     // The map between instructions in f(%iv.(i+1)) and f(%iv).
1211     DenseMap<Value *, Value *> BaseMap;
1212 
1213     // Compare iteration Iter to the base.
1214     SmallInstructionSet Visited;
1215     auto BaseIt = nextInstr(0, Uses, Visited);
1216     auto RootIt = nextInstr(Iter, Uses, Visited);
1217     auto LastRootIt = Uses.begin();
1218 
1219     while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1220       Instruction *BaseInst = BaseIt->first;
1221       Instruction *RootInst = RootIt->first;
1222 
1223       // Skip over the IV or root instructions; only match their users.
1224       bool Continue = false;
1225       if (isBaseInst(BaseInst)) {
1226         Visited.insert(BaseInst);
1227         BaseIt = nextInstr(0, Uses, Visited);
1228         Continue = true;
1229       }
1230       if (isRootInst(RootInst)) {
1231         LastRootIt = RootIt;
1232         Visited.insert(RootInst);
1233         RootIt = nextInstr(Iter, Uses, Visited);
1234         Continue = true;
1235       }
1236       if (Continue) continue;
1237 
1238       if (!BaseInst->isSameOperationAs(RootInst)) {
1239         // Last chance saloon. We don't try and solve the full isomorphism
1240         // problem, but try and at least catch the case where two instructions
1241         // *of different types* are round the wrong way. We won't be able to
1242         // efficiently tell, given two ADD instructions, which way around we
1243         // should match them, but given an ADD and a SUB, we can at least infer
1244         // which one is which.
1245         //
1246         // This should allow us to deal with a greater subset of the isomorphism
1247         // problem. It does however change a linear algorithm into a quadratic
1248         // one, so limit the number of probes we do.
1249         auto TryIt = RootIt;
1250         unsigned N = NumToleratedFailedMatches;
1251         while (TryIt != Uses.end() &&
1252                !BaseInst->isSameOperationAs(TryIt->first) &&
1253                N--) {
1254           ++TryIt;
1255           TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1256         }
1257 
1258         if (TryIt == Uses.end() || TryIt == RootIt ||
1259             instrDependsOn(TryIt->first, RootIt, TryIt)) {
1260           DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1261                 " vs. " << *RootInst << "\n");
1262           return false;
1263         }
1264 
1265         RootIt = TryIt;
1266         RootInst = TryIt->first;
1267       }
1268 
1269       // All instructions between the last root and this root
1270       // may belong to some other iteration. If they belong to a
1271       // future iteration, then they're dangerous to alias with.
1272       //
1273       // Note that because we allow a limited amount of flexibility in the order
1274       // that we visit nodes, LastRootIt might be *before* RootIt, in which
1275       // case we've already checked this set of instructions so we shouldn't
1276       // do anything.
1277       for (; LastRootIt < RootIt; ++LastRootIt) {
1278         Instruction *I = LastRootIt->first;
1279         if (LastRootIt->second.find_first() < (int)Iter)
1280           continue;
1281         if (I->mayWriteToMemory())
1282           AST.add(I);
1283         // Note: This is specifically guarded by a check on isa<PHINode>,
1284         // which while a valid (somewhat arbitrary) micro-optimization, is
1285         // needed because otherwise isSafeToSpeculativelyExecute returns
1286         // false on PHI nodes.
1287         if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
1288             !isSafeToSpeculativelyExecute(I))
1289           // Intervening instructions cause side effects.
1290           FutureSideEffects = true;
1291       }
1292 
1293       // Make sure that this instruction, which is in the use set of this
1294       // root instruction, does not also belong to the base set or the set of
1295       // some other root instruction.
1296       if (RootIt->second.count() > 1) {
1297         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1298                         " vs. " << *RootInst << " (prev. case overlap)\n");
1299         return false;
1300       }
1301 
1302       // Make sure that we don't alias with any instruction in the alias set
1303       // tracker. If we do, then we depend on a future iteration, and we
1304       // can't reroll.
1305       if (RootInst->mayReadFromMemory())
1306         for (auto &K : AST) {
1307           if (K.aliasesUnknownInst(RootInst, *AA)) {
1308             DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1309                             " vs. " << *RootInst << " (depends on future store)\n");
1310             return false;
1311           }
1312         }
1313 
1314       // If we've past an instruction from a future iteration that may have
1315       // side effects, and this instruction might also, then we can't reorder
1316       // them, and this matching fails. As an exception, we allow the alias
1317       // set tracker to handle regular (simple) load/store dependencies.
1318       if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
1319                                  !isSafeToSpeculativelyExecute(BaseInst)) ||
1320                                 (!isSimpleLoadStore(RootInst) &&
1321                                  !isSafeToSpeculativelyExecute(RootInst)))) {
1322         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1323                         " vs. " << *RootInst <<
1324                         " (side effects prevent reordering)\n");
1325         return false;
1326       }
1327 
1328       // For instructions that are part of a reduction, if the operation is
1329       // associative, then don't bother matching the operands (because we
1330       // already know that the instructions are isomorphic, and the order
1331       // within the iteration does not matter). For non-associative reductions,
1332       // we do need to match the operands, because we need to reject
1333       // out-of-order instructions within an iteration!
1334       // For example (assume floating-point addition), we need to reject this:
1335       //   x += a[i]; x += b[i];
1336       //   x += a[i+1]; x += b[i+1];
1337       //   x += b[i+2]; x += a[i+2];
1338       bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
1339 
1340       if (!(InReduction && BaseInst->isAssociative())) {
1341         bool Swapped = false, SomeOpMatched = false;
1342         for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1343           Value *Op2 = RootInst->getOperand(j);
1344 
1345           // If this is part of a reduction (and the operation is not
1346           // associatve), then we match all operands, but not those that are
1347           // part of the reduction.
1348           if (InReduction)
1349             if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
1350               if (Reductions.isPairInSame(RootInst, Op2I))
1351                 continue;
1352 
1353           DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
1354           if (BMI != BaseMap.end()) {
1355             Op2 = BMI->second;
1356           } else {
1357             for (auto &DRS : RootSets) {
1358               if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1359                 Op2 = DRS.BaseInst;
1360                 break;
1361               }
1362             }
1363           }
1364 
1365           if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
1366             // If we've not already decided to swap the matched operands, and
1367             // we've not already matched our first operand (note that we could
1368             // have skipped matching the first operand because it is part of a
1369             // reduction above), and the instruction is commutative, then try
1370             // the swapped match.
1371             if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1372                 BaseInst->getOperand(!j) == Op2) {
1373               Swapped = true;
1374             } else {
1375               DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1376                     << " vs. " << *RootInst << " (operand " << j << ")\n");
1377               return false;
1378             }
1379           }
1380 
1381           SomeOpMatched = true;
1382         }
1383       }
1384 
1385       if ((!PossibleRedLastSet.count(BaseInst) &&
1386            hasUsesOutsideLoop(BaseInst, L)) ||
1387           (!PossibleRedLastSet.count(RootInst) &&
1388            hasUsesOutsideLoop(RootInst, L))) {
1389         DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1390                         " vs. " << *RootInst << " (uses outside loop)\n");
1391         return false;
1392       }
1393 
1394       Reductions.recordPair(BaseInst, RootInst, Iter);
1395       BaseMap.insert(std::make_pair(RootInst, BaseInst));
1396 
1397       LastRootIt = RootIt;
1398       Visited.insert(BaseInst);
1399       Visited.insert(RootInst);
1400       BaseIt = nextInstr(0, Uses, Visited);
1401       RootIt = nextInstr(Iter, Uses, Visited);
1402     }
1403     assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1404             "Mismatched set sizes!");
1405   }
1406 
1407   DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
1408                   *IV << "\n");
1409 
1410   return true;
1411 }
1412 
1413 void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1414   BasicBlock *Header = L->getHeader();
1415   // Remove instructions associated with non-base iterations.
1416   for (BasicBlock::reverse_iterator J = Header->rbegin();
1417        J != Header->rend();) {
1418     unsigned I = Uses[&*J].find_first();
1419     if (I > 0 && I < IL_All) {
1420       Instruction *D = &*J;
1421       DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1422       D->eraseFromParent();
1423       continue;
1424     }
1425 
1426     ++J;
1427   }
1428 
1429   bool HasTwoIVs = LoopControlIV && LoopControlIV != IV;
1430 
1431   if (HasTwoIVs) {
1432     updateNonLoopCtrlIncr();
1433     replaceIV(LoopControlIV, LoopControlIV, IterCount);
1434   } else
1435     // We need to create a new induction variable for each different BaseInst.
1436     for (auto &DRS : RootSets)
1437       // Insert the new induction variable.
1438       replaceIV(DRS.BaseInst, IV, IterCount);
1439 
1440   SimplifyInstructionsInBlock(Header, TLI);
1441   DeleteDeadPHIs(Header, TLI);
1442 }
1443 
1444 // For non-loop-control IVs, we only need to update the last increment
1445 // with right amount, then we are done.
1446 void LoopReroll::DAGRootTracker::updateNonLoopCtrlIncr() {
1447   const SCEV *NewInc = nullptr;
1448   for (auto *LoopInc : LoopIncs) {
1449     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LoopInc);
1450     const SCEVConstant *COp = nullptr;
1451     if (GEP && LoopInc->getOperand(0)->getType()->isPointerTy()) {
1452       COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1453     } else {
1454       COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(0)));
1455       if (!COp)
1456         COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1457     }
1458 
1459     assert(COp && "Didn't find constant operand of LoopInc!\n");
1460 
1461     const APInt &AInt = COp->getValue()->getValue();
1462     const SCEV *ScaleSCEV = SE->getConstant(COp->getType(), Scale);
1463     if (AInt.isNegative()) {
1464       NewInc = SE->getNegativeSCEV(COp);
1465       NewInc = SE->getUDivExpr(NewInc, ScaleSCEV);
1466       NewInc = SE->getNegativeSCEV(NewInc);
1467     } else
1468       NewInc = SE->getUDivExpr(COp, ScaleSCEV);
1469 
1470     LoopInc->setOperand(1, dyn_cast<SCEVConstant>(NewInc)->getValue());
1471   }
1472 }
1473 
1474 void LoopReroll::DAGRootTracker::replaceIV(Instruction *Inst,
1475                                            Instruction *InstIV,
1476                                            const SCEV *IterCount) {
1477   BasicBlock *Header = L->getHeader();
1478   int64_t Inc = IVToIncMap[InstIV];
1479   bool NeedNewIV = InstIV == LoopControlIV;
1480   bool Negative = !NeedNewIV && Inc < 0;
1481 
1482   const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Inst));
1483   const SCEV *Start = RealIVSCEV->getStart();
1484 
1485   if (NeedNewIV)
1486     Start = SE->getConstant(Start->getType(), 0);
1487 
1488   const SCEV *SizeOfExpr = nullptr;
1489   const SCEV *IncrExpr =
1490       SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1);
1491   if (auto *PTy = dyn_cast<PointerType>(Inst->getType())) {
1492     Type *ElTy = PTy->getElementType();
1493     SizeOfExpr =
1494         SE->getSizeOfExpr(SE->getEffectiveSCEVType(Inst->getType()), ElTy);
1495     IncrExpr = SE->getMulExpr(IncrExpr, SizeOfExpr);
1496   }
1497   const SCEV *NewIVSCEV =
1498       SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1499 
1500   { // Limit the lifetime of SCEVExpander.
1501     const DataLayout &DL = Header->getModule()->getDataLayout();
1502     SCEVExpander Expander(*SE, DL, "reroll");
1503     Value *NewIV =
1504         Expander.expandCodeFor(NewIVSCEV, InstIV->getType(), &Header->front());
1505 
1506     for (auto &KV : Uses)
1507       if (KV.second.find_first() == 0)
1508         KV.first->replaceUsesOfWith(Inst, NewIV);
1509 
1510     if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1511       // FIXME: Why do we need this check?
1512       if (Uses[BI].find_first() == IL_All) {
1513         const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1514 
1515         if (NeedNewIV)
1516           ICSCEV = SE->getMulExpr(IterCount,
1517                                   SE->getConstant(IterCount->getType(), Scale));
1518 
1519         // Iteration count SCEV minus or plus 1
1520         const SCEV *MinusPlus1SCEV =
1521             SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1);
1522         if (Inst->getType()->isPointerTy()) {
1523           assert(SizeOfExpr && "SizeOfExpr is not initialized");
1524           MinusPlus1SCEV = SE->getMulExpr(MinusPlus1SCEV, SizeOfExpr);
1525         }
1526 
1527         const SCEV *ICMinusPlus1SCEV = SE->getMinusSCEV(ICSCEV, MinusPlus1SCEV);
1528         // Iteration count minus 1
1529         Instruction *InsertPtr = nullptr;
1530         if (isa<SCEVConstant>(ICMinusPlus1SCEV)) {
1531           InsertPtr = BI;
1532         } else {
1533           BasicBlock *Preheader = L->getLoopPreheader();
1534           if (!Preheader)
1535             Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
1536           InsertPtr = Preheader->getTerminator();
1537         }
1538 
1539         if (!isa<PointerType>(NewIV->getType()) && NeedNewIV &&
1540             (SE->getTypeSizeInBits(NewIV->getType()) <
1541              SE->getTypeSizeInBits(ICMinusPlus1SCEV->getType()))) {
1542           IRBuilder<> Builder(BI);
1543           Builder.SetCurrentDebugLocation(BI->getDebugLoc());
1544           NewIV = Builder.CreateSExt(NewIV, ICMinusPlus1SCEV->getType());
1545         }
1546         Value *ICMinusPlus1 = Expander.expandCodeFor(
1547             ICMinusPlus1SCEV, NewIV->getType(), InsertPtr);
1548 
1549         Value *Cond =
1550             new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinusPlus1, "exitcond");
1551         BI->setCondition(Cond);
1552 
1553         if (BI->getSuccessor(1) != Header)
1554           BI->swapSuccessors();
1555       }
1556     }
1557   }
1558 }
1559 
1560 // Validate the selected reductions. All iterations must have an isomorphic
1561 // part of the reduction chain and, for non-associative reductions, the chain
1562 // entries must appear in order.
1563 bool LoopReroll::ReductionTracker::validateSelected() {
1564   // For a non-associative reduction, the chain entries must appear in order.
1565   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1566        RI != RIE; ++RI) {
1567     int i = *RI;
1568     int PrevIter = 0, BaseCount = 0, Count = 0;
1569     for (Instruction *J : PossibleReds[i]) {
1570       // Note that all instructions in the chain must have been found because
1571       // all instructions in the function must have been assigned to some
1572       // iteration.
1573       int Iter = PossibleRedIter[J];
1574       if (Iter != PrevIter && Iter != PrevIter + 1 &&
1575           !PossibleReds[i].getReducedValue()->isAssociative()) {
1576         DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
1577                         J << "\n");
1578         return false;
1579       }
1580 
1581       if (Iter != PrevIter) {
1582         if (Count != BaseCount) {
1583           DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1584                 " reduction use count " << Count <<
1585                 " is not equal to the base use count " <<
1586                 BaseCount << "\n");
1587           return false;
1588         }
1589 
1590         Count = 0;
1591       }
1592 
1593       ++Count;
1594       if (Iter == 0)
1595         ++BaseCount;
1596 
1597       PrevIter = Iter;
1598     }
1599   }
1600 
1601   return true;
1602 }
1603 
1604 // For all selected reductions, remove all parts except those in the first
1605 // iteration (and the PHI). Replace outside uses of the reduced value with uses
1606 // of the first-iteration reduced value (in other words, reroll the selected
1607 // reductions).
1608 void LoopReroll::ReductionTracker::replaceSelected() {
1609   // Fixup reductions to refer to the last instruction associated with the
1610   // first iteration (not the last).
1611   for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1612        RI != RIE; ++RI) {
1613     int i = *RI;
1614     int j = 0;
1615     for (int e = PossibleReds[i].size(); j != e; ++j)
1616       if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1617         --j;
1618         break;
1619       }
1620 
1621     // Replace users with the new end-of-chain value.
1622     SmallInstructionVector Users;
1623     for (User *U : PossibleReds[i].getReducedValue()->users()) {
1624       Users.push_back(cast<Instruction>(U));
1625     }
1626 
1627     for (SmallInstructionVector::iterator J = Users.begin(),
1628          JE = Users.end(); J != JE; ++J)
1629       (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1630                               PossibleReds[i][j]);
1631   }
1632 }
1633 
1634 // Reroll the provided loop with respect to the provided induction variable.
1635 // Generally, we're looking for a loop like this:
1636 //
1637 // %iv = phi [ (preheader, ...), (body, %iv.next) ]
1638 // f(%iv)
1639 // %iv.1 = add %iv, 1                <-- a root increment
1640 // f(%iv.1)
1641 // %iv.2 = add %iv, 2                <-- a root increment
1642 // f(%iv.2)
1643 // %iv.scale_m_1 = add %iv, scale-1  <-- a root increment
1644 // f(%iv.scale_m_1)
1645 // ...
1646 // %iv.next = add %iv, scale
1647 // %cmp = icmp(%iv, ...)
1648 // br %cmp, header, exit
1649 //
1650 // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1651 // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1652 // be intermixed with eachother. The restriction imposed by this algorithm is
1653 // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1654 // etc. be the same.
1655 //
1656 // First, we collect the use set of %iv, excluding the other increment roots.
1657 // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1658 // times, having collected the use set of f(%iv.(i+1)), during which we:
1659 //   - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1660 //     the next unmatched instruction in f(%iv.(i+1)).
1661 //   - Ensure that both matched instructions don't have any external users
1662 //     (with the exception of last-in-chain reduction instructions).
1663 //   - Track the (aliasing) write set, and other side effects, of all
1664 //     instructions that belong to future iterations that come before the matched
1665 //     instructions. If the matched instructions read from that write set, then
1666 //     f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1667 //     f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1668 //     if any of these future instructions had side effects (could not be
1669 //     speculatively executed), and so do the matched instructions, when we
1670 //     cannot reorder those side-effect-producing instructions, and rerolling
1671 //     fails.
1672 //
1673 // Finally, we make sure that all loop instructions are either loop increment
1674 // roots, belong to simple latch code, parts of validated reductions, part of
1675 // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1676 // have been validated), then we reroll the loop.
1677 bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1678                         const SCEV *IterCount,
1679                         ReductionTracker &Reductions) {
1680   DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
1681                           IVToIncMap, LoopControlIV);
1682 
1683   if (!DAGRoots.findRoots())
1684     return false;
1685   DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
1686                   *IV << "\n");
1687 
1688   if (!DAGRoots.validate(Reductions))
1689     return false;
1690   if (!Reductions.validateSelected())
1691     return false;
1692   // At this point, we've validated the rerolling, and we're committed to
1693   // making changes!
1694 
1695   Reductions.replaceSelected();
1696   DAGRoots.replace(IterCount);
1697 
1698   ++NumRerolledLoops;
1699   return true;
1700 }
1701 
1702 bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
1703   if (skipLoop(L))
1704     return false;
1705 
1706   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1707   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1708   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1709   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1710   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1711   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1712 
1713   BasicBlock *Header = L->getHeader();
1714   DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1715         "] Loop %" << Header->getName() << " (" <<
1716         L->getNumBlocks() << " block(s))\n");
1717 
1718   // For now, we'll handle only single BB loops.
1719   if (L->getNumBlocks() > 1)
1720     return false;
1721 
1722   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1723     return false;
1724 
1725   const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
1726   const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
1727   DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
1728   DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1729 
1730   // First, we need to find the induction variable with respect to which we can
1731   // reroll (there may be several possible options).
1732   SmallInstructionVector PossibleIVs;
1733   IVToIncMap.clear();
1734   LoopControlIV = nullptr;
1735   collectPossibleIVs(L, PossibleIVs);
1736 
1737   if (PossibleIVs.empty()) {
1738     DEBUG(dbgs() << "LRR: No possible IVs found\n");
1739     return false;
1740   }
1741 
1742   ReductionTracker Reductions;
1743   collectPossibleReductions(L, Reductions);
1744   bool Changed = false;
1745 
1746   // For each possible IV, collect the associated possible set of 'root' nodes
1747   // (i+1, i+2, etc.).
1748   for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1749        IE = PossibleIVs.end(); I != IE; ++I)
1750     if (reroll(*I, L, Header, IterCount, Reductions)) {
1751       Changed = true;
1752       break;
1753     }
1754   DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
1755 
1756   // Trip count of L has changed so SE must be re-evaluated.
1757   if (Changed)
1758     SE->forgetLoop(L);
1759 
1760   return Changed;
1761 }
1762