blob: e2f1ab6935ada33cbdbc78ccbc9e45518b569b86 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
2//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "loop-reduce"
19#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/IntrinsicInst.h"
23#include "llvm/Type.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Analysis/Dominators.h"
26#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Analysis/LoopPass.h"
28#include "llvm/Analysis/ScalarEvolutionExpander.h"
29#include "llvm/Support/CFG.h"
30#include "llvm/Support/GetElementPtrTypeIterator.h"
31#include "llvm/Transforms/Utils/BasicBlockUtils.h"
32#include "llvm/Transforms/Utils/Local.h"
33#include "llvm/Target/TargetData.h"
Evan Cheng635b8f82007-10-26 23:08:19 +000034#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/ADT/Statistic.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Target/TargetLowering.h"
39#include <algorithm>
40#include <set>
41using namespace llvm;
42
Evan Cheng335d87d2007-10-25 09:11:16 +000043STATISTIC(NumReduced , "Number of GEPs strength reduced");
44STATISTIC(NumInserted, "Number of PHIs inserted");
45STATISTIC(NumVariable, "Number of PHIs with variable strides");
46STATISTIC(NumEliminated , "Number of strides eliminated");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047
48namespace {
49
50 struct BasedUser;
51
52 /// IVStrideUse - Keep track of one use of a strided induction variable, where
53 /// the stride is stored externally. The Offset member keeps track of the
Dan Gohman3e749e92007-10-29 19:32:39 +000054 /// offset from the IV, User is the actual user of the operand, and
55 /// 'OperandValToReplace' is the operand of the User that is the use.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 struct VISIBILITY_HIDDEN IVStrideUse {
57 SCEVHandle Offset;
58 Instruction *User;
59 Value *OperandValToReplace;
60
61 // isUseOfPostIncrementedValue - True if this should use the
62 // post-incremented version of this IV, not the preincremented version.
63 // This can only be set in special cases, such as the terminating setcc
64 // instruction for a loop or uses dominated by the loop.
65 bool isUseOfPostIncrementedValue;
66
67 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
68 : Offset(Offs), User(U), OperandValToReplace(O),
69 isUseOfPostIncrementedValue(false) {}
70 };
71
72 /// IVUsersOfOneStride - This structure keeps track of all instructions that
73 /// have an operand that is based on the trip count multiplied by some stride.
74 /// The stride for all of these users is common and kept external to this
75 /// structure.
76 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
77 /// Users - Keep track of all of the users of this stride as well as the
78 /// initial value and the operand that uses the IV.
79 std::vector<IVStrideUse> Users;
80
81 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
82 Users.push_back(IVStrideUse(Offset, User, Operand));
83 }
84 };
85
86 /// IVInfo - This structure keeps track of one IV expression inserted during
87 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
88 /// well as the PHI node and increment value created for rewrite.
89 struct VISIBILITY_HIDDEN IVExpr {
90 SCEVHandle Stride;
91 SCEVHandle Base;
92 PHINode *PHI;
93 Value *IncV;
94
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
96 Value *incv)
97 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
98 };
99
100 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
101 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
102 struct VISIBILITY_HIDDEN IVsOfOneStride {
103 std::vector<IVExpr> IVs;
104
105 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
106 Value *IncV) {
107 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
108 }
109 };
110
111 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
112 LoopInfo *LI;
113 DominatorTree *DT;
114 ScalarEvolution *SE;
115 const TargetData *TD;
116 const Type *UIntPtrTy;
117 bool Changed;
118
119 /// IVUsesByStride - Keep track of all uses of induction variables that we
120 /// are interested in. The key of the map is the stride of the access.
121 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
122
123 /// IVsByStride - Keep track of all IVs that have been inserted for a
124 /// particular stride.
125 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
126
127 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
128 /// We use this to iterate over the IVUsesByStride collection without being
129 /// dependent on random ordering of pointers in the process.
Evan Chengd7ea7002007-10-30 22:27:26 +0000130 SmallVector<SCEVHandle, 16> StrideOrder;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131
132 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
133 /// of the casted version of each value. This is accessed by
134 /// getCastedVersionOf.
Evan Chengd7ea7002007-10-30 22:27:26 +0000135 DenseMap<Value*, Value*> CastedPointers;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137 /// DeadInsts - Keep track of instructions we may have made dead, so that
138 /// we can remove them after we are done working.
Evan Cheng635b8f82007-10-26 23:08:19 +0000139 SmallPtrSet<Instruction*,16> DeadInsts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140
141 /// TLI - Keep a pointer of a TargetLowering to consult for determining
142 /// transformation profitability.
143 const TargetLowering *TLI;
144
145 public:
146 static char ID; // Pass ID, replacement for typeid
Dan Gohman34c280e2007-08-01 15:32:29 +0000147 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 LoopPass((intptr_t)&ID), TLI(tli) {
149 }
150
151 bool runOnLoop(Loop *L, LPPassManager &LPM);
152
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 // We split critical edges, so we change the CFG. However, we do update
155 // many analyses if they are around.
156 AU.addPreservedID(LoopSimplifyID);
157 AU.addPreserved<LoopInfo>();
158 AU.addPreserved<DominanceFrontier>();
159 AU.addPreserved<DominatorTree>();
160
161 AU.addRequiredID(LoopSimplifyID);
162 AU.addRequired<LoopInfo>();
163 AU.addRequired<DominatorTree>();
164 AU.addRequired<TargetData>();
165 AU.addRequired<ScalarEvolution>();
166 }
167
168 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
169 ///
170 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
171private:
172 bool AddUsersIfInteresting(Instruction *I, Loop *L,
Evan Cheng635b8f82007-10-26 23:08:19 +0000173 SmallPtrSet<Instruction*,16> &Processed);
Dan Gohman5c740ec2007-10-29 19:31:25 +0000174 SCEVHandle GetExpressionSCEV(Instruction *E);
Evan Cheng335d87d2007-10-25 09:11:16 +0000175 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
176 IVStrideUse* &CondUse,
177 const SCEVHandle* &CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 void OptimizeIndvars(Loop *L);
179 bool FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
180 const SCEVHandle *&CondStride);
Evan Cheng5385ab72007-10-25 22:45:20 +0000181 bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
Evan Cheng27a820a2007-10-26 01:56:11 +0000182 unsigned CheckForIVReuse(bool, bool, const SCEVHandle&,
Dan Gohman5766ac72007-10-22 20:40:42 +0000183 IVExpr&, const Type*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 const std::vector<BasedUser>& UsersToProcess);
Dan Gohman5766ac72007-10-22 20:40:42 +0000185 bool ValidStride(bool, int64_t,
186 const std::vector<BasedUser>& UsersToProcess);
Evan Cheng5385ab72007-10-25 22:45:20 +0000187 SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
188 IVUsersOfOneStride &Uses,
189 Loop *L,
190 bool &AllUsesAreAddresses,
191 std::vector<BasedUser> &UsersToProcess);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
193 IVUsersOfOneStride &Uses,
194 Loop *L, bool isOnlyStride);
Evan Cheng635b8f82007-10-26 23:08:19 +0000195 void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*,16> &Insts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 };
197 char LoopStrengthReduce::ID = 0;
198 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
199}
200
201LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
202 return new LoopStrengthReduce(TLI);
203}
204
205/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
206/// assumes that the Value* V is of integer or pointer type only.
207///
208Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
209 Value *V) {
210 if (V->getType() == UIntPtrTy) return V;
211 if (Constant *CB = dyn_cast<Constant>(V))
212 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
213
214 Value *&New = CastedPointers[V];
215 if (New) return New;
216
217 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
218 DeadInsts.insert(cast<Instruction>(New));
219 return New;
220}
221
222
223/// DeleteTriviallyDeadInstructions - If any of the instructions is the
224/// specified set are trivially dead, delete them and see if this makes any of
225/// their operands subsequently dead.
226void LoopStrengthReduce::
Evan Cheng635b8f82007-10-26 23:08:19 +0000227DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*,16> &Insts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 while (!Insts.empty()) {
229 Instruction *I = *Insts.begin();
Evan Cheng635b8f82007-10-26 23:08:19 +0000230 Insts.erase(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 if (isInstructionTriviallyDead(I)) {
232 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
233 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
234 Insts.insert(U);
235 SE->deleteValueFromRecords(I);
236 I->eraseFromParent();
237 Changed = true;
238 }
239 }
240}
241
242
243/// GetExpressionSCEV - Compute and return the SCEV for the specified
244/// instruction.
Dan Gohman5c740ec2007-10-29 19:31:25 +0000245SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 // Pointer to pointer bitcast instructions return the same value as their
247 // operand.
248 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
249 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
250 return SE->getSCEV(BCI);
Dan Gohman5c740ec2007-10-29 19:31:25 +0000251 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 SE->setSCEV(BCI, R);
253 return R;
254 }
255
256 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
257 // If this is a GEP that SE doesn't know about, compute it now and insert it.
258 // If this is not a GEP, or if we have already done this computation, just let
259 // SE figure it out.
260 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
261 if (!GEP || SE->hasSCEV(GEP))
262 return SE->getSCEV(Exp);
263
264 // Analyze all of the subscripts of this getelementptr instruction, looking
Dan Gohman5c740ec2007-10-29 19:31:25 +0000265 // for uses that are determined by the trip count of the loop. First, skip
266 // all operands the are not dependent on the IV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267
268 // Build up the base expression. Insert an LLVM cast of the pointer to
269 // uintptr_t first.
Dan Gohman89f85052007-10-22 18:31:58 +0000270 SCEVHandle GEPVal = SE->getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
272
273 gep_type_iterator GTI = gep_type_begin(GEP);
274
275 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
276 // If this is a use of a recurrence that we can analyze, and it comes before
277 // Op does in the GEP operand list, we will handle this when we process this
278 // operand.
279 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
280 const StructLayout *SL = TD->getStructLayout(STy);
281 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
282 uint64_t Offset = SL->getElementOffset(Idx);
Dan Gohman89f85052007-10-22 18:31:58 +0000283 GEPVal = SE->getAddExpr(GEPVal,
284 SE->getIntegerSCEV(Offset, UIntPtrTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 } else {
286 unsigned GEPOpiBits =
287 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
288 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
289 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
290 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
291 Instruction::BitCast));
292 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
293 SCEVHandle Idx = SE->getSCEV(OpVal);
294
Dale Johannesen5ec2e732007-10-01 23:08:35 +0000295 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 if (TypeSize != 1)
Dan Gohman89f85052007-10-22 18:31:58 +0000297 Idx = SE->getMulExpr(Idx,
298 SE->getConstant(ConstantInt::get(UIntPtrTy,
299 TypeSize)));
300 GEPVal = SE->getAddExpr(GEPVal, Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 }
302 }
303
304 SE->setSCEV(GEP, GEPVal);
305 return GEPVal;
306}
307
308/// getSCEVStartAndStride - Compute the start and stride of this expression,
309/// returning false if the expression is not a start/stride pair, or true if it
310/// is. The stride must be a loop invariant expression, but the start may be
311/// a mix of loop invariant and loop variant expressions.
312static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Dan Gohman89f85052007-10-22 18:31:58 +0000313 SCEVHandle &Start, SCEVHandle &Stride,
314 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 SCEVHandle TheAddRec = Start; // Initialize to zero.
316
317 // If the outer level is an AddExpr, the operands are all start values except
318 // for a nested AddRecExpr.
319 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
320 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
321 if (SCEVAddRecExpr *AddRec =
322 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
323 if (AddRec->getLoop() == L)
Dan Gohman89f85052007-10-22 18:31:58 +0000324 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 else
326 return false; // Nested IV of some sort?
327 } else {
Dan Gohman89f85052007-10-22 18:31:58 +0000328 Start = SE->getAddExpr(Start, AE->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329 }
330
331 } else if (isa<SCEVAddRecExpr>(SH)) {
332 TheAddRec = SH;
333 } else {
334 return false; // not analyzable.
335 }
336
337 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
338 if (!AddRec || AddRec->getLoop() != L) return false;
339
340 // FIXME: Generalize to non-affine IV's.
341 if (!AddRec->isAffine()) return false;
342
Dan Gohman89f85052007-10-22 18:31:58 +0000343 Start = SE->getAddExpr(Start, AddRec->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344
345 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
346 DOUT << "[" << L->getHeader()->getName()
347 << "] Variable stride: " << *AddRec << "\n";
348
349 Stride = AddRec->getOperand(1);
350 return true;
351}
352
353/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
354/// and now we need to decide whether the user should use the preinc or post-inc
355/// value. If this user should use the post-inc version of the IV, return true.
356///
357/// Choosing wrong here can break dominance properties (if we choose to use the
358/// post-inc value when we cannot) or it can end up adding extra live-ranges to
359/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
360/// should use the post-inc value).
361static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
362 Loop *L, DominatorTree *DT, Pass *P) {
363 // If the user is in the loop, use the preinc value.
364 if (L->contains(User->getParent())) return false;
365
366 BasicBlock *LatchBlock = L->getLoopLatch();
367
368 // Ok, the user is outside of the loop. If it is dominated by the latch
369 // block, use the post-inc value.
370 if (DT->dominates(LatchBlock, User->getParent()))
371 return true;
372
373 // There is one case we have to be careful of: PHI nodes. These little guys
374 // can live in blocks that do not dominate the latch block, but (since their
375 // uses occur in the predecessor block, not the block the PHI lives in) should
376 // still use the post-inc value. Check for this case now.
377 PHINode *PN = dyn_cast<PHINode>(User);
378 if (!PN) return false; // not a phi, not dominated by latch block.
379
380 // Look at all of the uses of IV by the PHI node. If any use corresponds to
381 // a block that is not dominated by the latch block, give up and use the
382 // preincremented value.
383 unsigned NumUses = 0;
384 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
385 if (PN->getIncomingValue(i) == IV) {
386 ++NumUses;
387 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
388 return false;
389 }
390
391 // Okay, all uses of IV by PN are in predecessor blocks that really are
392 // dominated by the latch block. Split the critical edges and use the
393 // post-incremented value.
394 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
395 if (PN->getIncomingValue(i) == IV) {
Evan Chengd7ea7002007-10-30 22:27:26 +0000396 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 // Splitting the critical edge can reduce the number of entries in this
398 // PHI.
399 e = PN->getNumIncomingValues();
400 if (--NumUses == 0) break;
401 }
402
403 return true;
404}
405
406
407
408/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
409/// reducible SCEV, recursively add its users to the IVUsesByStride set and
410/// return true. Otherwise, return false.
411bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
Evan Cheng635b8f82007-10-26 23:08:19 +0000412 SmallPtrSet<Instruction*,16> &Processed) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
414 return false; // Void and FP expressions cannot be reduced.
Evan Cheng635b8f82007-10-26 23:08:19 +0000415 if (!Processed.insert(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 return true; // Instruction already handled.
417
418 // Get the symbolic expression for this instruction.
Dan Gohman5c740ec2007-10-29 19:31:25 +0000419 SCEVHandle ISE = GetExpressionSCEV(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 if (isa<SCEVCouldNotCompute>(ISE)) return false;
421
422 // Get the start and stride for this expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000423 SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 SCEVHandle Stride = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000425 if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 return false; // Non-reducible symbolic expression, bail out.
427
428 std::vector<Instruction *> IUsers;
429 // Collect all I uses now because IVUseShouldUsePostIncValue may
430 // invalidate use_iterator.
431 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
432 IUsers.push_back(cast<Instruction>(*UI));
433
434 for (unsigned iused_index = 0, iused_size = IUsers.size();
435 iused_index != iused_size; ++iused_index) {
436
437 Instruction *User = IUsers[iused_index];
438
439 // Do not infinitely recurse on PHI nodes.
440 if (isa<PHINode>(User) && Processed.count(User))
441 continue;
442
443 // If this is an instruction defined in a nested loop, or outside this loop,
444 // don't recurse into it.
445 bool AddUserToIVUsers = false;
446 if (LI->getLoopFor(User->getParent()) != L) {
447 DOUT << "FOUND USER in other loop: " << *User
448 << " OF SCEV: " << *ISE << "\n";
449 AddUserToIVUsers = true;
450 } else if (!AddUsersIfInteresting(User, L, Processed)) {
451 DOUT << "FOUND USER: " << *User
452 << " OF SCEV: " << *ISE << "\n";
453 AddUserToIVUsers = true;
454 }
455
456 if (AddUserToIVUsers) {
457 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
458 if (StrideUses.Users.empty()) // First occurance of this stride?
459 StrideOrder.push_back(Stride);
460
461 // Okay, we found a user that we cannot reduce. Analyze the instruction
462 // and decide what to do with it. If we are a use inside of the loop, use
463 // the value before incrementation, otherwise use it after incrementation.
464 if (IVUseShouldUsePostIncValue(User, I, L, DT, this)) {
465 // The value used will be incremented by the stride more than we are
466 // expecting, so subtract this off.
Dan Gohman89f85052007-10-22 18:31:58 +0000467 SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468 StrideUses.addUser(NewStart, User, I);
469 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
470 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
471 } else {
472 StrideUses.addUser(Start, User, I);
473 }
474 }
475 }
476 return true;
477}
478
479namespace {
480 /// BasedUser - For a particular base value, keep information about how we've
481 /// partitioned the expression so far.
482 struct BasedUser {
Dan Gohman89f85052007-10-22 18:31:58 +0000483 /// SE - The current ScalarEvolution object.
484 ScalarEvolution *SE;
485
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 /// Base - The Base value for the PHI node that needs to be inserted for
487 /// this use. As the use is processed, information gets moved from this
488 /// field to the Imm field (below). BasedUser values are sorted by this
489 /// field.
490 SCEVHandle Base;
491
492 /// Inst - The instruction using the induction variable.
493 Instruction *Inst;
494
495 /// OperandValToReplace - The operand value of Inst to replace with the
496 /// EmittedBase.
497 Value *OperandValToReplace;
498
499 /// Imm - The immediate value that should be added to the base immediately
500 /// before Inst, because it will be folded into the imm field of the
501 /// instruction.
502 SCEVHandle Imm;
503
504 /// EmittedBase - The actual value* to use for the base value of this
505 /// operation. This is null if we should just use zero so far.
506 Value *EmittedBase;
507
508 // isUseOfPostIncrementedValue - True if this should use the
509 // post-incremented version of this IV, not the preincremented version.
510 // This can only be set in special cases, such as the terminating setcc
511 // instruction for a loop and uses outside the loop that are dominated by
512 // the loop.
513 bool isUseOfPostIncrementedValue;
514
Dan Gohman89f85052007-10-22 18:31:58 +0000515 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
516 : SE(se), Base(IVSU.Offset), Inst(IVSU.User),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 OperandValToReplace(IVSU.OperandValToReplace),
Dan Gohman89f85052007-10-22 18:31:58 +0000518 Imm(SE->getIntegerSCEV(0, Base->getType())), EmittedBase(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
520
521 // Once we rewrite the code to insert the new IVs we want, update the
522 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
523 // to it.
524 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
525 SCEVExpander &Rewriter, Loop *L,
526 Pass *P);
527
528 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
529 SCEVExpander &Rewriter,
530 Instruction *IP, Loop *L);
531 void dump() const;
532 };
533}
534
535void BasedUser::dump() const {
536 cerr << " Base=" << *Base;
537 cerr << " Imm=" << *Imm;
538 if (EmittedBase)
539 cerr << " EB=" << *EmittedBase;
540
541 cerr << " Inst: " << *Inst;
542}
543
544Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
545 SCEVExpander &Rewriter,
546 Instruction *IP, Loop *L) {
547 // Figure out where we *really* want to insert this code. In particular, if
548 // the user is inside of a loop that is nested inside of L, we really don't
549 // want to insert this expression before the user, we'd rather pull it out as
550 // many loops as possible.
551 LoopInfo &LI = Rewriter.getLoopInfo();
552 Instruction *BaseInsertPt = IP;
553
554 // Figure out the most-nested loop that IP is in.
555 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
556
557 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
558 // the preheader of the outer-most loop where NewBase is not loop invariant.
559 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
560 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
561 InsertLoop = InsertLoop->getParentLoop();
562 }
563
564 // If there is no immediate value, skip the next part.
565 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
566 if (SC->getValue()->isZero())
567 return Rewriter.expandCodeFor(NewBase, BaseInsertPt);
568
569 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
570
571 // If we are inserting the base and imm values in the same block, make sure to
572 // adjust the IP position if insertion reused a result.
573 if (IP == BaseInsertPt)
574 IP = Rewriter.getInsertionPoint();
575
576 // Always emit the immediate (if non-zero) into the same block as the user.
Dan Gohman89f85052007-10-22 18:31:58 +0000577 SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 return Rewriter.expandCodeFor(NewValSCEV, IP);
579
580}
581
582
583// Once we rewrite the code to insert the new IVs we want, update the
584// operands of Inst to use the new expression 'NewBase', with 'Imm' added
585// to it.
586void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
587 SCEVExpander &Rewriter,
588 Loop *L, Pass *P) {
589 if (!isa<PHINode>(Inst)) {
590 // By default, insert code at the user instruction.
591 BasicBlock::iterator InsertPt = Inst;
592
593 // However, if the Operand is itself an instruction, the (potentially
594 // complex) inserted code may be shared by many users. Because of this, we
595 // want to emit code for the computation of the operand right before its old
596 // computation. This is usually safe, because we obviously used to use the
597 // computation when it was computed in its current block. However, in some
598 // cases (e.g. use of a post-incremented induction variable) the NewBase
599 // value will be pinned to live somewhere after the original computation.
600 // In this case, we have to back off.
601 if (!isUseOfPostIncrementedValue) {
602 if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) {
603 InsertPt = OpInst;
604 while (isa<PHINode>(InsertPt)) ++InsertPt;
605 }
606 }
607 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Dan Gohman5d1dd952007-07-31 17:22:27 +0000608 // Adjust the type back to match the Inst. Note that we can't use InsertPt
609 // here because the SCEVExpander may have inserted the instructions after
610 // that point, in its efforts to avoid inserting redundant expressions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 if (isa<PointerType>(OperandValToReplace->getType())) {
Dan Gohman5d1dd952007-07-31 17:22:27 +0000612 NewVal = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
613 NewVal,
614 OperandValToReplace->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615 }
616 // Replace the use of the operand Value with the new Phi we just created.
617 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
618 DOUT << " CHANGED: IMM =" << *Imm;
619 DOUT << " \tNEWBASE =" << *NewBase;
620 DOUT << " \tInst = " << *Inst;
621 return;
622 }
623
624 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
625 // expression into each operand block that uses it. Note that PHI nodes can
626 // have multiple entries for the same predecessor. We use a map to make sure
627 // that a PHI node only has a single Value* for each predecessor (which also
628 // prevents us from inserting duplicate code in some blocks).
Evan Chengd7ea7002007-10-30 22:27:26 +0000629 DenseMap<BasicBlock*, Value*> InsertedCode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 PHINode *PN = cast<PHINode>(Inst);
631 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
632 if (PN->getIncomingValue(i) == OperandValToReplace) {
633 // If this is a critical edge, split the edge so that we do not insert the
634 // code on all predecessor/successor paths. We do this unless this is the
635 // canonical backedge for this loop, as this can make some inserted code
636 // be in an illegal position.
637 BasicBlock *PHIPred = PN->getIncomingBlock(i);
638 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
639 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
640
641 // First step, split the critical edge.
Evan Chengd7ea7002007-10-30 22:27:26 +0000642 SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643
644 // Next step: move the basic block. In particular, if the PHI node
645 // is outside of the loop, and PredTI is in the loop, we want to
646 // move the block to be immediately before the PHI block, not
647 // immediately after PredTI.
648 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
649 BasicBlock *NewBB = PN->getIncomingBlock(i);
650 NewBB->moveBefore(PN->getParent());
651 }
652
653 // Splitting the edge can reduce the number of PHI entries we have.
654 e = PN->getNumIncomingValues();
655 }
656
657 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
658 if (!Code) {
659 // Insert the code into the end of the predecessor block.
660 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
661 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
662
Chris Lattner03dc7d72007-08-02 16:53:43 +0000663 // Adjust the type back to match the PHI. Note that we can't use
664 // InsertPt here because the SCEVExpander may have inserted its
665 // instructions after that point, in its efforts to avoid inserting
666 // redundant expressions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667 if (isa<PointerType>(PN->getType())) {
Dan Gohman5d1dd952007-07-31 17:22:27 +0000668 Code = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
669 Code,
670 PN->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 }
672 }
673
674 // Replace the use of the operand Value with the new Phi we just created.
675 PN->setIncomingValue(i, Code);
676 Rewriter.clear();
677 }
678 }
679 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
680}
681
682
683/// isTargetConstant - Return true if the following can be referenced by the
684/// immediate field of a target instruction.
685static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
686 const TargetLowering *TLI) {
687 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
688 int64_t VC = SC->getValue()->getSExtValue();
689 if (TLI) {
690 TargetLowering::AddrMode AM;
691 AM.BaseOffs = VC;
692 return TLI->isLegalAddressingMode(AM, UseTy);
693 } else {
694 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
695 return (VC > -(1 << 16) && VC < (1 << 16)-1);
696 }
697 }
698
699 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
700 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
701 if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
702 Constant *Op0 = CE->getOperand(0);
703 if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
704 TargetLowering::AddrMode AM;
705 AM.BaseGV = GV;
706 return TLI->isLegalAddressingMode(AM, UseTy);
707 }
708 }
709 return false;
710}
711
712/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
713/// loop varying to the Imm operand.
714static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman89f85052007-10-22 18:31:58 +0000715 Loop *L, ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 if (Val->isLoopInvariant(L)) return; // Nothing to do.
717
718 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
719 std::vector<SCEVHandle> NewOps;
720 NewOps.reserve(SAE->getNumOperands());
721
722 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
723 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
724 // If this is a loop-variant expression, it must stay in the immediate
725 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000726 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 } else {
728 NewOps.push_back(SAE->getOperand(i));
729 }
730
731 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000732 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 else
Dan Gohman89f85052007-10-22 18:31:58 +0000734 Val = SE->getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
736 // Try to pull immediates out of the start value of nested addrec's.
737 SCEVHandle Start = SARE->getStart();
Dan Gohman89f85052007-10-22 18:31:58 +0000738 MoveLoopVariantsToImediateField(Start, Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739
740 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
741 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000742 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 } else {
744 // Otherwise, all of Val is variant, move the whole thing over.
Dan Gohman89f85052007-10-22 18:31:58 +0000745 Imm = SE->getAddExpr(Imm, Val);
746 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 }
748}
749
750
751/// MoveImmediateValues - Look at Val, and pull out any additions of constants
752/// that can fit into the immediate field of instructions in the target.
753/// Accumulate these immediate values into the Imm value.
754static void MoveImmediateValues(const TargetLowering *TLI,
755 Instruction *User,
756 SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman89f85052007-10-22 18:31:58 +0000757 bool isAddress, Loop *L,
758 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 const Type *UseTy = User->getType();
760 if (StoreInst *SI = dyn_cast<StoreInst>(User))
761 UseTy = SI->getOperand(0)->getType();
762
763 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
764 std::vector<SCEVHandle> NewOps;
765 NewOps.reserve(SAE->getNumOperands());
766
767 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
768 SCEVHandle NewOp = SAE->getOperand(i);
Dan Gohman89f85052007-10-22 18:31:58 +0000769 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770
771 if (!NewOp->isLoopInvariant(L)) {
772 // If this is a loop-variant expression, it must stay in the immediate
773 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000774 Imm = SE->getAddExpr(Imm, NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 } else {
776 NewOps.push_back(NewOp);
777 }
778 }
779
780 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000781 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 else
Dan Gohman89f85052007-10-22 18:31:58 +0000783 Val = SE->getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 return;
785 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
786 // Try to pull immediates out of the start value of nested addrec's.
787 SCEVHandle Start = SARE->getStart();
Dan Gohman89f85052007-10-22 18:31:58 +0000788 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789
790 if (Start != SARE->getStart()) {
791 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
792 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000793 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 }
795 return;
796 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
797 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
798 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
799 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
800
Dan Gohman89f85052007-10-22 18:31:58 +0000801 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 SCEVHandle NewOp = SME->getOperand(1);
Dan Gohman89f85052007-10-22 18:31:58 +0000803 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804
805 // If we extracted something out of the subexpressions, see if we can
806 // simplify this!
807 if (NewOp != SME->getOperand(1)) {
808 // Scale SubImm up by "8". If the result is a target constant, we are
809 // good.
Dan Gohman89f85052007-10-22 18:31:58 +0000810 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 if (isTargetConstant(SubImm, UseTy, TLI)) {
812 // Accumulate the immediate.
Dan Gohman89f85052007-10-22 18:31:58 +0000813 Imm = SE->getAddExpr(Imm, SubImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814
815 // Update what is left of 'Val'.
Dan Gohman89f85052007-10-22 18:31:58 +0000816 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 return;
818 }
819 }
820 }
821 }
822
823 // Loop-variant expressions must stay in the immediate field of the
824 // expression.
825 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
826 !Val->isLoopInvariant(L)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000827 Imm = SE->getAddExpr(Imm, Val);
828 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 return;
830 }
831
832 // Otherwise, no immediates to move.
833}
834
835
836/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
837/// added together. This is used to reassociate common addition subexprs
838/// together for maximal sharing when rewriting bases.
839static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
Dan Gohman89f85052007-10-22 18:31:58 +0000840 SCEVHandle Expr,
841 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
843 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
Dan Gohman89f85052007-10-22 18:31:58 +0000844 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000846 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 if (SARE->getOperand(0) == Zero) {
848 SubExprs.push_back(Expr);
849 } else {
850 // Compute the addrec with zero as its base.
851 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
852 Ops[0] = Zero; // Start with zero base.
Dan Gohman89f85052007-10-22 18:31:58 +0000853 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854
855
Dan Gohman89f85052007-10-22 18:31:58 +0000856 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 }
858 } else if (!isa<SCEVConstant>(Expr) ||
859 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
860 // Do not add zero.
861 SubExprs.push_back(Expr);
862 }
863}
864
865
866/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
867/// removing any common subexpressions from it. Anything truly common is
868/// removed, accumulated, and returned. This looks for things like (a+b+c) and
869/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
870static SCEVHandle
Dan Gohman89f85052007-10-22 18:31:58 +0000871RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
872 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 unsigned NumUses = Uses.size();
874
875 // Only one use? Use its base, regardless of what it is!
Dan Gohman89f85052007-10-22 18:31:58 +0000876 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 SCEVHandle Result = Zero;
878 if (NumUses == 1) {
879 std::swap(Result, Uses[0].Base);
880 return Result;
881 }
882
883 // To find common subexpressions, count how many of Uses use each expression.
884 // If any subexpressions are used Uses.size() times, they are common.
885 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
886
887 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
888 // order we see them.
889 std::vector<SCEVHandle> UniqueSubExprs;
890
891 std::vector<SCEVHandle> SubExprs;
892 for (unsigned i = 0; i != NumUses; ++i) {
893 // If the base is zero (which is common), return zero now, there are no
894 // CSEs we can find.
895 if (Uses[i].Base == Zero) return Zero;
896
897 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000898 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 // Add one to SubExpressionUseCounts for each subexpr present.
900 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
901 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
902 UniqueSubExprs.push_back(SubExprs[j]);
903 SubExprs.clear();
904 }
905
906 // Now that we know how many times each is used, build Result. Iterate over
907 // UniqueSubexprs so that we have a stable ordering.
908 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
909 std::map<SCEVHandle, unsigned>::iterator I =
910 SubExpressionUseCounts.find(UniqueSubExprs[i]);
911 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
912 if (I->second == NumUses) { // Found CSE!
Dan Gohman89f85052007-10-22 18:31:58 +0000913 Result = SE->getAddExpr(Result, I->first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 } else {
915 // Remove non-cse's from SubExpressionUseCounts.
916 SubExpressionUseCounts.erase(I);
917 }
918 }
919
920 // If we found no CSE's, return now.
921 if (Result == Zero) return Result;
922
923 // Otherwise, remove all of the CSE's we found from each of the base values.
924 for (unsigned i = 0; i != NumUses; ++i) {
925 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000926 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927
928 // Remove any common subexpressions.
929 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
930 if (SubExpressionUseCounts.count(SubExprs[j])) {
931 SubExprs.erase(SubExprs.begin()+j);
932 --j; --e;
933 }
934
935 // Finally, the non-shared expressions together.
936 if (SubExprs.empty())
937 Uses[i].Base = Zero;
938 else
Dan Gohman89f85052007-10-22 18:31:58 +0000939 Uses[i].Base = SE->getAddExpr(SubExprs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940 SubExprs.clear();
941 }
942
943 return Result;
944}
945
946/// isZero - returns true if the scalar evolution expression is zero.
947///
Dan Gohman5766ac72007-10-22 20:40:42 +0000948static bool isZero(const SCEVHandle &V) {
949 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000950 return SC->getValue()->isZero();
951 return false;
952}
953
954/// ValidStride - Check whether the given Scale is valid for all loads and
955/// stores in UsersToProcess.
956///
Dan Gohman5766ac72007-10-22 20:40:42 +0000957bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
958 int64_t Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959 const std::vector<BasedUser>& UsersToProcess) {
960 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
961 // If this is a load or other access, pass the type of the access in.
962 const Type *AccessTy = Type::VoidTy;
963 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
964 AccessTy = SI->getOperand(0)->getType();
965 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
966 AccessTy = LI->getType();
967
968 TargetLowering::AddrMode AM;
969 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
970 AM.BaseOffs = SC->getValue()->getSExtValue();
Dan Gohman5766ac72007-10-22 20:40:42 +0000971 AM.HasBaseReg = HasBaseReg || !isZero(UsersToProcess[i].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 AM.Scale = Scale;
973
974 // If load[imm+r*scale] is illegal, bail out.
Evan Chenga2cd98b2007-10-26 17:24:46 +0000975 if (TLI && !TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 return false;
977 }
978 return true;
979}
980
Evan Cheng5385ab72007-10-25 22:45:20 +0000981/// RequiresTypeConversion - Returns true if converting Ty to NewTy is not
982/// a nop.
Evan Cheng27a820a2007-10-26 01:56:11 +0000983bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
984 const Type *Ty2) {
985 if (Ty1 == Ty2)
Evan Cheng5385ab72007-10-25 22:45:20 +0000986 return false;
Evan Cheng27a820a2007-10-26 01:56:11 +0000987 if (TLI && TLI->isTruncateFree(Ty1, Ty2))
988 return false;
989 return (!Ty1->canLosslesslyBitCastTo(Ty2) &&
990 !(isa<PointerType>(Ty2) &&
991 Ty1->canLosslesslyBitCastTo(UIntPtrTy)) &&
992 !(isa<PointerType>(Ty1) &&
993 Ty2->canLosslesslyBitCastTo(UIntPtrTy)));
Evan Cheng5385ab72007-10-25 22:45:20 +0000994}
995
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996/// CheckForIVReuse - Returns the multiple if the stride is the multiple
997/// of a previous stride and it is a legal value for the target addressing
Dan Gohman5766ac72007-10-22 20:40:42 +0000998/// mode scale component and optional base reg. This allows the users of
999/// this stride to be rewritten as prev iv * factor. It returns 0 if no
1000/// reuse is possible.
1001unsigned LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
Evan Cheng27a820a2007-10-26 01:56:11 +00001002 bool AllUsesAreAddresses,
Dan Gohman5766ac72007-10-22 20:40:42 +00001003 const SCEVHandle &Stride,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004 IVExpr &IV, const Type *Ty,
1005 const std::vector<BasedUser>& UsersToProcess) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1007 int64_t SInt = SC->getValue()->getSExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
1009 SE = IVsByStride.end(); SI != SE; ++SI) {
1010 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Evan Cheng27a820a2007-10-26 01:56:11 +00001011 if (SI->first != Stride &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
1013 continue;
1014 int64_t Scale = SInt / SSInt;
1015 // Check that this stride is valid for all the types used for loads and
1016 // stores; if it can be used for some and not others, we might as well use
1017 // the original stride everywhere, since we have to create the IV for it
Dan Gohman55113942007-10-29 19:23:53 +00001018 // anyway. If the scale is 1, then we don't need to worry about folding
1019 // multiplications.
1020 if (Scale == 1 ||
1021 (AllUsesAreAddresses &&
1022 ValidStride(HasBaseReg, Scale, UsersToProcess)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1024 IE = SI->second.IVs.end(); II != IE; ++II)
1025 // FIXME: Only handle base == 0 for now.
1026 // Only reuse previous IV if it would not require a type conversion.
Evan Cheng5385ab72007-10-25 22:45:20 +00001027 if (isZero(II->Base) &&
Evan Cheng27a820a2007-10-26 01:56:11 +00001028 !RequiresTypeConversion(II->Base->getType(), Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 IV = *II;
1030 return Scale;
1031 }
1032 }
1033 }
1034 return 0;
1035}
1036
1037/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1038/// returns true if Val's isUseOfPostIncrementedValue is true.
1039static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1040 return Val.isUseOfPostIncrementedValue;
1041}
1042
1043/// isNonConstantNegative - REturn true if the specified scev is negated, but
1044/// not a constant.
1045static bool isNonConstantNegative(const SCEVHandle &Expr) {
1046 SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1047 if (!Mul) return false;
1048
1049 // If there is a constant factor, it will be first.
1050 SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1051 if (!SC) return false;
1052
1053 // Return true if the value is negative, this matches things like (-42 * V).
1054 return SC->getValue()->getValue().isNegative();
1055}
1056
Evan Cheng5385ab72007-10-25 22:45:20 +00001057// CollectIVUsers - Transform our list of users and offsets to a bit more
1058// complex table. In this new vector, each 'BasedUser' contains 'Base' the base
1059// of the strided accessas well as the old information from Uses. We
1060// progressively move information from the Base field to the Imm field, until
1061// we eventually have the full access expression to rewrite the use.
1062SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1063 IVUsersOfOneStride &Uses,
1064 Loop *L,
1065 bool &AllUsesAreAddresses,
1066 std::vector<BasedUser> &UsersToProcess) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067 UsersToProcess.reserve(Uses.Users.size());
1068 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +00001069 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070
1071 // Move any loop invariant operands from the offset field to the immediate
1072 // field of the use, so that we don't try to use something before it is
1073 // computed.
1074 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001075 UsersToProcess.back().Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1077 "Base value is not loop invariant!");
1078 }
1079
1080 // We now have a whole bunch of uses of like-strided induction variables, but
1081 // they might all have different bases. We want to emit one PHI node for this
1082 // stride which we fold as many common expressions (between the IVs) into as
1083 // possible. Start by identifying the common expressions in the base values
1084 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1085 // "A+B"), emit it to the preheader, then remove the expression from the
1086 // UsersToProcess base values.
1087 SCEVHandle CommonExprs =
Dan Gohman89f85052007-10-22 18:31:58 +00001088 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE);
Dan Gohman5766ac72007-10-22 20:40:42 +00001089
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090 // Next, figure out what we can represent in the immediate fields of
1091 // instructions. If we can represent anything there, move it to the imm
1092 // fields of the BasedUsers. We do this so that it increases the commonality
1093 // of the remaining uses.
1094 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1095 // If the user is not in the current loop, this means it is using the exit
1096 // value of the IV. Do not put anything in the base, make sure it's all in
1097 // the immediate field to allow as much factoring as possible.
1098 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Dan Gohman89f85052007-10-22 18:31:58 +00001099 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1100 UsersToProcess[i].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 UsersToProcess[i].Base =
Dan Gohman89f85052007-10-22 18:31:58 +00001102 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 } else {
1104
1105 // Addressing modes can be folded into loads and stores. Be careful that
1106 // the store is through the expression, not of the expression though.
1107 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1108 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst)) {
1109 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1110 isAddress = true;
1111 } else if (IntrinsicInst *II =
1112 dyn_cast<IntrinsicInst>(UsersToProcess[i].Inst)) {
Dan Gohman5766ac72007-10-22 20:40:42 +00001113 // Addressing modes can also be folded into prefetches and a variety
1114 // of intrinsics.
1115 switch (II->getIntrinsicID()) {
1116 default: break;
1117 case Intrinsic::prefetch:
1118 case Intrinsic::x86_sse2_loadu_dq:
1119 case Intrinsic::x86_sse2_loadu_pd:
1120 case Intrinsic::x86_sse_loadu_ps:
1121 case Intrinsic::x86_sse_storeu_ps:
1122 case Intrinsic::x86_sse2_storeu_pd:
1123 case Intrinsic::x86_sse2_storeu_dq:
1124 case Intrinsic::x86_sse2_storel_dq:
1125 if (II->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1126 isAddress = true;
1127 break;
1128 case Intrinsic::x86_sse2_loadh_pd:
1129 case Intrinsic::x86_sse2_loadl_pd:
1130 if (II->getOperand(2) == UsersToProcess[i].OperandValToReplace)
1131 isAddress = true;
1132 break;
1133 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 }
Dan Gohman5766ac72007-10-22 20:40:42 +00001135
1136 // If this use isn't an address, then not all uses are addresses.
1137 if (!isAddress)
1138 AllUsesAreAddresses = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139
1140 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001141 UsersToProcess[i].Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 }
1143 }
1144
Evan Cheng5385ab72007-10-25 22:45:20 +00001145 return CommonExprs;
1146}
1147
1148/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1149/// stride of IV. All of the users may have different starting values, and this
1150/// may not be the only stride (we know it is if isOnlyStride is true).
1151void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1152 IVUsersOfOneStride &Uses,
1153 Loop *L,
1154 bool isOnlyStride) {
1155 // If all the users are moved to another stride, then there is nothing to do.
1156 if (Uses.Users.size() == 0)
1157 return;
1158
1159 // Keep track if every use in UsersToProcess is an address. If they all are,
1160 // we may be able to rewrite the entire collection of them in terms of a
1161 // smaller-stride IV.
1162 bool AllUsesAreAddresses = true;
1163
1164 // Transform our list of users and offsets to a bit more complex table. In
1165 // this new vector, each 'BasedUser' contains 'Base' the base of the
1166 // strided accessas well as the old information from Uses. We progressively
1167 // move information from the Base field to the Imm field, until we eventually
1168 // have the full access expression to rewrite the use.
1169 std::vector<BasedUser> UsersToProcess;
1170 SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1171 UsersToProcess);
1172
1173 // If we managed to find some expressions in common, we'll need to carry
1174 // their value in a register and add it in for each use. This will take up
1175 // a register operand, which potentially restricts what stride values are
1176 // valid.
1177 bool HaveCommonExprs = !isZero(CommonExprs);
1178
Dan Gohman5766ac72007-10-22 20:40:42 +00001179 // If all uses are addresses, check if it is possible to reuse an IV with a
1180 // stride that is a factor of this stride. And that the multiple is a number
1181 // that can be encoded in the scale field of the target addressing mode. And
1182 // that we will have a valid instruction after this substition, including the
1183 // immediate field, if any.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 PHINode *NewPHI = NULL;
1185 Value *IncV = NULL;
Dan Gohman89f85052007-10-22 18:31:58 +00001186 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1187 SE->getIntegerSCEV(0, Type::Int32Ty),
1188 0, 0);
Dan Gohman5766ac72007-10-22 20:40:42 +00001189 unsigned RewriteFactor = 0;
Evan Cheng27a820a2007-10-26 01:56:11 +00001190 RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1191 Stride, ReuseIV, CommonExprs->getType(),
1192 UsersToProcess);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 if (RewriteFactor != 0) {
1194 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1195 << " and BASE " << *ReuseIV.Base << " :\n";
1196 NewPHI = ReuseIV.PHI;
1197 IncV = ReuseIV.IncV;
1198 }
1199
1200 const Type *ReplacedTy = CommonExprs->getType();
1201
1202 // Now that we know what we need to do, insert the PHI node itself.
1203 //
1204 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1205 << *Stride << " and BASE " << *CommonExprs << ": ";
1206
1207 SCEVExpander Rewriter(*SE, *LI);
1208 SCEVExpander PreheaderRewriter(*SE, *LI);
1209
1210 BasicBlock *Preheader = L->getLoopPreheader();
1211 Instruction *PreInsertPt = Preheader->getTerminator();
1212 Instruction *PhiInsertBefore = L->getHeader()->begin();
1213
1214 BasicBlock *LatchBlock = L->getLoopLatch();
1215
1216
1217 // Emit the initial base value into the loop preheader.
1218 Value *CommonBaseV
1219 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt);
1220
1221 if (RewriteFactor == 0) {
1222 // Create a new Phi for this base, and stick it in the loop header.
1223 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1224 ++NumInserted;
1225
1226 // Add common base to the new Phi node.
1227 NewPHI->addIncoming(CommonBaseV, Preheader);
1228
1229 // If the stride is negative, insert a sub instead of an add for the
1230 // increment.
1231 bool isNegative = isNonConstantNegative(Stride);
1232 SCEVHandle IncAmount = Stride;
1233 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001234 IncAmount = SE->getNegativeSCEV(Stride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235
1236 // Insert the stride into the preheader.
1237 Value *StrideV = PreheaderRewriter.expandCodeFor(IncAmount, PreInsertPt);
1238 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1239
1240 // Emit the increment of the base value before the terminator of the loop
1241 // latch block, and add it to the Phi node.
Dan Gohman89f85052007-10-22 18:31:58 +00001242 SCEVHandle IncExp = SE->getUnknown(StrideV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001244 IncExp = SE->getNegativeSCEV(IncExp);
1245 IncExp = SE->getAddExpr(SE->getUnknown(NewPHI), IncExp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246
1247 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator());
1248 IncV->setName(NewPHI->getName()+".inc");
1249 NewPHI->addIncoming(IncV, LatchBlock);
1250
1251 // Remember this in case a later stride is multiple of this.
1252 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1253
1254 DOUT << " IV=%" << NewPHI->getNameStr() << " INC=%" << IncV->getNameStr();
1255 } else {
1256 Constant *C = dyn_cast<Constant>(CommonBaseV);
1257 if (!C ||
1258 (!C->isNullValue() &&
Dan Gohman89f85052007-10-22 18:31:58 +00001259 !isTargetConstant(SE->getUnknown(CommonBaseV), ReplacedTy, TLI)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 // We want the common base emitted into the preheader! This is just
1261 // using cast as a copy so BitCast (no-op cast) is appropriate
1262 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1263 "commonbase", PreInsertPt);
1264 }
1265 DOUT << "\n";
1266
1267 // We want to emit code for users inside the loop first. To do this, we
1268 // rearrange BasedUser so that the entries at the end have
1269 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1270 // vector (so we handle them first).
1271 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1272 PartitionByIsUseOfPostIncrementedValue);
1273
1274 // Sort this by base, so that things with the same base are handled
1275 // together. By partitioning first and stable-sorting later, we are
1276 // guaranteed that within each base we will pop off users from within the
1277 // loop before users outside of the loop with a particular base.
1278 //
1279 // We would like to use stable_sort here, but we can't. The problem is that
1280 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1281 // we don't have anything to do a '<' comparison on. Because we think the
1282 // number of uses is small, do a horrible bubble sort which just relies on
1283 // ==.
1284 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1285 // Get a base value.
1286 SCEVHandle Base = UsersToProcess[i].Base;
1287
Evan Chengd7ea7002007-10-30 22:27:26 +00001288 // Compact everything with this base to be consequtive with this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 for (unsigned j = i+1; j != e; ++j) {
1290 if (UsersToProcess[j].Base == Base) {
1291 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1292 ++i;
1293 }
1294 }
1295 }
1296
1297 // Process all the users now. This outer loop handles all bases, the inner
1298 // loop handles all users of a particular base.
1299 while (!UsersToProcess.empty()) {
1300 SCEVHandle Base = UsersToProcess.back().Base;
1301
1302 // Emit the code for Base into the preheader.
1303 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt);
1304
1305 DOUT << " INSERTING code for BASE = " << *Base << ":";
1306 if (BaseV->hasName())
1307 DOUT << " Result value name = %" << BaseV->getNameStr();
1308 DOUT << "\n";
1309
1310 // If BaseV is a constant other than 0, make sure that it gets inserted into
1311 // the preheader, instead of being forward substituted into the uses. We do
1312 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1313 // in this case.
1314 if (Constant *C = dyn_cast<Constant>(BaseV)) {
1315 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
1316 // We want this constant emitted into the preheader! This is just
1317 // using cast as a copy so BitCast (no-op cast) is appropriate
1318 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1319 PreInsertPt);
1320 }
1321 }
1322
1323 // Emit the code to add the immediate offset to the Phi value, just before
1324 // the instructions that we identified as using this stride and base.
1325 do {
1326 // FIXME: Use emitted users to emit other users.
1327 BasedUser &User = UsersToProcess.back();
1328
1329 // If this instruction wants to use the post-incremented value, move it
1330 // after the post-inc and use its value instead of the PHI.
1331 Value *RewriteOp = NewPHI;
1332 if (User.isUseOfPostIncrementedValue) {
1333 RewriteOp = IncV;
1334
1335 // If this user is in the loop, make sure it is the last thing in the
1336 // loop to ensure it is dominated by the increment.
1337 if (L->contains(User.Inst->getParent()))
1338 User.Inst->moveBefore(LatchBlock->getTerminator());
1339 }
1340 if (RewriteOp->getType() != ReplacedTy) {
1341 Instruction::CastOps opcode = Instruction::Trunc;
1342 if (ReplacedTy->getPrimitiveSizeInBits() ==
1343 RewriteOp->getType()->getPrimitiveSizeInBits())
1344 opcode = Instruction::BitCast;
1345 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1346 }
1347
Dan Gohman89f85052007-10-22 18:31:58 +00001348 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
1350 // Clear the SCEVExpander's expression map so that we are guaranteed
1351 // to have the code emitted where we expect it.
1352 Rewriter.clear();
1353
1354 // If we are reusing the iv, then it must be multiplied by a constant
1355 // factor take advantage of addressing mode scale component.
1356 if (RewriteFactor != 0) {
Evan Chengd7ea7002007-10-30 22:27:26 +00001357 RewriteExpr = SE->getMulExpr(SE->getIntegerSCEV(RewriteFactor,
1358 RewriteExpr->getType()),
1359 RewriteExpr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360
1361 // The common base is emitted in the loop preheader. But since we
1362 // are reusing an IV, it has not been used to initialize the PHI node.
1363 // Add it to the expression used to rewrite the uses.
1364 if (!isa<ConstantInt>(CommonBaseV) ||
1365 !cast<ConstantInt>(CommonBaseV)->isZero())
Dan Gohman89f85052007-10-22 18:31:58 +00001366 RewriteExpr = SE->getAddExpr(RewriteExpr,
1367 SE->getUnknown(CommonBaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 }
1369
1370 // Now that we know what we need to do, insert code before User for the
1371 // immediate and any loop-variant expressions.
1372 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
1373 // Add BaseV to the PHI value if needed.
Dan Gohman89f85052007-10-22 18:31:58 +00001374 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001375
1376 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1377
1378 // Mark old value we replaced as possibly dead, so that it is elminated
1379 // if we just replaced the last use of that value.
1380 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1381
1382 UsersToProcess.pop_back();
1383 ++NumReduced;
1384
1385 // If there are any more users to process with the same base, process them
1386 // now. We sorted by base above, so we just have to check the last elt.
1387 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1388 // TODO: Next, find out which base index is the most common, pull it out.
1389 }
1390
1391 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1392 // different starting values, into different PHIs.
1393}
1394
1395/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1396/// set the IV user and stride information and return true, otherwise return
1397/// false.
1398bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1399 const SCEVHandle *&CondStride) {
1400 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1401 ++Stride) {
1402 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1403 IVUsesByStride.find(StrideOrder[Stride]);
1404 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1405
1406 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1407 E = SI->second.Users.end(); UI != E; ++UI)
1408 if (UI->User == Cond) {
1409 // NOTE: we could handle setcc instructions with multiple uses here, but
1410 // InstCombine does it as well for simple uses, it's not clear that it
1411 // occurs enough in real life to handle.
1412 CondUse = &*UI;
1413 CondStride = &SI->first;
1414 return true;
1415 }
1416 }
1417 return false;
1418}
1419
Evan Cheng335d87d2007-10-25 09:11:16 +00001420namespace {
1421 // Constant strides come first which in turns are sorted by their absolute
1422 // values. If absolute values are the same, then positive strides comes first.
1423 // e.g.
1424 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1425 struct StrideCompare {
1426 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1427 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1428 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1429 if (LHSC && RHSC) {
1430 int64_t LV = LHSC->getValue()->getSExtValue();
1431 int64_t RV = RHSC->getValue()->getSExtValue();
1432 uint64_t ALV = (LV < 0) ? -LV : LV;
1433 uint64_t ARV = (RV < 0) ? -RV : RV;
1434 if (ALV == ARV)
1435 return LV > RV;
1436 else
1437 return ALV < ARV;
1438 }
1439 return (LHSC && !RHSC);
1440 }
1441 };
1442}
1443
1444/// ChangeCompareStride - If a loop termination compare instruction is the
1445/// only use of its stride, and the compaison is against a constant value,
1446/// try eliminate the stride by moving the compare instruction to another
1447/// stride and change its constant operand accordingly. e.g.
1448///
1449/// loop:
1450/// ...
1451/// v1 = v1 + 3
1452/// v2 = v2 + 1
1453/// if (v2 < 10) goto loop
1454/// =>
1455/// loop:
1456/// ...
1457/// v1 = v1 + 3
1458/// if (v1 < 30) goto loop
1459ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1460 IVStrideUse* &CondUse,
1461 const SCEVHandle* &CondStride) {
1462 if (StrideOrder.size() < 2 ||
1463 IVUsesByStride[*CondStride].Users.size() != 1)
1464 return Cond;
Evan Cheng335d87d2007-10-25 09:11:16 +00001465 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1466 if (!SC) return Cond;
1467 ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1));
1468 if (!C) return Cond;
1469
1470 ICmpInst::Predicate Predicate = Cond->getPredicate();
Evan Cheng335d87d2007-10-25 09:11:16 +00001471 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1472 int64_t CmpVal = C->getValue().getSExtValue();
Evan Cheng635b8f82007-10-26 23:08:19 +00001473 unsigned BitWidth = C->getValue().getBitWidth();
1474 uint64_t SignBit = 1ULL << (BitWidth-1);
1475 const Type *CmpTy = C->getType();
1476 const Type *NewCmpTy = NULL;
Evan Cheng0ae1de62007-10-29 22:07:18 +00001477 unsigned TyBits = CmpTy->getPrimitiveSizeInBits();
1478 unsigned NewTyBits = 0;
Evan Cheng335d87d2007-10-25 09:11:16 +00001479 int64_t NewCmpVal = CmpVal;
1480 SCEVHandle *NewStride = NULL;
1481 Value *NewIncV = NULL;
1482 int64_t Scale = 1;
Evan Cheng335d87d2007-10-25 09:11:16 +00001483
1484 // Look for a suitable stride / iv as replacement.
1485 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1486 for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
1487 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1488 IVUsesByStride.find(StrideOrder[i]);
1489 if (!isa<SCEVConstant>(SI->first))
1490 continue;
1491 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
Evan Cheng635b8f82007-10-26 23:08:19 +00001492 if (abs(SSInt) <= abs(CmpSSInt) || (SSInt % CmpSSInt) != 0)
Evan Cheng335d87d2007-10-25 09:11:16 +00001493 continue;
1494
Evan Cheng635b8f82007-10-26 23:08:19 +00001495 Scale = SSInt / CmpSSInt;
1496 NewCmpVal = CmpVal * Scale;
1497 APInt Mul = APInt(BitWidth, NewCmpVal);
1498 // Check for overflow.
1499 if (Mul.getSExtValue() != NewCmpVal) {
Evan Cheng335d87d2007-10-25 09:11:16 +00001500 NewCmpVal = CmpVal;
Evan Cheng635b8f82007-10-26 23:08:19 +00001501 continue;
1502 }
1503
1504 // Watch out for overflow.
1505 if (ICmpInst::isSignedPredicate(Predicate) &&
1506 (CmpVal & SignBit) != (NewCmpVal & SignBit))
1507 NewCmpVal = CmpVal;
1508
Evan Cheng335d87d2007-10-25 09:11:16 +00001509 if (NewCmpVal != CmpVal) {
1510 // Pick the best iv to use trying to avoid a cast.
1511 NewIncV = NULL;
1512 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1513 E = SI->second.Users.end(); UI != E; ++UI) {
Evan Cheng335d87d2007-10-25 09:11:16 +00001514 NewIncV = UI->OperandValToReplace;
1515 if (NewIncV->getType() == CmpTy)
1516 break;
1517 }
1518 if (!NewIncV) {
1519 NewCmpVal = CmpVal;
1520 continue;
1521 }
1522
Evan Cheng335d87d2007-10-25 09:11:16 +00001523 NewCmpTy = NewIncV->getType();
Evan Cheng0ae1de62007-10-29 22:07:18 +00001524 NewTyBits = isa<PointerType>(NewCmpTy)
1525 ? UIntPtrTy->getPrimitiveSizeInBits()
1526 : NewCmpTy->getPrimitiveSizeInBits();
1527 if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
1528 // Check if it is possible to rewrite it using a iv / stride of a smaller
1529 // integer type.
1530 bool TruncOk = false;
1531 if (NewCmpTy->isInteger()) {
1532 unsigned Bits = NewTyBits;
1533 if (ICmpInst::isSignedPredicate(Predicate))
1534 --Bits;
1535 uint64_t Mask = (1ULL << Bits) - 1;
1536 if (((uint64_t)NewCmpVal & Mask) == (uint64_t)NewCmpVal)
1537 TruncOk = true;
1538 }
1539 if (!TruncOk) {
1540 NewCmpVal = CmpVal;
1541 continue;
1542 }
1543 }
1544
1545 // Don't rewrite if use offset is non-constant and the new type is
1546 // of a different type.
1547 // FIXME: too conservative?
1548 if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset)) {
Evan Cheng5385ab72007-10-25 22:45:20 +00001549 NewCmpVal = CmpVal;
1550 continue;
1551 }
1552
1553 bool AllUsesAreAddresses = true;
1554 std::vector<BasedUser> UsersToProcess;
1555 SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
1556 AllUsesAreAddresses,
1557 UsersToProcess);
1558 // Avoid rewriting the compare instruction with an iv of new stride
1559 // if it's likely the new stride uses will be rewritten using the
1560 if (AllUsesAreAddresses &&
1561 ValidStride(!isZero(CommonExprs), Scale, UsersToProcess)) {
Evan Cheng335d87d2007-10-25 09:11:16 +00001562 NewCmpVal = CmpVal;
1563 continue;
1564 }
1565
1566 // If scale is negative, use inverse predicate unless it's testing
1567 // for equality.
1568 if (Scale < 0 && !Cond->isEquality())
1569 Predicate = ICmpInst::getInversePredicate(Predicate);
1570
1571 NewStride = &StrideOrder[i];
1572 break;
1573 }
1574 }
1575
1576 if (NewCmpVal != CmpVal) {
1577 // Create a new compare instruction using new stride / iv.
1578 ICmpInst *OldCond = Cond;
Evan Cheng0ae1de62007-10-29 22:07:18 +00001579 Value *RHS;
1580 if (!isa<PointerType>(NewCmpTy))
1581 RHS = ConstantInt::get(NewCmpTy, NewCmpVal);
1582 else {
1583 RHS = ConstantInt::get(UIntPtrTy, NewCmpVal);
1584 RHS = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr, RHS, NewCmpTy);
Evan Cheng335d87d2007-10-25 09:11:16 +00001585 }
Evan Cheng635b8f82007-10-26 23:08:19 +00001586 // Insert new compare instruction.
Evan Cheng335d87d2007-10-25 09:11:16 +00001587 Cond = new ICmpInst(Predicate, NewIncV, RHS);
1588 Cond->setName(L->getHeader()->getName() + ".termcond");
1589 OldCond->getParent()->getInstList().insert(OldCond, Cond);
Evan Cheng635b8f82007-10-26 23:08:19 +00001590
1591 // Remove the old compare instruction. The old indvar is probably dead too.
1592 DeadInsts.insert(cast<Instruction>(CondUse->OperandValToReplace));
Evan Cheng335d87d2007-10-25 09:11:16 +00001593 OldCond->replaceAllUsesWith(Cond);
Evan Cheng635b8f82007-10-26 23:08:19 +00001594 SE->deleteValueFromRecords(OldCond);
Evan Cheng335d87d2007-10-25 09:11:16 +00001595 OldCond->eraseFromParent();
Evan Cheng635b8f82007-10-26 23:08:19 +00001596
Evan Cheng335d87d2007-10-25 09:11:16 +00001597 IVUsesByStride[*CondStride].Users.pop_back();
Evan Cheng0ae1de62007-10-29 22:07:18 +00001598 SCEVHandle NewOffset = TyBits == NewTyBits
1599 ? SE->getMulExpr(CondUse->Offset,
1600 SE->getConstant(ConstantInt::get(CmpTy, Scale)))
1601 : SE->getConstant(ConstantInt::get(NewCmpTy,
1602 cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
Evan Cheng335d87d2007-10-25 09:11:16 +00001603 IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewIncV);
1604 CondUse = &IVUsesByStride[*NewStride].Users.back();
1605 CondStride = NewStride;
1606 ++NumEliminated;
1607 }
1608
1609 return Cond;
1610}
1611
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1613// uses in the loop, look to see if we can eliminate some, in favor of using
1614// common indvars for the different uses.
1615void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1616 // TODO: implement optzns here.
1617
1618 // Finally, get the terminating condition for the loop if possible. If we
1619 // can, we want to change it to use a post-incremented version of its
1620 // induction variable, to allow coalescing the live ranges for the IV into
1621 // one register value.
1622 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1623 BasicBlock *Preheader = L->getLoopPreheader();
1624 BasicBlock *LatchBlock =
1625 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1626 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1627 if (!TermBr || TermBr->isUnconditional() ||
1628 !isa<ICmpInst>(TermBr->getCondition()))
1629 return;
1630 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1631
1632 // Search IVUsesByStride to find Cond's IVUse if there is one.
1633 IVStrideUse *CondUse = 0;
1634 const SCEVHandle *CondStride = 0;
1635
1636 if (!FindIVForUser(Cond, CondUse, CondStride))
1637 return; // setcc doesn't use the IV.
Evan Cheng335d87d2007-10-25 09:11:16 +00001638
1639 // If possible, change stride and operands of the compare instruction to
1640 // eliminate one stride.
1641 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642
1643 // It's possible for the setcc instruction to be anywhere in the loop, and
1644 // possible for it to have multiple users. If it is not immediately before
1645 // the latch block branch, move it.
1646 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1647 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1648 Cond->moveBefore(TermBr);
1649 } else {
1650 // Otherwise, clone the terminating condition and insert into the loopend.
1651 Cond = cast<ICmpInst>(Cond->clone());
1652 Cond->setName(L->getHeader()->getName() + ".termcond");
1653 LatchBlock->getInstList().insert(TermBr, Cond);
1654
1655 // Clone the IVUse, as the old use still exists!
1656 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1657 CondUse->OperandValToReplace);
1658 CondUse = &IVUsesByStride[*CondStride].Users.back();
1659 }
1660 }
1661
1662 // If we get to here, we know that we can transform the setcc instruction to
1663 // use the post-incremented version of the IV, allowing us to coalesce the
1664 // live ranges for the IV correctly.
Dan Gohman89f85052007-10-22 18:31:58 +00001665 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666 CondUse->isUseOfPostIncrementedValue = true;
1667}
1668
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
1670
1671 LI = &getAnalysis<LoopInfo>();
1672 DT = &getAnalysis<DominatorTree>();
1673 SE = &getAnalysis<ScalarEvolution>();
1674 TD = &getAnalysis<TargetData>();
1675 UIntPtrTy = TD->getIntPtrType();
1676
1677 // Find all uses of induction variables in this loop, and catagorize
1678 // them by stride. Start by finding all of the PHI nodes in the header for
1679 // this loop. If they are induction variables, inspect their uses.
Evan Cheng635b8f82007-10-26 23:08:19 +00001680 SmallPtrSet<Instruction*,16> Processed; // Don't reprocess instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1682 AddUsersIfInteresting(I, L, Processed);
1683
1684 // If we have nothing to do, return.
1685 if (IVUsesByStride.empty()) return false;
1686
1687 // Optimize induction variables. Some indvar uses can be transformed to use
1688 // strides that will be needed for other purposes. A common example of this
1689 // is the exit test for the loop, which can often be rewritten to use the
1690 // computation of some other indvar to decide when to terminate the loop.
1691 OptimizeIndvars(L);
1692
1693
1694 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1695 // doing computation in byte values, promote to 32-bit values if safe.
1696
1697 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1698 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1699 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1700 // to be careful that IV's are all the same type. Only works for intptr_t
1701 // indvars.
1702
1703 // If we only have one stride, we can more aggressively eliminate some things.
1704 bool HasOneStride = IVUsesByStride.size() == 1;
1705
1706#ifndef NDEBUG
1707 DOUT << "\nLSR on ";
1708 DEBUG(L->dump());
1709#endif
1710
1711 // IVsByStride keeps IVs for one particular loop.
1712 IVsByStride.clear();
1713
1714 // Sort the StrideOrder so we process larger strides first.
1715 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1716
1717 // Note: this processes each stride/type pair individually. All users passed
1718 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
Dan Gohman04c58c12007-10-29 19:26:14 +00001719 // note that we iterate over IVUsesByStride indirectly by using StrideOrder.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720 // This extra layer of indirection makes the ordering of strides deterministic
1721 // - not dependent on map order.
1722 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1723 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1724 IVUsesByStride.find(StrideOrder[Stride]);
1725 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1726 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1727 }
1728
1729 // Clean up after ourselves
1730 if (!DeadInsts.empty()) {
1731 DeleteTriviallyDeadInstructions(DeadInsts);
1732
1733 BasicBlock::iterator I = L->getHeader()->begin();
1734 PHINode *PN;
1735 while ((PN = dyn_cast<PHINode>(I))) {
1736 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1737
1738 // At this point, we know that we have killed one or more GEP
1739 // instructions. It is worth checking to see if the cann indvar is also
1740 // dead, so that we can remove it as well. The requirements for the cann
1741 // indvar to be considered dead are:
1742 // 1. the cann indvar has one use
1743 // 2. the use is an add instruction
1744 // 3. the add has one use
1745 // 4. the add is used by the cann indvar
1746 // If all four cases above are true, then we can remove both the add and
1747 // the cann indvar.
1748 // FIXME: this needs to eliminate an induction variable even if it's being
1749 // compared against some value to decide loop termination.
1750 if (PN->hasOneUse()) {
1751 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1752 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1753 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
1754 DeadInsts.insert(BO);
1755 // Break the cycle, then delete the PHI.
1756 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1757 SE->deleteValueFromRecords(PN);
1758 PN->eraseFromParent();
1759 }
1760 }
1761 }
1762 }
1763 DeleteTriviallyDeadInstructions(DeadInsts);
1764 }
1765
1766 CastedPointers.clear();
1767 IVUsesByStride.clear();
1768 StrideOrder.clear();
1769 return false;
1770}