blob: 5805e02a55a5a45f037cdd1b5d3e4c2705f2b45a [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
Evan Cheng335d87d2007-10-25 09:11:16 +000042STATISTIC(NumReduced , "Number of GEPs strength reduced");
43STATISTIC(NumInserted, "Number of PHIs inserted");
44STATISTIC(NumVariable, "Number of PHIs with variable strides");
45STATISTIC(NumEliminated , "Number of strides eliminated");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046
47namespace {
48
49 struct BasedUser;
50
51 /// IVStrideUse - Keep track of one use of a strided induction variable, where
52 /// the stride is stored externally. The Offset member keeps track of the
53 /// offset from the IV, User is the actual user of the operand, and 'Operand'
54 /// is the operand # of the User that is the use.
55 struct VISIBILITY_HIDDEN IVStrideUse {
56 SCEVHandle Offset;
57 Instruction *User;
58 Value *OperandValToReplace;
59
60 // isUseOfPostIncrementedValue - True if this should use the
61 // post-incremented version of this IV, not the preincremented version.
62 // This can only be set in special cases, such as the terminating setcc
63 // instruction for a loop or uses dominated by the loop.
64 bool isUseOfPostIncrementedValue;
65
66 IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
67 : Offset(Offs), User(U), OperandValToReplace(O),
68 isUseOfPostIncrementedValue(false) {}
69 };
70
71 /// IVUsersOfOneStride - This structure keeps track of all instructions that
72 /// have an operand that is based on the trip count multiplied by some stride.
73 /// The stride for all of these users is common and kept external to this
74 /// structure.
75 struct VISIBILITY_HIDDEN IVUsersOfOneStride {
76 /// Users - Keep track of all of the users of this stride as well as the
77 /// initial value and the operand that uses the IV.
78 std::vector<IVStrideUse> Users;
79
80 void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
81 Users.push_back(IVStrideUse(Offset, User, Operand));
82 }
83 };
84
85 /// IVInfo - This structure keeps track of one IV expression inserted during
86 /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
87 /// well as the PHI node and increment value created for rewrite.
88 struct VISIBILITY_HIDDEN IVExpr {
89 SCEVHandle Stride;
90 SCEVHandle Base;
91 PHINode *PHI;
92 Value *IncV;
93
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
95 Value *incv)
96 : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
97 };
98
99 /// IVsOfOneStride - This structure keeps track of all IV expression inserted
100 /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
101 struct VISIBILITY_HIDDEN IVsOfOneStride {
102 std::vector<IVExpr> IVs;
103
104 void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
105 Value *IncV) {
106 IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
107 }
108 };
109
110 class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
111 LoopInfo *LI;
112 DominatorTree *DT;
113 ScalarEvolution *SE;
114 const TargetData *TD;
115 const Type *UIntPtrTy;
116 bool Changed;
117
118 /// IVUsesByStride - Keep track of all uses of induction variables that we
119 /// are interested in. The key of the map is the stride of the access.
120 std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
121
122 /// IVsByStride - Keep track of all IVs that have been inserted for a
123 /// particular stride.
124 std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
125
126 /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
127 /// We use this to iterate over the IVUsesByStride collection without being
128 /// dependent on random ordering of pointers in the process.
129 std::vector<SCEVHandle> StrideOrder;
130
131 /// CastedValues - As we need to cast values to uintptr_t, this keeps track
132 /// of the casted version of each value. This is accessed by
133 /// getCastedVersionOf.
134 std::map<Value*, Value*> CastedPointers;
135
136 /// DeadInsts - Keep track of instructions we may have made dead, so that
137 /// we can remove them after we are done working.
138 std::set<Instruction*> DeadInsts;
139
140 /// TLI - Keep a pointer of a TargetLowering to consult for determining
141 /// transformation profitability.
142 const TargetLowering *TLI;
143
144 public:
145 static char ID; // Pass ID, replacement for typeid
Dan Gohman34c280e2007-08-01 15:32:29 +0000146 explicit LoopStrengthReduce(const TargetLowering *tli = NULL) :
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 LoopPass((intptr_t)&ID), TLI(tli) {
148 }
149
150 bool runOnLoop(Loop *L, LPPassManager &LPM);
151
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153 // We split critical edges, so we change the CFG. However, we do update
154 // many analyses if they are around.
155 AU.addPreservedID(LoopSimplifyID);
156 AU.addPreserved<LoopInfo>();
157 AU.addPreserved<DominanceFrontier>();
158 AU.addPreserved<DominatorTree>();
159
160 AU.addRequiredID(LoopSimplifyID);
161 AU.addRequired<LoopInfo>();
162 AU.addRequired<DominatorTree>();
163 AU.addRequired<TargetData>();
164 AU.addRequired<ScalarEvolution>();
165 }
166
167 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
168 ///
169 Value *getCastedVersionOf(Instruction::CastOps opcode, Value *V);
170private:
171 bool AddUsersIfInteresting(Instruction *I, Loop *L,
172 std::set<Instruction*> &Processed);
173 SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
Evan Cheng335d87d2007-10-25 09:11:16 +0000174 ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
175 IVStrideUse* &CondUse,
176 const SCEVHandle* &CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 void OptimizeIndvars(Loop *L);
178 bool FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
179 const SCEVHandle *&CondStride);
Dan Gohman5766ac72007-10-22 20:40:42 +0000180 unsigned CheckForIVReuse(bool, const SCEVHandle&,
181 IVExpr&, const Type*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 const std::vector<BasedUser>& UsersToProcess);
Dan Gohman5766ac72007-10-22 20:40:42 +0000183 bool ValidStride(bool, int64_t,
184 const std::vector<BasedUser>& UsersToProcess);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 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) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
985 int64_t SInt = SC->getValue()->getSExtValue();
986 if (SInt == 1) return 0;
987
988 for (std::map<SCEVHandle, IVsOfOneStride>::iterator SI= IVsByStride.begin(),
989 SE = IVsByStride.end(); SI != SE; ++SI) {
990 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
991 if (SInt != -SSInt &&
992 (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
993 continue;
994 int64_t Scale = SInt / SSInt;
995 // Check that this stride is valid for all the types used for loads and
996 // stores; if it can be used for some and not others, we might as well use
997 // the original stride everywhere, since we have to create the IV for it
998 // anyway.
Dan Gohman5766ac72007-10-22 20:40:42 +0000999 if (ValidStride(HasBaseReg, Scale, UsersToProcess))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1001 IE = SI->second.IVs.end(); II != IE; ++II)
1002 // FIXME: Only handle base == 0 for now.
1003 // Only reuse previous IV if it would not require a type conversion.
1004 if (isZero(II->Base) && II->Base->getType() == Ty) {
1005 IV = *II;
1006 return Scale;
1007 }
1008 }
1009 }
1010 return 0;
1011}
1012
1013/// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1014/// returns true if Val's isUseOfPostIncrementedValue is true.
1015static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1016 return Val.isUseOfPostIncrementedValue;
1017}
1018
1019/// isNonConstantNegative - REturn true if the specified scev is negated, but
1020/// not a constant.
1021static bool isNonConstantNegative(const SCEVHandle &Expr) {
1022 SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1023 if (!Mul) return false;
1024
1025 // If there is a constant factor, it will be first.
1026 SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1027 if (!SC) return false;
1028
1029 // Return true if the value is negative, this matches things like (-42 * V).
1030 return SC->getValue()->getValue().isNegative();
1031}
1032
1033/// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1034/// stride of IV. All of the users may have different starting values, and this
1035/// may not be the only stride (we know it is if isOnlyStride is true).
1036void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1037 IVUsersOfOneStride &Uses,
1038 Loop *L,
1039 bool isOnlyStride) {
Evan Cheng335d87d2007-10-25 09:11:16 +00001040 // If all the users are moved to another stride, then there is nothing to do.
1041 if (Uses.Users.size() == 0)
1042 return;
1043
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 // Transform our list of users and offsets to a bit more complex table. In
1045 // this new vector, each 'BasedUser' contains 'Base' the base of the
1046 // strided accessas well as the old information from Uses. We progressively
1047 // move information from the Base field to the Imm field, until we eventually
1048 // have the full access expression to rewrite the use.
1049 std::vector<BasedUser> UsersToProcess;
1050 UsersToProcess.reserve(Uses.Users.size());
1051 for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +00001052 UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053
1054 // Move any loop invariant operands from the offset field to the immediate
1055 // field of the use, so that we don't try to use something before it is
1056 // computed.
1057 MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001058 UsersToProcess.back().Imm, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1060 "Base value is not loop invariant!");
1061 }
1062
1063 // We now have a whole bunch of uses of like-strided induction variables, but
1064 // they might all have different bases. We want to emit one PHI node for this
1065 // stride which we fold as many common expressions (between the IVs) into as
1066 // possible. Start by identifying the common expressions in the base values
1067 // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1068 // "A+B"), emit it to the preheader, then remove the expression from the
1069 // UsersToProcess base values.
1070 SCEVHandle CommonExprs =
Dan Gohman89f85052007-10-22 18:31:58 +00001071 RemoveCommonExpressionsFromUseBases(UsersToProcess, SE);
Dan Gohman5766ac72007-10-22 20:40:42 +00001072
1073 // If we managed to find some expressions in common, we'll need to carry
1074 // their value in a register and add it in for each use. This will take up
1075 // a register operand, which potentially restricts what stride values are
1076 // valid.
1077 bool HaveCommonExprs = !isZero(CommonExprs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078
Dan Gohman5766ac72007-10-22 20:40:42 +00001079 // Keep track if every use in UsersToProcess is an address. If they all are,
1080 // we may be able to rewrite the entire collection of them in terms of a
1081 // smaller-stride IV.
1082 bool AllUsesAreAddresses = true;
1083
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 // Next, figure out what we can represent in the immediate fields of
1085 // instructions. If we can represent anything there, move it to the imm
1086 // fields of the BasedUsers. We do this so that it increases the commonality
1087 // of the remaining uses.
1088 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1089 // If the user is not in the current loop, this means it is using the exit
1090 // value of the IV. Do not put anything in the base, make sure it's all in
1091 // the immediate field to allow as much factoring as possible.
1092 if (!L->contains(UsersToProcess[i].Inst->getParent())) {
Dan Gohman89f85052007-10-22 18:31:58 +00001093 UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1094 UsersToProcess[i].Base);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 UsersToProcess[i].Base =
Dan Gohman89f85052007-10-22 18:31:58 +00001096 SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 } else {
1098
1099 // Addressing modes can be folded into loads and stores. Be careful that
1100 // the store is through the expression, not of the expression though.
1101 bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
1102 if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst)) {
1103 if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1104 isAddress = true;
1105 } else if (IntrinsicInst *II =
1106 dyn_cast<IntrinsicInst>(UsersToProcess[i].Inst)) {
Dan Gohman5766ac72007-10-22 20:40:42 +00001107 // Addressing modes can also be folded into prefetches and a variety
1108 // of intrinsics.
1109 switch (II->getIntrinsicID()) {
1110 default: break;
1111 case Intrinsic::prefetch:
1112 case Intrinsic::x86_sse2_loadu_dq:
1113 case Intrinsic::x86_sse2_loadu_pd:
1114 case Intrinsic::x86_sse_loadu_ps:
1115 case Intrinsic::x86_sse_storeu_ps:
1116 case Intrinsic::x86_sse2_storeu_pd:
1117 case Intrinsic::x86_sse2_storeu_dq:
1118 case Intrinsic::x86_sse2_storel_dq:
1119 if (II->getOperand(1) == UsersToProcess[i].OperandValToReplace)
1120 isAddress = true;
1121 break;
1122 case Intrinsic::x86_sse2_loadh_pd:
1123 case Intrinsic::x86_sse2_loadl_pd:
1124 if (II->getOperand(2) == UsersToProcess[i].OperandValToReplace)
1125 isAddress = true;
1126 break;
1127 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 }
Dan Gohman5766ac72007-10-22 20:40:42 +00001129
1130 // If this use isn't an address, then not all uses are addresses.
1131 if (!isAddress)
1132 AllUsesAreAddresses = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133
1134 MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
Dan Gohman89f85052007-10-22 18:31:58 +00001135 UsersToProcess[i].Imm, isAddress, L, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136 }
1137 }
1138
Dan Gohman5766ac72007-10-22 20:40:42 +00001139 // If all uses are addresses, check if it is possible to reuse an IV with a
1140 // stride that is a factor of this stride. And that the multiple is a number
1141 // that can be encoded in the scale field of the target addressing mode. And
1142 // that we will have a valid instruction after this substition, including the
1143 // immediate field, if any.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 PHINode *NewPHI = NULL;
1145 Value *IncV = NULL;
Dan Gohman89f85052007-10-22 18:31:58 +00001146 IVExpr ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1147 SE->getIntegerSCEV(0, Type::Int32Ty),
1148 0, 0);
Dan Gohman5766ac72007-10-22 20:40:42 +00001149 unsigned RewriteFactor = 0;
1150 if (AllUsesAreAddresses)
1151 RewriteFactor = CheckForIVReuse(HaveCommonExprs, Stride, ReuseIV,
1152 CommonExprs->getType(),
1153 UsersToProcess);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 if (RewriteFactor != 0) {
1155 DOUT << "BASED ON IV of STRIDE " << *ReuseIV.Stride
1156 << " and BASE " << *ReuseIV.Base << " :\n";
1157 NewPHI = ReuseIV.PHI;
1158 IncV = ReuseIV.IncV;
1159 }
1160
1161 const Type *ReplacedTy = CommonExprs->getType();
1162
1163 // Now that we know what we need to do, insert the PHI node itself.
1164 //
1165 DOUT << "INSERTING IV of TYPE " << *ReplacedTy << " of STRIDE "
1166 << *Stride << " and BASE " << *CommonExprs << ": ";
1167
1168 SCEVExpander Rewriter(*SE, *LI);
1169 SCEVExpander PreheaderRewriter(*SE, *LI);
1170
1171 BasicBlock *Preheader = L->getLoopPreheader();
1172 Instruction *PreInsertPt = Preheader->getTerminator();
1173 Instruction *PhiInsertBefore = L->getHeader()->begin();
1174
1175 BasicBlock *LatchBlock = L->getLoopLatch();
1176
1177
1178 // Emit the initial base value into the loop preheader.
1179 Value *CommonBaseV
1180 = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt);
1181
1182 if (RewriteFactor == 0) {
1183 // Create a new Phi for this base, and stick it in the loop header.
1184 NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1185 ++NumInserted;
1186
1187 // Add common base to the new Phi node.
1188 NewPHI->addIncoming(CommonBaseV, Preheader);
1189
1190 // If the stride is negative, insert a sub instead of an add for the
1191 // increment.
1192 bool isNegative = isNonConstantNegative(Stride);
1193 SCEVHandle IncAmount = Stride;
1194 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001195 IncAmount = SE->getNegativeSCEV(Stride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196
1197 // Insert the stride into the preheader.
1198 Value *StrideV = PreheaderRewriter.expandCodeFor(IncAmount, PreInsertPt);
1199 if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1200
1201 // Emit the increment of the base value before the terminator of the loop
1202 // latch block, and add it to the Phi node.
Dan Gohman89f85052007-10-22 18:31:58 +00001203 SCEVHandle IncExp = SE->getUnknown(StrideV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 if (isNegative)
Dan Gohman89f85052007-10-22 18:31:58 +00001205 IncExp = SE->getNegativeSCEV(IncExp);
1206 IncExp = SE->getAddExpr(SE->getUnknown(NewPHI), IncExp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001207
1208 IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator());
1209 IncV->setName(NewPHI->getName()+".inc");
1210 NewPHI->addIncoming(IncV, LatchBlock);
1211
1212 // Remember this in case a later stride is multiple of this.
1213 IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1214
1215 DOUT << " IV=%" << NewPHI->getNameStr() << " INC=%" << IncV->getNameStr();
1216 } else {
1217 Constant *C = dyn_cast<Constant>(CommonBaseV);
1218 if (!C ||
1219 (!C->isNullValue() &&
Dan Gohman89f85052007-10-22 18:31:58 +00001220 !isTargetConstant(SE->getUnknown(CommonBaseV), ReplacedTy, TLI)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221 // We want the common base emitted into the preheader! This is just
1222 // using cast as a copy so BitCast (no-op cast) is appropriate
1223 CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1224 "commonbase", PreInsertPt);
1225 }
1226 DOUT << "\n";
1227
1228 // We want to emit code for users inside the loop first. To do this, we
1229 // rearrange BasedUser so that the entries at the end have
1230 // isUseOfPostIncrementedValue = false, because we pop off the end of the
1231 // vector (so we handle them first).
1232 std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1233 PartitionByIsUseOfPostIncrementedValue);
1234
1235 // Sort this by base, so that things with the same base are handled
1236 // together. By partitioning first and stable-sorting later, we are
1237 // guaranteed that within each base we will pop off users from within the
1238 // loop before users outside of the loop with a particular base.
1239 //
1240 // We would like to use stable_sort here, but we can't. The problem is that
1241 // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1242 // we don't have anything to do a '<' comparison on. Because we think the
1243 // number of uses is small, do a horrible bubble sort which just relies on
1244 // ==.
1245 for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1246 // Get a base value.
1247 SCEVHandle Base = UsersToProcess[i].Base;
1248
1249 // Compact everything with this base to be consequetive with this one.
1250 for (unsigned j = i+1; j != e; ++j) {
1251 if (UsersToProcess[j].Base == Base) {
1252 std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1253 ++i;
1254 }
1255 }
1256 }
1257
1258 // Process all the users now. This outer loop handles all bases, the inner
1259 // loop handles all users of a particular base.
1260 while (!UsersToProcess.empty()) {
1261 SCEVHandle Base = UsersToProcess.back().Base;
1262
1263 // Emit the code for Base into the preheader.
1264 Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt);
1265
1266 DOUT << " INSERTING code for BASE = " << *Base << ":";
1267 if (BaseV->hasName())
1268 DOUT << " Result value name = %" << BaseV->getNameStr();
1269 DOUT << "\n";
1270
1271 // If BaseV is a constant other than 0, make sure that it gets inserted into
1272 // the preheader, instead of being forward substituted into the uses. We do
1273 // this by forcing a BitCast (noop cast) to be inserted into the preheader
1274 // in this case.
1275 if (Constant *C = dyn_cast<Constant>(BaseV)) {
1276 if (!C->isNullValue() && !isTargetConstant(Base, ReplacedTy, TLI)) {
1277 // We want this constant emitted into the preheader! This is just
1278 // using cast as a copy so BitCast (no-op cast) is appropriate
1279 BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1280 PreInsertPt);
1281 }
1282 }
1283
1284 // Emit the code to add the immediate offset to the Phi value, just before
1285 // the instructions that we identified as using this stride and base.
1286 do {
1287 // FIXME: Use emitted users to emit other users.
1288 BasedUser &User = UsersToProcess.back();
1289
1290 // If this instruction wants to use the post-incremented value, move it
1291 // after the post-inc and use its value instead of the PHI.
1292 Value *RewriteOp = NewPHI;
1293 if (User.isUseOfPostIncrementedValue) {
1294 RewriteOp = IncV;
1295
1296 // If this user is in the loop, make sure it is the last thing in the
1297 // loop to ensure it is dominated by the increment.
1298 if (L->contains(User.Inst->getParent()))
1299 User.Inst->moveBefore(LatchBlock->getTerminator());
1300 }
1301 if (RewriteOp->getType() != ReplacedTy) {
1302 Instruction::CastOps opcode = Instruction::Trunc;
1303 if (ReplacedTy->getPrimitiveSizeInBits() ==
1304 RewriteOp->getType()->getPrimitiveSizeInBits())
1305 opcode = Instruction::BitCast;
1306 RewriteOp = SCEVExpander::InsertCastOfTo(opcode, RewriteOp, ReplacedTy);
1307 }
1308
Dan Gohman89f85052007-10-22 18:31:58 +00001309 SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310
1311 // Clear the SCEVExpander's expression map so that we are guaranteed
1312 // to have the code emitted where we expect it.
1313 Rewriter.clear();
1314
1315 // If we are reusing the iv, then it must be multiplied by a constant
1316 // factor take advantage of addressing mode scale component.
1317 if (RewriteFactor != 0) {
1318 RewriteExpr =
Dan Gohman89f85052007-10-22 18:31:58 +00001319 SE->getMulExpr(SE->getIntegerSCEV(RewriteFactor,
1320 RewriteExpr->getType()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 RewriteExpr);
1322
1323 // The common base is emitted in the loop preheader. But since we
1324 // are reusing an IV, it has not been used to initialize the PHI node.
1325 // Add it to the expression used to rewrite the uses.
1326 if (!isa<ConstantInt>(CommonBaseV) ||
1327 !cast<ConstantInt>(CommonBaseV)->isZero())
Dan Gohman89f85052007-10-22 18:31:58 +00001328 RewriteExpr = SE->getAddExpr(RewriteExpr,
1329 SE->getUnknown(CommonBaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 }
1331
1332 // Now that we know what we need to do, insert code before User for the
1333 // immediate and any loop-variant expressions.
1334 if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isZero())
1335 // Add BaseV to the PHI value if needed.
Dan Gohman89f85052007-10-22 18:31:58 +00001336 RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337
1338 User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1339
1340 // Mark old value we replaced as possibly dead, so that it is elminated
1341 // if we just replaced the last use of that value.
1342 DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1343
1344 UsersToProcess.pop_back();
1345 ++NumReduced;
1346
1347 // If there are any more users to process with the same base, process them
1348 // now. We sorted by base above, so we just have to check the last elt.
1349 } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1350 // TODO: Next, find out which base index is the most common, pull it out.
1351 }
1352
1353 // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1354 // different starting values, into different PHIs.
1355}
1356
1357/// FindIVForUser - If Cond has an operand that is an expression of an IV,
1358/// set the IV user and stride information and return true, otherwise return
1359/// false.
1360bool LoopStrengthReduce::FindIVForUser(ICmpInst *Cond, IVStrideUse *&CondUse,
1361 const SCEVHandle *&CondStride) {
1362 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1363 ++Stride) {
1364 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1365 IVUsesByStride.find(StrideOrder[Stride]);
1366 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1367
1368 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1369 E = SI->second.Users.end(); UI != E; ++UI)
1370 if (UI->User == Cond) {
1371 // NOTE: we could handle setcc instructions with multiple uses here, but
1372 // InstCombine does it as well for simple uses, it's not clear that it
1373 // occurs enough in real life to handle.
1374 CondUse = &*UI;
1375 CondStride = &SI->first;
1376 return true;
1377 }
1378 }
1379 return false;
1380}
1381
Evan Cheng335d87d2007-10-25 09:11:16 +00001382namespace {
1383 // Constant strides come first which in turns are sorted by their absolute
1384 // values. If absolute values are the same, then positive strides comes first.
1385 // e.g.
1386 // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1387 struct StrideCompare {
1388 bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1389 SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1390 SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1391 if (LHSC && RHSC) {
1392 int64_t LV = LHSC->getValue()->getSExtValue();
1393 int64_t RV = RHSC->getValue()->getSExtValue();
1394 uint64_t ALV = (LV < 0) ? -LV : LV;
1395 uint64_t ARV = (RV < 0) ? -RV : RV;
1396 if (ALV == ARV)
1397 return LV > RV;
1398 else
1399 return ALV < ARV;
1400 }
1401 return (LHSC && !RHSC);
1402 }
1403 };
1404}
1405
1406/// ChangeCompareStride - If a loop termination compare instruction is the
1407/// only use of its stride, and the compaison is against a constant value,
1408/// try eliminate the stride by moving the compare instruction to another
1409/// stride and change its constant operand accordingly. e.g.
1410///
1411/// loop:
1412/// ...
1413/// v1 = v1 + 3
1414/// v2 = v2 + 1
1415/// if (v2 < 10) goto loop
1416/// =>
1417/// loop:
1418/// ...
1419/// v1 = v1 + 3
1420/// if (v1 < 30) goto loop
1421ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1422 IVStrideUse* &CondUse,
1423 const SCEVHandle* &CondStride) {
1424 if (StrideOrder.size() < 2 ||
1425 IVUsesByStride[*CondStride].Users.size() != 1)
1426 return Cond;
1427 // FIXME: loosen this restriction?
1428 if (!isa<SCEVConstant>(CondUse->Offset))
1429 return Cond;
1430 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1431 if (!SC) return Cond;
1432 ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1));
1433 if (!C) return Cond;
1434
1435 ICmpInst::Predicate Predicate = Cond->getPredicate();
1436 bool isSigned = ICmpInst::isSignedPredicate(Predicate);
1437 int64_t CmpSSInt = SC->getValue()->getSExtValue();
1438 int64_t CmpVal = C->getValue().getSExtValue();
1439 uint64_t SignBit = 1ULL << (C->getValue().getBitWidth()-1);
1440 int64_t NewCmpVal = CmpVal;
1441 SCEVHandle *NewStride = NULL;
1442 Value *NewIncV = NULL;
1443 int64_t Scale = 1;
1444 const Type *CmpTy = C->getType();
1445 const Type *NewCmpTy = NULL;
1446
1447 // Look for a suitable stride / iv as replacement.
1448 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1449 for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
1450 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1451 IVUsesByStride.find(StrideOrder[i]);
1452 if (!isa<SCEVConstant>(SI->first))
1453 continue;
1454 int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1455 if (abs(SSInt) < abs(CmpSSInt) && (CmpSSInt % SSInt) == 0) {
1456 Scale = CmpSSInt / SSInt;
1457 NewCmpVal = CmpVal / Scale;
1458 } else if (abs(SSInt) > abs(CmpSSInt) && (SSInt % CmpSSInt) == 0) {
1459 Scale = SSInt / CmpSSInt;
1460 NewCmpVal = CmpVal * Scale;
1461 } else
1462 continue;
1463
1464 // Watch out for overflow.
1465 if (isSigned && (CmpVal & SignBit) != (NewCmpVal & SignBit))
1466 NewCmpVal = CmpVal;
1467 if (NewCmpVal != CmpVal) {
1468 // Pick the best iv to use trying to avoid a cast.
1469 NewIncV = NULL;
1470 for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1471 E = SI->second.Users.end(); UI != E; ++UI) {
Evan Cheng335d87d2007-10-25 09:11:16 +00001472 NewIncV = UI->OperandValToReplace;
1473 if (NewIncV->getType() == CmpTy)
1474 break;
1475 }
1476 if (!NewIncV) {
1477 NewCmpVal = CmpVal;
1478 continue;
1479 }
1480
1481 // FIXME: allow reuse of iv of a smaller type?
1482 NewCmpTy = NewIncV->getType();
1483 if (!CmpTy->canLosslesslyBitCastTo(NewCmpTy) &&
1484 !(isa<PointerType>(NewCmpTy) &&
1485 CmpTy->canLosslesslyBitCastTo(UIntPtrTy))) {
1486 NewCmpVal = CmpVal;
1487 continue;
1488 }
1489
1490 // If scale is negative, use inverse predicate unless it's testing
1491 // for equality.
1492 if (Scale < 0 && !Cond->isEquality())
1493 Predicate = ICmpInst::getInversePredicate(Predicate);
1494
1495 NewStride = &StrideOrder[i];
1496 break;
1497 }
1498 }
1499
1500 if (NewCmpVal != CmpVal) {
1501 // Create a new compare instruction using new stride / iv.
1502 ICmpInst *OldCond = Cond;
1503 Value *RHS = ConstantInt::get(C->getType(), NewCmpVal);
1504 // Both sides of a ICmpInst must be of the same type.
1505 if (NewCmpTy != CmpTy) {
1506 if (isa<PointerType>(NewCmpTy) && !isa<PointerType>(CmpTy))
1507 RHS= SCEVExpander::InsertCastOfTo(Instruction::IntToPtr, RHS, NewCmpTy);
1508 else
1509 RHS = SCEVExpander::InsertCastOfTo(Instruction::BitCast, RHS, NewCmpTy);
1510 }
1511 Cond = new ICmpInst(Predicate, NewIncV, RHS);
1512 Cond->setName(L->getHeader()->getName() + ".termcond");
1513 OldCond->getParent()->getInstList().insert(OldCond, Cond);
1514 OldCond->replaceAllUsesWith(Cond);
1515 OldCond->eraseFromParent();
1516 IVUsesByStride[*CondStride].Users.pop_back();
1517 SCEVHandle NewOffset = SE->getMulExpr(CondUse->Offset,
1518 SE->getConstant(ConstantInt::get(CondUse->Offset->getType(), Scale)));
1519 IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewIncV);
1520 CondUse = &IVUsesByStride[*NewStride].Users.back();
1521 CondStride = NewStride;
1522 ++NumEliminated;
1523 }
1524
1525 return Cond;
1526}
1527
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528// OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1529// uses in the loop, look to see if we can eliminate some, in favor of using
1530// common indvars for the different uses.
1531void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1532 // TODO: implement optzns here.
1533
1534 // Finally, get the terminating condition for the loop if possible. If we
1535 // can, we want to change it to use a post-incremented version of its
1536 // induction variable, to allow coalescing the live ranges for the IV into
1537 // one register value.
1538 PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1539 BasicBlock *Preheader = L->getLoopPreheader();
1540 BasicBlock *LatchBlock =
1541 SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1542 BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1543 if (!TermBr || TermBr->isUnconditional() ||
1544 !isa<ICmpInst>(TermBr->getCondition()))
1545 return;
1546 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1547
1548 // Search IVUsesByStride to find Cond's IVUse if there is one.
1549 IVStrideUse *CondUse = 0;
1550 const SCEVHandle *CondStride = 0;
1551
1552 if (!FindIVForUser(Cond, CondUse, CondStride))
1553 return; // setcc doesn't use the IV.
Evan Cheng335d87d2007-10-25 09:11:16 +00001554
1555 // If possible, change stride and operands of the compare instruction to
1556 // eliminate one stride.
1557 Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558
1559 // It's possible for the setcc instruction to be anywhere in the loop, and
1560 // possible for it to have multiple users. If it is not immediately before
1561 // the latch block branch, move it.
1562 if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1563 if (Cond->hasOneUse()) { // Condition has a single use, just move it.
1564 Cond->moveBefore(TermBr);
1565 } else {
1566 // Otherwise, clone the terminating condition and insert into the loopend.
1567 Cond = cast<ICmpInst>(Cond->clone());
1568 Cond->setName(L->getHeader()->getName() + ".termcond");
1569 LatchBlock->getInstList().insert(TermBr, Cond);
1570
1571 // Clone the IVUse, as the old use still exists!
1572 IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1573 CondUse->OperandValToReplace);
1574 CondUse = &IVUsesByStride[*CondStride].Users.back();
1575 }
1576 }
1577
1578 // If we get to here, we know that we can transform the setcc instruction to
1579 // use the post-incremented version of the IV, allowing us to coalesce the
1580 // live ranges for the IV correctly.
Dan Gohman89f85052007-10-22 18:31:58 +00001581 CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001582 CondUse->isUseOfPostIncrementedValue = true;
1583}
1584
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
1586
1587 LI = &getAnalysis<LoopInfo>();
1588 DT = &getAnalysis<DominatorTree>();
1589 SE = &getAnalysis<ScalarEvolution>();
1590 TD = &getAnalysis<TargetData>();
1591 UIntPtrTy = TD->getIntPtrType();
1592
1593 // Find all uses of induction variables in this loop, and catagorize
1594 // them by stride. Start by finding all of the PHI nodes in the header for
1595 // this loop. If they are induction variables, inspect their uses.
1596 std::set<Instruction*> Processed; // Don't reprocess instructions.
1597 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1598 AddUsersIfInteresting(I, L, Processed);
1599
1600 // If we have nothing to do, return.
1601 if (IVUsesByStride.empty()) return false;
1602
1603 // Optimize induction variables. Some indvar uses can be transformed to use
1604 // strides that will be needed for other purposes. A common example of this
1605 // is the exit test for the loop, which can often be rewritten to use the
1606 // computation of some other indvar to decide when to terminate the loop.
1607 OptimizeIndvars(L);
1608
1609
1610 // FIXME: We can widen subreg IV's here for RISC targets. e.g. instead of
1611 // doing computation in byte values, promote to 32-bit values if safe.
1612
1613 // FIXME: Attempt to reuse values across multiple IV's. In particular, we
1614 // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1615 // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC. Need
1616 // to be careful that IV's are all the same type. Only works for intptr_t
1617 // indvars.
1618
1619 // If we only have one stride, we can more aggressively eliminate some things.
1620 bool HasOneStride = IVUsesByStride.size() == 1;
1621
1622#ifndef NDEBUG
1623 DOUT << "\nLSR on ";
1624 DEBUG(L->dump());
1625#endif
1626
1627 // IVsByStride keeps IVs for one particular loop.
1628 IVsByStride.clear();
1629
1630 // Sort the StrideOrder so we process larger strides first.
1631 std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1632
1633 // Note: this processes each stride/type pair individually. All users passed
1634 // into StrengthReduceStridedIVUsers have the same type AND stride. Also,
1635 // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1636 // This extra layer of indirection makes the ordering of strides deterministic
1637 // - not dependent on map order.
1638 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1639 std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI =
1640 IVUsesByStride.find(StrideOrder[Stride]);
1641 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1642 StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1643 }
1644
1645 // Clean up after ourselves
1646 if (!DeadInsts.empty()) {
1647 DeleteTriviallyDeadInstructions(DeadInsts);
1648
1649 BasicBlock::iterator I = L->getHeader()->begin();
1650 PHINode *PN;
1651 while ((PN = dyn_cast<PHINode>(I))) {
1652 ++I; // Preincrement iterator to avoid invalidating it when deleting PN.
1653
1654 // At this point, we know that we have killed one or more GEP
1655 // instructions. It is worth checking to see if the cann indvar is also
1656 // dead, so that we can remove it as well. The requirements for the cann
1657 // indvar to be considered dead are:
1658 // 1. the cann indvar has one use
1659 // 2. the use is an add instruction
1660 // 3. the add has one use
1661 // 4. the add is used by the cann indvar
1662 // If all four cases above are true, then we can remove both the add and
1663 // the cann indvar.
1664 // FIXME: this needs to eliminate an induction variable even if it's being
1665 // compared against some value to decide loop termination.
1666 if (PN->hasOneUse()) {
1667 Instruction *BO = dyn_cast<Instruction>(*PN->use_begin());
1668 if (BO && (isa<BinaryOperator>(BO) || isa<CmpInst>(BO))) {
1669 if (BO->hasOneUse() && PN == *(BO->use_begin())) {
1670 DeadInsts.insert(BO);
1671 // Break the cycle, then delete the PHI.
1672 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1673 SE->deleteValueFromRecords(PN);
1674 PN->eraseFromParent();
1675 }
1676 }
1677 }
1678 }
1679 DeleteTriviallyDeadInstructions(DeadInsts);
1680 }
1681
1682 CastedPointers.clear();
1683 IVUsesByStride.clear();
1684 StrideOrder.clear();
1685 return false;
1686}