blob: 6f2b1b4ce05f3671003ec27daa47e934d95474ba [file] [log] [blame]
Nate Begemanb18121e2004-10-18 21:08:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
10// This pass performs a strength reduction on array references inside loops that
11// have as one or more of their components the loop induction variable. This is
12// accomplished by creating a new Value to hold the initial value of the array
13// access for the first iteration, and then creating a new GEP instruction in
14// the loop to increment the value by the appropriate amount.
15//
Nate Begemanb18121e2004-10-18 21:08:22 +000016//===----------------------------------------------------------------------===//
17
Chris Lattnerbb78c972005-08-03 23:30:08 +000018#define DEBUG_TYPE "loop-reduce"
Nate Begemanb18121e2004-10-18 21:08:22 +000019#include "llvm/Transforms/Scalar.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/Type.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000023#include "llvm/DerivedTypes.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000024#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/LoopInfo.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000027#include "llvm/Support/CFG.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000028#include "llvm/Support/GetElementPtrTypeIterator.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000029#include "llvm/Transforms/Utils/Local.h"
Jeff Cohena2c59b72005-03-04 04:04:26 +000030#include "llvm/Target/TargetData.h"
Nate Begemanb18121e2004-10-18 21:08:22 +000031#include "llvm/ADT/Statistic.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000032#include "llvm/Support/Debug.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000033#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000034#include <set>
35using namespace llvm;
36
37namespace {
38 Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
Chris Lattner45f8b6e2005-08-04 22:34:05 +000039 Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
Nate Begemanb18121e2004-10-18 21:08:22 +000040
Chris Lattner430d0022005-08-03 22:21:05 +000041 /// IVStrideUse - Keep track of one use of a strided induction variable, where
42 /// the stride is stored externally. The Offset member keeps track of the
43 /// offset from the IV, User is the actual user of the operand, and 'Operand'
44 /// is the operand # of the User that is the use.
45 struct IVStrideUse {
46 SCEVHandle Offset;
47 Instruction *User;
48 Value *OperandValToReplace;
Chris Lattner9bfa6f82005-08-08 05:28:22 +000049
50 // isUseOfPostIncrementedValue - True if this should use the
51 // post-incremented version of this IV, not the preincremented version.
52 // This can only be set in special cases, such as the terminating setcc
53 // instruction for a loop.
54 bool isUseOfPostIncrementedValue;
Chris Lattner430d0022005-08-03 22:21:05 +000055
56 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
Chris Lattner9bfa6f82005-08-08 05:28:22 +000057 : Offset(Offs), User(U), OperandValToReplace(O),
58 isUseOfPostIncrementedValue(false) {}
Chris Lattner430d0022005-08-03 22:21:05 +000059 };
60
61 /// IVUsersOfOneStride - This structure keeps track of all instructions that
62 /// have an operand that is based on the trip count multiplied by some stride.
63 /// The stride for all of these users is common and kept external to this
64 /// structure.
65 struct IVUsersOfOneStride {
Nate Begemane68bcd12005-07-30 00:15:07 +000066 /// Users - Keep track of all of the users of this stride as well as the
Chris Lattner430d0022005-08-03 22:21:05 +000067 /// initial value and the operand that uses the IV.
68 std::vector<IVStrideUse> Users;
69
70 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
71 Users.push_back(IVStrideUse(Offset, User, Operand));
Nate Begemane68bcd12005-07-30 00:15:07 +000072 }
73 };
74
75
Nate Begemanb18121e2004-10-18 21:08:22 +000076 class LoopStrengthReduce : public FunctionPass {
77 LoopInfo *LI;
78 DominatorSet *DS;
Nate Begemane68bcd12005-07-30 00:15:07 +000079 ScalarEvolution *SE;
80 const TargetData *TD;
81 const Type *UIntPtrTy;
Nate Begemanb18121e2004-10-18 21:08:22 +000082 bool Changed;
Chris Lattner75a44e12005-08-02 02:52:02 +000083
84 /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
85 /// target can handle for free with its addressing modes.
Jeff Cohena2c59b72005-03-04 04:04:26 +000086 unsigned MaxTargetAMSize;
Nate Begemane68bcd12005-07-30 00:15:07 +000087
88 /// IVUsesByStride - Keep track of all uses of induction variables that we
89 /// are interested in. The key of the map is the stride of the access.
Chris Lattner430d0022005-08-03 22:21:05 +000090 std::map<Value*, IVUsersOfOneStride> IVUsesByStride;
Nate Begemane68bcd12005-07-30 00:15:07 +000091
Chris Lattner6f286b72005-08-04 01:19:13 +000092 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
93 /// of the casted version of each value. This is accessed by
94 /// getCastedVersionOf.
95 std::map<Value*, Value*> CastedPointers;
Nate Begemane68bcd12005-07-30 00:15:07 +000096
97 /// DeadInsts - Keep track of instructions we may have made dead, so that
98 /// we can remove them after we are done working.
99 std::set<Instruction*> DeadInsts;
Nate Begemanb18121e2004-10-18 21:08:22 +0000100 public:
Jeff Cohena2c59b72005-03-04 04:04:26 +0000101 LoopStrengthReduce(unsigned MTAMS = 1)
102 : MaxTargetAMSize(MTAMS) {
103 }
104
Nate Begemanb18121e2004-10-18 21:08:22 +0000105 virtual bool runOnFunction(Function &) {
106 LI = &getAnalysis<LoopInfo>();
107 DS = &getAnalysis<DominatorSet>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000108 SE = &getAnalysis<ScalarEvolution>();
109 TD = &getAnalysis<TargetData>();
110 UIntPtrTy = TD->getIntPtrType();
Nate Begemanb18121e2004-10-18 21:08:22 +0000111 Changed = false;
112
113 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
114 runOnLoop(*I);
Chris Lattner6f286b72005-08-04 01:19:13 +0000115
Nate Begemanb18121e2004-10-18 21:08:22 +0000116 return Changed;
117 }
118
119 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
120 AU.setPreservesCFG();
Jeff Cohen39751c32005-02-27 19:37:07 +0000121 AU.addRequiredID(LoopSimplifyID);
Nate Begemanb18121e2004-10-18 21:08:22 +0000122 AU.addRequired<LoopInfo>();
123 AU.addRequired<DominatorSet>();
Jeff Cohena2c59b72005-03-04 04:04:26 +0000124 AU.addRequired<TargetData>();
Nate Begemane68bcd12005-07-30 00:15:07 +0000125 AU.addRequired<ScalarEvolution>();
Nate Begemanb18121e2004-10-18 21:08:22 +0000126 }
Chris Lattner6f286b72005-08-04 01:19:13 +0000127
128 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
129 ///
130 Value *getCastedVersionOf(Value *V);
131private:
Nate Begemanb18121e2004-10-18 21:08:22 +0000132 void runOnLoop(Loop *L);
Chris Lattnereaf24722005-08-04 17:40:30 +0000133 bool AddUsersIfInteresting(Instruction *I, Loop *L,
134 std::set<Instruction*> &Processed);
135 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
136
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000137 void OptimizeIndvars(Loop *L);
Nate Begemane68bcd12005-07-30 00:15:07 +0000138
Chris Lattner430d0022005-08-03 22:21:05 +0000139 void StrengthReduceStridedIVUsers(Value *Stride, IVUsersOfOneStride &Uses,
140 Loop *L, bool isOnlyStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000141 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
142 };
Misha Brukmanb1c93172005-04-21 23:48:37 +0000143 RegisterOpt<LoopStrengthReduce> X("loop-reduce",
Nate Begemanb18121e2004-10-18 21:08:22 +0000144 "Strength Reduce GEP Uses of Ind. Vars");
145}
146
Jeff Cohena2c59b72005-03-04 04:04:26 +0000147FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
148 return new LoopStrengthReduce(MaxTargetAMSize);
Nate Begemanb18121e2004-10-18 21:08:22 +0000149}
150
Chris Lattner6f286b72005-08-04 01:19:13 +0000151/// getCastedVersionOf - Return the specified value casted to uintptr_t.
152///
153Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
154 if (V->getType() == UIntPtrTy) return V;
155 if (Constant *CB = dyn_cast<Constant>(V))
156 return ConstantExpr::getCast(CB, UIntPtrTy);
157
158 Value *&New = CastedPointers[V];
159 if (New) return New;
160
161 BasicBlock::iterator InsertPt;
162 if (Argument *Arg = dyn_cast<Argument>(V)) {
163 // Insert into the entry of the function, after any allocas.
164 InsertPt = Arg->getParent()->begin()->begin();
165 while (isa<AllocaInst>(InsertPt)) ++InsertPt;
166 } else {
167 if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
168 InsertPt = II->getNormalDest()->begin();
169 } else {
170 InsertPt = cast<Instruction>(V);
171 ++InsertPt;
172 }
173
174 // Do not insert casts into the middle of PHI node blocks.
175 while (isa<PHINode>(InsertPt)) ++InsertPt;
176 }
Chris Lattneracc42c42005-08-04 19:08:16 +0000177
178 New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
179 DeadInsts.insert(cast<Instruction>(New));
180 return New;
Chris Lattner6f286b72005-08-04 01:19:13 +0000181}
182
183
Nate Begemanb18121e2004-10-18 21:08:22 +0000184/// DeleteTriviallyDeadInstructions - If any of the instructions is the
185/// specified set are trivially dead, delete them and see if this makes any of
186/// their operands subsequently dead.
187void LoopStrengthReduce::
188DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
189 while (!Insts.empty()) {
190 Instruction *I = *Insts.begin();
191 Insts.erase(Insts.begin());
192 if (isInstructionTriviallyDead(I)) {
Jeff Cohen8ea6f9e2005-03-01 03:46:11 +0000193 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
194 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
195 Insts.insert(U);
Chris Lattner84e9baa2005-08-03 21:36:09 +0000196 SE->deleteInstructionFromRecords(I);
197 I->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000198 Changed = true;
199 }
200 }
201}
202
Jeff Cohen39751c32005-02-27 19:37:07 +0000203
Chris Lattnereaf24722005-08-04 17:40:30 +0000204/// GetExpressionSCEV - Compute and return the SCEV for the specified
205/// instruction.
206SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
207 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
208 if (!GEP)
209 return SE->getSCEV(Exp);
210
Nate Begemane68bcd12005-07-30 00:15:07 +0000211 // Analyze all of the subscripts of this getelementptr instruction, looking
212 // for uses that are determined by the trip count of L. First, skip all
213 // operands the are not dependent on the IV.
214
215 // Build up the base expression. Insert an LLVM cast of the pointer to
216 // uintptr_t first.
Chris Lattnereaf24722005-08-04 17:40:30 +0000217 SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
Nate Begemane68bcd12005-07-30 00:15:07 +0000218
219 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnereaf24722005-08-04 17:40:30 +0000220
221 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
Nate Begemane68bcd12005-07-30 00:15:07 +0000222 // If this is a use of a recurrence that we can analyze, and it comes before
223 // Op does in the GEP operand list, we will handle this when we process this
224 // operand.
225 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
226 const StructLayout *SL = TD->getStructLayout(STy);
227 unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
228 uint64_t Offset = SL->MemberOffsets[Idx];
Chris Lattnereaf24722005-08-04 17:40:30 +0000229 GEPVal = SCEVAddExpr::get(GEPVal,
230 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
Nate Begemane68bcd12005-07-30 00:15:07 +0000231 } else {
Chris Lattneracc42c42005-08-04 19:08:16 +0000232 Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
233 SCEVHandle Idx = SE->getSCEV(OpVal);
234
Chris Lattnereaf24722005-08-04 17:40:30 +0000235 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
236 if (TypeSize != 1)
237 Idx = SCEVMulExpr::get(Idx,
238 SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
239 TypeSize)));
240 GEPVal = SCEVAddExpr::get(GEPVal, Idx);
Nate Begemane68bcd12005-07-30 00:15:07 +0000241 }
242 }
243
Chris Lattnereaf24722005-08-04 17:40:30 +0000244 return GEPVal;
Nate Begemane68bcd12005-07-30 00:15:07 +0000245}
246
Chris Lattneracc42c42005-08-04 19:08:16 +0000247/// getSCEVStartAndStride - Compute the start and stride of this expression,
248/// returning false if the expression is not a start/stride pair, or true if it
249/// is. The stride must be a loop invariant expression, but the start may be
250/// a mix of loop invariant and loop variant expressions.
251static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
252 SCEVHandle &Start, Value *&Stride) {
253 SCEVHandle TheAddRec = Start; // Initialize to zero.
254
255 // If the outer level is an AddExpr, the operands are all start values except
256 // for a nested AddRecExpr.
257 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
258 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
259 if (SCEVAddRecExpr *AddRec =
260 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
261 if (AddRec->getLoop() == L)
262 TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
263 else
264 return false; // Nested IV of some sort?
265 } else {
266 Start = SCEVAddExpr::get(Start, AE->getOperand(i));
267 }
268
269 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
270 TheAddRec = SH;
271 } else {
272 return false; // not analyzable.
273 }
274
275 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
276 if (!AddRec || AddRec->getLoop() != L) return false;
277
278 // FIXME: Generalize to non-affine IV's.
279 if (!AddRec->isAffine()) return false;
280
281 Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
282
283 // FIXME: generalize to IV's with more complex strides (must emit stride
284 // expression outside of loop!)
285 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
286 return false;
287
288 SCEVConstant *StrideC = cast<SCEVConstant>(AddRec->getOperand(1));
289 Stride = StrideC->getValue();
290
291 assert(Stride->getType()->isUnsigned() &&
292 "Constants should be canonicalized to unsigned!");
293 return true;
294}
295
Nate Begemane68bcd12005-07-30 00:15:07 +0000296/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
297/// reducible SCEV, recursively add its users to the IVUsesByStride set and
298/// return true. Otherwise, return false.
Chris Lattnereaf24722005-08-04 17:40:30 +0000299bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
300 std::set<Instruction*> &Processed) {
Nate Begeman17a0e2af2005-07-30 00:21:31 +0000301 if (I->getType() == Type::VoidTy) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000302 if (!Processed.insert(I).second)
303 return true; // Instruction already handled.
304
Chris Lattneracc42c42005-08-04 19:08:16 +0000305 // Get the symbolic expression for this instruction.
Chris Lattnereaf24722005-08-04 17:40:30 +0000306 SCEVHandle ISE = GetExpressionSCEV(I, L);
Chris Lattneracc42c42005-08-04 19:08:16 +0000307 if (isa<SCEVCouldNotCompute>(ISE)) return false;
Chris Lattnereaf24722005-08-04 17:40:30 +0000308
Chris Lattneracc42c42005-08-04 19:08:16 +0000309 // Get the start and stride for this expression.
310 SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
311 Value *Stride = 0;
312 if (!getSCEVStartAndStride(ISE, L, Start, Stride))
313 return false; // Non-reducible symbolic expression, bail out.
314
Nate Begemane68bcd12005-07-30 00:15:07 +0000315 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
316 Instruction *User = cast<Instruction>(*UI);
317
318 // Do not infinitely recurse on PHI nodes.
319 if (isa<PHINode>(User) && User->getParent() == L->getHeader())
320 continue;
321
322 // If this is an instruction defined in a nested loop, or outside this loop,
Chris Lattnera0102fb2005-08-04 00:14:11 +0000323 // don't recurse into it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000324 bool AddUserToIVUsers = false;
Chris Lattnera0102fb2005-08-04 00:14:11 +0000325 if (LI->getLoopFor(User->getParent()) != L) {
326 DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
327 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000328 AddUserToIVUsers = true;
Chris Lattnereaf24722005-08-04 17:40:30 +0000329 } else if (!AddUsersIfInteresting(User, L, Processed)) {
Chris Lattner65107492005-08-04 00:40:47 +0000330 DEBUG(std::cerr << "FOUND USER: " << *User
331 << " OF SCEV: " << *ISE << "\n");
Chris Lattneracc42c42005-08-04 19:08:16 +0000332 AddUserToIVUsers = true;
333 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000334
Chris Lattneracc42c42005-08-04 19:08:16 +0000335 if (AddUserToIVUsers) {
Chris Lattner65107492005-08-04 00:40:47 +0000336 // Okay, we found a user that we cannot reduce. Analyze the instruction
337 // and decide what to do with it.
Chris Lattneracc42c42005-08-04 19:08:16 +0000338 IVUsesByStride[Stride].addUser(Start, User, I);
Nate Begemane68bcd12005-07-30 00:15:07 +0000339 }
340 }
341 return true;
342}
343
344namespace {
345 /// BasedUser - For a particular base value, keep information about how we've
346 /// partitioned the expression so far.
347 struct BasedUser {
348 /// Inst - The instruction using the induction variable.
349 Instruction *Inst;
350
Chris Lattner430d0022005-08-03 22:21:05 +0000351 /// OperandValToReplace - The operand value of Inst to replace with the
352 /// EmittedBase.
353 Value *OperandValToReplace;
Nate Begemane68bcd12005-07-30 00:15:07 +0000354
355 /// Imm - The immediate value that should be added to the base immediately
356 /// before Inst, because it will be folded into the imm field of the
357 /// instruction.
358 SCEVHandle Imm;
359
360 /// EmittedBase - The actual value* to use for the base value of this
361 /// operation. This is null if we should just use zero so far.
362 Value *EmittedBase;
363
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000364 // isUseOfPostIncrementedValue - True if this should use the
365 // post-incremented version of this IV, not the preincremented version.
366 // This can only be set in special cases, such as the terminating setcc
367 // instruction for a loop.
368 bool isUseOfPostIncrementedValue;
369
370 BasedUser(Instruction *I, Value *Op, const SCEVHandle &IMM, bool iUOPIV)
371 : Inst(I), OperandValToReplace(Op), Imm(IMM), EmittedBase(0),
372 isUseOfPostIncrementedValue(iUOPIV) {}
Nate Begemane68bcd12005-07-30 00:15:07 +0000373
Chris Lattnera6d7c352005-08-04 20:03:32 +0000374 // Once we rewrite the code to insert the new IVs we want, update the
375 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
376 // to it.
377 void RewriteInstructionToUseNewBase(Value *NewBase, SCEVExpander &Rewriter);
Nate Begemane68bcd12005-07-30 00:15:07 +0000378
379 // No need to compare these.
380 bool operator<(const BasedUser &BU) const { return 0; }
381
382 void dump() const;
383 };
384}
385
386void BasedUser::dump() const {
387 std::cerr << " Imm=" << *Imm;
388 if (EmittedBase)
389 std::cerr << " EB=" << *EmittedBase;
390
391 std::cerr << " Inst: " << *Inst;
392}
393
Chris Lattnera6d7c352005-08-04 20:03:32 +0000394// Once we rewrite the code to insert the new IVs we want, update the
395// operands of Inst to use the new expression 'NewBase', with 'Imm' added
396// to it.
397void BasedUser::RewriteInstructionToUseNewBase(Value *NewBase,
398 SCEVExpander &Rewriter) {
399 if (!isa<PHINode>(Inst)) {
400 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm);
401 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
402 OperandValToReplace->getType());
403
404 // Replace the use of the operand Value with the new Phi we just created.
405 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
406 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
407 return;
408 }
409
410 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
411 // expression into each operand block that uses it.
412 PHINode *PN = cast<PHINode>(Inst);
413 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
414 if (PN->getIncomingValue(i) == OperandValToReplace) {
415 // FIXME: this should split any critical edges.
416
417 // Insert the code into the end of the predecessor block.
418 BasicBlock::iterator InsertPt = PN->getIncomingBlock(i)->getTerminator();
419
420 SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(NewBase), Imm);
421 Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
422 OperandValToReplace->getType());
423
424 // Replace the use of the operand Value with the new Phi we just created.
425 PN->setIncomingValue(i, NewVal);
426 Rewriter.clear();
427 }
428 }
429 DEBUG(std::cerr << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst);
430}
431
432
Nate Begemane68bcd12005-07-30 00:15:07 +0000433/// isTargetConstant - Return true if the following can be referenced by the
434/// immediate field of a target instruction.
435static bool isTargetConstant(const SCEVHandle &V) {
Jeff Cohen546fd592005-07-30 18:33:25 +0000436
Nate Begemane68bcd12005-07-30 00:15:07 +0000437 // FIXME: Look at the target to decide if &GV is a legal constant immediate.
Chris Lattner14203e82005-08-08 06:25:50 +0000438 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
439 // PPC allows a sign-extended 16-bit immediate field.
440 if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
441 (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
442 return true;
443 return false;
444 }
Jeff Cohen546fd592005-07-30 18:33:25 +0000445
Nate Begemane68bcd12005-07-30 00:15:07 +0000446 return false; // ENABLE this for x86
Jeff Cohen546fd592005-07-30 18:33:25 +0000447
Nate Begemane68bcd12005-07-30 00:15:07 +0000448 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
449 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
450 if (CE->getOpcode() == Instruction::Cast)
451 if (isa<GlobalValue>(CE->getOperand(0)))
452 // FIXME: should check to see that the dest is uintptr_t!
453 return true;
454 return false;
455}
456
Chris Lattner37ed8952005-08-08 22:32:34 +0000457/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
458/// loop varying to the Imm operand.
459static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
460 Loop *L) {
461 if (Val->isLoopInvariant(L)) return; // Nothing to do.
462
463 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
464 std::vector<SCEVHandle> NewOps;
465 NewOps.reserve(SAE->getNumOperands());
466
467 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
468 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
469 // If this is a loop-variant expression, it must stay in the immediate
470 // field of the expression.
471 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
472 } else {
473 NewOps.push_back(SAE->getOperand(i));
474 }
475
476 if (NewOps.empty())
477 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
478 else
479 Val = SCEVAddExpr::get(NewOps);
480 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
481 // Try to pull immediates out of the start value of nested addrec's.
482 SCEVHandle Start = SARE->getStart();
483 MoveLoopVariantsToImediateField(Start, Imm, L);
484
485 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
486 Ops[0] = Start;
487 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
488 } else {
489 // Otherwise, all of Val is variant, move the whole thing over.
490 Imm = SCEVAddExpr::get(Imm, Val);
491 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
492 }
493}
494
495
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000496/// MoveImmediateValues - Look at Val, and pull out any additions of constants
Nate Begemane68bcd12005-07-30 00:15:07 +0000497/// that can fit into the immediate field of instructions in the target.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000498/// Accumulate these immediate values into the Imm value.
499static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
500 bool isAddress, Loop *L) {
Chris Lattnerfc624702005-08-03 23:44:42 +0000501 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000502 std::vector<SCEVHandle> NewOps;
503 NewOps.reserve(SAE->getNumOperands());
504
505 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
Chris Lattneracc42c42005-08-04 19:08:16 +0000506 if (isAddress && isTargetConstant(SAE->getOperand(i))) {
507 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
508 } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
509 // If this is a loop-variant expression, it must stay in the immediate
510 // field of the expression.
511 Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000512 } else {
513 NewOps.push_back(SAE->getOperand(i));
Nate Begemane68bcd12005-07-30 00:15:07 +0000514 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000515
516 if (NewOps.empty())
517 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
518 else
519 Val = SCEVAddExpr::get(NewOps);
520 return;
Chris Lattnerfc624702005-08-03 23:44:42 +0000521 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
522 // Try to pull immediates out of the start value of nested addrec's.
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000523 SCEVHandle Start = SARE->getStart();
524 MoveImmediateValues(Start, Imm, isAddress, L);
525
526 if (Start != SARE->getStart()) {
527 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
528 Ops[0] = Start;
529 Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
530 }
531 return;
Nate Begemane68bcd12005-07-30 00:15:07 +0000532 }
533
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000534 // Loop-variant expressions must stay in the immediate field of the
535 // expression.
536 if ((isAddress && isTargetConstant(Val)) ||
537 !Val->isLoopInvariant(L)) {
538 Imm = SCEVAddExpr::get(Imm, Val);
539 Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
540 return;
Chris Lattner0f7c0fa2005-08-04 19:26:19 +0000541 }
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000542
543 // Otherwise, no immediates to move.
Nate Begemane68bcd12005-07-30 00:15:07 +0000544}
545
Chris Lattner37ed8952005-08-08 22:32:34 +0000546
Nate Begemane68bcd12005-07-30 00:15:07 +0000547/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
548/// stride of IV. All of the users may have different starting values, and this
549/// may not be the only stride (we know it is if isOnlyStride is true).
550void LoopStrengthReduce::StrengthReduceStridedIVUsers(Value *Stride,
Chris Lattner430d0022005-08-03 22:21:05 +0000551 IVUsersOfOneStride &Uses,
552 Loop *L,
Nate Begemane68bcd12005-07-30 00:15:07 +0000553 bool isOnlyStride) {
554 // Transform our list of users and offsets to a bit more complex table. In
555 // this new vector, the first entry for each element is the base of the
556 // strided access, and the second is the BasedUser object for the use. We
557 // progressively move information from the first to the second entry, until we
558 // eventually emit the object.
559 std::vector<std::pair<SCEVHandle, BasedUser> > UsersToProcess;
560 UsersToProcess.reserve(Uses.Users.size());
Jeff Cohen546fd592005-07-30 18:33:25 +0000561
562 SCEVHandle ZeroBase = SCEVUnknown::getIntegerSCEV(0,
Chris Lattner430d0022005-08-03 22:21:05 +0000563 Uses.Users[0].Offset->getType());
Nate Begemane68bcd12005-07-30 00:15:07 +0000564
565 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i)
Chris Lattner430d0022005-08-03 22:21:05 +0000566 UsersToProcess.push_back(std::make_pair(Uses.Users[i].Offset,
567 BasedUser(Uses.Users[i].User,
568 Uses.Users[i].OperandValToReplace,
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000569 ZeroBase,
570 Uses.Users[i].isUseOfPostIncrementedValue)));
Chris Lattner37ed8952005-08-08 22:32:34 +0000571
572 // Move any loop invariant operands from the offset field to the immediate
573 // field of the use, so that we don't try to use something before it is
574 // computed.
Nate Begemane68bcd12005-07-30 00:15:07 +0000575 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
Chris Lattner37ed8952005-08-08 22:32:34 +0000576 MoveLoopVariantsToImediateField(UsersToProcess[i].first,
577 UsersToProcess[i].second.Imm, L);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000578 assert(UsersToProcess[i].first->isLoopInvariant(L) &&
579 "Base value is not loop invariant!");
Nate Begemane68bcd12005-07-30 00:15:07 +0000580 }
Chris Lattner37ed8952005-08-08 22:32:34 +0000581
Nate Begemane68bcd12005-07-30 00:15:07 +0000582 SCEVExpander Rewriter(*SE, *LI);
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000583 SCEVExpander PreheaderRewriter(*SE, *LI);
584
Nate Begemane68bcd12005-07-30 00:15:07 +0000585 BasicBlock *Preheader = L->getLoopPreheader();
586 Instruction *PreInsertPt = Preheader->getTerminator();
587 Instruction *PhiInsertBefore = L->getHeader()->begin();
588
Jeff Cohen546fd592005-07-30 18:33:25 +0000589 assert(isa<PHINode>(PhiInsertBefore) &&
Nate Begemane68bcd12005-07-30 00:15:07 +0000590 "How could this loop have IV's without any phis?");
591 PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
592 assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
593 "This loop isn't canonicalized right");
594 BasicBlock *LatchBlock =
595 SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
Chris Lattner37ed8952005-08-08 22:32:34 +0000596
597 // Next, figure out what we can represent in the immediate fields of
598 // instructions. If we can represent anything there, move it to the imm
599 // fields of the BasedUsers.
600 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
601 // Addressing modes can be folded into loads and stores. Be careful that
602 // the store is through the expression, not of the expression though.
603 bool isAddress = isa<LoadInst>(UsersToProcess[i].second.Inst);
604 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].second.Inst))
605 if (SI->getOperand(1) == UsersToProcess[i].second.OperandValToReplace)
606 isAddress = true;
607
608 MoveImmediateValues(UsersToProcess[i].first, UsersToProcess[i].second.Imm,
609 isAddress, L);
610 }
611
612
613
Chris Lattnerbb78c972005-08-03 23:30:08 +0000614 DEBUG(std::cerr << "INSERTING IVs of STRIDE " << *Stride << ":\n");
615
Chris Lattnerdb23c742005-08-03 22:51:21 +0000616 // Sort by the base value, so that all IVs with identical bases are next to
617 // each other.
618 std::sort(UsersToProcess.begin(), UsersToProcess.end());
Nate Begemane68bcd12005-07-30 00:15:07 +0000619 while (!UsersToProcess.empty()) {
Chris Lattnerdb23c742005-08-03 22:51:21 +0000620 SCEVHandle Base = UsersToProcess.front().first;
Chris Lattnerbb78c972005-08-03 23:30:08 +0000621
622 DEBUG(std::cerr << " INSERTING PHI with BASE = " << *Base << ":\n");
623
Nate Begemane68bcd12005-07-30 00:15:07 +0000624 // Create a new Phi for this base, and stick it in the loop header.
Chris Lattnerdb23c742005-08-03 22:51:21 +0000625 const Type *ReplacedTy = Base->getType();
626 PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
Chris Lattner45f8b6e2005-08-04 22:34:05 +0000627 ++NumInserted;
Nate Begemane68bcd12005-07-30 00:15:07 +0000628
Jeff Cohen546fd592005-07-30 18:33:25 +0000629 // Emit the initial base value into the loop preheader, and add it to the
Nate Begemane68bcd12005-07-30 00:15:07 +0000630 // Phi node.
Chris Lattnerc70bbc02005-08-08 05:47:49 +0000631 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
632 ReplacedTy);
Nate Begemane68bcd12005-07-30 00:15:07 +0000633 NewPHI->addIncoming(BaseV, Preheader);
634
635 // Emit the increment of the base value before the terminator of the loop
636 // latch block, and add it to the Phi node.
637 SCEVHandle Inc = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
638 SCEVUnknown::get(Stride));
639
640 Value *IncV = Rewriter.expandCodeFor(Inc, LatchBlock->getTerminator(),
641 ReplacedTy);
642 IncV->setName(NewPHI->getName()+".inc");
643 NewPHI->addIncoming(IncV, LatchBlock);
644
645 // Emit the code to add the immediate offset to the Phi value, just before
Chris Lattnerdb23c742005-08-03 22:51:21 +0000646 // the instructions that we identified as using this stride and base.
647 while (!UsersToProcess.empty() && UsersToProcess.front().first == Base) {
648 BasedUser &User = UsersToProcess.front().second;
Jeff Cohen546fd592005-07-30 18:33:25 +0000649
Chris Lattnerdb23c742005-08-03 22:51:21 +0000650 // Clear the SCEVExpander's expression map so that we are guaranteed
651 // to have the code emitted where we expect it.
652 Rewriter.clear();
Chris Lattnera6d7c352005-08-04 20:03:32 +0000653
654 // Now that we know what we need to do, insert code before User for the
655 // immediate and any loop-variant expressions.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000656 Value *NewBase = NewPHI;
657
658 // If this instruction wants to use the post-incremented value, move it
659 // after the post-inc and use its value instead of the PHI.
660 if (User.isUseOfPostIncrementedValue) {
661 NewBase = IncV;
662 User.Inst->moveBefore(LatchBlock->getTerminator());
663 }
664 User.RewriteInstructionToUseNewBase(NewBase, Rewriter);
Jeff Cohen546fd592005-07-30 18:33:25 +0000665
Chris Lattnerdb23c742005-08-03 22:51:21 +0000666 // Mark old value we replaced as possibly dead, so that it is elminated
667 // if we just replaced the last use of that value.
Chris Lattnera6d7c352005-08-04 20:03:32 +0000668 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
Nate Begemane68bcd12005-07-30 00:15:07 +0000669
Chris Lattnerdb23c742005-08-03 22:51:21 +0000670 UsersToProcess.erase(UsersToProcess.begin());
671 ++NumReduced;
672 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000673 // TODO: Next, find out which base index is the most common, pull it out.
674 }
675
676 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
677 // different starting values, into different PHIs.
Nate Begemane68bcd12005-07-30 00:15:07 +0000678}
679
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000680// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
681// uses in the loop, look to see if we can eliminate some, in favor of using
682// common indvars for the different uses.
683void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
684 // TODO: implement optzns here.
685
686
687
688
689 // Finally, get the terminating condition for the loop if possible. If we
690 // can, we want to change it to use a post-incremented version of its
691 // induction variable, to allow coallescing the live ranges for the IV into
692 // one register value.
693 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
694 BasicBlock *Preheader = L->getLoopPreheader();
695 BasicBlock *LatchBlock =
696 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
697 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
698 if (!TermBr || TermBr->isUnconditional() ||
699 !isa<SetCondInst>(TermBr->getCondition()))
700 return;
701 SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
702
703 // Search IVUsesByStride to find Cond's IVUse if there is one.
704 IVStrideUse *CondUse = 0;
705 Value *CondStride = 0;
706
707 for (std::map<Value*, IVUsersOfOneStride>::iterator I =IVUsesByStride.begin(),
708 E = IVUsesByStride.end(); I != E && !CondUse; ++I)
709 for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
710 E = I->second.Users.end(); UI != E; ++UI)
711 if (UI->User == Cond) {
712 CondUse = &*UI;
713 CondStride = I->first;
714 // NOTE: we could handle setcc instructions with multiple uses here, but
715 // InstCombine does it as well for simple uses, it's not clear that it
716 // occurs enough in real life to handle.
717 break;
718 }
719 if (!CondUse) return; // setcc doesn't use the IV.
720
721 // setcc stride is complex, don't mess with users.
722 if (!isa<ConstantInt>(CondStride)) return;
723
724 // It's possible for the setcc instruction to be anywhere in the loop, and
725 // possible for it to have multiple users. If it is not immediately before
726 // the latch block branch, move it.
727 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
728 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
729 Cond->moveBefore(TermBr);
730 } else {
731 // Otherwise, clone the terminating condition and insert into the loopend.
732 Cond = cast<SetCondInst>(Cond->clone());
733 Cond->setName(L->getHeader()->getName() + ".termcond");
734 LatchBlock->getInstList().insert(TermBr, Cond);
735
736 // Clone the IVUse, as the old use still exists!
737 IVUsesByStride[CondStride].addUser(CondUse->Offset, Cond,
738 CondUse->OperandValToReplace);
739 CondUse = &IVUsesByStride[CondStride].Users.back();
740 }
741 }
742
743 // If we get to here, we know that we can transform the setcc instruction to
744 // use the post-incremented version of the IV, allowing us to coallesce the
745 // live ranges for the IV correctly.
746 CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset,
747 SCEVUnknown::get(CondStride));
748 CondUse->isUseOfPostIncrementedValue = true;
749}
Nate Begemane68bcd12005-07-30 00:15:07 +0000750
Nate Begemanb18121e2004-10-18 21:08:22 +0000751void LoopStrengthReduce::runOnLoop(Loop *L) {
752 // First step, transform all loops nesting inside of this loop.
753 for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
754 runOnLoop(*I);
755
Nate Begemane68bcd12005-07-30 00:15:07 +0000756 // Next, find all uses of induction variables in this loop, and catagorize
757 // them by stride. Start by finding all of the PHI nodes in the header for
758 // this loop. If they are induction variables, inspect their uses.
Chris Lattnereaf24722005-08-04 17:40:30 +0000759 std::set<Instruction*> Processed; // Don't reprocess instructions.
Nate Begemane68bcd12005-07-30 00:15:07 +0000760 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
Chris Lattnereaf24722005-08-04 17:40:30 +0000761 AddUsersIfInteresting(I, L, Processed);
Nate Begemanb18121e2004-10-18 21:08:22 +0000762
Nate Begemane68bcd12005-07-30 00:15:07 +0000763 // If we have nothing to do, return.
Chris Lattner9bfa6f82005-08-08 05:28:22 +0000764 if (IVUsesByStride.empty()) return;
765
766 // Optimize induction variables. Some indvar uses can be transformed to use
767 // strides that will be needed for other purposes. A common example of this
768 // is the exit test for the loop, which can often be rewritten to use the
769 // computation of some other indvar to decide when to terminate the loop.
770 OptimizeIndvars(L);
771
Misha Brukmanb1c93172005-04-21 23:48:37 +0000772
Nate Begemane68bcd12005-07-30 00:15:07 +0000773 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
774 // doing computation in byte values, promote to 32-bit values if safe.
775
776 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
777 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
778 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
779 // to be careful that IV's are all the same type. Only works for intptr_t
780 // indvars.
781
782 // If we only have one stride, we can more aggressively eliminate some things.
783 bool HasOneStride = IVUsesByStride.size() == 1;
784
Chris Lattner430d0022005-08-03 22:21:05 +0000785 for (std::map<Value*, IVUsersOfOneStride>::iterator SI
786 = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
Nate Begemane68bcd12005-07-30 00:15:07 +0000787 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
Nate Begemanb18121e2004-10-18 21:08:22 +0000788
789 // Clean up after ourselves
790 if (!DeadInsts.empty()) {
791 DeleteTriviallyDeadInstructions(DeadInsts);
792
Nate Begemane68bcd12005-07-30 00:15:07 +0000793 BasicBlock::iterator I = L->getHeader()->begin();
794 PHINode *PN;
Chris Lattnerdcce49e2005-08-02 02:44:31 +0000795 while ((PN = dyn_cast<PHINode>(I))) {
Chris Lattner564900e2005-08-02 00:41:11 +0000796 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
797
Nate Begemane68bcd12005-07-30 00:15:07 +0000798 // At this point, we know that we have killed one or more GEP instructions.
799 // It is worth checking to see if the cann indvar is also dead, so that we
800 // can remove it as well. The requirements for the cann indvar to be
801 // considered dead are:
802 // 1. the cann indvar has one use
803 // 2. the use is an add instruction
804 // 3. the add has one use
805 // 4. the add is used by the cann indvar
806 // If all four cases above are true, then we can remove both the add and
807 // the cann indvar.
808 // FIXME: this needs to eliminate an induction variable even if it's being
809 // compared against some value to decide loop termination.
810 if (PN->hasOneUse()) {
811 BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
Chris Lattner75a44e12005-08-02 02:52:02 +0000812 if (BO && BO->hasOneUse()) {
813 if (PN == *(BO->use_begin())) {
814 DeadInsts.insert(BO);
815 // Break the cycle, then delete the PHI.
816 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner84e9baa2005-08-03 21:36:09 +0000817 SE->deleteInstructionFromRecords(PN);
Chris Lattner75a44e12005-08-02 02:52:02 +0000818 PN->eraseFromParent();
Nate Begemanb18121e2004-10-18 21:08:22 +0000819 }
Chris Lattner75a44e12005-08-02 02:52:02 +0000820 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000821 }
Nate Begemanb18121e2004-10-18 21:08:22 +0000822 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000823 DeleteTriviallyDeadInstructions(DeadInsts);
Nate Begemanb18121e2004-10-18 21:08:22 +0000824 }
Nate Begemane68bcd12005-07-30 00:15:07 +0000825
Chris Lattner11e7a5e2005-08-05 01:30:11 +0000826 CastedPointers.clear();
Nate Begemane68bcd12005-07-30 00:15:07 +0000827 IVUsesByStride.clear();
828 return;
Nate Begemanb18121e2004-10-18 21:08:22 +0000829}