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