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