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