blob: dc1dc18b899d3ace0da2d48e864658bab1cc6a27 [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000029#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000030#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000032#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000033#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000034#include <set>
35using namespace llvm;
36
37namespace {
38 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000039 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattneredff91a2005-08-10 00:45:21 +000040 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000041
Chris Lattner430d0022005-08-03 22:21:05 +000042 /// IVStrideUse - Keep track of one use of a strided induction variable, where
43 /// the stride is stored externally. The Offset member keeps track of the
44 /// offset from the IV, User is the actual user of the operand, and 'Operand'
45 /// is the operand # of the User that is the use.
46 struct IVStrideUse {
47 SCEVHandle Offset;
48 Instruction *User;
49 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000050
51 // isUseOfPostIncrementedValue - True if this should use the
52 // post-incremented version of this IV, not the preincremented version.
53 // This can only be set in special cases, such as the terminating setcc
54 // instruction for a loop.
55 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000056
57 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000058 : Offset(Offs), User(U), OperandValToReplace(O),
59 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000060 };
61
62 /// IVUsersOfOneStride - This structure keeps track of all instructions that
63 /// have an operand that is based on the trip count multiplied by some stride.
64 /// The stride for all of these users is common and kept external to this
65 /// structure.
66 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000067 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000068 /// initial value and the operand that uses the IV.
69 std::vector<IVStrideUse> Users;
70
71 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
72 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000073 }
74 };
75
76
Nate Begemanb18121e2004-10-18 21:08:22 +000077 class LoopStrengthReduce : public FunctionPass {
78 LoopInfo *LI;
79 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000080 ScalarEvolution *SE;
81 const TargetData *TD;
82 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000083 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000084
85 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
86 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000087 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000088
89 /// IVUsesByStride - Keep track of all uses of induction variables that we
90 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +000091 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000092
Chris Lattner6f286b72005-08-04 01:19:13 +000093 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
94 /// of the casted version of each value. This is accessed by
95 /// getCastedVersionOf.
96 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +000097
98 /// DeadInsts - Keep track of instructions we may have made dead, so that
99 /// we can remove them after we are done working.
100 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +0000101 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000102 LoopStrengthReduce(unsigned MTAMS = 1)
103 : MaxTargetAMSize(MTAMS) {
104 }
105
Nate Begemanb18121e2004-10-18 21:08:22 +0000106 virtual bool runOnFunction(Function &) {
107 LI = &getAnalysis<LoopInfo>();
108 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000109 SE = &getAnalysis<ScalarEvolution>();
110 TD = &getAnalysis<TargetData>();
111 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000112 Changed = false;
113
114 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
115 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000116
Nate Begemanb18121e2004-10-18 21:08:22 +0000117 return Changed;
118 }
119
120 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
121 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000122 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000123 AU.addRequired<LoopInfo>();
124 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000125 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000126 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000127 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000128
129 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
130 ///
131 Value *getCastedVersionOf(Value *V);
132private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000133 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000134 bool AddUsersIfInteresting(Instruction *I, Loop *L,
135 std::set<Instruction*> &Processed);
136 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
137
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000138 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000139
Chris Lattneredff91a2005-08-10 00:45:21 +0000140 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
141 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000142 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000143 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
144 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000145 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000146 "Strength Reduce GEP Uses of Ind. Vars");
147}
148
Jeff Cohena2c59b72005-03-04 04:04:26 +0000149FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
150 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000151}
152
Chris Lattner6f286b72005-08-04 01:19:13 +0000153/// getCastedVersionOf - Return the specified value casted to uintptr_t.
154///
155Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
156 if (V->getType() == UIntPtrTy) return V;
157 if (Constant *CB = dyn_cast<Constant>(V))
158 return ConstantExpr::getCast(CB, UIntPtrTy);
159
160 Value *&New = CastedPointers[V];
161 if (New) return New;
162
163 BasicBlock::iterator InsertPt;
164 if (Argument *Arg = dyn_cast<Argument>(V)) {
165 // Insert into the entry of the function, after any allocas.
166 InsertPt = Arg->getParent()->begin()->begin();
167 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
168 } else {
169 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
170 InsertPt = II->getNormalDest()->begin();
171 } else {
172 InsertPt = cast<Instruction>(V);
173 ++InsertPt;
174 }
175
176 // Do not insert casts into the middle of PHI node blocks.
177 while (isa<PHINode>(InsertPt)) ++InsertPt;
178 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000179
180 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
181 DeadInsts.insert(cast<Instruction>(New));
182 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000183}
184
185
Nate Begemanb18121e2004-10-18 21:08:22 +0000186/// DeleteTriviallyDeadInstructions - If any of the instructions is the
187/// specified set are trivially dead, delete them and see if this makes any of
188/// their operands subsequently dead.
189void LoopStrengthReduce::
190DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
191 while (!Insts.empty()) {
192 Instruction *I = *Insts.begin();
193 Insts.erase(Insts.begin());
194 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000195 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
196 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
197 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000198 SE->deleteInstructionFromRecords(I);
199 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000200 Changed = true;
201 }
202 }
203}
204
Jeff Cohen39751c32005-02-27 19:37:07 +0000205
Chris Lattnereaf24722005-08-04 17:40:30 +0000206/// GetExpressionSCEV - Compute and return the SCEV for the specified
207/// instruction.
208SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000209 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
210 // If this is a GEP that SE doesn't know about, compute it now and insert it.
211 // If this is not a GEP, or if we have already done this computation, just let
212 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000213 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000214 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000215 return SE->getSCEV(Exp);
216
Nate Begemane68bcd12005-07-30 00:15:07 +0000217 // Analyze all of the subscripts of this getelementptr instruction, looking
218 // for uses that are determined by the trip count of L. First, skip all
219 // operands the are not dependent on the IV.
220
221 // Build up the base expression. Insert an LLVM cast of the pointer to
222 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000223 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000224
225 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000226
227 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000228 // If this is a use of a recurrence that we can analyze, and it comes before
229 // Op does in the GEP operand list, we will handle this when we process this
230 // operand.
231 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
232 const StructLayout *SL = TD->getStructLayout(STy);
233 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
234 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000235 GEPVal = SCEVAddExpr::get(GEPVal,
236 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000237 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000238 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
239 SCEVHandle Idx = SE->getSCEV(OpVal);
240
Chris Lattnereaf24722005-08-04 17:40:30 +0000241 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
242 if (TypeSize != 1)
243 Idx = SCEVMulExpr::get(Idx,
244 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
245 TypeSize)));
246 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000247 }
248 }
249
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000250 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000251 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000252}
253
Chris Lattneracc42c42005-08-04 19:08:16 +0000254/// getSCEVStartAndStride - Compute the start and stride of this expression,
255/// returning false if the expression is not a start/stride pair, or true if it
256/// is. The stride must be a loop invariant expression, but the start may be
257/// a mix of loop invariant and loop variant expressions.
258static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000259 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000260 SCEVHandle TheAddRec = Start; // Initialize to zero.
261
262 // If the outer level is an AddExpr, the operands are all start values except
263 // for a nested AddRecExpr.
264 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
265 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
266 if (SCEVAddRecExpr *AddRec =
267 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
268 if (AddRec->getLoop() == L)
269 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
270 else
271 return false; // Nested IV of some sort?
272 } else {
273 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
274 }
275
276 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
277 TheAddRec = SH;
278 } else {
279 return false; // not analyzable.
280 }
281
282 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
283 if (!AddRec || AddRec->getLoop() != L) return false;
284
285 // FIXME: Generalize to non-affine IV's.
286 if (!AddRec->isAffine()) return false;
287
288 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
289
Chris Lattneracc42c42005-08-04 19:08:16 +0000290 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000291 DEBUG(std::cerr << "[" << L->getHeader()->getName()
292 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000293
Chris Lattneredff91a2005-08-10 00:45:21 +0000294 Stride = AddRec->getOperand(1);
295 // Check that all constant strides are the unsigned type, we don't want to
296 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
297 // merged.
298 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000299 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000300
Chris Lattneracc42c42005-08-04 19:08:16 +0000301 return true;
302}
303
Nate Begemane68bcd12005-07-30 00:15:07 +0000304/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
305/// reducible SCEV, recursively add its users to the IVUsesByStride set and
306/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000307bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
308 std::set<Instruction*> &Processed) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000309 if (I->getType() == Type::VoidTy) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000310 if (!Processed.insert(I).second)
311 return true; // Instruction already handled.
312
Chris Lattneracc42c42005-08-04 19:08:16 +0000313 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000314 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000315 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000316
Chris Lattneracc42c42005-08-04 19:08:16 +0000317 // Get the start and stride for this expression.
318 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000319 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000320 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
321 return false; // Non-reducible symbolic expression, bail out.
322
Nate Begemane68bcd12005-07-30 00:15:07 +0000323 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
324 Instruction *User = cast<Instruction>(*UI);
325
326 // Do not infinitely recurse on PHI nodes.
327 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
328 continue;
329
330 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000331 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000332 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000333 if (LI->getLoopFor(User->getParent()) != L) {
334 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
335 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000336 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000337 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000338 DEBUG(std::cerr << "FOUND USER: " << *User
339 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000340 AddUserToIVUsers = true;
341 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000342
Chris Lattneracc42c42005-08-04 19:08:16 +0000343 if (AddUserToIVUsers) {
Chris Lattner65107492005-08-04 00:40:47 +0000344 // Okay, we found a user that we cannot reduce. Analyze the instruction
345 // and decide what to do with it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000346 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begemane68bcd12005-07-30 00:15:07 +0000347 }
348 }
349 return true;
350}
351
352namespace {
353 /// BasedUser - For a particular base value, keep information about how we've
354 /// partitioned the expression so far.
355 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000356 /// Base - The Base value for the PHI node that needs to be inserted for
357 /// this use. As the use is processed, information gets moved from this
358 /// field to the Imm field (below). BasedUser values are sorted by this
359 /// field.
360 SCEVHandle Base;
361
Nate Begemane68bcd12005-07-30 00:15:07 +0000362 /// Inst - The instruction using the induction variable.
363 Instruction *Inst;
364
Chris Lattner430d0022005-08-03 22:21:05 +0000365 /// OperandValToReplace - The operand value of Inst to replace with the
366 /// EmittedBase.
367 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000368
369 /// Imm - The immediate value that should be added to the base immediately
370 /// before Inst, because it will be folded into the imm field of the
371 /// instruction.
372 SCEVHandle Imm;
373
374 /// EmittedBase - The actual value* to use for the base value of this
375 /// operation. This is null if we should just use zero so far.
376 Value *EmittedBase;
377
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000378 // isUseOfPostIncrementedValue - True if this should use the
379 // post-incremented version of this IV, not the preincremented version.
380 // This can only be set in special cases, such as the terminating setcc
381 // instruction for a loop.
382 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000383
384 BasedUser(IVStrideUse &IVSU)
385 : Base(IVSU.Offset), Inst(IVSU.User),
386 OperandValToReplace(IVSU.OperandValToReplace),
387 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
388 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000389
Chris Lattnera6d7c352005-08-04 20:03:32 +0000390 // Once we rewrite the code to insert the new IVs we want, update the
391 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
392 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000393 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
394 SCEVExpander &Rewriter);
Nate Begemane68bcd12005-07-30 00:15:07 +0000395
Chris Lattner37c24cc2005-08-08 22:56:21 +0000396 // Sort by the Base field.
397 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
Nate Begemane68bcd12005-07-30 00:15:07 +0000398
399 void dump() const;
400 };
401}
402
403void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000404 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000405 std::cerr << " Imm=" << *Imm;
406 if (EmittedBase)
407 std::cerr << " EB=" << *EmittedBase;
408
409 std::cerr << " Inst: " << *Inst;
410}
411
Chris Lattnera6d7c352005-08-04 20:03:32 +0000412// Once we rewrite the code to insert the new IVs we want, update the
413// operands of Inst to use the new expression 'NewBase', with 'Imm' added
414// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000415void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattnera6d7c352005-08-04 20:03:32 +0000416 SCEVExpander &Rewriter) {
417 if (!isa<PHINode>(Inst)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000418 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000419 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
420 OperandValToReplace->getType());
421
422 // Replace the use of the operand Value with the new Phi we just created.
423 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
424 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
425 return;
426 }
427
428 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000429 // expression into each operand block that uses it. Note that PHI nodes can
430 // have multiple entries for the same predecessor. We use a map to make sure
431 // that a PHI node only has a single Value* for each predecessor (which also
432 // prevents us from inserting duplicate code in some blocks).
433 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000434 PHINode *PN = cast<PHINode>(Inst);
435 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
436 if (PN->getIncomingValue(i) == OperandValToReplace) {
437 // FIXME: this should split any critical edges.
438
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000439 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
440 if (!Code) {
441 // Insert the code into the end of the predecessor block.
442 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
Chris Lattnera6d7c352005-08-04 20:03:32 +0000443
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000444 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
445 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
446 OperandValToReplace->getType());
447 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000448
449 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000450 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000451 Rewriter.clear();
452 }
453 }
454 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
455}
456
457
Nate Begemane68bcd12005-07-30 00:15:07 +0000458/// isTargetConstant - Return true if the following can be referenced by the
459/// immediate field of a target instruction.
460static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000461
Nate Begemane68bcd12005-07-30 00:15:07 +0000462 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner14203e82005-08-08 06:25:50 +0000463 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
464 // PPC allows a sign-extended 16-bit immediate field.
465 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
466 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
467 return true;
468 return false;
469 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000470
Nate Begemane68bcd12005-07-30 00:15:07 +0000471 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000472
Nate Begemane68bcd12005-07-30 00:15:07 +0000473 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
474 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
475 if (CE->getOpcode() == Instruction::Cast)
476 if (isa<GlobalValue>(CE->getOperand(0)))
477 // FIXME: should check to see that the dest is uintptr_t!
478 return true;
479 return false;
480}
481
Chris Lattner37ed8952005-08-08 22:32:34 +0000482/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
483/// loop varying to the Imm operand.
484static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
485 Loop *L) {
486 if (Val->isLoopInvariant(L)) return; // Nothing to do.
487
488 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
489 std::vector<SCEVHandle> NewOps;
490 NewOps.reserve(SAE->getNumOperands());
491
492 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
493 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
494 // If this is a loop-variant expression, it must stay in the immediate
495 // field of the expression.
496 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
497 } else {
498 NewOps.push_back(SAE->getOperand(i));
499 }
500
501 if (NewOps.empty())
502 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
503 else
504 Val = SCEVAddExpr::get(NewOps);
505 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
506 // Try to pull immediates out of the start value of nested addrec's.
507 SCEVHandle Start = SARE->getStart();
508 MoveLoopVariantsToImediateField(Start, Imm, L);
509
510 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
511 Ops[0] = Start;
512 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
513 } else {
514 // Otherwise, all of Val is variant, move the whole thing over.
515 Imm = SCEVAddExpr::get(Imm, Val);
516 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
517 }
518}
519
520
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000521/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000522/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000523/// Accumulate these immediate values into the Imm value.
524static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
525 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000526 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000527 std::vector<SCEVHandle> NewOps;
528 NewOps.reserve(SAE->getNumOperands());
529
530 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattneracc42c42005-08-04 19:08:16 +0000531 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
532 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
533 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
534 // If this is a loop-variant expression, it must stay in the immediate
535 // field of the expression.
536 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000537 } else {
538 NewOps.push_back(SAE->getOperand(i));
Nate Begemane68bcd12005-07-30 00:15:07 +0000539 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000540
541 if (NewOps.empty())
542 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
543 else
544 Val = SCEVAddExpr::get(NewOps);
545 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000546 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
547 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000548 SCEVHandle Start = SARE->getStart();
549 MoveImmediateValues(Start, Imm, isAddress, L);
550
551 if (Start != SARE->getStart()) {
552 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
553 Ops[0] = Start;
554 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
555 }
556 return;
Nate Begemane68bcd12005-07-30 00:15:07 +0000557 }
558
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000559 // Loop-variant expressions must stay in the immediate field of the
560 // expression.
561 if ((isAddress && isTargetConstant(Val)) ||
562 !Val->isLoopInvariant(L)) {
563 Imm = SCEVAddExpr::get(Imm, Val);
564 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
565 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000566 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000567
568 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000569}
570
Chris Lattnera091ff12005-08-09 00:18:09 +0000571/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
572/// removing any common subexpressions from it. Anything truly common is
573/// removed, accumulated, and returned. This looks for things like (a+b+c) and
574/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
575static SCEVHandle
576RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
577 unsigned NumUses = Uses.size();
578
579 // Only one use? Use its base, regardless of what it is!
580 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
581 SCEVHandle Result = Zero;
582 if (NumUses == 1) {
583 std::swap(Result, Uses[0].Base);
584 return Result;
585 }
586
587 // To find common subexpressions, count how many of Uses use each expression.
588 // If any subexpressions are used Uses.size() times, they are common.
589 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
590
591 for (unsigned i = 0; i != NumUses; ++i)
592 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
593 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
594 SubExpressionUseCounts[AE->getOperand(j)]++;
595 } else {
596 // If the base is zero (which is common), return zero now, there are no
597 // CSEs we can find.
598 if (Uses[i].Base == Zero) return Result;
599 SubExpressionUseCounts[Uses[i].Base]++;
600 }
601
602 // Now that we know how many times each is used, build Result.
603 for (std::map<SCEVHandle, unsigned>::iterator I =
604 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
605 I != E; )
606 if (I->second == NumUses) { // Found CSE!
607 Result = SCEVAddExpr::get(Result, I->first);
608 ++I;
609 } else {
610 // Remove non-cse's from SubExpressionUseCounts.
611 SubExpressionUseCounts.erase(I++);
612 }
613
614 // If we found no CSE's, return now.
615 if (Result == Zero) return Result;
616
617 // Otherwise, remove all of the CSE's we found from each of the base values.
618 for (unsigned i = 0; i != NumUses; ++i)
619 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Uses[i].Base)) {
620 std::vector<SCEVHandle> NewOps;
621
622 // Remove all of the values that are now in SubExpressionUseCounts.
623 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
624 if (!SubExpressionUseCounts.count(AE->getOperand(j)))
625 NewOps.push_back(AE->getOperand(j));
Chris Lattner02742712005-08-09 01:13:47 +0000626 if (NewOps.size() == 0)
627 Uses[i].Base = Zero;
628 else
629 Uses[i].Base = SCEVAddExpr::get(NewOps);
Chris Lattnera091ff12005-08-09 00:18:09 +0000630 } else {
631 // If the base is zero (which is common), return zero now, there are no
632 // CSEs we can find.
633 assert(Uses[i].Base == Result);
634 Uses[i].Base = Zero;
635 }
636
637 return Result;
638}
639
640
Nate Begemane68bcd12005-07-30 00:15:07 +0000641/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
642/// stride of IV. All of the users may have different starting values, and this
643/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000644void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000645 IVUsersOfOneStride &Uses,
646 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000647 bool isOnlyStride) {
648 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000649 // this new vector, each 'BasedUser' contains 'Base' the base of the
650 // strided accessas well as the old information from Uses. We progressively
651 // move information from the Base field to the Imm field, until we eventually
652 // have the full access expression to rewrite the use.
653 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000654 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000655 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
656 UsersToProcess.push_back(Uses.Users[i]);
657
658 // Move any loop invariant operands from the offset field to the immediate
659 // field of the use, so that we don't try to use something before it is
660 // computed.
661 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
662 UsersToProcess.back().Imm, L);
663 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000664 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000665 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000666
Chris Lattnera091ff12005-08-09 00:18:09 +0000667 // We now have a whole bunch of uses of like-strided induction variables, but
668 // they might all have different bases. We want to emit one PHI node for this
669 // stride which we fold as many common expressions (between the IVs) into as
670 // possible. Start by identifying the common expressions in the base values
671 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
672 // "A+B"), emit it to the preheader, then remove the expression from the
673 // UsersToProcess base values.
674 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
675
Chris Lattner37ed8952005-08-08 22:32:34 +0000676 // Next, figure out what we can represent in the immediate fields of
677 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000678 // fields of the BasedUsers. We do this so that it increases the commonality
679 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000680 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
681 // Addressing modes can be folded into loads and stores. Be careful that
682 // the store is through the expression, not of the expression though.
Chris Lattner37c24cc2005-08-08 22:56:21 +0000683 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
684 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
685 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
Chris Lattner37ed8952005-08-08 22:32:34 +0000686 isAddress = true;
687
Chris Lattner37c24cc2005-08-08 22:56:21 +0000688 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner37ed8952005-08-08 22:32:34 +0000689 isAddress, L);
690 }
691
Chris Lattnera091ff12005-08-09 00:18:09 +0000692 // Now that we know what we need to do, insert the PHI node itself.
693 //
694 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
695 << *CommonExprs << " :\n");
696
697 SCEVExpander Rewriter(*SE, *LI);
698 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000699
Chris Lattnera091ff12005-08-09 00:18:09 +0000700 BasicBlock *Preheader = L->getLoopPreheader();
701 Instruction *PreInsertPt = Preheader->getTerminator();
702 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000703
Chris Lattnera091ff12005-08-09 00:18:09 +0000704 assert(isa<PHINode>(PhiInsertBefore) &&
705 "How could this loop have IV's without any phis?");
706 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
707 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
708 "This loop isn't canonicalized right");
709 BasicBlock *LatchBlock =
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000710 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Chris Lattnerbb78c972005-08-03 23:30:08 +0000711
Chris Lattnera091ff12005-08-09 00:18:09 +0000712 // Create a new Phi for this base, and stick it in the loop header.
713 const Type *ReplacedTy = CommonExprs->getType();
714 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
715 ++NumInserted;
716
Chris Lattneredff91a2005-08-10 00:45:21 +0000717 // Insert the stride into the preheader.
718 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
719 ReplacedTy);
720 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
721
722
Chris Lattnera091ff12005-08-09 00:18:09 +0000723 // Emit the initial base value into the loop preheader, and add it to the
724 // Phi node.
725 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
726 ReplacedTy);
727 NewPHI->addIncoming(PHIBaseV, Preheader);
728
729 // Emit the increment of the base value before the terminator of the loop
730 // latch block, and add it to the Phi node.
731 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
Chris Lattneredff91a2005-08-10 00:45:21 +0000732 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +0000733
734 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
735 ReplacedTy);
736 IncV->setName(NewPHI->getName()+".inc");
737 NewPHI->addIncoming(IncV, LatchBlock);
738
Chris Lattnerdb23c742005-08-03 22:51:21 +0000739 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +0000740 // each other.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000741 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000742 while (!UsersToProcess.empty()) {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000743 SCEVHandle Base = UsersToProcess.front().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000744
Chris Lattnera091ff12005-08-09 00:18:09 +0000745 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +0000746
Chris Lattnera091ff12005-08-09 00:18:09 +0000747 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000748 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
749 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +0000750
751 // If BaseV is a constant other than 0, make sure that it gets inserted into
752 // the preheader, instead of being forward substituted into the uses. We do
753 // this by forcing a noop cast to be inserted into the preheader in this
754 // case.
755 if (Constant *C = dyn_cast<Constant>(BaseV))
756 if (!C->isNullValue()) {
757 // We want this constant emitted into the preheader!
758 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
759 PreInsertPt);
760 }
761
Nate Begemane68bcd12005-07-30 00:15:07 +0000762 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000763 // the instructions that we identified as using this stride and base.
Chris Lattner37c24cc2005-08-08 22:56:21 +0000764 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
765 BasedUser &User = UsersToProcess.front();
Jeff Cohen546fd592005-07-30 18:33:25 +0000766
Chris Lattnera091ff12005-08-09 00:18:09 +0000767 // If this instruction wants to use the post-incremented value, move it
768 // after the post-inc and use its value instead of the PHI.
769 Value *RewriteOp = NewPHI;
770 if (User.isUseOfPostIncrementedValue) {
771 RewriteOp = IncV;
772 User.Inst->moveBefore(LatchBlock->getTerminator());
773 }
774 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
775
Chris Lattnerdb23c742005-08-03 22:51:21 +0000776 // Clear the SCEVExpander's expression map so that we are guaranteed
777 // to have the code emitted where we expect it.
778 Rewriter.clear();
Chris Lattnera091ff12005-08-09 00:18:09 +0000779
Chris Lattnera6d7c352005-08-04 20:03:32 +0000780 // Now that we know what we need to do, insert code before User for the
781 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +0000782 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
783 // Add BaseV to the PHI value if needed.
784 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
785
786 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter);
Jeff Cohen546fd592005-07-30 18:33:25 +0000787
Chris Lattnerdb23c742005-08-03 22:51:21 +0000788 // Mark old value we replaced as possibly dead, so that it is elminated
789 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000790 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000791
Chris Lattnerdb23c742005-08-03 22:51:21 +0000792 UsersToProcess.erase(UsersToProcess.begin());
793 ++NumReduced;
794 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000795 // TODO: Next, find out which base index is the most common, pull it out.
796 }
797
798 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
799 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +0000800}
801
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000802// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
803// uses in the loop, look to see if we can eliminate some, in favor of using
804// common indvars for the different uses.
805void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
806 // TODO: implement optzns here.
807
808
809
810
811 // Finally, get the terminating condition for the loop if possible. If we
812 // can, we want to change it to use a post-incremented version of its
813 // induction variable, to allow coallescing the live ranges for the IV into
814 // one register value.
815 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
816 BasicBlock *Preheader = L->getLoopPreheader();
817 BasicBlock *LatchBlock =
818 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
819 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
820 if (!TermBr || TermBr->isUnconditional() ||
821 !isa<SetCondInst>(TermBr->getCondition()))
822 return;
823 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
824
825 // Search IVUsesByStride to find Cond's IVUse if there is one.
826 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +0000827 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000828
Chris Lattneredff91a2005-08-10 00:45:21 +0000829 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator
830 I = IVUsesByStride.begin(), E = IVUsesByStride.end();
831 I != E && !CondUse; ++I)
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000832 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
833 E = I->second.Users.end(); UI != E; ++UI)
834 if (UI->User == Cond) {
835 CondUse = &*UI;
Chris Lattneredff91a2005-08-10 00:45:21 +0000836 CondStride = &I->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000837 // NOTE: we could handle setcc instructions with multiple uses here, but
838 // InstCombine does it as well for simple uses, it's not clear that it
839 // occurs enough in real life to handle.
840 break;
841 }
842 if (!CondUse) return; // setcc doesn't use the IV.
843
844 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +0000845 // FIXME: Evaluate whether this is a good idea or not.
846 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000847
848 // It's possible for the setcc instruction to be anywhere in the loop, and
849 // possible for it to have multiple users. If it is not immediately before
850 // the latch block branch, move it.
851 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
852 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
853 Cond->moveBefore(TermBr);
854 } else {
855 // Otherwise, clone the terminating condition and insert into the loopend.
856 Cond = cast<SetCondInst>(Cond->clone());
857 Cond->setName(L->getHeader()->getName() + ".termcond");
858 LatchBlock->getInstList().insert(TermBr, Cond);
859
860 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +0000861 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000862 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +0000863 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000864 }
865 }
866
867 // If we get to here, we know that we can transform the setcc instruction to
868 // use the post-incremented version of the IV, allowing us to coallesce the
869 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +0000870 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000871 CondUse->isUseOfPostIncrementedValue = true;
872}
Nate Begemane68bcd12005-07-30 00:15:07 +0000873
Nate Begemanb18121e2004-10-18 21:08:22 +0000874void LoopStrengthReduce::runOnLoop(Loop *L) {
875 // First step, transform all loops nesting inside of this loop.
876 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
877 runOnLoop(*I);
878
Nate Begemane68bcd12005-07-30 00:15:07 +0000879 // Next, find all uses of induction variables in this loop, and catagorize
880 // them by stride. Start by finding all of the PHI nodes in the header for
881 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +0000882 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +0000883 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +0000884 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +0000885
Nate Begemane68bcd12005-07-30 00:15:07 +0000886 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000887 if (IVUsesByStride.empty()) return;
888
889 // Optimize induction variables. Some indvar uses can be transformed to use
890 // strides that will be needed for other purposes. A common example of this
891 // is the exit test for the loop, which can often be rewritten to use the
892 // computation of some other indvar to decide when to terminate the loop.
893 OptimizeIndvars(L);
894
Misha Brukmanb1c93172005-04-21 23:48:37 +0000895
Nate Begemane68bcd12005-07-30 00:15:07 +0000896 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
897 // doing computation in byte values, promote to 32-bit values if safe.
898
899 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
900 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
901 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
902 // to be careful that IV's are all the same type. Only works for intptr_t
903 // indvars.
904
905 // If we only have one stride, we can more aggressively eliminate some things.
906 bool HasOneStride = IVUsesByStride.size() == 1;
907
Chris Lattnera091ff12005-08-09 00:18:09 +0000908 // Note: this processes each stride/type pair individually. All users passed
909 // into StrengthReduceStridedIVUsers have the same type AND stride.
Chris Lattneredff91a2005-08-10 00:45:21 +0000910 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
Chris Lattner430d0022005-08-03 22:21:05 +0000911 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000912 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000913
914 // Clean up after ourselves
915 if (!DeadInsts.empty()) {
916 DeleteTriviallyDeadInstructions(DeadInsts);
917
Nate Begemane68bcd12005-07-30 00:15:07 +0000918 BasicBlock::iterator I = L->getHeader()->begin();
919 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000920 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000921 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
922
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000923 // At this point, we know that we have killed one or more GEP
924 // instructions. It is worth checking to see if the cann indvar is also
925 // dead, so that we can remove it as well. The requirements for the cann
926 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +0000927 // 1. the cann indvar has one use
928 // 2. the use is an add instruction
929 // 3. the add has one use
930 // 4. the add is used by the cann indvar
931 // If all four cases above are true, then we can remove both the add and
932 // the cann indvar.
933 // FIXME: this needs to eliminate an induction variable even if it's being
934 // compared against some value to decide loop termination.
935 if (PN->hasOneUse()) {
936 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000937 if (BO && BO->hasOneUse()) {
938 if (PN == *(BO->use_begin())) {
939 DeadInsts.insert(BO);
940 // Break the cycle, then delete the PHI.
941 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000942 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000943 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000944 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000945 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000946 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000947 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000948 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000949 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000950
Chris Lattner11e7a5e2005-08-05 01:30:11 +0000951 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +0000952 IVUsesByStride.clear();
953 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000954}