blob: ed5aca372ab0469aab9d44a109732b2998b38780 [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"
Chris Lattnerba4f3f62003-12-10 18:06:47 +000018#include "llvm/Constants.h"
19#include "llvm/Type.h"
Chris Lattner6148c022001-12-03 17:28:42 +000020#include "llvm/iPHINode.h"
Chris Lattner394437f2001-12-04 04:32:29 +000021#include "llvm/iOther.h"
Chris Lattnerba4f3f62003-12-10 18:06:47 +000022#include "llvm/Analysis/InductionVariable.h"
23#include "llvm/Analysis/LoopInfo.h"
Chris Lattner455889a2002-02-12 22:39:50 +000024#include "llvm/Support/CFG.h"
Chris Lattnerba4f3f62003-12-10 18:06:47 +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"
Chris Lattner6806f562003-08-01 22:15:03 +000028#include "Support/STLExtras.h"
Chris Lattnerba4f3f62003-12-10 18:06:47 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattner5e761402002-09-10 05:24:05 +000031namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000032 Statistic<> NumRemoved ("indvars", "Number of aux indvars removed");
Chris Lattner3adf51d2003-09-10 05:24:46 +000033 Statistic<> NumInserted("indvars", "Number of canonical indvars added");
Chris Lattner5e761402002-09-10 05:24:05 +000034}
Chris Lattner394437f2001-12-04 04:32:29 +000035
36// InsertCast - Cast Val to Ty, setting a useful name on the cast if Val has a
37// name...
38//
Chris Lattner5e761402002-09-10 05:24:05 +000039static Instruction *InsertCast(Value *Val, const Type *Ty,
Chris Lattner2a7c23e2002-09-10 17:04:02 +000040 Instruction *InsertBefore) {
41 return new CastInst(Val, Ty, Val->getName()+"-casted", InsertBefore);
Chris Lattner394437f2001-12-04 04:32:29 +000042}
43
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000044static bool TransformLoop(LoopInfo *Loops, Loop *Loop) {
Chris Lattner6148c022001-12-03 17:28:42 +000045 // Transform all subloops before this loop...
46 bool Changed = reduce_apply_bool(Loop->getSubLoops().begin(),
47 Loop->getSubLoops().end(),
Chris Lattner697954c2002-01-20 22:54:45 +000048 std::bind1st(std::ptr_fun(TransformLoop), Loops));
Chris Lattner6148c022001-12-03 17:28:42 +000049 // Get the header node for this loop. All of the phi nodes that could be
50 // induction variables must live in this basic block.
Chris Lattner3dec1f22002-05-10 15:38:35 +000051 //
Chris Lattner3adf51d2003-09-10 05:24:46 +000052 BasicBlock *Header = Loop->getHeader();
Chris Lattner6148c022001-12-03 17:28:42 +000053
54 // Loop over all of the PHI nodes in the basic block, calculating the
55 // induction variables that they represent... stuffing the induction variable
56 // info into a vector...
57 //
Chris Lattner697954c2002-01-20 22:54:45 +000058 std::vector<InductionVariable> IndVars; // Induction variables for block
Chris Lattner7e708292002-06-25 16:13:24 +000059 BasicBlock::iterator AfterPHIIt = Header->begin();
Chris Lattnere408e252003-04-23 16:37:45 +000060 for (; PHINode *PN = dyn_cast<PHINode>(AfterPHIIt); ++AfterPHIIt)
Chris Lattner6148c022001-12-03 17:28:42 +000061 IndVars.push_back(InductionVariable(PN, Loops));
Misha Brukmancf00c4a2003-10-10 17:57:28 +000062 // AfterPHIIt now points to first non-phi instruction...
Chris Lattner6148c022001-12-03 17:28:42 +000063
Chris Lattner394437f2001-12-04 04:32:29 +000064 // If there are no phi nodes in this basic block, there can't be indvars...
Chris Lattner6148c022001-12-03 17:28:42 +000065 if (IndVars.empty()) return Changed;
66
Chris Lattner3adf51d2003-09-10 05:24:46 +000067 // Loop over the induction variables, looking for a canonical induction
Chris Lattner6148c022001-12-03 17:28:42 +000068 // variable, and checking to make sure they are not all unknown induction
69 // variables.
70 //
71 bool FoundIndVars = false;
Chris Lattner3adf51d2003-09-10 05:24:46 +000072 InductionVariable *Canonical = 0;
Chris Lattner6148c022001-12-03 17:28:42 +000073 for (unsigned i = 0; i < IndVars.size(); ++i) {
Chris Lattner3adf51d2003-09-10 05:24:46 +000074 if (IndVars[i].InductionType == InductionVariable::Canonical &&
Chris Lattner5e761402002-09-10 05:24:05 +000075 !isa<PointerType>(IndVars[i].Phi->getType()))
Chris Lattner3adf51d2003-09-10 05:24:46 +000076 Canonical = &IndVars[i];
Chris Lattner6148c022001-12-03 17:28:42 +000077 if (IndVars[i].InductionType != InductionVariable::Unknown)
78 FoundIndVars = true;
79 }
80
Chris Lattner3adf51d2003-09-10 05:24:46 +000081 // No induction variables, bail early... don't add a canonical indvar
Chris Lattner6148c022001-12-03 17:28:42 +000082 if (!FoundIndVars) return Changed;
83
Chris Lattner3adf51d2003-09-10 05:24:46 +000084 // Okay, we want to convert other induction variables to use a canonical
Chris Lattner6148c022001-12-03 17:28:42 +000085 // indvar. If we don't have one, add one now...
Chris Lattner3adf51d2003-09-10 05:24:46 +000086 if (!Canonical) {
Chris Lattner2a7c23e2002-09-10 17:04:02 +000087 // Create the PHI node for the new induction variable, and insert the phi
Chris Lattner332ae7f2003-09-23 20:26:48 +000088 // node at the start of the PHI nodes...
89 PHINode *PN = new PHINode(Type::UIntTy, "cann-indvar", Header->begin());
Chris Lattner394437f2001-12-04 04:32:29 +000090
91 // Create the increment instruction to add one to the counter...
92 Instruction *Add = BinaryOperator::create(Instruction::Add, PN,
93 ConstantUInt::get(Type::UIntTy,1),
Chris Lattner2a7c23e2002-09-10 17:04:02 +000094 "add1-indvar", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +000095
96 // Figure out which block is incoming and which is the backedge for the loop
97 BasicBlock *Incoming, *BackEdgeBlock;
Chris Lattner455889a2002-02-12 22:39:50 +000098 pred_iterator PI = pred_begin(Header);
99 assert(PI != pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000100 if (Loop->contains(*PI)) { // First pred is back edge...
101 BackEdgeBlock = *PI++;
102 Incoming = *PI++;
103 } else {
104 Incoming = *PI++;
105 BackEdgeBlock = *PI++;
106 }
Chris Lattner455889a2002-02-12 22:39:50 +0000107 assert(PI == pred_end(Header) && "Loop headers should have 2 preds!");
Chris Lattner394437f2001-12-04 04:32:29 +0000108
109 // Add incoming values for the PHI node...
Chris Lattner1a18b7c2002-04-27 02:25:14 +0000110 PN->addIncoming(Constant::getNullValue(Type::UIntTy), Incoming);
Chris Lattner394437f2001-12-04 04:32:29 +0000111 PN->addIncoming(Add, BackEdgeBlock);
112
113 // Analyze the new induction variable...
114 IndVars.push_back(InductionVariable(PN, Loops));
Chris Lattner3adf51d2003-09-10 05:24:46 +0000115 assert(IndVars.back().InductionType == InductionVariable::Canonical &&
116 "Just inserted canonical indvar that is not canonical!");
117 Canonical = &IndVars.back();
Chris Lattner3dec1f22002-05-10 15:38:35 +0000118 ++NumInserted;
Chris Lattner4753bf22001-12-05 19:41:33 +0000119 Changed = true;
Chris Lattner332ae7f2003-09-23 20:26:48 +0000120 } else {
121 // If we have a canonical induction variable, make sure that it is the first
122 // one in the basic block.
123 if (&Header->front() != Canonical->Phi)
124 Header->getInstList().splice(Header->begin(), Header->getInstList(),
125 Canonical->Phi);
Chris Lattner394437f2001-12-04 04:32:29 +0000126 }
127
Anand Shukla5ba99bd2002-06-25 21:07:58 +0000128 DEBUG(std::cerr << "Induction variables:\n");
Chris Lattner394437f2001-12-04 04:32:29 +0000129
130 // Get the current loop iteration count, which is always the value of the
Chris Lattner3adf51d2003-09-10 05:24:46 +0000131 // canonical phi node...
Chris Lattner394437f2001-12-04 04:32:29 +0000132 //
Chris Lattner3adf51d2003-09-10 05:24:46 +0000133 PHINode *IterCount = Canonical->Phi;
Chris Lattner394437f2001-12-04 04:32:29 +0000134
Chris Lattner3adf51d2003-09-10 05:24:46 +0000135 // Loop through and replace all of the auxiliary induction variables with
136 // references to the canonical induction variable...
Chris Lattner394437f2001-12-04 04:32:29 +0000137 //
Chris Lattner394437f2001-12-04 04:32:29 +0000138 for (unsigned i = 0; i < IndVars.size(); ++i) {
139 InductionVariable *IV = &IndVars[i];
Chris Lattnerf016ea42002-05-22 17:17:27 +0000140
Chris Lattnera59cbb22002-07-27 01:12:17 +0000141 DEBUG(IV->print(std::cerr));
Chris Lattnerf016ea42002-05-22 17:17:27 +0000142
Chris Lattner88369d22003-12-10 20:43:04 +0000143 while (isa<PHINode>(AfterPHIIt)) ++AfterPHIIt;
144
Chris Lattner5e761402002-09-10 05:24:05 +0000145 // Don't do math with pointers...
146 const Type *IVTy = IV->Phi->getType();
147 if (isa<PointerType>(IVTy)) IVTy = Type::ULongTy;
148
Chris Lattner3adf51d2003-09-10 05:24:46 +0000149 // Don't modify the canonical indvar or unrecognized indvars...
150 if (IV != Canonical && IV->InductionType != InductionVariable::Unknown) {
Chris Lattner394437f2001-12-04 04:32:29 +0000151 Instruction *Val = IterCount;
152 if (!isa<ConstantInt>(IV->Step) || // If the step != 1
153 !cast<ConstantInt>(IV->Step)->equalsInt(1)) {
Chris Lattner394437f2001-12-04 04:32:29 +0000154
155 // If the types are not compatible, insert a cast now...
Chris Lattner5e761402002-09-10 05:24:05 +0000156 if (Val->getType() != IVTy)
157 Val = InsertCast(Val, IVTy, AfterPHIIt);
158 if (IV->Step->getType() != IVTy)
159 IV->Step = InsertCast(IV->Step, IVTy, AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000160
Chris Lattner5e761402002-09-10 05:24:05 +0000161 Val = BinaryOperator::create(Instruction::Mul, Val, IV->Step,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000162 IV->Phi->getName()+"-scale", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000163 }
164
Chris Lattner5e761402002-09-10 05:24:05 +0000165 // If the start != 0
166 if (IV->Start != Constant::getNullValue(IV->Start->getType())) {
Chris Lattner394437f2001-12-04 04:32:29 +0000167 // If the types are not compatible, insert a cast now...
Chris Lattner5e761402002-09-10 05:24:05 +0000168 if (Val->getType() != IVTy)
169 Val = InsertCast(Val, IVTy, AfterPHIIt);
170 if (IV->Start->getType() != IVTy)
171 IV->Start = InsertCast(IV->Start, IVTy, AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000172
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000173 // Insert the instruction after the phi nodes...
Chris Lattner5e761402002-09-10 05:24:05 +0000174 Val = BinaryOperator::create(Instruction::Add, Val, IV->Start,
Chris Lattner2a7c23e2002-09-10 17:04:02 +0000175 IV->Phi->getName()+"-offset", AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000176 }
177
178 // If the PHI node has a different type than val is, insert a cast now...
179 if (Val->getType() != IV->Phi->getType())
Chris Lattner7e708292002-06-25 16:13:24 +0000180 Val = InsertCast(Val, IV->Phi->getType(), AfterPHIIt);
Chris Lattner394437f2001-12-04 04:32:29 +0000181
182 // Replace all uses of the old PHI node with the new computed value...
183 IV->Phi->replaceAllUsesWith(Val);
184
185 // Move the PHI name to it's new equivalent value...
Chris Lattner697954c2002-01-20 22:54:45 +0000186 std::string OldName = IV->Phi->getName();
Chris Lattner394437f2001-12-04 04:32:29 +0000187 IV->Phi->setName("");
188 Val->setName(OldName);
189
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000190 // Get the incoming values used by the PHI node
191 std::vector<Value*> PHIOps;
192 PHIOps.reserve(IV->Phi->getNumIncomingValues());
193 for (unsigned i = 0, e = IV->Phi->getNumIncomingValues(); i != e; ++i)
194 PHIOps.push_back(IV->Phi->getIncomingValue(i));
195
Chris Lattner394437f2001-12-04 04:32:29 +0000196 // Delete the old, now unused, phi node...
Chris Lattner7e708292002-06-25 16:13:24 +0000197 Header->getInstList().erase(IV->Phi);
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000198
199 // If the PHI is the last user of any instructions for computing PHI nodes
200 // that are irrelevant now, delete those instructions.
201 while (!PHIOps.empty()) {
202 Instruction *MaybeDead = dyn_cast<Instruction>(PHIOps.back());
203 PHIOps.pop_back();
204
205 if (MaybeDead && isInstructionTriviallyDead(MaybeDead)) {
206 PHIOps.insert(PHIOps.end(), MaybeDead->op_begin(),
207 MaybeDead->op_end());
208 MaybeDead->getParent()->getInstList().erase(MaybeDead);
Chris Lattner88369d22003-12-10 20:43:04 +0000209
210 // Erasing the instruction could invalidate the AfterPHI iterator!
211 AfterPHIIt = Header->begin();
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000212 }
213 }
214
Chris Lattner4753bf22001-12-05 19:41:33 +0000215 Changed = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000216 ++NumRemoved;
Chris Lattner394437f2001-12-04 04:32:29 +0000217 }
Chris Lattner6148c022001-12-03 17:28:42 +0000218 }
219
220 return Changed;
221}
222
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000223namespace {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000224 struct InductionVariableSimplify : public FunctionPass {
Chris Lattner7e708292002-06-25 16:13:24 +0000225 virtual bool runOnFunction(Function &) {
Chris Lattner3dec1f22002-05-10 15:38:35 +0000226 LoopInfo &LI = getAnalysis<LoopInfo>();
227
228 // Induction Variables live in the header nodes of loops
229 return reduce_apply_bool(LI.getTopLevelLoops().begin(),
230 LI.getTopLevelLoops().end(),
231 std::bind1st(std::ptr_fun(TransformLoop), &LI));
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000232 }
233
Chris Lattnerf57b8452002-04-27 06:56:12 +0000234 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner5f0eb8d2002-08-08 19:01:30 +0000235 AU.addRequired<LoopInfo>();
Chris Lattner98bf4362003-10-12 21:52:28 +0000236 AU.addRequiredID(LoopSimplifyID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000237 AU.setPreservesCFG();
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000238 }
239 };
Chris Lattnera6275cc2002-07-26 21:12:46 +0000240 RegisterOpt<InductionVariableSimplify> X("indvars",
Chris Lattner3adf51d2003-09-10 05:24:46 +0000241 "Canonicalize Induction Variables");
Chris Lattner793c6b82002-01-31 00:45:11 +0000242}
243
Chris Lattnerba4f3f62003-12-10 18:06:47 +0000244Pass *llvm::createIndVarSimplifyPass() {
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000245 return new InductionVariableSimplify();
Chris Lattner793c6b82002-01-31 00:45:11 +0000246}
Brian Gaeked0fde302003-11-11 22:41:34 +0000247