1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
60 STATISTIC(NumRemoved , "Number of aux indvars removed");
61 STATISTIC(NumPointer , "Number of pointer indvars promoted");
62 STATISTIC(NumInserted, "Number of canonical indvars added");
63 STATISTIC(NumReplaced, "Number of exit values replaced");
64 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
67 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
73 static char ID; // Pass identification, replacement for typeid
74 IndVarSimplify() : LoopPass(&ID) {}
76 bool runOnLoop(Loop *L, LPPassManager &LPM);
77 bool doInitialization(Loop *L, LPPassManager &LPM);
78 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
79 AU.addRequired<ScalarEvolution>();
80 AU.addRequiredID(LCSSAID);
81 AU.addRequiredID(LoopSimplifyID);
82 AU.addRequired<LoopInfo>();
83 AU.addPreservedID(LoopSimplifyID);
84 AU.addPreservedID(LCSSAID);
90 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
91 SmallPtrSet<Instruction*, 16> &DeadInsts);
92 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
94 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
96 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
98 void OptimizeCanonicalIVType(Loop *L);
99 void HandleFloatingPointIV(Loop *L, PHINode *PH,
100 SmallPtrSet<Instruction*, 16> &DeadInsts);
104 char IndVarSimplify::ID = 0;
105 static RegisterPass<IndVarSimplify>
106 X("indvars", "Canonicalize Induction Variables");
108 Pass *llvm::createIndVarSimplifyPass() {
109 return new IndVarSimplify();
112 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
113 /// specified set are trivially dead, delete them and see if this makes any of
114 /// their operands subsequently dead.
115 void IndVarSimplify::
116 DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
117 while (!Insts.empty()) {
118 Instruction *I = *Insts.begin();
120 if (isInstructionTriviallyDead(I)) {
121 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
122 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
124 SE->deleteValueFromRecords(I);
125 DOUT << "INDVARS: Deleting: " << *I;
126 I->eraseFromParent();
133 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
134 /// recurrence. If so, change it into an integer recurrence, permitting
135 /// analysis by the SCEV routines.
136 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
137 BasicBlock *Preheader,
138 SmallPtrSet<Instruction*, 16> &DeadInsts) {
139 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
140 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
141 unsigned BackedgeIdx = PreheaderIdx^1;
142 if (GetElementPtrInst *GEPI =
143 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
144 if (GEPI->getOperand(0) == PN) {
145 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
146 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
148 // Okay, we found a pointer recurrence. Transform this pointer
149 // recurrence into an integer recurrence. Compute the value that gets
150 // added to the pointer at every iteration.
151 Value *AddedVal = GEPI->getOperand(1);
153 // Insert a new integer PHI node into the top of the block.
154 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
155 PN->getName()+".rec", PN);
156 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
158 // Create the new add instruction.
159 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
160 GEPI->getName()+".rec", GEPI);
161 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
163 // Update the existing GEP to use the recurrence.
164 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
166 // Update the GEP to use the new recurrence we just inserted.
167 GEPI->setOperand(1, NewAdd);
169 // If the incoming value is a constant expr GEP, try peeling out the array
170 // 0 index if possible to make things simpler.
171 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
172 if (CE->getOpcode() == Instruction::GetElementPtr) {
173 unsigned NumOps = CE->getNumOperands();
174 assert(NumOps > 1 && "CE folding didn't work!");
175 if (CE->getOperand(NumOps-1)->isNullValue()) {
176 // Check to make sure the last index really is an array index.
177 gep_type_iterator GTI = gep_type_begin(CE);
178 for (unsigned i = 1, e = CE->getNumOperands()-1;
181 if (isa<SequentialType>(*GTI)) {
182 // Pull the last index out of the constant expr GEP.
183 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
184 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
188 Idx[0] = Constant::getNullValue(Type::Int32Ty);
190 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
192 GEPI->getName(), GEPI);
193 SE->deleteValueFromRecords(GEPI);
194 GEPI->replaceAllUsesWith(NGEPI);
195 GEPI->eraseFromParent();
202 // Finally, if there are any other users of the PHI node, we must
203 // insert a new GEP instruction that uses the pre-incremented version
204 // of the induction amount.
205 if (!PN->use_empty()) {
206 BasicBlock::iterator InsertPos = PN; ++InsertPos;
207 while (isa<PHINode>(InsertPos)) ++InsertPos;
209 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
210 NewPhi, "", InsertPos);
211 PreInc->takeName(PN);
212 PN->replaceAllUsesWith(PreInc);
215 // Delete the old PHI for sure, and the GEP if its otherwise unused.
216 DeadInsts.insert(PN);
223 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
224 /// loop to be a canonical != comparison against the incremented loop induction
225 /// variable. This pass is able to rewrite the exit tests of any loop where the
226 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
227 /// is actually a much broader range than just linear tests.
229 /// This method returns a "potentially dead" instruction whose computation chain
230 /// should be deleted when convenient.
231 Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
232 SCEV *IterationCount,
234 // Find the exit block for the loop. We can currently only handle loops with
236 SmallVector<BasicBlock*, 8> ExitBlocks;
237 L->getExitBlocks(ExitBlocks);
238 if (ExitBlocks.size() != 1) return 0;
239 BasicBlock *ExitBlock = ExitBlocks[0];
241 // Make sure there is only one predecessor block in the loop.
242 BasicBlock *ExitingBlock = 0;
243 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
245 if (L->contains(*PI)) {
246 if (ExitingBlock == 0)
249 return 0; // Multiple exits from loop to this block.
251 assert(ExitingBlock && "Loop info is broken");
253 if (!isa<BranchInst>(ExitingBlock->getTerminator()))
254 return 0; // Can't rewrite non-branch yet
255 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
256 assert(BI->isConditional() && "Must be conditional to be part of loop!");
258 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition());
260 // If the exiting block is not the same as the backedge block, we must compare
261 // against the preincremented value, otherwise we prefer to compare against
262 // the post-incremented value.
263 BasicBlock *Header = L->getHeader();
264 pred_iterator HPI = pred_begin(Header);
265 assert(HPI != pred_end(Header) && "Loop with zero preds???");
266 if (!L->contains(*HPI)) ++HPI;
267 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
268 "No backedge in loop?");
270 SCEVHandle TripCount = IterationCount;
272 if (*HPI == ExitingBlock) {
273 // The IterationCount expression contains the number of times that the
274 // backedge actually branches to the loop header. This is one less than the
275 // number of times the loop executes, so add one to it.
276 ConstantInt *OneC = ConstantInt::get(IterationCount->getType(), 1);
277 TripCount = SE->getAddExpr(IterationCount, SE->getConstant(OneC));
278 IndVar = L->getCanonicalInductionVariableIncrement();
280 // We have to use the preincremented value...
281 IndVar = L->getCanonicalInductionVariable();
284 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount
285 << " IndVar = " << *IndVar << "\n";
287 // Expand the code for the iteration count into the preheader of the loop.
288 BasicBlock *Preheader = L->getLoopPreheader();
289 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator());
291 // Insert a new icmp_ne or icmp_eq instruction before the branch.
292 ICmpInst::Predicate Opcode;
293 if (L->contains(BI->getSuccessor(0)))
294 Opcode = ICmpInst::ICMP_NE;
296 Opcode = ICmpInst::ICMP_EQ;
298 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
299 BI->setCondition(Cond);
302 return PotentiallyDeadInst;
306 /// RewriteLoopExitValues - Check to see if this loop has a computable
307 /// loop-invariant execution count. If so, this means that we can compute the
308 /// final value of any expressions that are recurrent in the loop, and
309 /// substitute the exit values from the loop into any instructions outside of
310 /// the loop that use the final values of the current expressions.
311 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
312 BasicBlock *Preheader = L->getLoopPreheader();
314 // Scan all of the instructions in the loop, looking at those that have
315 // extra-loop users and which are recurrences.
316 SCEVExpander Rewriter(*SE, *LI);
318 // We insert the code into the preheader of the loop if the loop contains
319 // multiple exit blocks, or in the exit block if there is exactly one.
320 BasicBlock *BlockToInsertInto;
321 SmallVector<BasicBlock*, 8> ExitBlocks;
322 L->getUniqueExitBlocks(ExitBlocks);
323 if (ExitBlocks.size() == 1)
324 BlockToInsertInto = ExitBlocks[0];
326 BlockToInsertInto = Preheader;
327 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
329 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
331 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
332 std::map<Instruction*, Value*> ExitValues;
334 // Find all values that are computed inside the loop, but used outside of it.
335 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
336 // the exit blocks of the loop to find them.
337 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
338 BasicBlock *ExitBB = ExitBlocks[i];
340 // If there are no PHI nodes in this exit block, then no values defined
341 // inside the loop are used on this path, skip it.
342 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
345 unsigned NumPreds = PN->getNumIncomingValues();
347 // Iterate over all of the PHI nodes.
348 BasicBlock::iterator BBI = ExitBB->begin();
349 while ((PN = dyn_cast<PHINode>(BBI++))) {
351 // Iterate over all of the values in all the PHI nodes.
352 for (unsigned i = 0; i != NumPreds; ++i) {
353 // If the value being merged in is not integer or is not defined
354 // in the loop, skip it.
355 Value *InVal = PN->getIncomingValue(i);
356 if (!isa<Instruction>(InVal) ||
357 // SCEV only supports integer expressions for now.
358 !isa<IntegerType>(InVal->getType()))
361 // If this pred is for a subloop, not L itself, skip it.
362 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
363 continue; // The Block is in a subloop, skip it.
365 // Check that InVal is defined in the loop.
366 Instruction *Inst = cast<Instruction>(InVal);
367 if (!L->contains(Inst->getParent()))
370 // We require that this value either have a computable evolution or that
371 // the loop have a constant iteration count. In the case where the loop
372 // has a constant iteration count, we can sometimes force evaluation of
373 // the exit value through brute force.
374 SCEVHandle SH = SE->getSCEV(Inst);
375 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
376 continue; // Cannot get exit evolution for the loop value.
378 // Okay, this instruction has a user outside of the current loop
379 // and varies predictably *inside* the loop. Evaluate the value it
380 // contains when the loop exits, if possible.
381 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
382 if (isa<SCEVCouldNotCompute>(ExitValue) ||
383 !ExitValue->isLoopInvariant(L))
389 // See if we already computed the exit value for the instruction, if so,
391 Value *&ExitVal = ExitValues[Inst];
393 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
395 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
396 << " LoopVal = " << *Inst << "\n";
398 PN->setIncomingValue(i, ExitVal);
400 // If this instruction is dead now, schedule it to be removed.
401 if (Inst->use_empty())
402 InstructionsToDelete.insert(Inst);
404 // See if this is a single-entry LCSSA PHI node. If so, we can (and
406 // the PHI entirely. This is safe, because the NewVal won't be variant
407 // in the loop, so we don't need an LCSSA phi node anymore.
409 SE->deleteValueFromRecords(PN);
410 PN->replaceAllUsesWith(ExitVal);
411 PN->eraseFromParent();
418 DeleteTriviallyDeadInstructions(InstructionsToDelete);
421 bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) {
424 // First step. Check to see if there are any trivial GEP pointer recurrences.
425 // If there are, change them into integer recurrences, permitting analysis by
426 // the SCEV routines.
428 BasicBlock *Header = L->getHeader();
429 BasicBlock *Preheader = L->getLoopPreheader();
430 SE = &LPM.getAnalysis<ScalarEvolution>();
432 SmallPtrSet<Instruction*, 16> DeadInsts;
433 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
434 PHINode *PN = cast<PHINode>(I);
435 if (isa<PointerType>(PN->getType()))
436 EliminatePointerRecurrence(PN, Preheader, DeadInsts);
438 HandleFloatingPointIV(L, PN, DeadInsts);
441 if (!DeadInsts.empty())
442 DeleteTriviallyDeadInstructions(DeadInsts);
447 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
449 LI = &getAnalysis<LoopInfo>();
450 SE = &getAnalysis<ScalarEvolution>();
453 BasicBlock *Header = L->getHeader();
454 SmallPtrSet<Instruction*, 16> DeadInsts;
456 // Verify the input to the pass in already in LCSSA form.
457 assert(L->isLCSSAForm());
459 // Check to see if this loop has a computable loop-invariant execution count.
460 // If so, this means that we can compute the final value of any expressions
461 // that are recurrent in the loop, and substitute the exit values from the
462 // loop into any instructions outside of the loop that use the final values of
463 // the current expressions.
465 SCEVHandle IterationCount = SE->getIterationCount(L);
466 if (!isa<SCEVCouldNotCompute>(IterationCount))
467 RewriteLoopExitValues(L, IterationCount);
469 // Next, analyze all of the induction variables in the loop, canonicalizing
470 // auxillary induction variables.
471 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
473 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
474 PHINode *PN = cast<PHINode>(I);
475 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
476 SCEVHandle SCEV = SE->getSCEV(PN);
477 if (SCEV->hasComputableLoopEvolution(L))
478 // FIXME: It is an extremely bad idea to indvar substitute anything more
479 // complex than affine induction variables. Doing so will put expensive
480 // polynomial evaluations inside of the loop, and the str reduction pass
481 // currently can only reduce affine polynomials. For now just disable
482 // indvar subst on anything more complex than an affine addrec.
483 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
485 IndVars.push_back(std::make_pair(PN, SCEV));
489 // If there are no induction variables in the loop, there is nothing more to
491 if (IndVars.empty()) {
492 // Actually, if we know how many times the loop iterates, lets insert a
493 // canonical induction variable to help subsequent passes.
494 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
495 SCEVExpander Rewriter(*SE, *LI);
496 Rewriter.getOrInsertCanonicalInductionVariable(L,
497 IterationCount->getType());
498 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount,
500 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
501 InstructionsToDelete.insert(I);
502 DeleteTriviallyDeadInstructions(InstructionsToDelete);
508 // Compute the type of the largest recurrence expression.
510 const Type *LargestType = IndVars[0].first->getType();
511 bool DifferingSizes = false;
512 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
513 const Type *Ty = IndVars[i].first->getType();
515 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits();
516 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits())
520 // Create a rewriter object which we'll use to transform the code with.
521 SCEVExpander Rewriter(*SE, *LI);
523 // Now that we know the largest of of the induction variables in this loop,
524 // insert a canonical induction variable of the largest size.
525 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
528 DOUT << "INDVARS: New CanIV: " << *IndVar;
530 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
531 IterationCount = SE->getTruncateOrZeroExtend(IterationCount, LargestType);
532 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter))
533 DeadInsts.insert(DI);
536 // Now that we have a canonical induction variable, we can rewrite any
537 // recurrences in terms of the induction variable. Start with the auxillary
538 // induction variables, and recursively rewrite any of their uses.
539 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
541 // If there were induction variables of other sizes, cast the primary
542 // induction variable to the right size for them, avoiding the need for the
543 // code evaluation methods to insert induction variables of different sizes.
544 if (DifferingSizes) {
545 SmallVector<unsigned,4> InsertedSizes;
546 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits());
547 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
548 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits();
549 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize)
550 == InsertedSizes.end()) {
551 PHINode *PN = IndVars[i].first;
552 InsertedSizes.push_back(ithSize);
553 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar",
555 Rewriter.addInsertedValue(New, SE->getSCEV(New));
556 DOUT << "INDVARS: Made trunc IV for " << *PN
557 << " NewVal = " << *New << "\n";
562 // Rewrite all induction variables in terms of the canonical induction
564 while (!IndVars.empty()) {
565 PHINode *PN = IndVars.back().first;
566 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt);
567 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN
568 << " into = " << *NewVal << "\n";
569 NewVal->takeName(PN);
571 // Replace the old PHI Node with the inserted computation.
572 PN->replaceAllUsesWith(NewVal);
573 DeadInsts.insert(PN);
580 // Now replace all derived expressions in the loop body with simpler
582 for (LoopInfo::block_iterator I = L->block_begin(), E = L->block_end();
585 if (LI->getLoopFor(BB) == L) { // Not in a subloop...
586 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
587 if (I->getType()->isInteger() && // Is an integer instruction
589 !Rewriter.isInsertedInstruction(I)) {
590 SCEVHandle SH = SE->getSCEV(I);
591 Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
593 if (isa<Instruction>(V))
595 I->replaceAllUsesWith(V);
605 DeleteTriviallyDeadInstructions(DeadInsts);
606 OptimizeCanonicalIVType(L);
607 assert(L->isLCSSAForm());
611 /// OptimizeCanonicalIVType - If loop induction variable is always
612 /// sign or zero extended then extend the type of the induction
614 void IndVarSimplify::OptimizeCanonicalIVType(Loop *L) {
615 PHINode *PH = L->getCanonicalInductionVariable();
618 // Check loop iteration count.
619 SCEVHandle IC = SE->getIterationCount(L);
620 if (isa<SCEVCouldNotCompute>(IC)) return;
621 SCEVConstant *IterationCount = dyn_cast<SCEVConstant>(IC);
622 if (!IterationCount) return;
624 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
625 unsigned BackEdge = IncomingEdge^1;
627 // Check IV uses. If all IV uses are either SEXT or ZEXT (except
628 // IV increment instruction) then this IV is suitable for this
631 BinaryOperator *Incr = NULL;
632 const Type *NewType = NULL;
633 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
635 const Type *CandidateType = NULL;
636 if (ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
637 CandidateType = ZI->getDestTy();
638 else if (SExtInst *SI = dyn_cast<SExtInst>(UI)) {
639 CandidateType = SI->getDestTy();
642 else if ((Incr = dyn_cast<BinaryOperator>(UI))) {
643 // Validate IV increment instruction.
644 if (PH->getIncomingValue(BackEdge) == Incr)
647 if (!CandidateType) {
652 NewType = CandidateType;
653 else if (NewType != CandidateType) {
659 // IV uses are not suitable then avoid this transformation.
660 if (!NewType || !Incr)
663 // IV increment instruction has two uses, one is loop exit condition
664 // and second is the IV (phi node) itself.
665 ICmpInst *Exit = NULL;
666 for(Value::use_iterator II = Incr->use_begin(), IE = Incr->use_end();
668 if (PH == *II) continue;
669 Exit = dyn_cast<ICmpInst>(*II);
673 ConstantInt *EV = dyn_cast<ConstantInt>(Exit->getOperand(0));
675 EV = dyn_cast<ConstantInt>(Exit->getOperand(1));
678 // Check iteration count max value to avoid loops that wrap around IV.
679 APInt ICount = IterationCount->getValue()->getValue();
680 if (ICount.isNegative()) return;
681 uint32_t BW = PH->getType()->getPrimitiveSizeInBits();
682 APInt Max = (isSEXT ? APInt::getSignedMaxValue(BW) : APInt::getMaxValue(BW));
683 if (ICount.getZExtValue() > Max.getZExtValue()) return;
687 SCEVExpander Rewriter(*SE, *LI);
688 Value *NewIV = Rewriter.getOrInsertCanonicalInductionVariable(L,NewType);
689 PHINode *NewPH = cast<PHINode>(NewIV);
690 Instruction *NewIncr = cast<Instruction>(NewPH->getIncomingValue(BackEdge));
692 // Replace all SEXT or ZEXT uses.
693 SmallVector<Instruction *, 4> PHUses;
694 for(Value::use_iterator UI = PH->use_begin(), UE = PH->use_end();
696 Instruction *I = cast<Instruction>(UI);
699 while (!PHUses.empty()){
700 Instruction *Use = PHUses.back(); PHUses.pop_back();
701 if (Incr == Use) continue;
703 SE->deleteValueFromRecords(Use);
704 Use->replaceAllUsesWith(NewIV);
705 Use->eraseFromParent();
708 // Replace exit condition.
709 ConstantInt *NEV = ConstantInt::get(NewType, EV->getZExtValue());
710 Instruction *NE = new ICmpInst(Exit->getPredicate(),
711 NewIncr, NEV, "new.exit",
712 Exit->getParent()->getTerminator());
713 SE->deleteValueFromRecords(Exit);
714 Exit->replaceAllUsesWith(NE);
715 Exit->eraseFromParent();
717 // Remove old IV and increment instructions.
718 SE->deleteValueFromRecords(PH);
719 PH->removeIncomingValue((unsigned)0);
720 PH->removeIncomingValue((unsigned)0);
721 SE->deleteValueFromRecords(Incr);
722 Incr->eraseFromParent();
725 /// Return true if it is OK to use SIToFPInst for an inducation variable
726 /// with given inital and exit values.
727 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
728 uint64_t intIV, uint64_t intEV) {
730 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
733 // If the iteration range can be handled by SIToFPInst then use it.
734 APInt Max = APInt::getSignedMaxValue(32);
735 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
741 /// convertToInt - Convert APF to an integer, if possible.
742 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
744 bool isExact = false;
745 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
747 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
748 APFloat::rmTowardZero, &isExact)
757 /// HandleFloatingPointIV - If the loop has floating induction variable
758 /// then insert corresponding integer induction variable if possible.
760 /// for(double i = 0; i < 10000; ++i)
762 /// is converted into
763 /// for(int i = 0; i < 10000; ++i)
766 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
767 SmallPtrSet<Instruction*, 16> &DeadInsts) {
769 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
770 unsigned BackEdge = IncomingEdge^1;
772 // Check incoming value.
773 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
774 if (!InitValue) return;
775 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
776 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
779 // Check IV increment. Reject this PH if increement operation is not
780 // an add or increment value can not be represented by an integer.
781 BinaryOperator *Incr =
782 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
784 if (Incr->getOpcode() != Instruction::Add) return;
785 ConstantFP *IncrValue = NULL;
786 unsigned IncrVIndex = 1;
787 if (Incr->getOperand(1) == PH)
789 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
790 if (!IncrValue) return;
791 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
792 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
795 // Check Incr uses. One user is PH and the other users is exit condition used
796 // by the conditional terminator.
797 Value::use_iterator IncrUse = Incr->use_begin();
798 Instruction *U1 = cast<Instruction>(IncrUse++);
799 if (IncrUse == Incr->use_end()) return;
800 Instruction *U2 = cast<Instruction>(IncrUse++);
801 if (IncrUse != Incr->use_end()) return;
803 // Find exit condition.
804 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
806 EC = dyn_cast<FCmpInst>(U2);
809 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
810 if (!BI->isConditional()) return;
811 if (BI->getCondition() != EC) return;
814 // Find exit value. If exit value can not be represented as an interger then
815 // do not handle this floating point PH.
816 ConstantFP *EV = NULL;
817 unsigned EVIndex = 1;
818 if (EC->getOperand(1) == Incr)
820 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
822 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
823 if (!convertToInt(EV->getValueAPF(), &intEV))
826 // Find new predicate for integer comparison.
827 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
828 switch (EC->getPredicate()) {
829 case CmpInst::FCMP_OEQ:
830 case CmpInst::FCMP_UEQ:
831 NewPred = CmpInst::ICMP_EQ;
833 case CmpInst::FCMP_OGT:
834 case CmpInst::FCMP_UGT:
835 NewPred = CmpInst::ICMP_UGT;
837 case CmpInst::FCMP_OGE:
838 case CmpInst::FCMP_UGE:
839 NewPred = CmpInst::ICMP_UGE;
841 case CmpInst::FCMP_OLT:
842 case CmpInst::FCMP_ULT:
843 NewPred = CmpInst::ICMP_ULT;
845 case CmpInst::FCMP_OLE:
846 case CmpInst::FCMP_ULE:
847 NewPred = CmpInst::ICMP_ULE;
852 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
854 // Insert new integer induction variable.
855 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
856 PH->getName()+".int", PH);
857 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
858 PH->getIncomingBlock(IncomingEdge));
860 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
861 ConstantInt::get(Type::Int32Ty,
863 Incr->getName()+".int", Incr);
864 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
866 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
867 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
868 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
869 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
870 EC->getParent()->getTerminator());
872 // Delete old, floating point, exit comparision instruction.
873 EC->replaceAllUsesWith(NewEC);
874 DeadInsts.insert(EC);
876 // Delete old, floating point, increment instruction.
877 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
878 DeadInsts.insert(Incr);
880 // Replace floating induction variable. Give SIToFPInst preference over
881 // UIToFPInst because it is faster on platforms that are widely used.
882 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
883 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
884 PH->getParent()->getFirstNonPHI());
885 PH->replaceAllUsesWith(Conv);
887 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
888 PH->getParent()->getFirstNonPHI());
889 PH->replaceAllUsesWith(Conv);
891 DeadInsts.insert(PH);