blob: 19e8840320cfc3512b6eadf252ee437241379ca5 [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
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//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000029#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000030#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000032#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000033#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000034#include <set>
35using namespace llvm;
36
37namespace {
38 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000039 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Nate Begemanb18121e2004-10-18 21:08:22 +000040
Chris Lattner430d0022005-08-03 22:21:05 +000041 /// IVStrideUse - Keep track of one use of a strided induction variable, where
42 /// the stride is stored externally. The Offset member keeps track of the
43 /// offset from the IV, User is the actual user of the operand, and 'Operand'
44 /// is the operand # of the User that is the use.
45 struct IVStrideUse {
46 SCEVHandle Offset;
47 Instruction *User;
48 Value *OperandValToReplace;
49
50 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
51 : Offset(Offs), User(U), OperandValToReplace(O) {}
52 };
53
54 /// IVUsersOfOneStride - This structure keeps track of all instructions that
55 /// have an operand that is based on the trip count multiplied by some stride.
56 /// The stride for all of these users is common and kept external to this
57 /// structure.
58 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000059 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000060 /// initial value and the operand that uses the IV.
61 std::vector<IVStrideUse> Users;
62
63 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
64 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000065 }
66 };
67
68
Nate Begemanb18121e2004-10-18 21:08:22 +000069 class LoopStrengthReduce : public FunctionPass {
70 LoopInfo *LI;
71 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000072 ScalarEvolution *SE;
73 const TargetData *TD;
74 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000075 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000076
77 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
78 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000079 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000080
81 /// IVUsesByStride - Keep track of all uses of induction variables that we
82 /// are interested in. The key of the map is the stride of the access.
Chris Lattner430d0022005-08-03 22:21:05 +000083 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000084
Chris Lattner6f286b72005-08-04 01:19:13 +000085 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
86 /// of the casted version of each value. This is accessed by
87 /// getCastedVersionOf.
88 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +000089
90 /// DeadInsts - Keep track of instructions we may have made dead, so that
91 /// we can remove them after we are done working.
92 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +000093 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +000094 LoopStrengthReduce(unsigned MTAMS = 1)
95 : MaxTargetAMSize(MTAMS) {
96 }
97
Nate Begemanb18121e2004-10-18 21:08:22 +000098 virtual bool runOnFunction(Function &) {
99 LI = &getAnalysis<LoopInfo>();
100 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000101 SE = &getAnalysis<ScalarEvolution>();
102 TD = &getAnalysis<TargetData>();
103 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000104 Changed = false;
105
106 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
107 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000108
Nate Begemanb18121e2004-10-18 21:08:22 +0000109 return Changed;
110 }
111
112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000114 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000115 AU.addRequired<LoopInfo>();
116 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000117 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000118 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000119 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000120
121 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
122 ///
123 Value *getCastedVersionOf(Value *V);
124private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000125 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000126 bool AddUsersIfInteresting(Instruction *I, Loop *L,
127 std::set<Instruction*> &Processed);
128 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
129
Nate Begemane68bcd12005-07-30 00:15:07 +0000130
Chris Lattner430d0022005-08-03 22:21:05 +0000131 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
132 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000133 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
134 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000135 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000136 "Strength Reduce GEP Uses of Ind. Vars");
137}
138
Jeff Cohena2c59b72005-03-04 04:04:26 +0000139FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
140 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000141}
142
Chris Lattner6f286b72005-08-04 01:19:13 +0000143/// getCastedVersionOf - Return the specified value casted to uintptr_t.
144///
145Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
146 if (V->getType() == UIntPtrTy) return V;
147 if (Constant *CB = dyn_cast<Constant>(V))
148 return ConstantExpr::getCast(CB, UIntPtrTy);
149
150 Value *&New = CastedPointers[V];
151 if (New) return New;
152
153 BasicBlock::iterator InsertPt;
154 if (Argument *Arg = dyn_cast<Argument>(V)) {
155 // Insert into the entry of the function, after any allocas.
156 InsertPt = Arg->getParent()->begin()->begin();
157 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
158 } else {
159 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
160 InsertPt = II->getNormalDest()->begin();
161 } else {
162 InsertPt = cast<Instruction>(V);
163 ++InsertPt;
164 }
165
166 // Do not insert casts into the middle of PHI node blocks.
167 while (isa<PHINode>(InsertPt)) ++InsertPt;
168 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000169
170 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
171 DeadInsts.insert(cast<Instruction>(New));
172 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000173}
174
175
Nate Begemanb18121e2004-10-18 21:08:22 +0000176/// DeleteTriviallyDeadInstructions - If any of the instructions is the
177/// specified set are trivially dead, delete them and see if this makes any of
178/// their operands subsequently dead.
179void LoopStrengthReduce::
180DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
181 while (!Insts.empty()) {
182 Instruction *I = *Insts.begin();
183 Insts.erase(Insts.begin());
184 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000185 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
186 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
187 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000188 SE->deleteInstructionFromRecords(I);
189 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000190 Changed = true;
191 }
192 }
193}
194
Jeff Cohen39751c32005-02-27 19:37:07 +0000195
Chris Lattnereaf24722005-08-04 17:40:30 +0000196/// GetExpressionSCEV - Compute and return the SCEV for the specified
197/// instruction.
198SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
199 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
200 if (!GEP)
201 return SE->getSCEV(Exp);
202
Nate Begemane68bcd12005-07-30 00:15:07 +0000203 // Analyze all of the subscripts of this getelementptr instruction, looking
204 // for uses that are determined by the trip count of L. First, skip all
205 // operands the are not dependent on the IV.
206
207 // Build up the base expression. Insert an LLVM cast of the pointer to
208 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000209 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000210
211 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000212
213 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000214 // If this is a use of a recurrence that we can analyze, and it comes before
215 // Op does in the GEP operand list, we will handle this when we process this
216 // operand.
217 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
218 const StructLayout *SL = TD->getStructLayout(STy);
219 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
220 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000221 GEPVal = SCEVAddExpr::get(GEPVal,
222 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000223 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000224 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
225 SCEVHandle Idx = SE->getSCEV(OpVal);
226
Chris Lattnereaf24722005-08-04 17:40:30 +0000227 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
228 if (TypeSize != 1)
229 Idx = SCEVMulExpr::get(Idx,
230 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
231 TypeSize)));
232 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000233 }
234 }
235
Chris Lattnereaf24722005-08-04 17:40:30 +0000236 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000237}
238
Chris Lattneracc42c42005-08-04 19:08:16 +0000239/// getSCEVStartAndStride - Compute the start and stride of this expression,
240/// returning false if the expression is not a start/stride pair, or true if it
241/// is. The stride must be a loop invariant expression, but the start may be
242/// a mix of loop invariant and loop variant expressions.
243static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
244 SCEVHandle &Start, Value *&Stride) {
245 SCEVHandle TheAddRec = Start; // Initialize to zero.
246
247 // If the outer level is an AddExpr, the operands are all start values except
248 // for a nested AddRecExpr.
249 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
250 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
251 if (SCEVAddRecExpr *AddRec =
252 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
253 if (AddRec->getLoop() == L)
254 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
255 else
256 return false; // Nested IV of some sort?
257 } else {
258 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
259 }
260
261 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
262 TheAddRec = SH;
263 } else {
264 return false; // not analyzable.
265 }
266
267 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
268 if (!AddRec || AddRec->getLoop() != L) return false;
269
270 // FIXME: Generalize to non-affine IV's.
271 if (!AddRec->isAffine()) return false;
272
273 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
274
275 // FIXME: generalize to IV's with more complex strides (must emit stride
276 // expression outside of loop!)
277 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
278 return false;
279
280 SCEVConstant *StrideC = cast<SCEVConstant>(AddRec->getOperand(1));
281 Stride = StrideC->getValue();
282
283 assert(Stride->getType()->isUnsigned() &&
284 "Constants should be canonicalized to unsigned!");
285 return true;
286}
287
Nate Begemane68bcd12005-07-30 00:15:07 +0000288/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
289/// reducible SCEV, recursively add its users to the IVUsesByStride set and
290/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000291bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
292 std::set<Instruction*> &Processed) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000293 if (I->getType() == Type::VoidTy) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000294 if (!Processed.insert(I).second)
295 return true; // Instruction already handled.
296
Chris Lattneracc42c42005-08-04 19:08:16 +0000297 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000298 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000299 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000300
Chris Lattneracc42c42005-08-04 19:08:16 +0000301 // Get the start and stride for this expression.
302 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
303 Value *Stride = 0;
304 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
305 return false; // Non-reducible symbolic expression, bail out.
306
Nate Begemane68bcd12005-07-30 00:15:07 +0000307 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
308 Instruction *User = cast<Instruction>(*UI);
309
310 // Do not infinitely recurse on PHI nodes.
311 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
312 continue;
313
314 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000315 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000316 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000317 if (LI->getLoopFor(User->getParent()) != L) {
318 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
319 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000320 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000321 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000322 DEBUG(std::cerr << "FOUND USER: " << *User
323 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000324 AddUserToIVUsers = true;
325 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000326
Chris Lattneracc42c42005-08-04 19:08:16 +0000327 if (AddUserToIVUsers) {
Chris Lattner65107492005-08-04 00:40:47 +0000328 // Okay, we found a user that we cannot reduce. Analyze the instruction
329 // and decide what to do with it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000330 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begemane68bcd12005-07-30 00:15:07 +0000331 }
332 }
333 return true;
334}
335
336namespace {
337 /// BasedUser - For a particular base value, keep information about how we've
338 /// partitioned the expression so far.
339 struct BasedUser {
340 /// Inst - The instruction using the induction variable.
341 Instruction *Inst;
342
Chris Lattner430d0022005-08-03 22:21:05 +0000343 /// OperandValToReplace - The operand value of Inst to replace with the
344 /// EmittedBase.
345 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000346
347 /// Imm - The immediate value that should be added to the base immediately
348 /// before Inst, because it will be folded into the imm field of the
349 /// instruction.
350 SCEVHandle Imm;
351
352 /// EmittedBase - The actual value* to use for the base value of this
353 /// operation. This is null if we should just use zero so far.
354 Value *EmittedBase;
355
Chris Lattner430d0022005-08-03 22:21:05 +0000356 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM)
357 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000358
Chris Lattnera6d7c352005-08-04 20:03:32 +0000359 // Once we rewrite the code to insert the new IVs we want, update the
360 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
361 // to it.
362 void RewriteInstructionToUseNewBase(Value *NewBase, SCEVExpander &Rewriter);
Nate Begemane68bcd12005-07-30 00:15:07 +0000363
364 // No need to compare these.
365 bool operator<(const BasedUser &BU) const { return 0; }
366
367 void dump() const;
368 };
369}
370
371void BasedUser::dump() const {
372 std::cerr << " Imm=" << *Imm;
373 if (EmittedBase)
374 std::cerr << " EB=" << *EmittedBase;
375
376 std::cerr << " Inst: " << *Inst;
377}
378
Chris Lattnera6d7c352005-08-04 20:03:32 +0000379// Once we rewrite the code to insert the new IVs we want, update the
380// operands of Inst to use the new expression 'NewBase', with 'Imm' added
381// to it.
382void BasedUser::RewriteInstructionToUseNewBase(Value *NewBase,
383 SCEVExpander &Rewriter) {
384 if (!isa<PHINode>(Inst)) {
385 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm);
386 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
387 OperandValToReplace->getType());
388
389 // Replace the use of the operand Value with the new Phi we just created.
390 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
391 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
392 return;
393 }
394
395 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
396 // expression into each operand block that uses it.
397 PHINode *PN = cast<PHINode>(Inst);
398 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
399 if (PN->getIncomingValue(i) == OperandValToReplace) {
400 // FIXME: this should split any critical edges.
401
402 // Insert the code into the end of the predecessor block.
403 BasicBlock::iterator InsertPt = PN->getIncomingBlock(i)->getTerminator();
404
405 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm);
406 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
407 OperandValToReplace->getType());
408
409 // Replace the use of the operand Value with the new Phi we just created.
410 PN->setIncomingValue(i, NewVal);
411 Rewriter.clear();
412 }
413 }
414 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
415}
416
417
Nate Begemane68bcd12005-07-30 00:15:07 +0000418/// isTargetConstant - Return true if the following can be referenced by the
419/// immediate field of a target instruction.
420static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000421
Nate Begemane68bcd12005-07-30 00:15:07 +0000422 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
423 if (isa<SCEVConstant>(V)) return true;
Jeff Cohen546fd592005-07-30 18:33:25 +0000424
Nate Begemane68bcd12005-07-30 00:15:07 +0000425 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000426
Nate Begemane68bcd12005-07-30 00:15:07 +0000427 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
429 if (CE->getOpcode() == Instruction::Cast)
430 if (isa<GlobalValue>(CE->getOperand(0)))
431 // FIXME: should check to see that the dest is uintptr_t!
432 return true;
433 return false;
434}
435
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000436/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000437/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000438/// Accumulate these immediate values into the Imm value.
439static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
440 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000441 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000442 std::vector<SCEVHandle> NewOps;
443 NewOps.reserve(SAE->getNumOperands());
444
445 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattneracc42c42005-08-04 19:08:16 +0000446 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
447 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
448 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
449 // If this is a loop-variant expression, it must stay in the immediate
450 // field of the expression.
451 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000452 } else {
453 NewOps.push_back(SAE->getOperand(i));
Nate Begemane68bcd12005-07-30 00:15:07 +0000454 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000455
456 if (NewOps.empty())
457 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
458 else
459 Val = SCEVAddExpr::get(NewOps);
460 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000461 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
462 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000463 SCEVHandle Start = SARE->getStart();
464 MoveImmediateValues(Start, Imm, isAddress, L);
465
466 if (Start != SARE->getStart()) {
467 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
468 Ops[0] = Start;
469 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
470 }
471 return;
Nate Begemane68bcd12005-07-30 00:15:07 +0000472 }
473
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000474 // Loop-variant expressions must stay in the immediate field of the
475 // expression.
476 if ((isAddress && isTargetConstant(Val)) ||
477 !Val->isLoopInvariant(L)) {
478 Imm = SCEVAddExpr::get(Imm, Val);
479 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
480 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000481 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000482
483 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000484}
485
486/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
487/// stride of IV. All of the users may have different starting values, and this
488/// may not be the only stride (we know it is if isOnlyStride is true).
489void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000490 IVUsersOfOneStride &Uses,
491 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000492 bool isOnlyStride) {
493 // Transform our list of users and offsets to a bit more complex table. In
494 // this new vector, the first entry for each element is the base of the
495 // strided access, and the second is the BasedUser object for the use. We
496 // progressively move information from the first to the second entry, until we
497 // eventually emit the object.
498 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
499 UsersToProcess.reserve(Uses.Users.size());
Jeff Cohen546fd592005-07-30 18:33:25 +0000500
501 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
Chris Lattner430d0022005-08-03 22:21:05 +0000502 Uses.Users[0].Offset->getType());
Nate Begemane68bcd12005-07-30 00:15:07 +0000503
504 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
Chris Lattner430d0022005-08-03 22:21:05 +0000505 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
506 BasedUser(Uses.Users[i].User,
507 Uses.Users[i].OperandValToReplace,
Nate Begemane68bcd12005-07-30 00:15:07 +0000508 ZeroBase)));
509
510 // First pass, figure out what we can represent in the immediate fields of
511 // instructions. If we can represent anything there, move it to the imm
512 // fields of the BasedUsers.
513 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000514 // Addressing modes can be folded into loads and stores. Be careful that
515 // the store is through the expression, not of the expression though.
516 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst);
517 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].second.Inst))
518 if (SI->getOperand(1) == UsersToProcess[i].second.OperandValToReplace)
519 isAddress = true;
520
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000521 MoveImmediateValues(UsersToProcess[i].first, UsersToProcess[i].second.Imm,
522 isAddress, L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000523
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000524 assert(UsersToProcess[i].first->isLoopInvariant(L) &&
525 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000526 }
527
528 SCEVExpander Rewriter(*SE, *LI);
529 BasicBlock *Preheader = L->getLoopPreheader();
530 Instruction *PreInsertPt = Preheader->getTerminator();
531 Instruction *PhiInsertBefore = L->getHeader()->begin();
532
Jeff Cohen546fd592005-07-30 18:33:25 +0000533 assert(isa<PHINode>(PhiInsertBefore) &&
Nate Begemane68bcd12005-07-30 00:15:07 +0000534 "How could this loop have IV's without any phis?");
535 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
536 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
537 "This loop isn't canonicalized right");
538 BasicBlock *LatchBlock =
539 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Jeff Cohen546fd592005-07-30 18:33:25 +0000540
Chris Lattnerbb78c972005-08-03 23:30:08 +0000541 DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
542
Nate Begemane68bcd12005-07-30 00:15:07 +0000543 // FIXME: This loop needs increasing levels of intelligence.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000544 // STAGE 0: just emit everything as its own base.
Nate Begemane68bcd12005-07-30 00:15:07 +0000545 // STAGE 1: factor out common vars from bases, and try and push resulting
Chris Lattnerdb23c742005-08-03 22:51:21 +0000546 // constants into Imm field. <-- We are here
Nate Begemane68bcd12005-07-30 00:15:07 +0000547 // STAGE 2: factor out large constants to try and make more constants
548 // acceptable for target loads and stores.
Nate Begemane68bcd12005-07-30 00:15:07 +0000549
Chris Lattnerdb23c742005-08-03 22:51:21 +0000550 // Sort by the base value, so that all IVs with identical bases are next to
551 // each other.
552 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000553 while (!UsersToProcess.empty()) {
Chris Lattnerdb23c742005-08-03 22:51:21 +0000554 SCEVHandle Base = UsersToProcess.front().first;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000555
556 DEBUG(std::cerr << " INSERTING PHI with BASE = " << *Base << ":\n");
557
Nate Begemane68bcd12005-07-30 00:15:07 +0000558 // Create a new Phi for this base, and stick it in the loop header.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000559 const Type *ReplacedTy = Base->getType();
560 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000561 ++NumInserted;
Nate Begemane68bcd12005-07-30 00:15:07 +0000562
Jeff Cohen546fd592005-07-30 18:33:25 +0000563 // Emit the initial base value into the loop preheader, and add it to the
Nate Begemane68bcd12005-07-30 00:15:07 +0000564 // Phi node.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000565 Value *BaseV = Rewriter.expandCodeFor(Base, PreInsertPt, ReplacedTy);
Nate Begemane68bcd12005-07-30 00:15:07 +0000566 NewPHI->addIncoming(BaseV, Preheader);
567
568 // Emit the increment of the base value before the terminator of the loop
569 // latch block, and add it to the Phi node.
570 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
571 SCEVUnknown::get(Stride));
572
573 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
574 ReplacedTy);
575 IncV->setName(NewPHI->getName()+".inc");
576 NewPHI->addIncoming(IncV, LatchBlock);
577
578 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000579 // the instructions that we identified as using this stride and base.
580 while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
581 BasedUser &User = UsersToProcess.front().second;
Jeff Cohen546fd592005-07-30 18:33:25 +0000582
Chris Lattnerdb23c742005-08-03 22:51:21 +0000583 // Clear the SCEVExpander's expression map so that we are guaranteed
584 // to have the code emitted where we expect it.
585 Rewriter.clear();
Chris Lattnera6d7c352005-08-04 20:03:32 +0000586
587 // Now that we know what we need to do, insert code before User for the
588 // immediate and any loop-variant expressions.
589 User.RewriteInstructionToUseNewBase(NewPHI, Rewriter);
Jeff Cohen546fd592005-07-30 18:33:25 +0000590
Chris Lattnerdb23c742005-08-03 22:51:21 +0000591 // Mark old value we replaced as possibly dead, so that it is elminated
592 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000593 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000594
Chris Lattnerdb23c742005-08-03 22:51:21 +0000595 UsersToProcess.erase(UsersToProcess.begin());
596 ++NumReduced;
597 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000598 // TODO: Next, find out which base index is the most common, pull it out.
599 }
600
601 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
602 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +0000603}
604
605
Nate Begemanb18121e2004-10-18 21:08:22 +0000606void LoopStrengthReduce::runOnLoop(Loop *L) {
607 // First step, transform all loops nesting inside of this loop.
608 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
609 runOnLoop(*I);
610
Nate Begemane68bcd12005-07-30 00:15:07 +0000611 // Next, find all uses of induction variables in this loop, and catagorize
612 // them by stride. Start by finding all of the PHI nodes in the header for
613 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +0000614 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +0000615 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +0000616 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +0000617
Nate Begemane68bcd12005-07-30 00:15:07 +0000618 // If we have nothing to do, return.
619 //if (IVUsesByStride.empty()) return;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000620
Nate Begemane68bcd12005-07-30 00:15:07 +0000621 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
622 // doing computation in byte values, promote to 32-bit values if safe.
623
624 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
625 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
626 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
627 // to be careful that IV's are all the same type. Only works for intptr_t
628 // indvars.
629
630 // If we only have one stride, we can more aggressively eliminate some things.
631 bool HasOneStride = IVUsesByStride.size() == 1;
632
Chris Lattner430d0022005-08-03 22:21:05 +0000633 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
634 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000635 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000636
637 // Clean up after ourselves
638 if (!DeadInsts.empty()) {
639 DeleteTriviallyDeadInstructions(DeadInsts);
640
Nate Begemane68bcd12005-07-30 00:15:07 +0000641 BasicBlock::iterator I = L->getHeader()->begin();
642 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000643 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000644 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
645
Nate Begemane68bcd12005-07-30 00:15:07 +0000646 // At this point, we know that we have killed one or more GEP instructions.
647 // It is worth checking to see if the cann indvar is also dead, so that we
648 // can remove it as well. The requirements for the cann indvar to be
649 // considered dead are:
650 // 1. the cann indvar has one use
651 // 2. the use is an add instruction
652 // 3. the add has one use
653 // 4. the add is used by the cann indvar
654 // If all four cases above are true, then we can remove both the add and
655 // the cann indvar.
656 // FIXME: this needs to eliminate an induction variable even if it's being
657 // compared against some value to decide loop termination.
658 if (PN->hasOneUse()) {
659 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000660 if (BO && BO->hasOneUse()) {
661 if (PN == *(BO->use_begin())) {
662 DeadInsts.insert(BO);
663 // Break the cycle, then delete the PHI.
664 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000665 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000666 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000667 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000668 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000669 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000670 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000671 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000672 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000673
Chris Lattner11e7a5e2005-08-05 01:30:11 +0000674 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +0000675 IVUsesByStride.clear();
676 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000677}