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