blob: 0622b170c8c6643d13468853345f6b2a91db1efe [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
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//
14// This transformation make 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).
Chris Lattner476e6df2001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000040#include "llvm/Transforms/Scalar.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000041#include "llvm/BasicBlock.h"
42#include "llvm/Constant.h"
Chris Lattner6449dce2003-12-22 05:02:01 +000043#include "llvm/Instructions.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000044#include "llvm/Type.h"
45#include "llvm/Analysis/ScalarEvolution.h"
John Criswellb22e9b42003-12-18 17:19:19 +000046#include "llvm/Analysis/LoopInfo.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000047#include "llvm/Support/CFG.h"
John Criswellb22e9b42003-12-18 17:19:19 +000048#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere61b67d2004-04-02 20:24:31 +000049#include "Support/CommandLine.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000050#include "Support/Statistic.h"
John Criswellb22e9b42003-12-18 17:19:19 +000051using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000052
Chris Lattner4184bcc2002-09-10 05:24:05 +000053namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000054 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattnere61b67d2004-04-02 20:24:31 +000055 Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
Chris Lattner4e621cd2003-09-10 05:24:46 +000056 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattnere61b67d2004-04-02 20:24:31 +000057 Statistic<> NumReplaced("indvars", "Number of exit values replaced");
58 Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000059
60 class IndVarSimplify : public FunctionPass {
Chris Lattnere61b67d2004-04-02 20:24:31 +000061 LoopInfo *LI;
62 ScalarEvolution *SE;
Chris Lattner7e755e42003-12-23 07:47:09 +000063 bool Changed;
Chris Lattnerd3678bc2003-12-22 03:58:44 +000064 public:
65 virtual bool runOnFunction(Function &) {
Chris Lattnere61b67d2004-04-02 20:24:31 +000066 LI = &getAnalysis<LoopInfo>();
67 SE = &getAnalysis<ScalarEvolution>();
Chris Lattner7e755e42003-12-23 07:47:09 +000068 Changed = false;
69
Chris Lattnerd3678bc2003-12-22 03:58:44 +000070 // Induction Variables live in the header nodes of loops
Chris Lattnere61b67d2004-04-02 20:24:31 +000071 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +000072 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000073 return Changed;
74 }
75
Chris Lattnerd3678bc2003-12-22 03:58:44 +000076 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerd3678bc2003-12-22 03:58:44 +000077 AU.addRequiredID(LoopSimplifyID);
Chris Lattnere61b67d2004-04-02 20:24:31 +000078 AU.addRequired<ScalarEvolution>();
79 AU.addRequired<LoopInfo>();
Chris Lattnerd3678bc2003-12-22 03:58:44 +000080 AU.addPreservedID(LoopSimplifyID);
81 AU.setPreservesCFG();
82 }
Chris Lattnere61b67d2004-04-02 20:24:31 +000083 private:
84 void runOnLoop(Loop *L);
85 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
86 std::set<Instruction*> &DeadInsts);
87 void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
88 Value *IndVar, ScalarEvolutionRewriter &RW);
89 void RewriteLoopExitValues(Loop *L);
90
91 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000092 };
93 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner4184bcc2002-09-10 05:24:05 +000094}
Chris Lattner91daaab2001-12-04 04:32:29 +000095
Chris Lattnerd3678bc2003-12-22 03:58:44 +000096Pass *llvm::createIndVarSimplifyPass() {
97 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +000098}
99
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000100
Chris Lattnere61b67d2004-04-02 20:24:31 +0000101/// DeleteTriviallyDeadInstructions - If any of the instructions is the
102/// specified set are trivially dead, delete them and see if this makes any of
103/// their operands subsequently dead.
104void IndVarSimplify::
105DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
106 while (!Insts.empty()) {
107 Instruction *I = *Insts.begin();
108 Insts.erase(Insts.begin());
109 if (isInstructionTriviallyDead(I)) {
110 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
111 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
112 Insts.insert(U);
113 SE->deleteInstructionFromRecords(I);
114 I->getParent()->getInstList().erase(I);
115 Changed = true;
116 }
117 }
118}
119
120
121/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
122/// recurrence. If so, change it into an integer recurrence, permitting
123/// analysis by the SCEV routines.
124void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
125 BasicBlock *Preheader,
126 std::set<Instruction*> &DeadInsts) {
127 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
128 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
129 unsigned BackedgeIdx = PreheaderIdx^1;
130 if (GetElementPtrInst *GEPI =
131 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
132 if (GEPI->getOperand(0) == PN) {
133 assert(GEPI->getNumOperands() == 2 && "GEP types must mismatch!");
134
135 // Okay, we found a pointer recurrence. Transform this pointer
136 // recurrence into an integer recurrence. Compute the value that gets
137 // added to the pointer at every iteration.
138 Value *AddedVal = GEPI->getOperand(1);
139
140 // Insert a new integer PHI node into the top of the block.
141 PHINode *NewPhi = new PHINode(AddedVal->getType(),
142 PN->getName()+".rec", PN);
143 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()),
144 Preheader);
145 // Create the new add instruction.
146 Value *NewAdd = BinaryOperator::create(Instruction::Add, NewPhi,
147 AddedVal,
148 GEPI->getName()+".rec", GEPI);
149 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
150
151 // Update the existing GEP to use the recurrence.
152 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
153
154 // Update the GEP to use the new recurrence we just inserted.
155 GEPI->setOperand(1, NewAdd);
156
157 // Finally, if there are any other users of the PHI node, we must
158 // insert a new GEP instruction that uses the pre-incremented version
159 // of the induction amount.
160 if (!PN->use_empty()) {
161 BasicBlock::iterator InsertPos = PN; ++InsertPos;
162 while (isa<PHINode>(InsertPos)) ++InsertPos;
163 std::string Name = PN->getName(); PN->setName("");
164 Value *PreInc =
165 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
166 std::vector<Value*>(1, NewPhi), Name,
167 InsertPos);
168 PN->replaceAllUsesWith(PreInc);
169 }
170
171 // Delete the old PHI for sure, and the GEP if its otherwise unused.
172 DeadInsts.insert(PN);
173
174 ++NumPointer;
175 Changed = true;
176 }
177}
178
179/// LinearFunctionTestReplace - This method rewrites the exit condition of the
180/// loop to be a canonical != comparison against the loop induction variable.
181/// This pass is able to rewrite the exit tests of any loop where the SCEV
182/// analysis can determine the trip count of the loop, which is actually a much
183/// broader range than just linear tests.
184void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
185 Value *IndVar,
186 ScalarEvolutionRewriter &RW) {
187 // Find the exit block for the loop. We can currently only handle loops with
188 // a single exit.
189 if (L->getExitBlocks().size() != 1) return;
190 BasicBlock *ExitBlock = L->getExitBlocks()[0];
191
192 // Make sure there is only one predecessor block in the loop.
193 BasicBlock *ExitingBlock = 0;
194 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
195 PI != PE; ++PI)
196 if (L->contains(*PI)) {
197 if (ExitingBlock == 0)
198 ExitingBlock = *PI;
199 else
200 return; // Multiple exits from loop to this block.
201 }
202 assert(ExitingBlock && "Loop info is broken");
203
204 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
205 return; // Can't rewrite non-branch yet
206 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
207 assert(BI->isConditional() && "Must be conditional to be part of loop!");
208
209 std::set<Instruction*> InstructionsToDelete;
210 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
211 InstructionsToDelete.insert(Cond);
212
213 // Expand the code for the iteration count into the preheader of the loop.
214 BasicBlock *Preheader = L->getLoopPreheader();
215 Value *ExitCnt = RW.ExpandCodeFor(IterationCount, Preheader->getTerminator(),
216 IndVar->getType());
217
218 // Insert a new setne or seteq instruction before the branch.
219 Instruction::BinaryOps Opcode;
220 if (L->contains(BI->getSuccessor(0)))
221 Opcode = Instruction::SetNE;
222 else
223 Opcode = Instruction::SetEQ;
224
225 Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
226 BI->setCondition(Cond);
227 ++NumLFTR;
228 Changed = true;
229
230 DeleteTriviallyDeadInstructions(InstructionsToDelete);
231}
232
233
234/// RewriteLoopExitValues - Check to see if this loop has a computable
235/// loop-invariant execution count. If so, this means that we can compute the
236/// final value of any expressions that are recurrent in the loop, and
237/// substitute the exit values from the loop into any instructions outside of
238/// the loop that use the final values of the current expressions.
239void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
240 BasicBlock *Preheader = L->getLoopPreheader();
241
242 // Scan all of the instructions in the loop, looking at those that have
243 // extra-loop users and which are recurrences.
244 ScalarEvolutionRewriter Rewriter(*SE, *LI);
245
246 // We insert the code into the preheader of the loop if the loop contains
247 // multiple exit blocks, or in the exit block if there is exactly one.
248 BasicBlock *BlockToInsertInto;
249 if (L->getExitBlocks().size() == 1)
250 BlockToInsertInto = L->getExitBlocks()[0];
251 else
252 BlockToInsertInto = Preheader;
253 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
254 while (isa<PHINode>(InsertPt)) ++InsertPt;
255
256 std::set<Instruction*> InstructionsToDelete;
257
258 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
259 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
260 BasicBlock *BB = L->getBlocks()[i];
261 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
262 if (I->getType()->isInteger()) { // Is an integer instruction
263 SCEVHandle SH = SE->getSCEV(I);
264 if (SH->hasComputableLoopEvolution(L)) { // Varies predictably
265 // Find out if this predictably varying value is actually used
266 // outside of the loop. "extra" as opposed to "intra".
267 std::vector<User*> ExtraLoopUsers;
268 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
269 UI != E; ++UI)
270 if (!L->contains(cast<Instruction>(*UI)->getParent()))
271 ExtraLoopUsers.push_back(*UI);
272 if (!ExtraLoopUsers.empty()) {
273 // Okay, this instruction has a user outside of the current loop
274 // and varies predictably in this loop. Evaluate the value it
275 // contains when the loop exits, and insert code for it.
276 SCEVHandle ExitValue = SE->getSCEVAtScope(I,L->getParentLoop());
277 if (!isa<SCEVCouldNotCompute>(ExitValue)) {
278 Changed = true;
279 ++NumReplaced;
280 Value *NewVal = Rewriter.ExpandCodeFor(ExitValue, InsertPt,
281 I->getType());
282
283 // Rewrite any users of the computed value outside of the loop
284 // with the newly computed value.
285 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i)
286 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
287
288 // If this instruction is dead now, schedule it to be removed.
289 if (I->use_empty())
290 InstructionsToDelete.insert(I);
291 }
292 }
293 }
294 }
295 }
296
297 DeleteTriviallyDeadInstructions(InstructionsToDelete);
298}
299
300
301void IndVarSimplify::runOnLoop(Loop *L) {
302 // First step. Check to see if there are any trivial GEP pointer recurrences.
303 // If there are, change them into integer recurrences, permitting analysis by
304 // the SCEV routines.
305 //
306 BasicBlock *Header = L->getHeader();
307 BasicBlock *Preheader = L->getLoopPreheader();
308
309 std::set<Instruction*> DeadInsts;
310 for (BasicBlock::iterator I = Header->begin();
311 PHINode *PN = dyn_cast<PHINode>(I); ++I)
312 if (isa<PointerType>(PN->getType()))
313 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
314
315 if (!DeadInsts.empty())
316 DeleteTriviallyDeadInstructions(DeadInsts);
317
318
319 // Next, transform all loops nesting inside of this loop.
320 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000321 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000322
Chris Lattnere61b67d2004-04-02 20:24:31 +0000323 // Check to see if this loop has a computable loop-invariant execution count.
324 // If so, this means that we can compute the final value of any expressions
325 // that are recurrent in the loop, and substitute the exit values from the
326 // loop into any instructions outside of the loop that use the final values of
327 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000328 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000329 SCEVHandle IterationCount = SE->getIterationCount(L);
330 if (!isa<SCEVCouldNotCompute>(IterationCount))
331 RewriteLoopExitValues(L);
Chris Lattner476e6df2001-12-03 17:28:42 +0000332
Chris Lattnere61b67d2004-04-02 20:24:31 +0000333 // Next, analyze all of the induction variables in the loop, canonicalizing
334 // auxillary induction variables.
335 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
336
337 for (BasicBlock::iterator I = Header->begin();
338 PHINode *PN = dyn_cast<PHINode>(I); ++I)
339 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
340 SCEVHandle SCEV = SE->getSCEV(PN);
341 if (SCEV->hasComputableLoopEvolution(L))
342 if (SE->shouldSubstituteIndVar(SCEV)) // HACK!
343 IndVars.push_back(std::make_pair(PN, SCEV));
344 }
345
346 // If there are no induction variables in the loop, there is nothing more to
347 // do.
Chris Lattner7e755e42003-12-23 07:47:09 +0000348 if (IndVars.empty()) return;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000349
350 // Compute the type of the largest recurrence expression.
Chris Lattner476e6df2001-12-03 17:28:42 +0000351 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000352 const Type *LargestType = IndVars[0].first->getType();
353 bool DifferingSizes = false;
354 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
355 const Type *Ty = IndVars[i].first->getType();
356 DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
357 if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
358 LargestType = Ty;
Chris Lattner476e6df2001-12-03 17:28:42 +0000359 }
360
Chris Lattnere61b67d2004-04-02 20:24:31 +0000361 // Create a rewriter object which we'll use to transform the code with.
362 ScalarEvolutionRewriter Rewriter(*SE, *LI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000363
Chris Lattnere61b67d2004-04-02 20:24:31 +0000364 // Now that we know the largest of of the induction variables in this loop,
365 // insert a canonical induction variable of the largest size.
366 Value *IndVar = Rewriter.GetOrInsertCanonicalInductionVariable(L,LargestType);
367 ++NumInserted;
368 Changed = true;
Chris Lattner7e755e42003-12-23 07:47:09 +0000369
Chris Lattnere61b67d2004-04-02 20:24:31 +0000370 if (!isa<SCEVCouldNotCompute>(IterationCount))
371 LinearFunctionTestReplace(L, IterationCount, IndVar, Rewriter);
Chris Lattner7e755e42003-12-23 07:47:09 +0000372
Chris Lattnere61b67d2004-04-02 20:24:31 +0000373#if 0
374 // If there were induction variables of other sizes, cast the primary
375 // induction variable to the right size for them, avoiding the need for the
376 // code evaluation methods to insert induction variables of different sizes.
377 // FIXME!
378 if (DifferingSizes) {
379 std::map<unsigned, Value*> InsertedSizes;
380 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
381 }
Chris Lattner7e755e42003-12-23 07:47:09 +0000382 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000383#endif
Chris Lattner7e755e42003-12-23 07:47:09 +0000384
Chris Lattnere61b67d2004-04-02 20:24:31 +0000385 // Now that we have a canonical induction variable, we can rewrite any
386 // recurrences in terms of the induction variable. Start with the auxillary
387 // induction variables, and recursively rewrite any of their uses.
388 BasicBlock::iterator InsertPt = Header->begin();
389 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner476e6df2001-12-03 17:28:42 +0000390
Chris Lattnere61b67d2004-04-02 20:24:31 +0000391 while (!IndVars.empty()) {
392 PHINode *PN = IndVars.back().first;
393 Value *NewVal = Rewriter.ExpandCodeFor(IndVars.back().second, InsertPt,
394 PN->getType());
395 // Replace the old PHI Node with the inserted computation.
396 PN->replaceAllUsesWith(NewVal);
397 DeadInsts.insert(PN);
398 IndVars.pop_back();
399 ++NumRemoved;
Chris Lattner67439402001-12-05 19:41:33 +0000400 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000401 }
402
Chris Lattnere61b67d2004-04-02 20:24:31 +0000403 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner91daaab2001-12-04 04:32:29 +0000404
Chris Lattnere61b67d2004-04-02 20:24:31 +0000405 // TODO: In the future we could replace all instructions in the loop body with
406 // simpler expressions. It's not clear how useful this would be though or if
407 // the code expansion cost would be worth it! We probably shouldn't do this
408 // until we have a way to reuse expressions already in the code.
409#if 0
410 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
411 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
412 BasicBlock *BB = L->getBlocks()[i];
413 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
414 if (I->getType()->isInteger() && // Is an integer instruction
415 !Rewriter.isInsertedInstruction(I)) {
416 SCEVHandle SH = SE->getSCEV(I);
417 }
Chris Lattner91daaab2001-12-04 04:32:29 +0000418 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000419#endif
Chris Lattner476e6df2001-12-03 17:28:42 +0000420}