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/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Transforms/Utils/Local.h"
58 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
59 #include "llvm/Target/TargetData.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(NumWidened , "Number of indvars widened");
67 STATISTIC(NumInserted, "Number of canonical indvars added");
68 STATISTIC(NumReplaced, "Number of exit values replaced");
69 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
71 // DisableIVRewrite mode currently affects IVUsers, so is defined in libAnalysis
72 // and referenced here.
74 extern bool DisableIVRewrite;
78 class IndVarSimplify : public LoopPass {
84 SmallVector<WeakVH, 16> DeadInsts;
88 static char ID; // Pass identification, replacement for typeid
89 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0) {
90 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
93 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<DominatorTree>();
97 AU.addRequired<LoopInfo>();
98 AU.addRequired<ScalarEvolution>();
99 AU.addRequiredID(LoopSimplifyID);
100 AU.addRequiredID(LCSSAID);
101 AU.addRequired<IVUsers>();
102 AU.addPreserved<ScalarEvolution>();
103 AU.addPreservedID(LoopSimplifyID);
104 AU.addPreservedID(LCSSAID);
105 AU.addPreserved<IVUsers>();
106 AU.setPreservesCFG();
110 bool isValidRewrite(Value *FromVal, Value *ToVal);
112 void EliminateIVComparisons();
113 void EliminateIVRemainders();
114 void RewriteNonIntegerIVs(Loop *L);
115 const Type *WidenIVs(Loop *L, SCEVExpander &Rewriter);
117 bool canExpandBackedgeTakenCount(Loop *L,
118 const SCEV *BackedgeTakenCount);
120 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
122 SCEVExpander &Rewriter);
124 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
126 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
128 void SinkUnusedInvariants(Loop *L);
130 void HandleFloatingPointIV(Loop *L, PHINode *PH);
134 char IndVarSimplify::ID = 0;
135 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
136 "Induction Variable Simplification", false, false)
137 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
138 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
139 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
140 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
141 INITIALIZE_PASS_DEPENDENCY(LCSSA)
142 INITIALIZE_PASS_DEPENDENCY(IVUsers)
143 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
144 "Induction Variable Simplification", false, false)
146 Pass *llvm::createIndVarSimplifyPass() {
147 return new IndVarSimplify();
150 /// isValidRewrite - Return true if the SCEV expansion generated by the
151 /// rewriter can replace the original value. SCEV guarantees that it
152 /// produces the same value, but the way it is produced may be illegal IR.
153 /// Ideally, this function will only be called for verification.
154 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
155 // If an SCEV expression subsumed multiple pointers, its expansion could
156 // reassociate the GEP changing the base pointer. This is illegal because the
157 // final address produced by a GEP chain must be inbounds relative to its
158 // underlying object. Otherwise basic alias analysis, among other things,
159 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
160 // producing an expression involving multiple pointers. Until then, we must
163 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
164 // because it understands lcssa phis while SCEV does not.
165 Value *FromPtr = FromVal;
166 Value *ToPtr = ToVal;
167 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
168 FromPtr = GEP->getPointerOperand();
170 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
171 ToPtr = GEP->getPointerOperand();
173 if (FromPtr != FromVal || ToPtr != ToVal) {
174 // Quickly check the common case
175 if (FromPtr == ToPtr)
178 // SCEV may have rewritten an expression that produces the GEP's pointer
179 // operand. That's ok as long as the pointer operand has the same base
180 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
181 // base of a recurrence. This handles the case in which SCEV expansion
182 // converts a pointer type recurrence into a nonrecurrent pointer base
183 // indexed by an integer recurrence.
184 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
185 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
186 if (FromBase == ToBase)
189 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
190 << *FromBase << " != " << *ToBase << "\n");
197 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
198 /// count expression can be safely and cheaply expanded into an instruction
199 /// sequence that can be used by LinearFunctionTestReplace.
200 bool IndVarSimplify::
201 canExpandBackedgeTakenCount(Loop *L,
202 const SCEV *BackedgeTakenCount) {
203 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
204 BackedgeTakenCount->isZero())
207 if (!L->getExitingBlock())
210 // Can't rewrite non-branch yet.
211 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
215 // Special case: If the backedge-taken count is a UDiv, it's very likely a
216 // UDiv that ScalarEvolution produced in order to compute a precise
217 // expression, rather than a UDiv from the user's code. If we can't find a
218 // UDiv in the code with some simple searching, assume the former and forego
219 // rewriting the loop.
220 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
221 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
222 if (!OrigCond) return false;
223 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
224 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
225 if (R != BackedgeTakenCount) {
226 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
227 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
228 if (L != BackedgeTakenCount)
235 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
236 /// loop to be a canonical != comparison against the incremented loop induction
237 /// variable. This pass is able to rewrite the exit tests of any loop where the
238 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
239 /// is actually a much broader range than just linear tests.
240 ICmpInst *IndVarSimplify::
241 LinearFunctionTestReplace(Loop *L,
242 const SCEV *BackedgeTakenCount,
244 SCEVExpander &Rewriter) {
245 assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) && "precondition");
246 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
248 // If the exiting block is not the same as the backedge block, we must compare
249 // against the preincremented value, otherwise we prefer to compare against
250 // the post-incremented value.
252 const SCEV *RHS = BackedgeTakenCount;
253 if (L->getExitingBlock() == L->getLoopLatch()) {
254 // Add one to the "backedge-taken" count to get the trip count.
255 // If this addition may overflow, we have to be more pessimistic and
256 // cast the induction variable before doing the add.
257 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
259 SE->getAddExpr(BackedgeTakenCount,
260 SE->getConstant(BackedgeTakenCount->getType(), 1));
261 if ((isa<SCEVConstant>(N) && !N->isZero()) ||
262 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
263 // No overflow. Cast the sum.
264 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
266 // Potential overflow. Cast before doing the add.
267 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
269 RHS = SE->getAddExpr(RHS,
270 SE->getConstant(IndVar->getType(), 1));
273 // The BackedgeTaken expression contains the number of times that the
274 // backedge branches to the loop header. This is one less than the
275 // number of times the loop executes, so use the incremented indvar.
276 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
278 // We have to use the preincremented value...
279 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
284 // Expand the code for the iteration count.
285 assert(SE->isLoopInvariant(RHS, L) &&
286 "Computed iteration count is not loop invariant!");
287 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
289 // Insert a new icmp_ne or icmp_eq instruction before the branch.
290 ICmpInst::Predicate Opcode;
291 if (L->contains(BI->getSuccessor(0)))
292 Opcode = ICmpInst::ICMP_NE;
294 Opcode = ICmpInst::ICMP_EQ;
296 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
297 << " LHS:" << *CmpIndVar << '\n'
299 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
300 << " RHS:\t" << *RHS << "\n");
302 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
304 Value *OrigCond = BI->getCondition();
305 // It's tempting to use replaceAllUsesWith here to fully replace the old
306 // comparison, but that's not immediately safe, since users of the old
307 // comparison may not be dominated by the new comparison. Instead, just
308 // update the branch to use the new comparison; in the common case this
309 // will make old comparison dead.
310 BI->setCondition(Cond);
311 DeadInsts.push_back(OrigCond);
318 /// RewriteLoopExitValues - Check to see if this loop has a computable
319 /// loop-invariant execution count. If so, this means that we can compute the
320 /// final value of any expressions that are recurrent in the loop, and
321 /// substitute the exit values from the loop into any instructions outside of
322 /// the loop that use the final values of the current expressions.
324 /// This is mostly redundant with the regular IndVarSimplify activities that
325 /// happen later, except that it's more powerful in some cases, because it's
326 /// able to brute-force evaluate arbitrary instructions as long as they have
327 /// constant operands at the beginning of the loop.
328 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
329 // Verify the input to the pass in already in LCSSA form.
330 assert(L->isLCSSAForm(*DT));
332 SmallVector<BasicBlock*, 8> ExitBlocks;
333 L->getUniqueExitBlocks(ExitBlocks);
335 // Find all values that are computed inside the loop, but used outside of it.
336 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
337 // the exit blocks of the loop to find them.
338 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
339 BasicBlock *ExitBB = ExitBlocks[i];
341 // If there are no PHI nodes in this exit block, then no values defined
342 // inside the loop are used on this path, skip it.
343 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
346 unsigned NumPreds = PN->getNumIncomingValues();
348 // Iterate over all of the PHI nodes.
349 BasicBlock::iterator BBI = ExitBB->begin();
350 while ((PN = dyn_cast<PHINode>(BBI++))) {
352 continue; // dead use, don't replace it
354 // SCEV only supports integer expressions for now.
355 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
358 // It's necessary to tell ScalarEvolution about this explicitly so that
359 // it can walk the def-use list and forget all SCEVs, as it may not be
360 // watching the PHI itself. Once the new exit value is in place, there
361 // may not be a def-use connection between the loop and every instruction
362 // which got a SCEVAddRecExpr for that loop.
365 // Iterate over all of the values in all the PHI nodes.
366 for (unsigned i = 0; i != NumPreds; ++i) {
367 // If the value being merged in is not integer or is not defined
368 // in the loop, skip it.
369 Value *InVal = PN->getIncomingValue(i);
370 if (!isa<Instruction>(InVal))
373 // If this pred is for a subloop, not L itself, skip it.
374 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
375 continue; // The Block is in a subloop, skip it.
377 // Check that InVal is defined in the loop.
378 Instruction *Inst = cast<Instruction>(InVal);
379 if (!L->contains(Inst))
382 // Okay, this instruction has a user outside of the current loop
383 // and varies predictably *inside* the loop. Evaluate the value it
384 // contains when the loop exits, if possible.
385 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
386 if (!SE->isLoopInvariant(ExitValue, L))
389 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
391 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
392 << " LoopVal = " << *Inst << "\n");
394 if (!isValidRewrite(Inst, ExitVal)) {
395 DeadInsts.push_back(ExitVal);
401 PN->setIncomingValue(i, ExitVal);
403 // If this instruction is dead now, delete it.
404 RecursivelyDeleteTriviallyDeadInstructions(Inst);
407 // Completely replace a single-pred PHI. This is safe, because the
408 // NewVal won't be variant in the loop, so we don't need an LCSSA phi
410 PN->replaceAllUsesWith(ExitVal);
411 RecursivelyDeleteTriviallyDeadInstructions(PN);
415 // Clone the PHI and delete the original one. This lets IVUsers and
416 // any other maps purge the original user from their records.
417 PHINode *NewPN = cast<PHINode>(PN->clone());
419 NewPN->insertBefore(PN);
420 PN->replaceAllUsesWith(NewPN);
421 PN->eraseFromParent();
426 // The insertion point instruction may have been deleted; clear it out
427 // so that the rewriter doesn't trip over it later.
428 Rewriter.clearInsertPoint();
431 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
432 // First step. Check to see if there are any floating-point recurrences.
433 // If there are, change them into integer recurrences, permitting analysis by
434 // the SCEV routines.
436 BasicBlock *Header = L->getHeader();
438 SmallVector<WeakVH, 8> PHIs;
439 for (BasicBlock::iterator I = Header->begin();
440 PHINode *PN = dyn_cast<PHINode>(I); ++I)
443 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
444 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
445 HandleFloatingPointIV(L, PN);
447 // If the loop previously had floating-point IV, ScalarEvolution
448 // may not have been able to compute a trip count. Now that we've done some
449 // re-writing, the trip count may be computable.
454 void IndVarSimplify::EliminateIVComparisons() {
455 // Look for ICmp users.
456 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
457 IVStrideUse &UI = *I;
458 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
461 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
462 ICmpInst::Predicate Pred = ICmp->getPredicate();
463 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
465 // Get the SCEVs for the ICmp operands.
466 const SCEV *S = IU->getReplacementExpr(UI);
467 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
469 // Simplify unnecessary loops away.
470 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
471 S = SE->getSCEVAtScope(S, ICmpLoop);
472 X = SE->getSCEVAtScope(X, ICmpLoop);
474 // If the condition is always true or always false, replace it with
476 if (SE->isKnownPredicate(Pred, S, X))
477 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
478 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
479 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
483 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
484 DeadInsts.push_back(ICmp);
488 void IndVarSimplify::EliminateIVRemainders() {
489 // Look for SRem and URem users.
490 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
491 IVStrideUse &UI = *I;
492 BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
495 bool isSigned = Rem->getOpcode() == Instruction::SRem;
496 if (!isSigned && Rem->getOpcode() != Instruction::URem)
499 // We're only interested in the case where we know something about
501 if (UI.getOperandValToReplace() != Rem->getOperand(0))
504 // Get the SCEVs for the ICmp operands.
505 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
506 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
508 // Simplify unnecessary loops away.
509 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
510 S = SE->getSCEVAtScope(S, ICmpLoop);
511 X = SE->getSCEVAtScope(X, ICmpLoop);
513 // i % n --> i if i is in [0,n).
514 if ((!isSigned || SE->isKnownNonNegative(S)) &&
515 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
517 Rem->replaceAllUsesWith(Rem->getOperand(0));
519 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
520 const SCEV *LessOne =
521 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
522 if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
523 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
525 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
526 Rem->getOperand(0), Rem->getOperand(1),
529 SelectInst::Create(ICmp,
530 ConstantInt::get(Rem->getType(), 0),
531 Rem->getOperand(0), "tmp", Rem);
532 Rem->replaceAllUsesWith(Sel);
537 // Inform IVUsers about the new users.
538 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
539 IU->AddUsersIfInteresting(I);
541 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
542 DeadInsts.push_back(Rem);
546 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
547 // If LoopSimplify form is not available, stay out of trouble. Some notes:
548 // - LSR currently only supports LoopSimplify-form loops. Indvars'
549 // canonicalization can be a pessimization without LSR to "clean up"
551 // - We depend on having a preheader; in particular,
552 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
553 // and we're in trouble if we can't find the induction variable even when
554 // we've manually inserted one.
555 if (!L->isLoopSimplifyForm())
558 IU = &getAnalysis<IVUsers>();
559 LI = &getAnalysis<LoopInfo>();
560 SE = &getAnalysis<ScalarEvolution>();
561 DT = &getAnalysis<DominatorTree>();
562 TD = getAnalysisIfAvailable<TargetData>();
567 // If there are any floating-point recurrences, attempt to
568 // transform them to use integer recurrences.
569 RewriteNonIntegerIVs(L);
571 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
573 // Create a rewriter object which we'll use to transform the code with.
574 SCEVExpander Rewriter(*SE);
575 if (DisableIVRewrite)
576 Rewriter.disableCanonicalMode();
578 const Type *LargestType = 0;
579 if (DisableIVRewrite) {
580 LargestType = WidenIVs(L, Rewriter);
583 // Check to see if this loop has a computable loop-invariant execution count.
584 // If so, this means that we can compute the final value of any expressions
585 // that are recurrent in the loop, and substitute the exit values from the
586 // loop into any instructions outside of the loop that use the final values of
587 // the current expressions.
589 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
590 RewriteLoopExitValues(L, Rewriter);
592 // Simplify ICmp IV users.
593 EliminateIVComparisons();
595 // Simplify SRem and URem IV users.
596 EliminateIVRemainders();
598 // Compute the type of the largest recurrence expression, and decide whether
599 // a canonical induction variable should be inserted.
600 bool NeedCannIV = false;
601 bool ExpandBECount = canExpandBackedgeTakenCount(L, BackedgeTakenCount);
603 // If we have a known trip count and a single exit block, we'll be
604 // rewriting the loop exit test condition below, which requires a
605 // canonical induction variable.
607 const Type *Ty = BackedgeTakenCount->getType();
609 SE->getTypeSizeInBits(Ty) >
610 SE->getTypeSizeInBits(LargestType))
611 LargestType = SE->getEffectiveSCEVType(Ty);
613 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
616 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
618 SE->getTypeSizeInBits(Ty) >
619 SE->getTypeSizeInBits(LargestType))
620 LargestType = SE->getEffectiveSCEVType(Ty);
622 if (!DisableIVRewrite) {
623 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
626 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
628 SE->getTypeSizeInBits(Ty) >
629 SE->getTypeSizeInBits(LargestType))
634 // Now that we know the largest of the induction variable expressions
635 // in this loop, insert a canonical induction variable of the largest size.
638 // Check to see if the loop already has any canonical-looking induction
639 // variables. If any are present and wider than the planned canonical
640 // induction variable, temporarily remove them, so that the Rewriter
641 // doesn't attempt to reuse them.
642 SmallVector<PHINode *, 2> OldCannIVs;
643 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
644 if (SE->getTypeSizeInBits(OldCannIV->getType()) >
645 SE->getTypeSizeInBits(LargestType))
646 OldCannIV->removeFromParent();
649 OldCannIVs.push_back(OldCannIV);
652 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
656 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
658 // Now that the official induction variable is established, reinsert
659 // any old canonical-looking variables after it so that the IR remains
660 // consistent. They will be deleted as part of the dead-PHI deletion at
661 // the end of the pass.
662 while (!OldCannIVs.empty()) {
663 PHINode *OldCannIV = OldCannIVs.pop_back_val();
664 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
668 // If we have a trip count expression, rewrite the loop's exit condition
669 // using it. We can currently only handle loops with a single exit.
670 ICmpInst *NewICmp = 0;
672 assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) &&
673 "canonical IV disrupted BackedgeTaken expansion");
675 "LinearFunctionTestReplace requires a canonical induction variable");
676 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
679 // Rewrite IV-derived expressions.
680 if (!DisableIVRewrite)
681 RewriteIVExpressions(L, Rewriter);
683 // Clear the rewriter cache, because values that are in the rewriter's cache
684 // can be deleted in the loop below, causing the AssertingVH in the cache to
688 // Now that we're done iterating through lists, clean up any instructions
689 // which are now dead.
690 while (!DeadInsts.empty())
691 if (Instruction *Inst =
692 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
693 RecursivelyDeleteTriviallyDeadInstructions(Inst);
695 // The Rewriter may not be used from this point on.
697 // Loop-invariant instructions in the preheader that aren't used in the
698 // loop may be sunk below the loop to reduce register pressure.
699 SinkUnusedInvariants(L);
701 // For completeness, inform IVUsers of the IV use in the newly-created
702 // loop exit test instruction.
704 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
706 // Clean up dead instructions.
707 Changed |= DeleteDeadPHIs(L->getHeader());
708 // Check a post-condition.
709 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
713 // FIXME: It is an extremely bad idea to indvar substitute anything more
714 // complex than affine induction variables. Doing so will put expensive
715 // polynomial evaluations inside of the loop, and the str reduction pass
716 // currently can only reduce affine polynomials. For now just disable
717 // indvar subst on anything more complex than an affine addrec, unless
718 // it can be expanded to a trivial value.
719 static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
720 // Loop-invariant values are safe.
721 if (SE->isLoopInvariant(S, L)) return true;
723 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
724 // to transform them into efficient code.
725 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
726 return AR->isAffine();
728 // An add is safe it all its operands are safe.
729 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
730 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
731 E = Commutative->op_end(); I != E; ++I)
732 if (!isSafe(*I, L, SE)) return false;
736 // A cast is safe if its operand is.
737 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
738 return isSafe(C->getOperand(), L, SE);
740 // A udiv is safe if its operands are.
741 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
742 return isSafe(UD->getLHS(), L, SE) &&
743 isSafe(UD->getRHS(), L, SE);
745 // SCEVUnknown is always safe.
746 if (isa<SCEVUnknown>(S))
749 // Nothing else is safe.
753 /// Widen the type of any induction variables that are sign/zero extended and
754 /// remove the [sz]ext uses.
756 /// FIXME: This may currently create extra IVs which could increase regpressure
757 /// (without LSR to cleanup).
759 /// FIXME: may factor this with RewriteIVExpressions once it stabilizes.
760 const Type *IndVarSimplify::WidenIVs(Loop *L, SCEVExpander &Rewriter) {
761 const Type *LargestType = 0;
762 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
763 Instruction *ExtInst = UI->getUser();
764 if (!isa<SExtInst>(ExtInst) && !isa<ZExtInst>(ExtInst))
766 const SCEV *AR = SE->getSCEV(ExtInst);
767 // Only widen this IV is SCEV tells us it's safe.
768 if (!isa<SCEVAddRecExpr>(AR) && !isa<SCEVAddExpr>(AR))
771 if (!L->contains(UI->getUser())) {
772 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
773 if (SE->isLoopInvariant(ExitVal, L))
777 // Only expand affine recurences.
778 if (!isSafe(AR, L, SE))
782 SE->getEffectiveSCEVType(ExtInst->getType());
784 // Only remove [sz]ext if the wide IV is still a native type.
786 // FIXME: We may be able to remove the copy of this logic in
787 // IVUsers::AddUsersIfInteresting.
788 uint64_t Width = SE->getTypeSizeInBits(Ty);
789 if (Width > 64 || (TD && !TD->isLegalInteger(Width)))
792 // Now expand it into actual Instructions and patch it into place.
794 // FIXME: avoid creating a new IV.
795 Value *NewVal = Rewriter.expandCodeFor(AR, Ty, ExtInst);
797 DEBUG(dbgs() << "INDVARS: Widened IV '" << *AR << "' " << *ExtInst << '\n'
798 << " into = " << *NewVal << "\n");
800 if (!isValidRewrite(ExtInst, NewVal)) {
801 DeadInsts.push_back(NewVal);
809 SE->getTypeSizeInBits(Ty) >
810 SE->getTypeSizeInBits(LargestType))
813 SE->forgetValue(ExtInst);
815 // Patch the new value into place.
816 if (ExtInst->hasName())
817 NewVal->takeName(ExtInst);
818 ExtInst->replaceAllUsesWith(NewVal);
820 // The old value may be dead now.
821 DeadInsts.push_back(ExtInst);
823 // UI is a linked list iterator, so AddUsersIfInteresting effectively pushes
824 // nodes on the worklist.
825 IU->AddUsersIfInteresting(ExtInst);
830 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
831 // Rewrite all induction variable expressions in terms of the canonical
832 // induction variable.
834 // If there were induction variables of other sizes or offsets, manually
835 // add the offsets to the primary induction variable and cast, avoiding
836 // the need for the code evaluation methods to insert induction variables
837 // of different sizes.
838 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
839 Value *Op = UI->getOperandValToReplace();
840 const Type *UseTy = Op->getType();
841 Instruction *User = UI->getUser();
843 // Compute the final addrec to expand into code.
844 const SCEV *AR = IU->getReplacementExpr(*UI);
846 // Evaluate the expression out of the loop, if possible.
847 if (!L->contains(UI->getUser())) {
848 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
849 if (SE->isLoopInvariant(ExitVal, L))
853 // FIXME: It is an extremely bad idea to indvar substitute anything more
854 // complex than affine induction variables. Doing so will put expensive
855 // polynomial evaluations inside of the loop, and the str reduction pass
856 // currently can only reduce affine polynomials. For now just disable
857 // indvar subst on anything more complex than an affine addrec, unless
858 // it can be expanded to a trivial value.
859 if (!isSafe(AR, L, SE))
862 // Determine the insertion point for this user. By default, insert
863 // immediately before the user. The SCEVExpander class will automatically
864 // hoist loop invariants out of the loop. For PHI nodes, there may be
865 // multiple uses, so compute the nearest common dominator for the
867 Instruction *InsertPt = User;
868 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
869 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
870 if (PHI->getIncomingValue(i) == Op) {
871 if (InsertPt == User)
872 InsertPt = PHI->getIncomingBlock(i)->getTerminator();
875 DT->findNearestCommonDominator(InsertPt->getParent(),
876 PHI->getIncomingBlock(i))
880 // Now expand it into actual Instructions and patch it into place.
881 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
883 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
884 << " into = " << *NewVal << "\n");
886 if (!isValidRewrite(Op, NewVal)) {
887 DeadInsts.push_back(NewVal);
890 // Inform ScalarEvolution that this value is changing. The change doesn't
891 // affect its value, but it does potentially affect which use lists the
892 // value will be on after the replacement, which affects ScalarEvolution's
893 // ability to walk use lists and drop dangling pointers when a value is
895 SE->forgetValue(User);
897 // Patch the new value into place.
899 NewVal->takeName(Op);
900 User->replaceUsesOfWith(Op, NewVal);
901 UI->setOperandValToReplace(NewVal);
906 // The old value may be dead now.
907 DeadInsts.push_back(Op);
911 /// If there's a single exit block, sink any loop-invariant values that
912 /// were defined in the preheader but not used inside the loop into the
913 /// exit block to reduce register pressure in the loop.
914 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
915 BasicBlock *ExitBlock = L->getExitBlock();
916 if (!ExitBlock) return;
918 BasicBlock *Preheader = L->getLoopPreheader();
919 if (!Preheader) return;
921 Instruction *InsertPt = ExitBlock->getFirstNonPHI();
922 BasicBlock::iterator I = Preheader->getTerminator();
923 while (I != Preheader->begin()) {
925 // New instructions were inserted at the end of the preheader.
929 // Don't move instructions which might have side effects, since the side
930 // effects need to complete before instructions inside the loop. Also don't
931 // move instructions which might read memory, since the loop may modify
932 // memory. Note that it's okay if the instruction might have undefined
933 // behavior: LoopSimplify guarantees that the preheader dominates the exit
935 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
938 // Skip debug info intrinsics.
939 if (isa<DbgInfoIntrinsic>(I))
942 // Don't sink static AllocaInsts out of the entry block, which would
943 // turn them into dynamic allocas!
944 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
945 if (AI->isStaticAlloca())
948 // Determine if there is a use in or before the loop (direct or
950 bool UsedInLoop = false;
951 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
954 BasicBlock *UseBB = cast<Instruction>(U)->getParent();
955 if (PHINode *P = dyn_cast<PHINode>(U)) {
957 PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
958 UseBB = P->getIncomingBlock(i);
960 if (UseBB == Preheader || L->contains(UseBB)) {
966 // If there is, the def must remain in the preheader.
970 // Otherwise, sink it to the exit block.
971 Instruction *ToMove = I;
974 if (I != Preheader->begin()) {
975 // Skip debug info intrinsics.
978 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
980 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
986 ToMove->moveBefore(InsertPt);
992 /// ConvertToSInt - Convert APF to an integer, if possible.
993 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
994 bool isExact = false;
995 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
997 // See if we can convert this to an int64_t
999 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1000 &isExact) != APFloat::opOK || !isExact)
1006 /// HandleFloatingPointIV - If the loop has floating induction variable
1007 /// then insert corresponding integer induction variable if possible.
1009 /// for(double i = 0; i < 10000; ++i)
1011 /// is converted into
1012 /// for(int i = 0; i < 10000; ++i)
1015 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1016 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1017 unsigned BackEdge = IncomingEdge^1;
1019 // Check incoming value.
1020 ConstantFP *InitValueVal =
1021 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
1024 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
1027 // Check IV increment. Reject this PN if increment operation is not
1028 // an add or increment value can not be represented by an integer.
1029 BinaryOperator *Incr =
1030 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
1031 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
1033 // If this is not an add of the PHI with a constantfp, or if the constant fp
1034 // is not an integer, bail out.
1035 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
1037 if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
1038 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
1041 // Check Incr uses. One user is PN and the other user is an exit condition
1042 // used by the conditional terminator.
1043 Value::use_iterator IncrUse = Incr->use_begin();
1044 Instruction *U1 = cast<Instruction>(*IncrUse++);
1045 if (IncrUse == Incr->use_end()) return;
1046 Instruction *U2 = cast<Instruction>(*IncrUse++);
1047 if (IncrUse != Incr->use_end()) return;
1049 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
1050 // only used by a branch, we can't transform it.
1051 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1053 Compare = dyn_cast<FCmpInst>(U2);
1054 if (Compare == 0 || !Compare->hasOneUse() ||
1055 !isa<BranchInst>(Compare->use_back()))
1058 BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
1060 // We need to verify that the branch actually controls the iteration count
1061 // of the loop. If not, the new IV can overflow and no one will notice.
1062 // The branch block must be in the loop and one of the successors must be out
1064 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1065 if (!L->contains(TheBr->getParent()) ||
1066 (L->contains(TheBr->getSuccessor(0)) &&
1067 L->contains(TheBr->getSuccessor(1))))
1071 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1073 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
1075 if (ExitValueVal == 0 ||
1076 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
1079 // Find new predicate for integer comparison.
1080 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
1081 switch (Compare->getPredicate()) {
1082 default: return; // Unknown comparison.
1083 case CmpInst::FCMP_OEQ:
1084 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
1085 case CmpInst::FCMP_ONE:
1086 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
1087 case CmpInst::FCMP_OGT:
1088 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
1089 case CmpInst::FCMP_OGE:
1090 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
1091 case CmpInst::FCMP_OLT:
1092 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
1093 case CmpInst::FCMP_OLE:
1094 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
1097 // We convert the floating point induction variable to a signed i32 value if
1098 // we can. This is only safe if the comparison will not overflow in a way
1099 // that won't be trapped by the integer equivalent operations. Check for this
1101 // TODO: We could use i64 if it is native and the range requires it.
1103 // The start/stride/exit values must all fit in signed i32.
1104 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1107 // If not actually striding (add x, 0.0), avoid touching the code.
1111 // Positive and negative strides have different safety conditions.
1113 // If we have a positive stride, we require the init to be less than the
1114 // exit value and an equality or less than comparison.
1115 if (InitValue >= ExitValue ||
1116 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1119 uint32_t Range = uint32_t(ExitValue-InitValue);
1120 if (NewPred == CmpInst::ICMP_SLE) {
1121 // Normalize SLE -> SLT, check for infinite loop.
1122 if (++Range == 0) return; // Range overflows.
1125 unsigned Leftover = Range % uint32_t(IncValue);
1127 // If this is an equality comparison, we require that the strided value
1128 // exactly land on the exit value, otherwise the IV condition will wrap
1129 // around and do things the fp IV wouldn't.
1130 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1134 // If the stride would wrap around the i32 before exiting, we can't
1135 // transform the IV.
1136 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1140 // If we have a negative stride, we require the init to be greater than the
1141 // exit value and an equality or greater than comparison.
1142 if (InitValue >= ExitValue ||
1143 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1146 uint32_t Range = uint32_t(InitValue-ExitValue);
1147 if (NewPred == CmpInst::ICMP_SGE) {
1148 // Normalize SGE -> SGT, check for infinite loop.
1149 if (++Range == 0) return; // Range overflows.
1152 unsigned Leftover = Range % uint32_t(-IncValue);
1154 // If this is an equality comparison, we require that the strided value
1155 // exactly land on the exit value, otherwise the IV condition will wrap
1156 // around and do things the fp IV wouldn't.
1157 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1161 // If the stride would wrap around the i32 before exiting, we can't
1162 // transform the IV.
1163 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1167 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
1169 // Insert new integer induction variable.
1170 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
1171 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
1172 PN->getIncomingBlock(IncomingEdge));
1175 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
1176 Incr->getName()+".int", Incr);
1177 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
1179 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1180 ConstantInt::get(Int32Ty, ExitValue),
1181 Compare->getName());
1183 // In the following deletions, PN may become dead and may be deleted.
1184 // Use a WeakVH to observe whether this happens.
1187 // Delete the old floating point exit comparison. The branch starts using the
1189 NewCompare->takeName(Compare);
1190 Compare->replaceAllUsesWith(NewCompare);
1191 RecursivelyDeleteTriviallyDeadInstructions(Compare);
1193 // Delete the old floating point increment.
1194 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1195 RecursivelyDeleteTriviallyDeadInstructions(Incr);
1197 // If the FP induction variable still has uses, this is because something else
1198 // in the loop uses its value. In order to canonicalize the induction
1199 // variable, we chose to eliminate the IV and rewrite it in terms of an
1202 // We give preference to sitofp over uitofp because it is faster on most
1205 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1206 PN->getParent()->getFirstNonPHI());
1207 PN->replaceAllUsesWith(Conv);
1208 RecursivelyDeleteTriviallyDeadInstructions(PN);
1211 // Add a new IVUsers entry for the newly-created integer PHI.
1212 IU->AddUsersIfInteresting(NewPHI);