blob: 44d72e8e0a90c38251fc5ccf0100d743c0bf0cc8 [file] [log] [blame]
Dan Gohman28055122009-05-12 02:17:14 +00001//===- 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"
Dan Gohman28055122009-05-12 02:17:14 +000022#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Dan Gohman256c9612010-02-10 20:42:37 +000024#include "llvm/Assembly/AsmAnnotationWriter.h"
Dan Gohman28055122009-05-12 02:17:14 +000025#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
Dan Gohmand7df9e12010-02-12 10:34:29 +000039/// CollectSubexprs - Split S into subexpressions which can be pulled out into
40/// separate registers.
41static 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;
Dan Gohman28055122009-05-12 02:17:14 +000058 }
Dan Gohman28055122009-05-12 02:17:14 +000059 }
Dan Gohmand7df9e12010-02-12 10:34:29 +000060
61 // Otherwise use the value itself.
62 Ops.push_back(S);
Dan Gohman28055122009-05-12 02:17:14 +000063}
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.
Dan Gohman161ea032009-07-07 17:06:11 +000071static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop,
72 const SCEV *&Start, const SCEV *&Stride,
Dan Gohman28055122009-05-12 02:17:14 +000073 ScalarEvolution *SE, DominatorTree *DT) {
Dan Gohman161ea032009-07-07 17:06:11 +000074 const SCEV *TheAddRec = Start; // Initialize to zero.
Dan Gohman28055122009-05-12 02:17:14 +000075
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 =
Dan Gohmand7df9e12010-02-12 10:34:29 +000081 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i)))
82 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
83 else
Dan Gohman28055122009-05-12 02:17:14 +000084 Start = SE->getAddExpr(Start, AE->getOperand(i));
Dan Gohman28055122009-05-12 02:17:14 +000085 } else if (isa<SCEVAddRecExpr>(SH)) {
86 TheAddRec = SH;
87 } else {
88 return false; // not analyzable.
89 }
90
Dan Gohmand7df9e12010-02-12 10:34:29 +000091 // 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);
Dan Gohman28055122009-05-12 02:17:14 +0000113
114 // Use getSCEVAtScope to attempt to simplify other loops out of
115 // the picture.
Dan Gohman18c01092009-06-15 18:38:59 +0000116 AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
Dan Gohman28055122009-05-12 02:17:14 +0000117
Dan Gohman28055122009-05-12 02:17:14 +0000118 Start = SE->getAddExpr(Start, AddRecStart);
119
Dan Gohman12319f22009-09-27 15:30:00 +0000120 // If stride is an instruction, make sure it properly dominates the header.
Dan Gohman18c01092009-06-15 18:38:59 +0000121 // Otherwise we could end up with a use before def situation.
122 if (!isa<SCEVConstant>(AddRecStride)) {
Dan Gohman12319f22009-09-27 15:30:00 +0000123 BasicBlock *Header = L->getHeader();
124 if (!AddRecStride->properlyDominates(Header, DT))
Dan Gohman28055122009-05-12 02:17:14 +0000125 return false;
126
Dan Gohman169195e2010-01-09 18:17:45 +0000127 DEBUG(dbgs() << "[";
128 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
Dan Gohmand7df9e12010-02-12 10:34:29 +0000129 dbgs() << "] Variable stride: " << *AddRecStride << "\n");
Dan Gohman28055122009-05-12 02:17:14 +0000130 }
131
Dan Gohman18c01092009-06-15 18:38:59 +0000132 Stride = AddRecStride;
Dan Gohman28055122009-05-12 02:17:14 +0000133 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).
144static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
Dan Gohmane3979a22010-02-22 04:11:59 +0000145 Loop *L, DominatorTree *DT) {
Dan Gohman28055122009-05-12 02:17:14 +0000146 // If the user is in the loop, use the preinc value.
Dan Gohmane8df7dd2009-12-18 01:24:09 +0000147 if (L->contains(User)) return false;
Dan Gohman28055122009-05-12 02:17:14 +0000148
149 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman2c26c5b2009-11-05 19:41:37 +0000150 if (!LatchBlock)
151 return false;
Dan Gohman28055122009-05-12 02:17:14 +0000152
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.
184bool 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.
Dan Gohman161ea032009-07-07 17:06:11 +0000196 const SCEV *ISE = SE->getSCEV(I);
Dan Gohman28055122009-05-12 02:17:14 +0000197 if (isa<SCEVCouldNotCompute>(ISE)) return false;
198
199 // Get the start and stride for this expression.
200 Loop *UseLoop = LI->getLoopFor(I->getParent());
Dan Gohman161ea032009-07-07 17:06:11 +0000201 const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType());
202 const SCEV *Stride = Start;
Dan Gohman28055122009-05-12 02:17:14 +0000203
Dan Gohmandae43a22009-06-18 16:54:06 +0000204 if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT))
Dan Gohman28055122009-05-12 02:17:14 +0000205 return false; // Non-reducible symbolic expression, bail out.
206
Jim Grosbach51d2daf2009-11-19 02:05:44 +0000207 // Keep things simple. Don't touch loop-variant strides.
Dan Gohmane8df7dd2009-12-18 01:24:09 +0000208 if (!Stride->isLoopInvariant(L) && L->contains(I))
Jim Grosbach51d2daf2009-11-19 02:05:44 +0000209 return false;
210
Dan Gohman28055122009-05-12 02:17:14 +0000211 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 ouside 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)) {
David Greene76119d52009-12-23 20:20:46 +0000232 DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
Chris Lattner8a6411c2009-08-23 04:37:46 +0000233 << " OF SCEV: " << *ISE << '\n');
Dan Gohman28055122009-05-12 02:17:14 +0000234 AddUserToIVUsers = true;
235 }
236 } else if (Processed.count(User) ||
237 !AddUsersIfInteresting(User)) {
David Greene76119d52009-12-23 20:20:46 +0000238 DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
Chris Lattner8a6411c2009-08-23 04:37:46 +0000239 << " OF SCEV: " << *ISE << '\n');
Dan Gohman28055122009-05-12 02:17:14 +0000240 AddUserToIVUsers = true;
241 }
242
243 if (AddUserToIVUsers) {
Dan Gohman28055122009-05-12 02:17:14 +0000244 // 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.
Dan Gohmane3979a22010-02-22 04:11:59 +0000247 if (IVUseShouldUsePostIncValue(User, I, L, DT)) {
Dan Gohman28055122009-05-12 02:17:14 +0000248 // The value used will be incremented by the stride more than we are
249 // expecting, so subtract this off.
Dan Gohman161ea032009-07-07 17:06:11 +0000250 const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
Dan Gohmand7df9e12010-02-12 10:34:29 +0000251 IVUses.push_back(new IVStrideUse(this, Stride, NewStart, User, I));
252 IVUses.back().setIsUseOfPostIncrementedValue(true);
David Greene76119d52009-12-23 20:20:46 +0000253 DEBUG(dbgs() << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Dan Gohman28055122009-05-12 02:17:14 +0000254 } else {
Dan Gohmand7df9e12010-02-12 10:34:29 +0000255 IVUses.push_back(new IVStrideUse(this, Stride, Start, User, I));
Dan Gohman28055122009-05-12 02:17:14 +0000256 }
257 }
258 }
259 return true;
260}
261
Dan Gohmand7df9e12010-02-12 10:34:29 +0000262IVStrideUse &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();
Evan Cheng6d702002009-11-12 07:35:05 +0000266}
267
Dan Gohman28055122009-05-12 02:17:14 +0000268IVUsers::IVUsers()
269 : LoopPass(&ID) {
270}
271
272void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
273 AU.addRequired<LoopInfo>();
274 AU.addRequired<DominatorTree>();
275 AU.addRequired<ScalarEvolution>();
276 AU.setPreservesAll();
277}
278
279bool 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.
Dan Gohman161ea032009-07-07 17:06:11 +0000297const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {
Dan Gohman28055122009-05-12 02:17:14 +0000298 // Start with zero.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000299 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
Dan Gohman28055122009-05-12 02:17:14 +0000300 // Create the basic add recurrence.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000301 RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
Dan Gohman28055122009-05-12 02:17:14 +0000302 // 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())
Dan Gohmand7df9e12010-02-12 10:34:29 +0000307 RetVal = SE->getAddExpr(RetVal, U.getStride());
Dan Gohman28055122009-05-12 02:17:14 +0000308 return RetVal;
309}
310
Dan Gohman780a7d92010-01-19 21:55:32 +0000311/// getCanonicalExpr - Return a SCEV expression which computes the
312/// value of the SCEV of the given IVStrideUse, ignoring the
313/// isUseOfPostIncrementedValue flag.
314const SCEV *IVUsers::getCanonicalExpr(const IVStrideUse &U) const {
315 // Start with zero.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000316 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
Dan Gohman780a7d92010-01-19 21:55:32 +0000317 // Create the basic add recurrence.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000318 RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
Dan Gohman780a7d92010-01-19 21:55:32 +0000319 // 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
Dan Gohman28055122009-05-12 02:17:14 +0000324void 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
Dan Gohmand3a52af2010-02-14 02:48:58 +0000333 // Use a defualt AssemblyAnnotationWriter to suppress the default info
334 // comments, which aren't relevant here.
335 AssemblyAnnotationWriter Annotator;
Dan Gohmand7df9e12010-02-12 10:34:29 +0000336 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';
Dan Gohman28055122009-05-12 02:17:14 +0000347 }
348}
349
Dan Gohman28055122009-05-12 02:17:14 +0000350void IVUsers::dump() const {
David Greene76119d52009-12-23 20:20:46 +0000351 print(dbgs());
Dan Gohman28055122009-05-12 02:17:14 +0000352}
353
354void IVUsers::releaseMemory() {
Evan Cheng38e52382009-12-17 09:39:49 +0000355 Processed.clear();
Dan Gohman42ba40e2009-12-18 00:06:20 +0000356 IVUses.clear();
Dan Gohman28055122009-05-12 02:17:14 +0000357}
358
359void IVStrideUse::deleted() {
360 // Remove this user from the list.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000361 Parent->IVUses.erase(this);
Dan Gohman28055122009-05-12 02:17:14 +0000362 // this now dangles!
363}