blob: cd674ae4b6039f4307ff82023acde11cd4b843ed [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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//
Reid Spencer47a53ac2006-08-18 09:01:07 +000014// This transformation makes the following changes to each loop with an
Chris Lattner40bf8b42004-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 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"
Nate Begeman36f891b2005-07-30 00:12:19 +000045#include "llvm/Analysis/ScalarEvolutionExpander.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 Lattnera92f6962002-10-01 22:38:41 +000055 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner40bf8b42004-04-02 20:24:31 +000056 Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
Chris Lattner3adf51d2003-09-10 05:24:46 +000057 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner40bf8b42004-04-02 20:24:31 +000058 Statistic<> NumReplaced("indvars", "Number of exit values replaced");
59 Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced");
Chris Lattner3324e712003-12-22 03:58:44 +000060
61 class IndVarSimplify : public FunctionPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000062 LoopInfo *LI;
63 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000064 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000065 public:
66 virtual bool runOnFunction(Function &) {
Chris Lattner40bf8b42004-04-02 20:24:31 +000067 LI = &getAnalysis<LoopInfo>();
68 SE = &getAnalysis<ScalarEvolution>();
Chris Lattner15cad752003-12-23 07:47:09 +000069 Changed = false;
70
Chris Lattner3324e712003-12-22 03:58:44 +000071 // Induction Variables live in the header nodes of loops
Chris Lattner40bf8b42004-04-02 20:24:31 +000072 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner329c1c62004-01-08 00:09:44 +000073 runOnLoop(*I);
Chris Lattner3324e712003-12-22 03:58:44 +000074 return Changed;
75 }
76
Chris Lattner3324e712003-12-22 03:58:44 +000077 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner3324e712003-12-22 03:58:44 +000078 AU.addRequiredID(LoopSimplifyID);
Chris Lattner40bf8b42004-04-02 20:24:31 +000079 AU.addRequired<ScalarEvolution>();
80 AU.addRequired<LoopInfo>();
Chris Lattner3324e712003-12-22 03:58:44 +000081 AU.addPreservedID(LoopSimplifyID);
Owen Andersonac123222006-08-25 17:41:25 +000082 AU.addPreservedID(LCSSAID);
Chris Lattner3324e712003-12-22 03:58:44 +000083 AU.setPreservesCFG();
84 }
Chris Lattner40bf8b42004-04-02 20:24:31 +000085 private:
86 void runOnLoop(Loop *L);
87 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
88 std::set<Instruction*> &DeadInsts);
Chris Lattner9ba46c12006-09-21 05:12:20 +000089 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
90 SCEVExpander &RW);
Chris Lattner40bf8b42004-04-02 20:24:31 +000091 void RewriteLoopExitValues(Loop *L);
92
93 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattner3324e712003-12-22 03:58:44 +000094 };
Chris Lattner7f8897f2006-08-27 22:42:52 +000095 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner5e761402002-09-10 05:24:05 +000096}
Chris Lattner394437f2001-12-04 04:32:29 +000097
Chris Lattner4b501562004-09-20 04:43:15 +000098FunctionPass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +000099 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000100}
101
Chris Lattner40bf8b42004-04-02 20:24:31 +0000102/// DeleteTriviallyDeadInstructions - If any of the instructions is the
103/// specified set are trivially dead, delete them and see if this makes any of
104/// their operands subsequently dead.
105void IndVarSimplify::
106DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
107 while (!Insts.empty()) {
108 Instruction *I = *Insts.begin();
109 Insts.erase(Insts.begin());
110 if (isInstructionTriviallyDead(I)) {
111 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
112 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
113 Insts.insert(U);
114 SE->deleteInstructionFromRecords(I);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000115 I->eraseFromParent();
Chris Lattner40bf8b42004-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 Brukmanfd939082005-04-21 23:48:37 +0000125void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-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 Lattnercda9ca52005-08-10 01:12:06 +0000132 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000133 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000134 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000135
Chris Lattner40bf8b42004-04-02 20:24:31 +0000136 // Okay, we found a pointer recurrence. Transform this pointer
137 // recurrence into an integer recurrence. Compute the value that gets
138 // added to the pointer at every iteration.
139 Value *AddedVal = GEPI->getOperand(1);
140
141 // Insert a new integer PHI node into the top of the block.
142 PHINode *NewPhi = new PHINode(AddedVal->getType(),
143 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000144 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
145
Chris Lattner40bf8b42004-04-02 20:24:31 +0000146 // Create the new add instruction.
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000147 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
148 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000149 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000150
Chris Lattner40bf8b42004-04-02 20:24:31 +0000151 // Update the existing GEP to use the recurrence.
152 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000153
Chris Lattner40bf8b42004-04-02 20:24:31 +0000154 // Update the GEP to use the new recurrence we just inserted.
155 GEPI->setOperand(1, NewAdd);
156
Chris Lattnera4b9c782004-10-11 23:06:50 +0000157 // If the incoming value is a constant expr GEP, try peeling out the array
158 // 0 index if possible to make things simpler.
159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
160 if (CE->getOpcode() == Instruction::GetElementPtr) {
161 unsigned NumOps = CE->getNumOperands();
162 assert(NumOps > 1 && "CE folding didn't work!");
163 if (CE->getOperand(NumOps-1)->isNullValue()) {
164 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000165 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000166 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000167 i != e; ++i, ++GTI)
168 /*empty*/;
169 if (isa<SequentialType>(*GTI)) {
170 // Pull the last index out of the constant expr GEP.
171 std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
172 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
173 CEIdxs);
174 GetElementPtrInst *NGEPI =
175 new GetElementPtrInst(NCE, Constant::getNullValue(Type::IntTy),
176 NewAdd, GEPI->getName(), GEPI);
177 GEPI->replaceAllUsesWith(NGEPI);
178 GEPI->eraseFromParent();
179 GEPI = NGEPI;
180 }
181 }
182 }
183
184
Chris Lattner40bf8b42004-04-02 20:24:31 +0000185 // Finally, if there are any other users of the PHI node, we must
186 // insert a new GEP instruction that uses the pre-incremented version
187 // of the induction amount.
188 if (!PN->use_empty()) {
189 BasicBlock::iterator InsertPos = PN; ++InsertPos;
190 while (isa<PHINode>(InsertPos)) ++InsertPos;
191 std::string Name = PN->getName(); PN->setName("");
192 Value *PreInc =
193 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
194 std::vector<Value*>(1, NewPhi), Name,
195 InsertPos);
196 PN->replaceAllUsesWith(PreInc);
197 }
198
199 // Delete the old PHI for sure, and the GEP if its otherwise unused.
200 DeadInsts.insert(PN);
201
202 ++NumPointer;
203 Changed = true;
204 }
205}
206
207/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000208/// loop to be a canonical != comparison against the incremented loop induction
209/// variable. This pass is able to rewrite the exit tests of any loop where the
210/// SCEV analysis can determine a loop-invariant trip count of the loop, which
211/// is actually a much broader range than just linear tests.
Chris Lattner9ba46c12006-09-21 05:12:20 +0000212///
213/// This method returns a "potentially dead" instruction whose computation chain
214/// should be deleted when convenient.
215Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
216 SCEV *IterationCount,
217 SCEVExpander &RW) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000218 // Find the exit block for the loop. We can currently only handle loops with
219 // a single exit.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000220 std::vector<BasicBlock*> ExitBlocks;
221 L->getExitBlocks(ExitBlocks);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000222 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000223 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000224
225 // Make sure there is only one predecessor block in the loop.
226 BasicBlock *ExitingBlock = 0;
227 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
228 PI != PE; ++PI)
229 if (L->contains(*PI)) {
230 if (ExitingBlock == 0)
231 ExitingBlock = *PI;
232 else
Chris Lattner9ba46c12006-09-21 05:12:20 +0000233 return 0; // Multiple exits from loop to this block.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000234 }
235 assert(ExitingBlock && "Loop info is broken");
236
237 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner9ba46c12006-09-21 05:12:20 +0000238 return 0; // Can't rewrite non-branch yet
Chris Lattner40bf8b42004-04-02 20:24:31 +0000239 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
240 assert(BI->isConditional() && "Must be conditional to be part of loop!");
241
Chris Lattner9ba46c12006-09-21 05:12:20 +0000242 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
243
Chris Lattnerd2440572004-04-15 20:26:22 +0000244 // If the exiting block is not the same as the backedge block, we must compare
245 // against the preincremented value, otherwise we prefer to compare against
246 // the post-incremented value.
247 BasicBlock *Header = L->getHeader();
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?");
Chris Lattner59fdaee2004-04-15 15:21:43 +0000253
Chris Lattnerd2440572004-04-15 20:26:22 +0000254 SCEVHandle TripCount = IterationCount;
255 Value *IndVar;
256 if (*HPI == ExitingBlock) {
257 // The IterationCount expression contains the number of times that the
258 // backedge actually branches to the loop header. This is one less than the
259 // number of times the loop executes, so add one to it.
260 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
261 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
262 IndVar = L->getCanonicalInductionVariableIncrement();
263 } else {
264 // We have to use the preincremented value...
265 IndVar = L->getCanonicalInductionVariable();
266 }
Chris Lattner59fdaee2004-04-15 15:21:43 +0000267
Chris Lattner40bf8b42004-04-02 20:24:31 +0000268 // Expand the code for the iteration count into the preheader of the loop.
269 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattner4a7553e2004-04-23 21:29:48 +0000270 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
Chris Lattner40bf8b42004-04-02 20:24:31 +0000271 IndVar->getType());
272
273 // Insert a new setne or seteq instruction before the branch.
274 Instruction::BinaryOps Opcode;
275 if (L->contains(BI->getSuccessor(0)))
276 Opcode = Instruction::SetNE;
277 else
278 Opcode = Instruction::SetEQ;
279
280 Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
281 BI->setCondition(Cond);
282 ++NumLFTR;
283 Changed = true;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000284 return PotentiallyDeadInst;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000285}
286
287
288/// RewriteLoopExitValues - Check to see if this loop has a computable
289/// loop-invariant execution count. If so, this means that we can compute the
290/// final value of any expressions that are recurrent in the loop, and
291/// substitute the exit values from the loop into any instructions outside of
292/// the loop that use the final values of the current expressions.
293void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
294 BasicBlock *Preheader = L->getLoopPreheader();
295
296 // Scan all of the instructions in the loop, looking at those that have
297 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000298 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000299
300 // We insert the code into the preheader of the loop if the loop contains
301 // multiple exit blocks, or in the exit block if there is exactly one.
302 BasicBlock *BlockToInsertInto;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000303 std::vector<BasicBlock*> ExitBlocks;
304 L->getExitBlocks(ExitBlocks);
305 if (ExitBlocks.size() == 1)
306 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000307 else
308 BlockToInsertInto = Preheader;
309 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
310 while (isa<PHINode>(InsertPt)) ++InsertPt;
311
Chris Lattner20aa0982004-04-17 18:44:09 +0000312 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
313
Chris Lattner40bf8b42004-04-02 20:24:31 +0000314 std::set<Instruction*> InstructionsToDelete;
Misha Brukmanfd939082005-04-21 23:48:37 +0000315
Chris Lattner40bf8b42004-04-02 20:24:31 +0000316 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
317 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
318 BasicBlock *BB = L->getBlocks()[i];
Chris Lattner4bd09d72005-06-15 21:29:31 +0000319 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000320 if (I->getType()->isInteger()) { // Is an integer instruction
321 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner20aa0982004-04-17 18:44:09 +0000322 if (SH->hasComputableLoopEvolution(L) || // Varies predictably
323 HasConstantItCount) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000324 // Find out if this predictably varying value is actually used
325 // outside of the loop. "extra" as opposed to "intra".
Chris Lattnereb83f4e2006-06-17 01:02:31 +0000326 std::vector<Instruction*> ExtraLoopUsers;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000327 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Chris Lattnereb83f4e2006-06-17 01:02:31 +0000328 UI != E; ++UI) {
329 Instruction *User = cast<Instruction>(*UI);
Chris Lattner26204182006-07-13 19:05:20 +0000330 if (!L->contains(User->getParent())) {
331 // If this is a PHI node in the exit block and we're inserting,
332 // into the exit block, it must have a single entry. In this
333 // case, we can't insert the code after the PHI and have the PHI
334 // still use it. Instead, don't insert the the PHI.
335 if (PHINode *PN = dyn_cast<PHINode>(User)) {
336 // FIXME: This is a case where LCSSA pessimizes code, this
337 // should be fixed better.
338 if (PN->getNumOperands() == 2 &&
339 PN->getParent() == BlockToInsertInto)
340 continue;
341 }
Chris Lattnereb83f4e2006-06-17 01:02:31 +0000342 ExtraLoopUsers.push_back(User);
Chris Lattner26204182006-07-13 19:05:20 +0000343 }
Chris Lattnereb83f4e2006-06-17 01:02:31 +0000344 }
345
Chris Lattner40bf8b42004-04-02 20:24:31 +0000346 if (!ExtraLoopUsers.empty()) {
347 // Okay, this instruction has a user outside of the current loop
348 // and varies predictably in this loop. Evaluate the value it
349 // contains when the loop exits, and insert code for it.
Chris Lattner20aa0982004-04-17 18:44:09 +0000350 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000351 if (!isa<SCEVCouldNotCompute>(ExitValue)) {
352 Changed = true;
353 ++NumReplaced;
Chris Lattner4bd09d72005-06-15 21:29:31 +0000354 // Remember the next instruction. The rewriter can move code
355 // around in some cases.
356 BasicBlock::iterator NextI = I; ++NextI;
357
Chris Lattner4a7553e2004-04-23 21:29:48 +0000358 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000359 I->getType());
360
361 // Rewrite any users of the computed value outside of the loop
362 // with the newly computed value.
Owen Andersonc1be4922006-07-14 18:49:15 +0000363 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
364 PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]);
365 if (PN && PN->getNumOperands() == 2 &&
366 !L->contains(PN->getParent())) {
367 // We're dealing with an LCSSA Phi. Handle it specially.
368 Instruction* LCSSAInsertPt = BlockToInsertInto->begin();
369
370 Instruction* NewInstr = dyn_cast<Instruction>(NewVal);
371 if (NewInstr && !isa<PHINode>(NewInstr) &&
372 !L->contains(NewInstr->getParent()))
373 for (unsigned j = 0; j < NewInstr->getNumOperands(); ++j){
374 Instruction* PredI =
375 dyn_cast<Instruction>(NewInstr->getOperand(j));
376 if (PredI && L->contains(PredI->getParent())) {
377 PHINode* NewLCSSA = new PHINode(PredI->getType(),
378 PredI->getName() + ".lcssa",
379 LCSSAInsertPt);
380 NewLCSSA->addIncoming(PredI,
381 BlockToInsertInto->getSinglePredecessor());
382
383 NewInstr->replaceUsesOfWith(PredI, NewLCSSA);
384 }
385 }
386
387 PN->replaceAllUsesWith(NewVal);
388 PN->eraseFromParent();
389 } else {
390 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
391 }
392 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000393
394 // If this instruction is dead now, schedule it to be removed.
395 if (I->use_empty())
396 InstructionsToDelete.insert(I);
Chris Lattner4bd09d72005-06-15 21:29:31 +0000397 I = NextI;
398 continue; // Skip the ++I
Chris Lattner40bf8b42004-04-02 20:24:31 +0000399 }
400 }
401 }
402 }
Chris Lattner4bd09d72005-06-15 21:29:31 +0000403
404 // Next instruction. Continue instruction skips this.
405 ++I;
406 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000407 }
408
409 DeleteTriviallyDeadInstructions(InstructionsToDelete);
410}
411
412
413void IndVarSimplify::runOnLoop(Loop *L) {
414 // First step. Check to see if there are any trivial GEP pointer recurrences.
415 // If there are, change them into integer recurrences, permitting analysis by
416 // the SCEV routines.
417 //
418 BasicBlock *Header = L->getHeader();
419 BasicBlock *Preheader = L->getLoopPreheader();
Misha Brukmanfd939082005-04-21 23:48:37 +0000420
Chris Lattner40bf8b42004-04-02 20:24:31 +0000421 std::set<Instruction*> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000422 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
423 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000424 if (isa<PointerType>(PN->getType()))
425 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000426 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000427
428 if (!DeadInsts.empty())
429 DeleteTriviallyDeadInstructions(DeadInsts);
430
431
432 // Next, transform all loops nesting inside of this loop.
433 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
Chris Lattner329c1c62004-01-08 00:09:44 +0000434 runOnLoop(*I);
Chris Lattner3324e712003-12-22 03:58:44 +0000435
Chris Lattner40bf8b42004-04-02 20:24:31 +0000436 // Check to see if this loop has a computable loop-invariant execution count.
437 // If so, this means that we can compute the final value of any expressions
438 // that are recurrent in the loop, and substitute the exit values from the
439 // loop into any instructions outside of the loop that use the final values of
440 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000441 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000442 SCEVHandle IterationCount = SE->getIterationCount(L);
443 if (!isa<SCEVCouldNotCompute>(IterationCount))
444 RewriteLoopExitValues(L);
Chris Lattner6148c022001-12-03 17:28:42 +0000445
Chris Lattner40bf8b42004-04-02 20:24:31 +0000446 // Next, analyze all of the induction variables in the loop, canonicalizing
447 // auxillary induction variables.
448 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
449
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000450 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
451 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000452 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
453 SCEVHandle SCEV = SE->getSCEV(PN);
454 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000455 // FIXME: It is an extremely bad idea to indvar substitute anything more
456 // complex than affine induction variables. Doing so will put expensive
457 // polynomial evaluations inside of the loop, and the str reduction pass
458 // currently can only reduce affine polynomials. For now just disable
459 // indvar subst on anything more complex than an affine addrec.
Chris Lattner595ee7e2004-07-26 02:47:12 +0000460 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000461 if (AR->isAffine())
Chris Lattner595ee7e2004-07-26 02:47:12 +0000462 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000463 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000464 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000465
466 // If there are no induction variables in the loop, there is nothing more to
467 // do.
Chris Lattnerf50af082004-04-17 18:08:33 +0000468 if (IndVars.empty()) {
469 // Actually, if we know how many times the loop iterates, lets insert a
470 // canonical induction variable to help subsequent passes.
471 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner4a7553e2004-04-23 21:29:48 +0000472 SCEVExpander Rewriter(*SE, *LI);
473 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattnerf50af082004-04-17 18:08:33 +0000474 IterationCount->getType());
Chris Lattner9ba46c12006-09-21 05:12:20 +0000475 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
476 Rewriter)) {
477 std::set<Instruction*> InstructionsToDelete;
478 InstructionsToDelete.insert(I);
479 DeleteTriviallyDeadInstructions(InstructionsToDelete);
480 }
Chris Lattnerf50af082004-04-17 18:08:33 +0000481 }
482 return;
483 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000484
485 // Compute the type of the largest recurrence expression.
Chris Lattner6148c022001-12-03 17:28:42 +0000486 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000487 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000488 bool DifferingSizes = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000489 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
490 const Type *Ty = IndVars[i].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000491 DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000492 if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
493 LargestType = Ty;
Chris Lattner6148c022001-12-03 17:28:42 +0000494 }
495
Chris Lattner40bf8b42004-04-02 20:24:31 +0000496 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000497 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000498
Chris Lattner40bf8b42004-04-02 20:24:31 +0000499 // Now that we know the largest of of the induction variables in this loop,
500 // insert a canonical induction variable of the largest size.
Chris Lattner006118f2004-04-16 06:03:17 +0000501 LargestType = LargestType->getUnsignedVersion();
Chris Lattner4a7553e2004-04-23 21:29:48 +0000502 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000503 ++NumInserted;
504 Changed = true;
Chris Lattner15cad752003-12-23 07:47:09 +0000505
Chris Lattner40bf8b42004-04-02 20:24:31 +0000506 if (!isa<SCEVCouldNotCompute>(IterationCount))
Chris Lattner9ba46c12006-09-21 05:12:20 +0000507 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
508 DeadInsts.insert(DI);
Chris Lattner15cad752003-12-23 07:47:09 +0000509
Chris Lattner40bf8b42004-04-02 20:24:31 +0000510 // Now that we have a canonical induction variable, we can rewrite any
511 // recurrences in terms of the induction variable. Start with the auxillary
512 // induction variables, and recursively rewrite any of their uses.
513 BasicBlock::iterator InsertPt = Header->begin();
514 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner6148c022001-12-03 17:28:42 +0000515
Chris Lattner5d461d22004-04-21 22:22:01 +0000516 // If there were induction variables of other sizes, cast the primary
517 // induction variable to the right size for them, avoiding the need for the
518 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000519 if (DifferingSizes) {
520 bool InsertedSizes[17] = { false };
521 InsertedSizes[LargestType->getPrimitiveSize()] = true;
522 for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
523 if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
524 PHINode *PN = IndVars[i].first;
525 InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
Reid Spencer3da59db2006-11-27 01:05:10 +0000526 Instruction *New = CastInst::create(Instruction::Trunc, IndVar,
527 PN->getType()->getUnsignedVersion(), "indvar", InsertPt);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000528 Rewriter.addInsertedValue(New, SE->getSCEV(New));
529 }
530 }
531
532 // If there were induction variables of other sizes, cast the primary
533 // induction variable to the right size for them, avoiding the need for the
534 // code evaluation methods to insert induction variables of different sizes.
Chris Lattner5d461d22004-04-21 22:22:01 +0000535 std::map<unsigned, Value*> InsertedSizes;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000536 while (!IndVars.empty()) {
537 PHINode *PN = IndVars.back().first;
Chris Lattner4a7553e2004-04-23 21:29:48 +0000538 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000539 PN->getType());
540 std::string Name = PN->getName();
541 PN->setName("");
542 NewVal->setName(Name);
Chris Lattner5d461d22004-04-21 22:22:01 +0000543
Chris Lattner40bf8b42004-04-02 20:24:31 +0000544 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000545 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000546 DeadInsts.insert(PN);
547 IndVars.pop_back();
548 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000549 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000550 }
551
Chris Lattnerb4782d12004-04-22 15:12:36 +0000552#if 0
Chris Lattner1363e852004-04-21 23:36:08 +0000553 // Now replace all derived expressions in the loop body with simpler
554 // expressions.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000555 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
556 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
557 BasicBlock *BB = L->getBlocks()[i];
558 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
559 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattner1363e852004-04-21 23:36:08 +0000560 !I->use_empty() &&
Chris Lattner40bf8b42004-04-02 20:24:31 +0000561 !Rewriter.isInsertedInstruction(I)) {
562 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000563 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattner1363e852004-04-21 23:36:08 +0000564 if (V != I) {
565 if (isa<Instruction>(V)) {
566 std::string Name = I->getName();
567 I->setName("");
568 V->setName(Name);
569 }
570 I->replaceAllUsesWith(V);
571 DeadInsts.insert(I);
572 ++NumRemoved;
573 Changed = true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000574 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000575 }
Chris Lattner394437f2001-12-04 04:32:29 +0000576 }
Chris Lattnerb4782d12004-04-22 15:12:36 +0000577#endif
Chris Lattner1363e852004-04-21 23:36:08 +0000578
Chris Lattner1363e852004-04-21 23:36:08 +0000579 DeleteTriviallyDeadInstructions(DeadInsts);
Owen Andersoneb705912006-08-25 22:12:36 +0000580
581 if (mustPreserveAnalysisID(LCSSAID)) assert(L->isLCSSAForm());
Chris Lattner6148c022001-12-03 17:28:42 +0000582}