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/iPHINode.h"
12 #include "llvm/iOther.h"
13 #include "llvm/Type.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Support/CFG.h"
16 #include "Support/STLExtras.h"
17 #include "Support/StatisticReporter.h"
19 static Statistic<> NumRemoved ("indvars\t\t- Number of aux indvars removed");
20 static Statistic<> NumInserted("indvars\t\t- Number of cannonical indvars added");
23 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
26 static Instruction *InsertCast(Instruction *Val, const Type *Ty,
27 BasicBlock::iterator It) {
28 Instruction *Cast = new CastInst(Val, Ty);
29 if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
30 Val->getParent()->getInstList().insert(It, Cast);
34 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
35 // Transform all subloops before this loop...
36 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
37 Loop->getSubLoops().end(),
38 std::bind1st(std::ptr_fun(TransformLoop), Loops));
39 // Get the header node for this loop. All of the phi nodes that could be
40 // induction variables must live in this basic block.
42 BasicBlock *Header = Loop->getBlocks().front();
44 // Loop over all of the PHI nodes in the basic block, calculating the
45 // induction variables that they represent... stuffing the induction variable
46 // info into a vector...
48 std::vector<InductionVariable> IndVars; // Induction variables for block
49 BasicBlock::iterator AfterPHIIt = Header->begin();
50 for (; PHINode *PN = dyn_cast<PHINode>(&*AfterPHIIt); ++AfterPHIIt)
51 IndVars.push_back(InductionVariable(PN, Loops));
52 // AfterPHIIt now points to first nonphi instruction...
54 // If there are no phi nodes in this basic block, there can't be indvars...
55 if (IndVars.empty()) return Changed;
57 // Loop over the induction variables, looking for a cannonical induction
58 // variable, and checking to make sure they are not all unknown induction
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)
70 // No induction variables, bail early... don't add a cannonnical indvar
71 if (!FoundIndVars) return Changed;
73 // Okay, we want to convert other induction variables to use a cannonical
74 // indvar. If we don't have one, add one now...
76 // Create the PHI node for the new induction variable
77 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
79 // Insert the phi node at the end of the other phi nodes...
80 AfterPHIIt = ++Header->getInstList().insert(AfterPHIIt, PN);
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),
87 // Insert the add instruction after all of the PHI nodes...
88 Header->getInstList().insert(AfterPHIIt, Add);
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++;
99 BackEdgeBlock = *PI++;
101 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
103 // Add incoming values for the PHI node...
104 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
105 PN->addIncoming(Add, BackEdgeBlock);
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();
116 DEBUG(std::cerr << "Induction variables:\n");
118 // Get the current loop iteration count, which is always the value of the
119 // cannonical phi node...
121 PHINode *IterCount = Cannonical->Phi;
123 // Loop through and replace all of the auxillary induction variables with
124 // references to the primary induction variable...
126 for (unsigned i = 0; i < IndVars.size(); ++i) {
127 InductionVariable *IV = &IndVars[i];
129 DEBUG(IV->print(std::cerr));
131 // Don't modify the cannonical indvar or unrecognized indvars...
132 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
133 Instruction *Val = IterCount;
134 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
135 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
136 std::string Name; // Create a scale by the step value...
137 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
139 // If the types are not compatible, insert a cast now...
140 if (Val->getType() != IV->Step->getType())
141 Val = InsertCast(Val, IV->Step->getType(), AfterPHIIt);
143 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
144 // Insert the phi node at the end of the other phi nodes...
145 Header->getInstList().insert(AfterPHIIt, Val);
148 if (!isa<Constant>(IV->Start) || // If the start != 0
149 !cast<Constant>(IV->Start)->isNullValue()) {
150 std::string Name; // Create a offset by the start value...
151 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
153 // If the types are not compatible, insert a cast now...
154 if (Val->getType() != IV->Start->getType())
155 Val = InsertCast(Val, IV->Start->getType(), AfterPHIIt);
157 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
158 // Insert the phi node at the end of the other phi nodes...
159 Header->getInstList().insert(AfterPHIIt, Val);
162 // If the PHI node has a different type than val is, insert a cast now...
163 if (Val->getType() != IV->Phi->getType())
164 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
166 // Replace all uses of the old PHI node with the new computed value...
167 IV->Phi->replaceAllUsesWith(Val);
169 // Move the PHI name to it's new equivalent value...
170 std::string OldName = IV->Phi->getName();
171 IV->Phi->setName("");
172 Val->setName(OldName);
174 // Delete the old, now unused, phi node...
175 Header->getInstList().erase(IV->Phi);
185 struct InductionVariableSimplify : public FunctionPass {
186 virtual bool runOnFunction(Function &) {
187 LoopInfo &LI = getAnalysis<LoopInfo>();
189 // Induction Variables live in the header nodes of loops
190 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
191 LI.getTopLevelLoops().end(),
192 std::bind1st(std::ptr_fun(TransformLoop), &LI));
195 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
196 AU.addRequired(LoopInfo::ID);
200 RegisterOpt<InductionVariableSimplify> X("indvars",
201 "Cannonicalize Induction Variables");
204 Pass *createIndVarSimplifyPass() {
205 return new InductionVariableSimplify();