6b52ed7b84da363ef20ee2ac614c01fcf455d2ca
[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. Any pointer arithmetic recurrences are raised to use array subscripts.
21 //
22 // If the trip count of a loop is computable, this pass also makes the following
23 // changes:
24 //   1. The exit condition for the loop is canonicalized to compare the
25 //      induction value against the exit value.  This turns loops like:
26 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27 //   2. Any use outside of the loop of an expression derived from the indvar
28 //      is changed to compute the derived value outside of the loop, eliminating
29 //      the dependence on the exit value of the induction variable.  If the only
30 //      purpose of the loop is to compute the exit value of some derived
31 //      expression, this transformation will make the loop dead.
32 //
33 // This transformation should be followed by strength reduction after all of the
34 // desired loop transformations have been performed.  Additionally, on targets
35 // where it is profitable, the loop could be transformed to count down to zero
36 // (the "do loop" optimization).
37 //
38 //===----------------------------------------------------------------------===//
39
40 #define DEBUG_TYPE "indvars"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/BasicBlock.h"
43 #include "llvm/Constants.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/Type.h"
46 #include "llvm/Analysis/ScalarEvolutionExpander.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Support/CFG.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SetVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 using namespace llvm;
60
61 STATISTIC(NumRemoved , "Number of aux indvars removed");
62 STATISTIC(NumPointer , "Number of pointer indvars promoted");
63 STATISTIC(NumInserted, "Number of canonical indvars added");
64 STATISTIC(NumReplaced, "Number of exit values replaced");
65 STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
66
67 namespace {
68   class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
69     LoopInfo        *LI;
70     ScalarEvolution *SE;
71     bool Changed;
72   public:
73
74    static char ID; // Pass identification, replacement for typeid
75    IndVarSimplify() : LoopPass(&ID) {}
76
77    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
78
79    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80      AU.addRequired<ScalarEvolution>();
81      AU.addRequiredID(LCSSAID);
82      AU.addRequiredID(LoopSimplifyID);
83      AU.addRequired<LoopInfo>();
84      AU.addPreserved<ScalarEvolution>();
85      AU.addPreservedID(LoopSimplifyID);
86      AU.addPreservedID(LCSSAID);
87      AU.setPreservesCFG();
88    }
89
90   private:
91
92     void RewriteNonIntegerIVs(Loop *L);
93
94     void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
95                                     SmallPtrSet<Instruction*, 16> &DeadInsts);
96     void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
97                                    Value *IndVar,
98                                    BasicBlock *ExitingBlock,
99                                    BranchInst *BI,
100                                    SCEVExpander &Rewriter);
101     void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
102
103     void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
104
105     void HandleFloatingPointIV(Loop *L, PHINode *PH,
106                                SmallPtrSet<Instruction*, 16> &DeadInsts);
107   };
108 }
109
110 char IndVarSimplify::ID = 0;
111 static RegisterPass<IndVarSimplify>
112 X("indvars", "Canonicalize Induction Variables");
113
114 Pass *llvm::createIndVarSimplifyPass() {
115   return new IndVarSimplify();
116 }
117
118 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
119 /// specified set are trivially dead, delete them and see if this makes any of
120 /// their operands subsequently dead.
121 void IndVarSimplify::
122 DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
123   while (!Insts.empty()) {
124     Instruction *I = *Insts.begin();
125     Insts.erase(I);
126     if (isInstructionTriviallyDead(I)) {
127       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
128         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
129           Insts.insert(U);
130       SE->deleteValueFromRecords(I);
131       DOUT << "INDVARS: Deleting: " << *I;
132       I->eraseFromParent();
133       Changed = true;
134     }
135   }
136 }
137
138
139 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
140 /// recurrence.  If so, change it into an integer recurrence, permitting
141 /// analysis by the SCEV routines.
142 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
143                                                 BasicBlock *Preheader,
144                                      SmallPtrSet<Instruction*, 16> &DeadInsts) {
145   assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
146   unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
147   unsigned BackedgeIdx = PreheaderIdx^1;
148   if (GetElementPtrInst *GEPI =
149           dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
150     if (GEPI->getOperand(0) == PN) {
151       assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
152       DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
153
154       // Okay, we found a pointer recurrence.  Transform this pointer
155       // recurrence into an integer recurrence.  Compute the value that gets
156       // added to the pointer at every iteration.
157       Value *AddedVal = GEPI->getOperand(1);
158
159       // Insert a new integer PHI node into the top of the block.
160       PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
161                                         PN->getName()+".rec", PN);
162       NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
163
164       // Create the new add instruction.
165       Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
166                                                 GEPI->getName()+".rec", GEPI);
167       NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
168
169       // Update the existing GEP to use the recurrence.
170       GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
171
172       // Update the GEP to use the new recurrence we just inserted.
173       GEPI->setOperand(1, NewAdd);
174
175       // If the incoming value is a constant expr GEP, try peeling out the array
176       // 0 index if possible to make things simpler.
177       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
178         if (CE->getOpcode() == Instruction::GetElementPtr) {
179           unsigned NumOps = CE->getNumOperands();
180           assert(NumOps > 1 && "CE folding didn't work!");
181           if (CE->getOperand(NumOps-1)->isNullValue()) {
182             // Check to make sure the last index really is an array index.
183             gep_type_iterator GTI = gep_type_begin(CE);
184             for (unsigned i = 1, e = CE->getNumOperands()-1;
185                  i != e; ++i, ++GTI)
186               /*empty*/;
187             if (isa<SequentialType>(*GTI)) {
188               // Pull the last index out of the constant expr GEP.
189               SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
190               Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
191                                                              &CEIdxs[0],
192                                                              CEIdxs.size());
193               Value *Idx[2];
194               Idx[0] = Constant::getNullValue(Type::Int32Ty);
195               Idx[1] = NewAdd;
196               GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
197                   NCE, Idx, Idx + 2,
198                   GEPI->getName(), GEPI);
199               SE->deleteValueFromRecords(GEPI);
200               GEPI->replaceAllUsesWith(NGEPI);
201               GEPI->eraseFromParent();
202               GEPI = NGEPI;
203             }
204           }
205         }
206
207
208       // Finally, if there are any other users of the PHI node, we must
209       // insert a new GEP instruction that uses the pre-incremented version
210       // of the induction amount.
211       if (!PN->use_empty()) {
212         BasicBlock::iterator InsertPos = PN; ++InsertPos;
213         while (isa<PHINode>(InsertPos)) ++InsertPos;
214         Value *PreInc =
215           GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
216                                     NewPhi, "", InsertPos);
217         PreInc->takeName(PN);
218         PN->replaceAllUsesWith(PreInc);
219       }
220
221       // Delete the old PHI for sure, and the GEP if its otherwise unused.
222       DeadInsts.insert(PN);
223
224       ++NumPointer;
225       Changed = true;
226     }
227 }
228
229 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
230 /// loop to be a canonical != comparison against the incremented loop induction
231 /// variable.  This pass is able to rewrite the exit tests of any loop where the
232 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
233 /// is actually a much broader range than just linear tests.
234 void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
235                                    SCEVHandle IterationCount,
236                                    Value *IndVar,
237                                    BasicBlock *ExitingBlock,
238                                    BranchInst *BI,
239                                    SCEVExpander &Rewriter) {
240   // If the exiting block is not the same as the backedge block, we must compare
241   // against the preincremented value, otherwise we prefer to compare against
242   // the post-incremented value.
243   Value *CmpIndVar;
244   if (ExitingBlock == L->getLoopLatch()) {
245     // What ScalarEvolution calls the "iteration count" is actually the
246     // number of times the branch is taken. Add one to get the number
247     // of times the branch is executed. If this addition may overflow,
248     // we have to be more pessimistic and cast the induction variable
249     // before doing the add.
250     SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
251     SCEVHandle N =
252       SE->getAddExpr(IterationCount,
253                      SE->getIntegerSCEV(1, IterationCount->getType()));
254     if ((isa<SCEVConstant>(N) && !N->isZero()) ||
255         SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
256       // No overflow. Cast the sum.
257       IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
258     } else {
259       // Potential overflow. Cast before doing the add.
260       IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
261                                                    IndVar->getType());
262       IterationCount =
263         SE->getAddExpr(IterationCount,
264                        SE->getIntegerSCEV(1, IndVar->getType()));
265     }
266
267     // The IterationCount expression contains the number of times that the
268     // backedge actually branches to the loop header.  This is one less than the
269     // number of times the loop executes, so add one to it.
270     CmpIndVar = L->getCanonicalInductionVariableIncrement();
271   } else {
272     // We have to use the preincremented value...
273     IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
274                                                  IndVar->getType());
275     CmpIndVar = IndVar;
276   }
277
278   // Expand the code for the iteration count into the preheader of the loop.
279   BasicBlock *Preheader = L->getLoopPreheader();
280   Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
281                                           Preheader->getTerminator());
282
283   // Insert a new icmp_ne or icmp_eq instruction before the branch.
284   ICmpInst::Predicate Opcode;
285   if (L->contains(BI->getSuccessor(0)))
286     Opcode = ICmpInst::ICMP_NE;
287   else
288     Opcode = ICmpInst::ICMP_EQ;
289
290   DOUT << "INDVARS: Rewriting loop exit condition to:\n"
291        << "      LHS:" << *CmpIndVar // includes a newline
292        << "       op:\t"
293        << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
294        << "      RHS:\t" << *IterationCount << "\n";
295
296   Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
297   BI->setCondition(Cond);
298   ++NumLFTR;
299   Changed = true;
300 }
301
302 /// RewriteLoopExitValues - Check to see if this loop has a computable
303 /// loop-invariant execution count.  If so, this means that we can compute the
304 /// final value of any expressions that are recurrent in the loop, and
305 /// substitute the exit values from the loop into any instructions outside of
306 /// the loop that use the final values of the current expressions.
307 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
308   BasicBlock *Preheader = L->getLoopPreheader();
309
310   // Scan all of the instructions in the loop, looking at those that have
311   // extra-loop users and which are recurrences.
312   SCEVExpander Rewriter(*SE, *LI);
313
314   // We insert the code into the preheader of the loop if the loop contains
315   // multiple exit blocks, or in the exit block if there is exactly one.
316   BasicBlock *BlockToInsertInto;
317   SmallVector<BasicBlock*, 8> ExitBlocks;
318   L->getUniqueExitBlocks(ExitBlocks);
319   if (ExitBlocks.size() == 1)
320     BlockToInsertInto = ExitBlocks[0];
321   else
322     BlockToInsertInto = Preheader;
323   BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
324
325   bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
326
327   SmallPtrSet<Instruction*, 16> InstructionsToDelete;
328   std::map<Instruction*, Value*> ExitValues;
329
330   // Find all values that are computed inside the loop, but used outside of it.
331   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
332   // the exit blocks of the loop to find them.
333   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
334     BasicBlock *ExitBB = ExitBlocks[i];
335
336     // If there are no PHI nodes in this exit block, then no values defined
337     // inside the loop are used on this path, skip it.
338     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
339     if (!PN) continue;
340
341     unsigned NumPreds = PN->getNumIncomingValues();
342
343     // Iterate over all of the PHI nodes.
344     BasicBlock::iterator BBI = ExitBB->begin();
345     while ((PN = dyn_cast<PHINode>(BBI++))) {
346
347       // Iterate over all of the values in all the PHI nodes.
348       for (unsigned i = 0; i != NumPreds; ++i) {
349         // If the value being merged in is not integer or is not defined
350         // in the loop, skip it.
351         Value *InVal = PN->getIncomingValue(i);
352         if (!isa<Instruction>(InVal) ||
353             // SCEV only supports integer expressions for now.
354             !isa<IntegerType>(InVal->getType()))
355           continue;
356
357         // If this pred is for a subloop, not L itself, skip it.
358         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
359           continue; // The Block is in a subloop, skip it.
360
361         // Check that InVal is defined in the loop.
362         Instruction *Inst = cast<Instruction>(InVal);
363         if (!L->contains(Inst->getParent()))
364           continue;
365
366         // We require that this value either have a computable evolution or that
367         // the loop have a constant iteration count.  In the case where the loop
368         // has a constant iteration count, we can sometimes force evaluation of
369         // the exit value through brute force.
370         SCEVHandle SH = SE->getSCEV(Inst);
371         if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
372           continue;          // Cannot get exit evolution for the loop value.
373
374         // Okay, this instruction has a user outside of the current loop
375         // and varies predictably *inside* the loop.  Evaluate the value it
376         // contains when the loop exits, if possible.
377         SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
378         if (isa<SCEVCouldNotCompute>(ExitValue) ||
379             !ExitValue->isLoopInvariant(L))
380           continue;
381
382         Changed = true;
383         ++NumReplaced;
384
385         // See if we already computed the exit value for the instruction, if so,
386         // just reuse it.
387         Value *&ExitVal = ExitValues[Inst];
388         if (!ExitVal)
389           ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
390
391         DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
392              << "  LoopVal = " << *Inst << "\n";
393
394         PN->setIncomingValue(i, ExitVal);
395
396         // If this instruction is dead now, schedule it to be removed.
397         if (Inst->use_empty())
398           InstructionsToDelete.insert(Inst);
399
400         // See if this is a single-entry LCSSA PHI node.  If so, we can (and
401         // have to) remove
402         // the PHI entirely.  This is safe, because the NewVal won't be variant
403         // in the loop, so we don't need an LCSSA phi node anymore.
404         if (NumPreds == 1) {
405           SE->deleteValueFromRecords(PN);
406           PN->replaceAllUsesWith(ExitVal);
407           PN->eraseFromParent();
408           break;
409         }
410       }
411     }
412   }
413
414   DeleteTriviallyDeadInstructions(InstructionsToDelete);
415 }
416
417 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
418   // First step.  Check to see if there are any trivial GEP pointer recurrences.
419   // If there are, change them into integer recurrences, permitting analysis by
420   // the SCEV routines.
421   //
422   BasicBlock *Header    = L->getHeader();
423   BasicBlock *Preheader = L->getLoopPreheader();
424
425   SmallPtrSet<Instruction*, 16> DeadInsts;
426   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
427     PHINode *PN = cast<PHINode>(I);
428     if (isa<PointerType>(PN->getType()))
429       EliminatePointerRecurrence(PN, Preheader, DeadInsts);
430     else
431       HandleFloatingPointIV(L, PN, DeadInsts);
432   }
433
434   // If the loop previously had a pointer or floating-point IV, ScalarEvolution
435   // may not have been able to compute a trip count. Now that we've done some
436   // re-writing, the trip count may be computable.
437   if (Changed)
438     SE->forgetLoopIterationCount(L);
439
440   if (!DeadInsts.empty())
441     DeleteTriviallyDeadInstructions(DeadInsts);
442 }
443
444 /// getEffectiveIndvarType - Determine the widest type that the
445 /// induction-variable PHINode Phi is cast to.
446 ///
447 static const Type *getEffectiveIndvarType(const PHINode *Phi) {
448   const Type *Ty = Phi->getType();
449
450   for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
451        UI != UE; ++UI) {
452     const Type *CandidateType = NULL;
453     if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
454       CandidateType = ZI->getDestTy();
455     else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
456       CandidateType = SI->getDestTy();
457     if (CandidateType &&
458         CandidateType->getPrimitiveSizeInBits() >
459           Ty->getPrimitiveSizeInBits())
460       Ty = CandidateType;
461   }
462
463   return Ty;
464 }
465
466 /// TestOrigIVForWrap - Analyze the original induction variable
467 /// that controls the loop's iteration to determine whether it
468 /// would ever undergo signed or unsigned overflow. Also, check
469 /// whether an induction variable in the same type that starts
470 /// at 0 would undergo signed overflow.
471 ///
472 /// In addition to setting the NoSignedWrap, and NoUnsignedWrap,
473 /// variables, return the PHI for this induction variable.
474 ///
475 /// TODO: This duplicates a fair amount of ScalarEvolution logic.
476 /// Perhaps this can be merged with ScalarEvolution::getIterationCount
477 /// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
478 ///
479 static const PHINode *TestOrigIVForWrap(const Loop *L,
480                                         const BranchInst *BI,
481                                         const Instruction *OrigCond,
482                                         bool &NoSignedWrap,
483                                         bool &NoUnsignedWrap) {
484   // Verify that the loop is sane and find the exit condition.
485   const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
486   if (!Cmp) return 0;
487
488   const Value *CmpLHS = Cmp->getOperand(0);
489   const Value *CmpRHS = Cmp->getOperand(1);
490   const BasicBlock *TrueBB = BI->getSuccessor(0);
491   const BasicBlock *FalseBB = BI->getSuccessor(1);
492   ICmpInst::Predicate Pred = Cmp->getPredicate();
493
494   // Canonicalize a constant to the RHS.
495   if (isa<ConstantInt>(CmpLHS)) {
496     Pred = ICmpInst::getSwappedPredicate(Pred);
497     std::swap(CmpLHS, CmpRHS);
498   }
499   // Canonicalize SLE to SLT.
500   if (Pred == ICmpInst::ICMP_SLE)
501     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
502       if (!CI->getValue().isMaxSignedValue()) {
503         CmpRHS = ConstantInt::get(CI->getValue() + 1);
504         Pred = ICmpInst::ICMP_SLT;
505       }
506   // Canonicalize SGT to SGE.
507   if (Pred == ICmpInst::ICMP_SGT)
508     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
509       if (!CI->getValue().isMaxSignedValue()) {
510         CmpRHS = ConstantInt::get(CI->getValue() + 1);
511         Pred = ICmpInst::ICMP_SGE;
512       }
513   // Canonicalize SGE to SLT.
514   if (Pred == ICmpInst::ICMP_SGE) {
515     std::swap(TrueBB, FalseBB);
516     Pred = ICmpInst::ICMP_SLT;
517   }
518   // Canonicalize ULE to ULT.
519   if (Pred == ICmpInst::ICMP_ULE)
520     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
521       if (!CI->getValue().isMaxValue()) {
522         CmpRHS = ConstantInt::get(CI->getValue() + 1);
523         Pred = ICmpInst::ICMP_ULT;
524       }
525   // Canonicalize UGT to UGE.
526   if (Pred == ICmpInst::ICMP_UGT)
527     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
528       if (!CI->getValue().isMaxValue()) {
529         CmpRHS = ConstantInt::get(CI->getValue() + 1);
530         Pred = ICmpInst::ICMP_UGE;
531       }
532   // Canonicalize UGE to ULT.
533   if (Pred == ICmpInst::ICMP_UGE) {
534     std::swap(TrueBB, FalseBB);
535     Pred = ICmpInst::ICMP_ULT;
536   }
537   // For now, analyze only LT loops for signed overflow.
538   if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
539     return 0;
540
541   bool isSigned = Pred == ICmpInst::ICMP_SLT;
542
543   // Get the increment instruction. Look past casts if we will
544   // be able to prove that the original induction variable doesn't
545   // undergo signed or unsigned overflow, respectively.
546   const Value *IncrVal = CmpLHS;
547   if (isSigned) {
548     if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
549       if (!isa<ConstantInt>(CmpRHS) ||
550           !cast<ConstantInt>(CmpRHS)->getValue()
551             .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
552         return 0;
553       IncrVal = SI->getOperand(0);
554     }
555   } else {
556     if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
557       if (!isa<ConstantInt>(CmpRHS) ||
558           !cast<ConstantInt>(CmpRHS)->getValue()
559             .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
560         return 0;
561       IncrVal = ZI->getOperand(0);
562     }
563   }
564
565   // For now, only analyze induction variables that have simple increments.
566   const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
567   if (!IncrOp ||
568       IncrOp->getOpcode() != Instruction::Add ||
569       !isa<ConstantInt>(IncrOp->getOperand(1)) ||
570       !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
571     return 0;
572
573   // Make sure the PHI looks like a normal IV.
574   const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
575   if (!PN || PN->getNumIncomingValues() != 2)
576     return 0;
577   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
578   unsigned BackEdge = !IncomingEdge;
579   if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
580       PN->getIncomingValue(BackEdge) != IncrOp)
581     return 0;
582   if (!L->contains(TrueBB))
583     return 0;
584
585   // For now, only analyze loops with a constant start value, so that
586   // we can easily determine if the start value is not a maximum value
587   // which would wrap on the first iteration.
588   const ConstantInt *InitialVal =
589     dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
590   if (!InitialVal)
591     return 0;
592
593   // The original induction variable will start at some non-max value,
594   // it counts up by one, and the loop iterates only while it remans
595   // less than some value in the same type. As such, it will never wrap.
596   if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
597     NoSignedWrap = true;
598   } else if (!isSigned && !InitialVal->getValue().isMaxValue())
599     NoUnsignedWrap = true;
600   return PN;
601 }
602
603 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
604   LI = &getAnalysis<LoopInfo>();
605   SE = &getAnalysis<ScalarEvolution>();
606   Changed = false;
607
608   // If there are any floating-point or pointer recurrences, attempt to
609   // transform them to use integer recurrences.
610   RewriteNonIntegerIVs(L);
611
612   BasicBlock *Header       = L->getHeader();
613   BasicBlock *ExitingBlock = L->getExitingBlock();
614   SmallPtrSet<Instruction*, 16> DeadInsts;
615
616   // Verify the input to the pass in already in LCSSA form.
617   assert(L->isLCSSAForm());
618
619   // Check to see if this loop has a computable loop-invariant execution count.
620   // If so, this means that we can compute the final value of any expressions
621   // that are recurrent in the loop, and substitute the exit values from the
622   // loop into any instructions outside of the loop that use the final values of
623   // the current expressions.
624   //
625   SCEVHandle IterationCount = SE->getIterationCount(L);
626   if (!isa<SCEVCouldNotCompute>(IterationCount))
627     RewriteLoopExitValues(L, IterationCount);
628
629   // Next, analyze all of the induction variables in the loop, canonicalizing
630   // auxillary induction variables.
631   std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
632
633   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
634     PHINode *PN = cast<PHINode>(I);
635     if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
636       SCEVHandle SCEV = SE->getSCEV(PN);
637       // FIXME: It is an extremely bad idea to indvar substitute anything more
638       // complex than affine induction variables.  Doing so will put expensive
639       // polynomial evaluations inside of the loop, and the str reduction pass
640       // currently can only reduce affine polynomials.  For now just disable
641       // indvar subst on anything more complex than an affine addrec.
642       if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
643         if (AR->getLoop() == L && AR->isAffine())
644           IndVars.push_back(std::make_pair(PN, SCEV));
645     }
646   }
647
648   // Compute the type of the largest recurrence expression, and collect
649   // the set of the types of the other recurrence expressions.
650   const Type *LargestType = 0;
651   SmallSetVector<const Type *, 4> SizesToInsert;
652   if (!isa<SCEVCouldNotCompute>(IterationCount)) {
653     LargestType = IterationCount->getType();
654     SizesToInsert.insert(IterationCount->getType());
655   }
656   for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
657     const PHINode *PN = IndVars[i].first;
658     SizesToInsert.insert(PN->getType());
659     const Type *EffTy = getEffectiveIndvarType(PN);
660     SizesToInsert.insert(EffTy);
661     if (!LargestType ||
662         EffTy->getPrimitiveSizeInBits() >
663           LargestType->getPrimitiveSizeInBits())
664       LargestType = EffTy;
665   }
666
667   // Create a rewriter object which we'll use to transform the code with.
668   SCEVExpander Rewriter(*SE, *LI);
669
670   // Now that we know the largest of of the induction variables in this loop,
671   // insert a canonical induction variable of the largest size.
672   Value *IndVar = 0;
673   if (!SizesToInsert.empty()) {
674     IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
675     ++NumInserted;
676     Changed = true;
677     DOUT << "INDVARS: New CanIV: " << *IndVar;
678   }
679
680   // If we have a trip count expression, rewrite the loop's exit condition
681   // using it.  We can currently only handle loops with a single exit.
682   bool NoSignedWrap = false;
683   bool NoUnsignedWrap = false;
684   const PHINode *OrigControllingPHI = 0;
685   if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
686     // Can't rewrite non-branch yet.
687     if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
688       if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
689         // Determine if the OrigIV will ever undergo overflow.
690         OrigControllingPHI =
691           TestOrigIVForWrap(L, BI, OrigCond,
692                             NoSignedWrap, NoUnsignedWrap);
693
694         // We'll be replacing the original condition, so it'll be dead.
695         DeadInsts.insert(OrigCond);
696       }
697
698       LinearFunctionTestReplace(L, IterationCount, IndVar,
699                                 ExitingBlock, BI, Rewriter);
700     }
701
702   // Now that we have a canonical induction variable, we can rewrite any
703   // recurrences in terms of the induction variable.  Start with the auxillary
704   // induction variables, and recursively rewrite any of their uses.
705   BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
706
707   // If there were induction variables of other sizes, cast the primary
708   // induction variable to the right size for them, avoiding the need for the
709   // code evaluation methods to insert induction variables of different sizes.
710   for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
711     const Type *Ty = SizesToInsert[i];
712     if (Ty != LargestType) {
713       Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
714       Rewriter.addInsertedValue(New, SE->getSCEV(New));
715       DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
716            << *New << "\n";
717     }
718   }
719
720   // Rewrite all induction variables in terms of the canonical induction
721   // variable.
722   while (!IndVars.empty()) {
723     PHINode *PN = IndVars.back().first;
724     SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
725     Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
726     DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
727          << "   into = " << *NewVal << "\n";
728     NewVal->takeName(PN);
729
730     /// If the new canonical induction variable is wider than the original,
731     /// and the original has uses that are casts to wider types, see if the
732     /// truncate and extend can be omitted.
733     if (PN == OrigControllingPHI && PN->getType() != LargestType)
734       for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
735            UI != UE; ++UI) {
736         if (isa<SExtInst>(UI) && NoSignedWrap) {
737           SCEVHandle ExtendedStart =
738             SE->getSignExtendExpr(AR->getStart(), LargestType);
739           SCEVHandle ExtendedStep =
740             SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
741           SCEVHandle ExtendedAddRec =
742             SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
743           if (LargestType != UI->getType())
744             ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
745           Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
746           UI->replaceAllUsesWith(TruncIndVar);
747           if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
748             DeadInsts.insert(DeadUse);
749         }
750         if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
751           SCEVHandle ExtendedStart =
752             SE->getZeroExtendExpr(AR->getStart(), LargestType);
753           SCEVHandle ExtendedStep =
754             SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
755           SCEVHandle ExtendedAddRec =
756             SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
757           if (LargestType != UI->getType())
758             ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
759           Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
760           UI->replaceAllUsesWith(TruncIndVar);
761           if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
762             DeadInsts.insert(DeadUse);
763         }
764       }
765
766     // Replace the old PHI Node with the inserted computation.
767     PN->replaceAllUsesWith(NewVal);
768     DeadInsts.insert(PN);
769     IndVars.pop_back();
770     ++NumRemoved;
771     Changed = true;
772   }
773
774   DeleteTriviallyDeadInstructions(DeadInsts);
775   assert(L->isLCSSAForm());
776   return Changed;
777 }
778
779 /// Return true if it is OK to use SIToFPInst for an inducation variable
780 /// with given inital and exit values.
781 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
782                           uint64_t intIV, uint64_t intEV) {
783
784   if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
785     return true;
786
787   // If the iteration range can be handled by SIToFPInst then use it.
788   APInt Max = APInt::getSignedMaxValue(32);
789   if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
790     return true;
791
792   return false;
793 }
794
795 /// convertToInt - Convert APF to an integer, if possible.
796 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
797
798   bool isExact = false;
799   if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
800     return false;
801   if (APF.convertToInteger(intVal, 32, APF.isNegative(),
802                            APFloat::rmTowardZero, &isExact)
803       != APFloat::opOK)
804     return false;
805   if (!isExact)
806     return false;
807   return true;
808
809 }
810
811 /// HandleFloatingPointIV - If the loop has floating induction variable
812 /// then insert corresponding integer induction variable if possible.
813 /// For example,
814 /// for(double i = 0; i < 10000; ++i)
815 ///   bar(i)
816 /// is converted into
817 /// for(int i = 0; i < 10000; ++i)
818 ///   bar((double)i);
819 ///
820 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
821                                    SmallPtrSet<Instruction*, 16> &DeadInsts) {
822
823   unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
824   unsigned BackEdge     = IncomingEdge^1;
825
826   // Check incoming value.
827   ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
828   if (!InitValue) return;
829   uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
830   if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
831     return;
832
833   // Check IV increment. Reject this PH if increement operation is not
834   // an add or increment value can not be represented by an integer.
835   BinaryOperator *Incr =
836     dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
837   if (!Incr) return;
838   if (Incr->getOpcode() != Instruction::Add) return;
839   ConstantFP *IncrValue = NULL;
840   unsigned IncrVIndex = 1;
841   if (Incr->getOperand(1) == PH)
842     IncrVIndex = 0;
843   IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
844   if (!IncrValue) return;
845   uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
846   if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
847     return;
848
849   // Check Incr uses. One user is PH and the other users is exit condition used
850   // by the conditional terminator.
851   Value::use_iterator IncrUse = Incr->use_begin();
852   Instruction *U1 = cast<Instruction>(IncrUse++);
853   if (IncrUse == Incr->use_end()) return;
854   Instruction *U2 = cast<Instruction>(IncrUse++);
855   if (IncrUse != Incr->use_end()) return;
856
857   // Find exit condition.
858   FCmpInst *EC = dyn_cast<FCmpInst>(U1);
859   if (!EC)
860     EC = dyn_cast<FCmpInst>(U2);
861   if (!EC) return;
862
863   if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
864     if (!BI->isConditional()) return;
865     if (BI->getCondition() != EC) return;
866   }
867
868   // Find exit value. If exit value can not be represented as an interger then
869   // do not handle this floating point PH.
870   ConstantFP *EV = NULL;
871   unsigned EVIndex = 1;
872   if (EC->getOperand(1) == Incr)
873     EVIndex = 0;
874   EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
875   if (!EV) return;
876   uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
877   if (!convertToInt(EV->getValueAPF(), &intEV))
878     return;
879
880   // Find new predicate for integer comparison.
881   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
882   switch (EC->getPredicate()) {
883   case CmpInst::FCMP_OEQ:
884   case CmpInst::FCMP_UEQ:
885     NewPred = CmpInst::ICMP_EQ;
886     break;
887   case CmpInst::FCMP_OGT:
888   case CmpInst::FCMP_UGT:
889     NewPred = CmpInst::ICMP_UGT;
890     break;
891   case CmpInst::FCMP_OGE:
892   case CmpInst::FCMP_UGE:
893     NewPred = CmpInst::ICMP_UGE;
894     break;
895   case CmpInst::FCMP_OLT:
896   case CmpInst::FCMP_ULT:
897     NewPred = CmpInst::ICMP_ULT;
898     break;
899   case CmpInst::FCMP_OLE:
900   case CmpInst::FCMP_ULE:
901     NewPred = CmpInst::ICMP_ULE;
902     break;
903   default:
904     break;
905   }
906   if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
907
908   // Insert new integer induction variable.
909   PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
910                                     PH->getName()+".int", PH);
911   NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
912                       PH->getIncomingBlock(IncomingEdge));
913
914   Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
915                                             ConstantInt::get(Type::Int32Ty,
916                                                              newIncrValue),
917                                             Incr->getName()+".int", Incr);
918   NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
919
920   ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
921   Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
922   Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
923   ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
924                                  EC->getParent()->getTerminator());
925
926   // Delete old, floating point, exit comparision instruction.
927   EC->replaceAllUsesWith(NewEC);
928   DeadInsts.insert(EC);
929
930   // Delete old, floating point, increment instruction.
931   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
932   DeadInsts.insert(Incr);
933
934   // Replace floating induction variable. Give SIToFPInst preference over
935   // UIToFPInst because it is faster on platforms that are widely used.
936   if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
937     SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
938                                       PH->getParent()->getFirstNonPHI());
939     PH->replaceAllUsesWith(Conv);
940   } else {
941     UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
942                                       PH->getParent()->getFirstNonPHI());
943     PH->replaceAllUsesWith(Conv);
944   }
945   DeadInsts.insert(PH);
946 }
947