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 makes 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 #define DEBUG_TYPE "indvars"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/BasicBlock.h"
43 #include "llvm/Constants.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/Type.h"
46 #include "llvm/Analysis/ScalarEvolutionExpander.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Support/CFG.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/Statistic.h"
59 STATISTIC(NumRemoved , "Number of aux indvars removed");
60 STATISTIC(NumPointer , "Number of pointer indvars promoted");
61 STATISTIC(NumInserted, "Number of canonical indvars added");
62 STATISTIC(NumReplaced, "Number of exit values replaced");
63 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
66 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
72 static char ID; // Pass identification, replacement for typeid
73 IndVarSimplify() : LoopPass((intptr_t)&ID) {}
75 bool runOnLoop(Loop *L, LPPassManager &LPM);
76 bool doInitialization(Loop *L, LPPassManager &LPM);
77 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addRequiredID(LCSSAID);
79 AU.addRequiredID(LoopSimplifyID);
80 AU.addRequired<ScalarEvolution>();
81 AU.addRequired<LoopInfo>();
82 AU.addPreservedID(LoopSimplifyID);
83 AU.addPreservedID(LCSSAID);
89 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
90 std::set<Instruction*> &DeadInsts);
91 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
93 void RewriteLoopExitValues(Loop *L);
95 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
98 char IndVarSimplify::ID = 0;
99 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
102 LoopPass *llvm::createIndVarSimplifyPass() {
103 return new IndVarSimplify();
106 /// 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.
109 void IndVarSimplify::
110 DeleteTriviallyDeadInstructions(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)))
118 SE->deleteValueFromRecords(I);
119 DOUT << "INDVARS: Deleting: " << *I;
120 I->eraseFromParent();
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.
130 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
131 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 =
137 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
138 if (GEPI->getOperand(0) == PN) {
139 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
140 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
142 // 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);
147 // Insert a new integer PHI node into the top of the block.
148 PHINode *NewPhi = new PHINode(AddedVal->getType(),
149 PN->getName()+".rec", PN);
150 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
152 // Create the new add instruction.
153 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
154 GEPI->getName()+".rec", GEPI);
155 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
157 // Update the existing GEP to use the recurrence.
158 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
160 // Update the GEP to use the new recurrence we just inserted.
161 GEPI->setOperand(1, NewAdd);
163 // 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.
171 gep_type_iterator GTI = gep_type_begin(CE);
172 for (unsigned i = 1, e = CE->getNumOperands()-1;
175 if (isa<SequentialType>(*GTI)) {
176 // Pull the last index out of the constant expr GEP.
177 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
178 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
181 GetElementPtrInst *NGEPI = new GetElementPtrInst(
182 NCE, Constant::getNullValue(Type::Int32Ty), NewAdd,
183 GEPI->getName(), GEPI);
184 SE->deleteValueFromRecords(GEPI);
185 GEPI->replaceAllUsesWith(NGEPI);
186 GEPI->eraseFromParent();
193 // Finally, if there are any other users of the PHI node, we must
194 // insert a new GEP instruction that uses the pre-incremented version
195 // of the induction amount.
196 if (!PN->use_empty()) {
197 BasicBlock::iterator InsertPos = PN; ++InsertPos;
198 while (isa<PHINode>(InsertPos)) ++InsertPos;
200 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
201 NewPhi, "", InsertPos);
202 PreInc->takeName(PN);
203 PN->replaceAllUsesWith(PreInc);
206 // Delete the old PHI for sure, and the GEP if its otherwise unused.
207 DeadInsts.insert(PN);
214 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
215 /// loop to be a canonical != comparison against the incremented loop induction
216 /// variable. This pass is able to rewrite the exit tests of any loop where the
217 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
218 /// is actually a much broader range than just linear tests.
220 /// This method returns a "potentially dead" instruction whose computation chain
221 /// should be deleted when convenient.
222 Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
223 SCEV *IterationCount,
225 // Find the exit block for the loop. We can currently only handle loops with
227 std::vector<BasicBlock*> ExitBlocks;
228 L->getExitBlocks(ExitBlocks);
229 if (ExitBlocks.size() != 1) return 0;
230 BasicBlock *ExitBlock = ExitBlocks[0];
232 // Make sure there is only one predecessor block in the loop.
233 BasicBlock *ExitingBlock = 0;
234 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
236 if (L->contains(*PI)) {
237 if (ExitingBlock == 0)
240 return 0; // Multiple exits from loop to this block.
242 assert(ExitingBlock && "Loop info is broken");
244 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
245 return 0; // Can't rewrite non-branch yet
246 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
247 assert(BI->isConditional() && "Must be conditional to be part of loop!");
249 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
251 // If the exiting block is not the same as the backedge block, we must compare
252 // against the preincremented value, otherwise we prefer to compare against
253 // the post-incremented value.
254 BasicBlock *Header = L->getHeader();
255 pred_iterator HPI = pred_begin(Header);
256 assert(HPI != pred_end(Header) && "Loop with zero preds???");
257 if (!L->contains(*HPI)) ++HPI;
258 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
259 "No backedge in loop?");
261 SCEVHandle TripCount = IterationCount;
263 if (*HPI == ExitingBlock) {
264 // The IterationCount expression contains the number of times that the
265 // backedge actually branches to the loop header. This is one less than the
266 // number of times the loop executes, so add one to it.
267 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
268 TripCount = SCEVAddExpr::get(IterationCount, SCEVConstant::get(OneC));
269 IndVar = L->getCanonicalInductionVariableIncrement();
271 // We have to use the preincremented value...
272 IndVar = L->getCanonicalInductionVariable();
275 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
276 << " IndVar = " << *IndVar << "\n";
278 // Expand the code for the iteration count into the preheader of the loop.
279 BasicBlock *Preheader = L->getLoopPreheader();
280 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
282 // Insert a new icmp_ne or icmp_eq instruction before the branch.
283 ICmpInst::Predicate Opcode;
284 if (L->contains(BI->getSuccessor(0)))
285 Opcode = ICmpInst::ICMP_NE;
287 Opcode = ICmpInst::ICMP_EQ;
289 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
290 BI->setCondition(Cond);
293 return PotentiallyDeadInst;
297 /// RewriteLoopExitValues - Check to see if this loop has a computable
298 /// loop-invariant execution count. If so, this means that we can compute the
299 /// final value of any expressions that are recurrent in the loop, and
300 /// substitute the exit values from the loop into any instructions outside of
301 /// the loop that use the final values of the current expressions.
302 void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
303 BasicBlock *Preheader = L->getLoopPreheader();
305 // Scan all of the instructions in the loop, looking at those that have
306 // extra-loop users and which are recurrences.
307 SCEVExpander Rewriter(*SE, *LI);
309 // We insert the code into the preheader of the loop if the loop contains
310 // multiple exit blocks, or in the exit block if there is exactly one.
311 BasicBlock *BlockToInsertInto;
312 std::vector<BasicBlock*> ExitBlocks;
313 L->getUniqueExitBlocks(ExitBlocks);
314 if (ExitBlocks.size() == 1)
315 BlockToInsertInto = ExitBlocks[0];
317 BlockToInsertInto = Preheader;
318 BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
319 while (isa<PHINode>(InsertPt)) ++InsertPt;
321 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
323 std::set<Instruction*> InstructionsToDelete;
324 std::map<Instruction*, Value*> ExitValues;
326 // Find all values that are computed inside the loop, but used outside of it.
327 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
328 // the exit blocks of the loop to find them.
329 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
330 BasicBlock *ExitBB = ExitBlocks[i];
332 // If there are no PHI nodes in this exit block, then no values defined
333 // inside the loop are used on this path, skip it.
334 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
337 unsigned NumPreds = PN->getNumIncomingValues();
339 // Iterate over all of the PHI nodes.
340 BasicBlock::iterator BBI = ExitBB->begin();
341 while ((PN = dyn_cast<PHINode>(BBI++))) {
343 // Iterate over all of the values in all the PHI nodes.
344 for (unsigned i = 0; i != NumPreds; ++i) {
345 // If the value being merged in is not integer or is not defined
346 // in the loop, skip it.
347 Value *InVal = PN->getIncomingValue(i);
348 if (!isa<Instruction>(InVal) ||
349 // SCEV only supports integer expressions for now.
350 !isa<IntegerType>(InVal->getType()))
353 // If this pred is for a subloop, not L itself, skip it.
354 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
355 continue; // The Block is in a subloop, skip it.
357 // Check that InVal is defined in the loop.
358 Instruction *Inst = cast<Instruction>(InVal);
359 if (!L->contains(Inst->getParent()))
362 // We require that this value either have a computable evolution or that
363 // the loop have a constant iteration count. In the case where the loop
364 // has a constant iteration count, we can sometimes force evaluation of
365 // the exit value through brute force.
366 SCEVHandle SH = SE->getSCEV(Inst);
367 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
368 continue; // Cannot get exit evolution for the loop value.
370 // Okay, this instruction has a user outside of the current loop
371 // and varies predictably *inside* the loop. Evaluate the value it
372 // contains when the loop exits, if possible.
373 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
374 if (isa<SCEVCouldNotCompute>(ExitValue) ||
375 !ExitValue->isLoopInvariant(L))
381 // See if we already computed the exit value for the instruction, if so,
383 Value *&ExitVal = ExitValues[Inst];
385 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
387 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
388 << " LoopVal = " << *Inst << "\n";
390 PN->setIncomingValue(i, ExitVal);
392 // If this instruction is dead now, schedule it to be removed.
393 if (Inst->use_empty())
394 InstructionsToDelete.insert(Inst);
396 // See if this is a single-entry LCSSA PHI node. If so, we can (and
398 // the PHI entirely. This is safe, because the NewVal won't be variant
399 // in the loop, so we don't need an LCSSA phi node anymore.
401 SE->deleteValueFromRecords(PN);
402 PN->replaceAllUsesWith(ExitVal);
403 PN->eraseFromParent();
410 DeleteTriviallyDeadInstructions(InstructionsToDelete);
413 bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
416 // First step. Check to see if there are any trivial GEP pointer recurrences.
417 // If there are, change them into integer recurrences, permitting analysis by
418 // the SCEV routines.
420 BasicBlock *Header = L->getHeader();
421 BasicBlock *Preheader = L->getLoopPreheader();
422 SE = &LPM.getAnalysis<ScalarEvolution>();
424 std::set<Instruction*> DeadInsts;
425 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
426 PHINode *PN = cast<PHINode>(I);
427 if (isa<PointerType>(PN->getType()))
428 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
431 if (!DeadInsts.empty())
432 DeleteTriviallyDeadInstructions(DeadInsts);
437 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
440 LI = &getAnalysis<LoopInfo>();
441 SE = &getAnalysis<ScalarEvolution>();
444 BasicBlock *Header = L->getHeader();
445 std::set<Instruction*> DeadInsts;
447 // Verify the input to the pass in already in LCSSA form.
448 assert(L->isLCSSAForm());
450 // Check to see if this loop has a computable loop-invariant execution count.
451 // If so, this means that we can compute the final value of any expressions
452 // that are recurrent in the loop, and substitute the exit values from the
453 // loop into any instructions outside of the loop that use the final values of
454 // the current expressions.
456 SCEVHandle IterationCount = SE->getIterationCount(L);
457 if (!isa<SCEVCouldNotCompute>(IterationCount))
458 RewriteLoopExitValues(L);
460 // Next, analyze all of the induction variables in the loop, canonicalizing
461 // auxillary induction variables.
462 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
464 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
465 PHINode *PN = cast<PHINode>(I);
466 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
467 SCEVHandle SCEV = SE->getSCEV(PN);
468 if (SCEV->hasComputableLoopEvolution(L))
469 // FIXME: It is an extremely bad idea to indvar substitute anything more
470 // complex than affine induction variables. Doing so will put expensive
471 // polynomial evaluations inside of the loop, and the str reduction pass
472 // currently can only reduce affine polynomials. For now just disable
473 // indvar subst on anything more complex than an affine addrec.
474 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
476 IndVars.push_back(std::make_pair(PN, SCEV));
480 // If there are no induction variables in the loop, there is nothing more to
482 if (IndVars.empty()) {
483 // Actually, if we know how many times the loop iterates, lets insert a
484 // canonical induction variable to help subsequent passes.
485 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
486 SCEVExpander Rewriter(*SE, *LI);
487 Rewriter.getOrInsertCanonicalInductionVariable(L,
488 IterationCount->getType());
489 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
491 std::set<Instruction*> InstructionsToDelete;
492 InstructionsToDelete.insert(I);
493 DeleteTriviallyDeadInstructions(InstructionsToDelete);
499 // Compute the type of the largest recurrence expression.
501 const Type *LargestType = IndVars[0].first->getType();
502 bool DifferingSizes = false;
503 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
504 const Type *Ty = IndVars[i].first->getType();
506 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
507 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
511 // Create a rewriter object which we'll use to transform the code with.
512 SCEVExpander Rewriter(*SE, *LI);
514 // Now that we know the largest of of the induction variables in this loop,
515 // insert a canonical induction variable of the largest size.
516 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
519 DOUT << "INDVARS: New CanIV: " << *IndVar;
521 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
522 if (IterationCount->getType()->getPrimitiveSizeInBits() <
523 LargestType->getPrimitiveSizeInBits())
524 IterationCount = SCEVZeroExtendExpr::get(IterationCount, LargestType);
525 else if (IterationCount->getType() != LargestType)
526 IterationCount = SCEVTruncateExpr::get(IterationCount, LargestType);
527 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
528 DeadInsts.insert(DI);
531 // Now that we have a canonical induction variable, we can rewrite any
532 // recurrences in terms of the induction variable. Start with the auxillary
533 // induction variables, and recursively rewrite any of their uses.
534 BasicBlock::iterator InsertPt = Header->begin();
535 while (isa<PHINode>(InsertPt)) ++InsertPt;
537 // If there were induction variables of other sizes, cast the primary
538 // induction variable to the right size for them, avoiding the need for the
539 // code evaluation methods to insert induction variables of different sizes.
540 if (DifferingSizes) {
541 SmallVector<unsigned,4> InsertedSizes;
542 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
543 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
544 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
545 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
546 == InsertedSizes.end()) {
547 PHINode *PN = IndVars[i].first;
548 InsertedSizes.push_back(ithSize);
549 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
551 Rewriter.addInsertedValue(New, SE->getSCEV(New));
552 DOUT << "INDVARS: Made trunc IV for " << *PN
553 << " NewVal = " << *New << "\n";
558 // Rewrite all induction variables in terms of the canonical induction
560 std::map<unsigned, Value*> InsertedSizes;
561 while (!IndVars.empty()) {
562 PHINode *PN = IndVars.back().first;
563 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
564 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
565 << " into = " << *NewVal << "\n";
566 NewVal->takeName(PN);
568 // Replace the old PHI Node with the inserted computation.
569 PN->replaceAllUsesWith(NewVal);
570 DeadInsts.insert(PN);
577 // Now replace all derived expressions in the loop body with simpler
579 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
580 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop...
581 BasicBlock *BB = L->getBlocks()[i];
582 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
583 if (I->getType()->isInteger() && // Is an integer instruction
585 !Rewriter.isInsertedInstruction(I)) {
586 SCEVHandle SH = SE->getSCEV(I);
587 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
589 if (isa<Instruction>(V))
591 I->replaceAllUsesWith(V);
600 DeleteTriviallyDeadInstructions(DeadInsts);
602 assert(L->isLCSSAForm());