blob: 2723176edb18f314d3ae94fe06dc5b7ae529b857 [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"
Evan Chengc567c4e2006-03-13 23:14:23 +000034#include "llvm/Target/TargetLowering.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000035#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000036#include <iostream>
Nate Begemanb18121e2004-10-18 21:08:22 +000037#include <set>
38using namespace llvm;
39
40namespace {
41 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000042 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Chris Lattneredff91a2005-08-10 00:45:21 +000043 Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
Nate Begemanb18121e2004-10-18 21:08:22 +000044
Chris Lattner430d0022005-08-03 22:21:05 +000045 /// IVStrideUse - Keep track of one use of a strided induction variable, where
46 /// the stride is stored externally. The Offset member keeps track of the
47 /// offset from the IV, User is the actual user of the operand, and 'Operand'
48 /// is the operand # of the User that is the use.
49 struct IVStrideUse {
50 SCEVHandle Offset;
51 Instruction *User;
52 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000053
54 // isUseOfPostIncrementedValue - True if this should use the
55 // post-incremented version of this IV, not the preincremented version.
56 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +000057 // instruction for a loop or uses dominated by the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +000058 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000059
60 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000061 : Offset(Offs), User(U), OperandValToReplace(O),
62 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000063 };
64
65 /// IVUsersOfOneStride - This structure keeps track of all instructions that
66 /// have an operand that is based on the trip count multiplied by some stride.
67 /// The stride for all of these users is common and kept external to this
68 /// structure.
69 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000070 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000071 /// initial value and the operand that uses the IV.
72 std::vector<IVStrideUse> Users;
73
74 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
75 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000076 }
77 };
78
79
Nate Begemanb18121e2004-10-18 21:08:22 +000080 class LoopStrengthReduce : public FunctionPass {
81 LoopInfo *LI;
Chris Lattnercb367102006-01-11 05:10:20 +000082 ETForest *EF;
Nate Begemane68bcd12005-07-30 00:15:07 +000083 ScalarEvolution *SE;
84 const TargetData *TD;
85 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000086 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000087
88 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
89 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000090 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000091
92 /// IVUsesByStride - Keep track of all uses of induction variables that we
93 /// are interested in. The key of the map is the stride of the access.
Chris Lattneredff91a2005-08-10 00:45:21 +000094 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000095
Chris Lattner4ea0a3e2005-10-09 06:20:55 +000096 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
97 /// We use this to iterate over the IVUsesByStride collection without being
98 /// dependent on random ordering of pointers in the process.
99 std::vector<SCEVHandle> StrideOrder;
100
Chris Lattner6f286b72005-08-04 01:19:13 +0000101 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
102 /// of the casted version of each value. This is accessed by
103 /// getCastedVersionOf.
104 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +0000105
106 /// DeadInsts - Keep track of instructions we may have made dead, so that
107 /// we can remove them after we are done working.
108 std::set<Instruction*> DeadInsts;
Evan Chengc567c4e2006-03-13 23:14:23 +0000109
110 /// TLI - Keep a pointer of a TargetLowering to consult for determining
111 /// transformation profitability.
112 const TargetLowering *TLI;
113
Nate Begemanb18121e2004-10-18 21:08:22 +0000114 public:
Evan Chengc567c4e2006-03-13 23:14:23 +0000115 LoopStrengthReduce(unsigned MTAMS = 1, const TargetLowering *tli = NULL)
116 : MaxTargetAMSize(MTAMS), TLI(tli) {
Jeff Cohena2c59b72005-03-04 04:04:26 +0000117 }
118
Nate Begemanb18121e2004-10-18 21:08:22 +0000119 virtual bool runOnFunction(Function &) {
120 LI = &getAnalysis<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000121 EF = &getAnalysis<ETForest>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000122 SE = &getAnalysis<ScalarEvolution>();
123 TD = &getAnalysis<TargetData>();
124 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000125 Changed = false;
126
127 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
128 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000129
Nate Begemanb18121e2004-10-18 21:08:22 +0000130 return Changed;
131 }
132
133 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000134 // We split critical edges, so we change the CFG. However, we do update
135 // many analyses if they are around.
136 AU.addPreservedID(LoopSimplifyID);
137 AU.addPreserved<LoopInfo>();
138 AU.addPreserved<DominatorSet>();
Chris Lattnercb367102006-01-11 05:10:20 +0000139 AU.addPreserved<ETForest>();
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000140 AU.addPreserved<ImmediateDominators>();
141 AU.addPreserved<DominanceFrontier>();
142 AU.addPreserved<DominatorTree>();
143
Jeff Cohen39751c32005-02-27 19:37:07 +0000144 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000145 AU.addRequired<LoopInfo>();
Chris Lattnercb367102006-01-11 05:10:20 +0000146 AU.addRequired<ETForest>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000147 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000148 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000149 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000150
151 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
152 ///
153 Value *getCastedVersionOf(Value *V);
154private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000155 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000156 bool AddUsersIfInteresting(Instruction *I, Loop *L,
157 std::set<Instruction*> &Processed);
158 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
159
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000160 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000161
Chris Lattneredff91a2005-08-10 00:45:21 +0000162 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
163 IVUsersOfOneStride &Uses,
Chris Lattner430d0022005-08-03 22:21:05 +0000164 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000165 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
166 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000167 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Chris Lattner92233d22005-09-27 21:10:32 +0000168 "Loop Strength Reduction");
Nate Begemanb18121e2004-10-18 21:08:22 +0000169}
170
Evan Chengc567c4e2006-03-13 23:14:23 +0000171FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize,
172 const TargetLowering *TLI) {
173 return new LoopStrengthReduce(MaxTargetAMSize, TLI);
Nate Begemanb18121e2004-10-18 21:08:22 +0000174}
175
Chris Lattner6f286b72005-08-04 01:19:13 +0000176/// getCastedVersionOf - Return the specified value casted to uintptr_t.
177///
178Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
179 if (V->getType() == UIntPtrTy) return V;
180 if (Constant *CB = dyn_cast<Constant>(V))
181 return ConstantExpr::getCast(CB, UIntPtrTy);
182
183 Value *&New = CastedPointers[V];
184 if (New) return New;
185
Chris Lattnerd30c4992006-02-04 09:52:43 +0000186 New = SCEVExpander::InsertCastOfTo(V, UIntPtrTy);
Chris Lattneracc42c42005-08-04 19:08:16 +0000187 DeadInsts.insert(cast<Instruction>(New));
188 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000189}
190
191
Nate Begemanb18121e2004-10-18 21:08:22 +0000192/// DeleteTriviallyDeadInstructions - If any of the instructions is the
193/// specified set are trivially dead, delete them and see if this makes any of
194/// their operands subsequently dead.
195void LoopStrengthReduce::
196DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
197 while (!Insts.empty()) {
198 Instruction *I = *Insts.begin();
199 Insts.erase(Insts.begin());
200 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000201 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
202 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
203 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000204 SE->deleteInstructionFromRecords(I);
205 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000206 Changed = true;
207 }
208 }
209}
210
Jeff Cohen39751c32005-02-27 19:37:07 +0000211
Chris Lattnereaf24722005-08-04 17:40:30 +0000212/// GetExpressionSCEV - Compute and return the SCEV for the specified
213/// instruction.
214SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000215 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
216 // If this is a GEP that SE doesn't know about, compute it now and insert it.
217 // If this is not a GEP, or if we have already done this computation, just let
218 // SE figure it out.
Chris Lattnereaf24722005-08-04 17:40:30 +0000219 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000220 if (!GEP || SE->hasSCEV(GEP))
Chris Lattnereaf24722005-08-04 17:40:30 +0000221 return SE->getSCEV(Exp);
222
Nate Begemane68bcd12005-07-30 00:15:07 +0000223 // Analyze all of the subscripts of this getelementptr instruction, looking
224 // for uses that are determined by the trip count of L. First, skip all
225 // operands the are not dependent on the IV.
226
227 // Build up the base expression. Insert an LLVM cast of the pointer to
228 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000229 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000230
231 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000232
233 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000234 // If this is a use of a recurrence that we can analyze, and it comes before
235 // Op does in the GEP operand list, we will handle this when we process this
236 // operand.
237 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
238 const StructLayout *SL = TD->getStructLayout(STy);
239 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
240 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000241 GEPVal = SCEVAddExpr::get(GEPVal,
242 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000243 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000244 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
245 SCEVHandle Idx = SE->getSCEV(OpVal);
246
Chris Lattnereaf24722005-08-04 17:40:30 +0000247 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
248 if (TypeSize != 1)
249 Idx = SCEVMulExpr::get(Idx,
250 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
251 TypeSize)));
252 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000253 }
254 }
255
Chris Lattnerc6c4d992005-08-09 23:39:36 +0000256 SE->setSCEV(GEP, GEPVal);
Chris Lattnereaf24722005-08-04 17:40:30 +0000257 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000258}
259
Chris Lattneracc42c42005-08-04 19:08:16 +0000260/// getSCEVStartAndStride - Compute the start and stride of this expression,
261/// returning false if the expression is not a start/stride pair, or true if it
262/// is. The stride must be a loop invariant expression, but the start may be
263/// a mix of loop invariant and loop variant expressions.
264static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Chris Lattneredff91a2005-08-10 00:45:21 +0000265 SCEVHandle &Start, SCEVHandle &Stride) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000266 SCEVHandle TheAddRec = Start; // Initialize to zero.
267
268 // If the outer level is an AddExpr, the operands are all start values except
269 // for a nested AddRecExpr.
270 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
271 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
272 if (SCEVAddRecExpr *AddRec =
273 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
274 if (AddRec->getLoop() == L)
275 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
276 else
277 return false; // Nested IV of some sort?
278 } else {
279 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
280 }
281
282 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
283 TheAddRec = SH;
284 } else {
285 return false; // not analyzable.
286 }
287
288 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
289 if (!AddRec || AddRec->getLoop() != L) return false;
290
291 // FIXME: Generalize to non-affine IV's.
292 if (!AddRec->isAffine()) return false;
293
294 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
295
Chris Lattneracc42c42005-08-04 19:08:16 +0000296 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
Chris Lattneredff91a2005-08-10 00:45:21 +0000297 DEBUG(std::cerr << "[" << L->getHeader()->getName()
298 << "] Variable stride: " << *AddRec << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000299
Chris Lattneredff91a2005-08-10 00:45:21 +0000300 Stride = AddRec->getOperand(1);
301 // Check that all constant strides are the unsigned type, we don't want to
302 // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
303 // merged.
304 assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
Chris Lattneracc42c42005-08-04 19:08:16 +0000305 "Constants should be canonicalized to unsigned!");
Chris Lattneredff91a2005-08-10 00:45:21 +0000306
Chris Lattneracc42c42005-08-04 19:08:16 +0000307 return true;
308}
309
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000310/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
311/// and now we need to decide whether the user should use the preinc or post-inc
312/// value. If this user should use the post-inc version of the IV, return true.
313///
314/// Choosing wrong here can break dominance properties (if we choose to use the
315/// post-inc value when we cannot) or it can end up adding extra live-ranges to
316/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
317/// should use the post-inc value).
318static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Chris Lattnercb367102006-01-11 05:10:20 +0000319 Loop *L, ETForest *EF, Pass *P) {
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000320 // If the user is in the loop, use the preinc value.
321 if (L->contains(User->getParent())) return false;
322
Chris Lattnerf07a5872005-10-03 02:50:05 +0000323 BasicBlock *LatchBlock = L->getLoopLatch();
324
325 // Ok, the user is outside of the loop. If it is dominated by the latch
326 // block, use the post-inc value.
Chris Lattnercb367102006-01-11 05:10:20 +0000327 if (EF->dominates(LatchBlock, User->getParent()))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000328 return true;
329
330 // There is one case we have to be careful of: PHI nodes. These little guys
331 // can live in blocks that do not dominate the latch block, but (since their
332 // uses occur in the predecessor block, not the block the PHI lives in) should
333 // still use the post-inc value. Check for this case now.
334 PHINode *PN = dyn_cast<PHINode>(User);
335 if (!PN) return false; // not a phi, not dominated by latch block.
336
337 // Look at all of the uses of IV by the PHI node. If any use corresponds to
338 // a block that is not dominated by the latch block, give up and use the
339 // preincremented value.
340 unsigned NumUses = 0;
341 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
342 if (PN->getIncomingValue(i) == IV) {
343 ++NumUses;
Chris Lattnercb367102006-01-11 05:10:20 +0000344 if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
Chris Lattnerf07a5872005-10-03 02:50:05 +0000345 return false;
346 }
347
348 // Okay, all uses of IV by PN are in predecessor blocks that really are
349 // dominated by the latch block. Split the critical edges and use the
350 // post-incremented value.
351 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
352 if (PN->getIncomingValue(i) == IV) {
353 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
354 if (--NumUses == 0) break;
355 }
356
357 return true;
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000358}
359
360
361
Nate Begemane68bcd12005-07-30 00:15:07 +0000362/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
363/// reducible SCEV, recursively add its users to the IVUsesByStride set and
364/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000365bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
366 std::set<Instruction*> &Processed) {
Chris Lattner5df0e362005-10-21 05:45:41 +0000367 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
368 return false; // Void and FP expressions cannot be reduced.
Chris Lattnereaf24722005-08-04 17:40:30 +0000369 if (!Processed.insert(I).second)
370 return true; // Instruction already handled.
371
Chris Lattneracc42c42005-08-04 19:08:16 +0000372 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000373 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000374 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000375
Chris Lattneracc42c42005-08-04 19:08:16 +0000376 // Get the start and stride for this expression.
377 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
Chris Lattneredff91a2005-08-10 00:45:21 +0000378 SCEVHandle Stride = Start;
Chris Lattneracc42c42005-08-04 19:08:16 +0000379 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
380 return false; // Non-reducible symbolic expression, bail out.
381
Nate Begemane68bcd12005-07-30 00:15:07 +0000382 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
383 Instruction *User = cast<Instruction>(*UI);
384
385 // Do not infinitely recurse on PHI nodes.
Chris Lattnerfd018c82005-09-13 02:09:55 +0000386 if (isa<PHINode>(User) && Processed.count(User))
Nate Begemane68bcd12005-07-30 00:15:07 +0000387 continue;
388
389 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000390 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000391 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000392 if (LI->getLoopFor(User->getParent()) != L) {
Chris Lattnerfd018c82005-09-13 02:09:55 +0000393 DEBUG(std::cerr << "FOUND USER in other loop: " << *User
Chris Lattnera0102fb2005-08-04 00:14:11 +0000394 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000395 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000396 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000397 DEBUG(std::cerr << "FOUND USER: " << *User
398 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000399 AddUserToIVUsers = true;
400 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000401
Chris Lattneracc42c42005-08-04 19:08:16 +0000402 if (AddUserToIVUsers) {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000403 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
404 if (StrideUses.Users.empty()) // First occurance of this stride?
405 StrideOrder.push_back(Stride);
406
Chris Lattner65107492005-08-04 00:40:47 +0000407 // Okay, we found a user that we cannot reduce. Analyze the instruction
Chris Lattnera6764832005-09-12 06:04:47 +0000408 // and decide what to do with it. If we are a use inside of the loop, use
409 // the value before incrementation, otherwise use it after incrementation.
Chris Lattnercb367102006-01-11 05:10:20 +0000410 if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
Chris Lattnera6764832005-09-12 06:04:47 +0000411 // The value used will be incremented by the stride more than we are
412 // expecting, so subtract this off.
413 SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000414 StrideUses.addUser(NewStart, User, I);
415 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
Chris Lattnerf07a5872005-10-03 02:50:05 +0000416 DEBUG(std::cerr << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000417 } else {
Chris Lattner4ea0a3e2005-10-09 06:20:55 +0000418 StrideUses.addUser(Start, User, I);
Chris Lattnera6764832005-09-12 06:04:47 +0000419 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000420 }
421 }
422 return true;
423}
424
425namespace {
426 /// BasedUser - For a particular base value, keep information about how we've
427 /// partitioned the expression so far.
428 struct BasedUser {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000429 /// Base - The Base value for the PHI node that needs to be inserted for
430 /// this use. As the use is processed, information gets moved from this
431 /// field to the Imm field (below). BasedUser values are sorted by this
432 /// field.
433 SCEVHandle Base;
434
Nate Begemane68bcd12005-07-30 00:15:07 +0000435 /// Inst - The instruction using the induction variable.
436 Instruction *Inst;
437
Chris Lattner430d0022005-08-03 22:21:05 +0000438 /// OperandValToReplace - The operand value of Inst to replace with the
439 /// EmittedBase.
440 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000441
442 /// Imm - The immediate value that should be added to the base immediately
443 /// before Inst, because it will be folded into the imm field of the
444 /// instruction.
445 SCEVHandle Imm;
446
447 /// EmittedBase - The actual value* to use for the base value of this
448 /// operation. This is null if we should just use zero so far.
449 Value *EmittedBase;
450
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000451 // isUseOfPostIncrementedValue - True if this should use the
452 // post-incremented version of this IV, not the preincremented version.
453 // This can only be set in special cases, such as the terminating setcc
Chris Lattnera6764832005-09-12 06:04:47 +0000454 // instruction for a loop and uses outside the loop that are dominated by
455 // the loop.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000456 bool isUseOfPostIncrementedValue;
Chris Lattner37c24cc2005-08-08 22:56:21 +0000457
458 BasedUser(IVStrideUse &IVSU)
459 : Base(IVSU.Offset), Inst(IVSU.User),
460 OperandValToReplace(IVSU.OperandValToReplace),
461 Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
462 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000463
Chris Lattnera6d7c352005-08-04 20:03:32 +0000464 // Once we rewrite the code to insert the new IVs we want, update the
465 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
466 // to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000467 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner8447b492005-08-12 22:22:17 +0000468 SCEVExpander &Rewriter, Loop *L,
469 Pass *P);
Chris Lattner2959f002006-02-04 07:36:50 +0000470
471 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
472 SCEVExpander &Rewriter,
473 Instruction *IP, Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000474 void dump() const;
475 };
476}
477
478void BasedUser::dump() const {
Chris Lattner37c24cc2005-08-08 22:56:21 +0000479 std::cerr << " Base=" << *Base;
Nate Begemane68bcd12005-07-30 00:15:07 +0000480 std::cerr << " Imm=" << *Imm;
481 if (EmittedBase)
482 std::cerr << " EB=" << *EmittedBase;
483
484 std::cerr << " Inst: " << *Inst;
485}
486
Chris Lattner2959f002006-02-04 07:36:50 +0000487Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
488 SCEVExpander &Rewriter,
489 Instruction *IP, Loop *L) {
490 // Figure out where we *really* want to insert this code. In particular, if
491 // the user is inside of a loop that is nested inside of L, we really don't
492 // want to insert this expression before the user, we'd rather pull it out as
493 // many loops as possible.
494 LoopInfo &LI = Rewriter.getLoopInfo();
495 Instruction *BaseInsertPt = IP;
496
497 // Figure out the most-nested loop that IP is in.
498 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
499
500 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
501 // the preheader of the outer-most loop where NewBase is not loop invariant.
502 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
503 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
504 InsertLoop = InsertLoop->getParentLoop();
505 }
506
507 // If there is no immediate value, skip the next part.
508 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
509 if (SC->getValue()->isNullValue())
510 return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
511 OperandValToReplace->getType());
512
513 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
514
515 // Always emit the immediate (if non-zero) into the same block as the user.
516 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
517 return Rewriter.expandCodeFor(NewValSCEV, IP,
518 OperandValToReplace->getType());
519}
520
521
Chris Lattnera6d7c352005-08-04 20:03:32 +0000522// Once we rewrite the code to insert the new IVs we want, update the
523// operands of Inst to use the new expression 'NewBase', with 'Imm' added
524// to it.
Chris Lattnera091ff12005-08-09 00:18:09 +0000525void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
Chris Lattner4fec86d2005-08-12 22:06:11 +0000526 SCEVExpander &Rewriter,
Chris Lattner8447b492005-08-12 22:22:17 +0000527 Loop *L, Pass *P) {
Chris Lattnera6d7c352005-08-04 20:03:32 +0000528 if (!isa<PHINode>(Inst)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000529 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000530 // Replace the use of the operand Value with the new Phi we just created.
531 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
532 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
533 return;
534 }
535
536 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000537 // expression into each operand block that uses it. Note that PHI nodes can
538 // have multiple entries for the same predecessor. We use a map to make sure
539 // that a PHI node only has a single Value* for each predecessor (which also
540 // prevents us from inserting duplicate code in some blocks).
541 std::map<BasicBlock*, Value*> InsertedCode;
Chris Lattnera6d7c352005-08-04 20:03:32 +0000542 PHINode *PN = cast<PHINode>(Inst);
543 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
544 if (PN->getIncomingValue(i) == OperandValToReplace) {
Chris Lattner4fec86d2005-08-12 22:06:11 +0000545 // If this is a critical edge, split the edge so that we do not insert the
Chris Lattnerfd018c82005-09-13 02:09:55 +0000546 // code on all predecessor/successor paths. We do this unless this is the
547 // canonical backedge for this loop, as this can make some inserted code
548 // be in an illegal position.
Chris Lattner8fcce172005-10-03 00:31:52 +0000549 BasicBlock *PHIPred = PN->getIncomingBlock(i);
550 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
551 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
Chris Lattner8fcce172005-10-03 00:31:52 +0000552
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000553 // First step, split the critical edge.
Chris Lattner8fcce172005-10-03 00:31:52 +0000554 SplitCriticalEdge(PHIPred, PN->getParent(), P);
Chris Lattner8447b492005-08-12 22:22:17 +0000555
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000556 // Next step: move the basic block. In particular, if the PHI node
557 // is outside of the loop, and PredTI is in the loop, we want to
558 // move the block to be immediately before the PHI block, not
559 // immediately after PredTI.
Chris Lattner8fcce172005-10-03 00:31:52 +0000560 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
Chris Lattner2bf7cb52005-08-17 06:35:16 +0000561 BasicBlock *NewBB = PN->getIncomingBlock(i);
562 NewBB->moveBefore(PN->getParent());
Chris Lattner4fec86d2005-08-12 22:06:11 +0000563 }
564 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000565
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000566 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
567 if (!Code) {
568 // Insert the code into the end of the predecessor block.
Chris Lattner2959f002006-02-04 07:36:50 +0000569 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
570 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000571 }
Chris Lattnera6d7c352005-08-04 20:03:32 +0000572
573 // Replace the use of the operand Value with the new Phi we just created.
Chris Lattnerdde7dc52005-08-10 00:35:32 +0000574 PN->setIncomingValue(i, Code);
Chris Lattnera6d7c352005-08-04 20:03:32 +0000575 Rewriter.clear();
576 }
577 }
578 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
579}
580
581
Nate Begemane68bcd12005-07-30 00:15:07 +0000582/// isTargetConstant - Return true if the following can be referenced by the
583/// immediate field of a target instruction.
Evan Chengc567c4e2006-03-13 23:14:23 +0000584static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
Chris Lattner14203e82005-08-08 06:25:50 +0000585 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Chris Lattner07720072005-12-05 18:23:57 +0000586 int64_t V = SC->getValue()->getSExtValue();
Evan Chengc567c4e2006-03-13 23:14:23 +0000587 if (TLI)
588 return TLI->isLegalAddressImmediate(V);
589 else
590 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
591 return (V > -(1 << 16) && V < (1 << 16)-1);
Chris Lattner14203e82005-08-08 06:25:50 +0000592 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000593
Nate Begemane68bcd12005-07-30 00:15:07 +0000594 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
595 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
Evan Chengc567c4e2006-03-13 23:14:23 +0000596 if (CE->getOpcode() == Instruction::Cast) {
597 Constant *Op0 = CE->getOperand(0);
598 if (isa<GlobalValue>(Op0) &&
599 TLI &&
600 TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
Nate Begemane68bcd12005-07-30 00:15:07 +0000601 return true;
Evan Chengc567c4e2006-03-13 23:14:23 +0000602 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000603 return false;
604}
605
Chris Lattner37ed8952005-08-08 22:32:34 +0000606/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
607/// loop varying to the Imm operand.
608static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
609 Loop *L) {
610 if (Val->isLoopInvariant(L)) return; // Nothing to do.
611
612 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
613 std::vector<SCEVHandle> NewOps;
614 NewOps.reserve(SAE->getNumOperands());
615
616 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
617 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
618 // If this is a loop-variant expression, it must stay in the immediate
619 // field of the expression.
620 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
621 } else {
622 NewOps.push_back(SAE->getOperand(i));
623 }
624
625 if (NewOps.empty())
626 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
627 else
628 Val = SCEVAddExpr::get(NewOps);
629 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
630 // Try to pull immediates out of the start value of nested addrec's.
631 SCEVHandle Start = SARE->getStart();
632 MoveLoopVariantsToImediateField(Start, Imm, L);
633
634 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
635 Ops[0] = Start;
636 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
637 } else {
638 // Otherwise, all of Val is variant, move the whole thing over.
639 Imm = SCEVAddExpr::get(Imm, Val);
640 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
641 }
642}
643
644
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000645/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000646/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000647/// Accumulate these immediate values into the Imm value.
Evan Chengc567c4e2006-03-13 23:14:23 +0000648static void MoveImmediateValues(const TargetLowering *TLI,
649 SCEVHandle &Val, SCEVHandle &Imm,
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000650 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000651 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000652 std::vector<SCEVHandle> NewOps;
653 NewOps.reserve(SAE->getNumOperands());
654
Chris Lattner2959f002006-02-04 07:36:50 +0000655 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
656 SCEVHandle NewOp = SAE->getOperand(i);
Evan Chengc567c4e2006-03-13 23:14:23 +0000657 MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000658
659 if (!NewOp->isLoopInvariant(L)) {
Chris Lattneracc42c42005-08-04 19:08:16 +0000660 // If this is a loop-variant expression, it must stay in the immediate
661 // field of the expression.
Chris Lattner2959f002006-02-04 07:36:50 +0000662 Imm = SCEVAddExpr::get(Imm, NewOp);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000663 } else {
Chris Lattner2959f002006-02-04 07:36:50 +0000664 NewOps.push_back(NewOp);
Nate Begemane68bcd12005-07-30 00:15:07 +0000665 }
Chris Lattner2959f002006-02-04 07:36:50 +0000666 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000667
668 if (NewOps.empty())
669 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
670 else
671 Val = SCEVAddExpr::get(NewOps);
672 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000673 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
674 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000675 SCEVHandle Start = SARE->getStart();
Evan Chengc567c4e2006-03-13 23:14:23 +0000676 MoveImmediateValues(TLI, Start, Imm, isAddress, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000677
678 if (Start != SARE->getStart()) {
679 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
680 Ops[0] = Start;
681 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
682 }
683 return;
Chris Lattner2959f002006-02-04 07:36:50 +0000684 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
685 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
Evan Chengc567c4e2006-03-13 23:14:23 +0000686 if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
Chris Lattner2959f002006-02-04 07:36:50 +0000687 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
688
689 SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
690 SCEVHandle NewOp = SME->getOperand(1);
Evan Chengc567c4e2006-03-13 23:14:23 +0000691 MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
Chris Lattner2959f002006-02-04 07:36:50 +0000692
693 // If we extracted something out of the subexpressions, see if we can
694 // simplify this!
695 if (NewOp != SME->getOperand(1)) {
696 // Scale SubImm up by "8". If the result is a target constant, we are
697 // good.
698 SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
Evan Chengc567c4e2006-03-13 23:14:23 +0000699 if (isTargetConstant(SubImm, TLI)) {
Chris Lattner2959f002006-02-04 07:36:50 +0000700 // Accumulate the immediate.
701 Imm = SCEVAddExpr::get(Imm, SubImm);
702
703 // Update what is left of 'Val'.
704 Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
705 return;
706 }
707 }
708 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000709 }
710
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000711 // Loop-variant expressions must stay in the immediate field of the
712 // expression.
Evan Chengc567c4e2006-03-13 23:14:23 +0000713 if ((isAddress && isTargetConstant(Val, TLI)) ||
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000714 !Val->isLoopInvariant(L)) {
715 Imm = SCEVAddExpr::get(Imm, Val);
716 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
717 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000718 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000719
720 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000721}
722
Chris Lattner5949d492005-08-13 07:27:18 +0000723
724/// IncrementAddExprUses - Decompose the specified expression into its added
725/// subexpressions, and increment SubExpressionUseCounts for each of these
726/// decomposed parts.
727static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
728 SCEVHandle Expr) {
729 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
730 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
731 SeparateSubExprs(SubExprs, AE->getOperand(j));
732 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
733 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
734 if (SARE->getOperand(0) == Zero) {
735 SubExprs.push_back(Expr);
736 } else {
737 // Compute the addrec with zero as its base.
738 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
739 Ops[0] = Zero; // Start with zero base.
740 SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
741
742
743 SeparateSubExprs(SubExprs, SARE->getOperand(0));
744 }
745 } else if (!isa<SCEVConstant>(Expr) ||
746 !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
747 // Do not add zero.
748 SubExprs.push_back(Expr);
749 }
750}
751
752
Chris Lattnera091ff12005-08-09 00:18:09 +0000753/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
754/// removing any common subexpressions from it. Anything truly common is
755/// removed, accumulated, and returned. This looks for things like (a+b+c) and
756/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
757static SCEVHandle
758RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
759 unsigned NumUses = Uses.size();
760
761 // Only one use? Use its base, regardless of what it is!
762 SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
763 SCEVHandle Result = Zero;
764 if (NumUses == 1) {
765 std::swap(Result, Uses[0].Base);
766 return Result;
767 }
768
769 // To find common subexpressions, count how many of Uses use each expression.
770 // If any subexpressions are used Uses.size() times, they are common.
771 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
772
Chris Lattner192cd182005-10-11 18:41:04 +0000773 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
774 // order we see them.
775 std::vector<SCEVHandle> UniqueSubExprs;
776
Chris Lattner5949d492005-08-13 07:27:18 +0000777 std::vector<SCEVHandle> SubExprs;
778 for (unsigned i = 0; i != NumUses; ++i) {
779 // If the base is zero (which is common), return zero now, there are no
780 // CSEs we can find.
781 if (Uses[i].Base == Zero) return Zero;
782
783 // Split the expression into subexprs.
784 SeparateSubExprs(SubExprs, Uses[i].Base);
785 // Add one to SubExpressionUseCounts for each subexpr present.
786 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
Chris Lattner192cd182005-10-11 18:41:04 +0000787 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
788 UniqueSubExprs.push_back(SubExprs[j]);
Chris Lattner5949d492005-08-13 07:27:18 +0000789 SubExprs.clear();
790 }
791
Chris Lattner192cd182005-10-11 18:41:04 +0000792 // Now that we know how many times each is used, build Result. Iterate over
793 // UniqueSubexprs so that we have a stable ordering.
794 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
795 std::map<SCEVHandle, unsigned>::iterator I =
796 SubExpressionUseCounts.find(UniqueSubExprs[i]);
797 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
Chris Lattnera091ff12005-08-09 00:18:09 +0000798 if (I->second == NumUses) { // Found CSE!
799 Result = SCEVAddExpr::get(Result, I->first);
Chris Lattnera091ff12005-08-09 00:18:09 +0000800 } else {
801 // Remove non-cse's from SubExpressionUseCounts.
Chris Lattner192cd182005-10-11 18:41:04 +0000802 SubExpressionUseCounts.erase(I);
Chris Lattnera091ff12005-08-09 00:18:09 +0000803 }
Chris Lattner192cd182005-10-11 18:41:04 +0000804 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000805
806 // If we found no CSE's, return now.
807 if (Result == Zero) return Result;
808
809 // Otherwise, remove all of the CSE's we found from each of the base values.
Chris Lattner5949d492005-08-13 07:27:18 +0000810 for (unsigned i = 0; i != NumUses; ++i) {
811 // Split the expression into subexprs.
812 SeparateSubExprs(SubExprs, Uses[i].Base);
813
814 // Remove any common subexpressions.
815 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
816 if (SubExpressionUseCounts.count(SubExprs[j])) {
817 SubExprs.erase(SubExprs.begin()+j);
818 --j; --e;
819 }
820
821 // Finally, the non-shared expressions together.
822 if (SubExprs.empty())
Chris Lattnera091ff12005-08-09 00:18:09 +0000823 Uses[i].Base = Zero;
Chris Lattner5949d492005-08-13 07:27:18 +0000824 else
825 Uses[i].Base = SCEVAddExpr::get(SubExprs);
Chris Lattner47d3ec32005-08-13 07:42:01 +0000826 SubExprs.clear();
Chris Lattner5949d492005-08-13 07:27:18 +0000827 }
Chris Lattnera091ff12005-08-09 00:18:09 +0000828
829 return Result;
830}
831
832
Nate Begemane68bcd12005-07-30 00:15:07 +0000833/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
834/// stride of IV. All of the users may have different starting values, and this
835/// may not be the only stride (we know it is if isOnlyStride is true).
Chris Lattneredff91a2005-08-10 00:45:21 +0000836void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000837 IVUsersOfOneStride &Uses,
838 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000839 bool isOnlyStride) {
840 // Transform our list of users and offsets to a bit more complex table. In
Chris Lattner37c24cc2005-08-08 22:56:21 +0000841 // this new vector, each 'BasedUser' contains 'Base' the base of the
842 // strided accessas well as the old information from Uses. We progressively
843 // move information from the Base field to the Imm field, until we eventually
844 // have the full access expression to rewrite the use.
845 std::vector<BasedUser> UsersToProcess;
Nate Begemane68bcd12005-07-30 00:15:07 +0000846 UsersToProcess.reserve(Uses.Users.size());
Chris Lattner37c24cc2005-08-08 22:56:21 +0000847 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
848 UsersToProcess.push_back(Uses.Users[i]);
849
850 // Move any loop invariant operands from the offset field to the immediate
851 // field of the use, so that we don't try to use something before it is
852 // computed.
853 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
854 UsersToProcess.back().Imm, L);
855 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000856 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000857 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000858
Chris Lattnera091ff12005-08-09 00:18:09 +0000859 // We now have a whole bunch of uses of like-strided induction variables, but
860 // they might all have different bases. We want to emit one PHI node for this
861 // stride which we fold as many common expressions (between the IVs) into as
862 // possible. Start by identifying the common expressions in the base values
863 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
864 // "A+B"), emit it to the preheader, then remove the expression from the
865 // UsersToProcess base values.
866 SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
867
Chris Lattner37ed8952005-08-08 22:32:34 +0000868 // Next, figure out what we can represent in the immediate fields of
869 // instructions. If we can represent anything there, move it to the imm
Chris Lattnera091ff12005-08-09 00:18:09 +0000870 // fields of the BasedUsers. We do this so that it increases the commonality
871 // of the remaining uses.
Chris Lattner37ed8952005-08-08 22:32:34 +0000872 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner5cf983e2005-08-16 00:38:11 +0000873 // If the user is not in the current loop, this means it is using the exit
874 // value of the IV. Do not put anything in the base, make sure it's all in
875 // the immediate field to allow as much factoring as possible.
876 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Chris Lattnerea7dfd52005-08-17 21:22:41 +0000877 UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
878 UsersToProcess[i].Base);
879 UsersToProcess[i].Base =
880 SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Chris Lattner5cf983e2005-08-16 00:38:11 +0000881 } else {
882
883 // Addressing modes can be folded into loads and stores. Be careful that
884 // the store is through the expression, not of the expression though.
885 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
886 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
887 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
888 isAddress = true;
889
Evan Chengc567c4e2006-03-13 23:14:23 +0000890 MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
Chris Lattner5cf983e2005-08-16 00:38:11 +0000891 isAddress, L);
892 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000893 }
894
Chris Lattnera091ff12005-08-09 00:18:09 +0000895 // Now that we know what we need to do, insert the PHI node itself.
896 //
897 DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
898 << *CommonExprs << " :\n");
899
900 SCEVExpander Rewriter(*SE, *LI);
901 SCEVExpander PreheaderRewriter(*SE, *LI);
Chris Lattner37ed8952005-08-08 22:32:34 +0000902
Chris Lattnera091ff12005-08-09 00:18:09 +0000903 BasicBlock *Preheader = L->getLoopPreheader();
904 Instruction *PreInsertPt = Preheader->getTerminator();
905 Instruction *PhiInsertBefore = L->getHeader()->begin();
Chris Lattner37ed8952005-08-08 22:32:34 +0000906
Chris Lattner8048b852005-09-12 17:11:27 +0000907 BasicBlock *LatchBlock = L->getLoopLatch();
Chris Lattnerbb78c972005-08-03 23:30:08 +0000908
Chris Lattnera091ff12005-08-09 00:18:09 +0000909 // Create a new Phi for this base, and stick it in the loop header.
910 const Type *ReplacedTy = CommonExprs->getType();
911 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
912 ++NumInserted;
913
Chris Lattneredff91a2005-08-10 00:45:21 +0000914 // Insert the stride into the preheader.
915 Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
916 ReplacedTy);
917 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
918
919
Chris Lattnera091ff12005-08-09 00:18:09 +0000920 // Emit the initial base value into the loop preheader, and add it to the
921 // Phi node.
922 Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
923 ReplacedTy);
924 NewPHI->addIncoming(PHIBaseV, Preheader);
925
926 // Emit the increment of the base value before the terminator of the loop
927 // latch block, and add it to the Phi node.
928 SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
Chris Lattneredff91a2005-08-10 00:45:21 +0000929 SCEVUnknown::get(StrideV));
Chris Lattnera091ff12005-08-09 00:18:09 +0000930
931 Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
932 ReplacedTy);
933 IncV->setName(NewPHI->getName()+".inc");
934 NewPHI->addIncoming(IncV, LatchBlock);
935
Chris Lattnerdb23c742005-08-03 22:51:21 +0000936 // Sort by the base value, so that all IVs with identical bases are next to
Chris Lattnera091ff12005-08-09 00:18:09 +0000937 // each other.
Nate Begemane68bcd12005-07-30 00:15:07 +0000938 while (!UsersToProcess.empty()) {
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000939 SCEVHandle Base = UsersToProcess.back().Base;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000940
Chris Lattnera091ff12005-08-09 00:18:09 +0000941 DEBUG(std::cerr << " INSERTING code for BASE = " << *Base << ":\n");
Chris Lattnerbb78c972005-08-03 23:30:08 +0000942
Chris Lattnera091ff12005-08-09 00:18:09 +0000943 // Emit the code for Base into the preheader.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000944 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
945 ReplacedTy);
Chris Lattnera091ff12005-08-09 00:18:09 +0000946
947 // If BaseV is a constant other than 0, make sure that it gets inserted into
948 // the preheader, instead of being forward substituted into the uses. We do
949 // this by forcing a noop cast to be inserted into the preheader in this
950 // case.
951 if (Constant *C = dyn_cast<Constant>(BaseV))
Evan Chengc567c4e2006-03-13 23:14:23 +0000952 if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
Chris Lattnera091ff12005-08-09 00:18:09 +0000953 // We want this constant emitted into the preheader!
954 BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
955 PreInsertPt);
956 }
957
Nate Begemane68bcd12005-07-30 00:15:07 +0000958 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000959 // the instructions that we identified as using this stride and base.
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000960 unsigned ScanPos = 0;
961 do {
962 BasedUser &User = UsersToProcess.back();
Jeff Cohen546fd592005-07-30 18:33:25 +0000963
Chris Lattnera091ff12005-08-09 00:18:09 +0000964 // If this instruction wants to use the post-incremented value, move it
965 // after the post-inc and use its value instead of the PHI.
966 Value *RewriteOp = NewPHI;
967 if (User.isUseOfPostIncrementedValue) {
968 RewriteOp = IncV;
Chris Lattnera6764832005-09-12 06:04:47 +0000969
970 // If this user is in the loop, make sure it is the last thing in the
971 // loop to ensure it is dominated by the increment.
972 if (L->contains(User.Inst->getParent()))
973 User.Inst->moveBefore(LatchBlock->getTerminator());
Chris Lattnera091ff12005-08-09 00:18:09 +0000974 }
975 SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
976
Chris Lattnerdb23c742005-08-03 22:51:21 +0000977 // Clear the SCEVExpander's expression map so that we are guaranteed
978 // to have the code emitted where we expect it.
979 Rewriter.clear();
Chris Lattnera091ff12005-08-09 00:18:09 +0000980
Chris Lattnera6d7c352005-08-04 20:03:32 +0000981 // Now that we know what we need to do, insert code before User for the
982 // immediate and any loop-variant expressions.
Chris Lattnera091ff12005-08-09 00:18:09 +0000983 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
984 // Add BaseV to the PHI value if needed.
985 RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
986
Chris Lattner8447b492005-08-12 22:22:17 +0000987 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
Jeff Cohen546fd592005-07-30 18:33:25 +0000988
Chris Lattnerdb23c742005-08-03 22:51:21 +0000989 // Mark old value we replaced as possibly dead, so that it is elminated
990 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000991 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000992
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000993 UsersToProcess.pop_back();
Chris Lattnerdb23c742005-08-03 22:51:21 +0000994 ++NumReduced;
Chris Lattner5c9d63d2005-10-11 18:30:57 +0000995
996 // If there are any more users to process with the same base, move one of
997 // them to the end of the list so that we will process it.
998 if (!UsersToProcess.empty()) {
999 for (unsigned e = UsersToProcess.size(); ScanPos != e; ++ScanPos)
1000 if (UsersToProcess[ScanPos].Base == Base) {
1001 std::swap(UsersToProcess[ScanPos], UsersToProcess.back());
1002 break;
1003 }
1004 }
1005 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
Nate Begemane68bcd12005-07-30 00:15:07 +00001006 // TODO: Next, find out which base index is the most common, pull it out.
1007 }
1008
1009 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1010 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +00001011}
1012
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001013// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1014// uses in the loop, look to see if we can eliminate some, in favor of using
1015// common indvars for the different uses.
1016void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1017 // TODO: implement optzns here.
1018
1019
1020
1021
1022 // Finally, get the terminating condition for the loop if possible. If we
1023 // can, we want to change it to use a post-incremented version of its
1024 // induction variable, to allow coallescing the live ranges for the IV into
1025 // one register value.
1026 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1027 BasicBlock *Preheader = L->getLoopPreheader();
1028 BasicBlock *LatchBlock =
1029 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1030 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1031 if (!TermBr || TermBr->isUnconditional() ||
1032 !isa<SetCondInst>(TermBr->getCondition()))
1033 return;
1034 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1035
1036 // Search IVUsesByStride to find Cond's IVUse if there is one.
1037 IVStrideUse *CondUse = 0;
Chris Lattneredff91a2005-08-10 00:45:21 +00001038 const SCEVHandle *CondStride = 0;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001039
Chris Lattnerb7a38942005-10-11 18:17:57 +00001040 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1041 ++Stride) {
1042 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1043 IVUsesByStride.find(StrideOrder[Stride]);
1044 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1045
1046 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1047 E = SI->second.Users.end(); UI != E; ++UI)
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001048 if (UI->User == Cond) {
1049 CondUse = &*UI;
Chris Lattnerb7a38942005-10-11 18:17:57 +00001050 CondStride = &SI->first;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001051 // NOTE: we could handle setcc instructions with multiple uses here, but
1052 // InstCombine does it as well for simple uses, it's not clear that it
1053 // occurs enough in real life to handle.
1054 break;
1055 }
Chris Lattnerb7a38942005-10-11 18:17:57 +00001056 }
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001057 if (!CondUse) return; // setcc doesn't use the IV.
1058
1059 // setcc stride is complex, don't mess with users.
Chris Lattneredff91a2005-08-10 00:45:21 +00001060 // FIXME: Evaluate whether this is a good idea or not.
1061 if (!isa<SCEVConstant>(*CondStride)) return;
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001062
1063 // It's possible for the setcc instruction to be anywhere in the loop, and
1064 // possible for it to have multiple users. If it is not immediately before
1065 // the latch block branch, move it.
1066 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1067 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1068 Cond->moveBefore(TermBr);
1069 } else {
1070 // Otherwise, clone the terminating condition and insert into the loopend.
1071 Cond = cast<SetCondInst>(Cond->clone());
1072 Cond->setName(L->getHeader()->getName() + ".termcond");
1073 LatchBlock->getInstList().insert(TermBr, Cond);
1074
1075 // Clone the IVUse, as the old use still exists!
Chris Lattneredff91a2005-08-10 00:45:21 +00001076 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001077 CondUse->OperandValToReplace);
Chris Lattneredff91a2005-08-10 00:45:21 +00001078 CondUse = &IVUsesByStride[*CondStride].Users.back();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001079 }
1080 }
1081
1082 // If we get to here, we know that we can transform the setcc instruction to
1083 // use the post-incremented version of the IV, allowing us to coallesce the
1084 // live ranges for the IV correctly.
Chris Lattneredff91a2005-08-10 00:45:21 +00001085 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001086 CondUse->isUseOfPostIncrementedValue = true;
1087}
Nate Begemane68bcd12005-07-30 00:15:07 +00001088
Nate Begemanb18121e2004-10-18 21:08:22 +00001089void LoopStrengthReduce::runOnLoop(Loop *L) {
1090 // First step, transform all loops nesting inside of this loop.
1091 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1092 runOnLoop(*I);
1093
Nate Begemane68bcd12005-07-30 00:15:07 +00001094 // Next, find all uses of induction variables in this loop, and catagorize
1095 // them by stride. Start by finding all of the PHI nodes in the header for
1096 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +00001097 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +00001098 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +00001099 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +00001100
Nate Begemane68bcd12005-07-30 00:15:07 +00001101 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +00001102 if (IVUsesByStride.empty()) return;
1103
1104 // Optimize induction variables. Some indvar uses can be transformed to use
1105 // strides that will be needed for other purposes. A common example of this
1106 // is the exit test for the loop, which can often be rewritten to use the
1107 // computation of some other indvar to decide when to terminate the loop.
1108 OptimizeIndvars(L);
1109
Misha Brukmanb1c93172005-04-21 23:48:37 +00001110
Nate Begemane68bcd12005-07-30 00:15:07 +00001111 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1112 // doing computation in byte values, promote to 32-bit values if safe.
1113
1114 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1115 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1116 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1117 // to be careful that IV's are all the same type. Only works for intptr_t
1118 // indvars.
1119
1120 // If we only have one stride, we can more aggressively eliminate some things.
1121 bool HasOneStride = IVUsesByStride.size() == 1;
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001122
Chris Lattnera091ff12005-08-09 00:18:09 +00001123 // Note: this processes each stride/type pair individually. All users passed
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001124 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1125 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1126 // This extra layer of indirection makes the ordering of strides deterministic
1127 // - not dependent on map order.
1128 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1129 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1130 IVUsesByStride.find(StrideOrder[Stride]);
1131 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
Nate Begemane68bcd12005-07-30 00:15:07 +00001132 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001133 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001134
1135 // Clean up after ourselves
1136 if (!DeadInsts.empty()) {
1137 DeleteTriviallyDeadInstructions(DeadInsts);
1138
Nate Begemane68bcd12005-07-30 00:15:07 +00001139 BasicBlock::iterator I = L->getHeader()->begin();
1140 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +00001141 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +00001142 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1143
Chris Lattnerc6c4d992005-08-09 23:39:36 +00001144 // At this point, we know that we have killed one or more GEP
1145 // instructions. It is worth checking to see if the cann indvar is also
1146 // dead, so that we can remove it as well. The requirements for the cann
1147 // indvar to be considered dead are:
Nate Begemane68bcd12005-07-30 00:15:07 +00001148 // 1. the cann indvar has one use
1149 // 2. the use is an add instruction
1150 // 3. the add has one use
1151 // 4. the add is used by the cann indvar
1152 // If all four cases above are true, then we can remove both the add and
1153 // the cann indvar.
1154 // FIXME: this needs to eliminate an induction variable even if it's being
1155 // compared against some value to decide loop termination.
1156 if (PN->hasOneUse()) {
1157 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +00001158 if (BO && BO->hasOneUse()) {
1159 if (PN == *(BO->use_begin())) {
1160 DeadInsts.insert(BO);
1161 // Break the cycle, then delete the PHI.
1162 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +00001163 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +00001164 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +00001165 }
Chris Lattner75a44e12005-08-02 02:52:02 +00001166 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001167 }
Nate Begemanb18121e2004-10-18 21:08:22 +00001168 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001169 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +00001170 }
Nate Begemane68bcd12005-07-30 00:15:07 +00001171
Chris Lattner11e7a5e2005-08-05 01:30:11 +00001172 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001173 IVUsesByStride.clear();
Chris Lattner4ea0a3e2005-10-09 06:20:55 +00001174 StrideOrder.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +00001175 return;
Nate Begemanb18121e2004-10-18 21:08:22 +00001176}