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