LLVM API Documentation
00001 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This transformation analyzes and transforms the induction variables (and 00011 // computations derived from them) into simpler forms suitable for subsequent 00012 // analysis and transformation. 00013 // 00014 // This transformation make the following changes to each loop with an 00015 // identifiable induction variable: 00016 // 1. All loops are transformed to have a SINGLE canonical induction variable 00017 // which starts at zero and steps by one. 00018 // 2. The canonical induction variable is guaranteed to be the first PHI node 00019 // in the loop header block. 00020 // 3. Any pointer arithmetic recurrences are raised to use array subscripts. 00021 // 00022 // If the trip count of a loop is computable, this pass also makes the following 00023 // changes: 00024 // 1. The exit condition for the loop is canonicalized to compare the 00025 // induction value against the exit value. This turns loops like: 00026 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)' 00027 // 2. Any use outside of the loop of an expression derived from the indvar 00028 // is changed to compute the derived value outside of the loop, eliminating 00029 // the dependence on the exit value of the induction variable. If the only 00030 // purpose of the loop is to compute the exit value of some derived 00031 // expression, this transformation will make the loop dead. 00032 // 00033 // This transformation should be followed by strength reduction after all of the 00034 // desired loop transformations have been performed. Additionally, on targets 00035 // where it is profitable, the loop could be transformed to count down to zero 00036 // (the "do loop" optimization). 00037 // 00038 //===----------------------------------------------------------------------===// 00039 00040 #include "llvm/Transforms/Scalar.h" 00041 #include "llvm/BasicBlock.h" 00042 #include "llvm/Constants.h" 00043 #include "llvm/Instructions.h" 00044 #include "llvm/Type.h" 00045 #include "llvm/Analysis/ScalarEvolutionExpander.h" 00046 #include "llvm/Analysis/LoopInfo.h" 00047 #include "llvm/Support/CFG.h" 00048 #include "llvm/Support/GetElementPtrTypeIterator.h" 00049 #include "llvm/Transforms/Utils/Local.h" 00050 #include "llvm/Support/CommandLine.h" 00051 #include "llvm/ADT/Statistic.h" 00052 using namespace llvm; 00053 00054 namespace { 00055 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed"); 00056 Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted"); 00057 Statistic<> NumInserted("indvars", "Number of canonical indvars added"); 00058 Statistic<> NumReplaced("indvars", "Number of exit values replaced"); 00059 Statistic<> NumLFTR ("indvars", "Number of loop exit tests replaced"); 00060 00061 class IndVarSimplify : public FunctionPass { 00062 LoopInfo *LI; 00063 ScalarEvolution *SE; 00064 bool Changed; 00065 public: 00066 virtual bool runOnFunction(Function &) { 00067 LI = &getAnalysis<LoopInfo>(); 00068 SE = &getAnalysis<ScalarEvolution>(); 00069 Changed = false; 00070 00071 // Induction Variables live in the header nodes of loops 00072 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 00073 runOnLoop(*I); 00074 return Changed; 00075 } 00076 00077 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00078 AU.addRequiredID(LoopSimplifyID); 00079 AU.addRequired<ScalarEvolution>(); 00080 AU.addRequired<LoopInfo>(); 00081 AU.addPreservedID(LoopSimplifyID); 00082 AU.setPreservesCFG(); 00083 } 00084 private: 00085 void runOnLoop(Loop *L); 00086 void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader, 00087 std::set<Instruction*> &DeadInsts); 00088 void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount, 00089 SCEVExpander &RW); 00090 void RewriteLoopExitValues(Loop *L); 00091 00092 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts); 00093 }; 00094 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables"); 00095 } 00096 00097 FunctionPass *llvm::createIndVarSimplifyPass() { 00098 return new IndVarSimplify(); 00099 } 00100 00101 /// DeleteTriviallyDeadInstructions - If any of the instructions is the 00102 /// specified set are trivially dead, delete them and see if this makes any of 00103 /// their operands subsequently dead. 00104 void IndVarSimplify:: 00105 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) { 00106 while (!Insts.empty()) { 00107 Instruction *I = *Insts.begin(); 00108 Insts.erase(Insts.begin()); 00109 if (isInstructionTriviallyDead(I)) { 00110 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 00111 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i))) 00112 Insts.insert(U); 00113 SE->deleteInstructionFromRecords(I); 00114 I->eraseFromParent(); 00115 Changed = true; 00116 } 00117 } 00118 } 00119 00120 00121 /// EliminatePointerRecurrence - Check to see if this is a trivial GEP pointer 00122 /// recurrence. If so, change it into an integer recurrence, permitting 00123 /// analysis by the SCEV routines. 00124 void IndVarSimplify::EliminatePointerRecurrence(PHINode *PN, 00125 BasicBlock *Preheader, 00126 std::set<Instruction*> &DeadInsts) { 00127 assert(PN->getNumIncomingValues() == 2 && "Noncanonicalized loop!"); 00128 unsigned PreheaderIdx = PN->getBasicBlockIndex(Preheader); 00129 unsigned BackedgeIdx = PreheaderIdx^1; 00130 if (GetElementPtrInst *GEPI = 00131 dyn_cast<GetElementPtrInst>(PN->getIncomingValue(BackedgeIdx))) 00132 if (GEPI->getOperand(0) == PN) { 00133 assert(GEPI->getNumOperands() == 2 && "GEP types must match!"); 00134 00135 // Okay, we found a pointer recurrence. Transform this pointer 00136 // recurrence into an integer recurrence. Compute the value that gets 00137 // added to the pointer at every iteration. 00138 Value *AddedVal = GEPI->getOperand(1); 00139 00140 // Insert a new integer PHI node into the top of the block. 00141 PHINode *NewPhi = new PHINode(AddedVal->getType(), 00142 PN->getName()+".rec", PN); 00143 NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader); 00144 00145 // Create the new add instruction. 00146 Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal, 00147 GEPI->getName()+".rec", GEPI); 00148 NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx)); 00149 00150 // Update the existing GEP to use the recurrence. 00151 GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx)); 00152 00153 // Update the GEP to use the new recurrence we just inserted. 00154 GEPI->setOperand(1, NewAdd); 00155 00156 // If the incoming value is a constant expr GEP, try peeling out the array 00157 // 0 index if possible to make things simpler. 00158 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0))) 00159 if (CE->getOpcode() == Instruction::GetElementPtr) { 00160 unsigned NumOps = CE->getNumOperands(); 00161 assert(NumOps > 1 && "CE folding didn't work!"); 00162 if (CE->getOperand(NumOps-1)->isNullValue()) { 00163 // Check to make sure the last index really is an array index. 00164 gep_type_iterator GTI = gep_type_begin(CE); 00165 for (unsigned i = 1, e = CE->getNumOperands()-1; 00166 i != e; ++i, ++GTI) 00167 /*empty*/; 00168 if (isa<SequentialType>(*GTI)) { 00169 // Pull the last index out of the constant expr GEP. 00170 std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1); 00171 Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0), 00172 CEIdxs); 00173 GetElementPtrInst *NGEPI = 00174 new GetElementPtrInst(NCE, Constant::getNullValue(Type::IntTy), 00175 NewAdd, GEPI->getName(), GEPI); 00176 GEPI->replaceAllUsesWith(NGEPI); 00177 GEPI->eraseFromParent(); 00178 GEPI = NGEPI; 00179 } 00180 } 00181 } 00182 00183 00184 // Finally, if there are any other users of the PHI node, we must 00185 // insert a new GEP instruction that uses the pre-incremented version 00186 // of the induction amount. 00187 if (!PN->use_empty()) { 00188 BasicBlock::iterator InsertPos = PN; ++InsertPos; 00189 while (isa<PHINode>(InsertPos)) ++InsertPos; 00190 std::string Name = PN->getName(); PN->setName(""); 00191 Value *PreInc = 00192 new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx), 00193 std::vector<Value*>(1, NewPhi), Name, 00194 InsertPos); 00195 PN->replaceAllUsesWith(PreInc); 00196 } 00197 00198 // Delete the old PHI for sure, and the GEP if its otherwise unused. 00199 DeadInsts.insert(PN); 00200 00201 ++NumPointer; 00202 Changed = true; 00203 } 00204 } 00205 00206 /// LinearFunctionTestReplace - This method rewrites the exit condition of the 00207 /// loop to be a canonical != comparison against the incremented loop induction 00208 /// variable. This pass is able to rewrite the exit tests of any loop where the 00209 /// SCEV analysis can determine a loop-invariant trip count of the loop, which 00210 /// is actually a much broader range than just linear tests. 00211 void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount, 00212 SCEVExpander &RW) { 00213 // Find the exit block for the loop. We can currently only handle loops with 00214 // a single exit. 00215 std::vector<BasicBlock*> ExitBlocks; 00216 L->getExitBlocks(ExitBlocks); 00217 if (ExitBlocks.size() != 1) return; 00218 BasicBlock *ExitBlock = ExitBlocks[0]; 00219 00220 // Make sure there is only one predecessor block in the loop. 00221 BasicBlock *ExitingBlock = 0; 00222 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock); 00223 PI != PE; ++PI) 00224 if (L->contains(*PI)) { 00225 if (ExitingBlock == 0) 00226 ExitingBlock = *PI; 00227 else 00228 return; // Multiple exits from loop to this block. 00229 } 00230 assert(ExitingBlock && "Loop info is broken"); 00231 00232 if (!isa<BranchInst>(ExitingBlock->getTerminator())) 00233 return; // Can't rewrite non-branch yet 00234 BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator()); 00235 assert(BI->isConditional() && "Must be conditional to be part of loop!"); 00236 00237 std::set<Instruction*> InstructionsToDelete; 00238 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition())) 00239 InstructionsToDelete.insert(Cond); 00240 00241 // If the exiting block is not the same as the backedge block, we must compare 00242 // against the preincremented value, otherwise we prefer to compare against 00243 // the post-incremented value. 00244 BasicBlock *Header = L->getHeader(); 00245 pred_iterator HPI = pred_begin(Header); 00246 assert(HPI != pred_end(Header) && "Loop with zero preds???"); 00247 if (!L->contains(*HPI)) ++HPI; 00248 assert(HPI != pred_end(Header) && L->contains(*HPI) && 00249 "No backedge in loop?"); 00250 00251 SCEVHandle TripCount = IterationCount; 00252 Value *IndVar; 00253 if (*HPI == ExitingBlock) { 00254 // The IterationCount expression contains the number of times that the 00255 // backedge actually branches to the loop header. This is one less than the 00256 // number of times the loop executes, so add one to it. 00257 Constant *OneC = ConstantInt::get(IterationCount->getType(), 1); 00258 TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC)); 00259 IndVar = L->getCanonicalInductionVariableIncrement(); 00260 } else { 00261 // We have to use the preincremented value... 00262 IndVar = L->getCanonicalInductionVariable(); 00263 } 00264 00265 // Expand the code for the iteration count into the preheader of the loop. 00266 BasicBlock *Preheader = L->getLoopPreheader(); 00267 Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(), 00268 IndVar->getType()); 00269 00270 // Insert a new setne or seteq instruction before the branch. 00271 Instruction::BinaryOps Opcode; 00272 if (L->contains(BI->getSuccessor(0))) 00273 Opcode = Instruction::SetNE; 00274 else 00275 Opcode = Instruction::SetEQ; 00276 00277 Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI); 00278 BI->setCondition(Cond); 00279 ++NumLFTR; 00280 Changed = true; 00281 00282 DeleteTriviallyDeadInstructions(InstructionsToDelete); 00283 } 00284 00285 00286 /// RewriteLoopExitValues - Check to see if this loop has a computable 00287 /// loop-invariant execution count. If so, this means that we can compute the 00288 /// final value of any expressions that are recurrent in the loop, and 00289 /// substitute the exit values from the loop into any instructions outside of 00290 /// the loop that use the final values of the current expressions. 00291 void IndVarSimplify::RewriteLoopExitValues(Loop *L) { 00292 BasicBlock *Preheader = L->getLoopPreheader(); 00293 00294 // Scan all of the instructions in the loop, looking at those that have 00295 // extra-loop users and which are recurrences. 00296 SCEVExpander Rewriter(*SE, *LI); 00297 00298 // We insert the code into the preheader of the loop if the loop contains 00299 // multiple exit blocks, or in the exit block if there is exactly one. 00300 BasicBlock *BlockToInsertInto; 00301 std::vector<BasicBlock*> ExitBlocks; 00302 L->getExitBlocks(ExitBlocks); 00303 if (ExitBlocks.size() == 1) 00304 BlockToInsertInto = ExitBlocks[0]; 00305 else 00306 BlockToInsertInto = Preheader; 00307 BasicBlock::iterator InsertPt = BlockToInsertInto->begin(); 00308 while (isa<PHINode>(InsertPt)) ++InsertPt; 00309 00310 bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L)); 00311 00312 std::set<Instruction*> InstructionsToDelete; 00313 00314 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) 00315 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop... 00316 BasicBlock *BB = L->getBlocks()[i]; 00317 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 00318 if (I->getType()->isInteger()) { // Is an integer instruction 00319 SCEVHandle SH = SE->getSCEV(I); 00320 if (SH->hasComputableLoopEvolution(L) || // Varies predictably 00321 HasConstantItCount) { 00322 // Find out if this predictably varying value is actually used 00323 // outside of the loop. "extra" as opposed to "intra". 00324 std::vector<Instruction*> ExtraLoopUsers; 00325 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 00326 UI != E; ++UI) { 00327 Instruction *User = cast<Instruction>(*UI); 00328 if (!L->contains(User->getParent())) { 00329 // If this is a PHI node in the exit block and we're inserting, 00330 // into the exit block, it must have a single entry. In this 00331 // case, we can't insert the code after the PHI and have the PHI 00332 // still use it. Instead, don't insert the the PHI. 00333 if (PHINode *PN = dyn_cast<PHINode>(User)) { 00334 // FIXME: This is a case where LCSSA pessimizes code, this 00335 // should be fixed better. 00336 if (PN->getNumOperands() == 2 && 00337 PN->getParent() == BlockToInsertInto) 00338 continue; 00339 } 00340 ExtraLoopUsers.push_back(User); 00341 } 00342 } 00343 00344 if (!ExtraLoopUsers.empty()) { 00345 // Okay, this instruction has a user outside of the current loop 00346 // and varies predictably in this loop. Evaluate the value it 00347 // contains when the loop exits, and insert code for it. 00348 SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop()); 00349 if (!isa<SCEVCouldNotCompute>(ExitValue)) { 00350 Changed = true; 00351 ++NumReplaced; 00352 // Remember the next instruction. The rewriter can move code 00353 // around in some cases. 00354 BasicBlock::iterator NextI = I; ++NextI; 00355 00356 Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt, 00357 I->getType()); 00358 00359 // Rewrite any users of the computed value outside of the loop 00360 // with the newly computed value. 00361 for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) { 00362 PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]); 00363 if (PN && PN->getNumOperands() == 2 && 00364 !L->contains(PN->getParent())) { 00365 // We're dealing with an LCSSA Phi. Handle it specially. 00366 Instruction* LCSSAInsertPt = BlockToInsertInto->begin(); 00367 00368 Instruction* NewInstr = dyn_cast<Instruction>(NewVal); 00369 if (NewInstr && !isa<PHINode>(NewInstr) && 00370 !L->contains(NewInstr->getParent())) 00371 for (unsigned j = 0; j < NewInstr->getNumOperands(); ++j){ 00372 Instruction* PredI = 00373 dyn_cast<Instruction>(NewInstr->getOperand(j)); 00374 if (PredI && L->contains(PredI->getParent())) { 00375 PHINode* NewLCSSA = new PHINode(PredI->getType(), 00376 PredI->getName() + ".lcssa", 00377 LCSSAInsertPt); 00378 NewLCSSA->addIncoming(PredI, 00379 BlockToInsertInto->getSinglePredecessor()); 00380 00381 NewInstr->replaceUsesOfWith(PredI, NewLCSSA); 00382 } 00383 } 00384 00385 PN->replaceAllUsesWith(NewVal); 00386 PN->eraseFromParent(); 00387 } else { 00388 ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal); 00389 } 00390 } 00391 00392 // If this instruction is dead now, schedule it to be removed. 00393 if (I->use_empty()) 00394 InstructionsToDelete.insert(I); 00395 I = NextI; 00396 continue; // Skip the ++I 00397 } 00398 } 00399 } 00400 } 00401 00402 // Next instruction. Continue instruction skips this. 00403 ++I; 00404 } 00405 } 00406 00407 DeleteTriviallyDeadInstructions(InstructionsToDelete); 00408 } 00409 00410 00411 void IndVarSimplify::runOnLoop(Loop *L) { 00412 // First step. Check to see if there are any trivial GEP pointer recurrences. 00413 // If there are, change them into integer recurrences, permitting analysis by 00414 // the SCEV routines. 00415 // 00416 BasicBlock *Header = L->getHeader(); 00417 BasicBlock *Preheader = L->getLoopPreheader(); 00418 00419 std::set<Instruction*> DeadInsts; 00420 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 00421 PHINode *PN = cast<PHINode>(I); 00422 if (isa<PointerType>(PN->getType())) 00423 EliminatePointerRecurrence(PN, Preheader, DeadInsts); 00424 } 00425 00426 if (!DeadInsts.empty()) 00427 DeleteTriviallyDeadInstructions(DeadInsts); 00428 00429 00430 // Next, transform all loops nesting inside of this loop. 00431 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I) 00432 runOnLoop(*I); 00433 00434 // Check to see if this loop has a computable loop-invariant execution count. 00435 // If so, this means that we can compute the final value of any expressions 00436 // that are recurrent in the loop, and substitute the exit values from the 00437 // loop into any instructions outside of the loop that use the final values of 00438 // the current expressions. 00439 // 00440 SCEVHandle IterationCount = SE->getIterationCount(L); 00441 if (!isa<SCEVCouldNotCompute>(IterationCount)) 00442 RewriteLoopExitValues(L); 00443 00444 // Next, analyze all of the induction variables in the loop, canonicalizing 00445 // auxillary induction variables. 00446 std::vector<std::pair<PHINode*, SCEVHandle> > IndVars; 00447 00448 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 00449 PHINode *PN = cast<PHINode>(I); 00450 if (PN->getType()->isInteger()) { // FIXME: when we have fast-math, enable! 00451 SCEVHandle SCEV = SE->getSCEV(PN); 00452 if (SCEV->hasComputableLoopEvolution(L)) 00453 // FIXME: It is an extremely bad idea to indvar substitute anything more 00454 // complex than affine induction variables. Doing so will put expensive 00455 // polynomial evaluations inside of the loop, and the str reduction pass 00456 // currently can only reduce affine polynomials. For now just disable 00457 // indvar subst on anything more complex than an affine addrec. 00458 if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV)) 00459 if (AR->isAffine()) 00460 IndVars.push_back(std::make_pair(PN, SCEV)); 00461 } 00462 } 00463 00464 // If there are no induction variables in the loop, there is nothing more to 00465 // do. 00466 if (IndVars.empty()) { 00467 // Actually, if we know how many times the loop iterates, lets insert a 00468 // canonical induction variable to help subsequent passes. 00469 if (!isa<SCEVCouldNotCompute>(IterationCount)) { 00470 SCEVExpander Rewriter(*SE, *LI); 00471 Rewriter.getOrInsertCanonicalInductionVariable(L, 00472 IterationCount->getType()); 00473 LinearFunctionTestReplace(L, IterationCount, Rewriter); 00474 } 00475 return; 00476 } 00477 00478 // Compute the type of the largest recurrence expression. 00479 // 00480 const Type *LargestType = IndVars[0].first->getType(); 00481 bool DifferingSizes = false; 00482 for (unsigned i = 1, e = IndVars.size(); i != e; ++i) { 00483 const Type *Ty = IndVars[i].first->getType(); 00484 DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize(); 00485 if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize()) 00486 LargestType = Ty; 00487 } 00488 00489 // Create a rewriter object which we'll use to transform the code with. 00490 SCEVExpander Rewriter(*SE, *LI); 00491 00492 // Now that we know the largest of of the induction variables in this loop, 00493 // insert a canonical induction variable of the largest size. 00494 LargestType = LargestType->getUnsignedVersion(); 00495 Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType); 00496 ++NumInserted; 00497 Changed = true; 00498 00499 if (!isa<SCEVCouldNotCompute>(IterationCount)) 00500 LinearFunctionTestReplace(L, IterationCount, Rewriter); 00501 00502 // Now that we have a canonical induction variable, we can rewrite any 00503 // recurrences in terms of the induction variable. Start with the auxillary 00504 // induction variables, and recursively rewrite any of their uses. 00505 BasicBlock::iterator InsertPt = Header->begin(); 00506 while (isa<PHINode>(InsertPt)) ++InsertPt; 00507 00508 // If there were induction variables of other sizes, cast the primary 00509 // induction variable to the right size for them, avoiding the need for the 00510 // code evaluation methods to insert induction variables of different sizes. 00511 if (DifferingSizes) { 00512 bool InsertedSizes[17] = { false }; 00513 InsertedSizes[LargestType->getPrimitiveSize()] = true; 00514 for (unsigned i = 0, e = IndVars.size(); i != e; ++i) 00515 if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) { 00516 PHINode *PN = IndVars[i].first; 00517 InsertedSizes[PN->getType()->getPrimitiveSize()] = true; 00518 Instruction *New = new CastInst(IndVar, 00519 PN->getType()->getUnsignedVersion(), 00520 "indvar", InsertPt); 00521 Rewriter.addInsertedValue(New, SE->getSCEV(New)); 00522 } 00523 } 00524 00525 // If there were induction variables of other sizes, cast the primary 00526 // induction variable to the right size for them, avoiding the need for the 00527 // code evaluation methods to insert induction variables of different sizes. 00528 std::map<unsigned, Value*> InsertedSizes; 00529 while (!IndVars.empty()) { 00530 PHINode *PN = IndVars.back().first; 00531 Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt, 00532 PN->getType()); 00533 std::string Name = PN->getName(); 00534 PN->setName(""); 00535 NewVal->setName(Name); 00536 00537 // Replace the old PHI Node with the inserted computation. 00538 PN->replaceAllUsesWith(NewVal); 00539 DeadInsts.insert(PN); 00540 IndVars.pop_back(); 00541 ++NumRemoved; 00542 Changed = true; 00543 } 00544 00545 #if 0 00546 // Now replace all derived expressions in the loop body with simpler 00547 // expressions. 00548 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) 00549 if (LI->getLoopFor(L->getBlocks()[i]) == L) { // Not in a subloop... 00550 BasicBlock *BB = L->getBlocks()[i]; 00551 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 00552 if (I->getType()->isInteger() && // Is an integer instruction 00553 !I->use_empty() && 00554 !Rewriter.isInsertedInstruction(I)) { 00555 SCEVHandle SH = SE->getSCEV(I); 00556 Value *V = Rewriter.expandCodeFor(SH, I, I->getType()); 00557 if (V != I) { 00558 if (isa<Instruction>(V)) { 00559 std::string Name = I->getName(); 00560 I->setName(""); 00561 V->setName(Name); 00562 } 00563 I->replaceAllUsesWith(V); 00564 DeadInsts.insert(I); 00565 ++NumRemoved; 00566 Changed = true; 00567 } 00568 } 00569 } 00570 #endif 00571 00572 DeleteTriviallyDeadInstructions(DeadInsts); 00573 }