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 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/Instructions.h" 27 #include "llvm/IR/IntrinsicInst.h" 28 #include "llvm/IR/PatternMatch.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "indvars" 35 36 STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); 37 STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); 38 STATISTIC(NumFoldedUser, "Number of IV users folded into a constant"); 39 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); 40 STATISTIC( 41 NumSimplifiedSDiv, 42 "Number of IV signed division operations converted to unsigned division"); 43 STATISTIC( 44 NumSimplifiedSRem, 45 "Number of IV signed remainder operations converted to unsigned remainder"); 46 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); 47 48 namespace { 49 /// This is a utility for simplifying induction variables 50 /// based on ScalarEvolution. It is the primary instrument of the 51 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after 52 /// other loop passes that preserve SCEV. 53 class SimplifyIndvar { 54 Loop *L; 55 LoopInfo *LI; 56 ScalarEvolution *SE; 57 DominatorTree *DT; 58 59 SmallVectorImpl<WeakTrackingVH> &DeadInsts; 60 61 bool Changed; 62 63 public: 64 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT, 65 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) 66 : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) { 67 assert(LI && "IV simplification requires LoopInfo"); 68 } 69 70 bool hasChanged() const { return Changed; } 71 72 /// Iteratively perform simplification on a worklist of users of the 73 /// specified induction variable. This is the top-level driver that applies 74 /// all simplifications to users of an IV. 75 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr); 76 77 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand); 78 79 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand); 80 bool foldConstantSCEV(Instruction *UseInst); 81 82 bool eliminateOverflowIntrinsic(CallInst *CI); 83 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); 84 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand); 85 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, 86 bool IsSigned); 87 void replaceRemWithNumerator(BinaryOperator *Rem); 88 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem); 89 void replaceSRemWithURem(BinaryOperator *Rem); 90 bool eliminateSDiv(BinaryOperator *SDiv); 91 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand); 92 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand); 93 }; 94 } 95 96 /// Fold an IV operand into its use. This removes increments of an 97 /// aligned IV when used by a instruction that ignores the low bits. 98 /// 99 /// IVOperand is guaranteed SCEVable, but UseInst may not be. 100 /// 101 /// Return the operand of IVOperand for this induction variable if IVOperand can 102 /// be folded (in case more folding opportunities have been exposed). 103 /// Otherwise return null. 104 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { 105 Value *IVSrc = nullptr; 106 unsigned OperIdx = 0; 107 const SCEV *FoldedExpr = nullptr; 108 switch (UseInst->getOpcode()) { 109 default: 110 return nullptr; 111 case Instruction::UDiv: 112 case Instruction::LShr: 113 // We're only interested in the case where we know something about 114 // the numerator and have a constant denominator. 115 if (IVOperand != UseInst->getOperand(OperIdx) || 116 !isa<ConstantInt>(UseInst->getOperand(1))) 117 return nullptr; 118 119 // Attempt to fold a binary operator with constant operand. 120 // e.g. ((I + 1) >> 2) => I >> 2 121 if (!isa<BinaryOperator>(IVOperand) 122 || !isa<ConstantInt>(IVOperand->getOperand(1))) 123 return nullptr; 124 125 IVSrc = IVOperand->getOperand(0); 126 // IVSrc must be the (SCEVable) IV, since the other operand is const. 127 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); 128 129 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); 130 if (UseInst->getOpcode() == Instruction::LShr) { 131 // Get a constant for the divisor. See createSCEV. 132 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); 133 if (D->getValue().uge(BitWidth)) 134 return nullptr; 135 136 D = ConstantInt::get(UseInst->getContext(), 137 APInt::getOneBitSet(BitWidth, D->getZExtValue())); 138 } 139 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D)); 140 } 141 // We have something that might fold it's operand. Compare SCEVs. 142 if (!SE->isSCEVable(UseInst->getType())) 143 return nullptr; 144 145 // Bypass the operand if SCEV can prove it has no effect. 146 if (SE->getSCEV(UseInst) != FoldedExpr) 147 return nullptr; 148 149 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand 150 << " -> " << *UseInst << '\n'); 151 152 UseInst->setOperand(OperIdx, IVSrc); 153 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); 154 155 ++NumElimOperand; 156 Changed = true; 157 if (IVOperand->use_empty()) 158 DeadInsts.emplace_back(IVOperand); 159 return IVSrc; 160 } 161 162 /// SimplifyIVUsers helper for eliminating useless 163 /// comparisons against an induction variable. 164 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) { 165 unsigned IVOperIdx = 0; 166 ICmpInst::Predicate Pred = ICmp->getPredicate(); 167 ICmpInst::Predicate OriginalPred = Pred; 168 if (IVOperand != ICmp->getOperand(0)) { 169 // Swapped 170 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 171 IVOperIdx = 1; 172 Pred = ICmpInst::getSwappedPredicate(Pred); 173 } 174 175 // Get the SCEVs for the ICmp operands. 176 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx)); 177 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx)); 178 179 // Simplify unnecessary loops away. 180 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 181 S = SE->getSCEVAtScope(S, ICmpLoop); 182 X = SE->getSCEVAtScope(X, ICmpLoop); 183 184 ICmpInst::Predicate InvariantPredicate; 185 const SCEV *InvariantLHS, *InvariantRHS; 186 187 // If the condition is always true or always false, replace it with 188 // a constant value. 189 if (SE->isKnownPredicate(Pred, S, X)) { 190 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext())); 191 DeadInsts.emplace_back(ICmp); 192 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); 193 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) { 194 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext())); 195 DeadInsts.emplace_back(ICmp); 196 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); 197 } else if (isa<PHINode>(IVOperand) && 198 SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate, 199 InvariantLHS, InvariantRHS)) { 200 201 // Rewrite the comparison to a loop invariant comparison if it can be done 202 // cheaply, where cheaply means "we don't need to emit any new 203 // instructions". 204 205 Value *NewLHS = nullptr, *NewRHS = nullptr; 206 207 if (S == InvariantLHS || X == InvariantLHS) 208 NewLHS = 209 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx)); 210 211 if (S == InvariantRHS || X == InvariantRHS) 212 NewRHS = 213 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx)); 214 215 auto *PN = cast<PHINode>(IVOperand); 216 for (unsigned i = 0, e = PN->getNumIncomingValues(); 217 i != e && (!NewLHS || !NewRHS); 218 ++i) { 219 220 // If this is a value incoming from the backedge, then it cannot be a loop 221 // invariant value (since we know that IVOperand is an induction variable). 222 if (L->contains(PN->getIncomingBlock(i))) 223 continue; 224 225 // NB! This following assert does not fundamentally have to be true, but 226 // it is true today given how SCEV analyzes induction variables. 227 // Specifically, today SCEV will *not* recognize %iv as an induction 228 // variable in the following case: 229 // 230 // define void @f(i32 %k) { 231 // entry: 232 // br i1 undef, label %r, label %l 233 // 234 // l: 235 // %k.inc.l = add i32 %k, 1 236 // br label %loop 237 // 238 // r: 239 // %k.inc.r = add i32 %k, 1 240 // br label %loop 241 // 242 // loop: 243 // %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ] 244 // %iv.inc = add i32 %iv, 1 245 // br label %loop 246 // } 247 // 248 // but if it starts to, at some point, then the assertion below will have 249 // to be changed to a runtime check. 250 251 Value *Incoming = PN->getIncomingValue(i); 252 253 #ifndef NDEBUG 254 if (auto *I = dyn_cast<Instruction>(Incoming)) 255 assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!"); 256 #endif 257 258 const SCEV *IncomingS = SE->getSCEV(Incoming); 259 260 if (!NewLHS && IncomingS == InvariantLHS) 261 NewLHS = Incoming; 262 if (!NewRHS && IncomingS == InvariantRHS) 263 NewRHS = Incoming; 264 } 265 266 if (!NewLHS || !NewRHS) 267 // We could not find an existing value to replace either LHS or RHS. 268 // Generating new instructions has subtler tradeoffs, so avoid doing that 269 // for now. 270 return; 271 272 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n'); 273 ICmp->setPredicate(InvariantPredicate); 274 ICmp->setOperand(0, NewLHS); 275 ICmp->setOperand(1, NewRHS); 276 } else if (ICmpInst::isSigned(OriginalPred) && 277 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) { 278 // If we were unable to make anything above, all we can is to canonicalize 279 // the comparison hoping that it will open the doors for other 280 // optimizations. If we find out that we compare two non-negative values, 281 // we turn the instruction's predicate to its unsigned version. Note that 282 // we cannot rely on Pred here unless we check if we have swapped it. 283 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?"); 284 DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n'); 285 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred)); 286 } else 287 return; 288 289 ++NumElimCmp; 290 Changed = true; 291 } 292 293 bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) { 294 // Get the SCEVs for the ICmp operands. 295 auto *N = SE->getSCEV(SDiv->getOperand(0)); 296 auto *D = SE->getSCEV(SDiv->getOperand(1)); 297 298 // Simplify unnecessary loops away. 299 const Loop *L = LI->getLoopFor(SDiv->getParent()); 300 N = SE->getSCEVAtScope(N, L); 301 D = SE->getSCEVAtScope(D, L); 302 303 // Replace sdiv by udiv if both of the operands are non-negative 304 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) { 305 auto *UDiv = BinaryOperator::Create( 306 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1), 307 SDiv->getName() + ".udiv", SDiv); 308 UDiv->setIsExact(SDiv->isExact()); 309 SDiv->replaceAllUsesWith(UDiv); 310 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n'); 311 ++NumSimplifiedSDiv; 312 Changed = true; 313 DeadInsts.push_back(SDiv); 314 return true; 315 } 316 317 return false; 318 } 319 320 // i %s n -> i %u n if i >= 0 and n >= 0 321 void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) { 322 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 323 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D, 324 Rem->getName() + ".urem", Rem); 325 Rem->replaceAllUsesWith(URem); 326 DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n'); 327 ++NumSimplifiedSRem; 328 Changed = true; 329 DeadInsts.emplace_back(Rem); 330 } 331 332 // i % n --> i if i is in [0,n). 333 void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) { 334 Rem->replaceAllUsesWith(Rem->getOperand(0)); 335 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 336 ++NumElimRem; 337 Changed = true; 338 DeadInsts.emplace_back(Rem); 339 } 340 341 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). 342 void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) { 343 auto *T = Rem->getType(); 344 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 345 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D); 346 SelectInst *Sel = 347 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem); 348 Rem->replaceAllUsesWith(Sel); 349 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 350 ++NumElimRem; 351 Changed = true; 352 DeadInsts.emplace_back(Rem); 353 } 354 355 /// SimplifyIVUsers helper for eliminating useless remainder operations 356 /// operating on an induction variable or replacing srem by urem. 357 void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, 358 bool IsSigned) { 359 auto *NValue = Rem->getOperand(0); 360 auto *DValue = Rem->getOperand(1); 361 // We're only interested in the case where we know something about 362 // the numerator, unless it is a srem, because we want to replace srem by urem 363 // in general. 364 bool UsedAsNumerator = IVOperand == NValue; 365 if (!UsedAsNumerator && !IsSigned) 366 return; 367 368 const SCEV *N = SE->getSCEV(NValue); 369 370 // Simplify unnecessary loops away. 371 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); 372 N = SE->getSCEVAtScope(N, ICmpLoop); 373 374 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N); 375 376 // Do not proceed if the Numerator may be negative 377 if (!IsNumeratorNonNegative) 378 return; 379 380 const SCEV *D = SE->getSCEV(DValue); 381 D = SE->getSCEVAtScope(D, ICmpLoop); 382 383 if (UsedAsNumerator) { 384 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 385 if (SE->isKnownPredicate(LT, N, D)) { 386 replaceRemWithNumerator(Rem); 387 return; 388 } 389 390 auto *T = Rem->getType(); 391 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T)); 392 if (SE->isKnownPredicate(LT, NLessOne, D)) { 393 replaceRemWithNumeratorOrZero(Rem); 394 return; 395 } 396 } 397 398 // Try to replace SRem with URem, if both N and D are known non-negative. 399 // Since we had already check N, we only need to check D now 400 if (!IsSigned || !SE->isKnownNonNegative(D)) 401 return; 402 403 replaceSRemWithURem(Rem); 404 } 405 406 bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) { 407 auto *F = CI->getCalledFunction(); 408 if (!F) 409 return false; 410 411 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)( 412 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned); 413 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)( 414 const SCEV *, Type *, unsigned); 415 416 OperationFunctionTy Operation; 417 ExtensionFunctionTy Extension; 418 419 Instruction::BinaryOps RawOp; 420 421 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we 422 // have nuw. 423 bool NoSignedOverflow; 424 425 switch (F->getIntrinsicID()) { 426 default: 427 return false; 428 429 case Intrinsic::sadd_with_overflow: 430 Operation = &ScalarEvolution::getAddExpr; 431 Extension = &ScalarEvolution::getSignExtendExpr; 432 RawOp = Instruction::Add; 433 NoSignedOverflow = true; 434 break; 435 436 case Intrinsic::uadd_with_overflow: 437 Operation = &ScalarEvolution::getAddExpr; 438 Extension = &ScalarEvolution::getZeroExtendExpr; 439 RawOp = Instruction::Add; 440 NoSignedOverflow = false; 441 break; 442 443 case Intrinsic::ssub_with_overflow: 444 Operation = &ScalarEvolution::getMinusSCEV; 445 Extension = &ScalarEvolution::getSignExtendExpr; 446 RawOp = Instruction::Sub; 447 NoSignedOverflow = true; 448 break; 449 450 case Intrinsic::usub_with_overflow: 451 Operation = &ScalarEvolution::getMinusSCEV; 452 Extension = &ScalarEvolution::getZeroExtendExpr; 453 RawOp = Instruction::Sub; 454 NoSignedOverflow = false; 455 break; 456 } 457 458 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0)); 459 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1)); 460 461 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 462 auto *WideTy = 463 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 464 465 const SCEV *A = 466 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), 467 WideTy, 0); 468 const SCEV *B = 469 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0), 470 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0); 471 472 if (A != B) 473 return false; 474 475 // Proved no overflow, nuke the overflow check and, if possible, the overflow 476 // intrinsic as well. 477 478 BinaryOperator *NewResult = BinaryOperator::Create( 479 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI); 480 481 if (NoSignedOverflow) 482 NewResult->setHasNoSignedWrap(true); 483 else 484 NewResult->setHasNoUnsignedWrap(true); 485 486 SmallVector<ExtractValueInst *, 4> ToDelete; 487 488 for (auto *U : CI->users()) { 489 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) { 490 if (EVI->getIndices()[0] == 1) 491 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext())); 492 else { 493 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!"); 494 EVI->replaceAllUsesWith(NewResult); 495 } 496 ToDelete.push_back(EVI); 497 } 498 } 499 500 for (auto *EVI : ToDelete) 501 EVI->eraseFromParent(); 502 503 if (CI->use_empty()) 504 CI->eraseFromParent(); 505 506 return true; 507 } 508 509 /// Eliminate an operation that consumes a simple IV and has no observable 510 /// side-effect given the range of IV values. IVOperand is guaranteed SCEVable, 511 /// but UseInst may not be. 512 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, 513 Instruction *IVOperand) { 514 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { 515 eliminateIVComparison(ICmp, IVOperand); 516 return true; 517 } 518 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) { 519 bool IsSRem = Bin->getOpcode() == Instruction::SRem; 520 if (IsSRem || Bin->getOpcode() == Instruction::URem) { 521 simplifyIVRemainder(Bin, IVOperand, IsSRem); 522 return true; 523 } 524 525 if (Bin->getOpcode() == Instruction::SDiv) 526 return eliminateSDiv(Bin); 527 } 528 529 if (auto *CI = dyn_cast<CallInst>(UseInst)) 530 if (eliminateOverflowIntrinsic(CI)) 531 return true; 532 533 if (eliminateIdentitySCEV(UseInst, IVOperand)) 534 return true; 535 536 return false; 537 } 538 539 /// Replace the UseInst with a constant if possible 540 bool SimplifyIndvar::foldConstantSCEV(Instruction *I) { 541 if (!SE->isSCEVable(I->getType())) 542 return false; 543 544 // Get the symbolic expression for this instruction. 545 const SCEV *S = SE->getSCEV(I); 546 547 const Loop *L = LI->getLoopFor(I->getParent()); 548 S = SE->getSCEVAtScope(S, L); 549 550 if (auto *C = dyn_cast<SCEVConstant>(S)) { 551 I->replaceAllUsesWith(C->getValue()); 552 DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I 553 << " with constant: " << *C << '\n'); 554 ++NumFoldedUser; 555 Changed = true; 556 DeadInsts.emplace_back(I); 557 return true; 558 } 559 560 return false; 561 } 562 563 /// Eliminate any operation that SCEV can prove is an identity function. 564 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst, 565 Instruction *IVOperand) { 566 if (!SE->isSCEVable(UseInst->getType()) || 567 (UseInst->getType() != IVOperand->getType()) || 568 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand))) 569 return false; 570 571 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the 572 // dominator tree, even if X is an operand to Y. For instance, in 573 // 574 // %iv = phi i32 {0,+,1} 575 // br %cond, label %left, label %merge 576 // 577 // left: 578 // %X = add i32 %iv, 0 579 // br label %merge 580 // 581 // merge: 582 // %M = phi (%X, %iv) 583 // 584 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and 585 // %M.replaceAllUsesWith(%X) would be incorrect. 586 587 if (isa<PHINode>(UseInst)) 588 // If UseInst is not a PHI node then we know that IVOperand dominates 589 // UseInst directly from the legality of SSA. 590 if (!DT || !DT->dominates(IVOperand, UseInst)) 591 return false; 592 593 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand)) 594 return false; 595 596 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); 597 598 UseInst->replaceAllUsesWith(IVOperand); 599 ++NumElimIdentity; 600 Changed = true; 601 DeadInsts.emplace_back(UseInst); 602 return true; 603 } 604 605 /// Annotate BO with nsw / nuw if it provably does not signed-overflow / 606 /// unsigned-overflow. Returns true if anything changed, false otherwise. 607 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO, 608 Value *IVOperand) { 609 610 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`. 611 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap()) 612 return false; 613 614 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *, 615 SCEV::NoWrapFlags, unsigned); 616 switch (BO->getOpcode()) { 617 default: 618 return false; 619 620 case Instruction::Add: 621 GetExprForBO = &ScalarEvolution::getAddExpr; 622 break; 623 624 case Instruction::Sub: 625 GetExprForBO = &ScalarEvolution::getMinusSCEV; 626 break; 627 628 case Instruction::Mul: 629 GetExprForBO = &ScalarEvolution::getMulExpr; 630 break; 631 } 632 633 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth(); 634 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2); 635 const SCEV *LHS = SE->getSCEV(BO->getOperand(0)); 636 const SCEV *RHS = SE->getSCEV(BO->getOperand(1)); 637 638 bool Changed = false; 639 640 if (!BO->hasNoUnsignedWrap()) { 641 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy); 642 const SCEV *OpAfterExtend = (SE->*GetExprForBO)( 643 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy), 644 SCEV::FlagAnyWrap, 0u); 645 if (ExtendAfterOp == OpAfterExtend) { 646 BO->setHasNoUnsignedWrap(); 647 SE->forgetValue(BO); 648 Changed = true; 649 } 650 } 651 652 if (!BO->hasNoSignedWrap()) { 653 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy); 654 const SCEV *OpAfterExtend = (SE->*GetExprForBO)( 655 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy), 656 SCEV::FlagAnyWrap, 0u); 657 if (ExtendAfterOp == OpAfterExtend) { 658 BO->setHasNoSignedWrap(); 659 SE->forgetValue(BO); 660 Changed = true; 661 } 662 } 663 664 return Changed; 665 } 666 667 /// Annotate the Shr in (X << IVOperand) >> C as exact using the 668 /// information from the IV's range. Returns true if anything changed, false 669 /// otherwise. 670 bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO, 671 Value *IVOperand) { 672 using namespace llvm::PatternMatch; 673 674 if (BO->getOpcode() == Instruction::Shl) { 675 bool Changed = false; 676 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand)); 677 for (auto *U : BO->users()) { 678 const APInt *C; 679 if (match(U, 680 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) || 681 match(U, 682 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) { 683 BinaryOperator *Shr = cast<BinaryOperator>(U); 684 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) { 685 Shr->setIsExact(true); 686 Changed = true; 687 } 688 } 689 } 690 return Changed; 691 } 692 693 return false; 694 } 695 696 /// Add all uses of Def to the current IV's worklist. 697 static void pushIVUsers( 698 Instruction *Def, 699 SmallPtrSet<Instruction*,16> &Simplified, 700 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { 701 702 for (User *U : Def->users()) { 703 Instruction *UI = cast<Instruction>(U); 704 705 // Avoid infinite or exponential worklist processing. 706 // Also ensure unique worklist users. 707 // If Def is a LoopPhi, it may not be in the Simplified set, so check for 708 // self edges first. 709 if (UI != Def && Simplified.insert(UI).second) 710 SimpleIVUsers.push_back(std::make_pair(UI, Def)); 711 } 712 } 713 714 /// Return true if this instruction generates a simple SCEV 715 /// expression in terms of that IV. 716 /// 717 /// This is similar to IVUsers' isInteresting() but processes each instruction 718 /// non-recursively when the operand is already known to be a simpleIVUser. 719 /// 720 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { 721 if (!SE->isSCEVable(I->getType())) 722 return false; 723 724 // Get the symbolic expression for this instruction. 725 const SCEV *S = SE->getSCEV(I); 726 727 // Only consider affine recurrences. 728 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); 729 if (AR && AR->getLoop() == L) 730 return true; 731 732 return false; 733 } 734 735 /// Iteratively perform simplification on a worklist of users 736 /// of the specified induction variable. Each successive simplification may push 737 /// more users which may themselves be candidates for simplification. 738 /// 739 /// This algorithm does not require IVUsers analysis. Instead, it simplifies 740 /// instructions in-place during analysis. Rather than rewriting induction 741 /// variables bottom-up from their users, it transforms a chain of IVUsers 742 /// top-down, updating the IR only when it encounters a clear optimization 743 /// opportunity. 744 /// 745 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. 746 /// 747 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { 748 if (!SE->isSCEVable(CurrIV->getType())) 749 return; 750 751 // Instructions processed by SimplifyIndvar for CurrIV. 752 SmallPtrSet<Instruction*,16> Simplified; 753 754 // Use-def pairs if IV users waiting to be processed for CurrIV. 755 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; 756 757 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be 758 // called multiple times for the same LoopPhi. This is the proper thing to 759 // do for loop header phis that use each other. 760 pushIVUsers(CurrIV, Simplified, SimpleIVUsers); 761 762 while (!SimpleIVUsers.empty()) { 763 std::pair<Instruction*, Instruction*> UseOper = 764 SimpleIVUsers.pop_back_val(); 765 Instruction *UseInst = UseOper.first; 766 767 // Bypass back edges to avoid extra work. 768 if (UseInst == CurrIV) continue; 769 770 // Try to replace UseInst with a constant before any other simplifications 771 if (foldConstantSCEV(UseInst)) 772 continue; 773 774 Instruction *IVOperand = UseOper.second; 775 for (unsigned N = 0; IVOperand; ++N) { 776 assert(N <= Simplified.size() && "runaway iteration"); 777 778 Value *NewOper = foldIVUser(UseOper.first, IVOperand); 779 if (!NewOper) 780 break; // done folding 781 IVOperand = dyn_cast<Instruction>(NewOper); 782 } 783 if (!IVOperand) 784 continue; 785 786 if (eliminateIVUser(UseOper.first, IVOperand)) { 787 pushIVUsers(IVOperand, Simplified, SimpleIVUsers); 788 continue; 789 } 790 791 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) { 792 if ((isa<OverflowingBinaryOperator>(BO) && 793 strengthenOverflowingOperation(BO, IVOperand)) || 794 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) { 795 // re-queue uses of the now modified binary operator and fall 796 // through to the checks that remain. 797 pushIVUsers(IVOperand, Simplified, SimpleIVUsers); 798 } 799 } 800 801 CastInst *Cast = dyn_cast<CastInst>(UseOper.first); 802 if (V && Cast) { 803 V->visitCast(Cast); 804 continue; 805 } 806 if (isSimpleIVUser(UseOper.first, L, SE)) { 807 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers); 808 } 809 } 810 } 811 812 namespace llvm { 813 814 void IVVisitor::anchor() { } 815 816 /// Simplify instructions that use this induction variable 817 /// by using ScalarEvolution to analyze the IV's recurrence. 818 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, 819 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead, 820 IVVisitor *V) { 821 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead); 822 SIV.simplifyUsers(CurrIV, V); 823 return SIV.hasChanged(); 824 } 825 826 /// Simplify users of induction variables within this 827 /// loop. This does not actually change or add IVs. 828 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, 829 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) { 830 bool Changed = false; 831 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 832 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead); 833 } 834 return Changed; 835 } 836 837 } // namespace llvm 838