blob: 56829bd60ca3e01bb2d8f1920ce7518475a5f553 [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner476e6df2001-12-03 17:28:42 +00009//
Chris Lattnere61b67d2004-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 Spencer5495fe82006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattnere61b67d2004-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 Lattner476e6df2001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner79a42ac2006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner0cec5cb2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner6449dce2003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman2bca4d92005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswellb22e9b42003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel2ac57e12007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer557ab152007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattner08165592007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattner9776f722004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswellb22e9b42003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencer7a9c62b2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
John Criswellb22e9b42003-12-18 17:19:19 +000057using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner79a42ac2006-12-19 21:40:18 +000059STATISTIC(NumRemoved , "Number of aux indvars removed");
60STATISTIC(NumPointer , "Number of pointer indvars promoted");
61STATISTIC(NumInserted, "Number of canonical indvars added");
62STATISTIC(NumReplaced, "Number of exit values replaced");
63STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000064
Chris Lattner79a42ac2006-12-19 21:40:18 +000065namespace {
Devang Patel2ac57e12007-03-07 06:39:01 +000066 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattnere61b67d2004-04-02 20:24:31 +000067 LoopInfo *LI;
68 ScalarEvolution *SE;
Chris Lattner7e755e42003-12-23 07:47:09 +000069 bool Changed;
Chris Lattnerd3678bc2003-12-22 03:58:44 +000070 public:
Devang Patel09f162c2007-05-01 21:15:47 +000071
Nick Lewyckye7da2d62007-05-06 13:37:16 +000072 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000073 IndVarSimplify() : LoopPass(&ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +000074
Devang Patel2ac57e12007-03-07 06:39:01 +000075 bool runOnLoop(Loop *L, LPPassManager &LPM);
76 bool doInitialization(Loop *L, LPPassManager &LPM);
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Pateld7409fd2007-09-10 18:08:23 +000078 AU.addRequired<ScalarEvolution>();
Devang Patel2ac57e12007-03-07 06:39:01 +000079 AU.addRequiredID(LCSSAID);
80 AU.addRequiredID(LoopSimplifyID);
Devang Patel2ac57e12007-03-07 06:39:01 +000081 AU.addRequired<LoopInfo>();
82 AU.addPreservedID(LoopSimplifyID);
83 AU.addPreservedID(LCSSAID);
84 AU.setPreservesCFG();
85 }
Chris Lattner7e755e42003-12-23 07:47:09 +000086
Chris Lattnere61b67d2004-04-02 20:24:31 +000087 private:
Devang Patel2ac57e12007-03-07 06:39:01 +000088
Chris Lattnere61b67d2004-04-02 20:24:31 +000089 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
90 std::set<Instruction*> &DeadInsts);
Chris Lattner51c95cd2006-09-21 05:12:20 +000091 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
92 SCEVExpander &RW);
Dan Gohman1fcc8042008-08-05 22:34:21 +000093 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
Chris Lattnere61b67d2004-04-02 20:24:31 +000094
95 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Devang Patel92b032f2008-09-09 21:41:07 +000096
97 void OptimizeCanonicalIVType(Loop *L);
Devang Patelc1631db2008-11-03 18:32:19 +000098 void HandleFloatingPointIV(Loop *L);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000099 };
Chris Lattner4184bcc2002-09-10 05:24:05 +0000100}
Chris Lattner91daaab2001-12-04 04:32:29 +0000101
Dan Gohmand78c4002008-05-13 00:00:25 +0000102char IndVarSimplify::ID = 0;
103static RegisterPass<IndVarSimplify>
104X("indvars", "Canonicalize Induction Variables");
105
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000106Pass *llvm::createIndVarSimplifyPass() {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000107 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +0000108}
109
Chris Lattnere61b67d2004-04-02 20:24:31 +0000110/// DeleteTriviallyDeadInstructions - If any of the instructions is the
111/// specified set are trivially dead, delete them and see if this makes any of
112/// their operands subsequently dead.
113void IndVarSimplify::
114DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
115 while (!Insts.empty()) {
116 Instruction *I = *Insts.begin();
117 Insts.erase(Insts.begin());
118 if (isInstructionTriviallyDead(I)) {
119 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
120 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
121 Insts.insert(U);
Dan Gohman32f53bb2007-06-19 14:28:31 +0000122 SE->deleteValueFromRecords(I);
Chris Lattner08165592007-01-07 01:14:12 +0000123 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattner9776f722004-10-11 23:06:50 +0000124 I->eraseFromParent();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000125 Changed = true;
126 }
127 }
128}
129
130
131/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
132/// recurrence. If so, change it into an integer recurrence, permitting
133/// analysis by the SCEV routines.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000134void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattnere61b67d2004-04-02 20:24:31 +0000135 BasicBlock *Preheader,
136 std::set<Instruction*> &DeadInsts) {
137 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
138 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
139 unsigned BackedgeIdx = PreheaderIdx^1;
140 if (GetElementPtrInst *GEPI =
Chris Lattner677d8572005-08-10 01:12:06 +0000141 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattnere61b67d2004-04-02 20:24:31 +0000142 if (GEPI->getOperand(0) == PN) {
Chris Lattner677d8572005-08-10 01:12:06 +0000143 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattner08165592007-01-07 01:14:12 +0000144 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
145
Chris Lattnere61b67d2004-04-02 20:24:31 +0000146 // Okay, we found a pointer recurrence. Transform this pointer
147 // recurrence into an integer recurrence. Compute the value that gets
148 // added to the pointer at every iteration.
149 Value *AddedVal = GEPI->getOperand(1);
150
151 // Insert a new integer PHI node into the top of the block.
Gabor Greife9ecc682008-04-06 20:25:17 +0000152 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
153 PN->getName()+".rec", PN);
Chris Lattnerc9e06332004-06-20 05:04:01 +0000154 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
155
Chris Lattnere61b67d2004-04-02 20:24:31 +0000156 // Create the new add instruction.
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000157 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
Chris Lattnerc9e06332004-06-20 05:04:01 +0000158 GEPI->getName()+".rec", GEPI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000159 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000160
Chris Lattnere61b67d2004-04-02 20:24:31 +0000161 // Update the existing GEP to use the recurrence.
162 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000163
Chris Lattnere61b67d2004-04-02 20:24:31 +0000164 // Update the GEP to use the new recurrence we just inserted.
165 GEPI->setOperand(1, NewAdd);
166
Chris Lattner9776f722004-10-11 23:06:50 +0000167 // If the incoming value is a constant expr GEP, try peeling out the array
168 // 0 index if possible to make things simpler.
169 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
170 if (CE->getOpcode() == Instruction::GetElementPtr) {
171 unsigned NumOps = CE->getNumOperands();
172 assert(NumOps > 1 && "CE folding didn't work!");
173 if (CE->getOperand(NumOps-1)->isNullValue()) {
174 // Check to make sure the last index really is an array index.
Chris Lattner9c37f232005-11-18 18:30:47 +0000175 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerbca0be82005-11-17 19:35:42 +0000176 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattner9776f722004-10-11 23:06:50 +0000177 i != e; ++i, ++GTI)
178 /*empty*/;
179 if (isa<SequentialType>(*GTI)) {
180 // Pull the last index out of the constant expr GEP.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000181 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattner9776f722004-10-11 23:06:50 +0000182 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000183 &CEIdxs[0],
184 CEIdxs.size());
David Greenec656cbb2007-09-04 15:46:09 +0000185 Value *Idx[2];
186 Idx[0] = Constant::getNullValue(Type::Int32Ty);
187 Idx[1] = NewAdd;
Gabor Greife9ecc682008-04-06 20:25:17 +0000188 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greenec656cbb2007-09-04 15:46:09 +0000189 NCE, Idx, Idx + 2,
Reid Spencer2e54a152007-03-02 00:28:52 +0000190 GEPI->getName(), GEPI);
Dan Gohman32f53bb2007-06-19 14:28:31 +0000191 SE->deleteValueFromRecords(GEPI);
Chris Lattner9776f722004-10-11 23:06:50 +0000192 GEPI->replaceAllUsesWith(NGEPI);
193 GEPI->eraseFromParent();
194 GEPI = NGEPI;
195 }
196 }
197 }
198
199
Chris Lattnere61b67d2004-04-02 20:24:31 +0000200 // Finally, if there are any other users of the PHI node, we must
201 // insert a new GEP instruction that uses the pre-incremented version
202 // of the induction amount.
203 if (!PN->use_empty()) {
204 BasicBlock::iterator InsertPos = PN; ++InsertPos;
205 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000206 Value *PreInc =
Gabor Greife9ecc682008-04-06 20:25:17 +0000207 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
208 NewPhi, "", InsertPos);
Chris Lattner6e0123b2007-02-11 01:23:03 +0000209 PreInc->takeName(PN);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000210 PN->replaceAllUsesWith(PreInc);
211 }
212
213 // Delete the old PHI for sure, and the GEP if its otherwise unused.
214 DeadInsts.insert(PN);
215
216 ++NumPointer;
217 Changed = true;
218 }
219}
220
221/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000222/// loop to be a canonical != comparison against the incremented loop induction
223/// variable. This pass is able to rewrite the exit tests of any loop where the
224/// SCEV analysis can determine a loop-invariant trip count of the loop, which
225/// is actually a much broader range than just linear tests.
Chris Lattner51c95cd2006-09-21 05:12:20 +0000226///
227/// This method returns a "potentially dead" instruction whose computation chain
228/// should be deleted when convenient.
229Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
230 SCEV *IterationCount,
231 SCEVExpander &RW) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000232 // Find the exit block for the loop. We can currently only handle loops with
233 // a single exit.
Devang Patelb5933bb2007-08-21 00:31:24 +0000234 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000235 L->getExitBlocks(ExitBlocks);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000236 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000237 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000238
239 // Make sure there is only one predecessor block in the loop.
240 BasicBlock *ExitingBlock = 0;
241 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
242 PI != PE; ++PI)
243 if (L->contains(*PI)) {
244 if (ExitingBlock == 0)
245 ExitingBlock = *PI;
246 else
Chris Lattner51c95cd2006-09-21 05:12:20 +0000247 return 0; // Multiple exits from loop to this block.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000248 }
249 assert(ExitingBlock && "Loop info is broken");
250
251 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000252 return 0; // Can't rewrite non-branch yet
Chris Lattnere61b67d2004-04-02 20:24:31 +0000253 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
254 assert(BI->isConditional() && "Must be conditional to be part of loop!");
255
Chris Lattner51c95cd2006-09-21 05:12:20 +0000256 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
257
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000258 // If the exiting block is not the same as the backedge block, we must compare
259 // against the preincremented value, otherwise we prefer to compare against
260 // the post-incremented value.
261 BasicBlock *Header = L->getHeader();
262 pred_iterator HPI = pred_begin(Header);
263 assert(HPI != pred_end(Header) && "Loop with zero preds???");
264 if (!L->contains(*HPI)) ++HPI;
265 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
266 "No backedge in loop?");
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000267
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000268 SCEVHandle TripCount = IterationCount;
269 Value *IndVar;
270 if (*HPI == ExitingBlock) {
271 // The IterationCount expression contains the number of times that the
272 // backedge actually branches to the loop header. This is one less than the
273 // number of times the loop executes, so add one to it.
Dan Gohman203a0352007-06-15 18:00:55 +0000274 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +0000275 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000276 IndVar = L->getCanonicalInductionVariableIncrement();
277 } else {
278 // We have to use the preincremented value...
279 IndVar = L->getCanonicalInductionVariable();
280 }
Chris Lattner08165592007-01-07 01:14:12 +0000281
282 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
283 << " IndVar = " << *IndVar << "\n";
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000284
Chris Lattnere61b67d2004-04-02 20:24:31 +0000285 // Expand the code for the iteration count into the preheader of the loop.
286 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000287 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
Chris Lattnere61b67d2004-04-02 20:24:31 +0000288
Reid Spencer266e42b2006-12-23 06:05:41 +0000289 // Insert a new icmp_ne or icmp_eq instruction before the branch.
290 ICmpInst::Predicate Opcode;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000291 if (L->contains(BI->getSuccessor(0)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000292 Opcode = ICmpInst::ICMP_NE;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000293 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000294 Opcode = ICmpInst::ICMP_EQ;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000295
Reid Spencer266e42b2006-12-23 06:05:41 +0000296 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000297 BI->setCondition(Cond);
298 ++NumLFTR;
299 Changed = true;
Chris Lattner51c95cd2006-09-21 05:12:20 +0000300 return PotentiallyDeadInst;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000301}
302
303
304/// RewriteLoopExitValues - Check to see if this loop has a computable
305/// loop-invariant execution count. If so, this means that we can compute the
306/// final value of any expressions that are recurrent in the loop, and
307/// substitute the exit values from the loop into any instructions outside of
308/// the loop that use the final values of the current expressions.
Dan Gohman1fcc8042008-08-05 22:34:21 +0000309void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000310 BasicBlock *Preheader = L->getLoopPreheader();
311
312 // Scan all of the instructions in the loop, looking at those that have
313 // extra-loop users and which are recurrences.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000314 SCEVExpander Rewriter(*SE, *LI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000315
316 // We insert the code into the preheader of the loop if the loop contains
317 // multiple exit blocks, or in the exit block if there is exactly one.
318 BasicBlock *BlockToInsertInto;
Devang Patelb5933bb2007-08-21 00:31:24 +0000319 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000320 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000321 if (ExitBlocks.size() == 1)
322 BlockToInsertInto = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000323 else
324 BlockToInsertInto = Preheader;
Dan Gohmanf96e1372008-05-23 21:05:58 +0000325 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000326
Dan Gohman1fcc8042008-08-05 22:34:21 +0000327 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
Chris Lattnera8140802004-04-17 18:44:09 +0000328
Chris Lattnere61b67d2004-04-02 20:24:31 +0000329 std::set<Instruction*> InstructionsToDelete;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000330 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000331
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000332 // Find all values that are computed inside the loop, but used outside of it.
333 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
334 // the exit blocks of the loop to find them.
335 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
336 BasicBlock *ExitBB = ExitBlocks[i];
337
338 // If there are no PHI nodes in this exit block, then no values defined
339 // inside the loop are used on this path, skip it.
340 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
341 if (!PN) continue;
342
343 unsigned NumPreds = PN->getNumIncomingValues();
344
345 // Iterate over all of the PHI nodes.
346 BasicBlock::iterator BBI = ExitBB->begin();
347 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnered30abf2007-03-03 22:48:48 +0000348
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000349 // Iterate over all of the values in all the PHI nodes.
350 for (unsigned i = 0; i != NumPreds; ++i) {
351 // If the value being merged in is not integer or is not defined
352 // in the loop, skip it.
353 Value *InVal = PN->getIncomingValue(i);
354 if (!isa<Instruction>(InVal) ||
355 // SCEV only supports integer expressions for now.
356 !isa<IntegerType>(InVal->getType()))
357 continue;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000358
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000359 // If this pred is for a subloop, not L itself, skip it.
360 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
361 continue; // The Block is in a subloop, skip it.
362
363 // Check that InVal is defined in the loop.
364 Instruction *Inst = cast<Instruction>(InVal);
365 if (!L->contains(Inst->getParent()))
366 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000367
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000368 // We require that this value either have a computable evolution or that
369 // the loop have a constant iteration count. In the case where the loop
370 // has a constant iteration count, we can sometimes force evaluation of
371 // the exit value through brute force.
372 SCEVHandle SH = SE->getSCEV(Inst);
373 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
374 continue; // Cannot get exit evolution for the loop value.
375
376 // Okay, this instruction has a user outside of the current loop
377 // and varies predictably *inside* the loop. Evaluate the value it
378 // contains when the loop exits, if possible.
379 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
380 if (isa<SCEVCouldNotCompute>(ExitValue) ||
381 !ExitValue->isLoopInvariant(L))
382 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000383
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000384 Changed = true;
385 ++NumReplaced;
386
387 // See if we already computed the exit value for the instruction, if so,
388 // just reuse it.
389 Value *&ExitVal = ExitValues[Inst];
390 if (!ExitVal)
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000391 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000392
393 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
394 << " LoopVal = " << *Inst << "\n";
395
396 PN->setIncomingValue(i, ExitVal);
397
398 // If this instruction is dead now, schedule it to be removed.
399 if (Inst->use_empty())
400 InstructionsToDelete.insert(Inst);
401
402 // See if this is a single-entry LCSSA PHI node. If so, we can (and
403 // have to) remove
Chris Lattner1f7648e2007-03-04 01:00:28 +0000404 // the PHI entirely. This is safe, because the NewVal won't be variant
405 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000406 if (NumPreds == 1) {
Dan Gohman32f53bb2007-06-19 14:28:31 +0000407 SE->deleteValueFromRecords(PN);
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000408 PN->replaceAllUsesWith(ExitVal);
409 PN->eraseFromParent();
410 break;
Chris Lattnered30abf2007-03-03 22:48:48 +0000411 }
412 }
Chris Lattnered30abf2007-03-03 22:48:48 +0000413 }
414 }
415
Chris Lattnere61b67d2004-04-02 20:24:31 +0000416 DeleteTriviallyDeadInstructions(InstructionsToDelete);
417}
418
Devang Patel2ac57e12007-03-07 06:39:01 +0000419bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000420
Devang Patel2ac57e12007-03-07 06:39:01 +0000421 Changed = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000422 // First step. Check to see if there are any trivial GEP pointer recurrences.
423 // If there are, change them into integer recurrences, permitting analysis by
424 // the SCEV routines.
425 //
426 BasicBlock *Header = L->getHeader();
427 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel2ac57e12007-03-07 06:39:01 +0000428 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000429
Chris Lattnere61b67d2004-04-02 20:24:31 +0000430 std::set<Instruction*> DeadInsts;
Reid Spencer66149462004-09-15 17:06:42 +0000431 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
432 PHINode *PN = cast<PHINode>(I);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000433 if (isa<PointerType>(PN->getType()))
434 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer66149462004-09-15 17:06:42 +0000435 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000436
437 if (!DeadInsts.empty())
438 DeleteTriviallyDeadInstructions(DeadInsts);
439
Devang Patel2ac57e12007-03-07 06:39:01 +0000440 return Changed;
441}
Chris Lattnere61b67d2004-04-02 20:24:31 +0000442
Devang Patel2ac57e12007-03-07 06:39:01 +0000443bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000444
Devang Patel2ac57e12007-03-07 06:39:01 +0000445
446 LI = &getAnalysis<LoopInfo>();
447 SE = &getAnalysis<ScalarEvolution>();
448
449 Changed = false;
450 BasicBlock *Header = L->getHeader();
451 std::set<Instruction*> DeadInsts;
452
Chris Lattner1f7648e2007-03-04 01:00:28 +0000453 // Verify the input to the pass in already in LCSSA form.
454 assert(L->isLCSSAForm());
455
Chris Lattnere61b67d2004-04-02 20:24:31 +0000456 // Check to see if this loop has a computable loop-invariant execution count.
457 // If so, this means that we can compute the final value of any expressions
458 // that are recurrent in the loop, and substitute the exit values from the
459 // loop into any instructions outside of the loop that use the final values of
460 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000461 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000462 SCEVHandle IterationCount = SE->getIterationCount(L);
463 if (!isa<SCEVCouldNotCompute>(IterationCount))
Dan Gohman1fcc8042008-08-05 22:34:21 +0000464 RewriteLoopExitValues(L, IterationCount);
Chris Lattner476e6df2001-12-03 17:28:42 +0000465
Chris Lattnere61b67d2004-04-02 20:24:31 +0000466 // Next, analyze all of the induction variables in the loop, canonicalizing
467 // auxillary induction variables.
468 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
469
Devang Patelc1631db2008-11-03 18:32:19 +0000470 HandleFloatingPointIV(L);
Reid Spencer66149462004-09-15 17:06:42 +0000471 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
472 PHINode *PN = cast<PHINode>(I);
Chris Lattner03c49532007-01-15 02:27:26 +0000473 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattnere61b67d2004-04-02 20:24:31 +0000474 SCEVHandle SCEV = SE->getSCEV(PN);
475 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattner677d8572005-08-10 01:12:06 +0000476 // FIXME: It is an extremely bad idea to indvar substitute anything more
477 // complex than affine induction variables. Doing so will put expensive
478 // polynomial evaluations inside of the loop, and the str reduction pass
479 // currently can only reduce affine polynomials. For now just disable
480 // indvar subst on anything more complex than an affine addrec.
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000481 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattner677d8572005-08-10 01:12:06 +0000482 if (AR->isAffine())
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000483 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000484 }
Reid Spencer66149462004-09-15 17:06:42 +0000485 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000486
487 // If there are no induction variables in the loop, there is nothing more to
488 // do.
Chris Lattner885a6eb2004-04-17 18:08:33 +0000489 if (IndVars.empty()) {
490 // Actually, if we know how many times the loop iterates, lets insert a
491 // canonical induction variable to help subsequent passes.
492 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner83cd87e2004-04-23 21:29:48 +0000493 SCEVExpander Rewriter(*SE, *LI);
494 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattner885a6eb2004-04-17 18:08:33 +0000495 IterationCount->getType());
Chris Lattner51c95cd2006-09-21 05:12:20 +0000496 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
497 Rewriter)) {
498 std::set<Instruction*> InstructionsToDelete;
499 InstructionsToDelete.insert(I);
500 DeleteTriviallyDeadInstructions(InstructionsToDelete);
501 }
Chris Lattner885a6eb2004-04-17 18:08:33 +0000502 }
Devang Patel2ac57e12007-03-07 06:39:01 +0000503 return Changed;
Chris Lattner885a6eb2004-04-17 18:08:33 +0000504 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000505
506 // Compute the type of the largest recurrence expression.
Chris Lattner476e6df2001-12-03 17:28:42 +0000507 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000508 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000509 bool DifferingSizes = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000510 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
511 const Type *Ty = IndVars[i].first->getType();
Reid Spencer8f166b02007-01-08 16:32:00 +0000512 DifferingSizes |=
513 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
514 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattnere61b67d2004-04-02 20:24:31 +0000515 LargestType = Ty;
Chris Lattner476e6df2001-12-03 17:28:42 +0000516 }
517
Chris Lattnere61b67d2004-04-02 20:24:31 +0000518 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000519 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000520
Chris Lattnere61b67d2004-04-02 20:24:31 +0000521 // Now that we know the largest of of the induction variables in this loop,
522 // insert a canonical induction variable of the largest size.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000523 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000524 ++NumInserted;
525 Changed = true;
Chris Lattner08165592007-01-07 01:14:12 +0000526 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner7e755e42003-12-23 07:47:09 +0000527
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000528 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Wojciech Matyjewicz25a7f5d2008-06-13 17:02:03 +0000529 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000530 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
531 DeadInsts.insert(DI);
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000532 }
Chris Lattner7e755e42003-12-23 07:47:09 +0000533
Chris Lattnere61b67d2004-04-02 20:24:31 +0000534 // Now that we have a canonical induction variable, we can rewrite any
535 // recurrences in terms of the induction variable. Start with the auxillary
536 // induction variables, and recursively rewrite any of their uses.
Dan Gohmanf96e1372008-05-23 21:05:58 +0000537 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
Chris Lattner476e6df2001-12-03 17:28:42 +0000538
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000539 // If there were induction variables of other sizes, cast the primary
540 // induction variable to the right size for them, avoiding the need for the
541 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000542 if (DifferingSizes) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000543 SmallVector<unsigned,4> InsertedSizes;
544 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
545 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
546 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5e52362007-01-12 22:51:20 +0000547 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
548 == InsertedSizes.end()) {
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000549 PHINode *PN = IndVars[i].first;
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000550 InsertedSizes.push_back(ithSize);
Chris Lattner08165592007-01-07 01:14:12 +0000551 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
552 InsertPt);
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000553 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattner08165592007-01-07 01:14:12 +0000554 DOUT << "INDVARS: Made trunc IV for " << *PN
555 << " NewVal = " << *New << "\n";
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000556 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000557 }
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000558 }
559
Chris Lattner08165592007-01-07 01:14:12 +0000560 // Rewrite all induction variables in terms of the canonical induction
561 // variable.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000562 while (!IndVars.empty()) {
563 PHINode *PN = IndVars.back().first;
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000564 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
Chris Lattner08165592007-01-07 01:14:12 +0000565 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
566 << " into = " << *NewVal << "\n";
Chris Lattner6e0123b2007-02-11 01:23:03 +0000567 NewVal->takeName(PN);
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000568
Chris Lattnere61b67d2004-04-02 20:24:31 +0000569 // Replace the old PHI Node with the inserted computation.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000570 PN->replaceAllUsesWith(NewVal);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000571 DeadInsts.insert(PN);
572 IndVars.pop_back();
573 ++NumRemoved;
Chris Lattner67439402001-12-05 19:41:33 +0000574 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000575 }
576
Chris Lattnerc27302c2004-04-22 15:12:36 +0000577#if 0
Chris Lattneraf532f22004-04-21 23:36:08 +0000578 // Now replace all derived expressions in the loop body with simpler
579 // expressions.
Dan Gohman90071072008-06-22 20:18:58 +0000580 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
581 I != E; ++I) {
582 BasicBlock *BB = *I;
583 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
Chris Lattnere61b67d2004-04-02 20:24:31 +0000584 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner03c49532007-01-15 02:27:26 +0000585 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattneraf532f22004-04-21 23:36:08 +0000586 !I->use_empty() &&
Chris Lattnere61b67d2004-04-02 20:24:31 +0000587 !Rewriter.isInsertedInstruction(I)) {
588 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner83cd87e2004-04-23 21:29:48 +0000589 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattneraf532f22004-04-21 23:36:08 +0000590 if (V != I) {
Chris Lattner6e0123b2007-02-11 01:23:03 +0000591 if (isa<Instruction>(V))
592 V->takeName(I);
Chris Lattneraf532f22004-04-21 23:36:08 +0000593 I->replaceAllUsesWith(V);
594 DeadInsts.insert(I);
595 ++NumRemoved;
596 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000597 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000598 }
Chris Lattner91daaab2001-12-04 04:32:29 +0000599 }
Dan Gohman90071072008-06-22 20:18:58 +0000600 }
Chris Lattnerc27302c2004-04-22 15:12:36 +0000601#endif
Chris Lattneraf532f22004-04-21 23:36:08 +0000602
Chris Lattneraf532f22004-04-21 23:36:08 +0000603 DeleteTriviallyDeadInstructions(DeadInsts);
Devang Patel92b032f2008-09-09 21:41:07 +0000604 OptimizeCanonicalIVType(L);
Chris Lattner1f7648e2007-03-04 01:00:28 +0000605 assert(L->isLCSSAForm());
Devang Patel2ac57e12007-03-07 06:39:01 +0000606 return Changed;
Chris Lattner476e6df2001-12-03 17:28:42 +0000607}
Devang Patel92b032f2008-09-09 21:41:07 +0000608
609/// OptimizeCanonicalIVType - If loop induction variable is always
Devang Patel728c44a2008-09-10 14:49:55 +0000610/// sign or zero extended then extend the type of the induction
Devang Patel92b032f2008-09-09 21:41:07 +0000611/// variable.
612void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
613 PHINode *PH = L->getCanonicalInductionVariable();
614 if (!PH) return;
615
616 // Check loop iteration count.
617 SCEVHandle IC = SE->getIterationCount(L);
618 if (isa<SCEVCouldNotCompute>(IC)) return;
619 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
620 if (!IterationCount) return;
621
622 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
623 unsigned BackEdge = IncomingEdge^1;
624
625 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
626 // IV increment instruction) then this IV is suitable for this
Devang Patel728c44a2008-09-10 14:49:55 +0000627 // transformation.
628 bool isSEXT = false;
Devang Patel92b032f2008-09-09 21:41:07 +0000629 BinaryOperator *Incr = NULL;
Devang Patel728c44a2008-09-10 14:49:55 +0000630 const Type *NewType = NULL;
Devang Patel92b032f2008-09-09 21:41:07 +0000631 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
632 UI != UE; ++UI) {
633 const Type *CandidateType = NULL;
634 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
635 CandidateType = ZI->getDestTy();
636 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
637 CandidateType = SI->getDestTy();
Devang Patel728c44a2008-09-10 14:49:55 +0000638 isSEXT = true;
Devang Patel92b032f2008-09-09 21:41:07 +0000639 }
640 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
641 // Validate IV increment instruction.
642 if (PH->getIncomingValue(BackEdge) == Incr)
643 continue;
644 }
645 if (!CandidateType) {
646 NewType = NULL;
647 break;
648 }
649 if (!NewType)
650 NewType = CandidateType;
651 else if (NewType != CandidateType) {
652 NewType = NULL;
653 break;
654 }
655 }
656
657 // IV uses are not suitable then avoid this transformation.
658 if (!NewType || !Incr)
659 return;
660
661 // IV increment instruction has two uses, one is loop exit condition
662 // and second is the IV (phi node) itself.
663 ICmpInst *Exit = NULL;
664 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
665 II != IE; ++II) {
666 if (PH == *II) continue;
667 Exit = dyn_cast<ICmpInst>(*II);
668 break;
669 }
670 if (!Exit) return;
671 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
672 if (!EV)
673 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
674 if (!EV) return;
675
676 // Check iteration count max value to avoid loops that wrap around IV.
677 APInt ICount = IterationCount->getValue()->getValue();
678 if (ICount.isNegative()) return;
679 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
680 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
681 if (ICount.getZExtValue() > Max.getZExtValue()) return;
682
683 // Extend IV type.
684
685 SCEVExpander Rewriter(*SE, *LI);
686 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
687 PHINode *NewPH = cast<PHINode>(NewIV);
688 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
689
690 // Replace all SEXT or ZEXT uses.
691 SmallVector<Instruction *, 4> PHUses;
692 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
693 UI != UE; ++UI) {
694 Instruction *I = cast<Instruction>(UI);
695 PHUses.push_back(I);
696 }
697 while (!PHUses.empty()){
698 Instruction *Use = PHUses.back(); PHUses.pop_back();
699 if (Incr == Use) continue;
700
701 SE->deleteValueFromRecords(Use);
702 Use->replaceAllUsesWith(NewIV);
703 Use->eraseFromParent();
704 }
705
706 // Replace exit condition.
707 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
708 Instruction *NE = new ICmpInst(Exit->getPredicate(),
709 NewIncr, NEV, "new.exit",
710 Exit->getParent()->getTerminator());
711 SE->deleteValueFromRecords(Exit);
712 Exit->replaceAllUsesWith(NE);
713 Exit->eraseFromParent();
714
715 // Remove old IV and increment instructions.
716 SE->deleteValueFromRecords(PH);
717 PH->removeIncomingValue((unsigned)0);
718 PH->removeIncomingValue((unsigned)0);
719 SE->deleteValueFromRecords(Incr);
720 Incr->eraseFromParent();
721}
722
Devang Patelc1631db2008-11-03 18:32:19 +0000723/// HandleFloatingPointIV - If the loop has floating induction variable
724/// then insert corresponding integer induction variable if possible.
725void IndVarSimplify::HandleFloatingPointIV(Loop *L) {
726 BasicBlock *Header = L->getHeader();
727 SmallVector <PHINode *, 4> FPHIs;
728 Instruction *NonPHIInsn = NULL;
729
730 // Collect all floating point IVs first.
731 BasicBlock::iterator I = Header->begin();
732 while(true) {
733 if (!isa<PHINode>(I)) {
734 NonPHIInsn = I;
735 break;
736 }
737 PHINode *PH = cast<PHINode>(I);
738 if (PH->getType()->isFloatingPoint())
739 FPHIs.push_back(PH);
740 ++I;
741 }
742
743 for (SmallVector<PHINode *, 4>::iterator I = FPHIs.begin(), E = FPHIs.end();
744 I != E; ++I) {
745 PHINode *PH = *I;
746 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
747 unsigned BackEdge = IncomingEdge^1;
748
749 // Check incoming value.
750 ConstantFP *CZ = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
751 if (!CZ) continue;
752 APFloat PHInit = CZ->getValueAPF();
753 if (!PHInit.isPosZero()) continue;
754
755 // Check IV increment.
756 BinaryOperator *Incr =
757 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
758 if (!Incr) continue;
759 if (Incr->getOpcode() != Instruction::Add) continue;
760 ConstantFP *IncrValue = NULL;
761 unsigned IncrVIndex = 1;
762 if (Incr->getOperand(1) == PH)
763 IncrVIndex = 0;
764 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
765 if (!IncrValue) continue;
766 APFloat IVAPF = IncrValue->getValueAPF();
767 APFloat One = APFloat(IVAPF.getSemantics(), 1);
768 if (!IVAPF.bitwiseIsEqual(One)) continue;
769
770 // Check Incr uses.
771 Value::use_iterator IncrUse = Incr->use_begin();
772 Instruction *U1 = cast<Instruction>(IncrUse++);
773 if (IncrUse == Incr->use_end()) continue;
774 Instruction *U2 = cast<Instruction>(IncrUse++);
775 if (IncrUse != Incr->use_end()) continue;
776
777 // Find exict condition.
778 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
779 if (!EC)
780 EC = dyn_cast<FCmpInst>(U2);
781 if (!EC) continue;
782 bool skip = false;
783 Instruction *Terminator = EC->getParent()->getTerminator();
784 for(Value::use_iterator ECUI = EC->use_begin(), ECUE = EC->use_end();
785 ECUI != ECUE; ++ECUI) {
786 Instruction *U = cast<Instruction>(ECUI);
787 if (U != Terminator) {
788 skip = true;
789 break;
790 }
791 }
792 if (skip) continue;
793
794 // Find exit value.
795 ConstantFP *EV = NULL;
796 unsigned EVIndex = 1;
797 if (EC->getOperand(1) == Incr)
798 EVIndex = 0;
799 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
800 if (!EV) continue;
801 APFloat EVAPF = EV->getValueAPF();
802 if (EVAPF.isNegative()) continue;
803
804 // Find corresponding integer exit value.
805 uint64_t integerVal = Type::Int32Ty->getPrimitiveSizeInBits();
806 bool isExact = false;
807 if (EVAPF.convertToInteger(&integerVal, 32, false, APFloat::rmTowardZero, &isExact)
808 != APFloat::opOK)
809 continue;
810 if (!isExact) continue;
811
812 // Find new predicate for integer comparison.
813 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
814 switch (EC->getPredicate()) {
815 case CmpInst::FCMP_OEQ:
816 case CmpInst::FCMP_UEQ:
817 NewPred = CmpInst::ICMP_EQ;
818 break;
819 case CmpInst::FCMP_OGT:
820 case CmpInst::FCMP_UGT:
821 NewPred = CmpInst::ICMP_UGT;
822 break;
823 case CmpInst::FCMP_OGE:
824 case CmpInst::FCMP_UGE:
825 NewPred = CmpInst::ICMP_UGE;
826 break;
827 case CmpInst::FCMP_OLT:
828 case CmpInst::FCMP_ULT:
829 NewPred = CmpInst::ICMP_ULT;
830 break;
831 case CmpInst::FCMP_OLE:
832 case CmpInst::FCMP_ULE:
833 NewPred = CmpInst::ICMP_ULE;
834 break;
835 default:
836 break;
837 }
838 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) continue;
839
840 // Insert new integer induction variable.
841 SCEVExpander Rewriter(*SE, *LI);
842 PHINode *NewIV =
843 cast<PHINode>(Rewriter.getOrInsertCanonicalInductionVariable(L,Type::Int32Ty));
844 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, integerVal);
845 Value *LHS = (EVIndex == 1 ? NewIV->getIncomingValue(BackEdge) : NewEV);
846 Value *RHS = (EVIndex == 1 ? NewEV : NewIV->getIncomingValue(BackEdge));
847 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
848 EC->getParent()->getTerminator());
849
850 // Delete old, floating point, exit comparision instruction.
851 SE->deleteValueFromRecords(EC);
852 EC->replaceAllUsesWith(NewEC);
853 EC->eraseFromParent();
854
855 // Delete old, floating point, increment instruction.
856 SE->deleteValueFromRecords(Incr);
857 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
858 Incr->eraseFromParent();
859
860 // Replace floating induction variable.
861 UIToFPInst *Conv = new UIToFPInst(NewIV, PH->getType(), "indvar.conv",
862 NonPHIInsn);
863 PH->replaceAllUsesWith(Conv);
864
865 SE->deleteValueFromRecords(PH);
866 PH->removeIncomingValue((unsigned)0);
867 PH->removeIncomingValue((unsigned)0);
868 }
869}
870