blob: a58356542db5ea1f3fb3ab1661a1f82eb678fba0 [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
Dan Gohman5766ac72007-10-22 20:40:42 +0000178 unsigned CheckForIVReuse(bool, const SCEVHandle&,
179 IVExpr&, const Type*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 const std::vector<BasedUser>& UsersToProcess);
181
Dan Gohman5766ac72007-10-22 20:40:42 +0000182 bool ValidStride(bool, int64_t,
183 const std::vector<BasedUser>& UsersToProcess);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184
185 void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
186 IVUsersOfOneStride &Uses,
187 Loop *L, bool isOnlyStride);
188 void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
189 };
190 char LoopStrengthReduce::ID = 0;
191 RegisterPass<LoopStrengthReduce> X("loop-reduce", "Loop Strength Reduction");
192}
193
194LoopPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
195 return new LoopStrengthReduce(TLI);
196}
197
198/// getCastedVersionOf - Return the specified value casted to uintptr_t. This
199/// assumes that the Value* V is of integer or pointer type only.
200///
201Value *LoopStrengthReduce::getCastedVersionOf(Instruction::CastOps opcode,
202 Value *V) {
203 if (V->getType() == UIntPtrTy) return V;
204 if (Constant *CB = dyn_cast<Constant>(V))
205 return ConstantExpr::getCast(opcode, CB, UIntPtrTy);
206
207 Value *&New = CastedPointers[V];
208 if (New) return New;
209
210 New = SCEVExpander::InsertCastOfTo(opcode, V, UIntPtrTy);
211 DeadInsts.insert(cast<Instruction>(New));
212 return New;
213}
214
215
216/// DeleteTriviallyDeadInstructions - If any of the instructions is the
217/// specified set are trivially dead, delete them and see if this makes any of
218/// their operands subsequently dead.
219void LoopStrengthReduce::
220DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
221 while (!Insts.empty()) {
222 Instruction *I = *Insts.begin();
223 Insts.erase(Insts.begin());
224 if (isInstructionTriviallyDead(I)) {
225 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
226 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
227 Insts.insert(U);
228 SE->deleteValueFromRecords(I);
229 I->eraseFromParent();
230 Changed = true;
231 }
232 }
233}
234
235
236/// GetExpressionSCEV - Compute and return the SCEV for the specified
237/// instruction.
238SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
239 // Pointer to pointer bitcast instructions return the same value as their
240 // operand.
241 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Exp)) {
242 if (SE->hasSCEV(BCI) || !isa<Instruction>(BCI->getOperand(0)))
243 return SE->getSCEV(BCI);
244 SCEVHandle R = GetExpressionSCEV(cast<Instruction>(BCI->getOperand(0)), L);
245 SE->setSCEV(BCI, R);
246 return R;
247 }
248
249 // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
250 // If this is a GEP that SE doesn't know about, compute it now and insert it.
251 // If this is not a GEP, or if we have already done this computation, just let
252 // SE figure it out.
253 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
254 if (!GEP || SE->hasSCEV(GEP))
255 return SE->getSCEV(Exp);
256
257 // Analyze all of the subscripts of this getelementptr instruction, looking
258 // for uses that are determined by the trip count of L. First, skip all
259 // operands the are not dependent on the IV.
260
261 // Build up the base expression. Insert an LLVM cast of the pointer to
262 // uintptr_t first.
Dan Gohman89f85052007-10-22 18:31:58 +0000263 SCEVHandle GEPVal = SE->getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 getCastedVersionOf(Instruction::PtrToInt, GEP->getOperand(0)));
265
266 gep_type_iterator GTI = gep_type_begin(GEP);
267
268 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
269 // If this is a use of a recurrence that we can analyze, and it comes before
270 // Op does in the GEP operand list, we will handle this when we process this
271 // operand.
272 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
273 const StructLayout *SL = TD->getStructLayout(STy);
274 unsigned Idx = cast<ConstantInt>(GEP->getOperand(i))->getZExtValue();
275 uint64_t Offset = SL->getElementOffset(Idx);
Dan Gohman89f85052007-10-22 18:31:58 +0000276 GEPVal = SE->getAddExpr(GEPVal,
277 SE->getIntegerSCEV(Offset, UIntPtrTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 } else {
279 unsigned GEPOpiBits =
280 GEP->getOperand(i)->getType()->getPrimitiveSizeInBits();
281 unsigned IntPtrBits = UIntPtrTy->getPrimitiveSizeInBits();
282 Instruction::CastOps opcode = (GEPOpiBits < IntPtrBits ?
283 Instruction::SExt : (GEPOpiBits > IntPtrBits ? Instruction::Trunc :
284 Instruction::BitCast));
285 Value *OpVal = getCastedVersionOf(opcode, GEP->getOperand(i));
286 SCEVHandle Idx = SE->getSCEV(OpVal);
287
Dale Johannesen5ec2e732007-10-01 23:08:35 +0000288 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 if (TypeSize != 1)
Dan Gohman89f85052007-10-22 18:31:58 +0000290 Idx = SE->getMulExpr(Idx,
291 SE->getConstant(ConstantInt::get(UIntPtrTy,
292 TypeSize)));
293 GEPVal = SE->getAddExpr(GEPVal, Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 }
295 }
296
297 SE->setSCEV(GEP, GEPVal);
298 return GEPVal;
299}
300
301/// getSCEVStartAndStride - Compute the start and stride of this expression,
302/// returning false if the expression is not a start/stride pair, or true if it
303/// is. The stride must be a loop invariant expression, but the start may be
304/// a mix of loop invariant and loop variant expressions.
305static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
Dan Gohman89f85052007-10-22 18:31:58 +0000306 SCEVHandle &Start, SCEVHandle &Stride,
307 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 SCEVHandle TheAddRec = Start; // Initialize to zero.
309
310 // If the outer level is an AddExpr, the operands are all start values except
311 // for a nested AddRecExpr.
312 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
313 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
314 if (SCEVAddRecExpr *AddRec =
315 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
316 if (AddRec->getLoop() == L)
Dan Gohman89f85052007-10-22 18:31:58 +0000317 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 else
319 return false; // Nested IV of some sort?
320 } else {
Dan Gohman89f85052007-10-22 18:31:58 +0000321 Start = SE->getAddExpr(Start, AE->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 }
323
324 } else if (isa<SCEVAddRecExpr>(SH)) {
325 TheAddRec = SH;
326 } else {
327 return false; // not analyzable.
328 }
329
330 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
331 if (!AddRec || AddRec->getLoop() != L) return false;
332
333 // FIXME: Generalize to non-affine IV's.
334 if (!AddRec->isAffine()) return false;
335
Dan Gohman89f85052007-10-22 18:31:58 +0000336 Start = SE->getAddExpr(Start, AddRec->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337
338 if (!isa<SCEVConstant>(AddRec->getOperand(1)))
339 DOUT << "[" << L->getHeader()->getName()
340 << "] Variable stride: " << *AddRec << "\n";
341
342 Stride = AddRec->getOperand(1);
343 return true;
344}
345
346/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
347/// and now we need to decide whether the user should use the preinc or post-inc
348/// value. If this user should use the post-inc version of the IV, return true.
349///
350/// Choosing wrong here can break dominance properties (if we choose to use the
351/// post-inc value when we cannot) or it can end up adding extra live-ranges to
352/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
353/// should use the post-inc value).
354static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
355 Loop *L, DominatorTree *DT, Pass *P) {
356 // If the user is in the loop, use the preinc value.
357 if (L->contains(User->getParent())) return false;
358
359 BasicBlock *LatchBlock = L->getLoopLatch();
360
361 // Ok, the user is outside of the loop. If it is dominated by the latch
362 // block, use the post-inc value.
363 if (DT->dominates(LatchBlock, User->getParent()))
364 return true;
365
366 // There is one case we have to be careful of: PHI nodes. These little guys
367 // can live in blocks that do not dominate the latch block, but (since their
368 // uses occur in the predecessor block, not the block the PHI lives in) should
369 // still use the post-inc value. Check for this case now.
370 PHINode *PN = dyn_cast<PHINode>(User);
371 if (!PN) return false; // not a phi, not dominated by latch block.
372
373 // Look at all of the uses of IV by the PHI node. If any use corresponds to
374 // a block that is not dominated by the latch block, give up and use the
375 // preincremented value.
376 unsigned NumUses = 0;
377 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
378 if (PN->getIncomingValue(i) == IV) {
379 ++NumUses;
380 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
381 return false;
382 }
383
384 // Okay, all uses of IV by PN are in predecessor blocks that really are
385 // dominated by the latch block. Split the critical edges and use the
386 // post-incremented value.
387 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
388 if (PN->getIncomingValue(i) == IV) {
389 SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P,
390 true);
391 // Splitting the critical edge can reduce the number of entries in this
392 // PHI.
393 e = PN->getNumIncomingValues();
394 if (--NumUses == 0) break;
395 }
396
397 return true;
398}
399
400
401
402/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
403/// reducible SCEV, recursively add its users to the IVUsesByStride set and
404/// return true. Otherwise, return false.
405bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
406 std::set<Instruction*> &Processed) {
407 if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
408 return false; // Void and FP expressions cannot be reduced.
409 if (!Processed.insert(I).second)
410 return true; // Instruction already handled.
411
412 // Get the symbolic expression for this instruction.
413 SCEVHandle ISE = GetExpressionSCEV(I, L);
414 if (isa<SCEVCouldNotCompute>(ISE)) return false;
415
416 // Get the start and stride for this expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000417 SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 SCEVHandle Stride = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000419 if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 return false; // Non-reducible symbolic expression, bail out.
421
422 std::vector<Instruction *> IUsers;
423 // Collect all I uses now because IVUseShouldUsePostIncValue may
424 // invalidate use_iterator.
425 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
426 IUsers.push_back(cast<Instruction>(*UI));
427
428 for (unsigned iused_index = 0, iused_size = IUsers.size();
429 iused_index != iused_size; ++iused_index) {
430
431 Instruction *User = IUsers[iused_index];
432
433 // Do not infinitely recurse on PHI nodes.
434 if (isa<PHINode>(User) && Processed.count(User))
435 continue;
436
437 // If this is an instruction defined in a nested loop, or outside this loop,
438 // don't recurse into it.
439 bool AddUserToIVUsers = false;
440 if (LI->getLoopFor(User->getParent()) != L) {
441 DOUT << "FOUND USER in other loop: " << *User
442 << " OF SCEV: " << *ISE << "\n";
443 AddUserToIVUsers = true;
444 } else if (!AddUsersIfInteresting(User, L, Processed)) {
445 DOUT << "FOUND USER: " << *User
446 << " OF SCEV: " << *ISE << "\n";
447 AddUserToIVUsers = true;
448 }
449
450 if (AddUserToIVUsers) {
451 IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
452 if (StrideUses.Users.empty()) // First occurance of this stride?
453 StrideOrder.push_back(Stride);
454
455 // Okay, we found a user that we cannot reduce. Analyze the instruction
456 // and decide what to do with it. If we are a use inside of the loop, use
457 // the value before incrementation, otherwise use it after incrementation.
458 if (IVUseShouldUsePostIncValue(User, I, L, DT, this)) {
459 // The value used will be incremented by the stride more than we are
460 // expecting, so subtract this off.
Dan Gohman89f85052007-10-22 18:31:58 +0000461 SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 StrideUses.addUser(NewStart, User, I);
463 StrideUses.Users.back().isUseOfPostIncrementedValue = true;
464 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n";
465 } else {
466 StrideUses.addUser(Start, User, I);
467 }
468 }
469 }
470 return true;
471}
472
473namespace {
474 /// BasedUser - For a particular base value, keep information about how we've
475 /// partitioned the expression so far.
476 struct BasedUser {
Dan Gohman89f85052007-10-22 18:31:58 +0000477 /// SE - The current ScalarEvolution object.
478 ScalarEvolution *SE;
479
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 /// Base - The Base value for the PHI node that needs to be inserted for
481 /// this use. As the use is processed, information gets moved from this
482 /// field to the Imm field (below). BasedUser values are sorted by this
483 /// field.
484 SCEVHandle Base;
485
486 /// Inst - The instruction using the induction variable.
487 Instruction *Inst;
488
489 /// OperandValToReplace - The operand value of Inst to replace with the
490 /// EmittedBase.
491 Value *OperandValToReplace;
492
493 /// Imm - The immediate value that should be added to the base immediately
494 /// before Inst, because it will be folded into the imm field of the
495 /// instruction.
496 SCEVHandle Imm;
497
498 /// EmittedBase - The actual value* to use for the base value of this
499 /// operation. This is null if we should just use zero so far.
500 Value *EmittedBase;
501
502 // isUseOfPostIncrementedValue - True if this should use the
503 // post-incremented version of this IV, not the preincremented version.
504 // This can only be set in special cases, such as the terminating setcc
505 // instruction for a loop and uses outside the loop that are dominated by
506 // the loop.
507 bool isUseOfPostIncrementedValue;
508
Dan Gohman89f85052007-10-22 18:31:58 +0000509 BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
510 : SE(se), Base(IVSU.Offset), Inst(IVSU.User),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 OperandValToReplace(IVSU.OperandValToReplace),
Dan Gohman89f85052007-10-22 18:31:58 +0000512 Imm(SE->getIntegerSCEV(0, Base->getType())), EmittedBase(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
514
515 // Once we rewrite the code to insert the new IVs we want, update the
516 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
517 // to it.
518 void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
519 SCEVExpander &Rewriter, Loop *L,
520 Pass *P);
521
522 Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
523 SCEVExpander &Rewriter,
524 Instruction *IP, Loop *L);
525 void dump() const;
526 };
527}
528
529void BasedUser::dump() const {
530 cerr << " Base=" << *Base;
531 cerr << " Imm=" << *Imm;
532 if (EmittedBase)
533 cerr << " EB=" << *EmittedBase;
534
535 cerr << " Inst: " << *Inst;
536}
537
538Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase,
539 SCEVExpander &Rewriter,
540 Instruction *IP, Loop *L) {
541 // Figure out where we *really* want to insert this code. In particular, if
542 // the user is inside of a loop that is nested inside of L, we really don't
543 // want to insert this expression before the user, we'd rather pull it out as
544 // many loops as possible.
545 LoopInfo &LI = Rewriter.getLoopInfo();
546 Instruction *BaseInsertPt = IP;
547
548 // Figure out the most-nested loop that IP is in.
549 Loop *InsertLoop = LI.getLoopFor(IP->getParent());
550
551 // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
552 // the preheader of the outer-most loop where NewBase is not loop invariant.
553 while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
554 BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
555 InsertLoop = InsertLoop->getParentLoop();
556 }
557
558 // If there is no immediate value, skip the next part.
559 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
560 if (SC->getValue()->isZero())
561 return Rewriter.expandCodeFor(NewBase, BaseInsertPt);
562
563 Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
564
565 // If we are inserting the base and imm values in the same block, make sure to
566 // adjust the IP position if insertion reused a result.
567 if (IP == BaseInsertPt)
568 IP = Rewriter.getInsertionPoint();
569
570 // Always emit the immediate (if non-zero) into the same block as the user.
Dan Gohman89f85052007-10-22 18:31:58 +0000571 SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572 return Rewriter.expandCodeFor(NewValSCEV, IP);
573
574}
575
576
577// Once we rewrite the code to insert the new IVs we want, update the
578// operands of Inst to use the new expression 'NewBase', with 'Imm' added
579// to it.
580void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
581 SCEVExpander &Rewriter,
582 Loop *L, Pass *P) {
583 if (!isa<PHINode>(Inst)) {
584 // By default, insert code at the user instruction.
585 BasicBlock::iterator InsertPt = Inst;
586
587 // However, if the Operand is itself an instruction, the (potentially
588 // complex) inserted code may be shared by many users. Because of this, we
589 // want to emit code for the computation of the operand right before its old
590 // computation. This is usually safe, because we obviously used to use the
591 // computation when it was computed in its current block. However, in some
592 // cases (e.g. use of a post-incremented induction variable) the NewBase
593 // value will be pinned to live somewhere after the original computation.
594 // In this case, we have to back off.
595 if (!isUseOfPostIncrementedValue) {
596 if (Instruction *OpInst = dyn_cast<Instruction>(OperandValToReplace)) {
597 InsertPt = OpInst;
598 while (isa<PHINode>(InsertPt)) ++InsertPt;
599 }
600 }
601 Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
Dan Gohman5d1dd952007-07-31 17:22:27 +0000602 // Adjust the type back to match the Inst. Note that we can't use InsertPt
603 // here because the SCEVExpander may have inserted the instructions after
604 // that point, in its efforts to avoid inserting redundant expressions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 if (isa<PointerType>(OperandValToReplace->getType())) {
Dan Gohman5d1dd952007-07-31 17:22:27 +0000606 NewVal = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
607 NewVal,
608 OperandValToReplace->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609 }
610 // Replace the use of the operand Value with the new Phi we just created.
611 Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
612 DOUT << " CHANGED: IMM =" << *Imm;
613 DOUT << " \tNEWBASE =" << *NewBase;
614 DOUT << " \tInst = " << *Inst;
615 return;
616 }
617
618 // PHI nodes are more complex. We have to insert one copy of the NewBase+Imm
619 // expression into each operand block that uses it. Note that PHI nodes can
620 // have multiple entries for the same predecessor. We use a map to make sure
621 // that a PHI node only has a single Value* for each predecessor (which also
622 // prevents us from inserting duplicate code in some blocks).
623 std::map<BasicBlock*, Value*> InsertedCode;
624 PHINode *PN = cast<PHINode>(Inst);
625 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
626 if (PN->getIncomingValue(i) == OperandValToReplace) {
627 // If this is a critical edge, split the edge so that we do not insert the
628 // code on all predecessor/successor paths. We do this unless this is the
629 // canonical backedge for this loop, as this can make some inserted code
630 // be in an illegal position.
631 BasicBlock *PHIPred = PN->getIncomingBlock(i);
632 if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
633 (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
634
635 // First step, split the critical edge.
636 SplitCriticalEdge(PHIPred, PN->getParent(), P, true);
637
638 // Next step: move the basic block. In particular, if the PHI node
639 // is outside of the loop, and PredTI is in the loop, we want to
640 // move the block to be immediately before the PHI block, not
641 // immediately after PredTI.
642 if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
643 BasicBlock *NewBB = PN->getIncomingBlock(i);
644 NewBB->moveBefore(PN->getParent());
645 }
646
647 // Splitting the edge can reduce the number of PHI entries we have.
648 e = PN->getNumIncomingValues();
649 }
650
651 Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
652 if (!Code) {
653 // Insert the code into the end of the predecessor block.
654 Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
655 Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
656
Chris Lattner03dc7d72007-08-02 16:53:43 +0000657 // Adjust the type back to match the PHI. Note that we can't use
658 // InsertPt here because the SCEVExpander may have inserted its
659 // instructions after that point, in its efforts to avoid inserting
660 // redundant expressions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 if (isa<PointerType>(PN->getType())) {
Dan Gohman5d1dd952007-07-31 17:22:27 +0000662 Code = SCEVExpander::InsertCastOfTo(Instruction::IntToPtr,
663 Code,
664 PN->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 }
666 }
667
668 // Replace the use of the operand Value with the new Phi we just created.
669 PN->setIncomingValue(i, Code);
670 Rewriter.clear();
671 }
672 }
673 DOUT << " CHANGED: IMM =" << *Imm << " Inst = " << *Inst;
674}
675
676
677/// isTargetConstant - Return true if the following can be referenced by the
678/// immediate field of a target instruction.
679static bool isTargetConstant(const SCEVHandle &V, const Type *UseTy,
680 const TargetLowering *TLI) {
681 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
682 int64_t VC = SC->getValue()->getSExtValue();
683 if (TLI) {
684 TargetLowering::AddrMode AM;
685 AM.BaseOffs = VC;
686 return TLI->isLegalAddressingMode(AM, UseTy);
687 } else {
688 // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
689 return (VC > -(1 << 16) && VC < (1 << 16)-1);
690 }
691 }
692
693 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
694 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
695 if (TLI && CE->getOpcode() == Instruction::PtrToInt) {
696 Constant *Op0 = CE->getOperand(0);
697 if (GlobalValue *GV = dyn_cast<GlobalValue>(Op0)) {
698 TargetLowering::AddrMode AM;
699 AM.BaseGV = GV;
700 return TLI->isLegalAddressingMode(AM, UseTy);
701 }
702 }
703 return false;
704}
705
706/// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
707/// loop varying to the Imm operand.
708static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman89f85052007-10-22 18:31:58 +0000709 Loop *L, ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 if (Val->isLoopInvariant(L)) return; // Nothing to do.
711
712 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
713 std::vector<SCEVHandle> NewOps;
714 NewOps.reserve(SAE->getNumOperands());
715
716 for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
717 if (!SAE->getOperand(i)->isLoopInvariant(L)) {
718 // If this is a loop-variant expression, it must stay in the immediate
719 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000720 Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 } else {
722 NewOps.push_back(SAE->getOperand(i));
723 }
724
725 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000726 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000727 else
Dan Gohman89f85052007-10-22 18:31:58 +0000728 Val = SE->getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000729 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
730 // Try to pull immediates out of the start value of nested addrec's.
731 SCEVHandle Start = SARE->getStart();
Dan Gohman89f85052007-10-22 18:31:58 +0000732 MoveLoopVariantsToImediateField(Start, Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733
734 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
735 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000736 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 } else {
738 // Otherwise, all of Val is variant, move the whole thing over.
Dan Gohman89f85052007-10-22 18:31:58 +0000739 Imm = SE->getAddExpr(Imm, Val);
740 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 }
742}
743
744
745/// MoveImmediateValues - Look at Val, and pull out any additions of constants
746/// that can fit into the immediate field of instructions in the target.
747/// Accumulate these immediate values into the Imm value.
748static void MoveImmediateValues(const TargetLowering *TLI,
749 Instruction *User,
750 SCEVHandle &Val, SCEVHandle &Imm,
Dan Gohman89f85052007-10-22 18:31:58 +0000751 bool isAddress, Loop *L,
752 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753 const Type *UseTy = User->getType();
754 if (StoreInst *SI = dyn_cast<StoreInst>(User))
755 UseTy = SI->getOperand(0)->getType();
756
757 if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
758 std::vector<SCEVHandle> NewOps;
759 NewOps.reserve(SAE->getNumOperands());
760
761 for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
762 SCEVHandle NewOp = SAE->getOperand(i);
Dan Gohman89f85052007-10-22 18:31:58 +0000763 MoveImmediateValues(TLI, User, NewOp, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764
765 if (!NewOp->isLoopInvariant(L)) {
766 // If this is a loop-variant expression, it must stay in the immediate
767 // field of the expression.
Dan Gohman89f85052007-10-22 18:31:58 +0000768 Imm = SE->getAddExpr(Imm, NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 } else {
770 NewOps.push_back(NewOp);
771 }
772 }
773
774 if (NewOps.empty())
Dan Gohman89f85052007-10-22 18:31:58 +0000775 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776 else
Dan Gohman89f85052007-10-22 18:31:58 +0000777 Val = SE->getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778 return;
779 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
780 // Try to pull immediates out of the start value of nested addrec's.
781 SCEVHandle Start = SARE->getStart();
Dan Gohman89f85052007-10-22 18:31:58 +0000782 MoveImmediateValues(TLI, User, Start, Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783
784 if (Start != SARE->getStart()) {
785 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
786 Ops[0] = Start;
Dan Gohman89f85052007-10-22 18:31:58 +0000787 Val = SE->getAddRecExpr(Ops, SARE->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 }
789 return;
790 } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
791 // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
792 if (isAddress && isTargetConstant(SME->getOperand(0), UseTy, TLI) &&
793 SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
794
Dan Gohman89f85052007-10-22 18:31:58 +0000795 SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796 SCEVHandle NewOp = SME->getOperand(1);
Dan Gohman89f85052007-10-22 18:31:58 +0000797 MoveImmediateValues(TLI, User, NewOp, SubImm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798
799 // If we extracted something out of the subexpressions, see if we can
800 // simplify this!
801 if (NewOp != SME->getOperand(1)) {
802 // Scale SubImm up by "8". If the result is a target constant, we are
803 // good.
Dan Gohman89f85052007-10-22 18:31:58 +0000804 SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 if (isTargetConstant(SubImm, UseTy, TLI)) {
806 // Accumulate the immediate.
Dan Gohman89f85052007-10-22 18:31:58 +0000807 Imm = SE->getAddExpr(Imm, SubImm);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808
809 // Update what is left of 'Val'.
Dan Gohman89f85052007-10-22 18:31:58 +0000810 Val = SE->getMulExpr(SME->getOperand(0), NewOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 return;
812 }
813 }
814 }
815 }
816
817 // Loop-variant expressions must stay in the immediate field of the
818 // expression.
819 if ((isAddress && isTargetConstant(Val, UseTy, TLI)) ||
820 !Val->isLoopInvariant(L)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000821 Imm = SE->getAddExpr(Imm, Val);
822 Val = SE->getIntegerSCEV(0, Val->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823 return;
824 }
825
826 // Otherwise, no immediates to move.
827}
828
829
830/// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
831/// added together. This is used to reassociate common addition subexprs
832/// together for maximal sharing when rewriting bases.
833static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
Dan Gohman89f85052007-10-22 18:31:58 +0000834 SCEVHandle Expr,
835 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
837 for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
Dan Gohman89f85052007-10-22 18:31:58 +0000838 SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
Dan Gohman89f85052007-10-22 18:31:58 +0000840 SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 if (SARE->getOperand(0) == Zero) {
842 SubExprs.push_back(Expr);
843 } else {
844 // Compute the addrec with zero as its base.
845 std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
846 Ops[0] = Zero; // Start with zero base.
Dan Gohman89f85052007-10-22 18:31:58 +0000847 SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848
849
Dan Gohman89f85052007-10-22 18:31:58 +0000850 SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 }
852 } else if (!isa<SCEVConstant>(Expr) ||
853 !cast<SCEVConstant>(Expr)->getValue()->isZero()) {
854 // Do not add zero.
855 SubExprs.push_back(Expr);
856 }
857}
858
859
860/// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
861/// removing any common subexpressions from it. Anything truly common is
862/// removed, accumulated, and returned. This looks for things like (a+b+c) and
863/// (a+c+d) -> (a+c). The common expression is *removed* from the Bases.
864static SCEVHandle
Dan Gohman89f85052007-10-22 18:31:58 +0000865RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
866 ScalarEvolution *SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 unsigned NumUses = Uses.size();
868
869 // Only one use? Use its base, regardless of what it is!
Dan Gohman89f85052007-10-22 18:31:58 +0000870 SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 SCEVHandle Result = Zero;
872 if (NumUses == 1) {
873 std::swap(Result, Uses[0].Base);
874 return Result;
875 }
876
877 // To find common subexpressions, count how many of Uses use each expression.
878 // If any subexpressions are used Uses.size() times, they are common.
879 std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
880
881 // UniqueSubExprs - Keep track of all of the subexpressions we see in the
882 // order we see them.
883 std::vector<SCEVHandle> UniqueSubExprs;
884
885 std::vector<SCEVHandle> SubExprs;
886 for (unsigned i = 0; i != NumUses; ++i) {
887 // If the base is zero (which is common), return zero now, there are no
888 // CSEs we can find.
889 if (Uses[i].Base == Zero) return Zero;
890
891 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000892 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 // Add one to SubExpressionUseCounts for each subexpr present.
894 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
895 if (++SubExpressionUseCounts[SubExprs[j]] == 1)
896 UniqueSubExprs.push_back(SubExprs[j]);
897 SubExprs.clear();
898 }
899
900 // Now that we know how many times each is used, build Result. Iterate over
901 // UniqueSubexprs so that we have a stable ordering.
902 for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
903 std::map<SCEVHandle, unsigned>::iterator I =
904 SubExpressionUseCounts.find(UniqueSubExprs[i]);
905 assert(I != SubExpressionUseCounts.end() && "Entry not found?");
906 if (I->second == NumUses) { // Found CSE!
Dan Gohman89f85052007-10-22 18:31:58 +0000907 Result = SE->getAddExpr(Result, I->first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 } else {
909 // Remove non-cse's from SubExpressionUseCounts.
910 SubExpressionUseCounts.erase(I);
911 }
912 }
913
914 // If we found no CSE's, return now.
915 if (Result == Zero) return Result;
916
917 // Otherwise, remove all of the CSE's we found from each of the base values.
918 for (unsigned i = 0; i != NumUses; ++i) {
919 // Split the expression into subexprs.
Dan Gohman89f85052007-10-22 18:31:58 +0000920 SeparateSubExprs(SubExprs, Uses[i].Base, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921
922 // Remove any common subexpressions.
923 for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
924 if (SubExpressionUseCounts.count(SubExprs[j])) {
925 SubExprs.erase(SubExprs.begin()+j);
926 --j; --e;
927 }
928
929 // Finally, the non-shared expressions together.
930 if (SubExprs.empty())
931 Uses[i].Base = Zero;
932 else
Dan Gohman89f85052007-10-22 18:31:58 +0000933 Uses[i].Base = SE->getAddExpr(SubExprs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 SubExprs.clear();
935 }
936
937 return Result;
938}
939
940/// isZero - returns true if the scalar evolution expression is zero.
941///
Dan Gohman5766ac72007-10-22 20:40:42 +0000942static bool isZero(const SCEVHandle &V) {
943 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 return SC->getValue()->isZero();
945 return false;
946}
947
948/// ValidStride - Check whether the given Scale is valid for all loads and
949/// stores in UsersToProcess.
950///
Dan Gohman5766ac72007-10-22 20:40:42 +0000951bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
952 int64_t Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 const std::vector<BasedUser>& UsersToProcess) {
954 for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
955 // If this is a load or other access, pass the type of the access in.
956 const Type *AccessTy = Type::VoidTy;
957 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
958 AccessTy = SI->getOperand(0)->getType();
959 else if (LoadInst *LI = dyn_cast<LoadInst>(UsersToProcess[i].Inst))
960 AccessTy = LI->getType();
961
962 TargetLowering::AddrMode AM;
963 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
964 AM.BaseOffs = SC->getValue()->getSExtValue();
Dan Gohman5766ac72007-10-22 20:40:42 +0000965 AM.HasBaseReg = HasBaseReg || !isZero(UsersToProcess[i].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966 AM.Scale = Scale;
967
968 // If load[imm+r*scale] is illegal, bail out.
969 if (!TLI->isLegalAddressingMode(AM, AccessTy))
970 return false;
971 }
972 return true;
973}
974
975/// CheckForIVReuse - Returns the multiple if the stride is the multiple
976/// of a previous stride and it is a legal value for the target addressing
Dan Gohman5766ac72007-10-22 20:40:42 +0000977/// mode scale component and optional base reg. This allows the users of
978/// this stride to be rewritten as prev iv * factor. It returns 0 if no
979/// reuse is possible.
980unsigned LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
981 const SCEVHandle &Stride,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 IVExpr &IV, const Type *Ty,
983 const std::vector<BasedUser>& UsersToProcess) {
984 if (!TLI) return 0;
985
986 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
987 int64_t SInt = SC->getValue()->getSExtValue();
988 if (SInt == 1) return 0;
989
990 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
991 SE = IVsByStride.end(); SI != SE; ++SI) {
992 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
993 if (SInt != -SSInt &&
994 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
995 continue;
996 int64_t Scale = SInt / SSInt;
997 // Check that this stride is valid for all the types used for loads and
998 // stores; if it can be used for some and not others, we might as well use
999 // the original stride everywhere, since we have to create the IV for it
1000 // anyway.
Dan Gohman5766ac72007-10-22 20:40:42 +00001001 if (ValidStride(HasBaseReg, Scale, UsersToProcess))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1003 IE = SI->second.IVs.end(); II != IE; ++II)
1004 // FIXME: Only handle base == 0 for now.
1005 // Only reuse previous IV if it would not require a type conversion.
1006 if (isZero(II->Base) && II->Base->getType() == Ty) {
1007 IV = *II;
1008 return Scale;
1009 }
1010 }
1011 }
1012 return 0;
1013}
1014
1015/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1016/// returns true if Val's isUseOfPostIncrementedValue is true.
1017static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1018 return Val.isUseOfPostIncrementedValue;
1019}
1020
1021/// isNonConstantNegative - REturn true if the specified scev is negated, but
1022/// not a constant.
1023static bool isNonConstantNegative(const SCEVHandle &Expr) {
1024 SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1025 if (!Mul) return false;
1026
1027 // If there is a constant factor, it will be first.
1028 SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1029 if (!SC) return false;
1030
1031 // Return true if the value is negative, this matches things like (-42 * V).
1032 return SC->getValue()->getValue().isNegative();
1033}
1034
1035/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1036/// stride of IV. All of the users may have different starting values, and this
1037/// may not be the only stride (we know it is if isOnlyStride is true).
1038void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1039 IVUsersOfOneStride &Uses,
1040 Loop *L,
1041 bool isOnlyStride) {
1042 // Transform our list of users and offsets to a bit more complex table. In
1043 // this new vector, each 'BasedUser' contains 'Base' the base of the
1044 // strided accessas well as the old information from Uses. We progressively
1045 // move information from the Base field to the Imm field, until we eventually
1046 // have the full access expression to rewrite the use.
1047 std::vector<BasedUser> UsersToProcess;
1048 UsersToProcess.reserve(Uses.Users.size());
1049 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +00001050 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051
1052 // Move any loop invariant operands from the offset field to the immediate
1053 // field of the use, so that we don't try to use something before it is
1054 // computed.
1055 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001056 UsersToProcess.back().Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1058 "Base value is not loop invariant!");
1059 }
1060
1061 // We now have a whole bunch of uses of like-strided induction variables, but
1062 // they might all have different bases. We want to emit one PHI node for this
1063 // stride which we fold as many common expressions (between the IVs) into as
1064 // possible. Start by identifying the common expressions in the base values
1065 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1066 // "A+B"), emit it to the preheader, then remove the expression from the
1067 // UsersToProcess base values.
1068 SCEVHandle CommonExprs =
Dan Gohman89f85052007-10-22 18:31:58 +00001069 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE);
Dan Gohman5766ac72007-10-22 20:40:42 +00001070
1071 // If we managed to find some expressions in common, we'll need to carry
1072 // their value in a register and add it in for each use. This will take up
1073 // a register operand, which potentially restricts what stride values are
1074 // valid.
1075 bool HaveCommonExprs = !isZero(CommonExprs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076
Dan Gohman5766ac72007-10-22 20:40:42 +00001077 // Keep track if every use in UsersToProcess is an address. If they all are,
1078 // we may be able to rewrite the entire collection of them in terms of a
1079 // smaller-stride IV.
1080 bool AllUsesAreAddresses = true;
1081
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 // Next, figure out what we can represent in the immediate fields of
1083 // instructions. If we can represent anything there, move it to the imm
1084 // fields of the BasedUsers. We do this so that it increases the commonality
1085 // of the remaining uses.
1086 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1087 // If the user is not in the current loop, this means it is using the exit
1088 // value of the IV. Do not put anything in the base, make sure it's all in
1089 // the immediate field to allow as much factoring as possible.
1090 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Dan Gohman89f85052007-10-22 18:31:58 +00001091 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1092 UsersToProcess[i].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093 UsersToProcess[i].Base =
Dan Gohman89f85052007-10-22 18:31:58 +00001094 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 } else {
1096
1097 // Addressing modes can be folded into loads and stores. Be careful that
1098 // the store is through the expression, not of the expression though.
1099 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1100 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst)) {
1101 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1102 isAddress = true;
1103 } else if (IntrinsicInst *II =
1104 dyn_cast<IntrinsicInst>(UsersToProcess[i].Inst)) {
Dan Gohman5766ac72007-10-22 20:40:42 +00001105 // Addressing modes can also be folded into prefetches and a variety
1106 // of intrinsics.
1107 switch (II->getIntrinsicID()) {
1108 default: break;
1109 case Intrinsic::prefetch:
1110 case Intrinsic::x86_sse2_loadu_dq:
1111 case Intrinsic::x86_sse2_loadu_pd:
1112 case Intrinsic::x86_sse_loadu_ps:
1113 case Intrinsic::x86_sse_storeu_ps:
1114 case Intrinsic::x86_sse2_storeu_pd:
1115 case Intrinsic::x86_sse2_storeu_dq:
1116 case Intrinsic::x86_sse2_storel_dq:
1117 if (II->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1118 isAddress = true;
1119 break;
1120 case Intrinsic::x86_sse2_loadh_pd:
1121 case Intrinsic::x86_sse2_loadl_pd:
1122 if (II->getOperand(2) == UsersToProcess[i].OperandValToReplace)
1123 isAddress = true;
1124 break;
1125 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 }
Dan Gohman5766ac72007-10-22 20:40:42 +00001127
1128 // If this use isn't an address, then not all uses are addresses.
1129 if (!isAddress)
1130 AllUsesAreAddresses = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131
1132 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001133 UsersToProcess[i].Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 }
1135 }
1136
Dan Gohman5766ac72007-10-22 20:40:42 +00001137 // If all uses are addresses, check if it is possible to reuse an IV with a
1138 // stride that is a factor of this stride. And that the multiple is a number
1139 // that can be encoded in the scale field of the target addressing mode. And
1140 // that we will have a valid instruction after this substition, including the
1141 // immediate field, if any.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 PHINode *NewPHI = NULL;
1143 Value *IncV = NULL;
Dan Gohman89f85052007-10-22 18:31:58 +00001144 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1145 SE->getIntegerSCEV(0, Type::Int32Ty),
1146 0, 0);
Dan Gohman5766ac72007-10-22 20:40:42 +00001147 unsigned RewriteFactor = 0;
1148 if (AllUsesAreAddresses)
1149 RewriteFactor = CheckForIVReuse(HaveCommonExprs, Stride, ReuseIV,
1150 CommonExprs->getType(),
1151 UsersToProcess);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 if (RewriteFactor != 0) {
1153 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1154 << " and BASE " << *ReuseIV.Base << " :\n";
1155 NewPHI = ReuseIV.PHI;
1156 IncV = ReuseIV.IncV;
1157 }
1158
1159 const Type *ReplacedTy = CommonExprs->getType();
1160
1161 // Now that we know what we need to do, insert the PHI node itself.
1162 //
1163 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1164 << *Stride << " and BASE " << *CommonExprs << ": ";
1165
1166 SCEVExpander Rewriter(*SE, *LI);
1167 SCEVExpander PreheaderRewriter(*SE, *LI);
1168
1169 BasicBlock *Preheader = L->getLoopPreheader();
1170 Instruction *PreInsertPt = Preheader->getTerminator();
1171 Instruction *PhiInsertBefore = L->getHeader()->begin();
1172
1173 BasicBlock *LatchBlock = L->getLoopLatch();
1174
1175
1176 // Emit the initial base value into the loop preheader.
1177 Value *CommonBaseV
1178 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt);
1179
1180 if (RewriteFactor == 0) {
1181 // Create a new Phi for this base, and stick it in the loop header.
1182 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1183 ++NumInserted;
1184
1185 // Add common base to the new Phi node.
1186 NewPHI->addIncoming(CommonBaseV, Preheader);
1187
1188 // If the stride is negative, insert a sub instead of an add for the
1189 // increment.
1190 bool isNegative = isNonConstantNegative(Stride);
1191 SCEVHandle IncAmount = Stride;
1192 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001193 IncAmount = SE->getNegativeSCEV(Stride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194
1195 // Insert the stride into the preheader.
1196 Value *StrideV = PreheaderRewriter.expandCodeFor(IncAmount, PreInsertPt);
1197 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1198
1199 // Emit the increment of the base value before the terminator of the loop
1200 // latch block, and add it to the Phi node.
Dan Gohman89f85052007-10-22 18:31:58 +00001201 SCEVHandle IncExp = SE->getUnknown(StrideV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001203 IncExp = SE->getNegativeSCEV(IncExp);
1204 IncExp = SE->getAddExpr(SE->getUnknown(NewPHI), IncExp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205
1206 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator());
1207 IncV->setName(NewPHI->getName()+".inc");
1208 NewPHI->addIncoming(IncV, LatchBlock);
1209
1210 // Remember this in case a later stride is multiple of this.
1211 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1212
1213 DOUT << " IV=%" << NewPHI->getNameStr() << " INC=%" << IncV->getNameStr();
1214 } else {
1215 Constant *C = dyn_cast<Constant>(CommonBaseV);
1216 if (!C ||
1217 (!C->isNullValue() &&
Dan Gohman89f85052007-10-22 18:31:58 +00001218 !isTargetConstant(SE->getUnknown(CommonBaseV), ReplacedTy, TLI)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 // We want the common base emitted into the preheader! This is just
1220 // using cast as a copy so BitCast (no-op cast) is appropriate
1221 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1222 "commonbase", PreInsertPt);
1223 }
1224 DOUT << "\n";
1225
1226 // We want to emit code for users inside the loop first. To do this, we
1227 // rearrange BasedUser so that the entries at the end have
1228 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1229 // vector (so we handle them first).
1230 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1231 PartitionByIsUseOfPostIncrementedValue);
1232
1233 // Sort this by base, so that things with the same base are handled
1234 // together. By partitioning first and stable-sorting later, we are
1235 // guaranteed that within each base we will pop off users from within the
1236 // loop before users outside of the loop with a particular base.
1237 //
1238 // We would like to use stable_sort here, but we can't. The problem is that
1239 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1240 // we don't have anything to do a '<' comparison on. Because we think the
1241 // number of uses is small, do a horrible bubble sort which just relies on
1242 // ==.
1243 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1244 // Get a base value.
1245 SCEVHandle Base = UsersToProcess[i].Base;
1246
1247 // Compact everything with this base to be consequetive with this one.
1248 for (unsigned j = i+1; j != e; ++j) {
1249 if (UsersToProcess[j].Base == Base) {
1250 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1251 ++i;
1252 }
1253 }
1254 }
1255
1256 // Process all the users now. This outer loop handles all bases, the inner
1257 // loop handles all users of a particular base.
1258 while (!UsersToProcess.empty()) {
1259 SCEVHandle Base = UsersToProcess.back().Base;
1260
1261 // Emit the code for Base into the preheader.
1262 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt);
1263
1264 DOUT << " INSERTING code for BASE = " << *Base << ":";
1265 if (BaseV->hasName())
1266 DOUT << " Result value name = %" << BaseV->getNameStr();
1267 DOUT << "\n";
1268
1269 // If BaseV is a constant other than 0, make sure that it gets inserted into
1270 // the preheader, instead of being forward substituted into the uses. We do
1271 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1272 // in this case.
1273 if (Constant *C = dyn_cast<Constant>(BaseV)) {
1274 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
1275 // We want this constant emitted into the preheader! This is just
1276 // using cast as a copy so BitCast (no-op cast) is appropriate
1277 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1278 PreInsertPt);
1279 }
1280 }
1281
1282 // Emit the code to add the immediate offset to the Phi value, just before
1283 // the instructions that we identified as using this stride and base.
1284 do {
1285 // FIXME: Use emitted users to emit other users.
1286 BasedUser &User = UsersToProcess.back();
1287
1288 // If this instruction wants to use the post-incremented value, move it
1289 // after the post-inc and use its value instead of the PHI.
1290 Value *RewriteOp = NewPHI;
1291 if (User.isUseOfPostIncrementedValue) {
1292 RewriteOp = IncV;
1293
1294 // If this user is in the loop, make sure it is the last thing in the
1295 // loop to ensure it is dominated by the increment.
1296 if (L->contains(User.Inst->getParent()))
1297 User.Inst->moveBefore(LatchBlock->getTerminator());
1298 }
1299 if (RewriteOp->getType() != ReplacedTy) {
1300 Instruction::CastOps opcode = Instruction::Trunc;
1301 if (ReplacedTy->getPrimitiveSizeInBits() ==
1302 RewriteOp->getType()->getPrimitiveSizeInBits())
1303 opcode = Instruction::BitCast;
1304 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1305 }
1306
Dan Gohman89f85052007-10-22 18:31:58 +00001307 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308
1309 // Clear the SCEVExpander's expression map so that we are guaranteed
1310 // to have the code emitted where we expect it.
1311 Rewriter.clear();
1312
1313 // If we are reusing the iv, then it must be multiplied by a constant
1314 // factor take advantage of addressing mode scale component.
1315 if (RewriteFactor != 0) {
1316 RewriteExpr =
Dan Gohman89f85052007-10-22 18:31:58 +00001317 SE->getMulExpr(SE->getIntegerSCEV(RewriteFactor,
1318 RewriteExpr->getType()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 RewriteExpr);
1320
1321 // The common base is emitted in the loop preheader. But since we
1322 // are reusing an IV, it has not been used to initialize the PHI node.
1323 // Add it to the expression used to rewrite the uses.
1324 if (!isa<ConstantInt>(CommonBaseV) ||
1325 !cast<ConstantInt>(CommonBaseV)->isZero())
Dan Gohman89f85052007-10-22 18:31:58 +00001326 RewriteExpr = SE->getAddExpr(RewriteExpr,
1327 SE->getUnknown(CommonBaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 }
1329
1330 // Now that we know what we need to do, insert code before User for the
1331 // immediate and any loop-variant expressions.
1332 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
1333 // Add BaseV to the PHI value if needed.
Dan Gohman89f85052007-10-22 18:31:58 +00001334 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335
1336 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1337
1338 // Mark old value we replaced as possibly dead, so that it is elminated
1339 // if we just replaced the last use of that value.
1340 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1341
1342 UsersToProcess.pop_back();
1343 ++NumReduced;
1344
1345 // If there are any more users to process with the same base, process them
1346 // now. We sorted by base above, so we just have to check the last elt.
1347 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1348 // TODO: Next, find out which base index is the most common, pull it out.
1349 }
1350
1351 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1352 // different starting values, into different PHIs.
1353}
1354
1355/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1356/// set the IV user and stride information and return true, otherwise return
1357/// false.
1358bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1359 const SCEVHandle *&CondStride) {
1360 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1361 ++Stride) {
1362 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1363 IVUsesByStride.find(StrideOrder[Stride]);
1364 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1365
1366 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1367 E = SI->second.Users.end(); UI != E; ++UI)
1368 if (UI->User == Cond) {
1369 // NOTE: we could handle setcc instructions with multiple uses here, but
1370 // InstCombine does it as well for simple uses, it's not clear that it
1371 // occurs enough in real life to handle.
1372 CondUse = &*UI;
1373 CondStride = &SI->first;
1374 return true;
1375 }
1376 }
1377 return false;
1378}
1379
1380// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1381// uses in the loop, look to see if we can eliminate some, in favor of using
1382// common indvars for the different uses.
1383void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1384 // TODO: implement optzns here.
1385
1386 // Finally, get the terminating condition for the loop if possible. If we
1387 // can, we want to change it to use a post-incremented version of its
1388 // induction variable, to allow coalescing the live ranges for the IV into
1389 // one register value.
1390 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1391 BasicBlock *Preheader = L->getLoopPreheader();
1392 BasicBlock *LatchBlock =
1393 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1394 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1395 if (!TermBr || TermBr->isUnconditional() ||
1396 !isa<ICmpInst>(TermBr->getCondition()))
1397 return;
1398 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1399
1400 // Search IVUsesByStride to find Cond's IVUse if there is one.
1401 IVStrideUse *CondUse = 0;
1402 const SCEVHandle *CondStride = 0;
1403
1404 if (!FindIVForUser(Cond, CondUse, CondStride))
1405 return; // setcc doesn't use the IV.
1406
1407
1408 // It's possible for the setcc instruction to be anywhere in the loop, and
1409 // possible for it to have multiple users. If it is not immediately before
1410 // the latch block branch, move it.
1411 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1412 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1413 Cond->moveBefore(TermBr);
1414 } else {
1415 // Otherwise, clone the terminating condition and insert into the loopend.
1416 Cond = cast<ICmpInst>(Cond->clone());
1417 Cond->setName(L->getHeader()->getName() + ".termcond");
1418 LatchBlock->getInstList().insert(TermBr, Cond);
1419
1420 // Clone the IVUse, as the old use still exists!
1421 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1422 CondUse->OperandValToReplace);
1423 CondUse = &IVUsesByStride[*CondStride].Users.back();
1424 }
1425 }
1426
1427 // If we get to here, we know that we can transform the setcc instruction to
1428 // use the post-incremented version of the IV, allowing us to coalesce the
1429 // live ranges for the IV correctly.
Dan Gohman89f85052007-10-22 18:31:58 +00001430 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 CondUse->isUseOfPostIncrementedValue = true;
1432}
1433
1434namespace {
1435 // Constant strides come first which in turns are sorted by their absolute
1436 // values. If absolute values are the same, then positive strides comes first.
1437 // e.g.
1438 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1439 struct StrideCompare {
1440 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1441 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1442 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1443 if (LHSC && RHSC) {
1444 int64_t LV = LHSC->getValue()->getSExtValue();
1445 int64_t RV = RHSC->getValue()->getSExtValue();
1446 uint64_t ALV = (LV < 0) ? -LV : LV;
1447 uint64_t ARV = (RV < 0) ? -RV : RV;
1448 if (ALV == ARV)
1449 return LV > RV;
1450 else
1451 return ALV < ARV;
1452 }
1453 return (LHSC && !RHSC);
1454 }
1455 };
1456}
1457
1458bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
1459
1460 LI = &getAnalysis<LoopInfo>();
1461 DT = &getAnalysis<DominatorTree>();
1462 SE = &getAnalysis<ScalarEvolution>();
1463 TD = &getAnalysis<TargetData>();
1464 UIntPtrTy = TD->getIntPtrType();
1465
1466 // Find all uses of induction variables in this loop, and catagorize
1467 // them by stride. Start by finding all of the PHI nodes in the header for
1468 // this loop. If they are induction variables, inspect their uses.
1469 std::set<Instruction*> Processed; // Don't reprocess instructions.
1470 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1471 AddUsersIfInteresting(I, L, Processed);
1472
1473 // If we have nothing to do, return.
1474 if (IVUsesByStride.empty()) return false;
1475
1476 // Optimize induction variables. Some indvar uses can be transformed to use
1477 // strides that will be needed for other purposes. A common example of this
1478 // is the exit test for the loop, which can often be rewritten to use the
1479 // computation of some other indvar to decide when to terminate the loop.
1480 OptimizeIndvars(L);
1481
1482
1483 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1484 // doing computation in byte values, promote to 32-bit values if safe.
1485
1486 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1487 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1488 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1489 // to be careful that IV's are all the same type. Only works for intptr_t
1490 // indvars.
1491
1492 // If we only have one stride, we can more aggressively eliminate some things.
1493 bool HasOneStride = IVUsesByStride.size() == 1;
1494
1495#ifndef NDEBUG
1496 DOUT << "\nLSR on ";
1497 DEBUG(L->dump());
1498#endif
1499
1500 // IVsByStride keeps IVs for one particular loop.
1501 IVsByStride.clear();
1502
1503 // Sort the StrideOrder so we process larger strides first.
1504 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1505
1506 // Note: this processes each stride/type pair individually. All users passed
1507 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1508 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1509 // This extra layer of indirection makes the ordering of strides deterministic
1510 // - not dependent on map order.
1511 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1512 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1513 IVUsesByStride.find(StrideOrder[Stride]);
1514 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1515 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1516 }
1517
1518 // Clean up after ourselves
1519 if (!DeadInsts.empty()) {
1520 DeleteTriviallyDeadInstructions(DeadInsts);
1521
1522 BasicBlock::iterator I = L->getHeader()->begin();
1523 PHINode *PN;
1524 while ((PN = dyn_cast<PHINode>(I))) {
1525 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1526
1527 // At this point, we know that we have killed one or more GEP
1528 // instructions. It is worth checking to see if the cann indvar is also
1529 // dead, so that we can remove it as well. The requirements for the cann
1530 // indvar to be considered dead are:
1531 // 1. the cann indvar has one use
1532 // 2. the use is an add instruction
1533 // 3. the add has one use
1534 // 4. the add is used by the cann indvar
1535 // If all four cases above are true, then we can remove both the add and
1536 // the cann indvar.
1537 // FIXME: this needs to eliminate an induction variable even if it's being
1538 // compared against some value to decide loop termination.
1539 if (PN->hasOneUse()) {
1540 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1541 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1542 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
1543 DeadInsts.insert(BO);
1544 // Break the cycle, then delete the PHI.
1545 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1546 SE->deleteValueFromRecords(PN);
1547 PN->eraseFromParent();
1548 }
1549 }
1550 }
1551 }
1552 DeleteTriviallyDeadInstructions(DeadInsts);
1553 }
1554
1555 CastedPointers.clear();
1556 IVUsesByStride.clear();
1557 StrideOrder.clear();
1558 return false;
1559}