1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #define DEBUG_TYPE "indvars" 17 18 #include "llvm/Instructions.h" 19 #include "llvm/Analysis/Dominators.h" 20 #include "llvm/Analysis/IVUsers.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/Analysis/LoopPass.h" 23 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 28 #include "llvm/Target/TargetData.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/ADT/Statistic.h" 31 32 using namespace llvm; 33 34 STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); 35 STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); 36 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); 37 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); 38 39 namespace { 40 /// SimplifyIndvar - This is a utility for simplifying induction variables 41 /// based on ScalarEvolution. It is the primary instrument of the 42 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after 43 /// other loop passes that preserve SCEV. 44 class SimplifyIndvar { 45 Loop *L; 46 LoopInfo *LI; 47 DominatorTree *DT; 48 ScalarEvolution *SE; 49 IVUsers *IU; // NULL for DisableIVRewrite 50 const TargetData *TD; // May be NULL 51 52 SmallVectorImpl<WeakVH> &DeadInsts; 53 54 bool Changed; 55 56 public: 57 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LPPassManager *LPM, 58 SmallVectorImpl<WeakVH> &Dead, IVUsers *IVU = NULL) : 59 L(Loop), 60 LI(LPM->getAnalysisIfAvailable<LoopInfo>()), 61 SE(SE), 62 IU(IVU), 63 TD(LPM->getAnalysisIfAvailable<TargetData>()), 64 DeadInsts(Dead), 65 Changed(false) { 66 assert(LI && "IV simplification requires LoopInfo"); 67 } 68 69 bool hasChanged() const { return Changed; } 70 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); 75 76 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand); 77 78 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); 79 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand); 80 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand, 81 bool IsSigned); 82 }; 83 } 84 85 /// foldIVUser - Fold an IV operand into its use. This removes increments of an 86 /// aligned IV when used by a instruction that ignores the low bits. 87 /// 88 /// Return the operand of IVOperand for this induction variable if IVOperand can 89 /// be folded (in case more folding opportunities have been exposed). 90 /// Otherwise return null. 91 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { 92 Value *IVSrc = 0; 93 unsigned OperIdx = 0; 94 const SCEV *FoldedExpr = 0; 95 switch (UseInst->getOpcode()) { 96 default: 97 return 0; 98 case Instruction::UDiv: 99 case Instruction::LShr: 100 // We're only interested in the case where we know something about 101 // the numerator and have a constant denominator. 102 if (IVOperand != UseInst->getOperand(OperIdx) || 103 !isa<ConstantInt>(UseInst->getOperand(1))) 104 return 0; 105 106 // Attempt to fold a binary operator with constant operand. 107 // e.g. ((I + 1) >> 2) => I >> 2 108 if (IVOperand->getNumOperands() != 2 || 109 !isa<ConstantInt>(IVOperand->getOperand(1))) 110 return 0; 111 112 IVSrc = IVOperand->getOperand(0); 113 // IVSrc must be the (SCEVable) IV, since the other operand is const. 114 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); 115 116 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); 117 if (UseInst->getOpcode() == Instruction::LShr) { 118 // Get a constant for the divisor. See createSCEV. 119 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); 120 if (D->getValue().uge(BitWidth)) 121 return 0; 122 123 D = ConstantInt::get(UseInst->getContext(), 124 APInt(BitWidth, 1).shl(D->getZExtValue())); 125 } 126 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D)); 127 } 128 // We have something that might fold it's operand. Compare SCEVs. 129 if (!SE->isSCEVable(UseInst->getType())) 130 return 0; 131 132 // Bypass the operand if SCEV can prove it has no effect. 133 if (SE->getSCEV(UseInst) != FoldedExpr) 134 return 0; 135 136 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand 137 << " -> " << *UseInst << '\n'); 138 139 UseInst->setOperand(OperIdx, IVSrc); 140 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); 141 142 ++NumElimOperand; 143 Changed = true; 144 if (IVOperand->use_empty()) 145 DeadInsts.push_back(IVOperand); 146 return IVSrc; 147 } 148 149 /// eliminateIVComparison - SimplifyIVUsers helper for eliminating useless 150 /// comparisons against an induction variable. 151 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) { 152 unsigned IVOperIdx = 0; 153 ICmpInst::Predicate Pred = ICmp->getPredicate(); 154 if (IVOperand != ICmp->getOperand(0)) { 155 // Swapped 156 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 157 IVOperIdx = 1; 158 Pred = ICmpInst::getSwappedPredicate(Pred); 159 } 160 161 // Get the SCEVs for the ICmp operands. 162 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx)); 163 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx)); 164 165 // Simplify unnecessary loops away. 166 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 167 S = SE->getSCEVAtScope(S, ICmpLoop); 168 X = SE->getSCEVAtScope(X, ICmpLoop); 169 170 // If the condition is always true or always false, replace it with 171 // a constant value. 172 if (SE->isKnownPredicate(Pred, S, X)) 173 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext())); 174 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) 175 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext())); 176 else 177 return; 178 179 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); 180 ++NumElimCmp; 181 Changed = true; 182 DeadInsts.push_back(ICmp); 183 } 184 185 /// eliminateIVRemainder - SimplifyIVUsers helper for eliminating useless 186 /// remainder operations operating on an induction variable. 187 void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem, 188 Value *IVOperand, 189 bool IsSigned) { 190 // We're only interested in the case where we know something about 191 // the numerator. 192 if (IVOperand != Rem->getOperand(0)) 193 return; 194 195 // Get the SCEVs for the ICmp operands. 196 const SCEV *S = SE->getSCEV(Rem->getOperand(0)); 197 const SCEV *X = SE->getSCEV(Rem->getOperand(1)); 198 199 // Simplify unnecessary loops away. 200 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); 201 S = SE->getSCEVAtScope(S, ICmpLoop); 202 X = SE->getSCEVAtScope(X, ICmpLoop); 203 204 // i % n --> i if i is in [0,n). 205 if ((!IsSigned || SE->isKnownNonNegative(S)) && 206 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 207 S, X)) 208 Rem->replaceAllUsesWith(Rem->getOperand(0)); 209 else { 210 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). 211 const SCEV *LessOne = 212 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1)); 213 if (IsSigned && !SE->isKnownNonNegative(LessOne)) 214 return; 215 216 if (!SE->isKnownPredicate(IsSigned ? 217 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 218 LessOne, X)) 219 return; 220 221 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, 222 Rem->getOperand(0), Rem->getOperand(1), 223 "tmp"); 224 SelectInst *Sel = 225 SelectInst::Create(ICmp, 226 ConstantInt::get(Rem->getType(), 0), 227 Rem->getOperand(0), "tmp", Rem); 228 Rem->replaceAllUsesWith(Sel); 229 } 230 231 // Inform IVUsers about the new users. 232 if (IU) { 233 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0))) 234 IU->AddUsersIfInteresting(I); 235 } 236 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 237 ++NumElimRem; 238 Changed = true; 239 DeadInsts.push_back(Rem); 240 } 241 242 /// eliminateIVUser - Eliminate an operation that consumes a simple IV and has 243 /// no observable side-effect given the range of IV values. 244 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, 245 Instruction *IVOperand) { 246 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { 247 eliminateIVComparison(ICmp, IVOperand); 248 return true; 249 } 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); 254 return true; 255 } 256 } 257 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))) 262 return false; 263 264 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); 265 266 UseInst->replaceAllUsesWith(IVOperand); 267 ++NumElimIdentity; 268 Changed = true; 269 DeadInsts.push_back(UseInst); 270 return true; 271 } 272 273 /// pushIVUsers - Add all uses of Def to the current IV's worklist. 274 /// 275 static void pushIVUsers( 276 Instruction *Def, 277 SmallPtrSet<Instruction*,16> &Simplified, 278 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { 279 280 for (Value::use_iterator UI = Def->use_begin(), E = Def->use_end(); 281 UI != E; ++UI) { 282 Instruction *User = cast<Instruction>(*UI); 283 284 // Avoid infinite or exponential worklist processing. 285 // Also ensure unique worklist users. 286 // If Def is a LoopPhi, it may not be in the Simplified set, so check for 287 // self edges first. 288 if (User != Def && Simplified.insert(User)) 289 SimpleIVUsers.push_back(std::make_pair(User, Def)); 290 } 291 } 292 293 /// isSimpleIVUser - Return true if this instruction generates a simple SCEV 294 /// expression in terms of that IV. 295 /// 296 /// This is similar to IVUsers' isInteresting() but processes each instruction 297 /// non-recursively when the operand is already known to be a simpleIVUser. 298 /// 299 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { 300 if (!SE->isSCEVable(I->getType())) 301 return false; 302 303 // Get the symbolic expression for this instruction. 304 const SCEV *S = SE->getSCEV(I); 305 306 // Only consider affine recurrences. 307 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); 308 if (AR && AR->getLoop() == L) 309 return true; 310 311 return false; 312 } 313 314 /// simplifyUsers - Iteratively perform simplification on a worklist of users 315 /// of the specified induction variable. Each successive simplification may push 316 /// more users which may themselves be candidates for simplification. 317 /// 318 /// This algorithm does not require IVUsers analysis. Instead, it simplifies 319 /// instructions in-place during analysis. Rather than rewriting induction 320 /// variables bottom-up from their users, it transforms a chain of IVUsers 321 /// top-down, updating the IR only when it encouters a clear optimization 322 /// opportunitiy. 323 /// 324 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. 325 /// 326 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { 327 // Instructions processed by SimplifyIndvar for CurrIV. 328 SmallPtrSet<Instruction*,16> Simplified; 329 330 // Use-def pairs if IV users waiting to be processed for CurrIV. 331 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; 332 333 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be 334 // called multiple times for the same LoopPhi. This is the proper thing to 335 // do for loop header phis that use each other. 336 pushIVUsers(CurrIV, Simplified, SimpleIVUsers); 337 338 while (!SimpleIVUsers.empty()) { 339 std::pair<Instruction*, Instruction*> UseOper = 340 SimpleIVUsers.pop_back_val(); 341 // Bypass back edges to avoid extra work. 342 if (UseOper.first == CurrIV) continue; 343 344 Instruction *IVOperand = UseOper.second; 345 for (unsigned N = 0; IVOperand; ++N) { 346 assert(N <= Simplified.size() && "runaway iteration"); 347 348 Value *NewOper = foldIVUser(UseOper.first, IVOperand); 349 if (!NewOper) 350 break; // done folding 351 IVOperand = dyn_cast<Instruction>(NewOper); 352 } 353 if (!IVOperand) 354 continue; 355 356 if (eliminateIVUser(UseOper.first, IVOperand)) { 357 pushIVUsers(IVOperand, Simplified, SimpleIVUsers); 358 continue; 359 } 360 CastInst *Cast = dyn_cast<CastInst>(UseOper.first); 361 if (V && Cast) { 362 V->visitCast(Cast); 363 continue; 364 } 365 if (isSimpleIVUser(UseOper.first, L, SE)) { 366 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers); 367 } 368 } 369 } 370 371 namespace llvm { 372 373 /// simplifyUsersOfIV - Simplify instructions that use this induction variable 374 /// by using ScalarEvolution to analyze the IV's recurrence. 375 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM, 376 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V) 377 { 378 LoopInfo *LI = &LPM->getAnalysis<LoopInfo>(); 379 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LPM, Dead); 380 SIV.simplifyUsers(CurrIV, V); 381 return SIV.hasChanged(); 382 } 383 384 /// simplifyLoopIVs - Simplify users of induction variables within this 385 /// loop. This does not actually change or add IVs. 386 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM, 387 SmallVectorImpl<WeakVH> &Dead) { 388 bool Changed = false; 389 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 390 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead); 391 } 392 return Changed; 393 } 394 395 /// simplifyIVUsers - Perform simplification on instructions recorded by the 396 /// IVUsers pass. 397 /// 398 /// This is the old approach to IV simplification to be replaced by 399 /// SimplifyLoopIVs. 400 bool simplifyIVUsers(IVUsers *IU, ScalarEvolution *SE, LPPassManager *LPM, 401 SmallVectorImpl<WeakVH> &Dead) { 402 SimplifyIndvar SIV(IU->getLoop(), SE, LPM, Dead); 403 404 // Each round of simplification involves a round of eliminating operations 405 // followed by a round of widening IVs. A single IVUsers worklist is used 406 // across all rounds. The inner loop advances the user. If widening exposes 407 // more uses, then another pass through the outer loop is triggered. 408 for (IVUsers::iterator I = IU->begin(); I != IU->end(); ++I) { 409 Instruction *UseInst = I->getUser(); 410 Value *IVOperand = I->getOperandValToReplace(); 411 412 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { 413 SIV.eliminateIVComparison(ICmp, IVOperand); 414 continue; 415 } 416 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) { 417 bool IsSigned = Rem->getOpcode() == Instruction::SRem; 418 if (IsSigned || Rem->getOpcode() == Instruction::URem) { 419 SIV.eliminateIVRemainder(Rem, IVOperand, IsSigned); 420 continue; 421 } 422 } 423 } 424 return SIV.hasChanged(); 425 } 426 427 } // namespace llvm 428