blob: f6d53da3ab6e5704fb802924301b5d23a7d1ba06 [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,
145 Loop *L, LoopInfo *LI, DominatorTree *DT,
146 Pass *P) {
147 // If the user is in the loop, use the preinc value.
Dan Gohmane8df7dd2009-12-18 01:24:09 +0000148 if (L->contains(User)) return false;
Dan Gohman28055122009-05-12 02:17:14 +0000149
150 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohman2c26c5b2009-11-05 19:41:37 +0000151 if (!LatchBlock)
152 return false;
Dan Gohman28055122009-05-12 02:17:14 +0000153
154 // Ok, the user is outside of the loop. If it is dominated by the latch
155 // block, use the post-inc value.
156 if (DT->dominates(LatchBlock, User->getParent()))
157 return true;
158
159 // There is one case we have to be careful of: PHI nodes. These little guys
160 // can live in blocks that are not dominated by the latch block, but (since
161 // their uses occur in the predecessor block, not the block the PHI lives in)
162 // should still use the post-inc value. Check for this case now.
163 PHINode *PN = dyn_cast<PHINode>(User);
164 if (!PN) return false; // not a phi, not dominated by latch block.
165
166 // Look at all of the uses of IV by the PHI node. If any use corresponds to
167 // a block that is not dominated by the latch block, give up and use the
168 // preincremented value.
169 unsigned NumUses = 0;
170 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
171 if (PN->getIncomingValue(i) == IV) {
172 ++NumUses;
173 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
174 return false;
175 }
176
177 // Okay, all uses of IV by PN are in predecessor blocks that really are
178 // dominated by the latch block. Use the post-incremented value.
179 return true;
180}
181
182/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
183/// reducible SCEV, recursively add its users to the IVUsesByStride set and
184/// return true. Otherwise, return false.
185bool IVUsers::AddUsersIfInteresting(Instruction *I) {
186 if (!SE->isSCEVable(I->getType()))
187 return false; // Void and FP expressions cannot be reduced.
188
189 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
190 if (SE->getTypeSizeInBits(I->getType()) > 64)
191 return false;
192
193 if (!Processed.insert(I))
194 return true; // Instruction already handled.
195
196 // Get the symbolic expression for this instruction.
Dan Gohman161ea032009-07-07 17:06:11 +0000197 const SCEV *ISE = SE->getSCEV(I);
Dan Gohman28055122009-05-12 02:17:14 +0000198 if (isa<SCEVCouldNotCompute>(ISE)) return false;
199
200 // Get the start and stride for this expression.
201 Loop *UseLoop = LI->getLoopFor(I->getParent());
Dan Gohman161ea032009-07-07 17:06:11 +0000202 const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType());
203 const SCEV *Stride = Start;
Dan Gohman28055122009-05-12 02:17:14 +0000204
Dan Gohmandae43a22009-06-18 16:54:06 +0000205 if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT))
Dan Gohman28055122009-05-12 02:17:14 +0000206 return false; // Non-reducible symbolic expression, bail out.
207
Jim Grosbach51d2daf2009-11-19 02:05:44 +0000208 // Keep things simple. Don't touch loop-variant strides.
Dan Gohmane8df7dd2009-12-18 01:24:09 +0000209 if (!Stride->isLoopInvariant(L) && L->contains(I))
Jim Grosbach51d2daf2009-11-19 02:05:44 +0000210 return false;
211
Dan Gohman28055122009-05-12 02:17:14 +0000212 SmallPtrSet<Instruction *, 4> UniqueUsers;
213 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
214 UI != E; ++UI) {
215 Instruction *User = cast<Instruction>(*UI);
216 if (!UniqueUsers.insert(User))
217 continue;
218
219 // Do not infinitely recurse on PHI nodes.
220 if (isa<PHINode>(User) && Processed.count(User))
221 continue;
222
223 // Descend recursively, but not into PHI nodes outside the current loop.
224 // It's important to see the entire expression outside the loop to get
225 // choices that depend on addressing mode use right, although we won't
226 // consider references ouside the loop in all cases.
227 // If User is already in Processed, we don't want to recurse into it again,
228 // but do want to record a second reference in the same instruction.
229 bool AddUserToIVUsers = false;
230 if (LI->getLoopFor(User->getParent()) != L) {
231 if (isa<PHINode>(User) || Processed.count(User) ||
232 !AddUsersIfInteresting(User)) {
David Greene76119d52009-12-23 20:20:46 +0000233 DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
Chris Lattner8a6411c2009-08-23 04:37:46 +0000234 << " OF SCEV: " << *ISE << '\n');
Dan Gohman28055122009-05-12 02:17:14 +0000235 AddUserToIVUsers = true;
236 }
237 } else if (Processed.count(User) ||
238 !AddUsersIfInteresting(User)) {
David Greene76119d52009-12-23 20:20:46 +0000239 DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
Chris Lattner8a6411c2009-08-23 04:37:46 +0000240 << " OF SCEV: " << *ISE << '\n');
Dan Gohman28055122009-05-12 02:17:14 +0000241 AddUserToIVUsers = true;
242 }
243
244 if (AddUserToIVUsers) {
Dan Gohman28055122009-05-12 02:17:14 +0000245 // Okay, we found a user that we cannot reduce. Analyze the instruction
246 // and decide what to do with it. If we are a use inside of the loop, use
247 // the value before incrementation, otherwise use it after incrementation.
248 if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) {
249 // The value used will be incremented by the stride more than we are
250 // expecting, so subtract this off.
Dan Gohman161ea032009-07-07 17:06:11 +0000251 const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
Dan Gohmand7df9e12010-02-12 10:34:29 +0000252 IVUses.push_back(new IVStrideUse(this, Stride, NewStart, User, I));
253 IVUses.back().setIsUseOfPostIncrementedValue(true);
David Greene76119d52009-12-23 20:20:46 +0000254 DEBUG(dbgs() << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Dan Gohman28055122009-05-12 02:17:14 +0000255 } else {
Dan Gohmand7df9e12010-02-12 10:34:29 +0000256 IVUses.push_back(new IVStrideUse(this, Stride, Start, User, I));
Dan Gohman28055122009-05-12 02:17:14 +0000257 }
258 }
259 }
260 return true;
261}
262
Dan Gohmand7df9e12010-02-12 10:34:29 +0000263IVStrideUse &IVUsers::AddUser(const SCEV *Stride, const SCEV *Offset,
264 Instruction *User, Value *Operand) {
265 IVUses.push_back(new IVStrideUse(this, Stride, Offset, User, Operand));
266 return IVUses.back();
Evan Cheng6d702002009-11-12 07:35:05 +0000267}
268
Dan Gohman28055122009-05-12 02:17:14 +0000269IVUsers::IVUsers()
270 : LoopPass(&ID) {
271}
272
273void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
274 AU.addRequired<LoopInfo>();
275 AU.addRequired<DominatorTree>();
276 AU.addRequired<ScalarEvolution>();
277 AU.setPreservesAll();
278}
279
280bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
281
282 L = l;
283 LI = &getAnalysis<LoopInfo>();
284 DT = &getAnalysis<DominatorTree>();
285 SE = &getAnalysis<ScalarEvolution>();
286
287 // Find all uses of induction variables in this loop, and categorize
288 // them by stride. Start by finding all of the PHI nodes in the header for
289 // this loop. If they are induction variables, inspect their uses.
290 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
291 AddUsersIfInteresting(I);
292
293 return false;
294}
295
296/// getReplacementExpr - Return a SCEV expression which computes the
297/// value of the OperandValToReplace of the given IVStrideUse.
Dan Gohman161ea032009-07-07 17:06:11 +0000298const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {
Dan Gohman28055122009-05-12 02:17:14 +0000299 // Start with zero.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000300 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
Dan Gohman28055122009-05-12 02:17:14 +0000301 // Create the basic add recurrence.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000302 RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
Dan Gohman28055122009-05-12 02:17:14 +0000303 // Add the offset in a separate step, because it may be loop-variant.
304 RetVal = SE->getAddExpr(RetVal, U.getOffset());
305 // For uses of post-incremented values, add an extra stride to compute
306 // the actual replacement value.
307 if (U.isUseOfPostIncrementedValue())
Dan Gohmand7df9e12010-02-12 10:34:29 +0000308 RetVal = SE->getAddExpr(RetVal, U.getStride());
Dan Gohman28055122009-05-12 02:17:14 +0000309 return RetVal;
310}
311
Dan Gohman780a7d92010-01-19 21:55:32 +0000312/// getCanonicalExpr - Return a SCEV expression which computes the
313/// value of the SCEV of the given IVStrideUse, ignoring the
314/// isUseOfPostIncrementedValue flag.
315const SCEV *IVUsers::getCanonicalExpr(const IVStrideUse &U) const {
316 // Start with zero.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000317 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
Dan Gohman780a7d92010-01-19 21:55:32 +0000318 // Create the basic add recurrence.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000319 RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
Dan Gohman780a7d92010-01-19 21:55:32 +0000320 // Add the offset in a separate step, because it may be loop-variant.
321 RetVal = SE->getAddExpr(RetVal, U.getOffset());
322 return RetVal;
323}
324
Dan Gohman256c9612010-02-10 20:42:37 +0000325namespace {
326
327// Suppress extraneous comments.
328class IVUsersAsmAnnotator : public AssemblyAnnotationWriter {};
329
330}
331
Dan Gohman28055122009-05-12 02:17:14 +0000332void IVUsers::print(raw_ostream &OS, const Module *M) const {
333 OS << "IV Users for loop ";
334 WriteAsOperand(OS, L->getHeader(), false);
335 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
336 OS << " with backedge-taken count "
337 << *SE->getBackedgeTakenCount(L);
338 }
339 OS << ":\n";
340
Dan Gohman256c9612010-02-10 20:42:37 +0000341 IVUsersAsmAnnotator Annotator;
Dan Gohmand7df9e12010-02-12 10:34:29 +0000342 for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(),
343 E = IVUses.end(); UI != E; ++UI) {
344 OS << " ";
345 WriteAsOperand(OS, UI->getOperandValToReplace(), false);
346 OS << " = "
347 << *getReplacementExpr(*UI);
348 if (UI->isUseOfPostIncrementedValue())
349 OS << " (post-inc)";
350 OS << " in ";
351 UI->getUser()->print(OS, &Annotator);
352 OS << '\n';
Dan Gohman28055122009-05-12 02:17:14 +0000353 }
354}
355
Dan Gohman28055122009-05-12 02:17:14 +0000356void IVUsers::dump() const {
David Greene76119d52009-12-23 20:20:46 +0000357 print(dbgs());
Dan Gohman28055122009-05-12 02:17:14 +0000358}
359
360void IVUsers::releaseMemory() {
Evan Cheng38e52382009-12-17 09:39:49 +0000361 Processed.clear();
Dan Gohman42ba40e2009-12-18 00:06:20 +0000362 IVUses.clear();
Dan Gohman28055122009-05-12 02:17:14 +0000363}
364
365void IVStrideUse::deleted() {
366 // Remove this user from the list.
Dan Gohmand7df9e12010-02-12 10:34:29 +0000367 Parent->IVUses.erase(this);
Dan Gohman28055122009-05-12 02:17:14 +0000368 // this now dangles!
369}