blob: 7e894ca9dca169658f7a9cb1cb8187880a80aad4 [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"
Chris Lattner4fec86d2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Evan Chengc567c4e2006-03-13 23:14:23 +000034#include "llvm/Target/TargetLowering.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000035#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000036#include <iostream>
Nate Begemanb18121e2004-10-18 21:08:22 +000037#include <set>
38using namespace llvm;
39
40namespace {
41 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000042 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattneredff91a2005-08-10 00:45:21 +000043 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000044
Chris Lattner430d0022005-08-03 22:21:05 +000045 /// IVStrideUse - Keep track of one use of a strided induction variable, where
46 /// the stride is stored externally. The Offset member keeps track of the
47 /// offset from the IV, User is the actual user of the operand, and 'Operand'
48 /// is the operand # of the User that is the use.
49 struct IVStrideUse {
50 SCEVHandle Offset;
51 Instruction *User;
52 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000053
54 // isUseOfPostIncrementedValue - True if this should use the
55 // post-incremented version of this IV, not the preincremented version.
56 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000057 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000058 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000059
60 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000061 : Offset(Offs), User(U), OperandValToReplace(O),
62 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000063 };
64
65 /// IVUsersOfOneStride - This structure keeps track of all instructions that
66 /// have an operand that is based on the trip count multiplied by some stride.
67 /// The stride for all of these users is common and kept external to this
68 /// structure.
69 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000070 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000071 /// initial value and the operand that uses the IV.
72 std::vector<IVStrideUse> Users;
73
74 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
75 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000076 }
77 };
78
Evan Cheng3df447d2006-03-16 21:53:05 +000079 /// IVInfo - This structure keeps track of one IV expression inserted during
80 /// StrengthReduceStridedIVUsers. It contains the base value, as well as the
81 /// PHI node and increment value created for rewrite.
82 struct IVExpr {
83 SCEVHandle Base;
84 PHINode *PHI;
85 Value *IncV;
86
87 IVExpr(const SCEVHandle &base, PHINode *phi, Value *incv)
88 : Base(base), PHI(phi), IncV(incv) {}
89 };
90
91 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
92 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
93 struct IVsOfOneStride {
94 std::vector<IVExpr> IVs;
95
96 void addIV(const SCEVHandle &Base, PHINode *PHI, Value *IncV) {
97 IVs.push_back(IVExpr(Base, PHI, IncV));
98 }
99 };
Nate Begemane68bcd12005-07-30 00:15:07 +0000100
Nate Begemanb18121e2004-10-18 21:08:22 +0000101 class LoopStrengthReduce : public FunctionPass {
102 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +0000103 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +0000104 ScalarEvolution *SE;
105 const TargetData *TD;
106 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +0000107 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +0000108
Nate Begemane68bcd12005-07-30 00:15:07 +0000109 /// IVUsesByStride - Keep track of all uses of induction variables that we
110 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +0000111 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +0000112
Evan Cheng3df447d2006-03-16 21:53:05 +0000113 /// IVsByStride - Keep track of all IVs that have been inserted for a
114 /// particular stride.
115 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
116
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000117 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
118 /// We use this to iterate over the IVUsesByStride collection without being
119 /// dependent on random ordering of pointers in the process.
120 std::vector<SCEVHandle> StrideOrder;
121
Chris Lattner6f286b72005-08-04 01:19:13 +0000122 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
123 /// of the casted version of each value. This is accessed by
124 /// getCastedVersionOf.
125 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000126
127 /// DeadInsts - Keep track of instructions we may have made dead, so that
128 /// we can remove them after we are done working.
129 std::set<Instruction*> DeadInsts;
Evan Chengc567c4e2006-03-13 23:14:23 +0000130
131 /// TLI - Keep a pointer of a TargetLowering to consult for determining
132 /// transformation profitability.
133 const TargetLowering *TLI;
134
Nate Begemanb18121e2004-10-18 21:08:22 +0000135 public:
Evan Cheng3df447d2006-03-16 21:53:05 +0000136 LoopStrengthReduce(const TargetLowering *tli = NULL)
137 : TLI(tli) {
Jeff Cohena2c59b72005-03-04 04:04:26 +0000138 }
139
Nate Begemanb18121e2004-10-18 21:08:22 +0000140 virtual bool runOnFunction(Function &) {
141 LI = &getAnalysis<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000142 EF = &getAnalysis<ETForest>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000143 SE = &getAnalysis<ScalarEvolution>();
144 TD = &getAnalysis<TargetData>();
145 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000146 Changed = false;
147
148 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
149 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000150
Nate Begemanb18121e2004-10-18 21:08:22 +0000151 return Changed;
152 }
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000155 // We split critical edges, so we change the CFG. However, we do update
156 // many analyses if they are around.
157 AU.addPreservedID(LoopSimplifyID);
158 AU.addPreserved<LoopInfo>();
159 AU.addPreserved<DominatorSet>();
Chris Lattnercb367102006-01-11 05:10:20 +0000160 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000161 AU.addPreserved<ImmediateDominators>();
162 AU.addPreserved<DominanceFrontier>();
163 AU.addPreserved<DominatorTree>();
164
Jeff Cohen39751c32005-02-27 19:37:07 +0000165 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000166 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000167 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000168 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000169 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000170 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000171
172 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
173 ///
174 Value *getCastedVersionOf(Value *V);
175private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000176 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000177 bool AddUsersIfInteresting(Instruction *I, Loop *L,
178 std::set<Instruction*> &Processed);
179 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
180
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000181 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000182
Evan Cheng45206982006-03-17 19:52:23 +0000183 unsigned CheckForIVReuse(const SCEVHandle &Stride, IVExpr &IV);
184
Chris Lattneredff91a2005-08-10 00:45:21 +0000185 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
186 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000187 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000188 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
189 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000190 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Chris Lattner92233d22005-09-27 21:10:32 +0000191 "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000192}
193
Evan Cheng3df447d2006-03-16 21:53:05 +0000194FunctionPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
195 return new LoopStrengthReduce(TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000196}
197
Chris Lattner6f286b72005-08-04 01:19:13 +0000198/// getCastedVersionOf - Return the specified value casted to uintptr_t.
199///
200Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
201 if (V->getType() == UIntPtrTy) return V;
202 if (Constant *CB = dyn_cast<Constant>(V))
203 return ConstantExpr::getCast(CB, UIntPtrTy);
204
205 Value *&New = CastedPointers[V];
206 if (New) return New;
207
Chris Lattnerd30c4992006-02-04 09:52:43 +0000208 New = SCEVExpander::InsertCastOfTo(V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000209 DeadInsts.insert(cast<Instruction>(New));
210 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000211}
212
213
Nate Begemanb18121e2004-10-18 21:08:22 +0000214/// DeleteTriviallyDeadInstructions - If any of the instructions is the
215/// specified set are trivially dead, delete them and see if this makes any of
216/// their operands subsequently dead.
217void LoopStrengthReduce::
218DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
219 while (!Insts.empty()) {
220 Instruction *I = *Insts.begin();
221 Insts.erase(Insts.begin());
222 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000223 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
224 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
225 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000226 SE->deleteInstructionFromRecords(I);
227 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000228 Changed = true;
229 }
230 }
231}
232
Jeff Cohen39751c32005-02-27 19:37:07 +0000233
Chris Lattnereaf24722005-08-04 17:40:30 +0000234/// GetExpressionSCEV - Compute and return the SCEV for the specified
235/// instruction.
236SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000237 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
238 // If this is a GEP that SE doesn't know about, compute it now and insert it.
239 // If this is not a GEP, or if we have already done this computation, just let
240 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000241 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000242 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000243 return SE->getSCEV(Exp);
244
Nate Begemane68bcd12005-07-30 00:15:07 +0000245 // Analyze all of the subscripts of this getelementptr instruction, looking
246 // for uses that are determined by the trip count of L. First, skip all
247 // operands the are not dependent on the IV.
248
249 // Build up the base expression. Insert an LLVM cast of the pointer to
250 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000251 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000252
253 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000254
255 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000256 // If this is a use of a recurrence that we can analyze, and it comes before
257 // Op does in the GEP operand list, we will handle this when we process this
258 // operand.
259 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
260 const StructLayout *SL = TD->getStructLayout(STy);
261 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
262 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000263 GEPVal = SCEVAddExpr::get(GEPVal,
264 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000265 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000266 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
267 SCEVHandle Idx = SE->getSCEV(OpVal);
268
Chris Lattnereaf24722005-08-04 17:40:30 +0000269 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
270 if (TypeSize != 1)
271 Idx = SCEVMulExpr::get(Idx,
272 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
273 TypeSize)));
274 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000275 }
276 }
277
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000278 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000279 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000280}
281
Chris Lattneracc42c42005-08-04 19:08:16 +0000282/// getSCEVStartAndStride - Compute the start and stride of this expression,
283/// returning false if the expression is not a start/stride pair, or true if it
284/// is. The stride must be a loop invariant expression, but the start may be
285/// a mix of loop invariant and loop variant expressions.
286static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000287 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000288 SCEVHandle TheAddRec = Start; // Initialize to zero.
289
290 // If the outer level is an AddExpr, the operands are all start values except
291 // for a nested AddRecExpr.
292 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
293 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
294 if (SCEVAddRecExpr *AddRec =
295 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
296 if (AddRec->getLoop() == L)
297 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
298 else
299 return false; // Nested IV of some sort?
300 } else {
301 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
302 }
303
304 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
305 TheAddRec = SH;
306 } else {
307 return false; // not analyzable.
308 }
309
310 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
311 if (!AddRec || AddRec->getLoop() != L) return false;
312
313 // FIXME: Generalize to non-affine IV's.
314 if (!AddRec->isAffine()) return false;
315
316 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
317
Chris Lattneracc42c42005-08-04 19:08:16 +0000318 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000319 DEBUG(std::cerr << "[" << L->getHeader()->getName()
320 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000321
Chris Lattneredff91a2005-08-10 00:45:21 +0000322 Stride = AddRec->getOperand(1);
323 // Check that all constant strides are the unsigned type, we don't want to
324 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
325 // merged.
326 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000327 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000328
Chris Lattneracc42c42005-08-04 19:08:16 +0000329 return true;
330}
331
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000332/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
333/// and now we need to decide whether the user should use the preinc or post-inc
334/// value. If this user should use the post-inc version of the IV, return true.
335///
336/// Choosing wrong here can break dominance properties (if we choose to use the
337/// post-inc value when we cannot) or it can end up adding extra live-ranges to
338/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
339/// should use the post-inc value).
340static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000341 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000342 // If the user is in the loop, use the preinc value.
343 if (L->contains(User->getParent())) return false;
344
Chris Lattnerf07a5872005-10-03 02:50:05 +0000345 BasicBlock *LatchBlock = L->getLoopLatch();
346
347 // Ok, the user is outside of the loop. If it is dominated by the latch
348 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000349 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000350 return true;
351
352 // There is one case we have to be careful of: PHI nodes. These little guys
353 // can live in blocks that do not dominate the latch block, but (since their
354 // uses occur in the predecessor block, not the block the PHI lives in) should
355 // still use the post-inc value. Check for this case now.
356 PHINode *PN = dyn_cast<PHINode>(User);
357 if (!PN) return false; // not a phi, not dominated by latch block.
358
359 // Look at all of the uses of IV by the PHI node. If any use corresponds to
360 // a block that is not dominated by the latch block, give up and use the
361 // preincremented value.
362 unsigned NumUses = 0;
363 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
364 if (PN->getIncomingValue(i) == IV) {
365 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000366 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000367 return false;
368 }
369
370 // Okay, all uses of IV by PN are in predecessor blocks that really are
371 // dominated by the latch block. Split the critical edges and use the
372 // post-incremented value.
373 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
374 if (PN->getIncomingValue(i) == IV) {
375 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
376 if (--NumUses == 0) break;
377 }
378
379 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000380}
381
382
383
Nate Begemane68bcd12005-07-30 00:15:07 +0000384/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
385/// reducible SCEV, recursively add its users to the IVUsesByStride set and
386/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000387bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
388 std::set<Instruction*> &Processed) {
Chris Lattner5df0e362005-10-21 05:45:41 +0000389 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
390 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000391 if (!Processed.insert(I).second)
392 return true; // Instruction already handled.
393
Chris Lattneracc42c42005-08-04 19:08:16 +0000394 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000395 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000396 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000397
Chris Lattneracc42c42005-08-04 19:08:16 +0000398 // Get the start and stride for this expression.
399 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000400 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000401 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
402 return false; // Non-reducible symbolic expression, bail out.
403
Nate Begemane68bcd12005-07-30 00:15:07 +0000404 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
405 Instruction *User = cast<Instruction>(*UI);
406
407 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000408 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000409 continue;
410
411 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000412 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000413 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000414 if (LI->getLoopFor(User->getParent()) != L) {
Chris Lattnerfd018c82005-09-13 02:09:55 +0000415 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
Chris Lattnera0102fb2005-08-04 00:14:11 +0000416 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000417 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000418 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000419 DEBUG(std::cerr << "FOUND USER: " << *User
420 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000421 AddUserToIVUsers = true;
422 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000423
Chris Lattneracc42c42005-08-04 19:08:16 +0000424 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000425 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
426 if (StrideUses.Users.empty()) // First occurance of this stride?
427 StrideOrder.push_back(Stride);
428
Chris Lattner65107492005-08-04 00:40:47 +0000429 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000430 // and decide what to do with it. If we are a use inside of the loop, use
431 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000432 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000433 // The value used will be incremented by the stride more than we are
434 // expecting, so subtract this off.
435 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000436 StrideUses.addUser(NewStart, User, I);
437 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Chris Lattnerf07a5872005-10-03 02:50:05 +0000438 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000439 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000440 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000441 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000442 }
443 }
444 return true;
445}
446
447namespace {
448 /// BasedUser - For a particular base value, keep information about how we've
449 /// partitioned the expression so far.
450 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000451 /// Base - The Base value for the PHI node that needs to be inserted for
452 /// this use. As the use is processed, information gets moved from this
453 /// field to the Imm field (below). BasedUser values are sorted by this
454 /// field.
455 SCEVHandle Base;
456
Nate Begemane68bcd12005-07-30 00:15:07 +0000457 /// Inst - The instruction using the induction variable.
458 Instruction *Inst;
459
Chris Lattner430d0022005-08-03 22:21:05 +0000460 /// OperandValToReplace - The operand value of Inst to replace with the
461 /// EmittedBase.
462 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000463
464 /// Imm - The immediate value that should be added to the base immediately
465 /// before Inst, because it will be folded into the imm field of the
466 /// instruction.
467 SCEVHandle Imm;
468
469 /// EmittedBase - The actual value* to use for the base value of this
470 /// operation. This is null if we should just use zero so far.
471 Value *EmittedBase;
472
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000473 // isUseOfPostIncrementedValue - True if this should use the
474 // post-incremented version of this IV, not the preincremented version.
475 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000476 // instruction for a loop and uses outside the loop that are dominated by
477 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000478 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000479
480 BasedUser(IVStrideUse &IVSU)
481 : Base(IVSU.Offset), Inst(IVSU.User),
482 OperandValToReplace(IVSU.OperandValToReplace),
483 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
484 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000485
Chris Lattnera6d7c352005-08-04 20:03:32 +0000486 // Once we rewrite the code to insert the new IVs we want, update the
487 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
488 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000489 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000490 SCEVExpander &Rewriter, Loop *L,
491 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000492
493 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
494 SCEVExpander &Rewriter,
495 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000496 void dump() const;
497 };
498}
499
500void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000501 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000502 std::cerr << " Imm=" << *Imm;
503 if (EmittedBase)
504 std::cerr << " EB=" << *EmittedBase;
505
506 std::cerr << " Inst: " << *Inst;
507}
508
Chris Lattner2959f002006-02-04 07:36:50 +0000509Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
510 SCEVExpander &Rewriter,
511 Instruction *IP, Loop *L) {
512 // Figure out where we *really* want to insert this code. In particular, if
513 // the user is inside of a loop that is nested inside of L, we really don't
514 // want to insert this expression before the user, we'd rather pull it out as
515 // many loops as possible.
516 LoopInfo &LI = Rewriter.getLoopInfo();
517 Instruction *BaseInsertPt = IP;
518
519 // Figure out the most-nested loop that IP is in.
520 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
521
522 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
523 // the preheader of the outer-most loop where NewBase is not loop invariant.
524 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
525 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
526 InsertLoop = InsertLoop->getParentLoop();
527 }
528
529 // If there is no immediate value, skip the next part.
530 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
531 if (SC->getValue()->isNullValue())
532 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
533 OperandValToReplace->getType());
534
535 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
536
537 // Always emit the immediate (if non-zero) into the same block as the user.
538 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
539 return Rewriter.expandCodeFor(NewValSCEV, IP,
540 OperandValToReplace->getType());
541}
542
543
Chris Lattnera6d7c352005-08-04 20:03:32 +0000544// Once we rewrite the code to insert the new IVs we want, update the
545// operands of Inst to use the new expression 'NewBase', with 'Imm' added
546// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000547void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000548 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000549 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000550 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000551 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000552 // Replace the use of the operand Value with the new Phi we just created.
553 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
554 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
555 return;
556 }
557
558 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000559 // expression into each operand block that uses it. Note that PHI nodes can
560 // have multiple entries for the same predecessor. We use a map to make sure
561 // that a PHI node only has a single Value* for each predecessor (which also
562 // prevents us from inserting duplicate code in some blocks).
563 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000564 PHINode *PN = cast<PHINode>(Inst);
565 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
566 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000567 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000568 // code on all predecessor/successor paths. We do this unless this is the
569 // canonical backedge for this loop, as this can make some inserted code
570 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000571 BasicBlock *PHIPred = PN->getIncomingBlock(i);
572 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
573 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000574
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000575 // First step, split the critical edge.
Chris Lattner8fcce172005-10-03 00:31:52 +0000576 SplitCriticalEdge(PHIPred, PN->getParent(), P);
Chris Lattner8447b492005-08-12 22:22:17 +0000577
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000578 // Next step: move the basic block. In particular, if the PHI node
579 // is outside of the loop, and PredTI is in the loop, we want to
580 // move the block to be immediately before the PHI block, not
581 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000582 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000583 BasicBlock *NewBB = PN->getIncomingBlock(i);
584 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000585 }
586 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000587
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000588 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
589 if (!Code) {
590 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000591 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
592 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000593 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000594
595 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000596 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000597 Rewriter.clear();
598 }
599 }
600 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
601}
602
603
Nate Begemane68bcd12005-07-30 00:15:07 +0000604/// isTargetConstant - Return true if the following can be referenced by the
605/// immediate field of a target instruction.
Evan Chengc567c4e2006-03-13 23:14:23 +0000606static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000607 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattner07720072005-12-05 18:23:57 +0000608 int64_t V = SC->getValue()->getSExtValue();
Evan Chengc567c4e2006-03-13 23:14:23 +0000609 if (TLI)
610 return TLI->isLegalAddressImmediate(V);
611 else
612 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
613 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner14203e82005-08-08 06:25:50 +0000614 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000615
Nate Begemane68bcd12005-07-30 00:15:07 +0000616 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
617 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Evan Chengc567c4e2006-03-13 23:14:23 +0000618 if (CE->getOpcode() == Instruction::Cast) {
619 Constant *Op0 = CE->getOperand(0);
620 if (isa<GlobalValue>(Op0) &&
621 TLI &&
622 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begemane68bcd12005-07-30 00:15:07 +0000623 return true;
Evan Chengc567c4e2006-03-13 23:14:23 +0000624 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000625 return false;
626}
627
Chris Lattner37ed8952005-08-08 22:32:34 +0000628/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
629/// loop varying to the Imm operand.
630static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
631 Loop *L) {
632 if (Val->isLoopInvariant(L)) return; // Nothing to do.
633
634 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
635 std::vector<SCEVHandle> NewOps;
636 NewOps.reserve(SAE->getNumOperands());
637
638 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
639 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
640 // If this is a loop-variant expression, it must stay in the immediate
641 // field of the expression.
642 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
643 } else {
644 NewOps.push_back(SAE->getOperand(i));
645 }
646
647 if (NewOps.empty())
648 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
649 else
650 Val = SCEVAddExpr::get(NewOps);
651 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
652 // Try to pull immediates out of the start value of nested addrec's.
653 SCEVHandle Start = SARE->getStart();
654 MoveLoopVariantsToImediateField(Start, Imm, L);
655
656 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
657 Ops[0] = Start;
658 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
659 } else {
660 // Otherwise, all of Val is variant, move the whole thing over.
661 Imm = SCEVAddExpr::get(Imm, Val);
662 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
663 }
664}
665
666
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000667/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000668/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000669/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000670static void MoveImmediateValues(const TargetLowering *TLI,
671 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000672 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000673 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000674 std::vector<SCEVHandle> NewOps;
675 NewOps.reserve(SAE->getNumOperands());
676
Chris Lattner2959f002006-02-04 07:36:50 +0000677 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
678 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengc567c4e2006-03-13 23:14:23 +0000679 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000680
681 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000682 // If this is a loop-variant expression, it must stay in the immediate
683 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000684 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000685 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000686 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000687 }
Chris Lattner2959f002006-02-04 07:36:50 +0000688 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000689
690 if (NewOps.empty())
691 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
692 else
693 Val = SCEVAddExpr::get(NewOps);
694 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000695 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
696 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000697 SCEVHandle Start = SARE->getStart();
Evan Chengc567c4e2006-03-13 23:14:23 +0000698 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000699
700 if (Start != SARE->getStart()) {
701 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
702 Ops[0] = Start;
703 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
704 }
705 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000706 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
707 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengc567c4e2006-03-13 23:14:23 +0000708 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000709 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
710
711 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
712 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengc567c4e2006-03-13 23:14:23 +0000713 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000714
715 // If we extracted something out of the subexpressions, see if we can
716 // simplify this!
717 if (NewOp != SME->getOperand(1)) {
718 // Scale SubImm up by "8". If the result is a target constant, we are
719 // good.
720 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengc567c4e2006-03-13 23:14:23 +0000721 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000722 // Accumulate the immediate.
723 Imm = SCEVAddExpr::get(Imm, SubImm);
724
725 // Update what is left of 'Val'.
726 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
727 return;
728 }
729 }
730 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000731 }
732
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000733 // Loop-variant expressions must stay in the immediate field of the
734 // expression.
Evan Chengc567c4e2006-03-13 23:14:23 +0000735 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000736 !Val->isLoopInvariant(L)) {
737 Imm = SCEVAddExpr::get(Imm, Val);
738 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
739 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000740 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000741
742 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000743}
744
Chris Lattner5949d492005-08-13 07:27:18 +0000745
746/// IncrementAddExprUses - Decompose the specified expression into its added
747/// subexpressions, and increment SubExpressionUseCounts for each of these
748/// decomposed parts.
749static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
750 SCEVHandle Expr) {
751 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
752 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
753 SeparateSubExprs(SubExprs, AE->getOperand(j));
754 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
755 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
756 if (SARE->getOperand(0) == Zero) {
757 SubExprs.push_back(Expr);
758 } else {
759 // Compute the addrec with zero as its base.
760 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
761 Ops[0] = Zero; // Start with zero base.
762 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
763
764
765 SeparateSubExprs(SubExprs, SARE->getOperand(0));
766 }
767 } else if (!isa<SCEVConstant>(Expr) ||
768 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
769 // Do not add zero.
770 SubExprs.push_back(Expr);
771 }
772}
773
774
Chris Lattnera091ff12005-08-09 00:18:09 +0000775/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
776/// removing any common subexpressions from it. Anything truly common is
777/// removed, accumulated, and returned. This looks for things like (a+b+c) and
778/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
779static SCEVHandle
780RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
781 unsigned NumUses = Uses.size();
782
783 // Only one use? Use its base, regardless of what it is!
784 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
785 SCEVHandle Result = Zero;
786 if (NumUses == 1) {
787 std::swap(Result, Uses[0].Base);
788 return Result;
789 }
790
791 // To find common subexpressions, count how many of Uses use each expression.
792 // If any subexpressions are used Uses.size() times, they are common.
793 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
794
Chris Lattner192cd182005-10-11 18:41:04 +0000795 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
796 // order we see them.
797 std::vector<SCEVHandle> UniqueSubExprs;
798
Chris Lattner5949d492005-08-13 07:27:18 +0000799 std::vector<SCEVHandle> SubExprs;
800 for (unsigned i = 0; i != NumUses; ++i) {
801 // If the base is zero (which is common), return zero now, there are no
802 // CSEs we can find.
803 if (Uses[i].Base == Zero) return Zero;
804
805 // Split the expression into subexprs.
806 SeparateSubExprs(SubExprs, Uses[i].Base);
807 // Add one to SubExpressionUseCounts for each subexpr present.
808 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000809 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
810 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000811 SubExprs.clear();
812 }
813
Chris Lattner192cd182005-10-11 18:41:04 +0000814 // Now that we know how many times each is used, build Result. Iterate over
815 // UniqueSubexprs so that we have a stable ordering.
816 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
817 std::map<SCEVHandle, unsigned>::iterator I =
818 SubExpressionUseCounts.find(UniqueSubExprs[i]);
819 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000820 if (I->second == NumUses) { // Found CSE!
821 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000822 } else {
823 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000824 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000825 }
Chris Lattner192cd182005-10-11 18:41:04 +0000826 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000827
828 // If we found no CSE's, return now.
829 if (Result == Zero) return Result;
830
831 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000832 for (unsigned i = 0; i != NumUses; ++i) {
833 // Split the expression into subexprs.
834 SeparateSubExprs(SubExprs, Uses[i].Base);
835
836 // Remove any common subexpressions.
837 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
838 if (SubExpressionUseCounts.count(SubExprs[j])) {
839 SubExprs.erase(SubExprs.begin()+j);
840 --j; --e;
841 }
842
843 // Finally, the non-shared expressions together.
844 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000845 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000846 else
847 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000848 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000849 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000850
851 return Result;
852}
853
Evan Cheng3df447d2006-03-16 21:53:05 +0000854/// isZero - returns true if the scalar evolution expression is zero.
855///
856static bool isZero(SCEVHandle &V) {
857 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
858 return SC->getValue()->getRawValue() == 0;
859 return false;
860}
861
Chris Lattnera091ff12005-08-09 00:18:09 +0000862
Evan Cheng45206982006-03-17 19:52:23 +0000863/// CheckForIVReuse - Returns the multiple if the stride is the multiple
864/// of a previous stride and it is a legal value for the target addressing
865/// mode scale component. This allows the users of this stride to be rewritten
866/// as prev iv * factor. It returns 1 if no reuse is possible.
867unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
868 IVExpr &IV) {
869 if (!TLI)
870 return 1;
871
872 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
873 unsigned SInt = SC->getValue()->getRawValue();
874 if (SInt == 1)
875 return 1;
876
877 for (TargetLowering::legal_am_scale_iterator
878 I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
879 I != E; ++I) {
880 unsigned Scale = *I;
881 if (SInt >= Scale && (SInt % Scale) != 0)
882 continue;
883 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
884 IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, Type::UIntTy));
885 if (SI == IVsByStride.end())
886 continue;
887 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
888 IE = SI->second.IVs.end(); II != IE; ++II)
889 // FIXME: Only handle base == 0 for now.
890 if (isZero(II->Base)) {
891 IV = *II;
892 return Scale;
893 }
894 }
895 }
896
897 return 1;
898}
899
900
Nate Begemane68bcd12005-07-30 00:15:07 +0000901/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
902/// stride of IV. All of the users may have different starting values, and this
903/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000904void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000905 IVUsersOfOneStride &Uses,
906 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000907 bool isOnlyStride) {
908 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000909 // this new vector, each 'BasedUser' contains 'Base' the base of the
910 // strided accessas well as the old information from Uses. We progressively
911 // move information from the Base field to the Imm field, until we eventually
912 // have the full access expression to rewrite the use.
913 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000914 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000915 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
916 UsersToProcess.push_back(Uses.Users[i]);
917
918 // Move any loop invariant operands from the offset field to the immediate
919 // field of the use, so that we don't try to use something before it is
920 // computed.
921 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
922 UsersToProcess.back().Imm, L);
923 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000924 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000925 }
Evan Cheng45206982006-03-17 19:52:23 +0000926
927 // Check if it is possible to reuse a IV with stride that is factor of this
928 // stride. And the multiple is a number that can be encoded in the scale
929 // field of the target addressing mode.
930 PHINode *NewPHI = NULL;
931 Value *IncV = NULL;
932 IVExpr ReuseIV(Stride, NULL, NULL);
933 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV);
934 if (RewriteFactor > 1) {
935 NewPHI = ReuseIV.PHI;
936 IncV = ReuseIV.IncV;
937 }
938
Chris Lattnera091ff12005-08-09 00:18:09 +0000939 // We now have a whole bunch of uses of like-strided induction variables, but
940 // they might all have different bases. We want to emit one PHI node for this
941 // stride which we fold as many common expressions (between the IVs) into as
942 // possible. Start by identifying the common expressions in the base values
943 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
944 // "A+B"), emit it to the preheader, then remove the expression from the
945 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +0000946 SCEVHandle CommonExprs =
947 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +0000948
Chris Lattner37ed8952005-08-08 22:32:34 +0000949 // Next, figure out what we can represent in the immediate fields of
950 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000951 // fields of the BasedUsers. We do this so that it increases the commonality
952 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000953 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000954 // If the user is not in the current loop, this means it is using the exit
955 // value of the IV. Do not put anything in the base, make sure it's all in
956 // the immediate field to allow as much factoring as possible.
957 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000958 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
959 UsersToProcess[i].Base);
960 UsersToProcess[i].Base =
961 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000962 } else {
963
964 // Addressing modes can be folded into loads and stores. Be careful that
965 // the store is through the expression, not of the expression though.
966 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
967 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
968 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
969 isAddress = true;
970
Evan Chengc567c4e2006-03-13 23:14:23 +0000971 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner5cf983e2005-08-16 00:38:11 +0000972 isAddress, L);
973 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000974 }
Evan Cheng3df447d2006-03-16 21:53:05 +0000975
Chris Lattnera091ff12005-08-09 00:18:09 +0000976 // Now that we know what we need to do, insert the PHI node itself.
977 //
978 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
979 << *CommonExprs << " :\n");
Evan Cheng3df447d2006-03-16 21:53:05 +0000980
Chris Lattnera091ff12005-08-09 00:18:09 +0000981 SCEVExpander Rewriter(*SE, *LI);
982 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000983
Chris Lattnera091ff12005-08-09 00:18:09 +0000984 BasicBlock *Preheader = L->getLoopPreheader();
985 Instruction *PreInsertPt = Preheader->getTerminator();
986 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000987
Chris Lattner8048b852005-09-12 17:11:27 +0000988 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +0000989
Chris Lattnera091ff12005-08-09 00:18:09 +0000990 const Type *ReplacedTy = CommonExprs->getType();
Evan Cheng45206982006-03-17 19:52:23 +0000991
992 // Emit the initial base value into the loop preheader.
993 Value *CommonBaseV
994 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
995 ReplacedTy);
996
Evan Cheng3df447d2006-03-16 21:53:05 +0000997 if (RewriteFactor == 1) {
998 // Create a new Phi for this base, and stick it in the loop header.
999 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1000 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001001
Evan Cheng45206982006-03-17 19:52:23 +00001002 // Add common base to the new Phi node.
1003 NewPHI->addIncoming(CommonBaseV, Preheader);
1004
Evan Cheng3df447d2006-03-16 21:53:05 +00001005 // Insert the stride into the preheader.
1006 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1007 ReplacedTy);
1008 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001009
Evan Cheng3df447d2006-03-16 21:53:05 +00001010 // Emit the increment of the base value before the terminator of the loop
1011 // latch block, and add it to the Phi node.
1012 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1013 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +00001014
Evan Cheng3df447d2006-03-16 21:53:05 +00001015 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1016 ReplacedTy);
1017 IncV->setName(NewPHI->getName()+".inc");
1018 NewPHI->addIncoming(IncV, LatchBlock);
1019
Evan Cheng45206982006-03-17 19:52:23 +00001020 // Remember this in case a later stride is multiple of this.
Evan Cheng3df447d2006-03-16 21:53:05 +00001021 IVsByStride[Stride].addIV(CommonExprs, NewPHI, IncV);
Evan Cheng45206982006-03-17 19:52:23 +00001022 } else {
1023 Constant *C = dyn_cast<Constant>(CommonBaseV);
1024 if (!C ||
1025 (!C->isNullValue() &&
1026 !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
1027 // We want the common base emitted into the preheader!
1028 CommonBaseV = new CastInst(CommonBaseV, CommonBaseV->getType(),
1029 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001030 }
Chris Lattnera091ff12005-08-09 00:18:09 +00001031
Chris Lattnerdb23c742005-08-03 22:51:21 +00001032 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +00001033 // each other.
Nate Begemane68bcd12005-07-30 00:15:07 +00001034 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001035 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001036
Chris Lattnera091ff12005-08-09 00:18:09 +00001037 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +00001038
Chris Lattnera091ff12005-08-09 00:18:09 +00001039 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001040 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1041 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +00001042
1043 // If BaseV is a constant other than 0, make sure that it gets inserted into
1044 // the preheader, instead of being forward substituted into the uses. We do
1045 // this by forcing a noop cast to be inserted into the preheader in this
1046 // case.
1047 if (Constant *C = dyn_cast<Constant>(BaseV))
Evan Chengc567c4e2006-03-13 23:14:23 +00001048 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Chris Lattnera091ff12005-08-09 00:18:09 +00001049 // We want this constant emitted into the preheader!
1050 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
1051 PreInsertPt);
1052 }
1053
Nate Begemane68bcd12005-07-30 00:15:07 +00001054 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001055 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001056 unsigned ScanPos = 0;
1057 do {
1058 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001059
Chris Lattnera091ff12005-08-09 00:18:09 +00001060 // If this instruction wants to use the post-incremented value, move it
1061 // after the post-inc and use its value instead of the PHI.
1062 Value *RewriteOp = NewPHI;
1063 if (User.isUseOfPostIncrementedValue) {
1064 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001065
1066 // If this user is in the loop, make sure it is the last thing in the
1067 // loop to ensure it is dominated by the increment.
1068 if (L->contains(User.Inst->getParent()))
1069 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001070 }
1071 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1072
Chris Lattnerdb23c742005-08-03 22:51:21 +00001073 // Clear the SCEVExpander's expression map so that we are guaranteed
1074 // to have the code emitted where we expect it.
1075 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001076
1077 // If we are reusing the iv, then it must be multiplied by a constant
1078 // factor take advantage of addressing mode scale component.
Evan Cheng45206982006-03-17 19:52:23 +00001079 if (RewriteFactor != 1) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001080 RewriteExpr =
1081 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001082 RewriteExpr->getType()),
1083 RewriteExpr);
1084
1085 // The common base is emitted in the loop preheader. But since we
1086 // are reusing an IV, it has not been used to initialize the PHI node.
1087 // Add it to the expression used to rewrite the uses.
1088 if (!isa<ConstantInt>(CommonBaseV) ||
1089 !cast<ConstantInt>(CommonBaseV)->isNullValue())
1090 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1091 SCEVUnknown::get(CommonBaseV));
1092 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001093
Chris Lattnera6d7c352005-08-04 20:03:32 +00001094 // Now that we know what we need to do, insert code before User for the
1095 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +00001096 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
1097 // Add BaseV to the PHI value if needed.
1098 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001099
Chris Lattner8447b492005-08-12 22:22:17 +00001100 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001101
Chris Lattnerdb23c742005-08-03 22:51:21 +00001102 // Mark old value we replaced as possibly dead, so that it is elminated
1103 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001104 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001105
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001106 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001107 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001108
1109 // If there are any more users to process with the same base, move one of
1110 // them to the end of the list so that we will process it.
1111 if (!UsersToProcess.empty()) {
1112 for (unsigned e = UsersToProcess.size(); ScanPos != e; ++ScanPos)
1113 if (UsersToProcess[ScanPos].Base == Base) {
1114 std::swap(UsersToProcess[ScanPos], UsersToProcess.back());
1115 break;
1116 }
1117 }
1118 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001119 // TODO: Next, find out which base index is the most common, pull it out.
1120 }
1121
1122 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1123 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001124}
1125
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001126// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1127// uses in the loop, look to see if we can eliminate some, in favor of using
1128// common indvars for the different uses.
1129void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1130 // TODO: implement optzns here.
1131
1132
1133
1134
1135 // Finally, get the terminating condition for the loop if possible. If we
1136 // can, we want to change it to use a post-incremented version of its
1137 // induction variable, to allow coallescing the live ranges for the IV into
1138 // one register value.
1139 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1140 BasicBlock *Preheader = L->getLoopPreheader();
1141 BasicBlock *LatchBlock =
1142 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1143 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1144 if (!TermBr || TermBr->isUnconditional() ||
1145 !isa<SetCondInst>(TermBr->getCondition()))
1146 return;
1147 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1148
1149 // Search IVUsesByStride to find Cond's IVUse if there is one.
1150 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001151 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001152
Chris Lattnerb7a38942005-10-11 18:17:57 +00001153 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1154 ++Stride) {
1155 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1156 IVUsesByStride.find(StrideOrder[Stride]);
1157 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1158
1159 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1160 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001161 if (UI->User == Cond) {
1162 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001163 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001164 // NOTE: we could handle setcc instructions with multiple uses here, but
1165 // InstCombine does it as well for simple uses, it's not clear that it
1166 // occurs enough in real life to handle.
1167 break;
1168 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001169 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001170 if (!CondUse) return; // setcc doesn't use the IV.
1171
1172 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +00001173 // FIXME: Evaluate whether this is a good idea or not.
1174 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001175
1176 // It's possible for the setcc instruction to be anywhere in the loop, and
1177 // possible for it to have multiple users. If it is not immediately before
1178 // the latch block branch, move it.
1179 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1180 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1181 Cond->moveBefore(TermBr);
1182 } else {
1183 // Otherwise, clone the terminating condition and insert into the loopend.
1184 Cond = cast<SetCondInst>(Cond->clone());
1185 Cond->setName(L->getHeader()->getName() + ".termcond");
1186 LatchBlock->getInstList().insert(TermBr, Cond);
1187
1188 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001189 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001190 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001191 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001192 }
1193 }
1194
1195 // If we get to here, we know that we can transform the setcc instruction to
1196 // use the post-incremented version of the IV, allowing us to coallesce the
1197 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001198 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001199 CondUse->isUseOfPostIncrementedValue = true;
1200}
Nate Begemane68bcd12005-07-30 00:15:07 +00001201
Nate Begemanb18121e2004-10-18 21:08:22 +00001202void LoopStrengthReduce::runOnLoop(Loop *L) {
1203 // First step, transform all loops nesting inside of this loop.
1204 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1205 runOnLoop(*I);
1206
Nate Begemane68bcd12005-07-30 00:15:07 +00001207 // Next, find all uses of induction variables in this loop, and catagorize
1208 // them by stride. Start by finding all of the PHI nodes in the header for
1209 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001210 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001211 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001212 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001213
Nate Begemane68bcd12005-07-30 00:15:07 +00001214 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001215 if (IVUsesByStride.empty()) return;
1216
1217 // Optimize induction variables. Some indvar uses can be transformed to use
1218 // strides that will be needed for other purposes. A common example of this
1219 // is the exit test for the loop, which can often be rewritten to use the
1220 // computation of some other indvar to decide when to terminate the loop.
1221 OptimizeIndvars(L);
1222
Misha Brukmanb1c93172005-04-21 23:48:37 +00001223
Nate Begemane68bcd12005-07-30 00:15:07 +00001224 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1225 // doing computation in byte values, promote to 32-bit values if safe.
1226
1227 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1228 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1229 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1230 // to be careful that IV's are all the same type. Only works for intptr_t
1231 // indvars.
1232
1233 // If we only have one stride, we can more aggressively eliminate some things.
1234 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001235
1236#ifndef NDEBUG
1237 DEBUG(std::cerr << "\nLSR on ");
1238 DEBUG(L->dump());
1239#endif
1240
1241 // IVsByStride keeps IVs for one particular loop.
1242 IVsByStride.clear();
1243
Chris Lattnera091ff12005-08-09 00:18:09 +00001244 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001245 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1246 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1247 // This extra layer of indirection makes the ordering of strides deterministic
1248 // - not dependent on map order.
1249 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1250 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1251 IVUsesByStride.find(StrideOrder[Stride]);
1252 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001253 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001254 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001255
1256 // Clean up after ourselves
1257 if (!DeadInsts.empty()) {
1258 DeleteTriviallyDeadInstructions(DeadInsts);
1259
Nate Begemane68bcd12005-07-30 00:15:07 +00001260 BasicBlock::iterator I = L->getHeader()->begin();
1261 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001262 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001263 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1264
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001265 // At this point, we know that we have killed one or more GEP
1266 // instructions. It is worth checking to see if the cann indvar is also
1267 // dead, so that we can remove it as well. The requirements for the cann
1268 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001269 // 1. the cann indvar has one use
1270 // 2. the use is an add instruction
1271 // 3. the add has one use
1272 // 4. the add is used by the cann indvar
1273 // If all four cases above are true, then we can remove both the add and
1274 // the cann indvar.
1275 // FIXME: this needs to eliminate an induction variable even if it's being
1276 // compared against some value to decide loop termination.
1277 if (PN->hasOneUse()) {
1278 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +00001279 if (BO && BO->hasOneUse()) {
1280 if (PN == *(BO->use_begin())) {
1281 DeadInsts.insert(BO);
1282 // Break the cycle, then delete the PHI.
1283 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001284 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001285 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001286 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001287 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001288 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001289 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001290 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001291 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001292
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001293 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001294 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001295 StrideOrder.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001296 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001297}