blob: 946bbaa11b2c08211054a7a2e7f4e8c74f69d2e0 [file] [log] [blame]
Chris Lattner6148c022001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner6148c022001-12-03 17:28:42 +00009//
Chris Lattnerc01ccfd2003-09-10 05:10:34 +000010// Guarantees that all loops with identifiable, linear, induction variables will
Chris Lattner3adf51d2003-09-10 05:24:46 +000011// be transformed to have a single, canonical, induction variable. After this
Chris Lattnerc01ccfd2003-09-10 05:10:34 +000012// pass runs, it guarantees the the first PHI node of the header block in the
Chris Lattner3adf51d2003-09-10 05:24:46 +000013// loop is the canonical induction variable if there is one.
Chris Lattner6148c022001-12-03 17:28:42 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattner022103b2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
John Criswell47df12d2003-12-18 17:19:19 +000018#include "llvm/Constants.h"
19#include "llvm/Type.h"
Chris Lattner18b3c972003-12-22 05:02:01 +000020#include "llvm/Instructions.h"
John Criswell47df12d2003-12-18 17:19:19 +000021#include "llvm/Analysis/InductionVariable.h"
22#include "llvm/Analysis/LoopInfo.h"
Chris Lattner455889a2002-02-12 22:39:50 +000023#include "llvm/Support/CFG.h"
Chris Lattner3324e712003-12-22 03:58:44 +000024#include "llvm/Target/TargetData.h"
John Criswell47df12d2003-12-18 17:19:19 +000025#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6806f562003-08-01 22:15:03 +000026#include "Support/Debug.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000027#include "Support/Statistic.h"
John Criswell47df12d2003-12-18 17:19:19 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner5e761402002-09-10 05:24:05 +000030namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000031 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner3adf51d2003-09-10 05:24:46 +000032 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner3324e712003-12-22 03:58:44 +000033
34 class IndVarSimplify : public FunctionPass {
35 LoopInfo *Loops;
36 TargetData *TD;
37 public:
38 virtual bool runOnFunction(Function &) {
39 Loops = &getAnalysis<LoopInfo>();
40 TD = &getAnalysis<TargetData>();
41
42 // Induction Variables live in the header nodes of loops
43 bool Changed = false;
44 for (unsigned i = 0, e = Loops->getTopLevelLoops().size(); i != e; ++i)
45 Changed |= runOnLoop(Loops->getTopLevelLoops()[i]);
46 return Changed;
47 }
48
49 unsigned getTypeSize(const Type *Ty) {
50 if (unsigned Size = Ty->getPrimitiveSize())
51 return Size;
52 return TD->getTypeSize(Ty); // Must be a pointer
53 }
54
Chris Lattner500597a2003-12-22 09:53:29 +000055 Value *ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV);
56 void ReplaceIndVar(InductionVariable &IV, Value *Counter);
57
Chris Lattner3324e712003-12-22 03:58:44 +000058 bool runOnLoop(Loop *L);
59
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<TargetData>(); // Need pointer size
62 AU.addRequired<LoopInfo>();
63 AU.addRequiredID(LoopSimplifyID);
64 AU.addPreservedID(LoopSimplifyID);
65 AU.setPreservesCFG();
66 }
67 };
68 RegisterOpt<IndVarSimplify> X("indvars", "Canonicalize Induction Variables");
Chris Lattner5e761402002-09-10 05:24:05 +000069}
Chris Lattner394437f2001-12-04 04:32:29 +000070
Chris Lattner3324e712003-12-22 03:58:44 +000071Pass *llvm::createIndVarSimplifyPass() {
72 return new IndVarSimplify();
Chris Lattner394437f2001-12-04 04:32:29 +000073}
74
Chris Lattner3324e712003-12-22 03:58:44 +000075
76bool IndVarSimplify::runOnLoop(Loop *Loop) {
Chris Lattner6148c022001-12-03 17:28:42 +000077 // Transform all subloops before this loop...
Chris Lattner3324e712003-12-22 03:58:44 +000078 bool Changed = false;
79 for (unsigned i = 0, e = Loop->getSubLoops().size(); i != e; ++i)
80 Changed |= runOnLoop(Loop->getSubLoops()[i]);
81
Chris Lattner6148c022001-12-03 17:28:42 +000082 // Get the header node for this loop. All of the phi nodes that could be
83 // induction variables must live in this basic block.
Chris Lattner3dec1f22002-05-10 15:38:35 +000084 //
Chris Lattner3adf51d2003-09-10 05:24:46 +000085 BasicBlock *Header = Loop->getHeader();
Chris Lattner6148c022001-12-03 17:28:42 +000086
87 // Loop over all of the PHI nodes in the basic block, calculating the
88 // induction variables that they represent... stuffing the induction variable
89 // info into a vector...
90 //
Chris Lattner697954c2002-01-20 22:54:45 +000091 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner7e708292002-06-25 16:13:24 +000092 BasicBlock::iterator AfterPHIIt = Header->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000093 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
Chris Lattner6148c022001-12-03 17:28:42 +000094 IndVars.push_back(InductionVariable(PN, Loops));
Misha Brukmancf00c4a2003-10-10 17:57:28 +000095 // AfterPHIIt now points to first non-phi instruction...
Chris Lattner6148c022001-12-03 17:28:42 +000096
Chris Lattner394437f2001-12-04 04:32:29 +000097 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner6148c022001-12-03 17:28:42 +000098 if (IndVars.empty()) return Changed;
99
Chris Lattner3adf51d2003-09-10 05:24:46 +0000100 // Loop over the induction variables, looking for a canonical induction
Chris Lattner6148c022001-12-03 17:28:42 +0000101 // variable, and checking to make sure they are not all unknown induction
Chris Lattner3324e712003-12-22 03:58:44 +0000102 // variables. Keep track of the largest integer size of the induction
103 // variable.
Chris Lattner6148c022001-12-03 17:28:42 +0000104 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000105 InductionVariable *Canonical = 0;
Chris Lattner3324e712003-12-22 03:58:44 +0000106 unsigned MaxSize = 0;
107
108 for (unsigned i = 0; i != IndVars.size(); ++i) {
109 InductionVariable &IV = IndVars[i];
110
111 if (IV.InductionType != InductionVariable::Unknown) {
112 unsigned IVSize = getTypeSize(IV.Phi->getType());
113
114 if (IV.InductionType == InductionVariable::Canonical &&
115 !isa<PointerType>(IV.Phi->getType()) && IVSize >= MaxSize)
116 Canonical = &IV;
117
118 if (IVSize > MaxSize) MaxSize = IVSize;
119
120 // If this variable is larger than the currently identified canonical
121 // indvar, the canonical indvar is not usable.
122 if (Canonical && IVSize > getTypeSize(Canonical->Phi->getType()))
123 Canonical = 0;
124 }
Chris Lattner6148c022001-12-03 17:28:42 +0000125 }
126
Chris Lattner3adf51d2003-09-10 05:24:46 +0000127 // No induction variables, bail early... don't add a canonical indvar
Chris Lattner3324e712003-12-22 03:58:44 +0000128 if (MaxSize == 0) return Changed;
Chris Lattner6148c022001-12-03 17:28:42 +0000129
Chris Lattner3adf51d2003-09-10 05:24:46 +0000130 // Okay, we want to convert other induction variables to use a canonical
Chris Lattner6148c022001-12-03 17:28:42 +0000131 // indvar. If we don't have one, add one now...
Chris Lattner3adf51d2003-09-10 05:24:46 +0000132 if (!Canonical) {
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000133 // Create the PHI node for the new induction variable, and insert the phi
Chris Lattner332ae7f2003-09-23 20:26:48 +0000134 // node at the start of the PHI nodes...
Chris Lattner3324e712003-12-22 03:58:44 +0000135 const Type *IVType;
136 switch (MaxSize) {
137 default: assert(0 && "Unknown integer type size!");
138 case 1: IVType = Type::UByteTy; break;
139 case 2: IVType = Type::UShortTy; break;
140 case 4: IVType = Type::UIntTy; break;
141 case 8: IVType = Type::ULongTy; break;
142 }
143
144 PHINode *PN = new PHINode(IVType, "cann-indvar", Header->begin());
Chris Lattner394437f2001-12-04 04:32:29 +0000145
146 // Create the increment instruction to add one to the counter...
147 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
Chris Lattner3324e712003-12-22 03:58:44 +0000148 ConstantUInt::get(IVType, 1),
149 "next-indvar", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000150
151 // Figure out which block is incoming and which is the backedge for the loop
152 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner455889a2002-02-12 22:39:50 +0000153 pred_iterator PI = pred_begin(Header);
154 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000155 if (Loop->contains(*PI)) { // First pred is back edge...
156 BackEdgeBlock = *PI++;
157 Incoming = *PI++;
158 } else {
159 Incoming = *PI++;
160 BackEdgeBlock = *PI++;
161 }
Chris Lattner455889a2002-02-12 22:39:50 +0000162 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000163
164 // Add incoming values for the PHI node...
Chris Lattner3324e712003-12-22 03:58:44 +0000165 PN->addIncoming(Constant::getNullValue(IVType), Incoming);
Chris Lattner394437f2001-12-04 04:32:29 +0000166 PN->addIncoming(Add, BackEdgeBlock);
167
168 // Analyze the new induction variable...
169 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner3adf51d2003-09-10 05:24:46 +0000170 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
171 "Just inserted canonical indvar that is not canonical!");
172 Canonical = &IndVars.back();
Chris Lattner3dec1f22002-05-10 15:38:35 +0000173 ++NumInserted;
Chris Lattner4753bf22001-12-05 19:41:33 +0000174 Changed = true;
Chris Lattner332ae7f2003-09-23 20:26:48 +0000175 } else {
176 // If we have a canonical induction variable, make sure that it is the first
177 // one in the basic block.
178 if (&Header->front() != Canonical->Phi)
179 Header->getInstList().splice(Header->begin(), Header->getInstList(),
180 Canonical->Phi);
Chris Lattner394437f2001-12-04 04:32:29 +0000181 }
182
Anand Shukla5ba99bd2002-06-25 21:07:58 +0000183 DEBUG(std::cerr << "Induction variables:\n");
Chris Lattner394437f2001-12-04 04:32:29 +0000184
185 // Get the current loop iteration count, which is always the value of the
Chris Lattner3adf51d2003-09-10 05:24:46 +0000186 // canonical phi node...
Chris Lattner394437f2001-12-04 04:32:29 +0000187 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000188 PHINode *IterCount = Canonical->Phi;
Chris Lattner394437f2001-12-04 04:32:29 +0000189
Chris Lattner3adf51d2003-09-10 05:24:46 +0000190 // Loop through and replace all of the auxiliary induction variables with
191 // references to the canonical induction variable...
Chris Lattner394437f2001-12-04 04:32:29 +0000192 //
Chris Lattner3324e712003-12-22 03:58:44 +0000193 for (unsigned i = 0; i != IndVars.size(); ++i) {
Chris Lattner394437f2001-12-04 04:32:29 +0000194 InductionVariable *IV = &IndVars[i];
Chris Lattnerf016ea42002-05-22 17:17:27 +0000195
Chris Lattnera59cbb22002-07-27 01:12:17 +0000196 DEBUG(IV->print(std::cerr));
Chris Lattnerf016ea42002-05-22 17:17:27 +0000197
Chris Lattner3adf51d2003-09-10 05:24:46 +0000198 // Don't modify the canonical indvar or unrecognized indvars...
199 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner500597a2003-12-22 09:53:29 +0000200 ReplaceIndVar(*IV, IterCount);
Chris Lattner4753bf22001-12-05 19:41:33 +0000201 Changed = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000202 ++NumRemoved;
Chris Lattner394437f2001-12-04 04:32:29 +0000203 }
Chris Lattner6148c022001-12-03 17:28:42 +0000204 }
205
206 return Changed;
207}
208
Chris Lattner500597a2003-12-22 09:53:29 +0000209/// ComputeAuxIndVarValue - Given an auxillary induction variable, compute and
210/// return a value which will always be equal to the induction variable PHI, but
211/// is based off of the canonical induction variable CIV.
212///
213Value *IndVarSimplify::ComputeAuxIndVarValue(InductionVariable &IV, Value *CIV){
214 Instruction *Phi = IV.Phi;
215 const Type *IVTy = Phi->getType();
216 if (isa<PointerType>(IVTy)) // If indexing into a pointer, make the
217 IVTy = TD->getIntPtrType(); // index the appropriate type.
218
219 BasicBlock::iterator AfterPHIIt = Phi;
220 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
221
222 Value *Val = CIV;
223 if (Val->getType() != IVTy)
224 Val = new CastInst(Val, IVTy, Val->getName(), AfterPHIIt);
225
226 if (!isa<ConstantInt>(IV.Step) || // If the step != 1
227 !cast<ConstantInt>(IV.Step)->equalsInt(1)) {
228
229 // If the types are not compatible, insert a cast now...
230 if (IV.Step->getType() != IVTy)
231 IV.Step = new CastInst(IV.Step, IVTy, IV.Step->getName(), AfterPHIIt);
232
233 Val = BinaryOperator::create(Instruction::Mul, Val, IV.Step,
234 Phi->getName()+"-scale", AfterPHIIt);
235 }
236
237 // If this is a pointer indvar...
238 if (isa<PointerType>(Phi->getType())) {
239 std::vector<Value*> Idx;
240 // FIXME: this should not be needed when we fix PR82!
241 if (Val->getType() != Type::LongTy)
242 Val = new CastInst(Val, Type::LongTy, Val->getName(), AfterPHIIt);
243 Idx.push_back(Val);
244 Val = new GetElementPtrInst(IV.Start, Idx,
245 Phi->getName()+"-offset",
246 AfterPHIIt);
247
248 } else if (!isa<Constant>(IV.Start) || // If Start != 0...
249 !cast<Constant>(IV.Start)->isNullValue()) {
250 // If the types are not compatible, insert a cast now...
251 if (IV.Start->getType() != IVTy)
252 IV.Start = new CastInst(IV.Start, IVTy, IV.Start->getName(),
253 AfterPHIIt);
254
255 // Insert the instruction after the phi nodes...
256 Val = BinaryOperator::create(Instruction::Add, Val, IV.Start,
257 Phi->getName()+"-offset", AfterPHIIt);
258 }
259
260 // If the PHI node has a different type than val is, insert a cast now...
261 if (Val->getType() != Phi->getType())
262 Val = new CastInst(Val, Phi->getType(), Val->getName(), AfterPHIIt);
263
264 // Move the PHI name to it's new equivalent value...
265 std::string OldName = Phi->getName();
266 Phi->setName("");
267 Val->setName(OldName);
268
269 return Val;
270}
271
272
273// ReplaceIndVar - Replace all uses of the specified induction variable with
274// expressions computed from the specified loop iteration counter variable.
275// Return true if instructions were deleted.
276void IndVarSimplify::ReplaceIndVar(InductionVariable &IV, Value *CIV) {
277 Value *IndVarVal = 0;
278 PHINode *Phi = IV.Phi;
279
280 assert(Phi->getNumOperands() == 4 &&
281 "Only expect induction variables in canonical loops!");
282
283 // Remember the incoming values used by the PHI node
284 std::vector<Value*> PHIOps;
285 PHIOps.reserve(2);
286 PHIOps.push_back(Phi->getIncomingValue(0));
287 PHIOps.push_back(Phi->getIncomingValue(1));
288
289 // Delete all of the operands of the PHI node... FIXME, this should be more
290 // intelligent.
291 Phi->dropAllReferences();
292
293 // Now that we are rid of unneeded uses of the PHI node, replace any remaining
294 // ones with the appropriate code using the canonical induction variable.
295 while (!Phi->use_empty()) {
296 Instruction *U = cast<Instruction>(Phi->use_back());
297
298 // TODO: Perform LFTR here if possible
299 if (0) {
300
301 } else {
302 // Replace all uses of the old PHI node with the new computed value...
303 if (IndVarVal == 0)
304 IndVarVal = ComputeAuxIndVarValue(IV, CIV);
305 U->replaceUsesOfWith(Phi, IndVarVal);
306 }
307 }
308
309 // If the PHI is the last user of any instructions for computing PHI nodes
310 // that are irrelevant now, delete those instructions.
311 while (!PHIOps.empty()) {
312 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
313 PHIOps.pop_back();
314
315 if (MaybeDead && isInstructionTriviallyDead(MaybeDead) &&
316 (!isa<PHINode>(MaybeDead) ||
317 MaybeDead->getParent() != Phi->getParent())) {
318 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
319 MaybeDead->op_end());
320 MaybeDead->getParent()->getInstList().erase(MaybeDead);
321
322 // Erase any duplicates entries in the PHIOps list.
323 std::vector<Value*>::iterator It =
324 std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
325 while (It != PHIOps.end()) {
326 PHIOps.erase(It);
327 It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
328 }
329 }
330 }
331
332 // Delete the old, now unused, phi node...
333 Phi->getParent()->getInstList().erase(Phi);
334}
335