blob: aad6cc9a5e828e57774fcdfbf64a6f522641217b [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"
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 Patel2ac57e12007-03-07 06:39:01 +000071
72 bool runOnLoop(Loop *L, LPPassManager &LPM);
73 bool doInitialization(Loop *L, LPPassManager &LPM);
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.addRequiredID(LCSSAID);
76 AU.addRequiredID(LoopSimplifyID);
77 AU.addRequired<ScalarEvolution>();
78 AU.addRequired<LoopInfo>();
79 AU.addPreservedID(LoopSimplifyID);
80 AU.addPreservedID(LCSSAID);
81 AU.setPreservesCFG();
82 }
Chris Lattner7e755e42003-12-23 07:47:09 +000083
Chris Lattnere61b67d2004-04-02 20:24:31 +000084 private:
Devang Patel2ac57e12007-03-07 06:39:01 +000085
Chris Lattnere61b67d2004-04-02 20:24:31 +000086 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
87 std::set<Instruction*> &DeadInsts);
Chris Lattner51c95cd2006-09-21 05:12:20 +000088 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
89 SCEVExpander &RW);
Chris Lattnere61b67d2004-04-02 20:24:31 +000090 void RewriteLoopExitValues(Loop *L);
91
92 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattnerd3678bc2003-12-22 03:58:44 +000093 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +000094 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner4184bcc2002-09-10 05:24:05 +000095}
Chris Lattner91daaab2001-12-04 04:32:29 +000096
Devang Patel2ac57e12007-03-07 06:39:01 +000097LoopPass *llvm::createIndVarSimplifyPass() {
Chris Lattnerd3678bc2003-12-22 03:58:44 +000098 return new IndVarSimplify();
Chris Lattner91daaab2001-12-04 04:32:29 +000099}
100
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);
Chris Lattner08165592007-01-07 01:14:12 +0000114 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattner9776f722004-10-11 23:06:50 +0000115 I->eraseFromParent();
Chris Lattnere61b67d2004-04-02 20:24:31 +0000116 Changed = true;
117 }
118 }
119}
120
121
122/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
123/// recurrence. If so, change it into an integer recurrence, permitting
124/// analysis by the SCEV routines.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000125void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattnere61b67d2004-04-02 20:24:31 +0000126 BasicBlock *Preheader,
127 std::set<Instruction*> &DeadInsts) {
128 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
129 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
130 unsigned BackedgeIdx = PreheaderIdx^1;
131 if (GetElementPtrInst *GEPI =
Chris Lattner677d8572005-08-10 01:12:06 +0000132 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattnere61b67d2004-04-02 20:24:31 +0000133 if (GEPI->getOperand(0) == PN) {
Chris Lattner677d8572005-08-10 01:12:06 +0000134 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattner08165592007-01-07 01:14:12 +0000135 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
136
Chris Lattnere61b67d2004-04-02 20:24:31 +0000137 // Okay, we found a pointer recurrence. Transform this pointer
138 // recurrence into an integer recurrence. Compute the value that gets
139 // added to the pointer at every iteration.
140 Value *AddedVal = GEPI->getOperand(1);
141
142 // Insert a new integer PHI node into the top of the block.
143 PHINode *NewPhi = new PHINode(AddedVal->getType(),
144 PN->getName()+".rec", PN);
Chris Lattnerc9e06332004-06-20 05:04:01 +0000145 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
146
Chris Lattnere61b67d2004-04-02 20:24:31 +0000147 // Create the new add instruction.
Chris Lattnerc9e06332004-06-20 05:04:01 +0000148 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
149 GEPI->getName()+".rec", GEPI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000150 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000151
Chris Lattnere61b67d2004-04-02 20:24:31 +0000152 // Update the existing GEP to use the recurrence.
153 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000154
Chris Lattnere61b67d2004-04-02 20:24:31 +0000155 // Update the GEP to use the new recurrence we just inserted.
156 GEPI->setOperand(1, NewAdd);
157
Chris Lattner9776f722004-10-11 23:06:50 +0000158 // If the incoming value is a constant expr GEP, try peeling out the array
159 // 0 index if possible to make things simpler.
160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
161 if (CE->getOpcode() == Instruction::GetElementPtr) {
162 unsigned NumOps = CE->getNumOperands();
163 assert(NumOps > 1 && "CE folding didn't work!");
164 if (CE->getOperand(NumOps-1)->isNullValue()) {
165 // Check to make sure the last index really is an array index.
Chris Lattner9c37f232005-11-18 18:30:47 +0000166 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerbca0be82005-11-17 19:35:42 +0000167 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattner9776f722004-10-11 23:06:50 +0000168 i != e; ++i, ++GTI)
169 /*empty*/;
170 if (isa<SequentialType>(*GTI)) {
171 // Pull the last index out of the constant expr GEP.
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000172 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattner9776f722004-10-11 23:06:50 +0000173 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattnerf96f4a82007-01-31 04:40:53 +0000174 &CEIdxs[0],
175 CEIdxs.size());
Reid Spencer2e54a152007-03-02 00:28:52 +0000176 GetElementPtrInst *NGEPI = new GetElementPtrInst(
177 NCE, Constant::getNullValue(Type::Int32Ty), NewAdd,
178 GEPI->getName(), GEPI);
Chris Lattner9776f722004-10-11 23:06:50 +0000179 GEPI->replaceAllUsesWith(NGEPI);
180 GEPI->eraseFromParent();
181 GEPI = NGEPI;
182 }
183 }
184 }
185
186
Chris Lattnere61b67d2004-04-02 20:24:31 +0000187 // Finally, if there are any other users of the PHI node, we must
188 // insert a new GEP instruction that uses the pre-incremented version
189 // of the induction amount.
190 if (!PN->use_empty()) {
191 BasicBlock::iterator InsertPos = PN; ++InsertPos;
192 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000193 Value *PreInc =
194 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
Chris Lattner6e0123b2007-02-11 01:23:03 +0000195 NewPhi, "", InsertPos);
196 PreInc->takeName(PN);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000197 PN->replaceAllUsesWith(PreInc);
198 }
199
200 // Delete the old PHI for sure, and the GEP if its otherwise unused.
201 DeadInsts.insert(PN);
202
203 ++NumPointer;
204 Changed = true;
205 }
206}
207
208/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000209/// loop to be a canonical != comparison against the incremented loop induction
210/// variable. This pass is able to rewrite the exit tests of any loop where the
211/// SCEV analysis can determine a loop-invariant trip count of the loop, which
212/// is actually a much broader range than just linear tests.
Chris Lattner51c95cd2006-09-21 05:12:20 +0000213///
214/// This method returns a "potentially dead" instruction whose computation chain
215/// should be deleted when convenient.
216Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
217 SCEV *IterationCount,
218 SCEVExpander &RW) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000219 // Find the exit block for the loop. We can currently only handle loops with
220 // a single exit.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000221 std::vector<BasicBlock*> ExitBlocks;
222 L->getExitBlocks(ExitBlocks);
Chris Lattner51c95cd2006-09-21 05:12:20 +0000223 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000224 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000225
226 // Make sure there is only one predecessor block in the loop.
227 BasicBlock *ExitingBlock = 0;
228 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
229 PI != PE; ++PI)
230 if (L->contains(*PI)) {
231 if (ExitingBlock == 0)
232 ExitingBlock = *PI;
233 else
Chris Lattner51c95cd2006-09-21 05:12:20 +0000234 return 0; // Multiple exits from loop to this block.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000235 }
236 assert(ExitingBlock && "Loop info is broken");
237
238 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000239 return 0; // Can't rewrite non-branch yet
Chris Lattnere61b67d2004-04-02 20:24:31 +0000240 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
241 assert(BI->isConditional() && "Must be conditional to be part of loop!");
242
Chris Lattner51c95cd2006-09-21 05:12:20 +0000243 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
244
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000245 // If the exiting block is not the same as the backedge block, we must compare
246 // against the preincremented value, otherwise we prefer to compare against
247 // the post-incremented value.
248 BasicBlock *Header = L->getHeader();
249 pred_iterator HPI = pred_begin(Header);
250 assert(HPI != pred_end(Header) && "Loop with zero preds???");
251 if (!L->contains(*HPI)) ++HPI;
252 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
253 "No backedge in loop?");
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000254
Chris Lattnerd7a559e2004-04-15 20:26:22 +0000255 SCEVHandle TripCount = IterationCount;
256 Value *IndVar;
257 if (*HPI == ExitingBlock) {
258 // The IterationCount expression contains the number of times that the
259 // backedge actually branches to the loop header. This is one less than the
260 // number of times the loop executes, so add one to it.
261 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
262 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
263 IndVar = L->getCanonicalInductionVariableIncrement();
264 } else {
265 // We have to use the preincremented value...
266 IndVar = L->getCanonicalInductionVariable();
267 }
Chris Lattner08165592007-01-07 01:14:12 +0000268
269 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
270 << " IndVar = " << *IndVar << "\n";
Chris Lattner0cec5cb2004-04-15 15:21:43 +0000271
Chris Lattnere61b67d2004-04-02 20:24:31 +0000272 // Expand the code for the iteration count into the preheader of the loop.
273 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattner83cd87e2004-04-23 21:29:48 +0000274 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
Chris Lattnere61b67d2004-04-02 20:24:31 +0000275 IndVar->getType());
276
Reid Spencer266e42b2006-12-23 06:05:41 +0000277 // Insert a new icmp_ne or icmp_eq instruction before the branch.
278 ICmpInst::Predicate Opcode;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000279 if (L->contains(BI->getSuccessor(0)))
Reid Spencer266e42b2006-12-23 06:05:41 +0000280 Opcode = ICmpInst::ICMP_NE;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000281 else
Reid Spencer266e42b2006-12-23 06:05:41 +0000282 Opcode = ICmpInst::ICMP_EQ;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000283
Reid Spencer266e42b2006-12-23 06:05:41 +0000284 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000285 BI->setCondition(Cond);
286 ++NumLFTR;
287 Changed = true;
Chris Lattner51c95cd2006-09-21 05:12:20 +0000288 return PotentiallyDeadInst;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000289}
290
291
292/// RewriteLoopExitValues - Check to see if this loop has a computable
293/// loop-invariant execution count. If so, this means that we can compute the
294/// final value of any expressions that are recurrent in the loop, and
295/// substitute the exit values from the loop into any instructions outside of
296/// the loop that use the final values of the current expressions.
297void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
298 BasicBlock *Preheader = L->getLoopPreheader();
299
300 // Scan all of the instructions in the loop, looking at those that have
301 // extra-loop users and which are recurrences.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000302 SCEVExpander Rewriter(*SE, *LI);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000303
304 // We insert the code into the preheader of the loop if the loop contains
305 // multiple exit blocks, or in the exit block if there is exactly one.
306 BasicBlock *BlockToInsertInto;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000307 std::vector<BasicBlock*> ExitBlocks;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000308 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000309 if (ExitBlocks.size() == 1)
310 BlockToInsertInto = ExitBlocks[0];
Chris Lattnere61b67d2004-04-02 20:24:31 +0000311 else
312 BlockToInsertInto = Preheader;
313 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
314 while (isa<PHINode>(InsertPt)) ++InsertPt;
315
Chris Lattnera8140802004-04-17 18:44:09 +0000316 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
317
Chris Lattnere61b67d2004-04-02 20:24:31 +0000318 std::set<Instruction*> InstructionsToDelete;
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000319 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000320
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000321 // Find all values that are computed inside the loop, but used outside of it.
322 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
323 // the exit blocks of the loop to find them.
324 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
325 BasicBlock *ExitBB = ExitBlocks[i];
326
327 // If there are no PHI nodes in this exit block, then no values defined
328 // inside the loop are used on this path, skip it.
329 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
330 if (!PN) continue;
331
332 unsigned NumPreds = PN->getNumIncomingValues();
333
334 // Iterate over all of the PHI nodes.
335 BasicBlock::iterator BBI = ExitBB->begin();
336 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnered30abf2007-03-03 22:48:48 +0000337
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000338 // Iterate over all of the values in all the PHI nodes.
339 for (unsigned i = 0; i != NumPreds; ++i) {
340 // If the value being merged in is not integer or is not defined
341 // in the loop, skip it.
342 Value *InVal = PN->getIncomingValue(i);
343 if (!isa<Instruction>(InVal) ||
344 // SCEV only supports integer expressions for now.
345 !isa<IntegerType>(InVal->getType()))
346 continue;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000347
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000348 // If this pred is for a subloop, not L itself, skip it.
349 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
350 continue; // The Block is in a subloop, skip it.
351
352 // Check that InVal is defined in the loop.
353 Instruction *Inst = cast<Instruction>(InVal);
354 if (!L->contains(Inst->getParent()))
355 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000356
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000357 // We require that this value either have a computable evolution or that
358 // the loop have a constant iteration count. In the case where the loop
359 // has a constant iteration count, we can sometimes force evaluation of
360 // the exit value through brute force.
361 SCEVHandle SH = SE->getSCEV(Inst);
362 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
363 continue; // Cannot get exit evolution for the loop value.
364
365 // Okay, this instruction has a user outside of the current loop
366 // and varies predictably *inside* the loop. Evaluate the value it
367 // contains when the loop exits, if possible.
368 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
369 if (isa<SCEVCouldNotCompute>(ExitValue) ||
370 !ExitValue->isLoopInvariant(L))
371 continue;
Chris Lattner1f7648e2007-03-04 01:00:28 +0000372
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000373 Changed = true;
374 ++NumReplaced;
375
376 // See if we already computed the exit value for the instruction, if so,
377 // just reuse it.
378 Value *&ExitVal = ExitValues[Inst];
379 if (!ExitVal)
380 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt,Inst->getType());
381
382 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
383 << " LoopVal = " << *Inst << "\n";
384
385 PN->setIncomingValue(i, ExitVal);
386
387 // If this instruction is dead now, schedule it to be removed.
388 if (Inst->use_empty())
389 InstructionsToDelete.insert(Inst);
390
391 // See if this is a single-entry LCSSA PHI node. If so, we can (and
392 // have to) remove
Chris Lattner1f7648e2007-03-04 01:00:28 +0000393 // the PHI entirely. This is safe, because the NewVal won't be variant
394 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattnerd7b4c922007-03-04 03:43:23 +0000395 if (NumPreds == 1) {
396 PN->replaceAllUsesWith(ExitVal);
397 PN->eraseFromParent();
398 break;
Chris Lattnered30abf2007-03-03 22:48:48 +0000399 }
400 }
Chris Lattnered30abf2007-03-03 22:48:48 +0000401 }
402 }
403
Chris Lattnere61b67d2004-04-02 20:24:31 +0000404 DeleteTriviallyDeadInstructions(InstructionsToDelete);
405}
406
Devang Patel2ac57e12007-03-07 06:39:01 +0000407bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattnere61b67d2004-04-02 20:24:31 +0000408
Devang Patel2ac57e12007-03-07 06:39:01 +0000409 Changed = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000410 // First step. Check to see if there are any trivial GEP pointer recurrences.
411 // If there are, change them into integer recurrences, permitting analysis by
412 // the SCEV routines.
413 //
414 BasicBlock *Header = L->getHeader();
415 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel2ac57e12007-03-07 06:39:01 +0000416 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000417
Chris Lattnere61b67d2004-04-02 20:24:31 +0000418 std::set<Instruction*> DeadInsts;
Reid Spencer66149462004-09-15 17:06:42 +0000419 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
420 PHINode *PN = cast<PHINode>(I);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000421 if (isa<PointerType>(PN->getType()))
422 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer66149462004-09-15 17:06:42 +0000423 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000424
425 if (!DeadInsts.empty())
426 DeleteTriviallyDeadInstructions(DeadInsts);
427
Devang Patel2ac57e12007-03-07 06:39:01 +0000428 return Changed;
429}
Chris Lattnere61b67d2004-04-02 20:24:31 +0000430
Devang Patel2ac57e12007-03-07 06:39:01 +0000431bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattnerd3678bc2003-12-22 03:58:44 +0000432
Devang Patel2ac57e12007-03-07 06:39:01 +0000433
434 LI = &getAnalysis<LoopInfo>();
435 SE = &getAnalysis<ScalarEvolution>();
436
437 Changed = false;
438 BasicBlock *Header = L->getHeader();
439 std::set<Instruction*> DeadInsts;
440
Chris Lattner1f7648e2007-03-04 01:00:28 +0000441 // Verify the input to the pass in already in LCSSA form.
442 assert(L->isLCSSAForm());
443
Chris Lattnere61b67d2004-04-02 20:24:31 +0000444 // Check to see if this loop has a computable loop-invariant execution count.
445 // If so, this means that we can compute the final value of any expressions
446 // that are recurrent in the loop, and substitute the exit values from the
447 // loop into any instructions outside of the loop that use the final values of
448 // the current expressions.
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000449 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000450 SCEVHandle IterationCount = SE->getIterationCount(L);
451 if (!isa<SCEVCouldNotCompute>(IterationCount))
452 RewriteLoopExitValues(L);
Chris Lattner476e6df2001-12-03 17:28:42 +0000453
Chris Lattnere61b67d2004-04-02 20:24:31 +0000454 // Next, analyze all of the induction variables in the loop, canonicalizing
455 // auxillary induction variables.
456 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
457
Reid Spencer66149462004-09-15 17:06:42 +0000458 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
459 PHINode *PN = cast<PHINode>(I);
Chris Lattner03c49532007-01-15 02:27:26 +0000460 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattnere61b67d2004-04-02 20:24:31 +0000461 SCEVHandle SCEV = SE->getSCEV(PN);
462 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattner677d8572005-08-10 01:12:06 +0000463 // FIXME: It is an extremely bad idea to indvar substitute anything more
464 // complex than affine induction variables. Doing so will put expensive
465 // polynomial evaluations inside of the loop, and the str reduction pass
466 // currently can only reduce affine polynomials. For now just disable
467 // indvar subst on anything more complex than an affine addrec.
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000468 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattner677d8572005-08-10 01:12:06 +0000469 if (AR->isAffine())
Chris Lattnere5ad26d2004-07-26 02:47:12 +0000470 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattnere61b67d2004-04-02 20:24:31 +0000471 }
Reid Spencer66149462004-09-15 17:06:42 +0000472 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000473
474 // If there are no induction variables in the loop, there is nothing more to
475 // do.
Chris Lattner885a6eb2004-04-17 18:08:33 +0000476 if (IndVars.empty()) {
477 // Actually, if we know how many times the loop iterates, lets insert a
478 // canonical induction variable to help subsequent passes.
479 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner83cd87e2004-04-23 21:29:48 +0000480 SCEVExpander Rewriter(*SE, *LI);
481 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattner885a6eb2004-04-17 18:08:33 +0000482 IterationCount->getType());
Chris Lattner51c95cd2006-09-21 05:12:20 +0000483 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
484 Rewriter)) {
485 std::set<Instruction*> InstructionsToDelete;
486 InstructionsToDelete.insert(I);
487 DeleteTriviallyDeadInstructions(InstructionsToDelete);
488 }
Chris Lattner885a6eb2004-04-17 18:08:33 +0000489 }
Devang Patel2ac57e12007-03-07 06:39:01 +0000490 return Changed;
Chris Lattner885a6eb2004-04-17 18:08:33 +0000491 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000492
493 // Compute the type of the largest recurrence expression.
Chris Lattner476e6df2001-12-03 17:28:42 +0000494 //
Chris Lattnere61b67d2004-04-02 20:24:31 +0000495 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000496 bool DifferingSizes = false;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000497 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
498 const Type *Ty = IndVars[i].first->getType();
Reid Spencer8f166b02007-01-08 16:32:00 +0000499 DifferingSizes |=
500 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
501 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattnere61b67d2004-04-02 20:24:31 +0000502 LargestType = Ty;
Chris Lattner476e6df2001-12-03 17:28:42 +0000503 }
504
Chris Lattnere61b67d2004-04-02 20:24:31 +0000505 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000506 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000507
Chris Lattnere61b67d2004-04-02 20:24:31 +0000508 // Now that we know the largest of of the induction variables in this loop,
509 // insert a canonical induction variable of the largest size.
Chris Lattner83cd87e2004-04-23 21:29:48 +0000510 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000511 ++NumInserted;
512 Changed = true;
Chris Lattner08165592007-01-07 01:14:12 +0000513 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner7e755e42003-12-23 07:47:09 +0000514
Chris Lattnere61b67d2004-04-02 20:24:31 +0000515 if (!isa<SCEVCouldNotCompute>(IterationCount))
Chris Lattner51c95cd2006-09-21 05:12:20 +0000516 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
517 DeadInsts.insert(DI);
Chris Lattner7e755e42003-12-23 07:47:09 +0000518
Chris Lattnere61b67d2004-04-02 20:24:31 +0000519 // Now that we have a canonical induction variable, we can rewrite any
520 // recurrences in terms of the induction variable. Start with the auxillary
521 // induction variables, and recursively rewrite any of their uses.
522 BasicBlock::iterator InsertPt = Header->begin();
523 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner476e6df2001-12-03 17:28:42 +0000524
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000525 // If there were induction variables of other sizes, cast the primary
526 // induction variable to the right size for them, avoiding the need for the
527 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000528 if (DifferingSizes) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000529 SmallVector<unsigned,4> InsertedSizes;
530 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
531 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
532 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5e52362007-01-12 22:51:20 +0000533 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
534 == InsertedSizes.end()) {
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000535 PHINode *PN = IndVars[i].first;
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000536 InsertedSizes.push_back(ithSize);
Chris Lattner08165592007-01-07 01:14:12 +0000537 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
538 InsertPt);
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000539 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattner08165592007-01-07 01:14:12 +0000540 DOUT << "INDVARS: Made trunc IV for " << *PN
541 << " NewVal = " << *New << "\n";
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000542 }
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000543 }
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000544 }
545
Chris Lattner08165592007-01-07 01:14:12 +0000546 // Rewrite all induction variables in terms of the canonical induction
547 // variable.
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000548 std::map<unsigned, Value*> InsertedSizes;
Chris Lattnere61b67d2004-04-02 20:24:31 +0000549 while (!IndVars.empty()) {
550 PHINode *PN = IndVars.back().first;
Chris Lattner83cd87e2004-04-23 21:29:48 +0000551 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000552 PN->getType());
Chris Lattner08165592007-01-07 01:14:12 +0000553 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
554 << " into = " << *NewVal << "\n";
Chris Lattner6e0123b2007-02-11 01:23:03 +0000555 NewVal->takeName(PN);
Chris Lattnerdc7cc352004-04-21 22:22:01 +0000556
Chris Lattnere61b67d2004-04-02 20:24:31 +0000557 // Replace the old PHI Node with the inserted computation.
Chris Lattnerc1a682d2004-04-22 14:59:40 +0000558 PN->replaceAllUsesWith(NewVal);
Chris Lattnere61b67d2004-04-02 20:24:31 +0000559 DeadInsts.insert(PN);
560 IndVars.pop_back();
561 ++NumRemoved;
Chris Lattner67439402001-12-05 19:41:33 +0000562 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000563 }
564
Chris Lattnerc27302c2004-04-22 15:12:36 +0000565#if 0
Chris Lattneraf532f22004-04-21 23:36:08 +0000566 // Now replace all derived expressions in the loop body with simpler
567 // expressions.
Chris Lattnere61b67d2004-04-02 20:24:31 +0000568 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
569 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
570 BasicBlock *BB = L->getBlocks()[i];
571 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner03c49532007-01-15 02:27:26 +0000572 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattneraf532f22004-04-21 23:36:08 +0000573 !I->use_empty() &&
Chris Lattnere61b67d2004-04-02 20:24:31 +0000574 !Rewriter.isInsertedInstruction(I)) {
575 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner83cd87e2004-04-23 21:29:48 +0000576 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattneraf532f22004-04-21 23:36:08 +0000577 if (V != I) {
Chris Lattner6e0123b2007-02-11 01:23:03 +0000578 if (isa<Instruction>(V))
579 V->takeName(I);
Chris Lattneraf532f22004-04-21 23:36:08 +0000580 I->replaceAllUsesWith(V);
581 DeadInsts.insert(I);
582 ++NumRemoved;
583 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000584 }
Chris Lattnere61b67d2004-04-02 20:24:31 +0000585 }
Chris Lattner91daaab2001-12-04 04:32:29 +0000586 }
Chris Lattnerc27302c2004-04-22 15:12:36 +0000587#endif
Chris Lattneraf532f22004-04-21 23:36:08 +0000588
Chris Lattneraf532f22004-04-21 23:36:08 +0000589 DeleteTriviallyDeadInstructions(DeadInsts);
Owen Anderson8e4b0292006-08-25 22:12:36 +0000590
Chris Lattner1f7648e2007-03-04 01:00:28 +0000591 assert(L->isLCSSAForm());
Devang Patel2ac57e12007-03-07 06:39:01 +0000592 return Changed;
Chris Lattner476e6df2001-12-03 17:28:42 +0000593}