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. The canonical induction variable is guaranteed to be in a wide enough
21 // type so that IV expressions need not be (directly) zero-extended or
23 // 4. Any pointer arithmetic recurrences are raised to use array subscripts.
25 // If the trip count of a loop is computable, this pass also makes the following
27 // 1. The exit condition for the loop is canonicalized to compare the
28 // induction value against the exit value. This turns loops like:
29 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30 // 2. Any use outside of the loop of an expression derived from the indvar
31 // is changed to compute the derived value outside of the loop, eliminating
32 // the dependence on the exit value of the induction variable. If the only
33 // purpose of the loop is to compute the exit value of some derived
34 // expression, this transformation will make the loop dead.
36 // This transformation should be followed by strength reduction after all of the
37 // desired loop transformations have been performed.
39 //===----------------------------------------------------------------------===//
41 #define DEBUG_TYPE "indvars"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/BasicBlock.h"
44 #include "llvm/Constants.h"
45 #include "llvm/Instructions.h"
46 #include "llvm/IntrinsicInst.h"
47 #include "llvm/LLVMContext.h"
48 #include "llvm/Type.h"
49 #include "llvm/Analysis/Dominators.h"
50 #include "llvm/Analysis/IVUsers.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Support/CFG.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
65 STATISTIC(NumRemoved , "Number of aux indvars removed");
66 STATISTIC(NumInserted, "Number of canonical indvars added");
67 STATISTIC(NumReplaced, "Number of exit values replaced");
68 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
71 class IndVarSimplify : public LoopPass {
79 static char ID; // Pass identification, replacement for typeid
80 IndVarSimplify() : LoopPass(&ID) {}
82 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<DominatorTree>();
86 AU.addRequired<LoopInfo>();
87 AU.addRequired<ScalarEvolution>();
88 AU.addRequiredID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addRequired<IVUsers>();
91 AU.addPreserved<ScalarEvolution>();
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addPreservedID(LCSSAID);
94 AU.addPreserved<IVUsers>();
100 void EliminateIVComparisons();
101 void RewriteNonIntegerIVs(Loop *L);
103 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
105 BasicBlock *ExitingBlock,
107 SCEVExpander &Rewriter);
108 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
110 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
112 void SinkUnusedInvariants(Loop *L);
114 void HandleFloatingPointIV(Loop *L, PHINode *PH);
118 char IndVarSimplify::ID = 0;
119 static RegisterPass<IndVarSimplify>
120 X("indvars", "Canonicalize Induction Variables");
122 Pass *llvm::createIndVarSimplifyPass() {
123 return new IndVarSimplify();
126 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
127 /// loop to be a canonical != comparison against the incremented loop induction
128 /// variable. This pass is able to rewrite the exit tests of any loop where the
129 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
130 /// is actually a much broader range than just linear tests.
131 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
132 const SCEV *BackedgeTakenCount,
134 BasicBlock *ExitingBlock,
136 SCEVExpander &Rewriter) {
137 // Special case: If the backedge-taken count is a UDiv, it's very likely a
138 // UDiv that ScalarEvolution produced in order to compute a precise
139 // expression, rather than a UDiv from the user's code. If we can't find a
140 // UDiv in the code with some simple searching, assume the former and forego
141 // rewriting the loop.
142 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
143 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
144 if (!OrigCond) return 0;
145 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
146 R = SE->getMinusSCEV(R, SE->getIntegerSCEV(1, R->getType()));
147 if (R != BackedgeTakenCount) {
148 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
149 L = SE->getMinusSCEV(L, SE->getIntegerSCEV(1, L->getType()));
150 if (L != BackedgeTakenCount)
155 // If the exiting block is not the same as the backedge block, we must compare
156 // against the preincremented value, otherwise we prefer to compare against
157 // the post-incremented value.
159 const SCEV *RHS = BackedgeTakenCount;
160 if (ExitingBlock == L->getLoopLatch()) {
161 // Add one to the "backedge-taken" count to get the trip count.
162 // If this addition may overflow, we have to be more pessimistic and
163 // cast the induction variable before doing the add.
164 const SCEV *Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
166 SE->getAddExpr(BackedgeTakenCount,
167 SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
168 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
169 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
170 // No overflow. Cast the sum.
171 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
173 // Potential overflow. Cast before doing the add.
174 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
176 RHS = SE->getAddExpr(RHS,
177 SE->getIntegerSCEV(1, IndVar->getType()));
180 // The BackedgeTaken expression contains the number of times that the
181 // backedge branches to the loop header. This is one less than the
182 // number of times the loop executes, so use the incremented indvar.
183 CmpIndVar = L->getCanonicalInductionVariableIncrement();
185 // We have to use the preincremented value...
186 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
191 // Expand the code for the iteration count.
192 assert(RHS->isLoopInvariant(L) &&
193 "Computed iteration count is not loop invariant!");
194 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
196 // Insert a new icmp_ne or icmp_eq instruction before the branch.
197 ICmpInst::Predicate Opcode;
198 if (L->contains(BI->getSuccessor(0)))
199 Opcode = ICmpInst::ICMP_NE;
201 Opcode = ICmpInst::ICMP_EQ;
203 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
204 << " LHS:" << *CmpIndVar << '\n'
206 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
207 << " RHS:\t" << *RHS << "\n");
209 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
211 Value *OrigCond = BI->getCondition();
212 // It's tempting to use replaceAllUsesWith here to fully replace the old
213 // comparison, but that's not immediately safe, since users of the old
214 // comparison may not be dominated by the new comparison. Instead, just
215 // update the branch to use the new comparison; in the common case this
216 // will make old comparison dead.
217 BI->setCondition(Cond);
218 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
225 /// RewriteLoopExitValues - Check to see if this loop has a computable
226 /// loop-invariant execution count. If so, this means that we can compute the
227 /// final value of any expressions that are recurrent in the loop, and
228 /// substitute the exit values from the loop into any instructions outside of
229 /// the loop that use the final values of the current expressions.
231 /// This is mostly redundant with the regular IndVarSimplify activities that
232 /// happen later, except that it's more powerful in some cases, because it's
233 /// able to brute-force evaluate arbitrary instructions as long as they have
234 /// constant operands at the beginning of the loop.
235 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
236 SCEVExpander &Rewriter) {
237 // Verify the input to the pass in already in LCSSA form.
238 assert(L->isLCSSAForm(*DT));
240 SmallVector<BasicBlock*, 8> ExitBlocks;
241 L->getUniqueExitBlocks(ExitBlocks);
243 // Find all values that are computed inside the loop, but used outside of it.
244 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
245 // the exit blocks of the loop to find them.
246 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
247 BasicBlock *ExitBB = ExitBlocks[i];
249 // If there are no PHI nodes in this exit block, then no values defined
250 // inside the loop are used on this path, skip it.
251 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
254 unsigned NumPreds = PN->getNumIncomingValues();
256 // Iterate over all of the PHI nodes.
257 BasicBlock::iterator BBI = ExitBB->begin();
258 while ((PN = dyn_cast<PHINode>(BBI++))) {
260 continue; // dead use, don't replace it
262 // SCEV only supports integer expressions for now.
263 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
266 // It's necessary to tell ScalarEvolution about this explicitly so that
267 // it can walk the def-use list and forget all SCEVs, as it may not be
268 // watching the PHI itself. Once the new exit value is in place, there
269 // may not be a def-use connection between the loop and every instruction
270 // which got a SCEVAddRecExpr for that loop.
273 // Iterate over all of the values in all the PHI nodes.
274 for (unsigned i = 0; i != NumPreds; ++i) {
275 // If the value being merged in is not integer or is not defined
276 // in the loop, skip it.
277 Value *InVal = PN->getIncomingValue(i);
278 if (!isa<Instruction>(InVal))
281 // If this pred is for a subloop, not L itself, skip it.
282 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
283 continue; // The Block is in a subloop, skip it.
285 // Check that InVal is defined in the loop.
286 Instruction *Inst = cast<Instruction>(InVal);
287 if (!L->contains(Inst))
290 // Okay, this instruction has a user outside of the current loop
291 // and varies predictably *inside* the loop. Evaluate the value it
292 // contains when the loop exits, if possible.
293 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
294 if (!ExitValue->isLoopInvariant(L))
300 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
302 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
303 << " LoopVal = " << *Inst << "\n");
305 PN->setIncomingValue(i, ExitVal);
307 // If this instruction is dead now, delete it.
308 RecursivelyDeleteTriviallyDeadInstructions(Inst);
311 // Completely replace a single-pred PHI. This is safe, because the
312 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
314 PN->replaceAllUsesWith(ExitVal);
315 RecursivelyDeleteTriviallyDeadInstructions(PN);
319 // Clone the PHI and delete the original one. This lets IVUsers and
320 // any other maps purge the original user from their records.
321 PHINode *NewPN = cast<PHINode>(PN->clone());
323 NewPN->insertBefore(PN);
324 PN->replaceAllUsesWith(NewPN);
325 PN->eraseFromParent();
330 // The insertion point instruction may have been deleted; clear it out
331 // so that the rewriter doesn't trip over it later.
332 Rewriter.clearInsertPoint();
335 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
336 // First step. Check to see if there are any floating-point recurrences.
337 // If there are, change them into integer recurrences, permitting analysis by
338 // the SCEV routines.
340 BasicBlock *Header = L->getHeader();
342 SmallVector<WeakVH, 8> PHIs;
343 for (BasicBlock::iterator I = Header->begin();
344 PHINode *PN = dyn_cast<PHINode>(I); ++I)
347 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
348 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i]))
349 HandleFloatingPointIV(L, PN);
351 // If the loop previously had floating-point IV, ScalarEvolution
352 // may not have been able to compute a trip count. Now that we've done some
353 // re-writing, the trip count may be computable.
358 void IndVarSimplify::EliminateIVComparisons() {
359 SmallVector<WeakVH, 16> DeadInsts;
361 // Look for ICmp users.
362 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
363 IVStrideUse &UI = *I;
364 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
367 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
368 ICmpInst::Predicate Pred = ICmp->getPredicate();
369 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
371 // Get the SCEVs for the ICmp operands.
372 const SCEV *S = IU->getReplacementExpr(UI);
373 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
375 // Simplify unnecessary loops away.
376 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
377 S = SE->getSCEVAtScope(S, ICmpLoop);
378 X = SE->getSCEVAtScope(X, ICmpLoop);
380 // If the condition is always true or always false, replace it with
382 if (SE->isKnownPredicate(Pred, S, X))
383 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
384 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
385 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
389 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
390 DeadInsts.push_back(ICmp);
393 // Now that we're done iterating through lists, clean up any instructions
394 // which are now dead.
395 while (!DeadInsts.empty())
396 if (Instruction *Inst =
397 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
398 RecursivelyDeleteTriviallyDeadInstructions(Inst);
401 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
402 IU = &getAnalysis<IVUsers>();
403 LI = &getAnalysis<LoopInfo>();
404 SE = &getAnalysis<ScalarEvolution>();
405 DT = &getAnalysis<DominatorTree>();
408 // If there are any floating-point recurrences, attempt to
409 // transform them to use integer recurrences.
410 RewriteNonIntegerIVs(L);
412 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
413 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
415 // Create a rewriter object which we'll use to transform the code with.
416 SCEVExpander Rewriter(*SE);
418 // Check to see if this loop has a computable loop-invariant execution count.
419 // If so, this means that we can compute the final value of any expressions
420 // that are recurrent in the loop, and substitute the exit values from the
421 // loop into any instructions outside of the loop that use the final values of
422 // the current expressions.
424 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
425 RewriteLoopExitValues(L, Rewriter);
427 // Simplify ICmp IV users.
428 EliminateIVComparisons();
430 // Compute the type of the largest recurrence expression, and decide whether
431 // a canonical induction variable should be inserted.
432 const Type *LargestType = 0;
433 bool NeedCannIV = false;
434 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
435 LargestType = BackedgeTakenCount->getType();
436 LargestType = SE->getEffectiveSCEVType(LargestType);
437 // If we have a known trip count and a single exit block, we'll be
438 // rewriting the loop exit test condition below, which requires a
439 // canonical induction variable.
443 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
445 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
447 SE->getTypeSizeInBits(Ty) >
448 SE->getTypeSizeInBits(LargestType))
453 // Now that we know the largest of the induction variable expressions
454 // in this loop, insert a canonical induction variable of the largest size.
457 // Check to see if the loop already has any canonical-looking induction
458 // variables. If any are present and wider than the planned canonical
459 // induction variable, temporarily remove them, so that the Rewriter
460 // doesn't attempt to reuse them.
461 SmallVector<PHINode *, 2> OldCannIVs;
462 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
463 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
464 SE->getTypeSizeInBits(LargestType))
465 OldCannIV->removeFromParent();
468 OldCannIVs.push_back(OldCannIV);
471 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
475 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
477 // Now that the official induction variable is established, reinsert
478 // any old canonical-looking variables after it so that the IR remains
479 // consistent. They will be deleted as part of the dead-PHI deletion at
480 // the end of the pass.
481 while (!OldCannIVs.empty()) {
482 PHINode *OldCannIV = OldCannIVs.pop_back_val();
483 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
487 // If we have a trip count expression, rewrite the loop's exit condition
488 // using it. We can currently only handle loops with a single exit.
489 ICmpInst *NewICmp = 0;
490 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
491 !BackedgeTakenCount->isZero() &&
494 "LinearFunctionTestReplace requires a canonical induction variable");
495 // Can't rewrite non-branch yet.
496 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
497 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
498 ExitingBlock, BI, Rewriter);
501 // Rewrite IV-derived expressions. Clears the rewriter cache.
502 RewriteIVExpressions(L, Rewriter);
504 // The Rewriter may not be used from this point on.
506 // Loop-invariant instructions in the preheader that aren't used in the
507 // loop may be sunk below the loop to reduce register pressure.
508 SinkUnusedInvariants(L);
510 // For completeness, inform IVUsers of the IV use in the newly-created
511 // loop exit test instruction.
513 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
515 // Clean up dead instructions.
516 Changed |= DeleteDeadPHIs(L->getHeader());
517 // Check a post-condition.
518 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
522 // FIXME: It is an extremely bad idea to indvar substitute anything more
523 // complex than affine induction variables. Doing so will put expensive
524 // polynomial evaluations inside of the loop, and the str reduction pass
525 // currently can only reduce affine polynomials. For now just disable
526 // indvar subst on anything more complex than an affine addrec, unless
527 // it can be expanded to a trivial value.
528 static bool isSafe(const SCEV *S, const Loop *L) {
529 // Loop-invariant values are safe.
530 if (S->isLoopInvariant(L)) return true;
532 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
533 // to transform them into efficient code.
534 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
535 return AR->isAffine();
537 // An add is safe it all its operands are safe.
538 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
539 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
540 E = Commutative->op_end(); I != E; ++I)
541 if (!isSafe(*I, L)) return false;
545 // A cast is safe if its operand is.
546 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
547 return isSafe(C->getOperand(), L);
549 // A udiv is safe if its operands are.
550 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
551 return isSafe(UD->getLHS(), L) &&
552 isSafe(UD->getRHS(), L);
554 // SCEVUnknown is always safe.
555 if (isa<SCEVUnknown>(S))
558 // Nothing else is safe.
562 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
563 SmallVector<WeakVH, 16> DeadInsts;
565 // Rewrite all induction variable expressions in terms of the canonical
566 // induction variable.
568 // If there were induction variables of other sizes or offsets, manually
569 // add the offsets to the primary induction variable and cast, avoiding
570 // the need for the code evaluation methods to insert induction variables
571 // of different sizes.
572 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
573 Value *Op = UI->getOperandValToReplace();
574 const Type *UseTy = Op->getType();
575 Instruction *User = UI->getUser();
577 // Compute the final addrec to expand into code.
578 const SCEV *AR = IU->getReplacementExpr(*UI);
580 // Evaluate the expression out of the loop, if possible.
581 if (!L->contains(UI->getUser())) {
582 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
583 if (ExitVal->isLoopInvariant(L))
587 // FIXME: It is an extremely bad idea to indvar substitute anything more
588 // complex than affine induction variables. Doing so will put expensive
589 // polynomial evaluations inside of the loop, and the str reduction pass
590 // currently can only reduce affine polynomials. For now just disable
591 // indvar subst on anything more complex than an affine addrec, unless
592 // it can be expanded to a trivial value.
596 // Determine the insertion point for this user. By default, insert
597 // immediately before the user. The SCEVExpander class will automatically
598 // hoist loop invariants out of the loop. For PHI nodes, there may be
599 // multiple uses, so compute the nearest common dominator for the
601 Instruction *InsertPt = User;
602 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
603 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
604 if (PHI->getIncomingValue(i) == Op) {
605 if (InsertPt == User)
606 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
609 DT->findNearestCommonDominator(InsertPt->getParent(),
610 PHI->getIncomingBlock(i))
614 // Now expand it into actual Instructions and patch it into place.
615 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
617 // Inform ScalarEvolution that this value is changing. The change doesn't
618 // affect its value, but it does potentially affect which use lists the
619 // value will be on after the replacement, which affects ScalarEvolution's
620 // ability to walk use lists and drop dangling pointers when a value is
622 SE->forgetValue(User);
624 // Patch the new value into place.
626 NewVal->takeName(Op);
627 User->replaceUsesOfWith(Op, NewVal);
628 UI->setOperandValToReplace(NewVal);
629 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
630 << " into = " << *NewVal << "\n");
634 // The old value may be dead now.
635 DeadInsts.push_back(Op);
638 // Clear the rewriter cache, because values that are in the rewriter's cache
639 // can be deleted in the loop below, causing the AssertingVH in the cache to
642 // Now that we're done iterating through lists, clean up any instructions
643 // which are now dead.
644 while (!DeadInsts.empty())
645 if (Instruction *Inst =
646 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
647 RecursivelyDeleteTriviallyDeadInstructions(Inst);
650 /// If there's a single exit block, sink any loop-invariant values that
651 /// were defined in the preheader but not used inside the loop into the
652 /// exit block to reduce register pressure in the loop.
653 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
654 BasicBlock *ExitBlock = L->getExitBlock();
655 if (!ExitBlock) return;
657 BasicBlock *Preheader = L->getLoopPreheader();
658 if (!Preheader) return;
660 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
661 BasicBlock::iterator I = Preheader->getTerminator();
662 while (I != Preheader->begin()) {
664 // New instructions were inserted at the end of the preheader.
668 // Don't move instructions which might have side effects, since the side
669 // effects need to complete before instructions inside the loop. Also don't
670 // move instructions which might read memory, since the loop may modify
671 // memory. Note that it's okay if the instruction might have undefined
672 // behavior: LoopSimplify guarantees that the preheader dominates the exit
674 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
677 // Skip debug info intrinsics.
678 if (isa<DbgInfoIntrinsic>(I))
681 // Don't sink static AllocaInsts out of the entry block, which would
682 // turn them into dynamic allocas!
683 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
684 if (AI->isStaticAlloca())
687 // Determine if there is a use in or before the loop (direct or
689 bool UsedInLoop = false;
690 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
692 BasicBlock *UseBB = cast<Instruction>(UI)->getParent();
693 if (PHINode *P = dyn_cast<PHINode>(UI)) {
695 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
696 UseBB = P->getIncomingBlock(i);
698 if (UseBB == Preheader || L->contains(UseBB)) {
704 // If there is, the def must remain in the preheader.
708 // Otherwise, sink it to the exit block.
709 Instruction *ToMove = I;
712 if (I != Preheader->begin()) {
713 // Skip debug info intrinsics.
716 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
718 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
724 ToMove->moveBefore(InsertPt);
730 /// ConvertToSInt - Convert APF to an integer, if possible.
731 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
732 bool isExact = false;
733 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
735 // See if we can convert this to an int64_t
737 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
738 &isExact) != APFloat::opOK || !isExact)
744 /// HandleFloatingPointIV - If the loop has floating induction variable
745 /// then insert corresponding integer induction variable if possible.
747 /// for(double i = 0; i < 10000; ++i)
749 /// is converted into
750 /// for(int i = 0; i < 10000; ++i)
753 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
754 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
755 unsigned BackEdge = IncomingEdge^1;
757 // Check incoming value.
758 ConstantFP *InitValueVal =
759 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
762 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
765 // Check IV increment. Reject this PN if increment operation is not
766 // an add or increment value can not be represented by an integer.
767 BinaryOperator *Incr =
768 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
769 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
771 // If this is not an add of the PHI with a constantfp, or if the constant fp
772 // is not an integer, bail out.
773 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
775 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
776 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
779 // Check Incr uses. One user is PN and the other user is an exit condition
780 // used by the conditional terminator.
781 Value::use_iterator IncrUse = Incr->use_begin();
782 Instruction *U1 = cast<Instruction>(IncrUse++);
783 if (IncrUse == Incr->use_end()) return;
784 Instruction *U2 = cast<Instruction>(IncrUse++);
785 if (IncrUse != Incr->use_end()) return;
787 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
788 // only used by a branch, we can't transform it.
789 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
791 Compare = dyn_cast<FCmpInst>(U2);
792 if (Compare == 0 || !Compare->hasOneUse() ||
793 !isa<BranchInst>(Compare->use_back()))
796 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
798 // We need to verify that the branch actually controls the iteration count
799 // of the loop. If not, the new IV can overflow and no one will notice.
800 // The branch block must be in the loop and one of the successors must be out
802 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
803 if (!L->contains(TheBr->getParent()) ||
804 (L->contains(TheBr->getSuccessor(0)) &&
805 L->contains(TheBr->getSuccessor(1))))
809 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
811 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
813 if (ExitValueVal == 0 ||
814 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
817 // Find new predicate for integer comparison.
818 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
819 switch (Compare->getPredicate()) {
820 default: return; // Unknown comparison.
821 case CmpInst::FCMP_OEQ:
822 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
823 case CmpInst::FCMP_ONE:
824 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
825 case CmpInst::FCMP_OGT:
826 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
827 case CmpInst::FCMP_OGE:
828 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
829 case CmpInst::FCMP_OLT:
830 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
831 case CmpInst::FCMP_OLE:
832 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
835 // We convert the floating point induction variable to a signed i32 value if
836 // we can. This is only safe if the comparison will not overflow in a way
837 // that won't be trapped by the integer equivalent operations. Check for this
839 // TODO: We could use i64 if it is native and the range requires it.
841 // The start/stride/exit values must all fit in signed i32.
842 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
845 // If not actually striding (add x, 0.0), avoid touching the code.
849 // Positive and negative strides have different safety conditions.
851 // If we have a positive stride, we require the init to be less than the
852 // exit value and an equality or less than comparison.
853 if (InitValue >= ExitValue ||
854 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
857 uint32_t Range = uint32_t(ExitValue-InitValue);
858 if (NewPred == CmpInst::ICMP_SLE) {
859 // Normalize SLE -> SLT, check for infinite loop.
860 if (++Range == 0) return; // Range overflows.
863 unsigned Leftover = Range % uint32_t(IncValue);
865 // If this is an equality comparison, we require that the strided value
866 // exactly land on the exit value, otherwise the IV condition will wrap
867 // around and do things the fp IV wouldn't.
868 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
872 // If the stride would wrap around the i32 before exiting, we can't
874 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
878 // If we have a negative stride, we require the init to be greater than the
879 // exit value and an equality or greater than comparison.
880 if (InitValue >= ExitValue ||
881 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
884 uint32_t Range = uint32_t(InitValue-ExitValue);
885 if (NewPred == CmpInst::ICMP_SGE) {
886 // Normalize SGE -> SGT, check for infinite loop.
887 if (++Range == 0) return; // Range overflows.
890 unsigned Leftover = Range % uint32_t(-IncValue);
892 // If this is an equality comparison, we require that the strided value
893 // exactly land on the exit value, otherwise the IV condition will wrap
894 // around and do things the fp IV wouldn't.
895 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
899 // If the stride would wrap around the i32 before exiting, we can't
901 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
905 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
907 // Insert new integer induction variable.
908 PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN);
909 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
910 PN->getIncomingBlock(IncomingEdge));
913 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
914 Incr->getName()+".int", Incr);
915 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
917 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
918 ConstantInt::get(Int32Ty, ExitValue),
921 // In the following deletions, PN may become dead and may be deleted.
922 // Use a WeakVH to observe whether this happens.
925 // Delete the old floating point exit comparison. The branch starts using the
927 NewCompare->takeName(Compare);
928 Compare->replaceAllUsesWith(NewCompare);
929 RecursivelyDeleteTriviallyDeadInstructions(Compare);
931 // Delete the old floating point increment.
932 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
933 RecursivelyDeleteTriviallyDeadInstructions(Incr);
935 // If the FP induction variable still has uses, this is because something else
936 // in the loop uses its value. In order to canonicalize the induction
937 // variable, we chose to eliminate the IV and rewrite it in terms of an
940 // We give preference to sitofp over uitofp because it is faster on most
943 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
944 PN->getParent()->getFirstNonPHI());
945 PN->replaceAllUsesWith(Conv);
946 RecursivelyDeleteTriviallyDeadInstructions(PN);
949 // Add a new IVUsers entry for the newly-created integer PHI.
950 IU->AddUsersIfInteresting(NewPHI);