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