blob: 5d2cd87725b8e263698f29f6e9e3456905f2fe3f [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
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +00008#include "llvm/Transforms/Scalar.h"
Chris Lattner476e6df2001-12-03 17:28:42 +00009#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"
Chris Lattnerca142372002-04-28 19:55:58 +000014#include "llvm/Constants.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000015#include "llvm/Support/CFG.h"
Chris Lattner476e6df2001-12-03 17:28:42 +000016#include "Support/STLExtras.h"
17
Chris Lattner91daaab2001-12-04 04:32:29 +000018#if 0
19#define DEBUG
20#include "llvm/Analysis/Writer.h"
21#endif
22
23// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
24// name...
25//
26static 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);
31 return Cast;
32}
33
Chris Lattner78dd56f2002-04-28 16:21:30 +000034static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
Chris Lattner476e6df2001-12-03 17:28:42 +000035 // Transform all subloops before this loop...
36 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
37 Loop->getSubLoops().end(),
Chris Lattner7f74a562002-01-20 22:54:45 +000038 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner476e6df2001-12-03 17:28:42 +000039 // Get the header node for this loop. All of the phi nodes that could be
40 // induction variables must live in this basic block.
41 BasicBlock *Header = (BasicBlock*)Loop->getBlocks().front();
42
43 // Loop over all of the PHI nodes in the basic block, calculating the
44 // induction variables that they represent... stuffing the induction variable
45 // info into a vector...
46 //
Chris Lattner7f74a562002-01-20 22:54:45 +000047 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner476e6df2001-12-03 17:28:42 +000048 for (BasicBlock::iterator I = Header->begin();
49 PHINode *PN = dyn_cast<PHINode>(*I); ++I)
50 IndVars.push_back(InductionVariable(PN, Loops));
51
Chris Lattner91daaab2001-12-04 04:32:29 +000052 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner476e6df2001-12-03 17:28:42 +000053 if (IndVars.empty()) return Changed;
54
55 // Loop over the induction variables, looking for a cannonical induction
56 // variable, and checking to make sure they are not all unknown induction
57 // variables.
58 //
59 bool FoundIndVars = false;
60 InductionVariable *Cannonical = 0;
61 for (unsigned i = 0; i < IndVars.size(); ++i) {
62 if (IndVars[i].InductionType == InductionVariable::Cannonical)
63 Cannonical = &IndVars[i];
64 if (IndVars[i].InductionType != InductionVariable::Unknown)
65 FoundIndVars = true;
66 }
67
68 // No induction variables, bail early... don't add a cannonnical indvar
69 if (!FoundIndVars) return Changed;
70
71 // Okay, we want to convert other induction variables to use a cannonical
72 // indvar. If we don't have one, add one now...
73 if (!Cannonical) {
Chris Lattner91daaab2001-12-04 04:32:29 +000074 // Create the PHI node for the new induction variable
75 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar");
Chris Lattner476e6df2001-12-03 17:28:42 +000076
Chris Lattner91daaab2001-12-04 04:32:29 +000077 // Insert the phi node at the end of the other phi nodes...
78 Header->getInstList().insert(Header->begin()+IndVars.size(), PN);
79
80 // Create the increment instruction to add one to the counter...
81 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
82 ConstantUInt::get(Type::UIntTy,1),
83 "add1-indvar");
84
85 // Insert the add instruction after all of the PHI nodes...
86 Header->getInstList().insert(Header->begin()+(IndVars.size()+1), Add);
87
88 // Figure out which block is incoming and which is the backedge for the loop
89 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner83d485b2002-02-12 22:39:50 +000090 pred_iterator PI = pred_begin(Header);
91 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +000092 if (Loop->contains(*PI)) { // First pred is back edge...
93 BackEdgeBlock = *PI++;
94 Incoming = *PI++;
95 } else {
96 Incoming = *PI++;
97 BackEdgeBlock = *PI++;
98 }
Chris Lattner83d485b2002-02-12 22:39:50 +000099 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000100
101 // Add incoming values for the PHI node...
Chris Lattner2716b5e2002-04-27 02:25:14 +0000102 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
Chris Lattner91daaab2001-12-04 04:32:29 +0000103 PN->addIncoming(Add, BackEdgeBlock);
104
105 // Analyze the new induction variable...
106 IndVars.push_back(InductionVariable(PN, Loops));
107 assert(IndVars.back().InductionType == InductionVariable::Cannonical &&
108 "Just inserted cannonical indvar that is not cannonical!");
109 Cannonical = &IndVars.back();
Chris Lattner67439402001-12-05 19:41:33 +0000110 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000111 }
112
113#ifdef DEBUG
114 cerr << "Induction variables:\n";
115#endif
116
117 // Get the current loop iteration count, which is always the value of the
118 // cannonical phi node...
119 //
120 PHINode *IterCount = Cannonical->Phi;
121
122 // Loop through and replace all of the auxillary induction variables with
123 // references to the primary induction variable...
124 //
125 unsigned InsertPos = IndVars.size();
126 for (unsigned i = 0; i < IndVars.size(); ++i) {
127 InductionVariable *IV = &IndVars[i];
128#ifdef DEBUG
129 cerr << IndVars[i];
130#endif
Chris Lattnerd23d7522001-12-04 08:13:06 +0000131 // Don't modify the cannonical indvar or unrecognized indvars...
132 if (IV != Cannonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000133 Instruction *Val = IterCount;
134 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
135 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000136 std::string Name; // Create a scale by the step value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000137 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-scale";
138
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(),
142 Header->begin()+InsertPos++);
143
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(Header->begin()+InsertPos++, Val);
147 }
148
149 if (!isa<Constant>(IV->Start) || // If the start != 0
150 !cast<Constant>(IV->Start)->isNullValue()) {
Chris Lattner7f74a562002-01-20 22:54:45 +0000151 std::string Name; // Create a offset by the start value...
Chris Lattner91daaab2001-12-04 04:32:29 +0000152 if (IV->Phi->hasName()) Name = IV->Phi->getName()+"-offset";
153
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(),
157 Header->begin()+InsertPos++);
158
159 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start, Name);
160 // Insert the phi node at the end of the other phi nodes...
161 Header->getInstList().insert(Header->begin()+InsertPos++, Val);
162 }
163
164 // If the PHI node has a different type than val is, insert a cast now...
165 if (Val->getType() != IV->Phi->getType())
166 Val = InsertCast(Val, IV->Phi->getType(),
167 Header->begin()+InsertPos++);
168
169 // Replace all uses of the old PHI node with the new computed value...
170 IV->Phi->replaceAllUsesWith(Val);
171
172 // Move the PHI name to it's new equivalent value...
Chris Lattner7f74a562002-01-20 22:54:45 +0000173 std::string OldName = IV->Phi->getName();
Chris Lattner91daaab2001-12-04 04:32:29 +0000174 IV->Phi->setName("");
175 Val->setName(OldName);
176
177 // Delete the old, now unused, phi node...
178 Header->getInstList().remove(IV->Phi);
179 delete IV->Phi;
180 InsertPos--; // Deleted an instr, decrement insert position
Chris Lattner67439402001-12-05 19:41:33 +0000181 Changed = true;
Chris Lattner91daaab2001-12-04 04:32:29 +0000182 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000183 }
184
185 return Changed;
186}
187
Chris Lattner78dd56f2002-04-28 16:21:30 +0000188static bool doit(Function *M, LoopInfo &Loops) {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000189 // Induction Variables live in the header nodes of the loops of the function
Chris Lattner476e6df2001-12-03 17:28:42 +0000190 return reduce_apply_bool(Loops.getTopLevelLoops().begin(),
191 Loops.getTopLevelLoops().end(),
192 std::bind1st(std::ptr_fun(TransformLoop), &Loops));
193}
Chris Lattnerd5d56782002-01-31 00:45:11 +0000194
Chris Lattner04805fa2002-02-26 21:46:54 +0000195
196namespace {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000197 struct InductionVariableSimplify : public FunctionPass {
Chris Lattner37104aa2002-04-29 14:57:45 +0000198 const char *getPassName() const {
199 return "Induction Variable Cannonicalize";
200 }
201
Chris Lattnerc8e66542002-04-27 06:56:12 +0000202 virtual bool runOnFunction(Function *F) {
Chris Lattner78dd56f2002-04-28 16:21:30 +0000203 return doit(F, getAnalysis<LoopInfo>());
Chris Lattner04805fa2002-02-26 21:46:54 +0000204 }
205
Chris Lattnerc8e66542002-04-27 06:56:12 +0000206 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner78dd56f2002-04-28 16:21:30 +0000207 AU.addRequired(LoopInfo::ID);
Chris Lattnerf12cc842002-04-28 21:27:06 +0000208 AU.preservesCFG();
Chris Lattner04805fa2002-02-26 21:46:54 +0000209 }
210 };
Chris Lattnerd5d56782002-01-31 00:45:11 +0000211}
212
Chris Lattner04805fa2002-02-26 21:46:54 +0000213Pass *createIndVarSimplifyPass() {
214 return new InductionVariableSimplify();
Chris Lattnerd5d56782002-01-31 00:45:11 +0000215}
Chris Lattner04805fa2002-02-26 21:46:54 +0000216