blob: 2af10a6f7b2912cfde0a04a1df5723f9a8cd7a0c [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// 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//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-04-02 20:24:31 +000015// 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).
Chris Lattner6148c022001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner0e5f4992006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1a6111f2008-11-16 07:17:51 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000058using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000059
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumRemoved , "Number of aux indvars removed");
61STATISTIC(NumPointer , "Number of pointer indvars promoted");
62STATISTIC(NumInserted, "Number of canonical indvars added");
63STATISTIC(NumReplaced, "Number of exit values replaced");
64STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000067 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000068 LoopInfo *LI;
69 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000070 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000071 public:
Devang Patel794fd752007-05-01 21:15:47 +000072
Nick Lewyckyecd94c82007-05-06 13:37:16 +000073 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000074 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000075
Devang Patel5ee99972007-03-07 06:39:01 +000076 bool runOnLoop(Loop *L, LPPassManager &LPM);
77 bool doInitialization(Loop *L, LPPassManager &LPM);
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000079 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000080 AU.addRequiredID(LCSSAID);
81 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000082 AU.addRequired<LoopInfo>();
83 AU.addPreservedID(LoopSimplifyID);
84 AU.addPreservedID(LCSSAID);
85 AU.setPreservesCFG();
86 }
Chris Lattner15cad752003-12-23 07:47:09 +000087
Chris Lattner40bf8b42004-04-02 20:24:31 +000088 private:
Devang Patel5ee99972007-03-07 06:39:01 +000089
Chris Lattner40bf8b42004-04-02 20:24:31 +000090 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +000091 SmallPtrSet<Instruction*, 16> &DeadInsts);
Chris Lattner9ba46c12006-09-21 05:12:20 +000092 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
93 SCEVExpander &RW);
Dan Gohman5a6c4482008-08-05 22:34:21 +000094 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattner40bf8b42004-04-02 20:24:31 +000095
Chris Lattner1a6111f2008-11-16 07:17:51 +000096 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
Devang Pateld22a8492008-09-09 21:41:07 +000097
98 void OptimizeCanonicalIVType(Loop *L);
Devang Patel58d43d42008-11-03 18:32:19 +000099 void HandleFloatingPointIV(Loop *L);
Chris Lattner3324e712003-12-22 03:58:44 +0000100 };
Chris Lattner5e761402002-09-10 05:24:05 +0000101}
Chris Lattner394437f2001-12-04 04:32:29 +0000102
Dan Gohman844731a2008-05-13 00:00:25 +0000103char IndVarSimplify::ID = 0;
104static RegisterPass<IndVarSimplify>
105X("indvars", "Canonicalize Induction Variables");
106
Daniel Dunbar394f0442008-10-22 23:32:42 +0000107Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000108 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000109}
110
Chris Lattner40bf8b42004-04-02 20:24:31 +0000111/// DeleteTriviallyDeadInstructions - If any of the instructions is the
112/// specified set are trivially dead, delete them and see if this makes any of
113/// their operands subsequently dead.
114void IndVarSimplify::
Chris Lattner1a6111f2008-11-16 07:17:51 +0000115DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000116 while (!Insts.empty()) {
117 Instruction *I = *Insts.begin();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000118 Insts.erase(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000119 if (isInstructionTriviallyDead(I)) {
120 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
121 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
122 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000123 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000124 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000125 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000126 Changed = true;
127 }
128 }
129}
130
131
132/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
133/// recurrence. If so, change it into an integer recurrence, permitting
134/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000135void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000136 BasicBlock *Preheader,
Chris Lattner1a6111f2008-11-16 07:17:51 +0000137 SmallPtrSet<Instruction*, 16> &DeadInsts) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000138 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
139 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
140 unsigned BackedgeIdx = PreheaderIdx^1;
141 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000142 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000143 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000144 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000145 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
146
Chris Lattner40bf8b42004-04-02 20:24:31 +0000147 // Okay, we found a pointer recurrence. Transform this pointer
148 // recurrence into an integer recurrence. Compute the value that gets
149 // added to the pointer at every iteration.
150 Value *AddedVal = GEPI->getOperand(1);
151
152 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000153 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
154 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000155 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
156
Chris Lattner40bf8b42004-04-02 20:24:31 +0000157 // Create the new add instruction.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000158 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000159 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000160 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000161
Chris Lattner40bf8b42004-04-02 20:24:31 +0000162 // Update the existing GEP to use the recurrence.
163 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000164
Chris Lattner40bf8b42004-04-02 20:24:31 +0000165 // Update the GEP to use the new recurrence we just inserted.
166 GEPI->setOperand(1, NewAdd);
167
Chris Lattnera4b9c782004-10-11 23:06:50 +0000168 // If the incoming value is a constant expr GEP, try peeling out the array
169 // 0 index if possible to make things simpler.
170 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
171 if (CE->getOpcode() == Instruction::GetElementPtr) {
172 unsigned NumOps = CE->getNumOperands();
173 assert(NumOps > 1 && "CE folding didn't work!");
174 if (CE->getOperand(NumOps-1)->isNullValue()) {
175 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000176 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000177 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000178 i != e; ++i, ++GTI)
179 /*empty*/;
180 if (isa<SequentialType>(*GTI)) {
181 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000182 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000183 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000184 &CEIdxs[0],
185 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000186 Value *Idx[2];
187 Idx[0] = Constant::getNullValue(Type::Int32Ty);
188 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000189 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greeneb8f74792007-09-04 15:46:09 +0000190 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000191 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000192 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000193 GEPI->replaceAllUsesWith(NGEPI);
194 GEPI->eraseFromParent();
195 GEPI = NGEPI;
196 }
197 }
198 }
199
200
Chris Lattner40bf8b42004-04-02 20:24:31 +0000201 // Finally, if there are any other users of the PHI node, we must
202 // insert a new GEP instruction that uses the pre-incremented version
203 // of the induction amount.
204 if (!PN->use_empty()) {
205 BasicBlock::iterator InsertPos = PN; ++InsertPos;
206 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000207 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000208 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
209 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000210 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000211 PN->replaceAllUsesWith(PreInc);
212 }
213
214 // Delete the old PHI for sure, and the GEP if its otherwise unused.
215 DeadInsts.insert(PN);
216
217 ++NumPointer;
218 Changed = true;
219 }
220}
221
222/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000223/// loop to be a canonical != comparison against the incremented loop induction
224/// variable. This pass is able to rewrite the exit tests of any loop where the
225/// SCEV analysis can determine a loop-invariant trip count of the loop, which
226/// is actually a much broader range than just linear tests.
Chris Lattner9ba46c12006-09-21 05:12:20 +0000227///
228/// This method returns a "potentially dead" instruction whose computation chain
229/// should be deleted when convenient.
230Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
231 SCEV *IterationCount,
232 SCEVExpander &RW) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000233 // Find the exit block for the loop. We can currently only handle loops with
234 // a single exit.
Devang Patelb7211a22007-08-21 00:31:24 +0000235 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000236 L->getExitBlocks(ExitBlocks);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000237 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000238 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000239
240 // Make sure there is only one predecessor block in the loop.
241 BasicBlock *ExitingBlock = 0;
242 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
243 PI != PE; ++PI)
244 if (L->contains(*PI)) {
245 if (ExitingBlock == 0)
246 ExitingBlock = *PI;
247 else
Chris Lattner9ba46c12006-09-21 05:12:20 +0000248 return 0; // Multiple exits from loop to this block.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000249 }
250 assert(ExitingBlock && "Loop info is broken");
251
252 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner9ba46c12006-09-21 05:12:20 +0000253 return 0; // Can't rewrite non-branch yet
Chris Lattner40bf8b42004-04-02 20:24:31 +0000254 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
255 assert(BI->isConditional() && "Must be conditional to be part of loop!");
256
Chris Lattner9ba46c12006-09-21 05:12:20 +0000257 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
258
Chris Lattnerd2440572004-04-15 20:26:22 +0000259 // If the exiting block is not the same as the backedge block, we must compare
260 // against the preincremented value, otherwise we prefer to compare against
261 // the post-incremented value.
262 BasicBlock *Header = L->getHeader();
263 pred_iterator HPI = pred_begin(Header);
264 assert(HPI != pred_end(Header) && "Loop with zero preds???");
265 if (!L->contains(*HPI)) ++HPI;
266 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
267 "No backedge in loop?");
Chris Lattner59fdaee2004-04-15 15:21:43 +0000268
Chris Lattnerd2440572004-04-15 20:26:22 +0000269 SCEVHandle TripCount = IterationCount;
270 Value *IndVar;
271 if (*HPI == ExitingBlock) {
272 // The IterationCount expression contains the number of times that the
273 // backedge actually branches to the loop header. This is one less than the
274 // number of times the loop executes, so add one to it.
Dan Gohmane19dd872007-06-15 18:00:55 +0000275 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohman246b2562007-10-22 18:31:58 +0000276 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Chris Lattnerd2440572004-04-15 20:26:22 +0000277 IndVar = L->getCanonicalInductionVariableIncrement();
278 } else {
279 // We have to use the preincremented value...
280 IndVar = L->getCanonicalInductionVariable();
281 }
Chris Lattneree4f13a2007-01-07 01:14:12 +0000282
283 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
284 << " IndVar = " << *IndVar << "\n";
Chris Lattner59fdaee2004-04-15 15:21:43 +0000285
Chris Lattner40bf8b42004-04-02 20:24:31 +0000286 // Expand the code for the iteration count into the preheader of the loop.
287 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmand19534a2007-06-15 14:38:12 +0000288 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000289
Reid Spencere4d87aa2006-12-23 06:05:41 +0000290 // Insert a new icmp_ne or icmp_eq instruction before the branch.
291 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000292 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000293 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000294 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000295 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000296
Reid Spencere4d87aa2006-12-23 06:05:41 +0000297 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000298 BI->setCondition(Cond);
299 ++NumLFTR;
300 Changed = true;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000301 return PotentiallyDeadInst;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000302}
303
304
305/// RewriteLoopExitValues - Check to see if this loop has a computable
306/// loop-invariant execution count. If so, this means that we can compute the
307/// final value of any expressions that are recurrent in the loop, and
308/// substitute the exit values from the loop into any instructions outside of
309/// the loop that use the final values of the current expressions.
Dan Gohman5a6c4482008-08-05 22:34:21 +0000310void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000311 BasicBlock *Preheader = L->getLoopPreheader();
312
313 // Scan all of the instructions in the loop, looking at those that have
314 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000315 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000316
317 // We insert the code into the preheader of the loop if the loop contains
318 // multiple exit blocks, or in the exit block if there is exactly one.
319 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000320 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000321 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000322 if (ExitBlocks.size() == 1)
323 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000324 else
325 BlockToInsertInto = Preheader;
Dan Gohman02dea8b2008-05-23 21:05:58 +0000326 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000327
Dan Gohman5a6c4482008-08-05 22:34:21 +0000328 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattner20aa0982004-04-17 18:44:09 +0000329
Chris Lattner1a6111f2008-11-16 07:17:51 +0000330 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000331 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000332
Chris Lattner9f3d7382007-03-04 03:43:23 +0000333 // Find all values that are computed inside the loop, but used outside of it.
334 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
335 // the exit blocks of the loop to find them.
336 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
337 BasicBlock *ExitBB = ExitBlocks[i];
338
339 // If there are no PHI nodes in this exit block, then no values defined
340 // inside the loop are used on this path, skip it.
341 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
342 if (!PN) continue;
343
344 unsigned NumPreds = PN->getNumIncomingValues();
345
346 // Iterate over all of the PHI nodes.
347 BasicBlock::iterator BBI = ExitBB->begin();
348 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnerc9838f22007-03-03 22:48:48 +0000349
Chris Lattner9f3d7382007-03-04 03:43:23 +0000350 // Iterate over all of the values in all the PHI nodes.
351 for (unsigned i = 0; i != NumPreds; ++i) {
352 // If the value being merged in is not integer or is not defined
353 // in the loop, skip it.
354 Value *InVal = PN->getIncomingValue(i);
355 if (!isa<Instruction>(InVal) ||
356 // SCEV only supports integer expressions for now.
357 !isa<IntegerType>(InVal->getType()))
358 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000359
Chris Lattner9f3d7382007-03-04 03:43:23 +0000360 // If this pred is for a subloop, not L itself, skip it.
361 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
362 continue; // The Block is in a subloop, skip it.
363
364 // Check that InVal is defined in the loop.
365 Instruction *Inst = cast<Instruction>(InVal);
366 if (!L->contains(Inst->getParent()))
367 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000368
Chris Lattner9f3d7382007-03-04 03:43:23 +0000369 // We require that this value either have a computable evolution or that
370 // the loop have a constant iteration count. In the case where the loop
371 // has a constant iteration count, we can sometimes force evaluation of
372 // the exit value through brute force.
373 SCEVHandle SH = SE->getSCEV(Inst);
374 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
375 continue; // Cannot get exit evolution for the loop value.
376
377 // Okay, this instruction has a user outside of the current loop
378 // and varies predictably *inside* the loop. Evaluate the value it
379 // contains when the loop exits, if possible.
380 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
381 if (isa<SCEVCouldNotCompute>(ExitValue) ||
382 !ExitValue->isLoopInvariant(L))
383 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000384
Chris Lattner9f3d7382007-03-04 03:43:23 +0000385 Changed = true;
386 ++NumReplaced;
387
388 // See if we already computed the exit value for the instruction, if so,
389 // just reuse it.
390 Value *&ExitVal = ExitValues[Inst];
391 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000392 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000393
394 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
395 << " LoopVal = " << *Inst << "\n";
396
397 PN->setIncomingValue(i, ExitVal);
398
399 // If this instruction is dead now, schedule it to be removed.
400 if (Inst->use_empty())
401 InstructionsToDelete.insert(Inst);
402
403 // See if this is a single-entry LCSSA PHI node. If so, we can (and
404 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000405 // the PHI entirely. This is safe, because the NewVal won't be variant
406 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000407 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000408 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000409 PN->replaceAllUsesWith(ExitVal);
410 PN->eraseFromParent();
411 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000412 }
413 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000414 }
415 }
416
Chris Lattner40bf8b42004-04-02 20:24:31 +0000417 DeleteTriviallyDeadInstructions(InstructionsToDelete);
418}
419
Devang Patel5ee99972007-03-07 06:39:01 +0000420bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000421
Devang Patel5ee99972007-03-07 06:39:01 +0000422 Changed = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000423 // First step. Check to see if there are any trivial GEP pointer recurrences.
424 // If there are, change them into integer recurrences, permitting analysis by
425 // the SCEV routines.
426 //
427 BasicBlock *Header = L->getHeader();
428 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel5ee99972007-03-07 06:39:01 +0000429 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanfd939082005-04-21 23:48:37 +0000430
Chris Lattner1a6111f2008-11-16 07:17:51 +0000431 SmallPtrSet<Instruction*, 16> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000432 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
433 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000434 if (isa<PointerType>(PN->getType()))
435 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000436 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000437
438 if (!DeadInsts.empty())
439 DeleteTriviallyDeadInstructions(DeadInsts);
440
Devang Patel5ee99972007-03-07 06:39:01 +0000441 return Changed;
442}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000443
Devang Patel5ee99972007-03-07 06:39:01 +0000444bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner3324e712003-12-22 03:58:44 +0000445
Devang Patel5ee99972007-03-07 06:39:01 +0000446
447 LI = &getAnalysis<LoopInfo>();
448 SE = &getAnalysis<ScalarEvolution>();
449
450 Changed = false;
451 BasicBlock *Header = L->getHeader();
Chris Lattner1a6111f2008-11-16 07:17:51 +0000452 SmallPtrSet<Instruction*, 16> DeadInsts;
Devang Patel5ee99972007-03-07 06:39:01 +0000453
Chris Lattner9caed542007-03-04 01:00:28 +0000454 // Verify the input to the pass in already in LCSSA form.
455 assert(L->isLCSSAForm());
456
Chris Lattner40bf8b42004-04-02 20:24:31 +0000457 // Check to see if this loop has a computable loop-invariant execution count.
458 // If so, this means that we can compute the final value of any expressions
459 // that are recurrent in the loop, and substitute the exit values from the
460 // loop into any instructions outside of the loop that use the final values of
461 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000462 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000463 SCEVHandle IterationCount = SE->getIterationCount(L);
464 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman5a6c4482008-08-05 22:34:21 +0000465 RewriteLoopExitValues(L, IterationCount);
Chris Lattner6148c022001-12-03 17:28:42 +0000466
Chris Lattner40bf8b42004-04-02 20:24:31 +0000467 // Next, analyze all of the induction variables in the loop, canonicalizing
468 // auxillary induction variables.
469 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
470
Devang Patel58d43d42008-11-03 18:32:19 +0000471 HandleFloatingPointIV(L);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000472 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
473 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000474 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000475 SCEVHandle SCEV = SE->getSCEV(PN);
476 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000477 // FIXME: It is an extremely bad idea to indvar substitute anything more
478 // complex than affine induction variables. Doing so will put expensive
479 // polynomial evaluations inside of the loop, and the str reduction pass
480 // currently can only reduce affine polynomials. For now just disable
481 // indvar subst on anything more complex than an affine addrec.
Chris Lattner595ee7e2004-07-26 02:47:12 +0000482 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000483 if (AR->isAffine())
Chris Lattner595ee7e2004-07-26 02:47:12 +0000484 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000485 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000486 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000487
488 // If there are no induction variables in the loop, there is nothing more to
489 // do.
Chris Lattnerf50af082004-04-17 18:08:33 +0000490 if (IndVars.empty()) {
491 // Actually, if we know how many times the loop iterates, lets insert a
492 // canonical induction variable to help subsequent passes.
493 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner4a7553e2004-04-23 21:29:48 +0000494 SCEVExpander Rewriter(*SE, *LI);
495 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattnerf50af082004-04-17 18:08:33 +0000496 IterationCount->getType());
Chris Lattner9ba46c12006-09-21 05:12:20 +0000497 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
498 Rewriter)) {
Chris Lattner1a6111f2008-11-16 07:17:51 +0000499 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000500 InstructionsToDelete.insert(I);
501 DeleteTriviallyDeadInstructions(InstructionsToDelete);
502 }
Chris Lattnerf50af082004-04-17 18:08:33 +0000503 }
Devang Patel5ee99972007-03-07 06:39:01 +0000504 return Changed;
Chris Lattnerf50af082004-04-17 18:08:33 +0000505 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000506
507 // Compute the type of the largest recurrence expression.
Chris Lattner6148c022001-12-03 17:28:42 +0000508 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000509 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000510 bool DifferingSizes = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000511 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
512 const Type *Ty = IndVars[i].first->getType();
Reid Spencerabaa8ca2007-01-08 16:32:00 +0000513 DifferingSizes |=
514 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
515 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattner40bf8b42004-04-02 20:24:31 +0000516 LargestType = Ty;
Chris Lattner6148c022001-12-03 17:28:42 +0000517 }
518
Chris Lattner40bf8b42004-04-02 20:24:31 +0000519 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000520 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000521
Chris Lattner40bf8b42004-04-02 20:24:31 +0000522 // Now that we know the largest of of the induction variables in this loop,
523 // insert a canonical induction variable of the largest size.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000524 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000525 ++NumInserted;
526 Changed = true;
Chris Lattneree4f13a2007-01-07 01:14:12 +0000527 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner15cad752003-12-23 07:47:09 +0000528
Dan Gohmand19534a2007-06-15 14:38:12 +0000529 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewicz90087212008-06-13 17:02:03 +0000530 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000531 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
532 DeadInsts.insert(DI);
Dan Gohmand19534a2007-06-15 14:38:12 +0000533 }
Chris Lattner15cad752003-12-23 07:47:09 +0000534
Chris Lattner40bf8b42004-04-02 20:24:31 +0000535 // Now that we have a canonical induction variable, we can rewrite any
536 // recurrences in terms of the induction variable. Start with the auxillary
537 // induction variables, and recursively rewrite any of their uses.
Dan Gohman02dea8b2008-05-23 21:05:58 +0000538 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner6148c022001-12-03 17:28:42 +0000539
Chris Lattner5d461d22004-04-21 22:22:01 +0000540 // If there were induction variables of other sizes, cast the primary
541 // induction variable to the right size for them, avoiding the need for the
542 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000543 if (DifferingSizes) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000544 SmallVector<unsigned,4> InsertedSizes;
545 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
546 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
547 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattneref60b2c2007-01-12 22:51:20 +0000548 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
549 == InsertedSizes.end()) {
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000550 PHINode *PN = IndVars[i].first;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000551 InsertedSizes.push_back(ithSize);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000552 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
553 InsertPt);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000554 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattneree4f13a2007-01-07 01:14:12 +0000555 DOUT << "INDVARS: Made trunc IV for " << *PN
556 << " NewVal = " << *New << "\n";
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000557 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000558 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000559 }
560
Chris Lattneree4f13a2007-01-07 01:14:12 +0000561 // Rewrite all induction variables in terms of the canonical induction
562 // variable.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000563 while (!IndVars.empty()) {
564 PHINode *PN = IndVars.back().first;
Dan Gohmand19534a2007-06-15 14:38:12 +0000565 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000566 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
567 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000568 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000569
Chris Lattner40bf8b42004-04-02 20:24:31 +0000570 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000571 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000572 DeadInsts.insert(PN);
573 IndVars.pop_back();
574 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000575 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000576 }
577
Chris Lattnerb4782d12004-04-22 15:12:36 +0000578#if 0
Chris Lattner1363e852004-04-21 23:36:08 +0000579 // Now replace all derived expressions in the loop body with simpler
580 // expressions.
Dan Gohman9b787632008-06-22 20:18:58 +0000581 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
582 I != E; ++I) {
583 BasicBlock *BB = *I;
584 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Chris Lattner40bf8b42004-04-02 20:24:31 +0000585 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +0000586 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattner1363e852004-04-21 23:36:08 +0000587 !I->use_empty() &&
Chris Lattner40bf8b42004-04-02 20:24:31 +0000588 !Rewriter.isInsertedInstruction(I)) {
589 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000590 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattner1363e852004-04-21 23:36:08 +0000591 if (V != I) {
Chris Lattner6934a042007-02-11 01:23:03 +0000592 if (isa<Instruction>(V))
593 V->takeName(I);
Chris Lattner1363e852004-04-21 23:36:08 +0000594 I->replaceAllUsesWith(V);
595 DeadInsts.insert(I);
596 ++NumRemoved;
597 Changed = true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000598 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000599 }
Chris Lattner394437f2001-12-04 04:32:29 +0000600 }
Dan Gohman9b787632008-06-22 20:18:58 +0000601 }
Chris Lattnerb4782d12004-04-22 15:12:36 +0000602#endif
Chris Lattner1363e852004-04-21 23:36:08 +0000603
Chris Lattner1363e852004-04-21 23:36:08 +0000604 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Pateld22a8492008-09-09 21:41:07 +0000605 OptimizeCanonicalIVType(L);
Chris Lattner9caed542007-03-04 01:00:28 +0000606 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000607 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000608}
Devang Pateld22a8492008-09-09 21:41:07 +0000609
610/// OptimizeCanonicalIVType - If loop induction variable is always
Devang Patel36a5bf82008-09-10 14:49:55 +0000611/// sign or zero extended then extend the type of the induction
Devang Pateld22a8492008-09-09 21:41:07 +0000612/// variable.
613void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
614 PHINode *PH = L->getCanonicalInductionVariable();
615 if (!PH) return;
616
617 // Check loop iteration count.
618 SCEVHandle IC = SE->getIterationCount(L);
619 if (isa<SCEVCouldNotCompute>(IC)) return;
620 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
621 if (!IterationCount) return;
622
623 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
624 unsigned BackEdge = IncomingEdge^1;
625
626 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
627 // IV increment instruction) then this IV is suitable for this
Devang Patel36a5bf82008-09-10 14:49:55 +0000628 // transformation.
629 bool isSEXT = false;
Devang Pateld22a8492008-09-09 21:41:07 +0000630 BinaryOperator *Incr = NULL;
Devang Patel36a5bf82008-09-10 14:49:55 +0000631 const Type *NewType = NULL;
Devang Pateld22a8492008-09-09 21:41:07 +0000632 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
633 UI != UE; ++UI) {
634 const Type *CandidateType = NULL;
635 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
636 CandidateType = ZI->getDestTy();
637 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
638 CandidateType = SI->getDestTy();
Devang Patel36a5bf82008-09-10 14:49:55 +0000639 isSEXT = true;
Devang Pateld22a8492008-09-09 21:41:07 +0000640 }
641 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
642 // Validate IV increment instruction.
643 if (PH->getIncomingValue(BackEdge) == Incr)
644 continue;
645 }
646 if (!CandidateType) {
647 NewType = NULL;
648 break;
649 }
650 if (!NewType)
651 NewType = CandidateType;
652 else if (NewType != CandidateType) {
653 NewType = NULL;
654 break;
655 }
656 }
657
658 // IV uses are not suitable then avoid this transformation.
659 if (!NewType || !Incr)
660 return;
661
662 // IV increment instruction has two uses, one is loop exit condition
663 // and second is the IV (phi node) itself.
664 ICmpInst *Exit = NULL;
665 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
666 II != IE; ++II) {
667 if (PH == *II) continue;
668 Exit = dyn_cast<ICmpInst>(*II);
669 break;
670 }
671 if (!Exit) return;
672 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
673 if (!EV)
674 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
675 if (!EV) return;
676
677 // Check iteration count max value to avoid loops that wrap around IV.
678 APInt ICount = IterationCount->getValue()->getValue();
679 if (ICount.isNegative()) return;
680 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
681 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
682 if (ICount.getZExtValue() > Max.getZExtValue()) return;
683
684 // Extend IV type.
685
686 SCEVExpander Rewriter(*SE, *LI);
687 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
688 PHINode *NewPH = cast<PHINode>(NewIV);
689 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
690
691 // Replace all SEXT or ZEXT uses.
692 SmallVector<Instruction *, 4> PHUses;
693 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
694 UI != UE; ++UI) {
695 Instruction *I = cast<Instruction>(UI);
696 PHUses.push_back(I);
697 }
698 while (!PHUses.empty()){
699 Instruction *Use = PHUses.back(); PHUses.pop_back();
700 if (Incr == Use) continue;
701
702 SE->deleteValueFromRecords(Use);
703 Use->replaceAllUsesWith(NewIV);
704 Use->eraseFromParent();
705 }
706
707 // Replace exit condition.
708 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
709 Instruction *NE = new ICmpInst(Exit->getPredicate(),
710 NewIncr, NEV, "new.exit",
711 Exit->getParent()->getTerminator());
712 SE->deleteValueFromRecords(Exit);
713 Exit->replaceAllUsesWith(NE);
714 Exit->eraseFromParent();
715
716 // Remove old IV and increment instructions.
717 SE->deleteValueFromRecords(PH);
718 PH->removeIncomingValue((unsigned)0);
719 PH->removeIncomingValue((unsigned)0);
720 SE->deleteValueFromRecords(Incr);
721 Incr->eraseFromParent();
722}
723
Devang Patel58d43d42008-11-03 18:32:19 +0000724/// HandleFloatingPointIV - If the loop has floating induction variable
725/// then insert corresponding integer induction variable if possible.
726void IndVarSimplify::HandleFloatingPointIV(Loop *L) {
727 BasicBlock *Header = L->getHeader();
728 SmallVector <PHINode *, 4> FPHIs;
729 Instruction *NonPHIInsn = NULL;
730
731 // Collect all floating point IVs first.
732 BasicBlock::iterator I = Header->begin();
733 while(true) {
734 if (!isa<PHINode>(I)) {
735 NonPHIInsn = I;
736 break;
737 }
738 PHINode *PH = cast<PHINode>(I);
739 if (PH->getType()->isFloatingPoint())
740 FPHIs.push_back(PH);
741 ++I;
742 }
743
744 for (SmallVector<PHINode *, 4>::iterator I = FPHIs.begin(), E = FPHIs.end();
745 I != E; ++I) {
746 PHINode *PH = *I;
747 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
748 unsigned BackEdge = IncomingEdge^1;
749
750 // Check incoming value.
751 ConstantFP *CZ = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
752 if (!CZ) continue;
753 APFloat PHInit = CZ->getValueAPF();
754 if (!PHInit.isPosZero()) continue;
755
756 // Check IV increment.
757 BinaryOperator *Incr =
758 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
759 if (!Incr) continue;
760 if (Incr->getOpcode() != Instruction::Add) continue;
761 ConstantFP *IncrValue = NULL;
762 unsigned IncrVIndex = 1;
763 if (Incr->getOperand(1) == PH)
764 IncrVIndex = 0;
765 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
766 if (!IncrValue) continue;
767 APFloat IVAPF = IncrValue->getValueAPF();
768 APFloat One = APFloat(IVAPF.getSemantics(), 1);
769 if (!IVAPF.bitwiseIsEqual(One)) continue;
770
771 // Check Incr uses.
772 Value::use_iterator IncrUse = Incr->use_begin();
773 Instruction *U1 = cast<Instruction>(IncrUse++);
774 if (IncrUse == Incr->use_end()) continue;
775 Instruction *U2 = cast<Instruction>(IncrUse++);
776 if (IncrUse != Incr->use_end()) continue;
777
778 // Find exict condition.
779 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
780 if (!EC)
781 EC = dyn_cast<FCmpInst>(U2);
782 if (!EC) continue;
783 bool skip = false;
784 Instruction *Terminator = EC->getParent()->getTerminator();
785 for(Value::use_iterator ECUI = EC->use_begin(), ECUE = EC->use_end();
786 ECUI != ECUE; ++ECUI) {
787 Instruction *U = cast<Instruction>(ECUI);
788 if (U != Terminator) {
789 skip = true;
790 break;
791 }
792 }
793 if (skip) continue;
794
795 // Find exit value.
796 ConstantFP *EV = NULL;
797 unsigned EVIndex = 1;
798 if (EC->getOperand(1) == Incr)
799 EVIndex = 0;
800 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
801 if (!EV) continue;
802 APFloat EVAPF = EV->getValueAPF();
803 if (EVAPF.isNegative()) continue;
804
805 // Find corresponding integer exit value.
806 uint64_t integerVal = Type::Int32Ty->getPrimitiveSizeInBits();
807 bool isExact = false;
808 if (EVAPF.convertToInteger(&integerVal, 32, false, APFloat::rmTowardZero, &isExact)
809 != APFloat::opOK)
810 continue;
811 if (!isExact) continue;
812
813 // Find new predicate for integer comparison.
814 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
815 switch (EC->getPredicate()) {
816 case CmpInst::FCMP_OEQ:
817 case CmpInst::FCMP_UEQ:
818 NewPred = CmpInst::ICMP_EQ;
819 break;
820 case CmpInst::FCMP_OGT:
821 case CmpInst::FCMP_UGT:
822 NewPred = CmpInst::ICMP_UGT;
823 break;
824 case CmpInst::FCMP_OGE:
825 case CmpInst::FCMP_UGE:
826 NewPred = CmpInst::ICMP_UGE;
827 break;
828 case CmpInst::FCMP_OLT:
829 case CmpInst::FCMP_ULT:
830 NewPred = CmpInst::ICMP_ULT;
831 break;
832 case CmpInst::FCMP_OLE:
833 case CmpInst::FCMP_ULE:
834 NewPred = CmpInst::ICMP_ULE;
835 break;
836 default:
837 break;
838 }
839 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) continue;
840
841 // Insert new integer induction variable.
842 SCEVExpander Rewriter(*SE, *LI);
843 PHINode *NewIV =
844 cast<PHINode>(Rewriter.getOrInsertCanonicalInductionVariable(L,Type::Int32Ty));
845 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, integerVal);
846 Value *LHS = (EVIndex == 1 ? NewIV->getIncomingValue(BackEdge) : NewEV);
847 Value *RHS = (EVIndex == 1 ? NewEV : NewIV->getIncomingValue(BackEdge));
848 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
849 EC->getParent()->getTerminator());
850
851 // Delete old, floating point, exit comparision instruction.
852 SE->deleteValueFromRecords(EC);
853 EC->replaceAllUsesWith(NewEC);
854 EC->eraseFromParent();
855
856 // Delete old, floating point, increment instruction.
857 SE->deleteValueFromRecords(Incr);
858 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
859 Incr->eraseFromParent();
860
861 // Replace floating induction variable.
862 UIToFPInst *Conv = new UIToFPInst(NewIV, PH->getType(), "indvar.conv",
863 NonPHIInsn);
864 PH->replaceAllUsesWith(Conv);
865
866 SE->deleteValueFromRecords(PH);
867 PH->removeIncomingValue((unsigned)0);
868 PH->removeIncomingValue((unsigned)0);
869 }
870}
871