Move SCEV::isLoopInvariant and hasComputableLoopEvolution to be member
[oota-llvm.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
13 //
14 // This transformation makes the following changes to each loop with an
15 // identifiable induction variable:
16 //   1. All loops are transformed to have a SINGLE canonical induction variable
17 //      which starts at zero and steps by one.
18 //   2. The canonical induction variable is guaranteed to be the first PHI node
19 //      in the loop header block.
20 //   3. The canonical induction variable is guaranteed to be in a wide enough
21 //      type so that IV expressions need not be (directly) zero-extended or
22 //      sign-extended.
23 //   4. Any pointer arithmetic recurrences are raised to use array subscripts.
24 //
25 // If the trip count of a loop is computable, this pass also makes the following
26 // changes:
27 //   1. The exit condition for the loop is canonicalized to compare the
28 //      induction value against the exit value.  This turns loops like:
29 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30 //   2. Any use outside of the loop of an expression derived from the indvar
31 //      is changed to compute the derived value outside of the loop, eliminating
32 //      the dependence on the exit value of the induction variable.  If the only
33 //      purpose of the loop is to compute the exit value of some derived
34 //      expression, this transformation will make the loop dead.
35 //
36 // This transformation should be followed by strength reduction after all of the
37 // desired loop transformations have been performed.
38 //
39 //===----------------------------------------------------------------------===//
40
41 #define DEBUG_TYPE "indvars"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/BasicBlock.h"
44 #include "llvm/Constants.h"
45 #include "llvm/Instructions.h"
46 #include "llvm/IntrinsicInst.h"
47 #include "llvm/LLVMContext.h"
48 #include "llvm/Type.h"
49 #include "llvm/Analysis/Dominators.h"
50 #include "llvm/Analysis/IVUsers.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Support/CFG.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
63 using namespace llvm;
64
65 STATISTIC(NumRemoved , "Number of aux indvars removed");
66 STATISTIC(NumInserted, "Number of canonical indvars added");
67 STATISTIC(NumReplaced, "Number of exit values replaced");
68 STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
69
70 namespace {
71   class IndVarSimplify : public LoopPass {
72     IVUsers         *IU;
73     LoopInfo        *LI;
74     ScalarEvolution *SE;
75     DominatorTree   *DT;
76     bool Changed;
77   public:
78
79     static char ID; // Pass identification, replacement for typeid
80     IndVarSimplify() : LoopPass(ID) {
81       initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
82     }
83
84     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
85
86     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87       AU.addRequired<DominatorTree>();
88       AU.addRequired<LoopInfo>();
89       AU.addRequired<ScalarEvolution>();
90       AU.addRequiredID(LoopSimplifyID);
91       AU.addRequiredID(LCSSAID);
92       AU.addRequired<IVUsers>();
93       AU.addPreserved<ScalarEvolution>();
94       AU.addPreservedID(LoopSimplifyID);
95       AU.addPreservedID(LCSSAID);
96       AU.addPreserved<IVUsers>();
97       AU.setPreservesCFG();
98     }
99
100   private:
101
102     void EliminateIVComparisons();
103     void EliminateIVRemainders();
104     void RewriteNonIntegerIVs(Loop *L);
105
106     ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
107                                    PHINode *IndVar,
108                                    BasicBlock *ExitingBlock,
109                                    BranchInst *BI,
110                                    SCEVExpander &Rewriter);
111     void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
112
113     void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
114
115     void SinkUnusedInvariants(Loop *L);
116
117     void HandleFloatingPointIV(Loop *L, PHINode *PH);
118   };
119 }
120
121 char IndVarSimplify::ID = 0;
122 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
123                 "Canonicalize Induction Variables", false, false)
124 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
125 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
126 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
127 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
128 INITIALIZE_PASS_DEPENDENCY(LCSSA)
129 INITIALIZE_PASS_DEPENDENCY(IVUsers)
130 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
131                 "Canonicalize Induction Variables", false, false)
132
133 Pass *llvm::createIndVarSimplifyPass() {
134   return new IndVarSimplify();
135 }
136
137 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
138 /// loop to be a canonical != comparison against the incremented loop induction
139 /// variable.  This pass is able to rewrite the exit tests of any loop where the
140 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
141 /// is actually a much broader range than just linear tests.
142 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
143                                    const SCEV *BackedgeTakenCount,
144                                    PHINode *IndVar,
145                                    BasicBlock *ExitingBlock,
146                                    BranchInst *BI,
147                                    SCEVExpander &Rewriter) {
148   // Special case: If the backedge-taken count is a UDiv, it's very likely a
149   // UDiv that ScalarEvolution produced in order to compute a precise
150   // expression, rather than a UDiv from the user's code. If we can't find a
151   // UDiv in the code with some simple searching, assume the former and forego
152   // rewriting the loop.
153   if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
154     ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
155     if (!OrigCond) return 0;
156     const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
157     R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
158     if (R != BackedgeTakenCount) {
159       const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
160       L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
161       if (L != BackedgeTakenCount)
162         return 0;
163     }
164   }
165
166   // If the exiting block is not the same as the backedge block, we must compare
167   // against the preincremented value, otherwise we prefer to compare against
168   // the post-incremented value.
169   Value *CmpIndVar;
170   const SCEV *RHS = BackedgeTakenCount;
171   if (ExitingBlock == L->getLoopLatch()) {
172     // Add one to the "backedge-taken" count to get the trip count.
173     // If this addition may overflow, we have to be more pessimistic and
174     // cast the induction variable before doing the add.
175     const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
176     const SCEV *N =
177       SE->getAddExpr(BackedgeTakenCount,
178                      SE->getConstant(BackedgeTakenCount->getType(), 1));
179     if ((isa<SCEVConstant>(N) && !N->isZero()) ||
180         SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
181       // No overflow. Cast the sum.
182       RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
183     } else {
184       // Potential overflow. Cast before doing the add.
185       RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
186                                         IndVar->getType());
187       RHS = SE->getAddExpr(RHS,
188                            SE->getConstant(IndVar->getType(), 1));
189     }
190
191     // The BackedgeTaken expression contains the number of times that the
192     // backedge branches to the loop header.  This is one less than the
193     // number of times the loop executes, so use the incremented indvar.
194     CmpIndVar = IndVar->getIncomingValueForBlock(ExitingBlock);
195   } else {
196     // We have to use the preincremented value...
197     RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
198                                       IndVar->getType());
199     CmpIndVar = IndVar;
200   }
201
202   // Expand the code for the iteration count.
203   assert(SE->isLoopInvariant(RHS, L) &&
204          "Computed iteration count is not loop invariant!");
205   Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
206
207   // Insert a new icmp_ne or icmp_eq instruction before the branch.
208   ICmpInst::Predicate Opcode;
209   if (L->contains(BI->getSuccessor(0)))
210     Opcode = ICmpInst::ICMP_NE;
211   else
212     Opcode = ICmpInst::ICMP_EQ;
213
214   DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
215                << "      LHS:" << *CmpIndVar << '\n'
216                << "       op:\t"
217                << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
218                << "      RHS:\t" << *RHS << "\n");
219
220   ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
221
222   Value *OrigCond = BI->getCondition();
223   // It's tempting to use replaceAllUsesWith here to fully replace the old
224   // comparison, but that's not immediately safe, since users of the old
225   // comparison may not be dominated by the new comparison. Instead, just
226   // update the branch to use the new comparison; in the common case this
227   // will make old comparison dead.
228   BI->setCondition(Cond);
229   RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
230
231   ++NumLFTR;
232   Changed = true;
233   return Cond;
234 }
235
236 /// RewriteLoopExitValues - Check to see if this loop has a computable
237 /// loop-invariant execution count.  If so, this means that we can compute the
238 /// final value of any expressions that are recurrent in the loop, and
239 /// substitute the exit values from the loop into any instructions outside of
240 /// the loop that use the final values of the current expressions.
241 ///
242 /// This is mostly redundant with the regular IndVarSimplify activities that
243 /// happen later, except that it's more powerful in some cases, because it's
244 /// able to brute-force evaluate arbitrary instructions as long as they have
245 /// constant operands at the beginning of the loop.
246 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
247                                            SCEVExpander &Rewriter) {
248   // Verify the input to the pass in already in LCSSA form.
249   assert(L->isLCSSAForm(*DT));
250
251   SmallVector<BasicBlock*, 8> ExitBlocks;
252   L->getUniqueExitBlocks(ExitBlocks);
253
254   // Find all values that are computed inside the loop, but used outside of it.
255   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
256   // the exit blocks of the loop to find them.
257   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
258     BasicBlock *ExitBB = ExitBlocks[i];
259
260     // If there are no PHI nodes in this exit block, then no values defined
261     // inside the loop are used on this path, skip it.
262     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
263     if (!PN) continue;
264
265     unsigned NumPreds = PN->getNumIncomingValues();
266
267     // Iterate over all of the PHI nodes.
268     BasicBlock::iterator BBI = ExitBB->begin();
269     while ((PN = dyn_cast<PHINode>(BBI++))) {
270       if (PN->use_empty())
271         continue; // dead use, don't replace it
272
273       // SCEV only supports integer expressions for now.
274       if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
275         continue;
276
277       // It's necessary to tell ScalarEvolution about this explicitly so that
278       // it can walk the def-use list and forget all SCEVs, as it may not be
279       // watching the PHI itself. Once the new exit value is in place, there
280       // may not be a def-use connection between the loop and every instruction
281       // which got a SCEVAddRecExpr for that loop.
282       SE->forgetValue(PN);
283
284       // Iterate over all of the values in all the PHI nodes.
285       for (unsigned i = 0; i != NumPreds; ++i) {
286         // If the value being merged in is not integer or is not defined
287         // in the loop, skip it.
288         Value *InVal = PN->getIncomingValue(i);
289         if (!isa<Instruction>(InVal))
290           continue;
291
292         // If this pred is for a subloop, not L itself, skip it.
293         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
294           continue; // The Block is in a subloop, skip it.
295
296         // Check that InVal is defined in the loop.
297         Instruction *Inst = cast<Instruction>(InVal);
298         if (!L->contains(Inst))
299           continue;
300
301         // Okay, this instruction has a user outside of the current loop
302         // and varies predictably *inside* the loop.  Evaluate the value it
303         // contains when the loop exits, if possible.
304         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
305         if (!SE->isLoopInvariant(ExitValue, L))
306           continue;
307
308         Changed = true;
309         ++NumReplaced;
310
311         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
312
313         DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
314                      << "  LoopVal = " << *Inst << "\n");
315
316         PN->setIncomingValue(i, ExitVal);
317
318         // If this instruction is dead now, delete it.
319         RecursivelyDeleteTriviallyDeadInstructions(Inst);
320
321         if (NumPreds == 1) {
322           // Completely replace a single-pred PHI. This is safe, because the
323           // NewVal won't be variant in the loop, so we don't need an LCSSA phi
324           // node anymore.
325           PN->replaceAllUsesWith(ExitVal);
326           RecursivelyDeleteTriviallyDeadInstructions(PN);
327         }
328       }
329       if (NumPreds != 1) {
330         // Clone the PHI and delete the original one. This lets IVUsers and
331         // any other maps purge the original user from their records.
332         PHINode *NewPN = cast<PHINode>(PN->clone());
333         NewPN->takeName(PN);
334         NewPN->insertBefore(PN);
335         PN->replaceAllUsesWith(NewPN);
336         PN->eraseFromParent();
337       }
338     }
339   }
340
341   // The insertion point instruction may have been deleted; clear it out
342   // so that the rewriter doesn't trip over it later.
343   Rewriter.clearInsertPoint();
344 }
345
346 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
347   // First step.  Check to see if there are any floating-point recurrences.
348   // If there are, change them into integer recurrences, permitting analysis by
349   // the SCEV routines.
350   //
351   BasicBlock *Header    = L->getHeader();
352
353   SmallVector<WeakVH, 8> PHIs;
354   for (BasicBlock::iterator I = Header->begin();
355        PHINode *PN = dyn_cast<PHINode>(I); ++I)
356     PHIs.push_back(PN);
357
358   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
359     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
360       HandleFloatingPointIV(L, PN);
361
362   // If the loop previously had floating-point IV, ScalarEvolution
363   // may not have been able to compute a trip count. Now that we've done some
364   // re-writing, the trip count may be computable.
365   if (Changed)
366     SE->forgetLoop(L);
367 }
368
369 void IndVarSimplify::EliminateIVComparisons() {
370   SmallVector<WeakVH, 16> DeadInsts;
371
372   // Look for ICmp users.
373   for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
374     IVStrideUse &UI = *I;
375     ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
376     if (!ICmp) continue;
377
378     bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
379     ICmpInst::Predicate Pred = ICmp->getPredicate();
380     if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
381
382     // Get the SCEVs for the ICmp operands.
383     const SCEV *S = IU->getReplacementExpr(UI);
384     const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
385
386     // Simplify unnecessary loops away.
387     const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
388     S = SE->getSCEVAtScope(S, ICmpLoop);
389     X = SE->getSCEVAtScope(X, ICmpLoop);
390
391     // If the condition is always true or always false, replace it with
392     // a constant value.
393     if (SE->isKnownPredicate(Pred, S, X))
394       ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
395     else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
396       ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
397     else
398       continue;
399
400     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
401     DeadInsts.push_back(ICmp);
402   }
403
404   // Now that we're done iterating through lists, clean up any instructions
405   // which are now dead.
406   while (!DeadInsts.empty())
407     if (Instruction *Inst =
408         dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
409       RecursivelyDeleteTriviallyDeadInstructions(Inst);
410 }
411
412 void IndVarSimplify::EliminateIVRemainders() {
413   SmallVector<WeakVH, 16> DeadInsts;
414
415   // Look for SRem and URem users.
416   for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
417     IVStrideUse &UI = *I;
418     BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
419     if (!Rem) continue;
420
421     bool isSigned = Rem->getOpcode() == Instruction::SRem;
422     if (!isSigned && Rem->getOpcode() != Instruction::URem)
423       continue;
424
425     // We're only interested in the case where we know something about
426     // the numerator.
427     if (UI.getOperandValToReplace() != Rem->getOperand(0))
428       continue;
429
430     // Get the SCEVs for the ICmp operands.
431     const SCEV *S = SE->getSCEV(Rem->getOperand(0));
432     const SCEV *X = SE->getSCEV(Rem->getOperand(1));
433
434     // Simplify unnecessary loops away.
435     const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
436     S = SE->getSCEVAtScope(S, ICmpLoop);
437     X = SE->getSCEVAtScope(X, ICmpLoop);
438
439     // i % n  -->  i  if i is in [0,n).
440     if ((!isSigned || SE->isKnownNonNegative(S)) &&
441         SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
442                              S, X))
443       Rem->replaceAllUsesWith(Rem->getOperand(0));
444     else {
445       // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
446       const SCEV *LessOne =
447         SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
448       if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
449           SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
450                                LessOne, X)) {
451         ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
452                                       Rem->getOperand(0), Rem->getOperand(1),
453                                       "tmp");
454         SelectInst *Sel =
455           SelectInst::Create(ICmp,
456                              ConstantInt::get(Rem->getType(), 0),
457                              Rem->getOperand(0), "tmp", Rem);
458         Rem->replaceAllUsesWith(Sel);
459       } else
460         continue;
461     }
462
463     // Inform IVUsers about the new users.
464     if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
465       IU->AddUsersIfInteresting(I);
466
467     DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
468     DeadInsts.push_back(Rem);
469   }
470
471   // Now that we're done iterating through lists, clean up any instructions
472   // which are now dead.
473   while (!DeadInsts.empty())
474     if (Instruction *Inst =
475           dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
476       RecursivelyDeleteTriviallyDeadInstructions(Inst);
477 }
478
479 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
480   // If LoopSimplify form is not available, stay out of trouble. Some notes:
481   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
482   //    canonicalization can be a pessimization without LSR to "clean up"
483   //    afterwards.
484   //  - We depend on having a preheader; in particular,
485   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
486   //    and we're in trouble if we can't find the induction variable even when
487   //    we've manually inserted one.
488   if (!L->isLoopSimplifyForm())
489     return false;
490
491   IU = &getAnalysis<IVUsers>();
492   LI = &getAnalysis<LoopInfo>();
493   SE = &getAnalysis<ScalarEvolution>();
494   DT = &getAnalysis<DominatorTree>();
495   Changed = false;
496
497   // If there are any floating-point recurrences, attempt to
498   // transform them to use integer recurrences.
499   RewriteNonIntegerIVs(L);
500
501   BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
502   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
503
504   // Create a rewriter object which we'll use to transform the code with.
505   SCEVExpander Rewriter(*SE);
506
507   // Check to see if this loop has a computable loop-invariant execution count.
508   // If so, this means that we can compute the final value of any expressions
509   // that are recurrent in the loop, and substitute the exit values from the
510   // loop into any instructions outside of the loop that use the final values of
511   // the current expressions.
512   //
513   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
514     RewriteLoopExitValues(L, Rewriter);
515
516   // Simplify ICmp IV users.
517   EliminateIVComparisons();
518
519   // Simplify SRem and URem IV users.
520   EliminateIVRemainders();
521
522   // Compute the type of the largest recurrence expression, and decide whether
523   // a canonical induction variable should be inserted.
524   const Type *LargestType = 0;
525   bool NeedCannIV = false;
526   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
527     LargestType = BackedgeTakenCount->getType();
528     LargestType = SE->getEffectiveSCEVType(LargestType);
529     // If we have a known trip count and a single exit block, we'll be
530     // rewriting the loop exit test condition below, which requires a
531     // canonical induction variable.
532     if (ExitingBlock)
533       NeedCannIV = true;
534   }
535   for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
536     const Type *Ty =
537       SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
538     if (!LargestType ||
539         SE->getTypeSizeInBits(Ty) >
540           SE->getTypeSizeInBits(LargestType))
541       LargestType = Ty;
542     NeedCannIV = true;
543   }
544
545   // Now that we know the largest of the induction variable expressions
546   // in this loop, insert a canonical induction variable of the largest size.
547   PHINode *IndVar = 0;
548   if (NeedCannIV) {
549     // Check to see if the loop already has any canonical-looking induction
550     // variables. If any are present and wider than the planned canonical
551     // induction variable, temporarily remove them, so that the Rewriter
552     // doesn't attempt to reuse them.
553     SmallVector<PHINode *, 2> OldCannIVs;
554     while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
555       if (SE->getTypeSizeInBits(OldCannIV->getType()) >
556           SE->getTypeSizeInBits(LargestType))
557         OldCannIV->removeFromParent();
558       else
559         break;
560       OldCannIVs.push_back(OldCannIV);
561     }
562
563     IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
564
565     ++NumInserted;
566     Changed = true;
567     DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
568
569     // Now that the official induction variable is established, reinsert
570     // any old canonical-looking variables after it so that the IR remains
571     // consistent. They will be deleted as part of the dead-PHI deletion at
572     // the end of the pass.
573     while (!OldCannIVs.empty()) {
574       PHINode *OldCannIV = OldCannIVs.pop_back_val();
575       OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
576     }
577   }
578
579   // If we have a trip count expression, rewrite the loop's exit condition
580   // using it.  We can currently only handle loops with a single exit.
581   ICmpInst *NewICmp = 0;
582   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
583       !BackedgeTakenCount->isZero() &&
584       ExitingBlock) {
585     assert(NeedCannIV &&
586            "LinearFunctionTestReplace requires a canonical induction variable");
587     // Can't rewrite non-branch yet.
588     if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
589       NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
590                                           ExitingBlock, BI, Rewriter);
591   }
592
593   // Rewrite IV-derived expressions. Clears the rewriter cache.
594   RewriteIVExpressions(L, Rewriter);
595
596   // The Rewriter may not be used from this point on.
597
598   // Loop-invariant instructions in the preheader that aren't used in the
599   // loop may be sunk below the loop to reduce register pressure.
600   SinkUnusedInvariants(L);
601
602   // For completeness, inform IVUsers of the IV use in the newly-created
603   // loop exit test instruction.
604   if (NewICmp)
605     IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
606
607   // Clean up dead instructions.
608   Changed |= DeleteDeadPHIs(L->getHeader());
609   // Check a post-condition.
610   assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
611   return Changed;
612 }
613
614 // FIXME: It is an extremely bad idea to indvar substitute anything more
615 // complex than affine induction variables.  Doing so will put expensive
616 // polynomial evaluations inside of the loop, and the str reduction pass
617 // currently can only reduce affine polynomials.  For now just disable
618 // indvar subst on anything more complex than an affine addrec, unless
619 // it can be expanded to a trivial value.
620 static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
621   // Loop-invariant values are safe.
622   if (SE->isLoopInvariant(S, L)) return true;
623
624   // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
625   // to transform them into efficient code.
626   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
627     return AR->isAffine();
628
629   // An add is safe it all its operands are safe.
630   if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
631     for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
632          E = Commutative->op_end(); I != E; ++I)
633       if (!isSafe(*I, L, SE)) return false;
634     return true;
635   }
636   
637   // A cast is safe if its operand is.
638   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
639     return isSafe(C->getOperand(), L, SE);
640
641   // A udiv is safe if its operands are.
642   if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
643     return isSafe(UD->getLHS(), L, SE) &&
644            isSafe(UD->getRHS(), L, SE);
645
646   // SCEVUnknown is always safe.
647   if (isa<SCEVUnknown>(S))
648     return true;
649
650   // Nothing else is safe.
651   return false;
652 }
653
654 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
655   SmallVector<WeakVH, 16> DeadInsts;
656
657   // Rewrite all induction variable expressions in terms of the canonical
658   // induction variable.
659   //
660   // If there were induction variables of other sizes or offsets, manually
661   // add the offsets to the primary induction variable and cast, avoiding
662   // the need for the code evaluation methods to insert induction variables
663   // of different sizes.
664   for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
665     Value *Op = UI->getOperandValToReplace();
666     const Type *UseTy = Op->getType();
667     Instruction *User = UI->getUser();
668
669     // Compute the final addrec to expand into code.
670     const SCEV *AR = IU->getReplacementExpr(*UI);
671
672     // Evaluate the expression out of the loop, if possible.
673     if (!L->contains(UI->getUser())) {
674       const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
675       if (SE->isLoopInvariant(ExitVal, L))
676         AR = ExitVal;
677     }
678
679     // FIXME: It is an extremely bad idea to indvar substitute anything more
680     // complex than affine induction variables.  Doing so will put expensive
681     // polynomial evaluations inside of the loop, and the str reduction pass
682     // currently can only reduce affine polynomials.  For now just disable
683     // indvar subst on anything more complex than an affine addrec, unless
684     // it can be expanded to a trivial value.
685     if (!isSafe(AR, L, SE))
686       continue;
687
688     // Determine the insertion point for this user. By default, insert
689     // immediately before the user. The SCEVExpander class will automatically
690     // hoist loop invariants out of the loop. For PHI nodes, there may be
691     // multiple uses, so compute the nearest common dominator for the
692     // incoming blocks.
693     Instruction *InsertPt = User;
694     if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
695       for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
696         if (PHI->getIncomingValue(i) == Op) {
697           if (InsertPt == User)
698             InsertPt = PHI->getIncomingBlock(i)->getTerminator();
699           else
700             InsertPt =
701               DT->findNearestCommonDominator(InsertPt->getParent(),
702                                              PHI->getIncomingBlock(i))
703                     ->getTerminator();
704         }
705
706     // Now expand it into actual Instructions and patch it into place.
707     Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
708
709     // Inform ScalarEvolution that this value is changing. The change doesn't
710     // affect its value, but it does potentially affect which use lists the
711     // value will be on after the replacement, which affects ScalarEvolution's
712     // ability to walk use lists and drop dangling pointers when a value is
713     // deleted.
714     SE->forgetValue(User);
715
716     // Patch the new value into place.
717     if (Op->hasName())
718       NewVal->takeName(Op);
719     User->replaceUsesOfWith(Op, NewVal);
720     UI->setOperandValToReplace(NewVal);
721     DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
722                  << "   into = " << *NewVal << "\n");
723     ++NumRemoved;
724     Changed = true;
725
726     // The old value may be dead now.
727     DeadInsts.push_back(Op);
728   }
729
730   // Clear the rewriter cache, because values that are in the rewriter's cache
731   // can be deleted in the loop below, causing the AssertingVH in the cache to
732   // trigger.
733   Rewriter.clear();
734   // Now that we're done iterating through lists, clean up any instructions
735   // which are now dead.
736   while (!DeadInsts.empty())
737     if (Instruction *Inst =
738           dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
739       RecursivelyDeleteTriviallyDeadInstructions(Inst);
740 }
741
742 /// If there's a single exit block, sink any loop-invariant values that
743 /// were defined in the preheader but not used inside the loop into the
744 /// exit block to reduce register pressure in the loop.
745 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
746   BasicBlock *ExitBlock = L->getExitBlock();
747   if (!ExitBlock) return;
748
749   BasicBlock *Preheader = L->getLoopPreheader();
750   if (!Preheader) return;
751
752   Instruction *InsertPt = ExitBlock->getFirstNonPHI();
753   BasicBlock::iterator I = Preheader->getTerminator();
754   while (I != Preheader->begin()) {
755     --I;
756     // New instructions were inserted at the end of the preheader.
757     if (isa<PHINode>(I))
758       break;
759
760     // Don't move instructions which might have side effects, since the side
761     // effects need to complete before instructions inside the loop.  Also don't
762     // move instructions which might read memory, since the loop may modify
763     // memory. Note that it's okay if the instruction might have undefined
764     // behavior: LoopSimplify guarantees that the preheader dominates the exit
765     // block.
766     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
767       continue;
768
769     // Skip debug info intrinsics.
770     if (isa<DbgInfoIntrinsic>(I))
771       continue;
772
773     // Don't sink static AllocaInsts out of the entry block, which would
774     // turn them into dynamic allocas!
775     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
776       if (AI->isStaticAlloca())
777         continue;
778
779     // Determine if there is a use in or before the loop (direct or
780     // otherwise).
781     bool UsedInLoop = false;
782     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
783          UI != UE; ++UI) {
784       User *U = *UI;
785       BasicBlock *UseBB = cast<Instruction>(U)->getParent();
786       if (PHINode *P = dyn_cast<PHINode>(U)) {
787         unsigned i =
788           PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
789         UseBB = P->getIncomingBlock(i);
790       }
791       if (UseBB == Preheader || L->contains(UseBB)) {
792         UsedInLoop = true;
793         break;
794       }
795     }
796
797     // If there is, the def must remain in the preheader.
798     if (UsedInLoop)
799       continue;
800
801     // Otherwise, sink it to the exit block.
802     Instruction *ToMove = I;
803     bool Done = false;
804
805     if (I != Preheader->begin()) {
806       // Skip debug info intrinsics.
807       do {
808         --I;
809       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
810
811       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
812         Done = true;
813     } else {
814       Done = true;
815     }
816
817     ToMove->moveBefore(InsertPt);
818     if (Done) break;
819     InsertPt = ToMove;
820   }
821 }
822
823 /// ConvertToSInt - Convert APF to an integer, if possible.
824 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
825   bool isExact = false;
826   if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
827     return false;
828   // See if we can convert this to an int64_t
829   uint64_t UIntVal;
830   if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
831                            &isExact) != APFloat::opOK || !isExact)
832     return false;
833   IntVal = UIntVal;
834   return true;
835 }
836
837 /// HandleFloatingPointIV - If the loop has floating induction variable
838 /// then insert corresponding integer induction variable if possible.
839 /// For example,
840 /// for(double i = 0; i < 10000; ++i)
841 ///   bar(i)
842 /// is converted into
843 /// for(int i = 0; i < 10000; ++i)
844 ///   bar((double)i);
845 ///
846 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
847   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
848   unsigned BackEdge     = IncomingEdge^1;
849
850   // Check incoming value.
851   ConstantFP *InitValueVal =
852     dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
853
854   int64_t InitValue;
855   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
856     return;
857
858   // Check IV increment. Reject this PN if increment operation is not
859   // an add or increment value can not be represented by an integer.
860   BinaryOperator *Incr =
861     dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
862   if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
863   
864   // If this is not an add of the PHI with a constantfp, or if the constant fp
865   // is not an integer, bail out.
866   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
867   int64_t IncValue;
868   if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
869       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
870     return;
871
872   // Check Incr uses. One user is PN and the other user is an exit condition
873   // used by the conditional terminator.
874   Value::use_iterator IncrUse = Incr->use_begin();
875   Instruction *U1 = cast<Instruction>(*IncrUse++);
876   if (IncrUse == Incr->use_end()) return;
877   Instruction *U2 = cast<Instruction>(*IncrUse++);
878   if (IncrUse != Incr->use_end()) return;
879
880   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
881   // only used by a branch, we can't transform it.
882   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
883   if (!Compare)
884     Compare = dyn_cast<FCmpInst>(U2);
885   if (Compare == 0 || !Compare->hasOneUse() ||
886       !isa<BranchInst>(Compare->use_back()))
887     return;
888   
889   BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
890
891   // We need to verify that the branch actually controls the iteration count
892   // of the loop.  If not, the new IV can overflow and no one will notice.
893   // The branch block must be in the loop and one of the successors must be out
894   // of the loop.
895   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
896   if (!L->contains(TheBr->getParent()) ||
897       (L->contains(TheBr->getSuccessor(0)) &&
898        L->contains(TheBr->getSuccessor(1))))
899     return;
900   
901   
902   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
903   // transform it.
904   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
905   int64_t ExitValue;
906   if (ExitValueVal == 0 ||
907       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
908     return;
909   
910   // Find new predicate for integer comparison.
911   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
912   switch (Compare->getPredicate()) {
913   default: return;  // Unknown comparison.
914   case CmpInst::FCMP_OEQ:
915   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
916   case CmpInst::FCMP_ONE:
917   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
918   case CmpInst::FCMP_OGT:
919   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
920   case CmpInst::FCMP_OGE:
921   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
922   case CmpInst::FCMP_OLT:
923   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
924   case CmpInst::FCMP_OLE:
925   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
926   }
927   
928   // We convert the floating point induction variable to a signed i32 value if
929   // we can.  This is only safe if the comparison will not overflow in a way
930   // that won't be trapped by the integer equivalent operations.  Check for this
931   // now.
932   // TODO: We could use i64 if it is native and the range requires it.
933   
934   // The start/stride/exit values must all fit in signed i32.
935   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
936     return;
937
938   // If not actually striding (add x, 0.0), avoid touching the code.
939   if (IncValue == 0)
940     return;
941
942   // Positive and negative strides have different safety conditions.
943   if (IncValue > 0) {
944     // If we have a positive stride, we require the init to be less than the
945     // exit value and an equality or less than comparison.
946     if (InitValue >= ExitValue ||
947         NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
948       return;
949     
950     uint32_t Range = uint32_t(ExitValue-InitValue);
951     if (NewPred == CmpInst::ICMP_SLE) {
952       // Normalize SLE -> SLT, check for infinite loop.
953       if (++Range == 0) return;  // Range overflows.
954     }
955     
956     unsigned Leftover = Range % uint32_t(IncValue);
957     
958     // If this is an equality comparison, we require that the strided value
959     // exactly land on the exit value, otherwise the IV condition will wrap
960     // around and do things the fp IV wouldn't.
961     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
962         Leftover != 0)
963       return;
964     
965     // If the stride would wrap around the i32 before exiting, we can't
966     // transform the IV.
967     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
968       return;
969     
970   } else {
971     // If we have a negative stride, we require the init to be greater than the
972     // exit value and an equality or greater than comparison.
973     if (InitValue >= ExitValue ||
974         NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
975       return;
976     
977     uint32_t Range = uint32_t(InitValue-ExitValue);
978     if (NewPred == CmpInst::ICMP_SGE) {
979       // Normalize SGE -> SGT, check for infinite loop.
980       if (++Range == 0) return;  // Range overflows.
981     }
982     
983     unsigned Leftover = Range % uint32_t(-IncValue);
984     
985     // If this is an equality comparison, we require that the strided value
986     // exactly land on the exit value, otherwise the IV condition will wrap
987     // around and do things the fp IV wouldn't.
988     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
989         Leftover != 0)
990       return;
991     
992     // If the stride would wrap around the i32 before exiting, we can't
993     // transform the IV.
994     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
995       return;
996   }
997   
998   const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
999
1000   // Insert new integer induction variable.
1001   PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN);
1002   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
1003                       PN->getIncomingBlock(IncomingEdge));
1004
1005   Value *NewAdd =
1006     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
1007                               Incr->getName()+".int", Incr);
1008   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
1009
1010   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1011                                       ConstantInt::get(Int32Ty, ExitValue),
1012                                       Compare->getName());
1013
1014   // In the following deletions, PN may become dead and may be deleted.
1015   // Use a WeakVH to observe whether this happens.
1016   WeakVH WeakPH = PN;
1017
1018   // Delete the old floating point exit comparison.  The branch starts using the
1019   // new comparison.
1020   NewCompare->takeName(Compare);
1021   Compare->replaceAllUsesWith(NewCompare);
1022   RecursivelyDeleteTriviallyDeadInstructions(Compare);
1023
1024   // Delete the old floating point increment.
1025   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1026   RecursivelyDeleteTriviallyDeadInstructions(Incr);
1027
1028   // If the FP induction variable still has uses, this is because something else
1029   // in the loop uses its value.  In order to canonicalize the induction
1030   // variable, we chose to eliminate the IV and rewrite it in terms of an
1031   // int->fp cast.
1032   //
1033   // We give preference to sitofp over uitofp because it is faster on most
1034   // platforms.
1035   if (WeakPH) {
1036     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1037                                  PN->getParent()->getFirstNonPHI());
1038     PN->replaceAllUsesWith(Conv);
1039     RecursivelyDeleteTriviallyDeadInstructions(PN);
1040   }
1041
1042   // Add a new IVUsers entry for the newly-created integer PHI.
1043   IU->AddUsersIfInteresting(NewPHI);
1044 }