LLVM API Documentation

SimplifyIndVar.cpp
Go to the documentation of this file.
00001 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements induction variable simplification. It does
00011 // not define any actual pass or policy, but provides a single function to
00012 // simplify a loop's induction variables based on ScalarEvolution.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #define DEBUG_TYPE "indvars"
00017 
00018 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
00019 #include "llvm/ADT/SmallVector.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/Analysis/IVUsers.h"
00022 #include "llvm/Analysis/LoopInfo.h"
00023 #include "llvm/Analysis/LoopPass.h"
00024 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/Support/CommandLine.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 
00031 using namespace llvm;
00032 
00033 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
00034 STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
00035 STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
00036 STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
00037 
00038 namespace {
00039   /// SimplifyIndvar - This is a utility for simplifying induction variables
00040   /// based on ScalarEvolution. It is the primary instrument of the
00041   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
00042   /// other loop passes that preserve SCEV.
00043   class SimplifyIndvar {
00044     Loop             *L;
00045     LoopInfo         *LI;
00046     ScalarEvolution  *SE;
00047     const DataLayout *TD; // May be NULL
00048 
00049     SmallVectorImpl<WeakVH> &DeadInsts;
00050 
00051     bool Changed;
00052 
00053   public:
00054     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM,
00055                    SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) :
00056       L(Loop),
00057       LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
00058       SE(SE),
00059       TD(LPM->getAnalysisIfAvailable<DataLayout>()),
00060       DeadInsts(Dead),
00061       Changed(false) {
00062       assert(LI && "IV simplification requires LoopInfo");
00063     }
00064 
00065     bool hasChanged() const { return Changed; }
00066 
00067     /// Iteratively perform simplification on a worklist of users of the
00068     /// specified induction variable. This is the top-level driver that applies
00069     /// all simplicitions to users of an IV.
00070     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = NULL);
00071 
00072     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
00073 
00074     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
00075     void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
00076     void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
00077                               bool IsSigned);
00078   };
00079 }
00080 
00081 /// foldIVUser - Fold an IV operand into its use.  This removes increments of an
00082 /// aligned IV when used by a instruction that ignores the low bits.
00083 ///
00084 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
00085 ///
00086 /// Return the operand of IVOperand for this induction variable if IVOperand can
00087 /// be folded (in case more folding opportunities have been exposed).
00088 /// Otherwise return null.
00089 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
00090   Value *IVSrc = 0;
00091   unsigned OperIdx = 0;
00092   const SCEV *FoldedExpr = 0;
00093   switch (UseInst->getOpcode()) {
00094   default:
00095     return 0;
00096   case Instruction::UDiv:
00097   case Instruction::LShr:
00098     // We're only interested in the case where we know something about
00099     // the numerator and have a constant denominator.
00100     if (IVOperand != UseInst->getOperand(OperIdx) ||
00101         !isa<ConstantInt>(UseInst->getOperand(1)))
00102       return 0;
00103 
00104     // Attempt to fold a binary operator with constant operand.
00105     // e.g. ((I + 1) >> 2) => I >> 2
00106     if (!isa<BinaryOperator>(IVOperand)
00107         || !isa<ConstantInt>(IVOperand->getOperand(1)))
00108       return 0;
00109 
00110     IVSrc = IVOperand->getOperand(0);
00111     // IVSrc must be the (SCEVable) IV, since the other operand is const.
00112     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
00113 
00114     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
00115     if (UseInst->getOpcode() == Instruction::LShr) {
00116       // Get a constant for the divisor. See createSCEV.
00117       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
00118       if (D->getValue().uge(BitWidth))
00119         return 0;
00120 
00121       D = ConstantInt::get(UseInst->getContext(),
00122                            APInt(BitWidth, 1).shl(D->getZExtValue()));
00123     }
00124     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
00125   }
00126   // We have something that might fold it's operand. Compare SCEVs.
00127   if (!SE->isSCEVable(UseInst->getType()))
00128     return 0;
00129 
00130   // Bypass the operand if SCEV can prove it has no effect.
00131   if (SE->getSCEV(UseInst) != FoldedExpr)
00132     return 0;
00133 
00134   DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
00135         << " -> " << *UseInst << '\n');
00136 
00137   UseInst->setOperand(OperIdx, IVSrc);
00138   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
00139 
00140   ++NumElimOperand;
00141   Changed = true;
00142   if (IVOperand->use_empty())
00143     DeadInsts.push_back(IVOperand);
00144   return IVSrc;
00145 }
00146 
00147 /// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless
00148 /// comparisons against an induction variable.
00149 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
00150   unsigned IVOperIdx = 0;
00151   ICmpInst::Predicate Pred = ICmp->getPredicate();
00152   if (IVOperand != ICmp->getOperand(0)) {
00153     // Swapped
00154     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
00155     IVOperIdx = 1;
00156     Pred = ICmpInst::getSwappedPredicate(Pred);
00157   }
00158 
00159   // Get the SCEVs for the ICmp operands.
00160   const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
00161   const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
00162 
00163   // Simplify unnecessary loops away.
00164   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
00165   S = SE->getSCEVAtScope(S, ICmpLoop);
00166   X = SE->getSCEVAtScope(X, ICmpLoop);
00167 
00168   // If the condition is always true or always false, replace it with
00169   // a constant value.
00170   if (SE->isKnownPredicate(Pred, S, X))
00171     ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
00172   else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
00173     ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
00174   else
00175     return;
00176 
00177   DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
00178   ++NumElimCmp;
00179   Changed = true;
00180   DeadInsts.push_back(ICmp);
00181 }
00182 
00183 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless
00184 /// remainder operations operating on an induction variable.
00185 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
00186                                       Value *IVOperand,
00187                                       bool IsSigned) {
00188   // We're only interested in the case where we know something about
00189   // the numerator.
00190   if (IVOperand != Rem->getOperand(0))
00191     return;
00192 
00193   // Get the SCEVs for the ICmp operands.
00194   const SCEV *S = SE->getSCEV(Rem->getOperand(0));
00195   const SCEV *X = SE->getSCEV(Rem->getOperand(1));
00196 
00197   // Simplify unnecessary loops away.
00198   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
00199   S = SE->getSCEVAtScope(S, ICmpLoop);
00200   X = SE->getSCEVAtScope(X, ICmpLoop);
00201 
00202   // i % n  -->  i  if i is in [0,n).
00203   if ((!IsSigned || SE->isKnownNonNegative(S)) &&
00204       SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
00205                            S, X))
00206     Rem->replaceAllUsesWith(Rem->getOperand(0));
00207   else {
00208     // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
00209     const SCEV *LessOne =
00210       SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
00211     if (IsSigned && !SE->isKnownNonNegative(LessOne))
00212       return;
00213 
00214     if (!SE->isKnownPredicate(IsSigned ?
00215                               ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
00216                               LessOne, X))
00217       return;
00218 
00219     ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
00220                                   Rem->getOperand(0), Rem->getOperand(1));
00221     SelectInst *Sel =
00222       SelectInst::Create(ICmp,
00223                          ConstantInt::get(Rem->getType(), 0),
00224                          Rem->getOperand(0), "tmp", Rem);
00225     Rem->replaceAllUsesWith(Sel);
00226   }
00227 
00228   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
00229   ++NumElimRem;
00230   Changed = true;
00231   DeadInsts.push_back(Rem);
00232 }
00233 
00234 /// eliminateIVUser - Eliminate an operation that consumes a simple IV and has
00235 /// no observable side-effect given the range of IV values.
00236 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
00237 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
00238                                      Instruction *IVOperand) {
00239   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
00240     eliminateIVComparison(ICmp, IVOperand);
00241     return true;
00242   }
00243   if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
00244     bool IsSigned = Rem->getOpcode() == Instruction::SRem;
00245     if (IsSigned || Rem->getOpcode() == Instruction::URem) {
00246       eliminateIVRemainder(Rem, IVOperand, IsSigned);
00247       return true;
00248     }
00249   }
00250 
00251   // Eliminate any operation that SCEV can prove is an identity function.
00252   if (!SE->isSCEVable(UseInst->getType()) ||
00253       (UseInst->getType() != IVOperand->getType()) ||
00254       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
00255     return false;
00256 
00257   DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
00258 
00259   UseInst->replaceAllUsesWith(IVOperand);
00260   ++NumElimIdentity;
00261   Changed = true;
00262   DeadInsts.push_back(UseInst);
00263   return true;
00264 }
00265 
00266 /// pushIVUsers - Add all uses of Def to the current IV's worklist.
00267 ///
00268 static void pushIVUsers(
00269   Instruction *Def,
00270   SmallPtrSet<Instruction*,16> &Simplified,
00271   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
00272 
00273   for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end();
00274        UI != E; ++UI) {
00275     Instruction *User = cast<Instruction>(*UI);
00276 
00277     // Avoid infinite or exponential worklist processing.
00278     // Also ensure unique worklist users.
00279     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
00280     // self edges first.
00281     if (User != Def && Simplified.insert(User))
00282       SimpleIVUsers.push_back(std::make_pair(User, Def));
00283   }
00284 }
00285 
00286 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV
00287 /// expression in terms of that IV.
00288 ///
00289 /// This is similar to IVUsers' isInteresting() but processes each instruction
00290 /// non-recursively when the operand is already known to be a simpleIVUser.
00291 ///
00292 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
00293   if (!SE->isSCEVable(I->getType()))
00294     return false;
00295 
00296   // Get the symbolic expression for this instruction.
00297   const SCEV *S = SE->getSCEV(I);
00298 
00299   // Only consider affine recurrences.
00300   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
00301   if (AR && AR->getLoop() == L)
00302     return true;
00303 
00304   return false;
00305 }
00306 
00307 /// simplifyUsers - Iteratively perform simplification on a worklist of users
00308 /// of the specified induction variable. Each successive simplification may push
00309 /// more users which may themselves be candidates for simplification.
00310 ///
00311 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
00312 /// instructions in-place during analysis. Rather than rewriting induction
00313 /// variables bottom-up from their users, it transforms a chain of IVUsers
00314 /// top-down, updating the IR only when it encouters a clear optimization
00315 /// opportunitiy.
00316 ///
00317 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
00318 ///
00319 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
00320   if (!SE->isSCEVable(CurrIV->getType()))
00321     return;
00322 
00323   // Instructions processed by SimplifyIndvar for CurrIV.
00324   SmallPtrSet<Instruction*,16> Simplified;
00325 
00326   // Use-def pairs if IV users waiting to be processed for CurrIV.
00327   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
00328 
00329   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
00330   // called multiple times for the same LoopPhi. This is the proper thing to
00331   // do for loop header phis that use each other.
00332   pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
00333 
00334   while (!SimpleIVUsers.empty()) {
00335     std::pair<Instruction*, Instruction*> UseOper =
00336       SimpleIVUsers.pop_back_val();
00337     // Bypass back edges to avoid extra work.
00338     if (UseOper.first == CurrIV) continue;
00339 
00340     Instruction *IVOperand = UseOper.second;
00341     for (unsigned N = 0; IVOperand; ++N) {
00342       assert(N <= Simplified.size() && "runaway iteration");
00343 
00344       Value *NewOper = foldIVUser(UseOper.first, IVOperand);
00345       if (!NewOper)
00346         break; // done folding
00347       IVOperand = dyn_cast<Instruction>(NewOper);
00348     }
00349     if (!IVOperand)
00350       continue;
00351 
00352     if (eliminateIVUser(UseOper.first, IVOperand)) {
00353       pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
00354       continue;
00355     }
00356     CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
00357     if (V && Cast) {
00358       V->visitCast(Cast);
00359       continue;
00360     }
00361     if (isSimpleIVUser(UseOper.first, L, SE)) {
00362       pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
00363     }
00364   }
00365 }
00366 
00367 namespace llvm {
00368 
00369 void IVVisitor::anchor() { }
00370 
00371 /// simplifyUsersOfIV - Simplify instructions that use this induction variable
00372 /// by using ScalarEvolution to analyze the IV's recurrence.
00373 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
00374                        SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
00375 {
00376   LoopInfo *LI = &LPM->getAnalysis<LoopInfo>();
00377   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead);
00378   SIV.simplifyUsers(CurrIV, V);
00379   return SIV.hasChanged();
00380 }
00381 
00382 /// simplifyLoopIVs - Simplify users of induction variables within this
00383 /// loop. This does not actually change or add IVs.
00384 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
00385                      SmallVectorImpl<WeakVH> &Dead) {
00386   bool Changed = false;
00387   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
00388     Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
00389   }
00390   return Changed;
00391 }
00392 
00393 } // namespace llvm