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 // Additionally, unless -disable-iv-rewrite is on, this transformation makes the 15 // following changes to each loop with an identifiable induction variable: 16 // 1. All loops are transformed to have a SINGLE canonical induction variable 17 // which starts at zero and steps by one. 18 // 2. The canonical induction variable is guaranteed to be the first PHI node 19 // in the loop header block. 20 // 3. The canonical induction variable is guaranteed to be in a wide enough 21 // type so that IV expressions need not be (directly) zero-extended or 22 // sign-extended. 23 // 4. Any pointer arithmetic recurrences are raised to use array subscripts. 24 // 25 // If the trip count of a loop is computable, this pass also makes the following 26 // changes: 27 // 1. The exit condition for the loop is canonicalized to compare the 28 // induction value against the exit value. This turns loops like: 29 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)' 30 // 2. Any use outside of the loop of an expression derived from the indvar 31 // is changed to compute the derived value outside of the loop, eliminating 32 // the dependence on the exit value of the induction variable. If the only 33 // purpose of the loop is to compute the exit value of some derived 34 // expression, this transformation will make the loop dead. 35 // 36 // This transformation should be followed by strength reduction after all of the 37 // desired loop transformations have been performed. 38 // 39 //===----------------------------------------------------------------------===// 40 41 #define DEBUG_TYPE "indvars" 42 #include "llvm/Transforms/Scalar.h" 43 #include "llvm/BasicBlock.h" 44 #include "llvm/Constants.h" 45 #include "llvm/Instructions.h" 46 #include "llvm/IntrinsicInst.h" 47 #include "llvm/LLVMContext.h" 48 #include "llvm/Type.h" 49 #include "llvm/Analysis/Dominators.h" 50 #include "llvm/Analysis/IVUsers.h" 51 #include "llvm/Analysis/ScalarEvolutionExpander.h" 52 #include "llvm/Analysis/LoopInfo.h" 53 #include "llvm/Analysis/LoopPass.h" 54 #include "llvm/Support/CFG.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include "llvm/Transforms/Utils/Local.h" 59 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 60 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 61 #include "llvm/Target/TargetData.h" 62 #include "llvm/ADT/DenseMap.h" 63 #include "llvm/ADT/SmallVector.h" 64 #include "llvm/ADT/Statistic.h" 65 using namespace llvm; 66 67 STATISTIC(NumRemoved , "Number of aux indvars removed"); 68 STATISTIC(NumWidened , "Number of indvars widened"); 69 STATISTIC(NumInserted , "Number of canonical indvars added"); 70 STATISTIC(NumReplaced , "Number of exit values replaced"); 71 STATISTIC(NumLFTR , "Number of loop exit tests replaced"); 72 STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated"); 73 STATISTIC(NumElimIV , "Number of congruent IVs eliminated"); 74 75 namespace llvm { 76 cl::opt<bool> DisableIVRewrite( 77 "disable-iv-rewrite", cl::Hidden, 78 cl::desc("Disable canonical induction variable rewriting")); 79 80 // Trip count verification can be enabled by default under NDEBUG if we 81 // implement a strong expression equivalence checker in SCEV. Until then, we 82 // use the verify-indvars flag, which may assert in some cases. 83 cl::opt<bool> VerifyIndvars( 84 "verify-indvars", cl::Hidden, 85 cl::desc("Verify the ScalarEvolution result after running indvars")); 86 } 87 88 // Temporary flag for use with -disable-iv-rewrite to force a canonical IV for 89 // LFTR purposes. 90 static cl::opt<bool> ForceLFTR( 91 "force-lftr", cl::Hidden, 92 cl::desc("Enable forced linear function test replacement")); 93 94 namespace { 95 class IndVarSimplify : public LoopPass { 96 IVUsers *IU; 97 LoopInfo *LI; 98 ScalarEvolution *SE; 99 DominatorTree *DT; 100 TargetData *TD; 101 102 SmallVector<WeakVH, 16> DeadInsts; 103 bool Changed; 104 public: 105 106 static char ID; // Pass identification, replacement for typeid 107 IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0), 108 Changed(false) { 109 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry()); 110 } 111 112 virtual bool runOnLoop(Loop *L, LPPassManager &LPM); 113 114 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 115 AU.addRequired<DominatorTree>(); 116 AU.addRequired<LoopInfo>(); 117 AU.addRequired<ScalarEvolution>(); 118 AU.addRequiredID(LoopSimplifyID); 119 AU.addRequiredID(LCSSAID); 120 if (!DisableIVRewrite) 121 AU.addRequired<IVUsers>(); 122 AU.addPreserved<ScalarEvolution>(); 123 AU.addPreservedID(LoopSimplifyID); 124 AU.addPreservedID(LCSSAID); 125 if (!DisableIVRewrite) 126 AU.addPreserved<IVUsers>(); 127 AU.setPreservesCFG(); 128 } 129 130 private: 131 virtual void releaseMemory() { 132 DeadInsts.clear(); 133 } 134 135 bool isValidRewrite(Value *FromVal, Value *ToVal); 136 137 void HandleFloatingPointIV(Loop *L, PHINode *PH); 138 void RewriteNonIntegerIVs(Loop *L); 139 140 void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM); 141 142 void SimplifyCongruentIVs(Loop *L); 143 144 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter); 145 146 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter); 147 148 Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount, 149 PHINode *IndVar, SCEVExpander &Rewriter); 150 151 void SinkUnusedInvariants(Loop *L); 152 }; 153 } 154 155 char IndVarSimplify::ID = 0; 156 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars", 157 "Induction Variable Simplification", false, false) 158 INITIALIZE_PASS_DEPENDENCY(DominatorTree) 159 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 160 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 161 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 162 INITIALIZE_PASS_DEPENDENCY(LCSSA) 163 INITIALIZE_PASS_DEPENDENCY(IVUsers) 164 INITIALIZE_PASS_END(IndVarSimplify, "indvars", 165 "Induction Variable Simplification", false, false) 166 167 Pass *llvm::createIndVarSimplifyPass() { 168 return new IndVarSimplify(); 169 } 170 171 /// isValidRewrite - Return true if the SCEV expansion generated by the 172 /// rewriter can replace the original value. SCEV guarantees that it 173 /// produces the same value, but the way it is produced may be illegal IR. 174 /// Ideally, this function will only be called for verification. 175 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) { 176 // If an SCEV expression subsumed multiple pointers, its expansion could 177 // reassociate the GEP changing the base pointer. This is illegal because the 178 // final address produced by a GEP chain must be inbounds relative to its 179 // underlying object. Otherwise basic alias analysis, among other things, 180 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid 181 // producing an expression involving multiple pointers. Until then, we must 182 // bail out here. 183 // 184 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject 185 // because it understands lcssa phis while SCEV does not. 186 Value *FromPtr = FromVal; 187 Value *ToPtr = ToVal; 188 if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) { 189 FromPtr = GEP->getPointerOperand(); 190 } 191 if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) { 192 ToPtr = GEP->getPointerOperand(); 193 } 194 if (FromPtr != FromVal || ToPtr != ToVal) { 195 // Quickly check the common case 196 if (FromPtr == ToPtr) 197 return true; 198 199 // SCEV may have rewritten an expression that produces the GEP's pointer 200 // operand. That's ok as long as the pointer operand has the same base 201 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the 202 // base of a recurrence. This handles the case in which SCEV expansion 203 // converts a pointer type recurrence into a nonrecurrent pointer base 204 // indexed by an integer recurrence. 205 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr)); 206 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr)); 207 if (FromBase == ToBase) 208 return true; 209 210 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " 211 << *FromBase << " != " << *ToBase << "\n"); 212 213 return false; 214 } 215 return true; 216 } 217 218 /// Determine the insertion point for this user. By default, insert immediately 219 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the 220 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest 221 /// common dominator for the incoming blocks. 222 static Instruction *getInsertPointForUses(Instruction *User, Value *Def, 223 DominatorTree *DT) { 224 PHINode *PHI = dyn_cast<PHINode>(User); 225 if (!PHI) 226 return User; 227 228 Instruction *InsertPt = 0; 229 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { 230 if (PHI->getIncomingValue(i) != Def) 231 continue; 232 233 BasicBlock *InsertBB = PHI->getIncomingBlock(i); 234 if (!InsertPt) { 235 InsertPt = InsertBB->getTerminator(); 236 continue; 237 } 238 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); 239 InsertPt = InsertBB->getTerminator(); 240 } 241 assert(InsertPt && "Missing phi operand"); 242 assert((!isa<Instruction>(Def) || 243 DT->dominates(cast<Instruction>(Def), InsertPt)) && 244 "def does not dominate all uses"); 245 return InsertPt; 246 } 247 248 //===----------------------------------------------------------------------===// 249 // RewriteNonIntegerIVs and helpers. Prefer integer IVs. 250 //===----------------------------------------------------------------------===// 251 252 /// ConvertToSInt - Convert APF to an integer, if possible. 253 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) { 254 bool isExact = false; 255 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble) 256 return false; 257 // See if we can convert this to an int64_t 258 uint64_t UIntVal; 259 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero, 260 &isExact) != APFloat::opOK || !isExact) 261 return false; 262 IntVal = UIntVal; 263 return true; 264 } 265 266 /// HandleFloatingPointIV - If the loop has floating induction variable 267 /// then insert corresponding integer induction variable if possible. 268 /// For example, 269 /// for(double i = 0; i < 10000; ++i) 270 /// bar(i) 271 /// is converted into 272 /// for(int i = 0; i < 10000; ++i) 273 /// bar((double)i); 274 /// 275 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) { 276 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 277 unsigned BackEdge = IncomingEdge^1; 278 279 // Check incoming value. 280 ConstantFP *InitValueVal = 281 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge)); 282 283 int64_t InitValue; 284 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue)) 285 return; 286 287 // Check IV increment. Reject this PN if increment operation is not 288 // an add or increment value can not be represented by an integer. 289 BinaryOperator *Incr = 290 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge)); 291 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return; 292 293 // If this is not an add of the PHI with a constantfp, or if the constant fp 294 // is not an integer, bail out. 295 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1)); 296 int64_t IncValue; 297 if (IncValueVal == 0 || Incr->getOperand(0) != PN || 298 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue)) 299 return; 300 301 // Check Incr uses. One user is PN and the other user is an exit condition 302 // used by the conditional terminator. 303 Value::use_iterator IncrUse = Incr->use_begin(); 304 Instruction *U1 = cast<Instruction>(*IncrUse++); 305 if (IncrUse == Incr->use_end()) return; 306 Instruction *U2 = cast<Instruction>(*IncrUse++); 307 if (IncrUse != Incr->use_end()) return; 308 309 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't 310 // only used by a branch, we can't transform it. 311 FCmpInst *Compare = dyn_cast<FCmpInst>(U1); 312 if (!Compare) 313 Compare = dyn_cast<FCmpInst>(U2); 314 if (Compare == 0 || !Compare->hasOneUse() || 315 !isa<BranchInst>(Compare->use_back())) 316 return; 317 318 BranchInst *TheBr = cast<BranchInst>(Compare->use_back()); 319 320 // We need to verify that the branch actually controls the iteration count 321 // of the loop. If not, the new IV can overflow and no one will notice. 322 // The branch block must be in the loop and one of the successors must be out 323 // of the loop. 324 assert(TheBr->isConditional() && "Can't use fcmp if not conditional"); 325 if (!L->contains(TheBr->getParent()) || 326 (L->contains(TheBr->getSuccessor(0)) && 327 L->contains(TheBr->getSuccessor(1)))) 328 return; 329 330 331 // If it isn't a comparison with an integer-as-fp (the exit value), we can't 332 // transform it. 333 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1)); 334 int64_t ExitValue; 335 if (ExitValueVal == 0 || 336 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue)) 337 return; 338 339 // Find new predicate for integer comparison. 340 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE; 341 switch (Compare->getPredicate()) { 342 default: return; // Unknown comparison. 343 case CmpInst::FCMP_OEQ: 344 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break; 345 case CmpInst::FCMP_ONE: 346 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break; 347 case CmpInst::FCMP_OGT: 348 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break; 349 case CmpInst::FCMP_OGE: 350 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break; 351 case CmpInst::FCMP_OLT: 352 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break; 353 case CmpInst::FCMP_OLE: 354 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break; 355 } 356 357 // We convert the floating point induction variable to a signed i32 value if 358 // we can. This is only safe if the comparison will not overflow in a way 359 // that won't be trapped by the integer equivalent operations. Check for this 360 // now. 361 // TODO: We could use i64 if it is native and the range requires it. 362 363 // The start/stride/exit values must all fit in signed i32. 364 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue)) 365 return; 366 367 // If not actually striding (add x, 0.0), avoid touching the code. 368 if (IncValue == 0) 369 return; 370 371 // Positive and negative strides have different safety conditions. 372 if (IncValue > 0) { 373 // If we have a positive stride, we require the init to be less than the 374 // exit value and an equality or less than comparison. 375 if (InitValue >= ExitValue || 376 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE) 377 return; 378 379 uint32_t Range = uint32_t(ExitValue-InitValue); 380 if (NewPred == CmpInst::ICMP_SLE) { 381 // Normalize SLE -> SLT, check for infinite loop. 382 if (++Range == 0) return; // Range overflows. 383 } 384 385 unsigned Leftover = Range % uint32_t(IncValue); 386 387 // If this is an equality comparison, we require that the strided value 388 // exactly land on the exit value, otherwise the IV condition will wrap 389 // around and do things the fp IV wouldn't. 390 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 391 Leftover != 0) 392 return; 393 394 // If the stride would wrap around the i32 before exiting, we can't 395 // transform the IV. 396 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue) 397 return; 398 399 } else { 400 // If we have a negative stride, we require the init to be greater than the 401 // exit value and an equality or greater than comparison. 402 if (InitValue >= ExitValue || 403 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE) 404 return; 405 406 uint32_t Range = uint32_t(InitValue-ExitValue); 407 if (NewPred == CmpInst::ICMP_SGE) { 408 // Normalize SGE -> SGT, check for infinite loop. 409 if (++Range == 0) return; // Range overflows. 410 } 411 412 unsigned Leftover = Range % uint32_t(-IncValue); 413 414 // If this is an equality comparison, we require that the strided value 415 // exactly land on the exit value, otherwise the IV condition will wrap 416 // around and do things the fp IV wouldn't. 417 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 418 Leftover != 0) 419 return; 420 421 // If the stride would wrap around the i32 before exiting, we can't 422 // transform the IV. 423 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue) 424 return; 425 } 426 427 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext()); 428 429 // Insert new integer induction variable. 430 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN); 431 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue), 432 PN->getIncomingBlock(IncomingEdge)); 433 434 Value *NewAdd = 435 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue), 436 Incr->getName()+".int", Incr); 437 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge)); 438 439 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd, 440 ConstantInt::get(Int32Ty, ExitValue), 441 Compare->getName()); 442 443 // In the following deletions, PN may become dead and may be deleted. 444 // Use a WeakVH to observe whether this happens. 445 WeakVH WeakPH = PN; 446 447 // Delete the old floating point exit comparison. The branch starts using the 448 // new comparison. 449 NewCompare->takeName(Compare); 450 Compare->replaceAllUsesWith(NewCompare); 451 RecursivelyDeleteTriviallyDeadInstructions(Compare); 452 453 // Delete the old floating point increment. 454 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType())); 455 RecursivelyDeleteTriviallyDeadInstructions(Incr); 456 457 // If the FP induction variable still has uses, this is because something else 458 // in the loop uses its value. In order to canonicalize the induction 459 // variable, we chose to eliminate the IV and rewrite it in terms of an 460 // int->fp cast. 461 // 462 // We give preference to sitofp over uitofp because it is faster on most 463 // platforms. 464 if (WeakPH) { 465 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv", 466 PN->getParent()->getFirstInsertionPt()); 467 PN->replaceAllUsesWith(Conv); 468 RecursivelyDeleteTriviallyDeadInstructions(PN); 469 } 470 471 // Add a new IVUsers entry for the newly-created integer PHI. 472 if (IU) 473 IU->AddUsersIfInteresting(NewPHI); 474 475 Changed = true; 476 } 477 478 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) { 479 // First step. Check to see if there are any floating-point recurrences. 480 // If there are, change them into integer recurrences, permitting analysis by 481 // the SCEV routines. 482 // 483 BasicBlock *Header = L->getHeader(); 484 485 SmallVector<WeakVH, 8> PHIs; 486 for (BasicBlock::iterator I = Header->begin(); 487 PHINode *PN = dyn_cast<PHINode>(I); ++I) 488 PHIs.push_back(PN); 489 490 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 491 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i])) 492 HandleFloatingPointIV(L, PN); 493 494 // If the loop previously had floating-point IV, ScalarEvolution 495 // may not have been able to compute a trip count. Now that we've done some 496 // re-writing, the trip count may be computable. 497 if (Changed) 498 SE->forgetLoop(L); 499 } 500 501 //===----------------------------------------------------------------------===// 502 // RewriteLoopExitValues - Optimize IV users outside the loop. 503 // As a side effect, reduces the amount of IV processing within the loop. 504 //===----------------------------------------------------------------------===// 505 506 /// RewriteLoopExitValues - Check to see if this loop has a computable 507 /// loop-invariant execution count. If so, this means that we can compute the 508 /// final value of any expressions that are recurrent in the loop, and 509 /// substitute the exit values from the loop into any instructions outside of 510 /// the loop that use the final values of the current expressions. 511 /// 512 /// This is mostly redundant with the regular IndVarSimplify activities that 513 /// happen later, except that it's more powerful in some cases, because it's 514 /// able to brute-force evaluate arbitrary instructions as long as they have 515 /// constant operands at the beginning of the loop. 516 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) { 517 // Verify the input to the pass in already in LCSSA form. 518 assert(L->isLCSSAForm(*DT)); 519 520 SmallVector<BasicBlock*, 8> ExitBlocks; 521 L->getUniqueExitBlocks(ExitBlocks); 522 523 // Find all values that are computed inside the loop, but used outside of it. 524 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 525 // the exit blocks of the loop to find them. 526 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 527 BasicBlock *ExitBB = ExitBlocks[i]; 528 529 // If there are no PHI nodes in this exit block, then no values defined 530 // inside the loop are used on this path, skip it. 531 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 532 if (!PN) continue; 533 534 unsigned NumPreds = PN->getNumIncomingValues(); 535 536 // Iterate over all of the PHI nodes. 537 BasicBlock::iterator BBI = ExitBB->begin(); 538 while ((PN = dyn_cast<PHINode>(BBI++))) { 539 if (PN->use_empty()) 540 continue; // dead use, don't replace it 541 542 // SCEV only supports integer expressions for now. 543 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy()) 544 continue; 545 546 // It's necessary to tell ScalarEvolution about this explicitly so that 547 // it can walk the def-use list and forget all SCEVs, as it may not be 548 // watching the PHI itself. Once the new exit value is in place, there 549 // may not be a def-use connection between the loop and every instruction 550 // which got a SCEVAddRecExpr for that loop. 551 SE->forgetValue(PN); 552 553 // Iterate over all of the values in all the PHI nodes. 554 for (unsigned i = 0; i != NumPreds; ++i) { 555 // If the value being merged in is not integer or is not defined 556 // in the loop, skip it. 557 Value *InVal = PN->getIncomingValue(i); 558 if (!isa<Instruction>(InVal)) 559 continue; 560 561 // If this pred is for a subloop, not L itself, skip it. 562 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 563 continue; // The Block is in a subloop, skip it. 564 565 // Check that InVal is defined in the loop. 566 Instruction *Inst = cast<Instruction>(InVal); 567 if (!L->contains(Inst)) 568 continue; 569 570 // Okay, this instruction has a user outside of the current loop 571 // and varies predictably *inside* the loop. Evaluate the value it 572 // contains when the loop exits, if possible. 573 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 574 if (!SE->isLoopInvariant(ExitValue, L)) 575 continue; 576 577 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst); 578 579 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n' 580 << " LoopVal = " << *Inst << "\n"); 581 582 if (!isValidRewrite(Inst, ExitVal)) { 583 DeadInsts.push_back(ExitVal); 584 continue; 585 } 586 Changed = true; 587 ++NumReplaced; 588 589 PN->setIncomingValue(i, ExitVal); 590 591 // If this instruction is dead now, delete it. 592 RecursivelyDeleteTriviallyDeadInstructions(Inst); 593 594 if (NumPreds == 1) { 595 // Completely replace a single-pred PHI. This is safe, because the 596 // NewVal won't be variant in the loop, so we don't need an LCSSA phi 597 // node anymore. 598 PN->replaceAllUsesWith(ExitVal); 599 RecursivelyDeleteTriviallyDeadInstructions(PN); 600 } 601 } 602 if (NumPreds != 1) { 603 // Clone the PHI and delete the original one. This lets IVUsers and 604 // any other maps purge the original user from their records. 605 PHINode *NewPN = cast<PHINode>(PN->clone()); 606 NewPN->takeName(PN); 607 NewPN->insertBefore(PN); 608 PN->replaceAllUsesWith(NewPN); 609 PN->eraseFromParent(); 610 } 611 } 612 } 613 614 // The insertion point instruction may have been deleted; clear it out 615 // so that the rewriter doesn't trip over it later. 616 Rewriter.clearInsertPoint(); 617 } 618 619 //===----------------------------------------------------------------------===// 620 // Rewrite IV users based on a canonical IV. 621 // To be replaced by -disable-iv-rewrite. 622 //===----------------------------------------------------------------------===// 623 624 // FIXME: It is an extremely bad idea to indvar substitute anything more 625 // complex than affine induction variables. Doing so will put expensive 626 // polynomial evaluations inside of the loop, and the str reduction pass 627 // currently can only reduce affine polynomials. For now just disable 628 // indvar subst on anything more complex than an affine addrec, unless 629 // it can be expanded to a trivial value. 630 static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) { 631 // Loop-invariant values are safe. 632 if (SE->isLoopInvariant(S, L)) return true; 633 634 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how 635 // to transform them into efficient code. 636 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 637 return AR->isAffine(); 638 639 // An add is safe it all its operands are safe. 640 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) { 641 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(), 642 E = Commutative->op_end(); I != E; ++I) 643 if (!isSafe(*I, L, SE)) return false; 644 return true; 645 } 646 647 // A cast is safe if its operand is. 648 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) 649 return isSafe(C->getOperand(), L, SE); 650 651 // A udiv is safe if its operands are. 652 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S)) 653 return isSafe(UD->getLHS(), L, SE) && 654 isSafe(UD->getRHS(), L, SE); 655 656 // SCEVUnknown is always safe. 657 if (isa<SCEVUnknown>(S)) 658 return true; 659 660 // Nothing else is safe. 661 return false; 662 } 663 664 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) { 665 // Rewrite all induction variable expressions in terms of the canonical 666 // induction variable. 667 // 668 // If there were induction variables of other sizes or offsets, manually 669 // add the offsets to the primary induction variable and cast, avoiding 670 // the need for the code evaluation methods to insert induction variables 671 // of different sizes. 672 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) { 673 Value *Op = UI->getOperandValToReplace(); 674 Type *UseTy = Op->getType(); 675 Instruction *User = UI->getUser(); 676 677 // Compute the final addrec to expand into code. 678 const SCEV *AR = IU->getReplacementExpr(*UI); 679 680 // Evaluate the expression out of the loop, if possible. 681 if (!L->contains(UI->getUser())) { 682 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop()); 683 if (SE->isLoopInvariant(ExitVal, L)) 684 AR = ExitVal; 685 } 686 687 // FIXME: It is an extremely bad idea to indvar substitute anything more 688 // complex than affine induction variables. Doing so will put expensive 689 // polynomial evaluations inside of the loop, and the str reduction pass 690 // currently can only reduce affine polynomials. For now just disable 691 // indvar subst on anything more complex than an affine addrec, unless 692 // it can be expanded to a trivial value. 693 if (!isSafe(AR, L, SE)) 694 continue; 695 696 // Determine the insertion point for this user. By default, insert 697 // immediately before the user. The SCEVExpander class will automatically 698 // hoist loop invariants out of the loop. For PHI nodes, there may be 699 // multiple uses, so compute the nearest common dominator for the 700 // incoming blocks. 701 Instruction *InsertPt = getInsertPointForUses(User, Op, DT); 702 703 // Now expand it into actual Instructions and patch it into place. 704 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt); 705 706 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n' 707 << " into = " << *NewVal << "\n"); 708 709 if (!isValidRewrite(Op, NewVal)) { 710 DeadInsts.push_back(NewVal); 711 continue; 712 } 713 // Inform ScalarEvolution that this value is changing. The change doesn't 714 // affect its value, but it does potentially affect which use lists the 715 // value will be on after the replacement, which affects ScalarEvolution's 716 // ability to walk use lists and drop dangling pointers when a value is 717 // deleted. 718 SE->forgetValue(User); 719 720 // Patch the new value into place. 721 if (Op->hasName()) 722 NewVal->takeName(Op); 723 if (Instruction *NewValI = dyn_cast<Instruction>(NewVal)) 724 NewValI->setDebugLoc(User->getDebugLoc()); 725 User->replaceUsesOfWith(Op, NewVal); 726 UI->setOperandValToReplace(NewVal); 727 728 ++NumRemoved; 729 Changed = true; 730 731 // The old value may be dead now. 732 DeadInsts.push_back(Op); 733 } 734 } 735 736 //===----------------------------------------------------------------------===// 737 // IV Widening - Extend the width of an IV to cover its widest uses. 738 //===----------------------------------------------------------------------===// 739 740 namespace { 741 // Collect information about induction variables that are used by sign/zero 742 // extend operations. This information is recorded by CollectExtend and 743 // provides the input to WidenIV. 744 struct WideIVInfo { 745 Type *WidestNativeType; // Widest integer type created [sz]ext 746 bool IsSigned; // Was an sext user seen before a zext? 747 748 WideIVInfo() : WidestNativeType(0), IsSigned(false) {} 749 }; 750 751 class WideIVVisitor : public IVVisitor { 752 ScalarEvolution *SE; 753 const TargetData *TD; 754 755 public: 756 WideIVInfo WI; 757 758 WideIVVisitor(ScalarEvolution *SCEV, const TargetData *TData) : 759 SE(SCEV), TD(TData) {} 760 761 // Implement the interface used by simplifyUsersOfIV. 762 virtual void visitCast(CastInst *Cast); 763 }; 764 } 765 766 /// visitCast - Update information about the induction variable that is 767 /// extended by this sign or zero extend operation. This is used to determine 768 /// the final width of the IV before actually widening it. 769 void WideIVVisitor::visitCast(CastInst *Cast) { 770 bool IsSigned = Cast->getOpcode() == Instruction::SExt; 771 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt) 772 return; 773 774 Type *Ty = Cast->getType(); 775 uint64_t Width = SE->getTypeSizeInBits(Ty); 776 if (TD && !TD->isLegalInteger(Width)) 777 return; 778 779 if (!WI.WidestNativeType) { 780 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 781 WI.IsSigned = IsSigned; 782 return; 783 } 784 785 // We extend the IV to satisfy the sign of its first user, arbitrarily. 786 if (WI.IsSigned != IsSigned) 787 return; 788 789 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType)) 790 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty); 791 } 792 793 namespace { 794 795 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the 796 /// WideIV that computes the same value as the Narrow IV def. This avoids 797 /// caching Use* pointers. 798 struct NarrowIVDefUse { 799 Instruction *NarrowDef; 800 Instruction *NarrowUse; 801 Instruction *WideDef; 802 803 NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {} 804 805 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD): 806 NarrowDef(ND), NarrowUse(NU), WideDef(WD) {} 807 }; 808 809 /// WidenIV - The goal of this transform is to remove sign and zero extends 810 /// without creating any new induction variables. To do this, it creates a new 811 /// phi of the wider type and redirects all users, either removing extends or 812 /// inserting truncs whenever we stop propagating the type. 813 /// 814 class WidenIV { 815 // Parameters 816 PHINode *OrigPhi; 817 Type *WideType; 818 bool IsSigned; 819 820 // Context 821 LoopInfo *LI; 822 Loop *L; 823 ScalarEvolution *SE; 824 DominatorTree *DT; 825 826 // Result 827 PHINode *WidePhi; 828 Instruction *WideInc; 829 const SCEV *WideIncExpr; 830 SmallVectorImpl<WeakVH> &DeadInsts; 831 832 SmallPtrSet<Instruction*,16> Widened; 833 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; 834 835 public: 836 WidenIV(PHINode *PN, const WideIVInfo &WI, LoopInfo *LInfo, 837 ScalarEvolution *SEv, DominatorTree *DTree, 838 SmallVectorImpl<WeakVH> &DI) : 839 OrigPhi(PN), 840 WideType(WI.WidestNativeType), 841 IsSigned(WI.IsSigned), 842 LI(LInfo), 843 L(LI->getLoopFor(OrigPhi->getParent())), 844 SE(SEv), 845 DT(DTree), 846 WidePhi(0), 847 WideInc(0), 848 WideIncExpr(0), 849 DeadInsts(DI) { 850 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); 851 } 852 853 PHINode *CreateWideIV(SCEVExpander &Rewriter); 854 855 protected: 856 Instruction *CloneIVUser(NarrowIVDefUse DU); 857 858 const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse); 859 860 Instruction *WidenIVUse(NarrowIVDefUse DU); 861 862 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); 863 }; 864 } // anonymous namespace 865 866 static Value *getExtend( Value *NarrowOper, Type *WideType, 867 bool IsSigned, IRBuilder<> &Builder) { 868 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : 869 Builder.CreateZExt(NarrowOper, WideType); 870 } 871 872 /// CloneIVUser - Instantiate a wide operation to replace a narrow 873 /// operation. This only needs to handle operations that can evaluation to 874 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone. 875 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) { 876 unsigned Opcode = DU.NarrowUse->getOpcode(); 877 switch (Opcode) { 878 default: 879 return 0; 880 case Instruction::Add: 881 case Instruction::Mul: 882 case Instruction::UDiv: 883 case Instruction::Sub: 884 case Instruction::And: 885 case Instruction::Or: 886 case Instruction::Xor: 887 case Instruction::Shl: 888 case Instruction::LShr: 889 case Instruction::AShr: 890 DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n"); 891 892 IRBuilder<> Builder(DU.NarrowUse); 893 894 // Replace NarrowDef operands with WideDef. Otherwise, we don't know 895 // anything about the narrow operand yet so must insert a [sz]ext. It is 896 // probably loop invariant and will be folded or hoisted. If it actually 897 // comes from a widened IV, it should be removed during a future call to 898 // WidenIVUse. 899 Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef : 900 getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, Builder); 901 Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef : 902 getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, Builder); 903 904 BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse); 905 BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), 906 LHS, RHS, 907 NarrowBO->getName()); 908 Builder.Insert(WideBO); 909 if (const OverflowingBinaryOperator *OBO = 910 dyn_cast<OverflowingBinaryOperator>(NarrowBO)) { 911 if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap(); 912 if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap(); 913 } 914 return WideBO; 915 } 916 llvm_unreachable(0); 917 } 918 919 /// HoistStep - Attempt to hoist an IV increment above a potential use. 920 /// 921 /// To successfully hoist, two criteria must be met: 922 /// - IncV operands dominate InsertPos and 923 /// - InsertPos dominates IncV 924 /// 925 /// Meeting the second condition means that we don't need to check all of IncV's 926 /// existing uses (it's moving up in the domtree). 927 /// 928 /// This does not yet recursively hoist the operands, although that would 929 /// not be difficult. 930 static bool HoistStep(Instruction *IncV, Instruction *InsertPos, 931 const DominatorTree *DT) 932 { 933 if (DT->dominates(IncV, InsertPos)) 934 return true; 935 936 if (!DT->dominates(InsertPos->getParent(), IncV->getParent())) 937 return false; 938 939 if (IncV->mayHaveSideEffects()) 940 return false; 941 942 // Attempt to hoist IncV 943 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end(); 944 OI != OE; ++OI) { 945 Instruction *OInst = dyn_cast<Instruction>(OI); 946 if (OInst && !DT->dominates(OInst, InsertPos)) 947 return false; 948 } 949 IncV->moveBefore(InsertPos); 950 return true; 951 } 952 953 // GetWideRecurrence - Is this instruction potentially interesting from IVUsers' 954 // perspective after widening it's type? In other words, can the extend be 955 // safely hoisted out of the loop with SCEV reducing the value to a recurrence 956 // on the same loop. If so, return the sign or zero extended 957 // recurrence. Otherwise return NULL. 958 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) { 959 if (!SE->isSCEVable(NarrowUse->getType())) 960 return 0; 961 962 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse); 963 if (SE->getTypeSizeInBits(NarrowExpr->getType()) 964 >= SE->getTypeSizeInBits(WideType)) { 965 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow 966 // index. So don't follow this use. 967 return 0; 968 } 969 970 const SCEV *WideExpr = IsSigned ? 971 SE->getSignExtendExpr(NarrowExpr, WideType) : 972 SE->getZeroExtendExpr(NarrowExpr, WideType); 973 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); 974 if (!AddRec || AddRec->getLoop() != L) 975 return 0; 976 977 return AddRec; 978 } 979 980 /// WidenIVUse - Determine whether an individual user of the narrow IV can be 981 /// widened. If so, return the wide clone of the user. 982 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) { 983 984 // Stop traversing the def-use chain at inner-loop phis or post-loop phis. 985 if (isa<PHINode>(DU.NarrowUse) && 986 LI->getLoopFor(DU.NarrowUse->getParent()) != L) 987 return 0; 988 989 // Our raison d'etre! Eliminate sign and zero extension. 990 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) { 991 Value *NewDef = DU.WideDef; 992 if (DU.NarrowUse->getType() != WideType) { 993 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); 994 unsigned IVWidth = SE->getTypeSizeInBits(WideType); 995 if (CastWidth < IVWidth) { 996 // The cast isn't as wide as the IV, so insert a Trunc. 997 IRBuilder<> Builder(DU.NarrowUse); 998 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType()); 999 } 1000 else { 1001 // A wider extend was hidden behind a narrower one. This may induce 1002 // another round of IV widening in which the intermediate IV becomes 1003 // dead. It should be very rare. 1004 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi 1005 << " not wide enough to subsume " << *DU.NarrowUse << "\n"); 1006 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1007 NewDef = DU.NarrowUse; 1008 } 1009 } 1010 if (NewDef != DU.NarrowUse) { 1011 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse 1012 << " replaced by " << *DU.WideDef << "\n"); 1013 ++NumElimExt; 1014 DU.NarrowUse->replaceAllUsesWith(NewDef); 1015 DeadInsts.push_back(DU.NarrowUse); 1016 } 1017 // Now that the extend is gone, we want to expose it's uses for potential 1018 // further simplification. We don't need to directly inform SimplifyIVUsers 1019 // of the new users, because their parent IV will be processed later as a 1020 // new loop phi. If we preserved IVUsers analysis, we would also want to 1021 // push the uses of WideDef here. 1022 1023 // No further widening is needed. The deceased [sz]ext had done it for us. 1024 return 0; 1025 } 1026 1027 // Does this user itself evaluate to a recurrence after widening? 1028 const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse); 1029 if (!WideAddRec) { 1030 // This user does not evaluate to a recurence after widening, so don't 1031 // follow it. Instead insert a Trunc to kill off the original use, 1032 // eventually isolating the original narrow IV so it can be removed. 1033 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT)); 1034 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType()); 1035 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); 1036 return 0; 1037 } 1038 // Assume block terminators cannot evaluate to a recurrence. We can't to 1039 // insert a Trunc after a terminator if there happens to be a critical edge. 1040 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() && 1041 "SCEV is not expected to evaluate a block terminator"); 1042 1043 // Reuse the IV increment that SCEVExpander created as long as it dominates 1044 // NarrowUse. 1045 Instruction *WideUse = 0; 1046 if (WideAddRec == WideIncExpr && HoistStep(WideInc, DU.NarrowUse, DT)) { 1047 WideUse = WideInc; 1048 } 1049 else { 1050 WideUse = CloneIVUser(DU); 1051 if (!WideUse) 1052 return 0; 1053 } 1054 // Evaluation of WideAddRec ensured that the narrow expression could be 1055 // extended outside the loop without overflow. This suggests that the wide use 1056 // evaluates to the same expression as the extended narrow use, but doesn't 1057 // absolutely guarantee it. Hence the following failsafe check. In rare cases 1058 // where it fails, we simply throw away the newly created wide use. 1059 if (WideAddRec != SE->getSCEV(WideUse)) { 1060 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse 1061 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n"); 1062 DeadInsts.push_back(WideUse); 1063 return 0; 1064 } 1065 1066 // Returning WideUse pushes it on the worklist. 1067 return WideUse; 1068 } 1069 1070 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers. 1071 /// 1072 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { 1073 for (Value::use_iterator UI = NarrowDef->use_begin(), 1074 UE = NarrowDef->use_end(); UI != UE; ++UI) { 1075 Instruction *NarrowUse = cast<Instruction>(*UI); 1076 1077 // Handle data flow merges and bizarre phi cycles. 1078 if (!Widened.insert(NarrowUse)) 1079 continue; 1080 1081 NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUse, WideDef)); 1082 } 1083 } 1084 1085 /// CreateWideIV - Process a single induction variable. First use the 1086 /// SCEVExpander to create a wide induction variable that evaluates to the same 1087 /// recurrence as the original narrow IV. Then use a worklist to forward 1088 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all 1089 /// interesting IV users, the narrow IV will be isolated for removal by 1090 /// DeleteDeadPHIs. 1091 /// 1092 /// It would be simpler to delete uses as they are processed, but we must avoid 1093 /// invalidating SCEV expressions. 1094 /// 1095 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) { 1096 // Is this phi an induction variable? 1097 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); 1098 if (!AddRec) 1099 return NULL; 1100 1101 // Widen the induction variable expression. 1102 const SCEV *WideIVExpr = IsSigned ? 1103 SE->getSignExtendExpr(AddRec, WideType) : 1104 SE->getZeroExtendExpr(AddRec, WideType); 1105 1106 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && 1107 "Expect the new IV expression to preserve its type"); 1108 1109 // Can the IV be extended outside the loop without overflow? 1110 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); 1111 if (!AddRec || AddRec->getLoop() != L) 1112 return NULL; 1113 1114 // An AddRec must have loop-invariant operands. Since this AddRec is 1115 // materialized by a loop header phi, the expression cannot have any post-loop 1116 // operands, so they must dominate the loop header. 1117 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) && 1118 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) 1119 && "Loop header phi recurrence inputs do not dominate the loop"); 1120 1121 // The rewriter provides a value for the desired IV expression. This may 1122 // either find an existing phi or materialize a new one. Either way, we 1123 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part 1124 // of the phi-SCC dominates the loop entry. 1125 Instruction *InsertPt = L->getHeader()->begin(); 1126 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt)); 1127 1128 // Remembering the WideIV increment generated by SCEVExpander allows 1129 // WidenIVUse to reuse it when widening the narrow IV's increment. We don't 1130 // employ a general reuse mechanism because the call above is the only call to 1131 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. 1132 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1133 WideInc = 1134 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); 1135 WideIncExpr = SE->getSCEV(WideInc); 1136 } 1137 1138 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); 1139 ++NumWidened; 1140 1141 // Traverse the def-use chain using a worklist starting at the original IV. 1142 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); 1143 1144 Widened.insert(OrigPhi); 1145 pushNarrowIVUsers(OrigPhi, WidePhi); 1146 1147 while (!NarrowIVUsers.empty()) { 1148 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); 1149 1150 // Process a def-use edge. This may replace the use, so don't hold a 1151 // use_iterator across it. 1152 Instruction *WideUse = WidenIVUse(DU); 1153 1154 // Follow all def-use edges from the previous narrow use. 1155 if (WideUse) 1156 pushNarrowIVUsers(DU.NarrowUse, WideUse); 1157 1158 // WidenIVUse may have removed the def-use edge. 1159 if (DU.NarrowDef->use_empty()) 1160 DeadInsts.push_back(DU.NarrowDef); 1161 } 1162 return WidePhi; 1163 } 1164 1165 //===----------------------------------------------------------------------===// 1166 // Simplification of IV users based on SCEV evaluation. 1167 //===----------------------------------------------------------------------===// 1168 1169 1170 /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV 1171 /// users. Each successive simplification may push more users which may 1172 /// themselves be candidates for simplification. 1173 /// 1174 /// Sign/Zero extend elimination is interleaved with IV simplification. 1175 /// 1176 void IndVarSimplify::SimplifyAndExtend(Loop *L, 1177 SCEVExpander &Rewriter, 1178 LPPassManager &LPM) { 1179 std::map<PHINode *, WideIVInfo> WideIVMap; 1180 1181 SmallVector<PHINode*, 8> LoopPhis; 1182 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1183 LoopPhis.push_back(cast<PHINode>(I)); 1184 } 1185 // Each round of simplification iterates through the SimplifyIVUsers worklist 1186 // for all current phis, then determines whether any IVs can be 1187 // widened. Widening adds new phis to LoopPhis, inducing another round of 1188 // simplification on the wide IVs. 1189 while (!LoopPhis.empty()) { 1190 // Evaluate as many IV expressions as possible before widening any IVs. This 1191 // forces SCEV to set no-wrap flags before evaluating sign/zero 1192 // extension. The first time SCEV attempts to normalize sign/zero extension, 1193 // the result becomes final. So for the most predictable results, we delay 1194 // evaluation of sign/zero extend evaluation until needed, and avoid running 1195 // other SCEV based analysis prior to SimplifyAndExtend. 1196 do { 1197 PHINode *CurrIV = LoopPhis.pop_back_val(); 1198 1199 // Information about sign/zero extensions of CurrIV. 1200 WideIVVisitor WIV(SE, TD); 1201 1202 Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &WIV); 1203 1204 if (WIV.WI.WidestNativeType) { 1205 WideIVMap[CurrIV] = WIV.WI; 1206 } 1207 } while(!LoopPhis.empty()); 1208 1209 for (std::map<PHINode *, WideIVInfo>::const_iterator I = WideIVMap.begin(), 1210 E = WideIVMap.end(); I != E; ++I) { 1211 WidenIV Widener(I->first, I->second, LI, SE, DT, DeadInsts); 1212 if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) { 1213 Changed = true; 1214 LoopPhis.push_back(WidePhi); 1215 } 1216 } 1217 WideIVMap.clear(); 1218 } 1219 } 1220 1221 /// SimplifyCongruentIVs - Check for congruent phis in this loop header and 1222 /// replace them with their chosen representative. 1223 /// 1224 void IndVarSimplify::SimplifyCongruentIVs(Loop *L) { 1225 DenseMap<const SCEV *, PHINode *> ExprToIVMap; 1226 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1227 PHINode *Phi = cast<PHINode>(I); 1228 if (!SE->isSCEVable(Phi->getType())) 1229 continue; 1230 1231 const SCEV *S = SE->getSCEV(Phi); 1232 std::pair<DenseMap<const SCEV *, PHINode *>::const_iterator, bool> Tmp = 1233 ExprToIVMap.insert(std::make_pair(S, Phi)); 1234 if (Tmp.second) 1235 continue; 1236 PHINode *OrigPhi = Tmp.first->second; 1237 1238 // If one phi derives from the other via GEPs, types may differ. 1239 if (OrigPhi->getType() != Phi->getType()) 1240 continue; 1241 1242 // Replacing the congruent phi is sufficient because acyclic redundancy 1243 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves 1244 // that a phi is congruent, it's almost certain to be the head of an IV 1245 // user cycle that is isomorphic with the original phi. So it's worth 1246 // eagerly cleaning up the common case of a single IV increment. 1247 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 1248 Instruction *OrigInc = 1249 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock)); 1250 Instruction *IsomorphicInc = 1251 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock)); 1252 if (OrigInc != IsomorphicInc && 1253 OrigInc->getType() == IsomorphicInc->getType() && 1254 SE->getSCEV(OrigInc) == SE->getSCEV(IsomorphicInc) && 1255 HoistStep(OrigInc, IsomorphicInc, DT)) { 1256 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv.inc: " 1257 << *IsomorphicInc << '\n'); 1258 IsomorphicInc->replaceAllUsesWith(OrigInc); 1259 DeadInsts.push_back(IsomorphicInc); 1260 } 1261 } 1262 DEBUG(dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi << '\n'); 1263 ++NumElimIV; 1264 Phi->replaceAllUsesWith(OrigPhi); 1265 DeadInsts.push_back(Phi); 1266 } 1267 } 1268 1269 //===----------------------------------------------------------------------===// 1270 // LinearFunctionTestReplace and its kin. Rewrite the loop exit condition. 1271 //===----------------------------------------------------------------------===// 1272 1273 // Check for expressions that ScalarEvolution generates to compute 1274 // BackedgeTakenInfo. If these expressions have not been reduced, then expanding 1275 // them may incur additional cost (albeit in the loop preheader). 1276 static bool isHighCostExpansion(const SCEV *S, BranchInst *BI, 1277 ScalarEvolution *SE) { 1278 // If the backedge-taken count is a UDiv, it's very likely a UDiv that 1279 // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a 1280 // precise expression, rather than a UDiv from the user's code. If we can't 1281 // find a UDiv in the code with some simple searching, assume the former and 1282 // forego rewriting the loop. 1283 if (isa<SCEVUDivExpr>(S)) { 1284 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition()); 1285 if (!OrigCond) return true; 1286 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1)); 1287 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1)); 1288 if (R != S) { 1289 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0)); 1290 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1)); 1291 if (L != S) 1292 return true; 1293 } 1294 } 1295 1296 if (!DisableIVRewrite || ForceLFTR) 1297 return false; 1298 1299 // Recurse past add expressions, which commonly occur in the 1300 // BackedgeTakenCount. They may already exist in program code, and if not, 1301 // they are not too expensive rematerialize. 1302 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 1303 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end(); 1304 I != E; ++I) { 1305 if (isHighCostExpansion(*I, BI, SE)) 1306 return true; 1307 } 1308 return false; 1309 } 1310 1311 // HowManyLessThans uses a Max expression whenever the loop is not guarded by 1312 // the exit condition. 1313 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S)) 1314 return true; 1315 1316 // If we haven't recognized an expensive SCEV patter, assume its an expression 1317 // produced by program code. 1318 return false; 1319 } 1320 1321 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken 1322 /// count expression can be safely and cheaply expanded into an instruction 1323 /// sequence that can be used by LinearFunctionTestReplace. 1324 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) { 1325 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 1326 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) || 1327 BackedgeTakenCount->isZero()) 1328 return false; 1329 1330 if (!L->getExitingBlock()) 1331 return false; 1332 1333 // Can't rewrite non-branch yet. 1334 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1335 if (!BI) 1336 return false; 1337 1338 if (isHighCostExpansion(BackedgeTakenCount, BI, SE)) 1339 return false; 1340 1341 return true; 1342 } 1343 1344 /// getBackedgeIVType - Get the widest type used by the loop test after peeking 1345 /// through Truncs. 1346 /// 1347 /// TODO: Unnecessary when ForceLFTR is removed. 1348 static Type *getBackedgeIVType(Loop *L) { 1349 if (!L->getExitingBlock()) 1350 return 0; 1351 1352 // Can't rewrite non-branch yet. 1353 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1354 if (!BI) 1355 return 0; 1356 1357 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 1358 if (!Cond) 1359 return 0; 1360 1361 Type *Ty = 0; 1362 for(User::op_iterator OI = Cond->op_begin(), OE = Cond->op_end(); 1363 OI != OE; ++OI) { 1364 assert((!Ty || Ty == (*OI)->getType()) && "bad icmp operand types"); 1365 TruncInst *Trunc = dyn_cast<TruncInst>(*OI); 1366 if (!Trunc) 1367 continue; 1368 1369 return Trunc->getSrcTy(); 1370 } 1371 return Ty; 1372 } 1373 1374 /// isLoopInvariant - Perform a quick domtree based check for loop invariance 1375 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems 1376 /// gratuitous for this purpose. 1377 static bool isLoopInvariant(Value *V, Loop *L, DominatorTree *DT) { 1378 Instruction *Inst = dyn_cast<Instruction>(V); 1379 if (!Inst) 1380 return true; 1381 1382 return DT->properlyDominates(Inst->getParent(), L->getHeader()); 1383 } 1384 1385 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop 1386 /// invariant value to the phi. 1387 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) { 1388 Instruction *IncI = dyn_cast<Instruction>(IncV); 1389 if (!IncI) 1390 return 0; 1391 1392 switch (IncI->getOpcode()) { 1393 case Instruction::Add: 1394 case Instruction::Sub: 1395 break; 1396 case Instruction::GetElementPtr: 1397 // An IV counter must preserve its type. 1398 if (IncI->getNumOperands() == 2) 1399 break; 1400 default: 1401 return 0; 1402 } 1403 1404 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0)); 1405 if (Phi && Phi->getParent() == L->getHeader()) { 1406 if (isLoopInvariant(IncI->getOperand(1), L, DT)) 1407 return Phi; 1408 return 0; 1409 } 1410 if (IncI->getOpcode() == Instruction::GetElementPtr) 1411 return 0; 1412 1413 // Allow add/sub to be commuted. 1414 Phi = dyn_cast<PHINode>(IncI->getOperand(1)); 1415 if (Phi && Phi->getParent() == L->getHeader()) { 1416 if (isLoopInvariant(IncI->getOperand(0), L, DT)) 1417 return Phi; 1418 } 1419 return 0; 1420 } 1421 1422 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show 1423 /// that the current exit test is already sufficiently canonical. 1424 static bool needsLFTR(Loop *L, DominatorTree *DT) { 1425 assert(L->getExitingBlock() && "expected loop exit"); 1426 1427 BasicBlock *LatchBlock = L->getLoopLatch(); 1428 // Don't bother with LFTR if the loop is not properly simplified. 1429 if (!LatchBlock) 1430 return false; 1431 1432 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1433 assert(BI && "expected exit branch"); 1434 1435 // Do LFTR to simplify the exit condition to an ICMP. 1436 ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition()); 1437 if (!Cond) 1438 return true; 1439 1440 // Do LFTR to simplify the exit ICMP to EQ/NE 1441 ICmpInst::Predicate Pred = Cond->getPredicate(); 1442 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ) 1443 return true; 1444 1445 // Look for a loop invariant RHS 1446 Value *LHS = Cond->getOperand(0); 1447 Value *RHS = Cond->getOperand(1); 1448 if (!isLoopInvariant(RHS, L, DT)) { 1449 if (!isLoopInvariant(LHS, L, DT)) 1450 return true; 1451 std::swap(LHS, RHS); 1452 } 1453 // Look for a simple IV counter LHS 1454 PHINode *Phi = dyn_cast<PHINode>(LHS); 1455 if (!Phi) 1456 Phi = getLoopPhiForCounter(LHS, L, DT); 1457 1458 if (!Phi) 1459 return true; 1460 1461 // Do LFTR if the exit condition's IV is *not* a simple counter. 1462 Value *IncV = Phi->getIncomingValueForBlock(L->getLoopLatch()); 1463 return Phi != getLoopPhiForCounter(IncV, L, DT); 1464 } 1465 1466 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to 1467 /// be rewritten) loop exit test. 1468 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) { 1469 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 1470 Value *IncV = Phi->getIncomingValue(LatchIdx); 1471 1472 for (Value::use_iterator UI = Phi->use_begin(), UE = Phi->use_end(); 1473 UI != UE; ++UI) { 1474 if (*UI != Cond && *UI != IncV) return false; 1475 } 1476 1477 for (Value::use_iterator UI = IncV->use_begin(), UE = IncV->use_end(); 1478 UI != UE; ++UI) { 1479 if (*UI != Cond && *UI != Phi) return false; 1480 } 1481 return true; 1482 } 1483 1484 /// FindLoopCounter - Find an affine IV in canonical form. 1485 /// 1486 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount 1487 /// 1488 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride. 1489 /// This is difficult in general for SCEV because of potential overflow. But we 1490 /// could at least handle constant BECounts. 1491 static PHINode * 1492 FindLoopCounter(Loop *L, const SCEV *BECount, 1493 ScalarEvolution *SE, DominatorTree *DT, const TargetData *TD) { 1494 // I'm not sure how BECount could be a pointer type, but we definitely don't 1495 // want to LFTR that. 1496 if (BECount->getType()->isPointerTy()) 1497 return 0; 1498 1499 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType()); 1500 1501 Value *Cond = 1502 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition(); 1503 1504 // Loop over all of the PHI nodes, looking for a simple counter. 1505 PHINode *BestPhi = 0; 1506 const SCEV *BestInit = 0; 1507 BasicBlock *LatchBlock = L->getLoopLatch(); 1508 assert(LatchBlock && "needsLFTR should guarantee a loop latch"); 1509 1510 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 1511 PHINode *Phi = cast<PHINode>(I); 1512 if (!SE->isSCEVable(Phi->getType())) 1513 continue; 1514 1515 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi)); 1516 if (!AR || AR->getLoop() != L || !AR->isAffine()) 1517 continue; 1518 1519 // AR may be a pointer type, while BECount is an integer type. 1520 // AR may be wider than BECount. With eq/ne tests overflow is immaterial. 1521 // AR may not be a narrower type, or we may never exit. 1522 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType()); 1523 if (PhiWidth < BCWidth || (TD && !TD->isLegalInteger(PhiWidth))) 1524 continue; 1525 1526 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)); 1527 if (!Step || !Step->isOne()) 1528 continue; 1529 1530 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock); 1531 Value *IncV = Phi->getIncomingValue(LatchIdx); 1532 if (getLoopPhiForCounter(IncV, L, DT) != Phi) 1533 continue; 1534 1535 const SCEV *Init = AR->getStart(); 1536 1537 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) { 1538 // Don't force a live loop counter if another IV can be used. 1539 if (AlmostDeadIV(Phi, LatchBlock, Cond)) 1540 continue; 1541 1542 // Prefer to count-from-zero. This is a more "canonical" counter form. It 1543 // also prefers integer to pointer IVs. 1544 if (BestInit->isZero() != Init->isZero()) { 1545 if (BestInit->isZero()) 1546 continue; 1547 } 1548 // If two IVs both count from zero or both count from nonzero then the 1549 // narrower is likely a dead phi that has been widened. Use the wider phi 1550 // to allow the other to be eliminated. 1551 if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType())) 1552 continue; 1553 } 1554 BestPhi = Phi; 1555 BestInit = Init; 1556 } 1557 return BestPhi; 1558 } 1559 1560 /// LinearFunctionTestReplace - This method rewrites the exit condition of the 1561 /// loop to be a canonical != comparison against the incremented loop induction 1562 /// variable. This pass is able to rewrite the exit tests of any loop where the 1563 /// SCEV analysis can determine a loop-invariant trip count of the loop, which 1564 /// is actually a much broader range than just linear tests. 1565 Value *IndVarSimplify:: 1566 LinearFunctionTestReplace(Loop *L, 1567 const SCEV *BackedgeTakenCount, 1568 PHINode *IndVar, 1569 SCEVExpander &Rewriter) { 1570 assert(canExpandBackedgeTakenCount(L, SE) && "precondition"); 1571 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator()); 1572 1573 // In DisableIVRewrite mode, IndVar is not necessarily a canonical IV. In this 1574 // mode, LFTR can ignore IV overflow and truncate to the width of 1575 // BECount. This avoids materializing the add(zext(add)) expression. 1576 Type *CntTy = DisableIVRewrite ? 1577 BackedgeTakenCount->getType() : IndVar->getType(); 1578 1579 const SCEV *IVLimit = BackedgeTakenCount; 1580 1581 // If the exiting block is not the same as the backedge block, we must compare 1582 // against the preincremented value, otherwise we prefer to compare against 1583 // the post-incremented value. 1584 Value *CmpIndVar; 1585 if (L->getExitingBlock() == L->getLoopLatch()) { 1586 // Add one to the "backedge-taken" count to get the trip count. 1587 // If this addition may overflow, we have to be more pessimistic and 1588 // cast the induction variable before doing the add. 1589 const SCEV *N = 1590 SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1)); 1591 if (CntTy == IVLimit->getType()) 1592 IVLimit = N; 1593 else { 1594 const SCEV *Zero = SE->getConstant(IVLimit->getType(), 0); 1595 if ((isa<SCEVConstant>(N) && !N->isZero()) || 1596 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) { 1597 // No overflow. Cast the sum. 1598 IVLimit = SE->getTruncateOrZeroExtend(N, CntTy); 1599 } else { 1600 // Potential overflow. Cast before doing the add. 1601 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy); 1602 IVLimit = SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1)); 1603 } 1604 } 1605 // The BackedgeTaken expression contains the number of times that the 1606 // backedge branches to the loop header. This is one less than the 1607 // number of times the loop executes, so use the incremented indvar. 1608 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock()); 1609 } else { 1610 // We have to use the preincremented value... 1611 IVLimit = SE->getTruncateOrZeroExtend(IVLimit, CntTy); 1612 CmpIndVar = IndVar; 1613 } 1614 1615 // For unit stride, IVLimit = Start + BECount with 2's complement overflow. 1616 // So for, non-zero start compute the IVLimit here. 1617 bool isPtrIV = false; 1618 Type *CmpTy = CntTy; 1619 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar)); 1620 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter"); 1621 if (!AR->getStart()->isZero()) { 1622 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride"); 1623 const SCEV *IVInit = AR->getStart(); 1624 1625 // For pointer types, sign extend BECount in order to materialize a GEP. 1626 // Note that for DisableIVRewrite, we never run SCEVExpander on a 1627 // pointer type, because we must preserve the existing GEPs. Instead we 1628 // directly generate a GEP later. 1629 if (IVInit->getType()->isPointerTy()) { 1630 isPtrIV = true; 1631 CmpTy = SE->getEffectiveSCEVType(IVInit->getType()); 1632 IVLimit = SE->getTruncateOrSignExtend(IVLimit, CmpTy); 1633 } 1634 // For integer types, truncate the IV before computing IVInit + BECount. 1635 else { 1636 if (SE->getTypeSizeInBits(IVInit->getType()) 1637 > SE->getTypeSizeInBits(CmpTy)) 1638 IVInit = SE->getTruncateExpr(IVInit, CmpTy); 1639 1640 IVLimit = SE->getAddExpr(IVInit, IVLimit); 1641 } 1642 } 1643 // Expand the code for the iteration count. 1644 IRBuilder<> Builder(BI); 1645 1646 assert(SE->isLoopInvariant(IVLimit, L) && 1647 "Computed iteration count is not loop invariant!"); 1648 Value *ExitCnt = Rewriter.expandCodeFor(IVLimit, CmpTy, BI); 1649 1650 // Create a gep for IVInit + IVLimit from on an existing pointer base. 1651 assert(isPtrIV == IndVar->getType()->isPointerTy() && 1652 "IndVar type must match IVInit type"); 1653 if (isPtrIV) { 1654 Value *IVStart = IndVar->getIncomingValueForBlock(L->getLoopPreheader()); 1655 assert(AR->getStart() == SE->getSCEV(IVStart) && "bad loop counter"); 1656 assert(SE->getSizeOfExpr( 1657 cast<PointerType>(IVStart->getType())->getElementType())->isOne() 1658 && "unit stride pointer IV must be i8*"); 1659 1660 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 1661 ExitCnt = Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit"); 1662 Builder.SetInsertPoint(BI); 1663 } 1664 1665 // Insert a new icmp_ne or icmp_eq instruction before the branch. 1666 ICmpInst::Predicate P; 1667 if (L->contains(BI->getSuccessor(0))) 1668 P = ICmpInst::ICMP_NE; 1669 else 1670 P = ICmpInst::ICMP_EQ; 1671 1672 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n" 1673 << " LHS:" << *CmpIndVar << '\n' 1674 << " op:\t" 1675 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n" 1676 << " RHS:\t" << *ExitCnt << "\n" 1677 << " Expr:\t" << *IVLimit << "\n"); 1678 1679 if (SE->getTypeSizeInBits(CmpIndVar->getType()) 1680 > SE->getTypeSizeInBits(CmpTy)) { 1681 CmpIndVar = Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv"); 1682 } 1683 1684 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond"); 1685 Value *OrigCond = BI->getCondition(); 1686 // It's tempting to use replaceAllUsesWith here to fully replace the old 1687 // comparison, but that's not immediately safe, since users of the old 1688 // comparison may not be dominated by the new comparison. Instead, just 1689 // update the branch to use the new comparison; in the common case this 1690 // will make old comparison dead. 1691 BI->setCondition(Cond); 1692 DeadInsts.push_back(OrigCond); 1693 1694 ++NumLFTR; 1695 Changed = true; 1696 return Cond; 1697 } 1698 1699 //===----------------------------------------------------------------------===// 1700 // SinkUnusedInvariants. A late subpass to cleanup loop preheaders. 1701 //===----------------------------------------------------------------------===// 1702 1703 /// If there's a single exit block, sink any loop-invariant values that 1704 /// were defined in the preheader but not used inside the loop into the 1705 /// exit block to reduce register pressure in the loop. 1706 void IndVarSimplify::SinkUnusedInvariants(Loop *L) { 1707 BasicBlock *ExitBlock = L->getExitBlock(); 1708 if (!ExitBlock) return; 1709 1710 BasicBlock *Preheader = L->getLoopPreheader(); 1711 if (!Preheader) return; 1712 1713 Instruction *InsertPt = ExitBlock->getFirstInsertionPt(); 1714 BasicBlock::iterator I = Preheader->getTerminator(); 1715 while (I != Preheader->begin()) { 1716 --I; 1717 // New instructions were inserted at the end of the preheader. 1718 if (isa<PHINode>(I)) 1719 break; 1720 1721 // Don't move instructions which might have side effects, since the side 1722 // effects need to complete before instructions inside the loop. Also don't 1723 // move instructions which might read memory, since the loop may modify 1724 // memory. Note that it's okay if the instruction might have undefined 1725 // behavior: LoopSimplify guarantees that the preheader dominates the exit 1726 // block. 1727 if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 1728 continue; 1729 1730 // Skip debug info intrinsics. 1731 if (isa<DbgInfoIntrinsic>(I)) 1732 continue; 1733 1734 // Skip landingpad instructions. 1735 if (isa<LandingPadInst>(I)) 1736 continue; 1737 1738 // Don't sink static AllocaInsts out of the entry block, which would 1739 // turn them into dynamic allocas! 1740 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 1741 if (AI->isStaticAlloca()) 1742 continue; 1743 1744 // Determine if there is a use in or before the loop (direct or 1745 // otherwise). 1746 bool UsedInLoop = false; 1747 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 1748 UI != UE; ++UI) { 1749 User *U = *UI; 1750 BasicBlock *UseBB = cast<Instruction>(U)->getParent(); 1751 if (PHINode *P = dyn_cast<PHINode>(U)) { 1752 unsigned i = 1753 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()); 1754 UseBB = P->getIncomingBlock(i); 1755 } 1756 if (UseBB == Preheader || L->contains(UseBB)) { 1757 UsedInLoop = true; 1758 break; 1759 } 1760 } 1761 1762 // If there is, the def must remain in the preheader. 1763 if (UsedInLoop) 1764 continue; 1765 1766 // Otherwise, sink it to the exit block. 1767 Instruction *ToMove = I; 1768 bool Done = false; 1769 1770 if (I != Preheader->begin()) { 1771 // Skip debug info intrinsics. 1772 do { 1773 --I; 1774 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin()); 1775 1776 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin()) 1777 Done = true; 1778 } else { 1779 Done = true; 1780 } 1781 1782 ToMove->moveBefore(InsertPt); 1783 if (Done) break; 1784 InsertPt = ToMove; 1785 } 1786 } 1787 1788 //===----------------------------------------------------------------------===// 1789 // IndVarSimplify driver. Manage several subpasses of IV simplification. 1790 //===----------------------------------------------------------------------===// 1791 1792 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) { 1793 // If LoopSimplify form is not available, stay out of trouble. Some notes: 1794 // - LSR currently only supports LoopSimplify-form loops. Indvars' 1795 // canonicalization can be a pessimization without LSR to "clean up" 1796 // afterwards. 1797 // - We depend on having a preheader; in particular, 1798 // Loop::getCanonicalInductionVariable only supports loops with preheaders, 1799 // and we're in trouble if we can't find the induction variable even when 1800 // we've manually inserted one. 1801 if (!L->isLoopSimplifyForm()) 1802 return false; 1803 1804 if (!DisableIVRewrite) 1805 IU = &getAnalysis<IVUsers>(); 1806 LI = &getAnalysis<LoopInfo>(); 1807 SE = &getAnalysis<ScalarEvolution>(); 1808 DT = &getAnalysis<DominatorTree>(); 1809 TD = getAnalysisIfAvailable<TargetData>(); 1810 1811 DeadInsts.clear(); 1812 Changed = false; 1813 1814 // If there are any floating-point recurrences, attempt to 1815 // transform them to use integer recurrences. 1816 RewriteNonIntegerIVs(L); 1817 1818 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 1819 1820 // Create a rewriter object which we'll use to transform the code with. 1821 SCEVExpander Rewriter(*SE, "indvars"); 1822 1823 // Eliminate redundant IV users. 1824 // 1825 // Simplification works best when run before other consumers of SCEV. We 1826 // attempt to avoid evaluating SCEVs for sign/zero extend operations until 1827 // other expressions involving loop IVs have been evaluated. This helps SCEV 1828 // set no-wrap flags before normalizing sign/zero extension. 1829 if (DisableIVRewrite) { 1830 Rewriter.disableCanonicalMode(); 1831 SimplifyAndExtend(L, Rewriter, LPM); 1832 } 1833 1834 // Check to see if this loop has a computable loop-invariant execution count. 1835 // If so, this means that we can compute the final value of any expressions 1836 // that are recurrent in the loop, and substitute the exit values from the 1837 // loop into any instructions outside of the loop that use the final values of 1838 // the current expressions. 1839 // 1840 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 1841 RewriteLoopExitValues(L, Rewriter); 1842 1843 // Eliminate redundant IV users. 1844 if (!DisableIVRewrite) 1845 Changed |= simplifyIVUsers(IU, SE, &LPM, DeadInsts); 1846 1847 // Eliminate redundant IV cycles. 1848 if (DisableIVRewrite) 1849 SimplifyCongruentIVs(L); 1850 1851 // Compute the type of the largest recurrence expression, and decide whether 1852 // a canonical induction variable should be inserted. 1853 Type *LargestType = 0; 1854 bool NeedCannIV = false; 1855 bool ReuseIVForExit = DisableIVRewrite && !ForceLFTR; 1856 bool ExpandBECount = canExpandBackedgeTakenCount(L, SE); 1857 if (ExpandBECount && !ReuseIVForExit) { 1858 // If we have a known trip count and a single exit block, we'll be 1859 // rewriting the loop exit test condition below, which requires a 1860 // canonical induction variable. 1861 NeedCannIV = true; 1862 Type *Ty = BackedgeTakenCount->getType(); 1863 if (DisableIVRewrite) { 1864 // In this mode, SimplifyIVUsers may have already widened the IV used by 1865 // the backedge test and inserted a Trunc on the compare's operand. Get 1866 // the wider type to avoid creating a redundant narrow IV only used by the 1867 // loop test. 1868 LargestType = getBackedgeIVType(L); 1869 } 1870 if (!LargestType || 1871 SE->getTypeSizeInBits(Ty) > 1872 SE->getTypeSizeInBits(LargestType)) 1873 LargestType = SE->getEffectiveSCEVType(Ty); 1874 } 1875 if (!DisableIVRewrite) { 1876 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) { 1877 NeedCannIV = true; 1878 Type *Ty = 1879 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType()); 1880 if (!LargestType || 1881 SE->getTypeSizeInBits(Ty) > 1882 SE->getTypeSizeInBits(LargestType)) 1883 LargestType = Ty; 1884 } 1885 } 1886 1887 // Now that we know the largest of the induction variable expressions 1888 // in this loop, insert a canonical induction variable of the largest size. 1889 PHINode *IndVar = 0; 1890 if (NeedCannIV) { 1891 // Check to see if the loop already has any canonical-looking induction 1892 // variables. If any are present and wider than the planned canonical 1893 // induction variable, temporarily remove them, so that the Rewriter 1894 // doesn't attempt to reuse them. 1895 SmallVector<PHINode *, 2> OldCannIVs; 1896 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) { 1897 if (SE->getTypeSizeInBits(OldCannIV->getType()) > 1898 SE->getTypeSizeInBits(LargestType)) 1899 OldCannIV->removeFromParent(); 1900 else 1901 break; 1902 OldCannIVs.push_back(OldCannIV); 1903 } 1904 1905 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType); 1906 1907 ++NumInserted; 1908 Changed = true; 1909 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n'); 1910 1911 // Now that the official induction variable is established, reinsert 1912 // any old canonical-looking variables after it so that the IR remains 1913 // consistent. They will be deleted as part of the dead-PHI deletion at 1914 // the end of the pass. 1915 while (!OldCannIVs.empty()) { 1916 PHINode *OldCannIV = OldCannIVs.pop_back_val(); 1917 OldCannIV->insertBefore(L->getHeader()->getFirstInsertionPt()); 1918 } 1919 } 1920 else if (ExpandBECount && ReuseIVForExit && needsLFTR(L, DT)) { 1921 IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD); 1922 } 1923 // If we have a trip count expression, rewrite the loop's exit condition 1924 // using it. We can currently only handle loops with a single exit. 1925 Value *NewICmp = 0; 1926 if (ExpandBECount && IndVar) { 1927 // Check preconditions for proper SCEVExpander operation. SCEV does not 1928 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any 1929 // pass that uses the SCEVExpander must do it. This does not work well for 1930 // loop passes because SCEVExpander makes assumptions about all loops, while 1931 // LoopPassManager only forces the current loop to be simplified. 1932 // 1933 // FIXME: SCEV expansion has no way to bail out, so the caller must 1934 // explicitly check any assumptions made by SCEV. Brittle. 1935 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount); 1936 if (!AR || AR->getLoop()->getLoopPreheader()) 1937 NewICmp = 1938 LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter); 1939 } 1940 // Rewrite IV-derived expressions. 1941 if (!DisableIVRewrite) 1942 RewriteIVExpressions(L, Rewriter); 1943 1944 // Clear the rewriter cache, because values that are in the rewriter's cache 1945 // can be deleted in the loop below, causing the AssertingVH in the cache to 1946 // trigger. 1947 Rewriter.clear(); 1948 1949 // Now that we're done iterating through lists, clean up any instructions 1950 // which are now dead. 1951 while (!DeadInsts.empty()) 1952 if (Instruction *Inst = 1953 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) 1954 RecursivelyDeleteTriviallyDeadInstructions(Inst); 1955 1956 // The Rewriter may not be used from this point on. 1957 1958 // Loop-invariant instructions in the preheader that aren't used in the 1959 // loop may be sunk below the loop to reduce register pressure. 1960 SinkUnusedInvariants(L); 1961 1962 // For completeness, inform IVUsers of the IV use in the newly-created 1963 // loop exit test instruction. 1964 if (IU && NewICmp) { 1965 ICmpInst *NewICmpInst = dyn_cast<ICmpInst>(NewICmp); 1966 if (NewICmpInst) 1967 IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(0))); 1968 } 1969 // Clean up dead instructions. 1970 Changed |= DeleteDeadPHIs(L->getHeader()); 1971 // Check a post-condition. 1972 assert(L->isLCSSAForm(*DT) && 1973 "Indvars did not leave the loop in lcssa form!"); 1974 1975 // Verify that LFTR, and any other change have not interfered with SCEV's 1976 // ability to compute trip count. 1977 #ifndef NDEBUG 1978 if (DisableIVRewrite && VerifyIndvars && 1979 !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 1980 SE->forgetLoop(L); 1981 const SCEV *NewBECount = SE->getBackedgeTakenCount(L); 1982 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) < 1983 SE->getTypeSizeInBits(NewBECount->getType())) 1984 NewBECount = SE->getTruncateOrNoop(NewBECount, 1985 BackedgeTakenCount->getType()); 1986 else 1987 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, 1988 NewBECount->getType()); 1989 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV"); 1990 } 1991 #endif 1992 1993 return Changed; 1994 } 1995