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/SetVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
61 STATISTIC(NumRemoved , "Number of aux indvars removed");
62 STATISTIC(NumPointer , "Number of pointer indvars promoted");
63 STATISTIC(NumInserted, "Number of canonical indvars added");
64 STATISTIC(NumReplaced, "Number of exit values replaced");
65 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
68 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
74 static char ID; // Pass identification, replacement for typeid
75 IndVarSimplify() : LoopPass(&ID) {}
77 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80 AU.addRequired<ScalarEvolution>();
81 AU.addRequiredID(LCSSAID);
82 AU.addRequiredID(LoopSimplifyID);
83 AU.addRequired<LoopInfo>();
84 AU.addPreservedID(LoopSimplifyID);
85 AU.addPreservedID(LCSSAID);
91 void RewriteNonIntegerIVs(Loop *L);
93 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
94 SmallPtrSet<Instruction*, 16> &DeadInsts);
95 void LinearFunctionTestReplace(Loop *L, SCEVHandle IterationCount,
97 BasicBlock *ExitingBlock,
99 SCEVExpander &Rewriter);
100 void RewriteLoopExitValues(Loop *L, SCEV *IterationCount);
102 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
104 void HandleFloatingPointIV(Loop *L, PHINode *PH,
105 SmallPtrSet<Instruction*, 16> &DeadInsts);
109 char IndVarSimplify::ID = 0;
110 static RegisterPass<IndVarSimplify>
111 X("indvars", "Canonicalize Induction Variables");
113 Pass *llvm::createIndVarSimplifyPass() {
114 return new IndVarSimplify();
117 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
118 /// specified set are trivially dead, delete them and see if this makes any of
119 /// their operands subsequently dead.
120 void IndVarSimplify::
121 DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
122 while (!Insts.empty()) {
123 Instruction *I = *Insts.begin();
125 if (isInstructionTriviallyDead(I)) {
126 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
127 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
129 SE->deleteValueFromRecords(I);
130 DOUT << "INDVARS: Deleting: " << *I;
131 I->eraseFromParent();
138 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer
139 /// recurrence. If so, change it into an integer recurrence, permitting
140 /// analysis by the SCEV routines.
141 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN,
142 BasicBlock *Preheader,
143 SmallPtrSet<Instruction*, 16> &DeadInsts) {
144 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!");
145 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader);
146 unsigned BackedgeIdx = PreheaderIdx^1;
147 if (GetElementPtrInst *GEPI =
148 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx)))
149 if (GEPI->getOperand(0) == PN) {
150 assert(GEPI->getNumOperands() == 2 && "GEP types must match!");
151 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI;
153 // Okay, we found a pointer recurrence. Transform this pointer
154 // recurrence into an integer recurrence. Compute the value that gets
155 // added to the pointer at every iteration.
156 Value *AddedVal = GEPI->getOperand(1);
158 // Insert a new integer PHI node into the top of the block.
159 PHINode *NewPhi = PHINode::Create(AddedVal->getType(),
160 PN->getName()+".rec", PN);
161 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
163 // Create the new add instruction.
164 Value *NewAdd = BinaryOperator::CreateAdd(NewPhi, AddedVal,
165 GEPI->getName()+".rec", GEPI);
166 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
168 // Update the existing GEP to use the recurrence.
169 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
171 // Update the GEP to use the new recurrence we just inserted.
172 GEPI->setOperand(1, NewAdd);
174 // If the incoming value is a constant expr GEP, try peeling out the array
175 // 0 index if possible to make things simpler.
176 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
177 if (CE->getOpcode() == Instruction::GetElementPtr) {
178 unsigned NumOps = CE->getNumOperands();
179 assert(NumOps > 1 && "CE folding didn't work!");
180 if (CE->getOperand(NumOps-1)->isNullValue()) {
181 // Check to make sure the last index really is an array index.
182 gep_type_iterator GTI = gep_type_begin(CE);
183 for (unsigned i = 1, e = CE->getNumOperands()-1;
186 if (isa<SequentialType>(*GTI)) {
187 // Pull the last index out of the constant expr GEP.
188 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
189 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
193 Idx[0] = Constant::getNullValue(Type::Int32Ty);
195 GetElementPtrInst *NGEPI = GetElementPtrInst::Create(
197 GEPI->getName(), GEPI);
198 SE->deleteValueFromRecords(GEPI);
199 GEPI->replaceAllUsesWith(NGEPI);
200 GEPI->eraseFromParent();
207 // Finally, if there are any other users of the PHI node, we must
208 // insert a new GEP instruction that uses the pre-incremented version
209 // of the induction amount.
210 if (!PN->use_empty()) {
211 BasicBlock::iterator InsertPos = PN; ++InsertPos;
212 while (isa<PHINode>(InsertPos)) ++InsertPos;
214 GetElementPtrInst::Create(PN->getIncomingValue(PreheaderIdx),
215 NewPhi, "", InsertPos);
216 PreInc->takeName(PN);
217 PN->replaceAllUsesWith(PreInc);
220 // Delete the old PHI for sure, and the GEP if its otherwise unused.
221 DeadInsts.insert(PN);
228 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
229 /// loop to be a canonical != comparison against the incremented loop induction
230 /// variable. This pass is able to rewrite the exit tests of any loop where the
231 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
232 /// is actually a much broader range than just linear tests.
233 void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
234 SCEVHandle IterationCount,
236 BasicBlock *ExitingBlock,
238 SCEVExpander &Rewriter) {
239 // If the exiting block is not the same as the backedge block, we must compare
240 // against the preincremented value, otherwise we prefer to compare against
241 // the post-incremented value.
243 if (ExitingBlock == L->getLoopLatch()) {
244 // What ScalarEvolution calls the "iteration count" is actually the
245 // number of times the branch is taken. Add one to get the number
246 // of times the branch is executed. If this addition may overflow,
247 // we have to be more pessimistic and cast the induction variable
248 // before doing the add.
249 SCEVHandle Zero = SE->getIntegerSCEV(0, IterationCount->getType());
251 SE->getAddExpr(IterationCount,
252 SE->getIntegerSCEV(1, IterationCount->getType()));
253 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
254 SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
255 // No overflow. Cast the sum.
256 IterationCount = SE->getTruncateOrZeroExtend(N, IndVar->getType());
258 // Potential overflow. Cast before doing the add.
259 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
262 SE->getAddExpr(IterationCount,
263 SE->getIntegerSCEV(1, IndVar->getType()));
266 // The IterationCount expression contains the number of times that the
267 // backedge actually branches to the loop header. This is one less than the
268 // number of times the loop executes, so add one to it.
269 CmpIndVar = L->getCanonicalInductionVariableIncrement();
271 // We have to use the preincremented value...
272 IterationCount = SE->getTruncateOrZeroExtend(IterationCount,
277 // Expand the code for the iteration count into the preheader of the loop.
278 BasicBlock *Preheader = L->getLoopPreheader();
279 Value *ExitCnt = Rewriter.expandCodeFor(IterationCount,
280 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 DOUT << "INDVARS: Rewriting loop exit condition to:\n"
290 << " LHS:" << *CmpIndVar // includes a newline
292 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
293 << " RHS:\t" << *IterationCount << "\n";
295 Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
296 BI->setCondition(Cond);
301 /// RewriteLoopExitValues - Check to see if this loop has a computable
302 /// loop-invariant execution count. If so, this means that we can compute the
303 /// final value of any expressions that are recurrent in the loop, and
304 /// substitute the exit values from the loop into any instructions outside of
305 /// the loop that use the final values of the current expressions.
306 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEV *IterationCount) {
307 BasicBlock *Preheader = L->getLoopPreheader();
309 // Scan all of the instructions in the loop, looking at those that have
310 // extra-loop users and which are recurrences.
311 SCEVExpander Rewriter(*SE, *LI);
313 // We insert the code into the preheader of the loop if the loop contains
314 // multiple exit blocks, or in the exit block if there is exactly one.
315 BasicBlock *BlockToInsertInto;
316 SmallVector<BasicBlock*, 8> ExitBlocks;
317 L->getUniqueExitBlocks(ExitBlocks);
318 if (ExitBlocks.size() == 1)
319 BlockToInsertInto = ExitBlocks[0];
321 BlockToInsertInto = Preheader;
322 BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
324 bool HasConstantItCount = isa<SCEVConstant>(IterationCount);
326 SmallPtrSet<Instruction*, 16> InstructionsToDelete;
327 std::map<Instruction*, Value*> ExitValues;
329 // 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];
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());
340 unsigned NumPreds = PN->getNumIncomingValues();
342 // Iterate over all of the PHI nodes.
343 BasicBlock::iterator BBI = ExitBB->begin();
344 while ((PN = dyn_cast<PHINode>(BBI++))) {
346 // 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()))
356 // 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.
360 // Check that InVal is defined in the loop.
361 Instruction *Inst = cast<Instruction>(InVal);
362 if (!L->contains(Inst->getParent()))
365 // 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.
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))
384 // See if we already computed the exit value for the instruction, if so,
386 Value *&ExitVal = ExitValues[Inst];
388 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt);
390 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
391 << " LoopVal = " << *Inst << "\n";
393 PN->setIncomingValue(i, ExitVal);
395 // If this instruction is dead now, schedule it to be removed.
396 if (Inst->use_empty())
397 InstructionsToDelete.insert(Inst);
399 // See if this is a single-entry LCSSA PHI node. If so, we can (and
401 // 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.
404 SE->deleteValueFromRecords(PN);
405 PN->replaceAllUsesWith(ExitVal);
406 PN->eraseFromParent();
413 DeleteTriviallyDeadInstructions(InstructionsToDelete);
416 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
417 // First step. Check to see if there are any trivial GEP pointer recurrences.
418 // If there are, change them into integer recurrences, permitting analysis by
419 // the SCEV routines.
421 BasicBlock *Header = L->getHeader();
422 BasicBlock *Preheader = L->getLoopPreheader();
424 SmallPtrSet<Instruction*, 16> 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);
430 HandleFloatingPointIV(L, PN, DeadInsts);
433 // If the loop previously had a pointer or floating-point IV, ScalarEvolution
434 // may not have been able to compute a trip count. Now that we've done some
435 // re-writing, the trip count may be computable.
437 SE->forgetLoopIterationCount(L);
439 if (!DeadInsts.empty())
440 DeleteTriviallyDeadInstructions(DeadInsts);
443 /// getEffectiveIndvarType - Determine the widest type that the
444 /// induction-variable PHINode Phi is cast to.
446 static const Type *getEffectiveIndvarType(const PHINode *Phi) {
447 const Type *Ty = Phi->getType();
449 for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
451 const Type *CandidateType = NULL;
452 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
453 CandidateType = ZI->getDestTy();
454 else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
455 CandidateType = SI->getDestTy();
457 CandidateType->getPrimitiveSizeInBits() >
458 Ty->getPrimitiveSizeInBits())
465 /// TestOrigIVForWrap - Analyze the original induction variable
466 /// in the loop to determine whether it would ever undergo signed
467 /// or unsigned overflow.
469 /// TODO: This duplicates a fair amount of ScalarEvolution logic.
470 /// Perhaps this can be merged with ScalarEvolution::getIterationCount
471 /// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
473 static void TestOrigIVForWrap(const Loop *L,
474 const BranchInst *BI,
475 const Instruction *OrigCond,
477 bool &NoUnsignedWrap) {
478 // Verify that the loop is sane and find the exit condition.
479 const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
482 const Value *CmpLHS = Cmp->getOperand(0);
483 const Value *CmpRHS = Cmp->getOperand(1);
484 const BasicBlock *TrueBB = BI->getSuccessor(0);
485 const BasicBlock *FalseBB = BI->getSuccessor(1);
486 ICmpInst::Predicate Pred = Cmp->getPredicate();
488 // Canonicalize a constant to the RHS.
489 if (isa<ConstantInt>(CmpLHS)) {
490 Pred = ICmpInst::getSwappedPredicate(Pred);
491 std::swap(CmpLHS, CmpRHS);
493 // Canonicalize SLE to SLT.
494 if (Pred == ICmpInst::ICMP_SLE)
495 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
496 if (!CI->getValue().isMaxSignedValue()) {
497 CmpRHS = ConstantInt::get(CI->getValue() + 1);
498 Pred = ICmpInst::ICMP_SLT;
500 // Canonicalize SGT to SGE.
501 if (Pred == ICmpInst::ICMP_SGT)
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
503 if (!CI->getValue().isMaxSignedValue()) {
504 CmpRHS = ConstantInt::get(CI->getValue() + 1);
505 Pred = ICmpInst::ICMP_SGE;
507 // Canonicalize SGE to SLT.
508 if (Pred == ICmpInst::ICMP_SGE) {
509 std::swap(TrueBB, FalseBB);
510 Pred = ICmpInst::ICMP_SLT;
512 // Canonicalize ULE to ULT.
513 if (Pred == ICmpInst::ICMP_ULE)
514 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
515 if (!CI->getValue().isMaxValue()) {
516 CmpRHS = ConstantInt::get(CI->getValue() + 1);
517 Pred = ICmpInst::ICMP_ULT;
519 // Canonicalize UGT to UGE.
520 if (Pred == ICmpInst::ICMP_UGT)
521 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
522 if (!CI->getValue().isMaxValue()) {
523 CmpRHS = ConstantInt::get(CI->getValue() + 1);
524 Pred = ICmpInst::ICMP_UGE;
526 // Canonicalize UGE to ULT.
527 if (Pred == ICmpInst::ICMP_UGE) {
528 std::swap(TrueBB, FalseBB);
529 Pred = ICmpInst::ICMP_ULT;
531 // For now, analyze only LT loops for signed overflow.
532 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
535 bool isSigned = Pred == ICmpInst::ICMP_SLT;
537 // Get the increment instruction. Look past casts if we will
538 // be able to prove that the original induction variable doesn't
539 // undergo signed or unsigned overflow, respectively.
540 const Value *IncrVal = CmpLHS;
542 if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
543 if (!isa<ConstantInt>(CmpRHS) ||
544 !cast<ConstantInt>(CmpRHS)->getValue()
545 .isSignedIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
547 IncrVal = SI->getOperand(0);
550 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
551 if (!isa<ConstantInt>(CmpRHS) ||
552 !cast<ConstantInt>(CmpRHS)->getValue()
553 .isIntN(IncrVal->getType()->getPrimitiveSizeInBits()))
555 IncrVal = ZI->getOperand(0);
559 // For now, only analyze induction variables that have simple increments.
560 const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrVal);
562 IncrOp->getOpcode() != Instruction::Add ||
563 !isa<ConstantInt>(IncrOp->getOperand(1)) ||
564 !cast<ConstantInt>(IncrOp->getOperand(1))->equalsInt(1))
567 // Make sure the PHI looks like a normal IV.
568 const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
569 if (!PN || PN->getNumIncomingValues() != 2)
571 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
572 unsigned BackEdge = !IncomingEdge;
573 if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
574 PN->getIncomingValue(BackEdge) != IncrOp)
576 if (!L->contains(TrueBB))
579 // For now, only analyze loops with a constant start value, so that
580 // we can easily determine if the start value is not a maximum value
581 // which would wrap on the first iteration.
582 const Value *InitialVal = PN->getIncomingValue(IncomingEdge);
583 if (!isa<ConstantInt>(InitialVal))
586 // The original induction variable will start at some non-max value,
587 // it counts up by one, and the loop iterates only while it remans
588 // less than some value in the same type. As such, it will never wrap.
590 !cast<ConstantInt>(InitialVal)->getValue().isMaxSignedValue())
592 else if (!isSigned &&
593 !cast<ConstantInt>(InitialVal)->getValue().isMaxValue())
594 NoUnsignedWrap = true;
597 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
598 LI = &getAnalysis<LoopInfo>();
599 SE = &getAnalysis<ScalarEvolution>();
602 // If there are any floating-point or pointer recurrences, attempt to
603 // transform them to use integer recurrences.
604 RewriteNonIntegerIVs(L);
606 BasicBlock *Header = L->getHeader();
607 BasicBlock *ExitingBlock = L->getExitingBlock();
608 SmallPtrSet<Instruction*, 16> DeadInsts;
610 // Verify the input to the pass in already in LCSSA form.
611 assert(L->isLCSSAForm());
613 // Check to see if this loop has a computable loop-invariant execution count.
614 // If so, this means that we can compute the final value of any expressions
615 // that are recurrent in the loop, and substitute the exit values from the
616 // loop into any instructions outside of the loop that use the final values of
617 // the current expressions.
619 SCEVHandle IterationCount = SE->getIterationCount(L);
620 if (!isa<SCEVCouldNotCompute>(IterationCount))
621 RewriteLoopExitValues(L, IterationCount);
623 // Next, analyze all of the induction variables in the loop, canonicalizing
624 // auxillary induction variables.
625 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
627 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
628 PHINode *PN = cast<PHINode>(I);
629 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable!
630 SCEVHandle SCEV = SE->getSCEV(PN);
631 // FIXME: It is an extremely bad idea to indvar substitute anything more
632 // complex than affine induction variables. Doing so will put expensive
633 // polynomial evaluations inside of the loop, and the str reduction pass
634 // currently can only reduce affine polynomials. For now just disable
635 // indvar subst on anything more complex than an affine addrec.
636 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
637 if (AR->getLoop() == L && AR->isAffine())
638 IndVars.push_back(std::make_pair(PN, SCEV));
642 // Compute the type of the largest recurrence expression, and collect
643 // the set of the types of the other recurrence expressions.
644 const Type *LargestType = 0;
645 SmallSetVector<const Type *, 4> SizesToInsert;
646 if (!isa<SCEVCouldNotCompute>(IterationCount)) {
647 LargestType = IterationCount->getType();
648 SizesToInsert.insert(IterationCount->getType());
650 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
651 const PHINode *PN = IndVars[i].first;
652 SizesToInsert.insert(PN->getType());
653 const Type *EffTy = getEffectiveIndvarType(PN);
654 SizesToInsert.insert(EffTy);
656 EffTy->getPrimitiveSizeInBits() >
657 LargestType->getPrimitiveSizeInBits())
661 // Create a rewriter object which we'll use to transform the code with.
662 SCEVExpander Rewriter(*SE, *LI);
664 // Now that we know the largest of of the induction variables in this loop,
665 // insert a canonical induction variable of the largest size.
667 if (!SizesToInsert.empty()) {
668 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
671 DOUT << "INDVARS: New CanIV: " << *IndVar;
674 // If we have a trip count expression, rewrite the loop's exit condition
675 // using it. We can currently only handle loops with a single exit.
676 bool NoSignedWrap = false;
677 bool NoUnsignedWrap = false;
678 if (!isa<SCEVCouldNotCompute>(IterationCount) && ExitingBlock)
679 // Can't rewrite non-branch yet.
680 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
681 if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
682 // Determine if the OrigIV will ever undergo overflow.
683 TestOrigIVForWrap(L, BI, OrigCond,
684 NoSignedWrap, NoUnsignedWrap);
686 // We'll be replacing the original condition, so it'll be dead.
687 DeadInsts.insert(OrigCond);
690 LinearFunctionTestReplace(L, IterationCount, IndVar,
691 ExitingBlock, BI, Rewriter);
694 // Now that we have a canonical induction variable, we can rewrite any
695 // recurrences in terms of the induction variable. Start with the auxillary
696 // induction variables, and recursively rewrite any of their uses.
697 BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
699 // If there were induction variables of other sizes, cast the primary
700 // induction variable to the right size for them, avoiding the need for the
701 // code evaluation methods to insert induction variables of different sizes.
702 for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
703 const Type *Ty = SizesToInsert[i];
704 if (Ty != LargestType) {
705 Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
706 Rewriter.addInsertedValue(New, SE->getSCEV(New));
707 DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
712 // Rewrite all induction variables in terms of the canonical induction
714 while (!IndVars.empty()) {
715 PHINode *PN = IndVars.back().first;
716 SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
717 Value *NewVal = Rewriter.expandCodeFor(AR, InsertPt);
718 DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
719 << " into = " << *NewVal << "\n";
720 NewVal->takeName(PN);
722 /// If the new canonical induction variable is wider than the original,
723 /// and the original has uses that are casts to wider types, see if the
724 /// truncate and extend can be omitted.
725 if (PN->getType() != LargestType)
726 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
728 if (isa<SExtInst>(UI) && NoSignedWrap) {
729 SCEVHandle ExtendedStart =
730 SE->getSignExtendExpr(AR->getStart(), LargestType);
731 SCEVHandle ExtendedStep =
732 SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
733 SCEVHandle ExtendedAddRec =
734 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
735 if (LargestType != UI->getType())
736 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
737 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
738 UI->replaceAllUsesWith(TruncIndVar);
739 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
740 DeadInsts.insert(DeadUse);
742 if (isa<ZExtInst>(UI) && NoUnsignedWrap) {
743 SCEVHandle ExtendedStart =
744 SE->getZeroExtendExpr(AR->getStart(), LargestType);
745 SCEVHandle ExtendedStep =
746 SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
747 SCEVHandle ExtendedAddRec =
748 SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
749 if (LargestType != UI->getType())
750 ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, UI->getType());
751 Value *TruncIndVar = Rewriter.expandCodeFor(ExtendedAddRec, InsertPt);
752 UI->replaceAllUsesWith(TruncIndVar);
753 if (Instruction *DeadUse = dyn_cast<Instruction>(*UI))
754 DeadInsts.insert(DeadUse);
758 // Replace the old PHI Node with the inserted computation.
759 PN->replaceAllUsesWith(NewVal);
760 DeadInsts.insert(PN);
766 DeleteTriviallyDeadInstructions(DeadInsts);
767 assert(L->isLCSSAForm());
771 /// Return true if it is OK to use SIToFPInst for an inducation variable
772 /// with given inital and exit values.
773 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
774 uint64_t intIV, uint64_t intEV) {
776 if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
779 // If the iteration range can be handled by SIToFPInst then use it.
780 APInt Max = APInt::getSignedMaxValue(32);
781 if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
787 /// convertToInt - Convert APF to an integer, if possible.
788 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
790 bool isExact = false;
791 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
793 if (APF.convertToInteger(intVal, 32, APF.isNegative(),
794 APFloat::rmTowardZero, &isExact)
803 /// HandleFloatingPointIV - If the loop has floating induction variable
804 /// then insert corresponding integer induction variable if possible.
806 /// for(double i = 0; i < 10000; ++i)
808 /// is converted into
809 /// for(int i = 0; i < 10000; ++i)
812 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
813 SmallPtrSet<Instruction*, 16> &DeadInsts) {
815 unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
816 unsigned BackEdge = IncomingEdge^1;
818 // Check incoming value.
819 ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
820 if (!InitValue) return;
821 uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
822 if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
825 // Check IV increment. Reject this PH if increement operation is not
826 // an add or increment value can not be represented by an integer.
827 BinaryOperator *Incr =
828 dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
830 if (Incr->getOpcode() != Instruction::Add) return;
831 ConstantFP *IncrValue = NULL;
832 unsigned IncrVIndex = 1;
833 if (Incr->getOperand(1) == PH)
835 IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
836 if (!IncrValue) return;
837 uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
838 if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
841 // Check Incr uses. One user is PH and the other users is exit condition used
842 // by the conditional terminator.
843 Value::use_iterator IncrUse = Incr->use_begin();
844 Instruction *U1 = cast<Instruction>(IncrUse++);
845 if (IncrUse == Incr->use_end()) return;
846 Instruction *U2 = cast<Instruction>(IncrUse++);
847 if (IncrUse != Incr->use_end()) return;
849 // Find exit condition.
850 FCmpInst *EC = dyn_cast<FCmpInst>(U1);
852 EC = dyn_cast<FCmpInst>(U2);
855 if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
856 if (!BI->isConditional()) return;
857 if (BI->getCondition() != EC) return;
860 // Find exit value. If exit value can not be represented as an interger then
861 // do not handle this floating point PH.
862 ConstantFP *EV = NULL;
863 unsigned EVIndex = 1;
864 if (EC->getOperand(1) == Incr)
866 EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
868 uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
869 if (!convertToInt(EV->getValueAPF(), &intEV))
872 // Find new predicate for integer comparison.
873 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
874 switch (EC->getPredicate()) {
875 case CmpInst::FCMP_OEQ:
876 case CmpInst::FCMP_UEQ:
877 NewPred = CmpInst::ICMP_EQ;
879 case CmpInst::FCMP_OGT:
880 case CmpInst::FCMP_UGT:
881 NewPred = CmpInst::ICMP_UGT;
883 case CmpInst::FCMP_OGE:
884 case CmpInst::FCMP_UGE:
885 NewPred = CmpInst::ICMP_UGE;
887 case CmpInst::FCMP_OLT:
888 case CmpInst::FCMP_ULT:
889 NewPred = CmpInst::ICMP_ULT;
891 case CmpInst::FCMP_OLE:
892 case CmpInst::FCMP_ULE:
893 NewPred = CmpInst::ICMP_ULE;
898 if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
900 // Insert new integer induction variable.
901 PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
902 PH->getName()+".int", PH);
903 NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
904 PH->getIncomingBlock(IncomingEdge));
906 Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
907 ConstantInt::get(Type::Int32Ty,
909 Incr->getName()+".int", Incr);
910 NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
912 ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
913 Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(BackEdge) : NewEV);
914 Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(BackEdge));
915 ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
916 EC->getParent()->getTerminator());
918 // Delete old, floating point, exit comparision instruction.
919 EC->replaceAllUsesWith(NewEC);
920 DeadInsts.insert(EC);
922 // Delete old, floating point, increment instruction.
923 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
924 DeadInsts.insert(Incr);
926 // Replace floating induction variable. Give SIToFPInst preference over
927 // UIToFPInst because it is faster on platforms that are widely used.
928 if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
929 SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
930 PH->getParent()->getFirstNonPHI());
931 PH->replaceAllUsesWith(Conv);
933 UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
934 PH->getParent()->getFirstNonPHI());
935 PH->replaceAllUsesWith(Conv);
937 DeadInsts.insert(PH);