1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements induction variable simplification. It does 10 // not define any actual pass or policy, but provides a single function to 11 // simplify a loop's induction variables based on ScalarEvolution. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/IR/Dominators.h" 20 #include "llvm/IR/IRBuilder.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/PatternMatch.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Transforms/Utils/Local.h" 27 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 28 29 using namespace llvm; 30 31 #define DEBUG_TYPE "indvars" 32 33 STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); 34 STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); 35 STATISTIC(NumFoldedUser, "Number of IV users folded into a constant"); 36 STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); 37 STATISTIC( 38 NumSimplifiedSDiv, 39 "Number of IV signed division operations converted to unsigned division"); 40 STATISTIC( 41 NumSimplifiedSRem, 42 "Number of IV signed remainder operations converted to unsigned remainder"); 43 STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); 44 45 namespace { 46 /// This is a utility for simplifying induction variables 47 /// based on ScalarEvolution. It is the primary instrument of the 48 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after 49 /// other loop passes that preserve SCEV. 50 class SimplifyIndvar { 51 Loop *L; 52 LoopInfo *LI; 53 ScalarEvolution *SE; 54 DominatorTree *DT; 55 const TargetTransformInfo *TTI; 56 SCEVExpander &Rewriter; 57 SmallVectorImpl<WeakTrackingVH> &DeadInsts; 58 59 bool Changed = false; 60 61 public: 62 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT, 63 LoopInfo *LI, const TargetTransformInfo *TTI, 64 SCEVExpander &Rewriter, 65 SmallVectorImpl<WeakTrackingVH> &Dead) 66 : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter), 67 DeadInsts(Dead) { 68 assert(LI && "IV simplification requires LoopInfo"); 69 } 70 71 bool hasChanged() const { return Changed; } 72 73 /// Iteratively perform simplification on a worklist of users of the 74 /// specified induction variable. This is the top-level driver that applies 75 /// all simplifications to users of an IV. 76 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr); 77 78 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand); 79 80 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand); 81 bool replaceIVUserWithLoopInvariant(Instruction *UseInst); 82 bool replaceFloatIVWithIntegerIV(Instruction *UseInst); 83 84 bool eliminateOverflowIntrinsic(WithOverflowInst *WO); 85 bool eliminateSaturatingIntrinsic(SaturatingInst *SI); 86 bool eliminateTrunc(TruncInst *TI); 87 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); 88 bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand); 89 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand); 90 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, 91 bool IsSigned); 92 void replaceRemWithNumerator(BinaryOperator *Rem); 93 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem); 94 void replaceSRemWithURem(BinaryOperator *Rem); 95 bool eliminateSDiv(BinaryOperator *SDiv); 96 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand); 97 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand); 98 }; 99 } 100 101 /// Find a point in code which dominates all given instructions. We can safely 102 /// assume that, whatever fact we can prove at the found point, this fact is 103 /// also true for each of the given instructions. 104 static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions, 105 DominatorTree &DT) { 106 Instruction *CommonDom = nullptr; 107 for (auto *Insn : Instructions) 108 if (!CommonDom || DT.dominates(Insn, CommonDom)) 109 CommonDom = Insn; 110 else if (!DT.dominates(CommonDom, Insn)) 111 // If there is no dominance relation, use common dominator. 112 CommonDom = 113 DT.findNearestCommonDominator(CommonDom->getParent(), 114 Insn->getParent())->getTerminator(); 115 assert(CommonDom && "Common dominator not found?"); 116 return CommonDom; 117 } 118 119 /// Fold an IV operand into its use. This removes increments of an 120 /// aligned IV when used by a instruction that ignores the low bits. 121 /// 122 /// IVOperand is guaranteed SCEVable, but UseInst may not be. 123 /// 124 /// Return the operand of IVOperand for this induction variable if IVOperand can 125 /// be folded (in case more folding opportunities have been exposed). 126 /// Otherwise return null. 127 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { 128 Value *IVSrc = nullptr; 129 const unsigned OperIdx = 0; 130 const SCEV *FoldedExpr = nullptr; 131 bool MustDropExactFlag = false; 132 switch (UseInst->getOpcode()) { 133 default: 134 return nullptr; 135 case Instruction::UDiv: 136 case Instruction::LShr: 137 // We're only interested in the case where we know something about 138 // the numerator and have a constant denominator. 139 if (IVOperand != UseInst->getOperand(OperIdx) || 140 !isa<ConstantInt>(UseInst->getOperand(1))) 141 return nullptr; 142 143 // Attempt to fold a binary operator with constant operand. 144 // e.g. ((I + 1) >> 2) => I >> 2 145 if (!isa<BinaryOperator>(IVOperand) 146 || !isa<ConstantInt>(IVOperand->getOperand(1))) 147 return nullptr; 148 149 IVSrc = IVOperand->getOperand(0); 150 // IVSrc must be the (SCEVable) IV, since the other operand is const. 151 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); 152 153 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); 154 if (UseInst->getOpcode() == Instruction::LShr) { 155 // Get a constant for the divisor. See createSCEV. 156 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); 157 if (D->getValue().uge(BitWidth)) 158 return nullptr; 159 160 D = ConstantInt::get(UseInst->getContext(), 161 APInt::getOneBitSet(BitWidth, D->getZExtValue())); 162 } 163 const auto *LHS = SE->getSCEV(IVSrc); 164 const auto *RHS = SE->getSCEV(D); 165 FoldedExpr = SE->getUDivExpr(LHS, RHS); 166 // We might have 'exact' flag set at this point which will no longer be 167 // correct after we make the replacement. 168 if (UseInst->isExact() && LHS != SE->getMulExpr(FoldedExpr, RHS)) 169 MustDropExactFlag = true; 170 } 171 // We have something that might fold it's operand. Compare SCEVs. 172 if (!SE->isSCEVable(UseInst->getType())) 173 return nullptr; 174 175 // Bypass the operand if SCEV can prove it has no effect. 176 if (SE->getSCEV(UseInst) != FoldedExpr) 177 return nullptr; 178 179 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand 180 << " -> " << *UseInst << '\n'); 181 182 UseInst->setOperand(OperIdx, IVSrc); 183 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); 184 185 if (MustDropExactFlag) 186 UseInst->dropPoisonGeneratingFlags(); 187 188 ++NumElimOperand; 189 Changed = true; 190 if (IVOperand->use_empty()) 191 DeadInsts.emplace_back(IVOperand); 192 return IVSrc; 193 } 194 195 bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp, 196 Value *IVOperand) { 197 unsigned IVOperIdx = 0; 198 ICmpInst::Predicate Pred = ICmp->getPredicate(); 199 if (IVOperand != ICmp->getOperand(0)) { 200 // Swapped 201 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 202 IVOperIdx = 1; 203 Pred = ICmpInst::getSwappedPredicate(Pred); 204 } 205 206 // Get the SCEVs for the ICmp operands (in the specific context of the 207 // current loop) 208 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 209 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); 210 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); 211 212 auto *PN = dyn_cast<PHINode>(IVOperand); 213 if (!PN) 214 return false; 215 auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L); 216 if (!LIP) 217 return false; 218 ICmpInst::Predicate InvariantPredicate = LIP->Pred; 219 const SCEV *InvariantLHS = LIP->LHS; 220 const SCEV *InvariantRHS = LIP->RHS; 221 222 // Rewrite the comparison to a loop invariant comparison if it can be done 223 // cheaply, where cheaply means "we don't need to emit any new 224 // instructions". 225 226 SmallDenseMap<const SCEV*, Value*> CheapExpansions; 227 CheapExpansions[S] = ICmp->getOperand(IVOperIdx); 228 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx); 229 230 // TODO: Support multiple entry loops? (We currently bail out of these in 231 // the IndVarSimplify pass) 232 if (auto *BB = L->getLoopPredecessor()) { 233 const int Idx = PN->getBasicBlockIndex(BB); 234 if (Idx >= 0) { 235 Value *Incoming = PN->getIncomingValue(Idx); 236 const SCEV *IncomingS = SE->getSCEV(Incoming); 237 CheapExpansions[IncomingS] = Incoming; 238 } 239 } 240 Value *NewLHS = CheapExpansions[InvariantLHS]; 241 Value *NewRHS = CheapExpansions[InvariantRHS]; 242 243 if (!NewLHS) 244 if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS)) 245 NewLHS = ConstLHS->getValue(); 246 if (!NewRHS) 247 if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS)) 248 NewRHS = ConstRHS->getValue(); 249 250 if (!NewLHS || !NewRHS) 251 // We could not find an existing value to replace either LHS or RHS. 252 // Generating new instructions has subtler tradeoffs, so avoid doing that 253 // for now. 254 return false; 255 256 LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n'); 257 ICmp->setPredicate(InvariantPredicate); 258 ICmp->setOperand(0, NewLHS); 259 ICmp->setOperand(1, NewRHS); 260 return true; 261 } 262 263 /// SimplifyIVUsers helper for eliminating useless 264 /// comparisons against an induction variable. 265 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) { 266 unsigned IVOperIdx = 0; 267 ICmpInst::Predicate Pred = ICmp->getPredicate(); 268 ICmpInst::Predicate OriginalPred = Pred; 269 if (IVOperand != ICmp->getOperand(0)) { 270 // Swapped 271 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 272 IVOperIdx = 1; 273 Pred = ICmpInst::getSwappedPredicate(Pred); 274 } 275 276 // Get the SCEVs for the ICmp operands (in the specific context of the 277 // current loop) 278 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 279 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); 280 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); 281 282 // If the condition is always true or always false in the given context, 283 // replace it with a constant value. 284 SmallVector<Instruction *, 4> Users; 285 for (auto *U : ICmp->users()) 286 Users.push_back(cast<Instruction>(U)); 287 const Instruction *CtxI = findCommonDominator(Users, *DT); 288 if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) { 289 ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev)); 290 DeadInsts.emplace_back(ICmp); 291 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); 292 } else if (makeIVComparisonInvariant(ICmp, IVOperand)) { 293 // fallthrough to end of function 294 } else if (ICmpInst::isSigned(OriginalPred) && 295 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) { 296 // If we were unable to make anything above, all we can is to canonicalize 297 // the comparison hoping that it will open the doors for other 298 // optimizations. If we find out that we compare two non-negative values, 299 // we turn the instruction's predicate to its unsigned version. Note that 300 // we cannot rely on Pred here unless we check if we have swapped it. 301 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?"); 302 LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp 303 << '\n'); 304 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred)); 305 } else 306 return; 307 308 ++NumElimCmp; 309 Changed = true; 310 } 311 312 bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) { 313 // Get the SCEVs for the ICmp operands. 314 auto *N = SE->getSCEV(SDiv->getOperand(0)); 315 auto *D = SE->getSCEV(SDiv->getOperand(1)); 316 317 // Simplify unnecessary loops away. 318 const Loop *L = LI->getLoopFor(SDiv->getParent()); 319 N = SE->getSCEVAtScope(N, L); 320 D = SE->getSCEVAtScope(D, L); 321 322 // Replace sdiv by udiv if both of the operands are non-negative 323 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) { 324 auto *UDiv = BinaryOperator::Create( 325 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1), 326 SDiv->getName() + ".udiv", SDiv); 327 UDiv->setIsExact(SDiv->isExact()); 328 SDiv->replaceAllUsesWith(UDiv); 329 LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n'); 330 ++NumSimplifiedSDiv; 331 Changed = true; 332 DeadInsts.push_back(SDiv); 333 return true; 334 } 335 336 return false; 337 } 338 339 // i %s n -> i %u n if i >= 0 and n >= 0 340 void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) { 341 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 342 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D, 343 Rem->getName() + ".urem", Rem); 344 Rem->replaceAllUsesWith(URem); 345 LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n'); 346 ++NumSimplifiedSRem; 347 Changed = true; 348 DeadInsts.emplace_back(Rem); 349 } 350 351 // i % n --> i if i is in [0,n). 352 void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) { 353 Rem->replaceAllUsesWith(Rem->getOperand(0)); 354 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 355 ++NumElimRem; 356 Changed = true; 357 DeadInsts.emplace_back(Rem); 358 } 359 360 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). 361 void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) { 362 auto *T = Rem->getType(); 363 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 364 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D); 365 SelectInst *Sel = 366 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem); 367 Rem->replaceAllUsesWith(Sel); 368 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 369 ++NumElimRem; 370 Changed = true; 371 DeadInsts.emplace_back(Rem); 372 } 373 374 /// SimplifyIVUsers helper for eliminating useless remainder operations 375 /// operating on an induction variable or replacing srem by urem. 376 void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, 377 bool IsSigned) { 378 auto *NValue = Rem->getOperand(0); 379 auto *DValue = Rem->getOperand(1); 380 // We're only interested in the case where we know something about 381 // the numerator, unless it is a srem, because we want to replace srem by urem 382 // in general. 383 bool UsedAsNumerator = IVOperand == NValue; 384 if (!UsedAsNumerator && !IsSigned) 385 return; 386 387 const SCEV *N = SE->getSCEV(NValue); 388 389 // Simplify unnecessary loops away. 390 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); 391 N = SE->getSCEVAtScope(N, ICmpLoop); 392 393 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N); 394 395 // Do not proceed if the Numerator may be negative 396 if (!IsNumeratorNonNegative) 397 return; 398 399 const SCEV *D = SE->getSCEV(DValue); 400 D = SE->getSCEVAtScope(D, ICmpLoop); 401 402 if (UsedAsNumerator) { 403 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 404 if (SE->isKnownPredicate(LT, N, D)) { 405 replaceRemWithNumerator(Rem); 406 return; 407 } 408 409 auto *T = Rem->getType(); 410 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T)); 411 if (SE->isKnownPredicate(LT, NLessOne, D)) { 412 replaceRemWithNumeratorOrZero(Rem); 413 return; 414 } 415 } 416 417 // Try to replace SRem with URem, if both N and D are known non-negative. 418 // Since we had already check N, we only need to check D now 419 if (!IsSigned || !SE->isKnownNonNegative(D)) 420 return; 421 422 replaceSRemWithURem(Rem); 423 } 424 425 bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) { 426 const SCEV *LHS = SE->getSCEV(WO->getLHS()); 427 const SCEV *RHS = SE->getSCEV(WO->getRHS()); 428 if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS)) 429 return false; 430 431 // Proved no overflow, nuke the overflow check and, if possible, the overflow 432 // intrinsic as well. 433 434 BinaryOperator *NewResult = BinaryOperator::Create( 435 WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO); 436 437 if (WO->isSigned()) 438 NewResult->setHasNoSignedWrap(true); 439 else 440 NewResult->setHasNoUnsignedWrap(true); 441 442 SmallVector<ExtractValueInst *, 4> ToDelete; 443 444 for (auto *U : WO->users()) { 445 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) { 446 if (EVI->getIndices()[0] == 1) 447 EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext())); 448 else { 449 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!"); 450 EVI->replaceAllUsesWith(NewResult); 451 } 452 ToDelete.push_back(EVI); 453 } 454 } 455 456 for (auto *EVI : ToDelete) 457 EVI->eraseFromParent(); 458 459 if (WO->use_empty()) 460 WO->eraseFromParent(); 461 462 Changed = true; 463 return true; 464 } 465 466 bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) { 467 const SCEV *LHS = SE->getSCEV(SI->getLHS()); 468 const SCEV *RHS = SE->getSCEV(SI->getRHS()); 469 if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS)) 470 return false; 471 472 BinaryOperator *BO = BinaryOperator::Create( 473 SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI); 474 if (SI->isSigned()) 475 BO->setHasNoSignedWrap(); 476 else 477 BO->setHasNoUnsignedWrap(); 478 479 SI->replaceAllUsesWith(BO); 480 DeadInsts.emplace_back(SI); 481 Changed = true; 482 return true; 483 } 484 485 bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) { 486 // It is always legal to replace 487 // icmp <pred> i32 trunc(iv), n 488 // with 489 // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate. 490 // Or with 491 // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate. 492 // Or with either of these if pred is an equality predicate. 493 // 494 // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for 495 // every comparison which uses trunc, it means that we can replace each of 496 // them with comparison of iv against sext/zext(n). We no longer need trunc 497 // after that. 498 // 499 // TODO: Should we do this if we can widen *some* comparisons, but not all 500 // of them? Sometimes it is enough to enable other optimizations, but the 501 // trunc instruction will stay in the loop. 502 Value *IV = TI->getOperand(0); 503 Type *IVTy = IV->getType(); 504 const SCEV *IVSCEV = SE->getSCEV(IV); 505 const SCEV *TISCEV = SE->getSCEV(TI); 506 507 // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can 508 // get rid of trunc 509 bool DoesSExtCollapse = false; 510 bool DoesZExtCollapse = false; 511 if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy)) 512 DoesSExtCollapse = true; 513 if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy)) 514 DoesZExtCollapse = true; 515 516 // If neither sext nor zext does collapse, it is not profitable to do any 517 // transform. Bail. 518 if (!DoesSExtCollapse && !DoesZExtCollapse) 519 return false; 520 521 // Collect users of the trunc that look like comparisons against invariants. 522 // Bail if we find something different. 523 SmallVector<ICmpInst *, 4> ICmpUsers; 524 for (auto *U : TI->users()) { 525 // We don't care about users in unreachable blocks. 526 if (isa<Instruction>(U) && 527 !DT->isReachableFromEntry(cast<Instruction>(U)->getParent())) 528 continue; 529 ICmpInst *ICI = dyn_cast<ICmpInst>(U); 530 if (!ICI) return false; 531 assert(L->contains(ICI->getParent()) && "LCSSA form broken?"); 532 if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) && 533 !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0)))) 534 return false; 535 // If we cannot get rid of trunc, bail. 536 if (ICI->isSigned() && !DoesSExtCollapse) 537 return false; 538 if (ICI->isUnsigned() && !DoesZExtCollapse) 539 return false; 540 // For equality, either signed or unsigned works. 541 ICmpUsers.push_back(ICI); 542 } 543 544 auto CanUseZExt = [&](ICmpInst *ICI) { 545 // Unsigned comparison can be widened as unsigned. 546 if (ICI->isUnsigned()) 547 return true; 548 // Is it profitable to do zext? 549 if (!DoesZExtCollapse) 550 return false; 551 // For equality, we can safely zext both parts. 552 if (ICI->isEquality()) 553 return true; 554 // Otherwise we can only use zext when comparing two non-negative or two 555 // negative values. But in practice, we will never pass DoesZExtCollapse 556 // check for a negative value, because zext(trunc(x)) is non-negative. So 557 // it only make sense to check for non-negativity here. 558 const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0)); 559 const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1)); 560 return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2); 561 }; 562 // Replace all comparisons against trunc with comparisons against IV. 563 for (auto *ICI : ICmpUsers) { 564 bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0)); 565 auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1); 566 Instruction *Ext = nullptr; 567 // For signed/unsigned predicate, replace the old comparison with comparison 568 // of immediate IV against sext/zext of the invariant argument. If we can 569 // use either sext or zext (i.e. we are dealing with equality predicate), 570 // then prefer zext as a more canonical form. 571 // TODO: If we see a signed comparison which can be turned into unsigned, 572 // we can do it here for canonicalization purposes. 573 ICmpInst::Predicate Pred = ICI->getPredicate(); 574 if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred); 575 if (CanUseZExt(ICI)) { 576 assert(DoesZExtCollapse && "Unprofitable zext?"); 577 Ext = new ZExtInst(Op1, IVTy, "zext", ICI); 578 Pred = ICmpInst::getUnsignedPredicate(Pred); 579 } else { 580 assert(DoesSExtCollapse && "Unprofitable sext?"); 581 Ext = new SExtInst(Op1, IVTy, "sext", ICI); 582 assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!"); 583 } 584 bool Changed; 585 L->makeLoopInvariant(Ext, Changed); 586 (void)Changed; 587 ICmpInst *NewICI = new ICmpInst(ICI, Pred, IV, Ext); 588 ICI->replaceAllUsesWith(NewICI); 589 DeadInsts.emplace_back(ICI); 590 } 591 592 // Trunc no longer needed. 593 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 594 DeadInsts.emplace_back(TI); 595 return true; 596 } 597 598 /// Eliminate an operation that consumes a simple IV and has no observable 599 /// side-effect given the range of IV values. IVOperand is guaranteed SCEVable, 600 /// but UseInst may not be. 601 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, 602 Instruction *IVOperand) { 603 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { 604 eliminateIVComparison(ICmp, IVOperand); 605 return true; 606 } 607 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) { 608 bool IsSRem = Bin->getOpcode() == Instruction::SRem; 609 if (IsSRem || Bin->getOpcode() == Instruction::URem) { 610 simplifyIVRemainder(Bin, IVOperand, IsSRem); 611 return true; 612 } 613 614 if (Bin->getOpcode() == Instruction::SDiv) 615 return eliminateSDiv(Bin); 616 } 617 618 if (auto *WO = dyn_cast<WithOverflowInst>(UseInst)) 619 if (eliminateOverflowIntrinsic(WO)) 620 return true; 621 622 if (auto *SI = dyn_cast<SaturatingInst>(UseInst)) 623 if (eliminateSaturatingIntrinsic(SI)) 624 return true; 625 626 if (auto *TI = dyn_cast<TruncInst>(UseInst)) 627 if (eliminateTrunc(TI)) 628 return true; 629 630 if (eliminateIdentitySCEV(UseInst, IVOperand)) 631 return true; 632 633 return false; 634 } 635 636 static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) { 637 if (auto *BB = L->getLoopPreheader()) 638 return BB->getTerminator(); 639 640 return Hint; 641 } 642 643 /// Replace the UseInst with a loop invariant expression if it is safe. 644 bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) { 645 if (!SE->isSCEVable(I->getType())) 646 return false; 647 648 // Get the symbolic expression for this instruction. 649 const SCEV *S = SE->getSCEV(I); 650 651 if (!SE->isLoopInvariant(S, L)) 652 return false; 653 654 // Do not generate something ridiculous even if S is loop invariant. 655 if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I)) 656 return false; 657 658 auto *IP = GetLoopInvariantInsertPosition(L, I); 659 660 if (!isSafeToExpandAt(S, IP, *SE)) { 661 LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I 662 << " with non-speculable loop invariant: " << *S << '\n'); 663 return false; 664 } 665 666 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP); 667 668 I->replaceAllUsesWith(Invariant); 669 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I 670 << " with loop invariant: " << *S << '\n'); 671 ++NumFoldedUser; 672 Changed = true; 673 DeadInsts.emplace_back(I); 674 return true; 675 } 676 677 /// Eliminate redundant type cast between integer and float. 678 bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) { 679 if (UseInst->getOpcode() != CastInst::SIToFP) 680 return false; 681 682 Value *IVOperand = UseInst->getOperand(0); 683 // Get the symbolic expression for this instruction. 684 ConstantRange IVRange = SE->getSignedRange(SE->getSCEV(IVOperand)); 685 unsigned DestNumSigBits = UseInst->getType()->getFPMantissaWidth(); 686 if (IVRange.getActiveBits() <= DestNumSigBits) { 687 for (User *U : UseInst->users()) { 688 // Match for fptosi of sitofp and with same type. 689 auto *CI = dyn_cast<FPToSIInst>(U); 690 if (!CI || IVOperand->getType() != CI->getType()) 691 continue; 692 693 CI->replaceAllUsesWith(IVOperand); 694 DeadInsts.push_back(CI); 695 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *CI 696 << " with: " << *IVOperand << '\n'); 697 698 ++NumFoldedUser; 699 Changed = true; 700 } 701 } 702 703 return Changed; 704 } 705 706 /// Eliminate any operation that SCEV can prove is an identity function. 707 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst, 708 Instruction *IVOperand) { 709 if (!SE->isSCEVable(UseInst->getType()) || 710 (UseInst->getType() != IVOperand->getType()) || 711 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand))) 712 return false; 713 714 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the 715 // dominator tree, even if X is an operand to Y. For instance, in 716 // 717 // %iv = phi i32 {0,+,1} 718 // br %cond, label %left, label %merge 719 // 720 // left: 721 // %X = add i32 %iv, 0 722 // br label %merge 723 // 724 // merge: 725 // %M = phi (%X, %iv) 726 // 727 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and 728 // %M.replaceAllUsesWith(%X) would be incorrect. 729 730 if (isa<PHINode>(UseInst)) 731 // If UseInst is not a PHI node then we know that IVOperand dominates 732 // UseInst directly from the legality of SSA. 733 if (!DT || !DT->dominates(IVOperand, UseInst)) 734 return false; 735 736 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand)) 737 return false; 738 739 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); 740 741 UseInst->replaceAllUsesWith(IVOperand); 742 ++NumElimIdentity; 743 Changed = true; 744 DeadInsts.emplace_back(UseInst); 745 return true; 746 } 747 748 /// Annotate BO with nsw / nuw if it provably does not signed-overflow / 749 /// unsigned-overflow. Returns true if anything changed, false otherwise. 750 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO, 751 Value *IVOperand) { 752 auto Flags = SE->getStrengthenedNoWrapFlagsFromBinOp( 753 cast<OverflowingBinaryOperator>(BO)); 754 755 if (!Flags) 756 return false; 757 758 BO->setHasNoUnsignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == 759 SCEV::FlagNUW); 760 BO->setHasNoSignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == 761 SCEV::FlagNSW); 762 763 // The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap 764 // flags on addrecs while performing zero/sign extensions. We could call 765 // forgetValue() here to make sure those flags also propagate to any other 766 // SCEV expressions based on the addrec. However, this can have pathological 767 // compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384. 768 return true; 769 } 770 771 /// Annotate the Shr in (X << IVOperand) >> C as exact using the 772 /// information from the IV's range. Returns true if anything changed, false 773 /// otherwise. 774 bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO, 775 Value *IVOperand) { 776 using namespace llvm::PatternMatch; 777 778 if (BO->getOpcode() == Instruction::Shl) { 779 bool Changed = false; 780 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand)); 781 for (auto *U : BO->users()) { 782 const APInt *C; 783 if (match(U, 784 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) || 785 match(U, 786 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) { 787 BinaryOperator *Shr = cast<BinaryOperator>(U); 788 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) { 789 Shr->setIsExact(true); 790 Changed = true; 791 } 792 } 793 } 794 return Changed; 795 } 796 797 return false; 798 } 799 800 /// Add all uses of Def to the current IV's worklist. 801 static void pushIVUsers( 802 Instruction *Def, Loop *L, 803 SmallPtrSet<Instruction*,16> &Simplified, 804 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { 805 806 for (User *U : Def->users()) { 807 Instruction *UI = cast<Instruction>(U); 808 809 // Avoid infinite or exponential worklist processing. 810 // Also ensure unique worklist users. 811 // If Def is a LoopPhi, it may not be in the Simplified set, so check for 812 // self edges first. 813 if (UI == Def) 814 continue; 815 816 // Only change the current Loop, do not change the other parts (e.g. other 817 // Loops). 818 if (!L->contains(UI)) 819 continue; 820 821 // Do not push the same instruction more than once. 822 if (!Simplified.insert(UI).second) 823 continue; 824 825 SimpleIVUsers.push_back(std::make_pair(UI, Def)); 826 } 827 } 828 829 /// Return true if this instruction generates a simple SCEV 830 /// expression in terms of that IV. 831 /// 832 /// This is similar to IVUsers' isInteresting() but processes each instruction 833 /// non-recursively when the operand is already known to be a simpleIVUser. 834 /// 835 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { 836 if (!SE->isSCEVable(I->getType())) 837 return false; 838 839 // Get the symbolic expression for this instruction. 840 const SCEV *S = SE->getSCEV(I); 841 842 // Only consider affine recurrences. 843 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); 844 if (AR && AR->getLoop() == L) 845 return true; 846 847 return false; 848 } 849 850 /// Iteratively perform simplification on a worklist of users 851 /// of the specified induction variable. Each successive simplification may push 852 /// more users which may themselves be candidates for simplification. 853 /// 854 /// This algorithm does not require IVUsers analysis. Instead, it simplifies 855 /// instructions in-place during analysis. Rather than rewriting induction 856 /// variables bottom-up from their users, it transforms a chain of IVUsers 857 /// top-down, updating the IR only when it encounters a clear optimization 858 /// opportunity. 859 /// 860 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. 861 /// 862 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { 863 if (!SE->isSCEVable(CurrIV->getType())) 864 return; 865 866 // Instructions processed by SimplifyIndvar for CurrIV. 867 SmallPtrSet<Instruction*,16> Simplified; 868 869 // Use-def pairs if IV users waiting to be processed for CurrIV. 870 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; 871 872 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be 873 // called multiple times for the same LoopPhi. This is the proper thing to 874 // do for loop header phis that use each other. 875 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers); 876 877 while (!SimpleIVUsers.empty()) { 878 std::pair<Instruction*, Instruction*> UseOper = 879 SimpleIVUsers.pop_back_val(); 880 Instruction *UseInst = UseOper.first; 881 882 // If a user of the IndVar is trivially dead, we prefer just to mark it dead 883 // rather than try to do some complex analysis or transformation (such as 884 // widening) basing on it. 885 // TODO: Propagate TLI and pass it here to handle more cases. 886 if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) { 887 DeadInsts.emplace_back(UseInst); 888 continue; 889 } 890 891 // Bypass back edges to avoid extra work. 892 if (UseInst == CurrIV) continue; 893 894 // Try to replace UseInst with a loop invariant before any other 895 // simplifications. 896 if (replaceIVUserWithLoopInvariant(UseInst)) 897 continue; 898 899 Instruction *IVOperand = UseOper.second; 900 for (unsigned N = 0; IVOperand; ++N) { 901 assert(N <= Simplified.size() && "runaway iteration"); 902 (void) N; 903 904 Value *NewOper = foldIVUser(UseInst, IVOperand); 905 if (!NewOper) 906 break; // done folding 907 IVOperand = dyn_cast<Instruction>(NewOper); 908 } 909 if (!IVOperand) 910 continue; 911 912 if (eliminateIVUser(UseInst, IVOperand)) { 913 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); 914 continue; 915 } 916 917 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) { 918 if ((isa<OverflowingBinaryOperator>(BO) && 919 strengthenOverflowingOperation(BO, IVOperand)) || 920 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) { 921 // re-queue uses of the now modified binary operator and fall 922 // through to the checks that remain. 923 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); 924 } 925 } 926 927 // Try to use integer induction for FPToSI of float induction directly. 928 if (replaceFloatIVWithIntegerIV(UseInst)) { 929 // Re-queue the potentially new direct uses of IVOperand. 930 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); 931 continue; 932 } 933 934 CastInst *Cast = dyn_cast<CastInst>(UseInst); 935 if (V && Cast) { 936 V->visitCast(Cast); 937 continue; 938 } 939 if (isSimpleIVUser(UseInst, L, SE)) { 940 pushIVUsers(UseInst, L, Simplified, SimpleIVUsers); 941 } 942 } 943 } 944 945 namespace llvm { 946 947 void IVVisitor::anchor() { } 948 949 /// Simplify instructions that use this induction variable 950 /// by using ScalarEvolution to analyze the IV's recurrence. 951 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, 952 LoopInfo *LI, const TargetTransformInfo *TTI, 953 SmallVectorImpl<WeakTrackingVH> &Dead, 954 SCEVExpander &Rewriter, IVVisitor *V) { 955 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI, 956 Rewriter, Dead); 957 SIV.simplifyUsers(CurrIV, V); 958 return SIV.hasChanged(); 959 } 960 961 /// Simplify users of induction variables within this 962 /// loop. This does not actually change or add IVs. 963 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, 964 LoopInfo *LI, const TargetTransformInfo *TTI, 965 SmallVectorImpl<WeakTrackingVH> &Dead) { 966 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars"); 967 #ifndef NDEBUG 968 Rewriter.setDebugType(DEBUG_TYPE); 969 #endif 970 bool Changed = false; 971 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 972 Changed |= 973 simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter); 974 } 975 return Changed; 976 } 977 978 } // namespace llvm 979 980 namespace { 981 //===----------------------------------------------------------------------===// 982 // Widen Induction Variables - Extend the width of an IV to cover its 983 // widest uses. 984 //===----------------------------------------------------------------------===// 985 986 class WidenIV { 987 // Parameters 988 PHINode *OrigPhi; 989 Type *WideType; 990 991 // Context 992 LoopInfo *LI; 993 Loop *L; 994 ScalarEvolution *SE; 995 DominatorTree *DT; 996 997 // Does the module have any calls to the llvm.experimental.guard intrinsic 998 // at all? If not we can avoid scanning instructions looking for guards. 999 bool HasGuards; 1000 1001 bool UsePostIncrementRanges; 1002 1003 // Statistics 1004 unsigned NumElimExt = 0; 1005 unsigned NumWidened = 0; 1006 1007 // Result 1008 PHINode *WidePhi = nullptr; 1009 Instruction *WideInc = nullptr; 1010 const SCEV *WideIncExpr = nullptr; 1011 SmallVectorImpl<WeakTrackingVH> &DeadInsts; 1012 1013 SmallPtrSet<Instruction *,16> Widened; 1014 1015 enum ExtendKind { ZeroExtended, SignExtended, Unknown }; 1016 1017 // A map tracking the kind of extension used to widen each narrow IV 1018 // and narrow IV user. 1019 // Key: pointer to a narrow IV or IV user. 1020 // Value: the kind of extension used to widen this Instruction. 1021 DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap; 1022 1023 using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>; 1024 1025 // A map with control-dependent ranges for post increment IV uses. The key is 1026 // a pair of IV def and a use of this def denoting the context. The value is 1027 // a ConstantRange representing possible values of the def at the given 1028 // context. 1029 DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos; 1030 1031 Optional<ConstantRange> getPostIncRangeInfo(Value *Def, 1032 Instruction *UseI) { 1033 DefUserPair Key(Def, UseI); 1034 auto It = PostIncRangeInfos.find(Key); 1035 return It == PostIncRangeInfos.end() 1036 ? Optional<ConstantRange>(None) 1037 : Optional<ConstantRange>(It->second); 1038 } 1039 1040 void calculatePostIncRanges(PHINode *OrigPhi); 1041 void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser); 1042 1043 void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) { 1044 DefUserPair Key(Def, UseI); 1045 auto It = PostIncRangeInfos.find(Key); 1046 if (It == PostIncRangeInfos.end()) 1047 PostIncRangeInfos.insert({Key, R}); 1048 else 1049 It->second = R.intersectWith(It->second); 1050 } 1051 1052 public: 1053 /// Record a link in the Narrow IV def-use chain along with the WideIV that 1054 /// computes the same value as the Narrow IV def. This avoids caching Use* 1055 /// pointers. 1056 struct NarrowIVDefUse { 1057 Instruction *NarrowDef = nullptr; 1058 Instruction *NarrowUse = nullptr; 1059 Instruction *WideDef = nullptr; 1060 1061 // True if the narrow def is never negative. Tracking this information lets 1062 // us use a sign extension instead of a zero extension or vice versa, when 1063 // profitable and legal. 1064 bool NeverNegative = false; 1065 1066 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD, 1067 bool NeverNegative) 1068 : NarrowDef(ND), NarrowUse(NU), WideDef(WD), 1069 NeverNegative(NeverNegative) {} 1070 }; 1071 1072 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv, 1073 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI, 1074 bool HasGuards, bool UsePostIncrementRanges = true); 1075 1076 PHINode *createWideIV(SCEVExpander &Rewriter); 1077 1078 unsigned getNumElimExt() { return NumElimExt; }; 1079 unsigned getNumWidened() { return NumWidened; }; 1080 1081 protected: 1082 Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned, 1083 Instruction *Use); 1084 1085 Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR); 1086 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU, 1087 const SCEVAddRecExpr *WideAR); 1088 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU); 1089 1090 ExtendKind getExtendKind(Instruction *I); 1091 1092 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>; 1093 1094 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU); 1095 1096 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU); 1097 1098 const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1099 unsigned OpCode) const; 1100 1101 Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter); 1102 1103 bool widenLoopCompare(NarrowIVDefUse DU); 1104 bool widenWithVariantUse(NarrowIVDefUse DU); 1105 1106 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); 1107 1108 private: 1109 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; 1110 }; 1111 } // namespace 1112 1113 /// Determine the insertion point for this user. By default, insert immediately 1114 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the 1115 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest 1116 /// common dominator for the incoming blocks. A nullptr can be returned if no 1117 /// viable location is found: it may happen if User is a PHI and Def only comes 1118 /// to this PHI from unreachable blocks. 1119 static Instruction *getInsertPointForUses(Instruction *User, Value *Def, 1120 DominatorTree *DT, LoopInfo *LI) { 1121 PHINode *PHI = dyn_cast<PHINode>(User); 1122 if (!PHI) 1123 return User; 1124 1125 Instruction *InsertPt = nullptr; 1126 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { 1127 if (PHI->getIncomingValue(i) != Def) 1128 continue; 1129 1130 BasicBlock *InsertBB = PHI->getIncomingBlock(i); 1131 1132 if (!DT->isReachableFromEntry(InsertBB)) 1133 continue; 1134 1135 if (!InsertPt) { 1136 InsertPt = InsertBB->getTerminator(); 1137 continue; 1138 } 1139 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); 1140 InsertPt = InsertBB->getTerminator(); 1141 } 1142 1143 // If we have skipped all inputs, it means that Def only comes to Phi from 1144 // unreachable blocks. 1145 if (!InsertPt) 1146 return nullptr; 1147 1148 auto *DefI = dyn_cast<Instruction>(Def); 1149 if (!DefI) 1150 return InsertPt; 1151 1152 assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses"); 1153 1154 auto *L = LI->getLoopFor(DefI->getParent()); 1155 assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent()))); 1156 1157 for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom()) 1158 if (LI->getLoopFor(DTN->getBlock()) == L) 1159 return DTN->getBlock()->getTerminator(); 1160 1161 llvm_unreachable("DefI dominates InsertPt!"); 1162 } 1163 1164 WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv, 1165 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI, 1166 bool HasGuards, bool UsePostIncrementRanges) 1167 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo), 1168 L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree), 1169 HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges), 1170 DeadInsts(DI) { 1171 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); 1172 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended; 1173 } 1174 1175 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType, 1176 bool IsSigned, Instruction *Use) { 1177 // Set the debug location and conservative insertion point. 1178 IRBuilder<> Builder(Use); 1179 // Hoist the insertion point into loop preheaders as far as possible. 1180 for (const Loop *L = LI->getLoopFor(Use->getParent()); 1181 L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper); 1182 L = L->getParentLoop()) 1183 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 1184 1185 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : 1186 Builder.CreateZExt(NarrowOper, WideType); 1187 } 1188 1189 /// Instantiate a wide operation to replace a narrow operation. This only needs 1190 /// to handle operations that can evaluation to SCEVAddRec. It can safely return 1191 /// 0 for any operation we decide not to clone. 1192 Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU, 1193 const SCEVAddRecExpr *WideAR) { 1194 unsigned Opcode = DU.NarrowUse->getOpcode(); 1195 switch (Opcode) { 1196 default: 1197 return nullptr; 1198 case Instruction::Add: 1199 case Instruction::Mul: 1200 case Instruction::UDiv: 1201 case Instruction::Sub: 1202 return cloneArithmeticIVUser(DU, WideAR); 1203 1204 case Instruction::And: 1205 case Instruction::Or: 1206 case Instruction::Xor: 1207 case Instruction::Shl: 1208 case Instruction::LShr: 1209 case Instruction::AShr: 1210 return cloneBitwiseIVUser(DU); 1211 } 1212 } 1213 1214 Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) { 1215 Instruction *NarrowUse = DU.NarrowUse; 1216 Instruction *NarrowDef = DU.NarrowDef; 1217 Instruction *WideDef = DU.WideDef; 1218 1219 LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n"); 1220 1221 // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything 1222 // about the narrow operand yet so must insert a [sz]ext. It is probably loop 1223 // invariant and will be folded or hoisted. If it actually comes from a 1224 // widened IV, it should be removed during a future call to widenIVUse. 1225 bool IsSigned = getExtendKind(NarrowDef) == SignExtended; 1226 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1227 ? WideDef 1228 : createExtendInst(NarrowUse->getOperand(0), WideType, 1229 IsSigned, NarrowUse); 1230 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1231 ? WideDef 1232 : createExtendInst(NarrowUse->getOperand(1), WideType, 1233 IsSigned, NarrowUse); 1234 1235 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1236 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1237 NarrowBO->getName()); 1238 IRBuilder<> Builder(NarrowUse); 1239 Builder.Insert(WideBO); 1240 WideBO->copyIRFlags(NarrowBO); 1241 return WideBO; 1242 } 1243 1244 Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU, 1245 const SCEVAddRecExpr *WideAR) { 1246 Instruction *NarrowUse = DU.NarrowUse; 1247 Instruction *NarrowDef = DU.NarrowDef; 1248 Instruction *WideDef = DU.WideDef; 1249 1250 LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n"); 1251 1252 unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1; 1253 1254 // We're trying to find X such that 1255 // 1256 // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X 1257 // 1258 // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef), 1259 // and check using SCEV if any of them are correct. 1260 1261 // Returns true if extending NonIVNarrowDef according to `SignExt` is a 1262 // correct solution to X. 1263 auto GuessNonIVOperand = [&](bool SignExt) { 1264 const SCEV *WideLHS; 1265 const SCEV *WideRHS; 1266 1267 auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) { 1268 if (SignExt) 1269 return SE->getSignExtendExpr(S, Ty); 1270 return SE->getZeroExtendExpr(S, Ty); 1271 }; 1272 1273 if (IVOpIdx == 0) { 1274 WideLHS = SE->getSCEV(WideDef); 1275 const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1)); 1276 WideRHS = GetExtend(NarrowRHS, WideType); 1277 } else { 1278 const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0)); 1279 WideLHS = GetExtend(NarrowLHS, WideType); 1280 WideRHS = SE->getSCEV(WideDef); 1281 } 1282 1283 // WideUse is "WideDef `op.wide` X" as described in the comment. 1284 const SCEV *WideUse = 1285 getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode()); 1286 1287 return WideUse == WideAR; 1288 }; 1289 1290 bool SignExtend = getExtendKind(NarrowDef) == SignExtended; 1291 if (!GuessNonIVOperand(SignExtend)) { 1292 SignExtend = !SignExtend; 1293 if (!GuessNonIVOperand(SignExtend)) 1294 return nullptr; 1295 } 1296 1297 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1298 ? WideDef 1299 : createExtendInst(NarrowUse->getOperand(0), WideType, 1300 SignExtend, NarrowUse); 1301 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1302 ? WideDef 1303 : createExtendInst(NarrowUse->getOperand(1), WideType, 1304 SignExtend, NarrowUse); 1305 1306 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1307 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1308 NarrowBO->getName()); 1309 1310 IRBuilder<> Builder(NarrowUse); 1311 Builder.Insert(WideBO); 1312 WideBO->copyIRFlags(NarrowBO); 1313 return WideBO; 1314 } 1315 1316 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) { 1317 auto It = ExtendKindMap.find(I); 1318 assert(It != ExtendKindMap.end() && "Instruction not yet extended!"); 1319 return It->second; 1320 } 1321 1322 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1323 unsigned OpCode) const { 1324 switch (OpCode) { 1325 case Instruction::Add: 1326 return SE->getAddExpr(LHS, RHS); 1327 case Instruction::Sub: 1328 return SE->getMinusSCEV(LHS, RHS); 1329 case Instruction::Mul: 1330 return SE->getMulExpr(LHS, RHS); 1331 case Instruction::UDiv: 1332 return SE->getUDivExpr(LHS, RHS); 1333 default: 1334 llvm_unreachable("Unsupported opcode."); 1335 }; 1336 } 1337 1338 /// No-wrap operations can transfer sign extension of their result to their 1339 /// operands. Generate the SCEV value for the widened operation without 1340 /// actually modifying the IR yet. If the expression after extending the 1341 /// operands is an AddRec for this loop, return the AddRec and the kind of 1342 /// extension used. 1343 WidenIV::WidenedRecTy 1344 WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) { 1345 // Handle the common case of add<nsw/nuw> 1346 const unsigned OpCode = DU.NarrowUse->getOpcode(); 1347 // Only Add/Sub/Mul instructions supported yet. 1348 if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 1349 OpCode != Instruction::Mul) 1350 return {nullptr, Unknown}; 1351 1352 // One operand (NarrowDef) has already been extended to WideDef. Now determine 1353 // if extending the other will lead to a recurrence. 1354 const unsigned ExtendOperIdx = 1355 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0; 1356 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU"); 1357 1358 const SCEV *ExtendOperExpr = nullptr; 1359 const OverflowingBinaryOperator *OBO = 1360 cast<OverflowingBinaryOperator>(DU.NarrowUse); 1361 ExtendKind ExtKind = getExtendKind(DU.NarrowDef); 1362 if (ExtKind == SignExtended && OBO->hasNoSignedWrap()) 1363 ExtendOperExpr = SE->getSignExtendExpr( 1364 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1365 else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap()) 1366 ExtendOperExpr = SE->getZeroExtendExpr( 1367 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1368 else 1369 return {nullptr, Unknown}; 1370 1371 // When creating this SCEV expr, don't apply the current operations NSW or NUW 1372 // flags. This instruction may be guarded by control flow that the no-wrap 1373 // behavior depends on. Non-control-equivalent instructions can be mapped to 1374 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW 1375 // semantics to those operations. 1376 const SCEV *lhs = SE->getSCEV(DU.WideDef); 1377 const SCEV *rhs = ExtendOperExpr; 1378 1379 // Let's swap operands to the initial order for the case of non-commutative 1380 // operations, like SUB. See PR21014. 1381 if (ExtendOperIdx == 0) 1382 std::swap(lhs, rhs); 1383 const SCEVAddRecExpr *AddRec = 1384 dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode)); 1385 1386 if (!AddRec || AddRec->getLoop() != L) 1387 return {nullptr, Unknown}; 1388 1389 return {AddRec, ExtKind}; 1390 } 1391 1392 /// Is this instruction potentially interesting for further simplification after 1393 /// widening it's type? In other words, can the extend be safely hoisted out of 1394 /// the loop with SCEV reducing the value to a recurrence on the same loop. If 1395 /// so, return the extended recurrence and the kind of extension used. Otherwise 1396 /// return {nullptr, Unknown}. 1397 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) { 1398 if (!DU.NarrowUse->getType()->isIntegerTy()) 1399 return {nullptr, Unknown}; 1400 1401 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse); 1402 if (SE->getTypeSizeInBits(NarrowExpr->getType()) >= 1403 SE->getTypeSizeInBits(WideType)) { 1404 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow 1405 // index. So don't follow this use. 1406 return {nullptr, Unknown}; 1407 } 1408 1409 const SCEV *WideExpr; 1410 ExtendKind ExtKind; 1411 if (DU.NeverNegative) { 1412 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1413 if (isa<SCEVAddRecExpr>(WideExpr)) 1414 ExtKind = SignExtended; 1415 else { 1416 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1417 ExtKind = ZeroExtended; 1418 } 1419 } else if (getExtendKind(DU.NarrowDef) == SignExtended) { 1420 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1421 ExtKind = SignExtended; 1422 } else { 1423 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1424 ExtKind = ZeroExtended; 1425 } 1426 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); 1427 if (!AddRec || AddRec->getLoop() != L) 1428 return {nullptr, Unknown}; 1429 return {AddRec, ExtKind}; 1430 } 1431 1432 /// This IV user cannot be widened. Replace this use of the original narrow IV 1433 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV. 1434 static void truncateIVUse(WidenIV::NarrowIVDefUse DU, DominatorTree *DT, 1435 LoopInfo *LI) { 1436 auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI); 1437 if (!InsertPt) 1438 return; 1439 LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user " 1440 << *DU.NarrowUse << "\n"); 1441 IRBuilder<> Builder(InsertPt); 1442 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType()); 1443 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); 1444 } 1445 1446 /// If the narrow use is a compare instruction, then widen the compare 1447 // (and possibly the other operand). The extend operation is hoisted into the 1448 // loop preheader as far as possible. 1449 bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) { 1450 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse); 1451 if (!Cmp) 1452 return false; 1453 1454 // We can legally widen the comparison in the following two cases: 1455 // 1456 // - The signedness of the IV extension and comparison match 1457 // 1458 // - The narrow IV is always positive (and thus its sign extension is equal 1459 // to its zero extension). For instance, let's say we're zero extending 1460 // %narrow for the following use 1461 // 1462 // icmp slt i32 %narrow, %val ... (A) 1463 // 1464 // and %narrow is always positive. Then 1465 // 1466 // (A) == icmp slt i32 sext(%narrow), sext(%val) 1467 // == icmp slt i32 zext(%narrow), sext(%val) 1468 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended; 1469 if (!(DU.NeverNegative || IsSigned == Cmp->isSigned())) 1470 return false; 1471 1472 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0); 1473 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType()); 1474 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1475 assert(CastWidth <= IVWidth && "Unexpected width while widening compare."); 1476 1477 // Widen the compare instruction. 1478 auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI); 1479 if (!InsertPt) 1480 return false; 1481 IRBuilder<> Builder(InsertPt); 1482 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1483 1484 // Widen the other operand of the compare, if necessary. 1485 if (CastWidth < IVWidth) { 1486 Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp); 1487 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp); 1488 } 1489 return true; 1490 } 1491 1492 // The widenIVUse avoids generating trunc by evaluating the use as AddRec, this 1493 // will not work when: 1494 // 1) SCEV traces back to an instruction inside the loop that SCEV can not 1495 // expand, eg. add %indvar, (load %addr) 1496 // 2) SCEV finds a loop variant, eg. add %indvar, %loopvariant 1497 // While SCEV fails to avoid trunc, we can still try to use instruction 1498 // combining approach to prove trunc is not required. This can be further 1499 // extended with other instruction combining checks, but for now we handle the 1500 // following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext") 1501 // 1502 // Src: 1503 // %c = sub nsw %b, %indvar 1504 // %d = sext %c to i64 1505 // Dst: 1506 // %indvar.ext1 = sext %indvar to i64 1507 // %m = sext %b to i64 1508 // %d = sub nsw i64 %m, %indvar.ext1 1509 // Therefore, as long as the result of add/sub/mul is extended to wide type, no 1510 // trunc is required regardless of how %b is generated. This pattern is common 1511 // when calculating address in 64 bit architecture 1512 bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) { 1513 Instruction *NarrowUse = DU.NarrowUse; 1514 Instruction *NarrowDef = DU.NarrowDef; 1515 Instruction *WideDef = DU.WideDef; 1516 1517 // Handle the common case of add<nsw/nuw> 1518 const unsigned OpCode = NarrowUse->getOpcode(); 1519 // Only Add/Sub/Mul instructions are supported. 1520 if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 1521 OpCode != Instruction::Mul) 1522 return false; 1523 1524 // The operand that is not defined by NarrowDef of DU. Let's call it the 1525 // other operand. 1526 assert((NarrowUse->getOperand(0) == NarrowDef || 1527 NarrowUse->getOperand(1) == NarrowDef) && 1528 "bad DU"); 1529 1530 const OverflowingBinaryOperator *OBO = 1531 cast<OverflowingBinaryOperator>(NarrowUse); 1532 ExtendKind ExtKind = getExtendKind(NarrowDef); 1533 bool CanSignExtend = ExtKind == SignExtended && OBO->hasNoSignedWrap(); 1534 bool CanZeroExtend = ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap(); 1535 auto AnotherOpExtKind = ExtKind; 1536 1537 // Check that all uses are either: 1538 // - narrow def (in case of we are widening the IV increment); 1539 // - single-input LCSSA Phis; 1540 // - comparison of the chosen type; 1541 // - extend of the chosen type (raison d'etre). 1542 SmallVector<Instruction *, 4> ExtUsers; 1543 SmallVector<PHINode *, 4> LCSSAPhiUsers; 1544 SmallVector<ICmpInst *, 4> ICmpUsers; 1545 for (Use &U : NarrowUse->uses()) { 1546 Instruction *User = cast<Instruction>(U.getUser()); 1547 if (User == NarrowDef) 1548 continue; 1549 if (!L->contains(User)) { 1550 auto *LCSSAPhi = cast<PHINode>(User); 1551 // Make sure there is only 1 input, so that we don't have to split 1552 // critical edges. 1553 if (LCSSAPhi->getNumOperands() != 1) 1554 return false; 1555 LCSSAPhiUsers.push_back(LCSSAPhi); 1556 continue; 1557 } 1558 if (auto *ICmp = dyn_cast<ICmpInst>(User)) { 1559 auto Pred = ICmp->getPredicate(); 1560 // We have 3 types of predicates: signed, unsigned and equality 1561 // predicates. For equality, it's legal to widen icmp for either sign and 1562 // zero extend. For sign extend, we can also do so for signed predicates, 1563 // likeweise for zero extend we can widen icmp for unsigned predicates. 1564 if (ExtKind == ZeroExtended && ICmpInst::isSigned(Pred)) 1565 return false; 1566 if (ExtKind == SignExtended && ICmpInst::isUnsigned(Pred)) 1567 return false; 1568 ICmpUsers.push_back(ICmp); 1569 continue; 1570 } 1571 if (ExtKind == SignExtended) 1572 User = dyn_cast<SExtInst>(User); 1573 else 1574 User = dyn_cast<ZExtInst>(User); 1575 if (!User || User->getType() != WideType) 1576 return false; 1577 ExtUsers.push_back(User); 1578 } 1579 if (ExtUsers.empty()) { 1580 DeadInsts.emplace_back(NarrowUse); 1581 return true; 1582 } 1583 1584 // We'll prove some facts that should be true in the context of ext users. If 1585 // there is no users, we are done now. If there are some, pick their common 1586 // dominator as context. 1587 const Instruction *CtxI = findCommonDominator(ExtUsers, *DT); 1588 1589 if (!CanSignExtend && !CanZeroExtend) { 1590 // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we 1591 // will most likely not see it. Let's try to prove it. 1592 if (OpCode != Instruction::Add) 1593 return false; 1594 if (ExtKind != ZeroExtended) 1595 return false; 1596 const SCEV *LHS = SE->getSCEV(OBO->getOperand(0)); 1597 const SCEV *RHS = SE->getSCEV(OBO->getOperand(1)); 1598 // TODO: Support case for NarrowDef = NarrowUse->getOperand(1). 1599 if (NarrowUse->getOperand(0) != NarrowDef) 1600 return false; 1601 if (!SE->isKnownNegative(RHS)) 1602 return false; 1603 bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS, 1604 SE->getNegativeSCEV(RHS), CtxI); 1605 if (!ProvedSubNUW) 1606 return false; 1607 // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as 1608 // neg(zext(neg(op))), which is basically sext(op). 1609 AnotherOpExtKind = SignExtended; 1610 } 1611 1612 // Verifying that Defining operand is an AddRec 1613 const SCEV *Op1 = SE->getSCEV(WideDef); 1614 const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1); 1615 if (!AddRecOp1 || AddRecOp1->getLoop() != L) 1616 return false; 1617 1618 LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n"); 1619 1620 // Generating a widening use instruction. 1621 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1622 ? WideDef 1623 : createExtendInst(NarrowUse->getOperand(0), WideType, 1624 AnotherOpExtKind, NarrowUse); 1625 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1626 ? WideDef 1627 : createExtendInst(NarrowUse->getOperand(1), WideType, 1628 AnotherOpExtKind, NarrowUse); 1629 1630 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1631 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1632 NarrowBO->getName()); 1633 IRBuilder<> Builder(NarrowUse); 1634 Builder.Insert(WideBO); 1635 WideBO->copyIRFlags(NarrowBO); 1636 ExtendKindMap[NarrowUse] = ExtKind; 1637 1638 for (Instruction *User : ExtUsers) { 1639 assert(User->getType() == WideType && "Checked before!"); 1640 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by " 1641 << *WideBO << "\n"); 1642 ++NumElimExt; 1643 User->replaceAllUsesWith(WideBO); 1644 DeadInsts.emplace_back(User); 1645 } 1646 1647 for (PHINode *User : LCSSAPhiUsers) { 1648 assert(User->getNumOperands() == 1 && "Checked before!"); 1649 Builder.SetInsertPoint(User); 1650 auto *WidePN = 1651 Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide"); 1652 BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor(); 1653 assert(LoopExitingBlock && L->contains(LoopExitingBlock) && 1654 "Not a LCSSA Phi?"); 1655 WidePN->addIncoming(WideBO, LoopExitingBlock); 1656 Builder.SetInsertPoint(&*User->getParent()->getFirstInsertionPt()); 1657 auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType()); 1658 User->replaceAllUsesWith(TruncPN); 1659 DeadInsts.emplace_back(User); 1660 } 1661 1662 for (ICmpInst *User : ICmpUsers) { 1663 Builder.SetInsertPoint(User); 1664 auto ExtendedOp = [&](Value * V)->Value * { 1665 if (V == NarrowUse) 1666 return WideBO; 1667 if (ExtKind == ZeroExtended) 1668 return Builder.CreateZExt(V, WideBO->getType()); 1669 else 1670 return Builder.CreateSExt(V, WideBO->getType()); 1671 }; 1672 auto Pred = User->getPredicate(); 1673 auto *LHS = ExtendedOp(User->getOperand(0)); 1674 auto *RHS = ExtendedOp(User->getOperand(1)); 1675 auto *WideCmp = 1676 Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide"); 1677 User->replaceAllUsesWith(WideCmp); 1678 DeadInsts.emplace_back(User); 1679 } 1680 1681 return true; 1682 } 1683 1684 /// Determine whether an individual user of the narrow IV can be widened. If so, 1685 /// return the wide clone of the user. 1686 Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU, SCEVExpander &Rewriter) { 1687 assert(ExtendKindMap.count(DU.NarrowDef) && 1688 "Should already know the kind of extension used to widen NarrowDef"); 1689 1690 // Stop traversing the def-use chain at inner-loop phis or post-loop phis. 1691 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) { 1692 if (LI->getLoopFor(UsePhi->getParent()) != L) { 1693 // For LCSSA phis, sink the truncate outside the loop. 1694 // After SimplifyCFG most loop exit targets have a single predecessor. 1695 // Otherwise fall back to a truncate within the loop. 1696 if (UsePhi->getNumOperands() != 1) 1697 truncateIVUse(DU, DT, LI); 1698 else { 1699 // Widening the PHI requires us to insert a trunc. The logical place 1700 // for this trunc is in the same BB as the PHI. This is not possible if 1701 // the BB is terminated by a catchswitch. 1702 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator())) 1703 return nullptr; 1704 1705 PHINode *WidePhi = 1706 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide", 1707 UsePhi); 1708 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0)); 1709 IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt()); 1710 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType()); 1711 UsePhi->replaceAllUsesWith(Trunc); 1712 DeadInsts.emplace_back(UsePhi); 1713 LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to " 1714 << *WidePhi << "\n"); 1715 } 1716 return nullptr; 1717 } 1718 } 1719 1720 // This narrow use can be widened by a sext if it's non-negative or its narrow 1721 // def was widended by a sext. Same for zext. 1722 auto canWidenBySExt = [&]() { 1723 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended; 1724 }; 1725 auto canWidenByZExt = [&]() { 1726 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended; 1727 }; 1728 1729 // Our raison d'etre! Eliminate sign and zero extension. 1730 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) || 1731 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) { 1732 Value *NewDef = DU.WideDef; 1733 if (DU.NarrowUse->getType() != WideType) { 1734 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); 1735 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1736 if (CastWidth < IVWidth) { 1737 // The cast isn't as wide as the IV, so insert a Trunc. 1738 IRBuilder<> Builder(DU.NarrowUse); 1739 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType()); 1740 } 1741 else { 1742 // A wider extend was hidden behind a narrower one. This may induce 1743 // another round of IV widening in which the intermediate IV becomes 1744 // dead. It should be very rare. 1745 LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi 1746 << " not wide enough to subsume " << *DU.NarrowUse 1747 << "\n"); 1748 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1749 NewDef = DU.NarrowUse; 1750 } 1751 } 1752 if (NewDef != DU.NarrowUse) { 1753 LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse 1754 << " replaced by " << *DU.WideDef << "\n"); 1755 ++NumElimExt; 1756 DU.NarrowUse->replaceAllUsesWith(NewDef); 1757 DeadInsts.emplace_back(DU.NarrowUse); 1758 } 1759 // Now that the extend is gone, we want to expose it's uses for potential 1760 // further simplification. We don't need to directly inform SimplifyIVUsers 1761 // of the new users, because their parent IV will be processed later as a 1762 // new loop phi. If we preserved IVUsers analysis, we would also want to 1763 // push the uses of WideDef here. 1764 1765 // No further widening is needed. The deceased [sz]ext had done it for us. 1766 return nullptr; 1767 } 1768 1769 // Does this user itself evaluate to a recurrence after widening? 1770 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU); 1771 if (!WideAddRec.first) 1772 WideAddRec = getWideRecurrence(DU); 1773 1774 assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown)); 1775 if (!WideAddRec.first) { 1776 // If use is a loop condition, try to promote the condition instead of 1777 // truncating the IV first. 1778 if (widenLoopCompare(DU)) 1779 return nullptr; 1780 1781 // We are here about to generate a truncate instruction that may hurt 1782 // performance because the scalar evolution expression computed earlier 1783 // in WideAddRec.first does not indicate a polynomial induction expression. 1784 // In that case, look at the operands of the use instruction to determine 1785 // if we can still widen the use instead of truncating its operand. 1786 if (widenWithVariantUse(DU)) 1787 return nullptr; 1788 1789 // This user does not evaluate to a recurrence after widening, so don't 1790 // follow it. Instead insert a Trunc to kill off the original use, 1791 // eventually isolating the original narrow IV so it can be removed. 1792 truncateIVUse(DU, DT, LI); 1793 return nullptr; 1794 } 1795 1796 // Reuse the IV increment that SCEVExpander created as long as it dominates 1797 // NarrowUse. 1798 Instruction *WideUse = nullptr; 1799 if (WideAddRec.first == WideIncExpr && 1800 Rewriter.hoistIVInc(WideInc, DU.NarrowUse)) 1801 WideUse = WideInc; 1802 else { 1803 WideUse = cloneIVUser(DU, WideAddRec.first); 1804 if (!WideUse) 1805 return nullptr; 1806 } 1807 // Evaluation of WideAddRec ensured that the narrow expression could be 1808 // extended outside the loop without overflow. This suggests that the wide use 1809 // evaluates to the same expression as the extended narrow use, but doesn't 1810 // absolutely guarantee it. Hence the following failsafe check. In rare cases 1811 // where it fails, we simply throw away the newly created wide use. 1812 if (WideAddRec.first != SE->getSCEV(WideUse)) { 1813 LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": " 1814 << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first 1815 << "\n"); 1816 DeadInsts.emplace_back(WideUse); 1817 return nullptr; 1818 } 1819 1820 // if we reached this point then we are going to replace 1821 // DU.NarrowUse with WideUse. Reattach DbgValue then. 1822 replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT); 1823 1824 ExtendKindMap[DU.NarrowUse] = WideAddRec.second; 1825 // Returning WideUse pushes it on the worklist. 1826 return WideUse; 1827 } 1828 1829 /// Add eligible users of NarrowDef to NarrowIVUsers. 1830 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { 1831 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef); 1832 bool NonNegativeDef = 1833 SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV, 1834 SE->getZero(NarrowSCEV->getType())); 1835 for (User *U : NarrowDef->users()) { 1836 Instruction *NarrowUser = cast<Instruction>(U); 1837 1838 // Handle data flow merges and bizarre phi cycles. 1839 if (!Widened.insert(NarrowUser).second) 1840 continue; 1841 1842 bool NonNegativeUse = false; 1843 if (!NonNegativeDef) { 1844 // We might have a control-dependent range information for this context. 1845 if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser)) 1846 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative(); 1847 } 1848 1849 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef, 1850 NonNegativeDef || NonNegativeUse); 1851 } 1852 } 1853 1854 /// Process a single induction variable. First use the SCEVExpander to create a 1855 /// wide induction variable that evaluates to the same recurrence as the 1856 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's 1857 /// def-use chain. After widenIVUse has processed all interesting IV users, the 1858 /// narrow IV will be isolated for removal by DeleteDeadPHIs. 1859 /// 1860 /// It would be simpler to delete uses as they are processed, but we must avoid 1861 /// invalidating SCEV expressions. 1862 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) { 1863 // Is this phi an induction variable? 1864 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); 1865 if (!AddRec) 1866 return nullptr; 1867 1868 // Widen the induction variable expression. 1869 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended 1870 ? SE->getSignExtendExpr(AddRec, WideType) 1871 : SE->getZeroExtendExpr(AddRec, WideType); 1872 1873 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && 1874 "Expect the new IV expression to preserve its type"); 1875 1876 // Can the IV be extended outside the loop without overflow? 1877 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); 1878 if (!AddRec || AddRec->getLoop() != L) 1879 return nullptr; 1880 1881 // An AddRec must have loop-invariant operands. Since this AddRec is 1882 // materialized by a loop header phi, the expression cannot have any post-loop 1883 // operands, so they must dominate the loop header. 1884 assert( 1885 SE->properlyDominates(AddRec->getStart(), L->getHeader()) && 1886 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) && 1887 "Loop header phi recurrence inputs do not dominate the loop"); 1888 1889 // Iterate over IV uses (including transitive ones) looking for IV increments 1890 // of the form 'add nsw %iv, <const>'. For each increment and each use of 1891 // the increment calculate control-dependent range information basing on 1892 // dominating conditions inside of the loop (e.g. a range check inside of the 1893 // loop). Calculated ranges are stored in PostIncRangeInfos map. 1894 // 1895 // Control-dependent range information is later used to prove that a narrow 1896 // definition is not negative (see pushNarrowIVUsers). It's difficult to do 1897 // this on demand because when pushNarrowIVUsers needs this information some 1898 // of the dominating conditions might be already widened. 1899 if (UsePostIncrementRanges) 1900 calculatePostIncRanges(OrigPhi); 1901 1902 // The rewriter provides a value for the desired IV expression. This may 1903 // either find an existing phi or materialize a new one. Either way, we 1904 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part 1905 // of the phi-SCC dominates the loop entry. 1906 Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt(); 1907 Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt); 1908 // If the wide phi is not a phi node, for example a cast node, like bitcast, 1909 // inttoptr, ptrtoint, just skip for now. 1910 if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) { 1911 // if the cast node is an inserted instruction without any user, we should 1912 // remove it to make sure the pass don't touch the function as we can not 1913 // wide the phi. 1914 if (ExpandInst->hasNUses(0) && 1915 Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst))) 1916 DeadInsts.emplace_back(ExpandInst); 1917 return nullptr; 1918 } 1919 1920 // Remembering the WideIV increment generated by SCEVExpander allows 1921 // widenIVUse to reuse it when widening the narrow IV's increment. We don't 1922 // employ a general reuse mechanism because the call above is the only call to 1923 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. 1924 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1925 WideInc = 1926 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); 1927 WideIncExpr = SE->getSCEV(WideInc); 1928 // Propagate the debug location associated with the original loop increment 1929 // to the new (widened) increment. 1930 auto *OrigInc = 1931 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock)); 1932 WideInc->setDebugLoc(OrigInc->getDebugLoc()); 1933 } 1934 1935 LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); 1936 ++NumWidened; 1937 1938 // Traverse the def-use chain using a worklist starting at the original IV. 1939 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); 1940 1941 Widened.insert(OrigPhi); 1942 pushNarrowIVUsers(OrigPhi, WidePhi); 1943 1944 while (!NarrowIVUsers.empty()) { 1945 WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); 1946 1947 // Process a def-use edge. This may replace the use, so don't hold a 1948 // use_iterator across it. 1949 Instruction *WideUse = widenIVUse(DU, Rewriter); 1950 1951 // Follow all def-use edges from the previous narrow use. 1952 if (WideUse) 1953 pushNarrowIVUsers(DU.NarrowUse, WideUse); 1954 1955 // widenIVUse may have removed the def-use edge. 1956 if (DU.NarrowDef->use_empty()) 1957 DeadInsts.emplace_back(DU.NarrowDef); 1958 } 1959 1960 // Attach any debug information to the new PHI. 1961 replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT); 1962 1963 return WidePhi; 1964 } 1965 1966 /// Calculates control-dependent range for the given def at the given context 1967 /// by looking at dominating conditions inside of the loop 1968 void WidenIV::calculatePostIncRange(Instruction *NarrowDef, 1969 Instruction *NarrowUser) { 1970 using namespace llvm::PatternMatch; 1971 1972 Value *NarrowDefLHS; 1973 const APInt *NarrowDefRHS; 1974 if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS), 1975 m_APInt(NarrowDefRHS))) || 1976 !NarrowDefRHS->isNonNegative()) 1977 return; 1978 1979 auto UpdateRangeFromCondition = [&] (Value *Condition, 1980 bool TrueDest) { 1981 CmpInst::Predicate Pred; 1982 Value *CmpRHS; 1983 if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS), 1984 m_Value(CmpRHS)))) 1985 return; 1986 1987 CmpInst::Predicate P = 1988 TrueDest ? Pred : CmpInst::getInversePredicate(Pred); 1989 1990 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS)); 1991 auto CmpConstrainedLHSRange = 1992 ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange); 1993 auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap( 1994 *NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap); 1995 1996 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange); 1997 }; 1998 1999 auto UpdateRangeFromGuards = [&](Instruction *Ctx) { 2000 if (!HasGuards) 2001 return; 2002 2003 for (Instruction &I : make_range(Ctx->getIterator().getReverse(), 2004 Ctx->getParent()->rend())) { 2005 Value *C = nullptr; 2006 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C)))) 2007 UpdateRangeFromCondition(C, /*TrueDest=*/true); 2008 } 2009 }; 2010 2011 UpdateRangeFromGuards(NarrowUser); 2012 2013 BasicBlock *NarrowUserBB = NarrowUser->getParent(); 2014 // If NarrowUserBB is statically unreachable asking dominator queries may 2015 // yield surprising results. (e.g. the block may not have a dom tree node) 2016 if (!DT->isReachableFromEntry(NarrowUserBB)) 2017 return; 2018 2019 for (auto *DTB = (*DT)[NarrowUserBB]->getIDom(); 2020 L->contains(DTB->getBlock()); 2021 DTB = DTB->getIDom()) { 2022 auto *BB = DTB->getBlock(); 2023 auto *TI = BB->getTerminator(); 2024 UpdateRangeFromGuards(TI); 2025 2026 auto *BI = dyn_cast<BranchInst>(TI); 2027 if (!BI || !BI->isConditional()) 2028 continue; 2029 2030 auto *TrueSuccessor = BI->getSuccessor(0); 2031 auto *FalseSuccessor = BI->getSuccessor(1); 2032 2033 auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) { 2034 return BBE.isSingleEdge() && 2035 DT->dominates(BBE, NarrowUser->getParent()); 2036 }; 2037 2038 if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor))) 2039 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true); 2040 2041 if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor))) 2042 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false); 2043 } 2044 } 2045 2046 /// Calculates PostIncRangeInfos map for the given IV 2047 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) { 2048 SmallPtrSet<Instruction *, 16> Visited; 2049 SmallVector<Instruction *, 6> Worklist; 2050 Worklist.push_back(OrigPhi); 2051 Visited.insert(OrigPhi); 2052 2053 while (!Worklist.empty()) { 2054 Instruction *NarrowDef = Worklist.pop_back_val(); 2055 2056 for (Use &U : NarrowDef->uses()) { 2057 auto *NarrowUser = cast<Instruction>(U.getUser()); 2058 2059 // Don't go looking outside the current loop. 2060 auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()]; 2061 if (!NarrowUserLoop || !L->contains(NarrowUserLoop)) 2062 continue; 2063 2064 if (!Visited.insert(NarrowUser).second) 2065 continue; 2066 2067 Worklist.push_back(NarrowUser); 2068 2069 calculatePostIncRange(NarrowDef, NarrowUser); 2070 } 2071 } 2072 } 2073 2074 PHINode *llvm::createWideIV(const WideIVInfo &WI, 2075 LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, 2076 DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts, 2077 unsigned &NumElimExt, unsigned &NumWidened, 2078 bool HasGuards, bool UsePostIncrementRanges) { 2079 WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges); 2080 PHINode *WidePHI = Widener.createWideIV(Rewriter); 2081 NumElimExt = Widener.getNumElimExt(); 2082 NumWidened = Widener.getNumWidened(); 2083 return WidePHI; 2084 } 2085