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 // This transformation makes the following changes to each loop with an 15 // 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/ADT/SmallVector.h" 61 #include "llvm/ADT/Statistic.h" 62 #include "llvm/ADT/STLExtras.h" 63 using namespace llvm; 64 65 STATISTIC(NumRemoved , "Number of aux indvars removed"); 66 STATISTIC(NumInserted, "Number of canonical indvars added"); 67 STATISTIC(NumReplaced, "Number of exit values replaced"); 68 STATISTIC(NumLFTR , "Number of loop exit tests replaced"); 69 70 namespace { 71 class IndVarSimplify : public LoopPass { 72 IVUsers *IU; 73 LoopInfo *LI; 74 ScalarEvolution *SE; 75 DominatorTree *DT; 76 bool Changed; 77 public: 78 79 static char ID; // Pass identification, replacement for typeid 80 IndVarSimplify() : LoopPass(ID) {} 81 82 virtual bool runOnLoop(Loop *L, LPPassManager &LPM); 83 84 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 85 AU.addRequired<DominatorTree>(); 86 AU.addRequired<LoopInfo>(); 87 AU.addRequired<ScalarEvolution>(); 88 AU.addRequiredID(LoopSimplifyID); 89 AU.addRequiredID(LCSSAID); 90 AU.addRequired<IVUsers>(); 91 AU.addPreserved<ScalarEvolution>(); 92 AU.addPreservedID(LoopSimplifyID); 93 AU.addPreservedID(LCSSAID); 94 AU.addPreserved<IVUsers>(); 95 AU.setPreservesCFG(); 96 } 97 98 private: 99 100 void EliminateIVComparisons(); 101 void EliminateIVRemainders(); 102 void RewriteNonIntegerIVs(Loop *L); 103 104 ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount, 105 PHINode *IndVar, 106 BasicBlock *ExitingBlock, 107 BranchInst *BI, 108 SCEVExpander &Rewriter); 109 void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter); 110 111 void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter); 112 113 void SinkUnusedInvariants(Loop *L); 114 115 void HandleFloatingPointIV(Loop *L, PHINode *PH); 116 }; 117 } 118 119 char IndVarSimplify::ID = 0; 120 INITIALIZE_PASS(IndVarSimplify, "indvars", 121 "Canonicalize Induction Variables", false, false) 122 123 Pass *llvm::createIndVarSimplifyPass() { 124 return new IndVarSimplify(); 125 } 126 127 /// LinearFunctionTestReplace - This method rewrites the exit condition of the 128 /// loop to be a canonical != comparison against the incremented loop induction 129 /// variable. This pass is able to rewrite the exit tests of any loop where the 130 /// SCEV analysis can determine a loop-invariant trip count of the loop, which 131 /// is actually a much broader range than just linear tests. 132 ICmpInst *IndVarSimplify::LinearFunctionTestReplace(Loop *L, 133 const SCEV *BackedgeTakenCount, 134 PHINode *IndVar, 135 BasicBlock *ExitingBlock, 136 BranchInst *BI, 137 SCEVExpander &Rewriter) { 138 // Special case: If the backedge-taken count is a UDiv, it's very likely a 139 // UDiv that ScalarEvolution produced in order to compute a precise 140 // expression, rather than a UDiv from the user's code. If we can't find a 141 // UDiv in the code with some simple searching, assume the former and forego 142 // rewriting the loop. 143 if (isa<SCEVUDivExpr>(BackedgeTakenCount)) { 144 ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition()); 145 if (!OrigCond) return 0; 146 const SCEV *R = SE->getSCEV(OrigCond->getOperand(1)); 147 R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1)); 148 if (R != BackedgeTakenCount) { 149 const SCEV *L = SE->getSCEV(OrigCond->getOperand(0)); 150 L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1)); 151 if (L != BackedgeTakenCount) 152 return 0; 153 } 154 } 155 156 // If the exiting block is not the same as the backedge block, we must compare 157 // against the preincremented value, otherwise we prefer to compare against 158 // the post-incremented value. 159 Value *CmpIndVar; 160 const SCEV *RHS = BackedgeTakenCount; 161 if (ExitingBlock == L->getLoopLatch()) { 162 // Add one to the "backedge-taken" count to get the trip count. 163 // If this addition may overflow, we have to be more pessimistic and 164 // cast the induction variable before doing the add. 165 const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0); 166 const SCEV *N = 167 SE->getAddExpr(BackedgeTakenCount, 168 SE->getConstant(BackedgeTakenCount->getType(), 1)); 169 if ((isa<SCEVConstant>(N) && !N->isZero()) || 170 SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) { 171 // No overflow. Cast the sum. 172 RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType()); 173 } else { 174 // Potential overflow. Cast before doing the add. 175 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount, 176 IndVar->getType()); 177 RHS = SE->getAddExpr(RHS, 178 SE->getConstant(IndVar->getType(), 1)); 179 } 180 181 // The BackedgeTaken expression contains the number of times that the 182 // backedge branches to the loop header. This is one less than the 183 // number of times the loop executes, so use the incremented indvar. 184 CmpIndVar = IndVar->getIncomingValueForBlock(ExitingBlock); 185 } else { 186 // We have to use the preincremented value... 187 RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount, 188 IndVar->getType()); 189 CmpIndVar = IndVar; 190 } 191 192 // Expand the code for the iteration count. 193 assert(RHS->isLoopInvariant(L) && 194 "Computed iteration count is not loop invariant!"); 195 Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI); 196 197 // Insert a new icmp_ne or icmp_eq instruction before the branch. 198 ICmpInst::Predicate Opcode; 199 if (L->contains(BI->getSuccessor(0))) 200 Opcode = ICmpInst::ICMP_NE; 201 else 202 Opcode = ICmpInst::ICMP_EQ; 203 204 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n" 205 << " LHS:" << *CmpIndVar << '\n' 206 << " op:\t" 207 << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n" 208 << " RHS:\t" << *RHS << "\n"); 209 210 ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond"); 211 212 Value *OrigCond = BI->getCondition(); 213 // It's tempting to use replaceAllUsesWith here to fully replace the old 214 // comparison, but that's not immediately safe, since users of the old 215 // comparison may not be dominated by the new comparison. Instead, just 216 // update the branch to use the new comparison; in the common case this 217 // will make old comparison dead. 218 BI->setCondition(Cond); 219 RecursivelyDeleteTriviallyDeadInstructions(OrigCond); 220 221 ++NumLFTR; 222 Changed = true; 223 return Cond; 224 } 225 226 /// RewriteLoopExitValues - Check to see if this loop has a computable 227 /// loop-invariant execution count. If so, this means that we can compute the 228 /// final value of any expressions that are recurrent in the loop, and 229 /// substitute the exit values from the loop into any instructions outside of 230 /// the loop that use the final values of the current expressions. 231 /// 232 /// This is mostly redundant with the regular IndVarSimplify activities that 233 /// happen later, except that it's more powerful in some cases, because it's 234 /// able to brute-force evaluate arbitrary instructions as long as they have 235 /// constant operands at the beginning of the loop. 236 void IndVarSimplify::RewriteLoopExitValues(Loop *L, 237 SCEVExpander &Rewriter) { 238 // Verify the input to the pass in already in LCSSA form. 239 assert(L->isLCSSAForm(*DT)); 240 241 SmallVector<BasicBlock*, 8> ExitBlocks; 242 L->getUniqueExitBlocks(ExitBlocks); 243 244 // Find all values that are computed inside the loop, but used outside of it. 245 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 246 // the exit blocks of the loop to find them. 247 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 248 BasicBlock *ExitBB = ExitBlocks[i]; 249 250 // If there are no PHI nodes in this exit block, then no values defined 251 // inside the loop are used on this path, skip it. 252 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 253 if (!PN) continue; 254 255 unsigned NumPreds = PN->getNumIncomingValues(); 256 257 // Iterate over all of the PHI nodes. 258 BasicBlock::iterator BBI = ExitBB->begin(); 259 while ((PN = dyn_cast<PHINode>(BBI++))) { 260 if (PN->use_empty()) 261 continue; // dead use, don't replace it 262 263 // SCEV only supports integer expressions for now. 264 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy()) 265 continue; 266 267 // It's necessary to tell ScalarEvolution about this explicitly so that 268 // it can walk the def-use list and forget all SCEVs, as it may not be 269 // watching the PHI itself. Once the new exit value is in place, there 270 // may not be a def-use connection between the loop and every instruction 271 // which got a SCEVAddRecExpr for that loop. 272 SE->forgetValue(PN); 273 274 // Iterate over all of the values in all the PHI nodes. 275 for (unsigned i = 0; i != NumPreds; ++i) { 276 // If the value being merged in is not integer or is not defined 277 // in the loop, skip it. 278 Value *InVal = PN->getIncomingValue(i); 279 if (!isa<Instruction>(InVal)) 280 continue; 281 282 // If this pred is for a subloop, not L itself, skip it. 283 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 284 continue; // The Block is in a subloop, skip it. 285 286 // Check that InVal is defined in the loop. 287 Instruction *Inst = cast<Instruction>(InVal); 288 if (!L->contains(Inst)) 289 continue; 290 291 // Okay, this instruction has a user outside of the current loop 292 // and varies predictably *inside* the loop. Evaluate the value it 293 // contains when the loop exits, if possible. 294 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 295 if (!ExitValue->isLoopInvariant(L)) 296 continue; 297 298 Changed = true; 299 ++NumReplaced; 300 301 Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst); 302 303 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n' 304 << " LoopVal = " << *Inst << "\n"); 305 306 PN->setIncomingValue(i, ExitVal); 307 308 // If this instruction is dead now, delete it. 309 RecursivelyDeleteTriviallyDeadInstructions(Inst); 310 311 if (NumPreds == 1) { 312 // Completely replace a single-pred PHI. This is safe, because the 313 // NewVal won't be variant in the loop, so we don't need an LCSSA phi 314 // node anymore. 315 PN->replaceAllUsesWith(ExitVal); 316 RecursivelyDeleteTriviallyDeadInstructions(PN); 317 } 318 } 319 if (NumPreds != 1) { 320 // Clone the PHI and delete the original one. This lets IVUsers and 321 // any other maps purge the original user from their records. 322 PHINode *NewPN = cast<PHINode>(PN->clone()); 323 NewPN->takeName(PN); 324 NewPN->insertBefore(PN); 325 PN->replaceAllUsesWith(NewPN); 326 PN->eraseFromParent(); 327 } 328 } 329 } 330 331 // The insertion point instruction may have been deleted; clear it out 332 // so that the rewriter doesn't trip over it later. 333 Rewriter.clearInsertPoint(); 334 } 335 336 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) { 337 // First step. Check to see if there are any floating-point recurrences. 338 // If there are, change them into integer recurrences, permitting analysis by 339 // the SCEV routines. 340 // 341 BasicBlock *Header = L->getHeader(); 342 343 SmallVector<WeakVH, 8> PHIs; 344 for (BasicBlock::iterator I = Header->begin(); 345 PHINode *PN = dyn_cast<PHINode>(I); ++I) 346 PHIs.push_back(PN); 347 348 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 349 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i])) 350 HandleFloatingPointIV(L, PN); 351 352 // If the loop previously had floating-point IV, ScalarEvolution 353 // may not have been able to compute a trip count. Now that we've done some 354 // re-writing, the trip count may be computable. 355 if (Changed) 356 SE->forgetLoop(L); 357 } 358 359 void IndVarSimplify::EliminateIVComparisons() { 360 SmallVector<WeakVH, 16> DeadInsts; 361 362 // Look for ICmp users. 363 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) { 364 IVStrideUse &UI = *I; 365 ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser()); 366 if (!ICmp) continue; 367 368 bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1); 369 ICmpInst::Predicate Pred = ICmp->getPredicate(); 370 if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred); 371 372 // Get the SCEVs for the ICmp operands. 373 const SCEV *S = IU->getReplacementExpr(UI); 374 const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped)); 375 376 // Simplify unnecessary loops away. 377 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 378 S = SE->getSCEVAtScope(S, ICmpLoop); 379 X = SE->getSCEVAtScope(X, ICmpLoop); 380 381 // If the condition is always true or always false, replace it with 382 // a constant value. 383 if (SE->isKnownPredicate(Pred, S, X)) 384 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext())); 385 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) 386 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext())); 387 else 388 continue; 389 390 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); 391 DeadInsts.push_back(ICmp); 392 } 393 394 // Now that we're done iterating through lists, clean up any instructions 395 // which are now dead. 396 while (!DeadInsts.empty()) 397 if (Instruction *Inst = 398 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) 399 RecursivelyDeleteTriviallyDeadInstructions(Inst); 400 } 401 402 void IndVarSimplify::EliminateIVRemainders() { 403 SmallVector<WeakVH, 16> DeadInsts; 404 405 // Look for SRem and URem users. 406 for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) { 407 IVStrideUse &UI = *I; 408 BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser()); 409 if (!Rem) continue; 410 411 bool isSigned = Rem->getOpcode() == Instruction::SRem; 412 if (!isSigned && Rem->getOpcode() != Instruction::URem) 413 continue; 414 415 // We're only interested in the case where we know something about 416 // the numerator. 417 if (UI.getOperandValToReplace() != Rem->getOperand(0)) 418 continue; 419 420 // Get the SCEVs for the ICmp operands. 421 const SCEV *S = SE->getSCEV(Rem->getOperand(0)); 422 const SCEV *X = SE->getSCEV(Rem->getOperand(1)); 423 424 // Simplify unnecessary loops away. 425 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); 426 S = SE->getSCEVAtScope(S, ICmpLoop); 427 X = SE->getSCEVAtScope(X, ICmpLoop); 428 429 // i % n --> i if i is in [0,n). 430 if ((!isSigned || SE->isKnownNonNegative(S)) && 431 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 432 S, X)) 433 Rem->replaceAllUsesWith(Rem->getOperand(0)); 434 else { 435 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). 436 const SCEV *LessOne = 437 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1)); 438 if ((!isSigned || SE->isKnownNonNegative(LessOne)) && 439 SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, 440 LessOne, X)) { 441 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, 442 Rem->getOperand(0), Rem->getOperand(1), 443 "tmp"); 444 SelectInst *Sel = 445 SelectInst::Create(ICmp, 446 ConstantInt::get(Rem->getType(), 0), 447 Rem->getOperand(0), "tmp", Rem); 448 Rem->replaceAllUsesWith(Sel); 449 } else 450 continue; 451 } 452 453 // Inform IVUsers about the new users. 454 if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0))) 455 IU->AddUsersIfInteresting(I); 456 457 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 458 DeadInsts.push_back(Rem); 459 } 460 461 // Now that we're done iterating through lists, clean up any instructions 462 // which are now dead. 463 while (!DeadInsts.empty()) 464 if (Instruction *Inst = 465 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) 466 RecursivelyDeleteTriviallyDeadInstructions(Inst); 467 } 468 469 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) { 470 // If LoopSimplify form is not available, stay out of trouble. Some notes: 471 // - LSR currently only supports LoopSimplify-form loops. Indvars' 472 // canonicalization can be a pessimization without LSR to "clean up" 473 // afterwards. 474 // - We depend on having a preheader; in particular, 475 // Loop::getCanonicalInductionVariable only supports loops with preheaders, 476 // and we're in trouble if we can't find the induction variable even when 477 // we've manually inserted one. 478 if (!L->isLoopSimplifyForm()) 479 return false; 480 481 IU = &getAnalysis<IVUsers>(); 482 LI = &getAnalysis<LoopInfo>(); 483 SE = &getAnalysis<ScalarEvolution>(); 484 DT = &getAnalysis<DominatorTree>(); 485 Changed = false; 486 487 // If there are any floating-point recurrences, attempt to 488 // transform them to use integer recurrences. 489 RewriteNonIntegerIVs(L); 490 491 BasicBlock *ExitingBlock = L->getExitingBlock(); // may be null 492 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 493 494 // Create a rewriter object which we'll use to transform the code with. 495 SCEVExpander Rewriter(*SE); 496 497 // Check to see if this loop has a computable loop-invariant execution count. 498 // If so, this means that we can compute the final value of any expressions 499 // that are recurrent in the loop, and substitute the exit values from the 500 // loop into any instructions outside of the loop that use the final values of 501 // the current expressions. 502 // 503 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 504 RewriteLoopExitValues(L, Rewriter); 505 506 // Simplify ICmp IV users. 507 EliminateIVComparisons(); 508 509 // Simplify SRem and URem IV users. 510 EliminateIVRemainders(); 511 512 // Compute the type of the largest recurrence expression, and decide whether 513 // a canonical induction variable should be inserted. 514 const Type *LargestType = 0; 515 bool NeedCannIV = false; 516 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 517 LargestType = BackedgeTakenCount->getType(); 518 LargestType = SE->getEffectiveSCEVType(LargestType); 519 // If we have a known trip count and a single exit block, we'll be 520 // rewriting the loop exit test condition below, which requires a 521 // canonical induction variable. 522 if (ExitingBlock) 523 NeedCannIV = true; 524 } 525 for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) { 526 const Type *Ty = 527 SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType()); 528 if (!LargestType || 529 SE->getTypeSizeInBits(Ty) > 530 SE->getTypeSizeInBits(LargestType)) 531 LargestType = Ty; 532 NeedCannIV = true; 533 } 534 535 // Now that we know the largest of the induction variable expressions 536 // in this loop, insert a canonical induction variable of the largest size. 537 PHINode *IndVar = 0; 538 if (NeedCannIV) { 539 // Check to see if the loop already has any canonical-looking induction 540 // variables. If any are present and wider than the planned canonical 541 // induction variable, temporarily remove them, so that the Rewriter 542 // doesn't attempt to reuse them. 543 SmallVector<PHINode *, 2> OldCannIVs; 544 while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) { 545 if (SE->getTypeSizeInBits(OldCannIV->getType()) > 546 SE->getTypeSizeInBits(LargestType)) 547 OldCannIV->removeFromParent(); 548 else 549 break; 550 OldCannIVs.push_back(OldCannIV); 551 } 552 553 IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType); 554 555 ++NumInserted; 556 Changed = true; 557 DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n'); 558 559 // Now that the official induction variable is established, reinsert 560 // any old canonical-looking variables after it so that the IR remains 561 // consistent. They will be deleted as part of the dead-PHI deletion at 562 // the end of the pass. 563 while (!OldCannIVs.empty()) { 564 PHINode *OldCannIV = OldCannIVs.pop_back_val(); 565 OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI()); 566 } 567 } 568 569 // If we have a trip count expression, rewrite the loop's exit condition 570 // using it. We can currently only handle loops with a single exit. 571 ICmpInst *NewICmp = 0; 572 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 573 !BackedgeTakenCount->isZero() && 574 ExitingBlock) { 575 assert(NeedCannIV && 576 "LinearFunctionTestReplace requires a canonical induction variable"); 577 // Can't rewrite non-branch yet. 578 if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) 579 NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, 580 ExitingBlock, BI, Rewriter); 581 } 582 583 // Rewrite IV-derived expressions. Clears the rewriter cache. 584 RewriteIVExpressions(L, Rewriter); 585 586 // The Rewriter may not be used from this point on. 587 588 // Loop-invariant instructions in the preheader that aren't used in the 589 // loop may be sunk below the loop to reduce register pressure. 590 SinkUnusedInvariants(L); 591 592 // For completeness, inform IVUsers of the IV use in the newly-created 593 // loop exit test instruction. 594 if (NewICmp) 595 IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0))); 596 597 // Clean up dead instructions. 598 Changed |= DeleteDeadPHIs(L->getHeader()); 599 // Check a post-condition. 600 assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!"); 601 return Changed; 602 } 603 604 // FIXME: It is an extremely bad idea to indvar substitute anything more 605 // complex than affine induction variables. Doing so will put expensive 606 // polynomial evaluations inside of the loop, and the str reduction pass 607 // currently can only reduce affine polynomials. For now just disable 608 // indvar subst on anything more complex than an affine addrec, unless 609 // it can be expanded to a trivial value. 610 static bool isSafe(const SCEV *S, const Loop *L) { 611 // Loop-invariant values are safe. 612 if (S->isLoopInvariant(L)) return true; 613 614 // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how 615 // to transform them into efficient code. 616 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 617 return AR->isAffine(); 618 619 // An add is safe it all its operands are safe. 620 if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) { 621 for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(), 622 E = Commutative->op_end(); I != E; ++I) 623 if (!isSafe(*I, L)) return false; 624 return true; 625 } 626 627 // A cast is safe if its operand is. 628 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) 629 return isSafe(C->getOperand(), L); 630 631 // A udiv is safe if its operands are. 632 if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S)) 633 return isSafe(UD->getLHS(), L) && 634 isSafe(UD->getRHS(), L); 635 636 // SCEVUnknown is always safe. 637 if (isa<SCEVUnknown>(S)) 638 return true; 639 640 // Nothing else is safe. 641 return false; 642 } 643 644 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) { 645 SmallVector<WeakVH, 16> DeadInsts; 646 647 // Rewrite all induction variable expressions in terms of the canonical 648 // induction variable. 649 // 650 // If there were induction variables of other sizes or offsets, manually 651 // add the offsets to the primary induction variable and cast, avoiding 652 // the need for the code evaluation methods to insert induction variables 653 // of different sizes. 654 for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) { 655 Value *Op = UI->getOperandValToReplace(); 656 const Type *UseTy = Op->getType(); 657 Instruction *User = UI->getUser(); 658 659 // Compute the final addrec to expand into code. 660 const SCEV *AR = IU->getReplacementExpr(*UI); 661 662 // Evaluate the expression out of the loop, if possible. 663 if (!L->contains(UI->getUser())) { 664 const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop()); 665 if (ExitVal->isLoopInvariant(L)) 666 AR = ExitVal; 667 } 668 669 // FIXME: It is an extremely bad idea to indvar substitute anything more 670 // complex than affine induction variables. Doing so will put expensive 671 // polynomial evaluations inside of the loop, and the str reduction pass 672 // currently can only reduce affine polynomials. For now just disable 673 // indvar subst on anything more complex than an affine addrec, unless 674 // it can be expanded to a trivial value. 675 if (!isSafe(AR, L)) 676 continue; 677 678 // Determine the insertion point for this user. By default, insert 679 // immediately before the user. The SCEVExpander class will automatically 680 // hoist loop invariants out of the loop. For PHI nodes, there may be 681 // multiple uses, so compute the nearest common dominator for the 682 // incoming blocks. 683 Instruction *InsertPt = User; 684 if (PHINode *PHI = dyn_cast<PHINode>(InsertPt)) 685 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) 686 if (PHI->getIncomingValue(i) == Op) { 687 if (InsertPt == User) 688 InsertPt = PHI->getIncomingBlock(i)->getTerminator(); 689 else 690 InsertPt = 691 DT->findNearestCommonDominator(InsertPt->getParent(), 692 PHI->getIncomingBlock(i)) 693 ->getTerminator(); 694 } 695 696 // Now expand it into actual Instructions and patch it into place. 697 Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt); 698 699 // Inform ScalarEvolution that this value is changing. The change doesn't 700 // affect its value, but it does potentially affect which use lists the 701 // value will be on after the replacement, which affects ScalarEvolution's 702 // ability to walk use lists and drop dangling pointers when a value is 703 // deleted. 704 SE->forgetValue(User); 705 706 // Patch the new value into place. 707 if (Op->hasName()) 708 NewVal->takeName(Op); 709 User->replaceUsesOfWith(Op, NewVal); 710 UI->setOperandValToReplace(NewVal); 711 DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n' 712 << " into = " << *NewVal << "\n"); 713 ++NumRemoved; 714 Changed = true; 715 716 // The old value may be dead now. 717 DeadInsts.push_back(Op); 718 } 719 720 // Clear the rewriter cache, because values that are in the rewriter's cache 721 // can be deleted in the loop below, causing the AssertingVH in the cache to 722 // trigger. 723 Rewriter.clear(); 724 // Now that we're done iterating through lists, clean up any instructions 725 // which are now dead. 726 while (!DeadInsts.empty()) 727 if (Instruction *Inst = 728 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) 729 RecursivelyDeleteTriviallyDeadInstructions(Inst); 730 } 731 732 /// If there's a single exit block, sink any loop-invariant values that 733 /// were defined in the preheader but not used inside the loop into the 734 /// exit block to reduce register pressure in the loop. 735 void IndVarSimplify::SinkUnusedInvariants(Loop *L) { 736 BasicBlock *ExitBlock = L->getExitBlock(); 737 if (!ExitBlock) return; 738 739 BasicBlock *Preheader = L->getLoopPreheader(); 740 if (!Preheader) return; 741 742 Instruction *InsertPt = ExitBlock->getFirstNonPHI(); 743 BasicBlock::iterator I = Preheader->getTerminator(); 744 while (I != Preheader->begin()) { 745 --I; 746 // New instructions were inserted at the end of the preheader. 747 if (isa<PHINode>(I)) 748 break; 749 750 // Don't move instructions which might have side effects, since the side 751 // effects need to complete before instructions inside the loop. Also don't 752 // move instructions which might read memory, since the loop may modify 753 // memory. Note that it's okay if the instruction might have undefined 754 // behavior: LoopSimplify guarantees that the preheader dominates the exit 755 // block. 756 if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 757 continue; 758 759 // Skip debug info intrinsics. 760 if (isa<DbgInfoIntrinsic>(I)) 761 continue; 762 763 // Don't sink static AllocaInsts out of the entry block, which would 764 // turn them into dynamic allocas! 765 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) 766 if (AI->isStaticAlloca()) 767 continue; 768 769 // Determine if there is a use in or before the loop (direct or 770 // otherwise). 771 bool UsedInLoop = false; 772 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 773 UI != UE; ++UI) { 774 User *U = *UI; 775 BasicBlock *UseBB = cast<Instruction>(U)->getParent(); 776 if (PHINode *P = dyn_cast<PHINode>(U)) { 777 unsigned i = 778 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()); 779 UseBB = P->getIncomingBlock(i); 780 } 781 if (UseBB == Preheader || L->contains(UseBB)) { 782 UsedInLoop = true; 783 break; 784 } 785 } 786 787 // If there is, the def must remain in the preheader. 788 if (UsedInLoop) 789 continue; 790 791 // Otherwise, sink it to the exit block. 792 Instruction *ToMove = I; 793 bool Done = false; 794 795 if (I != Preheader->begin()) { 796 // Skip debug info intrinsics. 797 do { 798 --I; 799 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin()); 800 801 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin()) 802 Done = true; 803 } else { 804 Done = true; 805 } 806 807 ToMove->moveBefore(InsertPt); 808 if (Done) break; 809 InsertPt = ToMove; 810 } 811 } 812 813 /// ConvertToSInt - Convert APF to an integer, if possible. 814 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) { 815 bool isExact = false; 816 if (&APF.getSemantics() == &APFloat::PPCDoubleDouble) 817 return false; 818 // See if we can convert this to an int64_t 819 uint64_t UIntVal; 820 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero, 821 &isExact) != APFloat::opOK || !isExact) 822 return false; 823 IntVal = UIntVal; 824 return true; 825 } 826 827 /// HandleFloatingPointIV - If the loop has floating induction variable 828 /// then insert corresponding integer induction variable if possible. 829 /// For example, 830 /// for(double i = 0; i < 10000; ++i) 831 /// bar(i) 832 /// is converted into 833 /// for(int i = 0; i < 10000; ++i) 834 /// bar((double)i); 835 /// 836 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) { 837 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0)); 838 unsigned BackEdge = IncomingEdge^1; 839 840 // Check incoming value. 841 ConstantFP *InitValueVal = 842 dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge)); 843 844 int64_t InitValue; 845 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue)) 846 return; 847 848 // Check IV increment. Reject this PN if increment operation is not 849 // an add or increment value can not be represented by an integer. 850 BinaryOperator *Incr = 851 dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge)); 852 if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return; 853 854 // If this is not an add of the PHI with a constantfp, or if the constant fp 855 // is not an integer, bail out. 856 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1)); 857 int64_t IncValue; 858 if (IncValueVal == 0 || Incr->getOperand(0) != PN || 859 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue)) 860 return; 861 862 // Check Incr uses. One user is PN and the other user is an exit condition 863 // used by the conditional terminator. 864 Value::use_iterator IncrUse = Incr->use_begin(); 865 Instruction *U1 = cast<Instruction>(*IncrUse++); 866 if (IncrUse == Incr->use_end()) return; 867 Instruction *U2 = cast<Instruction>(*IncrUse++); 868 if (IncrUse != Incr->use_end()) return; 869 870 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't 871 // only used by a branch, we can't transform it. 872 FCmpInst *Compare = dyn_cast<FCmpInst>(U1); 873 if (!Compare) 874 Compare = dyn_cast<FCmpInst>(U2); 875 if (Compare == 0 || !Compare->hasOneUse() || 876 !isa<BranchInst>(Compare->use_back())) 877 return; 878 879 BranchInst *TheBr = cast<BranchInst>(Compare->use_back()); 880 881 // We need to verify that the branch actually controls the iteration count 882 // of the loop. If not, the new IV can overflow and no one will notice. 883 // The branch block must be in the loop and one of the successors must be out 884 // of the loop. 885 assert(TheBr->isConditional() && "Can't use fcmp if not conditional"); 886 if (!L->contains(TheBr->getParent()) || 887 (L->contains(TheBr->getSuccessor(0)) && 888 L->contains(TheBr->getSuccessor(1)))) 889 return; 890 891 892 // If it isn't a comparison with an integer-as-fp (the exit value), we can't 893 // transform it. 894 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1)); 895 int64_t ExitValue; 896 if (ExitValueVal == 0 || 897 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue)) 898 return; 899 900 // Find new predicate for integer comparison. 901 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE; 902 switch (Compare->getPredicate()) { 903 default: return; // Unknown comparison. 904 case CmpInst::FCMP_OEQ: 905 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break; 906 case CmpInst::FCMP_ONE: 907 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break; 908 case CmpInst::FCMP_OGT: 909 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break; 910 case CmpInst::FCMP_OGE: 911 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break; 912 case CmpInst::FCMP_OLT: 913 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break; 914 case CmpInst::FCMP_OLE: 915 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break; 916 } 917 918 // We convert the floating point induction variable to a signed i32 value if 919 // we can. This is only safe if the comparison will not overflow in a way 920 // that won't be trapped by the integer equivalent operations. Check for this 921 // now. 922 // TODO: We could use i64 if it is native and the range requires it. 923 924 // The start/stride/exit values must all fit in signed i32. 925 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue)) 926 return; 927 928 // If not actually striding (add x, 0.0), avoid touching the code. 929 if (IncValue == 0) 930 return; 931 932 // Positive and negative strides have different safety conditions. 933 if (IncValue > 0) { 934 // If we have a positive stride, we require the init to be less than the 935 // exit value and an equality or less than comparison. 936 if (InitValue >= ExitValue || 937 NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE) 938 return; 939 940 uint32_t Range = uint32_t(ExitValue-InitValue); 941 if (NewPred == CmpInst::ICMP_SLE) { 942 // Normalize SLE -> SLT, check for infinite loop. 943 if (++Range == 0) return; // Range overflows. 944 } 945 946 unsigned Leftover = Range % uint32_t(IncValue); 947 948 // If this is an equality comparison, we require that the strided value 949 // exactly land on the exit value, otherwise the IV condition will wrap 950 // around and do things the fp IV wouldn't. 951 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 952 Leftover != 0) 953 return; 954 955 // If the stride would wrap around the i32 before exiting, we can't 956 // transform the IV. 957 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue) 958 return; 959 960 } else { 961 // If we have a negative stride, we require the init to be greater than the 962 // exit value and an equality or greater than comparison. 963 if (InitValue >= ExitValue || 964 NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE) 965 return; 966 967 uint32_t Range = uint32_t(InitValue-ExitValue); 968 if (NewPred == CmpInst::ICMP_SGE) { 969 // Normalize SGE -> SGT, check for infinite loop. 970 if (++Range == 0) return; // Range overflows. 971 } 972 973 unsigned Leftover = Range % uint32_t(-IncValue); 974 975 // If this is an equality comparison, we require that the strided value 976 // exactly land on the exit value, otherwise the IV condition will wrap 977 // around and do things the fp IV wouldn't. 978 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) && 979 Leftover != 0) 980 return; 981 982 // If the stride would wrap around the i32 before exiting, we can't 983 // transform the IV. 984 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue) 985 return; 986 } 987 988 const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext()); 989 990 // Insert new integer induction variable. 991 PHINode *NewPHI = PHINode::Create(Int32Ty, PN->getName()+".int", PN); 992 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue), 993 PN->getIncomingBlock(IncomingEdge)); 994 995 Value *NewAdd = 996 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue), 997 Incr->getName()+".int", Incr); 998 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge)); 999 1000 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd, 1001 ConstantInt::get(Int32Ty, ExitValue), 1002 Compare->getName()); 1003 1004 // In the following deletions, PN may become dead and may be deleted. 1005 // Use a WeakVH to observe whether this happens. 1006 WeakVH WeakPH = PN; 1007 1008 // Delete the old floating point exit comparison. The branch starts using the 1009 // new comparison. 1010 NewCompare->takeName(Compare); 1011 Compare->replaceAllUsesWith(NewCompare); 1012 RecursivelyDeleteTriviallyDeadInstructions(Compare); 1013 1014 // Delete the old floating point increment. 1015 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType())); 1016 RecursivelyDeleteTriviallyDeadInstructions(Incr); 1017 1018 // If the FP induction variable still has uses, this is because something else 1019 // in the loop uses its value. In order to canonicalize the induction 1020 // variable, we chose to eliminate the IV and rewrite it in terms of an 1021 // int->fp cast. 1022 // 1023 // We give preference to sitofp over uitofp because it is faster on most 1024 // platforms. 1025 if (WeakPH) { 1026 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv", 1027 PN->getParent()->getFirstNonPHI()); 1028 PN->replaceAllUsesWith(Conv); 1029 RecursivelyDeleteTriviallyDeadInstructions(PN); 1030 } 1031 1032 // Add a new IVUsers entry for the newly-created integer PHI. 1033 IU->AddUsersIfInteresting(NewPHI); 1034 } 1035