blob: 763854ee0b111b3b2cdafddefcf6077f2e3d47c3 [file] [log] [blame]
Chris Lattner476e6df2001-12-03 17:28:42 +00001//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
John Criswell482202a2003-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 Lattner476e6df2001-12-03 17:28:42 +00009//
Chris Lattner36257f02003-09-10 05:10:34 +000010// Guarantees that all loops with identifiable, linear, induction variables will
Chris Lattner4e621cd2003-09-10 05:24:46 +000011// be transformed to have a single, canonical, induction variable. After this
Chris Lattner36257f02003-09-10 05:10:34 +000012// pass runs, it guarantees the the first PHI node of the header block in the
Chris Lattner4e621cd2003-09-10 05:24:46 +000013// loop is the canonical induction variable if there is one.
Chris Lattner476e6df2001-12-03 17:28:42 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
Chris Lattnerccd9f3c2003-12-10 18:06:47 +000018#include "llvm/Constants.h"
19#include "llvm/Type.h"
Chris Lattner476e6df2001-12-03 17:28:42 +000020#include "llvm/iPHINode.h"
Chris Lattner91daaab2001-12-04 04:32:29 +000021#include "llvm/iOther.h"
Chris Lattnerccd9f3c2003-12-10 18:06:47 +000022#include "llvm/Analysis/InductionVariable.h"
23#include "llvm/Analysis/LoopInfo.h"
Chris Lattner83d485b2002-02-12 22:39:50 +000024#include "llvm/Support/CFG.h"
Chris Lattnerccd9f3c2003-12-10 18:06:47 +000025#include "llvm/Transforms/Utils/Local.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000026#include "Support/Debug.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000027#include "Support/Statistic.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000028#include "Support/STLExtras.h"
Chris Lattner6c08bb82003-12-15 17:34:02 +000029#include <algorithm>
Chris Lattnerccd9f3c2003-12-10 18:06:47 +000030using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000031
Chris Lattner4184bcc2002-09-10 05:24:05 +000032namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000033 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner4e621cd2003-09-10 05:24:46 +000034 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner4184bcc2002-09-10 05:24:05 +000035}
Chris Lattner91daaab2001-12-04 04:32:29 +000036
37// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
38// name...
39//
Chris Lattner4184bcc2002-09-10 05:24:05 +000040static Instruction *InsertCast(Value *Val, const Type *Ty,
Chris Lattner28a8d242002-09-10 17:04:02 +000041 Instruction *InsertBefore) {
42 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
Chris Lattner91daaab2001-12-04 04:32:29 +000043}
44
Chris Lattner78dd56f2002-04-28 16:21:30 +000045static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
Chris Lattner476e6df2001-12-03 17:28:42 +000046 // Transform all subloops before this loop...
47 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
48 Loop->getSubLoops().end(),
Chris Lattner7f74a562002-01-20 22:54:45 +000049 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner476e6df2001-12-03 17:28:42 +000050 // Get the header node for this loop. All of the phi nodes that could be
51 // induction variables must live in this basic block.
Chris Lattner0b18c1d2002-05-10 15:38:35 +000052 //
Chris Lattner4e621cd2003-09-10 05:24:46 +000053 BasicBlock *Header = Loop->getHeader();
Chris Lattner476e6df2001-12-03 17:28:42 +000054
55 // Loop over all of the PHI nodes in the basic block, calculating the
56 // induction variables that they represent... stuffing the induction variable
57 // info into a vector...
58 //
Chris Lattner7f74a562002-01-20 22:54:45 +000059 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner113f4f42002-06-25 16:13:24 +000060 BasicBlock::iterator AfterPHIIt = Header->begin();
Chris Lattner889f6202003-04-23 16:37:45 +000061 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
Chris Lattner476e6df2001-12-03 17:28:42 +000062 IndVars.push_back(InductionVariable(PN, Loops));
Misha Brukman8b2bd4e2003-10-10 17:57:28 +000063 // AfterPHIIt now points to first non-phi instruction...
Chris Lattner476e6df2001-12-03 17:28:42 +000064
Chris Lattner91daaab2001-12-04 04:32:29 +000065 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner476e6df2001-12-03 17:28:42 +000066 if (IndVars.empty()) return Changed;
67
Chris Lattner4e621cd2003-09-10 05:24:46 +000068 // Loop over the induction variables, looking for a canonical induction
Chris Lattner476e6df2001-12-03 17:28:42 +000069 // variable, and checking to make sure they are not all unknown induction
70 // variables.
71 //
72 bool FoundIndVars = false;
Chris Lattner4e621cd2003-09-10 05:24:46 +000073 InductionVariable *Canonical = 0;
Chris Lattner476e6df2001-12-03 17:28:42 +000074 for (unsigned i = 0; i < IndVars.size(); ++i) {
Chris Lattner4e621cd2003-09-10 05:24:46 +000075 if (IndVars[i].InductionType == InductionVariable::Canonical &&
Chris Lattner4184bcc2002-09-10 05:24:05 +000076 !isa<PointerType>(IndVars[i].Phi->getType()))
Chris Lattner4e621cd2003-09-10 05:24:46 +000077 Canonical = &IndVars[i];
Chris Lattner476e6df2001-12-03 17:28:42 +000078 if (IndVars[i].InductionType != InductionVariable::Unknown)
79 FoundIndVars = true;
80 }
81
Chris Lattner4e621cd2003-09-10 05:24:46 +000082 // No induction variables, bail early... don't add a canonical indvar
Chris Lattner476e6df2001-12-03 17:28:42 +000083 if (!FoundIndVars) return Changed;
84
Chris Lattner4e621cd2003-09-10 05:24:46 +000085 // Okay, we want to convert other induction variables to use a canonical
Chris Lattner476e6df2001-12-03 17:28:42 +000086 // indvar. If we don't have one, add one now...
Chris Lattner4e621cd2003-09-10 05:24:46 +000087 if (!Canonical) {
Chris Lattner28a8d242002-09-10 17:04:02 +000088 // Create the PHI node for the new induction variable, and insert the phi
Chris Lattner295b9072003-09-23 20:26:48 +000089 // node at the start of the PHI nodes...
90 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", Header->begin());
Chris Lattner91daaab2001-12-04 04:32:29 +000091
92 // Create the increment instruction to add one to the counter...
93 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
94 ConstantUInt::get(Type::UIntTy,1),
Chris Lattner28a8d242002-09-10 17:04:02 +000095 "add1-indvar", AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +000096
97 // Figure out which block is incoming and which is the backedge for the loop
98 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner83d485b2002-02-12 22:39:50 +000099 pred_iterator PI = pred_begin(Header);
100 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000101 if (Loop->contains(*PI)) { // First pred is back edge...
102 BackEdgeBlock = *PI++;
103 Incoming = *PI++;
104 } else {
105 Incoming = *PI++;
106 BackEdgeBlock = *PI++;
107 }
Chris Lattner83d485b2002-02-12 22:39:50 +0000108 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner91daaab2001-12-04 04:32:29 +0000109
110 // Add incoming values for the PHI node...
Chris Lattner2716b5e2002-04-27 02:25:14 +0000111 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
Chris Lattner91daaab2001-12-04 04:32:29 +0000112 PN->addIncoming(Add, BackEdgeBlock);
113
114 // Analyze the new induction variable...
115 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner4e621cd2003-09-10 05:24:46 +0000116 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
117 "Just inserted canonical indvar that is not canonical!");
118 Canonical = &IndVars.back();
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000119 ++NumInserted;
Chris Lattner67439402001-12-05 19:41:33 +0000120 Changed = true;
Chris Lattner295b9072003-09-23 20:26:48 +0000121 } else {
122 // If we have a canonical induction variable, make sure that it is the first
123 // one in the basic block.
124 if (&Header->front() != Canonical->Phi)
125 Header->getInstList().splice(Header->begin(), Header->getInstList(),
126 Canonical->Phi);
Chris Lattner91daaab2001-12-04 04:32:29 +0000127 }
128
Anand Shukla2bc64192002-06-25 21:07:58 +0000129 DEBUG(std::cerr << "Induction variables:\n");
Chris Lattner91daaab2001-12-04 04:32:29 +0000130
131 // Get the current loop iteration count, which is always the value of the
Chris Lattner4e621cd2003-09-10 05:24:46 +0000132 // canonical phi node...
Chris Lattner91daaab2001-12-04 04:32:29 +0000133 //
Chris Lattner4e621cd2003-09-10 05:24:46 +0000134 PHINode *IterCount = Canonical->Phi;
Chris Lattner91daaab2001-12-04 04:32:29 +0000135
Chris Lattner4e621cd2003-09-10 05:24:46 +0000136 // Loop through and replace all of the auxiliary induction variables with
137 // references to the canonical induction variable...
Chris Lattner91daaab2001-12-04 04:32:29 +0000138 //
Chris Lattner91daaab2001-12-04 04:32:29 +0000139 for (unsigned i = 0; i < IndVars.size(); ++i) {
140 InductionVariable *IV = &IndVars[i];
Chris Lattner71cbd422002-05-22 17:17:27 +0000141
Chris Lattner26750072002-07-27 01:12:17 +0000142 DEBUG(IV->print(std::cerr));
Chris Lattner71cbd422002-05-22 17:17:27 +0000143
Chris Lattner713907e2003-12-10 20:43:04 +0000144 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
145
Chris Lattner4184bcc2002-09-10 05:24:05 +0000146 // Don't do math with pointers...
147 const Type *IVTy = IV->Phi->getType();
148 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
149
Chris Lattner4e621cd2003-09-10 05:24:46 +0000150 // Don't modify the canonical indvar or unrecognized indvars...
151 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000152 Instruction *Val = IterCount;
153 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
154 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000155
156 // If the types are not compatible, insert a cast now...
Chris Lattner4184bcc2002-09-10 05:24:05 +0000157 if (Val->getType() != IVTy)
158 Val = InsertCast(Val, IVTy, AfterPHIIt);
159 if (IV->Step->getType() != IVTy)
160 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000161
Chris Lattner4184bcc2002-09-10 05:24:05 +0000162 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
Chris Lattner28a8d242002-09-10 17:04:02 +0000163 IV->Phi->getName()+"-scale", AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000164 }
165
Chris Lattner4184bcc2002-09-10 05:24:05 +0000166 // If the start != 0
167 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
Chris Lattner91daaab2001-12-04 04:32:29 +0000168 // If the types are not compatible, insert a cast now...
Chris Lattner4184bcc2002-09-10 05:24:05 +0000169 if (Val->getType() != IVTy)
170 Val = InsertCast(Val, IVTy, AfterPHIIt);
171 if (IV->Start->getType() != IVTy)
172 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000173
Chris Lattner28a8d242002-09-10 17:04:02 +0000174 // Insert the instruction after the phi nodes...
Chris Lattner4184bcc2002-09-10 05:24:05 +0000175 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
Chris Lattner28a8d242002-09-10 17:04:02 +0000176 IV->Phi->getName()+"-offset", AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000177 }
178
179 // If the PHI node has a different type than val is, insert a cast now...
180 if (Val->getType() != IV->Phi->getType())
Chris Lattner113f4f42002-06-25 16:13:24 +0000181 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
Chris Lattner91daaab2001-12-04 04:32:29 +0000182
183 // Replace all uses of the old PHI node with the new computed value...
184 IV->Phi->replaceAllUsesWith(Val);
185
186 // Move the PHI name to it's new equivalent value...
Chris Lattner7f74a562002-01-20 22:54:45 +0000187 std::string OldName = IV->Phi->getName();
Chris Lattner91daaab2001-12-04 04:32:29 +0000188 IV->Phi->setName("");
189 Val->setName(OldName);
190
Chris Lattnerccd9f3c2003-12-10 18:06:47 +0000191 // Get the incoming values used by the PHI node
192 std::vector<Value*> PHIOps;
193 PHIOps.reserve(IV->Phi->getNumIncomingValues());
194 for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i)
195 PHIOps.push_back(IV->Phi->getIncomingValue(i));
196
Chris Lattner91daaab2001-12-04 04:32:29 +0000197 // Delete the old, now unused, phi node...
Chris Lattner113f4f42002-06-25 16:13:24 +0000198 Header->getInstList().erase(IV->Phi);
Chris Lattnerccd9f3c2003-12-10 18:06:47 +0000199
200 // If the PHI is the last user of any instructions for computing PHI nodes
201 // that are irrelevant now, delete those instructions.
202 while (!PHIOps.empty()) {
203 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
204 PHIOps.pop_back();
205
206 if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) {
207 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
208 MaybeDead->op_end());
209 MaybeDead->getParent()->getInstList().erase(MaybeDead);
Chris Lattner6c08bb82003-12-15 17:34:02 +0000210
211 // Erase any duplicates entries in the PHIOps list.
212 std::vector<Value*>::iterator It =
213 std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
214 while (It != PHIOps.end()) {
215 PHIOps.erase(It);
216 It = std::find(PHIOps.begin(), PHIOps.end(), MaybeDead);
217 }
Chris Lattner713907e2003-12-10 20:43:04 +0000218
219 // Erasing the instruction could invalidate the AfterPHI iterator!
220 AfterPHIIt = Header->begin();
Chris Lattnerccd9f3c2003-12-10 18:06:47 +0000221 }
222 }
223
Chris Lattner67439402001-12-05 19:41:33 +0000224 Changed = true;
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000225 ++NumRemoved;
Chris Lattner91daaab2001-12-04 04:32:29 +0000226 }
Chris Lattner476e6df2001-12-03 17:28:42 +0000227 }
228
229 return Changed;
230}
231
Chris Lattner04805fa2002-02-26 21:46:54 +0000232namespace {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000233 struct InductionVariableSimplify : public FunctionPass {
Chris Lattner113f4f42002-06-25 16:13:24 +0000234 virtual bool runOnFunction(Function &) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +0000235 LoopInfo &LI = getAnalysis<LoopInfo>();
236
237 // Induction Variables live in the header nodes of loops
238 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
239 LI.getTopLevelLoops().end(),
240 std::bind1st(std::ptr_fun(TransformLoop), &LI));
Chris Lattner04805fa2002-02-26 21:46:54 +0000241 }
242
Chris Lattnerc8e66542002-04-27 06:56:12 +0000243 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf0ed55d2002-08-08 19:01:30 +0000244 AU.addRequired<LoopInfo>();
Chris Lattner72272a72003-10-12 21:52:28 +0000245 AU.addRequiredID(LoopSimplifyID);
Chris Lattner820d9712002-10-21 20:00:28 +0000246 AU.setPreservesCFG();
Chris Lattner04805fa2002-02-26 21:46:54 +0000247 }
248 };
Chris Lattnerc8b70922002-07-26 21:12:46 +0000249 RegisterOpt<InductionVariableSimplify> X("indvars",
Chris Lattner4e621cd2003-09-10 05:24:46 +0000250 "Canonicalize Induction Variables");
Chris Lattnerd5d56782002-01-31 00:45:11 +0000251}
252
Chris Lattnerccd9f3c2003-12-10 18:06:47 +0000253Pass *llvm::createIndVarSimplifyPass() {
Chris Lattner04805fa2002-02-26 21:46:54 +0000254 return new InductionVariableSimplify();
Chris Lattnerd5d56782002-01-31 00:45:11 +0000255}
Brian Gaeke960707c2003-11-11 22:41:34 +0000256