IndVarSimplify.cpp revision 97e52e43361e77963145b95a576db11b4d14d309
1//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2//
3// InductionVariableSimplify - Transform induction variables in a program
4//   to all use a single cannonical induction variable per loop.
5//
6//===----------------------------------------------------------------------===//
7
8#include "llvm/Transforms/Scalar/IndVarSimplify.h"
9#include "llvm/Analysis/InductionVariable.h"
10#include "llvm/Analysis/LoopInfo.h"
11#include "llvm/iPHINode.h"
12#include "llvm/iOther.h"
13#include "llvm/Type.h"
14#include "llvm/BasicBlock.h"
15#include "llvm/Constants.h"
16#include "llvm/Pass.h"
17#include "llvm/Support/CFG.h"
18#include "Support/STLExtras.h"
19
20#if 0
21#define DEBUG
22#include "llvm/Analysis/Writer.h"
23#endif
24
25// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
26// name...
27//
28static Instruction *InsertCast(Instruction *Val, const Type *Ty,
29                               BasicBlock::iterator It) {
30  Instruction *Cast = new CastInst(Val, Ty);
31  if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
32  Val->getParent()->getInstList().insert(It, Cast);
33  return Cast;
34}
35
36static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
37  // Transform all subloops before this loop...
38  bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
39                                   Loop->getSubLoops().end(),
40                              std::bind1st(std::ptr_fun(TransformLoop), Loops));
41  // Get the header node for this loop.  All of the phi nodes that could be
42  // induction variables must live in this basic block.
43  BasicBlock *Header = (BasicBlock*)Loop->getBlocks().front();
44
45  // Loop over all of the PHI nodes in the basic block, calculating the
46  // induction variables that they represent... stuffing the induction variable
47  // info into a vector...
48  //
49  std::vector<InductionVariable> IndVars;    // Induction variables for block
50  for (BasicBlock::iterator I = Header->begin();
51       PHINode *PN = dyn_cast<PHINode>(*I); ++I)
52    IndVars.push_back(InductionVariable(PN, Loops));
53
54  // If there are no phi nodes in this basic block, there can't be indvars...
55  if (IndVars.empty()) return Changed;
56
57  // Loop over the induction variables, looking for a cannonical induction
58  // variable, and checking to make sure they are not all unknown induction
59  // variables.
60  //
61  bool FoundIndVars = false;
62  InductionVariable *Cannonical = 0;
63  for (unsigned i = 0; i < IndVars.size(); ++i) {
64    if (IndVars[i].InductionType == InductionVariable::Cannonical)
65      Cannonical = &IndVars[i];
66    if (IndVars[i].InductionType != InductionVariable::Unknown)
67      FoundIndVars = true;
68  }
69
70  // No induction variables, bail early... don't add a cannonnical indvar
71  if (!FoundIndVars) return Changed;
72
73  // Okay, we want to convert other induction variables to use a cannonical
74  // indvar.  If we don't have one, add one now...
75  if (!Cannonical) {
76    // Create the PHI node for the new induction variable
77    PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
78
79    // Insert the phi node at the end of the other phi nodes...
80    Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
81
82    // Create the increment instruction to add one to the counter...
83    Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
84                                              ConstantUInt::get(Type::UIntTy,1),
85                                              "add1-indvar");
86
87    // Insert the add instruction after all of the PHI nodes...
88    Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
89
90    // Figure out which block is incoming and which is the backedge for the loop
91    BasicBlock *Incoming, *BackEdgeBlock;
92    pred_iterator PI = pred_begin(Header);
93    assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
94    if (Loop->contains(*PI)) {  // First pred is back edge...
95      BackEdgeBlock = *PI++;
96      Incoming      = *PI++;
97    } else {
98      Incoming      = *PI++;
99      BackEdgeBlock = *PI++;
100    }
101    assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
102
103    // Add incoming values for the PHI node...
104    PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
105    PN->addIncoming(Add, BackEdgeBlock);
106
107    // Analyze the new induction variable...
108    IndVars.push_back(InductionVariable(PN, Loops));
109    assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
110           "Just inserted cannonical indvar that is not cannonical!");
111    Cannonical = &IndVars.back();
112    Changed = true;
113  }
114
115#ifdef DEBUG
116  cerr << "Induction variables:\n";
117#endif
118
119  // Get the current loop iteration count, which is always the value of the
120  // cannonical phi node...
121  //
122  PHINode *IterCount = Cannonical->Phi;
123
124  // Loop through and replace all of the auxillary induction variables with
125  // references to the primary induction variable...
126  //
127  unsigned InsertPos = IndVars.size();
128  for (unsigned i = 0; i < IndVars.size(); ++i) {
129    InductionVariable *IV = &IndVars[i];
130#ifdef DEBUG
131    cerr << IndVars[i];
132#endif
133    // Don't modify the cannonical indvar or unrecognized indvars...
134    if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
135      Instruction *Val = IterCount;
136      if (!isa<ConstantInt>(IV->Step) ||   // If the step != 1
137          !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
138        std::string Name;   // Create a scale by the step value...
139        if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
140
141        // If the types are not compatible, insert a cast now...
142        if (Val->getType() != IV->Step->getType())
143          Val = InsertCast(Val, IV->Step->getType(),
144                           Header->begin()+InsertPos++);
145
146        Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
147        // Insert the phi node at the end of the other phi nodes...
148        Header->getInstList().insert(Header->begin()+InsertPos++, Val);
149      }
150
151      if (!isa<Constant>(IV->Start) ||   // If the start != 0
152          !cast<Constant>(IV->Start)->isNullValue()) {
153        std::string Name;   // Create a offset by the start value...
154        if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
155
156        // If the types are not compatible, insert a cast now...
157        if (Val->getType() != IV->Start->getType())
158          Val = InsertCast(Val, IV->Start->getType(),
159                           Header->begin()+InsertPos++);
160
161        Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
162        // Insert the phi node at the end of the other phi nodes...
163        Header->getInstList().insert(Header->begin()+InsertPos++, Val);
164      }
165
166      // If the PHI node has a different type than val is, insert a cast now...
167      if (Val->getType() != IV->Phi->getType())
168          Val = InsertCast(Val, IV->Phi->getType(),
169                           Header->begin()+InsertPos++);
170
171      // Replace all uses of the old PHI node with the new computed value...
172      IV->Phi->replaceAllUsesWith(Val);
173
174      // Move the PHI name to it's new equivalent value...
175      std::string OldName = IV->Phi->getName();
176      IV->Phi->setName("");
177      Val->setName(OldName);
178
179      // Delete the old, now unused, phi node...
180      Header->getInstList().remove(IV->Phi);
181      delete IV->Phi;
182      InsertPos--;            // Deleted an instr, decrement insert position
183      Changed = true;
184    }
185  }
186
187  return Changed;
188}
189
190static bool doit(Function *M, LoopInfo &Loops) {
191  // Induction Variables live in the header nodes of the loops of the function
192  return reduce_apply_bool(Loops.getTopLevelLoops().begin(),
193                           Loops.getTopLevelLoops().end(),
194                           std::bind1st(std::ptr_fun(TransformLoop), &Loops));
195}
196
197
198namespace {
199  struct InductionVariableSimplify : public FunctionPass {
200    virtual bool runOnFunction(Function *F) {
201      return doit(F, getAnalysis<LoopInfo>());
202    }
203
204    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
205      AU.addRequired(LoopInfo::ID);
206      AU.preservesCFG();
207    }
208  };
209}
210
211Pass *createIndVarSimplifyPass() {
212  return new InductionVariableSimplify();
213}
214
215