blob: 1c6acc6eef81148d39e43f4115fcab817e9364de [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner4fec86d2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Evan Chengc567c4e2006-03-13 23:14:23 +000035#include "llvm/Target/TargetLowering.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000036#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000037#include <iostream>
Nate Begemanb18121e2004-10-18 21:08:22 +000038#include <set>
39using namespace llvm;
40
41namespace {
42 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000043 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattneredff91a2005-08-10 00:45:21 +000044 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000045
Chris Lattner430d0022005-08-03 22:21:05 +000046 /// IVStrideUse - Keep track of one use of a strided induction variable, where
47 /// the stride is stored externally. The Offset member keeps track of the
48 /// offset from the IV, User is the actual user of the operand, and 'Operand'
49 /// is the operand # of the User that is the use.
50 struct IVStrideUse {
51 SCEVHandle Offset;
52 Instruction *User;
53 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000054
55 // isUseOfPostIncrementedValue - True if this should use the
56 // post-incremented version of this IV, not the preincremented version.
57 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000058 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000059 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000060
61 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000062 : Offset(Offs), User(U), OperandValToReplace(O),
63 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000064 };
65
66 /// IVUsersOfOneStride - This structure keeps track of all instructions that
67 /// have an operand that is based on the trip count multiplied by some stride.
68 /// The stride for all of these users is common and kept external to this
69 /// structure.
70 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000071 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000072 /// initial value and the operand that uses the IV.
73 std::vector<IVStrideUse> Users;
74
75 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
76 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000077 }
78 };
79
Evan Cheng3df447d2006-03-16 21:53:05 +000080 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Chengc28282b2006-03-18 08:03:12 +000081 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
82 /// well as the PHI node and increment value created for rewrite.
Evan Cheng3df447d2006-03-16 21:53:05 +000083 struct IVExpr {
Evan Chengc28282b2006-03-18 08:03:12 +000084 SCEVHandle Stride;
Evan Cheng3df447d2006-03-16 21:53:05 +000085 SCEVHandle Base;
86 PHINode *PHI;
87 Value *IncV;
88
Evan Chengc28282b2006-03-18 08:03:12 +000089 IVExpr()
90 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::UIntTy)),
91 Base (SCEVUnknown::getIntegerSCEV(0, Type::UIntTy)) {}
92 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
93 Value *incv)
94 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
Evan Cheng3df447d2006-03-16 21:53:05 +000095 };
96
97 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
98 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
99 struct IVsOfOneStride {
100 std::vector<IVExpr> IVs;
101
Evan Chengc28282b2006-03-18 08:03:12 +0000102 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
103 Value *IncV) {
104 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
Evan Cheng3df447d2006-03-16 21:53:05 +0000105 }
106 };
Nate Begemane68bcd12005-07-30 00:15:07 +0000107
Chris Lattner996795b2006-06-28 23:17:24 +0000108 class VISIBILITY_HIDDEN LoopStrengthReduce : public FunctionPass {
Nate Begemanb18121e2004-10-18 21:08:22 +0000109 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +0000110 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +0000111 ScalarEvolution *SE;
112 const TargetData *TD;
113 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +0000114 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +0000115
Nate Begemane68bcd12005-07-30 00:15:07 +0000116 /// IVUsesByStride - Keep track of all uses of induction variables that we
117 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +0000118 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +0000119
Evan Cheng3df447d2006-03-16 21:53:05 +0000120 /// IVsByStride - Keep track of all IVs that have been inserted for a
121 /// particular stride.
122 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
123
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000124 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
125 /// We use this to iterate over the IVUsesByStride collection without being
126 /// dependent on random ordering of pointers in the process.
127 std::vector<SCEVHandle> StrideOrder;
128
Chris Lattner6f286b72005-08-04 01:19:13 +0000129 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
130 /// of the casted version of each value. This is accessed by
131 /// getCastedVersionOf.
132 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000133
134 /// DeadInsts - Keep track of instructions we may have made dead, so that
135 /// we can remove them after we are done working.
136 std::set<Instruction*> DeadInsts;
Evan Chengc567c4e2006-03-13 23:14:23 +0000137
138 /// TLI - Keep a pointer of a TargetLowering to consult for determining
139 /// transformation profitability.
140 const TargetLowering *TLI;
141
Nate Begemanb18121e2004-10-18 21:08:22 +0000142 public:
Evan Cheng3df447d2006-03-16 21:53:05 +0000143 LoopStrengthReduce(const TargetLowering *tli = NULL)
144 : TLI(tli) {
Jeff Cohena2c59b72005-03-04 04:04:26 +0000145 }
146
Nate Begemanb18121e2004-10-18 21:08:22 +0000147 virtual bool runOnFunction(Function &) {
148 LI = &getAnalysis<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000149 EF = &getAnalysis<ETForest>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000150 SE = &getAnalysis<ScalarEvolution>();
151 TD = &getAnalysis<TargetData>();
152 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000153 Changed = false;
154
155 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
156 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000157
Nate Begemanb18121e2004-10-18 21:08:22 +0000158 return Changed;
159 }
160
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000162 // We split critical edges, so we change the CFG. However, we do update
163 // many analyses if they are around.
164 AU.addPreservedID(LoopSimplifyID);
165 AU.addPreserved<LoopInfo>();
166 AU.addPreserved<DominatorSet>();
Chris Lattnercb367102006-01-11 05:10:20 +0000167 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000168 AU.addPreserved<ImmediateDominators>();
169 AU.addPreserved<DominanceFrontier>();
170 AU.addPreserved<DominatorTree>();
171
Jeff Cohen39751c32005-02-27 19:37:07 +0000172 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000173 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000174 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000175 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000176 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000177 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000178
179 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
180 ///
181 Value *getCastedVersionOf(Value *V);
182private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000183 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000184 bool AddUsersIfInteresting(Instruction *I, Loop *L,
185 std::set<Instruction*> &Processed);
186 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
187
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000188 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000189
Evan Chenge9c68f52006-07-18 19:07:58 +0000190 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*);
Evan Cheng45206982006-03-17 19:52:23 +0000191
Chris Lattneredff91a2005-08-10 00:45:21 +0000192 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
193 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000194 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000195 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
196 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000197 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000198}
199
Evan Cheng3df447d2006-03-16 21:53:05 +0000200FunctionPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
201 return new LoopStrengthReduce(TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000202}
203
Chris Lattner6f286b72005-08-04 01:19:13 +0000204/// getCastedVersionOf - Return the specified value casted to uintptr_t.
205///
206Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
207 if (V->getType() == UIntPtrTy) return V;
208 if (Constant *CB = dyn_cast<Constant>(V))
209 return ConstantExpr::getCast(CB, UIntPtrTy);
210
211 Value *&New = CastedPointers[V];
212 if (New) return New;
213
Chris Lattnerd30c4992006-02-04 09:52:43 +0000214 New = SCEVExpander::InsertCastOfTo(V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000215 DeadInsts.insert(cast<Instruction>(New));
216 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000217}
218
219
Nate Begemanb18121e2004-10-18 21:08:22 +0000220/// DeleteTriviallyDeadInstructions - If any of the instructions is the
221/// specified set are trivially dead, delete them and see if this makes any of
222/// their operands subsequently dead.
223void LoopStrengthReduce::
224DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
225 while (!Insts.empty()) {
226 Instruction *I = *Insts.begin();
227 Insts.erase(Insts.begin());
228 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000229 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
230 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
231 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000232 SE->deleteInstructionFromRecords(I);
233 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000234 Changed = true;
235 }
236 }
237}
238
Jeff Cohen39751c32005-02-27 19:37:07 +0000239
Chris Lattnereaf24722005-08-04 17:40:30 +0000240/// GetExpressionSCEV - Compute and return the SCEV for the specified
241/// instruction.
242SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000243 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
244 // If this is a GEP that SE doesn't know about, compute it now and insert it.
245 // If this is not a GEP, or if we have already done this computation, just let
246 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000247 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000248 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000249 return SE->getSCEV(Exp);
250
Nate Begemane68bcd12005-07-30 00:15:07 +0000251 // Analyze all of the subscripts of this getelementptr instruction, looking
252 // for uses that are determined by the trip count of L. First, skip all
253 // operands the are not dependent on the IV.
254
255 // Build up the base expression. Insert an LLVM cast of the pointer to
256 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000257 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000258
259 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000260
261 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000262 // If this is a use of a recurrence that we can analyze, and it comes before
263 // Op does in the GEP operand list, we will handle this when we process this
264 // operand.
265 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
266 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000267 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Nate Begemane68bcd12005-07-30 00:15:07 +0000268 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000269 GEPVal = SCEVAddExpr::get(GEPVal,
270 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000271 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000272 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
273 SCEVHandle Idx = SE->getSCEV(OpVal);
274
Chris Lattnereaf24722005-08-04 17:40:30 +0000275 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
276 if (TypeSize != 1)
277 Idx = SCEVMulExpr::get(Idx,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000278 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattnereaf24722005-08-04 17:40:30 +0000279 TypeSize)));
280 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000281 }
282 }
283
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000284 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000285 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000286}
287
Chris Lattneracc42c42005-08-04 19:08:16 +0000288/// getSCEVStartAndStride - Compute the start and stride of this expression,
289/// returning false if the expression is not a start/stride pair, or true if it
290/// is. The stride must be a loop invariant expression, but the start may be
291/// a mix of loop invariant and loop variant expressions.
292static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000293 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000294 SCEVHandle TheAddRec = Start; // Initialize to zero.
295
296 // If the outer level is an AddExpr, the operands are all start values except
297 // for a nested AddRecExpr.
298 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
299 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
300 if (SCEVAddRecExpr *AddRec =
301 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
302 if (AddRec->getLoop() == L)
303 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
304 else
305 return false; // Nested IV of some sort?
306 } else {
307 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
308 }
309
310 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
311 TheAddRec = SH;
312 } else {
313 return false; // not analyzable.
314 }
315
316 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
317 if (!AddRec || AddRec->getLoop() != L) return false;
318
319 // FIXME: Generalize to non-affine IV's.
320 if (!AddRec->isAffine()) return false;
321
322 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
323
Chris Lattneracc42c42005-08-04 19:08:16 +0000324 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000325 DEBUG(std::cerr << "[" << L->getHeader()->getName()
326 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000327
Chris Lattneredff91a2005-08-10 00:45:21 +0000328 Stride = AddRec->getOperand(1);
329 // Check that all constant strides are the unsigned type, we don't want to
330 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
331 // merged.
332 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000333 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000334
Chris Lattneracc42c42005-08-04 19:08:16 +0000335 return true;
336}
337
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000338/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
339/// and now we need to decide whether the user should use the preinc or post-inc
340/// value. If this user should use the post-inc version of the IV, return true.
341///
342/// Choosing wrong here can break dominance properties (if we choose to use the
343/// post-inc value when we cannot) or it can end up adding extra live-ranges to
344/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
345/// should use the post-inc value).
346static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000347 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000348 // If the user is in the loop, use the preinc value.
349 if (L->contains(User->getParent())) return false;
350
Chris Lattnerf07a5872005-10-03 02:50:05 +0000351 BasicBlock *LatchBlock = L->getLoopLatch();
352
353 // Ok, the user is outside of the loop. If it is dominated by the latch
354 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000355 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000356 return true;
357
358 // There is one case we have to be careful of: PHI nodes. These little guys
359 // can live in blocks that do not dominate the latch block, but (since their
360 // uses occur in the predecessor block, not the block the PHI lives in) should
361 // still use the post-inc value. Check for this case now.
362 PHINode *PN = dyn_cast<PHINode>(User);
363 if (!PN) return false; // not a phi, not dominated by latch block.
364
365 // Look at all of the uses of IV by the PHI node. If any use corresponds to
366 // a block that is not dominated by the latch block, give up and use the
367 // preincremented value.
368 unsigned NumUses = 0;
369 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
370 if (PN->getIncomingValue(i) == IV) {
371 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000372 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000373 return false;
374 }
375
376 // Okay, all uses of IV by PN are in predecessor blocks that really are
377 // dominated by the latch block. Split the critical edges and use the
378 // post-incremented value.
379 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
380 if (PN->getIncomingValue(i) == IV) {
381 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
Chris Lattner5191c652006-10-28 00:59:20 +0000382 // Splitting the critical edge can reduce the number of entries in this
383 // PHI.
384 e = PN->getNumIncomingValues();
Chris Lattnerf07a5872005-10-03 02:50:05 +0000385 if (--NumUses == 0) break;
386 }
387
388 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000389}
390
391
392
Nate Begemane68bcd12005-07-30 00:15:07 +0000393/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
394/// reducible SCEV, recursively add its users to the IVUsesByStride set and
395/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000396bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
397 std::set<Instruction*> &Processed) {
Chris Lattner5df0e362005-10-21 05:45:41 +0000398 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
399 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000400 if (!Processed.insert(I).second)
401 return true; // Instruction already handled.
402
Chris Lattneracc42c42005-08-04 19:08:16 +0000403 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000404 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000405 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000406
Chris Lattneracc42c42005-08-04 19:08:16 +0000407 // Get the start and stride for this expression.
408 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000409 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000410 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
411 return false; // Non-reducible symbolic expression, bail out.
412
Nate Begemane68bcd12005-07-30 00:15:07 +0000413 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
414 Instruction *User = cast<Instruction>(*UI);
415
416 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000417 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000418 continue;
419
420 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000421 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000422 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000423 if (LI->getLoopFor(User->getParent()) != L) {
Chris Lattnerfd018c82005-09-13 02:09:55 +0000424 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
Chris Lattnera0102fb2005-08-04 00:14:11 +0000425 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000426 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000427 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000428 DEBUG(std::cerr << "FOUND USER: " << *User
429 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000430 AddUserToIVUsers = true;
431 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000432
Chris Lattneracc42c42005-08-04 19:08:16 +0000433 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000434 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
435 if (StrideUses.Users.empty()) // First occurance of this stride?
436 StrideOrder.push_back(Stride);
437
Chris Lattner65107492005-08-04 00:40:47 +0000438 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000439 // and decide what to do with it. If we are a use inside of the loop, use
440 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000441 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000442 // The value used will be incremented by the stride more than we are
443 // expecting, so subtract this off.
444 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000445 StrideUses.addUser(NewStart, User, I);
446 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Chris Lattnerf07a5872005-10-03 02:50:05 +0000447 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000448 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000449 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000450 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000451 }
452 }
453 return true;
454}
455
456namespace {
457 /// BasedUser - For a particular base value, keep information about how we've
458 /// partitioned the expression so far.
459 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000460 /// Base - The Base value for the PHI node that needs to be inserted for
461 /// this use. As the use is processed, information gets moved from this
462 /// field to the Imm field (below). BasedUser values are sorted by this
463 /// field.
464 SCEVHandle Base;
465
Nate Begemane68bcd12005-07-30 00:15:07 +0000466 /// Inst - The instruction using the induction variable.
467 Instruction *Inst;
468
Chris Lattner430d0022005-08-03 22:21:05 +0000469 /// OperandValToReplace - The operand value of Inst to replace with the
470 /// EmittedBase.
471 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000472
473 /// Imm - The immediate value that should be added to the base immediately
474 /// before Inst, because it will be folded into the imm field of the
475 /// instruction.
476 SCEVHandle Imm;
477
478 /// EmittedBase - The actual value* to use for the base value of this
479 /// operation. This is null if we should just use zero so far.
480 Value *EmittedBase;
481
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000482 // isUseOfPostIncrementedValue - True if this should use the
483 // post-incremented version of this IV, not the preincremented version.
484 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000485 // instruction for a loop and uses outside the loop that are dominated by
486 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000487 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000488
489 BasedUser(IVStrideUse &IVSU)
490 : Base(IVSU.Offset), Inst(IVSU.User),
491 OperandValToReplace(IVSU.OperandValToReplace),
492 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
493 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000494
Chris Lattnera6d7c352005-08-04 20:03:32 +0000495 // Once we rewrite the code to insert the new IVs we want, update the
496 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
497 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000498 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000499 SCEVExpander &Rewriter, Loop *L,
500 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000501
502 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
503 SCEVExpander &Rewriter,
504 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000505 void dump() const;
506 };
507}
508
509void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000510 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000511 std::cerr << " Imm=" << *Imm;
512 if (EmittedBase)
513 std::cerr << " EB=" << *EmittedBase;
514
515 std::cerr << " Inst: " << *Inst;
516}
517
Chris Lattner2959f002006-02-04 07:36:50 +0000518Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
519 SCEVExpander &Rewriter,
520 Instruction *IP, Loop *L) {
521 // Figure out where we *really* want to insert this code. In particular, if
522 // the user is inside of a loop that is nested inside of L, we really don't
523 // want to insert this expression before the user, we'd rather pull it out as
524 // many loops as possible.
525 LoopInfo &LI = Rewriter.getLoopInfo();
526 Instruction *BaseInsertPt = IP;
527
528 // Figure out the most-nested loop that IP is in.
529 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
530
531 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
532 // the preheader of the outer-most loop where NewBase is not loop invariant.
533 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
534 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
535 InsertLoop = InsertLoop->getParentLoop();
536 }
537
538 // If there is no immediate value, skip the next part.
539 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
540 if (SC->getValue()->isNullValue())
541 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
542 OperandValToReplace->getType());
543
544 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
545
546 // Always emit the immediate (if non-zero) into the same block as the user.
547 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
548 return Rewriter.expandCodeFor(NewValSCEV, IP,
549 OperandValToReplace->getType());
550}
551
552
Chris Lattnera6d7c352005-08-04 20:03:32 +0000553// Once we rewrite the code to insert the new IVs we want, update the
554// operands of Inst to use the new expression 'NewBase', with 'Imm' added
555// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000556void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000557 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000558 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000559 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000560 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000561 // Replace the use of the operand Value with the new Phi we just created.
562 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
563 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
564 return;
565 }
566
567 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000568 // expression into each operand block that uses it. Note that PHI nodes can
569 // have multiple entries for the same predecessor. We use a map to make sure
570 // that a PHI node only has a single Value* for each predecessor (which also
571 // prevents us from inserting duplicate code in some blocks).
572 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000573 PHINode *PN = cast<PHINode>(Inst);
574 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
575 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000576 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000577 // code on all predecessor/successor paths. We do this unless this is the
578 // canonical backedge for this loop, as this can make some inserted code
579 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000580 BasicBlock *PHIPred = PN->getIncomingBlock(i);
581 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
582 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000583
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000584 // First step, split the critical edge.
Chris Lattner8fcce172005-10-03 00:31:52 +0000585 SplitCriticalEdge(PHIPred, PN->getParent(), P);
Chris Lattner8447b492005-08-12 22:22:17 +0000586
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000587 // Next step: move the basic block. In particular, if the PHI node
588 // is outside of the loop, and PredTI is in the loop, we want to
589 // move the block to be immediately before the PHI block, not
590 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000591 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000592 BasicBlock *NewBB = PN->getIncomingBlock(i);
593 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000594 }
Chris Lattner5191c652006-10-28 00:59:20 +0000595
596 // Splitting the edge can reduce the number of PHI entries we have.
597 e = PN->getNumIncomingValues();
Chris Lattner4fec86d2005-08-12 22:06:11 +0000598 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000599
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000600 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
601 if (!Code) {
602 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000603 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
604 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000605 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000606
607 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000608 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000609 Rewriter.clear();
610 }
611 }
612 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
613}
614
615
Nate Begemane68bcd12005-07-30 00:15:07 +0000616/// isTargetConstant - Return true if the following can be referenced by the
617/// immediate field of a target instruction.
Evan Chengc567c4e2006-03-13 23:14:23 +0000618static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000619 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattner07720072005-12-05 18:23:57 +0000620 int64_t V = SC->getValue()->getSExtValue();
Evan Chengc567c4e2006-03-13 23:14:23 +0000621 if (TLI)
622 return TLI->isLegalAddressImmediate(V);
623 else
624 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
625 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner14203e82005-08-08 06:25:50 +0000626 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000627
Nate Begemane68bcd12005-07-30 00:15:07 +0000628 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
629 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Evan Chengc567c4e2006-03-13 23:14:23 +0000630 if (CE->getOpcode() == Instruction::Cast) {
631 Constant *Op0 = CE->getOperand(0);
632 if (isa<GlobalValue>(Op0) &&
633 TLI &&
634 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begemane68bcd12005-07-30 00:15:07 +0000635 return true;
Evan Chengc567c4e2006-03-13 23:14:23 +0000636 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000637 return false;
638}
639
Chris Lattner37ed8952005-08-08 22:32:34 +0000640/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
641/// loop varying to the Imm operand.
642static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
643 Loop *L) {
644 if (Val->isLoopInvariant(L)) return; // Nothing to do.
645
646 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
647 std::vector<SCEVHandle> NewOps;
648 NewOps.reserve(SAE->getNumOperands());
649
650 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
651 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
652 // If this is a loop-variant expression, it must stay in the immediate
653 // field of the expression.
654 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
655 } else {
656 NewOps.push_back(SAE->getOperand(i));
657 }
658
659 if (NewOps.empty())
660 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
661 else
662 Val = SCEVAddExpr::get(NewOps);
663 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
664 // Try to pull immediates out of the start value of nested addrec's.
665 SCEVHandle Start = SARE->getStart();
666 MoveLoopVariantsToImediateField(Start, Imm, L);
667
668 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
669 Ops[0] = Start;
670 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
671 } else {
672 // Otherwise, all of Val is variant, move the whole thing over.
673 Imm = SCEVAddExpr::get(Imm, Val);
674 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
675 }
676}
677
678
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000679/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000680/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000681/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000682static void MoveImmediateValues(const TargetLowering *TLI,
683 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000684 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000685 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000686 std::vector<SCEVHandle> NewOps;
687 NewOps.reserve(SAE->getNumOperands());
688
Chris Lattner2959f002006-02-04 07:36:50 +0000689 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
690 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengc567c4e2006-03-13 23:14:23 +0000691 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000692
693 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000694 // If this is a loop-variant expression, it must stay in the immediate
695 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000696 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000697 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000698 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000699 }
Chris Lattner2959f002006-02-04 07:36:50 +0000700 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000701
702 if (NewOps.empty())
703 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
704 else
705 Val = SCEVAddExpr::get(NewOps);
706 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000707 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
708 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000709 SCEVHandle Start = SARE->getStart();
Evan Chengc567c4e2006-03-13 23:14:23 +0000710 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000711
712 if (Start != SARE->getStart()) {
713 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
714 Ops[0] = Start;
715 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
716 }
717 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000718 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
719 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengc567c4e2006-03-13 23:14:23 +0000720 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000721 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
722
723 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
724 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengc567c4e2006-03-13 23:14:23 +0000725 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000726
727 // If we extracted something out of the subexpressions, see if we can
728 // simplify this!
729 if (NewOp != SME->getOperand(1)) {
730 // Scale SubImm up by "8". If the result is a target constant, we are
731 // good.
732 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengc567c4e2006-03-13 23:14:23 +0000733 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000734 // Accumulate the immediate.
735 Imm = SCEVAddExpr::get(Imm, SubImm);
736
737 // Update what is left of 'Val'.
738 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
739 return;
740 }
741 }
742 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000743 }
744
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000745 // Loop-variant expressions must stay in the immediate field of the
746 // expression.
Evan Chengc567c4e2006-03-13 23:14:23 +0000747 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000748 !Val->isLoopInvariant(L)) {
749 Imm = SCEVAddExpr::get(Imm, Val);
750 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
751 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000752 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000753
754 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000755}
756
Chris Lattner5949d492005-08-13 07:27:18 +0000757
Chris Lattner3ff62012006-08-03 06:34:50 +0000758/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
759/// added together. This is used to reassociate common addition subexprs
760/// together for maximal sharing when rewriting bases.
Chris Lattner5949d492005-08-13 07:27:18 +0000761static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
762 SCEVHandle Expr) {
763 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
764 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
765 SeparateSubExprs(SubExprs, AE->getOperand(j));
766 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
767 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
768 if (SARE->getOperand(0) == Zero) {
769 SubExprs.push_back(Expr);
770 } else {
771 // Compute the addrec with zero as its base.
772 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
773 Ops[0] = Zero; // Start with zero base.
774 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
775
776
777 SeparateSubExprs(SubExprs, SARE->getOperand(0));
778 }
779 } else if (!isa<SCEVConstant>(Expr) ||
780 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
781 // Do not add zero.
782 SubExprs.push_back(Expr);
783 }
784}
785
786
Chris Lattnera091ff12005-08-09 00:18:09 +0000787/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
788/// removing any common subexpressions from it. Anything truly common is
789/// removed, accumulated, and returned. This looks for things like (a+b+c) and
790/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
791static SCEVHandle
792RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
793 unsigned NumUses = Uses.size();
794
795 // Only one use? Use its base, regardless of what it is!
796 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
797 SCEVHandle Result = Zero;
798 if (NumUses == 1) {
799 std::swap(Result, Uses[0].Base);
800 return Result;
801 }
802
803 // To find common subexpressions, count how many of Uses use each expression.
804 // If any subexpressions are used Uses.size() times, they are common.
805 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
806
Chris Lattner192cd182005-10-11 18:41:04 +0000807 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
808 // order we see them.
809 std::vector<SCEVHandle> UniqueSubExprs;
810
Chris Lattner5949d492005-08-13 07:27:18 +0000811 std::vector<SCEVHandle> SubExprs;
812 for (unsigned i = 0; i != NumUses; ++i) {
813 // If the base is zero (which is common), return zero now, there are no
814 // CSEs we can find.
815 if (Uses[i].Base == Zero) return Zero;
816
817 // Split the expression into subexprs.
818 SeparateSubExprs(SubExprs, Uses[i].Base);
819 // Add one to SubExpressionUseCounts for each subexpr present.
820 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000821 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
822 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000823 SubExprs.clear();
824 }
825
Chris Lattner192cd182005-10-11 18:41:04 +0000826 // Now that we know how many times each is used, build Result. Iterate over
827 // UniqueSubexprs so that we have a stable ordering.
828 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
829 std::map<SCEVHandle, unsigned>::iterator I =
830 SubExpressionUseCounts.find(UniqueSubExprs[i]);
831 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000832 if (I->second == NumUses) { // Found CSE!
833 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000834 } else {
835 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000836 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000837 }
Chris Lattner192cd182005-10-11 18:41:04 +0000838 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000839
840 // If we found no CSE's, return now.
841 if (Result == Zero) return Result;
842
843 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000844 for (unsigned i = 0; i != NumUses; ++i) {
845 // Split the expression into subexprs.
846 SeparateSubExprs(SubExprs, Uses[i].Base);
847
848 // Remove any common subexpressions.
849 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
850 if (SubExpressionUseCounts.count(SubExprs[j])) {
851 SubExprs.erase(SubExprs.begin()+j);
852 --j; --e;
853 }
854
855 // Finally, the non-shared expressions together.
856 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000857 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000858 else
859 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000860 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000861 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000862
863 return Result;
864}
865
Evan Cheng3df447d2006-03-16 21:53:05 +0000866/// isZero - returns true if the scalar evolution expression is zero.
867///
868static bool isZero(SCEVHandle &V) {
869 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000870 return SC->getValue()->getZExtValue() == 0;
Evan Cheng3df447d2006-03-16 21:53:05 +0000871 return false;
872}
873
Chris Lattnera091ff12005-08-09 00:18:09 +0000874
Evan Cheng45206982006-03-17 19:52:23 +0000875/// CheckForIVReuse - Returns the multiple if the stride is the multiple
876/// of a previous stride and it is a legal value for the target addressing
877/// mode scale component. This allows the users of this stride to be rewritten
Evan Chengc28282b2006-03-18 08:03:12 +0000878/// as prev iv * factor. It returns 0 if no reuse is possible.
Evan Cheng45206982006-03-17 19:52:23 +0000879unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
Evan Chenge9c68f52006-07-18 19:07:58 +0000880 IVExpr &IV, const Type *Ty) {
Evan Chengc28282b2006-03-18 08:03:12 +0000881 if (!TLI) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000882
883 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Evan Chengc28282b2006-03-18 08:03:12 +0000884 int64_t SInt = SC->getValue()->getSExtValue();
885 if (SInt == 1) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000886
887 for (TargetLowering::legal_am_scale_iterator
888 I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
889 I != E; ++I) {
890 unsigned Scale = *I;
Reid Spencer13a1a7a2006-04-12 19:28:15 +0000891 if (unsigned(abs(SInt)) < Scale || (SInt % Scale) != 0)
Evan Cheng45206982006-03-17 19:52:23 +0000892 continue;
893 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
894 IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, Type::UIntTy));
895 if (SI == IVsByStride.end())
896 continue;
897 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
898 IE = SI->second.IVs.end(); II != IE; ++II)
899 // FIXME: Only handle base == 0 for now.
Evan Chenge9c68f52006-07-18 19:07:58 +0000900 // Only reuse previous IV if it would not require a type conversion.
901 if (isZero(II->Base) &&
902 II->Base->getType()->isLosslesslyConvertibleTo(Ty)) {
Evan Cheng45206982006-03-17 19:52:23 +0000903 IV = *II;
904 return Scale;
905 }
906 }
907 }
908
Evan Chengc28282b2006-03-18 08:03:12 +0000909 return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000910}
911
Chris Lattner3ff62012006-08-03 06:34:50 +0000912/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
913/// returns true if Val's isUseOfPostIncrementedValue is true.
914static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
915 return Val.isUseOfPostIncrementedValue;
916}
Evan Cheng45206982006-03-17 19:52:23 +0000917
Nate Begemane68bcd12005-07-30 00:15:07 +0000918/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
919/// stride of IV. All of the users may have different starting values, and this
920/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000921void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000922 IVUsersOfOneStride &Uses,
923 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000924 bool isOnlyStride) {
925 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000926 // this new vector, each 'BasedUser' contains 'Base' the base of the
927 // strided accessas well as the old information from Uses. We progressively
928 // move information from the Base field to the Imm field, until we eventually
929 // have the full access expression to rewrite the use.
930 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000931 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000932 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
933 UsersToProcess.push_back(Uses.Users[i]);
934
935 // Move any loop invariant operands from the offset field to the immediate
936 // field of the use, so that we don't try to use something before it is
937 // computed.
938 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
939 UsersToProcess.back().Imm, L);
940 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000941 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000942 }
Evan Cheng45206982006-03-17 19:52:23 +0000943
Chris Lattnera091ff12005-08-09 00:18:09 +0000944 // We now have a whole bunch of uses of like-strided induction variables, but
945 // they might all have different bases. We want to emit one PHI node for this
946 // stride which we fold as many common expressions (between the IVs) into as
947 // possible. Start by identifying the common expressions in the base values
948 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
949 // "A+B"), emit it to the preheader, then remove the expression from the
950 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +0000951 SCEVHandle CommonExprs =
952 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +0000953
Evan Chenge9c68f52006-07-18 19:07:58 +0000954 // Check if it is possible to reuse a IV with stride that is factor of this
955 // stride. And the multiple is a number that can be encoded in the scale
956 // field of the target addressing mode.
957 PHINode *NewPHI = NULL;
958 Value *IncV = NULL;
959 IVExpr ReuseIV;
960 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
961 CommonExprs->getType());
962 if (RewriteFactor != 0) {
963 DEBUG(std::cerr << "BASED ON IV of STRIDE " << *ReuseIV.Stride
964 << " and BASE " << *ReuseIV.Base << " :\n");
965 NewPHI = ReuseIV.PHI;
966 IncV = ReuseIV.IncV;
967 }
968
Chris Lattner37ed8952005-08-08 22:32:34 +0000969 // Next, figure out what we can represent in the immediate fields of
970 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000971 // fields of the BasedUsers. We do this so that it increases the commonality
972 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000973 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000974 // If the user is not in the current loop, this means it is using the exit
975 // value of the IV. Do not put anything in the base, make sure it's all in
976 // the immediate field to allow as much factoring as possible.
977 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000978 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
979 UsersToProcess[i].Base);
980 UsersToProcess[i].Base =
981 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000982 } else {
983
984 // Addressing modes can be folded into loads and stores. Be careful that
985 // the store is through the expression, not of the expression though.
986 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
987 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
988 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
989 isAddress = true;
990
Evan Chengc567c4e2006-03-13 23:14:23 +0000991 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner5cf983e2005-08-16 00:38:11 +0000992 isAddress, L);
993 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000994 }
Evan Cheng3df447d2006-03-16 21:53:05 +0000995
Chris Lattnera091ff12005-08-09 00:18:09 +0000996 // Now that we know what we need to do, insert the PHI node itself.
997 //
998 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
999 << *CommonExprs << " :\n");
Evan Cheng3df447d2006-03-16 21:53:05 +00001000
Chris Lattnera091ff12005-08-09 00:18:09 +00001001 SCEVExpander Rewriter(*SE, *LI);
1002 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +00001003
Chris Lattnera091ff12005-08-09 00:18:09 +00001004 BasicBlock *Preheader = L->getLoopPreheader();
1005 Instruction *PreInsertPt = Preheader->getTerminator();
1006 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +00001007
Chris Lattner8048b852005-09-12 17:11:27 +00001008 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +00001009
Chris Lattnera091ff12005-08-09 00:18:09 +00001010 const Type *ReplacedTy = CommonExprs->getType();
Evan Cheng45206982006-03-17 19:52:23 +00001011
1012 // Emit the initial base value into the loop preheader.
1013 Value *CommonBaseV
1014 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1015 ReplacedTy);
1016
Evan Chengc28282b2006-03-18 08:03:12 +00001017 if (RewriteFactor == 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001018 // Create a new Phi for this base, and stick it in the loop header.
1019 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1020 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001021
Evan Cheng45206982006-03-17 19:52:23 +00001022 // Add common base to the new Phi node.
1023 NewPHI->addIncoming(CommonBaseV, Preheader);
1024
Evan Cheng3df447d2006-03-16 21:53:05 +00001025 // Insert the stride into the preheader.
1026 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1027 ReplacedTy);
1028 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001029
Evan Cheng3df447d2006-03-16 21:53:05 +00001030 // Emit the increment of the base value before the terminator of the loop
1031 // latch block, and add it to the Phi node.
1032 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1033 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +00001034
Evan Cheng3df447d2006-03-16 21:53:05 +00001035 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1036 ReplacedTy);
1037 IncV->setName(NewPHI->getName()+".inc");
1038 NewPHI->addIncoming(IncV, LatchBlock);
1039
Evan Cheng45206982006-03-17 19:52:23 +00001040 // Remember this in case a later stride is multiple of this.
Evan Chengc28282b2006-03-18 08:03:12 +00001041 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Cheng45206982006-03-17 19:52:23 +00001042 } else {
1043 Constant *C = dyn_cast<Constant>(CommonBaseV);
1044 if (!C ||
1045 (!C->isNullValue() &&
1046 !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
1047 // We want the common base emitted into the preheader!
1048 CommonBaseV = new CastInst(CommonBaseV, CommonBaseV->getType(),
1049 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001050 }
Chris Lattnera091ff12005-08-09 00:18:09 +00001051
Chris Lattner3ff62012006-08-03 06:34:50 +00001052 // We want to emit code for users inside the loop first. To do this, we
1053 // rearrange BasedUser so that the entries at the end have
1054 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1055 // vector (so we handle them first).
1056 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1057 PartitionByIsUseOfPostIncrementedValue);
1058
1059 // Sort this by base, so that things with the same base are handled
1060 // together. By partitioning first and stable-sorting later, we are
1061 // guaranteed that within each base we will pop off users from within the
1062 // loop before users outside of the loop with a particular base.
1063 //
1064 // We would like to use stable_sort here, but we can't. The problem is that
1065 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1066 // we don't have anything to do a '<' comparison on. Because we think the
1067 // number of uses is small, do a horrible bubble sort which just relies on
1068 // ==.
1069 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1070 // Get a base value.
1071 SCEVHandle Base = UsersToProcess[i].Base;
1072
1073 // Compact everything with this base to be consequetive with this one.
1074 for (unsigned j = i+1; j != e; ++j) {
1075 if (UsersToProcess[j].Base == Base) {
1076 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1077 ++i;
1078 }
1079 }
1080 }
1081
1082 // Process all the users now. This outer loop handles all bases, the inner
1083 // loop handles all users of a particular base.
Nate Begemane68bcd12005-07-30 00:15:07 +00001084 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001085 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001086
Chris Lattnera091ff12005-08-09 00:18:09 +00001087 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +00001088
Chris Lattnera091ff12005-08-09 00:18:09 +00001089 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001090 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1091 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +00001092
1093 // If BaseV is a constant other than 0, make sure that it gets inserted into
1094 // the preheader, instead of being forward substituted into the uses. We do
1095 // this by forcing a noop cast to be inserted into the preheader in this
1096 // case.
Chris Lattner3ff62012006-08-03 06:34:50 +00001097 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengc567c4e2006-03-13 23:14:23 +00001098 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Chris Lattnera091ff12005-08-09 00:18:09 +00001099 // We want this constant emitted into the preheader!
1100 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
1101 PreInsertPt);
1102 }
Chris Lattner3ff62012006-08-03 06:34:50 +00001103 }
1104
Nate Begemane68bcd12005-07-30 00:15:07 +00001105 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001106 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001107 do {
Chris Lattner3ff62012006-08-03 06:34:50 +00001108 // FIXME: Use emitted users to emit other users.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001109 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001110
Chris Lattnera091ff12005-08-09 00:18:09 +00001111 // If this instruction wants to use the post-incremented value, move it
1112 // after the post-inc and use its value instead of the PHI.
1113 Value *RewriteOp = NewPHI;
1114 if (User.isUseOfPostIncrementedValue) {
1115 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001116
1117 // If this user is in the loop, make sure it is the last thing in the
1118 // loop to ensure it is dominated by the increment.
1119 if (L->contains(User.Inst->getParent()))
1120 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001121 }
Evan Cheng398f7022006-06-09 00:12:42 +00001122 if (RewriteOp->getType() != ReplacedTy)
1123 RewriteOp = SCEVExpander::InsertCastOfTo(RewriteOp, ReplacedTy);
1124
Chris Lattnera091ff12005-08-09 00:18:09 +00001125 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1126
Chris Lattnerdb23c742005-08-03 22:51:21 +00001127 // Clear the SCEVExpander's expression map so that we are guaranteed
1128 // to have the code emitted where we expect it.
1129 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001130
1131 // If we are reusing the iv, then it must be multiplied by a constant
1132 // factor take advantage of addressing mode scale component.
Evan Chengc28282b2006-03-18 08:03:12 +00001133 if (RewriteFactor != 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001134 RewriteExpr =
1135 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001136 RewriteExpr->getType()),
1137 RewriteExpr);
1138
1139 // The common base is emitted in the loop preheader. But since we
1140 // are reusing an IV, it has not been used to initialize the PHI node.
1141 // Add it to the expression used to rewrite the uses.
1142 if (!isa<ConstantInt>(CommonBaseV) ||
1143 !cast<ConstantInt>(CommonBaseV)->isNullValue())
1144 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1145 SCEVUnknown::get(CommonBaseV));
1146 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001147
Chris Lattnera6d7c352005-08-04 20:03:32 +00001148 // Now that we know what we need to do, insert code before User for the
1149 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +00001150 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
1151 // Add BaseV to the PHI value if needed.
1152 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001153
Chris Lattner8447b492005-08-12 22:22:17 +00001154 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001155
Chris Lattnerdb23c742005-08-03 22:51:21 +00001156 // Mark old value we replaced as possibly dead, so that it is elminated
1157 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001158 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001159
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001160 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001161 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001162
Chris Lattner3ff62012006-08-03 06:34:50 +00001163 // If there are any more users to process with the same base, process them
1164 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001165 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001166 // TODO: Next, find out which base index is the most common, pull it out.
1167 }
1168
1169 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1170 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001171}
1172
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001173// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1174// uses in the loop, look to see if we can eliminate some, in favor of using
1175// common indvars for the different uses.
1176void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1177 // TODO: implement optzns here.
1178
1179
1180
1181
1182 // Finally, get the terminating condition for the loop if possible. If we
1183 // can, we want to change it to use a post-incremented version of its
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001184 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001185 // one register value.
1186 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1187 BasicBlock *Preheader = L->getLoopPreheader();
1188 BasicBlock *LatchBlock =
1189 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1190 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1191 if (!TermBr || TermBr->isUnconditional() ||
1192 !isa<SetCondInst>(TermBr->getCondition()))
1193 return;
1194 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1195
1196 // Search IVUsesByStride to find Cond's IVUse if there is one.
1197 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001198 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001199
Chris Lattnerb7a38942005-10-11 18:17:57 +00001200 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1201 ++Stride) {
1202 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1203 IVUsesByStride.find(StrideOrder[Stride]);
1204 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1205
1206 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1207 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001208 if (UI->User == Cond) {
1209 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001210 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001211 // NOTE: we could handle setcc instructions with multiple uses here, but
1212 // InstCombine does it as well for simple uses, it's not clear that it
1213 // occurs enough in real life to handle.
1214 break;
1215 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001216 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001217 if (!CondUse) return; // setcc doesn't use the IV.
1218
1219 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +00001220 // FIXME: Evaluate whether this is a good idea or not.
1221 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001222
1223 // It's possible for the setcc instruction to be anywhere in the loop, and
1224 // possible for it to have multiple users. If it is not immediately before
1225 // the latch block branch, move it.
1226 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1227 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1228 Cond->moveBefore(TermBr);
1229 } else {
1230 // Otherwise, clone the terminating condition and insert into the loopend.
1231 Cond = cast<SetCondInst>(Cond->clone());
1232 Cond->setName(L->getHeader()->getName() + ".termcond");
1233 LatchBlock->getInstList().insert(TermBr, Cond);
1234
1235 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001236 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001237 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001238 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001239 }
1240 }
1241
1242 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001243 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001244 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001245 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001246 CondUse->isUseOfPostIncrementedValue = true;
1247}
Nate Begemane68bcd12005-07-30 00:15:07 +00001248
Evan Chengf09f0eb2006-03-18 00:44:49 +00001249namespace {
1250 // Constant strides come first which in turns are sorted by their absolute
1251 // values. If absolute values are the same, then positive strides comes first.
1252 // e.g.
1253 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1254 struct StrideCompare {
1255 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1256 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1257 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1258 if (LHSC && RHSC) {
1259 int64_t LV = LHSC->getValue()->getSExtValue();
1260 int64_t RV = RHSC->getValue()->getSExtValue();
1261 uint64_t ALV = (LV < 0) ? -LV : LV;
1262 uint64_t ARV = (RV < 0) ? -RV : RV;
1263 if (ALV == ARV)
1264 return LV > RV;
1265 else
1266 return ALV < ARV;
Chris Lattner7d80b4f2006-03-22 17:27:24 +00001267 }
1268 return (LHSC && !RHSC);
Evan Chengf09f0eb2006-03-18 00:44:49 +00001269 }
1270 };
1271}
1272
Nate Begemanb18121e2004-10-18 21:08:22 +00001273void LoopStrengthReduce::runOnLoop(Loop *L) {
1274 // First step, transform all loops nesting inside of this loop.
1275 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1276 runOnLoop(*I);
1277
Nate Begemane68bcd12005-07-30 00:15:07 +00001278 // Next, find all uses of induction variables in this loop, and catagorize
1279 // them by stride. Start by finding all of the PHI nodes in the header for
1280 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001281 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001282 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001283 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001284
Nate Begemane68bcd12005-07-30 00:15:07 +00001285 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001286 if (IVUsesByStride.empty()) return;
1287
1288 // Optimize induction variables. Some indvar uses can be transformed to use
1289 // strides that will be needed for other purposes. A common example of this
1290 // is the exit test for the loop, which can often be rewritten to use the
1291 // computation of some other indvar to decide when to terminate the loop.
1292 OptimizeIndvars(L);
1293
Misha Brukmanb1c93172005-04-21 23:48:37 +00001294
Nate Begemane68bcd12005-07-30 00:15:07 +00001295 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1296 // doing computation in byte values, promote to 32-bit values if safe.
1297
1298 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1299 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1300 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1301 // to be careful that IV's are all the same type. Only works for intptr_t
1302 // indvars.
1303
1304 // If we only have one stride, we can more aggressively eliminate some things.
1305 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001306
1307#ifndef NDEBUG
1308 DEBUG(std::cerr << "\nLSR on ");
1309 DEBUG(L->dump());
1310#endif
1311
1312 // IVsByStride keeps IVs for one particular loop.
1313 IVsByStride.clear();
1314
Evan Chengf09f0eb2006-03-18 00:44:49 +00001315 // Sort the StrideOrder so we process larger strides first.
1316 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1317
Chris Lattnera091ff12005-08-09 00:18:09 +00001318 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001319 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1320 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1321 // This extra layer of indirection makes the ordering of strides deterministic
1322 // - not dependent on map order.
1323 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1324 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1325 IVUsesByStride.find(StrideOrder[Stride]);
1326 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001327 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001328 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001329
1330 // Clean up after ourselves
1331 if (!DeadInsts.empty()) {
1332 DeleteTriviallyDeadInstructions(DeadInsts);
1333
Nate Begemane68bcd12005-07-30 00:15:07 +00001334 BasicBlock::iterator I = L->getHeader()->begin();
1335 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001336 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001337 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1338
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001339 // At this point, we know that we have killed one or more GEP
1340 // instructions. It is worth checking to see if the cann indvar is also
1341 // dead, so that we can remove it as well. The requirements for the cann
1342 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001343 // 1. the cann indvar has one use
1344 // 2. the use is an add instruction
1345 // 3. the add has one use
1346 // 4. the add is used by the cann indvar
1347 // If all four cases above are true, then we can remove both the add and
1348 // the cann indvar.
1349 // FIXME: this needs to eliminate an induction variable even if it's being
1350 // compared against some value to decide loop termination.
1351 if (PN->hasOneUse()) {
1352 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +00001353 if (BO && BO->hasOneUse()) {
1354 if (PN == *(BO->use_begin())) {
1355 DeadInsts.insert(BO);
1356 // Break the cycle, then delete the PHI.
1357 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001358 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001359 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001360 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001361 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001362 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001363 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001364 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001365 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001366
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001367 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001368 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001369 StrideOrder.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001370 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001371}