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/ScalarEvolutionExpander.h"
46 #include "llvm/Analysis/LoopInfo.h"
47 #include "llvm/Support/CFG.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/ADT/Statistic.h"
55 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
56 Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
57 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
58 Statistic<> NumReplaced("indvars", "Number of exit values replaced");
59 Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced");
61 class IndVarSimplify : public FunctionPass {
66 virtual bool runOnFunction(Function &) {
67 LI = &getAnalysis<LoopInfo>();
68 SE = &getAnalysis<ScalarEvolution>();
71 // Induction Variables live in the header nodes of loops
72 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequiredID(LoopSimplifyID);
79 AU.addRequired<ScalarEvolution>();
80 AU.addRequired<LoopInfo>();
81 AU.addPreservedID(LoopSimplifyID);
85 void runOnLoop(Loop *L);
86 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
87 std::set<Instruction*> &DeadInsts);
88 void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
90 void RewriteLoopExitValues(Loop *L);
92 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
94 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
97 FunctionPass *llvm::createIndVarSimplifyPass() {
98 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->eraseFromParent();
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 match!");
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()), Preheader);
145 // Create the new add instruction.
146 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
147 GEPI->getName()+".rec", GEPI);
148 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
150 // Update the existing GEP to use the recurrence.
151 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
153 // Update the GEP to use the new recurrence we just inserted.
154 GEPI->setOperand(1, NewAdd);
156 // If the incoming value is a constant expr GEP, try peeling out the array
157 // 0 index if possible to make things simpler.
158 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
159 if (CE->getOpcode() == Instruction::GetElementPtr) {
160 unsigned NumOps = CE->getNumOperands();
161 assert(NumOps > 1 && "CE folding didn't work!");
162 if (CE->getOperand(NumOps-1)->isNullValue()) {
163 // Check to make sure the last index really is an array index.
164 gep_type_iterator GTI = gep_type_begin(CE);
165 for (unsigned i = 1, e = CE->getNumOperands()-1;
168 if (isa<SequentialType>(*GTI)) {
169 // Pull the last index out of the constant expr GEP.
170 std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
171 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
173 GetElementPtrInst *NGEPI =
174 new GetElementPtrInst(NCE, Constant::getNullValue(Type::IntTy),
175 NewAdd, GEPI->getName(), GEPI);
176 GEPI->replaceAllUsesWith(NGEPI);
177 GEPI->eraseFromParent();
184 // Finally, if there are any other users of the PHI node, we must
185 // insert a new GEP instruction that uses the pre-incremented version
186 // of the induction amount.
187 if (!PN->use_empty()) {
188 BasicBlock::iterator InsertPos = PN; ++InsertPos;
189 while (isa<PHINode>(InsertPos)) ++InsertPos;
190 std::string Name = PN->getName(); PN->setName("");
192 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
193 std::vector<Value*>(1, NewPhi), Name,
195 PN->replaceAllUsesWith(PreInc);
198 // Delete the old PHI for sure, and the GEP if its otherwise unused.
199 DeadInsts.insert(PN);
206 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
207 /// loop to be a canonical != comparison against the incremented loop induction
208 /// variable. This pass is able to rewrite the exit tests of any loop where the
209 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
210 /// is actually a much broader range than just linear tests.
211 void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
213 // Find the exit block for the loop. We can currently only handle loops with
215 std::vector<BasicBlock*> ExitBlocks;
216 L->getExitBlocks(ExitBlocks);
217 if (ExitBlocks.size() != 1) return;
218 BasicBlock *ExitBlock = ExitBlocks[0];
220 // Make sure there is only one predecessor block in the loop.
221 BasicBlock *ExitingBlock = 0;
222 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
224 if (L->contains(*PI)) {
225 if (ExitingBlock == 0)
228 return; // Multiple exits from loop to this block.
230 assert(ExitingBlock && "Loop info is broken");
232 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
233 return; // Can't rewrite non-branch yet
234 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
235 assert(BI->isConditional() && "Must be conditional to be part of loop!");
237 std::set<Instruction*> InstructionsToDelete;
238 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
239 InstructionsToDelete.insert(Cond);
241 // If the exiting block is not the same as the backedge block, we must compare
242 // against the preincremented value, otherwise we prefer to compare against
243 // the post-incremented value.
244 BasicBlock *Header = L->getHeader();
245 pred_iterator HPI = pred_begin(Header);
246 assert(HPI != pred_end(Header) && "Loop with zero preds???");
247 if (!L->contains(*HPI)) ++HPI;
248 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
249 "No backedge in loop?");
251 SCEVHandle TripCount = IterationCount;
253 if (*HPI == ExitingBlock) {
254 // The IterationCount expression contains the number of times that the
255 // backedge actually branches to the loop header. This is one less than the
256 // number of times the loop executes, so add one to it.
257 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
258 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
259 IndVar = L->getCanonicalInductionVariableIncrement();
261 // We have to use the preincremented value...
262 IndVar = L->getCanonicalInductionVariable();
265 // Expand the code for the iteration count into the preheader of the loop.
266 BasicBlock *Preheader = L->getLoopPreheader();
267 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
270 // Insert a new setne or seteq instruction before the branch.
271 Instruction::BinaryOps Opcode;
272 if (L->contains(BI->getSuccessor(0)))
273 Opcode = Instruction::SetNE;
275 Opcode = Instruction::SetEQ;
277 Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
278 BI->setCondition(Cond);
282 DeleteTriviallyDeadInstructions(InstructionsToDelete);
286 /// RewriteLoopExitValues - Check to see if this loop has a computable
287 /// loop-invariant execution count. If so, this means that we can compute the
288 /// final value of any expressions that are recurrent in the loop, and
289 /// substitute the exit values from the loop into any instructions outside of
290 /// the loop that use the final values of the current expressions.
291 void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
292 BasicBlock *Preheader = L->getLoopPreheader();
294 // Scan all of the instructions in the loop, looking at those that have
295 // extra-loop users and which are recurrences.
296 SCEVExpander Rewriter(*SE, *LI);
298 // We insert the code into the preheader of the loop if the loop contains
299 // multiple exit blocks, or in the exit block if there is exactly one.
300 BasicBlock *BlockToInsertInto;
301 std::vector<BasicBlock*> ExitBlocks;
302 L->getExitBlocks(ExitBlocks);
303 if (ExitBlocks.size() == 1)
304 BlockToInsertInto = ExitBlocks[0];
306 BlockToInsertInto = Preheader;
307 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
308 while (isa<PHINode>(InsertPt)) ++InsertPt;
310 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
312 std::set<Instruction*> InstructionsToDelete;
314 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
315 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
316 BasicBlock *BB = L->getBlocks()[i];
317 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
318 if (I->getType()->isInteger()) { // Is an integer instruction
319 SCEVHandle SH = SE->getSCEV(I);
320 if (SH->hasComputableLoopEvolution(L) || // Varies predictably
321 HasConstantItCount) {
322 // Find out if this predictably varying value is actually used
323 // outside of the loop. "extra" as opposed to "intra".
324 std::vector<Instruction*> ExtraLoopUsers;
325 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
327 Instruction *User = cast<Instruction>(*UI);
328 if (!L->contains(User->getParent()))
329 ExtraLoopUsers.push_back(User);
332 if (!ExtraLoopUsers.empty()) {
333 // Okay, this instruction has a user outside of the current loop
334 // and varies predictably in this loop. Evaluate the value it
335 // contains when the loop exits, and insert code for it.
336 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
337 if (!isa<SCEVCouldNotCompute>(ExitValue)) {
340 // Remember the next instruction. The rewriter can move code
341 // around in some cases.
342 BasicBlock::iterator NextI = I; ++NextI;
344 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
347 // Rewrite any users of the computed value outside of the loop
348 // with the newly computed value.
349 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
350 PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]);
351 if (PN && PN->getParent() == BlockToInsertInto) {
352 // We're dealing with an LCSSA Phi. Handle it specially.
353 Instruction* LCSSAInsertPt = BlockToInsertInto->begin();
355 Instruction* NewInstr = dyn_cast<Instruction>(NewVal);
356 if (Instruction* NewInstr = dyn_cast<Instruction>(NewVal))
357 for (unsigned j = 0; j < NewInstr->getNumOperands(); ++j){
359 dyn_cast<Instruction>(NewInstr->getOperand(j));
360 if (PredI && L->contains(PredI->getParent())) {
361 PHINode* NewLCSSA = new PHINode(PredI->getType(),
362 PredI->getName() + ".lcssa",
364 NewLCSSA->addIncoming(PredI,
365 BlockToInsertInto->getSinglePredecessor());
367 NewInstr->replaceUsesOfWith(PredI, NewLCSSA);
371 PN->replaceAllUsesWith(NewVal);
372 PN->eraseFromParent();
374 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
378 // If this instruction is dead now, schedule it to be removed.
380 InstructionsToDelete.insert(I);
382 continue; // Skip the ++I
388 // Next instruction. Continue instruction skips this.
393 DeleteTriviallyDeadInstructions(InstructionsToDelete);
397 void IndVarSimplify::runOnLoop(Loop *L) {
398 // First step. Check to see if there are any trivial GEP pointer recurrences.
399 // If there are, change them into integer recurrences, permitting analysis by
400 // the SCEV routines.
402 BasicBlock *Header = L->getHeader();
403 BasicBlock *Preheader = L->getLoopPreheader();
405 std::set<Instruction*> DeadInsts;
406 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
407 PHINode *PN = cast<PHINode>(I);
408 if (isa<PointerType>(PN->getType()))
409 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
412 if (!DeadInsts.empty())
413 DeleteTriviallyDeadInstructions(DeadInsts);
416 // Next, transform all loops nesting inside of this loop.
417 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
420 // Check to see if this loop has a computable loop-invariant execution count.
421 // If so, this means that we can compute the final value of any expressions
422 // that are recurrent in the loop, and substitute the exit values from the
423 // loop into any instructions outside of the loop that use the final values of
424 // the current expressions.
426 SCEVHandle IterationCount = SE->getIterationCount(L);
427 if (!isa<SCEVCouldNotCompute>(IterationCount))
428 RewriteLoopExitValues(L);
430 // Next, analyze all of the induction variables in the loop, canonicalizing
431 // auxillary induction variables.
432 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
434 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
435 PHINode *PN = cast<PHINode>(I);
436 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
437 SCEVHandle SCEV = SE->getSCEV(PN);
438 if (SCEV->hasComputableLoopEvolution(L))
439 // FIXME: It is an extremely bad idea to indvar substitute anything more
440 // complex than affine induction variables. Doing so will put expensive
441 // polynomial evaluations inside of the loop, and the str reduction pass
442 // currently can only reduce affine polynomials. For now just disable
443 // indvar subst on anything more complex than an affine addrec.
444 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
446 IndVars.push_back(std::make_pair(PN, SCEV));
450 // If there are no induction variables in the loop, there is nothing more to
452 if (IndVars.empty()) {
453 // Actually, if we know how many times the loop iterates, lets insert a
454 // canonical induction variable to help subsequent passes.
455 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
456 SCEVExpander Rewriter(*SE, *LI);
457 Rewriter.getOrInsertCanonicalInductionVariable(L,
458 IterationCount->getType());
459 LinearFunctionTestReplace(L, IterationCount, Rewriter);
464 // Compute the type of the largest recurrence expression.
466 const Type *LargestType = IndVars[0].first->getType();
467 bool DifferingSizes = false;
468 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
469 const Type *Ty = IndVars[i].first->getType();
470 DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
471 if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
475 // Create a rewriter object which we'll use to transform the code with.
476 SCEVExpander Rewriter(*SE, *LI);
478 // Now that we know the largest of of the induction variables in this loop,
479 // insert a canonical induction variable of the largest size.
480 LargestType = LargestType->getUnsignedVersion();
481 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
485 if (!isa<SCEVCouldNotCompute>(IterationCount))
486 LinearFunctionTestReplace(L, IterationCount, Rewriter);
488 // Now that we have a canonical induction variable, we can rewrite any
489 // recurrences in terms of the induction variable. Start with the auxillary
490 // induction variables, and recursively rewrite any of their uses.
491 BasicBlock::iterator InsertPt = Header->begin();
492 while (isa<PHINode>(InsertPt)) ++InsertPt;
494 // If there were induction variables of other sizes, cast the primary
495 // induction variable to the right size for them, avoiding the need for the
496 // code evaluation methods to insert induction variables of different sizes.
497 if (DifferingSizes) {
498 bool InsertedSizes[17] = { false };
499 InsertedSizes[LargestType->getPrimitiveSize()] = true;
500 for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
501 if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
502 PHINode *PN = IndVars[i].first;
503 InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
504 Instruction *New = new CastInst(IndVar,
505 PN->getType()->getUnsignedVersion(),
507 Rewriter.addInsertedValue(New, SE->getSCEV(New));
511 // If there were induction variables of other sizes, cast the primary
512 // induction variable to the right size for them, avoiding the need for the
513 // code evaluation methods to insert induction variables of different sizes.
514 std::map<unsigned, Value*> InsertedSizes;
515 while (!IndVars.empty()) {
516 PHINode *PN = IndVars.back().first;
517 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
519 std::string Name = PN->getName();
521 NewVal->setName(Name);
523 // Replace the old PHI Node with the inserted computation.
524 PN->replaceAllUsesWith(NewVal);
525 DeadInsts.insert(PN);
532 // Now replace all derived expressions in the loop body with simpler
534 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
535 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
536 BasicBlock *BB = L->getBlocks()[i];
537 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
538 if (I->getType()->isInteger() && // Is an integer instruction
540 !Rewriter.isInsertedInstruction(I)) {
541 SCEVHandle SH = SE->getSCEV(I);
542 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
544 if (isa<Instruction>(V)) {
545 std::string Name = I->getName();
549 I->replaceAllUsesWith(V);
558 DeleteTriviallyDeadInstructions(DeadInsts);