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