1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
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 file implements induction variable simplification. It does
11 // not define any actual pass or policy, but provides a single function to
12 // simplify a loop's induction variables based on ScalarEvolution.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "indvars"
18 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/IVUsers.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
37 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
38 STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
39 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
40 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
43 /// SimplifyIndvar - This is a utility for simplifying induction variables
44 /// based on ScalarEvolution. It is the primary instrument of the
45 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
46 /// other loop passes that preserve SCEV.
47 class SimplifyIndvar {
51 const DataLayout *TD; // May be NULL
53 SmallVectorImpl<WeakVH> &DeadInsts;
58 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
59 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
61 LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
63 TD(LPM->getAnalysisIfAvailable<DataLayout>()),
66 assert(LI && "IV simplification requires LoopInfo");
69 bool hasChanged() const { return Changed; }
71 /// Iteratively perform simplification on a worklist of users of the
72 /// specified induction variable. This is the top-level driver that applies
73 /// all simplicitions to users of an IV.
74 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = NULL);
76 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
78 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
79 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
80 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
83 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
84 const DominatorTree *DT);
88 /// foldIVUser - Fold an IV operand into its use. This removes increments of an
89 /// aligned IV when used by a instruction that ignores the low bits.
91 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
93 /// Return the operand of IVOperand for this induction variable if IVOperand can
94 /// be folded (in case more folding opportunities have been exposed).
95 /// Otherwise return null.
96 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
99 const SCEV *FoldedExpr = 0;
100 switch (UseInst->getOpcode()) {
103 case Instruction::UDiv:
104 case Instruction::LShr:
105 // We're only interested in the case where we know something about
106 // the numerator and have a constant denominator.
107 if (IVOperand != UseInst->getOperand(OperIdx) ||
108 !isa<ConstantInt>(UseInst->getOperand(1)))
111 // Attempt to fold a binary operator with constant operand.
112 // e.g. ((I + 1) >> 2) => I >> 2
113 if (!isa<BinaryOperator>(IVOperand)
114 || !isa<ConstantInt>(IVOperand->getOperand(1)))
117 IVSrc = IVOperand->getOperand(0);
118 // IVSrc must be the (SCEVable) IV, since the other operand is const.
119 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
121 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
122 if (UseInst->getOpcode() == Instruction::LShr) {
123 // Get a constant for the divisor. See createSCEV.
124 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
125 if (D->getValue().uge(BitWidth))
128 D = ConstantInt::get(UseInst->getContext(),
129 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
131 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
133 // We have something that might fold it's operand. Compare SCEVs.
134 if (!SE->isSCEVable(UseInst->getType()))
137 // Bypass the operand if SCEV can prove it has no effect.
138 if (SE->getSCEV(UseInst) != FoldedExpr)
141 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
142 << " -> " << *UseInst << '\n');
144 UseInst->setOperand(OperIdx, IVSrc);
145 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
149 if (IVOperand->use_empty())
150 DeadInsts.push_back(IVOperand);
154 /// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
155 /// comparisons against an induction variable.
156 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
157 unsigned IVOperIdx = 0;
158 ICmpInst::Predicate Pred = ICmp->getPredicate();
159 if (IVOperand != ICmp->getOperand(0)) {
161 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
163 Pred = ICmpInst::getSwappedPredicate(Pred);
166 // Get the SCEVs for the ICmp operands.
167 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
168 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
170 // Simplify unnecessary loops away.
171 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
172 S = SE->getSCEVAtScope(S, ICmpLoop);
173 X = SE->getSCEVAtScope(X, ICmpLoop);
175 // If the condition is always true or always false, replace it with
177 if (SE->isKnownPredicate(Pred, S, X))
178 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
179 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
180 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
184 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
187 DeadInsts.push_back(ICmp);
190 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
191 /// remainder operations operating on an induction variable.
192 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
195 // We're only interested in the case where we know something about
197 if (IVOperand != Rem->getOperand(0))
200 // Get the SCEVs for the ICmp operands.
201 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
202 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
204 // Simplify unnecessary loops away.
205 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
206 S = SE->getSCEVAtScope(S, ICmpLoop);
207 X = SE->getSCEVAtScope(X, ICmpLoop);
209 // i % n --> i if i is in [0,n).
210 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
211 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
213 Rem->replaceAllUsesWith(Rem->getOperand(0));
215 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
216 const SCEV *LessOne =
217 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
218 if (IsSigned && !SE->isKnownNonNegative(LessOne))
221 if (!SE->isKnownPredicate(IsSigned ?
222 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
226 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
227 Rem->getOperand(0), Rem->getOperand(1));
229 SelectInst::Create(ICmp,
230 ConstantInt::get(Rem->getType(), 0),
231 Rem->getOperand(0), "tmp", Rem);
232 Rem->replaceAllUsesWith(Sel);
235 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
238 DeadInsts.push_back(Rem);
241 /// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
242 /// no observable side-effect given the range of IV values.
243 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
244 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
245 Instruction *IVOperand) {
246 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
247 eliminateIVComparison(ICmp, IVOperand);
250 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
251 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
252 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
253 eliminateIVRemainder(Rem, IVOperand, IsSigned);
258 // Eliminate any operation that SCEV can prove is an identity function.
259 if (!SE->isSCEVable(UseInst->getType()) ||
260 (UseInst->getType() != IVOperand->getType()) ||
261 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
264 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
266 UseInst->replaceAllUsesWith(IVOperand);
269 DeadInsts.push_back(UseInst);
273 /// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
274 /// analysis and optimization.
276 /// \return A new value representing the non-overflowing add if possible,
277 /// otherwise return the original value.
278 Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
279 const DominatorTree *DT) {
280 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
281 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
284 // Find a branch guarded by the overflow check.
285 BranchInst *Branch = 0;
286 Instruction *AddVal = 0;
287 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
289 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(*UI)) {
290 if (ExtractInst->getNumIndices() != 1)
292 if (ExtractInst->getIndices()[0] == 0)
293 AddVal = ExtractInst;
294 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
295 Branch = dyn_cast<BranchInst>(ExtractInst->use_back());
298 if (!AddVal || !Branch)
301 BasicBlock *ContinueBB = Branch->getSuccessor(1);
302 if (llvm::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
305 // Check if all users of the add are provably NSW.
307 for (Value::use_iterator UI = AddVal->use_begin(), E = AddVal->use_end();
309 if (Instruction *UseInst = dyn_cast<Instruction>(*UI)) {
310 BasicBlock *UseBB = UseInst->getParent();
311 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
312 UseBB = PHI->getIncomingBlock(UI);
313 if (!DT->dominates(ContinueBB, UseBB)) {
323 IRBuilder<> Builder(IVUser);
324 Instruction *AddInst = dyn_cast<Instruction>(
325 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
327 // The caller expects the new add to have the same form as the intrinsic. The
328 // IV operand position must be the same.
329 assert((AddInst->getOpcode() == Instruction::Add &&
330 AddInst->getOperand(0) == II->getOperand(0)) &&
331 "Bad add instruction created from overflow intrinsic.");
333 AddVal->replaceAllUsesWith(AddInst);
334 DeadInsts.push_back(AddVal);
338 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
340 static void pushIVUsers(
342 SmallPtrSet<Instruction*,16> &Simplified,
343 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
345 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
347 Instruction *User = cast<Instruction>(*UI);
349 // Avoid infinite or exponential worklist processing.
350 // Also ensure unique worklist users.
351 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
353 if (User != Def && Simplified.insert(User))
354 SimpleIVUsers.push_back(std::make_pair(User, Def));
358 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
359 /// expression in terms of that IV.
361 /// This is similar to IVUsers' isInteresting() but processes each instruction
362 /// non-recursively when the operand is already known to be a simpleIVUser.
364 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
365 if (!SE->isSCEVable(I->getType()))
368 // Get the symbolic expression for this instruction.
369 const SCEV *S = SE->getSCEV(I);
371 // Only consider affine recurrences.
372 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
373 if (AR && AR->getLoop() == L)
379 /// simplifyUsers - Iteratively perform simplification on a worklist of users
380 /// of the specified induction variable. Each successive simplification may push
381 /// more users which may themselves be candidates for simplification.
383 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
384 /// instructions in-place during analysis. Rather than rewriting induction
385 /// variables bottom-up from their users, it transforms a chain of IVUsers
386 /// top-down, updating the IR only when it encouters a clear optimization
389 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
391 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
392 if (!SE->isSCEVable(CurrIV->getType()))
395 // Instructions processed by SimplifyIndvar for CurrIV.
396 SmallPtrSet<Instruction*,16> Simplified;
398 // Use-def pairs if IV users waiting to be processed for CurrIV.
399 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
401 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
402 // called multiple times for the same LoopPhi. This is the proper thing to
403 // do for loop header phis that use each other.
404 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
406 while (!SimpleIVUsers.empty()) {
407 std::pair<Instruction*, Instruction*> UseOper =
408 SimpleIVUsers.pop_back_val();
409 Instruction *UseInst = UseOper.first;
411 // Bypass back edges to avoid extra work.
412 if (UseInst == CurrIV) continue;
414 if (V && V->shouldSplitOverflowInstrinsics()) {
415 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
420 Instruction *IVOperand = UseOper.second;
421 for (unsigned N = 0; IVOperand; ++N) {
422 assert(N <= Simplified.size() && "runaway iteration");
424 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
426 break; // done folding
427 IVOperand = dyn_cast<Instruction>(NewOper);
432 if (eliminateIVUser(UseOper.first, IVOperand)) {
433 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
436 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
441 if (isSimpleIVUser(UseOper.first, L, SE)) {
442 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
449 void IVVisitor::anchor() { }
451 /// simplifyUsersOfIV - Simplify instructions that use this induction variable
452 /// by using ScalarEvolution to analyze the IV's recurrence.
453 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
454 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
456 LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
457 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
458 SIV.simplifyUsers(CurrIV, V);
459 return SIV.hasChanged();
462 /// simplifyLoopIVs - Simplify users of induction variables within this
463 /// loop. This does not actually change or add IVs.
464 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
465 SmallVectorImpl<WeakVH> &Dead) {
466 bool Changed = false;
467 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
468 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);