blob: fcbf9e301cfee558d32bb7a67afafd4d23f3fc01 [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Devang Patelb0743b52007-03-06 21:14:09 +000026#include "llvm/Analysis/LoopPass.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000027#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000028#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000029#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner4fec86d2005-08-12 22:06:11 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000031#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000032#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000033#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000034#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000035#include "llvm/Support/Compiler.h"
Evan Chengc567c4e2006-03-13 23:14:23 +000036#include "llvm/Target/TargetLowering.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000037#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000038#include <set>
39using namespace llvm;
40
Chris Lattner79a42ac2006-12-19 21:40:18 +000041STATISTIC(NumReduced , "Number of GEPs strength reduced");
42STATISTIC(NumInserted, "Number of PHIs inserted");
43STATISTIC(NumVariable, "Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000044
Chris Lattner79a42ac2006-12-19 21:40:18 +000045namespace {
Chris Lattner430d0022005-08-03 22:21:05 +000046 /// IVStrideUse - Keep track of one use of a strided induction variable, where
47 /// the stride is stored externally. The Offset member keeps track of the
48 /// offset from the IV, User is the actual user of the operand, and 'Operand'
49 /// is the operand # of the User that is the use.
Reid Spencer557ab152007-02-05 23:32:05 +000050 struct VISIBILITY_HIDDEN IVStrideUse {
Chris Lattner430d0022005-08-03 22:21:05 +000051 SCEVHandle Offset;
52 Instruction *User;
53 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000054
55 // isUseOfPostIncrementedValue - True if this should use the
56 // post-incremented version of this IV, not the preincremented version.
57 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000058 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000059 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000060
61 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000062 : Offset(Offs), User(U), OperandValToReplace(O),
63 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000064 };
65
66 /// IVUsersOfOneStride - This structure keeps track of all instructions that
67 /// have an operand that is based on the trip count multiplied by some stride.
68 /// The stride for all of these users is common and kept external to this
69 /// structure.
Reid Spencer557ab152007-02-05 23:32:05 +000070 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000071 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000072 /// initial value and the operand that uses the IV.
73 std::vector<IVStrideUse> Users;
74
75 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
76 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000077 }
78 };
79
Evan Cheng3df447d2006-03-16 21:53:05 +000080 /// IVInfo - This structure keeps track of one IV expression inserted during
Evan Chengc28282b2006-03-18 08:03:12 +000081 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
82 /// well as the PHI node and increment value created for rewrite.
Reid Spencer557ab152007-02-05 23:32:05 +000083 struct VISIBILITY_HIDDEN IVExpr {
Evan Chengc28282b2006-03-18 08:03:12 +000084 SCEVHandle Stride;
Evan Cheng3df447d2006-03-16 21:53:05 +000085 SCEVHandle Base;
86 PHINode *PHI;
87 Value *IncV;
88
Evan Chengc28282b2006-03-18 08:03:12 +000089 IVExpr()
Reid Spencerc635f472006-12-31 05:48:39 +000090 : Stride(SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)),
91 Base (SCEVUnknown::getIntegerSCEV(0, Type::Int32Ty)) {}
Evan Chengc28282b2006-03-18 08:03:12 +000092 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
93 Value *incv)
94 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
Evan Cheng3df447d2006-03-16 21:53:05 +000095 };
96
97 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
98 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
Reid Spencer557ab152007-02-05 23:32:05 +000099 struct VISIBILITY_HIDDEN IVsOfOneStride {
Evan Cheng3df447d2006-03-16 21:53:05 +0000100 std::vector<IVExpr> IVs;
101
Evan Chengc28282b2006-03-18 08:03:12 +0000102 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
103 Value *IncV) {
104 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
Evan Cheng3df447d2006-03-16 21:53:05 +0000105 }
106 };
Nate Begemane68bcd12005-07-30 00:15:07 +0000107
Devang Patelb0743b52007-03-06 21:14:09 +0000108 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
Nate Begemanb18121e2004-10-18 21:08:22 +0000109 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +0000110 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +0000111 ScalarEvolution *SE;
112 const TargetData *TD;
113 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +0000114 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +0000115
Nate Begemane68bcd12005-07-30 00:15:07 +0000116 /// IVUsesByStride - Keep track of all uses of induction variables that we
117 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +0000118 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +0000119
Evan Cheng3df447d2006-03-16 21:53:05 +0000120 /// IVsByStride - Keep track of all IVs that have been inserted for a
121 /// particular stride.
122 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
123
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000124 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
125 /// We use this to iterate over the IVUsesByStride collection without being
126 /// dependent on random ordering of pointers in the process.
127 std::vector<SCEVHandle> StrideOrder;
128
Chris Lattner6f286b72005-08-04 01:19:13 +0000129 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
130 /// of the casted version of each value. This is accessed by
131 /// getCastedVersionOf.
132 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000133
134 /// DeadInsts - Keep track of instructions we may have made dead, so that
135 /// we can remove them after we are done working.
136 std::set<Instruction*> DeadInsts;
Evan Chengc567c4e2006-03-13 23:14:23 +0000137
138 /// TLI - Keep a pointer of a TargetLowering to consult for determining
139 /// transformation profitability.
140 const TargetLowering *TLI;
141
Nate Begemanb18121e2004-10-18 21:08:22 +0000142 public:
Evan Cheng3df447d2006-03-16 21:53:05 +0000143 LoopStrengthReduce(const TargetLowering *tli = NULL)
144 : TLI(tli) {
Jeff Cohena2c59b72005-03-04 04:04:26 +0000145 }
146
Devang Patelb0743b52007-03-06 21:14:09 +0000147 bool runOnLoop(Loop *L, LPPassManager &LPM);
Nate Begemanb18121e2004-10-18 21:08:22 +0000148
149 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000150 // We split critical edges, so we change the CFG. However, we do update
151 // many analyses if they are around.
152 AU.addPreservedID(LoopSimplifyID);
153 AU.addPreserved<LoopInfo>();
154 AU.addPreserved<DominatorSet>();
Chris Lattnercb367102006-01-11 05:10:20 +0000155 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000156 AU.addPreserved<ImmediateDominators>();
157 AU.addPreserved<DominanceFrontier>();
158 AU.addPreserved<DominatorTree>();
159
Jeff Cohen39751c32005-02-27 19:37:07 +0000160 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000161 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000162 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000163 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000164 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000165 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000166
167 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
168 ///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000169 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
Chris Lattner6f286b72005-08-04 01:19:13 +0000170private:
Chris Lattnereaf24722005-08-04 17:40:30 +0000171 bool AddUsersIfInteresting(Instruction *I, Loop *L,
172 std::set<Instruction*> &Processed);
173 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
174
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000175 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000176
Evan Chenge9c68f52006-07-18 19:07:58 +0000177 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*);
Evan Cheng45206982006-03-17 19:52:23 +0000178
Chris Lattneredff91a2005-08-10 00:45:21 +0000179 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
180 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000181 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000182 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
183 };
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000184 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000185}
186
Devang Patelb0743b52007-03-06 21:14:09 +0000187LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
Evan Cheng3df447d2006-03-16 21:53:05 +0000188 return new LoopStrengthReduce(TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000189}
190
Reid Spencerb341b082006-12-12 05:05:00 +0000191/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
192/// assumes that the Value* V is of integer or pointer type only.
Chris Lattner6f286b72005-08-04 01:19:13 +0000193///
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000194Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
195 Value *V) {
Chris Lattner6f286b72005-08-04 01:19:13 +0000196 if (V->getType() == UIntPtrTy) return V;
197 if (Constant *CB = dyn_cast<Constant>(V))
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000198 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
Chris Lattner6f286b72005-08-04 01:19:13 +0000199
200 Value *&New = CastedPointers[V];
201 if (New) return New;
202
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000203 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000204 DeadInsts.insert(cast<Instruction>(New));
205 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000206}
207
208
Nate Begemanb18121e2004-10-18 21:08:22 +0000209/// DeleteTriviallyDeadInstructions - If any of the instructions is the
210/// specified set are trivially dead, delete them and see if this makes any of
211/// their operands subsequently dead.
212void LoopStrengthReduce::
213DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
214 while (!Insts.empty()) {
215 Instruction *I = *Insts.begin();
216 Insts.erase(Insts.begin());
217 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000218 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
219 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
220 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000221 SE->deleteInstructionFromRecords(I);
222 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000223 Changed = true;
224 }
225 }
226}
227
Jeff Cohen39751c32005-02-27 19:37:07 +0000228
Chris Lattnereaf24722005-08-04 17:40:30 +0000229/// GetExpressionSCEV - Compute and return the SCEV for the specified
230/// instruction.
231SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000232 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
233 // If this is a GEP that SE doesn't know about, compute it now and insert it.
234 // If this is not a GEP, or if we have already done this computation, just let
235 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000236 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000237 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000238 return SE->getSCEV(Exp);
239
Nate Begemane68bcd12005-07-30 00:15:07 +0000240 // Analyze all of the subscripts of this getelementptr instruction, looking
241 // for uses that are determined by the trip count of L. First, skip all
242 // operands the are not dependent on the IV.
243
244 // Build up the base expression. Insert an LLVM cast of the pointer to
245 // uintptr_t first.
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000246 SCEVHandle GEPVal = SCEVUnknown::get(
247 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000248
249 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000250
251 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000252 // If this is a use of a recurrence that we can analyze, and it comes before
253 // Op does in the GEP operand list, we will handle this when we process this
254 // operand.
255 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
256 const StructLayout *SL = TD->getStructLayout(STy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000257 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000258 uint64_t Offset = SL->getElementOffset(Idx);
Chris Lattnereaf24722005-08-04 17:40:30 +0000259 GEPVal = SCEVAddExpr::get(GEPVal,
260 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000261 } else {
Reid Spencerdf1f19a2006-12-13 08:06:42 +0000262 unsigned GEPOpiBits =
263 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
264 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
265 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
266 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
267 Instruction::BitCast));
268 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
Chris Lattneracc42c42005-08-04 19:08:16 +0000269 SCEVHandle Idx = SE->getSCEV(OpVal);
270
Chris Lattnereaf24722005-08-04 17:40:30 +0000271 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
272 if (TypeSize != 1)
273 Idx = SCEVMulExpr::get(Idx,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000274 SCEVConstant::get(ConstantInt::get(UIntPtrTy,
Chris Lattnereaf24722005-08-04 17:40:30 +0000275 TypeSize)));
276 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000277 }
278 }
279
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000280 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000281 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000282}
283
Chris Lattneracc42c42005-08-04 19:08:16 +0000284/// getSCEVStartAndStride - Compute the start and stride of this expression,
285/// returning false if the expression is not a start/stride pair, or true if it
286/// is. The stride must be a loop invariant expression, but the start may be
287/// a mix of loop invariant and loop variant expressions.
288static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000289 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000290 SCEVHandle TheAddRec = Start; // Initialize to zero.
291
292 // If the outer level is an AddExpr, the operands are all start values except
293 // for a nested AddRecExpr.
294 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
295 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
296 if (SCEVAddRecExpr *AddRec =
297 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
298 if (AddRec->getLoop() == L)
299 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
300 else
301 return false; // Nested IV of some sort?
302 } else {
303 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
304 }
305
Reid Spencerde46e482006-11-02 20:25:50 +0000306 } else if (isa<SCEVAddRecExpr>(SH)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000307 TheAddRec = SH;
308 } else {
309 return false; // not analyzable.
310 }
311
312 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
313 if (!AddRec || AddRec->getLoop() != L) return false;
314
315 // FIXME: Generalize to non-affine IV's.
316 if (!AddRec->isAffine()) return false;
317
318 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
319
Chris Lattneracc42c42005-08-04 19:08:16 +0000320 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000321 DOUT << "[" << L->getHeader()->getName()
322 << "] Variable stride: " << *AddRec << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000323
Chris Lattneredff91a2005-08-10 00:45:21 +0000324 Stride = AddRec->getOperand(1);
Chris Lattneracc42c42005-08-04 19:08:16 +0000325 return true;
326}
327
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000328/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
329/// and now we need to decide whether the user should use the preinc or post-inc
330/// value. If this user should use the post-inc version of the IV, return true.
331///
332/// Choosing wrong here can break dominance properties (if we choose to use the
333/// post-inc value when we cannot) or it can end up adding extra live-ranges to
334/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
335/// should use the post-inc value).
336static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000337 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000338 // If the user is in the loop, use the preinc value.
339 if (L->contains(User->getParent())) return false;
340
Chris Lattnerf07a5872005-10-03 02:50:05 +0000341 BasicBlock *LatchBlock = L->getLoopLatch();
342
343 // Ok, the user is outside of the loop. If it is dominated by the latch
344 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000345 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000346 return true;
347
348 // There is one case we have to be careful of: PHI nodes. These little guys
349 // can live in blocks that do not dominate the latch block, but (since their
350 // uses occur in the predecessor block, not the block the PHI lives in) should
351 // still use the post-inc value. Check for this case now.
352 PHINode *PN = dyn_cast<PHINode>(User);
353 if (!PN) return false; // not a phi, not dominated by latch block.
354
355 // Look at all of the uses of IV by the PHI node. If any use corresponds to
356 // a block that is not dominated by the latch block, give up and use the
357 // preincremented value.
358 unsigned NumUses = 0;
359 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
360 if (PN->getIncomingValue(i) == IV) {
361 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000362 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000363 return false;
364 }
365
366 // Okay, all uses of IV by PN are in predecessor blocks that really are
367 // dominated by the latch block. Split the critical edges and use the
368 // post-incremented value.
369 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
370 if (PN->getIncomingValue(i) == IV) {
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000371 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
372 true);
Chris Lattner5191c652006-10-28 00:59:20 +0000373 // Splitting the critical edge can reduce the number of entries in this
374 // PHI.
375 e = PN->getNumIncomingValues();
Chris Lattnerf07a5872005-10-03 02:50:05 +0000376 if (--NumUses == 0) break;
377 }
378
379 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000380}
381
382
383
Nate Begemane68bcd12005-07-30 00:15:07 +0000384/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
385/// reducible SCEV, recursively add its users to the IVUsesByStride set and
386/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000387bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
388 std::set<Instruction*> &Processed) {
Chris Lattner03c49532007-01-15 02:27:26 +0000389 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
Chris Lattner5df0e362005-10-21 05:45:41 +0000390 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000391 if (!Processed.insert(I).second)
392 return true; // Instruction already handled.
393
Chris Lattneracc42c42005-08-04 19:08:16 +0000394 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000395 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000396 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000397
Chris Lattneracc42c42005-08-04 19:08:16 +0000398 // Get the start and stride for this expression.
399 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000400 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000401 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
402 return false; // Non-reducible symbolic expression, bail out.
403
Nate Begemane68bcd12005-07-30 00:15:07 +0000404 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
405 Instruction *User = cast<Instruction>(*UI);
406
407 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000408 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000409 continue;
410
411 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000412 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000413 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000414 if (LI->getLoopFor(User->getParent()) != L) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000415 DOUT << "FOUND USER in other loop: " << *User
416 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000417 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000418 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000419 DOUT << "FOUND USER: " << *User
420 << " OF SCEV: " << *ISE << "\n";
Chris Lattneracc42c42005-08-04 19:08:16 +0000421 AddUserToIVUsers = true;
422 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000423
Chris Lattneracc42c42005-08-04 19:08:16 +0000424 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000425 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
426 if (StrideUses.Users.empty()) // First occurance of this stride?
427 StrideOrder.push_back(Stride);
428
Chris Lattner65107492005-08-04 00:40:47 +0000429 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000430 // and decide what to do with it. If we are a use inside of the loop, use
431 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000432 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000433 // The value used will be incremented by the stride more than we are
434 // expecting, so subtract this off.
435 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000436 StrideUses.addUser(NewStart, User, I);
437 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000438 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000439 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000440 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000441 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000442 }
443 }
444 return true;
445}
446
447namespace {
448 /// BasedUser - For a particular base value, keep information about how we've
449 /// partitioned the expression so far.
450 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000451 /// Base - The Base value for the PHI node that needs to be inserted for
452 /// this use. As the use is processed, information gets moved from this
453 /// field to the Imm field (below). BasedUser values are sorted by this
454 /// field.
455 SCEVHandle Base;
456
Nate Begemane68bcd12005-07-30 00:15:07 +0000457 /// Inst - The instruction using the induction variable.
458 Instruction *Inst;
459
Chris Lattner430d0022005-08-03 22:21:05 +0000460 /// OperandValToReplace - The operand value of Inst to replace with the
461 /// EmittedBase.
462 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000463
464 /// Imm - The immediate value that should be added to the base immediately
465 /// before Inst, because it will be folded into the imm field of the
466 /// instruction.
467 SCEVHandle Imm;
468
469 /// EmittedBase - The actual value* to use for the base value of this
470 /// operation. This is null if we should just use zero so far.
471 Value *EmittedBase;
472
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000473 // isUseOfPostIncrementedValue - True if this should use the
474 // post-incremented version of this IV, not the preincremented version.
475 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000476 // instruction for a loop and uses outside the loop that are dominated by
477 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000478 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000479
480 BasedUser(IVStrideUse &IVSU)
481 : Base(IVSU.Offset), Inst(IVSU.User),
482 OperandValToReplace(IVSU.OperandValToReplace),
483 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
484 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000485
Chris Lattnera6d7c352005-08-04 20:03:32 +0000486 // Once we rewrite the code to insert the new IVs we want, update the
487 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
488 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000489 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000490 SCEVExpander &Rewriter, Loop *L,
491 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000492
493 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
494 SCEVExpander &Rewriter,
495 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000496 void dump() const;
497 };
498}
499
500void BasedUser::dump() const {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000501 cerr << " Base=" << *Base;
502 cerr << " Imm=" << *Imm;
Nate Begemane68bcd12005-07-30 00:15:07 +0000503 if (EmittedBase)
Bill Wendlingf3baad32006-12-07 01:30:32 +0000504 cerr << " EB=" << *EmittedBase;
Nate Begemane68bcd12005-07-30 00:15:07 +0000505
Bill Wendlingf3baad32006-12-07 01:30:32 +0000506 cerr << " Inst: " << *Inst;
Nate Begemane68bcd12005-07-30 00:15:07 +0000507}
508
Chris Lattner2959f002006-02-04 07:36:50 +0000509Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
510 SCEVExpander &Rewriter,
511 Instruction *IP, Loop *L) {
512 // Figure out where we *really* want to insert this code. In particular, if
513 // the user is inside of a loop that is nested inside of L, we really don't
514 // want to insert this expression before the user, we'd rather pull it out as
515 // many loops as possible.
516 LoopInfo &LI = Rewriter.getLoopInfo();
517 Instruction *BaseInsertPt = IP;
518
519 // Figure out the most-nested loop that IP is in.
520 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
521
522 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
523 // the preheader of the outer-most loop where NewBase is not loop invariant.
524 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
525 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
526 InsertLoop = InsertLoop->getParentLoop();
527 }
528
529 // If there is no immediate value, skip the next part.
530 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
Reid Spencer53a37392007-03-02 23:51:25 +0000531 if (SC->getValue()->isZero())
Chris Lattner2959f002006-02-04 07:36:50 +0000532 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
533 OperandValToReplace->getType());
534
535 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
536
537 // Always emit the immediate (if non-zero) into the same block as the user.
538 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
539 return Rewriter.expandCodeFor(NewValSCEV, IP,
540 OperandValToReplace->getType());
541}
542
543
Chris Lattnera6d7c352005-08-04 20:03:32 +0000544// Once we rewrite the code to insert the new IVs we want, update the
545// operands of Inst to use the new expression 'NewBase', with 'Imm' added
546// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000547void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000548 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000549 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000550 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000551 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000552 // Replace the use of the operand Value with the new Phi we just created.
553 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000554 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000555 return;
556 }
557
558 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000559 // expression into each operand block that uses it. Note that PHI nodes can
560 // have multiple entries for the same predecessor. We use a map to make sure
561 // that a PHI node only has a single Value* for each predecessor (which also
562 // prevents us from inserting duplicate code in some blocks).
563 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000564 PHINode *PN = cast<PHINode>(Inst);
565 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
566 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000567 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000568 // code on all predecessor/successor paths. We do this unless this is the
569 // canonical backedge for this loop, as this can make some inserted code
570 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000571 BasicBlock *PHIPred = PN->getIncomingBlock(i);
572 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
573 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000574
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000575 // First step, split the critical edge.
Chris Lattnera6eb7e02006-10-28 06:45:33 +0000576 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
Chris Lattner8447b492005-08-12 22:22:17 +0000577
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000578 // Next step: move the basic block. In particular, if the PHI node
579 // is outside of the loop, and PredTI is in the loop, we want to
580 // move the block to be immediately before the PHI block, not
581 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000582 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000583 BasicBlock *NewBB = PN->getIncomingBlock(i);
584 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000585 }
Chris Lattner5191c652006-10-28 00:59:20 +0000586
587 // Splitting the edge can reduce the number of PHI entries we have.
588 e = PN->getNumIncomingValues();
Chris Lattner4fec86d2005-08-12 22:06:11 +0000589 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000590
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000591 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
592 if (!Code) {
593 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000594 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
595 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000596 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000597
598 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000599 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000600 Rewriter.clear();
601 }
602 }
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000603 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000604}
605
606
Nate Begemane68bcd12005-07-30 00:15:07 +0000607/// isTargetConstant - Return true if the following can be referenced by the
608/// immediate field of a target instruction.
Evan Chengc567c4e2006-03-13 23:14:23 +0000609static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000610 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattner07720072005-12-05 18:23:57 +0000611 int64_t V = SC->getValue()->getSExtValue();
Evan Chengc567c4e2006-03-13 23:14:23 +0000612 if (TLI)
613 return TLI->isLegalAddressImmediate(V);
614 else
615 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
616 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner14203e82005-08-08 06:25:50 +0000617 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000618
Nate Begemane68bcd12005-07-30 00:15:07 +0000619 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000621 if (CE->getOpcode() == Instruction::PtrToInt) {
Evan Chengc567c4e2006-03-13 23:14:23 +0000622 Constant *Op0 = CE->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000623 if (isa<GlobalValue>(Op0) && TLI &&
Evan Chengc567c4e2006-03-13 23:14:23 +0000624 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begemane68bcd12005-07-30 00:15:07 +0000625 return true;
Evan Chengc567c4e2006-03-13 23:14:23 +0000626 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000627 return false;
628}
629
Chris Lattner37ed8952005-08-08 22:32:34 +0000630/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
631/// loop varying to the Imm operand.
632static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
633 Loop *L) {
634 if (Val->isLoopInvariant(L)) return; // Nothing to do.
635
636 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
637 std::vector<SCEVHandle> NewOps;
638 NewOps.reserve(SAE->getNumOperands());
639
640 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
641 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
642 // If this is a loop-variant expression, it must stay in the immediate
643 // field of the expression.
644 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
645 } else {
646 NewOps.push_back(SAE->getOperand(i));
647 }
648
649 if (NewOps.empty())
650 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
651 else
652 Val = SCEVAddExpr::get(NewOps);
653 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
654 // Try to pull immediates out of the start value of nested addrec's.
655 SCEVHandle Start = SARE->getStart();
656 MoveLoopVariantsToImediateField(Start, Imm, L);
657
658 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
659 Ops[0] = Start;
660 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
661 } else {
662 // Otherwise, all of Val is variant, move the whole thing over.
663 Imm = SCEVAddExpr::get(Imm, Val);
664 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
665 }
666}
667
668
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000669/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000670/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000671/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000672static void MoveImmediateValues(const TargetLowering *TLI,
673 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000674 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000675 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000676 std::vector<SCEVHandle> NewOps;
677 NewOps.reserve(SAE->getNumOperands());
678
Chris Lattner2959f002006-02-04 07:36:50 +0000679 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
680 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengc567c4e2006-03-13 23:14:23 +0000681 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000682
683 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000684 // If this is a loop-variant expression, it must stay in the immediate
685 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000686 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000687 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000688 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000689 }
Chris Lattner2959f002006-02-04 07:36:50 +0000690 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000691
692 if (NewOps.empty())
693 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
694 else
695 Val = SCEVAddExpr::get(NewOps);
696 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000697 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
698 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000699 SCEVHandle Start = SARE->getStart();
Evan Chengc567c4e2006-03-13 23:14:23 +0000700 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000701
702 if (Start != SARE->getStart()) {
703 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
704 Ops[0] = Start;
705 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
706 }
707 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000708 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
709 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengc567c4e2006-03-13 23:14:23 +0000710 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000711 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
712
713 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
714 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengc567c4e2006-03-13 23:14:23 +0000715 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000716
717 // If we extracted something out of the subexpressions, see if we can
718 // simplify this!
719 if (NewOp != SME->getOperand(1)) {
720 // Scale SubImm up by "8". If the result is a target constant, we are
721 // good.
722 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengc567c4e2006-03-13 23:14:23 +0000723 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000724 // Accumulate the immediate.
725 Imm = SCEVAddExpr::get(Imm, SubImm);
726
727 // Update what is left of 'Val'.
728 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
729 return;
730 }
731 }
732 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000733 }
734
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000735 // Loop-variant expressions must stay in the immediate field of the
736 // expression.
Evan Chengc567c4e2006-03-13 23:14:23 +0000737 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000738 !Val->isLoopInvariant(L)) {
739 Imm = SCEVAddExpr::get(Imm, Val);
740 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
741 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000742 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000743
744 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000745}
746
Chris Lattner5949d492005-08-13 07:27:18 +0000747
Chris Lattner3ff62012006-08-03 06:34:50 +0000748/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
749/// added together. This is used to reassociate common addition subexprs
750/// together for maximal sharing when rewriting bases.
Chris Lattner5949d492005-08-13 07:27:18 +0000751static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
752 SCEVHandle Expr) {
753 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
754 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
755 SeparateSubExprs(SubExprs, AE->getOperand(j));
756 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
757 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
758 if (SARE->getOperand(0) == Zero) {
759 SubExprs.push_back(Expr);
760 } else {
761 // Compute the addrec with zero as its base.
762 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
763 Ops[0] = Zero; // Start with zero base.
764 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
765
766
767 SeparateSubExprs(SubExprs, SARE->getOperand(0));
768 }
769 } else if (!isa<SCEVConstant>(Expr) ||
Reid Spencer53a37392007-03-02 23:51:25 +0000770 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
Chris Lattner5949d492005-08-13 07:27:18 +0000771 // Do not add zero.
772 SubExprs.push_back(Expr);
773 }
774}
775
776
Chris Lattnera091ff12005-08-09 00:18:09 +0000777/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
778/// removing any common subexpressions from it. Anything truly common is
779/// removed, accumulated, and returned. This looks for things like (a+b+c) and
780/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
781static SCEVHandle
782RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
783 unsigned NumUses = Uses.size();
784
785 // Only one use? Use its base, regardless of what it is!
786 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
787 SCEVHandle Result = Zero;
788 if (NumUses == 1) {
789 std::swap(Result, Uses[0].Base);
790 return Result;
791 }
792
793 // To find common subexpressions, count how many of Uses use each expression.
794 // If any subexpressions are used Uses.size() times, they are common.
795 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
796
Chris Lattner192cd182005-10-11 18:41:04 +0000797 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
798 // order we see them.
799 std::vector<SCEVHandle> UniqueSubExprs;
800
Chris Lattner5949d492005-08-13 07:27:18 +0000801 std::vector<SCEVHandle> SubExprs;
802 for (unsigned i = 0; i != NumUses; ++i) {
803 // If the base is zero (which is common), return zero now, there are no
804 // CSEs we can find.
805 if (Uses[i].Base == Zero) return Zero;
806
807 // Split the expression into subexprs.
808 SeparateSubExprs(SubExprs, Uses[i].Base);
809 // Add one to SubExpressionUseCounts for each subexpr present.
810 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000811 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
812 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000813 SubExprs.clear();
814 }
815
Chris Lattner192cd182005-10-11 18:41:04 +0000816 // Now that we know how many times each is used, build Result. Iterate over
817 // UniqueSubexprs so that we have a stable ordering.
818 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
819 std::map<SCEVHandle, unsigned>::iterator I =
820 SubExpressionUseCounts.find(UniqueSubExprs[i]);
821 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000822 if (I->second == NumUses) { // Found CSE!
823 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000824 } else {
825 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000826 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000827 }
Chris Lattner192cd182005-10-11 18:41:04 +0000828 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000829
830 // If we found no CSE's, return now.
831 if (Result == Zero) return Result;
832
833 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000834 for (unsigned i = 0; i != NumUses; ++i) {
835 // Split the expression into subexprs.
836 SeparateSubExprs(SubExprs, Uses[i].Base);
837
838 // Remove any common subexpressions.
839 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
840 if (SubExpressionUseCounts.count(SubExprs[j])) {
841 SubExprs.erase(SubExprs.begin()+j);
842 --j; --e;
843 }
844
845 // Finally, the non-shared expressions together.
846 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000847 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000848 else
849 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000850 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000851 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000852
853 return Result;
854}
855
Evan Cheng3df447d2006-03-16 21:53:05 +0000856/// isZero - returns true if the scalar evolution expression is zero.
857///
858static bool isZero(SCEVHandle &V) {
859 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Reid Spencer53a37392007-03-02 23:51:25 +0000860 return SC->getValue()->isZero();
Evan Cheng3df447d2006-03-16 21:53:05 +0000861 return false;
862}
863
Chris Lattnera091ff12005-08-09 00:18:09 +0000864
Evan Cheng45206982006-03-17 19:52:23 +0000865/// CheckForIVReuse - Returns the multiple if the stride is the multiple
866/// of a previous stride and it is a legal value for the target addressing
867/// mode scale component. This allows the users of this stride to be rewritten
Evan Chengc28282b2006-03-18 08:03:12 +0000868/// as prev iv * factor. It returns 0 if no reuse is possible.
Evan Cheng45206982006-03-17 19:52:23 +0000869unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
Evan Chenge9c68f52006-07-18 19:07:58 +0000870 IVExpr &IV, const Type *Ty) {
Evan Chengc28282b2006-03-18 08:03:12 +0000871 if (!TLI) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000872
873 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
Reid Spencerba547cb2007-03-02 23:37:53 +0000874 int64_t SInt = SC->getValue()->getSExtValue();
875 if (SInt == 1) return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000876
877 for (TargetLowering::legal_am_scale_iterator
878 I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
879 I != E; ++I) {
Reid Spencerba547cb2007-03-02 23:37:53 +0000880 unsigned Scale = *I;
881 if (unsigned(abs(SInt)) < Scale || (SInt % Scale) != 0)
Evan Cheng45206982006-03-17 19:52:23 +0000882 continue;
883 std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
Reid Spencerba547cb2007-03-02 23:37:53 +0000884 IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, UIntPtrTy));
Evan Cheng45206982006-03-17 19:52:23 +0000885 if (SI == IVsByStride.end())
886 continue;
887 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
888 IE = SI->second.IVs.end(); II != IE; ++II)
889 // FIXME: Only handle base == 0 for now.
Evan Chenge9c68f52006-07-18 19:07:58 +0000890 // Only reuse previous IV if it would not require a type conversion.
Chris Lattner3fe98ae2007-01-06 01:37:35 +0000891 if (isZero(II->Base) && II->Base->getType() == Ty) {
Evan Cheng45206982006-03-17 19:52:23 +0000892 IV = *II;
Reid Spencerba547cb2007-03-02 23:37:53 +0000893 return Scale;
Evan Cheng45206982006-03-17 19:52:23 +0000894 }
895 }
896 }
897
Evan Chengc28282b2006-03-18 08:03:12 +0000898 return 0;
Evan Cheng45206982006-03-17 19:52:23 +0000899}
900
Chris Lattner3ff62012006-08-03 06:34:50 +0000901/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
902/// returns true if Val's isUseOfPostIncrementedValue is true.
903static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
904 return Val.isUseOfPostIncrementedValue;
905}
Evan Cheng45206982006-03-17 19:52:23 +0000906
Nate Begemane68bcd12005-07-30 00:15:07 +0000907/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
908/// stride of IV. All of the users may have different starting values, and this
909/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000910void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000911 IVUsersOfOneStride &Uses,
912 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000913 bool isOnlyStride) {
914 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000915 // this new vector, each 'BasedUser' contains 'Base' the base of the
916 // strided accessas well as the old information from Uses. We progressively
917 // move information from the Base field to the Imm field, until we eventually
918 // have the full access expression to rewrite the use.
919 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000920 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000921 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
922 UsersToProcess.push_back(Uses.Users[i]);
923
924 // Move any loop invariant operands from the offset field to the immediate
925 // field of the use, so that we don't try to use something before it is
926 // computed.
927 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
928 UsersToProcess.back().Imm, L);
929 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000930 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000931 }
Evan Cheng45206982006-03-17 19:52:23 +0000932
Chris Lattnera091ff12005-08-09 00:18:09 +0000933 // We now have a whole bunch of uses of like-strided induction variables, but
934 // they might all have different bases. We want to emit one PHI node for this
935 // stride which we fold as many common expressions (between the IVs) into as
936 // possible. Start by identifying the common expressions in the base values
937 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
938 // "A+B"), emit it to the preheader, then remove the expression from the
939 // UsersToProcess base values.
Evan Cheng3df447d2006-03-16 21:53:05 +0000940 SCEVHandle CommonExprs =
941 RemoveCommonExpressionsFromUseBases(UsersToProcess);
Chris Lattnera091ff12005-08-09 00:18:09 +0000942
Evan Chenge9c68f52006-07-18 19:07:58 +0000943 // Check if it is possible to reuse a IV with stride that is factor of this
944 // stride. And the multiple is a number that can be encoded in the scale
945 // field of the target addressing mode.
946 PHINode *NewPHI = NULL;
947 Value *IncV = NULL;
948 IVExpr ReuseIV;
949 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
950 CommonExprs->getType());
951 if (RewriteFactor != 0) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000952 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
953 << " and BASE " << *ReuseIV.Base << " :\n";
Evan Chenge9c68f52006-07-18 19:07:58 +0000954 NewPHI = ReuseIV.PHI;
955 IncV = ReuseIV.IncV;
956 }
957
Chris Lattner37ed8952005-08-08 22:32:34 +0000958 // Next, figure out what we can represent in the immediate fields of
959 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000960 // fields of the BasedUsers. We do this so that it increases the commonality
961 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000962 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000963 // If the user is not in the current loop, this means it is using the exit
964 // value of the IV. Do not put anything in the base, make sure it's all in
965 // the immediate field to allow as much factoring as possible.
966 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000967 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
968 UsersToProcess[i].Base);
969 UsersToProcess[i].Base =
970 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000971 } else {
972
973 // Addressing modes can be folded into loads and stores. Be careful that
974 // the store is through the expression, not of the expression though.
975 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
976 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
977 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
978 isAddress = true;
979
Evan Chengc567c4e2006-03-13 23:14:23 +0000980 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner5cf983e2005-08-16 00:38:11 +0000981 isAddress, L);
982 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000983 }
Evan Cheng3df447d2006-03-16 21:53:05 +0000984
Chris Lattnera091ff12005-08-09 00:18:09 +0000985 // Now that we know what we need to do, insert the PHI node itself.
986 //
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000987 DOUT << "INSERTING IV of STRIDE " << *Stride << " and BASE "
988 << *CommonExprs << " :\n";
Evan Cheng3df447d2006-03-16 21:53:05 +0000989
Chris Lattnera091ff12005-08-09 00:18:09 +0000990 SCEVExpander Rewriter(*SE, *LI);
991 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000992
Chris Lattnera091ff12005-08-09 00:18:09 +0000993 BasicBlock *Preheader = L->getLoopPreheader();
994 Instruction *PreInsertPt = Preheader->getTerminator();
995 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000996
Chris Lattner8048b852005-09-12 17:11:27 +0000997 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng3df447d2006-03-16 21:53:05 +0000998
Chris Lattnera091ff12005-08-09 00:18:09 +0000999 const Type *ReplacedTy = CommonExprs->getType();
Evan Cheng45206982006-03-17 19:52:23 +00001000
1001 // Emit the initial base value into the loop preheader.
1002 Value *CommonBaseV
1003 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1004 ReplacedTy);
1005
Evan Chengc28282b2006-03-18 08:03:12 +00001006 if (RewriteFactor == 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001007 // Create a new Phi for this base, and stick it in the loop header.
1008 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1009 ++NumInserted;
Chris Lattnera091ff12005-08-09 00:18:09 +00001010
Evan Cheng45206982006-03-17 19:52:23 +00001011 // Add common base to the new Phi node.
1012 NewPHI->addIncoming(CommonBaseV, Preheader);
1013
Evan Cheng3df447d2006-03-16 21:53:05 +00001014 // Insert the stride into the preheader.
1015 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1016 ReplacedTy);
1017 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
Chris Lattneredff91a2005-08-10 00:45:21 +00001018
Evan Cheng3df447d2006-03-16 21:53:05 +00001019 // Emit the increment of the base value before the terminator of the loop
1020 // latch block, and add it to the Phi node.
1021 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1022 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +00001023
Evan Cheng3df447d2006-03-16 21:53:05 +00001024 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1025 ReplacedTy);
1026 IncV->setName(NewPHI->getName()+".inc");
1027 NewPHI->addIncoming(IncV, LatchBlock);
1028
Evan Cheng45206982006-03-17 19:52:23 +00001029 // Remember this in case a later stride is multiple of this.
Evan Chengc28282b2006-03-18 08:03:12 +00001030 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
Evan Cheng45206982006-03-17 19:52:23 +00001031 } else {
1032 Constant *C = dyn_cast<Constant>(CommonBaseV);
1033 if (!C ||
1034 (!C->isNullValue() &&
1035 !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001036 // We want the common base emitted into the preheader! This is just
1037 // using cast as a copy so BitCast (no-op cast) is appropriate
1038 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1039 "commonbase", PreInsertPt);
Evan Cheng3df447d2006-03-16 21:53:05 +00001040 }
Chris Lattnera091ff12005-08-09 00:18:09 +00001041
Chris Lattner3ff62012006-08-03 06:34:50 +00001042 // We want to emit code for users inside the loop first. To do this, we
1043 // rearrange BasedUser so that the entries at the end have
1044 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1045 // vector (so we handle them first).
1046 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1047 PartitionByIsUseOfPostIncrementedValue);
1048
1049 // Sort this by base, so that things with the same base are handled
1050 // together. By partitioning first and stable-sorting later, we are
1051 // guaranteed that within each base we will pop off users from within the
1052 // loop before users outside of the loop with a particular base.
1053 //
1054 // We would like to use stable_sort here, but we can't. The problem is that
1055 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1056 // we don't have anything to do a '<' comparison on. Because we think the
1057 // number of uses is small, do a horrible bubble sort which just relies on
1058 // ==.
1059 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1060 // Get a base value.
1061 SCEVHandle Base = UsersToProcess[i].Base;
1062
1063 // Compact everything with this base to be consequetive with this one.
1064 for (unsigned j = i+1; j != e; ++j) {
1065 if (UsersToProcess[j].Base == Base) {
1066 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1067 ++i;
1068 }
1069 }
1070 }
1071
1072 // Process all the users now. This outer loop handles all bases, the inner
1073 // loop handles all users of a particular base.
Nate Begemane68bcd12005-07-30 00:15:07 +00001074 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001075 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +00001076
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001077 DOUT << " INSERTING code for BASE = " << *Base << ":\n";
Chris Lattnerbb78c972005-08-03 23:30:08 +00001078
Chris Lattnera091ff12005-08-09 00:18:09 +00001079 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +00001080 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1081 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +00001082
1083 // If BaseV is a constant other than 0, make sure that it gets inserted into
1084 // the preheader, instead of being forward substituted into the uses. We do
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001085 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1086 // in this case.
Chris Lattner3ff62012006-08-03 06:34:50 +00001087 if (Constant *C = dyn_cast<Constant>(BaseV)) {
Evan Chengc567c4e2006-03-13 23:14:23 +00001088 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001089 // We want this constant emitted into the preheader! This is just
1090 // using cast as a copy so BitCast (no-op cast) is appropriate
1091 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
Chris Lattnera091ff12005-08-09 00:18:09 +00001092 PreInsertPt);
1093 }
Chris Lattner3ff62012006-08-03 06:34:50 +00001094 }
1095
Nate Begemane68bcd12005-07-30 00:15:07 +00001096 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +00001097 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001098 do {
Chris Lattner3ff62012006-08-03 06:34:50 +00001099 // FIXME: Use emitted users to emit other users.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001100 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +00001101
Chris Lattnera091ff12005-08-09 00:18:09 +00001102 // If this instruction wants to use the post-incremented value, move it
1103 // after the post-inc and use its value instead of the PHI.
1104 Value *RewriteOp = NewPHI;
1105 if (User.isUseOfPostIncrementedValue) {
1106 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +00001107
1108 // If this user is in the loop, make sure it is the last thing in the
1109 // loop to ensure it is dominated by the increment.
1110 if (L->contains(User.Inst->getParent()))
1111 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +00001112 }
Reid Spencerdf1f19a2006-12-13 08:06:42 +00001113 if (RewriteOp->getType() != ReplacedTy) {
1114 Instruction::CastOps opcode = Instruction::Trunc;
1115 if (ReplacedTy->getPrimitiveSizeInBits() ==
1116 RewriteOp->getType()->getPrimitiveSizeInBits())
1117 opcode = Instruction::BitCast;
1118 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1119 }
Evan Cheng398f7022006-06-09 00:12:42 +00001120
Chris Lattnera091ff12005-08-09 00:18:09 +00001121 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1122
Chris Lattnerdb23c742005-08-03 22:51:21 +00001123 // Clear the SCEVExpander's expression map so that we are guaranteed
1124 // to have the code emitted where we expect it.
1125 Rewriter.clear();
Evan Cheng3df447d2006-03-16 21:53:05 +00001126
1127 // If we are reusing the iv, then it must be multiplied by a constant
1128 // factor take advantage of addressing mode scale component.
Evan Chengc28282b2006-03-18 08:03:12 +00001129 if (RewriteFactor != 0) {
Evan Cheng3df447d2006-03-16 21:53:05 +00001130 RewriteExpr =
1131 SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
Evan Cheng45206982006-03-17 19:52:23 +00001132 RewriteExpr->getType()),
1133 RewriteExpr);
1134
1135 // The common base is emitted in the loop preheader. But since we
1136 // are reusing an IV, it has not been used to initialize the PHI node.
1137 // Add it to the expression used to rewrite the uses.
1138 if (!isa<ConstantInt>(CommonBaseV) ||
Reid Spencer53a37392007-03-02 23:51:25 +00001139 !cast<ConstantInt>(CommonBaseV)->isZero())
Evan Cheng45206982006-03-17 19:52:23 +00001140 RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1141 SCEVUnknown::get(CommonBaseV));
1142 }
Evan Cheng3df447d2006-03-16 21:53:05 +00001143
Chris Lattnera6d7c352005-08-04 20:03:32 +00001144 // Now that we know what we need to do, insert code before User for the
1145 // immediate and any loop-variant expressions.
Reid Spencer53a37392007-03-02 23:51:25 +00001146 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
Chris Lattnera091ff12005-08-09 00:18:09 +00001147 // Add BaseV to the PHI value if needed.
1148 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
Evan Cheng3df447d2006-03-16 21:53:05 +00001149
Chris Lattner8447b492005-08-12 22:22:17 +00001150 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +00001151
Chris Lattnerdb23c742005-08-03 22:51:21 +00001152 // Mark old value we replaced as possibly dead, so that it is elminated
1153 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +00001154 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +00001155
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001156 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +00001157 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001158
Chris Lattner3ff62012006-08-03 06:34:50 +00001159 // If there are any more users to process with the same base, process them
1160 // now. We sorted by base above, so we just have to check the last elt.
Chris Lattner5c9d63d2005-10-11 18:30:57 +00001161 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001162 // TODO: Next, find out which base index is the most common, pull it out.
1163 }
1164
1165 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1166 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001167}
1168
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001169// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1170// uses in the loop, look to see if we can eliminate some, in favor of using
1171// common indvars for the different uses.
1172void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1173 // TODO: implement optzns here.
1174
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001175 // Finally, get the terminating condition for the loop if possible. If we
1176 // can, we want to change it to use a post-incremented version of its
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001177 // induction variable, to allow coalescing the live ranges for the IV into
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001178 // one register value.
1179 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1180 BasicBlock *Preheader = L->getLoopPreheader();
1181 BasicBlock *LatchBlock =
1182 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1183 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001184 if (!TermBr || TermBr->isUnconditional() ||
1185 !isa<ICmpInst>(TermBr->getCondition()))
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001186 return;
Reid Spencer266e42b2006-12-23 06:05:41 +00001187 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001188
1189 // Search IVUsesByStride to find Cond's IVUse if there is one.
1190 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001191 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001192
Chris Lattnerb7a38942005-10-11 18:17:57 +00001193 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1194 ++Stride) {
1195 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1196 IVUsesByStride.find(StrideOrder[Stride]);
1197 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1198
1199 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1200 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001201 if (UI->User == Cond) {
1202 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001203 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001204 // NOTE: we could handle setcc instructions with multiple uses here, but
1205 // InstCombine does it as well for simple uses, it's not clear that it
1206 // occurs enough in real life to handle.
1207 break;
1208 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001209 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001210 if (!CondUse) return; // setcc doesn't use the IV.
1211
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001212 // It's possible for the setcc instruction to be anywhere in the loop, and
1213 // possible for it to have multiple users. If it is not immediately before
1214 // the latch block branch, move it.
1215 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1216 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1217 Cond->moveBefore(TermBr);
1218 } else {
1219 // Otherwise, clone the terminating condition and insert into the loopend.
Reid Spencer266e42b2006-12-23 06:05:41 +00001220 Cond = cast<ICmpInst>(Cond->clone());
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001221 Cond->setName(L->getHeader()->getName() + ".termcond");
1222 LatchBlock->getInstList().insert(TermBr, Cond);
1223
1224 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001225 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001226 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001227 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001228 }
1229 }
1230
1231 // If we get to here, we know that we can transform the setcc instruction to
Chris Lattnerf365f5f2006-03-24 07:14:34 +00001232 // use the post-incremented version of the IV, allowing us to coalesce the
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001233 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001234 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001235 CondUse->isUseOfPostIncrementedValue = true;
1236}
Nate Begemane68bcd12005-07-30 00:15:07 +00001237
Evan Chengf09f0eb2006-03-18 00:44:49 +00001238namespace {
1239 // Constant strides come first which in turns are sorted by their absolute
1240 // values. If absolute values are the same, then positive strides comes first.
1241 // e.g.
1242 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1243 struct StrideCompare {
1244 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1245 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1246 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1247 if (LHSC && RHSC) {
Reid Spencer197adfa2007-03-02 00:31:39 +00001248 int64_t LV = LHSC->getValue()->getSExtValue();
1249 int64_t RV = RHSC->getValue()->getSExtValue();
1250 uint64_t ALV = (LV < 0) ? -LV : LV;
1251 uint64_t ARV = (RV < 0) ? -RV : RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001252 if (ALV == ARV)
Reid Spencer197adfa2007-03-02 00:31:39 +00001253 return LV > RV;
Evan Chengf09f0eb2006-03-18 00:44:49 +00001254 else
Reid Spencer197adfa2007-03-02 00:31:39 +00001255 return ALV < ARV;
Chris Lattner7d80b4f2006-03-22 17:27:24 +00001256 }
1257 return (LHSC && !RHSC);
Evan Chengf09f0eb2006-03-18 00:44:49 +00001258 }
1259 };
1260}
1261
Devang Patelb0743b52007-03-06 21:14:09 +00001262bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
Nate Begemanb18121e2004-10-18 21:08:22 +00001263
Devang Patelb0743b52007-03-06 21:14:09 +00001264 LI = &getAnalysis<LoopInfo>();
1265 EF = &getAnalysis<ETForest>();
1266 SE = &getAnalysis<ScalarEvolution>();
1267 TD = &getAnalysis<TargetData>();
1268 UIntPtrTy = TD->getIntPtrType();
1269
1270 // Find all uses of induction variables in this loop, and catagorize
Nate Begemane68bcd12005-07-30 00:15:07 +00001271 // them by stride. Start by finding all of the PHI nodes in the header for
1272 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001273 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001274 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001275 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001276
Nate Begemane68bcd12005-07-30 00:15:07 +00001277 // If we have nothing to do, return.
Devang Patelb0743b52007-03-06 21:14:09 +00001278 if (IVUsesByStride.empty()) return false;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001279
1280 // Optimize induction variables. Some indvar uses can be transformed to use
1281 // strides that will be needed for other purposes. A common example of this
1282 // is the exit test for the loop, which can often be rewritten to use the
1283 // computation of some other indvar to decide when to terminate the loop.
1284 OptimizeIndvars(L);
1285
Misha Brukmanb1c93172005-04-21 23:48:37 +00001286
Nate Begemane68bcd12005-07-30 00:15:07 +00001287 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1288 // doing computation in byte values, promote to 32-bit values if safe.
1289
1290 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1291 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1292 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1293 // to be careful that IV's are all the same type. Only works for intptr_t
1294 // indvars.
1295
1296 // If we only have one stride, we can more aggressively eliminate some things.
1297 bool HasOneStride = IVUsesByStride.size() == 1;
Evan Cheng3df447d2006-03-16 21:53:05 +00001298
1299#ifndef NDEBUG
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001300 DOUT << "\nLSR on ";
Evan Cheng3df447d2006-03-16 21:53:05 +00001301 DEBUG(L->dump());
1302#endif
1303
1304 // IVsByStride keeps IVs for one particular loop.
1305 IVsByStride.clear();
1306
Evan Chengf09f0eb2006-03-18 00:44:49 +00001307 // Sort the StrideOrder so we process larger strides first.
1308 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1309
Chris Lattnera091ff12005-08-09 00:18:09 +00001310 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001311 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1312 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1313 // This extra layer of indirection makes the ordering of strides deterministic
1314 // - not dependent on map order.
1315 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1316 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1317 IVUsesByStride.find(StrideOrder[Stride]);
1318 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001319 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001320 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001321
1322 // Clean up after ourselves
1323 if (!DeadInsts.empty()) {
1324 DeleteTriviallyDeadInstructions(DeadInsts);
1325
Nate Begemane68bcd12005-07-30 00:15:07 +00001326 BasicBlock::iterator I = L->getHeader()->begin();
1327 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001328 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001329 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1330
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001331 // At this point, we know that we have killed one or more GEP
1332 // instructions. It is worth checking to see if the cann indvar is also
1333 // dead, so that we can remove it as well. The requirements for the cann
1334 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001335 // 1. the cann indvar has one use
1336 // 2. the use is an add instruction
1337 // 3. the add has one use
1338 // 4. the add is used by the cann indvar
1339 // If all four cases above are true, then we can remove both the add and
1340 // the cann indvar.
1341 // FIXME: this needs to eliminate an induction variable even if it's being
1342 // compared against some value to decide loop termination.
1343 if (PN->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001344 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1345 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1346 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
Chris Lattner75a44e12005-08-02 02:52:02 +00001347 DeadInsts.insert(BO);
1348 // Break the cycle, then delete the PHI.
1349 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001350 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001351 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001352 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001353 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001354 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001355 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001356 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001357 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001358
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001359 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001360 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001361 StrideOrder.clear();
Devang Patelb0743b52007-03-06 21:14:09 +00001362 return false;
Nate Begemanb18121e2004-10-18 21:08:22 +00001363}