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 EliminateIVRemainders();
102 void RewriteNonIntegerIVs(Loop *L);
104 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
106 BasicBlock *ExitingBlock,
108 SCEVExpander &Rewriter);
109 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
111 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
113 void SinkUnusedInvariants(Loop *L);
115 void HandleFloatingPointIV(Loop *L, PHINode *PH);
119 char IndVarSimplify::ID = 0;
120 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
121 "Canonicalize Induction Variables", false, false)
122 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
123 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
124 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
125 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
126 INITIALIZE_PASS_DEPENDENCY(LCSSA)
127 INITIALIZE_PASS_DEPENDENCY(IVUsers)
128 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
129 "Canonicalize Induction Variables", false, false)
131 Pass *llvm::createIndVarSimplifyPass() {
132 return new IndVarSimplify();
135 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
136 /// loop to be a canonical != comparison against the incremented loop induction
137 /// variable. This pass is able to rewrite the exit tests of any loop where the
138 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
139 /// is actually a much broader range than just linear tests.
140 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L,
141 const SCEV *BackedgeTakenCount,
143 BasicBlock *ExitingBlock,
145 SCEVExpander &Rewriter) {
146 // Special case: If the backedge-taken count is a UDiv, it's very likely a
147 // UDiv that ScalarEvolution produced in order to compute a precise
148 // expression, rather than a UDiv from the user's code. If we can't find a
149 // UDiv in the code with some simple searching, assume the former and forego
150 // rewriting the loop.
151 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
152 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
153 if (!OrigCond) return 0;
154 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
155 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
156 if (R != BackedgeTakenCount) {
157 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
158 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
159 if (L != BackedgeTakenCount)
164 // If the exiting block is not the same as the backedge block, we must compare
165 // against the preincremented value, otherwise we prefer to compare against
166 // the post-incremented value.
168 const SCEV *RHS = BackedgeTakenCount;
169 if (ExitingBlock == L->getLoopLatch()) {
170 // Add one to the "backedge-taken" count to get the trip count.
171 // If this addition may overflow, we have to be more pessimistic and
172 // cast the induction variable before doing the add.
173 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
175 SE->getAddExpr(BackedgeTakenCount,
176 SE->getConstant(BackedgeTakenCount->getType(), 1));
177 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
178 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
179 // No overflow. Cast the sum.
180 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
182 // Potential overflow. Cast before doing the add.
183 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
185 RHS = SE->getAddExpr(RHS,
186 SE->getConstant(IndVar->getType(), 1));
189 // The BackedgeTaken expression contains the number of times that the
190 // backedge branches to the loop header. This is one less than the
191 // number of times the loop executes, so use the incremented indvar.
192 CmpIndVar = IndVar->getIncomingValueForBlock(ExitingBlock);
194 // We have to use the preincremented value...
195 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
200 // Expand the code for the iteration count.
201 assert(RHS->isLoopInvariant(L) &&
202 "Computed iteration count is not loop invariant!");
203 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
205 // Insert a new icmp_ne or icmp_eq instruction before the branch.
206 ICmpInst::Predicate Opcode;
207 if (L->contains(BI->getSuccessor(0)))
208 Opcode = ICmpInst::ICMP_NE;
210 Opcode = ICmpInst::ICMP_EQ;
212 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
213 << " LHS:" << *CmpIndVar << '\n'
215 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
216 << " RHS:\t" << *RHS << "\n");
218 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
220 Value *OrigCond = BI->getCondition();
221 // It's tempting to use replaceAllUsesWith here to fully replace the old
222 // comparison, but that's not immediately safe, since users of the old
223 // comparison may not be dominated by the new comparison. Instead, just
224 // update the branch to use the new comparison; in the common case this
225 // will make old comparison dead.
226 BI->setCondition(Cond);
227 RecursivelyDeleteTriviallyDeadInstructions(OrigCond);
234 /// RewriteLoopExitValues - Check to see if this loop has a computable
235 /// loop-invariant execution count. If so, this means that we can compute the
236 /// final value of any expressions that are recurrent in the loop, and
237 /// substitute the exit values from the loop into any instructions outside of
238 /// the loop that use the final values of the current expressions.
240 /// This is mostly redundant with the regular IndVarSimplify activities that
241 /// happen later, except that it's more powerful in some cases, because it's
242 /// able to brute-force evaluate arbitrary instructions as long as they have
243 /// constant operands at the beginning of the loop.
244 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
245 SCEVExpander &Rewriter) {
246 // Verify the input to the pass in already in LCSSA form.
247 assert(L->isLCSSAForm(*DT));
249 SmallVector<BasicBlock*, 8> ExitBlocks;
250 L->getUniqueExitBlocks(ExitBlocks);
252 // Find all values that are computed inside the loop, but used outside of it.
253 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
254 // the exit blocks of the loop to find them.
255 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
256 BasicBlock *ExitBB = ExitBlocks[i];
258 // If there are no PHI nodes in this exit block, then no values defined
259 // inside the loop are used on this path, skip it.
260 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
263 unsigned NumPreds = PN->getNumIncomingValues();
265 // Iterate over all of the PHI nodes.
266 BasicBlock::iterator BBI = ExitBB->begin();
267 while ((PN = dyn_cast<PHINode>(BBI++))) {
269 continue; // dead use, don't replace it
271 // SCEV only supports integer expressions for now.
272 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
275 // It's necessary to tell ScalarEvolution about this explicitly so that
276 // it can walk the def-use list and forget all SCEVs, as it may not be
277 // watching the PHI itself. Once the new exit value is in place, there
278 // may not be a def-use connection between the loop and every instruction
279 // which got a SCEVAddRecExpr for that loop.
282 // Iterate over all of the values in all the PHI nodes.
283 for (unsigned i = 0; i != NumPreds; ++i) {
284 // If the value being merged in is not integer or is not defined
285 // in the loop, skip it.
286 Value *InVal = PN->getIncomingValue(i);
287 if (!isa<Instruction>(InVal))
290 // If this pred is for a subloop, not L itself, skip it.
291 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
292 continue; // The Block is in a subloop, skip it.
294 // Check that InVal is defined in the loop.
295 Instruction *Inst = cast<Instruction>(InVal);
296 if (!L->contains(Inst))
299 // Okay, this instruction has a user outside of the current loop
300 // and varies predictably *inside* the loop. Evaluate the value it
301 // contains when the loop exits, if possible.
302 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
303 if (!ExitValue->isLoopInvariant(L))
309 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
311 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
312 << " LoopVal = " << *Inst << "\n");
314 PN->setIncomingValue(i, ExitVal);
316 // If this instruction is dead now, delete it.
317 RecursivelyDeleteTriviallyDeadInstructions(Inst);
320 // Completely replace a single-pred PHI. This is safe, because the
321 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
323 PN->replaceAllUsesWith(ExitVal);
324 RecursivelyDeleteTriviallyDeadInstructions(PN);
328 // Clone the PHI and delete the original one. This lets IVUsers and
329 // any other maps purge the original user from their records.
330 PHINode *NewPN = cast<PHINode>(PN->clone());
332 NewPN->insertBefore(PN);
333 PN->replaceAllUsesWith(NewPN);
334 PN->eraseFromParent();
339 // The insertion point instruction may have been deleted; clear it out
340 // so that the rewriter doesn't trip over it later.
341 Rewriter.clearInsertPoint();
344 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
345 // First step. Check to see if there are any floating-point recurrences.
346 // If there are, change them into integer recurrences, permitting analysis by
347 // the SCEV routines.
349 BasicBlock *Header = L->getHeader();
351 SmallVector<WeakVH, 8> PHIs;
352 for (BasicBlock::iterator I = Header->begin();
353 PHINode *PN = dyn_cast<PHINode>(I); ++I)
356 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
357 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
358 HandleFloatingPointIV(L, PN);
360 // If the loop previously had floating-point IV, ScalarEvolution
361 // may not have been able to compute a trip count. Now that we've done some
362 // re-writing, the trip count may be computable.
367 void IndVarSimplify::EliminateIVComparisons() {
368 SmallVector<WeakVH, 16> DeadInsts;
370 // Look for ICmp users.
371 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
372 IVStrideUse &UI = *I;
373 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
376 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
377 ICmpInst::Predicate Pred = ICmp->getPredicate();
378 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
380 // Get the SCEVs for the ICmp operands.
381 const SCEV *S = IU->getReplacementExpr(UI);
382 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
384 // Simplify unnecessary loops away.
385 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
386 S = SE->getSCEVAtScope(S, ICmpLoop);
387 X = SE->getSCEVAtScope(X, ICmpLoop);
389 // If the condition is always true or always false, replace it with
391 if (SE->isKnownPredicate(Pred, S, X))
392 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
393 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
394 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
398 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
399 DeadInsts.push_back(ICmp);
402 // Now that we're done iterating through lists, clean up any instructions
403 // which are now dead.
404 while (!DeadInsts.empty())
405 if (Instruction *Inst =
406 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
407 RecursivelyDeleteTriviallyDeadInstructions(Inst);
410 void IndVarSimplify::EliminateIVRemainders() {
411 SmallVector<WeakVH, 16> DeadInsts;
413 // Look for SRem and URem users.
414 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
415 IVStrideUse &UI = *I;
416 BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
419 bool isSigned = Rem->getOpcode() == Instruction::SRem;
420 if (!isSigned && Rem->getOpcode() != Instruction::URem)
423 // We're only interested in the case where we know something about
425 if (UI.getOperandValToReplace() != Rem->getOperand(0))
428 // Get the SCEVs for the ICmp operands.
429 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
430 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
432 // Simplify unnecessary loops away.
433 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
434 S = SE->getSCEVAtScope(S, ICmpLoop);
435 X = SE->getSCEVAtScope(X, ICmpLoop);
437 // i % n --> i if i is in [0,n).
438 if ((!isSigned || SE->isKnownNonNegative(S)) &&
439 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
441 Rem->replaceAllUsesWith(Rem->getOperand(0));
443 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
444 const SCEV *LessOne =
445 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
446 if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
447 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
449 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
450 Rem->getOperand(0), Rem->getOperand(1),
453 SelectInst::Create(ICmp,
454 ConstantInt::get(Rem->getType(), 0),
455 Rem->getOperand(0), "tmp", Rem);
456 Rem->replaceAllUsesWith(Sel);
461 // Inform IVUsers about the new users.
462 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
463 IU->AddUsersIfInteresting(I);
465 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
466 DeadInsts.push_back(Rem);
469 // Now that we're done iterating through lists, clean up any instructions
470 // which are now dead.
471 while (!DeadInsts.empty())
472 if (Instruction *Inst =
473 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
474 RecursivelyDeleteTriviallyDeadInstructions(Inst);
477 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
478 // If LoopSimplify form is not available, stay out of trouble. Some notes:
479 // - LSR currently only supports LoopSimplify-form loops. Indvars'
480 // canonicalization can be a pessimization without LSR to "clean up"
482 // - We depend on having a preheader; in particular,
483 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
484 // and we're in trouble if we can't find the induction variable even when
485 // we've manually inserted one.
486 if (!L->isLoopSimplifyForm())
489 IU = &getAnalysis<IVUsers>();
490 LI = &getAnalysis<LoopInfo>();
491 SE = &getAnalysis<ScalarEvolution>();
492 DT = &getAnalysis<DominatorTree>();
495 // If there are any floating-point recurrences, attempt to
496 // transform them to use integer recurrences.
497 RewriteNonIntegerIVs(L);
499 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null
500 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
502 // Create a rewriter object which we'll use to transform the code with.
503 SCEVExpander Rewriter(*SE);
505 // Check to see if this loop has a computable loop-invariant execution count.
506 // If so, this means that we can compute the final value of any expressions
507 // that are recurrent in the loop, and substitute the exit values from the
508 // loop into any instructions outside of the loop that use the final values of
509 // the current expressions.
511 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
512 RewriteLoopExitValues(L, Rewriter);
514 // Simplify ICmp IV users.
515 EliminateIVComparisons();
517 // Simplify SRem and URem IV users.
518 EliminateIVRemainders();
520 // Compute the type of the largest recurrence expression, and decide whether
521 // a canonical induction variable should be inserted.
522 const Type *LargestType = 0;
523 bool NeedCannIV = false;
524 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
525 LargestType = BackedgeTakenCount->getType();
526 LargestType = SE->getEffectiveSCEVType(LargestType);
527 // If we have a known trip count and a single exit block, we'll be
528 // rewriting the loop exit test condition below, which requires a
529 // canonical induction variable.
533 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
535 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
537 SE->getTypeSizeInBits(Ty) >
538 SE->getTypeSizeInBits(LargestType))
543 // Now that we know the largest of the induction variable expressions
544 // in this loop, insert a canonical induction variable of the largest size.
547 // Check to see if the loop already has any canonical-looking induction
548 // variables. If any are present and wider than the planned canonical
549 // induction variable, temporarily remove them, so that the Rewriter
550 // doesn't attempt to reuse them.
551 SmallVector<PHINode *, 2> OldCannIVs;
552 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
553 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
554 SE->getTypeSizeInBits(LargestType))
555 OldCannIV->removeFromParent();
558 OldCannIVs.push_back(OldCannIV);
561 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
565 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
567 // Now that the official induction variable is established, reinsert
568 // any old canonical-looking variables after it so that the IR remains
569 // consistent. They will be deleted as part of the dead-PHI deletion at
570 // the end of the pass.
571 while (!OldCannIVs.empty()) {
572 PHINode *OldCannIV = OldCannIVs.pop_back_val();
573 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
577 // If we have a trip count expression, rewrite the loop's exit condition
578 // using it. We can currently only handle loops with a single exit.
579 ICmpInst *NewICmp = 0;
580 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
581 !BackedgeTakenCount->isZero() &&
584 "LinearFunctionTestReplace requires a canonical induction variable");
585 // Can't rewrite non-branch yet.
586 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
587 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
588 ExitingBlock, BI, Rewriter);
591 // Rewrite IV-derived expressions. Clears the rewriter cache.
592 RewriteIVExpressions(L, Rewriter);
594 // The Rewriter may not be used from this point on.
596 // Loop-invariant instructions in the preheader that aren't used in the
597 // loop may be sunk below the loop to reduce register pressure.
598 SinkUnusedInvariants(L);
600 // For completeness, inform IVUsers of the IV use in the newly-created
601 // loop exit test instruction.
603 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
605 // Clean up dead instructions.
606 Changed |= DeleteDeadPHIs(L->getHeader());
607 // Check a post-condition.
608 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
612 // FIXME: It is an extremely bad idea to indvar substitute anything more
613 // complex than affine induction variables. Doing so will put expensive
614 // polynomial evaluations inside of the loop, and the str reduction pass
615 // currently can only reduce affine polynomials. For now just disable
616 // indvar subst on anything more complex than an affine addrec, unless
617 // it can be expanded to a trivial value.
618 static bool isSafe(const SCEV *S, const Loop *L) {
619 // Loop-invariant values are safe.
620 if (S->isLoopInvariant(L)) return true;
622 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
623 // to transform them into efficient code.
624 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
625 return AR->isAffine();
627 // An add is safe it all its operands are safe.
628 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
629 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
630 E = Commutative->op_end(); I != E; ++I)
631 if (!isSafe(*I, L)) return false;
635 // A cast is safe if its operand is.
636 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
637 return isSafe(C->getOperand(), L);
639 // A udiv is safe if its operands are.
640 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
641 return isSafe(UD->getLHS(), L) &&
642 isSafe(UD->getRHS(), L);
644 // SCEVUnknown is always safe.
645 if (isa<SCEVUnknown>(S))
648 // Nothing else is safe.
652 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
653 SmallVector<WeakVH, 16> DeadInsts;
655 // Rewrite all induction variable expressions in terms of the canonical
656 // induction variable.
658 // If there were induction variables of other sizes or offsets, manually
659 // add the offsets to the primary induction variable and cast, avoiding
660 // the need for the code evaluation methods to insert induction variables
661 // of different sizes.
662 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
663 Value *Op = UI->getOperandValToReplace();
664 const Type *UseTy = Op->getType();
665 Instruction *User = UI->getUser();
667 // Compute the final addrec to expand into code.
668 const SCEV *AR = IU->getReplacementExpr(*UI);
670 // Evaluate the expression out of the loop, if possible.
671 if (!L->contains(UI->getUser())) {
672 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
673 if (ExitVal->isLoopInvariant(L))
677 // FIXME: It is an extremely bad idea to indvar substitute anything more
678 // complex than affine induction variables. Doing so will put expensive
679 // polynomial evaluations inside of the loop, and the str reduction pass
680 // currently can only reduce affine polynomials. For now just disable
681 // indvar subst on anything more complex than an affine addrec, unless
682 // it can be expanded to a trivial value.
686 // Determine the insertion point for this user. By default, insert
687 // immediately before the user. The SCEVExpander class will automatically
688 // hoist loop invariants out of the loop. For PHI nodes, there may be
689 // multiple uses, so compute the nearest common dominator for the
691 Instruction *InsertPt = User;
692 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
693 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
694 if (PHI->getIncomingValue(i) == Op) {
695 if (InsertPt == User)
696 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
699 DT->findNearestCommonDominator(InsertPt->getParent(),
700 PHI->getIncomingBlock(i))
704 // Now expand it into actual Instructions and patch it into place.
705 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
707 // Inform ScalarEvolution that this value is changing. The change doesn't
708 // affect its value, but it does potentially affect which use lists the
709 // value will be on after the replacement, which affects ScalarEvolution's
710 // ability to walk use lists and drop dangling pointers when a value is
712 SE->forgetValue(User);
714 // Patch the new value into place.
716 NewVal->takeName(Op);
717 User->replaceUsesOfWith(Op, NewVal);
718 UI->setOperandValToReplace(NewVal);
719 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
720 << " into = " << *NewVal << "\n");
724 // The old value may be dead now.
725 DeadInsts.push_back(Op);
728 // Clear the rewriter cache, because values that are in the rewriter's cache
729 // can be deleted in the loop below, causing the AssertingVH in the cache to
732 // Now that we're done iterating through lists, clean up any instructions
733 // which are now dead.
734 while (!DeadInsts.empty())
735 if (Instruction *Inst =
736 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
737 RecursivelyDeleteTriviallyDeadInstructions(Inst);
740 /// If there's a single exit block, sink any loop-invariant values that
741 /// were defined in the preheader but not used inside the loop into the
742 /// exit block to reduce register pressure in the loop.
743 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
744 BasicBlock *ExitBlock = L->getExitBlock();
745 if (!ExitBlock) return;
747 BasicBlock *Preheader = L->getLoopPreheader();
748 if (!Preheader) return;
750 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
751 BasicBlock::iterator I = Preheader->getTerminator();
752 while (I != Preheader->begin()) {
754 // New instructions were inserted at the end of the preheader.
758 // Don't move instructions which might have side effects, since the side
759 // effects need to complete before instructions inside the loop. Also don't
760 // move instructions which might read memory, since the loop may modify
761 // memory. Note that it's okay if the instruction might have undefined
762 // behavior: LoopSimplify guarantees that the preheader dominates the exit
764 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
767 // Skip debug info intrinsics.
768 if (isa<DbgInfoIntrinsic>(I))
771 // Don't sink static AllocaInsts out of the entry block, which would
772 // turn them into dynamic allocas!
773 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
774 if (AI->isStaticAlloca())
777 // Determine if there is a use in or before the loop (direct or
779 bool UsedInLoop = false;
780 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
783 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
784 if (PHINode *P = dyn_cast<PHINode>(U)) {
786 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
787 UseBB = P->getIncomingBlock(i);
789 if (UseBB == Preheader || L->contains(UseBB)) {
795 // If there is, the def must remain in the preheader.
799 // Otherwise, sink it to the exit block.
800 Instruction *ToMove = I;
803 if (I != Preheader->begin()) {
804 // Skip debug info intrinsics.
807 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
809 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
815 ToMove->moveBefore(InsertPt);
821 /// ConvertToSInt - Convert APF to an integer, if possible.
822 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
823 bool isExact = false;
824 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
826 // See if we can convert this to an int64_t
828 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
829 &isExact) != APFloat::opOK || !isExact)
835 /// HandleFloatingPointIV - If the loop has floating induction variable
836 /// then insert corresponding integer induction variable if possible.
838 /// for(double i = 0; i < 10000; ++i)
840 /// is converted into
841 /// for(int i = 0; i < 10000; ++i)
844 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
845 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
846 unsigned BackEdge = IncomingEdge^1;
848 // Check incoming value.
849 ConstantFP *InitValueVal =
850 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
853 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
856 // Check IV increment. Reject this PN if increment operation is not
857 // an add or increment value can not be represented by an integer.
858 BinaryOperator *Incr =
859 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
860 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
862 // If this is not an add of the PHI with a constantfp, or if the constant fp
863 // is not an integer, bail out.
864 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
866 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
867 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
870 // Check Incr uses. One user is PN and the other user is an exit condition
871 // used by the conditional terminator.
872 Value::use_iterator IncrUse = Incr->use_begin();
873 Instruction *U1 = cast<Instruction>(*IncrUse++);
874 if (IncrUse == Incr->use_end()) return;
875 Instruction *U2 = cast<Instruction>(*IncrUse++);
876 if (IncrUse != Incr->use_end()) return;
878 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
879 // only used by a branch, we can't transform it.
880 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
882 Compare = dyn_cast<FCmpInst>(U2);
883 if (Compare == 0 || !Compare->hasOneUse() ||
884 !isa<BranchInst>(Compare->use_back()))
887 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
889 // We need to verify that the branch actually controls the iteration count
890 // of the loop. If not, the new IV can overflow and no one will notice.
891 // The branch block must be in the loop and one of the successors must be out
893 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
894 if (!L->contains(TheBr->getParent()) ||
895 (L->contains(TheBr->getSuccessor(0)) &&
896 L->contains(TheBr->getSuccessor(1))))
900 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
902 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
904 if (ExitValueVal == 0 ||
905 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
908 // Find new predicate for integer comparison.
909 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
910 switch (Compare->getPredicate()) {
911 default: return; // Unknown comparison.
912 case CmpInst::FCMP_OEQ:
913 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
914 case CmpInst::FCMP_ONE:
915 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
916 case CmpInst::FCMP_OGT:
917 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
918 case CmpInst::FCMP_OGE:
919 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
920 case CmpInst::FCMP_OLT:
921 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
922 case CmpInst::FCMP_OLE:
923 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
926 // We convert the floating point induction variable to a signed i32 value if
927 // we can. This is only safe if the comparison will not overflow in a way
928 // that won't be trapped by the integer equivalent operations. Check for this
930 // TODO: We could use i64 if it is native and the range requires it.
932 // The start/stride/exit values must all fit in signed i32.
933 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
936 // If not actually striding (add x, 0.0), avoid touching the code.
940 // Positive and negative strides have different safety conditions.
942 // If we have a positive stride, we require the init to be less than the
943 // exit value and an equality or less than comparison.
944 if (InitValue >= ExitValue ||
945 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
948 uint32_t Range = uint32_t(ExitValue-InitValue);
949 if (NewPred == CmpInst::ICMP_SLE) {
950 // Normalize SLE -> SLT, check for infinite loop.
951 if (++Range == 0) return; // Range overflows.
954 unsigned Leftover = Range % uint32_t(IncValue);
956 // If this is an equality comparison, we require that the strided value
957 // exactly land on the exit value, otherwise the IV condition will wrap
958 // around and do things the fp IV wouldn't.
959 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
963 // If the stride would wrap around the i32 before exiting, we can't
965 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
969 // If we have a negative stride, we require the init to be greater than the
970 // exit value and an equality or greater than comparison.
971 if (InitValue >= ExitValue ||
972 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
975 uint32_t Range = uint32_t(InitValue-ExitValue);
976 if (NewPred == CmpInst::ICMP_SGE) {
977 // Normalize SGE -> SGT, check for infinite loop.
978 if (++Range == 0) return; // Range overflows.
981 unsigned Leftover = Range % uint32_t(-IncValue);
983 // If this is an equality comparison, we require that the strided value
984 // exactly land on the exit value, otherwise the IV condition will wrap
985 // around and do things the fp IV wouldn't.
986 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
990 // If the stride would wrap around the i32 before exiting, we can't
992 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
996 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
998 // Insert new integer induction variable.
999 PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN);
1000 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
1001 PN->getIncomingBlock(IncomingEdge));
1004 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
1005 Incr->getName()+".int", Incr);
1006 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
1008 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1009 ConstantInt::get(Int32Ty, ExitValue),
1010 Compare->getName());
1012 // In the following deletions, PN may become dead and may be deleted.
1013 // Use a WeakVH to observe whether this happens.
1016 // Delete the old floating point exit comparison. The branch starts using the
1018 NewCompare->takeName(Compare);
1019 Compare->replaceAllUsesWith(NewCompare);
1020 RecursivelyDeleteTriviallyDeadInstructions(Compare);
1022 // Delete the old floating point increment.
1023 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1024 RecursivelyDeleteTriviallyDeadInstructions(Incr);
1026 // If the FP induction variable still has uses, this is because something else
1027 // in the loop uses its value. In order to canonicalize the induction
1028 // variable, we chose to eliminate the IV and rewrite it in terms of an
1031 // We give preference to sitofp over uitofp because it is faster on most
1034 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1035 PN->getParent()->getFirstNonPHI());
1036 PN->replaceAllUsesWith(Conv);
1037 RecursivelyDeleteTriviallyDeadInstructions(PN);
1040 // Add a new IVUsers entry for the newly-created integer PHI.
1041 IU->AddUsersIfInteresting(NewPHI);