1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
3 // InductionVariableSimplify - Transform induction variables in a program
4 // to all use a single cannonical induction variable per loop.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Transforms/Scalar.h"
9 #include "llvm/Analysis/InductionVariable.h"
10 #include "llvm/Analysis/LoopInfo.h"
11 #include "llvm/Analysis/Writer.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iOther.h"
14 #include "llvm/Type.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Support/CFG.h"
17 #include "Support/STLExtras.h"
18 #include "Support/StatisticReporter.h"
20 static Statistic<> NumRemoved ("indvars\t\t- Number of aux indvars removed");
21 static Statistic<> NumInserted("indvars\t\t- Number of cannonical indvars added");
24 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
27 static Instruction *InsertCast(Instruction *Val, const Type *Ty,
28 BasicBlock::iterator It) {
29 Instruction *Cast = new CastInst(Val, Ty);
30 if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
31 Val->getParent()->getInstList().insert(It, Cast);
35 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
36 // Transform all subloops before this loop...
37 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
38 Loop->getSubLoops().end(),
39 std::bind1st(std::ptr_fun(TransformLoop), Loops));
40 // Get the header node for this loop. All of the phi nodes that could be
41 // induction variables must live in this basic block.
43 BasicBlock *Header = Loop->getBlocks().front();
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...
49 std::vector<InductionVariable> IndVars; // Induction variables for block
50 BasicBlock::iterator AfterPHIIt = Header->begin();
51 for (; PHINode *PN = dyn_cast<PHINode>(&*AfterPHIIt); ++AfterPHIIt)
52 IndVars.push_back(InductionVariable(PN, Loops));
53 // AfterPHIIt now points to first nonphi instruction...
55 // If there are no phi nodes in this basic block, there can't be indvars...
56 if (IndVars.empty()) return Changed;
58 // Loop over the induction variables, looking for a cannonical induction
59 // variable, and checking to make sure they are not all unknown induction
62 bool FoundIndVars = false;
63 InductionVariable *Cannonical = 0;
64 for (unsigned i = 0; i < IndVars.size(); ++i) {
65 if (IndVars[i].InductionType == InductionVariable::Cannonical)
66 Cannonical = &IndVars[i];
67 if (IndVars[i].InductionType != InductionVariable::Unknown)
71 // No induction variables, bail early... don't add a cannonnical indvar
72 if (!FoundIndVars) return Changed;
74 // Okay, we want to convert other induction variables to use a cannonical
75 // indvar. If we don't have one, add one now...
77 // Create the PHI node for the new induction variable
78 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
80 // Insert the phi node at the end of the other phi nodes...
81 AfterPHIIt = ++Header->getInstList().insert(AfterPHIIt, PN);
83 // Create the increment instruction to add one to the counter...
84 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
85 ConstantUInt::get(Type::UIntTy,1),
88 // Insert the add instruction after all of the PHI nodes...
89 Header->getInstList().insert(AfterPHIIt, Add);
91 // Figure out which block is incoming and which is the backedge for the loop
92 BasicBlock *Incoming, *BackEdgeBlock;
93 pred_iterator PI = pred_begin(Header);
94 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
95 if (Loop->contains(*PI)) { // First pred is back edge...
96 BackEdgeBlock = *PI++;
100 BackEdgeBlock = *PI++;
102 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
104 // Add incoming values for the PHI node...
105 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
106 PN->addIncoming(Add, BackEdgeBlock);
108 // Analyze the new induction variable...
109 IndVars.push_back(InductionVariable(PN, Loops));
110 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
111 "Just inserted cannonical indvar that is not cannonical!");
112 Cannonical = &IndVars.back();
117 DEBUG(std::cerr << "Induction variables:\n");
119 // Get the current loop iteration count, which is always the value of the
120 // cannonical phi node...
122 PHINode *IterCount = Cannonical->Phi;
124 // Loop through and replace all of the auxillary induction variables with
125 // references to the primary induction variable...
127 for (unsigned i = 0; i < IndVars.size(); ++i) {
128 InductionVariable *IV = &IndVars[i];
130 DEBUG(std::cerr << IV);
132 // Don't modify the cannonical indvar or unrecognized indvars...
133 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
134 Instruction *Val = IterCount;
135 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
136 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
137 std::string Name; // Create a scale by the step value...
138 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
140 // If the types are not compatible, insert a cast now...
141 if (Val->getType() != IV->Step->getType())
142 Val = InsertCast(Val, IV->Step->getType(), AfterPHIIt);
144 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
145 // Insert the phi node at the end of the other phi nodes...
146 Header->getInstList().insert(AfterPHIIt, Val);
149 if (!isa<Constant>(IV->Start) || // If the start != 0
150 !cast<Constant>(IV->Start)->isNullValue()) {
151 std::string Name; // Create a offset by the start value...
152 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
154 // If the types are not compatible, insert a cast now...
155 if (Val->getType() != IV->Start->getType())
156 Val = InsertCast(Val, IV->Start->getType(), AfterPHIIt);
158 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
159 // Insert the phi node at the end of the other phi nodes...
160 Header->getInstList().insert(AfterPHIIt, Val);
163 // If the PHI node has a different type than val is, insert a cast now...
164 if (Val->getType() != IV->Phi->getType())
165 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
167 // Replace all uses of the old PHI node with the new computed value...
168 IV->Phi->replaceAllUsesWith(Val);
170 // Move the PHI name to it's new equivalent value...
171 std::string OldName = IV->Phi->getName();
172 IV->Phi->setName("");
173 Val->setName(OldName);
175 // Delete the old, now unused, phi node...
176 Header->getInstList().erase(IV->Phi);
186 struct InductionVariableSimplify : public FunctionPass {
187 const char *getPassName() const {
188 return "Induction Variable Cannonicalize";
191 virtual bool runOnFunction(Function &) {
192 LoopInfo &LI = getAnalysis<LoopInfo>();
194 // Induction Variables live in the header nodes of loops
195 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
196 LI.getTopLevelLoops().end(),
197 std::bind1st(std::ptr_fun(TransformLoop), &LI));
200 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
201 AU.addRequired(LoopInfo::ID);
207 Pass *createIndVarSimplifyPass() {
208 return new InductionVariableSimplify();