blob: 614904561d8442416ab8a01cd8ce77393f88eb46 [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner4fec86d2005-08-12 22:06:11 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000030#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000031#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000032#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000033#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000034#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000035#include <set>
36using namespace llvm;
37
38namespace {
39 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000040 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattneredff91a2005-08-10 00:45:21 +000041 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000042
Chris Lattner430d0022005-08-03 22:21:05 +000043 /// IVStrideUse - Keep track of one use of a strided induction variable, where
44 /// the stride is stored externally. The Offset member keeps track of the
45 /// offset from the IV, User is the actual user of the operand, and 'Operand'
46 /// is the operand # of the User that is the use.
47 struct IVStrideUse {
48 SCEVHandle Offset;
49 Instruction *User;
50 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000051
52 // isUseOfPostIncrementedValue - True if this should use the
53 // post-incremented version of this IV, not the preincremented version.
54 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000055 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000056 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000057
58 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000059 : Offset(Offs), User(U), OperandValToReplace(O),
60 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000061 };
62
63 /// IVUsersOfOneStride - This structure keeps track of all instructions that
64 /// have an operand that is based on the trip count multiplied by some stride.
65 /// The stride for all of these users is common and kept external to this
66 /// structure.
67 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000068 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000069 /// initial value and the operand that uses the IV.
70 std::vector<IVStrideUse> Users;
71
72 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
73 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000074 }
75 };
76
77
Nate Begemanb18121e2004-10-18 21:08:22 +000078 class LoopStrengthReduce : public FunctionPass {
79 LoopInfo *LI;
80 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000081 ScalarEvolution *SE;
82 const TargetData *TD;
83 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000084 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000085
86 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
87 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000088 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000089
90 /// IVUsesByStride - Keep track of all uses of induction variables that we
91 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +000092 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000093
Chris Lattner6f286b72005-08-04 01:19:13 +000094 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
95 /// of the casted version of each value. This is accessed by
96 /// getCastedVersionOf.
97 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +000098
99 /// DeadInsts - Keep track of instructions we may have made dead, so that
100 /// we can remove them after we are done working.
101 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +0000102 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000103 LoopStrengthReduce(unsigned MTAMS = 1)
104 : MaxTargetAMSize(MTAMS) {
105 }
106
Nate Begemanb18121e2004-10-18 21:08:22 +0000107 virtual bool runOnFunction(Function &) {
108 LI = &getAnalysis<LoopInfo>();
109 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000110 SE = &getAnalysis<ScalarEvolution>();
111 TD = &getAnalysis<TargetData>();
112 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000113 Changed = false;
114
115 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
116 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000117
Nate Begemanb18121e2004-10-18 21:08:22 +0000118 return Changed;
119 }
120
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000122 // We split critical edges, so we change the CFG. However, we do update
123 // many analyses if they are around.
124 AU.addPreservedID(LoopSimplifyID);
125 AU.addPreserved<LoopInfo>();
126 AU.addPreserved<DominatorSet>();
127 AU.addPreserved<ImmediateDominators>();
128 AU.addPreserved<DominanceFrontier>();
129 AU.addPreserved<DominatorTree>();
130
Jeff Cohen39751c32005-02-27 19:37:07 +0000131 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000132 AU.addRequired<LoopInfo>();
133 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000134 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000135 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000136 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000137
138 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
139 ///
140 Value *getCastedVersionOf(Value *V);
141private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000142 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000143 bool AddUsersIfInteresting(Instruction *I, Loop *L,
144 std::set<Instruction*> &Processed);
145 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
146
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000147 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000148
Chris Lattneredff91a2005-08-10 00:45:21 +0000149 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
150 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000151 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000152 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
153 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000154 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Chris Lattner92233d22005-09-27 21:10:32 +0000155 "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000156}
157
Jeff Cohena2c59b72005-03-04 04:04:26 +0000158FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
159 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000160}
161
Chris Lattner6f286b72005-08-04 01:19:13 +0000162/// getCastedVersionOf - Return the specified value casted to uintptr_t.
163///
164Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
165 if (V->getType() == UIntPtrTy) return V;
166 if (Constant *CB = dyn_cast<Constant>(V))
167 return ConstantExpr::getCast(CB, UIntPtrTy);
168
169 Value *&New = CastedPointers[V];
170 if (New) return New;
171
172 BasicBlock::iterator InsertPt;
173 if (Argument *Arg = dyn_cast<Argument>(V)) {
174 // Insert into the entry of the function, after any allocas.
175 InsertPt = Arg->getParent()->begin()->begin();
176 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
177 } else {
178 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
179 InsertPt = II->getNormalDest()->begin();
180 } else {
181 InsertPt = cast<Instruction>(V);
182 ++InsertPt;
183 }
184
185 // Do not insert casts into the middle of PHI node blocks.
186 while (isa<PHINode>(InsertPt)) ++InsertPt;
187 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000188
189 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
190 DeadInsts.insert(cast<Instruction>(New));
191 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000192}
193
194
Nate Begemanb18121e2004-10-18 21:08:22 +0000195/// DeleteTriviallyDeadInstructions - If any of the instructions is the
196/// specified set are trivially dead, delete them and see if this makes any of
197/// their operands subsequently dead.
198void LoopStrengthReduce::
199DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
200 while (!Insts.empty()) {
201 Instruction *I = *Insts.begin();
202 Insts.erase(Insts.begin());
203 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000204 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
205 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
206 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000207 SE->deleteInstructionFromRecords(I);
208 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000209 Changed = true;
210 }
211 }
212}
213
Jeff Cohen39751c32005-02-27 19:37:07 +0000214
Chris Lattnereaf24722005-08-04 17:40:30 +0000215/// GetExpressionSCEV - Compute and return the SCEV for the specified
216/// instruction.
217SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000218 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
219 // If this is a GEP that SE doesn't know about, compute it now and insert it.
220 // If this is not a GEP, or if we have already done this computation, just let
221 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000222 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000223 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000224 return SE->getSCEV(Exp);
225
Nate Begemane68bcd12005-07-30 00:15:07 +0000226 // Analyze all of the subscripts of this getelementptr instruction, looking
227 // for uses that are determined by the trip count of L. First, skip all
228 // operands the are not dependent on the IV.
229
230 // Build up the base expression. Insert an LLVM cast of the pointer to
231 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000232 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000233
234 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000235
236 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000237 // If this is a use of a recurrence that we can analyze, and it comes before
238 // Op does in the GEP operand list, we will handle this when we process this
239 // operand.
240 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
241 const StructLayout *SL = TD->getStructLayout(STy);
242 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
243 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000244 GEPVal = SCEVAddExpr::get(GEPVal,
245 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000246 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000247 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
248 SCEVHandle Idx = SE->getSCEV(OpVal);
249
Chris Lattnereaf24722005-08-04 17:40:30 +0000250 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
251 if (TypeSize != 1)
252 Idx = SCEVMulExpr::get(Idx,
253 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
254 TypeSize)));
255 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000256 }
257 }
258
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000259 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000260 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000261}
262
Chris Lattneracc42c42005-08-04 19:08:16 +0000263/// getSCEVStartAndStride - Compute the start and stride of this expression,
264/// returning false if the expression is not a start/stride pair, or true if it
265/// is. The stride must be a loop invariant expression, but the start may be
266/// a mix of loop invariant and loop variant expressions.
267static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000268 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000269 SCEVHandle TheAddRec = Start; // Initialize to zero.
270
271 // If the outer level is an AddExpr, the operands are all start values except
272 // for a nested AddRecExpr.
273 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
274 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
275 if (SCEVAddRecExpr *AddRec =
276 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
277 if (AddRec->getLoop() == L)
278 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
279 else
280 return false; // Nested IV of some sort?
281 } else {
282 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
283 }
284
285 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
286 TheAddRec = SH;
287 } else {
288 return false; // not analyzable.
289 }
290
291 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
292 if (!AddRec || AddRec->getLoop() != L) return false;
293
294 // FIXME: Generalize to non-affine IV's.
295 if (!AddRec->isAffine()) return false;
296
297 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
298
Chris Lattneracc42c42005-08-04 19:08:16 +0000299 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000300 DEBUG(std::cerr << "[" << L->getHeader()->getName()
301 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000302
Chris Lattneredff91a2005-08-10 00:45:21 +0000303 Stride = AddRec->getOperand(1);
304 // Check that all constant strides are the unsigned type, we don't want to
305 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
306 // merged.
307 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000308 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000309
Chris Lattneracc42c42005-08-04 19:08:16 +0000310 return true;
311}
312
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000313/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
314/// and now we need to decide whether the user should use the preinc or post-inc
315/// value. If this user should use the post-inc version of the IV, return true.
316///
317/// Choosing wrong here can break dominance properties (if we choose to use the
318/// post-inc value when we cannot) or it can end up adding extra live-ranges to
319/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
320/// should use the post-inc value).
321static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnerf07a5872005-10-03 02:50:05 +0000322 Loop *L, DominatorSet *DS, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000323 // If the user is in the loop, use the preinc value.
324 if (L->contains(User->getParent())) return false;
325
Chris Lattnerf07a5872005-10-03 02:50:05 +0000326 BasicBlock *LatchBlock = L->getLoopLatch();
327
328 // Ok, the user is outside of the loop. If it is dominated by the latch
329 // block, use the post-inc value.
330 if (DS->dominates(LatchBlock, User->getParent()))
331 return true;
332
333 // There is one case we have to be careful of: PHI nodes. These little guys
334 // can live in blocks that do not dominate the latch block, but (since their
335 // uses occur in the predecessor block, not the block the PHI lives in) should
336 // still use the post-inc value. Check for this case now.
337 PHINode *PN = dyn_cast<PHINode>(User);
338 if (!PN) return false; // not a phi, not dominated by latch block.
339
340 // Look at all of the uses of IV by the PHI node. If any use corresponds to
341 // a block that is not dominated by the latch block, give up and use the
342 // preincremented value.
343 unsigned NumUses = 0;
344 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
345 if (PN->getIncomingValue(i) == IV) {
346 ++NumUses;
347 if (!DS->dominates(LatchBlock, PN->getIncomingBlock(i)))
348 return false;
349 }
350
351 // Okay, all uses of IV by PN are in predecessor blocks that really are
352 // dominated by the latch block. Split the critical edges and use the
353 // post-incremented value.
354 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
355 if (PN->getIncomingValue(i) == IV) {
356 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
357 if (--NumUses == 0) break;
358 }
359
360 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000361}
362
363
364
Nate Begemane68bcd12005-07-30 00:15:07 +0000365/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
366/// reducible SCEV, recursively add its users to the IVUsesByStride set and
367/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000368bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
369 std::set<Instruction*> &Processed) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000370 if (I->getType() == Type::VoidTy) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000371 if (!Processed.insert(I).second)
372 return true; // Instruction already handled.
373
Chris Lattneracc42c42005-08-04 19:08:16 +0000374 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000375 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000376 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000377
Chris Lattneracc42c42005-08-04 19:08:16 +0000378 // Get the start and stride for this expression.
379 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000380 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000381 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
382 return false; // Non-reducible symbolic expression, bail out.
383
Nate Begemane68bcd12005-07-30 00:15:07 +0000384 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
385 Instruction *User = cast<Instruction>(*UI);
386
387 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000388 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000389 continue;
390
391 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000392 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000393 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000394 if (LI->getLoopFor(User->getParent()) != L) {
Chris Lattnerfd018c82005-09-13 02:09:55 +0000395 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
Chris Lattnera0102fb2005-08-04 00:14:11 +0000396 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000397 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000398 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000399 DEBUG(std::cerr << "FOUND USER: " << *User
400 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000401 AddUserToIVUsers = true;
402 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000403
Chris Lattneracc42c42005-08-04 19:08:16 +0000404 if (AddUserToIVUsers) {
Chris Lattner65107492005-08-04 00:40:47 +0000405 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000406 // and decide what to do with it. If we are a use inside of the loop, use
407 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnerf07a5872005-10-03 02:50:05 +0000408 if (IVUseShouldUsePostIncValue(User, I, L, DS, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000409 // The value used will be incremented by the stride more than we are
410 // expecting, so subtract this off.
411 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
412 IVUsesByStride[Stride].addUser(NewStart, User, I);
413 IVUsesByStride[Stride].Users.back().isUseOfPostIncrementedValue = true;
Chris Lattnerf07a5872005-10-03 02:50:05 +0000414 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000415 } else {
416 IVUsesByStride[Stride].addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000417 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000418 }
419 }
420 return true;
421}
422
423namespace {
424 /// BasedUser - For a particular base value, keep information about how we've
425 /// partitioned the expression so far.
426 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000427 /// Base - The Base value for the PHI node that needs to be inserted for
428 /// this use. As the use is processed, information gets moved from this
429 /// field to the Imm field (below). BasedUser values are sorted by this
430 /// field.
431 SCEVHandle Base;
432
Nate Begemane68bcd12005-07-30 00:15:07 +0000433 /// Inst - The instruction using the induction variable.
434 Instruction *Inst;
435
Chris Lattner430d0022005-08-03 22:21:05 +0000436 /// OperandValToReplace - The operand value of Inst to replace with the
437 /// EmittedBase.
438 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000439
440 /// Imm - The immediate value that should be added to the base immediately
441 /// before Inst, because it will be folded into the imm field of the
442 /// instruction.
443 SCEVHandle Imm;
444
445 /// EmittedBase - The actual value* to use for the base value of this
446 /// operation. This is null if we should just use zero so far.
447 Value *EmittedBase;
448
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000449 // isUseOfPostIncrementedValue - True if this should use the
450 // post-incremented version of this IV, not the preincremented version.
451 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000452 // instruction for a loop and uses outside the loop that are dominated by
453 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000454 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000455
456 BasedUser(IVStrideUse &IVSU)
457 : Base(IVSU.Offset), Inst(IVSU.User),
458 OperandValToReplace(IVSU.OperandValToReplace),
459 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
460 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000461
Chris Lattnera6d7c352005-08-04 20:03:32 +0000462 // Once we rewrite the code to insert the new IVs we want, update the
463 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
464 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000465 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000466 SCEVExpander &Rewriter, Loop *L,
467 Pass *P);
Nate Begemane68bcd12005-07-30 00:15:07 +0000468
Chris Lattner37c24cc2005-08-08 22:56:21 +0000469 // Sort by the Base field.
470 bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
Nate Begemane68bcd12005-07-30 00:15:07 +0000471
472 void dump() const;
473 };
474}
475
476void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000477 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000478 std::cerr << " Imm=" << *Imm;
479 if (EmittedBase)
480 std::cerr << " EB=" << *EmittedBase;
481
482 std::cerr << " Inst: " << *Inst;
483}
484
Chris Lattnera6d7c352005-08-04 20:03:32 +0000485// Once we rewrite the code to insert the new IVs we want, update the
486// operands of Inst to use the new expression 'NewBase', with 'Imm' added
487// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000488void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000489 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000490 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000491 if (!isa<PHINode>(Inst)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000492 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000493 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
494 OperandValToReplace->getType());
Chris Lattnera6d7c352005-08-04 20:03:32 +0000495 // Replace the use of the operand Value with the new Phi we just created.
496 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
497 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
498 return;
499 }
500
501 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000502 // expression into each operand block that uses it. Note that PHI nodes can
503 // have multiple entries for the same predecessor. We use a map to make sure
504 // that a PHI node only has a single Value* for each predecessor (which also
505 // prevents us from inserting duplicate code in some blocks).
506 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000507 PHINode *PN = cast<PHINode>(Inst);
508 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
509 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000510 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000511 // code on all predecessor/successor paths. We do this unless this is the
512 // canonical backedge for this loop, as this can make some inserted code
513 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000514 BasicBlock *PHIPred = PN->getIncomingBlock(i);
515 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
516 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000517
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000518 // First step, split the critical edge.
Chris Lattner8fcce172005-10-03 00:31:52 +0000519 SplitCriticalEdge(PHIPred, PN->getParent(), P);
Chris Lattner8447b492005-08-12 22:22:17 +0000520
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000521 // Next step: move the basic block. In particular, if the PHI node
522 // is outside of the loop, and PredTI is in the loop, we want to
523 // move the block to be immediately before the PHI block, not
524 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000525 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000526 BasicBlock *NewBB = PN->getIncomingBlock(i);
527 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000528 }
529 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000530
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000531 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
532 if (!Code) {
533 // Insert the code into the end of the predecessor block.
534 BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
Chris Lattnera6d7c352005-08-04 20:03:32 +0000535
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000536 SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
537 Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
538 OperandValToReplace->getType());
539 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000540
541 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000542 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000543 Rewriter.clear();
544 }
545 }
546 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
547}
548
549
Nate Begemane68bcd12005-07-30 00:15:07 +0000550/// isTargetConstant - Return true if the following can be referenced by the
551/// immediate field of a target instruction.
552static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000553
Nate Begemane68bcd12005-07-30 00:15:07 +0000554 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner14203e82005-08-08 06:25:50 +0000555 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
556 // PPC allows a sign-extended 16-bit immediate field.
557 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
558 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
559 return true;
560 return false;
561 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000562
Nate Begemane68bcd12005-07-30 00:15:07 +0000563 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000564
Nate Begemane68bcd12005-07-30 00:15:07 +0000565 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
566 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
567 if (CE->getOpcode() == Instruction::Cast)
568 if (isa<GlobalValue>(CE->getOperand(0)))
569 // FIXME: should check to see that the dest is uintptr_t!
570 return true;
571 return false;
572}
573
Chris Lattner37ed8952005-08-08 22:32:34 +0000574/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
575/// loop varying to the Imm operand.
576static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
577 Loop *L) {
578 if (Val->isLoopInvariant(L)) return; // Nothing to do.
579
580 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
581 std::vector<SCEVHandle> NewOps;
582 NewOps.reserve(SAE->getNumOperands());
583
584 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
585 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
586 // If this is a loop-variant expression, it must stay in the immediate
587 // field of the expression.
588 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
589 } else {
590 NewOps.push_back(SAE->getOperand(i));
591 }
592
593 if (NewOps.empty())
594 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
595 else
596 Val = SCEVAddExpr::get(NewOps);
597 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
598 // Try to pull immediates out of the start value of nested addrec's.
599 SCEVHandle Start = SARE->getStart();
600 MoveLoopVariantsToImediateField(Start, Imm, L);
601
602 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
603 Ops[0] = Start;
604 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
605 } else {
606 // Otherwise, all of Val is variant, move the whole thing over.
607 Imm = SCEVAddExpr::get(Imm, Val);
608 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
609 }
610}
611
612
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000613/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000614/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000615/// Accumulate these immediate values into the Imm value.
616static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
617 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000618 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000619 std::vector<SCEVHandle> NewOps;
620 NewOps.reserve(SAE->getNumOperands());
621
622 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattneracc42c42005-08-04 19:08:16 +0000623 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
624 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
625 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
626 // If this is a loop-variant expression, it must stay in the immediate
627 // field of the expression.
628 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000629 } else {
630 NewOps.push_back(SAE->getOperand(i));
Nate Begemane68bcd12005-07-30 00:15:07 +0000631 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000632
633 if (NewOps.empty())
634 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
635 else
636 Val = SCEVAddExpr::get(NewOps);
637 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000638 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
639 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000640 SCEVHandle Start = SARE->getStart();
641 MoveImmediateValues(Start, Imm, isAddress, L);
642
643 if (Start != SARE->getStart()) {
644 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
645 Ops[0] = Start;
646 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
647 }
648 return;
Nate Begemane68bcd12005-07-30 00:15:07 +0000649 }
650
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000651 // Loop-variant expressions must stay in the immediate field of the
652 // expression.
653 if ((isAddress && isTargetConstant(Val)) ||
654 !Val->isLoopInvariant(L)) {
655 Imm = SCEVAddExpr::get(Imm, Val);
656 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
657 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000658 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000659
660 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000661}
662
Chris Lattner5949d492005-08-13 07:27:18 +0000663
664/// IncrementAddExprUses - Decompose the specified expression into its added
665/// subexpressions, and increment SubExpressionUseCounts for each of these
666/// decomposed parts.
667static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
668 SCEVHandle Expr) {
669 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
670 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
671 SeparateSubExprs(SubExprs, AE->getOperand(j));
672 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
673 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
674 if (SARE->getOperand(0) == Zero) {
675 SubExprs.push_back(Expr);
676 } else {
677 // Compute the addrec with zero as its base.
678 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
679 Ops[0] = Zero; // Start with zero base.
680 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
681
682
683 SeparateSubExprs(SubExprs, SARE->getOperand(0));
684 }
685 } else if (!isa<SCEVConstant>(Expr) ||
686 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
687 // Do not add zero.
688 SubExprs.push_back(Expr);
689 }
690}
691
692
Chris Lattnera091ff12005-08-09 00:18:09 +0000693/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
694/// removing any common subexpressions from it. Anything truly common is
695/// removed, accumulated, and returned. This looks for things like (a+b+c) and
696/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
697static SCEVHandle
698RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
699 unsigned NumUses = Uses.size();
700
701 // Only one use? Use its base, regardless of what it is!
702 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
703 SCEVHandle Result = Zero;
704 if (NumUses == 1) {
705 std::swap(Result, Uses[0].Base);
706 return Result;
707 }
708
709 // To find common subexpressions, count how many of Uses use each expression.
710 // If any subexpressions are used Uses.size() times, they are common.
711 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
712
Chris Lattner5949d492005-08-13 07:27:18 +0000713 std::vector<SCEVHandle> SubExprs;
714 for (unsigned i = 0; i != NumUses; ++i) {
715 // If the base is zero (which is common), return zero now, there are no
716 // CSEs we can find.
717 if (Uses[i].Base == Zero) return Zero;
718
719 // Split the expression into subexprs.
720 SeparateSubExprs(SubExprs, Uses[i].Base);
721 // Add one to SubExpressionUseCounts for each subexpr present.
722 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
723 SubExpressionUseCounts[SubExprs[j]]++;
724 SubExprs.clear();
725 }
726
727
Chris Lattnera091ff12005-08-09 00:18:09 +0000728 // Now that we know how many times each is used, build Result.
729 for (std::map<SCEVHandle, unsigned>::iterator I =
730 SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
731 I != E; )
732 if (I->second == NumUses) { // Found CSE!
733 Result = SCEVAddExpr::get(Result, I->first);
734 ++I;
735 } else {
736 // Remove non-cse's from SubExpressionUseCounts.
737 SubExpressionUseCounts.erase(I++);
738 }
739
740 // If we found no CSE's, return now.
741 if (Result == Zero) return Result;
742
743 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000744 for (unsigned i = 0; i != NumUses; ++i) {
745 // Split the expression into subexprs.
746 SeparateSubExprs(SubExprs, Uses[i].Base);
747
748 // Remove any common subexpressions.
749 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
750 if (SubExpressionUseCounts.count(SubExprs[j])) {
751 SubExprs.erase(SubExprs.begin()+j);
752 --j; --e;
753 }
754
755 // Finally, the non-shared expressions together.
756 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000757 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000758 else
759 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000760 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000761 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000762
763 return Result;
764}
765
766
Nate Begemane68bcd12005-07-30 00:15:07 +0000767/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
768/// stride of IV. All of the users may have different starting values, and this
769/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000770void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000771 IVUsersOfOneStride &Uses,
772 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000773 bool isOnlyStride) {
774 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000775 // this new vector, each 'BasedUser' contains 'Base' the base of the
776 // strided accessas well as the old information from Uses. We progressively
777 // move information from the Base field to the Imm field, until we eventually
778 // have the full access expression to rewrite the use.
779 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000780 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000781 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
782 UsersToProcess.push_back(Uses.Users[i]);
783
784 // Move any loop invariant operands from the offset field to the immediate
785 // field of the use, so that we don't try to use something before it is
786 // computed.
787 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
788 UsersToProcess.back().Imm, L);
789 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000790 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000791 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000792
Chris Lattnera091ff12005-08-09 00:18:09 +0000793 // We now have a whole bunch of uses of like-strided induction variables, but
794 // they might all have different bases. We want to emit one PHI node for this
795 // stride which we fold as many common expressions (between the IVs) into as
796 // possible. Start by identifying the common expressions in the base values
797 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
798 // "A+B"), emit it to the preheader, then remove the expression from the
799 // UsersToProcess base values.
800 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
801
Chris Lattner37ed8952005-08-08 22:32:34 +0000802 // Next, figure out what we can represent in the immediate fields of
803 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000804 // fields of the BasedUsers. We do this so that it increases the commonality
805 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000806 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000807 // If the user is not in the current loop, this means it is using the exit
808 // value of the IV. Do not put anything in the base, make sure it's all in
809 // the immediate field to allow as much factoring as possible.
810 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000811 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
812 UsersToProcess[i].Base);
813 UsersToProcess[i].Base =
814 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000815 } else {
816
817 // Addressing modes can be folded into loads and stores. Be careful that
818 // the store is through the expression, not of the expression though.
819 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
820 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
821 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
822 isAddress = true;
823
824 MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
825 isAddress, L);
826 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000827 }
828
Chris Lattnera091ff12005-08-09 00:18:09 +0000829 // Now that we know what we need to do, insert the PHI node itself.
830 //
831 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
832 << *CommonExprs << " :\n");
833
834 SCEVExpander Rewriter(*SE, *LI);
835 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000836
Chris Lattnera091ff12005-08-09 00:18:09 +0000837 BasicBlock *Preheader = L->getLoopPreheader();
838 Instruction *PreInsertPt = Preheader->getTerminator();
839 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000840
Chris Lattner8048b852005-09-12 17:11:27 +0000841 BasicBlock *LatchBlock = L->getLoopLatch();
Chris Lattnerbb78c972005-08-03 23:30:08 +0000842
Chris Lattnera091ff12005-08-09 00:18:09 +0000843 // Create a new Phi for this base, and stick it in the loop header.
844 const Type *ReplacedTy = CommonExprs->getType();
845 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
846 ++NumInserted;
847
Chris Lattneredff91a2005-08-10 00:45:21 +0000848 // Insert the stride into the preheader.
849 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
850 ReplacedTy);
851 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
852
853
Chris Lattnera091ff12005-08-09 00:18:09 +0000854 // Emit the initial base value into the loop preheader, and add it to the
855 // Phi node.
856 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
857 ReplacedTy);
858 NewPHI->addIncoming(PHIBaseV, Preheader);
859
860 // Emit the increment of the base value before the terminator of the loop
861 // latch block, and add it to the Phi node.
862 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
Chris Lattneredff91a2005-08-10 00:45:21 +0000863 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +0000864
865 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
866 ReplacedTy);
867 IncV->setName(NewPHI->getName()+".inc");
868 NewPHI->addIncoming(IncV, LatchBlock);
869
Chris Lattnerdb23c742005-08-03 22:51:21 +0000870 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +0000871 // each other.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000872 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000873 while (!UsersToProcess.empty()) {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000874 SCEVHandle Base = UsersToProcess.front().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000875
Chris Lattnera091ff12005-08-09 00:18:09 +0000876 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +0000877
Chris Lattnera091ff12005-08-09 00:18:09 +0000878 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000879 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
880 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +0000881
882 // If BaseV is a constant other than 0, make sure that it gets inserted into
883 // the preheader, instead of being forward substituted into the uses. We do
884 // this by forcing a noop cast to be inserted into the preheader in this
885 // case.
886 if (Constant *C = dyn_cast<Constant>(BaseV))
Chris Lattner530fe6a2005-09-10 01:18:45 +0000887 if (!C->isNullValue() && !isTargetConstant(Base)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000888 // We want this constant emitted into the preheader!
889 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
890 PreInsertPt);
891 }
892
Nate Begemane68bcd12005-07-30 00:15:07 +0000893 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000894 // the instructions that we identified as using this stride and base.
Chris Lattner37c24cc2005-08-08 22:56:21 +0000895 while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
896 BasedUser &User = UsersToProcess.front();
Jeff Cohen546fd592005-07-30 18:33:25 +0000897
Chris Lattnera091ff12005-08-09 00:18:09 +0000898 // If this instruction wants to use the post-incremented value, move it
899 // after the post-inc and use its value instead of the PHI.
900 Value *RewriteOp = NewPHI;
901 if (User.isUseOfPostIncrementedValue) {
902 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +0000903
904 // If this user is in the loop, make sure it is the last thing in the
905 // loop to ensure it is dominated by the increment.
906 if (L->contains(User.Inst->getParent()))
907 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +0000908 }
909 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
910
Chris Lattnerdb23c742005-08-03 22:51:21 +0000911 // Clear the SCEVExpander's expression map so that we are guaranteed
912 // to have the code emitted where we expect it.
913 Rewriter.clear();
Chris Lattnera091ff12005-08-09 00:18:09 +0000914
Chris Lattnera6d7c352005-08-04 20:03:32 +0000915 // Now that we know what we need to do, insert code before User for the
916 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +0000917 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
918 // Add BaseV to the PHI value if needed.
919 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
920
Chris Lattner8447b492005-08-12 22:22:17 +0000921 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +0000922
Chris Lattnerdb23c742005-08-03 22:51:21 +0000923 // Mark old value we replaced as possibly dead, so that it is elminated
924 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000925 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000926
Chris Lattnerdb23c742005-08-03 22:51:21 +0000927 UsersToProcess.erase(UsersToProcess.begin());
928 ++NumReduced;
929 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000930 // TODO: Next, find out which base index is the most common, pull it out.
931 }
932
933 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
934 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +0000935}
936
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000937// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
938// uses in the loop, look to see if we can eliminate some, in favor of using
939// common indvars for the different uses.
940void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
941 // TODO: implement optzns here.
942
943
944
945
946 // Finally, get the terminating condition for the loop if possible. If we
947 // can, we want to change it to use a post-incremented version of its
948 // induction variable, to allow coallescing the live ranges for the IV into
949 // one register value.
950 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
951 BasicBlock *Preheader = L->getLoopPreheader();
952 BasicBlock *LatchBlock =
953 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
954 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
955 if (!TermBr || TermBr->isUnconditional() ||
956 !isa<SetCondInst>(TermBr->getCondition()))
957 return;
958 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
959
960 // Search IVUsesByStride to find Cond's IVUse if there is one.
961 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +0000962 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000963
Chris Lattneredff91a2005-08-10 00:45:21 +0000964 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator
965 I = IVUsesByStride.begin(), E = IVUsesByStride.end();
966 I != E && !CondUse; ++I)
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000967 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
968 E = I->second.Users.end(); UI != E; ++UI)
969 if (UI->User == Cond) {
970 CondUse = &*UI;
Chris Lattneredff91a2005-08-10 00:45:21 +0000971 CondStride = &I->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000972 // NOTE: we could handle setcc instructions with multiple uses here, but
973 // InstCombine does it as well for simple uses, it's not clear that it
974 // occurs enough in real life to handle.
975 break;
976 }
977 if (!CondUse) return; // setcc doesn't use the IV.
978
979 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +0000980 // FIXME: Evaluate whether this is a good idea or not.
981 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000982
983 // It's possible for the setcc instruction to be anywhere in the loop, and
984 // possible for it to have multiple users. If it is not immediately before
985 // the latch block branch, move it.
986 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
987 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
988 Cond->moveBefore(TermBr);
989 } else {
990 // Otherwise, clone the terminating condition and insert into the loopend.
991 Cond = cast<SetCondInst>(Cond->clone());
992 Cond->setName(L->getHeader()->getName() + ".termcond");
993 LatchBlock->getInstList().insert(TermBr, Cond);
994
995 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +0000996 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000997 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +0000998 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000999 }
1000 }
1001
1002 // If we get to here, we know that we can transform the setcc instruction to
1003 // use the post-incremented version of the IV, allowing us to coallesce the
1004 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001005 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001006 CondUse->isUseOfPostIncrementedValue = true;
1007}
Nate Begemane68bcd12005-07-30 00:15:07 +00001008
Nate Begemanb18121e2004-10-18 21:08:22 +00001009void LoopStrengthReduce::runOnLoop(Loop *L) {
1010 // First step, transform all loops nesting inside of this loop.
1011 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1012 runOnLoop(*I);
1013
Nate Begemane68bcd12005-07-30 00:15:07 +00001014 // Next, find all uses of induction variables in this loop, and catagorize
1015 // them by stride. Start by finding all of the PHI nodes in the header for
1016 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001017 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001018 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001019 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001020
Nate Begemane68bcd12005-07-30 00:15:07 +00001021 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001022 if (IVUsesByStride.empty()) return;
1023
1024 // Optimize induction variables. Some indvar uses can be transformed to use
1025 // strides that will be needed for other purposes. A common example of this
1026 // is the exit test for the loop, which can often be rewritten to use the
1027 // computation of some other indvar to decide when to terminate the loop.
1028 OptimizeIndvars(L);
1029
Misha Brukmanb1c93172005-04-21 23:48:37 +00001030
Nate Begemane68bcd12005-07-30 00:15:07 +00001031 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1032 // doing computation in byte values, promote to 32-bit values if safe.
1033
1034 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1035 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1036 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1037 // to be careful that IV's are all the same type. Only works for intptr_t
1038 // indvars.
1039
1040 // If we only have one stride, we can more aggressively eliminate some things.
1041 bool HasOneStride = IVUsesByStride.size() == 1;
1042
Chris Lattnera091ff12005-08-09 00:18:09 +00001043 // Note: this processes each stride/type pair individually. All users passed
1044 // into StrengthReduceStridedIVUsers have the same type AND stride.
Chris Lattneredff91a2005-08-10 00:45:21 +00001045 for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
Chris Lattner430d0022005-08-03 22:21:05 +00001046 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +00001047 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +00001048
1049 // Clean up after ourselves
1050 if (!DeadInsts.empty()) {
1051 DeleteTriviallyDeadInstructions(DeadInsts);
1052
Nate Begemane68bcd12005-07-30 00:15:07 +00001053 BasicBlock::iterator I = L->getHeader()->begin();
1054 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001055 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001056 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1057
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001058 // At this point, we know that we have killed one or more GEP
1059 // instructions. It is worth checking to see if the cann indvar is also
1060 // dead, so that we can remove it as well. The requirements for the cann
1061 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001062 // 1. the cann indvar has one use
1063 // 2. the use is an add instruction
1064 // 3. the add has one use
1065 // 4. the add is used by the cann indvar
1066 // If all four cases above are true, then we can remove both the add and
1067 // the cann indvar.
1068 // FIXME: this needs to eliminate an induction variable even if it's being
1069 // compared against some value to decide loop termination.
1070 if (PN->hasOneUse()) {
1071 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +00001072 if (BO && BO->hasOneUse()) {
1073 if (PN == *(BO->use_begin())) {
1074 DeadInsts.insert(BO);
1075 // Break the cycle, then delete the PHI.
1076 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001077 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001078 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001079 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001080 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001081 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001082 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001083 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001084 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001085
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001086 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001087 IVUsesByStride.clear();
1088 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001089}