IndVarSimplify.cpp revision bcfb913df0def0cb9f866e7811229768334144f3
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 make 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#include "llvm/Transforms/Scalar.h"
41#include "llvm/BasicBlock.h"
42#include "llvm/Constants.h"
43#include "llvm/Instructions.h"
44#include "llvm/Type.h"
45#include "llvm/Analysis/ScalarEvolutionExpander.h"
46#include "llvm/Analysis/LoopInfo.h"
47#include "llvm/Support/CFG.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
49#include "llvm/Transforms/Utils/Local.h"
50#include "llvm/Support/CommandLine.h"
51#include "llvm/ADT/Statistic.h"
52using namespace llvm;
53
54namespace {
55  Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
56  Statistic<> NumPointer ("indvars", "Number of pointer indvars promoted");
57  Statistic<> NumInserted("indvars", "Number of canonical indvars added");
58  Statistic<> NumReplaced("indvars", "Number of exit values replaced");
59  Statistic<> NumLFTR    ("indvars", "Number of loop exit tests replaced");
60
61  class IndVarSimplify : public FunctionPass {
62    LoopInfo        *LI;
63    ScalarEvolution *SE;
64    bool Changed;
65  public:
66    virtual bool runOnFunction(Function &) {
67      LI = &getAnalysis<LoopInfo>();
68      SE = &getAnalysis<ScalarEvolution>();
69      Changed = false;
70
71      // Induction Variables live in the header nodes of loops
72      for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
73        runOnLoop(*I);
74      return Changed;
75    }
76
77    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78      AU.addRequiredID(LoopSimplifyID);
79      AU.addRequired<ScalarEvolution>();
80      AU.addRequired<LoopInfo>();
81      AU.addPreservedID(LoopSimplifyID);
82      AU.addPreservedID(LCSSAID);
83      AU.setPreservesCFG();
84    }
85  private:
86    void runOnLoop(Loop *L);
87    void EliminatePointerRecurrence(PHINode *PN, BasicBlock *Preheader,
88                                    std::set<Instruction*> &DeadInsts);
89    void LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
90                                   SCEVExpander &RW);
91    void RewriteLoopExitValues(Loop *L);
92
93    void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
94  };
95  RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
96}
97
98FunctionPass *llvm::createIndVarSimplifyPass() {
99  return new IndVarSimplify();
100}
101
102/// DeleteTriviallyDeadInstructions - If any of the instructions is the
103/// specified set are trivially dead, delete them and see if this makes any of
104/// their operands subsequently dead.
105void IndVarSimplify::
106DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
107  while (!Insts.empty()) {
108    Instruction *I = *Insts.begin();
109    Insts.erase(Insts.begin());
110    if (isInstructionTriviallyDead(I)) {
111      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
112        if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
113          Insts.insert(U);
114      SE->deleteInstructionFromRecords(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
136      // Okay, we found a pointer recurrence.  Transform this pointer
137      // recurrence into an integer recurrence.  Compute the value that gets
138      // added to the pointer at every iteration.
139      Value *AddedVal = GEPI->getOperand(1);
140
141      // Insert a new integer PHI node into the top of the block.
142      PHINode *NewPhi = new PHINode(AddedVal->getType(),
143                                    PN->getName()+".rec", PN);
144      NewPhi->addIncoming(Constant::getNullValue(NewPhi->getType()), Preheader);
145
146      // Create the new add instruction.
147      Value *NewAdd = BinaryOperator::createAdd(NewPhi, AddedVal,
148                                                GEPI->getName()+".rec", GEPI);
149      NewPhi->addIncoming(NewAdd, PN->getIncomingBlock(BackedgeIdx));
150
151      // Update the existing GEP to use the recurrence.
152      GEPI->setOperand(0, PN->getIncomingValue(PreheaderIdx));
153
154      // Update the GEP to use the new recurrence we just inserted.
155      GEPI->setOperand(1, NewAdd);
156
157      // If the incoming value is a constant expr GEP, try peeling out the array
158      // 0 index if possible to make things simpler.
159      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEPI->getOperand(0)))
160        if (CE->getOpcode() == Instruction::GetElementPtr) {
161          unsigned NumOps = CE->getNumOperands();
162          assert(NumOps > 1 && "CE folding didn't work!");
163          if (CE->getOperand(NumOps-1)->isNullValue()) {
164            // Check to make sure the last index really is an array index.
165            gep_type_iterator GTI = gep_type_begin(CE);
166            for (unsigned i = 1, e = CE->getNumOperands()-1;
167                 i != e; ++i, ++GTI)
168              /*empty*/;
169            if (isa<SequentialType>(*GTI)) {
170              // Pull the last index out of the constant expr GEP.
171              std::vector<Value*> CEIdxs(CE->op_begin()+1, CE->op_end()-1);
172              Constant *NCE = ConstantExpr::getGetElementPtr(CE->getOperand(0),
173                                                             CEIdxs);
174              GetElementPtrInst *NGEPI =
175                new GetElementPtrInst(NCE, Constant::getNullValue(Type::IntTy),
176                                      NewAdd, GEPI->getName(), GEPI);
177              GEPI->replaceAllUsesWith(NGEPI);
178              GEPI->eraseFromParent();
179              GEPI = NGEPI;
180            }
181          }
182        }
183
184
185      // Finally, if there are any other users of the PHI node, we must
186      // insert a new GEP instruction that uses the pre-incremented version
187      // of the induction amount.
188      if (!PN->use_empty()) {
189        BasicBlock::iterator InsertPos = PN; ++InsertPos;
190        while (isa<PHINode>(InsertPos)) ++InsertPos;
191        std::string Name = PN->getName(); PN->setName("");
192        Value *PreInc =
193          new GetElementPtrInst(PN->getIncomingValue(PreheaderIdx),
194                                std::vector<Value*>(1, NewPhi), Name,
195                                InsertPos);
196        PN->replaceAllUsesWith(PreInc);
197      }
198
199      // Delete the old PHI for sure, and the GEP if its otherwise unused.
200      DeadInsts.insert(PN);
201
202      ++NumPointer;
203      Changed = true;
204    }
205}
206
207/// LinearFunctionTestReplace - This method rewrites the exit condition of the
208/// loop to be a canonical != comparison against the incremented loop induction
209/// variable.  This pass is able to rewrite the exit tests of any loop where the
210/// SCEV analysis can determine a loop-invariant trip count of the loop, which
211/// is actually a much broader range than just linear tests.
212void IndVarSimplify::LinearFunctionTestReplace(Loop *L, SCEV *IterationCount,
213                                               SCEVExpander &RW) {
214  // Find the exit block for the loop.  We can currently only handle loops with
215  // a single exit.
216  std::vector<BasicBlock*> ExitBlocks;
217  L->getExitBlocks(ExitBlocks);
218  if (ExitBlocks.size() != 1) return;
219  BasicBlock *ExitBlock = ExitBlocks[0];
220
221  // Make sure there is only one predecessor block in the loop.
222  BasicBlock *ExitingBlock = 0;
223  for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
224       PI != PE; ++PI)
225    if (L->contains(*PI)) {
226      if (ExitingBlock == 0)
227        ExitingBlock = *PI;
228      else
229        return;  // Multiple exits from loop to this block.
230    }
231  assert(ExitingBlock && "Loop info is broken");
232
233  if (!isa<BranchInst>(ExitingBlock->getTerminator()))
234    return;  // Can't rewrite non-branch yet
235  BranchInst *BI = cast<BranchInst>(ExitingBlock->getTerminator());
236  assert(BI->isConditional() && "Must be conditional to be part of loop!");
237
238  std::set<Instruction*> InstructionsToDelete;
239  if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
240    InstructionsToDelete.insert(Cond);
241
242  // If the exiting block is not the same as the backedge block, we must compare
243  // against the preincremented value, otherwise we prefer to compare against
244  // the post-incremented value.
245  BasicBlock *Header = L->getHeader();
246  pred_iterator HPI = pred_begin(Header);
247  assert(HPI != pred_end(Header) && "Loop with zero preds???");
248  if (!L->contains(*HPI)) ++HPI;
249  assert(HPI != pred_end(Header) && L->contains(*HPI) &&
250         "No backedge in loop?");
251
252  SCEVHandle TripCount = IterationCount;
253  Value *IndVar;
254  if (*HPI == ExitingBlock) {
255    // The IterationCount expression contains the number of times that the
256    // backedge actually branches to the loop header.  This is one less than the
257    // number of times the loop executes, so add one to it.
258    Constant *OneC = ConstantInt::get(IterationCount->getType(), 1);
259    TripCount = SCEVAddExpr::get(IterationCount, SCEVUnknown::get(OneC));
260    IndVar = L->getCanonicalInductionVariableIncrement();
261  } else {
262    // We have to use the preincremented value...
263    IndVar = L->getCanonicalInductionVariable();
264  }
265
266  // Expand the code for the iteration count into the preheader of the loop.
267  BasicBlock *Preheader = L->getLoopPreheader();
268  Value *ExitCnt = RW.expandCodeFor(TripCount, Preheader->getTerminator(),
269                                    IndVar->getType());
270
271  // Insert a new setne or seteq instruction before the branch.
272  Instruction::BinaryOps Opcode;
273  if (L->contains(BI->getSuccessor(0)))
274    Opcode = Instruction::SetNE;
275  else
276    Opcode = Instruction::SetEQ;
277
278  Value *Cond = new SetCondInst(Opcode, IndVar, ExitCnt, "exitcond", BI);
279  BI->setCondition(Cond);
280  ++NumLFTR;
281  Changed = true;
282
283  DeleteTriviallyDeadInstructions(InstructionsToDelete);
284}
285
286
287/// RewriteLoopExitValues - Check to see if this loop has a computable
288/// loop-invariant execution count.  If so, this means that we can compute the
289/// final value of any expressions that are recurrent in the loop, and
290/// substitute the exit values from the loop into any instructions outside of
291/// the loop that use the final values of the current expressions.
292void IndVarSimplify::RewriteLoopExitValues(Loop *L) {
293  BasicBlock *Preheader = L->getLoopPreheader();
294
295  // Scan all of the instructions in the loop, looking at those that have
296  // extra-loop users and which are recurrences.
297  SCEVExpander Rewriter(*SE, *LI);
298
299  // We insert the code into the preheader of the loop if the loop contains
300  // multiple exit blocks, or in the exit block if there is exactly one.
301  BasicBlock *BlockToInsertInto;
302  std::vector<BasicBlock*> ExitBlocks;
303  L->getExitBlocks(ExitBlocks);
304  if (ExitBlocks.size() == 1)
305    BlockToInsertInto = ExitBlocks[0];
306  else
307    BlockToInsertInto = Preheader;
308  BasicBlock::iterator InsertPt = BlockToInsertInto->begin();
309  while (isa<PHINode>(InsertPt)) ++InsertPt;
310
311  bool HasConstantItCount = isa<SCEVConstant>(SE->getIterationCount(L));
312
313  std::set<Instruction*> InstructionsToDelete;
314
315  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
316    if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
317      BasicBlock *BB = L->getBlocks()[i];
318      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
319        if (I->getType()->isInteger()) {      // Is an integer instruction
320          SCEVHandle SH = SE->getSCEV(I);
321          if (SH->hasComputableLoopEvolution(L) ||    // Varies predictably
322              HasConstantItCount) {
323            // Find out if this predictably varying value is actually used
324            // outside of the loop.  "extra" as opposed to "intra".
325            std::vector<Instruction*> ExtraLoopUsers;
326            for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
327                 UI != E; ++UI) {
328              Instruction *User = cast<Instruction>(*UI);
329              if (!L->contains(User->getParent()))
330                ExtraLoopUsers.push_back(User);
331            }
332
333            if (!ExtraLoopUsers.empty()) {
334              // Okay, this instruction has a user outside of the current loop
335              // and varies predictably in this loop.  Evaluate the value it
336              // contains when the loop exits, and insert code for it.
337              SCEVHandle ExitValue = SE->getSCEVAtScope(I, L->getParentLoop());
338              if (!isa<SCEVCouldNotCompute>(ExitValue)) {
339                Changed = true;
340                ++NumReplaced;
341                // Remember the next instruction.  The rewriter can move code
342                // around in some cases.
343                BasicBlock::iterator NextI = I; ++NextI;
344
345                Value *NewVal = Rewriter.expandCodeFor(ExitValue, InsertPt,
346                                                       I->getType());
347
348                // Rewrite any users of the computed value outside of the loop
349                // with the newly computed value.
350                for (unsigned i = 0, e = ExtraLoopUsers.size(); i != e; ++i) {
351                  PHINode* PN = dyn_cast<PHINode>(ExtraLoopUsers[i]);
352                  if (PN && !L->contains(PN->getParent())) {
353                     // We're dealing with an LCSSA Phi.  Handle it specially.
354                    Instruction* LCSSAInsertPt = BlockToInsertInto->begin();
355
356                    Instruction* NewInstr = dyn_cast<Instruction>(NewVal);
357                    if (NewInstr && !isa<PHINode>(NewInstr) &&
358                        !L->contains(NewInstr->getParent()))
359                      for (unsigned j = 0; j < NewInstr->getNumOperands(); ++j){
360                        Instruction* PredI =
361                                 dyn_cast<Instruction>(NewInstr->getOperand(j));
362                        if (PredI && L->contains(PredI->getParent())) {
363                          PHINode* NewLCSSA = new PHINode(PredI->getType(),
364                                                    PredI->getName() + ".lcssa",
365                                                    LCSSAInsertPt);
366                          NewLCSSA->addIncoming(PredI,
367                                     BlockToInsertInto->getSinglePredecessor());
368
369                          NewInstr->replaceUsesOfWith(PredI, NewLCSSA);
370                        }
371                      }
372
373                    PN->replaceAllUsesWith(NewVal);
374                    PN->eraseFromParent();
375                  } else {
376                    ExtraLoopUsers[i]->replaceUsesOfWith(I, NewVal);
377                  }
378                }
379
380                // If this instruction is dead now, schedule it to be removed.
381                if (I->use_empty())
382                  InstructionsToDelete.insert(I);
383                I = NextI;
384                continue;  // Skip the ++I
385              }
386            }
387          }
388        }
389
390        // Next instruction.  Continue instruction skips this.
391        ++I;
392      }
393    }
394
395  DeleteTriviallyDeadInstructions(InstructionsToDelete);
396}
397
398
399void IndVarSimplify::runOnLoop(Loop *L) {
400  // First step.  Check to see if there are any trivial GEP pointer recurrences.
401  // If there are, change them into integer recurrences, permitting analysis by
402  // the SCEV routines.
403  //
404  BasicBlock *Header    = L->getHeader();
405  BasicBlock *Preheader = L->getLoopPreheader();
406
407  std::set<Instruction*> DeadInsts;
408  for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
409    PHINode *PN = cast<PHINode>(I);
410    if (isa<PointerType>(PN->getType()))
411      EliminatePointerRecurrence(PN, Preheader, DeadInsts);
412  }
413
414  if (!DeadInsts.empty())
415    DeleteTriviallyDeadInstructions(DeadInsts);
416
417
418  // Next, transform all loops nesting inside of this loop.
419  for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
420    runOnLoop(*I);
421
422  // Check to see if this loop has a computable loop-invariant execution count.
423  // If so, this means that we can compute the final value of any expressions
424  // that are recurrent in the loop, and substitute the exit values from the
425  // loop into any instructions outside of the loop that use the final values of
426  // the current expressions.
427  //
428  SCEVHandle IterationCount = SE->getIterationCount(L);
429  if (!isa<SCEVCouldNotCompute>(IterationCount))
430    RewriteLoopExitValues(L);
431
432  // Next, analyze all of the induction variables in the loop, canonicalizing
433  // auxillary induction variables.
434  std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
435
436  for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
437    PHINode *PN = cast<PHINode>(I);
438    if (PN->getType()->isInteger()) {  // FIXME: when we have fast-math, enable!
439      SCEVHandle SCEV = SE->getSCEV(PN);
440      if (SCEV->hasComputableLoopEvolution(L))
441        // FIXME: It is an extremely bad idea to indvar substitute anything more
442        // complex than affine induction variables.  Doing so will put expensive
443        // polynomial evaluations inside of the loop, and the str reduction pass
444        // currently can only reduce affine polynomials.  For now just disable
445        // indvar subst on anything more complex than an affine addrec.
446        if (SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
447          if (AR->isAffine())
448            IndVars.push_back(std::make_pair(PN, SCEV));
449    }
450  }
451
452  // If there are no induction variables in the loop, there is nothing more to
453  // do.
454  if (IndVars.empty()) {
455    // Actually, if we know how many times the loop iterates, lets insert a
456    // canonical induction variable to help subsequent passes.
457    if (!isa<SCEVCouldNotCompute>(IterationCount)) {
458      SCEVExpander Rewriter(*SE, *LI);
459      Rewriter.getOrInsertCanonicalInductionVariable(L,
460                                                     IterationCount->getType());
461      LinearFunctionTestReplace(L, IterationCount, Rewriter);
462    }
463    return;
464  }
465
466  // Compute the type of the largest recurrence expression.
467  //
468  const Type *LargestType = IndVars[0].first->getType();
469  bool DifferingSizes = false;
470  for (unsigned i = 1, e = IndVars.size(); i != e; ++i) {
471    const Type *Ty = IndVars[i].first->getType();
472    DifferingSizes |= Ty->getPrimitiveSize() != LargestType->getPrimitiveSize();
473    if (Ty->getPrimitiveSize() > LargestType->getPrimitiveSize())
474      LargestType = Ty;
475  }
476
477  // Create a rewriter object which we'll use to transform the code with.
478  SCEVExpander Rewriter(*SE, *LI);
479
480  // Now that we know the largest of of the induction variables in this loop,
481  // insert a canonical induction variable of the largest size.
482  LargestType = LargestType->getUnsignedVersion();
483  Value *IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
484  ++NumInserted;
485  Changed = true;
486
487  if (!isa<SCEVCouldNotCompute>(IterationCount))
488    LinearFunctionTestReplace(L, IterationCount, Rewriter);
489
490  // Now that we have a canonical induction variable, we can rewrite any
491  // recurrences in terms of the induction variable.  Start with the auxillary
492  // induction variables, and recursively rewrite any of their uses.
493  BasicBlock::iterator InsertPt = Header->begin();
494  while (isa<PHINode>(InsertPt)) ++InsertPt;
495
496  // If there were induction variables of other sizes, cast the primary
497  // induction variable to the right size for them, avoiding the need for the
498  // code evaluation methods to insert induction variables of different sizes.
499  if (DifferingSizes) {
500    bool InsertedSizes[17] = { false };
501    InsertedSizes[LargestType->getPrimitiveSize()] = true;
502    for (unsigned i = 0, e = IndVars.size(); i != e; ++i)
503      if (!InsertedSizes[IndVars[i].first->getType()->getPrimitiveSize()]) {
504        PHINode *PN = IndVars[i].first;
505        InsertedSizes[PN->getType()->getPrimitiveSize()] = true;
506        Instruction *New = new CastInst(IndVar,
507                                        PN->getType()->getUnsignedVersion(),
508                                        "indvar", InsertPt);
509        Rewriter.addInsertedValue(New, SE->getSCEV(New));
510      }
511  }
512
513  // If there were induction variables of other sizes, cast the primary
514  // induction variable to the right size for them, avoiding the need for the
515  // code evaluation methods to insert induction variables of different sizes.
516  std::map<unsigned, Value*> InsertedSizes;
517  while (!IndVars.empty()) {
518    PHINode *PN = IndVars.back().first;
519    Value *NewVal = Rewriter.expandCodeFor(IndVars.back().second, InsertPt,
520                                           PN->getType());
521    std::string Name = PN->getName();
522    PN->setName("");
523    NewVal->setName(Name);
524
525    // Replace the old PHI Node with the inserted computation.
526    PN->replaceAllUsesWith(NewVal);
527    DeadInsts.insert(PN);
528    IndVars.pop_back();
529    ++NumRemoved;
530    Changed = true;
531  }
532
533#if 0
534  // Now replace all derived expressions in the loop body with simpler
535  // expressions.
536  for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
537    if (LI->getLoopFor(L->getBlocks()[i]) == L) {  // Not in a subloop...
538      BasicBlock *BB = L->getBlocks()[i];
539      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
540        if (I->getType()->isInteger() &&      // Is an integer instruction
541            !I->use_empty() &&
542            !Rewriter.isInsertedInstruction(I)) {
543          SCEVHandle SH = SE->getSCEV(I);
544          Value *V = Rewriter.expandCodeFor(SH, I, I->getType());
545          if (V != I) {
546            if (isa<Instruction>(V)) {
547              std::string Name = I->getName();
548              I->setName("");
549              V->setName(Name);
550            }
551            I->replaceAllUsesWith(V);
552            DeadInsts.insert(I);
553            ++NumRemoved;
554            Changed = true;
555          }
556        }
557    }
558#endif
559
560  DeleteTriviallyDeadInstructions(DeadInsts);
561}
562