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