IndVarSimplify.cpp revision 5ee99979065d75605d150d7e567e4351024aae8f
1//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source 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. Any pointer arithmetic recurrences are raised to use array subscripts. 21// 22// If the trip count of a loop is computable, this pass also makes the following 23// changes: 24// 1. The exit condition for the loop is canonicalized to compare the 25// induction value against the exit value. This turns loops like: 26// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)' 27// 2. Any use outside of the loop of an expression derived from the indvar 28// is changed to compute the derived value outside of the loop, eliminating 29// the dependence on the exit value of the induction variable. If the only 30// purpose of the loop is to compute the exit value of some derived 31// expression, this transformation will make the loop dead. 32// 33// This transformation should be followed by strength reduction after all of the 34// desired loop transformations have been performed. Additionally, on targets 35// where it is profitable, the loop could be transformed to count down to zero 36// (the "do loop" optimization). 37// 38//===----------------------------------------------------------------------===// 39 40#define DEBUG_TYPE "indvars" 41#include "llvm/Transforms/Scalar.h" 42#include "llvm/BasicBlock.h" 43#include "llvm/Constants.h" 44#include "llvm/Instructions.h" 45#include "llvm/Type.h" 46#include "llvm/Analysis/ScalarEvolutionExpander.h" 47#include "llvm/Analysis/LoopInfo.h" 48#include "llvm/Analysis/LoopPass.h" 49#include "llvm/Support/CFG.h" 50#include "llvm/Support/Compiler.h" 51#include "llvm/Support/Debug.h" 52#include "llvm/Support/GetElementPtrTypeIterator.h" 53#include "llvm/Transforms/Utils/Local.h" 54#include "llvm/Support/CommandLine.h" 55#include "llvm/ADT/SmallVector.h" 56#include "llvm/ADT/Statistic.h" 57using namespace llvm; 58 59STATISTIC(NumRemoved , "Number of aux indvars removed"); 60STATISTIC(NumPointer , "Number of pointer indvars promoted"); 61STATISTIC(NumInserted, "Number of canonical indvars added"); 62STATISTIC(NumReplaced, "Number of exit values replaced"); 63STATISTIC(NumLFTR , "Number of loop exit tests replaced"); 64 65namespace { 66 class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass { 67 LoopInfo *LI; 68 ScalarEvolution *SE; 69 bool Changed; 70 public: 71 72 bool runOnLoop(Loop *L, LPPassManager &LPM); 73 bool doInitialization(Loop *L, LPPassManager &LPM); 74 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 75 AU.addRequiredID(LCSSAID); 76 AU.addRequiredID(LoopSimplifyID); 77 AU.addRequired<ScalarEvolution>(); 78 AU.addRequired<LoopInfo>(); 79 AU.addPreservedID(LoopSimplifyID); 80 AU.addPreservedID(LCSSAID); 81 AU.setPreservesCFG(); 82 } 83 84 private: 85 86 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader, 87 std::set<Instruction*> &DeadInsts); 88 Instruction *LinearFunctionTestReplace(Loop *L, SCEV *IterationCount, 89 SCEVExpander &RW); 90 void RewriteLoopExitValues(Loop *L); 91 92 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts); 93 }; 94 RegisterPass<IndVarSimplify> X("indvars", "Canonicalize Induction Variables"); 95} 96 97LoopPass *llvm::createIndVarSimplifyPass() { 98 return new IndVarSimplify(); 99} 100 101/// DeleteTriviallyDeadInstructions - If any of the instructions is the 102/// specified set are trivially dead, delete them and see if this makes any of 103/// their operands subsequently dead. 104void IndVarSimplify:: 105DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) { 106 while (!Insts.empty()) { 107 Instruction *I = *Insts.begin(); 108 Insts.erase(Insts.begin()); 109 if (isInstructionTriviallyDead(I)) { 110 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 111 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i))) 112 Insts.insert(U); 113 SE->deleteInstructionFromRecords(I); 114 DOUT << "INDVARS: Deleting: " << *I; 115 I->eraseFromParent(); 116 Changed = true; 117 } 118 } 119} 120 121 122/// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer 123/// recurrence. If so, change it into an integer recurrence, permitting 124/// analysis by the SCEV routines. 125void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN, 126 BasicBlock *Preheader, 127 std::set<Instruction*> &DeadInsts) { 128 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!"); 129 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader); 130 unsigned BackedgeIdx = PreheaderIdx^1; 131 if (GetElementPtrInst *GEPI = 132 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx))) 133 if (GEPI->getOperand(0) == PN) { 134 assert(GEPI->getNumOperands() == 2 && "GEP types must match!"); 135 DOUT << "INDVARS: Eliminating pointer recurrence: " << *GEPI; 136 137 // Okay, we found a pointer recurrence. Transform this pointer 138 // recurrence into an integer recurrence. Compute the value that gets 139 // added to the pointer at every iteration. 140 Value *AddedVal = GEPI->getOperand(1); 141 142 // Insert a new integer PHI node into the top of the block. 143 PHINode *NewPhi = new PHINode(AddedVal->getType(), 144 PN->getName()+".rec", PN); 145 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader); 146 147 // Create the new add instruction. 148 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal, 149 GEPI->getName()+".rec", GEPI); 150 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx)); 151 152 // Update the existing GEP to use the recurrence. 153 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx)); 154 155 // Update the GEP to use the new recurrence we just inserted. 156 GEPI->setOperand(1, NewAdd); 157 158 // If the incoming value is a constant expr GEP, try peeling out the array 159 // 0 index if possible to make things simpler. 160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0))) 161 if (CE->getOpcode() == Instruction::GetElementPtr) { 162 unsigned NumOps = CE->getNumOperands(); 163 assert(NumOps > 1 && "CE folding didn't work!"); 164 if (CE->getOperand(NumOps-1)->isNullValue()) { 165 // Check to make sure the last index really is an array index. 166 gep_type_iterator GTI = gep_type_begin(CE); 167 for (unsigned i = 1, e = CE->getNumOperands()-1; 168 i != e; ++i, ++GTI) 169 /*empty*/; 170 if (isa<SequentialType>(*GTI)) { 171 // Pull the last index out of the constant expr GEP. 172 SmallVector<Value*, 8> CEIdxs(CE->op_begin()+1, CE->op_end()-1); 173 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0), 174 &CEIdxs[0], 175 CEIdxs.size()); 176 GetElementPtrInst *NGEPI = new GetElementPtrInst( 177 NCE, Constant::getNullValue(Type::Int32Ty), NewAdd, 178 GEPI->getName(), GEPI); 179 GEPI->replaceAllUsesWith(NGEPI); 180 GEPI->eraseFromParent(); 181 GEPI = NGEPI; 182 } 183 } 184 } 185 186 187 // Finally, if there are any other users of the PHI node, we must 188 // insert a new GEP instruction that uses the pre-incremented version 189 // of the induction amount. 190 if (!PN->use_empty()) { 191 BasicBlock::iterator InsertPos = PN; ++InsertPos; 192 while (isa<PHINode>(InsertPos)) ++InsertPos; 193 Value *PreInc = 194 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx), 195 NewPhi, "", InsertPos); 196 PreInc->takeName(PN); 197 PN->replaceAllUsesWith(PreInc); 198 } 199 200 // Delete the old PHI for sure, and the GEP if its otherwise unused. 201 DeadInsts.insert(PN); 202 203 ++NumPointer; 204 Changed = true; 205 } 206} 207 208/// LinearFunctionTestReplace - This method rewrites the exit condition of the 209/// loop to be a canonical != comparison against the incremented loop induction 210/// variable. This pass is able to rewrite the exit tests of any loop where the 211/// SCEV analysis can determine a loop-invariant trip count of the loop, which 212/// is actually a much broader range than just linear tests. 213/// 214/// This method returns a "potentially dead" instruction whose computation chain 215/// should be deleted when convenient. 216Instruction *IndVarSimplify::LinearFunctionTestReplace(Loop *L, 217 SCEV *IterationCount, 218 SCEVExpander &RW) { 219 // Find the exit block for the loop. We can currently only handle loops with 220 // a single exit. 221 std::vector<BasicBlock*> ExitBlocks; 222 L->getExitBlocks(ExitBlocks); 223 if (ExitBlocks.size() != 1) return 0; 224 BasicBlock *ExitBlock = ExitBlocks[0]; 225 226 // Make sure there is only one predecessor block in the loop. 227 BasicBlock *ExitingBlock = 0; 228 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock); 229 PI != PE; ++PI) 230 if (L->contains(*PI)) { 231 if (ExitingBlock == 0) 232 ExitingBlock = *PI; 233 else 234 return 0; // Multiple exits from loop to this block. 235 } 236 assert(ExitingBlock && "Loop info is broken"); 237 238 if (!isa<BranchInst>(ExitingBlock->getTerminator())) 239 return 0; // Can't rewrite non-branch yet 240 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator()); 241 assert(BI->isConditional() && "Must be conditional to be part of loop!"); 242 243 Instruction *PotentiallyDeadInst = dyn_cast<Instruction>(BI->getCondition()); 244 245 // If the exiting block is not the same as the backedge block, we must compare 246 // against the preincremented value, otherwise we prefer to compare against 247 // the post-incremented value. 248 BasicBlock *Header = L->getHeader(); 249 pred_iterator HPI = pred_begin(Header); 250 assert(HPI != pred_end(Header) && "Loop with zero preds???"); 251 if (!L->contains(*HPI)) ++HPI; 252 assert(HPI != pred_end(Header) && L->contains(*HPI) && 253 "No backedge in loop?"); 254 255 SCEVHandle TripCount = IterationCount; 256 Value *IndVar; 257 if (*HPI == ExitingBlock) { 258 // The IterationCount expression contains the number of times that the 259 // backedge actually branches to the loop header. This is one less than the 260 // number of times the loop executes, so add one to it. 261 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1); 262 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC)); 263 IndVar = L->getCanonicalInductionVariableIncrement(); 264 } else { 265 // We have to use the preincremented value... 266 IndVar = L->getCanonicalInductionVariable(); 267 } 268 269 DOUT << "INDVARS: LFTR: TripCount = " << *TripCount 270 << " IndVar = " << *IndVar << "\n"; 271 272 // Expand the code for the iteration count into the preheader of the loop. 273 BasicBlock *Preheader = L->getLoopPreheader(); 274 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(), 275 IndVar->getType()); 276 277 // Insert a new icmp_ne or icmp_eq instruction before the branch. 278 ICmpInst::Predicate Opcode; 279 if (L->contains(BI->getSuccessor(0))) 280 Opcode = ICmpInst::ICMP_NE; 281 else 282 Opcode = ICmpInst::ICMP_EQ; 283 284 Value *Cond = new ICmpInst(Opcode, IndVar, ExitCnt, "exitcond", BI); 285 BI->setCondition(Cond); 286 ++NumLFTR; 287 Changed = true; 288 return PotentiallyDeadInst; 289} 290 291 292/// RewriteLoopExitValues - Check to see if this loop has a computable 293/// loop-invariant execution count. If so, this means that we can compute the 294/// final value of any expressions that are recurrent in the loop, and 295/// substitute the exit values from the loop into any instructions outside of 296/// the loop that use the final values of the current expressions. 297void IndVarSimplify::RewriteLoopExitValues(Loop *L) { 298 BasicBlock *Preheader = L->getLoopPreheader(); 299 300 // Scan all of the instructions in the loop, looking at those that have 301 // extra-loop users and which are recurrences. 302 SCEVExpander Rewriter(*SE, *LI); 303 304 // We insert the code into the preheader of the loop if the loop contains 305 // multiple exit blocks, or in the exit block if there is exactly one. 306 BasicBlock *BlockToInsertInto; 307 std::vector<BasicBlock*> ExitBlocks; 308 L->getUniqueExitBlocks(ExitBlocks); 309 if (ExitBlocks.size() == 1) 310 BlockToInsertInto = ExitBlocks[0]; 311 else 312 BlockToInsertInto = Preheader; 313 BasicBlock::iterator InsertPt = BlockToInsertInto->begin(); 314 while (isa<PHINode>(InsertPt)) ++InsertPt; 315 316 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L)); 317 318 std::set<Instruction*> InstructionsToDelete; 319 std::map<Instruction*, Value*> ExitValues; 320 321 // Find all values that are computed inside the loop, but used outside of it. 322 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan 323 // the exit blocks of the loop to find them. 324 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) { 325 BasicBlock *ExitBB = ExitBlocks[i]; 326 327 // If there are no PHI nodes in this exit block, then no values defined 328 // inside the loop are used on this path, skip it. 329 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin()); 330 if (!PN) continue; 331 332 unsigned NumPreds = PN->getNumIncomingValues(); 333 334 // Iterate over all of the PHI nodes. 335 BasicBlock::iterator BBI = ExitBB->begin(); 336 while ((PN = dyn_cast<PHINode>(BBI++))) { 337 338 // Iterate over all of the values in all the PHI nodes. 339 for (unsigned i = 0; i != NumPreds; ++i) { 340 // If the value being merged in is not integer or is not defined 341 // in the loop, skip it. 342 Value *InVal = PN->getIncomingValue(i); 343 if (!isa<Instruction>(InVal) || 344 // SCEV only supports integer expressions for now. 345 !isa<IntegerType>(InVal->getType())) 346 continue; 347 348 // If this pred is for a subloop, not L itself, skip it. 349 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L) 350 continue; // The Block is in a subloop, skip it. 351 352 // Check that InVal is defined in the loop. 353 Instruction *Inst = cast<Instruction>(InVal); 354 if (!L->contains(Inst->getParent())) 355 continue; 356 357 // We require that this value either have a computable evolution or that 358 // the loop have a constant iteration count. In the case where the loop 359 // has a constant iteration count, we can sometimes force evaluation of 360 // the exit value through brute force. 361 SCEVHandle SH = SE->getSCEV(Inst); 362 if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount) 363 continue; // Cannot get exit evolution for the loop value. 364 365 // Okay, this instruction has a user outside of the current loop 366 // and varies predictably *inside* the loop. Evaluate the value it 367 // contains when the loop exits, if possible. 368 SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop()); 369 if (isa<SCEVCouldNotCompute>(ExitValue) || 370 !ExitValue->isLoopInvariant(L)) 371 continue; 372 373 Changed = true; 374 ++NumReplaced; 375 376 // See if we already computed the exit value for the instruction, if so, 377 // just reuse it. 378 Value *&ExitVal = ExitValues[Inst]; 379 if (!ExitVal) 380 ExitVal = Rewriter.expandCodeFor(ExitValue, InsertPt,Inst->getType()); 381 382 DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal 383 << " LoopVal = " << *Inst << "\n"; 384 385 PN->setIncomingValue(i, ExitVal); 386 387 // If this instruction is dead now, schedule it to be removed. 388 if (Inst->use_empty()) 389 InstructionsToDelete.insert(Inst); 390 391 // See if this is a single-entry LCSSA PHI node. If so, we can (and 392 // have to) remove 393 // the PHI entirely. This is safe, because the NewVal won't be variant 394 // in the loop, so we don't need an LCSSA phi node anymore. 395 if (NumPreds == 1) { 396 PN->replaceAllUsesWith(ExitVal); 397 PN->eraseFromParent(); 398 break; 399 } 400 } 401 } 402 } 403 404 DeleteTriviallyDeadInstructions(InstructionsToDelete); 405} 406 407bool IndVarSimplify::doInitialization(Loop *L, LPPassManager &LPM) { 408 409 Changed = false; 410 // First step. Check to see if there are any trivial GEP pointer recurrences. 411 // If there are, change them into integer recurrences, permitting analysis by 412 // the SCEV routines. 413 // 414 BasicBlock *Header = L->getHeader(); 415 BasicBlock *Preheader = L->getLoopPreheader(); 416 SE = &LPM.getAnalysis<ScalarEvolution>(); 417 418 std::set<Instruction*> DeadInsts; 419 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 420 PHINode *PN = cast<PHINode>(I); 421 if (isa<PointerType>(PN->getType())) 422 EliminatePointerRecurrence(PN, Preheader, DeadInsts); 423 } 424 425 if (!DeadInsts.empty()) 426 DeleteTriviallyDeadInstructions(DeadInsts); 427 428 return Changed; 429} 430 431bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) { 432 433 434 LI = &getAnalysis<LoopInfo>(); 435 SE = &getAnalysis<ScalarEvolution>(); 436 437 Changed = false; 438 BasicBlock *Header = L->getHeader(); 439 std::set<Instruction*> DeadInsts; 440 441 // Verify the input to the pass in already in LCSSA form. 442 assert(L->isLCSSAForm()); 443 444 // Check to see if this loop has a computable loop-invariant execution count. 445 // If so, this means that we can compute the final value of any expressions 446 // that are recurrent in the loop, and substitute the exit values from the 447 // loop into any instructions outside of the loop that use the final values of 448 // the current expressions. 449 // 450 SCEVHandle IterationCount = SE->getIterationCount(L); 451 if (!isa<SCEVCouldNotCompute>(IterationCount)) 452 RewriteLoopExitValues(L); 453 454 // Next, analyze all of the induction variables in the loop, canonicalizing 455 // auxillary induction variables. 456 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars; 457 458 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 459 PHINode *PN = cast<PHINode>(I); 460 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable! 461 SCEVHandle SCEV = SE->getSCEV(PN); 462 if (SCEV->hasComputableLoopEvolution(L)) 463 // FIXME: It is an extremely bad idea to indvar substitute anything more 464 // complex than affine induction variables. Doing so will put expensive 465 // polynomial evaluations inside of the loop, and the str reduction pass 466 // currently can only reduce affine polynomials. For now just disable 467 // indvar subst on anything more complex than an affine addrec. 468 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV)) 469 if (AR->isAffine()) 470 IndVars.push_back(std::make_pair(PN, SCEV)); 471 } 472 } 473 474 // If there are no induction variables in the loop, there is nothing more to 475 // do. 476 if (IndVars.empty()) { 477 // Actually, if we know how many times the loop iterates, lets insert a 478 // canonical induction variable to help subsequent passes. 479 if (!isa<SCEVCouldNotCompute>(IterationCount)) { 480 SCEVExpander Rewriter(*SE, *LI); 481 Rewriter.getOrInsertCanonicalInductionVariable(L, 482 IterationCount->getType()); 483 if (Instruction *I = LinearFunctionTestReplace(L, IterationCount, 484 Rewriter)) { 485 std::set<Instruction*> InstructionsToDelete; 486 InstructionsToDelete.insert(I); 487 DeleteTriviallyDeadInstructions(InstructionsToDelete); 488 } 489 } 490 return Changed; 491 } 492 493 // Compute the type of the largest recurrence expression. 494 // 495 const Type *LargestType = IndVars[0].first->getType(); 496 bool DifferingSizes = false; 497 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) { 498 const Type *Ty = IndVars[i].first->getType(); 499 DifferingSizes |= 500 Ty->getPrimitiveSizeInBits() != LargestType->getPrimitiveSizeInBits(); 501 if (Ty->getPrimitiveSizeInBits() > LargestType->getPrimitiveSizeInBits()) 502 LargestType = Ty; 503 } 504 505 // Create a rewriter object which we'll use to transform the code with. 506 SCEVExpander Rewriter(*SE, *LI); 507 508 // Now that we know the largest of of the induction variables in this loop, 509 // insert a canonical induction variable of the largest size. 510 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType); 511 ++NumInserted; 512 Changed = true; 513 DOUT << "INDVARS: New CanIV: " << *IndVar; 514 515 if (!isa<SCEVCouldNotCompute>(IterationCount)) 516 if (Instruction *DI = LinearFunctionTestReplace(L, IterationCount,Rewriter)) 517 DeadInsts.insert(DI); 518 519 // Now that we have a canonical induction variable, we can rewrite any 520 // recurrences in terms of the induction variable. Start with the auxillary 521 // induction variables, and recursively rewrite any of their uses. 522 BasicBlock::iterator InsertPt = Header->begin(); 523 while (isa<PHINode>(InsertPt)) ++InsertPt; 524 525 // If there were induction variables of other sizes, cast the primary 526 // induction variable to the right size for them, avoiding the need for the 527 // code evaluation methods to insert induction variables of different sizes. 528 if (DifferingSizes) { 529 SmallVector<unsigned,4> InsertedSizes; 530 InsertedSizes.push_back(LargestType->getPrimitiveSizeInBits()); 531 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) { 532 unsigned ithSize = IndVars[i].first->getType()->getPrimitiveSizeInBits(); 533 if (std::find(InsertedSizes.begin(), InsertedSizes.end(), ithSize) 534 == InsertedSizes.end()) { 535 PHINode *PN = IndVars[i].first; 536 InsertedSizes.push_back(ithSize); 537 Instruction *New = new TruncInst(IndVar, PN->getType(), "indvar", 538 InsertPt); 539 Rewriter.addInsertedValue(New, SE->getSCEV(New)); 540 DOUT << "INDVARS: Made trunc IV for " << *PN 541 << " NewVal = " << *New << "\n"; 542 } 543 } 544 } 545 546 // Rewrite all induction variables in terms of the canonical induction 547 // variable. 548 std::map<unsigned, Value*> InsertedSizes; 549 while (!IndVars.empty()) { 550 PHINode *PN = IndVars.back().first; 551 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt, 552 PN->getType()); 553 DOUT << "INDVARS: Rewrote IV '" << *IndVars.back().second << "' " << *PN 554 << " into = " << *NewVal << "\n"; 555 NewVal->takeName(PN); 556 557 // Replace the old PHI Node with the inserted computation. 558 PN->replaceAllUsesWith(NewVal); 559 DeadInsts.insert(PN); 560 IndVars.pop_back(); 561 ++NumRemoved; 562 Changed = true; 563 } 564 565#if 0 566 // Now replace all derived expressions in the loop body with simpler 567 // expressions. 568 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) 569 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop... 570 BasicBlock *BB = L->getBlocks()[i]; 571 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 572 if (I->getType()->isInteger() && // Is an integer instruction 573 !I->use_empty() && 574 !Rewriter.isInsertedInstruction(I)) { 575 SCEVHandle SH = SE->getSCEV(I); 576 Value *V = Rewriter.expandCodeFor(SH, I, I->getType()); 577 if (V != I) { 578 if (isa<Instruction>(V)) 579 V->takeName(I); 580 I->replaceAllUsesWith(V); 581 DeadInsts.insert(I); 582 ++NumRemoved; 583 Changed = true; 584 } 585 } 586 } 587#endif 588 589 DeleteTriviallyDeadInstructions(DeadInsts); 590 591 assert(L->isLCSSAForm()); 592 return Changed; 593} 594