blob: 5b64e54f1f23e373f3b3246e44915a0971eec430 [file] [log] [blame]
Nate Begemaneaa13852004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Nate Begemaneaa13852004-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 Brukmanfd939082005-04-21 23:48:37 +00007//
Nate Begemaneaa13852004-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 Begemaneaa13852004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbe3e5212005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-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 Cohen2f3c9b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begeman16997482005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begeman16997482005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnere0391be2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begeman16997482005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000034#include "llvm/Support/Compiler.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000035#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000036#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000037#include <iostream>
Nate Begemaneaa13852004-10-18 21:08:22 +000038#include <set>
39using namespace llvm;
40
41namespace {
42 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner26d91f12005-08-04 22:34:05 +000043 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattner50fad702005-08-10 00:45:21 +000044 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemaneaa13852004-10-18 21:08:22 +000045
Chris Lattnerec3fb632005-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 Lattner010de252005-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 Lattnerc6bae652005-09-12 06:04:47 +000058 // instruction for a loop or uses dominated by the loop.
Chris Lattner010de252005-08-08 05:28:22 +000059 bool isUseOfPostIncrementedValue;
Chris Lattnerec3fb632005-08-03 22:21:05 +000060
61 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner010de252005-08-08 05:28:22 +000062 : Offset(Offs), User(U), OperandValToReplace(O),
63 isUseOfPostIncrementedValue(false) {}
Chris Lattnerec3fb632005-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 Begeman16997482005-07-30 00:15:07 +000071 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattnerec3fb632005-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 Begeman16997482005-07-30 00:15:07 +000077 }
78 };
79
Evan Chengd1d6b5c2006-03-16 21:53:05 +000080 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Cheng21495772006-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 Chengd1d6b5c2006-03-16 21:53:05 +000083 struct IVExpr {
Evan Cheng21495772006-03-18 08:03:12 +000084 SCEVHandle Stride;
Evan Chengd1d6b5c2006-03-16 21:53:05 +000085 SCEVHandle Base;
86 PHINode *PHI;
87 Value *IncV;
88
Evan Cheng21495772006-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 Chengd1d6b5c2006-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 Cheng21495772006-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 Chengd1d6b5c2006-03-16 21:53:05 +0000105 }
106 };
Nate Begeman16997482005-07-30 00:15:07 +0000107
Chris Lattner95255282006-06-28 23:17:24 +0000108 class VISIBILITY_HIDDEN LoopStrengthReduce : public FunctionPass {
Nate Begemaneaa13852004-10-18 21:08:22 +0000109 LoopInfo *LI;
Chris Lattner88cac3d2006-01-11 05:10:20 +0000110 ETForest *EF;
Nate Begeman16997482005-07-30 00:15:07 +0000111 ScalarEvolution *SE;
112 const TargetData *TD;
113 const Type *UIntPtrTy;
Nate Begemaneaa13852004-10-18 21:08:22 +0000114 bool Changed;
Chris Lattner7e608bb2005-08-02 02:52:02 +0000115
Nate Begeman16997482005-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 Lattner50fad702005-08-10 00:45:21 +0000118 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begeman16997482005-07-30 00:15:07 +0000119
Evan Chengd1d6b5c2006-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 Lattner7305ae22005-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 Lattner49f72e62005-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 Begeman16997482005-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 Chengd277f2c2006-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 Begemaneaa13852004-10-18 21:08:22 +0000142 public:
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000143 LoopStrengthReduce(const TargetLowering *tli = NULL)
144 : TLI(tli) {
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000145 }
146
Nate Begemaneaa13852004-10-18 21:08:22 +0000147 virtual bool runOnFunction(Function &) {
148 LI = &getAnalysis<LoopInfo>();
Chris Lattner88cac3d2006-01-11 05:10:20 +0000149 EF = &getAnalysis<ETForest>();
Nate Begeman16997482005-07-30 00:15:07 +0000150 SE = &getAnalysis<ScalarEvolution>();
151 TD = &getAnalysis<TargetData>();
152 UIntPtrTy = TD->getIntPtrType();
Nate Begemaneaa13852004-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 Lattner49f72e62005-08-04 01:19:13 +0000157
Nate Begemaneaa13852004-10-18 21:08:22 +0000158 return Changed;
159 }
160
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattneraa96ae72005-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 Lattner88cac3d2006-01-11 05:10:20 +0000167 AU.addPreserved<ETForest>();
Chris Lattneraa96ae72005-08-17 06:35:16 +0000168 AU.addPreserved<ImmediateDominators>();
169 AU.addPreserved<DominanceFrontier>();
170 AU.addPreserved<DominatorTree>();
171
Jeff Cohenf465db62005-02-27 19:37:07 +0000172 AU.addRequiredID(LoopSimplifyID);
Nate Begemaneaa13852004-10-18 21:08:22 +0000173 AU.addRequired<LoopInfo>();
Chris Lattner88cac3d2006-01-11 05:10:20 +0000174 AU.addRequired<ETForest>();
Jeff Cohen2f3c9b72005-03-04 04:04:26 +0000175 AU.addRequired<TargetData>();
Nate Begeman16997482005-07-30 00:15:07 +0000176 AU.addRequired<ScalarEvolution>();
Nate Begemaneaa13852004-10-18 21:08:22 +0000177 }
Chris Lattner49f72e62005-08-04 01:19:13 +0000178
179 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
180 ///
181 Value *getCastedVersionOf(Value *V);
182private:
Nate Begemaneaa13852004-10-18 21:08:22 +0000183 void runOnLoop(Loop *L);
Chris Lattner3416e5f2005-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 Lattner010de252005-08-08 05:28:22 +0000188 void OptimizeIndvars(Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000189
Evan Cheng31e77312006-07-18 19:07:58 +0000190 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*);
Evan Chengeb8f9e22006-03-17 19:52:23 +0000191
Chris Lattner50fad702005-08-10 00:45:21 +0000192 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
193 IVUsersOfOneStride &Uses,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000194 Loop *L, bool isOnlyStride);
Nate Begemaneaa13852004-10-18 21:08:22 +0000195 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
196 };
Chris Lattner7f8897f2006-08-27 22:42:52 +0000197 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemaneaa13852004-10-18 21:08:22 +0000198}
199
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000200FunctionPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
201 return new LoopStrengthReduce(TLI);
Nate Begemaneaa13852004-10-18 21:08:22 +0000202}
203
Chris Lattner49f72e62005-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 Lattner0a70f212006-02-04 09:52:43 +0000214 New = SCEVExpander::InsertCastOfTo(V, UIntPtrTy);
Chris Lattner7db543f2005-08-04 19:08:16 +0000215 DeadInsts.insert(cast<Instruction>(New));
216 return New;
Chris Lattner49f72e62005-08-04 01:19:13 +0000217}
218
219
Nate Begemaneaa13852004-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 Cohen0456e4a2005-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 Lattner52d83e62005-08-03 21:36:09 +0000232 SE->deleteInstructionFromRecords(I);
233 I->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +0000234 Changed = true;
235 }
236 }
237}
238
Jeff Cohenf465db62005-02-27 19:37:07 +0000239
Chris Lattner3416e5f2005-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 Lattner87265ab2005-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 Lattner3416e5f2005-08-04 17:40:30 +0000247 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattner87265ab2005-08-09 23:39:36 +0000248 if (!GEP || SE->hasSCEV(GEP))
Chris Lattner3416e5f2005-08-04 17:40:30 +0000249 return SE->getSCEV(Exp);
250
Nate Begeman16997482005-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 Lattner3416e5f2005-08-04 17:40:30 +0000257 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begeman16997482005-07-30 00:15:07 +0000258
259 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000260
261 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begeman16997482005-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 Spencerb83eb642006-10-20 07:07:24 +0000267 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Nate Begeman16997482005-07-30 00:15:07 +0000268 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattner3416e5f2005-08-04 17:40:30 +0000269 GEPVal = SCEVAddExpr::get(GEPVal,
270 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begeman16997482005-07-30 00:15:07 +0000271 } else {
Chris Lattner7db543f2005-08-04 19:08:16 +0000272 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
273 SCEVHandle Idx = SE->getSCEV(OpVal);
274
Chris Lattner3416e5f2005-08-04 17:40:30 +0000275 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
276 if (TypeSize != 1)
277 Idx = SCEVMulExpr::get(Idx,
Reid Spencerb83eb642006-10-20 07:07:24 +0000278 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattner3416e5f2005-08-04 17:40:30 +0000279 TypeSize)));
280 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begeman16997482005-07-30 00:15:07 +0000281 }
282 }
283
Chris Lattner87265ab2005-08-09 23:39:36 +0000284 SE->setSCEV(GEP, GEPVal);
Chris Lattner3416e5f2005-08-04 17:40:30 +0000285 return GEPVal;
Nate Begeman16997482005-07-30 00:15:07 +0000286}
287
Chris Lattner7db543f2005-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 Lattner50fad702005-08-10 00:45:21 +0000293 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattner7db543f2005-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 Lattner7db543f2005-08-04 19:08:16 +0000324 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattner50fad702005-08-10 00:45:21 +0000325 DEBUG(std::cerr << "[" << L->getHeader()->getName()
326 << "] Variable stride: " << *AddRec << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000327
Chris Lattner50fad702005-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 Lattner7db543f2005-08-04 19:08:16 +0000333 "Constants should be canonicalized to unsigned!");
Chris Lattner50fad702005-08-10 00:45:21 +0000334
Chris Lattner7db543f2005-08-04 19:08:16 +0000335 return true;
336}
337
Chris Lattner0ae33eb2005-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 Lattner88cac3d2006-01-11 05:10:20 +0000347 Loop *L, ETForest *EF, Pass *P) {
Chris Lattner0ae33eb2005-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 Lattner5e8ca662005-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 Lattner88cac3d2006-01-11 05:10:20 +0000355 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattner5e8ca662005-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 Lattner88cac3d2006-01-11 05:10:20 +0000372 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattner5e8ca662005-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) {
Chris Lattner0997fad2006-10-28 06:45:33 +0000381 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
382 true);
Chris Lattner1b9c8e72006-10-28 00:59:20 +0000383 // Splitting the critical edge can reduce the number of entries in this
384 // PHI.
385 e = PN->getNumIncomingValues();
Chris Lattner5e8ca662005-10-03 02:50:05 +0000386 if (--NumUses == 0) break;
387 }
388
389 return true;
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000390}
391
392
393
Nate Begeman16997482005-07-30 00:15:07 +0000394/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
395/// reducible SCEV, recursively add its users to the IVUsesByStride set and
396/// return true. Otherwise, return false.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000397bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
398 std::set<Instruction*> &Processed) {
Chris Lattner63ad7962005-10-21 05:45:41 +0000399 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
400 return false; // Void and FP expressions cannot be reduced.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000401 if (!Processed.insert(I).second)
402 return true; // Instruction already handled.
403
Chris Lattner7db543f2005-08-04 19:08:16 +0000404 // Get the symbolic expression for this instruction.
Chris Lattner3416e5f2005-08-04 17:40:30 +0000405 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattner7db543f2005-08-04 19:08:16 +0000406 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000407
Chris Lattner7db543f2005-08-04 19:08:16 +0000408 // Get the start and stride for this expression.
409 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattner50fad702005-08-10 00:45:21 +0000410 SCEVHandle Stride = Start;
Chris Lattner7db543f2005-08-04 19:08:16 +0000411 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
412 return false; // Non-reducible symbolic expression, bail out.
413
Nate Begeman16997482005-07-30 00:15:07 +0000414 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
415 Instruction *User = cast<Instruction>(*UI);
416
417 // Do not infinitely recurse on PHI nodes.
Chris Lattner396b2ba2005-09-13 02:09:55 +0000418 if (isa<PHINode>(User) && Processed.count(User))
Nate Begeman16997482005-07-30 00:15:07 +0000419 continue;
420
421 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnerf9186592005-08-04 00:14:11 +0000422 // don't recurse into it.
Chris Lattner7db543f2005-08-04 19:08:16 +0000423 bool AddUserToIVUsers = false;
Chris Lattnerf9186592005-08-04 00:14:11 +0000424 if (LI->getLoopFor(User->getParent()) != L) {
Chris Lattner396b2ba2005-09-13 02:09:55 +0000425 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
Chris Lattnerf9186592005-08-04 00:14:11 +0000426 << " OF SCEV: " << *ISE << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000427 AddUserToIVUsers = true;
Chris Lattner3416e5f2005-08-04 17:40:30 +0000428 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattnera4479ad2005-08-04 00:40:47 +0000429 DEBUG(std::cerr << "FOUND USER: " << *User
430 << " OF SCEV: " << *ISE << "\n");
Chris Lattner7db543f2005-08-04 19:08:16 +0000431 AddUserToIVUsers = true;
432 }
Nate Begeman16997482005-07-30 00:15:07 +0000433
Chris Lattner7db543f2005-08-04 19:08:16 +0000434 if (AddUserToIVUsers) {
Chris Lattner7305ae22005-10-09 06:20:55 +0000435 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
436 if (StrideUses.Users.empty()) // First occurance of this stride?
437 StrideOrder.push_back(Stride);
438
Chris Lattnera4479ad2005-08-04 00:40:47 +0000439 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnerc6bae652005-09-12 06:04:47 +0000440 // and decide what to do with it. If we are a use inside of the loop, use
441 // the value before incrementation, otherwise use it after incrementation.
Chris Lattner88cac3d2006-01-11 05:10:20 +0000442 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnerc6bae652005-09-12 06:04:47 +0000443 // The value used will be incremented by the stride more than we are
444 // expecting, so subtract this off.
445 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner7305ae22005-10-09 06:20:55 +0000446 StrideUses.addUser(NewStart, User, I);
447 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Chris Lattner5e8ca662005-10-03 02:50:05 +0000448 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000449 } else {
Chris Lattner7305ae22005-10-09 06:20:55 +0000450 StrideUses.addUser(Start, User, I);
Chris Lattnerc6bae652005-09-12 06:04:47 +0000451 }
Nate Begeman16997482005-07-30 00:15:07 +0000452 }
453 }
454 return true;
455}
456
457namespace {
458 /// BasedUser - For a particular base value, keep information about how we've
459 /// partitioned the expression so far.
460 struct BasedUser {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000461 /// Base - The Base value for the PHI node that needs to be inserted for
462 /// this use. As the use is processed, information gets moved from this
463 /// field to the Imm field (below). BasedUser values are sorted by this
464 /// field.
465 SCEVHandle Base;
466
Nate Begeman16997482005-07-30 00:15:07 +0000467 /// Inst - The instruction using the induction variable.
468 Instruction *Inst;
469
Chris Lattnerec3fb632005-08-03 22:21:05 +0000470 /// OperandValToReplace - The operand value of Inst to replace with the
471 /// EmittedBase.
472 Value *OperandValToReplace;
Nate Begeman16997482005-07-30 00:15:07 +0000473
474 /// Imm - The immediate value that should be added to the base immediately
475 /// before Inst, because it will be folded into the imm field of the
476 /// instruction.
477 SCEVHandle Imm;
478
479 /// EmittedBase - The actual value* to use for the base value of this
480 /// operation. This is null if we should just use zero so far.
481 Value *EmittedBase;
482
Chris Lattner010de252005-08-08 05:28:22 +0000483 // isUseOfPostIncrementedValue - True if this should use the
484 // post-incremented version of this IV, not the preincremented version.
485 // This can only be set in special cases, such as the terminating setcc
Chris Lattnerc6bae652005-09-12 06:04:47 +0000486 // instruction for a loop and uses outside the loop that are dominated by
487 // the loop.
Chris Lattner010de252005-08-08 05:28:22 +0000488 bool isUseOfPostIncrementedValue;
Chris Lattnera553b0c2005-08-08 22:56:21 +0000489
490 BasedUser(IVStrideUse &IVSU)
491 : Base(IVSU.Offset), Inst(IVSU.User),
492 OperandValToReplace(IVSU.OperandValToReplace),
493 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
494 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begeman16997482005-07-30 00:15:07 +0000495
Chris Lattner2114b272005-08-04 20:03:32 +0000496 // Once we rewrite the code to insert the new IVs we want, update the
497 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
498 // to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000499 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000500 SCEVExpander &Rewriter, Loop *L,
501 Pass *P);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000502
503 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
504 SCEVExpander &Rewriter,
505 Instruction *IP, Loop *L);
Nate Begeman16997482005-07-30 00:15:07 +0000506 void dump() const;
507 };
508}
509
510void BasedUser::dump() const {
Chris Lattnera553b0c2005-08-08 22:56:21 +0000511 std::cerr << " Base=" << *Base;
Nate Begeman16997482005-07-30 00:15:07 +0000512 std::cerr << " Imm=" << *Imm;
513 if (EmittedBase)
514 std::cerr << " EB=" << *EmittedBase;
515
516 std::cerr << " Inst: " << *Inst;
517}
518
Chris Lattner221fc3c2006-02-04 07:36:50 +0000519Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
520 SCEVExpander &Rewriter,
521 Instruction *IP, Loop *L) {
522 // Figure out where we *really* want to insert this code. In particular, if
523 // the user is inside of a loop that is nested inside of L, we really don't
524 // want to insert this expression before the user, we'd rather pull it out as
525 // many loops as possible.
526 LoopInfo &LI = Rewriter.getLoopInfo();
527 Instruction *BaseInsertPt = IP;
528
529 // Figure out the most-nested loop that IP is in.
530 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
531
532 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
533 // the preheader of the outer-most loop where NewBase is not loop invariant.
534 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
535 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
536 InsertLoop = InsertLoop->getParentLoop();
537 }
538
539 // If there is no immediate value, skip the next part.
540 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
541 if (SC->getValue()->isNullValue())
542 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
543 OperandValToReplace->getType());
544
545 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
546
547 // Always emit the immediate (if non-zero) into the same block as the user.
548 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
549 return Rewriter.expandCodeFor(NewValSCEV, IP,
550 OperandValToReplace->getType());
551}
552
553
Chris Lattner2114b272005-08-04 20:03:32 +0000554// Once we rewrite the code to insert the new IVs we want, update the
555// operands of Inst to use the new expression 'NewBase', with 'Imm' added
556// to it.
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000557void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnere0391be2005-08-12 22:06:11 +0000558 SCEVExpander &Rewriter,
Chris Lattnerc60fb082005-08-12 22:22:17 +0000559 Loop *L, Pass *P) {
Chris Lattner2114b272005-08-04 20:03:32 +0000560 if (!isa<PHINode>(Inst)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000561 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattner2114b272005-08-04 20:03:32 +0000562 // Replace the use of the operand Value with the new Phi we just created.
563 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
564 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
565 return;
566 }
567
568 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerc41e3452005-08-10 00:35:32 +0000569 // expression into each operand block that uses it. Note that PHI nodes can
570 // have multiple entries for the same predecessor. We use a map to make sure
571 // that a PHI node only has a single Value* for each predecessor (which also
572 // prevents us from inserting duplicate code in some blocks).
573 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattner2114b272005-08-04 20:03:32 +0000574 PHINode *PN = cast<PHINode>(Inst);
575 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
576 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattnere0391be2005-08-12 22:06:11 +0000577 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattner396b2ba2005-09-13 02:09:55 +0000578 // code on all predecessor/successor paths. We do this unless this is the
579 // canonical backedge for this loop, as this can make some inserted code
580 // be in an illegal position.
Chris Lattner37edbf02005-10-03 00:31:52 +0000581 BasicBlock *PHIPred = PN->getIncomingBlock(i);
582 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
583 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner37edbf02005-10-03 00:31:52 +0000584
Chris Lattneraa96ae72005-08-17 06:35:16 +0000585 // First step, split the critical edge.
Chris Lattner0997fad2006-10-28 06:45:33 +0000586 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattnerc60fb082005-08-12 22:22:17 +0000587
Chris Lattneraa96ae72005-08-17 06:35:16 +0000588 // Next step: move the basic block. In particular, if the PHI node
589 // is outside of the loop, and PredTI is in the loop, we want to
590 // move the block to be immediately before the PHI block, not
591 // immediately after PredTI.
Chris Lattner37edbf02005-10-03 00:31:52 +0000592 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattneraa96ae72005-08-17 06:35:16 +0000593 BasicBlock *NewBB = PN->getIncomingBlock(i);
594 NewBB->moveBefore(PN->getParent());
Chris Lattnere0391be2005-08-12 22:06:11 +0000595 }
Chris Lattner1b9c8e72006-10-28 00:59:20 +0000596
597 // Splitting the edge can reduce the number of PHI entries we have.
598 e = PN->getNumIncomingValues();
Chris Lattnere0391be2005-08-12 22:06:11 +0000599 }
Chris Lattner2114b272005-08-04 20:03:32 +0000600
Chris Lattnerc41e3452005-08-10 00:35:32 +0000601 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
602 if (!Code) {
603 // Insert the code into the end of the predecessor block.
Chris Lattner221fc3c2006-02-04 07:36:50 +0000604 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
605 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerc41e3452005-08-10 00:35:32 +0000606 }
Chris Lattner2114b272005-08-04 20:03:32 +0000607
608 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerc41e3452005-08-10 00:35:32 +0000609 PN->setIncomingValue(i, Code);
Chris Lattner2114b272005-08-04 20:03:32 +0000610 Rewriter.clear();
611 }
612 }
613 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
614}
615
616
Nate Begeman16997482005-07-30 00:15:07 +0000617/// isTargetConstant - Return true if the following can be referenced by the
618/// immediate field of a target instruction.
Evan Chengd277f2c2006-03-13 23:14:23 +0000619static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner3821e472005-08-08 06:25:50 +0000620 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattnere08dc622005-12-05 18:23:57 +0000621 int64_t V = SC->getValue()->getSExtValue();
Evan Chengd277f2c2006-03-13 23:14:23 +0000622 if (TLI)
623 return TLI->isLegalAddressImmediate(V);
624 else
625 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
626 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner3821e472005-08-08 06:25:50 +0000627 }
Jeff Cohend29b6aa2005-07-30 18:33:25 +0000628
Nate Begeman16997482005-07-30 00:15:07 +0000629 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
630 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Evan Chengd277f2c2006-03-13 23:14:23 +0000631 if (CE->getOpcode() == Instruction::Cast) {
632 Constant *Op0 = CE->getOperand(0);
633 if (isa<GlobalValue>(Op0) &&
634 TLI &&
635 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begeman16997482005-07-30 00:15:07 +0000636 return true;
Evan Chengd277f2c2006-03-13 23:14:23 +0000637 }
Nate Begeman16997482005-07-30 00:15:07 +0000638 return false;
639}
640
Chris Lattner44b807e2005-08-08 22:32:34 +0000641/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
642/// loop varying to the Imm operand.
643static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
644 Loop *L) {
645 if (Val->isLoopInvariant(L)) return; // Nothing to do.
646
647 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
648 std::vector<SCEVHandle> NewOps;
649 NewOps.reserve(SAE->getNumOperands());
650
651 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
652 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
653 // If this is a loop-variant expression, it must stay in the immediate
654 // field of the expression.
655 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
656 } else {
657 NewOps.push_back(SAE->getOperand(i));
658 }
659
660 if (NewOps.empty())
661 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
662 else
663 Val = SCEVAddExpr::get(NewOps);
664 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
665 // Try to pull immediates out of the start value of nested addrec's.
666 SCEVHandle Start = SARE->getStart();
667 MoveLoopVariantsToImediateField(Start, Imm, L);
668
669 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
670 Ops[0] = Start;
671 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
672 } else {
673 // Otherwise, all of Val is variant, move the whole thing over.
674 Imm = SCEVAddExpr::get(Imm, Val);
675 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
676 }
677}
678
679
Chris Lattner26d91f12005-08-04 22:34:05 +0000680/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begeman16997482005-07-30 00:15:07 +0000681/// that can fit into the immediate field of instructions in the target.
Chris Lattner26d91f12005-08-04 22:34:05 +0000682/// Accumulate these immediate values into the Imm value.
Evan Chengd277f2c2006-03-13 23:14:23 +0000683static void MoveImmediateValues(const TargetLowering *TLI,
684 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner26d91f12005-08-04 22:34:05 +0000685 bool isAddress, Loop *L) {
Chris Lattner7a658392005-08-03 23:44:42 +0000686 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner26d91f12005-08-04 22:34:05 +0000687 std::vector<SCEVHandle> NewOps;
688 NewOps.reserve(SAE->getNumOperands());
689
Chris Lattner221fc3c2006-02-04 07:36:50 +0000690 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
691 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengd277f2c2006-03-13 23:14:23 +0000692 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000693
694 if (!NewOp->isLoopInvariant(L)) {
Chris Lattner7db543f2005-08-04 19:08:16 +0000695 // If this is a loop-variant expression, it must stay in the immediate
696 // field of the expression.
Chris Lattner221fc3c2006-02-04 07:36:50 +0000697 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner26d91f12005-08-04 22:34:05 +0000698 } else {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000699 NewOps.push_back(NewOp);
Nate Begeman16997482005-07-30 00:15:07 +0000700 }
Chris Lattner221fc3c2006-02-04 07:36:50 +0000701 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000702
703 if (NewOps.empty())
704 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
705 else
706 Val = SCEVAddExpr::get(NewOps);
707 return;
Chris Lattner7a658392005-08-03 23:44:42 +0000708 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
709 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner26d91f12005-08-04 22:34:05 +0000710 SCEVHandle Start = SARE->getStart();
Evan Chengd277f2c2006-03-13 23:14:23 +0000711 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner26d91f12005-08-04 22:34:05 +0000712
713 if (Start != SARE->getStart()) {
714 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
715 Ops[0] = Start;
716 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
717 }
718 return;
Chris Lattner221fc3c2006-02-04 07:36:50 +0000719 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
720 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengd277f2c2006-03-13 23:14:23 +0000721 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner221fc3c2006-02-04 07:36:50 +0000722 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
723
724 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
725 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengd277f2c2006-03-13 23:14:23 +0000726 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner221fc3c2006-02-04 07:36:50 +0000727
728 // If we extracted something out of the subexpressions, see if we can
729 // simplify this!
730 if (NewOp != SME->getOperand(1)) {
731 // Scale SubImm up by "8". If the result is a target constant, we are
732 // good.
733 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengd277f2c2006-03-13 23:14:23 +0000734 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner221fc3c2006-02-04 07:36:50 +0000735 // Accumulate the immediate.
736 Imm = SCEVAddExpr::get(Imm, SubImm);
737
738 // Update what is left of 'Val'.
739 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
740 return;
741 }
742 }
743 }
Nate Begeman16997482005-07-30 00:15:07 +0000744 }
745
Chris Lattner26d91f12005-08-04 22:34:05 +0000746 // Loop-variant expressions must stay in the immediate field of the
747 // expression.
Evan Chengd277f2c2006-03-13 23:14:23 +0000748 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner26d91f12005-08-04 22:34:05 +0000749 !Val->isLoopInvariant(L)) {
750 Imm = SCEVAddExpr::get(Imm, Val);
751 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
752 return;
Chris Lattner7a2ca562005-08-04 19:26:19 +0000753 }
Chris Lattner26d91f12005-08-04 22:34:05 +0000754
755 // Otherwise, no immediates to move.
Nate Begeman16997482005-07-30 00:15:07 +0000756}
757
Chris Lattner934520a2005-08-13 07:27:18 +0000758
Chris Lattner7e79b382006-08-03 06:34:50 +0000759/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
760/// added together. This is used to reassociate common addition subexprs
761/// together for maximal sharing when rewriting bases.
Chris Lattner934520a2005-08-13 07:27:18 +0000762static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
763 SCEVHandle Expr) {
764 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
765 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
766 SeparateSubExprs(SubExprs, AE->getOperand(j));
767 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
768 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
769 if (SARE->getOperand(0) == Zero) {
770 SubExprs.push_back(Expr);
771 } else {
772 // Compute the addrec with zero as its base.
773 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
774 Ops[0] = Zero; // Start with zero base.
775 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
776
777
778 SeparateSubExprs(SubExprs, SARE->getOperand(0));
779 }
780 } else if (!isa<SCEVConstant>(Expr) ||
781 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
782 // Do not add zero.
783 SubExprs.push_back(Expr);
784 }
785}
786
787
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000788/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
789/// removing any common subexpressions from it. Anything truly common is
790/// removed, accumulated, and returned. This looks for things like (a+b+c) and
791/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
792static SCEVHandle
793RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
794 unsigned NumUses = Uses.size();
795
796 // Only one use? Use its base, regardless of what it is!
797 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
798 SCEVHandle Result = Zero;
799 if (NumUses == 1) {
800 std::swap(Result, Uses[0].Base);
801 return Result;
802 }
803
804 // To find common subexpressions, count how many of Uses use each expression.
805 // If any subexpressions are used Uses.size() times, they are common.
806 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
807
Chris Lattnerd6155e92005-10-11 18:41:04 +0000808 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
809 // order we see them.
810 std::vector<SCEVHandle> UniqueSubExprs;
811
Chris Lattner934520a2005-08-13 07:27:18 +0000812 std::vector<SCEVHandle> SubExprs;
813 for (unsigned i = 0; i != NumUses; ++i) {
814 // If the base is zero (which is common), return zero now, there are no
815 // CSEs we can find.
816 if (Uses[i].Base == Zero) return Zero;
817
818 // Split the expression into subexprs.
819 SeparateSubExprs(SubExprs, Uses[i].Base);
820 // Add one to SubExpressionUseCounts for each subexpr present.
821 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattnerd6155e92005-10-11 18:41:04 +0000822 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
823 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner934520a2005-08-13 07:27:18 +0000824 SubExprs.clear();
825 }
826
Chris Lattnerd6155e92005-10-11 18:41:04 +0000827 // Now that we know how many times each is used, build Result. Iterate over
828 // UniqueSubexprs so that we have a stable ordering.
829 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
830 std::map<SCEVHandle, unsigned>::iterator I =
831 SubExpressionUseCounts.find(UniqueSubExprs[i]);
832 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000833 if (I->second == NumUses) { // Found CSE!
834 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000835 } else {
836 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattnerd6155e92005-10-11 18:41:04 +0000837 SubExpressionUseCounts.erase(I);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000838 }
Chris Lattnerd6155e92005-10-11 18:41:04 +0000839 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000840
841 // If we found no CSE's, return now.
842 if (Result == Zero) return Result;
843
844 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner934520a2005-08-13 07:27:18 +0000845 for (unsigned i = 0; i != NumUses; ++i) {
846 // Split the expression into subexprs.
847 SeparateSubExprs(SubExprs, Uses[i].Base);
848
849 // Remove any common subexpressions.
850 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
851 if (SubExpressionUseCounts.count(SubExprs[j])) {
852 SubExprs.erase(SubExprs.begin()+j);
853 --j; --e;
854 }
855
856 // Finally, the non-shared expressions together.
857 if (SubExprs.empty())
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000858 Uses[i].Base = Zero;
Chris Lattner934520a2005-08-13 07:27:18 +0000859 else
860 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner27e51422005-08-13 07:42:01 +0000861 SubExprs.clear();
Chris Lattner934520a2005-08-13 07:27:18 +0000862 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000863
864 return Result;
865}
866
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000867/// isZero - returns true if the scalar evolution expression is zero.
868///
869static bool isZero(SCEVHandle &V) {
870 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencerb83eb642006-10-20 07:07:24 +0000871 return SC->getValue()->getZExtValue() == 0;
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000872 return false;
873}
874
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000875
Evan Chengeb8f9e22006-03-17 19:52:23 +0000876/// CheckForIVReuse - Returns the multiple if the stride is the multiple
877/// of a previous stride and it is a legal value for the target addressing
878/// mode scale component. This allows the users of this stride to be rewritten
Evan Cheng21495772006-03-18 08:03:12 +0000879/// as prev iv * factor. It returns 0 if no reuse is possible.
Evan Chengeb8f9e22006-03-17 19:52:23 +0000880unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
Evan Cheng31e77312006-07-18 19:07:58 +0000881 IVExpr &IV, const Type *Ty) {
Evan Cheng21495772006-03-18 08:03:12 +0000882 if (!TLI) return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000883
884 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Evan Cheng21495772006-03-18 08:03:12 +0000885 int64_t SInt = SC->getValue()->getSExtValue();
886 if (SInt == 1) return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000887
888 for (TargetLowering::legal_am_scale_iterator
889 I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
890 I != E; ++I) {
891 unsigned Scale = *I;
Reid Spencerad207262006-04-12 19:28:15 +0000892 if (unsigned(abs(SInt)) < Scale || (SInt % Scale) != 0)
Evan Chengeb8f9e22006-03-17 19:52:23 +0000893 continue;
894 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
895 IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, Type::UIntTy));
896 if (SI == IVsByStride.end())
897 continue;
898 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
899 IE = SI->second.IVs.end(); II != IE; ++II)
900 // FIXME: Only handle base == 0 for now.
Evan Cheng31e77312006-07-18 19:07:58 +0000901 // Only reuse previous IV if it would not require a type conversion.
902 if (isZero(II->Base) &&
903 II->Base->getType()->isLosslesslyConvertibleTo(Ty)) {
Evan Chengeb8f9e22006-03-17 19:52:23 +0000904 IV = *II;
905 return Scale;
906 }
907 }
908 }
909
Evan Cheng21495772006-03-18 08:03:12 +0000910 return 0;
Evan Chengeb8f9e22006-03-17 19:52:23 +0000911}
912
Chris Lattner7e79b382006-08-03 06:34:50 +0000913/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
914/// returns true if Val's isUseOfPostIncrementedValue is true.
915static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
916 return Val.isUseOfPostIncrementedValue;
917}
Evan Chengeb8f9e22006-03-17 19:52:23 +0000918
Nate Begeman16997482005-07-30 00:15:07 +0000919/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
920/// stride of IV. All of the users may have different starting values, and this
921/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattner50fad702005-08-10 00:45:21 +0000922void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattnerec3fb632005-08-03 22:21:05 +0000923 IVUsersOfOneStride &Uses,
924 Loop *L,
Nate Begeman16997482005-07-30 00:15:07 +0000925 bool isOnlyStride) {
926 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattnera553b0c2005-08-08 22:56:21 +0000927 // this new vector, each 'BasedUser' contains 'Base' the base of the
928 // strided accessas well as the old information from Uses. We progressively
929 // move information from the Base field to the Imm field, until we eventually
930 // have the full access expression to rewrite the use.
931 std::vector<BasedUser> UsersToProcess;
Nate Begeman16997482005-07-30 00:15:07 +0000932 UsersToProcess.reserve(Uses.Users.size());
Chris Lattnera553b0c2005-08-08 22:56:21 +0000933 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
934 UsersToProcess.push_back(Uses.Users[i]);
935
936 // Move any loop invariant operands from the offset field to the immediate
937 // field of the use, so that we don't try to use something before it is
938 // computed.
939 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
940 UsersToProcess.back().Imm, L);
941 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner26d91f12005-08-04 22:34:05 +0000942 "Base value is not loop invariant!");
Nate Begeman16997482005-07-30 00:15:07 +0000943 }
Evan Chengeb8f9e22006-03-17 19:52:23 +0000944
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000945 // We now have a whole bunch of uses of like-strided induction variables, but
946 // they might all have different bases. We want to emit one PHI node for this
947 // stride which we fold as many common expressions (between the IVs) into as
948 // possible. Start by identifying the common expressions in the base values
949 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
950 // "A+B"), emit it to the preheader, then remove the expression from the
951 // UsersToProcess base values.
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000952 SCEVHandle CommonExprs =
953 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000954
Evan Cheng31e77312006-07-18 19:07:58 +0000955 // Check if it is possible to reuse a IV with stride that is factor of this
956 // stride. And the multiple is a number that can be encoded in the scale
957 // field of the target addressing mode.
958 PHINode *NewPHI = NULL;
959 Value *IncV = NULL;
960 IVExpr ReuseIV;
961 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
962 CommonExprs->getType());
963 if (RewriteFactor != 0) {
964 DEBUG(std::cerr << "BASED ON IV of STRIDE " << *ReuseIV.Stride
965 << " and BASE " << *ReuseIV.Base << " :\n");
966 NewPHI = ReuseIV.PHI;
967 IncV = ReuseIV.IncV;
968 }
969
Chris Lattner44b807e2005-08-08 22:32:34 +0000970 // Next, figure out what we can represent in the immediate fields of
971 // instructions. If we can represent anything there, move it to the imm
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000972 // fields of the BasedUsers. We do this so that it increases the commonality
973 // of the remaining uses.
Chris Lattner44b807e2005-08-08 22:32:34 +0000974 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner80b32b32005-08-16 00:38:11 +0000975 // If the user is not in the current loop, this means it is using the exit
976 // value of the IV. Do not put anything in the base, make sure it's all in
977 // the immediate field to allow as much factoring as possible.
978 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattner8385e512005-08-17 21:22:41 +0000979 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
980 UsersToProcess[i].Base);
981 UsersToProcess[i].Base =
982 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner80b32b32005-08-16 00:38:11 +0000983 } else {
984
985 // Addressing modes can be folded into loads and stores. Be careful that
986 // the store is through the expression, not of the expression though.
987 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
988 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
989 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
990 isAddress = true;
991
Evan Chengd277f2c2006-03-13 23:14:23 +0000992 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner80b32b32005-08-16 00:38:11 +0000993 isAddress, L);
994 }
Chris Lattner44b807e2005-08-08 22:32:34 +0000995 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000996
Chris Lattner1bbae0c2005-08-09 00:18:09 +0000997 // Now that we know what we need to do, insert the PHI node itself.
998 //
999 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
1000 << *CommonExprs << " :\n");
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001001
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001002 SCEVExpander Rewriter(*SE, *LI);
1003 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner44b807e2005-08-08 22:32:34 +00001004
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001005 BasicBlock *Preheader = L->getLoopPreheader();
1006 Instruction *PreInsertPt = Preheader->getTerminator();
1007 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner44b807e2005-08-08 22:32:34 +00001008
Chris Lattner12b50412005-09-12 17:11:27 +00001009 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001010
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001011 const Type *ReplacedTy = CommonExprs->getType();
Evan Chengeb8f9e22006-03-17 19:52:23 +00001012
1013 // Emit the initial base value into the loop preheader.
1014 Value *CommonBaseV
1015 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1016 ReplacedTy);
1017
Evan Cheng21495772006-03-18 08:03:12 +00001018 if (RewriteFactor == 0) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001019 // Create a new Phi for this base, and stick it in the loop header.
1020 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1021 ++NumInserted;
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001022
Evan Chengeb8f9e22006-03-17 19:52:23 +00001023 // Add common base to the new Phi node.
1024 NewPHI->addIncoming(CommonBaseV, Preheader);
1025
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001026 // Insert the stride into the preheader.
1027 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1028 ReplacedTy);
1029 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattner50fad702005-08-10 00:45:21 +00001030
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001031 // Emit the increment of the base value before the terminator of the loop
1032 // latch block, and add it to the Phi node.
1033 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1034 SCEVUnknown::get(StrideV));
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001035
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001036 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1037 ReplacedTy);
1038 IncV->setName(NewPHI->getName()+".inc");
1039 NewPHI->addIncoming(IncV, LatchBlock);
1040
Evan Chengeb8f9e22006-03-17 19:52:23 +00001041 // Remember this in case a later stride is multiple of this.
Evan Cheng21495772006-03-18 08:03:12 +00001042 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Chengeb8f9e22006-03-17 19:52:23 +00001043 } else {
1044 Constant *C = dyn_cast<Constant>(CommonBaseV);
1045 if (!C ||
1046 (!C->isNullValue() &&
1047 !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
1048 // We want the common base emitted into the preheader!
1049 CommonBaseV = new CastInst(CommonBaseV, CommonBaseV->getType(),
1050 "commonbase", PreInsertPt);
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001051 }
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001052
Chris Lattner7e79b382006-08-03 06:34:50 +00001053 // We want to emit code for users inside the loop first. To do this, we
1054 // rearrange BasedUser so that the entries at the end have
1055 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1056 // vector (so we handle them first).
1057 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1058 PartitionByIsUseOfPostIncrementedValue);
1059
1060 // Sort this by base, so that things with the same base are handled
1061 // together. By partitioning first and stable-sorting later, we are
1062 // guaranteed that within each base we will pop off users from within the
1063 // loop before users outside of the loop with a particular base.
1064 //
1065 // We would like to use stable_sort here, but we can't. The problem is that
1066 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1067 // we don't have anything to do a '<' comparison on. Because we think the
1068 // number of uses is small, do a horrible bubble sort which just relies on
1069 // ==.
1070 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1071 // Get a base value.
1072 SCEVHandle Base = UsersToProcess[i].Base;
1073
1074 // Compact everything with this base to be consequetive with this one.
1075 for (unsigned j = i+1; j != e; ++j) {
1076 if (UsersToProcess[j].Base == Base) {
1077 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1078 ++i;
1079 }
1080 }
1081 }
1082
1083 // Process all the users now. This outer loop handles all bases, the inner
1084 // loop handles all users of a particular base.
Nate Begeman16997482005-07-30 00:15:07 +00001085 while (!UsersToProcess.empty()) {
Chris Lattner7b445c52005-10-11 18:30:57 +00001086 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001087
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001088 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbe3e5212005-08-03 23:30:08 +00001089
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001090 // Emit the code for Base into the preheader.
Chris Lattner5272f3c2005-08-08 05:47:49 +00001091 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1092 ReplacedTy);
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001093
1094 // If BaseV is a constant other than 0, make sure that it gets inserted into
1095 // the preheader, instead of being forward substituted into the uses. We do
1096 // this by forcing a noop cast to be inserted into the preheader in this
1097 // case.
Chris Lattner7e79b382006-08-03 06:34:50 +00001098 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengd277f2c2006-03-13 23:14:23 +00001099 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001100 // We want this constant emitted into the preheader!
1101 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
1102 PreInsertPt);
1103 }
Chris Lattner7e79b382006-08-03 06:34:50 +00001104 }
1105
Nate Begeman16997482005-07-30 00:15:07 +00001106 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattner2351aba2005-08-03 22:51:21 +00001107 // the instructions that we identified as using this stride and base.
Chris Lattner7b445c52005-10-11 18:30:57 +00001108 do {
Chris Lattner7e79b382006-08-03 06:34:50 +00001109 // FIXME: Use emitted users to emit other users.
Chris Lattner7b445c52005-10-11 18:30:57 +00001110 BasedUser &User = UsersToProcess.back();
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001111
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001112 // If this instruction wants to use the post-incremented value, move it
1113 // after the post-inc and use its value instead of the PHI.
1114 Value *RewriteOp = NewPHI;
1115 if (User.isUseOfPostIncrementedValue) {
1116 RewriteOp = IncV;
Chris Lattnerc6bae652005-09-12 06:04:47 +00001117
1118 // If this user is in the loop, make sure it is the last thing in the
1119 // loop to ensure it is dominated by the increment.
1120 if (L->contains(User.Inst->getParent()))
1121 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001122 }
Evan Cheng86c75d32006-06-09 00:12:42 +00001123 if (RewriteOp->getType() != ReplacedTy)
1124 RewriteOp = SCEVExpander::InsertCastOfTo(RewriteOp, ReplacedTy);
1125
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001126 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1127
Chris Lattner2351aba2005-08-03 22:51:21 +00001128 // Clear the SCEVExpander's expression map so that we are guaranteed
1129 // to have the code emitted where we expect it.
1130 Rewriter.clear();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001131
1132 // If we are reusing the iv, then it must be multiplied by a constant
1133 // factor take advantage of addressing mode scale component.
Evan Cheng21495772006-03-18 08:03:12 +00001134 if (RewriteFactor != 0) {
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001135 RewriteExpr =
1136 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Chengeb8f9e22006-03-17 19:52:23 +00001137 RewriteExpr->getType()),
1138 RewriteExpr);
1139
1140 // The common base is emitted in the loop preheader. But since we
1141 // are reusing an IV, it has not been used to initialize the PHI node.
1142 // Add it to the expression used to rewrite the uses.
1143 if (!isa<ConstantInt>(CommonBaseV) ||
1144 !cast<ConstantInt>(CommonBaseV)->isNullValue())
1145 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1146 SCEVUnknown::get(CommonBaseV));
1147 }
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001148
Chris Lattner2114b272005-08-04 20:03:32 +00001149 // Now that we know what we need to do, insert code before User for the
1150 // immediate and any loop-variant expressions.
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001151 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
1152 // Add BaseV to the PHI value if needed.
1153 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001154
Chris Lattnerc60fb082005-08-12 22:22:17 +00001155 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohend29b6aa2005-07-30 18:33:25 +00001156
Chris Lattner2351aba2005-08-03 22:51:21 +00001157 // Mark old value we replaced as possibly dead, so that it is elminated
1158 // if we just replaced the last use of that value.
Chris Lattner2114b272005-08-04 20:03:32 +00001159 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begeman16997482005-07-30 00:15:07 +00001160
Chris Lattner7b445c52005-10-11 18:30:57 +00001161 UsersToProcess.pop_back();
Chris Lattner2351aba2005-08-03 22:51:21 +00001162 ++NumReduced;
Chris Lattner7b445c52005-10-11 18:30:57 +00001163
Chris Lattner7e79b382006-08-03 06:34:50 +00001164 // If there are any more users to process with the same base, process them
1165 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner7b445c52005-10-11 18:30:57 +00001166 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begeman16997482005-07-30 00:15:07 +00001167 // TODO: Next, find out which base index is the most common, pull it out.
1168 }
1169
1170 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1171 // different starting values, into different PHIs.
Nate Begeman16997482005-07-30 00:15:07 +00001172}
1173
Chris Lattner010de252005-08-08 05:28:22 +00001174// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1175// uses in the loop, look to see if we can eliminate some, in favor of using
1176// common indvars for the different uses.
1177void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1178 // TODO: implement optzns here.
1179
1180
1181
1182
1183 // Finally, get the terminating condition for the loop if possible. If we
1184 // can, we want to change it to use a post-incremented version of its
Chris Lattner98d98112006-03-24 07:14:34 +00001185 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner010de252005-08-08 05:28:22 +00001186 // one register value.
1187 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1188 BasicBlock *Preheader = L->getLoopPreheader();
1189 BasicBlock *LatchBlock =
1190 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1191 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1192 if (!TermBr || TermBr->isUnconditional() ||
1193 !isa<SetCondInst>(TermBr->getCondition()))
1194 return;
1195 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1196
1197 // Search IVUsesByStride to find Cond's IVUse if there is one.
1198 IVStrideUse *CondUse = 0;
Chris Lattner50fad702005-08-10 00:45:21 +00001199 const SCEVHandle *CondStride = 0;
Chris Lattner010de252005-08-08 05:28:22 +00001200
Chris Lattnerb4dd1b82005-10-11 18:17:57 +00001201 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1202 ++Stride) {
1203 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1204 IVUsesByStride.find(StrideOrder[Stride]);
1205 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1206
1207 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1208 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner010de252005-08-08 05:28:22 +00001209 if (UI->User == Cond) {
1210 CondUse = &*UI;
Chris Lattnerb4dd1b82005-10-11 18:17:57 +00001211 CondStride = &SI->first;
Chris Lattner010de252005-08-08 05:28:22 +00001212 // NOTE: we could handle setcc instructions with multiple uses here, but
1213 // InstCombine does it as well for simple uses, it's not clear that it
1214 // occurs enough in real life to handle.
1215 break;
1216 }
Chris Lattnerb4dd1b82005-10-11 18:17:57 +00001217 }
Chris Lattner010de252005-08-08 05:28:22 +00001218 if (!CondUse) return; // setcc doesn't use the IV.
1219
1220 // setcc stride is complex, don't mess with users.
Chris Lattner50fad702005-08-10 00:45:21 +00001221 // FIXME: Evaluate whether this is a good idea or not.
1222 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner010de252005-08-08 05:28:22 +00001223
1224 // It's possible for the setcc instruction to be anywhere in the loop, and
1225 // possible for it to have multiple users. If it is not immediately before
1226 // the latch block branch, move it.
1227 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1228 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1229 Cond->moveBefore(TermBr);
1230 } else {
1231 // Otherwise, clone the terminating condition and insert into the loopend.
1232 Cond = cast<SetCondInst>(Cond->clone());
1233 Cond->setName(L->getHeader()->getName() + ".termcond");
1234 LatchBlock->getInstList().insert(TermBr, Cond);
1235
1236 // Clone the IVUse, as the old use still exists!
Chris Lattner50fad702005-08-10 00:45:21 +00001237 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner010de252005-08-08 05:28:22 +00001238 CondUse->OperandValToReplace);
Chris Lattner50fad702005-08-10 00:45:21 +00001239 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner010de252005-08-08 05:28:22 +00001240 }
1241 }
1242
1243 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattner98d98112006-03-24 07:14:34 +00001244 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner010de252005-08-08 05:28:22 +00001245 // live ranges for the IV correctly.
Chris Lattner50fad702005-08-10 00:45:21 +00001246 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner010de252005-08-08 05:28:22 +00001247 CondUse->isUseOfPostIncrementedValue = true;
1248}
Nate Begeman16997482005-07-30 00:15:07 +00001249
Evan Cheng4496a502006-03-18 00:44:49 +00001250namespace {
1251 // Constant strides come first which in turns are sorted by their absolute
1252 // values. If absolute values are the same, then positive strides comes first.
1253 // e.g.
1254 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1255 struct StrideCompare {
1256 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1257 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1258 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1259 if (LHSC && RHSC) {
1260 int64_t LV = LHSC->getValue()->getSExtValue();
1261 int64_t RV = RHSC->getValue()->getSExtValue();
1262 uint64_t ALV = (LV < 0) ? -LV : LV;
1263 uint64_t ARV = (RV < 0) ? -RV : RV;
1264 if (ALV == ARV)
1265 return LV > RV;
1266 else
1267 return ALV < ARV;
Chris Lattner035c6a22006-03-22 17:27:24 +00001268 }
1269 return (LHSC && !RHSC);
Evan Cheng4496a502006-03-18 00:44:49 +00001270 }
1271 };
1272}
1273
Nate Begemaneaa13852004-10-18 21:08:22 +00001274void LoopStrengthReduce::runOnLoop(Loop *L) {
1275 // First step, transform all loops nesting inside of this loop.
1276 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1277 runOnLoop(*I);
1278
Nate Begeman16997482005-07-30 00:15:07 +00001279 // Next, find all uses of induction variables in this loop, and catagorize
1280 // them by stride. Start by finding all of the PHI nodes in the header for
1281 // this loop. If they are induction variables, inspect their uses.
Chris Lattner3416e5f2005-08-04 17:40:30 +00001282 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begeman16997482005-07-30 00:15:07 +00001283 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattner3416e5f2005-08-04 17:40:30 +00001284 AddUsersIfInteresting(I, L, Processed);
Nate Begemaneaa13852004-10-18 21:08:22 +00001285
Nate Begeman16997482005-07-30 00:15:07 +00001286 // If we have nothing to do, return.
Chris Lattner010de252005-08-08 05:28:22 +00001287 if (IVUsesByStride.empty()) return;
1288
1289 // Optimize induction variables. Some indvar uses can be transformed to use
1290 // strides that will be needed for other purposes. A common example of this
1291 // is the exit test for the loop, which can often be rewritten to use the
1292 // computation of some other indvar to decide when to terminate the loop.
1293 OptimizeIndvars(L);
1294
Misha Brukmanfd939082005-04-21 23:48:37 +00001295
Nate Begeman16997482005-07-30 00:15:07 +00001296 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1297 // doing computation in byte values, promote to 32-bit values if safe.
1298
1299 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1300 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1301 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1302 // to be careful that IV's are all the same type. Only works for intptr_t
1303 // indvars.
1304
1305 // If we only have one stride, we can more aggressively eliminate some things.
1306 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Chengd1d6b5c2006-03-16 21:53:05 +00001307
1308#ifndef NDEBUG
1309 DEBUG(std::cerr << "\nLSR on ");
1310 DEBUG(L->dump());
1311#endif
1312
1313 // IVsByStride keeps IVs for one particular loop.
1314 IVsByStride.clear();
1315
Evan Cheng4496a502006-03-18 00:44:49 +00001316 // Sort the StrideOrder so we process larger strides first.
1317 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1318
Chris Lattner1bbae0c2005-08-09 00:18:09 +00001319 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner7305ae22005-10-09 06:20:55 +00001320 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1321 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1322 // This extra layer of indirection makes the ordering of strides deterministic
1323 // - not dependent on map order.
1324 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1325 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1326 IVUsesByStride.find(StrideOrder[Stride]);
1327 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begeman16997482005-07-30 00:15:07 +00001328 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner7305ae22005-10-09 06:20:55 +00001329 }
Nate Begemaneaa13852004-10-18 21:08:22 +00001330
1331 // Clean up after ourselves
1332 if (!DeadInsts.empty()) {
1333 DeleteTriviallyDeadInstructions(DeadInsts);
1334
Nate Begeman16997482005-07-30 00:15:07 +00001335 BasicBlock::iterator I = L->getHeader()->begin();
1336 PHINode *PN;
Chris Lattnere9100c62005-08-02 02:44:31 +00001337 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner1060e092005-08-02 00:41:11 +00001338 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1339
Chris Lattner87265ab2005-08-09 23:39:36 +00001340 // At this point, we know that we have killed one or more GEP
1341 // instructions. It is worth checking to see if the cann indvar is also
1342 // dead, so that we can remove it as well. The requirements for the cann
1343 // indvar to be considered dead are:
Nate Begeman16997482005-07-30 00:15:07 +00001344 // 1. the cann indvar has one use
1345 // 2. the use is an add instruction
1346 // 3. the add has one use
1347 // 4. the add is used by the cann indvar
1348 // If all four cases above are true, then we can remove both the add and
1349 // the cann indvar.
1350 // FIXME: this needs to eliminate an induction variable even if it's being
1351 // compared against some value to decide loop termination.
1352 if (PN->hasOneUse()) {
1353 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner7e608bb2005-08-02 02:52:02 +00001354 if (BO && BO->hasOneUse()) {
1355 if (PN == *(BO->use_begin())) {
1356 DeadInsts.insert(BO);
1357 // Break the cycle, then delete the PHI.
1358 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner52d83e62005-08-03 21:36:09 +00001359 SE->deleteInstructionFromRecords(PN);
Chris Lattner7e608bb2005-08-02 02:52:02 +00001360 PN->eraseFromParent();
Nate Begemaneaa13852004-10-18 21:08:22 +00001361 }
Chris Lattner7e608bb2005-08-02 02:52:02 +00001362 }
Nate Begeman16997482005-07-30 00:15:07 +00001363 }
Nate Begemaneaa13852004-10-18 21:08:22 +00001364 }
Nate Begeman16997482005-07-30 00:15:07 +00001365 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemaneaa13852004-10-18 21:08:22 +00001366 }
Nate Begeman16997482005-07-30 00:15:07 +00001367
Chris Lattner9a59fbb2005-08-05 01:30:11 +00001368 CastedPointers.clear();
Nate Begeman16997482005-07-30 00:15:07 +00001369 IVUsesByStride.clear();
Chris Lattner7305ae22005-10-09 06:20:55 +00001370 StrideOrder.clear();
Nate Begeman16997482005-07-30 00:15:07 +00001371 return;
Nate Begemaneaa13852004-10-18 21:08:22 +00001372}