1 //===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements bookkeeping for "interesting" users of expressions
11 // computed from induction variables.
13 //===----------------------------------------------------------------------===//
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/ADT/STLExtras.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
31 static RegisterPass<IVUsers>
32 X("iv-users", "Induction Variable Users", false, true);
34 Pass *llvm::createIVUsersPass() {
38 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
39 /// subexpression that is an AddRec from a loop other than L. An outer loop
40 /// of L is OK, but not an inner loop nor a disjoint loop.
41 static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) {
42 // This is very common, put it first.
43 if (isa<SCEVConstant>(S))
45 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
46 for (unsigned int i=0; i< AE->getNumOperands(); i++)
47 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
51 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
52 if (const Loop *newLoop = AE->getLoop()) {
55 // if newLoop is an outer loop of L, this is OK.
56 if (!LoopInfo::isNotAlreadyContainedIn(L, newLoop))
61 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
62 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
63 containsAddRecFromDifferentLoop(DE->getRHS(), L);
65 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
66 // need this when it is.
67 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
68 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
69 containsAddRecFromDifferentLoop(DE->getRHS(), L);
71 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
72 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
76 /// getSCEVStartAndStride - Compute the start and stride of this expression,
77 /// returning false if the expression is not a start/stride pair, or true if it
78 /// is. The stride must be a loop invariant expression, but the start may be
79 /// a mix of loop invariant and loop variant expressions. The start cannot,
80 /// however, contain an AddRec from a different loop, unless that loop is an
81 /// outer loop of the current loop.
82 static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop,
83 const SCEV *&Start, const SCEV *&Stride,
84 ScalarEvolution *SE, DominatorTree *DT) {
85 const SCEV *TheAddRec = Start; // Initialize to zero.
87 // If the outer level is an AddExpr, the operands are all start values except
88 // for a nested AddRecExpr.
89 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
90 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
91 if (const SCEVAddRecExpr *AddRec =
92 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
93 if (AddRec->getLoop() == L)
94 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
96 return false; // Nested IV of some sort?
98 Start = SE->getAddExpr(Start, AE->getOperand(i));
100 } else if (isa<SCEVAddRecExpr>(SH)) {
103 return false; // not analyzable.
106 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
107 if (!AddRec || AddRec->getLoop() != L) return false;
109 // Use getSCEVAtScope to attempt to simplify other loops out of
111 const SCEV *AddRecStart = AddRec->getStart();
112 AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
113 const SCEV *AddRecStride = AddRec->getStepRecurrence(*SE);
115 // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other
116 // than an outer loop of the current loop, reject it. LSR has no concept of
117 // operating on more than one loop at a time so don't confuse it with such
119 if (containsAddRecFromDifferentLoop(AddRecStart, L))
122 Start = SE->getAddExpr(Start, AddRecStart);
124 // If stride is an instruction, make sure it properly dominates the header.
125 // Otherwise we could end up with a use before def situation.
126 if (!isa<SCEVConstant>(AddRecStride)) {
127 BasicBlock *Header = L->getHeader();
128 if (!AddRecStride->properlyDominates(Header, DT))
131 DEBUG(errs() << "[" << L->getHeader()->getName()
132 << "] Variable stride: " << *AddRec << "\n");
135 Stride = AddRecStride;
139 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
140 /// and now we need to decide whether the user should use the preinc or post-inc
141 /// value. If this user should use the post-inc version of the IV, return true.
143 /// Choosing wrong here can break dominance properties (if we choose to use the
144 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
145 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
146 /// should use the post-inc value).
147 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
148 Loop *L, LoopInfo *LI, DominatorTree *DT,
150 // If the user is in the loop, use the preinc value.
151 if (L->contains(User->getParent())) return false;
153 BasicBlock *LatchBlock = L->getLoopLatch();
155 // Ok, the user is outside of the loop. If it is dominated by the latch
156 // block, use the post-inc value.
157 if (DT->dominates(LatchBlock, User->getParent()))
160 // There is one case we have to be careful of: PHI nodes. These little guys
161 // can live in blocks that are not dominated by the latch block, but (since
162 // their uses occur in the predecessor block, not the block the PHI lives in)
163 // should still use the post-inc value. Check for this case now.
164 PHINode *PN = dyn_cast<PHINode>(User);
165 if (!PN) return false; // not a phi, not dominated by latch block.
167 // Look at all of the uses of IV by the PHI node. If any use corresponds to
168 // a block that is not dominated by the latch block, give up and use the
169 // preincremented value.
170 unsigned NumUses = 0;
171 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
172 if (PN->getIncomingValue(i) == IV) {
174 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
178 // Okay, all uses of IV by PN are in predecessor blocks that really are
179 // dominated by the latch block. Use the post-incremented value.
183 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
184 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
185 /// return true. Otherwise, return false.
186 bool IVUsers::AddUsersIfInteresting(Instruction *I) {
187 if (!SE->isSCEVable(I->getType()))
188 return false; // Void and FP expressions cannot be reduced.
190 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
191 if (SE->getTypeSizeInBits(I->getType()) > 64)
194 if (!Processed.insert(I))
195 return true; // Instruction already handled.
197 // Get the symbolic expression for this instruction.
198 const SCEV *ISE = SE->getSCEV(I);
199 if (isa<SCEVCouldNotCompute>(ISE)) return false;
201 // Get the start and stride for this expression.
202 Loop *UseLoop = LI->getLoopFor(I->getParent());
203 const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType());
204 const SCEV *Stride = Start;
206 if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT))
207 return false; // Non-reducible symbolic expression, bail out.
209 SmallPtrSet<Instruction *, 4> UniqueUsers;
210 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
212 Instruction *User = cast<Instruction>(*UI);
213 if (!UniqueUsers.insert(User))
216 // Do not infinitely recurse on PHI nodes.
217 if (isa<PHINode>(User) && Processed.count(User))
220 // Descend recursively, but not into PHI nodes outside the current loop.
221 // It's important to see the entire expression outside the loop to get
222 // choices that depend on addressing mode use right, although we won't
223 // consider references ouside the loop in all cases.
224 // If User is already in Processed, we don't want to recurse into it again,
225 // but do want to record a second reference in the same instruction.
226 bool AddUserToIVUsers = false;
227 if (LI->getLoopFor(User->getParent()) != L) {
228 if (isa<PHINode>(User) || Processed.count(User) ||
229 !AddUsersIfInteresting(User)) {
230 DEBUG(errs() << "FOUND USER in other loop: " << *User << '\n'
231 << " OF SCEV: " << *ISE << '\n');
232 AddUserToIVUsers = true;
234 } else if (Processed.count(User) ||
235 !AddUsersIfInteresting(User)) {
236 DEBUG(errs() << "FOUND USER: " << *User << '\n'
237 << " OF SCEV: " << *ISE << '\n');
238 AddUserToIVUsers = true;
241 if (AddUserToIVUsers) {
242 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
243 if (!StrideUses) { // First occurrence of this stride?
244 StrideOrder.push_back(Stride);
245 StrideUses = new IVUsersOfOneStride(Stride);
246 IVUses.push_back(StrideUses);
247 IVUsesByStride[Stride] = StrideUses;
250 // Okay, we found a user that we cannot reduce. Analyze the instruction
251 // and decide what to do with it. If we are a use inside of the loop, use
252 // the value before incrementation, otherwise use it after incrementation.
253 if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) {
254 // The value used will be incremented by the stride more than we are
255 // expecting, so subtract this off.
256 const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
257 StrideUses->addUser(NewStart, User, I);
258 StrideUses->Users.back().setIsUseOfPostIncrementedValue(true);
259 DEBUG(errs() << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
261 StrideUses->addUser(Start, User, I);
272 void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
273 AU.addRequired<LoopInfo>();
274 AU.addRequired<DominatorTree>();
275 AU.addRequired<ScalarEvolution>();
276 AU.setPreservesAll();
279 bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
282 LI = &getAnalysis<LoopInfo>();
283 DT = &getAnalysis<DominatorTree>();
284 SE = &getAnalysis<ScalarEvolution>();
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);
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 {
299 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType());
300 // Create the basic add recurrence.
301 RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, 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.getParent()->Stride);
308 // Evaluate the expression out of the loop, if possible.
309 if (!L->contains(U.getUser()->getParent())) {
310 const SCEV *ExitVal = SE->getSCEVAtScope(RetVal, L->getParentLoop());
311 if (ExitVal->isLoopInvariant(L))
317 void IVUsers::print(raw_ostream &OS, const Module *M) const {
318 OS << "IV Users for loop ";
319 WriteAsOperand(OS, L->getHeader(), false);
320 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
321 OS << " with backedge-taken count "
322 << *SE->getBackedgeTakenCount(L);
326 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
327 std::map<const SCEV *, IVUsersOfOneStride*>::const_iterator SI =
328 IVUsesByStride.find(StrideOrder[Stride]);
329 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
330 OS << " Stride " << *SI->first->getType() << " " << *SI->first << ":\n";
332 for (ilist<IVStrideUse>::const_iterator UI = SI->second->Users.begin(),
333 E = SI->second->Users.end(); UI != E; ++UI) {
335 WriteAsOperand(OS, UI->getOperandValToReplace(), false);
337 OS << *getReplacementExpr(*UI);
338 if (UI->isUseOfPostIncrementedValue())
341 UI->getUser()->print(OS);
347 void IVUsers::dump() const {
351 void IVUsers::releaseMemory() {
352 IVUsesByStride.clear();
357 void IVStrideUse::deleted() {
358 // Remove this user from the list.
359 Parent->Users.erase(this);