blob: 56bc43e62f309976a052b40732921db777492cb6 [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
16// There are currently several deficiencies in the implementation, marked with
17// FIXME in the code.
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Constants.h"
23#include "llvm/Instructions.h"
24#include "llvm/Type.h"
25#include "llvm/Analysis/Dominators.h"
26#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Support/CFG.h"
28#include "llvm/Transforms/Utils/Local.h"
29#include "llvm/ADT/Statistic.h"
30#include <set>
31using namespace llvm;
32
33namespace {
34 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
35
36 class LoopStrengthReduce : public FunctionPass {
37 LoopInfo *LI;
38 DominatorSet *DS;
39 bool Changed;
40 public:
41 virtual bool runOnFunction(Function &) {
42 LI = &getAnalysis<LoopInfo>();
43 DS = &getAnalysis<DominatorSet>();
44 Changed = false;
45
46 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
47 runOnLoop(*I);
48 return Changed;
49 }
50
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +000053 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +000054 AU.addRequired<LoopInfo>();
55 AU.addRequired<DominatorSet>();
56 }
57 private:
58 void runOnLoop(Loop *L);
59 void strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L,
60 Instruction *InsertBefore,
61 std::set<Instruction*> &DeadInsts);
62 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
63 };
64 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
65 "Strength Reduce GEP Uses of Ind. Vars");
66}
67
68FunctionPass *llvm::createLoopStrengthReducePass() {
69 return new LoopStrengthReduce();
70}
71
72/// DeleteTriviallyDeadInstructions - If any of the instructions is the
73/// specified set are trivially dead, delete them and see if this makes any of
74/// their operands subsequently dead.
75void LoopStrengthReduce::
76DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
77 while (!Insts.empty()) {
78 Instruction *I = *Insts.begin();
79 Insts.erase(Insts.begin());
80 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +000081 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
82 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
83 Insts.insert(U);
Nate Begemanb18121e2004-10-18 21:08:22 +000084 I->getParent()->getInstList().erase(I);
85 Changed = true;
86 }
87 }
88}
89
90void LoopStrengthReduce::strengthReduceGEP(GetElementPtrInst *GEPI, Loop *L,
91 Instruction *InsertBefore,
92 std::set<Instruction*> &DeadInsts) {
93 // We will strength reduce the GEP by splitting it into two parts. The first
94 // is a GEP to hold the initial value of the non-strength-reduced GEP upon
95 // entering the loop, which we will insert at the end of the loop preheader.
96 // The second is a GEP to hold the incremented value of the initial GEP.
97 // The LoopIndVarSimplify pass guarantees that loop counts start at zero, so
98 // we will replace the indvar with a constant zero value to create the first
99 // GEP.
100 //
101 // We currently only handle GEP instructions that consist of zero or more
Jeff Cohenfd63d3a2005-02-27 21:08:04 +0000102 // constants or loop invariable expressions prior to an instance of the
103 // canonical induction variable.
Jeff Cohen39751c32005-02-27 19:37:07 +0000104 unsigned indvar = 0;
Nate Begemanb18121e2004-10-18 21:08:22 +0000105 std::vector<Value *> pre_op_vector;
106 std::vector<Value *> inc_op_vector;
107 Value *CanonicalIndVar = L->getCanonicalInductionVariable();
Jeff Cohen39751c32005-02-27 19:37:07 +0000108 BasicBlock *Header = L->getHeader();
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000109 BasicBlock *Preheader = L->getLoopPreheader();
110 bool AllConstantOperands = true;
Jeff Cohen39751c32005-02-27 19:37:07 +0000111
Nate Begemanb18121e2004-10-18 21:08:22 +0000112 for (unsigned op = 1, e = GEPI->getNumOperands(); op != e; ++op) {
113 Value *operand = GEPI->getOperand(op);
114 if (operand == CanonicalIndVar) {
Nate Begemanb18121e2004-10-18 21:08:22 +0000115 // FIXME: use getCanonicalInductionVariableIncrement to choose between
116 // one and neg one maybe? We need to support int *foo = GEP base, -1
117 const Type *Ty = CanonicalIndVar->getType();
118 pre_op_vector.push_back(Constant::getNullValue(Ty));
119 inc_op_vector.push_back(ConstantInt::get(Ty, 1));
Jeff Cohen39751c32005-02-27 19:37:07 +0000120 indvar = op;
121 break;
Nate Begemanb18121e2004-10-18 21:08:22 +0000122 } else if (isa<Constant>(operand)) {
123 pre_op_vector.push_back(operand);
Jeff Cohen39751c32005-02-27 19:37:07 +0000124 } else if (Instruction *inst = dyn_cast<Instruction>(operand)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000125 if (!DS->dominates(inst, Preheader->getTerminator()))
Jeff Cohen39751c32005-02-27 19:37:07 +0000126 return;
127 pre_op_vector.push_back(operand);
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000128 AllConstantOperands = false;
Nate Begemanb18121e2004-10-18 21:08:22 +0000129 } else
130 return;
131 }
Jeff Cohen39751c32005-02-27 19:37:07 +0000132 assert(indvar > 0 && "Indvar used by GEP not found in operand list");
Nate Begemanb18121e2004-10-18 21:08:22 +0000133
Jeff Cohen39751c32005-02-27 19:37:07 +0000134 // Ensure the pointer base is loop invariant. While strength reduction
135 // makes sense even if the pointer changed on every iteration, there is no
136 // realistic way of handling it unless GEPs were completely decomposed into
137 // their constituent operations so we have explicit multiplications to work
138 // with.
Nate Begemanb18121e2004-10-18 21:08:22 +0000139 if (Instruction *GepPtrOp = dyn_cast<Instruction>(GEPI->getOperand(0)))
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000140 if (!DS->dominates(GepPtrOp, Preheader->getTerminator()))
Nate Begemanb18121e2004-10-18 21:08:22 +0000141 return;
142
143 // If all operands of the GEP we are going to insert into the preheader
144 // are constants, generate a GEP ConstantExpr instead.
145 //
146 // If there is only one operand after the initial non-constant one, we know
147 // that it was the induction variable, and has been replaced by a constant
148 // null value. In this case, replace the GEP with a use of pointer directly.
Nate Begemanb18121e2004-10-18 21:08:22 +0000149 Value *PreGEP;
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000150 if (AllConstantOperands && isa<Constant>(GEPI->getOperand(0))) {
Nate Begemanb18121e2004-10-18 21:08:22 +0000151 Constant *C = dyn_cast<Constant>(GEPI->getOperand(0));
152 PreGEP = ConstantExpr::getGetElementPtr(C, pre_op_vector);
153 } else if (pre_op_vector.size() == 1) {
154 PreGEP = GEPI->getOperand(0);
155 } else {
156 PreGEP = new GetElementPtrInst(GEPI->getOperand(0),
Jeff Cohen39751c32005-02-27 19:37:07 +0000157 pre_op_vector, GEPI->getName()+".pre",
Nate Begemanb18121e2004-10-18 21:08:22 +0000158 Preheader->getTerminator());
159 }
160
161 // The next step of the strength reduction is to create a PHI that will choose
162 // between the initial GEP we created and inserted into the preheader, and
163 // the incremented GEP that we will create below and insert into the loop body
164 PHINode *NewPHI = new PHINode(PreGEP->getType(),
165 GEPI->getName()+".str", InsertBefore);
166 NewPHI->addIncoming(PreGEP, Preheader);
167
Jeff Cohen39751c32005-02-27 19:37:07 +0000168 // Now, create the GEP instruction to increment by one the value selected by
169 // the PHI instruction we just created above, and add it as the second
170 // incoming Value/BasicBlock pair to the PHINode. It is inserted before the
171 // increment of the canonical induction variable.
Nate Begemanb18121e2004-10-18 21:08:22 +0000172 Instruction *IncrInst =
173 const_cast<Instruction*>(L->getCanonicalInductionVariableIncrement());
174 GetElementPtrInst *StrGEP = new GetElementPtrInst(NewPHI, inc_op_vector,
175 GEPI->getName()+".inc",
176 IncrInst);
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000177 pred_iterator PI = pred_begin(Header);
178 if (*PI == Preheader)
179 ++PI;
180 NewPHI->addIncoming(StrGEP, *PI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000181
Jeff Cohen39751c32005-02-27 19:37:07 +0000182 if (GEPI->getNumOperands() - 1 == indvar) {
183 // If there were no operands following the induction variable, replace all
184 // uses of the old GEP instruction with the new PHI.
185 GEPI->replaceAllUsesWith(NewPHI);
186 } else {
187 // Create a new GEP instruction using the new PHI as the base. The
188 // operands of the original GEP past the induction variable become
189 // operands of this new GEP.
190 std::vector<Value *> op_vector;
191 const Type *Ty = CanonicalIndVar->getType();
192 op_vector.push_back(Constant::getNullValue(Ty));
193 for (unsigned op = indvar + 1; op < GEPI->getNumOperands(); op++)
194 op_vector.push_back(GEPI->getOperand(op));
195 GetElementPtrInst *newGEP = new GetElementPtrInst(NewPHI, op_vector,
196 GEPI->getName() + ".lsr",
197 GEPI);
198 GEPI->replaceAllUsesWith(newGEP);
199}
Nate Begemanb18121e2004-10-18 21:08:22 +0000200
201 // The old GEP is now dead.
202 DeadInsts.insert(GEPI);
203 ++NumReduced;
204}
205
206void LoopStrengthReduce::runOnLoop(Loop *L) {
207 // First step, transform all loops nesting inside of this loop.
208 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
209 runOnLoop(*I);
210
211 // Next, get the first PHINode since it is guaranteed to be the canonical
212 // induction variable for the loop by the preceding IndVarSimplify pass.
213 PHINode *PN = L->getCanonicalInductionVariable();
214 if (0 == PN)
215 return;
216
Nate Begemanb18121e2004-10-18 21:08:22 +0000217 // FIXME: Need to use SCEV to detect GEP uses of the indvar, since indvars
218 // pass creates code like this, which we can't currently detect:
219 // %tmp.1 = sub uint 2000, %indvar
220 // %tmp.8 = getelementptr int* %y, uint %tmp.1
221
Jeff Cohenfd63d3a2005-02-27 21:08:04 +0000222 // Strength reduce all GEPs in the Loop. Insert secondary PHI nodes for the
223 // strength reduced pointers we'll be creating after the canonical induction
224 // variable's PHI.
Nate Begemanb18121e2004-10-18 21:08:22 +0000225 std::set<Instruction*> DeadInsts;
226 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
227 UI != UE; ++UI)
228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI))
Jeff Cohenfd63d3a2005-02-27 21:08:04 +0000229 strengthReduceGEP(GEPI, L, PN->getNext(), DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000230
231 // Clean up after ourselves
232 if (!DeadInsts.empty()) {
233 DeleteTriviallyDeadInstructions(DeadInsts);
234
235 // At this point, we know that we have killed one or more GEP instructions.
236 // It is worth checking to see if the cann indvar is also dead, so that we
237 // can remove it as well. The requirements for the cann indvar to be
238 // considered dead are:
239 // 1. the cann indvar has one use
240 // 2. the use is an add instruction
241 // 3. the add has one use
242 // 4. the add is used by the cann indvar
243 // If all four cases above are true, then we can remove both the add and
244 // the cann indvar.
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000245 // FIXME: this needs to eliminate an induction variable even if it's being
246 // compared against some value to decide loop termination.
Nate Begemanb18121e2004-10-18 21:08:22 +0000247 if (PN->hasOneUse()) {
248 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
249 if (BO && BO->getOpcode() == Instruction::Add)
250 if (BO->hasOneUse()) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000251 if (PN == dyn_cast<PHINode>(*(BO->use_begin()))) {
Nate Begemanb18121e2004-10-18 21:08:22 +0000252 DeadInsts.insert(BO);
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000253 // Break the cycle, then delete the PHI.
254 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
255 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000256 DeleteTriviallyDeadInstructions(DeadInsts);
257 }
258 }
259 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000260 }
261}