1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
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.
22 // If the trip count of a loop is computable, this pass also makes the following
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.
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).
38 //===----------------------------------------------------------------------===//
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/BasicBlock.h"
42 #include "llvm/Constants.h"
43 #include "llvm/Instructions.h"
44 #include "llvm/Type.h"
45 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Support/CFG.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "Support/CommandLine.h"
50 #include "Support/Statistic.h"
54 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
55 Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
56 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
57 Statistic<> NumReplaced("indvars", "Number of exit values replaced");
58 Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced");
60 class IndVarSimplify : public FunctionPass {
65 virtual bool runOnFunction(Function &) {
66 LI = &getAnalysis<LoopInfo>();
67 SE = &getAnalysis<ScalarEvolution>();
70 // Induction Variables live in the header nodes of loops
71 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addRequiredID(LoopSimplifyID);
78 AU.addRequired<ScalarEvolution>();
79 AU.addRequired<LoopInfo>();
80 AU.addPreservedID(LoopSimplifyID);
84 void runOnLoop(Loop *L);
85 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
86 std::set<Instruction*> &DeadInsts);
87 void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
88 ScalarEvolutionRewriter &RW);
89 void RewriteLoopExitValues(Loop *L);
91 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
93 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
96 Pass *llvm::createIndVarSimplifyPass() {
97 return new IndVarSimplify();
101 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
102 /// specified set are trivially dead, delete them and see if this makes any of
103 /// their operands subsequently dead.
104 void IndVarSimplify::
105 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
106 while (!Insts.empty()) {
107 Instruction *I = *Insts.begin();
108 Insts.erase(Insts.begin());
109 if (isInstructionTriviallyDead(I)) {
110 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
111 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
113 SE->deleteInstructionFromRecords(I);
114 I->getParent()->getInstList().erase(I);
121 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
122 /// recurrence. If so, change it into an integer recurrence, permitting
123 /// analysis by the SCEV routines.
124 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
125 BasicBlock *Preheader,
126 std::set<Instruction*> &DeadInsts) {
127 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
128 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
129 unsigned BackedgeIdx = PreheaderIdx^1;
130 if (GetElementPtrInst *GEPI =
131 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
132 if (GEPI->getOperand(0) == PN) {
133 assert(GEPI->getNumOperands() == 2 && "GEP types must mismatch!");
135 // Okay, we found a pointer recurrence. Transform this pointer
136 // recurrence into an integer recurrence. Compute the value that gets
137 // added to the pointer at every iteration.
138 Value *AddedVal = GEPI->getOperand(1);
140 // Insert a new integer PHI node into the top of the block.
141 PHINode *NewPhi = new PHINode(AddedVal->getType(),
142 PN->getName()+".rec", PN);
143 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()),
145 // Create the new add instruction.
146 Value *NewAdd = BinaryOperator::create(Instruction::Add, NewPhi,
148 GEPI->getName()+".rec", GEPI);
149 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
151 // Update the existing GEP to use the recurrence.
152 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
154 // Update the GEP to use the new recurrence we just inserted.
155 GEPI->setOperand(1, NewAdd);
157 // Finally, if there are any other users of the PHI node, we must
158 // insert a new GEP instruction that uses the pre-incremented version
159 // of the induction amount.
160 if (!PN->use_empty()) {
161 BasicBlock::iterator InsertPos = PN; ++InsertPos;
162 while (isa<PHINode>(InsertPos)) ++InsertPos;
163 std::string Name = PN->getName(); PN->setName("");
165 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
166 std::vector<Value*>(1, NewPhi), Name,
168 PN->replaceAllUsesWith(PreInc);
171 // Delete the old PHI for sure, and the GEP if its otherwise unused.
172 DeadInsts.insert(PN);
179 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
180 /// loop to be a canonical != comparison against the incremented loop induction
181 /// variable. This pass is able to rewrite the exit tests of any loop where the
182 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
183 /// is actually a much broader range than just linear tests.
184 void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
185 ScalarEvolutionRewriter &RW) {
186 // Find the exit block for the loop. We can currently only handle loops with
188 if (L->getExitBlocks().size() != 1) return;
189 BasicBlock *ExitBlock = L->getExitBlocks()[0];
191 // Make sure there is only one predecessor block in the loop.
192 BasicBlock *ExitingBlock = 0;
193 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
195 if (L->contains(*PI)) {
196 if (ExitingBlock == 0)
199 return; // Multiple exits from loop to this block.
201 assert(ExitingBlock && "Loop info is broken");
203 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
204 return; // Can't rewrite non-branch yet
205 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
206 assert(BI->isConditional() && "Must be conditional to be part of loop!");
208 std::set<Instruction*> InstructionsToDelete;
209 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
210 InstructionsToDelete.insert(Cond);
212 // If the exiting block is not the same as the backedge block, we must compare
213 // against the preincremented value, otherwise we prefer to compare against
214 // the post-incremented value.
215 BasicBlock *Header = L->getHeader();
216 pred_iterator HPI = pred_begin(Header);
217 assert(HPI != pred_end(Header) && "Loop with zero preds???");
218 if (!L->contains(*HPI)) ++HPI;
219 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
220 "No backedge in loop?");
222 SCEVHandle TripCount = IterationCount;
224 if (*HPI == ExitingBlock) {
225 // The IterationCount expression contains the number of times that the
226 // backedge actually branches to the loop header. This is one less than the
227 // number of times the loop executes, so add one to it.
228 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
229 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
230 IndVar = L->getCanonicalInductionVariableIncrement();
232 // We have to use the preincremented value...
233 IndVar = L->getCanonicalInductionVariable();
236 // Expand the code for the iteration count into the preheader of the loop.
237 BasicBlock *Preheader = L->getLoopPreheader();
238 Value *ExitCnt = RW.ExpandCodeFor(TripCount, Preheader->getTerminator(),
241 // Insert a new setne or seteq instruction before the branch.
242 Instruction::BinaryOps Opcode;
243 if (L->contains(BI->getSuccessor(0)))
244 Opcode = Instruction::SetNE;
246 Opcode = Instruction::SetEQ;
248 Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
249 BI->setCondition(Cond);
253 DeleteTriviallyDeadInstructions(InstructionsToDelete);
257 /// RewriteLoopExitValues - Check to see if this loop has a computable
258 /// loop-invariant execution count. If so, this means that we can compute the
259 /// final value of any expressions that are recurrent in the loop, and
260 /// substitute the exit values from the loop into any instructions outside of
261 /// the loop that use the final values of the current expressions.
262 void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
263 BasicBlock *Preheader = L->getLoopPreheader();
265 // Scan all of the instructions in the loop, looking at those that have
266 // extra-loop users and which are recurrences.
267 ScalarEvolutionRewriter Rewriter(*SE, *LI);
269 // We insert the code into the preheader of the loop if the loop contains
270 // multiple exit blocks, or in the exit block if there is exactly one.
271 BasicBlock *BlockToInsertInto;
272 if (L->getExitBlocks().size() == 1)
273 BlockToInsertInto = L->getExitBlocks()[0];
275 BlockToInsertInto = Preheader;
276 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
277 while (isa<PHINode>(InsertPt)) ++InsertPt;
279 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
281 std::set<Instruction*> InstructionsToDelete;
283 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
284 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
285 BasicBlock *BB = L->getBlocks()[i];
286 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
287 if (I->getType()->isInteger()) { // Is an integer instruction
288 SCEVHandle SH = SE->getSCEV(I);
289 if (SH->hasComputableLoopEvolution(L) || // Varies predictably
290 HasConstantItCount) {
291 // Find out if this predictably varying value is actually used
292 // outside of the loop. "extra" as opposed to "intra".
293 std::vector<User*> ExtraLoopUsers;
294 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
296 if (!L->contains(cast<Instruction>(*UI)->getParent()))
297 ExtraLoopUsers.push_back(*UI);
298 if (!ExtraLoopUsers.empty()) {
299 // Okay, this instruction has a user outside of the current loop
300 // and varies predictably in this loop. Evaluate the value it
301 // contains when the loop exits, and insert code for it.
302 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
303 if (!isa<SCEVCouldNotCompute>(ExitValue)) {
306 Value *NewVal = Rewriter.ExpandCodeFor(ExitValue, InsertPt,
309 // Rewrite any users of the computed value outside of the loop
310 // with the newly computed value.
311 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i)
312 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
314 // If this instruction is dead now, schedule it to be removed.
316 InstructionsToDelete.insert(I);
323 DeleteTriviallyDeadInstructions(InstructionsToDelete);
327 void IndVarSimplify::runOnLoop(Loop *L) {
328 // First step. Check to see if there are any trivial GEP pointer recurrences.
329 // If there are, change them into integer recurrences, permitting analysis by
330 // the SCEV routines.
332 BasicBlock *Header = L->getHeader();
333 BasicBlock *Preheader = L->getLoopPreheader();
335 std::set<Instruction*> DeadInsts;
336 for (BasicBlock::iterator I = Header->begin();
337 PHINode *PN = dyn_cast<PHINode>(I); ++I)
338 if (isa<PointerType>(PN->getType()))
339 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
341 if (!DeadInsts.empty())
342 DeleteTriviallyDeadInstructions(DeadInsts);
345 // Next, transform all loops nesting inside of this loop.
346 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
349 // Check to see if this loop has a computable loop-invariant execution count.
350 // If so, this means that we can compute the final value of any expressions
351 // that are recurrent in the loop, and substitute the exit values from the
352 // loop into any instructions outside of the loop that use the final values of
353 // the current expressions.
355 SCEVHandle IterationCount = SE->getIterationCount(L);
356 if (!isa<SCEVCouldNotCompute>(IterationCount))
357 RewriteLoopExitValues(L);
359 // Next, analyze all of the induction variables in the loop, canonicalizing
360 // auxillary induction variables.
361 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
363 for (BasicBlock::iterator I = Header->begin();
364 PHINode *PN = dyn_cast<PHINode>(I); ++I)
365 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
366 SCEVHandle SCEV = SE->getSCEV(PN);
367 if (SCEV->hasComputableLoopEvolution(L))
368 if (SE->shouldSubstituteIndVar(SCEV)) // HACK!
369 IndVars.push_back(std::make_pair(PN, SCEV));
372 // If there are no induction variables in the loop, there is nothing more to
374 if (IndVars.empty()) {
375 // Actually, if we know how many times the loop iterates, lets insert a
376 // canonical induction variable to help subsequent passes.
377 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
378 ScalarEvolutionRewriter Rewriter(*SE, *LI);
379 Rewriter.GetOrInsertCanonicalInductionVariable(L,
380 IterationCount->getType());
381 LinearFunctionTestReplace(L, IterationCount, Rewriter);
386 // Compute the type of the largest recurrence expression.
388 const Type *LargestType = IndVars[0].first->getType();
389 bool DifferingSizes = false;
390 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
391 const Type *Ty = IndVars[i].first->getType();
392 DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
393 if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
397 // Create a rewriter object which we'll use to transform the code with.
398 ScalarEvolutionRewriter Rewriter(*SE, *LI);
400 // Now that we know the largest of of the induction variables in this loop,
401 // insert a canonical induction variable of the largest size.
402 LargestType = LargestType->getUnsignedVersion();
403 Value *IndVar = Rewriter.GetOrInsertCanonicalInductionVariable(L,LargestType);
407 if (!isa<SCEVCouldNotCompute>(IterationCount))
408 LinearFunctionTestReplace(L, IterationCount, Rewriter);
411 // If there were induction variables of other sizes, cast the primary
412 // induction variable to the right size for them, avoiding the need for the
413 // code evaluation methods to insert induction variables of different sizes.
415 if (DifferingSizes) {
416 std::map<unsigned, Value*> InsertedSizes;
417 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
422 // Now that we have a canonical induction variable, we can rewrite any
423 // recurrences in terms of the induction variable. Start with the auxillary
424 // induction variables, and recursively rewrite any of their uses.
425 BasicBlock::iterator InsertPt = Header->begin();
426 while (isa<PHINode>(InsertPt)) ++InsertPt;
428 while (!IndVars.empty()) {
429 PHINode *PN = IndVars.back().first;
430 Value *NewVal = Rewriter.ExpandCodeFor(IndVars.back().second, InsertPt,
432 // Replace the old PHI Node with the inserted computation.
433 PN->replaceAllUsesWith(NewVal);
434 DeadInsts.insert(PN);
440 DeleteTriviallyDeadInstructions(DeadInsts);
442 // TODO: In the future we could replace all instructions in the loop body with
443 // simpler expressions. It's not clear how useful this would be though or if
444 // the code expansion cost would be worth it! We probably shouldn't do this
445 // until we have a way to reuse expressions already in the code.
447 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
448 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
449 BasicBlock *BB = L->getBlocks()[i];
450 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
451 if (I->getType()->isInteger() && // Is an integer instruction
452 !Rewriter.isInsertedInstruction(I)) {
453 SCEVHandle SH = SE->getSCEV(I);