Add a const qualifier.
[oota-llvm.git] / lib / Analysis / IVUsers.cpp
1 //===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements bookkeeping for "interesting" users of expressions
11 // computed from induction variables.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "iv-users"
16 #include "llvm/Analysis/IVUsers.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Type.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/Assembly/AsmAnnotationWriter.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 using namespace llvm;
30
31 char IVUsers::ID = 0;
32 static RegisterPass<IVUsers>
33 X("iv-users", "Induction Variable Users", false, true);
34
35 Pass *llvm::createIVUsersPass() {
36   return new IVUsers();
37 }
38
39 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
40 /// separate registers.
41 static void CollectSubexprs(const SCEV *S,
42                             SmallVectorImpl<const SCEV *> &Ops,
43                             ScalarEvolution &SE) {
44   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
45     // Break out add operands.
46     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
47          I != E; ++I)
48       CollectSubexprs(*I, Ops, SE);
49     return;
50   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
51     // Split a non-zero base out of an addrec.
52     if (!AR->getStart()->isZero()) {
53       CollectSubexprs(AR->getStart(), Ops, SE);
54       CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
55                                        AR->getStepRecurrence(SE),
56                                        AR->getLoop()), Ops, SE);
57       return;
58     }
59   }
60
61   // Otherwise use the value itself.
62   Ops.push_back(S);
63 }
64
65 /// getSCEVStartAndStride - Compute the start and stride of this expression,
66 /// returning false if the expression is not a start/stride pair, or true if it
67 /// is.  The stride must be a loop invariant expression, but the start may be
68 /// a mix of loop invariant and loop variant expressions.  The start cannot,
69 /// however, contain an AddRec from a different loop, unless that loop is an
70 /// outer loop of the current loop.
71 static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop,
72                                   const SCEV *&Start, const SCEV *&Stride,
73                                   ScalarEvolution *SE, DominatorTree *DT) {
74   const SCEV *TheAddRec = Start;   // Initialize to zero.
75
76   // If the outer level is an AddExpr, the operands are all start values except
77   // for a nested AddRecExpr.
78   if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
79     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
80       if (const SCEVAddRecExpr *AddRec =
81              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i)))
82         TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
83       else
84         Start = SE->getAddExpr(Start, AE->getOperand(i));
85   } else if (isa<SCEVAddRecExpr>(SH)) {
86     TheAddRec = SH;
87   } else {
88     return false;  // not analyzable.
89   }
90
91   // Break down TheAddRec into its component parts.
92   SmallVector<const SCEV *, 4> Subexprs;
93   CollectSubexprs(TheAddRec, Subexprs, *SE);
94
95   // Look for an addrec on the current loop among the parts.
96   const SCEV *AddRecStride = 0;
97   for (SmallVectorImpl<const SCEV *>::iterator I = Subexprs.begin(),
98        E = Subexprs.end(); I != E; ++I) {
99     const SCEV *S = *I;
100     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
101       if (AR->getLoop() == L) {
102         *I = AR->getStart();
103         AddRecStride = AR->getStepRecurrence(*SE);
104         break;
105       }
106   }
107   if (!AddRecStride)
108     return false;
109
110   // Add up everything else into a start value (which may not be
111   // loop-invariant).
112   const SCEV *AddRecStart = SE->getAddExpr(Subexprs);
113
114   // Use getSCEVAtScope to attempt to simplify other loops out of
115   // the picture.
116   AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
117
118   Start = SE->getAddExpr(Start, AddRecStart);
119
120   // If stride is an instruction, make sure it properly dominates the header.
121   // Otherwise we could end up with a use before def situation.
122   if (!isa<SCEVConstant>(AddRecStride)) {
123     BasicBlock *Header = L->getHeader();
124     if (!AddRecStride->properlyDominates(Header, DT))
125       return false;
126
127     DEBUG(dbgs() << "[";
128           WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
129           dbgs() << "] Variable stride: " << *AddRecStride << "\n");
130   }
131
132   Stride = AddRecStride;
133   return true;
134 }
135
136 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
137 /// and now we need to decide whether the user should use the preinc or post-inc
138 /// value.  If this user should use the post-inc version of the IV, return true.
139 ///
140 /// Choosing wrong here can break dominance properties (if we choose to use the
141 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
142 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
143 /// should use the post-inc value).
144 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
145                                        const Loop *L, DominatorTree *DT) {
146   // If the user is in the loop, use the preinc value.
147   if (L->contains(User)) return false;
148
149   BasicBlock *LatchBlock = L->getLoopLatch();
150   if (!LatchBlock)
151     return false;
152
153   // Ok, the user is outside of the loop.  If it is dominated by the latch
154   // block, use the post-inc value.
155   if (DT->dominates(LatchBlock, User->getParent()))
156     return true;
157
158   // There is one case we have to be careful of: PHI nodes.  These little guys
159   // can live in blocks that are not dominated by the latch block, but (since
160   // their uses occur in the predecessor block, not the block the PHI lives in)
161   // should still use the post-inc value.  Check for this case now.
162   PHINode *PN = dyn_cast<PHINode>(User);
163   if (!PN) return false;  // not a phi, not dominated by latch block.
164
165   // Look at all of the uses of IV by the PHI node.  If any use corresponds to
166   // a block that is not dominated by the latch block, give up and use the
167   // preincremented value.
168   unsigned NumUses = 0;
169   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
170     if (PN->getIncomingValue(i) == IV) {
171       ++NumUses;
172       if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
173         return false;
174     }
175
176   // Okay, all uses of IV by PN are in predecessor blocks that really are
177   // dominated by the latch block.  Use the post-incremented value.
178   return true;
179 }
180
181 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
182 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
183 /// return true.  Otherwise, return false.
184 bool IVUsers::AddUsersIfInteresting(Instruction *I) {
185   if (!SE->isSCEVable(I->getType()))
186     return false;   // Void and FP expressions cannot be reduced.
187
188   // LSR is not APInt clean, do not touch integers bigger than 64-bits.
189   if (SE->getTypeSizeInBits(I->getType()) > 64)
190     return false;
191
192   if (!Processed.insert(I))
193     return true;    // Instruction already handled.
194
195   // Get the symbolic expression for this instruction.
196   const SCEV *ISE = SE->getSCEV(I);
197   if (isa<SCEVCouldNotCompute>(ISE)) return false;
198
199   // Get the start and stride for this expression.
200   Loop *UseLoop = LI->getLoopFor(I->getParent());
201   const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType());
202   const SCEV *Stride = Start;
203
204   if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT))
205     return false;  // Non-reducible symbolic expression, bail out.
206
207   // Keep things simple. Don't touch loop-variant strides.
208   if (!Stride->isLoopInvariant(L) && L->contains(I))
209     return false;
210
211   SmallPtrSet<Instruction *, 4> UniqueUsers;
212   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
213        UI != E; ++UI) {
214     Instruction *User = cast<Instruction>(*UI);
215     if (!UniqueUsers.insert(User))
216       continue;
217
218     // Do not infinitely recurse on PHI nodes.
219     if (isa<PHINode>(User) && Processed.count(User))
220       continue;
221
222     // Descend recursively, but not into PHI nodes outside the current loop.
223     // It's important to see the entire expression outside the loop to get
224     // choices that depend on addressing mode use right, although we won't
225     // consider references outside the loop in all cases.
226     // If User is already in Processed, we don't want to recurse into it again,
227     // but do want to record a second reference in the same instruction.
228     bool AddUserToIVUsers = false;
229     if (LI->getLoopFor(User->getParent()) != L) {
230       if (isa<PHINode>(User) || Processed.count(User) ||
231           !AddUsersIfInteresting(User)) {
232         DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
233                      << "   OF SCEV: " << *ISE << '\n');
234         AddUserToIVUsers = true;
235       }
236     } else if (Processed.count(User) ||
237                !AddUsersIfInteresting(User)) {
238       DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
239                    << "   OF SCEV: " << *ISE << '\n');
240       AddUserToIVUsers = true;
241     }
242
243     if (AddUserToIVUsers) {
244       // Okay, we found a user that we cannot reduce.  Analyze the instruction
245       // and decide what to do with it.  If we are a use inside of the loop, use
246       // the value before incrementation, otherwise use it after incrementation.
247       if (IVUseShouldUsePostIncValue(User, I, L, DT)) {
248         // The value used will be incremented by the stride more than we are
249         // expecting, so subtract this off.
250         const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
251         IVUses.push_back(new IVStrideUse(this, Stride, NewStart, User, I));
252         IVUses.back().setIsUseOfPostIncrementedValue(true);
253         DEBUG(dbgs() << "   USING POSTINC SCEV, START=" << *NewStart<< "\n");
254       } else {
255         IVUses.push_back(new IVStrideUse(this, Stride, Start, User, I));
256       }
257     }
258   }
259   return true;
260 }
261
262 IVStrideUse &IVUsers::AddUser(const SCEV *Stride, const SCEV *Offset,
263                               Instruction *User, Value *Operand) {
264   IVUses.push_back(new IVStrideUse(this, Stride, Offset, User, Operand));
265   return IVUses.back();
266 }
267
268 IVUsers::IVUsers()
269  : LoopPass(&ID) {
270 }
271
272 void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
273   AU.addRequired<LoopInfo>();
274   AU.addRequired<DominatorTree>();
275   AU.addRequired<ScalarEvolution>();
276   AU.setPreservesAll();
277 }
278
279 bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
280
281   L = l;
282   LI = &getAnalysis<LoopInfo>();
283   DT = &getAnalysis<DominatorTree>();
284   SE = &getAnalysis<ScalarEvolution>();
285
286   // Find all uses of induction variables in this loop, and categorize
287   // them by stride.  Start by finding all of the PHI nodes in the header for
288   // this loop.  If they are induction variables, inspect their uses.
289   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
290     AddUsersIfInteresting(I);
291
292   return false;
293 }
294
295 /// getReplacementExpr - Return a SCEV expression which computes the
296 /// value of the OperandValToReplace of the given IVStrideUse.
297 const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {
298   // Start with zero.
299   const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
300   // Create the basic add recurrence.
301   RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
302   // Add the offset in a separate step, because it may be loop-variant.
303   RetVal = SE->getAddExpr(RetVal, U.getOffset());
304   // For uses of post-incremented values, add an extra stride to compute
305   // the actual replacement value.
306   if (U.isUseOfPostIncrementedValue())
307     RetVal = SE->getAddExpr(RetVal, U.getStride());
308   return RetVal;
309 }
310
311 /// getCanonicalExpr - Return a SCEV expression which computes the
312 /// value of the SCEV of the given IVStrideUse, ignoring the 
313 /// isUseOfPostIncrementedValue flag.
314 const SCEV *IVUsers::getCanonicalExpr(const IVStrideUse &U) const {
315   // Start with zero.
316   const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
317   // Create the basic add recurrence.
318   RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
319   // Add the offset in a separate step, because it may be loop-variant.
320   RetVal = SE->getAddExpr(RetVal, U.getOffset());
321   return RetVal;
322 }
323
324 void IVUsers::print(raw_ostream &OS, const Module *M) const {
325   OS << "IV Users for loop ";
326   WriteAsOperand(OS, L->getHeader(), false);
327   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
328     OS << " with backedge-taken count "
329        << *SE->getBackedgeTakenCount(L);
330   }
331   OS << ":\n";
332
333   // Use a default AssemblyAnnotationWriter to suppress the default info
334   // comments, which aren't relevant here.
335   AssemblyAnnotationWriter Annotator;
336   for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(),
337        E = IVUses.end(); UI != E; ++UI) {
338     OS << "  ";
339     WriteAsOperand(OS, UI->getOperandValToReplace(), false);
340     OS << " = "
341        << *getReplacementExpr(*UI);
342     if (UI->isUseOfPostIncrementedValue())
343       OS << " (post-inc)";
344     OS << " in  ";
345     UI->getUser()->print(OS, &Annotator);
346     OS << '\n';
347   }
348 }
349
350 void IVUsers::dump() const {
351   print(dbgs());
352 }
353
354 void IVUsers::releaseMemory() {
355   Processed.clear();
356   IVUses.clear();
357 }
358
359 void IVStrideUse::deleted() {
360   // Remove this user from the list.
361   Parent->IVUses.erase(this);
362   // this now dangles!
363 }