IVUsers.cpp revision 193323
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/LoopInfo.h"
23#include "llvm/Analysis/LoopPass.h"
24#include "llvm/Analysis/ScalarEvolutionExpressions.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
28#include <algorithm>
29using namespace llvm;
30
31char IVUsers::ID = 0;
32static RegisterPass<IVUsers>
33X("iv-users", "Induction Variable Users", false, true);
34
35Pass *llvm::createIVUsersPass() {
36  return new IVUsers();
37}
38
39/// containsAddRecFromDifferentLoop - Determine whether expression S involves a
40/// subexpression that is an AddRec from a loop other than L.  An outer loop
41/// of L is OK, but not an inner loop nor a disjoint loop.
42static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
43  // This is very common, put it first.
44  if (isa<SCEVConstant>(S))
45    return false;
46  if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
47    for (unsigned int i=0; i< AE->getNumOperands(); i++)
48      if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
49        return true;
50    return false;
51  }
52  if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
53    if (const Loop *newLoop = AE->getLoop()) {
54      if (newLoop == L)
55        return false;
56      // if newLoop is an outer loop of L, this is OK.
57      if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
58        return false;
59    }
60    return true;
61  }
62  if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
63    return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
64           containsAddRecFromDifferentLoop(DE->getRHS(), L);
65#if 0
66  // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
67  // need this when it is.
68  if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
69    return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
70           containsAddRecFromDifferentLoop(DE->getRHS(), L);
71#endif
72  if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
73    return containsAddRecFromDifferentLoop(CE->getOperand(), L);
74  return false;
75}
76
77/// getSCEVStartAndStride - Compute the start and stride of this expression,
78/// returning false if the expression is not a start/stride pair, or true if it
79/// is.  The stride must be a loop invariant expression, but the start may be
80/// a mix of loop invariant and loop variant expressions.  The start cannot,
81/// however, contain an AddRec from a different loop, unless that loop is an
82/// outer loop of the current loop.
83static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L, Loop *UseLoop,
84                                  SCEVHandle &Start, SCEVHandle &Stride,
85                                  bool &isSigned,
86                                  ScalarEvolution *SE, DominatorTree *DT) {
87  SCEVHandle TheAddRec = Start;   // Initialize to zero.
88  bool isSExt = false;
89  bool isZExt = false;
90
91  // If the outer level is an AddExpr, the operands are all start values except
92  // for a nested AddRecExpr.
93  if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
94    for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
95      if (const SCEVAddRecExpr *AddRec =
96             dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
97        if (AddRec->getLoop() == L)
98          TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
99        else
100          return false;  // Nested IV of some sort?
101      } else {
102        Start = SE->getAddExpr(Start, AE->getOperand(i));
103      }
104
105  } else if (const SCEVZeroExtendExpr *Z = dyn_cast<SCEVZeroExtendExpr>(SH)) {
106    TheAddRec = Z->getOperand();
107    isZExt = true;
108  } else if (const SCEVSignExtendExpr *S = dyn_cast<SCEVSignExtendExpr>(SH)) {
109    TheAddRec = S->getOperand();
110    isSExt = true;
111  } else if (isa<SCEVAddRecExpr>(SH)) {
112    TheAddRec = SH;
113  } else {
114    return false;  // not analyzable.
115  }
116
117  const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
118  if (!AddRec || AddRec->getLoop() != L) return false;
119
120  // Use getSCEVAtScope to attempt to simplify other loops out of
121  // the picture.
122  SCEVHandle AddRecStart = AddRec->getStart();
123  SCEVHandle BetterAddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
124  if (!isa<SCEVCouldNotCompute>(BetterAddRecStart))
125    AddRecStart = BetterAddRecStart;
126
127  // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other
128  // than an outer loop of the current loop, reject it.  LSR has no concept of
129  // operating on more than one loop at a time so don't confuse it with such
130  // expressions.
131  if (containsAddRecFromDifferentLoop(AddRecStart, L))
132    return false;
133
134  if (isSExt || isZExt)
135    Start = SE->getTruncateExpr(Start, AddRec->getType());
136
137  Start = SE->getAddExpr(Start, AddRecStart);
138
139  if (!isa<SCEVConstant>(AddRec->getStepRecurrence(*SE))) {
140    // If stride is an instruction, make sure it dominates the loop preheader.
141    // Otherwise we could end up with a use before def situation.
142    BasicBlock *Preheader = L->getLoopPreheader();
143    if (!AddRec->getStepRecurrence(*SE)->dominates(Preheader, DT))
144      return false;
145
146    DOUT << "[" << L->getHeader()->getName()
147         << "] Variable stride: " << *AddRec << "\n";
148  }
149
150  Stride = AddRec->getStepRecurrence(*SE);
151  isSigned = isSExt;
152  return true;
153}
154
155/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
156/// and now we need to decide whether the user should use the preinc or post-inc
157/// value.  If this user should use the post-inc version of the IV, return true.
158///
159/// Choosing wrong here can break dominance properties (if we choose to use the
160/// post-inc value when we cannot) or it can end up adding extra live-ranges to
161/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
162/// should use the post-inc value).
163static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
164                                       Loop *L, LoopInfo *LI, DominatorTree *DT,
165                                       Pass *P) {
166  // If the user is in the loop, use the preinc value.
167  if (L->contains(User->getParent())) return false;
168
169  BasicBlock *LatchBlock = L->getLoopLatch();
170
171  // Ok, the user is outside of the loop.  If it is dominated by the latch
172  // block, use the post-inc value.
173  if (DT->dominates(LatchBlock, User->getParent()))
174    return true;
175
176  // There is one case we have to be careful of: PHI nodes.  These little guys
177  // can live in blocks that are not dominated by the latch block, but (since
178  // their uses occur in the predecessor block, not the block the PHI lives in)
179  // should still use the post-inc value.  Check for this case now.
180  PHINode *PN = dyn_cast<PHINode>(User);
181  if (!PN) return false;  // not a phi, not dominated by latch block.
182
183  // Look at all of the uses of IV by the PHI node.  If any use corresponds to
184  // a block that is not dominated by the latch block, give up and use the
185  // preincremented value.
186  unsigned NumUses = 0;
187  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
188    if (PN->getIncomingValue(i) == IV) {
189      ++NumUses;
190      if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
191        return false;
192    }
193
194  // Okay, all uses of IV by PN are in predecessor blocks that really are
195  // dominated by the latch block.  Use the post-incremented value.
196  return true;
197}
198
199/// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
200/// reducible SCEV, recursively add its users to the IVUsesByStride set and
201/// return true.  Otherwise, return false.
202bool IVUsers::AddUsersIfInteresting(Instruction *I) {
203  if (!SE->isSCEVable(I->getType()))
204    return false;   // Void and FP expressions cannot be reduced.
205
206  // LSR is not APInt clean, do not touch integers bigger than 64-bits.
207  if (SE->getTypeSizeInBits(I->getType()) > 64)
208    return false;
209
210  if (!Processed.insert(I))
211    return true;    // Instruction already handled.
212
213  // Get the symbolic expression for this instruction.
214  SCEVHandle ISE = SE->getSCEV(I);
215  if (isa<SCEVCouldNotCompute>(ISE)) return false;
216
217  // Get the start and stride for this expression.
218  Loop *UseLoop = LI->getLoopFor(I->getParent());
219  SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
220  SCEVHandle Stride = Start;
221  bool isSigned = false; // Arbitrary initial value - pacifies compiler.
222
223  if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, isSigned, SE, DT))
224    return false;  // Non-reducible symbolic expression, bail out.
225
226  SmallPtrSet<Instruction *, 4> UniqueUsers;
227  for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
228       UI != E; ++UI) {
229    Instruction *User = cast<Instruction>(*UI);
230    if (!UniqueUsers.insert(User))
231      continue;
232
233    // Do not infinitely recurse on PHI nodes.
234    if (isa<PHINode>(User) && Processed.count(User))
235      continue;
236
237    // Descend recursively, but not into PHI nodes outside the current loop.
238    // It's important to see the entire expression outside the loop to get
239    // choices that depend on addressing mode use right, although we won't
240    // consider references ouside the loop in all cases.
241    // If User is already in Processed, we don't want to recurse into it again,
242    // but do want to record a second reference in the same instruction.
243    bool AddUserToIVUsers = false;
244    if (LI->getLoopFor(User->getParent()) != L) {
245      if (isa<PHINode>(User) || Processed.count(User) ||
246          !AddUsersIfInteresting(User)) {
247        DOUT << "FOUND USER in other loop: " << *User
248             << "   OF SCEV: " << *ISE << "\n";
249        AddUserToIVUsers = true;
250      }
251    } else if (Processed.count(User) ||
252               !AddUsersIfInteresting(User)) {
253      DOUT << "FOUND USER: " << *User
254           << "   OF SCEV: " << *ISE << "\n";
255      AddUserToIVUsers = true;
256    }
257
258    if (AddUserToIVUsers) {
259      IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
260      if (!StrideUses) {    // First occurrence of this stride?
261        StrideOrder.push_back(Stride);
262        StrideUses = new IVUsersOfOneStride(Stride);
263        IVUses.push_back(StrideUses);
264        IVUsesByStride[Stride] = StrideUses;
265      }
266
267      // Okay, we found a user that we cannot reduce.  Analyze the instruction
268      // and decide what to do with it.  If we are a use inside of the loop, use
269      // the value before incrementation, otherwise use it after incrementation.
270      if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) {
271        // The value used will be incremented by the stride more than we are
272        // expecting, so subtract this off.
273        SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
274        StrideUses->addUser(NewStart, User, I, isSigned);
275        StrideUses->Users.back().setIsUseOfPostIncrementedValue(true);
276        DOUT << "   USING POSTINC SCEV, START=" << *NewStart<< "\n";
277      } else {
278        StrideUses->addUser(Start, User, I, isSigned);
279      }
280    }
281  }
282  return true;
283}
284
285IVUsers::IVUsers()
286 : LoopPass(&ID) {
287}
288
289void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
290  AU.addRequired<LoopInfo>();
291  AU.addRequired<DominatorTree>();
292  AU.addRequired<ScalarEvolution>();
293  AU.setPreservesAll();
294}
295
296bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
297
298  L = l;
299  LI = &getAnalysis<LoopInfo>();
300  DT = &getAnalysis<DominatorTree>();
301  SE = &getAnalysis<ScalarEvolution>();
302
303  // Find all uses of induction variables in this loop, and categorize
304  // them by stride.  Start by finding all of the PHI nodes in the header for
305  // this loop.  If they are induction variables, inspect their uses.
306  for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
307    AddUsersIfInteresting(I);
308
309  return false;
310}
311
312/// getReplacementExpr - Return a SCEV expression which computes the
313/// value of the OperandValToReplace of the given IVStrideUse.
314SCEVHandle IVUsers::getReplacementExpr(const IVStrideUse &U) const {
315  const Type *UseTy = U.getOperandValToReplace()->getType();
316  // Start with zero.
317  SCEVHandle RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType());
318  // Create the basic add recurrence.
319  RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L);
320  // Add the offset in a separate step, because it may be loop-variant.
321  RetVal = SE->getAddExpr(RetVal, U.getOffset());
322  // For uses of post-incremented values, add an extra stride to compute
323  // the actual replacement value.
324  if (U.isUseOfPostIncrementedValue())
325    RetVal = SE->getAddExpr(RetVal, U.getParent()->Stride);
326  // Evaluate the expression out of the loop, if possible.
327  if (!L->contains(U.getUser()->getParent())) {
328    SCEVHandle ExitVal = SE->getSCEVAtScope(RetVal, L->getParentLoop());
329    if (!isa<SCEVCouldNotCompute>(ExitVal) && ExitVal->isLoopInvariant(L))
330      RetVal = ExitVal;
331  }
332  // Promote the result to the type of the use.
333  if (SE->getTypeSizeInBits(RetVal->getType()) !=
334      SE->getTypeSizeInBits(UseTy)) {
335    if (U.isSigned())
336      RetVal = SE->getSignExtendExpr(RetVal, UseTy);
337    else
338      RetVal = SE->getZeroExtendExpr(RetVal, UseTy);
339  }
340  return RetVal;
341}
342
343void IVUsers::print(raw_ostream &OS, const Module *M) const {
344  OS << "IV Users for loop ";
345  WriteAsOperand(OS, L->getHeader(), false);
346  if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
347    OS << " with backedge-taken count "
348       << *SE->getBackedgeTakenCount(L);
349  }
350  OS << ":\n";
351
352  for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
353    std::map<SCEVHandle, IVUsersOfOneStride*>::const_iterator SI =
354      IVUsesByStride.find(StrideOrder[Stride]);
355    assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
356    OS << "  Stride " << *SI->first->getType() << " " << *SI->first << ":\n";
357
358    for (ilist<IVStrideUse>::const_iterator UI = SI->second->Users.begin(),
359         E = SI->second->Users.end(); UI != E; ++UI) {
360      OS << "    ";
361      WriteAsOperand(OS, UI->getOperandValToReplace(), false);
362      OS << " = ";
363      OS << *getReplacementExpr(*UI);
364      if (UI->isUseOfPostIncrementedValue())
365        OS << " (post-inc)";
366      OS << " in ";
367      UI->getUser()->print(OS);
368    }
369  }
370}
371
372void IVUsers::print(std::ostream &o, const Module *M) const {
373  raw_os_ostream OS(o);
374  print(OS, M);
375}
376
377void IVUsers::dump() const {
378  print(errs());
379}
380
381void IVUsers::releaseMemory() {
382  IVUsesByStride.clear();
383  StrideOrder.clear();
384  Processed.clear();
385}
386
387void IVStrideUse::deleted() {
388  // Remove this user from the list.
389  Parent->Users.erase(this);
390  // this now dangles!
391}
392