blob: c75627e3152c123d7e26f1e4f8524a048eda5b0b [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//
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.
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"
Chris Lattner83d485b2002-02-12 22:39:50 +000048#include "llvm/Support/CFG.h"
Reid Spencer557ab152007-02-05 23:32:05 +000049#include "llvm/Support/Compiler.h"
Chris Lattner08165592007-01-07 01:14:12 +000050#include "llvm/Support/Debug.h"
Chris Lattner9776f722004-10-11 23:06:50 +000051#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswellb22e9b42003-12-18 17:19:19 +000052#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000053#include "llvm/Support/CommandLine.h"
Reid Spencer7a9c62b2007-01-12 07:05:14 +000054#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000055#include "llvm/ADT/Statistic.h"
John Criswellb22e9b42003-12-18 17:19:19 +000056using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumRemoved , "Number of aux indvars removed");
59STATISTIC(NumPointer , "Number of pointer indvars promoted");
60STATISTIC(NumInserted, "Number of canonical indvars added");
61STATISTIC(NumReplaced, "Number of exit values replaced");
62STATISTIC(NumLFTR , "Number of loop exit tests replaced");
Chris Lattnerd3678bc2003-12-22 03:58:44 +000063
Chris Lattner79a42ac2006-12-19 21:40:18 +000064namespace {
Reid Spencer557ab152007-02-05 23:32:05 +000065 class VISIBILITY_HIDDEN IndVarSimplify : public FunctionPass {
Chris Lattnere61b67d2004-04-02 20:24:31 +000066 LoopInfo *LI;
67 ScalarEvolution *SE;
Chris Lattner7e755e42003-12-23 07:47:09 +000068 bool Changed;
Chris Lattnerd3678bc2003-12-22 03:58:44 +000069 public:
70 virtual bool runOnFunction(Function &) {
Chris Lattnere61b67d2004-04-02 20:24:31 +000071 LI = &getAnalysis<LoopInfo>();
72 SE = &getAnalysis<ScalarEvolution>();
Chris Lattner7e755e42003-12-23 07:47:09 +000073 Changed = false;
74
Chris Lattnerd3678bc2003-12-22 03:58:44 +000075 // Induction Variables live in the header nodes of loops
Chris Lattnere61b67d2004-04-02 20:24:31 +000076 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +000077 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000078 return Changed;
79 }
80
Chris Lattnerd3678bc2003-12-22 03:58:44 +000081 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1f7648e2007-03-04 01:00:28 +000082 AU.addRequiredID(LCSSAID);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000083 AU.addRequiredID(LoopSimplifyID);
Chris Lattnere61b67d2004-04-02 20:24:31 +000084 AU.addRequired<ScalarEvolution>();
85 AU.addRequired<LoopInfo>();
Chris Lattnerd3678bc2003-12-22 03:58:44 +000086 AU.addPreservedID(LoopSimplifyID);
Owen Anderson8cca95c2006-08-25 17:41:25 +000087 AU.addPreservedID(LCSSAID);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000088 AU.setPreservesCFG();
89 }
Chris Lattnere61b67d2004-04-02 20:24:31 +000090 private:
91 void runOnLoop(Loop *L);
92 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
93 std::set<Instruction*> &DeadInsts);
Chris Lattner51c95cd2006-09-21 05:12:20 +000094 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
95 SCEVExpander &RW);
Chris Lattnere61b67d2004-04-02 20:24:31 +000096 void RewriteLoopExitValues(Loop *L);
97
98 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000099 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000100 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner4184bcc2002-09-10 05:24:05 +0000101}
Chris Lattner91daaab2001-12-04 04:32:29 +0000102
Chris Lattner3e860842004-09-20 04:43:15 +0000103FunctionPass *llvm::createIndVarSimplifyPass() {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000104 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +0000105}
106
Chris Lattnere61b67d2004-04-02 20:24:31 +0000107/// DeleteTriviallyDeadInstructions - If any of the instructions is the
108/// specified set are trivially dead, delete them and see if this makes any of
109/// their operands subsequently dead.
110void IndVarSimplify::
111DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
112 while (!Insts.empty()) {
113 Instruction *I = *Insts.begin();
114 Insts.erase(Insts.begin());
115 if (isInstructionTriviallyDead(I)) {
116 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
117 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
118 Insts.insert(U);
119 SE->deleteInstructionFromRecords(I);
Chris Lattner08165592007-01-07 01:14:12 +0000120 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattner9776f722004-10-11 23:06:50 +0000121 I->eraseFromParent();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000122 Changed = true;
123 }
124 }
125}
126
127
128/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
129/// recurrence. If so, change it into an integer recurrence, permitting
130/// analysis by the SCEV routines.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000131void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattnere61b67d2004-04-02 20:24:31 +0000132 BasicBlock *Preheader,
133 std::set<Instruction*> &DeadInsts) {
134 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
135 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
136 unsigned BackedgeIdx = PreheaderIdx^1;
137 if (GetElementPtrInst *GEPI =
Chris Lattner677d8572005-08-10 01:12:06 +0000138 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattnere61b67d2004-04-02 20:24:31 +0000139 if (GEPI->getOperand(0) == PN) {
Chris Lattner677d8572005-08-10 01:12:06 +0000140 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattner08165592007-01-07 01:14:12 +0000141 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
142
Chris Lattnere61b67d2004-04-02 20:24:31 +0000143 // Okay, we found a pointer recurrence. Transform this pointer
144 // recurrence into an integer recurrence. Compute the value that gets
145 // added to the pointer at every iteration.
146 Value *AddedVal = GEPI->getOperand(1);
147
148 // Insert a new integer PHI node into the top of the block.
149 PHINode *NewPhi = new PHINode(AddedVal->getType(),
150 PN->getName()+".rec", PN);
Chris Lattnerc9e06332004-06-20 05:04:01 +0000151 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
152
Chris Lattnere61b67d2004-04-02 20:24:31 +0000153 // Create the new add instruction.
Chris Lattnerc9e06332004-06-20 05:04:01 +0000154 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
155 GEPI->getName()+".rec", GEPI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000156 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000157
Chris Lattnere61b67d2004-04-02 20:24:31 +0000158 // Update the existing GEP to use the recurrence.
159 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000160
Chris Lattnere61b67d2004-04-02 20:24:31 +0000161 // Update the GEP to use the new recurrence we just inserted.
162 GEPI->setOperand(1, NewAdd);
163
Chris Lattner9776f722004-10-11 23:06:50 +0000164 // If the incoming value is a constant expr GEP, try peeling out the array
165 // 0 index if possible to make things simpler.
166 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
167 if (CE->getOpcode() == Instruction::GetElementPtr) {
168 unsigned NumOps = CE->getNumOperands();
169 assert(NumOps > 1 && "CE folding didn't work!");
170 if (CE->getOperand(NumOps-1)->isNullValue()) {
171 // Check to make sure the last index really is an array index.
Chris Lattner9c37f232005-11-18 18:30:47 +0000172 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerbca0be82005-11-17 19:35:42 +0000173 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattner9776f722004-10-11 23:06:50 +0000174 i != e; ++i, ++GTI)
175 /*empty*/;
176 if (isa<SequentialType>(*GTI)) {
177 // Pull the last index out of the constant expr GEP.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000178 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattner9776f722004-10-11 23:06:50 +0000179 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000180 &CEIdxs[0],
181 CEIdxs.size());
Reid Spencer2e54a152007-03-02 00:28:52 +0000182 GetElementPtrInst *NGEPI = new GetElementPtrInst(
183 NCE, Constant::getNullValue(Type::Int32Ty), NewAdd,
184 GEPI->getName(), GEPI);
Chris Lattner9776f722004-10-11 23:06:50 +0000185 GEPI->replaceAllUsesWith(NGEPI);
186 GEPI->eraseFromParent();
187 GEPI = NGEPI;
188 }
189 }
190 }
191
192
Chris Lattnere61b67d2004-04-02 20:24:31 +0000193 // Finally, if there are any other users of the PHI node, we must
194 // insert a new GEP instruction that uses the pre-incremented version
195 // of the induction amount.
196 if (!PN->use_empty()) {
197 BasicBlock::iterator InsertPos = PN; ++InsertPos;
198 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000199 Value *PreInc =
200 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
Chris Lattner6e0123b2007-02-11 01:23:03 +0000201 NewPhi, "", InsertPos);
202 PreInc->takeName(PN);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000203 PN->replaceAllUsesWith(PreInc);
204 }
205
206 // Delete the old PHI for sure, and the GEP if its otherwise unused.
207 DeadInsts.insert(PN);
208
209 ++NumPointer;
210 Changed = true;
211 }
212}
213
214/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000215/// loop to be a canonical != comparison against the incremented loop induction
216/// variable. This pass is able to rewrite the exit tests of any loop where the
217/// SCEV analysis can determine a loop-invariant trip count of the loop, which
218/// is actually a much broader range than just linear tests.
Chris Lattner51c95cd2006-09-21 05:12:20 +0000219///
220/// This method returns a "potentially dead" instruction whose computation chain
221/// should be deleted when convenient.
222Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
223 SCEV *IterationCount,
224 SCEVExpander &RW) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000225 // Find the exit block for the loop. We can currently only handle loops with
226 // a single exit.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000227 std::vector<BasicBlock*> ExitBlocks;
228 L->getExitBlocks(ExitBlocks);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000229 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000230 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000231
232 // Make sure there is only one predecessor block in the loop.
233 BasicBlock *ExitingBlock = 0;
234 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
235 PI != PE; ++PI)
236 if (L->contains(*PI)) {
237 if (ExitingBlock == 0)
238 ExitingBlock = *PI;
239 else
Chris Lattner51c95cd2006-09-21 05:12:20 +0000240 return 0; // Multiple exits from loop to this block.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000241 }
242 assert(ExitingBlock && "Loop info is broken");
243
244 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000245 return 0; // Can't rewrite non-branch yet
Chris Lattnere61b67d2004-04-02 20:24:31 +0000246 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
247 assert(BI->isConditional() && "Must be conditional to be part of loop!");
248
Chris Lattner51c95cd2006-09-21 05:12:20 +0000249 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
250
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000251 // If the exiting block is not the same as the backedge block, we must compare
252 // against the preincremented value, otherwise we prefer to compare against
253 // the post-incremented value.
254 BasicBlock *Header = L->getHeader();
255 pred_iterator HPI = pred_begin(Header);
256 assert(HPI != pred_end(Header) && "Loop with zero preds???");
257 if (!L->contains(*HPI)) ++HPI;
258 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
259 "No backedge in loop?");
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000260
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000261 SCEVHandle TripCount = IterationCount;
262 Value *IndVar;
263 if (*HPI == ExitingBlock) {
264 // The IterationCount expression contains the number of times that the
265 // backedge actually branches to the loop header. This is one less than the
266 // number of times the loop executes, so add one to it.
267 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
268 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
269 IndVar = L->getCanonicalInductionVariableIncrement();
270 } else {
271 // We have to use the preincremented value...
272 IndVar = L->getCanonicalInductionVariable();
273 }
Chris Lattner08165592007-01-07 01:14:12 +0000274
275 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
276 << " IndVar = " << *IndVar << "\n";
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000277
Chris Lattnere61b67d2004-04-02 20:24:31 +0000278 // Expand the code for the iteration count into the preheader of the loop.
279 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattner83cd87e2004-04-23 21:29:48 +0000280 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
Chris Lattnere61b67d2004-04-02 20:24:31 +0000281 IndVar->getType());
282
Reid Spencer266e42b2006-12-23 06:05:41 +0000283 // Insert a new icmp_ne or icmp_eq instruction before the branch.
284 ICmpInst::Predicate Opcode;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000285 if (L->contains(BI->getSuccessor(0)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000286 Opcode = ICmpInst::ICMP_NE;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000287 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000288 Opcode = ICmpInst::ICMP_EQ;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000289
Reid Spencer266e42b2006-12-23 06:05:41 +0000290 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000291 BI->setCondition(Cond);
292 ++NumLFTR;
293 Changed = true;
Chris Lattner51c95cd2006-09-21 05:12:20 +0000294 return PotentiallyDeadInst;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000295}
296
297
298/// RewriteLoopExitValues - Check to see if this loop has a computable
299/// loop-invariant execution count. If so, this means that we can compute the
300/// final value of any expressions that are recurrent in the loop, and
301/// substitute the exit values from the loop into any instructions outside of
302/// the loop that use the final values of the current expressions.
303void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
304 BasicBlock *Preheader = L->getLoopPreheader();
305
306 // Scan all of the instructions in the loop, looking at those that have
307 // extra-loop users and which are recurrences.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000308 SCEVExpander Rewriter(*SE, *LI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000309
310 // We insert the code into the preheader of the loop if the loop contains
311 // multiple exit blocks, or in the exit block if there is exactly one.
312 BasicBlock *BlockToInsertInto;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000313 std::vector<BasicBlock*> ExitBlocks;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000314 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000315 if (ExitBlocks.size() == 1)
316 BlockToInsertInto = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000317 else
318 BlockToInsertInto = Preheader;
319 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
320 while (isa<PHINode>(InsertPt)) ++InsertPt;
321
Chris Lattnera8140802004-04-17 18:44:09 +0000322 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
323
Chris Lattnere61b67d2004-04-02 20:24:31 +0000324 std::set<Instruction*> InstructionsToDelete;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000325 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000326
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000327 // Find all values that are computed inside the loop, but used outside of it.
328 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
329 // the exit blocks of the loop to find them.
330 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
331 BasicBlock *ExitBB = ExitBlocks[i];
332
333 // If there are no PHI nodes in this exit block, then no values defined
334 // inside the loop are used on this path, skip it.
335 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
336 if (!PN) continue;
337
338 unsigned NumPreds = PN->getNumIncomingValues();
339
340 // Iterate over all of the PHI nodes.
341 BasicBlock::iterator BBI = ExitBB->begin();
342 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnered30abf2007-03-03 22:48:48 +0000343
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000344 // Iterate over all of the values in all the PHI nodes.
345 for (unsigned i = 0; i != NumPreds; ++i) {
346 // If the value being merged in is not integer or is not defined
347 // in the loop, skip it.
348 Value *InVal = PN->getIncomingValue(i);
349 if (!isa<Instruction>(InVal) ||
350 // SCEV only supports integer expressions for now.
351 !isa<IntegerType>(InVal->getType()))
352 continue;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000353
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000354 // If this pred is for a subloop, not L itself, skip it.
355 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
356 continue; // The Block is in a subloop, skip it.
357
358 // Check that InVal is defined in the loop.
359 Instruction *Inst = cast<Instruction>(InVal);
360 if (!L->contains(Inst->getParent()))
361 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000362
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000363 // We require that this value either have a computable evolution or that
364 // the loop have a constant iteration count. In the case where the loop
365 // has a constant iteration count, we can sometimes force evaluation of
366 // the exit value through brute force.
367 SCEVHandle SH = SE->getSCEV(Inst);
368 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
369 continue; // Cannot get exit evolution for the loop value.
370
371 // Okay, this instruction has a user outside of the current loop
372 // and varies predictably *inside* the loop. Evaluate the value it
373 // contains when the loop exits, if possible.
374 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
375 if (isa<SCEVCouldNotCompute>(ExitValue) ||
376 !ExitValue->isLoopInvariant(L))
377 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000378
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000379 Changed = true;
380 ++NumReplaced;
381
382 // See if we already computed the exit value for the instruction, if so,
383 // just reuse it.
384 Value *&ExitVal = ExitValues[Inst];
385 if (!ExitVal)
386 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt,Inst->getType());
387
388 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
389 << " LoopVal = " << *Inst << "\n";
390
391 PN->setIncomingValue(i, ExitVal);
392
393 // If this instruction is dead now, schedule it to be removed.
394 if (Inst->use_empty())
395 InstructionsToDelete.insert(Inst);
396
397 // See if this is a single-entry LCSSA PHI node. If so, we can (and
398 // have to) remove
Chris Lattner1f7648e2007-03-04 01:00:28 +0000399 // the PHI entirely. This is safe, because the NewVal won't be variant
400 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000401 if (NumPreds == 1) {
402 PN->replaceAllUsesWith(ExitVal);
403 PN->eraseFromParent();
404 break;
Chris Lattnered30abf2007-03-03 22:48:48 +0000405 }
406 }
Chris Lattnered30abf2007-03-03 22:48:48 +0000407 }
408 }
409
Chris Lattnere61b67d2004-04-02 20:24:31 +0000410 DeleteTriviallyDeadInstructions(InstructionsToDelete);
411}
412
413
414void IndVarSimplify::runOnLoop(Loop *L) {
415 // First step. Check to see if there are any trivial GEP pointer recurrences.
416 // If there are, change them into integer recurrences, permitting analysis by
417 // the SCEV routines.
418 //
419 BasicBlock *Header = L->getHeader();
420 BasicBlock *Preheader = L->getLoopPreheader();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000421
Chris Lattnere61b67d2004-04-02 20:24:31 +0000422 std::set<Instruction*> DeadInsts;
Reid Spencer66149462004-09-15 17:06:42 +0000423 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
424 PHINode *PN = cast<PHINode>(I);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000425 if (isa<PointerType>(PN->getType()))
426 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer66149462004-09-15 17:06:42 +0000427 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000428
429 if (!DeadInsts.empty())
430 DeleteTriviallyDeadInstructions(DeadInsts);
431
432
433 // Next, transform all loops nesting inside of this loop.
434 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000435 runOnLoop(*I);
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000436
Chris Lattner1f7648e2007-03-04 01:00:28 +0000437 // Verify the input to the pass in already in LCSSA form.
438 assert(L->isLCSSAForm());
439
Chris Lattnere61b67d2004-04-02 20:24:31 +0000440 // Check to see if this loop has a computable loop-invariant execution count.
441 // If so, this means that we can compute the final value of any expressions
442 // that are recurrent in the loop, and substitute the exit values from the
443 // loop into any instructions outside of the loop that use the final values of
444 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000445 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000446 SCEVHandle IterationCount = SE->getIterationCount(L);
447 if (!isa<SCEVCouldNotCompute>(IterationCount))
448 RewriteLoopExitValues(L);
Chris Lattner476e6df2001-12-03 17:28:42 +0000449
Chris Lattnere61b67d2004-04-02 20:24:31 +0000450 // Next, analyze all of the induction variables in the loop, canonicalizing
451 // auxillary induction variables.
452 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
453
Reid Spencer66149462004-09-15 17:06:42 +0000454 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
455 PHINode *PN = cast<PHINode>(I);
Chris Lattner03c49532007-01-15 02:27:26 +0000456 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattnere61b67d2004-04-02 20:24:31 +0000457 SCEVHandle SCEV = SE->getSCEV(PN);
458 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattner677d8572005-08-10 01:12:06 +0000459 // FIXME: It is an extremely bad idea to indvar substitute anything more
460 // complex than affine induction variables. Doing so will put expensive
461 // polynomial evaluations inside of the loop, and the str reduction pass
462 // currently can only reduce affine polynomials. For now just disable
463 // indvar subst on anything more complex than an affine addrec.
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000464 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattner677d8572005-08-10 01:12:06 +0000465 if (AR->isAffine())
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000466 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000467 }
Reid Spencer66149462004-09-15 17:06:42 +0000468 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000469
470 // If there are no induction variables in the loop, there is nothing more to
471 // do.
Chris Lattner885a6eb2004-04-17 18:08:33 +0000472 if (IndVars.empty()) {
473 // Actually, if we know how many times the loop iterates, lets insert a
474 // canonical induction variable to help subsequent passes.
475 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner83cd87e2004-04-23 21:29:48 +0000476 SCEVExpander Rewriter(*SE, *LI);
477 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattner885a6eb2004-04-17 18:08:33 +0000478 IterationCount->getType());
Chris Lattner51c95cd2006-09-21 05:12:20 +0000479 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
480 Rewriter)) {
481 std::set<Instruction*> InstructionsToDelete;
482 InstructionsToDelete.insert(I);
483 DeleteTriviallyDeadInstructions(InstructionsToDelete);
484 }
Chris Lattner885a6eb2004-04-17 18:08:33 +0000485 }
486 return;
487 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000488
489 // Compute the type of the largest recurrence expression.
Chris Lattner476e6df2001-12-03 17:28:42 +0000490 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000491 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000492 bool DifferingSizes = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000493 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
494 const Type *Ty = IndVars[i].first->getType();
Reid Spencer8f166b02007-01-08 16:32:00 +0000495 DifferingSizes |=
496 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
497 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattnere61b67d2004-04-02 20:24:31 +0000498 LargestType = Ty;
Chris Lattner476e6df2001-12-03 17:28:42 +0000499 }
500
Chris Lattnere61b67d2004-04-02 20:24:31 +0000501 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000502 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000503
Chris Lattnere61b67d2004-04-02 20:24:31 +0000504 // Now that we know the largest of of the induction variables in this loop,
505 // insert a canonical induction variable of the largest size.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000506 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000507 ++NumInserted;
508 Changed = true;
Chris Lattner08165592007-01-07 01:14:12 +0000509 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner7e755e42003-12-23 07:47:09 +0000510
Chris Lattnere61b67d2004-04-02 20:24:31 +0000511 if (!isa<SCEVCouldNotCompute>(IterationCount))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000512 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
513 DeadInsts.insert(DI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000514
Chris Lattnere61b67d2004-04-02 20:24:31 +0000515 // Now that we have a canonical induction variable, we can rewrite any
516 // recurrences in terms of the induction variable. Start with the auxillary
517 // induction variables, and recursively rewrite any of their uses.
518 BasicBlock::iterator InsertPt = Header->begin();
519 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner476e6df2001-12-03 17:28:42 +0000520
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000521 // If there were induction variables of other sizes, cast the primary
522 // induction variable to the right size for them, avoiding the need for the
523 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000524 if (DifferingSizes) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000525 SmallVector<unsigned,4> InsertedSizes;
526 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
527 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
528 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5e52362007-01-12 22:51:20 +0000529 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
530 == InsertedSizes.end()) {
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000531 PHINode *PN = IndVars[i].first;
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000532 InsertedSizes.push_back(ithSize);
Chris Lattner08165592007-01-07 01:14:12 +0000533 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
534 InsertPt);
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000535 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattner08165592007-01-07 01:14:12 +0000536 DOUT << "INDVARS: Made trunc IV for " << *PN
537 << " NewVal = " << *New << "\n";
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000538 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000539 }
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000540 }
541
Chris Lattner08165592007-01-07 01:14:12 +0000542 // Rewrite all induction variables in terms of the canonical induction
543 // variable.
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000544 std::map<unsigned, Value*> InsertedSizes;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000545 while (!IndVars.empty()) {
546 PHINode *PN = IndVars.back().first;
Chris Lattner83cd87e2004-04-23 21:29:48 +0000547 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000548 PN->getType());
Chris Lattner08165592007-01-07 01:14:12 +0000549 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
550 << " into = " << *NewVal << "\n";
Chris Lattner6e0123b2007-02-11 01:23:03 +0000551 NewVal->takeName(PN);
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000552
Chris Lattnere61b67d2004-04-02 20:24:31 +0000553 // Replace the old PHI Node with the inserted computation.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000554 PN->replaceAllUsesWith(NewVal);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000555 DeadInsts.insert(PN);
556 IndVars.pop_back();
557 ++NumRemoved;
Chris Lattner67439402001-12-05 19:41:33 +0000558 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000559 }
560
Chris Lattnerc27302c2004-04-22 15:12:36 +0000561#if 0
Chris Lattneraf532f22004-04-21 23:36:08 +0000562 // Now replace all derived expressions in the loop body with simpler
563 // expressions.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000564 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
565 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
566 BasicBlock *BB = L->getBlocks()[i];
567 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner03c49532007-01-15 02:27:26 +0000568 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattneraf532f22004-04-21 23:36:08 +0000569 !I->use_empty() &&
Chris Lattnere61b67d2004-04-02 20:24:31 +0000570 !Rewriter.isInsertedInstruction(I)) {
571 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner83cd87e2004-04-23 21:29:48 +0000572 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattneraf532f22004-04-21 23:36:08 +0000573 if (V != I) {
Chris Lattner6e0123b2007-02-11 01:23:03 +0000574 if (isa<Instruction>(V))
575 V->takeName(I);
Chris Lattneraf532f22004-04-21 23:36:08 +0000576 I->replaceAllUsesWith(V);
577 DeadInsts.insert(I);
578 ++NumRemoved;
579 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000580 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000581 }
Chris Lattner91daaab2001-12-04 04:32:29 +0000582 }
Chris Lattnerc27302c2004-04-22 15:12:36 +0000583#endif
Chris Lattneraf532f22004-04-21 23:36:08 +0000584
Chris Lattneraf532f22004-04-21 23:36:08 +0000585 DeleteTriviallyDeadInstructions(DeadInsts);
Owen Anderson8e4b0292006-08-25 22:12:36 +0000586
Chris Lattner1f7648e2007-03-04 01:00:28 +0000587 assert(L->isLCSSAForm());
Chris Lattner476e6df2001-12-03 17:28:42 +0000588}