blob: 332ddfa488e6ec6c19fb79e1ed1089620836f52d [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<ImmediateDominators>();
158 AU.addPreserved<DominanceFrontier>();
159 AU.addPreserved<DominatorTree>();
160
Jeff Cohen39751c32005-02-27 19:37:07 +0000161 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000162 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000163 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000164 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000165 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000166 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000167
168 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
169 ///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000170 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
Chris Lattner6f286b72005-08-04 01:19:13 +0000171private:
Chris Lattnereaf24722005-08-04 17:40:30 +0000172 bool AddUsersIfInteresting(Instruction *I, Loop *L,
173 std::set<Instruction*> &Processed);
174 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
175
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000176 void OptimizeIndvars(Loop *L);
Chris Lattner81e07072007-04-03 05:11:24 +0000177 bool FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
178 const SCEVHandle *&CondStride);
Nate Begemane68bcd12005-07-30 00:15:07 +0000179
Dale Johannesene3a02be2007-03-20 00:47:50 +0000180 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*,
181 const std::vector<BasedUser>& UsersToProcess);
182
183 bool ValidStride(int64_t, const std::vector<BasedUser>& UsersToProcess);
Evan Cheng45206982006-03-17 19:52:23 +0000184
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 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000190 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000191}
192
Devang Patelb0743b52007-03-06 21:14:09 +0000193LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Evan Cheng3df447d2006-03-16 21:53:05 +0000194 return new LoopStrengthReduce(TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000195}
196
Reid Spencerb341b082006-12-12 05:05:00 +0000197/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
198/// assumes that the Value* V is of integer or pointer type only.
Chris Lattner6f286b72005-08-04 01:19:13 +0000199///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000200Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
201 Value *V) {
Chris Lattner6f286b72005-08-04 01:19:13 +0000202 if (V->getType() == UIntPtrTy) return V;
203 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000204 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
Chris Lattner6f286b72005-08-04 01:19:13 +0000205
206 Value *&New = CastedPointers[V];
207 if (New) return New;
208
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000209 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000210 DeadInsts.insert(cast<Instruction>(New));
211 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000212}
213
214
Nate Begemanb18121e2004-10-18 21:08:22 +0000215/// DeleteTriviallyDeadInstructions - If any of the instructions is the
216/// specified set are trivially dead, delete them and see if this makes any of
217/// their operands subsequently dead.
218void LoopStrengthReduce::
219DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
220 while (!Insts.empty()) {
221 Instruction *I = *Insts.begin();
222 Insts.erase(Insts.begin());
223 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000224 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
225 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
226 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000227 SE->deleteInstructionFromRecords(I);
228 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000229 Changed = true;
230 }
231 }
232}
233
Jeff Cohen39751c32005-02-27 19:37:07 +0000234
Chris Lattnereaf24722005-08-04 17:40:30 +0000235/// GetExpressionSCEV - Compute and return the SCEV for the specified
236/// instruction.
237SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Dale Johannesene5866e72007-03-26 03:01:27 +0000238 // Pointer to pointer bitcast instructions return the same value as their
239 // operand.
240 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
241 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
242 return SE->getSCEV(BCI);
243 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)), L);
244 SE->setSCEV(BCI, R);
245 return R;
246 }
247
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000248 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
249 // If this is a GEP that SE doesn't know about, compute it now and insert it.
250 // If this is not a GEP, or if we have already done this computation, just let
251 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000252 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000253 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000254 return SE->getSCEV(Exp);
255
Nate Begemane68bcd12005-07-30 00:15:07 +0000256 // Analyze all of the subscripts of this getelementptr instruction, looking
257 // for uses that are determined by the trip count of L. First, skip all
258 // operands the are not dependent on the IV.
259
260 // Build up the base expression. Insert an LLVM cast of the pointer to
261 // uintptr_t first.
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000262 SCEVHandle GEPVal = SCEVUnknown::get(
263 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000264
265 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000266
267 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000268 // If this is a use of a recurrence that we can analyze, and it comes before
269 // Op does in the GEP operand list, we will handle this when we process this
270 // operand.
271 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
272 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000273 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000274 uint64_t Offset = SL->getElementOffset(Idx);
Chris Lattnereaf24722005-08-04 17:40:30 +0000275 GEPVal = SCEVAddExpr::get(GEPVal,
276 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000277 } else {
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000278 unsigned GEPOpiBits =
279 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
280 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
281 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
282 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
283 Instruction::BitCast));
284 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
Chris Lattneracc42c42005-08-04 19:08:16 +0000285 SCEVHandle Idx = SE->getSCEV(OpVal);
286
Chris Lattnereaf24722005-08-04 17:40:30 +0000287 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
288 if (TypeSize != 1)
289 Idx = SCEVMulExpr::get(Idx,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000290 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattnereaf24722005-08-04 17:40:30 +0000291 TypeSize)));
292 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000293 }
294 }
295
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000296 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000297 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000298}
299
Chris Lattneracc42c42005-08-04 19:08:16 +0000300/// getSCEVStartAndStride - Compute the start and stride of this expression,
301/// returning false if the expression is not a start/stride pair, or true if it
302/// is. The stride must be a loop invariant expression, but the start may be
303/// a mix of loop invariant and loop variant expressions.
304static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000305 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000306 SCEVHandle TheAddRec = Start; // Initialize to zero.
307
308 // If the outer level is an AddExpr, the operands are all start values except
309 // for a nested AddRecExpr.
310 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
311 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
312 if (SCEVAddRecExpr *AddRec =
313 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
314 if (AddRec->getLoop() == L)
315 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
316 else
317 return false; // Nested IV of some sort?
318 } else {
319 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
320 }
321
Reid Spencerde46e482006-11-02 20:25:50 +0000322 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000323 TheAddRec = SH;
324 } else {
325 return false; // not analyzable.
326 }
327
328 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
329 if (!AddRec || AddRec->getLoop() != L) return false;
330
331 // FIXME: Generalize to non-affine IV's.
332 if (!AddRec->isAffine()) return false;
333
334 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
335
Chris Lattneracc42c42005-08-04 19:08:16 +0000336 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000337 DOUT << "[" << L->getHeader()->getName()
338 << "] Variable stride: " << *AddRec << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000339
Chris Lattneredff91a2005-08-10 00:45:21 +0000340 Stride = AddRec->getOperand(1);
Chris Lattneracc42c42005-08-04 19:08:16 +0000341 return true;
342}
343
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000344/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
345/// and now we need to decide whether the user should use the preinc or post-inc
346/// value. If this user should use the post-inc version of the IV, return true.
347///
348/// Choosing wrong here can break dominance properties (if we choose to use the
349/// post-inc value when we cannot) or it can end up adding extra live-ranges to
350/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
351/// should use the post-inc value).
352static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000353 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000354 // If the user is in the loop, use the preinc value.
355 if (L->contains(User->getParent())) return false;
356
Chris Lattnerf07a5872005-10-03 02:50:05 +0000357 BasicBlock *LatchBlock = L->getLoopLatch();
358
359 // Ok, the user is outside of the loop. If it is dominated by the latch
360 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000361 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000362 return true;
363
364 // There is one case we have to be careful of: PHI nodes. These little guys
365 // can live in blocks that do not dominate the latch block, but (since their
366 // uses occur in the predecessor block, not the block the PHI lives in) should
367 // still use the post-inc value. Check for this case now.
368 PHINode *PN = dyn_cast<PHINode>(User);
369 if (!PN) return false; // not a phi, not dominated by latch block.
370
371 // Look at all of the uses of IV by the PHI node. If any use corresponds to
372 // a block that is not dominated by the latch block, give up and use the
373 // preincremented value.
374 unsigned NumUses = 0;
375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
376 if (PN->getIncomingValue(i) == IV) {
377 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000378 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000379 return false;
380 }
381
382 // Okay, all uses of IV by PN are in predecessor blocks that really are
383 // dominated by the latch block. Split the critical edges and use the
384 // post-incremented value.
385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
386 if (PN->getIncomingValue(i) == IV) {
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000387 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
388 true);
Chris Lattner5191c652006-10-28 00:59:20 +0000389 // Splitting the critical edge can reduce the number of entries in this
390 // PHI.
391 e = PN->getNumIncomingValues();
Chris Lattnerf07a5872005-10-03 02:50:05 +0000392 if (--NumUses == 0) break;
393 }
394
395 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000396}
397
398
399
Nate Begemane68bcd12005-07-30 00:15:07 +0000400/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
401/// reducible SCEV, recursively add its users to the IVUsesByStride set and
402/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000403bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
404 std::set<Instruction*> &Processed) {
Chris Lattner03c49532007-01-15 02:27:26 +0000405 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
Chris Lattner5df0e362005-10-21 05:45:41 +0000406 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000407 if (!Processed.insert(I).second)
408 return true; // Instruction already handled.
409
Chris Lattneracc42c42005-08-04 19:08:16 +0000410 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000411 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000412 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000413
Chris Lattneracc42c42005-08-04 19:08:16 +0000414 // Get the start and stride for this expression.
415 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000416 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000417 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
418 return false; // Non-reducible symbolic expression, bail out.
Devang Patel58818c52007-03-09 21:19:53 +0000419
420 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000421 Instruction *User = cast<Instruction>(*UI);
422
Devang Patel58818c52007-03-09 21:19:53 +0000423 // Increment iterator now because IVUseShouldUsePostIncValue may remove
424 // User from the list of I users.
425 ++UI;
426
Nate Begemane68bcd12005-07-30 00:15:07 +0000427 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000428 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000429 continue;
430
431 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000432 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000433 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000434 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000435 DOUT << "FOUND USER in other loop: " << *User
436 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000437 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000438 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000439 DOUT << "FOUND USER: " << *User
440 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000441 AddUserToIVUsers = true;
442 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000443
Chris Lattneracc42c42005-08-04 19:08:16 +0000444 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000445 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
446 if (StrideUses.Users.empty()) // First occurance of this stride?
447 StrideOrder.push_back(Stride);
448
Chris Lattner65107492005-08-04 00:40:47 +0000449 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000450 // and decide what to do with it. If we are a use inside of the loop, use
451 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000452 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000453 // The value used will be incremented by the stride more than we are
454 // expecting, so subtract this off.
455 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000456 StrideUses.addUser(NewStart, User, I);
457 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000458 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000459 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000460 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000461 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000462 }
463 }
464 return true;
465}
466
467namespace {
468 /// BasedUser - For a particular base value, keep information about how we've
469 /// partitioned the expression so far.
470 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000471 /// Base - The Base value for the PHI node that needs to be inserted for
472 /// this use. As the use is processed, information gets moved from this
473 /// field to the Imm field (below). BasedUser values are sorted by this
474 /// field.
475 SCEVHandle Base;
476
Nate Begemane68bcd12005-07-30 00:15:07 +0000477 /// Inst - The instruction using the induction variable.
478 Instruction *Inst;
479
Chris Lattner430d0022005-08-03 22:21:05 +0000480 /// OperandValToReplace - The operand value of Inst to replace with the
481 /// EmittedBase.
482 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000483
484 /// Imm - The immediate value that should be added to the base immediately
485 /// before Inst, because it will be folded into the imm field of the
486 /// instruction.
487 SCEVHandle Imm;
488
489 /// EmittedBase - The actual value* to use for the base value of this
490 /// operation. This is null if we should just use zero so far.
491 Value *EmittedBase;
492
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000493 // isUseOfPostIncrementedValue - True if this should use the
494 // post-incremented version of this IV, not the preincremented version.
495 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000496 // instruction for a loop and uses outside the loop that are dominated by
497 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000498 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000499
500 BasedUser(IVStrideUse &IVSU)
501 : Base(IVSU.Offset), Inst(IVSU.User),
502 OperandValToReplace(IVSU.OperandValToReplace),
503 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
504 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000505
Chris Lattnera6d7c352005-08-04 20:03:32 +0000506 // Once we rewrite the code to insert the new IVs we want, update the
507 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
508 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000509 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000510 SCEVExpander &Rewriter, Loop *L,
511 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000512
513 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
514 SCEVExpander &Rewriter,
515 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000516 void dump() const;
517 };
518}
519
520void BasedUser::dump() const {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000521 cerr << " Base=" << *Base;
522 cerr << " Imm=" << *Imm;
Nate Begemane68bcd12005-07-30 00:15:07 +0000523 if (EmittedBase)
Bill Wendlingf3baad32006-12-07 01:30:32 +0000524 cerr << " EB=" << *EmittedBase;
Nate Begemane68bcd12005-07-30 00:15:07 +0000525
Bill Wendlingf3baad32006-12-07 01:30:32 +0000526 cerr << " Inst: " << *Inst;
Nate Begemane68bcd12005-07-30 00:15:07 +0000527}
528
Chris Lattner2959f002006-02-04 07:36:50 +0000529Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
530 SCEVExpander &Rewriter,
531 Instruction *IP, Loop *L) {
532 // Figure out where we *really* want to insert this code. In particular, if
533 // the user is inside of a loop that is nested inside of L, we really don't
534 // want to insert this expression before the user, we'd rather pull it out as
535 // many loops as possible.
536 LoopInfo &LI = Rewriter.getLoopInfo();
537 Instruction *BaseInsertPt = IP;
538
539 // Figure out the most-nested loop that IP is in.
540 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
541
542 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
543 // the preheader of the outer-most loop where NewBase is not loop invariant.
544 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
545 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
546 InsertLoop = InsertLoop->getParentLoop();
547 }
548
549 // If there is no immediate value, skip the next part.
550 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
Reid Spencer53a37392007-03-02 23:51:25 +0000551 if (SC->getValue()->isZero())
Chris Lattner2959f002006-02-04 07:36:50 +0000552 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
553 OperandValToReplace->getType());
554
555 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
556
557 // Always emit the immediate (if non-zero) into the same block as the user.
558 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
559 return Rewriter.expandCodeFor(NewValSCEV, IP,
560 OperandValToReplace->getType());
561}
562
563
Chris Lattnera6d7c352005-08-04 20:03:32 +0000564// Once we rewrite the code to insert the new IVs we want, update the
565// operands of Inst to use the new expression 'NewBase', with 'Imm' added
566// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000567void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000568 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000569 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000570 if (!isa<PHINode>(Inst)) {
Chris Lattnerefd30512007-04-13 20:42:26 +0000571 // By default, insert code at the user instruction.
572 BasicBlock::iterator InsertPt = Inst;
573
574 // However, if the Operand is itself an instruction, the (potentially
575 // complex) inserted code may be shared by many users. Because of this, we
576 // want to emit code for the computation of the operand right before its old
577 // computation. This is usually safe, because we obviously used to use the
578 // computation when it was computed in its current block. However, in some
579 // cases (e.g. use of a post-incremented induction variable) the NewBase
580 // value will be pinned to live somewhere after the original computation.
581 // In this case, we have to back off.
582 if (!isUseOfPostIncrementedValue) {
583 if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) {
584 InsertPt = OpInst;
585 while (isa<PHINode>(InsertPt)) ++InsertPt;
586 }
587 }
588
589 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000590 // Replace the use of the operand Value with the new Phi we just created.
591 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000592 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000593 return;
594 }
595
596 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000597 // expression into each operand block that uses it. Note that PHI nodes can
598 // have multiple entries for the same predecessor. We use a map to make sure
599 // that a PHI node only has a single Value* for each predecessor (which also
600 // prevents us from inserting duplicate code in some blocks).
601 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000602 PHINode *PN = cast<PHINode>(Inst);
603 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
604 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000605 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000606 // code on all predecessor/successor paths. We do this unless this is the
607 // canonical backedge for this loop, as this can make some inserted code
608 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000609 BasicBlock *PHIPred = PN->getIncomingBlock(i);
610 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
611 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000612
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000613 // First step, split the critical edge.
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000614 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattner8447b492005-08-12 22:22:17 +0000615
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000616 // Next step: move the basic block. In particular, if the PHI node
617 // is outside of the loop, and PredTI is in the loop, we want to
618 // move the block to be immediately before the PHI block, not
619 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000620 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000621 BasicBlock *NewBB = PN->getIncomingBlock(i);
622 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000623 }
Chris Lattner5191c652006-10-28 00:59:20 +0000624
625 // Splitting the edge can reduce the number of PHI entries we have.
626 e = PN->getNumIncomingValues();
Chris Lattner4fec86d2005-08-12 22:06:11 +0000627 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000628
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000629 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
630 if (!Code) {
631 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000632 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
633 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000634 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000635
636 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000637 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000638 Rewriter.clear();
639 }
640 }
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000641 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000642}
643
644
Nate Begemane68bcd12005-07-30 00:15:07 +0000645/// isTargetConstant - Return true if the following can be referenced by the
646/// immediate field of a target instruction.
Evan Chengb5eb9322007-03-13 20:34:37 +0000647static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
648 const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000649 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Evan Cheng720acdf2007-03-12 23:27:37 +0000650 int64_t VC = SC->getValue()->getSExtValue();
Chris Lattner780c0092007-04-09 22:20:14 +0000651 if (TLI) {
652 TargetLowering::AddrMode AM;
653 AM.BaseOffs = VC;
654 return TLI->isLegalAddressingMode(AM, UseTy);
655 } else {
Evan Chengc567c4e2006-03-13 23:14:23 +0000656 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
Evan Cheng720acdf2007-03-12 23:27:37 +0000657 return (VC > -(1 << 16) && VC < (1 << 16)-1);
Chris Lattner780c0092007-04-09 22:20:14 +0000658 }
Chris Lattner14203e82005-08-08 06:25:50 +0000659 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000660
Nate Begemane68bcd12005-07-30 00:15:07 +0000661 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
662 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Chris Lattner780c0092007-04-09 22:20:14 +0000663 if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengc567c4e2006-03-13 23:14:23 +0000664 Constant *Op0 = CE->getOperand(0);
Chris Lattner780c0092007-04-09 22:20:14 +0000665 if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
666 TargetLowering::AddrMode AM;
667 AM.BaseGV = GV;
668 return TLI->isLegalAddressingMode(AM, UseTy);
669 }
Evan Chengc567c4e2006-03-13 23:14:23 +0000670 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000671 return false;
672}
673
Chris Lattner37ed8952005-08-08 22:32:34 +0000674/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
675/// loop varying to the Imm operand.
676static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
677 Loop *L) {
678 if (Val->isLoopInvariant(L)) return; // Nothing to do.
679
680 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
681 std::vector<SCEVHandle> NewOps;
682 NewOps.reserve(SAE->getNumOperands());
683
684 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
685 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
686 // If this is a loop-variant expression, it must stay in the immediate
687 // field of the expression.
688 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
689 } else {
690 NewOps.push_back(SAE->getOperand(i));
691 }
692
693 if (NewOps.empty())
694 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
695 else
696 Val = SCEVAddExpr::get(NewOps);
697 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
698 // Try to pull immediates out of the start value of nested addrec's.
699 SCEVHandle Start = SARE->getStart();
700 MoveLoopVariantsToImediateField(Start, Imm, L);
701
702 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
703 Ops[0] = Start;
704 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
705 } else {
706 // Otherwise, all of Val is variant, move the whole thing over.
707 Imm = SCEVAddExpr::get(Imm, Val);
708 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
709 }
710}
711
712
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000713/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000714/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000715/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000716static void MoveImmediateValues(const TargetLowering *TLI,
Evan Chengb5eb9322007-03-13 20:34:37 +0000717 Instruction *User,
Evan Chengc567c4e2006-03-13 23:14:23 +0000718 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000719 bool isAddress, Loop *L) {
Evan Chengb5eb9322007-03-13 20:34:37 +0000720 const Type *UseTy = User->getType();
721 if (StoreInst *SI = dyn_cast<StoreInst>(User))
722 UseTy = SI->getOperand(0)->getType();
723
Chris Lattnerfc624702005-08-03 23:44:42 +0000724 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000725 std::vector<SCEVHandle> NewOps;
726 NewOps.reserve(SAE->getNumOperands());
727
Chris Lattner2959f002006-02-04 07:36:50 +0000728 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
729 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengb5eb9322007-03-13 20:34:37 +0000730 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000731
732 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000733 // If this is a loop-variant expression, it must stay in the immediate
734 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000735 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000736 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000737 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000738 }
Chris Lattner2959f002006-02-04 07:36:50 +0000739 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000740
741 if (NewOps.empty())
742 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
743 else
744 Val = SCEVAddExpr::get(NewOps);
745 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000746 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
747 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000748 SCEVHandle Start = SARE->getStart();
Evan Chengb5eb9322007-03-13 20:34:37 +0000749 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000750
751 if (Start != SARE->getStart()) {
752 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
753 Ops[0] = Start;
754 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
755 }
756 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000757 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
758 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengb5eb9322007-03-13 20:34:37 +0000759 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000760 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
761
762 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
763 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengb5eb9322007-03-13 20:34:37 +0000764 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000765
766 // If we extracted something out of the subexpressions, see if we can
767 // simplify this!
768 if (NewOp != SME->getOperand(1)) {
769 // Scale SubImm up by "8". If the result is a target constant, we are
770 // good.
771 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengb5eb9322007-03-13 20:34:37 +0000772 if (isTargetConstant(SubImm, UseTy, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000773 // Accumulate the immediate.
774 Imm = SCEVAddExpr::get(Imm, SubImm);
775
776 // Update what is left of 'Val'.
777 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
778 return;
779 }
780 }
781 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000782 }
783
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000784 // Loop-variant expressions must stay in the immediate field of the
785 // expression.
Evan Chengb5eb9322007-03-13 20:34:37 +0000786 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000787 !Val->isLoopInvariant(L)) {
788 Imm = SCEVAddExpr::get(Imm, Val);
789 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
790 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000791 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000792
793 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000794}
795
Chris Lattner5949d492005-08-13 07:27:18 +0000796
Chris Lattner3ff62012006-08-03 06:34:50 +0000797/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
798/// added together. This is used to reassociate common addition subexprs
799/// together for maximal sharing when rewriting bases.
Chris Lattner5949d492005-08-13 07:27:18 +0000800static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
801 SCEVHandle Expr) {
802 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
803 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
804 SeparateSubExprs(SubExprs, AE->getOperand(j));
805 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
806 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
807 if (SARE->getOperand(0) == Zero) {
808 SubExprs.push_back(Expr);
809 } else {
810 // Compute the addrec with zero as its base.
811 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
812 Ops[0] = Zero; // Start with zero base.
813 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
814
815
816 SeparateSubExprs(SubExprs, SARE->getOperand(0));
817 }
818 } else if (!isa<SCEVConstant>(Expr) ||
Reid Spencer53a37392007-03-02 23:51:25 +0000819 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
Chris Lattner5949d492005-08-13 07:27:18 +0000820 // Do not add zero.
821 SubExprs.push_back(Expr);
822 }
823}
824
825
Chris Lattnera091ff12005-08-09 00:18:09 +0000826/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
827/// removing any common subexpressions from it. Anything truly common is
828/// removed, accumulated, and returned. This looks for things like (a+b+c) and
829/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
830static SCEVHandle
831RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
832 unsigned NumUses = Uses.size();
833
834 // Only one use? Use its base, regardless of what it is!
835 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
836 SCEVHandle Result = Zero;
837 if (NumUses == 1) {
838 std::swap(Result, Uses[0].Base);
839 return Result;
840 }
841
842 // To find common subexpressions, count how many of Uses use each expression.
843 // If any subexpressions are used Uses.size() times, they are common.
844 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
845
Chris Lattner192cd182005-10-11 18:41:04 +0000846 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
847 // order we see them.
848 std::vector<SCEVHandle> UniqueSubExprs;
849
Chris Lattner5949d492005-08-13 07:27:18 +0000850 std::vector<SCEVHandle> SubExprs;
851 for (unsigned i = 0; i != NumUses; ++i) {
852 // If the base is zero (which is common), return zero now, there are no
853 // CSEs we can find.
854 if (Uses[i].Base == Zero) return Zero;
855
856 // Split the expression into subexprs.
857 SeparateSubExprs(SubExprs, Uses[i].Base);
858 // Add one to SubExpressionUseCounts for each subexpr present.
859 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000860 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
861 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000862 SubExprs.clear();
863 }
864
Chris Lattner192cd182005-10-11 18:41:04 +0000865 // Now that we know how many times each is used, build Result. Iterate over
866 // UniqueSubexprs so that we have a stable ordering.
867 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
868 std::map<SCEVHandle, unsigned>::iterator I =
869 SubExpressionUseCounts.find(UniqueSubExprs[i]);
870 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000871 if (I->second == NumUses) { // Found CSE!
872 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000873 } else {
874 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000875 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000876 }
Chris Lattner192cd182005-10-11 18:41:04 +0000877 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000878
879 // If we found no CSE's, return now.
880 if (Result == Zero) return Result;
881
882 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000883 for (unsigned i = 0; i != NumUses; ++i) {
884 // Split the expression into subexprs.
885 SeparateSubExprs(SubExprs, Uses[i].Base);
886
887 // Remove any common subexpressions.
888 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
889 if (SubExpressionUseCounts.count(SubExprs[j])) {
890 SubExprs.erase(SubExprs.begin()+j);
891 --j; --e;
892 }
893
894 // Finally, the non-shared expressions together.
895 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000896 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000897 else
898 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000899 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000900 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000901
902 return Result;
903}
904
Evan Cheng3df447d2006-03-16 21:53:05 +0000905/// isZero - returns true if the scalar evolution expression is zero.
906///
907static bool isZero(SCEVHandle &V) {
908 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencer53a37392007-03-02 23:51:25 +0000909 return SC->getValue()->isZero();
Evan Cheng3df447d2006-03-16 21:53:05 +0000910 return false;
911}
912
Dale Johannesene3a02be2007-03-20 00:47:50 +0000913/// ValidStride - Check whether the given Scale is valid for all loads and
Chris Lattner780c0092007-04-09 22:20:14 +0000914/// stores in UsersToProcess.
Dale Johannesene3a02be2007-03-20 00:47:50 +0000915///
916bool LoopStrengthReduce::ValidStride(int64_t Scale,
917 const std::vector<BasedUser>& UsersToProcess) {
Dale Johannesenbacf4ac2007-03-20 21:54:54 +0000918 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
Chris Lattner28e0e4e2007-04-02 06:34:44 +0000919 // If this is a load or other access, pass the type of the access in.
920 const Type *AccessTy = Type::VoidTy;
921 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
922 AccessTy = SI->getOperand(0)->getType();
923 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
924 AccessTy = LI->getType();
925
Chris Lattner780c0092007-04-09 22:20:14 +0000926 TargetLowering::AddrMode AM;
927 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
928 AM.BaseOffs = SC->getValue()->getSExtValue();
929 AM.Scale = Scale;
930
931 // If load[imm+r*scale] is illegal, bail out.
932 if (!TLI->isLegalAddressingMode(AM, AccessTy))
Dale Johannesene3a02be2007-03-20 00:47:50 +0000933 return false;
Dale Johannesenbacf4ac2007-03-20 21:54:54 +0000934 }
Dale Johannesene3a02be2007-03-20 00:47:50 +0000935 return true;
936}
Chris Lattnera091ff12005-08-09 00:18:09 +0000937
Evan Cheng45206982006-03-17 19:52:23 +0000938/// CheckForIVReuse - Returns the multiple if the stride is the multiple
939/// of a previous stride and it is a legal value for the target addressing
940/// mode scale component. This allows the users of this stride to be rewritten
Evan Chengc28282b2006-03-18 08:03:12 +0000941/// as prev iv * factor. It returns 0 if no reuse is possible.
Dale Johannesene3a02be2007-03-20 00:47:50 +0000942unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
943 IVExpr &IV, const Type *Ty,
944 const std::vector<BasedUser>& UsersToProcess) {
Evan Chengc28282b2006-03-18 08:03:12 +0000945 if (!TLI) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000946
947 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Reid Spencerba547cb2007-03-02 23:37:53 +0000948 int64_t SInt = SC->getValue()->getSExtValue();
949 if (SInt == 1) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000950
Evan Cheng720acdf2007-03-12 23:27:37 +0000951 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
952 SE = IVsByStride.end(); SI != SE; ++SI) {
953 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Chris Lattnerf3197a72007-04-02 22:51:58 +0000954 if (SInt != -SSInt &&
955 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
Evan Cheng45206982006-03-17 19:52:23 +0000956 continue;
Evan Cheng720acdf2007-03-12 23:27:37 +0000957 int64_t Scale = SInt / SSInt;
Dale Johannesene3a02be2007-03-20 00:47:50 +0000958 // Check that this stride is valid for all the types used for loads and
959 // stores; if it can be used for some and not others, we might as well use
960 // the original stride everywhere, since we have to create the IV for it
961 // anyway.
962 if (ValidStride(Scale, UsersToProcess))
Evan Cheng720acdf2007-03-12 23:27:37 +0000963 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
964 IE = SI->second.IVs.end(); II != IE; ++II)
965 // FIXME: Only handle base == 0 for now.
966 // Only reuse previous IV if it would not require a type conversion.
967 if (isZero(II->Base) && II->Base->getType() == Ty) {
968 IV = *II;
969 return Scale;
970 }
Evan Cheng45206982006-03-17 19:52:23 +0000971 }
972 }
Evan Chengc28282b2006-03-18 08:03:12 +0000973 return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000974}
975
Chris Lattner3ff62012006-08-03 06:34:50 +0000976/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
977/// returns true if Val's isUseOfPostIncrementedValue is true.
978static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
979 return Val.isUseOfPostIncrementedValue;
980}
Evan Cheng45206982006-03-17 19:52:23 +0000981
Nate Begemane68bcd12005-07-30 00:15:07 +0000982/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
983/// stride of IV. All of the users may have different starting values, and this
984/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000985void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000986 IVUsersOfOneStride &Uses,
987 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000988 bool isOnlyStride) {
989 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000990 // this new vector, each 'BasedUser' contains 'Base' the base of the
991 // strided accessas well as the old information from Uses. We progressively
992 // move information from the Base field to the Imm field, until we eventually
993 // have the full access expression to rewrite the use.
994 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000995 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000996 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
997 UsersToProcess.push_back(Uses.Users[i]);
998
999 // Move any loop invariant operands from the offset field to the immediate
1000 // field of the use, so that we don't try to use something before it is
1001 // computed.
1002 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
1003 UsersToProcess.back().Imm, L);
1004 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +00001005 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001006 }
Evan Cheng45206982006-03-17 19:52:23 +00001007
Chris Lattnera091ff12005-08-09 00:18:09 +00001008 // We now have a whole bunch of uses of like-strided induction variables, but
1009 // they might all have different bases. We want to emit one PHI node for this
1010 // stride which we fold as many common expressions (between the IVs) into as
1011 // possible. Start by identifying the common expressions in the base values
1012 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1013 // "A+B"), emit it to the preheader, then remove the expression from the
1014 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +00001015 SCEVHandle CommonExprs =
1016 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +00001017
Chris Lattner37ed8952005-08-08 22:32:34 +00001018 // Next, figure out what we can represent in the immediate fields of
1019 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +00001020 // fields of the BasedUsers. We do this so that it increases the commonality
1021 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +00001022 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +00001023 // If the user is not in the current loop, this means it is using the exit
1024 // value of the IV. Do not put anything in the base, make sure it's all in
1025 // the immediate field to allow as much factoring as possible.
1026 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +00001027 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
1028 UsersToProcess[i].Base);
1029 UsersToProcess[i].Base =
1030 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +00001031 } else {
1032
1033 // Addressing modes can be folded into loads and stores. Be careful that
1034 // the store is through the expression, not of the expression though.
1035 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1036 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
1037 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1038 isAddress = true;
1039
Evan Chengb5eb9322007-03-13 20:34:37 +00001040 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1041 UsersToProcess[i].Imm, isAddress, L);
Chris Lattner5cf983e2005-08-16 00:38:11 +00001042 }
Chris Lattner37ed8952005-08-08 22:32:34 +00001043 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001044
Dale Johannesenbacf4ac2007-03-20 21:54:54 +00001045 // Check if it is possible to reuse a IV with stride that is factor of this
1046 // stride. And the multiple is a number that can be encoded in the scale
1047 // field of the target addressing mode. And we will have a valid
1048 // instruction after this substition, including the immediate field, if any.
1049 PHINode *NewPHI = NULL;
1050 Value *IncV = NULL;
1051 IVExpr ReuseIV;
1052 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1053 CommonExprs->getType(),
1054 UsersToProcess);
1055 if (RewriteFactor != 0) {
1056 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1057 << " and BASE " << *ReuseIV.Base << " :\n";
1058 NewPHI = ReuseIV.PHI;
1059 IncV = ReuseIV.IncV;
1060 }
1061
Chris Lattner8fe3cbe2007-04-01 22:21:39 +00001062 const Type *ReplacedTy = CommonExprs->getType();
1063
Chris Lattnera091ff12005-08-09 00:18:09 +00001064 // Now that we know what we need to do, insert the PHI node itself.
1065 //
Chris Lattner8fe3cbe2007-04-01 22:21:39 +00001066 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1067 << *Stride << " and BASE " << *CommonExprs << " :\n";
Evan Cheng3df447d2006-03-16 21:53:05 +00001068
Chris Lattnera091ff12005-08-09 00:18:09 +00001069 SCEVExpander Rewriter(*SE, *LI);
1070 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +00001071
Chris Lattnera091ff12005-08-09 00:18:09 +00001072 BasicBlock *Preheader = L->getLoopPreheader();
1073 Instruction *PreInsertPt = Preheader->getTerminator();
1074 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +00001075
Chris Lattner8048b852005-09-12 17:11:27 +00001076 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +00001077
Evan Cheng45206982006-03-17 19:52:23 +00001078
1079 // Emit the initial base value into the loop preheader.
1080 Value *CommonBaseV
1081 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1082 ReplacedTy);
1083
Evan Chengc28282b2006-03-18 08:03:12 +00001084 if (RewriteFactor == 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001085 // Create a new Phi for this base, and stick it in the loop header.
1086 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1087 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001088
Evan Cheng45206982006-03-17 19:52:23 +00001089 // Add common base to the new Phi node.
1090 NewPHI->addIncoming(CommonBaseV, Preheader);
1091
Evan Cheng3df447d2006-03-16 21:53:05 +00001092 // Insert the stride into the preheader.
1093 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1094 ReplacedTy);
1095 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001096
Evan Cheng3df447d2006-03-16 21:53:05 +00001097 // Emit the increment of the base value before the terminator of the loop
1098 // latch block, and add it to the Phi node.
1099 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1100 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +00001101
Evan Cheng3df447d2006-03-16 21:53:05 +00001102 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1103 ReplacedTy);
1104 IncV->setName(NewPHI->getName()+".inc");
1105 NewPHI->addIncoming(IncV, LatchBlock);
1106
Evan Cheng45206982006-03-17 19:52:23 +00001107 // Remember this in case a later stride is multiple of this.
Evan Chengc28282b2006-03-18 08:03:12 +00001108 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Cheng45206982006-03-17 19:52:23 +00001109 } else {
1110 Constant *C = dyn_cast<Constant>(CommonBaseV);
1111 if (!C ||
1112 (!C->isNullValue() &&
Evan Chengb5eb9322007-03-13 20:34:37 +00001113 !isTargetConstant(SCEVUnknown::get(CommonBaseV), ReplacedTy, TLI)))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001114 // We want the common base emitted into the preheader! This is just
1115 // using cast as a copy so BitCast (no-op cast) is appropriate
1116 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1117 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001118 }
Chris Lattnera091ff12005-08-09 00:18:09 +00001119
Chris Lattner3ff62012006-08-03 06:34:50 +00001120 // We want to emit code for users inside the loop first. To do this, we
1121 // rearrange BasedUser so that the entries at the end have
1122 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1123 // vector (so we handle them first).
1124 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1125 PartitionByIsUseOfPostIncrementedValue);
1126
1127 // Sort this by base, so that things with the same base are handled
1128 // together. By partitioning first and stable-sorting later, we are
1129 // guaranteed that within each base we will pop off users from within the
1130 // loop before users outside of the loop with a particular base.
1131 //
1132 // We would like to use stable_sort here, but we can't. The problem is that
1133 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1134 // we don't have anything to do a '<' comparison on. Because we think the
1135 // number of uses is small, do a horrible bubble sort which just relies on
1136 // ==.
1137 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1138 // Get a base value.
1139 SCEVHandle Base = UsersToProcess[i].Base;
1140
1141 // Compact everything with this base to be consequetive with this one.
1142 for (unsigned j = i+1; j != e; ++j) {
1143 if (UsersToProcess[j].Base == Base) {
1144 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1145 ++i;
1146 }
1147 }
1148 }
1149
1150 // Process all the users now. This outer loop handles all bases, the inner
1151 // loop handles all users of a particular base.
Nate Begemane68bcd12005-07-30 00:15:07 +00001152 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001153 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001154
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001155 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
Chris Lattnerbb78c972005-08-03 23:30:08 +00001156
Chris Lattnera091ff12005-08-09 00:18:09 +00001157 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001158 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1159 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +00001160
1161 // If BaseV is a constant other than 0, make sure that it gets inserted into
1162 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001163 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1164 // in this case.
Chris Lattner3ff62012006-08-03 06:34:50 +00001165 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengb5eb9322007-03-13 20:34:37 +00001166 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001167 // We want this constant emitted into the preheader! This is just
1168 // using cast as a copy so BitCast (no-op cast) is appropriate
1169 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattnera091ff12005-08-09 00:18:09 +00001170 PreInsertPt);
1171 }
Chris Lattner3ff62012006-08-03 06:34:50 +00001172 }
1173
Nate Begemane68bcd12005-07-30 00:15:07 +00001174 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001175 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001176 do {
Chris Lattner3ff62012006-08-03 06:34:50 +00001177 // FIXME: Use emitted users to emit other users.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001178 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001179
Chris Lattnera091ff12005-08-09 00:18:09 +00001180 // If this instruction wants to use the post-incremented value, move it
1181 // after the post-inc and use its value instead of the PHI.
1182 Value *RewriteOp = NewPHI;
1183 if (User.isUseOfPostIncrementedValue) {
1184 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001185
1186 // If this user is in the loop, make sure it is the last thing in the
1187 // loop to ensure it is dominated by the increment.
1188 if (L->contains(User.Inst->getParent()))
1189 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001190 }
Reid Spencerdf1f19a2006-12-13 08:06:42 +00001191 if (RewriteOp->getType() != ReplacedTy) {
1192 Instruction::CastOps opcode = Instruction::Trunc;
1193 if (ReplacedTy->getPrimitiveSizeInBits() ==
1194 RewriteOp->getType()->getPrimitiveSizeInBits())
1195 opcode = Instruction::BitCast;
1196 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1197 }
Evan Cheng398f7022006-06-09 00:12:42 +00001198
Chris Lattnera091ff12005-08-09 00:18:09 +00001199 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1200
Chris Lattnerdb23c742005-08-03 22:51:21 +00001201 // Clear the SCEVExpander's expression map so that we are guaranteed
1202 // to have the code emitted where we expect it.
1203 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001204
1205 // If we are reusing the iv, then it must be multiplied by a constant
1206 // factor take advantage of addressing mode scale component.
Evan Chengc28282b2006-03-18 08:03:12 +00001207 if (RewriteFactor != 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001208 RewriteExpr =
1209 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001210 RewriteExpr->getType()),
1211 RewriteExpr);
1212
1213 // The common base is emitted in the loop preheader. But since we
1214 // are reusing an IV, it has not been used to initialize the PHI node.
1215 // Add it to the expression used to rewrite the uses.
1216 if (!isa<ConstantInt>(CommonBaseV) ||
Reid Spencer53a37392007-03-02 23:51:25 +00001217 !cast<ConstantInt>(CommonBaseV)->isZero())
Evan Cheng45206982006-03-17 19:52:23 +00001218 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1219 SCEVUnknown::get(CommonBaseV));
1220 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001221
Chris Lattnera6d7c352005-08-04 20:03:32 +00001222 // Now that we know what we need to do, insert code before User for the
1223 // immediate and any loop-variant expressions.
Reid Spencer53a37392007-03-02 23:51:25 +00001224 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
Chris Lattnera091ff12005-08-09 00:18:09 +00001225 // Add BaseV to the PHI value if needed.
1226 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001227
Chris Lattner8447b492005-08-12 22:22:17 +00001228 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001229
Chris Lattnerdb23c742005-08-03 22:51:21 +00001230 // Mark old value we replaced as possibly dead, so that it is elminated
1231 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001232 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001233
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001234 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001235 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001236
Chris Lattner3ff62012006-08-03 06:34:50 +00001237 // If there are any more users to process with the same base, process them
1238 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001239 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001240 // TODO: Next, find out which base index is the most common, pull it out.
1241 }
1242
1243 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1244 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001245}
1246
Chris Lattner81e07072007-04-03 05:11:24 +00001247/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1248/// set the IV user and stride information and return true, otherwise return
1249/// false.
1250bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1251 const SCEVHandle *&CondStride) {
1252 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1253 ++Stride) {
1254 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1255 IVUsesByStride.find(StrideOrder[Stride]);
1256 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1257
1258 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1259 E = SI->second.Users.end(); UI != E; ++UI)
1260 if (UI->User == Cond) {
1261 // NOTE: we could handle setcc instructions with multiple uses here, but
1262 // InstCombine does it as well for simple uses, it's not clear that it
1263 // occurs enough in real life to handle.
1264 CondUse = &*UI;
1265 CondStride = &SI->first;
1266 return true;
1267 }
1268 }
1269 return false;
1270}
1271
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001272// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1273// uses in the loop, look to see if we can eliminate some, in favor of using
1274// common indvars for the different uses.
1275void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1276 // TODO: implement optzns here.
1277
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001278 // Finally, get the terminating condition for the loop if possible. If we
1279 // can, we want to change it to use a post-incremented version of its
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001280 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001281 // one register value.
1282 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1283 BasicBlock *Preheader = L->getLoopPreheader();
1284 BasicBlock *LatchBlock =
1285 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1286 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001287 if (!TermBr || TermBr->isUnconditional() ||
1288 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001289 return;
Reid Spencer266e42b2006-12-23 06:05:41 +00001290 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001291
1292 // Search IVUsesByStride to find Cond's IVUse if there is one.
1293 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001294 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001295
Chris Lattner81e07072007-04-03 05:11:24 +00001296 if (!FindIVForUser(Cond, CondUse, CondStride))
1297 return; // setcc doesn't use the IV.
1298
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001299
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001300 // It's possible for the setcc instruction to be anywhere in the loop, and
1301 // possible for it to have multiple users. If it is not immediately before
1302 // the latch block branch, move it.
1303 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1304 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1305 Cond->moveBefore(TermBr);
1306 } else {
1307 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencer266e42b2006-12-23 06:05:41 +00001308 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001309 Cond->setName(L->getHeader()->getName() + ".termcond");
1310 LatchBlock->getInstList().insert(TermBr, Cond);
1311
1312 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001313 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001314 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001315 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001316 }
1317 }
1318
1319 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001320 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001321 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001322 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001323 CondUse->isUseOfPostIncrementedValue = true;
1324}
Nate Begemane68bcd12005-07-30 00:15:07 +00001325
Evan Chengf09f0eb2006-03-18 00:44:49 +00001326namespace {
1327 // Constant strides come first which in turns are sorted by their absolute
1328 // values. If absolute values are the same, then positive strides comes first.
1329 // e.g.
1330 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1331 struct StrideCompare {
1332 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1333 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1334 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1335 if (LHSC && RHSC) {
Reid Spencer197adfa2007-03-02 00:31:39 +00001336 int64_t LV = LHSC->getValue()->getSExtValue();
1337 int64_t RV = RHSC->getValue()->getSExtValue();
1338 uint64_t ALV = (LV < 0) ? -LV : LV;
1339 uint64_t ARV = (RV < 0) ? -RV : RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001340 if (ALV == ARV)
Reid Spencer197adfa2007-03-02 00:31:39 +00001341 return LV > RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001342 else
Reid Spencer197adfa2007-03-02 00:31:39 +00001343 return ALV < ARV;
Chris Lattner7d80b4f2006-03-22 17:27:24 +00001344 }
1345 return (LHSC && !RHSC);
Evan Chengf09f0eb2006-03-18 00:44:49 +00001346 }
1347 };
1348}
1349
Devang Patelb0743b52007-03-06 21:14:09 +00001350bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
Nate Begemanb18121e2004-10-18 21:08:22 +00001351
Devang Patelb0743b52007-03-06 21:14:09 +00001352 LI = &getAnalysis<LoopInfo>();
1353 EF = &getAnalysis<ETForest>();
1354 SE = &getAnalysis<ScalarEvolution>();
1355 TD = &getAnalysis<TargetData>();
1356 UIntPtrTy = TD->getIntPtrType();
1357
1358 // Find all uses of induction variables in this loop, and catagorize
Nate Begemane68bcd12005-07-30 00:15:07 +00001359 // them by stride. Start by finding all of the PHI nodes in the header for
1360 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001361 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001362 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001363 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001364
Nate Begemane68bcd12005-07-30 00:15:07 +00001365 // If we have nothing to do, return.
Devang Patelb0743b52007-03-06 21:14:09 +00001366 if (IVUsesByStride.empty()) return false;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001367
1368 // Optimize induction variables. Some indvar uses can be transformed to use
1369 // strides that will be needed for other purposes. A common example of this
1370 // is the exit test for the loop, which can often be rewritten to use the
1371 // computation of some other indvar to decide when to terminate the loop.
1372 OptimizeIndvars(L);
1373
Misha Brukmanb1c93172005-04-21 23:48:37 +00001374
Nate Begemane68bcd12005-07-30 00:15:07 +00001375 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1376 // doing computation in byte values, promote to 32-bit values if safe.
1377
1378 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1379 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1380 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1381 // to be careful that IV's are all the same type. Only works for intptr_t
1382 // indvars.
1383
1384 // If we only have one stride, we can more aggressively eliminate some things.
1385 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001386
1387#ifndef NDEBUG
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001388 DOUT << "\nLSR on ";
Evan Cheng3df447d2006-03-16 21:53:05 +00001389 DEBUG(L->dump());
1390#endif
1391
1392 // IVsByStride keeps IVs for one particular loop.
1393 IVsByStride.clear();
1394
Evan Chengf09f0eb2006-03-18 00:44:49 +00001395 // Sort the StrideOrder so we process larger strides first.
1396 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1397
Chris Lattnera091ff12005-08-09 00:18:09 +00001398 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001399 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1400 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1401 // This extra layer of indirection makes the ordering of strides deterministic
1402 // - not dependent on map order.
1403 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1404 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1405 IVUsesByStride.find(StrideOrder[Stride]);
1406 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001407 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001408 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001409
1410 // Clean up after ourselves
1411 if (!DeadInsts.empty()) {
1412 DeleteTriviallyDeadInstructions(DeadInsts);
1413
Nate Begemane68bcd12005-07-30 00:15:07 +00001414 BasicBlock::iterator I = L->getHeader()->begin();
1415 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001416 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001417 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1418
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001419 // At this point, we know that we have killed one or more GEP
1420 // instructions. It is worth checking to see if the cann indvar is also
1421 // dead, so that we can remove it as well. The requirements for the cann
1422 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001423 // 1. the cann indvar has one use
1424 // 2. the use is an add instruction
1425 // 3. the add has one use
1426 // 4. the add is used by the cann indvar
1427 // If all four cases above are true, then we can remove both the add and
1428 // the cann indvar.
1429 // FIXME: this needs to eliminate an induction variable even if it's being
1430 // compared against some value to decide loop termination.
1431 if (PN->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001432 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1433 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1434 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
Chris Lattner75a44e12005-08-02 02:52:02 +00001435 DeadInsts.insert(BO);
1436 // Break the cycle, then delete the PHI.
1437 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001438 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001439 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001440 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001441 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001442 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001443 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001444 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001445 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001446
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001447 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001448 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001449 StrideOrder.clear();
Devang Patelb0743b52007-03-06 21:14:09 +00001450 return false;
Nate Begemanb18121e2004-10-18 21:08:22 +00001451}