blob: 32d22ed5402cabb9717a796d0b81d91a673e4df0 [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"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Target/TargetLowering.h"
38#include <algorithm>
39#include <set>
40using namespace llvm;
41
42STATISTIC(NumReduced , "Number of GEPs strength reduced");
43STATISTIC(NumInserted, "Number of PHIs inserted");
44STATISTIC(NumVariable, "Number of PHIs with variable strides");
45
46namespace {
47
48 struct BasedUser;
49
50 /// IVStrideUse - Keep track of one use of a strided induction variable, where
51 /// the stride is stored externally. The Offset member keeps track of the
52 /// offset from the IV, User is the actual user of the operand, and 'Operand'
53 /// is the operand # of the User that is the use.
54 struct VISIBILITY_HIDDEN IVStrideUse {
55 SCEVHandle Offset;
56 Instruction *User;
57 Value *OperandValToReplace;
58
59 // isUseOfPostIncrementedValue - True if this should use the
60 // post-incremented version of this IV, not the preincremented version.
61 // This can only be set in special cases, such as the terminating setcc
62 // instruction for a loop or uses dominated by the loop.
63 bool isUseOfPostIncrementedValue;
64
65 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
66 : Offset(Offs), User(U), OperandValToReplace(O),
67 isUseOfPostIncrementedValue(false) {}
68 };
69
70 /// IVUsersOfOneStride - This structure keeps track of all instructions that
71 /// have an operand that is based on the trip count multiplied by some stride.
72 /// The stride for all of these users is common and kept external to this
73 /// structure.
74 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
75 /// Users - Keep track of all of the users of this stride as well as the
76 /// initial value and the operand that uses the IV.
77 std::vector<IVStrideUse> Users;
78
79 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
80 Users.push_back(IVStrideUse(Offset, User, Operand));
81 }
82 };
83
84 /// IVInfo - This structure keeps track of one IV expression inserted during
85 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
86 /// well as the PHI node and increment value created for rewrite.
87 struct VISIBILITY_HIDDEN IVExpr {
88 SCEVHandle Stride;
89 SCEVHandle Base;
90 PHINode *PHI;
91 Value *IncV;
92
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
94 Value *incv)
95 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
96 };
97
98 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
99 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
100 struct VISIBILITY_HIDDEN IVsOfOneStride {
101 std::vector<IVExpr> IVs;
102
103 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
104 Value *IncV) {
105 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
106 }
107 };
108
109 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
110 LoopInfo *LI;
111 DominatorTree *DT;
112 ScalarEvolution *SE;
113 const TargetData *TD;
114 const Type *UIntPtrTy;
115 bool Changed;
116
117 /// IVUsesByStride - Keep track of all uses of induction variables that we
118 /// are interested in. The key of the map is the stride of the access.
119 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
120
121 /// IVsByStride - Keep track of all IVs that have been inserted for a
122 /// particular stride.
123 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
124
125 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
126 /// We use this to iterate over the IVUsesByStride collection without being
127 /// dependent on random ordering of pointers in the process.
128 std::vector<SCEVHandle> StrideOrder;
129
130 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
131 /// of the casted version of each value. This is accessed by
132 /// getCastedVersionOf.
133 std::map<Value*, Value*> CastedPointers;
134
135 /// DeadInsts - Keep track of instructions we may have made dead, so that
136 /// we can remove them after we are done working.
137 std::set<Instruction*> DeadInsts;
138
139 /// TLI - Keep a pointer of a TargetLowering to consult for determining
140 /// transformation profitability.
141 const TargetLowering *TLI;
142
143 public:
144 static char ID; // Pass ID, replacement for typeid
Dan Gohman34c280e2007-08-01 15:32:29 +0000145 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 LoopPass((intptr_t)&ID), TLI(tli) {
147 }
148
149 bool runOnLoop(Loop *L, LPPassManager &LPM);
150
151 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
152 // We split critical edges, so we change the CFG. However, we do update
153 // many analyses if they are around.
154 AU.addPreservedID(LoopSimplifyID);
155 AU.addPreserved<LoopInfo>();
156 AU.addPreserved<DominanceFrontier>();
157 AU.addPreserved<DominatorTree>();
158
159 AU.addRequiredID(LoopSimplifyID);
160 AU.addRequired<LoopInfo>();
161 AU.addRequired<DominatorTree>();
162 AU.addRequired<TargetData>();
163 AU.addRequired<ScalarEvolution>();
164 }
165
166 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
167 ///
168 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
169private:
170 bool AddUsersIfInteresting(Instruction *I, Loop *L,
171 std::set<Instruction*> &Processed);
172 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
173
174 void OptimizeIndvars(Loop *L);
175 bool FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
176 const SCEVHandle *&CondStride);
177
178 unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*,
179 const std::vector<BasedUser>& UsersToProcess);
180
181 bool ValidStride(int64_t, const std::vector<BasedUser>& UsersToProcess);
182
183 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
184 IVUsersOfOneStride &Uses,
185 Loop *L, bool isOnlyStride);
186 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
187 };
188 char LoopStrengthReduce::ID = 0;
189 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
190}
191
192LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
193 return new LoopStrengthReduce(TLI);
194}
195
196/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
197/// assumes that the Value* V is of integer or pointer type only.
198///
199Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
200 Value *V) {
201 if (V->getType() == UIntPtrTy) return V;
202 if (Constant *CB = dyn_cast<Constant>(V))
203 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
204
205 Value *&New = CastedPointers[V];
206 if (New) return New;
207
208 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
209 DeadInsts.insert(cast<Instruction>(New));
210 return New;
211}
212
213
214/// DeleteTriviallyDeadInstructions - If any of the instructions is the
215/// specified set are trivially dead, delete them and see if this makes any of
216/// their operands subsequently dead.
217void LoopStrengthReduce::
218DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
219 while (!Insts.empty()) {
220 Instruction *I = *Insts.begin();
221 Insts.erase(Insts.begin());
222 if (isInstructionTriviallyDead(I)) {
223 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
224 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
225 Insts.insert(U);
226 SE->deleteValueFromRecords(I);
227 I->eraseFromParent();
228 Changed = true;
229 }
230 }
231}
232
233
234/// GetExpressionSCEV - Compute and return the SCEV for the specified
235/// instruction.
236SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
237 // Pointer to pointer bitcast instructions return the same value as their
238 // operand.
239 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
240 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
241 return SE->getSCEV(BCI);
242 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)), L);
243 SE->setSCEV(BCI, R);
244 return R;
245 }
246
247 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
248 // If this is a GEP that SE doesn't know about, compute it now and insert it.
249 // If this is not a GEP, or if we have already done this computation, just let
250 // SE figure it out.
251 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
252 if (!GEP || SE->hasSCEV(GEP))
253 return SE->getSCEV(Exp);
254
255 // Analyze all of the subscripts of this getelementptr instruction, looking
256 // for uses that are determined by the trip count of L. First, skip all
257 // operands the are not dependent on the IV.
258
259 // Build up the base expression. Insert an LLVM cast of the pointer to
260 // uintptr_t first.
Dan Gohman89f85052007-10-22 18:31:58 +0000261 SCEVHandle GEPVal = SE->getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
263
264 gep_type_iterator GTI = gep_type_begin(GEP);
265
266 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
267 // If this is a use of a recurrence that we can analyze, and it comes before
268 // Op does in the GEP operand list, we will handle this when we process this
269 // operand.
270 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
271 const StructLayout *SL = TD->getStructLayout(STy);
272 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
273 uint64_t Offset = SL->getElementOffset(Idx);
Dan Gohman89f85052007-10-22 18:31:58 +0000274 GEPVal = SE->getAddExpr(GEPVal,
275 SE->getIntegerSCEV(Offset, UIntPtrTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 } else {
277 unsigned GEPOpiBits =
278 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
279 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
280 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
281 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
282 Instruction::BitCast));
283 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
284 SCEVHandle Idx = SE->getSCEV(OpVal);
285
Dale Johannesen5ec2e732007-10-01 23:08:35 +0000286 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 if (TypeSize != 1)
Dan Gohman89f85052007-10-22 18:31:58 +0000288 Idx = SE->getMulExpr(Idx,
289 SE->getConstant(ConstantInt::get(UIntPtrTy,
290 TypeSize)));
291 GEPVal = SE->getAddExpr(GEPVal, Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 }
293 }
294
295 SE->setSCEV(GEP, GEPVal);
296 return GEPVal;
297}
298
299/// getSCEVStartAndStride - Compute the start and stride of this expression,
300/// returning false if the expression is not a start/stride pair, or true if it
301/// is. The stride must be a loop invariant expression, but the start may be
302/// a mix of loop invariant and loop variant expressions.
303static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Dan Gohman89f85052007-10-22 18:31:58 +0000304 SCEVHandle &Start, SCEVHandle &Stride,
305 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 SCEVHandle TheAddRec = Start; // Initialize to zero.
307
308 // If the outer level is an AddExpr, the operands are all start values except
309 // for a nested AddRecExpr.
310 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
311 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
312 if (SCEVAddRecExpr *AddRec =
313 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
314 if (AddRec->getLoop() == L)
Dan Gohman89f85052007-10-22 18:31:58 +0000315 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 else
317 return false; // Nested IV of some sort?
318 } else {
Dan Gohman89f85052007-10-22 18:31:58 +0000319 Start = SE->getAddExpr(Start, AE->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 }
321
322 } else if (isa<SCEVAddRecExpr>(SH)) {
323 TheAddRec = SH;
324 } else {
325 return false; // not analyzable.
326 }
327
328 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
329 if (!AddRec || AddRec->getLoop() != L) return false;
330
331 // FIXME: Generalize to non-affine IV's.
332 if (!AddRec->isAffine()) return false;
333
Dan Gohman89f85052007-10-22 18:31:58 +0000334 Start = SE->getAddExpr(Start, AddRec->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335
336 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
337 DOUT << "[" << L->getHeader()->getName()
338 << "] Variable stride: " << *AddRec << "\n";
339
340 Stride = AddRec->getOperand(1);
341 return true;
342}
343
344/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
345/// and now we need to decide whether the user should use the preinc or post-inc
346/// value. If this user should use the post-inc version of the IV, return true.
347///
348/// Choosing wrong here can break dominance properties (if we choose to use the
349/// post-inc value when we cannot) or it can end up adding extra live-ranges to
350/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
351/// should use the post-inc value).
352static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
353 Loop *L, DominatorTree *DT, Pass *P) {
354 // If the user is in the loop, use the preinc value.
355 if (L->contains(User->getParent())) return false;
356
357 BasicBlock *LatchBlock = L->getLoopLatch();
358
359 // Ok, the user is outside of the loop. If it is dominated by the latch
360 // block, use the post-inc value.
361 if (DT->dominates(LatchBlock, User->getParent()))
362 return true;
363
364 // There is one case we have to be careful of: PHI nodes. These little guys
365 // can live in blocks that do not dominate the latch block, but (since their
366 // uses occur in the predecessor block, not the block the PHI lives in) should
367 // still use the post-inc value. Check for this case now.
368 PHINode *PN = dyn_cast<PHINode>(User);
369 if (!PN) return false; // not a phi, not dominated by latch block.
370
371 // Look at all of the uses of IV by the PHI node. If any use corresponds to
372 // a block that is not dominated by the latch block, give up and use the
373 // preincremented value.
374 unsigned NumUses = 0;
375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
376 if (PN->getIncomingValue(i) == IV) {
377 ++NumUses;
378 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
379 return false;
380 }
381
382 // Okay, all uses of IV by PN are in predecessor blocks that really are
383 // dominated by the latch block. Split the critical edges and use the
384 // post-incremented value.
385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
386 if (PN->getIncomingValue(i) == IV) {
387 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
388 true);
389 // Splitting the critical edge can reduce the number of entries in this
390 // PHI.
391 e = PN->getNumIncomingValues();
392 if (--NumUses == 0) break;
393 }
394
395 return true;
396}
397
398
399
400/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
401/// reducible SCEV, recursively add its users to the IVUsesByStride set and
402/// return true. Otherwise, return false.
403bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
404 std::set<Instruction*> &Processed) {
405 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
406 return false; // Void and FP expressions cannot be reduced.
407 if (!Processed.insert(I).second)
408 return true; // Instruction already handled.
409
410 // Get the symbolic expression for this instruction.
411 SCEVHandle ISE = GetExpressionSCEV(I, L);
412 if (isa<SCEVCouldNotCompute>(ISE)) return false;
413
414 // Get the start and stride for this expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000415 SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 SCEVHandle Stride = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000417 if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 return false; // Non-reducible symbolic expression, bail out.
419
420 std::vector<Instruction *> IUsers;
421 // Collect all I uses now because IVUseShouldUsePostIncValue may
422 // invalidate use_iterator.
423 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
424 IUsers.push_back(cast<Instruction>(*UI));
425
426 for (unsigned iused_index = 0, iused_size = IUsers.size();
427 iused_index != iused_size; ++iused_index) {
428
429 Instruction *User = IUsers[iused_index];
430
431 // Do not infinitely recurse on PHI nodes.
432 if (isa<PHINode>(User) && Processed.count(User))
433 continue;
434
435 // If this is an instruction defined in a nested loop, or outside this loop,
436 // don't recurse into it.
437 bool AddUserToIVUsers = false;
438 if (LI->getLoopFor(User->getParent()) != L) {
439 DOUT << "FOUND USER in other loop: " << *User
440 << " OF SCEV: " << *ISE << "\n";
441 AddUserToIVUsers = true;
442 } else if (!AddUsersIfInteresting(User, L, Processed)) {
443 DOUT << "FOUND USER: " << *User
444 << " OF SCEV: " << *ISE << "\n";
445 AddUserToIVUsers = true;
446 }
447
448 if (AddUserToIVUsers) {
449 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
450 if (StrideUses.Users.empty()) // First occurance of this stride?
451 StrideOrder.push_back(Stride);
452
453 // Okay, we found a user that we cannot reduce. Analyze the instruction
454 // and decide what to do with it. If we are a use inside of the loop, use
455 // the value before incrementation, otherwise use it after incrementation.
456 if (IVUseShouldUsePostIncValue(User, I, L, DT, this)) {
457 // The value used will be incremented by the stride more than we are
458 // expecting, so subtract this off.
Dan Gohman89f85052007-10-22 18:31:58 +0000459 SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 StrideUses.addUser(NewStart, User, I);
461 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
462 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
463 } else {
464 StrideUses.addUser(Start, User, I);
465 }
466 }
467 }
468 return true;
469}
470
471namespace {
472 /// BasedUser - For a particular base value, keep information about how we've
473 /// partitioned the expression so far.
474 struct BasedUser {
Dan Gohman89f85052007-10-22 18:31:58 +0000475 /// SE - The current ScalarEvolution object.
476 ScalarEvolution *SE;
477
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000478 /// Base - The Base value for the PHI node that needs to be inserted for
479 /// this use. As the use is processed, information gets moved from this
480 /// field to the Imm field (below). BasedUser values are sorted by this
481 /// field.
482 SCEVHandle Base;
483
484 /// Inst - The instruction using the induction variable.
485 Instruction *Inst;
486
487 /// OperandValToReplace - The operand value of Inst to replace with the
488 /// EmittedBase.
489 Value *OperandValToReplace;
490
491 /// Imm - The immediate value that should be added to the base immediately
492 /// before Inst, because it will be folded into the imm field of the
493 /// instruction.
494 SCEVHandle Imm;
495
496 /// EmittedBase - The actual value* to use for the base value of this
497 /// operation. This is null if we should just use zero so far.
498 Value *EmittedBase;
499
500 // isUseOfPostIncrementedValue - True if this should use the
501 // post-incremented version of this IV, not the preincremented version.
502 // This can only be set in special cases, such as the terminating setcc
503 // instruction for a loop and uses outside the loop that are dominated by
504 // the loop.
505 bool isUseOfPostIncrementedValue;
506
Dan Gohman89f85052007-10-22 18:31:58 +0000507 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
508 : SE(se), Base(IVSU.Offset), Inst(IVSU.User),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000509 OperandValToReplace(IVSU.OperandValToReplace),
Dan Gohman89f85052007-10-22 18:31:58 +0000510 Imm(SE->getIntegerSCEV(0, Base->getType())), EmittedBase(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
512
513 // Once we rewrite the code to insert the new IVs we want, update the
514 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
515 // to it.
516 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
517 SCEVExpander &Rewriter, Loop *L,
518 Pass *P);
519
520 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
521 SCEVExpander &Rewriter,
522 Instruction *IP, Loop *L);
523 void dump() const;
524 };
525}
526
527void BasedUser::dump() const {
528 cerr << " Base=" << *Base;
529 cerr << " Imm=" << *Imm;
530 if (EmittedBase)
531 cerr << " EB=" << *EmittedBase;
532
533 cerr << " Inst: " << *Inst;
534}
535
536Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
537 SCEVExpander &Rewriter,
538 Instruction *IP, Loop *L) {
539 // Figure out where we *really* want to insert this code. In particular, if
540 // the user is inside of a loop that is nested inside of L, we really don't
541 // want to insert this expression before the user, we'd rather pull it out as
542 // many loops as possible.
543 LoopInfo &LI = Rewriter.getLoopInfo();
544 Instruction *BaseInsertPt = IP;
545
546 // Figure out the most-nested loop that IP is in.
547 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
548
549 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
550 // the preheader of the outer-most loop where NewBase is not loop invariant.
551 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
552 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
553 InsertLoop = InsertLoop->getParentLoop();
554 }
555
556 // If there is no immediate value, skip the next part.
557 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
558 if (SC->getValue()->isZero())
559 return Rewriter.expandCodeFor(NewBase, BaseInsertPt);
560
561 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
562
563 // If we are inserting the base and imm values in the same block, make sure to
564 // adjust the IP position if insertion reused a result.
565 if (IP == BaseInsertPt)
566 IP = Rewriter.getInsertionPoint();
567
568 // Always emit the immediate (if non-zero) into the same block as the user.
Dan Gohman89f85052007-10-22 18:31:58 +0000569 SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570 return Rewriter.expandCodeFor(NewValSCEV, IP);
571
572}
573
574
575// Once we rewrite the code to insert the new IVs we want, update the
576// operands of Inst to use the new expression 'NewBase', with 'Imm' added
577// to it.
578void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
579 SCEVExpander &Rewriter,
580 Loop *L, Pass *P) {
581 if (!isa<PHINode>(Inst)) {
582 // By default, insert code at the user instruction.
583 BasicBlock::iterator InsertPt = Inst;
584
585 // However, if the Operand is itself an instruction, the (potentially
586 // complex) inserted code may be shared by many users. Because of this, we
587 // want to emit code for the computation of the operand right before its old
588 // computation. This is usually safe, because we obviously used to use the
589 // computation when it was computed in its current block. However, in some
590 // cases (e.g. use of a post-incremented induction variable) the NewBase
591 // value will be pinned to live somewhere after the original computation.
592 // In this case, we have to back off.
593 if (!isUseOfPostIncrementedValue) {
594 if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) {
595 InsertPt = OpInst;
596 while (isa<PHINode>(InsertPt)) ++InsertPt;
597 }
598 }
599 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Dan Gohman5d1dd952007-07-31 17:22:27 +0000600 // Adjust the type back to match the Inst. Note that we can't use InsertPt
601 // here because the SCEVExpander may have inserted the instructions after
602 // that point, in its efforts to avoid inserting redundant expressions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 if (isa<PointerType>(OperandValToReplace->getType())) {
Dan Gohman5d1dd952007-07-31 17:22:27 +0000604 NewVal = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
605 NewVal,
606 OperandValToReplace->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 }
608 // Replace the use of the operand Value with the new Phi we just created.
609 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
610 DOUT << " CHANGED: IMM =" << *Imm;
611 DOUT << " \tNEWBASE =" << *NewBase;
612 DOUT << " \tInst = " << *Inst;
613 return;
614 }
615
616 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
617 // expression into each operand block that uses it. Note that PHI nodes can
618 // have multiple entries for the same predecessor. We use a map to make sure
619 // that a PHI node only has a single Value* for each predecessor (which also
620 // prevents us from inserting duplicate code in some blocks).
621 std::map<BasicBlock*, Value*> InsertedCode;
622 PHINode *PN = cast<PHINode>(Inst);
623 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
624 if (PN->getIncomingValue(i) == OperandValToReplace) {
625 // If this is a critical edge, split the edge so that we do not insert the
626 // code on all predecessor/successor paths. We do this unless this is the
627 // canonical backedge for this loop, as this can make some inserted code
628 // be in an illegal position.
629 BasicBlock *PHIPred = PN->getIncomingBlock(i);
630 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
631 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
632
633 // First step, split the critical edge.
634 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
635
636 // Next step: move the basic block. In particular, if the PHI node
637 // is outside of the loop, and PredTI is in the loop, we want to
638 // move the block to be immediately before the PHI block, not
639 // immediately after PredTI.
640 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
641 BasicBlock *NewBB = PN->getIncomingBlock(i);
642 NewBB->moveBefore(PN->getParent());
643 }
644
645 // Splitting the edge can reduce the number of PHI entries we have.
646 e = PN->getNumIncomingValues();
647 }
648
649 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
650 if (!Code) {
651 // Insert the code into the end of the predecessor block.
652 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
653 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
654
Chris Lattner03dc7d72007-08-02 16:53:43 +0000655 // Adjust the type back to match the PHI. Note that we can't use
656 // InsertPt here because the SCEVExpander may have inserted its
657 // instructions after that point, in its efforts to avoid inserting
658 // redundant expressions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 if (isa<PointerType>(PN->getType())) {
Dan Gohman5d1dd952007-07-31 17:22:27 +0000660 Code = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
661 Code,
662 PN->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 }
664 }
665
666 // Replace the use of the operand Value with the new Phi we just created.
667 PN->setIncomingValue(i, Code);
668 Rewriter.clear();
669 }
670 }
671 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
672}
673
674
675/// isTargetConstant - Return true if the following can be referenced by the
676/// immediate field of a target instruction.
677static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
678 const TargetLowering *TLI) {
679 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
680 int64_t VC = SC->getValue()->getSExtValue();
681 if (TLI) {
682 TargetLowering::AddrMode AM;
683 AM.BaseOffs = VC;
684 return TLI->isLegalAddressingMode(AM, UseTy);
685 } else {
686 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
687 return (VC > -(1 << 16) && VC < (1 << 16)-1);
688 }
689 }
690
691 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
692 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
693 if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
694 Constant *Op0 = CE->getOperand(0);
695 if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
696 TargetLowering::AddrMode AM;
697 AM.BaseGV = GV;
698 return TLI->isLegalAddressingMode(AM, UseTy);
699 }
700 }
701 return false;
702}
703
704/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
705/// loop varying to the Imm operand.
706static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman89f85052007-10-22 18:31:58 +0000707 Loop *L, ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708 if (Val->isLoopInvariant(L)) return; // Nothing to do.
709
710 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
711 std::vector<SCEVHandle> NewOps;
712 NewOps.reserve(SAE->getNumOperands());
713
714 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
715 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
716 // If this is a loop-variant expression, it must stay in the immediate
717 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000718 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 } else {
720 NewOps.push_back(SAE->getOperand(i));
721 }
722
723 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000724 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 else
Dan Gohman89f85052007-10-22 18:31:58 +0000726 Val = SE->getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
728 // Try to pull immediates out of the start value of nested addrec's.
729 SCEVHandle Start = SARE->getStart();
Dan Gohman89f85052007-10-22 18:31:58 +0000730 MoveLoopVariantsToImediateField(Start, Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731
732 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
733 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000734 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 } else {
736 // Otherwise, all of Val is variant, move the whole thing over.
Dan Gohman89f85052007-10-22 18:31:58 +0000737 Imm = SE->getAddExpr(Imm, Val);
738 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 }
740}
741
742
743/// MoveImmediateValues - Look at Val, and pull out any additions of constants
744/// that can fit into the immediate field of instructions in the target.
745/// Accumulate these immediate values into the Imm value.
746static void MoveImmediateValues(const TargetLowering *TLI,
747 Instruction *User,
748 SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman89f85052007-10-22 18:31:58 +0000749 bool isAddress, Loop *L,
750 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 const Type *UseTy = User->getType();
752 if (StoreInst *SI = dyn_cast<StoreInst>(User))
753 UseTy = SI->getOperand(0)->getType();
754
755 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
756 std::vector<SCEVHandle> NewOps;
757 NewOps.reserve(SAE->getNumOperands());
758
759 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
760 SCEVHandle NewOp = SAE->getOperand(i);
Dan Gohman89f85052007-10-22 18:31:58 +0000761 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762
763 if (!NewOp->isLoopInvariant(L)) {
764 // If this is a loop-variant expression, it must stay in the immediate
765 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000766 Imm = SE->getAddExpr(Imm, NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 } else {
768 NewOps.push_back(NewOp);
769 }
770 }
771
772 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000773 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774 else
Dan Gohman89f85052007-10-22 18:31:58 +0000775 Val = SE->getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776 return;
777 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
778 // Try to pull immediates out of the start value of nested addrec's.
779 SCEVHandle Start = SARE->getStart();
Dan Gohman89f85052007-10-22 18:31:58 +0000780 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781
782 if (Start != SARE->getStart()) {
783 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
784 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000785 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 }
787 return;
788 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
789 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
790 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
791 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
792
Dan Gohman89f85052007-10-22 18:31:58 +0000793 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 SCEVHandle NewOp = SME->getOperand(1);
Dan Gohman89f85052007-10-22 18:31:58 +0000795 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796
797 // If we extracted something out of the subexpressions, see if we can
798 // simplify this!
799 if (NewOp != SME->getOperand(1)) {
800 // Scale SubImm up by "8". If the result is a target constant, we are
801 // good.
Dan Gohman89f85052007-10-22 18:31:58 +0000802 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 if (isTargetConstant(SubImm, UseTy, TLI)) {
804 // Accumulate the immediate.
Dan Gohman89f85052007-10-22 18:31:58 +0000805 Imm = SE->getAddExpr(Imm, SubImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806
807 // Update what is left of 'Val'.
Dan Gohman89f85052007-10-22 18:31:58 +0000808 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 return;
810 }
811 }
812 }
813 }
814
815 // Loop-variant expressions must stay in the immediate field of the
816 // expression.
817 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
818 !Val->isLoopInvariant(L)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000819 Imm = SE->getAddExpr(Imm, Val);
820 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000821 return;
822 }
823
824 // Otherwise, no immediates to move.
825}
826
827
828/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
829/// added together. This is used to reassociate common addition subexprs
830/// together for maximal sharing when rewriting bases.
831static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
Dan Gohman89f85052007-10-22 18:31:58 +0000832 SCEVHandle Expr,
833 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
835 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
Dan Gohman89f85052007-10-22 18:31:58 +0000836 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000838 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 if (SARE->getOperand(0) == Zero) {
840 SubExprs.push_back(Expr);
841 } else {
842 // Compute the addrec with zero as its base.
843 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
844 Ops[0] = Zero; // Start with zero base.
Dan Gohman89f85052007-10-22 18:31:58 +0000845 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846
847
Dan Gohman89f85052007-10-22 18:31:58 +0000848 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
850 } else if (!isa<SCEVConstant>(Expr) ||
851 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
852 // Do not add zero.
853 SubExprs.push_back(Expr);
854 }
855}
856
857
858/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
859/// removing any common subexpressions from it. Anything truly common is
860/// removed, accumulated, and returned. This looks for things like (a+b+c) and
861/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
862static SCEVHandle
Dan Gohman89f85052007-10-22 18:31:58 +0000863RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
864 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 unsigned NumUses = Uses.size();
866
867 // Only one use? Use its base, regardless of what it is!
Dan Gohman89f85052007-10-22 18:31:58 +0000868 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000869 SCEVHandle Result = Zero;
870 if (NumUses == 1) {
871 std::swap(Result, Uses[0].Base);
872 return Result;
873 }
874
875 // To find common subexpressions, count how many of Uses use each expression.
876 // If any subexpressions are used Uses.size() times, they are common.
877 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
878
879 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
880 // order we see them.
881 std::vector<SCEVHandle> UniqueSubExprs;
882
883 std::vector<SCEVHandle> SubExprs;
884 for (unsigned i = 0; i != NumUses; ++i) {
885 // If the base is zero (which is common), return zero now, there are no
886 // CSEs we can find.
887 if (Uses[i].Base == Zero) return Zero;
888
889 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000890 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 // Add one to SubExpressionUseCounts for each subexpr present.
892 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
893 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
894 UniqueSubExprs.push_back(SubExprs[j]);
895 SubExprs.clear();
896 }
897
898 // Now that we know how many times each is used, build Result. Iterate over
899 // UniqueSubexprs so that we have a stable ordering.
900 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
901 std::map<SCEVHandle, unsigned>::iterator I =
902 SubExpressionUseCounts.find(UniqueSubExprs[i]);
903 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
904 if (I->second == NumUses) { // Found CSE!
Dan Gohman89f85052007-10-22 18:31:58 +0000905 Result = SE->getAddExpr(Result, I->first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 } else {
907 // Remove non-cse's from SubExpressionUseCounts.
908 SubExpressionUseCounts.erase(I);
909 }
910 }
911
912 // If we found no CSE's, return now.
913 if (Result == Zero) return Result;
914
915 // Otherwise, remove all of the CSE's we found from each of the base values.
916 for (unsigned i = 0; i != NumUses; ++i) {
917 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000918 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919
920 // Remove any common subexpressions.
921 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
922 if (SubExpressionUseCounts.count(SubExprs[j])) {
923 SubExprs.erase(SubExprs.begin()+j);
924 --j; --e;
925 }
926
927 // Finally, the non-shared expressions together.
928 if (SubExprs.empty())
929 Uses[i].Base = Zero;
930 else
Dan Gohman89f85052007-10-22 18:31:58 +0000931 Uses[i].Base = SE->getAddExpr(SubExprs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 SubExprs.clear();
933 }
934
935 return Result;
936}
937
938/// isZero - returns true if the scalar evolution expression is zero.
939///
940static bool isZero(SCEVHandle &V) {
941 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
942 return SC->getValue()->isZero();
943 return false;
944}
945
946/// ValidStride - Check whether the given Scale is valid for all loads and
947/// stores in UsersToProcess.
948///
949bool LoopStrengthReduce::ValidStride(int64_t Scale,
950 const std::vector<BasedUser>& UsersToProcess) {
951 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
952 // If this is a load or other access, pass the type of the access in.
953 const Type *AccessTy = Type::VoidTy;
954 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
955 AccessTy = SI->getOperand(0)->getType();
956 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
957 AccessTy = LI->getType();
958
959 TargetLowering::AddrMode AM;
960 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
961 AM.BaseOffs = SC->getValue()->getSExtValue();
962 AM.Scale = Scale;
963
964 // If load[imm+r*scale] is illegal, bail out.
965 if (!TLI->isLegalAddressingMode(AM, AccessTy))
966 return false;
967 }
968 return true;
969}
970
971/// CheckForIVReuse - Returns the multiple if the stride is the multiple
972/// of a previous stride and it is a legal value for the target addressing
973/// mode scale component. This allows the users of this stride to be rewritten
974/// as prev iv * factor. It returns 0 if no reuse is possible.
975unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
976 IVExpr &IV, const Type *Ty,
977 const std::vector<BasedUser>& UsersToProcess) {
978 if (!TLI) return 0;
979
980 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
981 int64_t SInt = SC->getValue()->getSExtValue();
982 if (SInt == 1) return 0;
983
984 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
985 SE = IVsByStride.end(); SI != SE; ++SI) {
986 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
987 if (SInt != -SSInt &&
988 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
989 continue;
990 int64_t Scale = SInt / SSInt;
991 // Check that this stride is valid for all the types used for loads and
992 // stores; if it can be used for some and not others, we might as well use
993 // the original stride everywhere, since we have to create the IV for it
994 // anyway.
995 if (ValidStride(Scale, UsersToProcess))
996 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
997 IE = SI->second.IVs.end(); II != IE; ++II)
998 // FIXME: Only handle base == 0 for now.
999 // Only reuse previous IV if it would not require a type conversion.
1000 if (isZero(II->Base) && II->Base->getType() == Ty) {
1001 IV = *II;
1002 return Scale;
1003 }
1004 }
1005 }
1006 return 0;
1007}
1008
1009/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1010/// returns true if Val's isUseOfPostIncrementedValue is true.
1011static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1012 return Val.isUseOfPostIncrementedValue;
1013}
1014
1015/// isNonConstantNegative - REturn true if the specified scev is negated, but
1016/// not a constant.
1017static bool isNonConstantNegative(const SCEVHandle &Expr) {
1018 SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1019 if (!Mul) return false;
1020
1021 // If there is a constant factor, it will be first.
1022 SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1023 if (!SC) return false;
1024
1025 // Return true if the value is negative, this matches things like (-42 * V).
1026 return SC->getValue()->getValue().isNegative();
1027}
1028
1029/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1030/// stride of IV. All of the users may have different starting values, and this
1031/// may not be the only stride (we know it is if isOnlyStride is true).
1032void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1033 IVUsersOfOneStride &Uses,
1034 Loop *L,
1035 bool isOnlyStride) {
1036 // Transform our list of users and offsets to a bit more complex table. In
1037 // this new vector, each 'BasedUser' contains 'Base' the base of the
1038 // strided accessas well as the old information from Uses. We progressively
1039 // move information from the Base field to the Imm field, until we eventually
1040 // have the full access expression to rewrite the use.
1041 std::vector<BasedUser> UsersToProcess;
1042 UsersToProcess.reserve(Uses.Users.size());
1043 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +00001044 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045
1046 // Move any loop invariant operands from the offset field to the immediate
1047 // field of the use, so that we don't try to use something before it is
1048 // computed.
1049 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001050 UsersToProcess.back().Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1052 "Base value is not loop invariant!");
1053 }
1054
1055 // We now have a whole bunch of uses of like-strided induction variables, but
1056 // they might all have different bases. We want to emit one PHI node for this
1057 // stride which we fold as many common expressions (between the IVs) into as
1058 // possible. Start by identifying the common expressions in the base values
1059 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1060 // "A+B"), emit it to the preheader, then remove the expression from the
1061 // UsersToProcess base values.
1062 SCEVHandle CommonExprs =
Dan Gohman89f85052007-10-22 18:31:58 +00001063 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064
1065 // Next, figure out what we can represent in the immediate fields of
1066 // instructions. If we can represent anything there, move it to the imm
1067 // fields of the BasedUsers. We do this so that it increases the commonality
1068 // of the remaining uses.
1069 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1070 // If the user is not in the current loop, this means it is using the exit
1071 // value of the IV. Do not put anything in the base, make sure it's all in
1072 // the immediate field to allow as much factoring as possible.
1073 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Dan Gohman89f85052007-10-22 18:31:58 +00001074 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1075 UsersToProcess[i].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 UsersToProcess[i].Base =
Dan Gohman89f85052007-10-22 18:31:58 +00001077 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 } else {
1079
1080 // Addressing modes can be folded into loads and stores. Be careful that
1081 // the store is through the expression, not of the expression though.
1082 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1083 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst)) {
1084 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1085 isAddress = true;
1086 } else if (IntrinsicInst *II =
1087 dyn_cast<IntrinsicInst>(UsersToProcess[i].Inst)) {
1088 // Addressing modes can also be folded into prefetches.
1089 if (II->getIntrinsicID() == Intrinsic::prefetch &&
1090 II->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1091 isAddress = true;
1092 }
1093
1094 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001095 UsersToProcess[i].Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 }
1097 }
1098
1099 // Check if it is possible to reuse a IV with stride that is factor of this
1100 // stride. And the multiple is a number that can be encoded in the scale
1101 // field of the target addressing mode. And we will have a valid
1102 // instruction after this substition, including the immediate field, if any.
1103 PHINode *NewPHI = NULL;
1104 Value *IncV = NULL;
Dan Gohman89f85052007-10-22 18:31:58 +00001105 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1106 SE->getIntegerSCEV(0, Type::Int32Ty),
1107 0, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
1109 CommonExprs->getType(),
1110 UsersToProcess);
1111 if (RewriteFactor != 0) {
1112 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1113 << " and BASE " << *ReuseIV.Base << " :\n";
1114 NewPHI = ReuseIV.PHI;
1115 IncV = ReuseIV.IncV;
1116 }
1117
1118 const Type *ReplacedTy = CommonExprs->getType();
1119
1120 // Now that we know what we need to do, insert the PHI node itself.
1121 //
1122 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1123 << *Stride << " and BASE " << *CommonExprs << ": ";
1124
1125 SCEVExpander Rewriter(*SE, *LI);
1126 SCEVExpander PreheaderRewriter(*SE, *LI);
1127
1128 BasicBlock *Preheader = L->getLoopPreheader();
1129 Instruction *PreInsertPt = Preheader->getTerminator();
1130 Instruction *PhiInsertBefore = L->getHeader()->begin();
1131
1132 BasicBlock *LatchBlock = L->getLoopLatch();
1133
1134
1135 // Emit the initial base value into the loop preheader.
1136 Value *CommonBaseV
1137 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt);
1138
1139 if (RewriteFactor == 0) {
1140 // Create a new Phi for this base, and stick it in the loop header.
1141 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1142 ++NumInserted;
1143
1144 // Add common base to the new Phi node.
1145 NewPHI->addIncoming(CommonBaseV, Preheader);
1146
1147 // If the stride is negative, insert a sub instead of an add for the
1148 // increment.
1149 bool isNegative = isNonConstantNegative(Stride);
1150 SCEVHandle IncAmount = Stride;
1151 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001152 IncAmount = SE->getNegativeSCEV(Stride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153
1154 // Insert the stride into the preheader.
1155 Value *StrideV = PreheaderRewriter.expandCodeFor(IncAmount, PreInsertPt);
1156 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1157
1158 // Emit the increment of the base value before the terminator of the loop
1159 // latch block, and add it to the Phi node.
Dan Gohman89f85052007-10-22 18:31:58 +00001160 SCEVHandle IncExp = SE->getUnknown(StrideV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001162 IncExp = SE->getNegativeSCEV(IncExp);
1163 IncExp = SE->getAddExpr(SE->getUnknown(NewPHI), IncExp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164
1165 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator());
1166 IncV->setName(NewPHI->getName()+".inc");
1167 NewPHI->addIncoming(IncV, LatchBlock);
1168
1169 // Remember this in case a later stride is multiple of this.
1170 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1171
1172 DOUT << " IV=%" << NewPHI->getNameStr() << " INC=%" << IncV->getNameStr();
1173 } else {
1174 Constant *C = dyn_cast<Constant>(CommonBaseV);
1175 if (!C ||
1176 (!C->isNullValue() &&
Dan Gohman89f85052007-10-22 18:31:58 +00001177 !isTargetConstant(SE->getUnknown(CommonBaseV), ReplacedTy, TLI)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178 // We want the common base emitted into the preheader! This is just
1179 // using cast as a copy so BitCast (no-op cast) is appropriate
1180 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1181 "commonbase", PreInsertPt);
1182 }
1183 DOUT << "\n";
1184
1185 // We want to emit code for users inside the loop first. To do this, we
1186 // rearrange BasedUser so that the entries at the end have
1187 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1188 // vector (so we handle them first).
1189 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1190 PartitionByIsUseOfPostIncrementedValue);
1191
1192 // Sort this by base, so that things with the same base are handled
1193 // together. By partitioning first and stable-sorting later, we are
1194 // guaranteed that within each base we will pop off users from within the
1195 // loop before users outside of the loop with a particular base.
1196 //
1197 // We would like to use stable_sort here, but we can't. The problem is that
1198 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1199 // we don't have anything to do a '<' comparison on. Because we think the
1200 // number of uses is small, do a horrible bubble sort which just relies on
1201 // ==.
1202 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1203 // Get a base value.
1204 SCEVHandle Base = UsersToProcess[i].Base;
1205
1206 // Compact everything with this base to be consequetive with this one.
1207 for (unsigned j = i+1; j != e; ++j) {
1208 if (UsersToProcess[j].Base == Base) {
1209 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1210 ++i;
1211 }
1212 }
1213 }
1214
1215 // Process all the users now. This outer loop handles all bases, the inner
1216 // loop handles all users of a particular base.
1217 while (!UsersToProcess.empty()) {
1218 SCEVHandle Base = UsersToProcess.back().Base;
1219
1220 // Emit the code for Base into the preheader.
1221 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt);
1222
1223 DOUT << " INSERTING code for BASE = " << *Base << ":";
1224 if (BaseV->hasName())
1225 DOUT << " Result value name = %" << BaseV->getNameStr();
1226 DOUT << "\n";
1227
1228 // If BaseV is a constant other than 0, make sure that it gets inserted into
1229 // the preheader, instead of being forward substituted into the uses. We do
1230 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1231 // in this case.
1232 if (Constant *C = dyn_cast<Constant>(BaseV)) {
1233 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
1234 // We want this constant emitted into the preheader! This is just
1235 // using cast as a copy so BitCast (no-op cast) is appropriate
1236 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1237 PreInsertPt);
1238 }
1239 }
1240
1241 // Emit the code to add the immediate offset to the Phi value, just before
1242 // the instructions that we identified as using this stride and base.
1243 do {
1244 // FIXME: Use emitted users to emit other users.
1245 BasedUser &User = UsersToProcess.back();
1246
1247 // If this instruction wants to use the post-incremented value, move it
1248 // after the post-inc and use its value instead of the PHI.
1249 Value *RewriteOp = NewPHI;
1250 if (User.isUseOfPostIncrementedValue) {
1251 RewriteOp = IncV;
1252
1253 // If this user is in the loop, make sure it is the last thing in the
1254 // loop to ensure it is dominated by the increment.
1255 if (L->contains(User.Inst->getParent()))
1256 User.Inst->moveBefore(LatchBlock->getTerminator());
1257 }
1258 if (RewriteOp->getType() != ReplacedTy) {
1259 Instruction::CastOps opcode = Instruction::Trunc;
1260 if (ReplacedTy->getPrimitiveSizeInBits() ==
1261 RewriteOp->getType()->getPrimitiveSizeInBits())
1262 opcode = Instruction::BitCast;
1263 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1264 }
1265
Dan Gohman89f85052007-10-22 18:31:58 +00001266 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267
1268 // Clear the SCEVExpander's expression map so that we are guaranteed
1269 // to have the code emitted where we expect it.
1270 Rewriter.clear();
1271
1272 // If we are reusing the iv, then it must be multiplied by a constant
1273 // factor take advantage of addressing mode scale component.
1274 if (RewriteFactor != 0) {
1275 RewriteExpr =
Dan Gohman89f85052007-10-22 18:31:58 +00001276 SE->getMulExpr(SE->getIntegerSCEV(RewriteFactor,
1277 RewriteExpr->getType()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 RewriteExpr);
1279
1280 // The common base is emitted in the loop preheader. But since we
1281 // are reusing an IV, it has not been used to initialize the PHI node.
1282 // Add it to the expression used to rewrite the uses.
1283 if (!isa<ConstantInt>(CommonBaseV) ||
1284 !cast<ConstantInt>(CommonBaseV)->isZero())
Dan Gohman89f85052007-10-22 18:31:58 +00001285 RewriteExpr = SE->getAddExpr(RewriteExpr,
1286 SE->getUnknown(CommonBaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 }
1288
1289 // Now that we know what we need to do, insert code before User for the
1290 // immediate and any loop-variant expressions.
1291 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
1292 // Add BaseV to the PHI value if needed.
Dan Gohman89f85052007-10-22 18:31:58 +00001293 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294
1295 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1296
1297 // Mark old value we replaced as possibly dead, so that it is elminated
1298 // if we just replaced the last use of that value.
1299 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1300
1301 UsersToProcess.pop_back();
1302 ++NumReduced;
1303
1304 // If there are any more users to process with the same base, process them
1305 // now. We sorted by base above, so we just have to check the last elt.
1306 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1307 // TODO: Next, find out which base index is the most common, pull it out.
1308 }
1309
1310 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1311 // different starting values, into different PHIs.
1312}
1313
1314/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1315/// set the IV user and stride information and return true, otherwise return
1316/// false.
1317bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1318 const SCEVHandle *&CondStride) {
1319 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1320 ++Stride) {
1321 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1322 IVUsesByStride.find(StrideOrder[Stride]);
1323 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1324
1325 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1326 E = SI->second.Users.end(); UI != E; ++UI)
1327 if (UI->User == Cond) {
1328 // NOTE: we could handle setcc instructions with multiple uses here, but
1329 // InstCombine does it as well for simple uses, it's not clear that it
1330 // occurs enough in real life to handle.
1331 CondUse = &*UI;
1332 CondStride = &SI->first;
1333 return true;
1334 }
1335 }
1336 return false;
1337}
1338
1339// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1340// uses in the loop, look to see if we can eliminate some, in favor of using
1341// common indvars for the different uses.
1342void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1343 // TODO: implement optzns here.
1344
1345 // Finally, get the terminating condition for the loop if possible. If we
1346 // can, we want to change it to use a post-incremented version of its
1347 // induction variable, to allow coalescing the live ranges for the IV into
1348 // one register value.
1349 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1350 BasicBlock *Preheader = L->getLoopPreheader();
1351 BasicBlock *LatchBlock =
1352 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1353 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1354 if (!TermBr || TermBr->isUnconditional() ||
1355 !isa<ICmpInst>(TermBr->getCondition()))
1356 return;
1357 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1358
1359 // Search IVUsesByStride to find Cond's IVUse if there is one.
1360 IVStrideUse *CondUse = 0;
1361 const SCEVHandle *CondStride = 0;
1362
1363 if (!FindIVForUser(Cond, CondUse, CondStride))
1364 return; // setcc doesn't use the IV.
1365
1366
1367 // It's possible for the setcc instruction to be anywhere in the loop, and
1368 // possible for it to have multiple users. If it is not immediately before
1369 // the latch block branch, move it.
1370 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1371 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1372 Cond->moveBefore(TermBr);
1373 } else {
1374 // Otherwise, clone the terminating condition and insert into the loopend.
1375 Cond = cast<ICmpInst>(Cond->clone());
1376 Cond->setName(L->getHeader()->getName() + ".termcond");
1377 LatchBlock->getInstList().insert(TermBr, Cond);
1378
1379 // Clone the IVUse, as the old use still exists!
1380 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1381 CondUse->OperandValToReplace);
1382 CondUse = &IVUsesByStride[*CondStride].Users.back();
1383 }
1384 }
1385
1386 // If we get to here, we know that we can transform the setcc instruction to
1387 // use the post-incremented version of the IV, allowing us to coalesce the
1388 // live ranges for the IV correctly.
Dan Gohman89f85052007-10-22 18:31:58 +00001389 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 CondUse->isUseOfPostIncrementedValue = true;
1391}
1392
1393namespace {
1394 // Constant strides come first which in turns are sorted by their absolute
1395 // values. If absolute values are the same, then positive strides comes first.
1396 // e.g.
1397 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1398 struct StrideCompare {
1399 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1400 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1401 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1402 if (LHSC && RHSC) {
1403 int64_t LV = LHSC->getValue()->getSExtValue();
1404 int64_t RV = RHSC->getValue()->getSExtValue();
1405 uint64_t ALV = (LV < 0) ? -LV : LV;
1406 uint64_t ARV = (RV < 0) ? -RV : RV;
1407 if (ALV == ARV)
1408 return LV > RV;
1409 else
1410 return ALV < ARV;
1411 }
1412 return (LHSC && !RHSC);
1413 }
1414 };
1415}
1416
1417bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
1418
1419 LI = &getAnalysis<LoopInfo>();
1420 DT = &getAnalysis<DominatorTree>();
1421 SE = &getAnalysis<ScalarEvolution>();
1422 TD = &getAnalysis<TargetData>();
1423 UIntPtrTy = TD->getIntPtrType();
1424
1425 // Find all uses of induction variables in this loop, and catagorize
1426 // them by stride. Start by finding all of the PHI nodes in the header for
1427 // this loop. If they are induction variables, inspect their uses.
1428 std::set<Instruction*> Processed; // Don't reprocess instructions.
1429 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1430 AddUsersIfInteresting(I, L, Processed);
1431
1432 // If we have nothing to do, return.
1433 if (IVUsesByStride.empty()) return false;
1434
1435 // Optimize induction variables. Some indvar uses can be transformed to use
1436 // strides that will be needed for other purposes. A common example of this
1437 // is the exit test for the loop, which can often be rewritten to use the
1438 // computation of some other indvar to decide when to terminate the loop.
1439 OptimizeIndvars(L);
1440
1441
1442 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1443 // doing computation in byte values, promote to 32-bit values if safe.
1444
1445 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1446 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1447 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1448 // to be careful that IV's are all the same type. Only works for intptr_t
1449 // indvars.
1450
1451 // If we only have one stride, we can more aggressively eliminate some things.
1452 bool HasOneStride = IVUsesByStride.size() == 1;
1453
1454#ifndef NDEBUG
1455 DOUT << "\nLSR on ";
1456 DEBUG(L->dump());
1457#endif
1458
1459 // IVsByStride keeps IVs for one particular loop.
1460 IVsByStride.clear();
1461
1462 // Sort the StrideOrder so we process larger strides first.
1463 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1464
1465 // Note: this processes each stride/type pair individually. All users passed
1466 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1467 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1468 // This extra layer of indirection makes the ordering of strides deterministic
1469 // - not dependent on map order.
1470 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1471 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1472 IVUsesByStride.find(StrideOrder[Stride]);
1473 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1474 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1475 }
1476
1477 // Clean up after ourselves
1478 if (!DeadInsts.empty()) {
1479 DeleteTriviallyDeadInstructions(DeadInsts);
1480
1481 BasicBlock::iterator I = L->getHeader()->begin();
1482 PHINode *PN;
1483 while ((PN = dyn_cast<PHINode>(I))) {
1484 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1485
1486 // At this point, we know that we have killed one or more GEP
1487 // instructions. It is worth checking to see if the cann indvar is also
1488 // dead, so that we can remove it as well. The requirements for the cann
1489 // indvar to be considered dead are:
1490 // 1. the cann indvar has one use
1491 // 2. the use is an add instruction
1492 // 3. the add has one use
1493 // 4. the add is used by the cann indvar
1494 // If all four cases above are true, then we can remove both the add and
1495 // the cann indvar.
1496 // FIXME: this needs to eliminate an induction variable even if it's being
1497 // compared against some value to decide loop termination.
1498 if (PN->hasOneUse()) {
1499 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1500 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1501 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
1502 DeadInsts.insert(BO);
1503 // Break the cycle, then delete the PHI.
1504 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1505 SE->deleteValueFromRecords(PN);
1506 PN->eraseFromParent();
1507 }
1508 }
1509 }
1510 }
1511 DeleteTriviallyDeadInstructions(DeadInsts);
1512 }
1513
1514 CastedPointers.clear();
1515 IVUsesByStride.clear();
1516 StrideOrder.clear();
1517 return false;
1518}