blob: d06c19787fec5836c23e48044edba19841a0e5c7 [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- 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"
Chris Lattner476e6df2001-12-03 17:28:42 +000011#include "llvm/iPHINode.h"
Chris Lattner91daaab2001-12-04 04:32:29 +000012#include "llvm/iOther.h"
13#include "llvm/Type.h"
14#include "llvm/ConstantVals.h"
Chris Lattner476e6df2001-12-03 17:28:42 +000015#include "Support/STLExtras.h"
16
Chris Lattner91daaab2001-12-04 04:32:29 +000017#if 0
18#define DEBUG
19#include "llvm/Analysis/Writer.h"
20#endif
21
22// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
23// name...
24//
25static Instruction *InsertCast(Instruction *Val, const Type *Ty,
26 BasicBlock::iterator It) {
27 Instruction *Cast = new CastInst(Val, Ty);
28 if (Val->hasName()) Cast->setName(Val->getName()+"-casted");
29 Val->getParent()->getInstList().insert(It, Cast);
30 return Cast;
31}
32
Chris Lattner476e6df2001-12-03 17:28:42 +000033static bool TransformLoop(cfg::LoopInfo *Loops, cfg::Loop *Loop) {
34 // Transform all subloops before this loop...
35 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
36 Loop->getSubLoops().end(),
Chris Lattner7f74a562002-01-20 22:54:45 +000037 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner476e6df2001-12-03 17:28:42 +000038 // Get the header node for this loop. All of the phi nodes that could be
39 // induction variables must live in this basic block.
40 BasicBlock *Header = (BasicBlock*)Loop->getBlocks().front();
41
42 // Loop over all of the PHI nodes in the basic block, calculating the
43 // induction variables that they represent... stuffing the induction variable
44 // info into a vector...
45 //
Chris Lattner7f74a562002-01-20 22:54:45 +000046 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner476e6df2001-12-03 17:28:42 +000047 for (BasicBlock::iterator I = Header->begin();
48 PHINode *PN = dyn_cast<PHINode>(*I); ++I)
49 IndVars.push_back(InductionVariable(PN, Loops));
50
Chris Lattner91daaab2001-12-04 04:32:29 +000051 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner476e6df2001-12-03 17:28:42 +000052 if (IndVars.empty()) return Changed;
53
54 // Loop over the induction variables, looking for a cannonical induction
55 // variable, and checking to make sure they are not all unknown induction
56 // variables.
57 //
58 bool FoundIndVars = false;
59 InductionVariable *Cannonical = 0;
60 for (unsigned i = 0; i < IndVars.size(); ++i) {
61 if (IndVars[i].InductionType == InductionVariable::Cannonical)
62 Cannonical = &IndVars[i];
63 if (IndVars[i].InductionType != InductionVariable::Unknown)
64 FoundIndVars = true;
65 }
66
67 // No induction variables, bail early... don't add a cannonnical indvar
68 if (!FoundIndVars) return Changed;
69
70 // Okay, we want to convert other induction variables to use a cannonical
71 // indvar. If we don't have one, add one now...
72 if (!Cannonical) {
Chris Lattner91daaab2001-12-04 04:32:29 +000073 // Create the PHI node for the new induction variable
74 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
Chris Lattner476e6df2001-12-03 17:28:42 +000075
Chris Lattner91daaab2001-12-04 04:32:29 +000076 // Insert the phi node at the end of the other phi nodes...
77 Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
78
79 // Create the increment instruction to add one to the counter...
80 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
81 ConstantUInt::get(Type::UIntTy,1),
82 "add1-indvar");
83
84 // Insert the add instruction after all of the PHI nodes...
85 Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
86
87 // Figure out which block is incoming and which is the backedge for the loop
88 BasicBlock *Incoming, *BackEdgeBlock;
89 BasicBlock::pred_iterator PI = Header->pred_begin();
90 assert(PI != Header->pred_end() && "Loop headers should have 2 preds!");
91 if (Loop->contains(*PI)) { // First pred is back edge...
92 BackEdgeBlock = *PI++;
93 Incoming = *PI++;
94 } else {
95 Incoming = *PI++;
96 BackEdgeBlock = *PI++;
97 }
98 assert(PI == Header->pred_end() && "Loop headers should have 2 preds!");
99
100 // Add incoming values for the PHI node...
101 PN->addIncoming(Constant::getNullConstant(Type::UIntTy), Incoming);
102 PN->addIncoming(Add, BackEdgeBlock);
103
104 // Analyze the new induction variable...
105 IndVars.push_back(InductionVariable(PN, Loops));
106 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
107 "Just inserted cannonical indvar that is not cannonical!");
108 Cannonical = &IndVars.back();
Chris Lattner67439402001-12-05 19:41:33 +0000109 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000110 }
111
112#ifdef DEBUG
113 cerr << "Induction variables:\n";
114#endif
115
116 // Get the current loop iteration count, which is always the value of the
117 // cannonical phi node...
118 //
119 PHINode *IterCount = Cannonical->Phi;
120
121 // Loop through and replace all of the auxillary induction variables with
122 // references to the primary induction variable...
123 //
124 unsigned InsertPos = IndVars.size();
125 for (unsigned i = 0; i < IndVars.size(); ++i) {
126 InductionVariable *IV = &IndVars[i];
127#ifdef DEBUG
128 cerr << IndVars[i];
129#endif
Chris Lattnerd23d7522001-12-04 08:13:06 +0000130 // Don't modify the cannonical indvar or unrecognized indvars...
131 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000132 Instruction *Val = IterCount;
133 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
134 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000135 std::string Name; // Create a scale by the step value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000136 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
137
138 // If the types are not compatible, insert a cast now...
139 if (Val->getType() != IV->Step->getType())
140 Val = InsertCast(Val, IV->Step->getType(),
141 Header->begin()+InsertPos++);
142
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(Header->begin()+InsertPos++, Val);
146 }
147
148 if (!isa<Constant>(IV->Start) || // If the start != 0
149 !cast<Constant>(IV->Start)->isNullValue()) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000150 std::string Name; // Create a offset by the start value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000151 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
152
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(),
156 Header->begin()+InsertPos++);
157
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(Header->begin()+InsertPos++, Val);
161 }
162
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(),
166 Header->begin()+InsertPos++);
167
168 // Replace all uses of the old PHI node with the new computed value...
169 IV->Phi->replaceAllUsesWith(Val);
170
171 // Move the PHI name to it's new equivalent value...
Chris Lattner7f74a562002-01-20 22:54:45 +0000172 std::string OldName = IV->Phi->getName();
Chris Lattner91daaab2001-12-04 04:32:29 +0000173 IV->Phi->setName("");
174 Val->setName(OldName);
175
176 // Delete the old, now unused, phi node...
177 Header->getInstList().remove(IV->Phi);
178 delete IV->Phi;
179 InsertPos--; // Deleted an instr, decrement insert position
Chris Lattner67439402001-12-05 19:41:33 +0000180 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000181 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000182 }
183
184 return Changed;
185}
186
Chris Lattnerd5d56782002-01-31 00:45:11 +0000187bool InductionVariableSimplify::doit(Method *M, cfg::LoopInfo &Loops) {
Chris Lattner476e6df2001-12-03 17:28:42 +0000188 // Induction Variables live in the header nodes of the loops of the method...
189 return reduce_apply_bool(Loops.getTopLevelLoops().begin(),
190 Loops.getTopLevelLoops().end(),
191 std::bind1st(std::ptr_fun(TransformLoop), &Loops));
192}
Chris Lattnerd5d56782002-01-31 00:45:11 +0000193
194bool InductionVariableSimplify::runOnMethod(Method *M) {
195 return doit(M, getAnalysis<cfg::LoopInfo>());
196}
197
198void InductionVariableSimplify::getAnalysisUsageInfo(Pass::AnalysisSet &Req,
199 Pass::AnalysisSet &Dest,
200 Pass::AnalysisSet &Prov) {
201 Req.push_back(cfg::LoopInfo::ID);
202}