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