1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This transformation analyzes and transforms the induction variables (and 11 // computations derived from them) into simpler forms suitable for subsequent 12 // analysis and transformation. 13 // 14 // If the trip count of a loop is computable, this pass also makes the following 15 // changes: 16 // 1. The exit condition for the loop is canonicalized to compare the 17 // induction value against the exit value. This turns loops like: 18 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)' 19 // 2. Any use outside of the loop of an expression derived from the indvar 20 // is changed to compute the derived value outside of the loop, eliminating 21 // the dependence on the exit value of the induction variable. If the only 22 // purpose of the loop is to compute the exit value of some derived 23 // expression, this transformation will make the loop dead. 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "llvm/Transforms/Scalar/IndVarSimplify.h" 28 #include "llvm/ADT/APFloat.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/ArrayRef.h" 31 #include "llvm/ADT/DenseMap.h" 32 #include "llvm/ADT/None.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallPtrSet.h" 36 #include "llvm/ADT/SmallVector.h" 37 #include "llvm/ADT/Statistic.h" 38 #include "llvm/ADT/iterator_range.h" 39 #include "llvm/Analysis/LoopInfo.h" 40 #include "llvm/Analysis/LoopPass.h" 41 #include "llvm/Analysis/ScalarEvolution.h" 42 #include "llvm/Analysis/ScalarEvolutionExpander.h" 43 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 44 #include "llvm/Analysis/TargetLibraryInfo.h" 45 #include "llvm/Analysis/TargetTransformInfo.h" 46 #include "llvm/IR/BasicBlock.h" 47 #include "llvm/IR/Constant.h" 48 #include "llvm/IR/ConstantRange.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Dominators.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/IRBuilder.h" 55 #include "llvm/IR/InstrTypes.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/IR/Intrinsics.h" 60 #include "llvm/IR/Module.h" 61 #include "llvm/IR/Operator.h" 62 #include "llvm/IR/PassManager.h" 63 #include "llvm/IR/PatternMatch.h" 64 #include "llvm/IR/Type.h" 65 #include "llvm/IR/Use.h" 66 #include "llvm/IR/User.h" 67 #include "llvm/IR/Value.h" 68 #include "llvm/IR/ValueHandle.h" 69 #include "llvm/Pass.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CommandLine.h" 72 #include "llvm/Support/Compiler.h" 73 #include "llvm/Support/Debug.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/MathExtras.h" 76 #include "llvm/Support/raw_ostream.h" 77 #include "llvm/Transforms/Scalar.h" 78 #include "llvm/Transforms/Scalar/LoopPassManager.h" 79 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 80 #include "llvm/Transforms/Utils/Local.h" 81 #include "llvm/Transforms/Utils/LoopUtils.h" 82 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 83 #include <cassert> 84 #include <cstdint> 85 #include <utility> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "indvars" 90 91 STATISTIC(NumWidened , "Number of indvars widened"); 92 STATISTIC(NumReplaced , "Number of exit values replaced"); 93 STATISTIC(NumLFTR , "Number of loop exit tests replaced"); 94 STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated"); 95 STATISTIC(NumElimIV , "Number of congruent IVs eliminated"); 96 97 // Trip count verification can be enabled by default under NDEBUG if we 98 // implement a strong expression equivalence checker in SCEV. Until then, we 99 // use the verify-indvars flag, which may assert in some cases. 100 static cl::opt<bool> VerifyIndvars( 101 "verify-indvars", cl::Hidden, 102 cl::desc("Verify the ScalarEvolution result after running indvars")); 103 104 enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl }; 105 106 static cl::opt<ReplaceExitVal> ReplaceExitValue( 107 "replexitval", cl::Hidden, cl::init(OnlyCheapRepl), 108 cl::desc("Choose the strategy to replace exit value in IndVarSimplify"), 109 cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"), 110 clEnumValN(OnlyCheapRepl, "cheap", 111 "only replace exit value when the cost is cheap"), 112 clEnumValN(AlwaysRepl, "always", 113 "always replace exit value whenever possible"))); 114 115 static cl::opt<bool> UsePostIncrementRanges( 116 "indvars-post-increment-ranges", cl::Hidden, 117 cl::desc("Use post increment control-dependent ranges in IndVarSimplify"), 118 cl::init(true)); 119 120 static cl::opt<bool> 121 DisableLFTR("disable-lftr", cl::Hidden, cl::init(false), 122 cl::desc("Disable Linear Function Test Replace optimization")); 123 124 namespace { 125 126 struct RewritePhi; 127 128 class IndVarSimplify { 129 LoopInfo *LI; 130 ScalarEvolution *SE; 131 DominatorTree *DT; 132 const DataLayout &DL; 133 TargetLibraryInfo *TLI; 134 const TargetTransformInfo *TTI; 135 136 SmallVector<WeakTrackingVH, 16> DeadInsts; 137 bool Changed = false; 138 139 bool isValidRewrite(Value *FromVal, Value *ToVal); 140 141 void handleFloatingPointIV(Loop *L, PHINode *PH); 142 void rewriteNonIntegerIVs(Loop *L); 143 144 void simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI); 145 146 bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet); 147 void rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter); 148 void rewriteFirstIterationLoopExitValues(Loop *L); 149 150 Value *linearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount, 151 PHINode *IndVar, SCEVExpander &Rewriter); 152 153 void sinkUnusedInvariants(Loop *L); 154 155 Value *expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, Loop *L, 156 Instruction *InsertPt, Type *Ty); 157 158 public: 159 IndVarSimplify(LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, 160 const DataLayout &DL, TargetLibraryInfo *TLI, 161 TargetTransformInfo *TTI) 162 : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {} 163 164 bool run(Loop *L); 165 }; 166 167 } // end anonymous namespace 168 169 /// Return true if the SCEV expansion generated by the rewriter can replace the 170 /// original value. SCEV guarantees that it produces the same value, but the way 171 /// it is produced may be illegal IR. Ideally, this function will only be 172 /// called for verification. 173 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) { 174 // If an SCEV expression subsumed multiple pointers, its expansion could 175 // reassociate the GEP changing the base pointer. This is illegal because the 176 // final address produced by a GEP chain must be inbounds relative to its 177 // underlying object. Otherwise basic alias analysis, among other things, 178 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 179 // producing an expression involving multiple pointers. Until then, we must 180 // bail out here. 181 // 182 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject 183 // because it understands lcssa phis while SCEV does not. 184 Value *FromPtr = FromVal; 185 Value *ToPtr = ToVal; 186 if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) { 187 FromPtr = GEP->getPointerOperand(); 188 } 189 if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) { 190 ToPtr = GEP->getPointerOperand(); 191 } 192 if (FromPtr != FromVal || ToPtr != ToVal) { 193 // Quickly check the common case 194 if (FromPtr == ToPtr) 195 return true; 196 197 // SCEV may have rewritten an expression that produces the GEP's pointer 198 // operand. That's ok as long as the pointer operand has the same base 199 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the 200 // base of a recurrence. This handles the case in which SCEV expansion 201 // converts a pointer type recurrence into a nonrecurrent pointer base 202 // indexed by an integer recurrence. 203 204 // If the GEP base pointer is a vector of pointers, abort. 205 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy()) 206 return false; 207 208 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 209 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 210 if (FromBase == ToBase) 211 return true; 212 213 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " 214 << *FromBase << " != " << *ToBase << "\n"); 215 216 return false; 217 } 218 return true; 219 } 220 221 /// Determine the insertion point for this user. By default, insert immediately 222 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the 223 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest 224 /// common dominator for the incoming blocks. 225 static Instruction *getInsertPointForUses(Instruction *User, Value *Def, 226 DominatorTree *DT, LoopInfo *LI) { 227 PHINode *PHI = dyn_cast<PHINode>(User); 228 if (!PHI) 229 return User; 230 231 Instruction *InsertPt = nullptr; 232 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { 233 if (PHI->getIncomingValue(i) != Def) 234 continue; 235 236 BasicBlock *InsertBB = PHI->getIncomingBlock(i); 237 if (!InsertPt) { 238 InsertPt = InsertBB->getTerminator(); 239 continue; 240 } 241 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); 242 InsertPt = InsertBB->getTerminator(); 243 } 244 assert(InsertPt && "Missing phi operand"); 245 246 auto *DefI = dyn_cast<Instruction>(Def); 247 if (!DefI) 248 return InsertPt; 249 250 assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses"); 251 252 auto *L = LI->getLoopFor(DefI->getParent()); 253 assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent()))); 254 255 for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom()) 256 if (LI->getLoopFor(DTN->getBlock()) == L) 257 return DTN->getBlock()->getTerminator(); 258 259 llvm_unreachable("DefI dominates InsertPt!"); 260 } 261 262 //===----------------------------------------------------------------------===// 263 // rewriteNonIntegerIVs and helpers. Prefer integer IVs. 264 //===----------------------------------------------------------------------===// 265 266 /// Convert APF to an integer, if possible. 267 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) { 268 bool isExact = false; 269 // See if we can convert this to an int64_t 270 uint64_t UIntVal; 271 if (APF.convertToInteger(makeMutableArrayRef(UIntVal), 64, true, 272 APFloat::rmTowardZero, &isExact) != APFloat::opOK || 273 !isExact) 274 return false; 275 IntVal = UIntVal; 276 return true; 277 } 278 279 /// If the loop has floating induction variable then insert corresponding 280 /// integer induction variable if possible. 281 /// For example, 282 /// for(double i = 0; i < 10000; ++i) 283 /// bar(i) 284 /// is converted into 285 /// for(int i = 0; i < 10000; ++i) 286 /// bar((double)i); 287 void IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) { 288 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 289 unsigned BackEdge = IncomingEdge^1; 290 291 // Check incoming value. 292 auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge)); 293 294 int64_t InitValue; 295 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue)) 296 return; 297 298 // Check IV increment. Reject this PN if increment operation is not 299 // an add or increment value can not be represented by an integer. 300 auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge)); 301 if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return; 302 303 // If this is not an add of the PHI with a constantfp, or if the constant fp 304 // is not an integer, bail out. 305 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1)); 306 int64_t IncValue; 307 if (IncValueVal == nullptr || Incr->getOperand(0) != PN || 308 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue)) 309 return; 310 311 // Check Incr uses. One user is PN and the other user is an exit condition 312 // used by the conditional terminator. 313 Value::user_iterator IncrUse = Incr->user_begin(); 314 Instruction *U1 = cast<Instruction>(*IncrUse++); 315 if (IncrUse == Incr->user_end()) return; 316 Instruction *U2 = cast<Instruction>(*IncrUse++); 317 if (IncrUse != Incr->user_end()) return; 318 319 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't 320 // only used by a branch, we can't transform it. 321 FCmpInst *Compare = dyn_cast<FCmpInst>(U1); 322 if (!Compare) 323 Compare = dyn_cast<FCmpInst>(U2); 324 if (!Compare || !Compare->hasOneUse() || 325 !isa<BranchInst>(Compare->user_back())) 326 return; 327 328 BranchInst *TheBr = cast<BranchInst>(Compare->user_back()); 329 330 // We need to verify that the branch actually controls the iteration count 331 // of the loop. If not, the new IV can overflow and no one will notice. 332 // The branch block must be in the loop and one of the successors must be out 333 // of the loop. 334 assert(TheBr->isConditional() && "Can't use fcmp if not conditional"); 335 if (!L->contains(TheBr->getParent()) || 336 (L->contains(TheBr->getSuccessor(0)) && 337 L->contains(TheBr->getSuccessor(1)))) 338 return; 339 340 // If it isn't a comparison with an integer-as-fp (the exit value), we can't 341 // transform it. 342 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1)); 343 int64_t ExitValue; 344 if (ExitValueVal == nullptr || 345 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue)) 346 return; 347 348 // Find new predicate for integer comparison. 349 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE; 350 switch (Compare->getPredicate()) { 351 default: return; // Unknown comparison. 352 case CmpInst::FCMP_OEQ: 353 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break; 354 case CmpInst::FCMP_ONE: 355 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break; 356 case CmpInst::FCMP_OGT: 357 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break; 358 case CmpInst::FCMP_OGE: 359 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break; 360 case CmpInst::FCMP_OLT: 361 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break; 362 case CmpInst::FCMP_OLE: 363 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break; 364 } 365 366 // We convert the floating point induction variable to a signed i32 value if 367 // we can. This is only safe if the comparison will not overflow in a way 368 // that won't be trapped by the integer equivalent operations. Check for this 369 // now. 370 // TODO: We could use i64 if it is native and the range requires it. 371 372 // The start/stride/exit values must all fit in signed i32. 373 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue)) 374 return; 375 376 // If not actually striding (add x, 0.0), avoid touching the code. 377 if (IncValue == 0) 378 return; 379 380 // Positive and negative strides have different safety conditions. 381 if (IncValue > 0) { 382 // If we have a positive stride, we require the init to be less than the 383 // exit value. 384 if (InitValue >= ExitValue) 385 return; 386 387 uint32_t Range = uint32_t(ExitValue-InitValue); 388 // Check for infinite loop, either: 389 // while (i <= Exit) or until (i > Exit) 390 if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) { 391 if (++Range == 0) return; // Range overflows. 392 } 393 394 unsigned Leftover = Range % uint32_t(IncValue); 395 396 // If this is an equality comparison, we require that the strided value 397 // exactly land on the exit value, otherwise the IV condition will wrap 398 // around and do things the fp IV wouldn't. 399 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 400 Leftover != 0) 401 return; 402 403 // If the stride would wrap around the i32 before exiting, we can't 404 // transform the IV. 405 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue) 406 return; 407 } else { 408 // If we have a negative stride, we require the init to be greater than the 409 // exit value. 410 if (InitValue <= ExitValue) 411 return; 412 413 uint32_t Range = uint32_t(InitValue-ExitValue); 414 // Check for infinite loop, either: 415 // while (i >= Exit) or until (i < Exit) 416 if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) { 417 if (++Range == 0) return; // Range overflows. 418 } 419 420 unsigned Leftover = Range % uint32_t(-IncValue); 421 422 // If this is an equality comparison, we require that the strided value 423 // exactly land on the exit value, otherwise the IV condition will wrap 424 // around and do things the fp IV wouldn't. 425 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 426 Leftover != 0) 427 return; 428 429 // If the stride would wrap around the i32 before exiting, we can't 430 // transform the IV. 431 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue) 432 return; 433 } 434 435 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext()); 436 437 // Insert new integer induction variable. 438 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN); 439 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue), 440 PN->getIncomingBlock(IncomingEdge)); 441 442 Value *NewAdd = 443 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue), 444 Incr->getName()+".int", Incr); 445 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge)); 446 447 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd, 448 ConstantInt::get(Int32Ty, ExitValue), 449 Compare->getName()); 450 451 // In the following deletions, PN may become dead and may be deleted. 452 // Use a WeakTrackingVH to observe whether this happens. 453 WeakTrackingVH WeakPH = PN; 454 455 // Delete the old floating point exit comparison. The branch starts using the 456 // new comparison. 457 NewCompare->takeName(Compare); 458 Compare->replaceAllUsesWith(NewCompare); 459 RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI); 460 461 // Delete the old floating point increment. 462 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType())); 463 RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI); 464 465 // If the FP induction variable still has uses, this is because something else 466 // in the loop uses its value. In order to canonicalize the induction 467 // variable, we chose to eliminate the IV and rewrite it in terms of an 468 // int->fp cast. 469 // 470 // We give preference to sitofp over uitofp because it is faster on most 471 // platforms. 472 if (WeakPH) { 473 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv", 474 &*PN->getParent()->getFirstInsertionPt()); 475 PN->replaceAllUsesWith(Conv); 476 RecursivelyDeleteTriviallyDeadInstructions(PN, TLI); 477 } 478 Changed = true; 479 } 480 481 void IndVarSimplify::rewriteNonIntegerIVs(Loop *L) { 482 // First step. Check to see if there are any floating-point recurrences. 483 // If there are, change them into integer recurrences, permitting analysis by 484 // the SCEV routines. 485 BasicBlock *Header = L->getHeader(); 486 487 SmallVector<WeakTrackingVH, 8> PHIs; 488 for (BasicBlock::iterator I = Header->begin(); 489 PHINode *PN = dyn_cast<PHINode>(I); ++I) 490 PHIs.push_back(PN); 491 492 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 493 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i])) 494 handleFloatingPointIV(L, PN); 495 496 // If the loop previously had floating-point IV, ScalarEvolution 497 // may not have been able to compute a trip count. Now that we've done some 498 // re-writing, the trip count may be computable. 499 if (Changed) 500 SE->forgetLoop(L); 501 } 502 503 namespace { 504 505 // Collect information about PHI nodes which can be transformed in 506 // rewriteLoopExitValues. 507 struct RewritePhi { 508 PHINode *PN; 509 510 // Ith incoming value. 511 unsigned Ith; 512 513 // Exit value after expansion. 514 Value *Val; 515 516 // High Cost when expansion. 517 bool HighCost; 518 519 RewritePhi(PHINode *P, unsigned I, Value *V, bool H) 520 : PN(P), Ith(I), Val(V), HighCost(H) {} 521 }; 522 523 } // end anonymous namespace 524 525 Value *IndVarSimplify::expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, 526 Loop *L, Instruction *InsertPt, 527 Type *ResultTy) { 528 // Before expanding S into an expensive LLVM expression, see if we can use an 529 // already existing value as the expansion for S. 530 if (Value *ExistingValue = Rewriter.getExactExistingExpansion(S, InsertPt, L)) 531 if (ExistingValue->getType() == ResultTy) 532 return ExistingValue; 533 534 // We didn't find anything, fall back to using SCEVExpander. 535 return Rewriter.expandCodeFor(S, ResultTy, InsertPt); 536 } 537 538 //===----------------------------------------------------------------------===// 539 // rewriteLoopExitValues - Optimize IV users outside the loop. 540 // As a side effect, reduces the amount of IV processing within the loop. 541 //===----------------------------------------------------------------------===// 542 543 /// Check to see if this loop has a computable loop-invariant execution count. 544 /// If so, this means that we can compute the final value of any expressions 545 /// that are recurrent in the loop, and substitute the exit values from the loop 546 /// into any instructions outside of the loop that use the final values of the 547 /// current expressions. 548 /// 549 /// This is mostly redundant with the regular IndVarSimplify activities that 550 /// happen later, except that it's more powerful in some cases, because it's 551 /// able to brute-force evaluate arbitrary instructions as long as they have 552 /// constant operands at the beginning of the loop. 553 void IndVarSimplify::rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) { 554 // Check a pre-condition. 555 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 556 "Indvars did not preserve LCSSA!"); 557 558 SmallVector<BasicBlock*, 8> ExitBlocks; 559 L->getUniqueExitBlocks(ExitBlocks); 560 561 SmallVector<RewritePhi, 8> RewritePhiSet; 562 // Find all values that are computed inside the loop, but used outside of it. 563 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 564 // the exit blocks of the loop to find them. 565 for (BasicBlock *ExitBB : ExitBlocks) { 566 // If there are no PHI nodes in this exit block, then no values defined 567 // inside the loop are used on this path, skip it. 568 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 569 if (!PN) continue; 570 571 unsigned NumPreds = PN->getNumIncomingValues(); 572 573 // Iterate over all of the PHI nodes. 574 BasicBlock::iterator BBI = ExitBB->begin(); 575 while ((PN = dyn_cast<PHINode>(BBI++))) { 576 if (PN->use_empty()) 577 continue; // dead use, don't replace it 578 579 if (!SE->isSCEVable(PN->getType())) 580 continue; 581 582 // It's necessary to tell ScalarEvolution about this explicitly so that 583 // it can walk the def-use list and forget all SCEVs, as it may not be 584 // watching the PHI itself. Once the new exit value is in place, there 585 // may not be a def-use connection between the loop and every instruction 586 // which got a SCEVAddRecExpr for that loop. 587 SE->forgetValue(PN); 588 589 // Iterate over all of the values in all the PHI nodes. 590 for (unsigned i = 0; i != NumPreds; ++i) { 591 // If the value being merged in is not integer or is not defined 592 // in the loop, skip it. 593 Value *InVal = PN->getIncomingValue(i); 594 if (!isa<Instruction>(InVal)) 595 continue; 596 597 // If this pred is for a subloop, not L itself, skip it. 598 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 599 continue; // The Block is in a subloop, skip it. 600 601 // Check that InVal is defined in the loop. 602 Instruction *Inst = cast<Instruction>(InVal); 603 if (!L->contains(Inst)) 604 continue; 605 606 // Okay, this instruction has a user outside of the current loop 607 // and varies predictably *inside* the loop. Evaluate the value it 608 // contains when the loop exits, if possible. 609 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 610 if (!SE->isLoopInvariant(ExitValue, L) || 611 !isSafeToExpand(ExitValue, *SE)) 612 continue; 613 614 // Computing the value outside of the loop brings no benefit if : 615 // - it is definitely used inside the loop in a way which can not be 616 // optimized away. 617 // - no use outside of the loop can take advantage of hoisting the 618 // computation out of the loop 619 if (ExitValue->getSCEVType()>=scMulExpr) { 620 unsigned NumHardInternalUses = 0; 621 unsigned NumSoftExternalUses = 0; 622 unsigned NumUses = 0; 623 for (auto IB = Inst->user_begin(), IE = Inst->user_end(); 624 IB != IE && NumUses <= 6; ++IB) { 625 Instruction *UseInstr = cast<Instruction>(*IB); 626 unsigned Opc = UseInstr->getOpcode(); 627 NumUses++; 628 if (L->contains(UseInstr)) { 629 if (Opc == Instruction::Call || Opc == Instruction::Ret) 630 NumHardInternalUses++; 631 } else { 632 if (Opc == Instruction::PHI) { 633 // Do not count the Phi as a use. LCSSA may have inserted 634 // plenty of trivial ones. 635 NumUses--; 636 for (auto PB = UseInstr->user_begin(), 637 PE = UseInstr->user_end(); 638 PB != PE && NumUses <= 6; ++PB, ++NumUses) { 639 unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode(); 640 if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret) 641 NumSoftExternalUses++; 642 } 643 continue; 644 } 645 if (Opc != Instruction::Call && Opc != Instruction::Ret) 646 NumSoftExternalUses++; 647 } 648 } 649 if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses) 650 continue; 651 } 652 653 bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst); 654 Value *ExitVal = 655 expandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->getType()); 656 657 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n' 658 << " LoopVal = " << *Inst << "\n"); 659 660 if (!isValidRewrite(Inst, ExitVal)) { 661 DeadInsts.push_back(ExitVal); 662 continue; 663 } 664 665 // Collect all the candidate PHINodes to be rewritten. 666 RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost); 667 } 668 } 669 } 670 671 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet); 672 673 // Transformation. 674 for (const RewritePhi &Phi : RewritePhiSet) { 675 PHINode *PN = Phi.PN; 676 Value *ExitVal = Phi.Val; 677 678 // Only do the rewrite when the ExitValue can be expanded cheaply. 679 // If LoopCanBeDel is true, rewrite exit value aggressively. 680 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) { 681 DeadInsts.push_back(ExitVal); 682 continue; 683 } 684 685 Changed = true; 686 ++NumReplaced; 687 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith)); 688 PN->setIncomingValue(Phi.Ith, ExitVal); 689 690 // If this instruction is dead now, delete it. Don't do it now to avoid 691 // invalidating iterators. 692 if (isInstructionTriviallyDead(Inst, TLI)) 693 DeadInsts.push_back(Inst); 694 695 // Replace PN with ExitVal if that is legal and does not break LCSSA. 696 if (PN->getNumIncomingValues() == 1 && 697 LI->replacementPreservesLCSSAForm(PN, ExitVal)) { 698 PN->replaceAllUsesWith(ExitVal); 699 PN->eraseFromParent(); 700 } 701 } 702 703 // The insertion point instruction may have been deleted; clear it out 704 // so that the rewriter doesn't trip over it later. 705 Rewriter.clearInsertPoint(); 706 } 707 708 //===---------------------------------------------------------------------===// 709 // rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know 710 // they will exit at the first iteration. 711 //===---------------------------------------------------------------------===// 712 713 /// Check to see if this loop has loop invariant conditions which lead to loop 714 /// exits. If so, we know that if the exit path is taken, it is at the first 715 /// loop iteration. This lets us predict exit values of PHI nodes that live in 716 /// loop header. 717 void IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) { 718 // Verify the input to the pass is already in LCSSA form. 719 assert(L->isLCSSAForm(*DT)); 720 721 SmallVector<BasicBlock *, 8> ExitBlocks; 722 L->getUniqueExitBlocks(ExitBlocks); 723 auto *LoopHeader = L->getHeader(); 724 assert(LoopHeader && "Invalid loop"); 725 726 for (auto *ExitBB : ExitBlocks) { 727 BasicBlock::iterator BBI = ExitBB->begin(); 728 // If there are no more PHI nodes in this exit block, then no more 729 // values defined inside the loop are used on this path. 730 while (auto *PN = dyn_cast<PHINode>(BBI++)) { 731 for (unsigned IncomingValIdx = 0, E = PN->getNumIncomingValues(); 732 IncomingValIdx != E; ++IncomingValIdx) { 733 auto *IncomingBB = PN->getIncomingBlock(IncomingValIdx); 734 735 // We currently only support loop exits from loop header. If the 736 // incoming block is not loop header, we need to recursively check 737 // all conditions starting from loop header are loop invariants. 738 // Additional support might be added in the future. 739 if (IncomingBB != LoopHeader) 740 continue; 741 742 // Get condition that leads to the exit path. 743 auto *TermInst = IncomingBB->getTerminator(); 744 745 Value *Cond = nullptr; 746 if (auto *BI = dyn_cast<BranchInst>(TermInst)) { 747 // Must be a conditional branch, otherwise the block 748 // should not be in the loop. 749 Cond = BI->getCondition(); 750 } else if (auto *SI = dyn_cast<SwitchInst>(TermInst)) 751 Cond = SI->getCondition(); 752 else 753 continue; 754 755 if (!L->isLoopInvariant(Cond)) 756 continue; 757 758 auto *ExitVal = 759 dyn_cast<PHINode>(PN->getIncomingValue(IncomingValIdx)); 760 761 // Only deal with PHIs. 762 if (!ExitVal) 763 continue; 764 765 // If ExitVal is a PHI on the loop header, then we know its 766 // value along this exit because the exit can only be taken 767 // on the first iteration. 768 auto *LoopPreheader = L->getLoopPreheader(); 769 assert(LoopPreheader && "Invalid loop"); 770 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader); 771 if (PreheaderIdx != -1) { 772 assert(ExitVal->getParent() == LoopHeader && 773 "ExitVal must be in loop header"); 774 PN->setIncomingValue(IncomingValIdx, 775 ExitVal->getIncomingValue(PreheaderIdx)); 776 } 777 } 778 } 779 } 780 } 781 782 /// Check whether it is possible to delete the loop after rewriting exit 783 /// value. If it is possible, ignore ReplaceExitValue and do rewriting 784 /// aggressively. 785 bool IndVarSimplify::canLoopBeDeleted( 786 Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) { 787 BasicBlock *Preheader = L->getLoopPreheader(); 788 // If there is no preheader, the loop will not be deleted. 789 if (!Preheader) 790 return false; 791 792 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1. 793 // We obviate multiple ExitingBlocks case for simplicity. 794 // TODO: If we see testcase with multiple ExitingBlocks can be deleted 795 // after exit value rewriting, we can enhance the logic here. 796 SmallVector<BasicBlock *, 4> ExitingBlocks; 797 L->getExitingBlocks(ExitingBlocks); 798 SmallVector<BasicBlock *, 8> ExitBlocks; 799 L->getUniqueExitBlocks(ExitBlocks); 800 if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1) 801 return false; 802 803 BasicBlock *ExitBlock = ExitBlocks[0]; 804 BasicBlock::iterator BI = ExitBlock->begin(); 805 while (PHINode *P = dyn_cast<PHINode>(BI)) { 806 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); 807 808 // If the Incoming value of P is found in RewritePhiSet, we know it 809 // could be rewritten to use a loop invariant value in transformation 810 // phase later. Skip it in the loop invariant check below. 811 bool found = false; 812 for (const RewritePhi &Phi : RewritePhiSet) { 813 unsigned i = Phi.Ith; 814 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) { 815 found = true; 816 break; 817 } 818 } 819 820 Instruction *I; 821 if (!found && (I = dyn_cast<Instruction>(Incoming))) 822 if (!L->hasLoopInvariantOperands(I)) 823 return false; 824 825 ++BI; 826 } 827 828 for (auto *BB : L->blocks()) 829 if (llvm::any_of(*BB, [](Instruction &I) { 830 return I.mayHaveSideEffects(); 831 })) 832 return false; 833 834 return true; 835 } 836 837 //===----------------------------------------------------------------------===// 838 // IV Widening - Extend the width of an IV to cover its widest uses. 839 //===----------------------------------------------------------------------===// 840 841 namespace { 842 843 // Collect information about induction variables that are used by sign/zero 844 // extend operations. This information is recorded by CollectExtend and provides 845 // the input to WidenIV. 846 struct WideIVInfo { 847 PHINode *NarrowIV = nullptr; 848 849 // Widest integer type created [sz]ext 850 Type *WidestNativeType = nullptr; 851 852 // Was a sext user seen before a zext? 853 bool IsSigned = false; 854 }; 855 856 } // end anonymous namespace 857 858 /// Update information about the induction variable that is extended by this 859 /// sign or zero extend operation. This is used to determine the final width of 860 /// the IV before actually widening it. 861 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE, 862 const TargetTransformInfo *TTI) { 863 bool IsSigned = Cast->getOpcode() == Instruction::SExt; 864 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt) 865 return; 866 867 Type *Ty = Cast->getType(); 868 uint64_t Width = SE->getTypeSizeInBits(Ty); 869 if (!Cast->getModule()->getDataLayout().isLegalInteger(Width)) 870 return; 871 872 // Check that `Cast` actually extends the induction variable (we rely on this 873 // later). This takes care of cases where `Cast` is extending a truncation of 874 // the narrow induction variable, and thus can end up being narrower than the 875 // "narrow" induction variable. 876 uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType()); 877 if (NarrowIVWidth >= Width) 878 return; 879 880 // Cast is either an sext or zext up to this point. 881 // We should not widen an indvar if arithmetics on the wider indvar are more 882 // expensive than those on the narrower indvar. We check only the cost of ADD 883 // because at least an ADD is required to increment the induction variable. We 884 // could compute more comprehensively the cost of all instructions on the 885 // induction variable when necessary. 886 if (TTI && 887 TTI->getArithmeticInstrCost(Instruction::Add, Ty) > 888 TTI->getArithmeticInstrCost(Instruction::Add, 889 Cast->getOperand(0)->getType())) { 890 return; 891 } 892 893 if (!WI.WidestNativeType) { 894 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 895 WI.IsSigned = IsSigned; 896 return; 897 } 898 899 // We extend the IV to satisfy the sign of its first user, arbitrarily. 900 if (WI.IsSigned != IsSigned) 901 return; 902 903 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType)) 904 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 905 } 906 907 namespace { 908 909 /// Record a link in the Narrow IV def-use chain along with the WideIV that 910 /// computes the same value as the Narrow IV def. This avoids caching Use* 911 /// pointers. 912 struct NarrowIVDefUse { 913 Instruction *NarrowDef = nullptr; 914 Instruction *NarrowUse = nullptr; 915 Instruction *WideDef = nullptr; 916 917 // True if the narrow def is never negative. Tracking this information lets 918 // us use a sign extension instead of a zero extension or vice versa, when 919 // profitable and legal. 920 bool NeverNegative = false; 921 922 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD, 923 bool NeverNegative) 924 : NarrowDef(ND), NarrowUse(NU), WideDef(WD), 925 NeverNegative(NeverNegative) {} 926 }; 927 928 /// The goal of this transform is to remove sign and zero extends without 929 /// creating any new induction variables. To do this, it creates a new phi of 930 /// the wider type and redirects all users, either removing extends or inserting 931 /// truncs whenever we stop propagating the type. 932 class WidenIV { 933 // Parameters 934 PHINode *OrigPhi; 935 Type *WideType; 936 937 // Context 938 LoopInfo *LI; 939 Loop *L; 940 ScalarEvolution *SE; 941 DominatorTree *DT; 942 943 // Does the module have any calls to the llvm.experimental.guard intrinsic 944 // at all? If not we can avoid scanning instructions looking for guards. 945 bool HasGuards; 946 947 // Result 948 PHINode *WidePhi = nullptr; 949 Instruction *WideInc = nullptr; 950 const SCEV *WideIncExpr = nullptr; 951 SmallVectorImpl<WeakTrackingVH> &DeadInsts; 952 953 SmallPtrSet<Instruction *,16> Widened; 954 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; 955 956 enum ExtendKind { ZeroExtended, SignExtended, Unknown }; 957 958 // A map tracking the kind of extension used to widen each narrow IV 959 // and narrow IV user. 960 // Key: pointer to a narrow IV or IV user. 961 // Value: the kind of extension used to widen this Instruction. 962 DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap; 963 964 using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>; 965 966 // A map with control-dependent ranges for post increment IV uses. The key is 967 // a pair of IV def and a use of this def denoting the context. The value is 968 // a ConstantRange representing possible values of the def at the given 969 // context. 970 DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos; 971 972 Optional<ConstantRange> getPostIncRangeInfo(Value *Def, 973 Instruction *UseI) { 974 DefUserPair Key(Def, UseI); 975 auto It = PostIncRangeInfos.find(Key); 976 return It == PostIncRangeInfos.end() 977 ? Optional<ConstantRange>(None) 978 : Optional<ConstantRange>(It->second); 979 } 980 981 void calculatePostIncRanges(PHINode *OrigPhi); 982 void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser); 983 984 void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) { 985 DefUserPair Key(Def, UseI); 986 auto It = PostIncRangeInfos.find(Key); 987 if (It == PostIncRangeInfos.end()) 988 PostIncRangeInfos.insert({Key, R}); 989 else 990 It->second = R.intersectWith(It->second); 991 } 992 993 public: 994 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv, 995 DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI, 996 bool HasGuards) 997 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo), 998 L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree), 999 HasGuards(HasGuards), DeadInsts(DI) { 1000 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); 1001 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended; 1002 } 1003 1004 PHINode *createWideIV(SCEVExpander &Rewriter); 1005 1006 protected: 1007 Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned, 1008 Instruction *Use); 1009 1010 Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR); 1011 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU, 1012 const SCEVAddRecExpr *WideAR); 1013 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU); 1014 1015 ExtendKind getExtendKind(Instruction *I); 1016 1017 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>; 1018 1019 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU); 1020 1021 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU); 1022 1023 const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1024 unsigned OpCode) const; 1025 1026 Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter); 1027 1028 bool widenLoopCompare(NarrowIVDefUse DU); 1029 1030 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); 1031 }; 1032 1033 } // end anonymous namespace 1034 1035 /// Perform a quick domtree based check for loop invariance assuming that V is 1036 /// used within the loop. LoopInfo::isLoopInvariant() seems gratuitous for this 1037 /// purpose. 1038 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) { 1039 Instruction *Inst = dyn_cast<Instruction>(V); 1040 if (!Inst) 1041 return true; 1042 1043 return DT->properlyDominates(Inst->getParent(), L->getHeader()); 1044 } 1045 1046 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType, 1047 bool IsSigned, Instruction *Use) { 1048 // Set the debug location and conservative insertion point. 1049 IRBuilder<> Builder(Use); 1050 // Hoist the insertion point into loop preheaders as far as possible. 1051 for (const Loop *L = LI->getLoopFor(Use->getParent()); 1052 L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT); 1053 L = L->getParentLoop()) 1054 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 1055 1056 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : 1057 Builder.CreateZExt(NarrowOper, WideType); 1058 } 1059 1060 /// Instantiate a wide operation to replace a narrow operation. This only needs 1061 /// to handle operations that can evaluation to SCEVAddRec. It can safely return 1062 /// 0 for any operation we decide not to clone. 1063 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU, 1064 const SCEVAddRecExpr *WideAR) { 1065 unsigned Opcode = DU.NarrowUse->getOpcode(); 1066 switch (Opcode) { 1067 default: 1068 return nullptr; 1069 case Instruction::Add: 1070 case Instruction::Mul: 1071 case Instruction::UDiv: 1072 case Instruction::Sub: 1073 return cloneArithmeticIVUser(DU, WideAR); 1074 1075 case Instruction::And: 1076 case Instruction::Or: 1077 case Instruction::Xor: 1078 case Instruction::Shl: 1079 case Instruction::LShr: 1080 case Instruction::AShr: 1081 return cloneBitwiseIVUser(DU); 1082 } 1083 } 1084 1085 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) { 1086 Instruction *NarrowUse = DU.NarrowUse; 1087 Instruction *NarrowDef = DU.NarrowDef; 1088 Instruction *WideDef = DU.WideDef; 1089 1090 DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n"); 1091 1092 // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything 1093 // about the narrow operand yet so must insert a [sz]ext. It is probably loop 1094 // invariant and will be folded or hoisted. If it actually comes from a 1095 // widened IV, it should be removed during a future call to widenIVUse. 1096 bool IsSigned = getExtendKind(NarrowDef) == SignExtended; 1097 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1098 ? WideDef 1099 : createExtendInst(NarrowUse->getOperand(0), WideType, 1100 IsSigned, NarrowUse); 1101 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1102 ? WideDef 1103 : createExtendInst(NarrowUse->getOperand(1), WideType, 1104 IsSigned, NarrowUse); 1105 1106 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1107 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1108 NarrowBO->getName()); 1109 IRBuilder<> Builder(NarrowUse); 1110 Builder.Insert(WideBO); 1111 WideBO->copyIRFlags(NarrowBO); 1112 return WideBO; 1113 } 1114 1115 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU, 1116 const SCEVAddRecExpr *WideAR) { 1117 Instruction *NarrowUse = DU.NarrowUse; 1118 Instruction *NarrowDef = DU.NarrowDef; 1119 Instruction *WideDef = DU.WideDef; 1120 1121 DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n"); 1122 1123 unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1; 1124 1125 // We're trying to find X such that 1126 // 1127 // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X 1128 // 1129 // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef), 1130 // and check using SCEV if any of them are correct. 1131 1132 // Returns true if extending NonIVNarrowDef according to `SignExt` is a 1133 // correct solution to X. 1134 auto GuessNonIVOperand = [&](bool SignExt) { 1135 const SCEV *WideLHS; 1136 const SCEV *WideRHS; 1137 1138 auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) { 1139 if (SignExt) 1140 return SE->getSignExtendExpr(S, Ty); 1141 return SE->getZeroExtendExpr(S, Ty); 1142 }; 1143 1144 if (IVOpIdx == 0) { 1145 WideLHS = SE->getSCEV(WideDef); 1146 const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1)); 1147 WideRHS = GetExtend(NarrowRHS, WideType); 1148 } else { 1149 const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0)); 1150 WideLHS = GetExtend(NarrowLHS, WideType); 1151 WideRHS = SE->getSCEV(WideDef); 1152 } 1153 1154 // WideUse is "WideDef `op.wide` X" as described in the comment. 1155 const SCEV *WideUse = nullptr; 1156 1157 switch (NarrowUse->getOpcode()) { 1158 default: 1159 llvm_unreachable("No other possibility!"); 1160 1161 case Instruction::Add: 1162 WideUse = SE->getAddExpr(WideLHS, WideRHS); 1163 break; 1164 1165 case Instruction::Mul: 1166 WideUse = SE->getMulExpr(WideLHS, WideRHS); 1167 break; 1168 1169 case Instruction::UDiv: 1170 WideUse = SE->getUDivExpr(WideLHS, WideRHS); 1171 break; 1172 1173 case Instruction::Sub: 1174 WideUse = SE->getMinusSCEV(WideLHS, WideRHS); 1175 break; 1176 } 1177 1178 return WideUse == WideAR; 1179 }; 1180 1181 bool SignExtend = getExtendKind(NarrowDef) == SignExtended; 1182 if (!GuessNonIVOperand(SignExtend)) { 1183 SignExtend = !SignExtend; 1184 if (!GuessNonIVOperand(SignExtend)) 1185 return nullptr; 1186 } 1187 1188 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1189 ? WideDef 1190 : createExtendInst(NarrowUse->getOperand(0), WideType, 1191 SignExtend, NarrowUse); 1192 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1193 ? WideDef 1194 : createExtendInst(NarrowUse->getOperand(1), WideType, 1195 SignExtend, NarrowUse); 1196 1197 auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1198 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1199 NarrowBO->getName()); 1200 1201 IRBuilder<> Builder(NarrowUse); 1202 Builder.Insert(WideBO); 1203 WideBO->copyIRFlags(NarrowBO); 1204 return WideBO; 1205 } 1206 1207 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) { 1208 auto It = ExtendKindMap.find(I); 1209 assert(It != ExtendKindMap.end() && "Instruction not yet extended!"); 1210 return It->second; 1211 } 1212 1213 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1214 unsigned OpCode) const { 1215 if (OpCode == Instruction::Add) 1216 return SE->getAddExpr(LHS, RHS); 1217 if (OpCode == Instruction::Sub) 1218 return SE->getMinusSCEV(LHS, RHS); 1219 if (OpCode == Instruction::Mul) 1220 return SE->getMulExpr(LHS, RHS); 1221 1222 llvm_unreachable("Unsupported opcode."); 1223 } 1224 1225 /// No-wrap operations can transfer sign extension of their result to their 1226 /// operands. Generate the SCEV value for the widened operation without 1227 /// actually modifying the IR yet. If the expression after extending the 1228 /// operands is an AddRec for this loop, return the AddRec and the kind of 1229 /// extension used. 1230 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) { 1231 // Handle the common case of add<nsw/nuw> 1232 const unsigned OpCode = DU.NarrowUse->getOpcode(); 1233 // Only Add/Sub/Mul instructions supported yet. 1234 if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 1235 OpCode != Instruction::Mul) 1236 return {nullptr, Unknown}; 1237 1238 // One operand (NarrowDef) has already been extended to WideDef. Now determine 1239 // if extending the other will lead to a recurrence. 1240 const unsigned ExtendOperIdx = 1241 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0; 1242 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU"); 1243 1244 const SCEV *ExtendOperExpr = nullptr; 1245 const OverflowingBinaryOperator *OBO = 1246 cast<OverflowingBinaryOperator>(DU.NarrowUse); 1247 ExtendKind ExtKind = getExtendKind(DU.NarrowDef); 1248 if (ExtKind == SignExtended && OBO->hasNoSignedWrap()) 1249 ExtendOperExpr = SE->getSignExtendExpr( 1250 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1251 else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap()) 1252 ExtendOperExpr = SE->getZeroExtendExpr( 1253 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType); 1254 else 1255 return {nullptr, Unknown}; 1256 1257 // When creating this SCEV expr, don't apply the current operations NSW or NUW 1258 // flags. This instruction may be guarded by control flow that the no-wrap 1259 // behavior depends on. Non-control-equivalent instructions can be mapped to 1260 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW 1261 // semantics to those operations. 1262 const SCEV *lhs = SE->getSCEV(DU.WideDef); 1263 const SCEV *rhs = ExtendOperExpr; 1264 1265 // Let's swap operands to the initial order for the case of non-commutative 1266 // operations, like SUB. See PR21014. 1267 if (ExtendOperIdx == 0) 1268 std::swap(lhs, rhs); 1269 const SCEVAddRecExpr *AddRec = 1270 dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode)); 1271 1272 if (!AddRec || AddRec->getLoop() != L) 1273 return {nullptr, Unknown}; 1274 1275 return {AddRec, ExtKind}; 1276 } 1277 1278 /// Is this instruction potentially interesting for further simplification after 1279 /// widening it's type? In other words, can the extend be safely hoisted out of 1280 /// the loop with SCEV reducing the value to a recurrence on the same loop. If 1281 /// so, return the extended recurrence and the kind of extension used. Otherwise 1282 /// return {nullptr, Unknown}. 1283 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) { 1284 if (!SE->isSCEVable(DU.NarrowUse->getType())) 1285 return {nullptr, Unknown}; 1286 1287 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse); 1288 if (SE->getTypeSizeInBits(NarrowExpr->getType()) >= 1289 SE->getTypeSizeInBits(WideType)) { 1290 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow 1291 // index. So don't follow this use. 1292 return {nullptr, Unknown}; 1293 } 1294 1295 const SCEV *WideExpr; 1296 ExtendKind ExtKind; 1297 if (DU.NeverNegative) { 1298 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1299 if (isa<SCEVAddRecExpr>(WideExpr)) 1300 ExtKind = SignExtended; 1301 else { 1302 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1303 ExtKind = ZeroExtended; 1304 } 1305 } else if (getExtendKind(DU.NarrowDef) == SignExtended) { 1306 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1307 ExtKind = SignExtended; 1308 } else { 1309 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1310 ExtKind = ZeroExtended; 1311 } 1312 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); 1313 if (!AddRec || AddRec->getLoop() != L) 1314 return {nullptr, Unknown}; 1315 return {AddRec, ExtKind}; 1316 } 1317 1318 /// This IV user cannot be widen. Replace this use of the original narrow IV 1319 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV. 1320 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI) { 1321 DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef 1322 << " for user " << *DU.NarrowUse << "\n"); 1323 IRBuilder<> Builder( 1324 getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI)); 1325 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType()); 1326 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); 1327 } 1328 1329 /// If the narrow use is a compare instruction, then widen the compare 1330 // (and possibly the other operand). The extend operation is hoisted into the 1331 // loop preheader as far as possible. 1332 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) { 1333 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse); 1334 if (!Cmp) 1335 return false; 1336 1337 // We can legally widen the comparison in the following two cases: 1338 // 1339 // - The signedness of the IV extension and comparison match 1340 // 1341 // - The narrow IV is always positive (and thus its sign extension is equal 1342 // to its zero extension). For instance, let's say we're zero extending 1343 // %narrow for the following use 1344 // 1345 // icmp slt i32 %narrow, %val ... (A) 1346 // 1347 // and %narrow is always positive. Then 1348 // 1349 // (A) == icmp slt i32 sext(%narrow), sext(%val) 1350 // == icmp slt i32 zext(%narrow), sext(%val) 1351 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended; 1352 if (!(DU.NeverNegative || IsSigned == Cmp->isSigned())) 1353 return false; 1354 1355 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0); 1356 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType()); 1357 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1358 assert(CastWidth <= IVWidth && "Unexpected width while widening compare."); 1359 1360 // Widen the compare instruction. 1361 IRBuilder<> Builder( 1362 getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI)); 1363 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1364 1365 // Widen the other operand of the compare, if necessary. 1366 if (CastWidth < IVWidth) { 1367 Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp); 1368 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp); 1369 } 1370 return true; 1371 } 1372 1373 /// Determine whether an individual user of the narrow IV can be widened. If so, 1374 /// return the wide clone of the user. 1375 Instruction *WidenIV::widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) { 1376 assert(ExtendKindMap.count(DU.NarrowDef) && 1377 "Should already know the kind of extension used to widen NarrowDef"); 1378 1379 // Stop traversing the def-use chain at inner-loop phis or post-loop phis. 1380 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) { 1381 if (LI->getLoopFor(UsePhi->getParent()) != L) { 1382 // For LCSSA phis, sink the truncate outside the loop. 1383 // After SimplifyCFG most loop exit targets have a single predecessor. 1384 // Otherwise fall back to a truncate within the loop. 1385 if (UsePhi->getNumOperands() != 1) 1386 truncateIVUse(DU, DT, LI); 1387 else { 1388 // Widening the PHI requires us to insert a trunc. The logical place 1389 // for this trunc is in the same BB as the PHI. This is not possible if 1390 // the BB is terminated by a catchswitch. 1391 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator())) 1392 return nullptr; 1393 1394 PHINode *WidePhi = 1395 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide", 1396 UsePhi); 1397 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0)); 1398 IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt()); 1399 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType()); 1400 UsePhi->replaceAllUsesWith(Trunc); 1401 DeadInsts.emplace_back(UsePhi); 1402 DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi 1403 << " to " << *WidePhi << "\n"); 1404 } 1405 return nullptr; 1406 } 1407 } 1408 1409 // This narrow use can be widened by a sext if it's non-negative or its narrow 1410 // def was widended by a sext. Same for zext. 1411 auto canWidenBySExt = [&]() { 1412 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended; 1413 }; 1414 auto canWidenByZExt = [&]() { 1415 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended; 1416 }; 1417 1418 // Our raison d'etre! Eliminate sign and zero extension. 1419 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) || 1420 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) { 1421 Value *NewDef = DU.WideDef; 1422 if (DU.NarrowUse->getType() != WideType) { 1423 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); 1424 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1425 if (CastWidth < IVWidth) { 1426 // The cast isn't as wide as the IV, so insert a Trunc. 1427 IRBuilder<> Builder(DU.NarrowUse); 1428 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType()); 1429 } 1430 else { 1431 // A wider extend was hidden behind a narrower one. This may induce 1432 // another round of IV widening in which the intermediate IV becomes 1433 // dead. It should be very rare. 1434 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi 1435 << " not wide enough to subsume " << *DU.NarrowUse << "\n"); 1436 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1437 NewDef = DU.NarrowUse; 1438 } 1439 } 1440 if (NewDef != DU.NarrowUse) { 1441 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse 1442 << " replaced by " << *DU.WideDef << "\n"); 1443 ++NumElimExt; 1444 DU.NarrowUse->replaceAllUsesWith(NewDef); 1445 DeadInsts.emplace_back(DU.NarrowUse); 1446 } 1447 // Now that the extend is gone, we want to expose it's uses for potential 1448 // further simplification. We don't need to directly inform SimplifyIVUsers 1449 // of the new users, because their parent IV will be processed later as a 1450 // new loop phi. If we preserved IVUsers analysis, we would also want to 1451 // push the uses of WideDef here. 1452 1453 // No further widening is needed. The deceased [sz]ext had done it for us. 1454 return nullptr; 1455 } 1456 1457 // Does this user itself evaluate to a recurrence after widening? 1458 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU); 1459 if (!WideAddRec.first) 1460 WideAddRec = getWideRecurrence(DU); 1461 1462 assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown)); 1463 if (!WideAddRec.first) { 1464 // If use is a loop condition, try to promote the condition instead of 1465 // truncating the IV first. 1466 if (widenLoopCompare(DU)) 1467 return nullptr; 1468 1469 // This user does not evaluate to a recurrence after widening, so don't 1470 // follow it. Instead insert a Trunc to kill off the original use, 1471 // eventually isolating the original narrow IV so it can be removed. 1472 truncateIVUse(DU, DT, LI); 1473 return nullptr; 1474 } 1475 // Assume block terminators cannot evaluate to a recurrence. We can't to 1476 // insert a Trunc after a terminator if there happens to be a critical edge. 1477 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() && 1478 "SCEV is not expected to evaluate a block terminator"); 1479 1480 // Reuse the IV increment that SCEVExpander created as long as it dominates 1481 // NarrowUse. 1482 Instruction *WideUse = nullptr; 1483 if (WideAddRec.first == WideIncExpr && 1484 Rewriter.hoistIVInc(WideInc, DU.NarrowUse)) 1485 WideUse = WideInc; 1486 else { 1487 WideUse = cloneIVUser(DU, WideAddRec.first); 1488 if (!WideUse) 1489 return nullptr; 1490 } 1491 // Evaluation of WideAddRec ensured that the narrow expression could be 1492 // extended outside the loop without overflow. This suggests that the wide use 1493 // evaluates to the same expression as the extended narrow use, but doesn't 1494 // absolutely guarantee it. Hence the following failsafe check. In rare cases 1495 // where it fails, we simply throw away the newly created wide use. 1496 if (WideAddRec.first != SE->getSCEV(WideUse)) { 1497 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse 1498 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first << "\n"); 1499 DeadInsts.emplace_back(WideUse); 1500 return nullptr; 1501 } 1502 1503 ExtendKindMap[DU.NarrowUse] = WideAddRec.second; 1504 // Returning WideUse pushes it on the worklist. 1505 return WideUse; 1506 } 1507 1508 /// Add eligible users of NarrowDef to NarrowIVUsers. 1509 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { 1510 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef); 1511 bool NonNegativeDef = 1512 SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV, 1513 SE->getConstant(NarrowSCEV->getType(), 0)); 1514 for (User *U : NarrowDef->users()) { 1515 Instruction *NarrowUser = cast<Instruction>(U); 1516 1517 // Handle data flow merges and bizarre phi cycles. 1518 if (!Widened.insert(NarrowUser).second) 1519 continue; 1520 1521 bool NonNegativeUse = false; 1522 if (!NonNegativeDef) { 1523 // We might have a control-dependent range information for this context. 1524 if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser)) 1525 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative(); 1526 } 1527 1528 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef, 1529 NonNegativeDef || NonNegativeUse); 1530 } 1531 } 1532 1533 /// Process a single induction variable. First use the SCEVExpander to create a 1534 /// wide induction variable that evaluates to the same recurrence as the 1535 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's 1536 /// def-use chain. After widenIVUse has processed all interesting IV users, the 1537 /// narrow IV will be isolated for removal by DeleteDeadPHIs. 1538 /// 1539 /// It would be simpler to delete uses as they are processed, but we must avoid 1540 /// invalidating SCEV expressions. 1541 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) { 1542 // Is this phi an induction variable? 1543 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); 1544 if (!AddRec) 1545 return nullptr; 1546 1547 // Widen the induction variable expression. 1548 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended 1549 ? SE->getSignExtendExpr(AddRec, WideType) 1550 : SE->getZeroExtendExpr(AddRec, WideType); 1551 1552 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && 1553 "Expect the new IV expression to preserve its type"); 1554 1555 // Can the IV be extended outside the loop without overflow? 1556 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); 1557 if (!AddRec || AddRec->getLoop() != L) 1558 return nullptr; 1559 1560 // An AddRec must have loop-invariant operands. Since this AddRec is 1561 // materialized by a loop header phi, the expression cannot have any post-loop 1562 // operands, so they must dominate the loop header. 1563 assert( 1564 SE->properlyDominates(AddRec->getStart(), L->getHeader()) && 1565 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) && 1566 "Loop header phi recurrence inputs do not dominate the loop"); 1567 1568 // Iterate over IV uses (including transitive ones) looking for IV increments 1569 // of the form 'add nsw %iv, <const>'. For each increment and each use of 1570 // the increment calculate control-dependent range information basing on 1571 // dominating conditions inside of the loop (e.g. a range check inside of the 1572 // loop). Calculated ranges are stored in PostIncRangeInfos map. 1573 // 1574 // Control-dependent range information is later used to prove that a narrow 1575 // definition is not negative (see pushNarrowIVUsers). It's difficult to do 1576 // this on demand because when pushNarrowIVUsers needs this information some 1577 // of the dominating conditions might be already widened. 1578 if (UsePostIncrementRanges) 1579 calculatePostIncRanges(OrigPhi); 1580 1581 // The rewriter provides a value for the desired IV expression. This may 1582 // either find an existing phi or materialize a new one. Either way, we 1583 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part 1584 // of the phi-SCC dominates the loop entry. 1585 Instruction *InsertPt = &L->getHeader()->front(); 1586 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt)); 1587 1588 // Remembering the WideIV increment generated by SCEVExpander allows 1589 // widenIVUse to reuse it when widening the narrow IV's increment. We don't 1590 // employ a general reuse mechanism because the call above is the only call to 1591 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. 1592 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1593 WideInc = 1594 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); 1595 WideIncExpr = SE->getSCEV(WideInc); 1596 // Propagate the debug location associated with the original loop increment 1597 // to the new (widened) increment. 1598 auto *OrigInc = 1599 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock)); 1600 WideInc->setDebugLoc(OrigInc->getDebugLoc()); 1601 } 1602 1603 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); 1604 ++NumWidened; 1605 1606 // Traverse the def-use chain using a worklist starting at the original IV. 1607 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); 1608 1609 Widened.insert(OrigPhi); 1610 pushNarrowIVUsers(OrigPhi, WidePhi); 1611 1612 while (!NarrowIVUsers.empty()) { 1613 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); 1614 1615 // Process a def-use edge. This may replace the use, so don't hold a 1616 // use_iterator across it. 1617 Instruction *WideUse = widenIVUse(DU, Rewriter); 1618 1619 // Follow all def-use edges from the previous narrow use. 1620 if (WideUse) 1621 pushNarrowIVUsers(DU.NarrowUse, WideUse); 1622 1623 // widenIVUse may have removed the def-use edge. 1624 if (DU.NarrowDef->use_empty()) 1625 DeadInsts.emplace_back(DU.NarrowDef); 1626 } 1627 return WidePhi; 1628 } 1629 1630 /// Calculates control-dependent range for the given def at the given context 1631 /// by looking at dominating conditions inside of the loop 1632 void WidenIV::calculatePostIncRange(Instruction *NarrowDef, 1633 Instruction *NarrowUser) { 1634 using namespace llvm::PatternMatch; 1635 1636 Value *NarrowDefLHS; 1637 const APInt *NarrowDefRHS; 1638 if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS), 1639 m_APInt(NarrowDefRHS))) || 1640 !NarrowDefRHS->isNonNegative()) 1641 return; 1642 1643 auto UpdateRangeFromCondition = [&] (Value *Condition, 1644 bool TrueDest) { 1645 CmpInst::Predicate Pred; 1646 Value *CmpRHS; 1647 if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS), 1648 m_Value(CmpRHS)))) 1649 return; 1650 1651 CmpInst::Predicate P = 1652 TrueDest ? Pred : CmpInst::getInversePredicate(Pred); 1653 1654 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS)); 1655 auto CmpConstrainedLHSRange = 1656 ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange); 1657 auto NarrowDefRange = 1658 CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS); 1659 1660 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange); 1661 }; 1662 1663 auto UpdateRangeFromGuards = [&](Instruction *Ctx) { 1664 if (!HasGuards) 1665 return; 1666 1667 for (Instruction &I : make_range(Ctx->getIterator().getReverse(), 1668 Ctx->getParent()->rend())) { 1669 Value *C = nullptr; 1670 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C)))) 1671 UpdateRangeFromCondition(C, /*TrueDest=*/true); 1672 } 1673 }; 1674 1675 UpdateRangeFromGuards(NarrowUser); 1676 1677 BasicBlock *NarrowUserBB = NarrowUser->getParent(); 1678 // If NarrowUserBB is statically unreachable asking dominator queries may 1679 // yield surprising results. (e.g. the block may not have a dom tree node) 1680 if (!DT->isReachableFromEntry(NarrowUserBB)) 1681 return; 1682 1683 for (auto *DTB = (*DT)[NarrowUserBB]->getIDom(); 1684 L->contains(DTB->getBlock()); 1685 DTB = DTB->getIDom()) { 1686 auto *BB = DTB->getBlock(); 1687 auto *TI = BB->getTerminator(); 1688 UpdateRangeFromGuards(TI); 1689 1690 auto *BI = dyn_cast<BranchInst>(TI); 1691 if (!BI || !BI->isConditional()) 1692 continue; 1693 1694 auto *TrueSuccessor = BI->getSuccessor(0); 1695 auto *FalseSuccessor = BI->getSuccessor(1); 1696 1697 auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) { 1698 return BBE.isSingleEdge() && 1699 DT->dominates(BBE, NarrowUser->getParent()); 1700 }; 1701 1702 if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor))) 1703 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true); 1704 1705 if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor))) 1706 UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false); 1707 } 1708 } 1709 1710 /// Calculates PostIncRangeInfos map for the given IV 1711 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) { 1712 SmallPtrSet<Instruction *, 16> Visited; 1713 SmallVector<Instruction *, 6> Worklist; 1714 Worklist.push_back(OrigPhi); 1715 Visited.insert(OrigPhi); 1716 1717 while (!Worklist.empty()) { 1718 Instruction *NarrowDef = Worklist.pop_back_val(); 1719 1720 for (Use &U : NarrowDef->uses()) { 1721 auto *NarrowUser = cast<Instruction>(U.getUser()); 1722 1723 // Don't go looking outside the current loop. 1724 auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()]; 1725 if (!NarrowUserLoop || !L->contains(NarrowUserLoop)) 1726 continue; 1727 1728 if (!Visited.insert(NarrowUser).second) 1729 continue; 1730 1731 Worklist.push_back(NarrowUser); 1732 1733 calculatePostIncRange(NarrowDef, NarrowUser); 1734 } 1735 } 1736 } 1737 1738 //===----------------------------------------------------------------------===// 1739 // Live IV Reduction - Minimize IVs live across the loop. 1740 //===----------------------------------------------------------------------===// 1741 1742 //===----------------------------------------------------------------------===// 1743 // Simplification of IV users based on SCEV evaluation. 1744 //===----------------------------------------------------------------------===// 1745 1746 namespace { 1747 1748 class IndVarSimplifyVisitor : public IVVisitor { 1749 ScalarEvolution *SE; 1750 const TargetTransformInfo *TTI; 1751 PHINode *IVPhi; 1752 1753 public: 1754 WideIVInfo WI; 1755 1756 IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV, 1757 const TargetTransformInfo *TTI, 1758 const DominatorTree *DTree) 1759 : SE(SCEV), TTI(TTI), IVPhi(IV) { 1760 DT = DTree; 1761 WI.NarrowIV = IVPhi; 1762 } 1763 1764 // Implement the interface used by simplifyUsersOfIV. 1765 void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); } 1766 }; 1767 1768 } // end anonymous namespace 1769 1770 /// Iteratively perform simplification on a worklist of IV users. Each 1771 /// successive simplification may push more users which may themselves be 1772 /// candidates for simplification. 1773 /// 1774 /// Sign/Zero extend elimination is interleaved with IV simplification. 1775 void IndVarSimplify::simplifyAndExtend(Loop *L, 1776 SCEVExpander &Rewriter, 1777 LoopInfo *LI) { 1778 SmallVector<WideIVInfo, 8> WideIVs; 1779 1780 auto *GuardDecl = L->getBlocks()[0]->getModule()->getFunction( 1781 Intrinsic::getName(Intrinsic::experimental_guard)); 1782 bool HasGuards = GuardDecl && !GuardDecl->use_empty(); 1783 1784 SmallVector<PHINode*, 8> LoopPhis; 1785 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1786 LoopPhis.push_back(cast<PHINode>(I)); 1787 } 1788 // Each round of simplification iterates through the SimplifyIVUsers worklist 1789 // for all current phis, then determines whether any IVs can be 1790 // widened. Widening adds new phis to LoopPhis, inducing another round of 1791 // simplification on the wide IVs. 1792 while (!LoopPhis.empty()) { 1793 // Evaluate as many IV expressions as possible before widening any IVs. This 1794 // forces SCEV to set no-wrap flags before evaluating sign/zero 1795 // extension. The first time SCEV attempts to normalize sign/zero extension, 1796 // the result becomes final. So for the most predictable results, we delay 1797 // evaluation of sign/zero extend evaluation until needed, and avoid running 1798 // other SCEV based analysis prior to simplifyAndExtend. 1799 do { 1800 PHINode *CurrIV = LoopPhis.pop_back_val(); 1801 1802 // Information about sign/zero extensions of CurrIV. 1803 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT); 1804 1805 Changed |= 1806 simplifyUsersOfIV(CurrIV, SE, DT, LI, DeadInsts, Rewriter, &Visitor); 1807 1808 if (Visitor.WI.WidestNativeType) { 1809 WideIVs.push_back(Visitor.WI); 1810 } 1811 } while(!LoopPhis.empty()); 1812 1813 for (; !WideIVs.empty(); WideIVs.pop_back()) { 1814 WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts, HasGuards); 1815 if (PHINode *WidePhi = Widener.createWideIV(Rewriter)) { 1816 Changed = true; 1817 LoopPhis.push_back(WidePhi); 1818 } 1819 } 1820 } 1821 } 1822 1823 //===----------------------------------------------------------------------===// 1824 // linearFunctionTestReplace and its kin. Rewrite the loop exit condition. 1825 //===----------------------------------------------------------------------===// 1826 1827 /// Return true if this loop's backedge taken count expression can be safely and 1828 /// cheaply expanded into an instruction sequence that can be used by 1829 /// linearFunctionTestReplace. 1830 /// 1831 /// TODO: This fails for pointer-type loop counters with greater than one byte 1832 /// strides, consequently preventing LFTR from running. For the purpose of LFTR 1833 /// we could skip this check in the case that the LFTR loop counter (chosen by 1834 /// FindLoopCounter) is also pointer type. Instead, we could directly convert 1835 /// the loop test to an inequality test by checking the target data's alignment 1836 /// of element types (given that the initial pointer value originates from or is 1837 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint). 1838 /// However, we don't yet have a strong motivation for converting loop tests 1839 /// into inequality tests. 1840 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE, 1841 SCEVExpander &Rewriter) { 1842 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 1843 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) || 1844 BackedgeTakenCount->isZero()) 1845 return false; 1846 1847 if (!L->getExitingBlock()) 1848 return false; 1849 1850 // Can't rewrite non-branch yet. 1851 if (!isa<BranchInst>(L->getExitingBlock()->getTerminator())) 1852 return false; 1853 1854 if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L)) 1855 return false; 1856 1857 return true; 1858 } 1859 1860 /// Return the loop header phi IFF IncV adds a loop invariant value to the phi. 1861 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) { 1862 Instruction *IncI = dyn_cast<Instruction>(IncV); 1863 if (!IncI) 1864 return nullptr; 1865 1866 switch (IncI->getOpcode()) { 1867 case Instruction::Add: 1868 case Instruction::Sub: 1869 break; 1870 case Instruction::GetElementPtr: 1871 // An IV counter must preserve its type. 1872 if (IncI->getNumOperands() == 2) 1873 break; 1874 LLVM_FALLTHROUGH; 1875 default: 1876 return nullptr; 1877 } 1878 1879 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0)); 1880 if (Phi && Phi->getParent() == L->getHeader()) { 1881 if (isLoopInvariant(IncI->getOperand(1), L, DT)) 1882 return Phi; 1883 return nullptr; 1884 } 1885 if (IncI->getOpcode() == Instruction::GetElementPtr) 1886 return nullptr; 1887 1888 // Allow add/sub to be commuted. 1889 Phi = dyn_cast<PHINode>(IncI->getOperand(1)); 1890 if (Phi && Phi->getParent() == L->getHeader()) { 1891 if (isLoopInvariant(IncI->getOperand(0), L, DT)) 1892 return Phi; 1893 } 1894 return nullptr; 1895 } 1896 1897 /// Return the compare guarding the loop latch, or NULL for unrecognized tests. 1898 static ICmpInst *getLoopTest(Loop *L) { 1899 assert(L->getExitingBlock() && "expected loop exit"); 1900 1901 BasicBlock *LatchBlock = L->getLoopLatch(); 1902 // Don't bother with LFTR if the loop is not properly simplified. 1903 if (!LatchBlock) 1904 return nullptr; 1905 1906 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1907 assert(BI && "expected exit branch"); 1908 1909 return dyn_cast<ICmpInst>(BI->getCondition()); 1910 } 1911 1912 /// linearFunctionTestReplace policy. Return true unless we can show that the 1913 /// current exit test is already sufficiently canonical. 1914 static bool needsLFTR(Loop *L, DominatorTree *DT) { 1915 // Do LFTR to simplify the exit condition to an ICMP. 1916 ICmpInst *Cond = getLoopTest(L); 1917 if (!Cond) 1918 return true; 1919 1920 // Do LFTR to simplify the exit ICMP to EQ/NE 1921 ICmpInst::Predicate Pred = Cond->getPredicate(); 1922 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ) 1923 return true; 1924 1925 // Look for a loop invariant RHS 1926 Value *LHS = Cond->getOperand(0); 1927 Value *RHS = Cond->getOperand(1); 1928 if (!isLoopInvariant(RHS, L, DT)) { 1929 if (!isLoopInvariant(LHS, L, DT)) 1930 return true; 1931 std::swap(LHS, RHS); 1932 } 1933 // Look for a simple IV counter LHS 1934 PHINode *Phi = dyn_cast<PHINode>(LHS); 1935 if (!Phi) 1936 Phi = getLoopPhiForCounter(LHS, L, DT); 1937 1938 if (!Phi) 1939 return true; 1940 1941 // Do LFTR if PHI node is defined in the loop, but is *not* a counter. 1942 int Idx = Phi->getBasicBlockIndex(L->getLoopLatch()); 1943 if (Idx < 0) 1944 return true; 1945 1946 // Do LFTR if the exit condition's IV is *not* a simple counter. 1947 Value *IncV = Phi->getIncomingValue(Idx); 1948 return Phi != getLoopPhiForCounter(IncV, L, DT); 1949 } 1950 1951 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils 1952 /// down to checking that all operands are constant and listing instructions 1953 /// that may hide undef. 1954 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited, 1955 unsigned Depth) { 1956 if (isa<Constant>(V)) 1957 return !isa<UndefValue>(V); 1958 1959 if (Depth >= 6) 1960 return false; 1961 1962 // Conservatively handle non-constant non-instructions. For example, Arguments 1963 // may be undef. 1964 Instruction *I = dyn_cast<Instruction>(V); 1965 if (!I) 1966 return false; 1967 1968 // Load and return values may be undef. 1969 if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I)) 1970 return false; 1971 1972 // Optimistically handle other instructions. 1973 for (Value *Op : I->operands()) { 1974 if (!Visited.insert(Op).second) 1975 continue; 1976 if (!hasConcreteDefImpl(Op, Visited, Depth+1)) 1977 return false; 1978 } 1979 return true; 1980 } 1981 1982 /// Return true if the given value is concrete. We must prove that undef can 1983 /// never reach it. 1984 /// 1985 /// TODO: If we decide that this is a good approach to checking for undef, we 1986 /// may factor it into a common location. 1987 static bool hasConcreteDef(Value *V) { 1988 SmallPtrSet<Value*, 8> Visited; 1989 Visited.insert(V); 1990 return hasConcreteDefImpl(V, Visited, 0); 1991 } 1992 1993 /// Return true if this IV has any uses other than the (soon to be rewritten) 1994 /// loop exit test. 1995 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) { 1996 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 1997 Value *IncV = Phi->getIncomingValue(LatchIdx); 1998 1999 for (User *U : Phi->users()) 2000 if (U != Cond && U != IncV) return false; 2001 2002 for (User *U : IncV->users()) 2003 if (U != Cond && U != Phi) return false; 2004 return true; 2005 } 2006 2007 /// Find an affine IV in canonical form. 2008 /// 2009 /// BECount may be an i8* pointer type. The pointer difference is already 2010 /// valid count without scaling the address stride, so it remains a pointer 2011 /// expression as far as SCEV is concerned. 2012 /// 2013 /// Currently only valid for LFTR. See the comments on hasConcreteDef below. 2014 /// 2015 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount 2016 /// 2017 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride. 2018 /// This is difficult in general for SCEV because of potential overflow. But we 2019 /// could at least handle constant BECounts. 2020 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount, 2021 ScalarEvolution *SE, DominatorTree *DT) { 2022 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType()); 2023 2024 Value *Cond = 2025 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition(); 2026 2027 // Loop over all of the PHI nodes, looking for a simple counter. 2028 PHINode *BestPhi = nullptr; 2029 const SCEV *BestInit = nullptr; 2030 BasicBlock *LatchBlock = L->getLoopLatch(); 2031 assert(LatchBlock && "needsLFTR should guarantee a loop latch"); 2032 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 2033 2034 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 2035 PHINode *Phi = cast<PHINode>(I); 2036 if (!SE->isSCEVable(Phi->getType())) 2037 continue; 2038 2039 // Avoid comparing an integer IV against a pointer Limit. 2040 if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy()) 2041 continue; 2042 2043 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi)); 2044 if (!AR || AR->getLoop() != L || !AR->isAffine()) 2045 continue; 2046 2047 // AR may be a pointer type, while BECount is an integer type. 2048 // AR may be wider than BECount. With eq/ne tests overflow is immaterial. 2049 // AR may not be a narrower type, or we may never exit. 2050 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType()); 2051 if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth)) 2052 continue; 2053 2054 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)); 2055 if (!Step || !Step->isOne()) 2056 continue; 2057 2058 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 2059 Value *IncV = Phi->getIncomingValue(LatchIdx); 2060 if (getLoopPhiForCounter(IncV, L, DT) != Phi) 2061 continue; 2062 2063 // Avoid reusing a potentially undef value to compute other values that may 2064 // have originally had a concrete definition. 2065 if (!hasConcreteDef(Phi)) { 2066 // We explicitly allow unknown phis as long as they are already used by 2067 // the loop test. In this case we assume that performing LFTR could not 2068 // increase the number of undef users. 2069 if (ICmpInst *Cond = getLoopTest(L)) { 2070 if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT) && 2071 Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) { 2072 continue; 2073 } 2074 } 2075 } 2076 const SCEV *Init = AR->getStart(); 2077 2078 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) { 2079 // Don't force a live loop counter if another IV can be used. 2080 if (AlmostDeadIV(Phi, LatchBlock, Cond)) 2081 continue; 2082 2083 // Prefer to count-from-zero. This is a more "canonical" counter form. It 2084 // also prefers integer to pointer IVs. 2085 if (BestInit->isZero() != Init->isZero()) { 2086 if (BestInit->isZero()) 2087 continue; 2088 } 2089 // If two IVs both count from zero or both count from nonzero then the 2090 // narrower is likely a dead phi that has been widened. Use the wider phi 2091 // to allow the other to be eliminated. 2092 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType())) 2093 continue; 2094 } 2095 BestPhi = Phi; 2096 BestInit = Init; 2097 } 2098 return BestPhi; 2099 } 2100 2101 /// Help linearFunctionTestReplace by generating a value that holds the RHS of 2102 /// the new loop test. 2103 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L, 2104 SCEVExpander &Rewriter, ScalarEvolution *SE) { 2105 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); 2106 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter"); 2107 const SCEV *IVInit = AR->getStart(); 2108 2109 // IVInit may be a pointer while IVCount is an integer when FindLoopCounter 2110 // finds a valid pointer IV. Sign extend BECount in order to materialize a 2111 // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing 2112 // the existing GEPs whenever possible. 2113 if (IndVar->getType()->isPointerTy() && !IVCount->getType()->isPointerTy()) { 2114 // IVOffset will be the new GEP offset that is interpreted by GEP as a 2115 // signed value. IVCount on the other hand represents the loop trip count, 2116 // which is an unsigned value. FindLoopCounter only allows induction 2117 // variables that have a positive unit stride of one. This means we don't 2118 // have to handle the case of negative offsets (yet) and just need to zero 2119 // extend IVCount. 2120 Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType()); 2121 const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy); 2122 2123 // Expand the code for the iteration count. 2124 assert(SE->isLoopInvariant(IVOffset, L) && 2125 "Computed iteration count is not loop invariant!"); 2126 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 2127 Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI); 2128 2129 Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader()); 2130 assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter"); 2131 // We could handle pointer IVs other than i8*, but we need to compensate for 2132 // gep index scaling. See canExpandBackedgeTakenCount comments. 2133 assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()), 2134 cast<PointerType>(GEPBase->getType()) 2135 ->getElementType())->isOne() && 2136 "unit stride pointer IV must be i8*"); 2137 2138 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 2139 return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit"); 2140 } else { 2141 // In any other case, convert both IVInit and IVCount to integers before 2142 // comparing. This may result in SCEV expansion of pointers, but in practice 2143 // SCEV will fold the pointer arithmetic away as such: 2144 // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc). 2145 // 2146 // Valid Cases: (1) both integers is most common; (2) both may be pointers 2147 // for simple memset-style loops. 2148 // 2149 // IVInit integer and IVCount pointer would only occur if a canonical IV 2150 // were generated on top of case #2, which is not expected. 2151 2152 const SCEV *IVLimit = nullptr; 2153 // For unit stride, IVCount = Start + BECount with 2's complement overflow. 2154 // For non-zero Start, compute IVCount here. 2155 if (AR->getStart()->isZero()) 2156 IVLimit = IVCount; 2157 else { 2158 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride"); 2159 const SCEV *IVInit = AR->getStart(); 2160 2161 // For integer IVs, truncate the IV before computing IVInit + BECount. 2162 if (SE->getTypeSizeInBits(IVInit->getType()) 2163 > SE->getTypeSizeInBits(IVCount->getType())) 2164 IVInit = SE->getTruncateExpr(IVInit, IVCount->getType()); 2165 2166 IVLimit = SE->getAddExpr(IVInit, IVCount); 2167 } 2168 // Expand the code for the iteration count. 2169 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 2170 IRBuilder<> Builder(BI); 2171 assert(SE->isLoopInvariant(IVLimit, L) && 2172 "Computed iteration count is not loop invariant!"); 2173 // Ensure that we generate the same type as IndVar, or a smaller integer 2174 // type. In the presence of null pointer values, we have an integer type 2175 // SCEV expression (IVInit) for a pointer type IV value (IndVar). 2176 Type *LimitTy = IVCount->getType()->isPointerTy() ? 2177 IndVar->getType() : IVCount->getType(); 2178 return Rewriter.expandCodeFor(IVLimit, LimitTy, BI); 2179 } 2180 } 2181 2182 /// This method rewrites the exit condition of the loop to be a canonical != 2183 /// comparison against the incremented loop induction variable. This pass is 2184 /// able to rewrite the exit tests of any loop where the SCEV analysis can 2185 /// determine a loop-invariant trip count of the loop, which is actually a much 2186 /// broader range than just linear tests. 2187 Value *IndVarSimplify:: 2188 linearFunctionTestReplace(Loop *L, 2189 const SCEV *BackedgeTakenCount, 2190 PHINode *IndVar, 2191 SCEVExpander &Rewriter) { 2192 assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition"); 2193 2194 // Initialize CmpIndVar and IVCount to their preincremented values. 2195 Value *CmpIndVar = IndVar; 2196 const SCEV *IVCount = BackedgeTakenCount; 2197 2198 assert(L->getLoopLatch() && "Loop no longer in simplified form?"); 2199 2200 // If the exiting block is the same as the backedge block, we prefer to 2201 // compare against the post-incremented value, otherwise we must compare 2202 // against the preincremented value. 2203 if (L->getExitingBlock() == L->getLoopLatch()) { 2204 // Add one to the "backedge-taken" count to get the trip count. 2205 // This addition may overflow, which is valid as long as the comparison is 2206 // truncated to BackedgeTakenCount->getType(). 2207 IVCount = SE->getAddExpr(BackedgeTakenCount, 2208 SE->getOne(BackedgeTakenCount->getType())); 2209 // The BackedgeTaken expression contains the number of times that the 2210 // backedge branches to the loop header. This is one less than the 2211 // number of times the loop executes, so use the incremented indvar. 2212 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock()); 2213 } 2214 2215 Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE); 2216 assert(ExitCnt->getType()->isPointerTy() == 2217 IndVar->getType()->isPointerTy() && 2218 "genLoopLimit missed a cast"); 2219 2220 // Insert a new icmp_ne or icmp_eq instruction before the branch. 2221 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 2222 ICmpInst::Predicate P; 2223 if (L->contains(BI->getSuccessor(0))) 2224 P = ICmpInst::ICMP_NE; 2225 else 2226 P = ICmpInst::ICMP_EQ; 2227 2228 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n" 2229 << " LHS:" << *CmpIndVar << '\n' 2230 << " op:\t" 2231 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n" 2232 << " RHS:\t" << *ExitCnt << "\n" 2233 << " IVCount:\t" << *IVCount << "\n"); 2234 2235 IRBuilder<> Builder(BI); 2236 2237 // The new loop exit condition should reuse the debug location of the 2238 // original loop exit condition. 2239 if (auto *Cond = dyn_cast<Instruction>(BI->getCondition())) 2240 Builder.SetCurrentDebugLocation(Cond->getDebugLoc()); 2241 2242 // LFTR can ignore IV overflow and truncate to the width of 2243 // BECount. This avoids materializing the add(zext(add)) expression. 2244 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType()); 2245 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType()); 2246 if (CmpIndVarSize > ExitCntSize) { 2247 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); 2248 const SCEV *ARStart = AR->getStart(); 2249 const SCEV *ARStep = AR->getStepRecurrence(*SE); 2250 // For constant IVCount, avoid truncation. 2251 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) { 2252 const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt(); 2253 APInt Count = cast<SCEVConstant>(IVCount)->getAPInt(); 2254 // Note that the post-inc value of BackedgeTakenCount may have overflowed 2255 // above such that IVCount is now zero. 2256 if (IVCount != BackedgeTakenCount && Count == 0) { 2257 Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize); 2258 ++Count; 2259 } 2260 else 2261 Count = Count.zext(CmpIndVarSize); 2262 APInt NewLimit; 2263 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative()) 2264 NewLimit = Start - Count; 2265 else 2266 NewLimit = Start + Count; 2267 ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit); 2268 2269 DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n"); 2270 } else { 2271 // We try to extend trip count first. If that doesn't work we truncate IV. 2272 // Zext(trunc(IV)) == IV implies equivalence of the following two: 2273 // Trunc(IV) == ExitCnt and IV == zext(ExitCnt). Similarly for sext. If 2274 // one of the two holds, extend the trip count, otherwise we truncate IV. 2275 bool Extended = false; 2276 const SCEV *IV = SE->getSCEV(CmpIndVar); 2277 const SCEV *ZExtTrunc = 2278 SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar), 2279 ExitCnt->getType()), 2280 CmpIndVar->getType()); 2281 2282 if (ZExtTrunc == IV) { 2283 Extended = true; 2284 ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(), 2285 "wide.trip.count"); 2286 } else { 2287 const SCEV *SExtTrunc = 2288 SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar), 2289 ExitCnt->getType()), 2290 CmpIndVar->getType()); 2291 if (SExtTrunc == IV) { 2292 Extended = true; 2293 ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(), 2294 "wide.trip.count"); 2295 } 2296 } 2297 2298 if (!Extended) 2299 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(), 2300 "lftr.wideiv"); 2301 } 2302 } 2303 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond"); 2304 Value *OrigCond = BI->getCondition(); 2305 // It's tempting to use replaceAllUsesWith here to fully replace the old 2306 // comparison, but that's not immediately safe, since users of the old 2307 // comparison may not be dominated by the new comparison. Instead, just 2308 // update the branch to use the new comparison; in the common case this 2309 // will make old comparison dead. 2310 BI->setCondition(Cond); 2311 DeadInsts.push_back(OrigCond); 2312 2313 ++NumLFTR; 2314 Changed = true; 2315 return Cond; 2316 } 2317 2318 //===----------------------------------------------------------------------===// 2319 // sinkUnusedInvariants. A late subpass to cleanup loop preheaders. 2320 //===----------------------------------------------------------------------===// 2321 2322 /// If there's a single exit block, sink any loop-invariant values that 2323 /// were defined in the preheader but not used inside the loop into the 2324 /// exit block to reduce register pressure in the loop. 2325 void IndVarSimplify::sinkUnusedInvariants(Loop *L) { 2326 BasicBlock *ExitBlock = L->getExitBlock(); 2327 if (!ExitBlock) return; 2328 2329 BasicBlock *Preheader = L->getLoopPreheader(); 2330 if (!Preheader) return; 2331 2332 BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt(); 2333 BasicBlock::iterator I(Preheader->getTerminator()); 2334 while (I != Preheader->begin()) { 2335 --I; 2336 // New instructions were inserted at the end of the preheader. 2337 if (isa<PHINode>(I)) 2338 break; 2339 2340 // Don't move instructions which might have side effects, since the side 2341 // effects need to complete before instructions inside the loop. Also don't 2342 // move instructions which might read memory, since the loop may modify 2343 // memory. Note that it's okay if the instruction might have undefined 2344 // behavior: LoopSimplify guarantees that the preheader dominates the exit 2345 // block. 2346 if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 2347 continue; 2348 2349 // Skip debug info intrinsics. 2350 if (isa<DbgInfoIntrinsic>(I)) 2351 continue; 2352 2353 // Skip eh pad instructions. 2354 if (I->isEHPad()) 2355 continue; 2356 2357 // Don't sink alloca: we never want to sink static alloca's out of the 2358 // entry block, and correctly sinking dynamic alloca's requires 2359 // checks for stacksave/stackrestore intrinsics. 2360 // FIXME: Refactor this check somehow? 2361 if (isa<AllocaInst>(I)) 2362 continue; 2363 2364 // Determine if there is a use in or before the loop (direct or 2365 // otherwise). 2366 bool UsedInLoop = false; 2367 for (Use &U : I->uses()) { 2368 Instruction *User = cast<Instruction>(U.getUser()); 2369 BasicBlock *UseBB = User->getParent(); 2370 if (PHINode *P = dyn_cast<PHINode>(User)) { 2371 unsigned i = 2372 PHINode::getIncomingValueNumForOperand(U.getOperandNo()); 2373 UseBB = P->getIncomingBlock(i); 2374 } 2375 if (UseBB == Preheader || L->contains(UseBB)) { 2376 UsedInLoop = true; 2377 break; 2378 } 2379 } 2380 2381 // If there is, the def must remain in the preheader. 2382 if (UsedInLoop) 2383 continue; 2384 2385 // Otherwise, sink it to the exit block. 2386 Instruction *ToMove = &*I; 2387 bool Done = false; 2388 2389 if (I != Preheader->begin()) { 2390 // Skip debug info intrinsics. 2391 do { 2392 --I; 2393 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin()); 2394 2395 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin()) 2396 Done = true; 2397 } else { 2398 Done = true; 2399 } 2400 2401 ToMove->moveBefore(*ExitBlock, InsertPt); 2402 if (Done) break; 2403 InsertPt = ToMove->getIterator(); 2404 } 2405 } 2406 2407 //===----------------------------------------------------------------------===// 2408 // IndVarSimplify driver. Manage several subpasses of IV simplification. 2409 //===----------------------------------------------------------------------===// 2410 2411 bool IndVarSimplify::run(Loop *L) { 2412 // We need (and expect!) the incoming loop to be in LCSSA. 2413 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 2414 "LCSSA required to run indvars!"); 2415 2416 // If LoopSimplify form is not available, stay out of trouble. Some notes: 2417 // - LSR currently only supports LoopSimplify-form loops. Indvars' 2418 // canonicalization can be a pessimization without LSR to "clean up" 2419 // afterwards. 2420 // - We depend on having a preheader; in particular, 2421 // Loop::getCanonicalInductionVariable only supports loops with preheaders, 2422 // and we're in trouble if we can't find the induction variable even when 2423 // we've manually inserted one. 2424 // - LFTR relies on having a single backedge. 2425 if (!L->isLoopSimplifyForm()) 2426 return false; 2427 2428 // If there are any floating-point recurrences, attempt to 2429 // transform them to use integer recurrences. 2430 rewriteNonIntegerIVs(L); 2431 2432 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 2433 2434 // Create a rewriter object which we'll use to transform the code with. 2435 SCEVExpander Rewriter(*SE, DL, "indvars"); 2436 #ifndef NDEBUG 2437 Rewriter.setDebugType(DEBUG_TYPE); 2438 #endif 2439 2440 // Eliminate redundant IV users. 2441 // 2442 // Simplification works best when run before other consumers of SCEV. We 2443 // attempt to avoid evaluating SCEVs for sign/zero extend operations until 2444 // other expressions involving loop IVs have been evaluated. This helps SCEV 2445 // set no-wrap flags before normalizing sign/zero extension. 2446 Rewriter.disableCanonicalMode(); 2447 simplifyAndExtend(L, Rewriter, LI); 2448 2449 // Check to see if this loop has a computable loop-invariant execution count. 2450 // If so, this means that we can compute the final value of any expressions 2451 // that are recurrent in the loop, and substitute the exit values from the 2452 // loop into any instructions outside of the loop that use the final values of 2453 // the current expressions. 2454 // 2455 if (ReplaceExitValue != NeverRepl && 2456 !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 2457 rewriteLoopExitValues(L, Rewriter); 2458 2459 // Eliminate redundant IV cycles. 2460 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts); 2461 2462 // If we have a trip count expression, rewrite the loop's exit condition 2463 // using it. We can currently only handle loops with a single exit. 2464 if (!DisableLFTR && canExpandBackedgeTakenCount(L, SE, Rewriter) && 2465 needsLFTR(L, DT)) { 2466 PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT); 2467 if (IndVar) { 2468 // Check preconditions for proper SCEVExpander operation. SCEV does not 2469 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any 2470 // pass that uses the SCEVExpander must do it. This does not work well for 2471 // loop passes because SCEVExpander makes assumptions about all loops, 2472 // while LoopPassManager only forces the current loop to be simplified. 2473 // 2474 // FIXME: SCEV expansion has no way to bail out, so the caller must 2475 // explicitly check any assumptions made by SCEV. Brittle. 2476 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount); 2477 if (!AR || AR->getLoop()->getLoopPreheader()) 2478 (void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar, 2479 Rewriter); 2480 } 2481 } 2482 // Clear the rewriter cache, because values that are in the rewriter's cache 2483 // can be deleted in the loop below, causing the AssertingVH in the cache to 2484 // trigger. 2485 Rewriter.clear(); 2486 2487 // Now that we're done iterating through lists, clean up any instructions 2488 // which are now dead. 2489 while (!DeadInsts.empty()) 2490 if (Instruction *Inst = 2491 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val())) 2492 RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI); 2493 2494 // The Rewriter may not be used from this point on. 2495 2496 // Loop-invariant instructions in the preheader that aren't used in the 2497 // loop may be sunk below the loop to reduce register pressure. 2498 sinkUnusedInvariants(L); 2499 2500 // rewriteFirstIterationLoopExitValues does not rely on the computation of 2501 // trip count and therefore can further simplify exit values in addition to 2502 // rewriteLoopExitValues. 2503 rewriteFirstIterationLoopExitValues(L); 2504 2505 // Clean up dead instructions. 2506 Changed |= DeleteDeadPHIs(L->getHeader(), TLI); 2507 2508 // Check a post-condition. 2509 assert(L->isRecursivelyLCSSAForm(*DT, *LI) && 2510 "Indvars did not preserve LCSSA!"); 2511 2512 // Verify that LFTR, and any other change have not interfered with SCEV's 2513 // ability to compute trip count. 2514 #ifndef NDEBUG 2515 if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 2516 SE->forgetLoop(L); 2517 const SCEV *NewBECount = SE->getBackedgeTakenCount(L); 2518 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) < 2519 SE->getTypeSizeInBits(NewBECount->getType())) 2520 NewBECount = SE->getTruncateOrNoop(NewBECount, 2521 BackedgeTakenCount->getType()); 2522 else 2523 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, 2524 NewBECount->getType()); 2525 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV"); 2526 } 2527 #endif 2528 2529 return Changed; 2530 } 2531 2532 PreservedAnalyses IndVarSimplifyPass::run(Loop &L, LoopAnalysisManager &AM, 2533 LoopStandardAnalysisResults &AR, 2534 LPMUpdater &) { 2535 Function *F = L.getHeader()->getParent(); 2536 const DataLayout &DL = F->getParent()->getDataLayout(); 2537 2538 IndVarSimplify IVS(&AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI); 2539 if (!IVS.run(&L)) 2540 return PreservedAnalyses::all(); 2541 2542 auto PA = getLoopPassPreservedAnalyses(); 2543 PA.preserveSet<CFGAnalyses>(); 2544 return PA; 2545 } 2546 2547 namespace { 2548 2549 struct IndVarSimplifyLegacyPass : public LoopPass { 2550 static char ID; // Pass identification, replacement for typeid 2551 2552 IndVarSimplifyLegacyPass() : LoopPass(ID) { 2553 initializeIndVarSimplifyLegacyPassPass(*PassRegistry::getPassRegistry()); 2554 } 2555 2556 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 2557 if (skipLoop(L)) 2558 return false; 2559 2560 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2561 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 2562 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2563 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 2564 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr; 2565 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>(); 2566 auto *TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr; 2567 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 2568 2569 IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI); 2570 return IVS.run(L); 2571 } 2572 2573 void getAnalysisUsage(AnalysisUsage &AU) const override { 2574 AU.setPreservesCFG(); 2575 getLoopAnalysisUsage(AU); 2576 } 2577 }; 2578 2579 } // end anonymous namespace 2580 2581 char IndVarSimplifyLegacyPass::ID = 0; 2582 2583 INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars", 2584 "Induction Variable Simplification", false, false) 2585 INITIALIZE_PASS_DEPENDENCY(LoopPass) 2586 INITIALIZE_PASS_END(IndVarSimplifyLegacyPass, "indvars", 2587 "Induction Variable Simplification", false, false) 2588 2589 Pass *llvm::createIndVarSimplifyPass() { 2590 return new IndVarSimplifyLegacyPass(); 2591 } 2592