blob: 5c007551afb629e18b0f8d7fdba74eae0f4d6ad4 [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"
Dan Gohman2bcbd5b2007-05-04 14:59:09 +000022#include "llvm/IntrinsicInst.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000023#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000024#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000025#include "llvm/Analysis/Dominators.h"
26#include "llvm/Analysis/LoopInfo.h"
Devang Patelb0743b52007-03-06 21:14:09 +000027#include "llvm/Analysis/LoopPass.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000029#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner4fec86d2005-08-12 22:06:11 +000031#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000032#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000033#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000034#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000035#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000036#include "llvm/Support/Compiler.h"
Evan Chengc567c4e2006-03-13 23:14:23 +000037#include "llvm/Target/TargetLowering.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000038#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000039#include <set>
40using namespace llvm;
41
Chris Lattner79a42ac2006-12-19 21:40:18 +000042STATISTIC(NumReduced , "Number of GEPs strength reduced");
43STATISTIC(NumInserted, "Number of PHIs inserted");
44STATISTIC(NumVariable, "Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000045
Chris Lattner79a42ac2006-12-19 21:40:18 +000046namespace {
Dale Johannesene3a02be2007-03-20 00:47:50 +000047
Jeff Cohen1baf5c82007-03-20 20:43:18 +000048 struct BasedUser;
Dale Johannesene3a02be2007-03-20 00:47:50 +000049
Chris Lattner430d0022005-08-03 22:21:05 +000050 /// IVStrideUse - Keep track of one use of a strided induction variable, where
51 /// the stride is stored externally. The Offset member keeps track of the
52 /// offset from the IV, User is the actual user of the operand, and 'Operand'
53 /// is the operand # of the User that is the use.
Reid Spencer557ab152007-02-05 23:32:05 +000054 struct VISIBILITY_HIDDEN IVStrideUse {
Chris Lattner430d0022005-08-03 22:21:05 +000055 SCEVHandle Offset;
56 Instruction *User;
57 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000058
59 // isUseOfPostIncrementedValue - True if this should use the
60 // post-incremented version of this IV, not the preincremented version.
61 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000062 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000063 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000064
65 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000066 : Offset(Offs), User(U), OperandValToReplace(O),
67 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000068 };
69
70 /// IVUsersOfOneStride - This structure keeps track of all instructions that
71 /// have an operand that is based on the trip count multiplied by some stride.
72 /// The stride for all of these users is common and kept external to this
73 /// structure.
Reid Spencer557ab152007-02-05 23:32:05 +000074 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000075 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000076 /// initial value and the operand that uses the IV.
77 std::vector<IVStrideUse> Users;
78
79 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
80 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000081 }
82 };
83
Evan Cheng3df447d2006-03-16 21:53:05 +000084 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Chengc28282b2006-03-18 08:03:12 +000085 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
86 /// well as the PHI node and increment value created for rewrite.
Reid Spencer557ab152007-02-05 23:32:05 +000087 struct VISIBILITY_HIDDEN IVExpr {
Evan Chengc28282b2006-03-18 08:03:12 +000088 SCEVHandle Stride;
Evan Cheng3df447d2006-03-16 21:53:05 +000089 SCEVHandle Base;
90 PHINode *PHI;
91 Value *IncV;
92
Evan Chengc28282b2006-03-18 08:03:12 +000093 IVExpr()
Reid Spencerc635f472006-12-31 05:48:39 +000094 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)),
95 Base (SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)) {}
Evan Chengc28282b2006-03-18 08:03:12 +000096 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
97 Value *incv)
98 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
Evan Cheng3df447d2006-03-16 21:53:05 +000099 };
100
101 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
102 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
Reid Spencer557ab152007-02-05 23:32:05 +0000103 struct VISIBILITY_HIDDEN IVsOfOneStride {
Evan Cheng3df447d2006-03-16 21:53:05 +0000104 std::vector<IVExpr> IVs;
105
Evan Chengc28282b2006-03-18 08:03:12 +0000106 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
107 Value *IncV) {
108 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
Evan Cheng3df447d2006-03-16 21:53:05 +0000109 }
110 };
Nate Begemane68bcd12005-07-30 00:15:07 +0000111
Devang Patelb0743b52007-03-06 21:14:09 +0000112 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
Nate Begemanb18121e2004-10-18 21:08:22 +0000113 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +0000114 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +0000115 ScalarEvolution *SE;
116 const TargetData *TD;
117 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +0000118 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +0000119
Nate Begemane68bcd12005-07-30 00:15:07 +0000120 /// IVUsesByStride - Keep track of all uses of induction variables that we
121 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +0000122 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +0000123
Evan Cheng3df447d2006-03-16 21:53:05 +0000124 /// IVsByStride - Keep track of all IVs that have been inserted for a
125 /// particular stride.
126 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
127
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000128 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
129 /// We use this to iterate over the IVUsesByStride collection without being
130 /// dependent on random ordering of pointers in the process.
131 std::vector<SCEVHandle> StrideOrder;
132
Chris Lattner6f286b72005-08-04 01:19:13 +0000133 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
134 /// of the casted version of each value. This is accessed by
135 /// getCastedVersionOf.
136 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000137
138 /// DeadInsts - Keep track of instructions we may have made dead, so that
139 /// we can remove them after we are done working.
140 std::set<Instruction*> DeadInsts;
Evan Chengc567c4e2006-03-13 23:14:23 +0000141
142 /// TLI - Keep a pointer of a TargetLowering to consult for determining
143 /// transformation profitability.
144 const TargetLowering *TLI;
145
Nate Begemanb18121e2004-10-18 21:08:22 +0000146 public:
Devang Patel8c78a0b2007-05-03 01:11:54 +0000147 static char ID; // Pass ID, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +0000148 LoopStrengthReduce(const TargetLowering *tli = NULL) :
149 LoopPass((intptr_t)&ID), TLI(tli) {
Jeff Cohena2c59b72005-03-04 04:04:26 +0000150 }
151
Devang Patelb0743b52007-03-06 21:14:09 +0000152 bool runOnLoop(Loop *L, LPPassManager &LPM);
Nate Begemanb18121e2004-10-18 21:08:22 +0000153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000155 // We split critical edges, so we change the CFG. However, we do update
156 // many analyses if they are around.
157 AU.addPreservedID(LoopSimplifyID);
158 AU.addPreserved<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000159 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000160 AU.addPreserved<DominanceFrontier>();
161 AU.addPreserved<DominatorTree>();
162
Jeff Cohen39751c32005-02-27 19:37:07 +0000163 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000164 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000165 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000166 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000167 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000168 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000169
170 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
171 ///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000172 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
Chris Lattner6f286b72005-08-04 01:19:13 +0000173private:
Chris Lattnereaf24722005-08-04 17:40:30 +0000174 bool AddUsersIfInteresting(Instruction *I, Loop *L,
175 std::set<Instruction*> &Processed);
176 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
177
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000178 void OptimizeIndvars(Loop *L);
Chris Lattner81e07072007-04-03 05:11:24 +0000179 bool FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
180 const SCEVHandle *&CondStride);
Nate Begemane68bcd12005-07-30 00:15:07 +0000181
Dale Johannesene3a02be2007-03-20 00:47:50 +0000182 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*,
183 const std::vector<BasedUser>& UsersToProcess);
184
185 bool ValidStride(int64_t, const std::vector<BasedUser>& UsersToProcess);
Evan Cheng45206982006-03-17 19:52:23 +0000186
Chris Lattneredff91a2005-08-10 00:45:21 +0000187 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
188 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000189 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000190 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
191 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000192 char LoopStrengthReduce::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000193 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000194}
195
Devang Patelb0743b52007-03-06 21:14:09 +0000196LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Evan Cheng3df447d2006-03-16 21:53:05 +0000197 return new LoopStrengthReduce(TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000198}
199
Reid Spencerb341b082006-12-12 05:05:00 +0000200/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
201/// assumes that the Value* V is of integer or pointer type only.
Chris Lattner6f286b72005-08-04 01:19:13 +0000202///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000203Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
204 Value *V) {
Chris Lattner6f286b72005-08-04 01:19:13 +0000205 if (V->getType() == UIntPtrTy) return V;
206 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000207 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
Chris Lattner6f286b72005-08-04 01:19:13 +0000208
209 Value *&New = CastedPointers[V];
210 if (New) return New;
211
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000212 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000213 DeadInsts.insert(cast<Instruction>(New));
214 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000215}
216
217
Nate Begemanb18121e2004-10-18 21:08:22 +0000218/// DeleteTriviallyDeadInstructions - If any of the instructions is the
219/// specified set are trivially dead, delete them and see if this makes any of
220/// their operands subsequently dead.
221void LoopStrengthReduce::
222DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
223 while (!Insts.empty()) {
224 Instruction *I = *Insts.begin();
225 Insts.erase(Insts.begin());
226 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000227 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
228 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
229 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000230 SE->deleteInstructionFromRecords(I);
231 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000232 Changed = true;
233 }
234 }
235}
236
Jeff Cohen39751c32005-02-27 19:37:07 +0000237
Chris Lattnereaf24722005-08-04 17:40:30 +0000238/// GetExpressionSCEV - Compute and return the SCEV for the specified
239/// instruction.
240SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Dale Johannesene5866e72007-03-26 03:01:27 +0000241 // Pointer to pointer bitcast instructions return the same value as their
242 // operand.
243 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
244 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
245 return SE->getSCEV(BCI);
246 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)), L);
247 SE->setSCEV(BCI, R);
248 return R;
249 }
250
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000251 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
252 // If this is a GEP that SE doesn't know about, compute it now and insert it.
253 // If this is not a GEP, or if we have already done this computation, just let
254 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000255 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000256 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000257 return SE->getSCEV(Exp);
258
Nate Begemane68bcd12005-07-30 00:15:07 +0000259 // Analyze all of the subscripts of this getelementptr instruction, looking
260 // for uses that are determined by the trip count of L. First, skip all
261 // operands the are not dependent on the IV.
262
263 // Build up the base expression. Insert an LLVM cast of the pointer to
264 // uintptr_t first.
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000265 SCEVHandle GEPVal = SCEVUnknown::get(
266 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000267
268 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000269
270 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000271 // If this is a use of a recurrence that we can analyze, and it comes before
272 // Op does in the GEP operand list, we will handle this when we process this
273 // operand.
274 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
275 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000276 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000277 uint64_t Offset = SL->getElementOffset(Idx);
Chris Lattnereaf24722005-08-04 17:40:30 +0000278 GEPVal = SCEVAddExpr::get(GEPVal,
279 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000280 } else {
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000281 unsigned GEPOpiBits =
282 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
283 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
284 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
285 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
286 Instruction::BitCast));
287 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
Chris Lattneracc42c42005-08-04 19:08:16 +0000288 SCEVHandle Idx = SE->getSCEV(OpVal);
289
Chris Lattnereaf24722005-08-04 17:40:30 +0000290 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
291 if (TypeSize != 1)
292 Idx = SCEVMulExpr::get(Idx,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000293 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattnereaf24722005-08-04 17:40:30 +0000294 TypeSize)));
295 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000296 }
297 }
298
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000299 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000300 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000301}
302
Chris Lattneracc42c42005-08-04 19:08:16 +0000303/// getSCEVStartAndStride - Compute the start and stride of this expression,
304/// returning false if the expression is not a start/stride pair, or true if it
305/// is. The stride must be a loop invariant expression, but the start may be
306/// a mix of loop invariant and loop variant expressions.
307static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000308 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000309 SCEVHandle TheAddRec = Start; // Initialize to zero.
310
311 // If the outer level is an AddExpr, the operands are all start values except
312 // for a nested AddRecExpr.
313 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
314 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
315 if (SCEVAddRecExpr *AddRec =
316 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
317 if (AddRec->getLoop() == L)
318 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
319 else
320 return false; // Nested IV of some sort?
321 } else {
322 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
323 }
324
Reid Spencerde46e482006-11-02 20:25:50 +0000325 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000326 TheAddRec = SH;
327 } else {
328 return false; // not analyzable.
329 }
330
331 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
332 if (!AddRec || AddRec->getLoop() != L) return false;
333
334 // FIXME: Generalize to non-affine IV's.
335 if (!AddRec->isAffine()) return false;
336
337 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
338
Chris Lattneracc42c42005-08-04 19:08:16 +0000339 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000340 DOUT << "[" << L->getHeader()->getName()
341 << "] Variable stride: " << *AddRec << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000342
Chris Lattneredff91a2005-08-10 00:45:21 +0000343 Stride = AddRec->getOperand(1);
Chris Lattneracc42c42005-08-04 19:08:16 +0000344 return true;
345}
346
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000347/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
348/// and now we need to decide whether the user should use the preinc or post-inc
349/// value. If this user should use the post-inc version of the IV, return true.
350///
351/// Choosing wrong here can break dominance properties (if we choose to use the
352/// post-inc value when we cannot) or it can end up adding extra live-ranges to
353/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
354/// should use the post-inc value).
355static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000356 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000357 // If the user is in the loop, use the preinc value.
358 if (L->contains(User->getParent())) return false;
359
Chris Lattnerf07a5872005-10-03 02:50:05 +0000360 BasicBlock *LatchBlock = L->getLoopLatch();
361
362 // Ok, the user is outside of the loop. If it is dominated by the latch
363 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000364 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000365 return true;
366
367 // There is one case we have to be careful of: PHI nodes. These little guys
368 // can live in blocks that do not dominate the latch block, but (since their
369 // uses occur in the predecessor block, not the block the PHI lives in) should
370 // still use the post-inc value. Check for this case now.
371 PHINode *PN = dyn_cast<PHINode>(User);
372 if (!PN) return false; // not a phi, not dominated by latch block.
373
374 // Look at all of the uses of IV by the PHI node. If any use corresponds to
375 // a block that is not dominated by the latch block, give up and use the
376 // preincremented value.
377 unsigned NumUses = 0;
378 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
379 if (PN->getIncomingValue(i) == IV) {
380 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000381 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000382 return false;
383 }
384
385 // Okay, all uses of IV by PN are in predecessor blocks that really are
386 // dominated by the latch block. Split the critical edges and use the
387 // post-incremented value.
388 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
389 if (PN->getIncomingValue(i) == IV) {
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000390 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
391 true);
Chris Lattner5191c652006-10-28 00:59:20 +0000392 // Splitting the critical edge can reduce the number of entries in this
393 // PHI.
394 e = PN->getNumIncomingValues();
Chris Lattnerf07a5872005-10-03 02:50:05 +0000395 if (--NumUses == 0) break;
396 }
397
398 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000399}
400
401
402
Nate Begemane68bcd12005-07-30 00:15:07 +0000403/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
404/// reducible SCEV, recursively add its users to the IVUsesByStride set and
405/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000406bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
407 std::set<Instruction*> &Processed) {
Chris Lattner03c49532007-01-15 02:27:26 +0000408 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
Chris Lattner5df0e362005-10-21 05:45:41 +0000409 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000410 if (!Processed.insert(I).second)
411 return true; // Instruction already handled.
412
Chris Lattneracc42c42005-08-04 19:08:16 +0000413 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000414 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000415 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000416
Chris Lattneracc42c42005-08-04 19:08:16 +0000417 // Get the start and stride for this expression.
418 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000419 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000420 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
421 return false; // Non-reducible symbolic expression, bail out.
Devang Patel58818c52007-03-09 21:19:53 +0000422
Devang Patel38bc86f2007-04-23 22:42:03 +0000423 std::vector<Instruction *> IUsers;
424 // Collect all I uses now because IVUseShouldUsePostIncValue may
425 // invalidate use_iterator.
426 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
427 IUsers.push_back(cast<Instruction>(*UI));
Nate Begemane68bcd12005-07-30 00:15:07 +0000428
Devang Patel38bc86f2007-04-23 22:42:03 +0000429 for (unsigned iused_index = 0, iused_size = IUsers.size();
430 iused_index != iused_size; ++iused_index) {
431
432 Instruction *User = IUsers[iused_index];
Devang Patel58818c52007-03-09 21:19:53 +0000433
Nate Begemane68bcd12005-07-30 00:15:07 +0000434 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000435 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000436 continue;
437
438 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000439 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000440 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000441 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000442 DOUT << "FOUND USER in other loop: " << *User
443 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000444 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000445 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000446 DOUT << "FOUND USER: " << *User
447 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000448 AddUserToIVUsers = true;
449 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000450
Chris Lattneracc42c42005-08-04 19:08:16 +0000451 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000452 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
453 if (StrideUses.Users.empty()) // First occurance of this stride?
454 StrideOrder.push_back(Stride);
455
Chris Lattner65107492005-08-04 00:40:47 +0000456 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000457 // and decide what to do with it. If we are a use inside of the loop, use
458 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000459 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000460 // The value used will be incremented by the stride more than we are
461 // expecting, so subtract this off.
462 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000463 StrideUses.addUser(NewStart, User, I);
464 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000465 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000466 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000467 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000468 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000469 }
470 }
471 return true;
472}
473
474namespace {
475 /// BasedUser - For a particular base value, keep information about how we've
476 /// partitioned the expression so far.
477 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000478 /// Base - The Base value for the PHI node that needs to be inserted for
479 /// this use. As the use is processed, information gets moved from this
480 /// field to the Imm field (below). BasedUser values are sorted by this
481 /// field.
482 SCEVHandle Base;
483
Nate Begemane68bcd12005-07-30 00:15:07 +0000484 /// Inst - The instruction using the induction variable.
485 Instruction *Inst;
486
Chris Lattner430d0022005-08-03 22:21:05 +0000487 /// OperandValToReplace - The operand value of Inst to replace with the
488 /// EmittedBase.
489 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000490
491 /// Imm - The immediate value that should be added to the base immediately
492 /// before Inst, because it will be folded into the imm field of the
493 /// instruction.
494 SCEVHandle Imm;
495
496 /// EmittedBase - The actual value* to use for the base value of this
497 /// operation. This is null if we should just use zero so far.
498 Value *EmittedBase;
499
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000500 // isUseOfPostIncrementedValue - True if this should use the
501 // post-incremented version of this IV, not the preincremented version.
502 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000503 // instruction for a loop and uses outside the loop that are dominated by
504 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000505 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000506
507 BasedUser(IVStrideUse &IVSU)
508 : Base(IVSU.Offset), Inst(IVSU.User),
509 OperandValToReplace(IVSU.OperandValToReplace),
510 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
511 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000512
Chris Lattnera6d7c352005-08-04 20:03:32 +0000513 // Once we rewrite the code to insert the new IVs we want, update the
514 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
515 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000516 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000517 SCEVExpander &Rewriter, Loop *L,
518 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000519
520 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
521 SCEVExpander &Rewriter,
522 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000523 void dump() const;
524 };
525}
526
527void BasedUser::dump() const {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000528 cerr << " Base=" << *Base;
529 cerr << " Imm=" << *Imm;
Nate Begemane68bcd12005-07-30 00:15:07 +0000530 if (EmittedBase)
Bill Wendlingf3baad32006-12-07 01:30:32 +0000531 cerr << " EB=" << *EmittedBase;
Nate Begemane68bcd12005-07-30 00:15:07 +0000532
Bill Wendlingf3baad32006-12-07 01:30:32 +0000533 cerr << " Inst: " << *Inst;
Nate Begemane68bcd12005-07-30 00:15:07 +0000534}
535
Chris Lattner2959f002006-02-04 07:36:50 +0000536Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
537 SCEVExpander &Rewriter,
538 Instruction *IP, Loop *L) {
539 // Figure out where we *really* want to insert this code. In particular, if
540 // the user is inside of a loop that is nested inside of L, we really don't
541 // want to insert this expression before the user, we'd rather pull it out as
542 // many loops as possible.
543 LoopInfo &LI = Rewriter.getLoopInfo();
544 Instruction *BaseInsertPt = IP;
545
546 // Figure out the most-nested loop that IP is in.
547 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
548
549 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
550 // the preheader of the outer-most loop where NewBase is not loop invariant.
551 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
552 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
553 InsertLoop = InsertLoop->getParentLoop();
554 }
555
556 // If there is no immediate value, skip the next part.
557 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
Reid Spencer53a37392007-03-02 23:51:25 +0000558 if (SC->getValue()->isZero())
Chris Lattner2959f002006-02-04 07:36:50 +0000559 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
560 OperandValToReplace->getType());
561
562 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
Chris Lattner1b7b6e72007-06-06 01:23:55 +0000563
564 // If we are inserting the base and imm values in the same block, make sure to
565 // adjust the IP position if insertion reused a result.
566 if (IP == BaseInsertPt)
567 IP = Rewriter.getInsertionPoint();
Chris Lattner2959f002006-02-04 07:36:50 +0000568
569 // Always emit the immediate (if non-zero) into the same block as the user.
570 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
571 return Rewriter.expandCodeFor(NewValSCEV, IP,
572 OperandValToReplace->getType());
Chris Lattner1b7b6e72007-06-06 01:23:55 +0000573
Chris Lattner2959f002006-02-04 07:36:50 +0000574}
575
576
Chris Lattnera6d7c352005-08-04 20:03:32 +0000577// Once we rewrite the code to insert the new IVs we want, update the
578// operands of Inst to use the new expression 'NewBase', with 'Imm' added
579// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000580void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000581 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000582 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000583 if (!isa<PHINode>(Inst)) {
Chris Lattnerefd30512007-04-13 20:42:26 +0000584 // By default, insert code at the user instruction.
585 BasicBlock::iterator InsertPt = Inst;
586
587 // However, if the Operand is itself an instruction, the (potentially
588 // complex) inserted code may be shared by many users. Because of this, we
589 // want to emit code for the computation of the operand right before its old
590 // computation. This is usually safe, because we obviously used to use the
591 // computation when it was computed in its current block. However, in some
592 // cases (e.g. use of a post-incremented induction variable) the NewBase
593 // value will be pinned to live somewhere after the original computation.
594 // In this case, we have to back off.
595 if (!isUseOfPostIncrementedValue) {
596 if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) {
597 InsertPt = OpInst;
598 while (isa<PHINode>(InsertPt)) ++InsertPt;
599 }
600 }
Chris Lattnerefd30512007-04-13 20:42:26 +0000601 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000602 // Replace the use of the operand Value with the new Phi we just created.
603 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Chris Lattner1480e162007-05-11 22:40:34 +0000604 DOUT << " CHANGED: IMM =" << *Imm;
605 DOUT << " \tNEWBASE =" << *NewBase;
606 DOUT << " \tInst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000607 return;
608 }
609
610 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000611 // expression into each operand block that uses it. Note that PHI nodes can
612 // have multiple entries for the same predecessor. We use a map to make sure
613 // that a PHI node only has a single Value* for each predecessor (which also
614 // prevents us from inserting duplicate code in some blocks).
615 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000616 PHINode *PN = cast<PHINode>(Inst);
617 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
618 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000619 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000620 // code on all predecessor/successor paths. We do this unless this is the
621 // canonical backedge for this loop, as this can make some inserted code
622 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000623 BasicBlock *PHIPred = PN->getIncomingBlock(i);
624 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
625 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000626
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000627 // First step, split the critical edge.
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000628 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattner8447b492005-08-12 22:22:17 +0000629
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000630 // Next step: move the basic block. In particular, if the PHI node
631 // is outside of the loop, and PredTI is in the loop, we want to
632 // move the block to be immediately before the PHI block, not
633 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000634 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000635 BasicBlock *NewBB = PN->getIncomingBlock(i);
636 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000637 }
Chris Lattner5191c652006-10-28 00:59:20 +0000638
639 // Splitting the edge can reduce the number of PHI entries we have.
640 e = PN->getNumIncomingValues();
Chris Lattner4fec86d2005-08-12 22:06:11 +0000641 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000642
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000643 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
644 if (!Code) {
645 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000646 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
647 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000648 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000649
650 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000651 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000652 Rewriter.clear();
653 }
654 }
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000655 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000656}
657
658
Nate Begemane68bcd12005-07-30 00:15:07 +0000659/// isTargetConstant - Return true if the following can be referenced by the
660/// immediate field of a target instruction.
Evan Chengb5eb9322007-03-13 20:34:37 +0000661static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
662 const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000663 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Evan Cheng720acdf2007-03-12 23:27:37 +0000664 int64_t VC = SC->getValue()->getSExtValue();
Chris Lattner780c0092007-04-09 22:20:14 +0000665 if (TLI) {
666 TargetLowering::AddrMode AM;
667 AM.BaseOffs = VC;
668 return TLI->isLegalAddressingMode(AM, UseTy);
669 } else {
Evan Chengc567c4e2006-03-13 23:14:23 +0000670 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
Evan Cheng720acdf2007-03-12 23:27:37 +0000671 return (VC > -(1 << 16) && VC < (1 << 16)-1);
Chris Lattner780c0092007-04-09 22:20:14 +0000672 }
Chris Lattner14203e82005-08-08 06:25:50 +0000673 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000674
Nate Begemane68bcd12005-07-30 00:15:07 +0000675 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
676 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Chris Lattner780c0092007-04-09 22:20:14 +0000677 if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengc567c4e2006-03-13 23:14:23 +0000678 Constant *Op0 = CE->getOperand(0);
Chris Lattner780c0092007-04-09 22:20:14 +0000679 if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
680 TargetLowering::AddrMode AM;
681 AM.BaseGV = GV;
682 return TLI->isLegalAddressingMode(AM, UseTy);
683 }
Evan Chengc567c4e2006-03-13 23:14:23 +0000684 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000685 return false;
686}
687
Chris Lattner37ed8952005-08-08 22:32:34 +0000688/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
689/// loop varying to the Imm operand.
690static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
691 Loop *L) {
692 if (Val->isLoopInvariant(L)) return; // Nothing to do.
693
694 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
695 std::vector<SCEVHandle> NewOps;
696 NewOps.reserve(SAE->getNumOperands());
697
698 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
699 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
700 // If this is a loop-variant expression, it must stay in the immediate
701 // field of the expression.
702 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
703 } else {
704 NewOps.push_back(SAE->getOperand(i));
705 }
706
707 if (NewOps.empty())
708 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
709 else
710 Val = SCEVAddExpr::get(NewOps);
711 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
712 // Try to pull immediates out of the start value of nested addrec's.
713 SCEVHandle Start = SARE->getStart();
714 MoveLoopVariantsToImediateField(Start, Imm, L);
715
716 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
717 Ops[0] = Start;
718 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
719 } else {
720 // Otherwise, all of Val is variant, move the whole thing over.
721 Imm = SCEVAddExpr::get(Imm, Val);
722 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
723 }
724}
725
726
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000727/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000728/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000729/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000730static void MoveImmediateValues(const TargetLowering *TLI,
Evan Chengb5eb9322007-03-13 20:34:37 +0000731 Instruction *User,
Evan Chengc567c4e2006-03-13 23:14:23 +0000732 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000733 bool isAddress, Loop *L) {
Evan Chengb5eb9322007-03-13 20:34:37 +0000734 const Type *UseTy = User->getType();
735 if (StoreInst *SI = dyn_cast<StoreInst>(User))
736 UseTy = SI->getOperand(0)->getType();
737
Chris Lattnerfc624702005-08-03 23:44:42 +0000738 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000739 std::vector<SCEVHandle> NewOps;
740 NewOps.reserve(SAE->getNumOperands());
741
Chris Lattner2959f002006-02-04 07:36:50 +0000742 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
743 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengb5eb9322007-03-13 20:34:37 +0000744 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000745
746 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000747 // If this is a loop-variant expression, it must stay in the immediate
748 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000749 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000750 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000751 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000752 }
Chris Lattner2959f002006-02-04 07:36:50 +0000753 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000754
755 if (NewOps.empty())
756 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
757 else
758 Val = SCEVAddExpr::get(NewOps);
759 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000760 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
761 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000762 SCEVHandle Start = SARE->getStart();
Evan Chengb5eb9322007-03-13 20:34:37 +0000763 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000764
765 if (Start != SARE->getStart()) {
766 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
767 Ops[0] = Start;
768 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
769 }
770 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000771 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
772 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengb5eb9322007-03-13 20:34:37 +0000773 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000774 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
775
776 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
777 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengb5eb9322007-03-13 20:34:37 +0000778 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000779
780 // If we extracted something out of the subexpressions, see if we can
781 // simplify this!
782 if (NewOp != SME->getOperand(1)) {
783 // Scale SubImm up by "8". If the result is a target constant, we are
784 // good.
785 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengb5eb9322007-03-13 20:34:37 +0000786 if (isTargetConstant(SubImm, UseTy, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000787 // Accumulate the immediate.
788 Imm = SCEVAddExpr::get(Imm, SubImm);
789
790 // Update what is left of 'Val'.
791 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
792 return;
793 }
794 }
795 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000796 }
797
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000798 // Loop-variant expressions must stay in the immediate field of the
799 // expression.
Evan Chengb5eb9322007-03-13 20:34:37 +0000800 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000801 !Val->isLoopInvariant(L)) {
802 Imm = SCEVAddExpr::get(Imm, Val);
803 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
804 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000805 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000806
807 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000808}
809
Chris Lattner5949d492005-08-13 07:27:18 +0000810
Chris Lattner3ff62012006-08-03 06:34:50 +0000811/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
812/// added together. This is used to reassociate common addition subexprs
813/// together for maximal sharing when rewriting bases.
Chris Lattner5949d492005-08-13 07:27:18 +0000814static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
815 SCEVHandle Expr) {
816 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
817 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
818 SeparateSubExprs(SubExprs, AE->getOperand(j));
819 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
820 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
821 if (SARE->getOperand(0) == Zero) {
822 SubExprs.push_back(Expr);
823 } else {
824 // Compute the addrec with zero as its base.
825 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
826 Ops[0] = Zero; // Start with zero base.
827 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
828
829
830 SeparateSubExprs(SubExprs, SARE->getOperand(0));
831 }
832 } else if (!isa<SCEVConstant>(Expr) ||
Reid Spencer53a37392007-03-02 23:51:25 +0000833 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
Chris Lattner5949d492005-08-13 07:27:18 +0000834 // Do not add zero.
835 SubExprs.push_back(Expr);
836 }
837}
838
839
Chris Lattnera091ff12005-08-09 00:18:09 +0000840/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
841/// removing any common subexpressions from it. Anything truly common is
842/// removed, accumulated, and returned. This looks for things like (a+b+c) and
843/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
844static SCEVHandle
845RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
846 unsigned NumUses = Uses.size();
847
848 // Only one use? Use its base, regardless of what it is!
849 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
850 SCEVHandle Result = Zero;
851 if (NumUses == 1) {
852 std::swap(Result, Uses[0].Base);
853 return Result;
854 }
855
856 // To find common subexpressions, count how many of Uses use each expression.
857 // If any subexpressions are used Uses.size() times, they are common.
858 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
859
Chris Lattner192cd182005-10-11 18:41:04 +0000860 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
861 // order we see them.
862 std::vector<SCEVHandle> UniqueSubExprs;
863
Chris Lattner5949d492005-08-13 07:27:18 +0000864 std::vector<SCEVHandle> SubExprs;
865 for (unsigned i = 0; i != NumUses; ++i) {
866 // If the base is zero (which is common), return zero now, there are no
867 // CSEs we can find.
868 if (Uses[i].Base == Zero) return Zero;
869
870 // Split the expression into subexprs.
871 SeparateSubExprs(SubExprs, Uses[i].Base);
872 // Add one to SubExpressionUseCounts for each subexpr present.
873 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000874 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
875 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000876 SubExprs.clear();
877 }
878
Chris Lattner192cd182005-10-11 18:41:04 +0000879 // Now that we know how many times each is used, build Result. Iterate over
880 // UniqueSubexprs so that we have a stable ordering.
881 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
882 std::map<SCEVHandle, unsigned>::iterator I =
883 SubExpressionUseCounts.find(UniqueSubExprs[i]);
884 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000885 if (I->second == NumUses) { // Found CSE!
886 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000887 } else {
888 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000889 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000890 }
Chris Lattner192cd182005-10-11 18:41:04 +0000891 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000892
893 // If we found no CSE's, return now.
894 if (Result == Zero) return Result;
895
896 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000897 for (unsigned i = 0; i != NumUses; ++i) {
898 // Split the expression into subexprs.
899 SeparateSubExprs(SubExprs, Uses[i].Base);
900
901 // Remove any common subexpressions.
902 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
903 if (SubExpressionUseCounts.count(SubExprs[j])) {
904 SubExprs.erase(SubExprs.begin()+j);
905 --j; --e;
906 }
907
908 // Finally, the non-shared expressions together.
909 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000910 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000911 else
912 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000913 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000914 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000915
916 return Result;
917}
918
Evan Cheng3df447d2006-03-16 21:53:05 +0000919/// isZero - returns true if the scalar evolution expression is zero.
920///
921static bool isZero(SCEVHandle &V) {
922 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencer53a37392007-03-02 23:51:25 +0000923 return SC->getValue()->isZero();
Evan Cheng3df447d2006-03-16 21:53:05 +0000924 return false;
925}
926
Dale Johannesene3a02be2007-03-20 00:47:50 +0000927/// ValidStride - Check whether the given Scale is valid for all loads and
Chris Lattner780c0092007-04-09 22:20:14 +0000928/// stores in UsersToProcess.
Dale Johannesene3a02be2007-03-20 00:47:50 +0000929///
930bool LoopStrengthReduce::ValidStride(int64_t Scale,
931 const std::vector<BasedUser>& UsersToProcess) {
Dale Johannesenbacf4ac2007-03-20 21:54:54 +0000932 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
Chris Lattner28e0e4e2007-04-02 06:34:44 +0000933 // If this is a load or other access, pass the type of the access in.
934 const Type *AccessTy = Type::VoidTy;
935 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
936 AccessTy = SI->getOperand(0)->getType();
937 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
938 AccessTy = LI->getType();
939
Chris Lattner780c0092007-04-09 22:20:14 +0000940 TargetLowering::AddrMode AM;
941 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
942 AM.BaseOffs = SC->getValue()->getSExtValue();
943 AM.Scale = Scale;
944
945 // If load[imm+r*scale] is illegal, bail out.
946 if (!TLI->isLegalAddressingMode(AM, AccessTy))
Dale Johannesene3a02be2007-03-20 00:47:50 +0000947 return false;
Dale Johannesenbacf4ac2007-03-20 21:54:54 +0000948 }
Dale Johannesene3a02be2007-03-20 00:47:50 +0000949 return true;
950}
Chris Lattnera091ff12005-08-09 00:18:09 +0000951
Evan Cheng45206982006-03-17 19:52:23 +0000952/// CheckForIVReuse - Returns the multiple if the stride is the multiple
953/// of a previous stride and it is a legal value for the target addressing
954/// mode scale component. This allows the users of this stride to be rewritten
Evan Chengc28282b2006-03-18 08:03:12 +0000955/// as prev iv * factor. It returns 0 if no reuse is possible.
Dale Johannesene3a02be2007-03-20 00:47:50 +0000956unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
957 IVExpr &IV, const Type *Ty,
958 const std::vector<BasedUser>& UsersToProcess) {
Evan Chengc28282b2006-03-18 08:03:12 +0000959 if (!TLI) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000960
961 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Reid Spencerba547cb2007-03-02 23:37:53 +0000962 int64_t SInt = SC->getValue()->getSExtValue();
963 if (SInt == 1) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000964
Evan Cheng720acdf2007-03-12 23:27:37 +0000965 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
966 SE = IVsByStride.end(); SI != SE; ++SI) {
967 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Chris Lattnerf3197a72007-04-02 22:51:58 +0000968 if (SInt != -SSInt &&
969 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
Evan Cheng45206982006-03-17 19:52:23 +0000970 continue;
Evan Cheng720acdf2007-03-12 23:27:37 +0000971 int64_t Scale = SInt / SSInt;
Dale Johannesene3a02be2007-03-20 00:47:50 +0000972 // Check that this stride is valid for all the types used for loads and
973 // stores; if it can be used for some and not others, we might as well use
974 // the original stride everywhere, since we have to create the IV for it
975 // anyway.
976 if (ValidStride(Scale, UsersToProcess))
Evan Cheng720acdf2007-03-12 23:27:37 +0000977 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
978 IE = SI->second.IVs.end(); II != IE; ++II)
979 // FIXME: Only handle base == 0 for now.
980 // Only reuse previous IV if it would not require a type conversion.
981 if (isZero(II->Base) && II->Base->getType() == Ty) {
982 IV = *II;
983 return Scale;
984 }
Evan Cheng45206982006-03-17 19:52:23 +0000985 }
986 }
Evan Chengc28282b2006-03-18 08:03:12 +0000987 return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000988}
989
Chris Lattner3ff62012006-08-03 06:34:50 +0000990/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
991/// returns true if Val's isUseOfPostIncrementedValue is true.
992static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
993 return Val.isUseOfPostIncrementedValue;
994}
Evan Cheng45206982006-03-17 19:52:23 +0000995
Chris Lattnere8bd53c2007-05-19 01:22:21 +0000996/// isNonConstantNegative - REturn true if the specified scev is negated, but
997/// not a constant.
998static bool isNonConstantNegative(const SCEVHandle &Expr) {
999 SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1000 if (!Mul) return false;
1001
1002 // If there is a constant factor, it will be first.
1003 SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1004 if (!SC) return false;
1005
1006 // Return true if the value is negative, this matches things like (-42 * V).
1007 return SC->getValue()->getValue().isNegative();
1008}
1009
Nate Begemane68bcd12005-07-30 00:15:07 +00001010/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1011/// stride of IV. All of the users may have different starting values, and this
1012/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +00001013void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +00001014 IVUsersOfOneStride &Uses,
1015 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +00001016 bool isOnlyStride) {
1017 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +00001018 // this new vector, each 'BasedUser' contains 'Base' the base of the
1019 // strided accessas well as the old information from Uses. We progressively
1020 // move information from the Base field to the Imm field, until we eventually
1021 // have the full access expression to rewrite the use.
1022 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +00001023 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +00001024 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1025 UsersToProcess.push_back(Uses.Users[i]);
1026
1027 // Move any loop invariant operands from the offset field to the immediate
1028 // field of the use, so that we don't try to use something before it is
1029 // computed.
1030 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
1031 UsersToProcess.back().Imm, L);
1032 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +00001033 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001034 }
Evan Cheng45206982006-03-17 19:52:23 +00001035
Chris Lattnera091ff12005-08-09 00:18:09 +00001036 // We now have a whole bunch of uses of like-strided induction variables, but
1037 // they might all have different bases. We want to emit one PHI node for this
1038 // stride which we fold as many common expressions (between the IVs) into as
1039 // possible. Start by identifying the common expressions in the base values
1040 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1041 // "A+B"), emit it to the preheader, then remove the expression from the
1042 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +00001043 SCEVHandle CommonExprs =
1044 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +00001045
Chris Lattner37ed8952005-08-08 22:32:34 +00001046 // Next, figure out what we can represent in the immediate fields of
1047 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +00001048 // fields of the BasedUsers. We do this so that it increases the commonality
1049 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +00001050 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +00001051 // If the user is not in the current loop, this means it is using the exit
1052 // value of the IV. Do not put anything in the base, make sure it's all in
1053 // the immediate field to allow as much factoring as possible.
1054 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +00001055 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
1056 UsersToProcess[i].Base);
1057 UsersToProcess[i].Base =
1058 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +00001059 } else {
1060
1061 // Addressing modes can be folded into loads and stores. Be careful that
1062 // the store is through the expression, not of the expression though.
1063 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
Dan Gohman3fbb18d2007-05-03 23:20:33 +00001064 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst)) {
Chris Lattner5cf983e2005-08-16 00:38:11 +00001065 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1066 isAddress = true;
Dan Gohman2bcbd5b2007-05-04 14:59:09 +00001067 } else if (IntrinsicInst *II =
1068 dyn_cast<IntrinsicInst>(UsersToProcess[i].Inst)) {
Dan Gohman3fbb18d2007-05-03 23:20:33 +00001069 // Addressing modes can also be folded into prefetches.
Dan Gohman2bcbd5b2007-05-04 14:59:09 +00001070 if (II->getIntrinsicID() == Intrinsic::prefetch &&
1071 II->getOperand(1) == UsersToProcess[i].OperandValToReplace)
Dan Gohman3fbb18d2007-05-03 23:20:33 +00001072 isAddress = true;
1073 }
Chris Lattner5cf983e2005-08-16 00:38:11 +00001074
Evan Chengb5eb9322007-03-13 20:34:37 +00001075 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1076 UsersToProcess[i].Imm, isAddress, L);
Chris Lattner5cf983e2005-08-16 00:38:11 +00001077 }
Chris Lattner37ed8952005-08-08 22:32:34 +00001078 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001079
Dale Johannesenbacf4ac2007-03-20 21:54:54 +00001080 // Check if it is possible to reuse a IV with stride that is factor of this
1081 // stride. And the multiple is a number that can be encoded in the scale
1082 // field of the target addressing mode. And we will have a valid
1083 // instruction after this substition, including the immediate field, if any.
1084 PHINode *NewPHI = NULL;
1085 Value *IncV = NULL;
1086 IVExpr ReuseIV;
1087 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1088 CommonExprs->getType(),
1089 UsersToProcess);
1090 if (RewriteFactor != 0) {
1091 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1092 << " and BASE " << *ReuseIV.Base << " :\n";
1093 NewPHI = ReuseIV.PHI;
1094 IncV = ReuseIV.IncV;
1095 }
1096
Chris Lattner8fe3cbe2007-04-01 22:21:39 +00001097 const Type *ReplacedTy = CommonExprs->getType();
1098
Chris Lattnera091ff12005-08-09 00:18:09 +00001099 // Now that we know what we need to do, insert the PHI node itself.
1100 //
Chris Lattner8fe3cbe2007-04-01 22:21:39 +00001101 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
Chris Lattner1480e162007-05-11 22:40:34 +00001102 << *Stride << " and BASE " << *CommonExprs << ": ";
Evan Cheng3df447d2006-03-16 21:53:05 +00001103
Chris Lattnera091ff12005-08-09 00:18:09 +00001104 SCEVExpander Rewriter(*SE, *LI);
1105 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +00001106
Chris Lattnera091ff12005-08-09 00:18:09 +00001107 BasicBlock *Preheader = L->getLoopPreheader();
1108 Instruction *PreInsertPt = Preheader->getTerminator();
1109 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +00001110
Chris Lattner8048b852005-09-12 17:11:27 +00001111 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +00001112
Evan Cheng45206982006-03-17 19:52:23 +00001113
1114 // Emit the initial base value into the loop preheader.
1115 Value *CommonBaseV
1116 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1117 ReplacedTy);
1118
Evan Chengc28282b2006-03-18 08:03:12 +00001119 if (RewriteFactor == 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001120 // Create a new Phi for this base, and stick it in the loop header.
1121 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1122 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001123
Evan Cheng45206982006-03-17 19:52:23 +00001124 // Add common base to the new Phi node.
1125 NewPHI->addIncoming(CommonBaseV, Preheader);
1126
Chris Lattnere8bd53c2007-05-19 01:22:21 +00001127 // If the stride is negative, insert a sub instead of an add for the
1128 // increment.
1129 bool isNegative = isNonConstantNegative(Stride);
1130 SCEVHandle IncAmount = Stride;
1131 if (isNegative)
1132 IncAmount = SCEV::getNegativeSCEV(Stride);
1133
Evan Cheng3df447d2006-03-16 21:53:05 +00001134 // Insert the stride into the preheader.
Chris Lattnere8bd53c2007-05-19 01:22:21 +00001135 Value *StrideV = PreheaderRewriter.expandCodeFor(IncAmount, PreInsertPt,
Evan Cheng3df447d2006-03-16 21:53:05 +00001136 ReplacedTy);
1137 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001138
Evan Cheng3df447d2006-03-16 21:53:05 +00001139 // Emit the increment of the base value before the terminator of the loop
1140 // latch block, and add it to the Phi node.
Chris Lattnere8bd53c2007-05-19 01:22:21 +00001141 SCEVHandle IncExp = SCEVUnknown::get(StrideV);
1142 if (isNegative)
1143 IncExp = SCEV::getNegativeSCEV(IncExp);
1144 IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI), IncExp);
Chris Lattnera091ff12005-08-09 00:18:09 +00001145
Evan Cheng3df447d2006-03-16 21:53:05 +00001146 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1147 ReplacedTy);
1148 IncV->setName(NewPHI->getName()+".inc");
1149 NewPHI->addIncoming(IncV, LatchBlock);
1150
Evan Cheng45206982006-03-17 19:52:23 +00001151 // Remember this in case a later stride is multiple of this.
Evan Chengc28282b2006-03-18 08:03:12 +00001152 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Chris Lattner1480e162007-05-11 22:40:34 +00001153
1154 DOUT << " IV=%" << NewPHI->getNameStr() << " INC=%" << IncV->getNameStr();
Evan Cheng45206982006-03-17 19:52:23 +00001155 } else {
1156 Constant *C = dyn_cast<Constant>(CommonBaseV);
1157 if (!C ||
1158 (!C->isNullValue() &&
Evan Chengb5eb9322007-03-13 20:34:37 +00001159 !isTargetConstant(SCEVUnknown::get(CommonBaseV), ReplacedTy, TLI)))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001160 // We want the common base emitted into the preheader! This is just
1161 // using cast as a copy so BitCast (no-op cast) is appropriate
1162 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1163 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001164 }
Chris Lattner1480e162007-05-11 22:40:34 +00001165 DOUT << "\n";
Chris Lattnera091ff12005-08-09 00:18:09 +00001166
Chris Lattner3ff62012006-08-03 06:34:50 +00001167 // We want to emit code for users inside the loop first. To do this, we
1168 // rearrange BasedUser so that the entries at the end have
1169 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1170 // vector (so we handle them first).
1171 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1172 PartitionByIsUseOfPostIncrementedValue);
1173
1174 // Sort this by base, so that things with the same base are handled
1175 // together. By partitioning first and stable-sorting later, we are
1176 // guaranteed that within each base we will pop off users from within the
1177 // loop before users outside of the loop with a particular base.
1178 //
1179 // We would like to use stable_sort here, but we can't. The problem is that
1180 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1181 // we don't have anything to do a '<' comparison on. Because we think the
1182 // number of uses is small, do a horrible bubble sort which just relies on
1183 // ==.
1184 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1185 // Get a base value.
1186 SCEVHandle Base = UsersToProcess[i].Base;
1187
1188 // Compact everything with this base to be consequetive with this one.
1189 for (unsigned j = i+1; j != e; ++j) {
1190 if (UsersToProcess[j].Base == Base) {
1191 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1192 ++i;
1193 }
1194 }
1195 }
1196
1197 // Process all the users now. This outer loop handles all bases, the inner
1198 // loop handles all users of a particular base.
Nate Begemane68bcd12005-07-30 00:15:07 +00001199 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001200 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001201
Chris Lattnera091ff12005-08-09 00:18:09 +00001202 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001203 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1204 ReplacedTy);
Chris Lattner1480e162007-05-11 22:40:34 +00001205
1206 DOUT << " INSERTING code for BASE = " << *Base << ":";
1207 if (BaseV->hasName())
1208 DOUT << " Result value name = %" << BaseV->getNameStr();
1209 DOUT << "\n";
1210
Chris Lattnera091ff12005-08-09 00:18:09 +00001211 // If BaseV is a constant other than 0, make sure that it gets inserted into
1212 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001213 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1214 // in this case.
Chris Lattner3ff62012006-08-03 06:34:50 +00001215 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengb5eb9322007-03-13 20:34:37 +00001216 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001217 // We want this constant emitted into the preheader! This is just
1218 // using cast as a copy so BitCast (no-op cast) is appropriate
1219 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattnera091ff12005-08-09 00:18:09 +00001220 PreInsertPt);
1221 }
Chris Lattner3ff62012006-08-03 06:34:50 +00001222 }
1223
Nate Begemane68bcd12005-07-30 00:15:07 +00001224 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001225 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001226 do {
Chris Lattner3ff62012006-08-03 06:34:50 +00001227 // FIXME: Use emitted users to emit other users.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001228 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001229
Chris Lattnera091ff12005-08-09 00:18:09 +00001230 // If this instruction wants to use the post-incremented value, move it
1231 // after the post-inc and use its value instead of the PHI.
1232 Value *RewriteOp = NewPHI;
1233 if (User.isUseOfPostIncrementedValue) {
1234 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001235
1236 // If this user is in the loop, make sure it is the last thing in the
1237 // loop to ensure it is dominated by the increment.
1238 if (L->contains(User.Inst->getParent()))
1239 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001240 }
Reid Spencerdf1f19a2006-12-13 08:06:42 +00001241 if (RewriteOp->getType() != ReplacedTy) {
1242 Instruction::CastOps opcode = Instruction::Trunc;
1243 if (ReplacedTy->getPrimitiveSizeInBits() ==
1244 RewriteOp->getType()->getPrimitiveSizeInBits())
1245 opcode = Instruction::BitCast;
1246 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1247 }
Evan Cheng398f7022006-06-09 00:12:42 +00001248
Chris Lattnera091ff12005-08-09 00:18:09 +00001249 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1250
Chris Lattnerdb23c742005-08-03 22:51:21 +00001251 // Clear the SCEVExpander's expression map so that we are guaranteed
1252 // to have the code emitted where we expect it.
1253 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001254
1255 // If we are reusing the iv, then it must be multiplied by a constant
1256 // factor take advantage of addressing mode scale component.
Evan Chengc28282b2006-03-18 08:03:12 +00001257 if (RewriteFactor != 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001258 RewriteExpr =
1259 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001260 RewriteExpr->getType()),
1261 RewriteExpr);
1262
1263 // The common base is emitted in the loop preheader. But since we
1264 // are reusing an IV, it has not been used to initialize the PHI node.
1265 // Add it to the expression used to rewrite the uses.
1266 if (!isa<ConstantInt>(CommonBaseV) ||
Reid Spencer53a37392007-03-02 23:51:25 +00001267 !cast<ConstantInt>(CommonBaseV)->isZero())
Evan Cheng45206982006-03-17 19:52:23 +00001268 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1269 SCEVUnknown::get(CommonBaseV));
1270 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001271
Chris Lattnera6d7c352005-08-04 20:03:32 +00001272 // Now that we know what we need to do, insert code before User for the
1273 // immediate and any loop-variant expressions.
Reid Spencer53a37392007-03-02 23:51:25 +00001274 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
Chris Lattnera091ff12005-08-09 00:18:09 +00001275 // Add BaseV to the PHI value if needed.
1276 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001277
Chris Lattner8447b492005-08-12 22:22:17 +00001278 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001279
Chris Lattnerdb23c742005-08-03 22:51:21 +00001280 // Mark old value we replaced as possibly dead, so that it is elminated
1281 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001282 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001283
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001284 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001285 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001286
Chris Lattner3ff62012006-08-03 06:34:50 +00001287 // If there are any more users to process with the same base, process them
1288 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001289 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001290 // TODO: Next, find out which base index is the most common, pull it out.
1291 }
1292
1293 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1294 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001295}
1296
Chris Lattner81e07072007-04-03 05:11:24 +00001297/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1298/// set the IV user and stride information and return true, otherwise return
1299/// false.
1300bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1301 const SCEVHandle *&CondStride) {
1302 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1303 ++Stride) {
1304 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1305 IVUsesByStride.find(StrideOrder[Stride]);
1306 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1307
1308 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1309 E = SI->second.Users.end(); UI != E; ++UI)
1310 if (UI->User == Cond) {
1311 // NOTE: we could handle setcc instructions with multiple uses here, but
1312 // InstCombine does it as well for simple uses, it's not clear that it
1313 // occurs enough in real life to handle.
1314 CondUse = &*UI;
1315 CondStride = &SI->first;
1316 return true;
1317 }
1318 }
1319 return false;
1320}
1321
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001322// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1323// uses in the loop, look to see if we can eliminate some, in favor of using
1324// common indvars for the different uses.
1325void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1326 // TODO: implement optzns here.
1327
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001328 // Finally, get the terminating condition for the loop if possible. If we
1329 // can, we want to change it to use a post-incremented version of its
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001330 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001331 // one register value.
1332 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1333 BasicBlock *Preheader = L->getLoopPreheader();
1334 BasicBlock *LatchBlock =
1335 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1336 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001337 if (!TermBr || TermBr->isUnconditional() ||
1338 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001339 return;
Reid Spencer266e42b2006-12-23 06:05:41 +00001340 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001341
1342 // Search IVUsesByStride to find Cond's IVUse if there is one.
1343 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001344 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001345
Chris Lattner81e07072007-04-03 05:11:24 +00001346 if (!FindIVForUser(Cond, CondUse, CondStride))
1347 return; // setcc doesn't use the IV.
1348
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001349
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001350 // It's possible for the setcc instruction to be anywhere in the loop, and
1351 // possible for it to have multiple users. If it is not immediately before
1352 // the latch block branch, move it.
1353 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1354 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1355 Cond->moveBefore(TermBr);
1356 } else {
1357 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencer266e42b2006-12-23 06:05:41 +00001358 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001359 Cond->setName(L->getHeader()->getName() + ".termcond");
1360 LatchBlock->getInstList().insert(TermBr, Cond);
1361
1362 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001363 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001364 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001365 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001366 }
1367 }
1368
1369 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001370 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001371 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001372 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001373 CondUse->isUseOfPostIncrementedValue = true;
1374}
Nate Begemane68bcd12005-07-30 00:15:07 +00001375
Evan Chengf09f0eb2006-03-18 00:44:49 +00001376namespace {
1377 // Constant strides come first which in turns are sorted by their absolute
1378 // values. If absolute values are the same, then positive strides comes first.
1379 // e.g.
1380 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1381 struct StrideCompare {
1382 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1383 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1384 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1385 if (LHSC && RHSC) {
Reid Spencer197adfa2007-03-02 00:31:39 +00001386 int64_t LV = LHSC->getValue()->getSExtValue();
1387 int64_t RV = RHSC->getValue()->getSExtValue();
1388 uint64_t ALV = (LV < 0) ? -LV : LV;
1389 uint64_t ARV = (RV < 0) ? -RV : RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001390 if (ALV == ARV)
Reid Spencer197adfa2007-03-02 00:31:39 +00001391 return LV > RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001392 else
Reid Spencer197adfa2007-03-02 00:31:39 +00001393 return ALV < ARV;
Chris Lattner7d80b4f2006-03-22 17:27:24 +00001394 }
1395 return (LHSC && !RHSC);
Evan Chengf09f0eb2006-03-18 00:44:49 +00001396 }
1397 };
1398}
1399
Devang Patelb0743b52007-03-06 21:14:09 +00001400bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
Nate Begemanb18121e2004-10-18 21:08:22 +00001401
Devang Patelb0743b52007-03-06 21:14:09 +00001402 LI = &getAnalysis<LoopInfo>();
1403 EF = &getAnalysis<ETForest>();
1404 SE = &getAnalysis<ScalarEvolution>();
1405 TD = &getAnalysis<TargetData>();
1406 UIntPtrTy = TD->getIntPtrType();
1407
1408 // Find all uses of induction variables in this loop, and catagorize
Nate Begemane68bcd12005-07-30 00:15:07 +00001409 // them by stride. Start by finding all of the PHI nodes in the header for
1410 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001411 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001412 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001413 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001414
Nate Begemane68bcd12005-07-30 00:15:07 +00001415 // If we have nothing to do, return.
Devang Patelb0743b52007-03-06 21:14:09 +00001416 if (IVUsesByStride.empty()) return false;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001417
1418 // Optimize induction variables. Some indvar uses can be transformed to use
1419 // strides that will be needed for other purposes. A common example of this
1420 // is the exit test for the loop, which can often be rewritten to use the
1421 // computation of some other indvar to decide when to terminate the loop.
1422 OptimizeIndvars(L);
1423
Misha Brukmanb1c93172005-04-21 23:48:37 +00001424
Nate Begemane68bcd12005-07-30 00:15:07 +00001425 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1426 // doing computation in byte values, promote to 32-bit values if safe.
1427
1428 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1429 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1430 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1431 // to be careful that IV's are all the same type. Only works for intptr_t
1432 // indvars.
1433
1434 // If we only have one stride, we can more aggressively eliminate some things.
1435 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001436
1437#ifndef NDEBUG
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001438 DOUT << "\nLSR on ";
Evan Cheng3df447d2006-03-16 21:53:05 +00001439 DEBUG(L->dump());
1440#endif
1441
1442 // IVsByStride keeps IVs for one particular loop.
1443 IVsByStride.clear();
1444
Evan Chengf09f0eb2006-03-18 00:44:49 +00001445 // Sort the StrideOrder so we process larger strides first.
1446 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1447
Chris Lattnera091ff12005-08-09 00:18:09 +00001448 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001449 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1450 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1451 // This extra layer of indirection makes the ordering of strides deterministic
1452 // - not dependent on map order.
1453 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1454 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1455 IVUsesByStride.find(StrideOrder[Stride]);
1456 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001457 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001458 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001459
1460 // Clean up after ourselves
1461 if (!DeadInsts.empty()) {
1462 DeleteTriviallyDeadInstructions(DeadInsts);
1463
Nate Begemane68bcd12005-07-30 00:15:07 +00001464 BasicBlock::iterator I = L->getHeader()->begin();
1465 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001466 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001467 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1468
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001469 // At this point, we know that we have killed one or more GEP
1470 // instructions. It is worth checking to see if the cann indvar is also
1471 // dead, so that we can remove it as well. The requirements for the cann
1472 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001473 // 1. the cann indvar has one use
1474 // 2. the use is an add instruction
1475 // 3. the add has one use
1476 // 4. the add is used by the cann indvar
1477 // If all four cases above are true, then we can remove both the add and
1478 // the cann indvar.
1479 // FIXME: this needs to eliminate an induction variable even if it's being
1480 // compared against some value to decide loop termination.
1481 if (PN->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001482 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1483 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1484 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
Chris Lattner75a44e12005-08-02 02:52:02 +00001485 DeadInsts.insert(BO);
1486 // Break the cycle, then delete the PHI.
1487 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001488 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001489 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001490 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001491 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001492 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001493 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001494 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001495 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001496
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001497 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001498 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001499 StrideOrder.clear();
Devang Patelb0743b52007-03-06 21:14:09 +00001500 return false;
Nate Begemanb18121e2004-10-18 21:08:22 +00001501}