blob: 43054227aeaece19b73a5a395bf876ecfcd00366 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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 Lattner0e5f4992006-12-19 21:40:18 +000040#define DEBUG_TYPE "indvars"
Chris Lattner022103b2002-05-07 20:03:00 +000041#include "llvm/Transforms/Scalar.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000042#include "llvm/BasicBlock.h"
Chris Lattner59fdaee2004-04-15 15:21:43 +000043#include "llvm/Constants.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000044#include "llvm/Instructions.h"
Chris Lattner40bf8b42004-04-02 20:24:31 +000045#include "llvm/Type.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
John Criswell47df12d2003-12-18 17:19:19 +000047#include "llvm/Analysis/LoopInfo.h"
Devang Patel5ee99972007-03-07 06:39:01 +000048#include "llvm/Analysis/LoopPass.h"
Chris Lattner455889a2002-02-12 22:39:50 +000049#include "llvm/Support/CFG.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000050#include "llvm/Support/Compiler.h"
Chris Lattneree4f13a2007-01-07 01:14:12 +000051#include "llvm/Support/Debug.h"
Chris Lattnera4b9c782004-10-11 23:06:50 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
John Criswell47df12d2003-12-18 17:19:19 +000053#include "llvm/Transforms/Utils/Local.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000054#include "llvm/Support/CommandLine.h"
Reid Spencera54b7cb2007-01-12 07:05:14 +000055#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000056#include "llvm/ADT/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000057using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattner0e5f4992006-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 Lattner3324e712003-12-22 03:58:44 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065namespace {
Devang Patel5ee99972007-03-07 06:39:01 +000066 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
Chris Lattner40bf8b42004-04-02 20:24:31 +000067 LoopInfo *LI;
68 ScalarEvolution *SE;
Chris Lattner15cad752003-12-23 07:47:09 +000069 bool Changed;
Chris Lattner3324e712003-12-22 03:58:44 +000070 public:
Devang Patel794fd752007-05-01 21:15:47 +000071
Nick Lewyckyecd94c82007-05-06 13:37:16 +000072 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000073 IndVarSimplify() : LoopPass((intptr_t)&ID) {}
74
Devang Patel5ee99972007-03-07 06:39:01 +000075 bool runOnLoop(Loop *L, LPPassManager &LPM);
76 bool doInitialization(Loop *L, LPPassManager &LPM);
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelbc533cd2007-09-10 18:08:23 +000078 AU.addRequired<ScalarEvolution>();
Devang Patel5ee99972007-03-07 06:39:01 +000079 AU.addRequiredID(LCSSAID);
80 AU.addRequiredID(LoopSimplifyID);
Devang Patel5ee99972007-03-07 06:39:01 +000081 AU.addRequired<LoopInfo>();
82 AU.addPreservedID(LoopSimplifyID);
83 AU.addPreservedID(LCSSAID);
84 AU.setPreservesCFG();
85 }
Chris Lattner15cad752003-12-23 07:47:09 +000086
Chris Lattner40bf8b42004-04-02 20:24:31 +000087 private:
Devang Patel5ee99972007-03-07 06:39:01 +000088
Chris Lattner40bf8b42004-04-02 20:24:31 +000089 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
90 std::set<Instruction*> &DeadInsts);
Chris Lattner9ba46c12006-09-21 05:12:20 +000091 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
92 SCEVExpander &RW);
Chris Lattner40bf8b42004-04-02 20:24:31 +000093 void RewriteLoopExitValues(Loop *L);
94
95 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
Chris Lattner3324e712003-12-22 03:58:44 +000096 };
Devang Patel794fd752007-05-01 21:15:47 +000097
Devang Patel19974732007-05-03 01:11:54 +000098 char IndVarSimplify::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000099 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner5e761402002-09-10 05:24:05 +0000100}
Chris Lattner394437f2001-12-04 04:32:29 +0000101
Devang Patel5ee99972007-03-07 06:39:01 +0000102LoopPass *llvm::createIndVarSimplifyPass() {
Chris Lattner3324e712003-12-22 03:58:44 +0000103 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +0000104}
105
Chris Lattner40bf8b42004-04-02 20:24:31 +0000106/// DeleteTriviallyDeadInstructions - If any of the instructions is the
107/// specified set are trivially dead, delete them and see if this makes any of
108/// their operands subsequently dead.
109void IndVarSimplify::
110DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
111 while (!Insts.empty()) {
112 Instruction *I = *Insts.begin();
113 Insts.erase(Insts.begin());
114 if (isInstructionTriviallyDead(I)) {
115 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
116 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
117 Insts.insert(U);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000118 SE->deleteValueFromRecords(I);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000119 DOUT << "INDVARS: Deleting: " << *I;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000120 I->eraseFromParent();
Chris Lattner40bf8b42004-04-02 20:24:31 +0000121 Changed = true;
122 }
123 }
124}
125
126
127/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
128/// recurrence. If so, change it into an integer recurrence, permitting
129/// analysis by the SCEV routines.
Misha Brukmanfd939082005-04-21 23:48:37 +0000130void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
Chris Lattner40bf8b42004-04-02 20:24:31 +0000131 BasicBlock *Preheader,
132 std::set<Instruction*> &DeadInsts) {
133 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
134 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
135 unsigned BackedgeIdx = PreheaderIdx^1;
136 if (GetElementPtrInst *GEPI =
Chris Lattnercda9ca52005-08-10 01:12:06 +0000137 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
Chris Lattner40bf8b42004-04-02 20:24:31 +0000138 if (GEPI->getOperand(0) == PN) {
Chris Lattnercda9ca52005-08-10 01:12:06 +0000139 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
Chris Lattneree4f13a2007-01-07 01:14:12 +0000140 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
141
Chris Lattner40bf8b42004-04-02 20:24:31 +0000142 // Okay, we found a pointer recurrence. Transform this pointer
143 // recurrence into an integer recurrence. Compute the value that gets
144 // added to the pointer at every iteration.
145 Value *AddedVal = GEPI->getOperand(1);
146
147 // Insert a new integer PHI node into the top of the block.
Gabor Greif051a9502008-04-06 20:25:17 +0000148 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
149 PN->getName()+".rec", PN);
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000150 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
151
Chris Lattner40bf8b42004-04-02 20:24:31 +0000152 // Create the new add instruction.
Chris Lattnerc5c5e6a2004-06-20 05:04:01 +0000153 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
154 GEPI->getName()+".rec", GEPI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000155 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000156
Chris Lattner40bf8b42004-04-02 20:24:31 +0000157 // Update the existing GEP to use the recurrence.
158 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
Misha Brukmanfd939082005-04-21 23:48:37 +0000159
Chris Lattner40bf8b42004-04-02 20:24:31 +0000160 // Update the GEP to use the new recurrence we just inserted.
161 GEPI->setOperand(1, NewAdd);
162
Chris Lattnera4b9c782004-10-11 23:06:50 +0000163 // If the incoming value is a constant expr GEP, try peeling out the array
164 // 0 index if possible to make things simpler.
165 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
166 if (CE->getOpcode() == Instruction::GetElementPtr) {
167 unsigned NumOps = CE->getNumOperands();
168 assert(NumOps > 1 && "CE folding didn't work!");
169 if (CE->getOperand(NumOps-1)->isNullValue()) {
170 // Check to make sure the last index really is an array index.
Chris Lattner17300782005-11-18 18:30:47 +0000171 gep_type_iterator GTI = gep_type_begin(CE);
Chris Lattnerceda6052005-11-17 19:35:42 +0000172 for (unsigned i = 1, e = CE->getNumOperands()-1;
Chris Lattnera4b9c782004-10-11 23:06:50 +0000173 i != e; ++i, ++GTI)
174 /*empty*/;
175 if (isa<SequentialType>(*GTI)) {
176 // Pull the last index out of the constant expr GEP.
Chris Lattner55eb1c42007-01-31 04:40:53 +0000177 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000178 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
Chris Lattner55eb1c42007-01-31 04:40:53 +0000179 &CEIdxs[0],
180 CEIdxs.size());
David Greeneb8f74792007-09-04 15:46:09 +0000181 Value *Idx[2];
182 Idx[0] = Constant::getNullValue(Type::Int32Ty);
183 Idx[1] = NewAdd;
Gabor Greif051a9502008-04-06 20:25:17 +0000184 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
David Greeneb8f74792007-09-04 15:46:09 +0000185 NCE, Idx, Idx + 2,
Reid Spencercae57542007-03-02 00:28:52 +0000186 GEPI->getName(), GEPI);
Dan Gohman5cec4db2007-06-19 14:28:31 +0000187 SE->deleteValueFromRecords(GEPI);
Chris Lattnera4b9c782004-10-11 23:06:50 +0000188 GEPI->replaceAllUsesWith(NGEPI);
189 GEPI->eraseFromParent();
190 GEPI = NGEPI;
191 }
192 }
193 }
194
195
Chris Lattner40bf8b42004-04-02 20:24:31 +0000196 // Finally, if there are any other users of the PHI node, we must
197 // insert a new GEP instruction that uses the pre-incremented version
198 // of the induction amount.
199 if (!PN->use_empty()) {
200 BasicBlock::iterator InsertPos = PN; ++InsertPos;
201 while (isa<PHINode>(InsertPos)) ++InsertPos;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000202 Value *PreInc =
Gabor Greif051a9502008-04-06 20:25:17 +0000203 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
204 NewPhi, "", InsertPos);
Chris Lattner6934a042007-02-11 01:23:03 +0000205 PreInc->takeName(PN);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000206 PN->replaceAllUsesWith(PreInc);
207 }
208
209 // Delete the old PHI for sure, and the GEP if its otherwise unused.
210 DeadInsts.insert(PN);
211
212 ++NumPointer;
213 Changed = true;
214 }
215}
216
217/// LinearFunctionTestReplace - This method rewrites the exit condition of the
Chris Lattner59fdaee2004-04-15 15:21:43 +0000218/// loop to be a canonical != comparison against the incremented loop induction
219/// variable. This pass is able to rewrite the exit tests of any loop where the
220/// SCEV analysis can determine a loop-invariant trip count of the loop, which
221/// is actually a much broader range than just linear tests.
Chris Lattner9ba46c12006-09-21 05:12:20 +0000222///
223/// This method returns a "potentially dead" instruction whose computation chain
224/// should be deleted when convenient.
225Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
226 SCEV *IterationCount,
227 SCEVExpander &RW) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000228 // Find the exit block for the loop. We can currently only handle loops with
229 // a single exit.
Devang Patelb7211a22007-08-21 00:31:24 +0000230 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000231 L->getExitBlocks(ExitBlocks);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000232 if (ExitBlocks.size() != 1) return 0;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000233 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000234
235 // Make sure there is only one predecessor block in the loop.
236 BasicBlock *ExitingBlock = 0;
237 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
238 PI != PE; ++PI)
239 if (L->contains(*PI)) {
240 if (ExitingBlock == 0)
241 ExitingBlock = *PI;
242 else
Chris Lattner9ba46c12006-09-21 05:12:20 +0000243 return 0; // Multiple exits from loop to this block.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000244 }
245 assert(ExitingBlock && "Loop info is broken");
246
247 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
Chris Lattner9ba46c12006-09-21 05:12:20 +0000248 return 0; // Can't rewrite non-branch yet
Chris Lattner40bf8b42004-04-02 20:24:31 +0000249 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
250 assert(BI->isConditional() && "Must be conditional to be part of loop!");
251
Chris Lattner9ba46c12006-09-21 05:12:20 +0000252 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
253
Chris Lattnerd2440572004-04-15 20:26:22 +0000254 // If the exiting block is not the same as the backedge block, we must compare
255 // against the preincremented value, otherwise we prefer to compare against
256 // the post-incremented value.
257 BasicBlock *Header = L->getHeader();
258 pred_iterator HPI = pred_begin(Header);
259 assert(HPI != pred_end(Header) && "Loop with zero preds???");
260 if (!L->contains(*HPI)) ++HPI;
261 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
262 "No backedge in loop?");
Chris Lattner59fdaee2004-04-15 15:21:43 +0000263
Chris Lattnerd2440572004-04-15 20:26:22 +0000264 SCEVHandle TripCount = IterationCount;
265 Value *IndVar;
266 if (*HPI == ExitingBlock) {
267 // The IterationCount expression contains the number of times that the
268 // backedge actually branches to the loop header. This is one less than the
269 // number of times the loop executes, so add one to it.
Dan Gohmane19dd872007-06-15 18:00:55 +0000270 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
Dan Gohman246b2562007-10-22 18:31:58 +0000271 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
Chris Lattnerd2440572004-04-15 20:26:22 +0000272 IndVar = L->getCanonicalInductionVariableIncrement();
273 } else {
274 // We have to use the preincremented value...
275 IndVar = L->getCanonicalInductionVariable();
276 }
Chris Lattneree4f13a2007-01-07 01:14:12 +0000277
278 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
279 << " IndVar = " << *IndVar << "\n";
Chris Lattner59fdaee2004-04-15 15:21:43 +0000280
Chris Lattner40bf8b42004-04-02 20:24:31 +0000281 // Expand the code for the iteration count into the preheader of the loop.
282 BasicBlock *Preheader = L->getLoopPreheader();
Dan Gohmand19534a2007-06-15 14:38:12 +0000283 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
Chris Lattner40bf8b42004-04-02 20:24:31 +0000284
Reid Spencere4d87aa2006-12-23 06:05:41 +0000285 // Insert a new icmp_ne or icmp_eq instruction before the branch.
286 ICmpInst::Predicate Opcode;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000287 if (L->contains(BI->getSuccessor(0)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000288 Opcode = ICmpInst::ICMP_NE;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000289 else
Reid Spencere4d87aa2006-12-23 06:05:41 +0000290 Opcode = ICmpInst::ICMP_EQ;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000291
Reid Spencere4d87aa2006-12-23 06:05:41 +0000292 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000293 BI->setCondition(Cond);
294 ++NumLFTR;
295 Changed = true;
Chris Lattner9ba46c12006-09-21 05:12:20 +0000296 return PotentiallyDeadInst;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000297}
298
299
300/// RewriteLoopExitValues - Check to see if this loop has a computable
301/// loop-invariant execution count. If so, this means that we can compute the
302/// final value of any expressions that are recurrent in the loop, and
303/// substitute the exit values from the loop into any instructions outside of
304/// the loop that use the final values of the current expressions.
305void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
306 BasicBlock *Preheader = L->getLoopPreheader();
307
308 // Scan all of the instructions in the loop, looking at those that have
309 // extra-loop users and which are recurrences.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000310 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000311
312 // We insert the code into the preheader of the loop if the loop contains
313 // multiple exit blocks, or in the exit block if there is exactly one.
314 BasicBlock *BlockToInsertInto;
Devang Patelb7211a22007-08-21 00:31:24 +0000315 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000316 L->getUniqueExitBlocks(ExitBlocks);
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000317 if (ExitBlocks.size() == 1)
318 BlockToInsertInto = ExitBlocks[0];
Chris Lattner40bf8b42004-04-02 20:24:31 +0000319 else
320 BlockToInsertInto = Preheader;
321 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
322 while (isa<PHINode>(InsertPt)) ++InsertPt;
323
Chris Lattner20aa0982004-04-17 18:44:09 +0000324 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
325
Chris Lattner40bf8b42004-04-02 20:24:31 +0000326 std::set<Instruction*> InstructionsToDelete;
Chris Lattner9f3d7382007-03-04 03:43:23 +0000327 std::map<Instruction*, Value*> ExitValues;
Misha Brukmanfd939082005-04-21 23:48:37 +0000328
Chris Lattner9f3d7382007-03-04 03:43:23 +0000329 // Find all values that are computed inside the loop, but used outside of it.
330 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
331 // the exit blocks of the loop to find them.
332 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
333 BasicBlock *ExitBB = ExitBlocks[i];
334
335 // If there are no PHI nodes in this exit block, then no values defined
336 // inside the loop are used on this path, skip it.
337 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
338 if (!PN) continue;
339
340 unsigned NumPreds = PN->getNumIncomingValues();
341
342 // Iterate over all of the PHI nodes.
343 BasicBlock::iterator BBI = ExitBB->begin();
344 while ((PN = dyn_cast<PHINode>(BBI++))) {
Chris Lattnerc9838f22007-03-03 22:48:48 +0000345
Chris Lattner9f3d7382007-03-04 03:43:23 +0000346 // Iterate over all of the values in all the PHI nodes.
347 for (unsigned i = 0; i != NumPreds; ++i) {
348 // If the value being merged in is not integer or is not defined
349 // in the loop, skip it.
350 Value *InVal = PN->getIncomingValue(i);
351 if (!isa<Instruction>(InVal) ||
352 // SCEV only supports integer expressions for now.
353 !isa<IntegerType>(InVal->getType()))
354 continue;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000355
Chris Lattner9f3d7382007-03-04 03:43:23 +0000356 // If this pred is for a subloop, not L itself, skip it.
357 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
358 continue; // The Block is in a subloop, skip it.
359
360 // Check that InVal is defined in the loop.
361 Instruction *Inst = cast<Instruction>(InVal);
362 if (!L->contains(Inst->getParent()))
363 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000364
Chris Lattner9f3d7382007-03-04 03:43:23 +0000365 // We require that this value either have a computable evolution or that
366 // the loop have a constant iteration count. In the case where the loop
367 // has a constant iteration count, we can sometimes force evaluation of
368 // the exit value through brute force.
369 SCEVHandle SH = SE->getSCEV(Inst);
370 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
371 continue; // Cannot get exit evolution for the loop value.
372
373 // Okay, this instruction has a user outside of the current loop
374 // and varies predictably *inside* the loop. Evaluate the value it
375 // contains when the loop exits, if possible.
376 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
377 if (isa<SCEVCouldNotCompute>(ExitValue) ||
378 !ExitValue->isLoopInvariant(L))
379 continue;
Chris Lattner9caed542007-03-04 01:00:28 +0000380
Chris Lattner9f3d7382007-03-04 03:43:23 +0000381 Changed = true;
382 ++NumReplaced;
383
384 // See if we already computed the exit value for the instruction, if so,
385 // just reuse it.
386 Value *&ExitVal = ExitValues[Inst];
387 if (!ExitVal)
Dan Gohmand19534a2007-06-15 14:38:12 +0000388 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000389
390 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
391 << " LoopVal = " << *Inst << "\n";
392
393 PN->setIncomingValue(i, ExitVal);
394
395 // If this instruction is dead now, schedule it to be removed.
396 if (Inst->use_empty())
397 InstructionsToDelete.insert(Inst);
398
399 // See if this is a single-entry LCSSA PHI node. If so, we can (and
400 // have to) remove
Chris Lattner9caed542007-03-04 01:00:28 +0000401 // the PHI entirely. This is safe, because the NewVal won't be variant
402 // in the loop, so we don't need an LCSSA phi node anymore.
Chris Lattner9f3d7382007-03-04 03:43:23 +0000403 if (NumPreds == 1) {
Dan Gohman5cec4db2007-06-19 14:28:31 +0000404 SE->deleteValueFromRecords(PN);
Chris Lattner9f3d7382007-03-04 03:43:23 +0000405 PN->replaceAllUsesWith(ExitVal);
406 PN->eraseFromParent();
407 break;
Chris Lattnerc9838f22007-03-03 22:48:48 +0000408 }
409 }
Chris Lattnerc9838f22007-03-03 22:48:48 +0000410 }
411 }
412
Chris Lattner40bf8b42004-04-02 20:24:31 +0000413 DeleteTriviallyDeadInstructions(InstructionsToDelete);
414}
415
Devang Patel5ee99972007-03-07 06:39:01 +0000416bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
Chris Lattner40bf8b42004-04-02 20:24:31 +0000417
Devang Patel5ee99972007-03-07 06:39:01 +0000418 Changed = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000419 // First step. Check to see if there are any trivial GEP pointer recurrences.
420 // If there are, change them into integer recurrences, permitting analysis by
421 // the SCEV routines.
422 //
423 BasicBlock *Header = L->getHeader();
424 BasicBlock *Preheader = L->getLoopPreheader();
Devang Patel5ee99972007-03-07 06:39:01 +0000425 SE = &LPM.getAnalysis<ScalarEvolution>();
Misha Brukmanfd939082005-04-21 23:48:37 +0000426
Chris Lattner40bf8b42004-04-02 20:24:31 +0000427 std::set<Instruction*> DeadInsts;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000428 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
429 PHINode *PN = cast<PHINode>(I);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000430 if (isa<PointerType>(PN->getType()))
431 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000432 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000433
434 if (!DeadInsts.empty())
435 DeleteTriviallyDeadInstructions(DeadInsts);
436
Devang Patel5ee99972007-03-07 06:39:01 +0000437 return Changed;
438}
Chris Lattner40bf8b42004-04-02 20:24:31 +0000439
Devang Patel5ee99972007-03-07 06:39:01 +0000440bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner3324e712003-12-22 03:58:44 +0000441
Devang Patel5ee99972007-03-07 06:39:01 +0000442
443 LI = &getAnalysis<LoopInfo>();
444 SE = &getAnalysis<ScalarEvolution>();
445
446 Changed = false;
447 BasicBlock *Header = L->getHeader();
448 std::set<Instruction*> DeadInsts;
449
Chris Lattner9caed542007-03-04 01:00:28 +0000450 // Verify the input to the pass in already in LCSSA form.
451 assert(L->isLCSSAForm());
452
Chris Lattner40bf8b42004-04-02 20:24:31 +0000453 // Check to see if this loop has a computable loop-invariant execution count.
454 // If so, this means that we can compute the final value of any expressions
455 // that are recurrent in the loop, and substitute the exit values from the
456 // loop into any instructions outside of the loop that use the final values of
457 // the current expressions.
Chris Lattner3dec1f22002-05-10 15:38:35 +0000458 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000459 SCEVHandle IterationCount = SE->getIterationCount(L);
460 if (!isa<SCEVCouldNotCompute>(IterationCount))
461 RewriteLoopExitValues(L);
Chris Lattner6148c022001-12-03 17:28:42 +0000462
Chris Lattner40bf8b42004-04-02 20:24:31 +0000463 // Next, analyze all of the induction variables in the loop, canonicalizing
464 // auxillary induction variables.
465 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
466
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000467 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
468 PHINode *PN = cast<PHINode>(I);
Chris Lattner42a75512007-01-15 02:27:26 +0000469 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
Chris Lattner40bf8b42004-04-02 20:24:31 +0000470 SCEVHandle SCEV = SE->getSCEV(PN);
471 if (SCEV->hasComputableLoopEvolution(L))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000472 // FIXME: It is an extremely bad idea to indvar substitute anything more
473 // complex than affine induction variables. Doing so will put expensive
474 // polynomial evaluations inside of the loop, and the str reduction pass
475 // currently can only reduce affine polynomials. For now just disable
476 // indvar subst on anything more complex than an affine addrec.
Chris Lattner595ee7e2004-07-26 02:47:12 +0000477 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
Chris Lattnercda9ca52005-08-10 01:12:06 +0000478 if (AR->isAffine())
Chris Lattner595ee7e2004-07-26 02:47:12 +0000479 IndVars.push_back(std::make_pair(PN, SCEV));
Chris Lattner40bf8b42004-04-02 20:24:31 +0000480 }
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000481 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000482
483 // If there are no induction variables in the loop, there is nothing more to
484 // do.
Chris Lattnerf50af082004-04-17 18:08:33 +0000485 if (IndVars.empty()) {
486 // Actually, if we know how many times the loop iterates, lets insert a
487 // canonical induction variable to help subsequent passes.
488 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Chris Lattner4a7553e2004-04-23 21:29:48 +0000489 SCEVExpander Rewriter(*SE, *LI);
490 Rewriter.getOrInsertCanonicalInductionVariable(L,
Chris Lattnerf50af082004-04-17 18:08:33 +0000491 IterationCount->getType());
Chris Lattner9ba46c12006-09-21 05:12:20 +0000492 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
493 Rewriter)) {
494 std::set<Instruction*> InstructionsToDelete;
495 InstructionsToDelete.insert(I);
496 DeleteTriviallyDeadInstructions(InstructionsToDelete);
497 }
Chris Lattnerf50af082004-04-17 18:08:33 +0000498 }
Devang Patel5ee99972007-03-07 06:39:01 +0000499 return Changed;
Chris Lattnerf50af082004-04-17 18:08:33 +0000500 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000501
502 // Compute the type of the largest recurrence expression.
Chris Lattner6148c022001-12-03 17:28:42 +0000503 //
Chris Lattner40bf8b42004-04-02 20:24:31 +0000504 const Type *LargestType = IndVars[0].first->getType();
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000505 bool DifferingSizes = false;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000506 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
507 const Type *Ty = IndVars[i].first->getType();
Reid Spencerabaa8ca2007-01-08 16:32:00 +0000508 DifferingSizes |=
509 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
510 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
Chris Lattner40bf8b42004-04-02 20:24:31 +0000511 LargestType = Ty;
Chris Lattner6148c022001-12-03 17:28:42 +0000512 }
513
Chris Lattner40bf8b42004-04-02 20:24:31 +0000514 // Create a rewriter object which we'll use to transform the code with.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000515 SCEVExpander Rewriter(*SE, *LI);
Chris Lattner15cad752003-12-23 07:47:09 +0000516
Chris Lattner40bf8b42004-04-02 20:24:31 +0000517 // Now that we know the largest of of the induction variables in this loop,
518 // insert a canonical induction variable of the largest size.
Chris Lattner4a7553e2004-04-23 21:29:48 +0000519 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000520 ++NumInserted;
521 Changed = true;
Chris Lattneree4f13a2007-01-07 01:14:12 +0000522 DOUT << "INDVARS: New CanIV: " << *IndVar;
Chris Lattner15cad752003-12-23 07:47:09 +0000523
Dan Gohmand19534a2007-06-15 14:38:12 +0000524 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
Zhou Sheng0d7d3652007-06-27 09:50:26 +0000525 if (IterationCount->getType()->getPrimitiveSizeInBits() <
526 LargestType->getPrimitiveSizeInBits())
Dan Gohman246b2562007-10-22 18:31:58 +0000527 IterationCount = SE->getZeroExtendExpr(IterationCount, LargestType);
Zhou Sheng0d7d3652007-06-27 09:50:26 +0000528 else if (IterationCount->getType() != LargestType)
Dan Gohman246b2562007-10-22 18:31:58 +0000529 IterationCount = SE->getTruncateExpr(IterationCount, LargestType);
Chris Lattner9ba46c12006-09-21 05:12:20 +0000530 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
531 DeadInsts.insert(DI);
Dan Gohmand19534a2007-06-15 14:38:12 +0000532 }
Chris Lattner15cad752003-12-23 07:47:09 +0000533
Chris Lattner40bf8b42004-04-02 20:24:31 +0000534 // Now that we have a canonical induction variable, we can rewrite any
535 // recurrences in terms of the induction variable. Start with the auxillary
536 // induction variables, and recursively rewrite any of their uses.
537 BasicBlock::iterator InsertPt = Header->begin();
538 while (isa<PHINode>(InsertPt)) ++InsertPt;
Chris Lattner6148c022001-12-03 17:28:42 +0000539
Chris Lattner5d461d22004-04-21 22:22:01 +0000540 // If there were induction variables of other sizes, cast the primary
541 // induction variable to the right size for them, avoiding the need for the
542 // code evaluation methods to insert induction variables of different sizes.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000543 if (DifferingSizes) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000544 SmallVector<unsigned,4> InsertedSizes;
545 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
546 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
547 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
Chris Lattneref60b2c2007-01-12 22:51:20 +0000548 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
549 == InsertedSizes.end()) {
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000550 PHINode *PN = IndVars[i].first;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000551 InsertedSizes.push_back(ithSize);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000552 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
553 InsertPt);
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000554 Rewriter.addInsertedValue(New, SE->getSCEV(New));
Chris Lattneree4f13a2007-01-07 01:14:12 +0000555 DOUT << "INDVARS: Made trunc IV for " << *PN
556 << " NewVal = " << *New << "\n";
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000557 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000558 }
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000559 }
560
Chris Lattneree4f13a2007-01-07 01:14:12 +0000561 // Rewrite all induction variables in terms of the canonical induction
562 // variable.
Chris Lattner5d461d22004-04-21 22:22:01 +0000563 std::map<unsigned, Value*> InsertedSizes;
Chris Lattner40bf8b42004-04-02 20:24:31 +0000564 while (!IndVars.empty()) {
565 PHINode *PN = IndVars.back().first;
Dan Gohmand19534a2007-06-15 14:38:12 +0000566 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
Chris Lattneree4f13a2007-01-07 01:14:12 +0000567 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
568 << " into = " << *NewVal << "\n";
Chris Lattner6934a042007-02-11 01:23:03 +0000569 NewVal->takeName(PN);
Chris Lattner5d461d22004-04-21 22:22:01 +0000570
Chris Lattner40bf8b42004-04-02 20:24:31 +0000571 // Replace the old PHI Node with the inserted computation.
Chris Lattnerfcb81f52004-04-22 14:59:40 +0000572 PN->replaceAllUsesWith(NewVal);
Chris Lattner40bf8b42004-04-02 20:24:31 +0000573 DeadInsts.insert(PN);
574 IndVars.pop_back();
575 ++NumRemoved;
Chris Lattner4753bf22001-12-05 19:41:33 +0000576 Changed = true;
Chris Lattner394437f2001-12-04 04:32:29 +0000577 }
578
Chris Lattnerb4782d12004-04-22 15:12:36 +0000579#if 0
Chris Lattner1363e852004-04-21 23:36:08 +0000580 // Now replace all derived expressions in the loop body with simpler
581 // expressions.
Chris Lattner40bf8b42004-04-02 20:24:31 +0000582 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
583 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
584 BasicBlock *BB = L->getBlocks()[i];
585 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +0000586 if (I->getType()->isInteger() && // Is an integer instruction
Chris Lattner1363e852004-04-21 23:36:08 +0000587 !I->use_empty() &&
Chris Lattner40bf8b42004-04-02 20:24:31 +0000588 !Rewriter.isInsertedInstruction(I)) {
589 SCEVHandle SH = SE->getSCEV(I);
Chris Lattner4a7553e2004-04-23 21:29:48 +0000590 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
Chris Lattner1363e852004-04-21 23:36:08 +0000591 if (V != I) {
Chris Lattner6934a042007-02-11 01:23:03 +0000592 if (isa<Instruction>(V))
593 V->takeName(I);
Chris Lattner1363e852004-04-21 23:36:08 +0000594 I->replaceAllUsesWith(V);
595 DeadInsts.insert(I);
596 ++NumRemoved;
597 Changed = true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000598 }
Chris Lattner40bf8b42004-04-02 20:24:31 +0000599 }
Chris Lattner394437f2001-12-04 04:32:29 +0000600 }
Chris Lattnerb4782d12004-04-22 15:12:36 +0000601#endif
Chris Lattner1363e852004-04-21 23:36:08 +0000602
Chris Lattner1363e852004-04-21 23:36:08 +0000603 DeleteTriviallyDeadInstructions(DeadInsts);
Owen Andersoneb705912006-08-25 22:12:36 +0000604
Chris Lattner9caed542007-03-04 01:00:28 +0000605 assert(L->isLCSSAForm());
Devang Patel5ee99972007-03-07 06:39:01 +0000606 return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000607}