blob: 3398b376abfd716a82c0aff13344dbd57fc8af9b [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
John Criswellb576c942003-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 Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattner40bf8b42004-04-02 20:24:31 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into simpler forms suitable for subsequent
12// analysis and transformation.
13//
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 Lattner6148c022001-12-03 17:28:42 +000037//
38//===----------------------------------------------------------------------===//
39
Chris Lattner022103b2002-05-07 20:03:00 +000040#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000041#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000042#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000043#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000044#include "llvm/Type.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000045#include "llvm/Analysis/ScalarEvolutionExpressions.h"
John Criswell47df12d2003-12-18 17:19:19 +000046#include "llvm/Analysis/LoopInfo.h"
Chris Lattner455889a2002-02-12 22:39:50 +000047#include "llvm/Support/CFG.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000049#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/Support/CommandLine.h"
51#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000052using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000053
Chris Lattner5e761402002-09-10 05:24:05 +000054namespace {
Chris Lattner4a7553e2004-04-23 21:29:48 +000055 /// SCEVExpander - This class uses information about analyze scalars to
56 /// rewrite expressions in canonical form.
57 ///
58 /// Clients should create an instance of this class when rewriting is needed,
59 /// and destroying it when finished to allow the release of the associated
60 /// memory.
61 struct SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
62 ScalarEvolution &SE;
63 LoopInfo &LI;
64 std::map<SCEVHandle, Value*> InsertedExpressions;
65 std::set<Instruction*> InsertedInstructions;
66
67 Instruction *InsertPt;
68
69 friend class SCEVVisitor<SCEVExpander, Value*>;
70 public:
71 SCEVExpander(ScalarEvolution &se, LoopInfo &li) : SE(se), LI(li) {}
72
73 /// isInsertedInstruction - Return true if the specified instruction was
74 /// inserted by the code rewriter. If so, the client should not modify the
75 /// instruction.
76 bool isInsertedInstruction(Instruction *I) const {
77 return InsertedInstructions.count(I);
78 }
79
80 /// getOrInsertCanonicalInductionVariable - This method returns the
81 /// canonical induction variable of the specified type for the specified
82 /// loop (inserting one if there is none). A canonical induction variable
83 /// starts at zero and steps by one on each iteration.
84 Value *getOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty){
85 assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
86 "Can only insert integer or floating point induction variables!");
87 SCEVHandle H = SCEVAddRecExpr::get(SCEVUnknown::getIntegerSCEV(0, Ty),
88 SCEVUnknown::getIntegerSCEV(1, Ty), L);
89 return expand(H);
90 }
91
92 /// addInsertedValue - Remember the specified instruction as being the
93 /// canonical form for the specified SCEV.
94 void addInsertedValue(Instruction *I, SCEV *S) {
95 InsertedExpressions[S] = (Value*)I;
96 InsertedInstructions.insert(I);
97 }
98
99 /// expandCodeFor - Insert code to directly compute the specified SCEV
100 /// expression into the program. The inserted code is inserted into the
101 /// specified block.
102 ///
103 /// If a particular value sign is required, a type may be specified for the
104 /// result.
105 Value *expandCodeFor(SCEVHandle SH, Instruction *IP, const Type *Ty = 0) {
106 // Expand the code for this SCEV.
107 this->InsertPt = IP;
108 return expandInTy(SH, Ty);
109 }
110
111 protected:
112 Value *expand(SCEV *S) {
113 // Check to see if we already expanded this.
114 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
115 if (I != InsertedExpressions.end())
116 return I->second;
117
118 Value *V = visit(S);
119 InsertedExpressions[S] = V;
120 return V;
121 }
122
123 Value *expandInTy(SCEV *S, const Type *Ty) {
124 Value *V = expand(S);
125 if (Ty && V->getType() != Ty) {
126 // FIXME: keep track of the cast instruction.
127 if (Constant *C = dyn_cast<Constant>(V))
128 return ConstantExpr::getCast(C, Ty);
129 else if (Instruction *I = dyn_cast<Instruction>(V)) {
130 // Check to see if there is already a cast. If there is, use it.
131 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
132 UI != E; ++UI) {
133 if ((*UI)->getType() == Ty)
134 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
135 BasicBlock::iterator It = I; ++It;
136 while (isa<PHINode>(It)) ++It;
137 if (It != BasicBlock::iterator(CI)) {
138 // Splice the cast immediately after the operand in question.
Chris Lattnera4b9c782004-10-11 23:06:50 +0000139 BasicBlock::InstListType &InstList =
140 I->getParent()->getInstList();
141 InstList.splice(It, InstList, CI);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000142 }
143 return CI;
144 }
145 }
146 BasicBlock::iterator IP = I; ++IP;
147 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
148 IP = II->getNormalDest()->begin();
149 while (isa<PHINode>(IP)) ++IP;
150 return new CastInst(V, Ty, V->getName(), IP);
151 } else {
152 // FIXME: check to see if there is already a cast!
153 return new CastInst(V, Ty, V->getName(), InsertPt);
154 }
155 }
156 return V;
157 }
158
159 Value *visitConstant(SCEVConstant *S) {
160 return S->getValue();
161 }
162
163 Value *visitTruncateExpr(SCEVTruncateExpr *S) {
164 Value *V = expand(S->getOperand());
165 return new CastInst(V, S->getType(), "tmp.", InsertPt);
166 }
167
168 Value *visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
Chris Lattner2b994c72004-06-19 18:15:50 +0000169 Value *V = expandInTy(S->getOperand(),S->getType()->getUnsignedVersion());
Chris Lattner4a7553e2004-04-23 21:29:48 +0000170 return new CastInst(V, S->getType(), "tmp.", InsertPt);
171 }
172
173 Value *visitAddExpr(SCEVAddExpr *S) {
174 const Type *Ty = S->getType();
175 Value *V = expandInTy(S->getOperand(S->getNumOperands()-1), Ty);
176
177 // Emit a bunch of add instructions
178 for (int i = S->getNumOperands()-2; i >= 0; --i)
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000179 V = BinaryOperator::createAdd(V, expandInTy(S->getOperand(i), Ty),
180 "tmp.", InsertPt);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000181 return V;
182 }
183
184 Value *visitMulExpr(SCEVMulExpr *S);
185
186 Value *visitUDivExpr(SCEVUDivExpr *S) {
187 const Type *Ty = S->getType();
188 Value *LHS = expandInTy(S->getLHS(), Ty);
189 Value *RHS = expandInTy(S->getRHS(), Ty);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000190 return BinaryOperator::createDiv(LHS, RHS, "tmp.", InsertPt);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000191 }
192
193 Value *visitAddRecExpr(SCEVAddRecExpr *S);
194
195 Value *visitUnknown(SCEVUnknown *S) {
196 return S->getValue();
197 }
198 };
199}
200
201Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
202 const Type *Ty = S->getType();
203 int FirstOp = 0; // Set if we should emit a subtract.
204 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
205 if (SC->getValue()->isAllOnesValue())
206 FirstOp = 1;
207
208 int i = S->getNumOperands()-2;
209 Value *V = expandInTy(S->getOperand(i+1), Ty);
210
211 // Emit a bunch of multiply instructions
212 for (; i >= FirstOp; --i)
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000213 V = BinaryOperator::createMul(V, expandInTy(S->getOperand(i), Ty),
214 "tmp.", InsertPt);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000215 // -1 * ... ---> 0 - ...
216 if (FirstOp == 1)
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000217 V = BinaryOperator::createNeg(V, "tmp.", InsertPt);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000218 return V;
219}
220
221Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
222 const Type *Ty = S->getType();
223 const Loop *L = S->getLoop();
224 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
225 assert(Ty->isIntegral() && "Cannot expand fp recurrences yet!");
226
227 // {X,+,F} --> X + {0,+,F}
228 if (!isa<SCEVConstant>(S->getStart()) ||
229 !cast<SCEVConstant>(S->getStart())->getValue()->isNullValue()) {
230 Value *Start = expandInTy(S->getStart(), Ty);
231 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
232 NewOps[0] = SCEVUnknown::getIntegerSCEV(0, Ty);
233 Value *Rest = expandInTy(SCEVAddRecExpr::get(NewOps, L), Ty);
234
235 // FIXME: look for an existing add to use.
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000236 return BinaryOperator::createAdd(Rest, Start, "tmp.", InsertPt);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000237 }
238
239 // {0,+,1} --> Insert a canonical induction variable into the loop!
240 if (S->getNumOperands() == 2 &&
241 S->getOperand(1) == SCEVUnknown::getIntegerSCEV(1, Ty)) {
242 // Create and insert the PHI node for the induction variable in the
243 // specified loop.
244 BasicBlock *Header = L->getHeader();
245 PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
246 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
247
248 pred_iterator HPI = pred_begin(Header);
249 assert(HPI != pred_end(Header) && "Loop with zero preds???");
250 if (!L->contains(*HPI)) ++HPI;
251 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
252 "No backedge in loop?");
253
254 // Insert a unit add instruction right before the terminator corresponding
255 // to the back-edge.
256 Constant *One = Ty->isFloatingPoint() ? (Constant*)ConstantFP::get(Ty, 1.0)
257 : ConstantInt::get(Ty, 1);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000258 Instruction *Add = BinaryOperator::createAdd(PN, One, "indvar.next",
259 (*HPI)->getTerminator());
Chris Lattner4a7553e2004-04-23 21:29:48 +0000260
261 pred_iterator PI = pred_begin(Header);
262 if (*PI == L->getLoopPreheader())
263 ++PI;
264 PN->addIncoming(Add, *PI);
265 return PN;
266 }
267
268 // Get the canonical induction variable I for this loop.
269 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
270
271 if (S->getNumOperands() == 2) { // {0,+,F} --> i*F
272 Value *F = expandInTy(S->getOperand(1), Ty);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000273 return BinaryOperator::createMul(I, F, "tmp.", InsertPt);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000274 }
275
276 // If this is a chain of recurrences, turn it into a closed form, using the
277 // folders, then expandCodeFor the closed form. This allows the folders to
278 // simplify the expression without having to build a bunch of special code
279 // into this folder.
280 SCEVHandle IH = SCEVUnknown::get(I); // Get I as a "symbolic" SCEV.
281
282 SCEVHandle V = S->evaluateAtIteration(IH);
283 //std::cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
284
285 return expandInTy(V, Ty);
286}
287
288
289namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +0000290 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner40bf8b42004-04-02 20:24:31 +0000291 Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
Chris Lattner3adf51d2003-09-10 05:24:46 +0000292 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner40bf8b42004-04-02 20:24:31 +0000293 Statistic<> NumReplaced("indvars", "Number of exit values replaced");
294 Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +0000295
296 class IndVarSimplify : public FunctionPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000297 LoopInfo *LI;
298 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +0000299 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +0000300 public:
301 virtual bool runOnFunction(Function &) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000302 LI = &getAnalysis<LoopInfo>();
303 SE = &getAnalysis<ScalarEvolution>();
Chris Lattner15cad752003-12-23 07:47:09 +0000304 Changed = false;
305
Chris Lattner3324e712003-12-22 03:58:44 +0000306 // Induction Variables live in the header nodes of loops
Chris Lattner40bf8b42004-04-02 20:24:31 +0000307 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner329c1c62004-01-08 00:09:44 +0000308 runOnLoop(*I);
Chris Lattner3324e712003-12-22 03:58:44 +0000309 return Changed;
310 }
311
Chris Lattner3324e712003-12-22 03:58:44 +0000312 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner3324e712003-12-22 03:58:44 +0000313 AU.addRequiredID(LoopSimplifyID);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000314 AU.addRequired<ScalarEvolution>();
315 AU.addRequired<LoopInfo>();
Chris Lattner3324e712003-12-22 03:58:44 +0000316 AU.addPreservedID(LoopSimplifyID);
317 AU.setPreservesCFG();
318 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000319 private:
320 void runOnLoop(Loop *L);
321 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
322 std::set<Instruction*> &DeadInsts);
323 void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
Chris Lattner4a7553e2004-04-23 21:29:48 +0000324 SCEVExpander &RW);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000325 void RewriteLoopExitValues(Loop *L);
326
327 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattner3324e712003-12-22 03:58:44 +0000328 };
329 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner5e761402002-09-10 05:24:05 +0000330}
Chris Lattner394437f2001-12-04 04:32:29 +0000331
Chris Lattner4b501562004-09-20 04:43:15 +0000332FunctionPass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000333 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000334}
335
Chris Lattner40bf8b42004-04-02 20:24:31 +0000336/// DeleteTriviallyDeadInstructions - If any of the instructions is the
337/// specified set are trivially dead, delete them and see if this makes any of
338/// their operands subsequently dead.
339void IndVarSimplify::
340DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
341 while (!Insts.empty()) {
342 Instruction *I = *Insts.begin();
343 Insts.erase(Insts.begin());
344 if (isInstructionTriviallyDead(I)) {
345 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
346 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
347 Insts.insert(U);
348 SE->deleteInstructionFromRecords(I);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000349 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000350 Changed = true;
351 }
352 }
353}
354
355
356/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
357/// recurrence. If so, change it into an integer recurrence, permitting
358/// analysis by the SCEV routines.
359void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
360 BasicBlock *Preheader,
361 std::set<Instruction*> &DeadInsts) {
362 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
363 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
364 unsigned BackedgeIdx = PreheaderIdx^1;
365 if (GetElementPtrInst *GEPI =
366 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
367 if (GEPI->getOperand(0) == PN) {
368 assert(GEPI->getNumOperands() == 2 && "GEP types must mismatch!");
369
370 // Okay, we found a pointer recurrence. Transform this pointer
371 // recurrence into an integer recurrence. Compute the value that gets
372 // added to the pointer at every iteration.
373 Value *AddedVal = GEPI->getOperand(1);
374
375 // Insert a new integer PHI node into the top of the block.
376 PHINode *NewPhi = new PHINode(AddedVal->getType(),
377 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000378 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
379
Chris Lattner40bf8b42004-04-02 20:24:31 +0000380 // Create the new add instruction.
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000381 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
382 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000383 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
384
385 // Update the existing GEP to use the recurrence.
386 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
387
388 // Update the GEP to use the new recurrence we just inserted.
389 GEPI->setOperand(1, NewAdd);
390
Chris Lattnera4b9c782004-10-11 23:06:50 +0000391 // If the incoming value is a constant expr GEP, try peeling out the array
392 // 0 index if possible to make things simpler.
393 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
394 if (CE->getOpcode() == Instruction::GetElementPtr) {
395 unsigned NumOps = CE->getNumOperands();
396 assert(NumOps > 1 && "CE folding didn't work!");
397 if (CE->getOperand(NumOps-1)->isNullValue()) {
398 // Check to make sure the last index really is an array index.
399 gep_type_iterator GTI = gep_type_begin(GEPI);
400 for (unsigned i = 1, e = GEPI->getNumOperands()-1;
401 i != e; ++i, ++GTI)
402 /*empty*/;
403 if (isa<SequentialType>(*GTI)) {
404 // Pull the last index out of the constant expr GEP.
405 std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
406 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
407 CEIdxs);
408 GetElementPtrInst *NGEPI =
409 new GetElementPtrInst(NCE, Constant::getNullValue(Type::IntTy),
410 NewAdd, GEPI->getName(), GEPI);
411 GEPI->replaceAllUsesWith(NGEPI);
412 GEPI->eraseFromParent();
413 GEPI = NGEPI;
414 }
415 }
416 }
417
418
Chris Lattner40bf8b42004-04-02 20:24:31 +0000419 // Finally, if there are any other users of the PHI node, we must
420 // insert a new GEP instruction that uses the pre-incremented version
421 // of the induction amount.
422 if (!PN->use_empty()) {
423 BasicBlock::iterator InsertPos = PN; ++InsertPos;
424 while (isa<PHINode>(InsertPos)) ++InsertPos;
425 std::string Name = PN->getName(); PN->setName("");
426 Value *PreInc =
427 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
428 std::vector<Value*>(1, NewPhi), Name,
429 InsertPos);
430 PN->replaceAllUsesWith(PreInc);
431 }
432
433 // Delete the old PHI for sure, and the GEP if its otherwise unused.
434 DeadInsts.insert(PN);
435
436 ++NumPointer;
437 Changed = true;
438 }
439}
440
441/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000442/// loop to be a canonical != comparison against the incremented loop induction
443/// variable. This pass is able to rewrite the exit tests of any loop where the
444/// SCEV analysis can determine a loop-invariant trip count of the loop, which
445/// is actually a much broader range than just linear tests.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000446void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
Chris Lattner4a7553e2004-04-23 21:29:48 +0000447 SCEVExpander &RW) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000448 // Find the exit block for the loop. We can currently only handle loops with
449 // a single exit.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000450 std::vector<BasicBlock*> ExitBlocks;
451 L->getExitBlocks(ExitBlocks);
452 if (ExitBlocks.size() != 1) return;
453 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000454
455 // Make sure there is only one predecessor block in the loop.
456 BasicBlock *ExitingBlock = 0;
457 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
458 PI != PE; ++PI)
459 if (L->contains(*PI)) {
460 if (ExitingBlock == 0)
461 ExitingBlock = *PI;
462 else
463 return; // Multiple exits from loop to this block.
464 }
465 assert(ExitingBlock && "Loop info is broken");
466
467 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
468 return; // Can't rewrite non-branch yet
469 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
470 assert(BI->isConditional() && "Must be conditional to be part of loop!");
471
472 std::set<Instruction*> InstructionsToDelete;
473 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
474 InstructionsToDelete.insert(Cond);
475
Chris Lattnerd2440572004-04-15 20:26:22 +0000476 // If the exiting block is not the same as the backedge block, we must compare
477 // against the preincremented value, otherwise we prefer to compare against
478 // the post-incremented value.
479 BasicBlock *Header = L->getHeader();
480 pred_iterator HPI = pred_begin(Header);
481 assert(HPI != pred_end(Header) && "Loop with zero preds???");
482 if (!L->contains(*HPI)) ++HPI;
483 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
484 "No backedge in loop?");
Chris Lattner59fdaee2004-04-15 15:21:43 +0000485
Chris Lattnerd2440572004-04-15 20:26:22 +0000486 SCEVHandle TripCount = IterationCount;
487 Value *IndVar;
488 if (*HPI == ExitingBlock) {
489 // The IterationCount expression contains the number of times that the
490 // backedge actually branches to the loop header. This is one less than the
491 // number of times the loop executes, so add one to it.
492 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
493 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
494 IndVar = L->getCanonicalInductionVariableIncrement();
495 } else {
496 // We have to use the preincremented value...
497 IndVar = L->getCanonicalInductionVariable();
498 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000499
Chris Lattner40bf8b42004-04-02 20:24:31 +0000500 // Expand the code for the iteration count into the preheader of the loop.
501 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattner4a7553e2004-04-23 21:29:48 +0000502 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
Chris Lattner40bf8b42004-04-02 20:24:31 +0000503 IndVar->getType());
504
505 // Insert a new setne or seteq instruction before the branch.
506 Instruction::BinaryOps Opcode;
507 if (L->contains(BI->getSuccessor(0)))
508 Opcode = Instruction::SetNE;
509 else
510 Opcode = Instruction::SetEQ;
511
512 Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
513 BI->setCondition(Cond);
514 ++NumLFTR;
515 Changed = true;
516
517 DeleteTriviallyDeadInstructions(InstructionsToDelete);
518}
519
520
521/// RewriteLoopExitValues - Check to see if this loop has a computable
522/// loop-invariant execution count. If so, this means that we can compute the
523/// final value of any expressions that are recurrent in the loop, and
524/// substitute the exit values from the loop into any instructions outside of
525/// the loop that use the final values of the current expressions.
526void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
527 BasicBlock *Preheader = L->getLoopPreheader();
528
529 // Scan all of the instructions in the loop, looking at those that have
530 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000531 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000532
533 // We insert the code into the preheader of the loop if the loop contains
534 // multiple exit blocks, or in the exit block if there is exactly one.
535 BasicBlock *BlockToInsertInto;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000536 std::vector<BasicBlock*> ExitBlocks;
537 L->getExitBlocks(ExitBlocks);
538 if (ExitBlocks.size() == 1)
539 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000540 else
541 BlockToInsertInto = Preheader;
542 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
543 while (isa<PHINode>(InsertPt)) ++InsertPt;
544
Chris Lattner20aa0982004-04-17 18:44:09 +0000545 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
546
Chris Lattner40bf8b42004-04-02 20:24:31 +0000547 std::set<Instruction*> InstructionsToDelete;
548
549 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
550 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
551 BasicBlock *BB = L->getBlocks()[i];
552 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
553 if (I->getType()->isInteger()) { // Is an integer instruction
554 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner20aa0982004-04-17 18:44:09 +0000555 if (SH->hasComputableLoopEvolution(L) || // Varies predictably
556 HasConstantItCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000557 // Find out if this predictably varying value is actually used
558 // outside of the loop. "extra" as opposed to "intra".
559 std::vector<User*> ExtraLoopUsers;
560 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
561 UI != E; ++UI)
562 if (!L->contains(cast<Instruction>(*UI)->getParent()))
563 ExtraLoopUsers.push_back(*UI);
564 if (!ExtraLoopUsers.empty()) {
565 // Okay, this instruction has a user outside of the current loop
566 // and varies predictably in this loop. Evaluate the value it
567 // contains when the loop exits, and insert code for it.
Chris Lattner20aa0982004-04-17 18:44:09 +0000568 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000569 if (!isa<SCEVCouldNotCompute>(ExitValue)) {
570 Changed = true;
571 ++NumReplaced;
Chris Lattner4a7553e2004-04-23 21:29:48 +0000572 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000573 I->getType());
574
575 // Rewrite any users of the computed value outside of the loop
576 // with the newly computed value.
577 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i)
578 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
579
580 // If this instruction is dead now, schedule it to be removed.
581 if (I->use_empty())
582 InstructionsToDelete.insert(I);
583 }
584 }
585 }
586 }
587 }
588
589 DeleteTriviallyDeadInstructions(InstructionsToDelete);
590}
591
592
593void IndVarSimplify::runOnLoop(Loop *L) {
594 // First step. Check to see if there are any trivial GEP pointer recurrences.
595 // If there are, change them into integer recurrences, permitting analysis by
596 // the SCEV routines.
597 //
598 BasicBlock *Header = L->getHeader();
599 BasicBlock *Preheader = L->getLoopPreheader();
600
601 std::set<Instruction*> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000602 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
603 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000604 if (isa<PointerType>(PN->getType()))
605 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000606 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000607
608 if (!DeadInsts.empty())
609 DeleteTriviallyDeadInstructions(DeadInsts);
610
611
612 // Next, transform all loops nesting inside of this loop.
613 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
Chris Lattner329c1c62004-01-08 00:09:44 +0000614 runOnLoop(*I);
Chris Lattner3324e712003-12-22 03:58:44 +0000615
Chris Lattner40bf8b42004-04-02 20:24:31 +0000616 // Check to see if this loop has a computable loop-invariant execution count.
617 // If so, this means that we can compute the final value of any expressions
618 // that are recurrent in the loop, and substitute the exit values from the
619 // loop into any instructions outside of the loop that use the final values of
620 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000621 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000622 SCEVHandle IterationCount = SE->getIterationCount(L);
623 if (!isa<SCEVCouldNotCompute>(IterationCount))
624 RewriteLoopExitValues(L);
Chris Lattner6148c022001-12-03 17:28:42 +0000625
Chris Lattner40bf8b42004-04-02 20:24:31 +0000626 // Next, analyze all of the induction variables in the loop, canonicalizing
627 // auxillary induction variables.
628 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
629
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000630 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
631 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000632 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
633 SCEVHandle SCEV = SE->getSCEV(PN);
634 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattnera25502a2004-06-24 06:49:18 +0000635 // FIXME: Without a strength reduction pass, it is an extremely bad idea
636 // to indvar substitute anything more complex than a linear induction
637 // variable. Doing so will put expensive multiply instructions inside
638 // of the loop. For now just disable indvar subst on anything more
639 // complex than a linear addrec.
Chris Lattner595ee7e2004-07-26 02:47:12 +0000640 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
641 if (AR->getNumOperands() == 2 && isa<SCEVConstant>(AR->getOperand(1)))
642 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000643 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000644 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000645
646 // If there are no induction variables in the loop, there is nothing more to
647 // do.
Chris Lattnerf50af082004-04-17 18:08:33 +0000648 if (IndVars.empty()) {
649 // Actually, if we know how many times the loop iterates, lets insert a
650 // canonical induction variable to help subsequent passes.
651 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner4a7553e2004-04-23 21:29:48 +0000652 SCEVExpander Rewriter(*SE, *LI);
653 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattnerf50af082004-04-17 18:08:33 +0000654 IterationCount->getType());
655 LinearFunctionTestReplace(L, IterationCount, Rewriter);
656 }
657 return;
658 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000659
660 // Compute the type of the largest recurrence expression.
Chris Lattner6148c022001-12-03 17:28:42 +0000661 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000662 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000663 bool DifferingSizes = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000664 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
665 const Type *Ty = IndVars[i].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000666 DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000667 if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
668 LargestType = Ty;
Chris Lattner6148c022001-12-03 17:28:42 +0000669 }
670
Chris Lattner40bf8b42004-04-02 20:24:31 +0000671 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000672 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000673
Chris Lattner40bf8b42004-04-02 20:24:31 +0000674 // Now that we know the largest of of the induction variables in this loop,
675 // insert a canonical induction variable of the largest size.
Chris Lattner006118f2004-04-16 06:03:17 +0000676 LargestType = LargestType->getUnsignedVersion();
Chris Lattner4a7553e2004-04-23 21:29:48 +0000677 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000678 ++NumInserted;
679 Changed = true;
Chris Lattner15cad752003-12-23 07:47:09 +0000680
Chris Lattner40bf8b42004-04-02 20:24:31 +0000681 if (!isa<SCEVCouldNotCompute>(IterationCount))
Chris Lattner59fdaee2004-04-15 15:21:43 +0000682 LinearFunctionTestReplace(L, IterationCount, Rewriter);
Chris Lattner15cad752003-12-23 07:47:09 +0000683
Chris Lattner40bf8b42004-04-02 20:24:31 +0000684 // Now that we have a canonical induction variable, we can rewrite any
685 // recurrences in terms of the induction variable. Start with the auxillary
686 // induction variables, and recursively rewrite any of their uses.
687 BasicBlock::iterator InsertPt = Header->begin();
688 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner6148c022001-12-03 17:28:42 +0000689
Chris Lattner5d461d22004-04-21 22:22:01 +0000690 // If there were induction variables of other sizes, cast the primary
691 // induction variable to the right size for them, avoiding the need for the
692 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000693 if (DifferingSizes) {
694 bool InsertedSizes[17] = { false };
695 InsertedSizes[LargestType->getPrimitiveSize()] = true;
696 for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
697 if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
698 PHINode *PN = IndVars[i].first;
699 InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
700 Instruction *New = new CastInst(IndVar,
701 PN->getType()->getUnsignedVersion(),
702 "indvar", InsertPt);
703 Rewriter.addInsertedValue(New, SE->getSCEV(New));
704 }
705 }
706
707 // If there were induction variables of other sizes, cast the primary
708 // induction variable to the right size for them, avoiding the need for the
709 // code evaluation methods to insert induction variables of different sizes.
Chris Lattner5d461d22004-04-21 22:22:01 +0000710 std::map<unsigned, Value*> InsertedSizes;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000711 while (!IndVars.empty()) {
712 PHINode *PN = IndVars.back().first;
Chris Lattner4a7553e2004-04-23 21:29:48 +0000713 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000714 PN->getType());
715 std::string Name = PN->getName();
716 PN->setName("");
717 NewVal->setName(Name);
Chris Lattner5d461d22004-04-21 22:22:01 +0000718
Chris Lattner40bf8b42004-04-02 20:24:31 +0000719 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000720 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000721 DeadInsts.insert(PN);
722 IndVars.pop_back();
723 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000724 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000725 }
726
Chris Lattnerb4782d12004-04-22 15:12:36 +0000727#if 0
Chris Lattner1363e852004-04-21 23:36:08 +0000728 // Now replace all derived expressions in the loop body with simpler
729 // expressions.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000730 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
731 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
732 BasicBlock *BB = L->getBlocks()[i];
733 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
734 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattner1363e852004-04-21 23:36:08 +0000735 !I->use_empty() &&
Chris Lattner40bf8b42004-04-02 20:24:31 +0000736 !Rewriter.isInsertedInstruction(I)) {
737 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000738 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattner1363e852004-04-21 23:36:08 +0000739 if (V != I) {
740 if (isa<Instruction>(V)) {
741 std::string Name = I->getName();
742 I->setName("");
743 V->setName(Name);
744 }
745 I->replaceAllUsesWith(V);
746 DeadInsts.insert(I);
747 ++NumRemoved;
748 Changed = true;
749 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000750 }
Chris Lattner394437f2001-12-04 04:32:29 +0000751 }
Chris Lattnerb4782d12004-04-22 15:12:36 +0000752#endif
Chris Lattner1363e852004-04-21 23:36:08 +0000753
Chris Lattner1363e852004-04-21 23:36:08 +0000754 DeleteTriviallyDeadInstructions(DeadInsts);
Chris Lattner6148c022001-12-03 17:28:42 +0000755}