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");
24 #include "llvm/Analysis/Writer.h"
27 // InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
30 static Instruction *InsertCast(Instruction *Val, const Type *Ty,
31 BasicBlock::iterator It) {
32 Instruction *Cast = new CastInst(Val, Ty);
33 if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
34 Val->getParent()->getInstList().insert(It, Cast);
38 static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
39 // Transform all subloops before this loop...
40 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
41 Loop->getSubLoops().end(),
42 std::bind1st(std::ptr_fun(TransformLoop), Loops));
43 // Get the header node for this loop. All of the phi nodes that could be
44 // induction variables must live in this basic block.
46 BasicBlock *Header = Loop->getBlocks().front();
48 // Loop over all of the PHI nodes in the basic block, calculating the
49 // induction variables that they represent... stuffing the induction variable
50 // info into a vector...
52 std::vector<InductionVariable> IndVars; // Induction variables for block
53 for (BasicBlock::iterator I = Header->begin();
54 PHINode *PN = dyn_cast<PHINode>(*I); ++I)
55 IndVars.push_back(InductionVariable(PN, Loops));
57 // If there are no phi nodes in this basic block, there can't be indvars...
58 if (IndVars.empty()) return Changed;
60 // Loop over the induction variables, looking for a cannonical induction
61 // variable, and checking to make sure they are not all unknown induction
64 bool FoundIndVars = false;
65 InductionVariable *Cannonical = 0;
66 for (unsigned i = 0; i < IndVars.size(); ++i) {
67 if (IndVars[i].InductionType == InductionVariable::Cannonical)
68 Cannonical = &IndVars[i];
69 if (IndVars[i].InductionType != InductionVariable::Unknown)
73 // No induction variables, bail early... don't add a cannonnical indvar
74 if (!FoundIndVars) return Changed;
76 // Okay, we want to convert other induction variables to use a cannonical
77 // indvar. If we don't have one, add one now...
79 // Create the PHI node for the new induction variable
80 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
82 // Insert the phi node at the end of the other phi nodes...
83 Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
85 // Create the increment instruction to add one to the counter...
86 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
87 ConstantUInt::get(Type::UIntTy,1),
90 // Insert the add instruction after all of the PHI nodes...
91 Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
93 // Figure out which block is incoming and which is the backedge for the loop
94 BasicBlock *Incoming, *BackEdgeBlock;
95 pred_iterator PI = pred_begin(Header);
96 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
97 if (Loop->contains(*PI)) { // First pred is back edge...
98 BackEdgeBlock = *PI++;
102 BackEdgeBlock = *PI++;
104 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
106 // Add incoming values for the PHI node...
107 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
108 PN->addIncoming(Add, BackEdgeBlock);
110 // Analyze the new induction variable...
111 IndVars.push_back(InductionVariable(PN, Loops));
112 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
113 "Just inserted cannonical indvar that is not cannonical!");
114 Cannonical = &IndVars.back();
120 cerr << "Induction variables:\n";
123 // Get the current loop iteration count, which is always the value of the
124 // cannonical phi node...
126 PHINode *IterCount = Cannonical->Phi;
128 // Loop through and replace all of the auxillary induction variables with
129 // references to the primary induction variable...
131 unsigned InsertPos = IndVars.size();
132 for (unsigned i = 0; i < IndVars.size(); ++i) {
133 InductionVariable *IV = &IndVars[i];
137 // Don't modify the cannonical indvar or unrecognized indvars...
138 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
139 Instruction *Val = IterCount;
140 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
141 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
142 std::string Name; // Create a scale by the step value...
143 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
145 // If the types are not compatible, insert a cast now...
146 if (Val->getType() != IV->Step->getType())
147 Val = InsertCast(Val, IV->Step->getType(),
148 Header->begin()+InsertPos++);
150 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step, Name);
151 // Insert the phi node at the end of the other phi nodes...
152 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
155 if (!isa<Constant>(IV->Start) || // If the start != 0
156 !cast<Constant>(IV->Start)->isNullValue()) {
157 std::string Name; // Create a offset by the start value...
158 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
160 // If the types are not compatible, insert a cast now...
161 if (Val->getType() != IV->Start->getType())
162 Val = InsertCast(Val, IV->Start->getType(),
163 Header->begin()+InsertPos++);
165 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
166 // Insert the phi node at the end of the other phi nodes...
167 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
170 // If the PHI node has a different type than val is, insert a cast now...
171 if (Val->getType() != IV->Phi->getType())
172 Val = InsertCast(Val, IV->Phi->getType(),
173 Header->begin()+InsertPos++);
175 // Replace all uses of the old PHI node with the new computed value...
176 IV->Phi->replaceAllUsesWith(Val);
178 // Move the PHI name to it's new equivalent value...
179 std::string OldName = IV->Phi->getName();
180 IV->Phi->setName("");
181 Val->setName(OldName);
183 // Delete the old, now unused, phi node...
184 Header->getInstList().remove(IV->Phi);
186 InsertPos--; // Deleted an instr, decrement insert position
196 struct InductionVariableSimplify : public FunctionPass {
197 const char *getPassName() const {
198 return "Induction Variable Cannonicalize";
201 virtual bool runOnFunction(Function *F) {
202 LoopInfo &LI = getAnalysis<LoopInfo>();
204 // Induction Variables live in the header nodes of loops
205 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
206 LI.getTopLevelLoops().end(),
207 std::bind1st(std::ptr_fun(TransformLoop), &LI));
210 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
211 AU.addRequired(LoopInfo::ID);
217 Pass *createIndVarSimplifyPass() {
218 return new InductionVariableSimplify();