blob: 6bece9cfb7ebcb3437b1765dd29678da86d6cf97 [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"
Devang Patelb0743b52007-03-06 21:14:09 +000026#include "llvm/Analysis/LoopPass.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000027#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000028#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner4fec86d2005-08-12 22:06:11 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000031#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000032#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000033#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000034#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000035#include "llvm/Support/Compiler.h"
Evan Chengc567c4e2006-03-13 23:14:23 +000036#include "llvm/Target/TargetLowering.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000037#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000038#include <set>
39using namespace llvm;
40
Chris Lattner79a42ac2006-12-19 21:40:18 +000041STATISTIC(NumReduced , "Number of GEPs strength reduced");
42STATISTIC(NumInserted, "Number of PHIs inserted");
43STATISTIC(NumVariable, "Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000044
Chris Lattner79a42ac2006-12-19 21:40:18 +000045namespace {
Dale Johannesene3a02be2007-03-20 00:47:50 +000046
Jeff Cohen1baf5c82007-03-20 20:43:18 +000047 struct BasedUser;
Dale Johannesene3a02be2007-03-20 00:47:50 +000048
Chris Lattner430d0022005-08-03 22:21:05 +000049 /// IVStrideUse - Keep track of one use of a strided induction variable, where
50 /// the stride is stored externally. The Offset member keeps track of the
51 /// offset from the IV, User is the actual user of the operand, and 'Operand'
52 /// is the operand # of the User that is the use.
Reid Spencer557ab152007-02-05 23:32:05 +000053 struct VISIBILITY_HIDDEN IVStrideUse {
Chris Lattner430d0022005-08-03 22:21:05 +000054 SCEVHandle Offset;
55 Instruction *User;
56 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000057
58 // isUseOfPostIncrementedValue - True if this should use the
59 // post-incremented version of this IV, not the preincremented version.
60 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000061 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000062 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000063
64 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000065 : Offset(Offs), User(U), OperandValToReplace(O),
66 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000067 };
68
69 /// IVUsersOfOneStride - This structure keeps track of all instructions that
70 /// have an operand that is based on the trip count multiplied by some stride.
71 /// The stride for all of these users is common and kept external to this
72 /// structure.
Reid Spencer557ab152007-02-05 23:32:05 +000073 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000074 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000075 /// initial value and the operand that uses the IV.
76 std::vector<IVStrideUse> Users;
77
78 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
79 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000080 }
81 };
82
Evan Cheng3df447d2006-03-16 21:53:05 +000083 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Chengc28282b2006-03-18 08:03:12 +000084 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
85 /// well as the PHI node and increment value created for rewrite.
Reid Spencer557ab152007-02-05 23:32:05 +000086 struct VISIBILITY_HIDDEN IVExpr {
Evan Chengc28282b2006-03-18 08:03:12 +000087 SCEVHandle Stride;
Evan Cheng3df447d2006-03-16 21:53:05 +000088 SCEVHandle Base;
89 PHINode *PHI;
90 Value *IncV;
91
Evan Chengc28282b2006-03-18 08:03:12 +000092 IVExpr()
Reid Spencerc635f472006-12-31 05:48:39 +000093 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)),
94 Base (SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)) {}
Evan Chengc28282b2006-03-18 08:03:12 +000095 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
96 Value *incv)
97 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
Evan Cheng3df447d2006-03-16 21:53:05 +000098 };
99
100 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
101 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
Reid Spencer557ab152007-02-05 23:32:05 +0000102 struct VISIBILITY_HIDDEN IVsOfOneStride {
Evan Cheng3df447d2006-03-16 21:53:05 +0000103 std::vector<IVExpr> IVs;
104
Evan Chengc28282b2006-03-18 08:03:12 +0000105 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
106 Value *IncV) {
107 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
Evan Cheng3df447d2006-03-16 21:53:05 +0000108 }
109 };
Nate Begemane68bcd12005-07-30 00:15:07 +0000110
Devang Patelb0743b52007-03-06 21:14:09 +0000111 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
Nate Begemanb18121e2004-10-18 21:08:22 +0000112 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +0000113 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +0000114 ScalarEvolution *SE;
115 const TargetData *TD;
116 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +0000117 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +0000118
Nate Begemane68bcd12005-07-30 00:15:07 +0000119 /// IVUsesByStride - Keep track of all uses of induction variables that we
120 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +0000121 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +0000122
Evan Cheng3df447d2006-03-16 21:53:05 +0000123 /// IVsByStride - Keep track of all IVs that have been inserted for a
124 /// particular stride.
125 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
126
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000127 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
128 /// We use this to iterate over the IVUsesByStride collection without being
129 /// dependent on random ordering of pointers in the process.
130 std::vector<SCEVHandle> StrideOrder;
131
Chris Lattner6f286b72005-08-04 01:19:13 +0000132 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
133 /// of the casted version of each value. This is accessed by
134 /// getCastedVersionOf.
135 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000136
137 /// DeadInsts - Keep track of instructions we may have made dead, so that
138 /// we can remove them after we are done working.
139 std::set<Instruction*> DeadInsts;
Evan Chengc567c4e2006-03-13 23:14:23 +0000140
141 /// TLI - Keep a pointer of a TargetLowering to consult for determining
142 /// transformation profitability.
143 const TargetLowering *TLI;
144
Nate Begemanb18121e2004-10-18 21:08:22 +0000145 public:
Chris Lattner780c0092007-04-09 22:20:14 +0000146 LoopStrengthReduce(const TargetLowering *tli = NULL) : TLI(tli) {
Jeff Cohena2c59b72005-03-04 04:04:26 +0000147 }
148
Devang Patelb0743b52007-03-06 21:14:09 +0000149 bool runOnLoop(Loop *L, LPPassManager &LPM);
Nate Begemanb18121e2004-10-18 21:08:22 +0000150
151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000152 // We split critical edges, so we change the CFG. However, we do update
153 // many analyses if they are around.
154 AU.addPreservedID(LoopSimplifyID);
155 AU.addPreserved<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000156 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000157 AU.addPreserved<DominanceFrontier>();
158 AU.addPreserved<DominatorTree>();
159
Jeff Cohen39751c32005-02-27 19:37:07 +0000160 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000161 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000162 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000163 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000164 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000165 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000166
167 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
168 ///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000169 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
Chris Lattner6f286b72005-08-04 01:19:13 +0000170private:
Chris Lattnereaf24722005-08-04 17:40:30 +0000171 bool AddUsersIfInteresting(Instruction *I, Loop *L,
172 std::set<Instruction*> &Processed);
173 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
174
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000175 void OptimizeIndvars(Loop *L);
Chris Lattner81e07072007-04-03 05:11:24 +0000176 bool FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
177 const SCEVHandle *&CondStride);
Nate Begemane68bcd12005-07-30 00:15:07 +0000178
Dale Johannesene3a02be2007-03-20 00:47:50 +0000179 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*,
180 const std::vector<BasedUser>& UsersToProcess);
181
182 bool ValidStride(int64_t, const std::vector<BasedUser>& UsersToProcess);
Evan Cheng45206982006-03-17 19:52:23 +0000183
Chris Lattneredff91a2005-08-10 00:45:21 +0000184 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
185 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000186 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000187 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
188 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000189 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000190}
191
Devang Patelb0743b52007-03-06 21:14:09 +0000192LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Evan Cheng3df447d2006-03-16 21:53:05 +0000193 return new LoopStrengthReduce(TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000194}
195
Reid Spencerb341b082006-12-12 05:05:00 +0000196/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
197/// assumes that the Value* V is of integer or pointer type only.
Chris Lattner6f286b72005-08-04 01:19:13 +0000198///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000199Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
200 Value *V) {
Chris Lattner6f286b72005-08-04 01:19:13 +0000201 if (V->getType() == UIntPtrTy) return V;
202 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000203 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
Chris Lattner6f286b72005-08-04 01:19:13 +0000204
205 Value *&New = CastedPointers[V];
206 if (New) return New;
207
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000208 New = SCEVExpander::InsertCastOfTo(opcode, 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) {
Dale Johannesene5866e72007-03-26 03:01:27 +0000237 // Pointer to pointer bitcast instructions return the same value as their
238 // operand.
239 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
240 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
241 return SE->getSCEV(BCI);
242 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)), L);
243 SE->setSCEV(BCI, R);
244 return R;
245 }
246
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000247 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
248 // If this is a GEP that SE doesn't know about, compute it now and insert it.
249 // If this is not a GEP, or if we have already done this computation, just let
250 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000251 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000252 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000253 return SE->getSCEV(Exp);
254
Nate Begemane68bcd12005-07-30 00:15:07 +0000255 // Analyze all of the subscripts of this getelementptr instruction, looking
256 // for uses that are determined by the trip count of L. First, skip all
257 // operands the are not dependent on the IV.
258
259 // Build up the base expression. Insert an LLVM cast of the pointer to
260 // uintptr_t first.
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000261 SCEVHandle GEPVal = SCEVUnknown::get(
262 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000263
264 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000265
266 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000267 // If this is a use of a recurrence that we can analyze, and it comes before
268 // Op does in the GEP operand list, we will handle this when we process this
269 // operand.
270 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
271 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000272 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000273 uint64_t Offset = SL->getElementOffset(Idx);
Chris Lattnereaf24722005-08-04 17:40:30 +0000274 GEPVal = SCEVAddExpr::get(GEPVal,
275 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000276 } else {
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000277 unsigned GEPOpiBits =
278 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
279 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
280 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
281 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
282 Instruction::BitCast));
283 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
Chris Lattneracc42c42005-08-04 19:08:16 +0000284 SCEVHandle Idx = SE->getSCEV(OpVal);
285
Chris Lattnereaf24722005-08-04 17:40:30 +0000286 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
287 if (TypeSize != 1)
288 Idx = SCEVMulExpr::get(Idx,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000289 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattnereaf24722005-08-04 17:40:30 +0000290 TypeSize)));
291 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000292 }
293 }
294
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000295 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000296 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000297}
298
Chris Lattneracc42c42005-08-04 19:08:16 +0000299/// getSCEVStartAndStride - Compute the start and stride of this expression,
300/// returning false if the expression is not a start/stride pair, or true if it
301/// is. The stride must be a loop invariant expression, but the start may be
302/// a mix of loop invariant and loop variant expressions.
303static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000304 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000305 SCEVHandle TheAddRec = Start; // Initialize to zero.
306
307 // If the outer level is an AddExpr, the operands are all start values except
308 // for a nested AddRecExpr.
309 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
310 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
311 if (SCEVAddRecExpr *AddRec =
312 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
313 if (AddRec->getLoop() == L)
314 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
315 else
316 return false; // Nested IV of some sort?
317 } else {
318 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
319 }
320
Reid Spencerde46e482006-11-02 20:25:50 +0000321 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000322 TheAddRec = SH;
323 } else {
324 return false; // not analyzable.
325 }
326
327 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
328 if (!AddRec || AddRec->getLoop() != L) return false;
329
330 // FIXME: Generalize to non-affine IV's.
331 if (!AddRec->isAffine()) return false;
332
333 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
334
Chris Lattneracc42c42005-08-04 19:08:16 +0000335 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000336 DOUT << "[" << L->getHeader()->getName()
337 << "] Variable stride: " << *AddRec << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000338
Chris Lattneredff91a2005-08-10 00:45:21 +0000339 Stride = AddRec->getOperand(1);
Chris Lattneracc42c42005-08-04 19:08:16 +0000340 return true;
341}
342
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000343/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
344/// and now we need to decide whether the user should use the preinc or post-inc
345/// value. If this user should use the post-inc version of the IV, return true.
346///
347/// Choosing wrong here can break dominance properties (if we choose to use the
348/// post-inc value when we cannot) or it can end up adding extra live-ranges to
349/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
350/// should use the post-inc value).
351static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000352 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000353 // If the user is in the loop, use the preinc value.
354 if (L->contains(User->getParent())) return false;
355
Chris Lattnerf07a5872005-10-03 02:50:05 +0000356 BasicBlock *LatchBlock = L->getLoopLatch();
357
358 // Ok, the user is outside of the loop. If it is dominated by the latch
359 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000360 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000361 return true;
362
363 // There is one case we have to be careful of: PHI nodes. These little guys
364 // can live in blocks that do not dominate the latch block, but (since their
365 // uses occur in the predecessor block, not the block the PHI lives in) should
366 // still use the post-inc value. Check for this case now.
367 PHINode *PN = dyn_cast<PHINode>(User);
368 if (!PN) return false; // not a phi, not dominated by latch block.
369
370 // Look at all of the uses of IV by the PHI node. If any use corresponds to
371 // a block that is not dominated by the latch block, give up and use the
372 // preincremented value.
373 unsigned NumUses = 0;
374 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
375 if (PN->getIncomingValue(i) == IV) {
376 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000377 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000378 return false;
379 }
380
381 // Okay, all uses of IV by PN are in predecessor blocks that really are
382 // dominated by the latch block. Split the critical edges and use the
383 // post-incremented value.
384 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
385 if (PN->getIncomingValue(i) == IV) {
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000386 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
387 true);
Chris Lattner5191c652006-10-28 00:59:20 +0000388 // Splitting the critical edge can reduce the number of entries in this
389 // PHI.
390 e = PN->getNumIncomingValues();
Chris Lattnerf07a5872005-10-03 02:50:05 +0000391 if (--NumUses == 0) break;
392 }
393
394 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000395}
396
397
398
Nate Begemane68bcd12005-07-30 00:15:07 +0000399/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
400/// reducible SCEV, recursively add its users to the IVUsesByStride set and
401/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000402bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
403 std::set<Instruction*> &Processed) {
Chris Lattner03c49532007-01-15 02:27:26 +0000404 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
Chris Lattner5df0e362005-10-21 05:45:41 +0000405 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000406 if (!Processed.insert(I).second)
407 return true; // Instruction already handled.
408
Chris Lattneracc42c42005-08-04 19:08:16 +0000409 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000410 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000411 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000412
Chris Lattneracc42c42005-08-04 19:08:16 +0000413 // Get the start and stride for this expression.
414 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000415 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000416 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
417 return false; // Non-reducible symbolic expression, bail out.
Devang Patel58818c52007-03-09 21:19:53 +0000418
Devang Patel38bc86f2007-04-23 22:42:03 +0000419 std::vector<Instruction *> IUsers;
420 // Collect all I uses now because IVUseShouldUsePostIncValue may
421 // invalidate use_iterator.
422 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
423 IUsers.push_back(cast<Instruction>(*UI));
Nate Begemane68bcd12005-07-30 00:15:07 +0000424
Devang Patel38bc86f2007-04-23 22:42:03 +0000425 for (unsigned iused_index = 0, iused_size = IUsers.size();
426 iused_index != iused_size; ++iused_index) {
427
428 Instruction *User = IUsers[iused_index];
Devang Patel58818c52007-03-09 21:19:53 +0000429
Nate Begemane68bcd12005-07-30 00:15:07 +0000430 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000431 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000432 continue;
433
434 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000435 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000436 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000437 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000438 DOUT << "FOUND USER in other loop: " << *User
439 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000440 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000441 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000442 DOUT << "FOUND USER: " << *User
443 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000444 AddUserToIVUsers = true;
445 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000446
Chris Lattneracc42c42005-08-04 19:08:16 +0000447 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000448 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
449 if (StrideUses.Users.empty()) // First occurance of this stride?
450 StrideOrder.push_back(Stride);
451
Chris Lattner65107492005-08-04 00:40:47 +0000452 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000453 // and decide what to do with it. If we are a use inside of the loop, use
454 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000455 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000456 // The value used will be incremented by the stride more than we are
457 // expecting, so subtract this off.
458 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000459 StrideUses.addUser(NewStart, User, I);
460 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000461 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000462 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000463 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000464 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000465 }
466 }
467 return true;
468}
469
470namespace {
471 /// BasedUser - For a particular base value, keep information about how we've
472 /// partitioned the expression so far.
473 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000474 /// Base - The Base value for the PHI node that needs to be inserted for
475 /// this use. As the use is processed, information gets moved from this
476 /// field to the Imm field (below). BasedUser values are sorted by this
477 /// field.
478 SCEVHandle Base;
479
Nate Begemane68bcd12005-07-30 00:15:07 +0000480 /// Inst - The instruction using the induction variable.
481 Instruction *Inst;
482
Chris Lattner430d0022005-08-03 22:21:05 +0000483 /// OperandValToReplace - The operand value of Inst to replace with the
484 /// EmittedBase.
485 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000486
487 /// Imm - The immediate value that should be added to the base immediately
488 /// before Inst, because it will be folded into the imm field of the
489 /// instruction.
490 SCEVHandle Imm;
491
492 /// EmittedBase - The actual value* to use for the base value of this
493 /// operation. This is null if we should just use zero so far.
494 Value *EmittedBase;
495
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000496 // isUseOfPostIncrementedValue - True if this should use the
497 // post-incremented version of this IV, not the preincremented version.
498 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000499 // instruction for a loop and uses outside the loop that are dominated by
500 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000501 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000502
503 BasedUser(IVStrideUse &IVSU)
504 : Base(IVSU.Offset), Inst(IVSU.User),
505 OperandValToReplace(IVSU.OperandValToReplace),
506 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
507 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000508
Chris Lattnera6d7c352005-08-04 20:03:32 +0000509 // Once we rewrite the code to insert the new IVs we want, update the
510 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
511 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000512 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000513 SCEVExpander &Rewriter, Loop *L,
514 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000515
516 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
517 SCEVExpander &Rewriter,
518 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000519 void dump() const;
520 };
521}
522
523void BasedUser::dump() const {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000524 cerr << " Base=" << *Base;
525 cerr << " Imm=" << *Imm;
Nate Begemane68bcd12005-07-30 00:15:07 +0000526 if (EmittedBase)
Bill Wendlingf3baad32006-12-07 01:30:32 +0000527 cerr << " EB=" << *EmittedBase;
Nate Begemane68bcd12005-07-30 00:15:07 +0000528
Bill Wendlingf3baad32006-12-07 01:30:32 +0000529 cerr << " Inst: " << *Inst;
Nate Begemane68bcd12005-07-30 00:15:07 +0000530}
531
Chris Lattner2959f002006-02-04 07:36:50 +0000532Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
533 SCEVExpander &Rewriter,
534 Instruction *IP, Loop *L) {
535 // Figure out where we *really* want to insert this code. In particular, if
536 // the user is inside of a loop that is nested inside of L, we really don't
537 // want to insert this expression before the user, we'd rather pull it out as
538 // many loops as possible.
539 LoopInfo &LI = Rewriter.getLoopInfo();
540 Instruction *BaseInsertPt = IP;
541
542 // Figure out the most-nested loop that IP is in.
543 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
544
545 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
546 // the preheader of the outer-most loop where NewBase is not loop invariant.
547 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
548 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
549 InsertLoop = InsertLoop->getParentLoop();
550 }
551
552 // If there is no immediate value, skip the next part.
553 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
Reid Spencer53a37392007-03-02 23:51:25 +0000554 if (SC->getValue()->isZero())
Chris Lattner2959f002006-02-04 07:36:50 +0000555 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
556 OperandValToReplace->getType());
557
558 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
559
560 // Always emit the immediate (if non-zero) into the same block as the user.
561 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
562 return Rewriter.expandCodeFor(NewValSCEV, IP,
563 OperandValToReplace->getType());
564}
565
566
Chris Lattnera6d7c352005-08-04 20:03:32 +0000567// Once we rewrite the code to insert the new IVs we want, update the
568// operands of Inst to use the new expression 'NewBase', with 'Imm' added
569// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000570void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000571 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000572 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000573 if (!isa<PHINode>(Inst)) {
Chris Lattnerefd30512007-04-13 20:42:26 +0000574 // By default, insert code at the user instruction.
575 BasicBlock::iterator InsertPt = Inst;
576
577 // However, if the Operand is itself an instruction, the (potentially
578 // complex) inserted code may be shared by many users. Because of this, we
579 // want to emit code for the computation of the operand right before its old
580 // computation. This is usually safe, because we obviously used to use the
581 // computation when it was computed in its current block. However, in some
582 // cases (e.g. use of a post-incremented induction variable) the NewBase
583 // value will be pinned to live somewhere after the original computation.
584 // In this case, we have to back off.
585 if (!isUseOfPostIncrementedValue) {
586 if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) {
587 InsertPt = OpInst;
588 while (isa<PHINode>(InsertPt)) ++InsertPt;
589 }
590 }
591
592 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000593 // Replace the use of the operand Value with the new Phi we just created.
594 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000595 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000596 return;
597 }
598
599 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000600 // expression into each operand block that uses it. Note that PHI nodes can
601 // have multiple entries for the same predecessor. We use a map to make sure
602 // that a PHI node only has a single Value* for each predecessor (which also
603 // prevents us from inserting duplicate code in some blocks).
604 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000605 PHINode *PN = cast<PHINode>(Inst);
606 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
607 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000608 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000609 // code on all predecessor/successor paths. We do this unless this is the
610 // canonical backedge for this loop, as this can make some inserted code
611 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000612 BasicBlock *PHIPred = PN->getIncomingBlock(i);
613 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
614 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000615
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000616 // First step, split the critical edge.
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000617 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattner8447b492005-08-12 22:22:17 +0000618
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000619 // Next step: move the basic block. In particular, if the PHI node
620 // is outside of the loop, and PredTI is in the loop, we want to
621 // move the block to be immediately before the PHI block, not
622 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000623 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000624 BasicBlock *NewBB = PN->getIncomingBlock(i);
625 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000626 }
Chris Lattner5191c652006-10-28 00:59:20 +0000627
628 // Splitting the edge can reduce the number of PHI entries we have.
629 e = PN->getNumIncomingValues();
Chris Lattner4fec86d2005-08-12 22:06:11 +0000630 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000631
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000632 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
633 if (!Code) {
634 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000635 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
636 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000637 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000638
639 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000640 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000641 Rewriter.clear();
642 }
643 }
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000644 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000645}
646
647
Nate Begemane68bcd12005-07-30 00:15:07 +0000648/// isTargetConstant - Return true if the following can be referenced by the
649/// immediate field of a target instruction.
Evan Chengb5eb9322007-03-13 20:34:37 +0000650static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
651 const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000652 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Evan Cheng720acdf2007-03-12 23:27:37 +0000653 int64_t VC = SC->getValue()->getSExtValue();
Chris Lattner780c0092007-04-09 22:20:14 +0000654 if (TLI) {
655 TargetLowering::AddrMode AM;
656 AM.BaseOffs = VC;
657 return TLI->isLegalAddressingMode(AM, UseTy);
658 } else {
Evan Chengc567c4e2006-03-13 23:14:23 +0000659 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
Evan Cheng720acdf2007-03-12 23:27:37 +0000660 return (VC > -(1 << 16) && VC < (1 << 16)-1);
Chris Lattner780c0092007-04-09 22:20:14 +0000661 }
Chris Lattner14203e82005-08-08 06:25:50 +0000662 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000663
Nate Begemane68bcd12005-07-30 00:15:07 +0000664 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
665 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Chris Lattner780c0092007-04-09 22:20:14 +0000666 if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengc567c4e2006-03-13 23:14:23 +0000667 Constant *Op0 = CE->getOperand(0);
Chris Lattner780c0092007-04-09 22:20:14 +0000668 if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
669 TargetLowering::AddrMode AM;
670 AM.BaseGV = GV;
671 return TLI->isLegalAddressingMode(AM, UseTy);
672 }
Evan Chengc567c4e2006-03-13 23:14:23 +0000673 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000674 return false;
675}
676
Chris Lattner37ed8952005-08-08 22:32:34 +0000677/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
678/// loop varying to the Imm operand.
679static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
680 Loop *L) {
681 if (Val->isLoopInvariant(L)) return; // Nothing to do.
682
683 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
684 std::vector<SCEVHandle> NewOps;
685 NewOps.reserve(SAE->getNumOperands());
686
687 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
688 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
689 // If this is a loop-variant expression, it must stay in the immediate
690 // field of the expression.
691 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
692 } else {
693 NewOps.push_back(SAE->getOperand(i));
694 }
695
696 if (NewOps.empty())
697 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
698 else
699 Val = SCEVAddExpr::get(NewOps);
700 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
701 // Try to pull immediates out of the start value of nested addrec's.
702 SCEVHandle Start = SARE->getStart();
703 MoveLoopVariantsToImediateField(Start, Imm, L);
704
705 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
706 Ops[0] = Start;
707 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
708 } else {
709 // Otherwise, all of Val is variant, move the whole thing over.
710 Imm = SCEVAddExpr::get(Imm, Val);
711 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
712 }
713}
714
715
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000716/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000717/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000718/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000719static void MoveImmediateValues(const TargetLowering *TLI,
Evan Chengb5eb9322007-03-13 20:34:37 +0000720 Instruction *User,
Evan Chengc567c4e2006-03-13 23:14:23 +0000721 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000722 bool isAddress, Loop *L) {
Evan Chengb5eb9322007-03-13 20:34:37 +0000723 const Type *UseTy = User->getType();
724 if (StoreInst *SI = dyn_cast<StoreInst>(User))
725 UseTy = SI->getOperand(0)->getType();
726
Chris Lattnerfc624702005-08-03 23:44:42 +0000727 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000728 std::vector<SCEVHandle> NewOps;
729 NewOps.reserve(SAE->getNumOperands());
730
Chris Lattner2959f002006-02-04 07:36:50 +0000731 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
732 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengb5eb9322007-03-13 20:34:37 +0000733 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000734
735 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000736 // If this is a loop-variant expression, it must stay in the immediate
737 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000738 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000739 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000740 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000741 }
Chris Lattner2959f002006-02-04 07:36:50 +0000742 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000743
744 if (NewOps.empty())
745 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
746 else
747 Val = SCEVAddExpr::get(NewOps);
748 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000749 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
750 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000751 SCEVHandle Start = SARE->getStart();
Evan Chengb5eb9322007-03-13 20:34:37 +0000752 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000753
754 if (Start != SARE->getStart()) {
755 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
756 Ops[0] = Start;
757 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
758 }
759 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000760 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
761 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengb5eb9322007-03-13 20:34:37 +0000762 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000763 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
764
765 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
766 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengb5eb9322007-03-13 20:34:37 +0000767 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000768
769 // If we extracted something out of the subexpressions, see if we can
770 // simplify this!
771 if (NewOp != SME->getOperand(1)) {
772 // Scale SubImm up by "8". If the result is a target constant, we are
773 // good.
774 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengb5eb9322007-03-13 20:34:37 +0000775 if (isTargetConstant(SubImm, UseTy, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000776 // Accumulate the immediate.
777 Imm = SCEVAddExpr::get(Imm, SubImm);
778
779 // Update what is left of 'Val'.
780 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
781 return;
782 }
783 }
784 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000785 }
786
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000787 // Loop-variant expressions must stay in the immediate field of the
788 // expression.
Evan Chengb5eb9322007-03-13 20:34:37 +0000789 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000790 !Val->isLoopInvariant(L)) {
791 Imm = SCEVAddExpr::get(Imm, Val);
792 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
793 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000794 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000795
796 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000797}
798
Chris Lattner5949d492005-08-13 07:27:18 +0000799
Chris Lattner3ff62012006-08-03 06:34:50 +0000800/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
801/// added together. This is used to reassociate common addition subexprs
802/// together for maximal sharing when rewriting bases.
Chris Lattner5949d492005-08-13 07:27:18 +0000803static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
804 SCEVHandle Expr) {
805 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
806 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
807 SeparateSubExprs(SubExprs, AE->getOperand(j));
808 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
809 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
810 if (SARE->getOperand(0) == Zero) {
811 SubExprs.push_back(Expr);
812 } else {
813 // Compute the addrec with zero as its base.
814 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
815 Ops[0] = Zero; // Start with zero base.
816 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
817
818
819 SeparateSubExprs(SubExprs, SARE->getOperand(0));
820 }
821 } else if (!isa<SCEVConstant>(Expr) ||
Reid Spencer53a37392007-03-02 23:51:25 +0000822 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
Chris Lattner5949d492005-08-13 07:27:18 +0000823 // Do not add zero.
824 SubExprs.push_back(Expr);
825 }
826}
827
828
Chris Lattnera091ff12005-08-09 00:18:09 +0000829/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
830/// removing any common subexpressions from it. Anything truly common is
831/// removed, accumulated, and returned. This looks for things like (a+b+c) and
832/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
833static SCEVHandle
834RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
835 unsigned NumUses = Uses.size();
836
837 // Only one use? Use its base, regardless of what it is!
838 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
839 SCEVHandle Result = Zero;
840 if (NumUses == 1) {
841 std::swap(Result, Uses[0].Base);
842 return Result;
843 }
844
845 // To find common subexpressions, count how many of Uses use each expression.
846 // If any subexpressions are used Uses.size() times, they are common.
847 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
848
Chris Lattner192cd182005-10-11 18:41:04 +0000849 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
850 // order we see them.
851 std::vector<SCEVHandle> UniqueSubExprs;
852
Chris Lattner5949d492005-08-13 07:27:18 +0000853 std::vector<SCEVHandle> SubExprs;
854 for (unsigned i = 0; i != NumUses; ++i) {
855 // If the base is zero (which is common), return zero now, there are no
856 // CSEs we can find.
857 if (Uses[i].Base == Zero) return Zero;
858
859 // Split the expression into subexprs.
860 SeparateSubExprs(SubExprs, Uses[i].Base);
861 // Add one to SubExpressionUseCounts for each subexpr present.
862 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000863 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
864 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000865 SubExprs.clear();
866 }
867
Chris Lattner192cd182005-10-11 18:41:04 +0000868 // Now that we know how many times each is used, build Result. Iterate over
869 // UniqueSubexprs so that we have a stable ordering.
870 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
871 std::map<SCEVHandle, unsigned>::iterator I =
872 SubExpressionUseCounts.find(UniqueSubExprs[i]);
873 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000874 if (I->second == NumUses) { // Found CSE!
875 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000876 } else {
877 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000878 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000879 }
Chris Lattner192cd182005-10-11 18:41:04 +0000880 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000881
882 // If we found no CSE's, return now.
883 if (Result == Zero) return Result;
884
885 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000886 for (unsigned i = 0; i != NumUses; ++i) {
887 // Split the expression into subexprs.
888 SeparateSubExprs(SubExprs, Uses[i].Base);
889
890 // Remove any common subexpressions.
891 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
892 if (SubExpressionUseCounts.count(SubExprs[j])) {
893 SubExprs.erase(SubExprs.begin()+j);
894 --j; --e;
895 }
896
897 // Finally, the non-shared expressions together.
898 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000899 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000900 else
901 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000902 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000903 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000904
905 return Result;
906}
907
Evan Cheng3df447d2006-03-16 21:53:05 +0000908/// isZero - returns true if the scalar evolution expression is zero.
909///
910static bool isZero(SCEVHandle &V) {
911 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencer53a37392007-03-02 23:51:25 +0000912 return SC->getValue()->isZero();
Evan Cheng3df447d2006-03-16 21:53:05 +0000913 return false;
914}
915
Dale Johannesene3a02be2007-03-20 00:47:50 +0000916/// ValidStride - Check whether the given Scale is valid for all loads and
Chris Lattner780c0092007-04-09 22:20:14 +0000917/// stores in UsersToProcess.
Dale Johannesene3a02be2007-03-20 00:47:50 +0000918///
919bool LoopStrengthReduce::ValidStride(int64_t Scale,
920 const std::vector<BasedUser>& UsersToProcess) {
Dale Johannesenbacf4ac2007-03-20 21:54:54 +0000921 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
Chris Lattner28e0e4e2007-04-02 06:34:44 +0000922 // If this is a load or other access, pass the type of the access in.
923 const Type *AccessTy = Type::VoidTy;
924 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
925 AccessTy = SI->getOperand(0)->getType();
926 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
927 AccessTy = LI->getType();
928
Chris Lattner780c0092007-04-09 22:20:14 +0000929 TargetLowering::AddrMode AM;
930 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
931 AM.BaseOffs = SC->getValue()->getSExtValue();
932 AM.Scale = Scale;
933
934 // If load[imm+r*scale] is illegal, bail out.
935 if (!TLI->isLegalAddressingMode(AM, AccessTy))
Dale Johannesene3a02be2007-03-20 00:47:50 +0000936 return false;
Dale Johannesenbacf4ac2007-03-20 21:54:54 +0000937 }
Dale Johannesene3a02be2007-03-20 00:47:50 +0000938 return true;
939}
Chris Lattnera091ff12005-08-09 00:18:09 +0000940
Evan Cheng45206982006-03-17 19:52:23 +0000941/// CheckForIVReuse - Returns the multiple if the stride is the multiple
942/// of a previous stride and it is a legal value for the target addressing
943/// mode scale component. This allows the users of this stride to be rewritten
Evan Chengc28282b2006-03-18 08:03:12 +0000944/// as prev iv * factor. It returns 0 if no reuse is possible.
Dale Johannesene3a02be2007-03-20 00:47:50 +0000945unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
946 IVExpr &IV, const Type *Ty,
947 const std::vector<BasedUser>& UsersToProcess) {
Evan Chengc28282b2006-03-18 08:03:12 +0000948 if (!TLI) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000949
950 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Reid Spencerba547cb2007-03-02 23:37:53 +0000951 int64_t SInt = SC->getValue()->getSExtValue();
952 if (SInt == 1) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000953
Evan Cheng720acdf2007-03-12 23:27:37 +0000954 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
955 SE = IVsByStride.end(); SI != SE; ++SI) {
956 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Chris Lattnerf3197a72007-04-02 22:51:58 +0000957 if (SInt != -SSInt &&
958 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
Evan Cheng45206982006-03-17 19:52:23 +0000959 continue;
Evan Cheng720acdf2007-03-12 23:27:37 +0000960 int64_t Scale = SInt / SSInt;
Dale Johannesene3a02be2007-03-20 00:47:50 +0000961 // Check that this stride is valid for all the types used for loads and
962 // stores; if it can be used for some and not others, we might as well use
963 // the original stride everywhere, since we have to create the IV for it
964 // anyway.
965 if (ValidStride(Scale, UsersToProcess))
Evan Cheng720acdf2007-03-12 23:27:37 +0000966 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
967 IE = SI->second.IVs.end(); II != IE; ++II)
968 // FIXME: Only handle base == 0 for now.
969 // Only reuse previous IV if it would not require a type conversion.
970 if (isZero(II->Base) && II->Base->getType() == Ty) {
971 IV = *II;
972 return Scale;
973 }
Evan Cheng45206982006-03-17 19:52:23 +0000974 }
975 }
Evan Chengc28282b2006-03-18 08:03:12 +0000976 return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000977}
978
Chris Lattner3ff62012006-08-03 06:34:50 +0000979/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
980/// returns true if Val's isUseOfPostIncrementedValue is true.
981static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
982 return Val.isUseOfPostIncrementedValue;
983}
Evan Cheng45206982006-03-17 19:52:23 +0000984
Nate Begemane68bcd12005-07-30 00:15:07 +0000985/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
986/// stride of IV. All of the users may have different starting values, and this
987/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000988void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000989 IVUsersOfOneStride &Uses,
990 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000991 bool isOnlyStride) {
992 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000993 // this new vector, each 'BasedUser' contains 'Base' the base of the
994 // strided accessas well as the old information from Uses. We progressively
995 // move information from the Base field to the Imm field, until we eventually
996 // have the full access expression to rewrite the use.
997 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000998 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000999 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1000 UsersToProcess.push_back(Uses.Users[i]);
1001
1002 // Move any loop invariant operands from the offset field to the immediate
1003 // field of the use, so that we don't try to use something before it is
1004 // computed.
1005 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
1006 UsersToProcess.back().Imm, L);
1007 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +00001008 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001009 }
Evan Cheng45206982006-03-17 19:52:23 +00001010
Chris Lattnera091ff12005-08-09 00:18:09 +00001011 // We now have a whole bunch of uses of like-strided induction variables, but
1012 // they might all have different bases. We want to emit one PHI node for this
1013 // stride which we fold as many common expressions (between the IVs) into as
1014 // possible. Start by identifying the common expressions in the base values
1015 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1016 // "A+B"), emit it to the preheader, then remove the expression from the
1017 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +00001018 SCEVHandle CommonExprs =
1019 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +00001020
Chris Lattner37ed8952005-08-08 22:32:34 +00001021 // Next, figure out what we can represent in the immediate fields of
1022 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +00001023 // fields of the BasedUsers. We do this so that it increases the commonality
1024 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +00001025 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +00001026 // If the user is not in the current loop, this means it is using the exit
1027 // value of the IV. Do not put anything in the base, make sure it's all in
1028 // the immediate field to allow as much factoring as possible.
1029 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +00001030 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
1031 UsersToProcess[i].Base);
1032 UsersToProcess[i].Base =
1033 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +00001034 } else {
1035
1036 // Addressing modes can be folded into loads and stores. Be careful that
1037 // the store is through the expression, not of the expression though.
1038 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1039 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
1040 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1041 isAddress = true;
1042
Evan Chengb5eb9322007-03-13 20:34:37 +00001043 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1044 UsersToProcess[i].Imm, isAddress, L);
Chris Lattner5cf983e2005-08-16 00:38:11 +00001045 }
Chris Lattner37ed8952005-08-08 22:32:34 +00001046 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001047
Dale Johannesenbacf4ac2007-03-20 21:54:54 +00001048 // Check if it is possible to reuse a IV with stride that is factor of this
1049 // stride. And the multiple is a number that can be encoded in the scale
1050 // field of the target addressing mode. And we will have a valid
1051 // instruction after this substition, including the immediate field, if any.
1052 PHINode *NewPHI = NULL;
1053 Value *IncV = NULL;
1054 IVExpr ReuseIV;
1055 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1056 CommonExprs->getType(),
1057 UsersToProcess);
1058 if (RewriteFactor != 0) {
1059 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1060 << " and BASE " << *ReuseIV.Base << " :\n";
1061 NewPHI = ReuseIV.PHI;
1062 IncV = ReuseIV.IncV;
1063 }
1064
Chris Lattner8fe3cbe2007-04-01 22:21:39 +00001065 const Type *ReplacedTy = CommonExprs->getType();
1066
Chris Lattnera091ff12005-08-09 00:18:09 +00001067 // Now that we know what we need to do, insert the PHI node itself.
1068 //
Chris Lattner8fe3cbe2007-04-01 22:21:39 +00001069 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1070 << *Stride << " and BASE " << *CommonExprs << " :\n";
Evan Cheng3df447d2006-03-16 21:53:05 +00001071
Chris Lattnera091ff12005-08-09 00:18:09 +00001072 SCEVExpander Rewriter(*SE, *LI);
1073 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +00001074
Chris Lattnera091ff12005-08-09 00:18:09 +00001075 BasicBlock *Preheader = L->getLoopPreheader();
1076 Instruction *PreInsertPt = Preheader->getTerminator();
1077 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +00001078
Chris Lattner8048b852005-09-12 17:11:27 +00001079 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +00001080
Evan Cheng45206982006-03-17 19:52:23 +00001081
1082 // Emit the initial base value into the loop preheader.
1083 Value *CommonBaseV
1084 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1085 ReplacedTy);
1086
Evan Chengc28282b2006-03-18 08:03:12 +00001087 if (RewriteFactor == 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001088 // Create a new Phi for this base, and stick it in the loop header.
1089 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1090 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001091
Evan Cheng45206982006-03-17 19:52:23 +00001092 // Add common base to the new Phi node.
1093 NewPHI->addIncoming(CommonBaseV, Preheader);
1094
Evan Cheng3df447d2006-03-16 21:53:05 +00001095 // Insert the stride into the preheader.
1096 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1097 ReplacedTy);
1098 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001099
Evan Cheng3df447d2006-03-16 21:53:05 +00001100 // Emit the increment of the base value before the terminator of the loop
1101 // latch block, and add it to the Phi node.
1102 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1103 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +00001104
Evan Cheng3df447d2006-03-16 21:53:05 +00001105 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1106 ReplacedTy);
1107 IncV->setName(NewPHI->getName()+".inc");
1108 NewPHI->addIncoming(IncV, LatchBlock);
1109
Evan Cheng45206982006-03-17 19:52:23 +00001110 // Remember this in case a later stride is multiple of this.
Evan Chengc28282b2006-03-18 08:03:12 +00001111 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Cheng45206982006-03-17 19:52:23 +00001112 } else {
1113 Constant *C = dyn_cast<Constant>(CommonBaseV);
1114 if (!C ||
1115 (!C->isNullValue() &&
Evan Chengb5eb9322007-03-13 20:34:37 +00001116 !isTargetConstant(SCEVUnknown::get(CommonBaseV), ReplacedTy, TLI)))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001117 // We want the common base emitted into the preheader! This is just
1118 // using cast as a copy so BitCast (no-op cast) is appropriate
1119 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1120 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001121 }
Chris Lattnera091ff12005-08-09 00:18:09 +00001122
Chris Lattner3ff62012006-08-03 06:34:50 +00001123 // We want to emit code for users inside the loop first. To do this, we
1124 // rearrange BasedUser so that the entries at the end have
1125 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1126 // vector (so we handle them first).
1127 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1128 PartitionByIsUseOfPostIncrementedValue);
1129
1130 // Sort this by base, so that things with the same base are handled
1131 // together. By partitioning first and stable-sorting later, we are
1132 // guaranteed that within each base we will pop off users from within the
1133 // loop before users outside of the loop with a particular base.
1134 //
1135 // We would like to use stable_sort here, but we can't. The problem is that
1136 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1137 // we don't have anything to do a '<' comparison on. Because we think the
1138 // number of uses is small, do a horrible bubble sort which just relies on
1139 // ==.
1140 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1141 // Get a base value.
1142 SCEVHandle Base = UsersToProcess[i].Base;
1143
1144 // Compact everything with this base to be consequetive with this one.
1145 for (unsigned j = i+1; j != e; ++j) {
1146 if (UsersToProcess[j].Base == Base) {
1147 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1148 ++i;
1149 }
1150 }
1151 }
1152
1153 // Process all the users now. This outer loop handles all bases, the inner
1154 // loop handles all users of a particular base.
Nate Begemane68bcd12005-07-30 00:15:07 +00001155 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001156 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001157
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001158 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
Chris Lattnerbb78c972005-08-03 23:30:08 +00001159
Chris Lattnera091ff12005-08-09 00:18:09 +00001160 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001161 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1162 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +00001163
1164 // If BaseV is a constant other than 0, make sure that it gets inserted into
1165 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001166 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1167 // in this case.
Chris Lattner3ff62012006-08-03 06:34:50 +00001168 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengb5eb9322007-03-13 20:34:37 +00001169 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001170 // We want this constant emitted into the preheader! This is just
1171 // using cast as a copy so BitCast (no-op cast) is appropriate
1172 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattnera091ff12005-08-09 00:18:09 +00001173 PreInsertPt);
1174 }
Chris Lattner3ff62012006-08-03 06:34:50 +00001175 }
1176
Nate Begemane68bcd12005-07-30 00:15:07 +00001177 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001178 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001179 do {
Chris Lattner3ff62012006-08-03 06:34:50 +00001180 // FIXME: Use emitted users to emit other users.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001181 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001182
Chris Lattnera091ff12005-08-09 00:18:09 +00001183 // If this instruction wants to use the post-incremented value, move it
1184 // after the post-inc and use its value instead of the PHI.
1185 Value *RewriteOp = NewPHI;
1186 if (User.isUseOfPostIncrementedValue) {
1187 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001188
1189 // If this user is in the loop, make sure it is the last thing in the
1190 // loop to ensure it is dominated by the increment.
1191 if (L->contains(User.Inst->getParent()))
1192 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001193 }
Reid Spencerdf1f19a2006-12-13 08:06:42 +00001194 if (RewriteOp->getType() != ReplacedTy) {
1195 Instruction::CastOps opcode = Instruction::Trunc;
1196 if (ReplacedTy->getPrimitiveSizeInBits() ==
1197 RewriteOp->getType()->getPrimitiveSizeInBits())
1198 opcode = Instruction::BitCast;
1199 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1200 }
Evan Cheng398f7022006-06-09 00:12:42 +00001201
Chris Lattnera091ff12005-08-09 00:18:09 +00001202 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1203
Chris Lattnerdb23c742005-08-03 22:51:21 +00001204 // Clear the SCEVExpander's expression map so that we are guaranteed
1205 // to have the code emitted where we expect it.
1206 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001207
1208 // If we are reusing the iv, then it must be multiplied by a constant
1209 // factor take advantage of addressing mode scale component.
Evan Chengc28282b2006-03-18 08:03:12 +00001210 if (RewriteFactor != 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001211 RewriteExpr =
1212 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001213 RewriteExpr->getType()),
1214 RewriteExpr);
1215
1216 // The common base is emitted in the loop preheader. But since we
1217 // are reusing an IV, it has not been used to initialize the PHI node.
1218 // Add it to the expression used to rewrite the uses.
1219 if (!isa<ConstantInt>(CommonBaseV) ||
Reid Spencer53a37392007-03-02 23:51:25 +00001220 !cast<ConstantInt>(CommonBaseV)->isZero())
Evan Cheng45206982006-03-17 19:52:23 +00001221 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1222 SCEVUnknown::get(CommonBaseV));
1223 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001224
Chris Lattnera6d7c352005-08-04 20:03:32 +00001225 // Now that we know what we need to do, insert code before User for the
1226 // immediate and any loop-variant expressions.
Reid Spencer53a37392007-03-02 23:51:25 +00001227 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
Chris Lattnera091ff12005-08-09 00:18:09 +00001228 // Add BaseV to the PHI value if needed.
1229 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001230
Chris Lattner8447b492005-08-12 22:22:17 +00001231 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001232
Chris Lattnerdb23c742005-08-03 22:51:21 +00001233 // Mark old value we replaced as possibly dead, so that it is elminated
1234 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001235 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001236
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001237 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001238 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001239
Chris Lattner3ff62012006-08-03 06:34:50 +00001240 // If there are any more users to process with the same base, process them
1241 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001242 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001243 // TODO: Next, find out which base index is the most common, pull it out.
1244 }
1245
1246 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1247 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001248}
1249
Chris Lattner81e07072007-04-03 05:11:24 +00001250/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1251/// set the IV user and stride information and return true, otherwise return
1252/// false.
1253bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1254 const SCEVHandle *&CondStride) {
1255 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1256 ++Stride) {
1257 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1258 IVUsesByStride.find(StrideOrder[Stride]);
1259 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1260
1261 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1262 E = SI->second.Users.end(); UI != E; ++UI)
1263 if (UI->User == Cond) {
1264 // NOTE: we could handle setcc instructions with multiple uses here, but
1265 // InstCombine does it as well for simple uses, it's not clear that it
1266 // occurs enough in real life to handle.
1267 CondUse = &*UI;
1268 CondStride = &SI->first;
1269 return true;
1270 }
1271 }
1272 return false;
1273}
1274
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001275// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1276// uses in the loop, look to see if we can eliminate some, in favor of using
1277// common indvars for the different uses.
1278void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1279 // TODO: implement optzns here.
1280
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001281 // Finally, get the terminating condition for the loop if possible. If we
1282 // can, we want to change it to use a post-incremented version of its
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001283 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001284 // one register value.
1285 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1286 BasicBlock *Preheader = L->getLoopPreheader();
1287 BasicBlock *LatchBlock =
1288 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1289 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001290 if (!TermBr || TermBr->isUnconditional() ||
1291 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001292 return;
Reid Spencer266e42b2006-12-23 06:05:41 +00001293 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001294
1295 // Search IVUsesByStride to find Cond's IVUse if there is one.
1296 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001297 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001298
Chris Lattner81e07072007-04-03 05:11:24 +00001299 if (!FindIVForUser(Cond, CondUse, CondStride))
1300 return; // setcc doesn't use the IV.
1301
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001302
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001303 // It's possible for the setcc instruction to be anywhere in the loop, and
1304 // possible for it to have multiple users. If it is not immediately before
1305 // the latch block branch, move it.
1306 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1307 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1308 Cond->moveBefore(TermBr);
1309 } else {
1310 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencer266e42b2006-12-23 06:05:41 +00001311 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001312 Cond->setName(L->getHeader()->getName() + ".termcond");
1313 LatchBlock->getInstList().insert(TermBr, Cond);
1314
1315 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001316 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001317 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001318 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001319 }
1320 }
1321
1322 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001323 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001324 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001325 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001326 CondUse->isUseOfPostIncrementedValue = true;
1327}
Nate Begemane68bcd12005-07-30 00:15:07 +00001328
Evan Chengf09f0eb2006-03-18 00:44:49 +00001329namespace {
1330 // Constant strides come first which in turns are sorted by their absolute
1331 // values. If absolute values are the same, then positive strides comes first.
1332 // e.g.
1333 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1334 struct StrideCompare {
1335 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1336 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1337 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1338 if (LHSC && RHSC) {
Reid Spencer197adfa2007-03-02 00:31:39 +00001339 int64_t LV = LHSC->getValue()->getSExtValue();
1340 int64_t RV = RHSC->getValue()->getSExtValue();
1341 uint64_t ALV = (LV < 0) ? -LV : LV;
1342 uint64_t ARV = (RV < 0) ? -RV : RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001343 if (ALV == ARV)
Reid Spencer197adfa2007-03-02 00:31:39 +00001344 return LV > RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001345 else
Reid Spencer197adfa2007-03-02 00:31:39 +00001346 return ALV < ARV;
Chris Lattner7d80b4f2006-03-22 17:27:24 +00001347 }
1348 return (LHSC && !RHSC);
Evan Chengf09f0eb2006-03-18 00:44:49 +00001349 }
1350 };
1351}
1352
Devang Patelb0743b52007-03-06 21:14:09 +00001353bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
Nate Begemanb18121e2004-10-18 21:08:22 +00001354
Devang Patelb0743b52007-03-06 21:14:09 +00001355 LI = &getAnalysis<LoopInfo>();
1356 EF = &getAnalysis<ETForest>();
1357 SE = &getAnalysis<ScalarEvolution>();
1358 TD = &getAnalysis<TargetData>();
1359 UIntPtrTy = TD->getIntPtrType();
1360
1361 // Find all uses of induction variables in this loop, and catagorize
Nate Begemane68bcd12005-07-30 00:15:07 +00001362 // them by stride. Start by finding all of the PHI nodes in the header for
1363 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001364 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001365 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001366 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001367
Nate Begemane68bcd12005-07-30 00:15:07 +00001368 // If we have nothing to do, return.
Devang Patelb0743b52007-03-06 21:14:09 +00001369 if (IVUsesByStride.empty()) return false;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001370
1371 // Optimize induction variables. Some indvar uses can be transformed to use
1372 // strides that will be needed for other purposes. A common example of this
1373 // is the exit test for the loop, which can often be rewritten to use the
1374 // computation of some other indvar to decide when to terminate the loop.
1375 OptimizeIndvars(L);
1376
Misha Brukmanb1c93172005-04-21 23:48:37 +00001377
Nate Begemane68bcd12005-07-30 00:15:07 +00001378 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1379 // doing computation in byte values, promote to 32-bit values if safe.
1380
1381 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1382 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1383 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1384 // to be careful that IV's are all the same type. Only works for intptr_t
1385 // indvars.
1386
1387 // If we only have one stride, we can more aggressively eliminate some things.
1388 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001389
1390#ifndef NDEBUG
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001391 DOUT << "\nLSR on ";
Evan Cheng3df447d2006-03-16 21:53:05 +00001392 DEBUG(L->dump());
1393#endif
1394
1395 // IVsByStride keeps IVs for one particular loop.
1396 IVsByStride.clear();
1397
Evan Chengf09f0eb2006-03-18 00:44:49 +00001398 // Sort the StrideOrder so we process larger strides first.
1399 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1400
Chris Lattnera091ff12005-08-09 00:18:09 +00001401 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001402 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1403 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1404 // This extra layer of indirection makes the ordering of strides deterministic
1405 // - not dependent on map order.
1406 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1407 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1408 IVUsesByStride.find(StrideOrder[Stride]);
1409 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001410 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001411 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001412
1413 // Clean up after ourselves
1414 if (!DeadInsts.empty()) {
1415 DeleteTriviallyDeadInstructions(DeadInsts);
1416
Nate Begemane68bcd12005-07-30 00:15:07 +00001417 BasicBlock::iterator I = L->getHeader()->begin();
1418 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001419 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001420 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1421
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001422 // At this point, we know that we have killed one or more GEP
1423 // instructions. It is worth checking to see if the cann indvar is also
1424 // dead, so that we can remove it as well. The requirements for the cann
1425 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001426 // 1. the cann indvar has one use
1427 // 2. the use is an add instruction
1428 // 3. the add has one use
1429 // 4. the add is used by the cann indvar
1430 // If all four cases above are true, then we can remove both the add and
1431 // the cann indvar.
1432 // FIXME: this needs to eliminate an induction variable even if it's being
1433 // compared against some value to decide loop termination.
1434 if (PN->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001435 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1436 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1437 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
Chris Lattner75a44e12005-08-02 02:52:02 +00001438 DeadInsts.insert(BO);
1439 // Break the cycle, then delete the PHI.
1440 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001441 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001442 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001443 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001444 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001445 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001446 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001447 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001448 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001449
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001450 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001451 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001452 StrideOrder.clear();
Devang Patelb0743b52007-03-06 21:14:09 +00001453 return false;
Nate Begemanb18121e2004-10-18 21:08:22 +00001454}