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