blob: d03b86a7e9d7aa410679703693dc34460d104ebd [file] [log] [blame]
Dan Gohman2d1be872009-04-16 03:18:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Nate Begemaneaa13852004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Nate Begemaneaa13852004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
Dan Gohmancec8f9d2009-05-19 20:37:36 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into forms suitable for efficient execution
12// on the target.
13//
Nate Begemaneaa13852004-10-18 21:08:22 +000014// This pass performs a strength reduction on array references inside loops that
Dan Gohmancec8f9d2009-05-19 20:37:36 +000015// have as one or more of their components the loop induction variable, it
16// rewrites expressions to take advantage of scaled-index addressing modes
17// available on the target, and it performs a variety of other optimizations
18// related to loop induction variables.
Nate Begemaneaa13852004-10-18 21:08:22 +000019//
Dan Gohman572645c2010-02-12 10:34:29 +000020// Terminology note: this code has a lot of handling for "post-increment" or
21// "post-inc" users. This is not talking about post-increment addressing modes;
22// it is instead talking about code like this:
23//
24// %i = phi [ 0, %entry ], [ %i.next, %latch ]
25// ...
26// %i.next = add %i, 1
27// %c = icmp eq %i.next, %n
28//
29// The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
30// it's useful to think about these as the same register, with some uses using
31// the value of the register before the add and some using // it after. In this
32// example, the icmp is a post-increment user, since it uses %i.next, which is
33// the value of the induction variable after the increment. The other common
34// case of post-increment users is users outside the loop.
35//
36// TODO: More sophistication in the way Formulae are generated and filtered.
37//
38// TODO: Handle multiple loops at a time.
39//
40// TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
41// instead of a GlobalValue?
42//
43// TODO: When truncation is free, truncate ICmp users' operands to make it a
44// smaller encoding (on x86 at least).
45//
46// TODO: When a negated register is used by an add (such as in a list of
47// multiple base registers, or as the increment expression in an addrec),
48// we may not actually need both reg and (-1 * reg) in registers; the
49// negation can be implemented by using a sub instead of an add. The
50// lack of support for taking this into consideration when making
51// register pressure decisions is partly worked around by the "Special"
52// use kind.
53//
Nate Begemaneaa13852004-10-18 21:08:22 +000054//===----------------------------------------------------------------------===//
55
Chris Lattnerbe3e5212005-08-03 23:30:08 +000056#define DEBUG_TYPE "loop-reduce"
Nate Begemaneaa13852004-10-18 21:08:22 +000057#include "llvm/Transforms/Scalar.h"
58#include "llvm/Constants.h"
59#include "llvm/Instructions.h"
Dan Gohmane5b01be2007-05-04 14:59:09 +000060#include "llvm/IntrinsicInst.h"
Jeff Cohen2f3c9b72005-03-04 04:04:26 +000061#include "llvm/DerivedTypes.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000062#include "llvm/Analysis/IVUsers.h"
Dan Gohman572645c2010-02-12 10:34:29 +000063#include "llvm/Analysis/Dominators.h"
Devang Patel0f54dcb2007-03-06 21:14:09 +000064#include "llvm/Analysis/LoopPass.h"
Nate Begeman16997482005-07-30 00:15:07 +000065#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner9fc5cdf2011-01-02 22:09:33 +000066#include "llvm/Assembly/Writer.h"
Chris Lattnere0391be2005-08-12 22:06:11 +000067#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000068#include "llvm/Transforms/Utils/Local.h"
Dan Gohman572645c2010-02-12 10:34:29 +000069#include "llvm/ADT/SmallBitVector.h"
70#include "llvm/ADT/SetVector.h"
71#include "llvm/ADT/DenseSet.h"
Nate Begeman16997482005-07-30 00:15:07 +000072#include "llvm/Support/Debug.h"
Andrew Trick80ef1b22011-09-27 00:44:14 +000073#include "llvm/Support/CommandLine.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000074#include "llvm/Support/ValueHandle.h"
Daniel Dunbar460f6562009-07-26 09:48:23 +000075#include "llvm/Support/raw_ostream.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000076#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000077#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000078using namespace llvm;
79
Andrew Trick80ef1b22011-09-27 00:44:14 +000080namespace llvm {
Andrew Trick0c01bc32011-09-29 01:33:38 +000081cl::opt<bool> EnableNested(
82 "enable-lsr-nested", cl::Hidden, cl::desc("Enable LSR on nested loops"));
83
Andrew Trick80ef1b22011-09-27 00:44:14 +000084cl::opt<bool> EnableRetry(
85 "enable-lsr-retry", cl::Hidden, cl::desc("Enable LSR retry"));
Andrew Tricka02bfce2011-10-11 02:30:45 +000086
87// Temporary flag to cleanup congruent phis after LSR phi expansion.
88// It's currently disabled until we can determine whether it's truly useful or
89// not. The flag should be removed after the v3.0 release.
90cl::opt<bool> EnablePhiElim(
91 "enable-lsr-phielim", cl::Hidden, cl::desc("Enable LSR phi elimination"));
Andrew Trick80ef1b22011-09-27 00:44:14 +000092}
93
Dan Gohman572645c2010-02-12 10:34:29 +000094namespace {
Nate Begemaneaa13852004-10-18 21:08:22 +000095
Dan Gohman572645c2010-02-12 10:34:29 +000096/// RegSortData - This class holds data which is used to order reuse candidates.
97class RegSortData {
98public:
99 /// UsedByIndices - This represents the set of LSRUse indices which reference
100 /// a particular register.
101 SmallBitVector UsedByIndices;
102
103 RegSortData() {}
104
105 void print(raw_ostream &OS) const;
106 void dump() const;
107};
108
109}
110
111void RegSortData::print(raw_ostream &OS) const {
112 OS << "[NumUses=" << UsedByIndices.count() << ']';
113}
114
115void RegSortData::dump() const {
116 print(errs()); errs() << '\n';
117}
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000118
Chris Lattner0e5f4992006-12-19 21:40:18 +0000119namespace {
Dale Johannesendc42f482007-03-20 00:47:50 +0000120
Dan Gohman572645c2010-02-12 10:34:29 +0000121/// RegUseTracker - Map register candidates to information about how they are
122/// used.
123class RegUseTracker {
124 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
Dale Johannesendc42f482007-03-20 00:47:50 +0000125
Dan Gohman90bb3552010-05-18 22:33:00 +0000126 RegUsesTy RegUsesMap;
Dan Gohman572645c2010-02-12 10:34:29 +0000127 SmallVector<const SCEV *, 16> RegSequence;
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000128
Dan Gohman572645c2010-02-12 10:34:29 +0000129public:
130 void CountRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmanb2df4332010-05-18 23:42:37 +0000131 void DropRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmanc6897702010-10-07 23:33:43 +0000132 void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000133
Dan Gohman572645c2010-02-12 10:34:29 +0000134 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000135
Dan Gohman572645c2010-02-12 10:34:29 +0000136 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000137
Dan Gohman572645c2010-02-12 10:34:29 +0000138 void clear();
Dan Gohmana10756e2010-01-21 02:09:26 +0000139
Dan Gohman572645c2010-02-12 10:34:29 +0000140 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
141 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
142 iterator begin() { return RegSequence.begin(); }
143 iterator end() { return RegSequence.end(); }
144 const_iterator begin() const { return RegSequence.begin(); }
145 const_iterator end() const { return RegSequence.end(); }
146};
Dan Gohmana10756e2010-01-21 02:09:26 +0000147
Dan Gohmana10756e2010-01-21 02:09:26 +0000148}
149
Dan Gohman572645c2010-02-12 10:34:29 +0000150void
151RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
152 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman90bb3552010-05-18 22:33:00 +0000153 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman572645c2010-02-12 10:34:29 +0000154 RegSortData &RSD = Pair.first->second;
155 if (Pair.second)
156 RegSequence.push_back(Reg);
157 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
158 RSD.UsedByIndices.set(LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000159}
160
Dan Gohmanb2df4332010-05-18 23:42:37 +0000161void
162RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
163 RegUsesTy::iterator It = RegUsesMap.find(Reg);
164 assert(It != RegUsesMap.end());
165 RegSortData &RSD = It->second;
166 assert(RSD.UsedByIndices.size() > LUIdx);
167 RSD.UsedByIndices.reset(LUIdx);
168}
169
Dan Gohmana2086b32010-05-19 23:43:12 +0000170void
Dan Gohmanc6897702010-10-07 23:33:43 +0000171RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
172 assert(LUIdx <= LastLUIdx);
173
174 // Update RegUses. The data structure is not optimized for this purpose;
175 // we must iterate through it and update each of the bit vectors.
Dan Gohmana2086b32010-05-19 23:43:12 +0000176 for (RegUsesTy::iterator I = RegUsesMap.begin(), E = RegUsesMap.end();
Dan Gohmanc6897702010-10-07 23:33:43 +0000177 I != E; ++I) {
178 SmallBitVector &UsedByIndices = I->second.UsedByIndices;
179 if (LUIdx < UsedByIndices.size())
180 UsedByIndices[LUIdx] =
181 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
182 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
183 }
Dan Gohmana2086b32010-05-19 23:43:12 +0000184}
185
Dan Gohman572645c2010-02-12 10:34:29 +0000186bool
187RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman46fd7a62010-08-29 15:18:49 +0000188 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
189 if (I == RegUsesMap.end())
190 return false;
191 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
Dan Gohman572645c2010-02-12 10:34:29 +0000192 int i = UsedByIndices.find_first();
193 if (i == -1) return false;
194 if ((size_t)i != LUIdx) return true;
195 return UsedByIndices.find_next(i) != -1;
196}
Dan Gohmana10756e2010-01-21 02:09:26 +0000197
Dan Gohman572645c2010-02-12 10:34:29 +0000198const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman90bb3552010-05-18 22:33:00 +0000199 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
200 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman572645c2010-02-12 10:34:29 +0000201 return I->second.UsedByIndices;
202}
Dan Gohmana10756e2010-01-21 02:09:26 +0000203
Dan Gohman572645c2010-02-12 10:34:29 +0000204void RegUseTracker::clear() {
Dan Gohman90bb3552010-05-18 22:33:00 +0000205 RegUsesMap.clear();
Dan Gohman572645c2010-02-12 10:34:29 +0000206 RegSequence.clear();
207}
Dan Gohmana10756e2010-01-21 02:09:26 +0000208
Dan Gohman572645c2010-02-12 10:34:29 +0000209namespace {
210
211/// Formula - This class holds information that describes a formula for
212/// computing satisfying a use. It may include broken-out immediates and scaled
213/// registers.
214struct Formula {
215 /// AM - This is used to represent complex addressing, as well as other kinds
216 /// of interesting uses.
217 TargetLowering::AddrMode AM;
218
219 /// BaseRegs - The list of "base" registers for this use. When this is
220 /// non-empty, AM.HasBaseReg should be set to true.
221 SmallVector<const SCEV *, 2> BaseRegs;
222
223 /// ScaledReg - The 'scaled' register for this use. This should be non-null
224 /// when AM.Scale is not zero.
225 const SCEV *ScaledReg;
226
Dan Gohmancca82142011-05-03 00:46:49 +0000227 /// UnfoldedOffset - An additional constant offset which added near the
228 /// use. This requires a temporary register, but the offset itself can
229 /// live in an add immediate field rather than a register.
230 int64_t UnfoldedOffset;
231
232 Formula() : ScaledReg(0), UnfoldedOffset(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +0000233
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000234 void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000235
236 unsigned getNumRegs() const;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 Type *getType() const;
Dan Gohman572645c2010-02-12 10:34:29 +0000238
Dan Gohman5ce6d052010-05-20 15:17:54 +0000239 void DeleteBaseReg(const SCEV *&S);
240
Dan Gohman572645c2010-02-12 10:34:29 +0000241 bool referencesReg(const SCEV *S) const;
242 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
243 const RegUseTracker &RegUses) const;
244
245 void print(raw_ostream &OS) const;
246 void dump() const;
247};
248
249}
250
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000251/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman572645c2010-02-12 10:34:29 +0000252static void DoInitialMatch(const SCEV *S, Loop *L,
253 SmallVectorImpl<const SCEV *> &Good,
254 SmallVectorImpl<const SCEV *> &Bad,
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000255 ScalarEvolution &SE) {
Dan Gohman572645c2010-02-12 10:34:29 +0000256 // Collect expressions which properly dominate the loop header.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000257 if (SE.properlyDominates(S, L->getHeader())) {
Dan Gohman572645c2010-02-12 10:34:29 +0000258 Good.push_back(S);
259 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000260 }
Dan Gohman572645c2010-02-12 10:34:29 +0000261
262 // Look at add operands.
263 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
264 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
265 I != E; ++I)
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000266 DoInitialMatch(*I, L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000267 return;
268 }
269
270 // Look at addrec operands.
271 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
272 if (!AR->getStart()->isZero()) {
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000273 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000274 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +0000275 AR->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000276 // FIXME: AR->getNoWrapFlags()
277 AR->getLoop(), SCEV::FlagAnyWrap),
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000278 L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000279 return;
280 }
281
282 // Handle a multiplication by -1 (negation) if it didn't fold.
283 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
284 if (Mul->getOperand(0)->isAllOnesValue()) {
285 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
286 const SCEV *NewMul = SE.getMulExpr(Ops);
287
288 SmallVector<const SCEV *, 4> MyGood;
289 SmallVector<const SCEV *, 4> MyBad;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000290 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000291 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
292 SE.getEffectiveSCEVType(NewMul->getType())));
293 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
294 E = MyGood.end(); I != E; ++I)
295 Good.push_back(SE.getMulExpr(NegOne, *I));
296 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
297 E = MyBad.end(); I != E; ++I)
298 Bad.push_back(SE.getMulExpr(NegOne, *I));
299 return;
300 }
301
302 // Ok, we can't do anything interesting. Just stuff the whole thing into a
303 // register and hope for the best.
304 Bad.push_back(S);
305}
306
307/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
308/// attempting to keep all loop-invariant and loop-computable values in a
309/// single base register.
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000310void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
Dan Gohman572645c2010-02-12 10:34:29 +0000311 SmallVector<const SCEV *, 4> Good;
312 SmallVector<const SCEV *, 4> Bad;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +0000313 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman572645c2010-02-12 10:34:29 +0000314 if (!Good.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000315 const SCEV *Sum = SE.getAddExpr(Good);
316 if (!Sum->isZero())
317 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000318 AM.HasBaseReg = true;
319 }
320 if (!Bad.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000321 const SCEV *Sum = SE.getAddExpr(Bad);
322 if (!Sum->isZero())
323 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000324 AM.HasBaseReg = true;
325 }
326}
327
328/// getNumRegs - Return the total number of register operands used by this
329/// formula. This does not include register uses implied by non-constant
330/// addrec strides.
331unsigned Formula::getNumRegs() const {
332 return !!ScaledReg + BaseRegs.size();
333}
334
335/// getType - Return the type of this formula, if it has one, or null
336/// otherwise. This type is meaningless except for the bit size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000337Type *Formula::getType() const {
Dan Gohman572645c2010-02-12 10:34:29 +0000338 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
339 ScaledReg ? ScaledReg->getType() :
340 AM.BaseGV ? AM.BaseGV->getType() :
341 0;
342}
343
Dan Gohman5ce6d052010-05-20 15:17:54 +0000344/// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
345void Formula::DeleteBaseReg(const SCEV *&S) {
346 if (&S != &BaseRegs.back())
347 std::swap(S, BaseRegs.back());
348 BaseRegs.pop_back();
349}
350
Dan Gohman572645c2010-02-12 10:34:29 +0000351/// referencesReg - Test if this formula references the given register.
352bool Formula::referencesReg(const SCEV *S) const {
353 return S == ScaledReg ||
354 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
355}
356
357/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
358/// which are used by uses other than the use with the given index.
359bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
360 const RegUseTracker &RegUses) const {
361 if (ScaledReg)
362 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
363 return true;
364 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
365 E = BaseRegs.end(); I != E; ++I)
366 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
367 return true;
368 return false;
369}
370
371void Formula::print(raw_ostream &OS) const {
372 bool First = true;
373 if (AM.BaseGV) {
374 if (!First) OS << " + "; else First = false;
375 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
376 }
377 if (AM.BaseOffs != 0) {
378 if (!First) OS << " + "; else First = false;
379 OS << AM.BaseOffs;
380 }
381 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
382 E = BaseRegs.end(); I != E; ++I) {
383 if (!First) OS << " + "; else First = false;
384 OS << "reg(" << **I << ')';
385 }
Dan Gohmanc4cfbaf2010-05-18 22:35:55 +0000386 if (AM.HasBaseReg && BaseRegs.empty()) {
387 if (!First) OS << " + "; else First = false;
388 OS << "**error: HasBaseReg**";
389 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
390 if (!First) OS << " + "; else First = false;
391 OS << "**error: !HasBaseReg**";
392 }
Dan Gohman572645c2010-02-12 10:34:29 +0000393 if (AM.Scale != 0) {
394 if (!First) OS << " + "; else First = false;
395 OS << AM.Scale << "*reg(";
396 if (ScaledReg)
397 OS << *ScaledReg;
398 else
399 OS << "<unknown>";
400 OS << ')';
401 }
Dan Gohmancca82142011-05-03 00:46:49 +0000402 if (UnfoldedOffset != 0) {
403 if (!First) OS << " + "; else First = false;
404 OS << "imm(" << UnfoldedOffset << ')';
405 }
Dan Gohman572645c2010-02-12 10:34:29 +0000406}
407
408void Formula::dump() const {
409 print(errs()); errs() << '\n';
410}
411
Dan Gohmanaae01f12010-02-19 19:32:49 +0000412/// isAddRecSExtable - Return true if the given addrec can be sign-extended
413/// without changing its value.
414static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000415 Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000416 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000417 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
418}
419
420/// isAddSExtable - Return true if the given add can be sign-extended
421/// without changing its value.
422static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000423 Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000424 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000425 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
426}
427
Dan Gohman473e6352010-06-24 16:45:11 +0000428/// isMulSExtable - Return true if the given mul can be sign-extended
Dan Gohmanaae01f12010-02-19 19:32:49 +0000429/// without changing its value.
Dan Gohman473e6352010-06-24 16:45:11 +0000430static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000431 Type *WideTy =
Dan Gohman473e6352010-06-24 16:45:11 +0000432 IntegerType::get(SE.getContext(),
433 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
434 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohmanaae01f12010-02-19 19:32:49 +0000435}
436
Dan Gohmanf09b7122010-02-19 19:35:48 +0000437/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
438/// and if the remainder is known to be zero, or null otherwise. If
439/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
440/// to Y, ignoring that the multiplication may overflow, which is useful when
441/// the result will be used in a context where the most significant bits are
442/// ignored.
443static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
444 ScalarEvolution &SE,
445 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000446 // Handle the trivial case, which works for any SCEV type.
447 if (LHS == RHS)
Dan Gohmandeff6212010-05-03 22:09:21 +0000448 return SE.getConstant(LHS->getType(), 1);
Dan Gohman572645c2010-02-12 10:34:29 +0000449
Dan Gohmand42819a2010-06-24 16:51:25 +0000450 // Handle a few RHS special cases.
451 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
452 if (RC) {
453 const APInt &RA = RC->getValue()->getValue();
454 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
455 // some folding.
456 if (RA.isAllOnesValue())
457 return SE.getMulExpr(LHS, RC);
458 // Handle x /s 1 as x.
459 if (RA == 1)
460 return LHS;
461 }
Dan Gohman572645c2010-02-12 10:34:29 +0000462
463 // Check for a division of a constant by a constant.
464 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000465 if (!RC)
466 return 0;
Dan Gohmand42819a2010-06-24 16:51:25 +0000467 const APInt &LA = C->getValue()->getValue();
468 const APInt &RA = RC->getValue()->getValue();
469 if (LA.srem(RA) != 0)
Dan Gohman572645c2010-02-12 10:34:29 +0000470 return 0;
Dan Gohmand42819a2010-06-24 16:51:25 +0000471 return SE.getConstant(LA.sdiv(RA));
Dan Gohman572645c2010-02-12 10:34:29 +0000472 }
473
Dan Gohmanaae01f12010-02-19 19:32:49 +0000474 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000475 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000476 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000477 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
478 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000479 if (!Step) return 0;
Dan Gohman694a15e2010-08-19 01:02:31 +0000480 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
481 IgnoreSignificantBits);
482 if (!Start) return 0;
Andrew Trick3228cc22011-03-14 16:50:06 +0000483 // FlagNW is independent of the start value, step direction, and is
484 // preserved with smaller magnitude steps.
485 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
486 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000487 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000488 return 0;
Dan Gohman572645c2010-02-12 10:34:29 +0000489 }
490
Dan Gohmanaae01f12010-02-19 19:32:49 +0000491 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000492 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000493 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
494 SmallVector<const SCEV *, 8> Ops;
495 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
496 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000497 const SCEV *Op = getExactSDiv(*I, RHS, SE,
498 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000499 if (!Op) return 0;
500 Ops.push_back(Op);
501 }
502 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000503 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000504 return 0;
Dan Gohman572645c2010-02-12 10:34:29 +0000505 }
506
507 // Check for a multiply operand that we can pull RHS out of.
Dan Gohman2ea09e02010-06-24 16:57:52 +0000508 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000509 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000510 SmallVector<const SCEV *, 4> Ops;
511 bool Found = false;
512 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
513 I != E; ++I) {
Dan Gohman47667442010-05-20 16:23:28 +0000514 const SCEV *S = *I;
Dan Gohman572645c2010-02-12 10:34:29 +0000515 if (!Found)
Dan Gohman47667442010-05-20 16:23:28 +0000516 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohmanf09b7122010-02-19 19:35:48 +0000517 IgnoreSignificantBits)) {
Dan Gohman47667442010-05-20 16:23:28 +0000518 S = Q;
Dan Gohman572645c2010-02-12 10:34:29 +0000519 Found = true;
Dan Gohman572645c2010-02-12 10:34:29 +0000520 }
Dan Gohman47667442010-05-20 16:23:28 +0000521 Ops.push_back(S);
Dan Gohman572645c2010-02-12 10:34:29 +0000522 }
523 return Found ? SE.getMulExpr(Ops) : 0;
524 }
Dan Gohman2ea09e02010-06-24 16:57:52 +0000525 return 0;
526 }
Dan Gohman572645c2010-02-12 10:34:29 +0000527
528 // Otherwise we don't know.
529 return 0;
530}
531
532/// ExtractImmediate - If S involves the addition of a constant integer value,
533/// return that integer value, and mutate S to point to a new SCEV with that
534/// value excluded.
535static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
536 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
537 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000538 S = SE.getConstant(C->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000539 return C->getValue()->getSExtValue();
540 }
541 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
542 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
543 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000544 if (Result != 0)
545 S = SE.getAddExpr(NewOps);
Dan Gohman572645c2010-02-12 10:34:29 +0000546 return Result;
547 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
548 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
549 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000550 if (Result != 0)
Andrew Trick3228cc22011-03-14 16:50:06 +0000551 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
552 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
553 SCEV::FlagAnyWrap);
Dan Gohman572645c2010-02-12 10:34:29 +0000554 return Result;
555 }
556 return 0;
557}
558
559/// ExtractSymbol - If S involves the addition of a GlobalValue address,
560/// return that symbol, and mutate S to point to a new SCEV with that
561/// value excluded.
562static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
563 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
564 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000565 S = SE.getConstant(GV->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000566 return GV;
567 }
568 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
569 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
570 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000571 if (Result)
572 S = SE.getAddExpr(NewOps);
Dan Gohman572645c2010-02-12 10:34:29 +0000573 return Result;
574 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
575 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
576 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
Dan Gohmane62d5882010-08-13 21:17:19 +0000577 if (Result)
Andrew Trick3228cc22011-03-14 16:50:06 +0000578 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
579 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
580 SCEV::FlagAnyWrap);
Dan Gohman572645c2010-02-12 10:34:29 +0000581 return Result;
582 }
583 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000584}
585
Dan Gohmanf284ce22009-02-18 00:08:39 +0000586/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000587/// specified value as an address.
588static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
589 bool isAddress = isa<LoadInst>(Inst);
590 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
591 if (SI->getOperand(1) == OperandVal)
592 isAddress = true;
593 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
594 // Addressing modes can also be folded into prefetches and a variety
595 // of intrinsics.
596 switch (II->getIntrinsicID()) {
597 default: break;
598 case Intrinsic::prefetch:
Dale Johannesen203af582008-12-05 21:47:27 +0000599 case Intrinsic::x86_sse_storeu_ps:
600 case Intrinsic::x86_sse2_storeu_pd:
601 case Intrinsic::x86_sse2_storeu_dq:
602 case Intrinsic::x86_sse2_storel_dq:
Gabor Greifad72e732010-06-30 09:15:28 +0000603 if (II->getArgOperand(0) == OperandVal)
Dale Johannesen203af582008-12-05 21:47:27 +0000604 isAddress = true;
605 break;
606 }
607 }
608 return isAddress;
609}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000610
Dan Gohman21e77222009-03-09 21:01:17 +0000611/// getAccessType - Return the type of the memory being accessed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000612static Type *getAccessType(const Instruction *Inst) {
613 Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000614 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000615 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000616 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
617 // Addressing modes can also be folded into prefetches and a variety
618 // of intrinsics.
619 switch (II->getIntrinsicID()) {
620 default: break;
621 case Intrinsic::x86_sse_storeu_ps:
622 case Intrinsic::x86_sse2_storeu_pd:
623 case Intrinsic::x86_sse2_storeu_dq:
624 case Intrinsic::x86_sse2_storel_dq:
Gabor Greifad72e732010-06-30 09:15:28 +0000625 AccessTy = II->getArgOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000626 break;
627 }
628 }
Dan Gohman572645c2010-02-12 10:34:29 +0000629
630 // All pointers have the same requirements, so canonicalize them to an
631 // arbitrary pointer type to minimize variation.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000632 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +0000633 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
634 PTy->getAddressSpace());
635
Dan Gohmana537bf82009-05-18 16:45:28 +0000636 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000637}
638
Dan Gohman572645c2010-02-12 10:34:29 +0000639/// DeleteTriviallyDeadInstructions - If any of the instructions is the
640/// specified set are trivially dead, delete them and see if this makes any of
641/// their operands subsequently dead.
642static bool
643DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
644 bool Changed = false;
645
646 while (!DeadInsts.empty()) {
Gabor Greiff097b592010-09-18 11:55:34 +0000647 Instruction *I = dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val());
Dan Gohman572645c2010-02-12 10:34:29 +0000648
649 if (I == 0 || !isInstructionTriviallyDead(I))
650 continue;
651
652 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
653 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
654 *OI = 0;
655 if (U->use_empty())
656 DeadInsts.push_back(U);
657 }
658
659 I->eraseFromParent();
660 Changed = true;
661 }
662
663 return Changed;
664}
665
Dan Gohman7979b722010-01-22 00:46:49 +0000666namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000667
Dan Gohman572645c2010-02-12 10:34:29 +0000668/// Cost - This class is used to measure and compare candidate formulae.
669class Cost {
670 /// TODO: Some of these could be merged. Also, a lexical ordering
671 /// isn't always optimal.
672 unsigned NumRegs;
673 unsigned AddRecCost;
674 unsigned NumIVMuls;
675 unsigned NumBaseAdds;
676 unsigned ImmCost;
677 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000678
Dan Gohman572645c2010-02-12 10:34:29 +0000679public:
680 Cost()
681 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
682 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000683
Dan Gohman572645c2010-02-12 10:34:29 +0000684 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000685
Dan Gohman572645c2010-02-12 10:34:29 +0000686 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000687
Andrew Trick7d11bd82011-09-26 23:11:04 +0000688#ifndef NDEBUG
689 // Once any of the metrics loses, they must all remain losers.
690 bool isValid() {
691 return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
692 | ImmCost | SetupCost) != ~0u)
693 || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
694 & ImmCost & SetupCost) == ~0u);
695 }
696#endif
697
698 bool isLoser() {
699 assert(isValid() && "invalid cost");
700 return NumRegs == ~0u;
701 }
702
Dan Gohman572645c2010-02-12 10:34:29 +0000703 void RateFormula(const Formula &F,
704 SmallPtrSet<const SCEV *, 16> &Regs,
705 const DenseSet<const SCEV *> &VisitedRegs,
706 const Loop *L,
707 const SmallVectorImpl<int64_t> &Offsets,
708 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000709
Dan Gohman572645c2010-02-12 10:34:29 +0000710 void print(raw_ostream &OS) const;
711 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000712
Dan Gohman572645c2010-02-12 10:34:29 +0000713private:
714 void RateRegister(const SCEV *Reg,
715 SmallPtrSet<const SCEV *, 16> &Regs,
716 const Loop *L,
717 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000718 void RatePrimaryRegister(const SCEV *Reg,
719 SmallPtrSet<const SCEV *, 16> &Regs,
720 const Loop *L,
721 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000722};
723
724}
725
726/// RateRegister - Tally up interesting quantities from the given register.
727void Cost::RateRegister(const SCEV *Reg,
728 SmallPtrSet<const SCEV *, 16> &Regs,
729 const Loop *L,
730 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000731 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
732 if (AR->getLoop() == L)
733 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000734
Andrew Trick0c01bc32011-09-29 01:33:38 +0000735 // If this is an addrec for another loop, don't second-guess its addrec phi
736 // nodes. LSR isn't currently smart enough to reason about more than one
737 // loop at a time. LSR has either already run on inner loops, will not run
738 // on other loops, and cannot be expected to change sibling loops. If the
739 // AddRec exists, consider it's register free and leave it alone. Otherwise,
740 // do not consider this formula at all.
741 // FIXME: why do we need to generate such fomulae?
742 else if (!EnableNested || L->contains(AR->getLoop()) ||
Dan Gohman9214b822010-02-13 02:06:02 +0000743 (!AR->getLoop()->contains(L) &&
744 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
745 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
Andrew Trick7d11bd82011-09-26 23:11:04 +0000746 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman9214b822010-02-13 02:06:02 +0000747 if (SE.isSCEVable(PN->getType()) &&
748 (SE.getEffectiveSCEVType(PN->getType()) ==
749 SE.getEffectiveSCEVType(AR->getType())) &&
750 SE.getSCEV(PN) == AR)
751 return;
Andrew Trick7d11bd82011-09-26 23:11:04 +0000752 }
Andrew Trick0c01bc32011-09-29 01:33:38 +0000753 if (!EnableNested) {
754 Loose();
755 return;
756 }
Dan Gohman9214b822010-02-13 02:06:02 +0000757 // If this isn't one of the addrecs that the loop already has, it
758 // would require a costly new phi and add. TODO: This isn't
759 // precisely modeled right now.
760 ++NumBaseAdds;
Andrew Trick7d11bd82011-09-26 23:11:04 +0000761 if (!Regs.count(AR->getStart())) {
Dan Gohman572645c2010-02-12 10:34:29 +0000762 RateRegister(AR->getStart(), Regs, L, SE, DT);
Andrew Trick7d11bd82011-09-26 23:11:04 +0000763 if (isLoser())
764 return;
765 }
Dan Gohman572645c2010-02-12 10:34:29 +0000766 }
Dan Gohman572645c2010-02-12 10:34:29 +0000767
Dan Gohman9214b822010-02-13 02:06:02 +0000768 // Add the step value register, if it needs one.
769 // TODO: The non-affine case isn't precisely modeled here.
Andrew Trick25b689e2011-09-26 23:35:25 +0000770 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
771 if (!Regs.count(AR->getOperand(1))) {
Dan Gohman9214b822010-02-13 02:06:02 +0000772 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Andrew Trick25b689e2011-09-26 23:35:25 +0000773 if (isLoser())
774 return;
775 }
776 }
Dan Gohman572645c2010-02-12 10:34:29 +0000777 }
Dan Gohman9214b822010-02-13 02:06:02 +0000778 ++NumRegs;
779
780 // Rough heuristic; favor registers which don't require extra setup
781 // instructions in the preheader.
782 if (!isa<SCEVUnknown>(Reg) &&
783 !isa<SCEVConstant>(Reg) &&
784 !(isa<SCEVAddRecExpr>(Reg) &&
785 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
786 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
787 ++SetupCost;
Dan Gohman23c3fde2010-10-07 23:41:58 +0000788
789 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
Dan Gohman17ead4f2010-11-17 21:23:15 +0000790 SE.hasComputableLoopEvolution(Reg, L);
Dan Gohman9214b822010-02-13 02:06:02 +0000791}
792
793/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
794/// before, rate it.
795void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000796 SmallPtrSet<const SCEV *, 16> &Regs,
797 const Loop *L,
798 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000799 if (Regs.insert(Reg))
800 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000801}
802
803void Cost::RateFormula(const Formula &F,
804 SmallPtrSet<const SCEV *, 16> &Regs,
805 const DenseSet<const SCEV *> &VisitedRegs,
806 const Loop *L,
807 const SmallVectorImpl<int64_t> &Offsets,
808 ScalarEvolution &SE, DominatorTree &DT) {
809 // Tally up the registers.
810 if (const SCEV *ScaledReg = F.ScaledReg) {
811 if (VisitedRegs.count(ScaledReg)) {
812 Loose();
813 return;
814 }
Dan Gohman9214b822010-02-13 02:06:02 +0000815 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Andrew Trick7d11bd82011-09-26 23:11:04 +0000816 if (isLoser())
817 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000818 }
819 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
820 E = F.BaseRegs.end(); I != E; ++I) {
821 const SCEV *BaseReg = *I;
822 if (VisitedRegs.count(BaseReg)) {
823 Loose();
824 return;
825 }
Dan Gohman9214b822010-02-13 02:06:02 +0000826 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Andrew Trick7d11bd82011-09-26 23:11:04 +0000827 if (isLoser())
828 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000829 }
830
Dan Gohmancca82142011-05-03 00:46:49 +0000831 // Determine how many (unfolded) adds we'll need inside the loop.
832 size_t NumBaseParts = F.BaseRegs.size() + (F.UnfoldedOffset != 0);
833 if (NumBaseParts > 1)
834 NumBaseAdds += NumBaseParts - 1;
Dan Gohman572645c2010-02-12 10:34:29 +0000835
836 // Tally up the non-zero immediates.
837 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
838 E = Offsets.end(); I != E; ++I) {
839 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
840 if (F.AM.BaseGV)
841 ImmCost += 64; // Handle symbolic values conservatively.
842 // TODO: This should probably be the pointer size.
843 else if (Offset != 0)
844 ImmCost += APInt(64, Offset, true).getMinSignedBits();
845 }
Andrew Trick7d11bd82011-09-26 23:11:04 +0000846 assert(isValid() && "invalid cost");
Dan Gohman572645c2010-02-12 10:34:29 +0000847}
848
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000849/// Loose - Set this cost to a losing value.
Dan Gohman572645c2010-02-12 10:34:29 +0000850void Cost::Loose() {
851 NumRegs = ~0u;
852 AddRecCost = ~0u;
853 NumIVMuls = ~0u;
854 NumBaseAdds = ~0u;
855 ImmCost = ~0u;
856 SetupCost = ~0u;
857}
858
859/// operator< - Choose the lower cost.
860bool Cost::operator<(const Cost &Other) const {
861 if (NumRegs != Other.NumRegs)
862 return NumRegs < Other.NumRegs;
863 if (AddRecCost != Other.AddRecCost)
864 return AddRecCost < Other.AddRecCost;
865 if (NumIVMuls != Other.NumIVMuls)
866 return NumIVMuls < Other.NumIVMuls;
867 if (NumBaseAdds != Other.NumBaseAdds)
868 return NumBaseAdds < Other.NumBaseAdds;
869 if (ImmCost != Other.ImmCost)
870 return ImmCost < Other.ImmCost;
871 if (SetupCost != Other.SetupCost)
872 return SetupCost < Other.SetupCost;
873 return false;
874}
875
876void Cost::print(raw_ostream &OS) const {
877 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
878 if (AddRecCost != 0)
879 OS << ", with addrec cost " << AddRecCost;
880 if (NumIVMuls != 0)
881 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
882 if (NumBaseAdds != 0)
883 OS << ", plus " << NumBaseAdds << " base add"
884 << (NumBaseAdds == 1 ? "" : "s");
885 if (ImmCost != 0)
886 OS << ", plus " << ImmCost << " imm cost";
887 if (SetupCost != 0)
888 OS << ", plus " << SetupCost << " setup cost";
889}
890
891void Cost::dump() const {
892 print(errs()); errs() << '\n';
893}
894
895namespace {
896
897/// LSRFixup - An operand value in an instruction which is to be replaced
898/// with some equivalent, possibly strength-reduced, replacement.
899struct LSRFixup {
900 /// UserInst - The instruction which will be updated.
901 Instruction *UserInst;
902
903 /// OperandValToReplace - The operand of the instruction which will
904 /// be replaced. The operand may be used more than once; every instance
905 /// will be replaced.
906 Value *OperandValToReplace;
907
Dan Gohman448db1c2010-04-07 22:27:08 +0000908 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman572645c2010-02-12 10:34:29 +0000909 /// induction variable, this variable is non-null and holds the loop
910 /// associated with the induction variable.
Dan Gohman448db1c2010-04-07 22:27:08 +0000911 PostIncLoopSet PostIncLoops;
Dan Gohman572645c2010-02-12 10:34:29 +0000912
913 /// LUIdx - The index of the LSRUse describing the expression which
914 /// this fixup needs, minus an offset (below).
915 size_t LUIdx;
916
917 /// Offset - A constant offset to be added to the LSRUse expression.
918 /// This allows multiple fixups to share the same LSRUse with different
919 /// offsets, for example in an unrolled loop.
920 int64_t Offset;
921
Dan Gohman448db1c2010-04-07 22:27:08 +0000922 bool isUseFullyOutsideLoop(const Loop *L) const;
923
Dan Gohman572645c2010-02-12 10:34:29 +0000924 LSRFixup();
925
926 void print(raw_ostream &OS) const;
927 void dump() const;
928};
929
930}
931
932LSRFixup::LSRFixup()
Dan Gohmanea507f52010-05-20 19:44:23 +0000933 : UserInst(0), OperandValToReplace(0), LUIdx(~size_t(0)), Offset(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +0000934
Dan Gohman448db1c2010-04-07 22:27:08 +0000935/// isUseFullyOutsideLoop - Test whether this fixup always uses its
936/// value outside of the given loop.
937bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
938 // PHI nodes use their value in their incoming blocks.
939 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
940 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
941 if (PN->getIncomingValue(i) == OperandValToReplace &&
942 L->contains(PN->getIncomingBlock(i)))
943 return false;
944 return true;
945 }
946
947 return !L->contains(UserInst);
948}
949
Dan Gohman572645c2010-02-12 10:34:29 +0000950void LSRFixup::print(raw_ostream &OS) const {
951 OS << "UserInst=";
952 // Store is common and interesting enough to be worth special-casing.
953 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
954 OS << "store ";
955 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
956 } else if (UserInst->getType()->isVoidTy())
957 OS << UserInst->getOpcodeName();
958 else
959 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
960
961 OS << ", OperandValToReplace=";
962 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
963
Dan Gohman448db1c2010-04-07 22:27:08 +0000964 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
965 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +0000966 OS << ", PostIncLoop=";
Dan Gohman448db1c2010-04-07 22:27:08 +0000967 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
Dan Gohman572645c2010-02-12 10:34:29 +0000968 }
969
970 if (LUIdx != ~size_t(0))
971 OS << ", LUIdx=" << LUIdx;
972
973 if (Offset != 0)
974 OS << ", Offset=" << Offset;
975}
976
977void LSRFixup::dump() const {
978 print(errs()); errs() << '\n';
979}
980
981namespace {
982
983/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
984/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
985struct UniquifierDenseMapInfo {
986 static SmallVector<const SCEV *, 2> getEmptyKey() {
987 SmallVector<const SCEV *, 2> V;
988 V.push_back(reinterpret_cast<const SCEV *>(-1));
989 return V;
990 }
991
992 static SmallVector<const SCEV *, 2> getTombstoneKey() {
993 SmallVector<const SCEV *, 2> V;
994 V.push_back(reinterpret_cast<const SCEV *>(-2));
995 return V;
996 }
997
998 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
999 unsigned Result = 0;
1000 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
1001 E = V.end(); I != E; ++I)
1002 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
1003 return Result;
1004 }
1005
1006 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
1007 const SmallVector<const SCEV *, 2> &RHS) {
1008 return LHS == RHS;
1009 }
1010};
1011
1012/// LSRUse - This class holds the state that LSR keeps for each use in
1013/// IVUsers, as well as uses invented by LSR itself. It includes information
1014/// about what kinds of things can be folded into the user, information about
1015/// the user itself, and information about how the use may be satisfied.
1016/// TODO: Represent multiple users of the same expression in common?
1017class LSRUse {
1018 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
1019
1020public:
1021 /// KindType - An enum for a kind of use, indicating what types of
1022 /// scaled and immediate operands it might support.
1023 enum KindType {
1024 Basic, ///< A normal use, with no folding.
1025 Special, ///< A special case of basic, allowing -1 scales.
1026 Address, ///< An address use; folding according to TargetLowering
1027 ICmpZero ///< An equality icmp with both operands folded into one.
1028 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +00001029 };
Dan Gohman572645c2010-02-12 10:34:29 +00001030
1031 KindType Kind;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001032 Type *AccessTy;
Dan Gohman572645c2010-02-12 10:34:29 +00001033
1034 SmallVector<int64_t, 8> Offsets;
1035 int64_t MinOffset;
1036 int64_t MaxOffset;
1037
1038 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
1039 /// LSRUse are outside of the loop, in which case some special-case heuristics
1040 /// may be used.
1041 bool AllFixupsOutsideLoop;
1042
Dan Gohmana9db1292010-07-15 20:24:58 +00001043 /// WidestFixupType - This records the widest use type for any fixup using
1044 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
1045 /// max fixup widths to be equivalent, because the narrower one may be relying
1046 /// on the implicit truncation to truncate away bogus bits.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001047 Type *WidestFixupType;
Dan Gohmana9db1292010-07-15 20:24:58 +00001048
Dan Gohman572645c2010-02-12 10:34:29 +00001049 /// Formulae - A list of ways to build a value that can satisfy this user.
1050 /// After the list is populated, one of these is selected heuristically and
1051 /// used to formulate a replacement for OperandValToReplace in UserInst.
1052 SmallVector<Formula, 12> Formulae;
1053
1054 /// Regs - The set of register candidates used by all formulae in this LSRUse.
1055 SmallPtrSet<const SCEV *, 4> Regs;
1056
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001057 LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
Dan Gohman572645c2010-02-12 10:34:29 +00001058 MinOffset(INT64_MAX),
1059 MaxOffset(INT64_MIN),
Dan Gohmana9db1292010-07-15 20:24:58 +00001060 AllFixupsOutsideLoop(true),
1061 WidestFixupType(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +00001062
Dan Gohmana2086b32010-05-19 23:43:12 +00001063 bool HasFormulaWithSameRegs(const Formula &F) const;
Dan Gohman454d26d2010-02-22 04:11:59 +00001064 bool InsertFormula(const Formula &F);
Dan Gohmand69d6282010-05-18 22:39:15 +00001065 void DeleteFormula(Formula &F);
Dan Gohmanb2df4332010-05-18 23:42:37 +00001066 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
Dan Gohman572645c2010-02-12 10:34:29 +00001067
Dan Gohman572645c2010-02-12 10:34:29 +00001068 void print(raw_ostream &OS) const;
1069 void dump() const;
1070};
1071
Dan Gohmanb6211712010-06-19 21:21:39 +00001072}
1073
Dan Gohmana2086b32010-05-19 23:43:12 +00001074/// HasFormula - Test whether this use as a formula which has the same
1075/// registers as the given formula.
1076bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1077 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1078 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1079 // Unstable sort by host order ok, because this is only used for uniquifying.
1080 std::sort(Key.begin(), Key.end());
1081 return Uniquifier.count(Key);
1082}
1083
Dan Gohman572645c2010-02-12 10:34:29 +00001084/// InsertFormula - If the given formula has not yet been inserted, add it to
1085/// the list, and return true. Return false otherwise.
Dan Gohman454d26d2010-02-22 04:11:59 +00001086bool LSRUse::InsertFormula(const Formula &F) {
Dan Gohman572645c2010-02-12 10:34:29 +00001087 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1088 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1089 // Unstable sort by host order ok, because this is only used for uniquifying.
1090 std::sort(Key.begin(), Key.end());
1091
1092 if (!Uniquifier.insert(Key).second)
1093 return false;
1094
1095 // Using a register to hold the value of 0 is not profitable.
1096 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1097 "Zero allocated in a scaled register!");
1098#ifndef NDEBUG
1099 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1100 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1101 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1102#endif
1103
1104 // Add the formula to the list.
1105 Formulae.push_back(F);
1106
1107 // Record registers now being used by this use.
1108 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1109 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1110
1111 return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001112}
1113
Dan Gohmand69d6282010-05-18 22:39:15 +00001114/// DeleteFormula - Remove the given formula from this use's list.
1115void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman5ce6d052010-05-20 15:17:54 +00001116 if (&F != &Formulae.back())
1117 std::swap(F, Formulae.back());
Dan Gohmand69d6282010-05-18 22:39:15 +00001118 Formulae.pop_back();
Dan Gohmana2086b32010-05-19 23:43:12 +00001119 assert(!Formulae.empty() && "LSRUse has no formulae left!");
Dan Gohmand69d6282010-05-18 22:39:15 +00001120}
1121
Dan Gohmanb2df4332010-05-18 23:42:37 +00001122/// RecomputeRegs - Recompute the Regs field, and update RegUses.
1123void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1124 // Now that we've filtered out some formulae, recompute the Regs set.
1125 SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1126 Regs.clear();
Dan Gohman402d4352010-05-20 20:33:18 +00001127 for (SmallVectorImpl<Formula>::const_iterator I = Formulae.begin(),
1128 E = Formulae.end(); I != E; ++I) {
1129 const Formula &F = *I;
Dan Gohmanb2df4332010-05-18 23:42:37 +00001130 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1131 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1132 }
1133
1134 // Update the RegTracker.
1135 for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1136 E = OldRegs.end(); I != E; ++I)
1137 if (!Regs.count(*I))
1138 RegUses.DropRegister(*I, LUIdx);
1139}
1140
Dan Gohman572645c2010-02-12 10:34:29 +00001141void LSRUse::print(raw_ostream &OS) const {
1142 OS << "LSR Use: Kind=";
1143 switch (Kind) {
1144 case Basic: OS << "Basic"; break;
1145 case Special: OS << "Special"; break;
1146 case ICmpZero: OS << "ICmpZero"; break;
1147 case Address:
1148 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +00001149 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +00001150 OS << "pointer"; // the full pointer type could be really verbose
1151 else
1152 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +00001153 }
1154
Dan Gohman572645c2010-02-12 10:34:29 +00001155 OS << ", Offsets={";
1156 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1157 E = Offsets.end(); I != E; ++I) {
1158 OS << *I;
Oscar Fuentesee56c422010-08-02 06:00:15 +00001159 if (llvm::next(I) != E)
Dan Gohman572645c2010-02-12 10:34:29 +00001160 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +00001161 }
Dan Gohman572645c2010-02-12 10:34:29 +00001162 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +00001163
Dan Gohman572645c2010-02-12 10:34:29 +00001164 if (AllFixupsOutsideLoop)
1165 OS << ", all-fixups-outside-loop";
Dan Gohmana9db1292010-07-15 20:24:58 +00001166
1167 if (WidestFixupType)
1168 OS << ", widest fixup type: " << *WidestFixupType;
Dan Gohman7979b722010-01-22 00:46:49 +00001169}
1170
Dan Gohman572645c2010-02-12 10:34:29 +00001171void LSRUse::dump() const {
1172 print(errs()); errs() << '\n';
1173}
Dan Gohman7979b722010-01-22 00:46:49 +00001174
Dan Gohman572645c2010-02-12 10:34:29 +00001175/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1176/// be completely folded into the user instruction at isel time. This includes
1177/// address-mode folding and special icmp tricks.
1178static bool isLegalUse(const TargetLowering::AddrMode &AM,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001179 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman572645c2010-02-12 10:34:29 +00001180 const TargetLowering *TLI) {
1181 switch (Kind) {
1182 case LSRUse::Address:
1183 // If we have low-level target information, ask the target if it can
1184 // completely fold this address.
1185 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1186
1187 // Otherwise, just guess that reg+reg addressing is legal.
1188 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1189
1190 case LSRUse::ICmpZero:
1191 // There's not even a target hook for querying whether it would be legal to
1192 // fold a GV into an ICmp.
1193 if (AM.BaseGV)
1194 return false;
1195
1196 // ICmp only has two operands; don't allow more than two non-trivial parts.
1197 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1198 return false;
1199
1200 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1201 // putting the scaled register in the other operand of the icmp.
1202 if (AM.Scale != 0 && AM.Scale != -1)
1203 return false;
1204
1205 // If we have low-level target information, ask the target if it can fold an
1206 // integer immediate on an icmp.
1207 if (AM.BaseOffs != 0) {
1208 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1209 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001210 }
Dan Gohman572645c2010-02-12 10:34:29 +00001211
1212 return true;
1213
1214 case LSRUse::Basic:
1215 // Only handle single-register values.
1216 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1217
1218 case LSRUse::Special:
1219 // Only handle -1 scales, or no scale.
1220 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001221 }
1222
Dan Gohman7979b722010-01-22 00:46:49 +00001223 return false;
1224}
1225
Dan Gohman572645c2010-02-12 10:34:29 +00001226static bool isLegalUse(TargetLowering::AddrMode AM,
1227 int64_t MinOffset, int64_t MaxOffset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001228 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman572645c2010-02-12 10:34:29 +00001229 const TargetLowering *TLI) {
1230 // Check for overflow.
1231 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1232 (MinOffset > 0))
1233 return false;
1234 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1235 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1236 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1237 // Check for overflow.
1238 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1239 (MaxOffset > 0))
1240 return false;
1241 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1242 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001243 }
Dan Gohman572645c2010-02-12 10:34:29 +00001244 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001245}
1246
Dan Gohman572645c2010-02-12 10:34:29 +00001247static bool isAlwaysFoldable(int64_t BaseOffs,
1248 GlobalValue *BaseGV,
1249 bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001250 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman454d26d2010-02-22 04:11:59 +00001251 const TargetLowering *TLI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001252 // Fast-path: zero is always foldable.
1253 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001254
Dan Gohman572645c2010-02-12 10:34:29 +00001255 // Conservatively, create an address with an immediate and a
1256 // base and a scale.
1257 TargetLowering::AddrMode AM;
1258 AM.BaseOffs = BaseOffs;
1259 AM.BaseGV = BaseGV;
1260 AM.HasBaseReg = HasBaseReg;
1261 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001262
Dan Gohmana2086b32010-05-19 23:43:12 +00001263 // Canonicalize a scale of 1 to a base register if the formula doesn't
1264 // already have a base register.
1265 if (!AM.HasBaseReg && AM.Scale == 1) {
1266 AM.Scale = 0;
1267 AM.HasBaseReg = true;
1268 }
1269
Dan Gohman572645c2010-02-12 10:34:29 +00001270 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001271}
1272
Dan Gohman572645c2010-02-12 10:34:29 +00001273static bool isAlwaysFoldable(const SCEV *S,
1274 int64_t MinOffset, int64_t MaxOffset,
1275 bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001276 LSRUse::KindType Kind, Type *AccessTy,
Dan Gohman572645c2010-02-12 10:34:29 +00001277 const TargetLowering *TLI,
1278 ScalarEvolution &SE) {
1279 // Fast-path: zero is always foldable.
1280 if (S->isZero()) return true;
1281
1282 // Conservatively, create an address with an immediate and a
1283 // base and a scale.
1284 int64_t BaseOffs = ExtractImmediate(S, SE);
1285 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1286
1287 // If there's anything else involved, it's not foldable.
1288 if (!S->isZero()) return false;
1289
1290 // Fast-path: zero is always foldable.
1291 if (BaseOffs == 0 && !BaseGV) return true;
1292
1293 // Conservatively, create an address with an immediate and a
1294 // base and a scale.
1295 TargetLowering::AddrMode AM;
1296 AM.BaseOffs = BaseOffs;
1297 AM.BaseGV = BaseGV;
1298 AM.HasBaseReg = HasBaseReg;
1299 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1300
1301 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001302}
1303
Dan Gohmanb6211712010-06-19 21:21:39 +00001304namespace {
1305
Dan Gohman1e3121c2010-06-19 21:29:59 +00001306/// UseMapDenseMapInfo - A DenseMapInfo implementation for holding
1307/// DenseMaps and DenseSets of pairs of const SCEV* and LSRUse::Kind.
1308struct UseMapDenseMapInfo {
1309 static std::pair<const SCEV *, LSRUse::KindType> getEmptyKey() {
1310 return std::make_pair(reinterpret_cast<const SCEV *>(-1), LSRUse::Basic);
1311 }
1312
1313 static std::pair<const SCEV *, LSRUse::KindType> getTombstoneKey() {
1314 return std::make_pair(reinterpret_cast<const SCEV *>(-2), LSRUse::Basic);
1315 }
1316
1317 static unsigned
1318 getHashValue(const std::pair<const SCEV *, LSRUse::KindType> &V) {
1319 unsigned Result = DenseMapInfo<const SCEV *>::getHashValue(V.first);
1320 Result ^= DenseMapInfo<unsigned>::getHashValue(unsigned(V.second));
1321 return Result;
1322 }
1323
1324 static bool isEqual(const std::pair<const SCEV *, LSRUse::KindType> &LHS,
1325 const std::pair<const SCEV *, LSRUse::KindType> &RHS) {
1326 return LHS == RHS;
1327 }
1328};
1329
Dan Gohman572645c2010-02-12 10:34:29 +00001330/// LSRInstance - This class holds state for the main loop strength reduction
1331/// logic.
1332class LSRInstance {
1333 IVUsers &IU;
1334 ScalarEvolution &SE;
1335 DominatorTree &DT;
Dan Gohmane5f76872010-04-09 22:07:05 +00001336 LoopInfo &LI;
Dan Gohman572645c2010-02-12 10:34:29 +00001337 const TargetLowering *const TLI;
1338 Loop *const L;
1339 bool Changed;
1340
1341 /// IVIncInsertPos - This is the insert position that the current loop's
1342 /// induction variable increment should be placed. In simple loops, this is
1343 /// the latch block's terminator. But in more complicated cases, this is a
1344 /// position which will dominate all the in-loop post-increment users.
1345 Instruction *IVIncInsertPos;
1346
1347 /// Factors - Interesting factors between use strides.
1348 SmallSetVector<int64_t, 8> Factors;
1349
1350 /// Types - Interesting use types, to facilitate truncation reuse.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001351 SmallSetVector<Type *, 4> Types;
Dan Gohman572645c2010-02-12 10:34:29 +00001352
1353 /// Fixups - The list of operands which are to be replaced.
1354 SmallVector<LSRFixup, 16> Fixups;
1355
1356 /// Uses - The list of interesting uses.
1357 SmallVector<LSRUse, 16> Uses;
1358
1359 /// RegUses - Track which uses use which register candidates.
1360 RegUseTracker RegUses;
1361
1362 void OptimizeShadowIV();
1363 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1364 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohmanc6519f92010-05-20 20:05:31 +00001365 void OptimizeLoopTermCond();
Dan Gohman572645c2010-02-12 10:34:29 +00001366
1367 void CollectInterestingTypesAndFactors();
1368 void CollectFixupsAndInitialFormulae();
1369
1370 LSRFixup &getNewFixup() {
1371 Fixups.push_back(LSRFixup());
1372 return Fixups.back();
1373 }
1374
1375 // Support for sharing of LSRUses between LSRFixups.
Dan Gohman1e3121c2010-06-19 21:29:59 +00001376 typedef DenseMap<std::pair<const SCEV *, LSRUse::KindType>,
1377 size_t,
1378 UseMapDenseMapInfo> UseMapTy;
Dan Gohman572645c2010-02-12 10:34:29 +00001379 UseMapTy UseMap;
1380
Dan Gohman191bd642010-09-01 01:45:53 +00001381 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001382 LSRUse::KindType Kind, Type *AccessTy);
Dan Gohman572645c2010-02-12 10:34:29 +00001383
1384 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1385 LSRUse::KindType Kind,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001386 Type *AccessTy);
Dan Gohman572645c2010-02-12 10:34:29 +00001387
Dan Gohmanc6897702010-10-07 23:33:43 +00001388 void DeleteUse(LSRUse &LU, size_t LUIdx);
Dan Gohman5ce6d052010-05-20 15:17:54 +00001389
Dan Gohman191bd642010-09-01 01:45:53 +00001390 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
Dan Gohmana2086b32010-05-19 23:43:12 +00001391
Dan Gohman572645c2010-02-12 10:34:29 +00001392public:
Dan Gohman454d26d2010-02-22 04:11:59 +00001393 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001394 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1395 void CountRegisters(const Formula &F, size_t LUIdx);
1396 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1397
1398 void CollectLoopInvariantFixupsAndFormulae();
1399
1400 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1401 unsigned Depth = 0);
1402 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1403 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1404 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1405 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1406 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1407 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1408 void GenerateCrossUseConstantOffsets();
1409 void GenerateAllReuseFormulae();
1410
1411 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmand079c302010-05-18 22:51:59 +00001412
1413 size_t EstimateSearchSpaceComplexity() const;
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00001414 void NarrowSearchSpaceByDetectingSupersets();
1415 void NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman4f7e18d2010-08-29 16:39:22 +00001416 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00001417 void NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohman572645c2010-02-12 10:34:29 +00001418 void NarrowSearchSpaceUsingHeuristics();
1419
1420 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1421 Cost &SolutionCost,
1422 SmallVectorImpl<const Formula *> &Workspace,
1423 const Cost &CurCost,
1424 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1425 DenseSet<const SCEV *> &VisitedRegs) const;
1426 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1427
Dan Gohmane5f76872010-04-09 22:07:05 +00001428 BasicBlock::iterator
1429 HoistInsertPosition(BasicBlock::iterator IP,
1430 const SmallVectorImpl<Instruction *> &Inputs) const;
1431 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1432 const LSRFixup &LF,
1433 const LSRUse &LU) const;
Dan Gohmand96eae82010-04-09 02:00:38 +00001434
Dan Gohman572645c2010-02-12 10:34:29 +00001435 Value *Expand(const LSRFixup &LF,
1436 const Formula &F,
Dan Gohman454d26d2010-02-22 04:11:59 +00001437 BasicBlock::iterator IP,
Dan Gohman572645c2010-02-12 10:34:29 +00001438 SCEVExpander &Rewriter,
Dan Gohman454d26d2010-02-22 04:11:59 +00001439 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001440 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1441 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001442 SCEVExpander &Rewriter,
1443 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001444 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001445 void Rewrite(const LSRFixup &LF,
1446 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00001447 SCEVExpander &Rewriter,
1448 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00001449 Pass *P) const;
1450 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1451 Pass *P);
1452
1453 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1454
1455 bool getChanged() const { return Changed; }
1456
1457 void print_factors_and_types(raw_ostream &OS) const;
1458 void print_fixups(raw_ostream &OS) const;
1459 void print_uses(raw_ostream &OS) const;
1460 void print(raw_ostream &OS) const;
1461 void dump() const;
1462};
1463
1464}
1465
1466/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001467/// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00001468void LSRInstance::OptimizeShadowIV() {
1469 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1470 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1471 return;
1472
1473 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1474 UI != E; /* empty */) {
1475 IVUsers::const_iterator CandidateUI = UI;
1476 ++UI;
1477 Instruction *ShadowUse = CandidateUI->getUser();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001478 Type *DestTy = NULL;
Andrew Trickc2c988e2011-07-21 01:05:01 +00001479 bool IsSigned = false;
Dan Gohman572645c2010-02-12 10:34:29 +00001480
1481 /* If shadow use is a int->float cast then insert a second IV
1482 to eliminate this cast.
1483
1484 for (unsigned i = 0; i < n; ++i)
1485 foo((double)i);
1486
1487 is transformed into
1488
1489 double d = 0.0;
1490 for (unsigned i = 0; i < n; ++i, ++d)
1491 foo(d);
1492 */
Andrew Trickc2c988e2011-07-21 01:05:01 +00001493 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1494 IsSigned = false;
Dan Gohman572645c2010-02-12 10:34:29 +00001495 DestTy = UCast->getDestTy();
Andrew Trickc2c988e2011-07-21 01:05:01 +00001496 }
1497 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1498 IsSigned = true;
Dan Gohman572645c2010-02-12 10:34:29 +00001499 DestTy = SCast->getDestTy();
Andrew Trickc2c988e2011-07-21 01:05:01 +00001500 }
Dan Gohman572645c2010-02-12 10:34:29 +00001501 if (!DestTy) continue;
1502
1503 if (TLI) {
1504 // If target does not support DestTy natively then do not apply
1505 // this transformation.
1506 EVT DVT = TLI->getValueType(DestTy);
1507 if (!TLI->isTypeLegal(DVT)) continue;
1508 }
1509
1510 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1511 if (!PH) continue;
1512 if (PH->getNumIncomingValues() != 2) continue;
1513
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001514 Type *SrcTy = PH->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00001515 int Mantissa = DestTy->getFPMantissaWidth();
1516 if (Mantissa == -1) continue;
1517 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1518 continue;
1519
1520 unsigned Entry, Latch;
1521 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1522 Entry = 0;
1523 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001524 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001525 Entry = 1;
1526 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001527 }
Dan Gohman7979b722010-01-22 00:46:49 +00001528
Dan Gohman572645c2010-02-12 10:34:29 +00001529 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1530 if (!Init) continue;
Andrew Trickc2c988e2011-07-21 01:05:01 +00001531 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
Andrew Trickc205a092011-07-21 01:45:54 +00001532 (double)Init->getSExtValue() :
1533 (double)Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001534
Dan Gohman572645c2010-02-12 10:34:29 +00001535 BinaryOperator *Incr =
1536 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1537 if (!Incr) continue;
1538 if (Incr->getOpcode() != Instruction::Add
1539 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001540 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001541
Dan Gohman572645c2010-02-12 10:34:29 +00001542 /* Initialize new IV, double d = 0.0 in above example. */
1543 ConstantInt *C = NULL;
1544 if (Incr->getOperand(0) == PH)
1545 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1546 else if (Incr->getOperand(1) == PH)
1547 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001548 else
Dan Gohman7979b722010-01-22 00:46:49 +00001549 continue;
1550
Dan Gohman572645c2010-02-12 10:34:29 +00001551 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001552
Dan Gohman572645c2010-02-12 10:34:29 +00001553 // Ignore negative constants, as the code below doesn't handle them
1554 // correctly. TODO: Remove this restriction.
1555 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001556
Dan Gohman572645c2010-02-12 10:34:29 +00001557 /* Add new PHINode. */
Jay Foad3ecfc862011-03-30 11:28:46 +00001558 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001559
Dan Gohman572645c2010-02-12 10:34:29 +00001560 /* create new increment. '++d' in above example. */
1561 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1562 BinaryOperator *NewIncr =
1563 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1564 Instruction::FAdd : Instruction::FSub,
1565 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001566
Dan Gohman572645c2010-02-12 10:34:29 +00001567 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1568 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001569
Dan Gohman572645c2010-02-12 10:34:29 +00001570 /* Remove cast operation */
1571 ShadowUse->replaceAllUsesWith(NewPH);
1572 ShadowUse->eraseFromParent();
Dan Gohmanc6519f92010-05-20 20:05:31 +00001573 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00001574 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001575 }
1576}
1577
1578/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1579/// set the IV user and stride information and return true, otherwise return
1580/// false.
Dan Gohmanea507f52010-05-20 19:44:23 +00001581bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Dan Gohman572645c2010-02-12 10:34:29 +00001582 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1583 if (UI->getUser() == Cond) {
1584 // NOTE: we could handle setcc instructions with multiple uses here, but
1585 // InstCombine does it as well for simple uses, it's not clear that it
1586 // occurs enough in real life to handle.
1587 CondUse = UI;
1588 return true;
1589 }
Dan Gohman7979b722010-01-22 00:46:49 +00001590 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001591}
1592
Dan Gohman7979b722010-01-22 00:46:49 +00001593/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1594/// a max computation.
1595///
1596/// This is a narrow solution to a specific, but acute, problem. For loops
1597/// like this:
1598///
1599/// i = 0;
1600/// do {
1601/// p[i] = 0.0;
1602/// } while (++i < n);
1603///
1604/// the trip count isn't just 'n', because 'n' might not be positive. And
1605/// unfortunately this can come up even for loops where the user didn't use
1606/// a C do-while loop. For example, seemingly well-behaved top-test loops
1607/// will commonly be lowered like this:
1608//
1609/// if (n > 0) {
1610/// i = 0;
1611/// do {
1612/// p[i] = 0.0;
1613/// } while (++i < n);
1614/// }
1615///
1616/// and then it's possible for subsequent optimization to obscure the if
1617/// test in such a way that indvars can't find it.
1618///
1619/// When indvars can't find the if test in loops like this, it creates a
1620/// max expression, which allows it to give the loop a canonical
1621/// induction variable:
1622///
1623/// i = 0;
1624/// max = n < 1 ? 1 : n;
1625/// do {
1626/// p[i] = 0.0;
1627/// } while (++i != max);
1628///
1629/// Canonical induction variables are necessary because the loop passes
1630/// are designed around them. The most obvious example of this is the
1631/// LoopInfo analysis, which doesn't remember trip count values. It
1632/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001633/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001634/// the loop has a canonical induction variable.
1635///
1636/// However, when it comes time to generate code, the maximum operation
1637/// can be quite costly, especially if it's inside of an outer loop.
1638///
1639/// This function solves this problem by detecting this type of loop and
1640/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1641/// the instructions for the maximum computation.
1642///
Dan Gohman572645c2010-02-12 10:34:29 +00001643ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001644 // Check that the loop matches the pattern we're looking for.
1645 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1646 Cond->getPredicate() != CmpInst::ICMP_NE)
1647 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001648
Dan Gohman7979b722010-01-22 00:46:49 +00001649 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1650 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001651
Dan Gohman572645c2010-02-12 10:34:29 +00001652 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001653 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1654 return Cond;
Dan Gohmandeff6212010-05-03 22:09:21 +00001655 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001656
Dan Gohman7979b722010-01-22 00:46:49 +00001657 // Add one to the backedge-taken count to get the trip count.
Dan Gohman4065f602010-08-16 15:39:27 +00001658 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
Dan Gohman1d367982010-04-24 03:13:44 +00001659 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001660
Dan Gohman1d367982010-04-24 03:13:44 +00001661 // Check for a max calculation that matches the pattern. There's no check
1662 // for ICMP_ULE here because the comparison would be with zero, which
1663 // isn't interesting.
1664 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1665 const SCEVNAryExpr *Max = 0;
1666 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1667 Pred = ICmpInst::ICMP_SLE;
1668 Max = S;
1669 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1670 Pred = ICmpInst::ICMP_SLT;
1671 Max = S;
1672 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1673 Pred = ICmpInst::ICMP_ULT;
1674 Max = U;
1675 } else {
1676 // No match; bail.
Dan Gohman7979b722010-01-22 00:46:49 +00001677 return Cond;
Dan Gohman1d367982010-04-24 03:13:44 +00001678 }
Dan Gohman7979b722010-01-22 00:46:49 +00001679
1680 // To handle a max with more than two operands, this optimization would
1681 // require additional checking and setup.
1682 if (Max->getNumOperands() != 2)
1683 return Cond;
1684
1685 const SCEV *MaxLHS = Max->getOperand(0);
1686 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman1d367982010-04-24 03:13:44 +00001687
1688 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1689 // for a comparison with 1. For <= and >=, a comparison with zero.
1690 if (!MaxLHS ||
1691 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1692 return Cond;
1693
Dan Gohman7979b722010-01-22 00:46:49 +00001694 // Check the relevant induction variable for conformance to
1695 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001696 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001697 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1698 if (!AR || !AR->isAffine() ||
1699 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001700 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001701 return Cond;
1702
1703 assert(AR->getLoop() == L &&
1704 "Loop condition operand is an addrec in a different loop!");
1705
1706 // Check the right operand of the select, and remember it, as it will
1707 // be used in the new comparison instruction.
1708 Value *NewRHS = 0;
Dan Gohman1d367982010-04-24 03:13:44 +00001709 if (ICmpInst::isTrueWhenEqual(Pred)) {
1710 // Look for n+1, and grab n.
1711 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1712 if (isa<ConstantInt>(BO->getOperand(1)) &&
1713 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1714 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1715 NewRHS = BO->getOperand(0);
1716 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1717 if (isa<ConstantInt>(BO->getOperand(1)) &&
1718 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1719 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1720 NewRHS = BO->getOperand(0);
1721 if (!NewRHS)
1722 return Cond;
1723 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001724 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001725 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001726 NewRHS = Sel->getOperand(2);
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001727 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
1728 NewRHS = SU->getValue();
Dan Gohman1d367982010-04-24 03:13:44 +00001729 else
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001730 // Max doesn't match expected pattern.
1731 return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001732
1733 // Determine the new comparison opcode. It may be signed or unsigned,
1734 // and the original comparison may be either equality or inequality.
Dan Gohman7979b722010-01-22 00:46:49 +00001735 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1736 Pred = CmpInst::getInversePredicate(Pred);
1737
1738 // Ok, everything looks ok to change the condition into an SLT or SGE and
1739 // delete the max calculation.
1740 ICmpInst *NewCond =
1741 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1742
1743 // Delete the max calculation instructions.
1744 Cond->replaceAllUsesWith(NewCond);
1745 CondUse->setUser(NewCond);
1746 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1747 Cond->eraseFromParent();
1748 Sel->eraseFromParent();
1749 if (Cmp->use_empty())
1750 Cmp->eraseFromParent();
1751 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001752}
1753
Jim Grosbach56a1f802009-11-17 17:53:56 +00001754/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001755/// postinc iv when possible.
Dan Gohmanc6519f92010-05-20 20:05:31 +00001756void
Dan Gohman572645c2010-02-12 10:34:29 +00001757LSRInstance::OptimizeLoopTermCond() {
1758 SmallPtrSet<Instruction *, 4> PostIncs;
1759
Evan Cheng586f69a2009-11-12 07:35:05 +00001760 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001761 SmallVector<BasicBlock*, 8> ExitingBlocks;
1762 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001763
Evan Cheng076e0852009-11-17 18:10:11 +00001764 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1765 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001766
Dan Gohman572645c2010-02-12 10:34:29 +00001767 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001768 // can, we want to change it to use a post-incremented version of its
1769 // induction variable, to allow coalescing the live ranges for the IV into
1770 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001771
Evan Cheng076e0852009-11-17 18:10:11 +00001772 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1773 if (!TermBr)
1774 continue;
1775 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1776 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1777 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001778
Evan Cheng076e0852009-11-17 18:10:11 +00001779 // Search IVUsesByStride to find Cond's IVUse if there is one.
1780 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001781 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001782 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001783 continue;
1784
Evan Cheng076e0852009-11-17 18:10:11 +00001785 // If the trip count is computed in terms of a max (due to ScalarEvolution
1786 // being unable to find a sufficient guard, for example), change the loop
1787 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001788 // One consequence of doing this now is that it disrupts the count-down
1789 // optimization. That's not always a bad thing though, because in such
1790 // cases it may still be worthwhile to avoid a max.
1791 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001792
Dan Gohman572645c2010-02-12 10:34:29 +00001793 // If this exiting block dominates the latch block, it may also use
1794 // the post-inc value if it won't be shared with other uses.
1795 // Check for dominance.
1796 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001797 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001798
Dan Gohman572645c2010-02-12 10:34:29 +00001799 // Conservatively avoid trying to use the post-inc value in non-latch
1800 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001801 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001802 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1803 // Test if the use is reachable from the exiting block. This dominator
1804 // query is a conservative approximation of reachability.
1805 if (&*UI != CondUse &&
1806 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1807 // Conservatively assume there may be reuse if the quotient of their
1808 // strides could be a legal scale.
Dan Gohmanc0564542010-04-19 21:48:58 +00001809 const SCEV *A = IU.getStride(*CondUse, L);
1810 const SCEV *B = IU.getStride(*UI, L);
Dan Gohman448db1c2010-04-07 22:27:08 +00001811 if (!A || !B) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001812 if (SE.getTypeSizeInBits(A->getType()) !=
1813 SE.getTypeSizeInBits(B->getType())) {
1814 if (SE.getTypeSizeInBits(A->getType()) >
1815 SE.getTypeSizeInBits(B->getType()))
1816 B = SE.getSignExtendExpr(B, A->getType());
1817 else
1818 A = SE.getSignExtendExpr(A, B->getType());
1819 }
1820 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001821 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00001822 const ConstantInt *C = D->getValue();
Dan Gohman572645c2010-02-12 10:34:29 +00001823 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001824 if (C->isOne() || C->isAllOnesValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001825 goto decline_post_inc;
1826 // Avoid weird situations.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001827 if (C->getValue().getMinSignedBits() >= 64 ||
1828 C->getValue().isMinSignedValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001829 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001830 // Without TLI, assume that any stride might be valid, and so any
1831 // use might be shared.
1832 if (!TLI)
1833 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001834 // Check for possible scaled-address reuse.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001835 Type *AccessTy = getAccessType(UI->getUser());
Dan Gohman572645c2010-02-12 10:34:29 +00001836 TargetLowering::AddrMode AM;
Dan Gohman9f383eb2010-05-20 22:25:20 +00001837 AM.Scale = C->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001838 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001839 goto decline_post_inc;
1840 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001841 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001842 goto decline_post_inc;
1843 }
1844 }
1845
David Greene63c94632009-12-23 22:58:38 +00001846 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001847 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001848
1849 // It's possible for the setcc instruction to be anywhere in the loop, and
1850 // possible for it to have multiple users. If it is not immediately before
1851 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001852 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1853 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001854 Cond->moveBefore(TermBr);
1855 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001856 // Clone the terminating condition and insert into the loopend.
1857 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001858 Cond = cast<ICmpInst>(Cond->clone());
1859 Cond->setName(L->getHeader()->getName() + ".termcond");
1860 ExitingBlock->getInstList().insert(TermBr, Cond);
1861
1862 // Clone the IVUse, as the old use still exists!
Andrew Trick4417e532011-06-21 15:43:52 +00001863 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman572645c2010-02-12 10:34:29 +00001864 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001865 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001866 }
1867
Evan Cheng076e0852009-11-17 18:10:11 +00001868 // If we get to here, we know that we can transform the setcc instruction to
1869 // use the post-incremented version of the IV, allowing us to coalesce the
1870 // live ranges for the IV correctly.
Dan Gohman448db1c2010-04-07 22:27:08 +00001871 CondUse->transformToPostInc(L);
Evan Cheng076e0852009-11-17 18:10:11 +00001872 Changed = true;
1873
Dan Gohman572645c2010-02-12 10:34:29 +00001874 PostIncs.insert(Cond);
1875 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001876 }
Dan Gohman572645c2010-02-12 10:34:29 +00001877
1878 // Determine an insertion point for the loop induction variable increment. It
1879 // must dominate all the post-inc comparisons we just set up, and it must
1880 // dominate the loop latch edge.
1881 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1882 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1883 E = PostIncs.end(); I != E; ++I) {
1884 BasicBlock *BB =
1885 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1886 (*I)->getParent());
1887 if (BB == (*I)->getParent())
1888 IVIncInsertPos = *I;
1889 else if (BB != IVIncInsertPos->getParent())
1890 IVIncInsertPos = BB->getTerminator();
1891 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001892}
1893
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001894/// reconcileNewOffset - Determine if the given use can accommodate a fixup
Dan Gohman76c315a2010-05-20 20:52:00 +00001895/// at the given offset and other details. If so, update the use and
1896/// return true.
Dan Gohman572645c2010-02-12 10:34:29 +00001897bool
Dan Gohman191bd642010-09-01 01:45:53 +00001898LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001899 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman191bd642010-09-01 01:45:53 +00001900 int64_t NewMinOffset = LU.MinOffset;
1901 int64_t NewMaxOffset = LU.MaxOffset;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001902 Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001903
Dan Gohman572645c2010-02-12 10:34:29 +00001904 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1905 // something conservative, however this can pessimize in the case that one of
1906 // the uses will have all its uses outside the loop, for example.
1907 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001908 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001909 // Conservatively assume HasBaseReg is true for now.
Dan Gohman191bd642010-09-01 01:45:53 +00001910 if (NewOffset < LU.MinOffset) {
1911 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001912 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001913 return false;
Dan Gohman191bd642010-09-01 01:45:53 +00001914 NewMinOffset = NewOffset;
1915 } else if (NewOffset > LU.MaxOffset) {
1916 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001917 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001918 return false;
Dan Gohman191bd642010-09-01 01:45:53 +00001919 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001920 }
Dan Gohman572645c2010-02-12 10:34:29 +00001921 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman74e5ef02010-06-19 21:30:18 +00001922 // TODO: Be less conservative when the type is similar and can use the same
1923 // addressing modes.
Dan Gohman572645c2010-02-12 10:34:29 +00001924 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
Dan Gohman191bd642010-09-01 01:45:53 +00001925 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001926
Dan Gohman572645c2010-02-12 10:34:29 +00001927 // Update the use.
Dan Gohman191bd642010-09-01 01:45:53 +00001928 LU.MinOffset = NewMinOffset;
1929 LU.MaxOffset = NewMaxOffset;
1930 LU.AccessTy = NewAccessTy;
1931 if (NewOffset != LU.Offsets.back())
1932 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001933 return true;
1934}
1935
Dan Gohman572645c2010-02-12 10:34:29 +00001936/// getUse - Return an LSRUse index and an offset value for a fixup which
1937/// needs the given expression, with the given kind and optional access type.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001938/// Either reuse an existing use or create a new one, as needed.
Dan Gohman572645c2010-02-12 10:34:29 +00001939std::pair<size_t, int64_t>
1940LSRInstance::getUse(const SCEV *&Expr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001941 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman572645c2010-02-12 10:34:29 +00001942 const SCEV *Copy = Expr;
1943 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001944
Dan Gohman572645c2010-02-12 10:34:29 +00001945 // Basic uses can't accept any offset, for example.
Dan Gohman454d26d2010-02-22 04:11:59 +00001946 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
Dan Gohman572645c2010-02-12 10:34:29 +00001947 Expr = Copy;
1948 Offset = 0;
1949 }
1950
1951 std::pair<UseMapTy::iterator, bool> P =
Dan Gohman1e3121c2010-06-19 21:29:59 +00001952 UseMap.insert(std::make_pair(std::make_pair(Expr, Kind), 0));
Dan Gohman572645c2010-02-12 10:34:29 +00001953 if (!P.second) {
1954 // A use already existed with this base.
1955 size_t LUIdx = P.first->second;
1956 LSRUse &LU = Uses[LUIdx];
Dan Gohman191bd642010-09-01 01:45:53 +00001957 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001958 // Reuse this use.
1959 return std::make_pair(LUIdx, Offset);
1960 }
1961
1962 // Create a new use.
1963 size_t LUIdx = Uses.size();
1964 P.first->second = LUIdx;
1965 Uses.push_back(LSRUse(Kind, AccessTy));
1966 LSRUse &LU = Uses[LUIdx];
1967
Dan Gohman191bd642010-09-01 01:45:53 +00001968 // We don't need to track redundant offsets, but we don't need to go out
1969 // of our way here to avoid them.
1970 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1971 LU.Offsets.push_back(Offset);
1972
Dan Gohman572645c2010-02-12 10:34:29 +00001973 LU.MinOffset = Offset;
1974 LU.MaxOffset = Offset;
1975 return std::make_pair(LUIdx, Offset);
1976}
1977
Dan Gohman5ce6d052010-05-20 15:17:54 +00001978/// DeleteUse - Delete the given use from the Uses list.
Dan Gohmanc6897702010-10-07 23:33:43 +00001979void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
Dan Gohman191bd642010-09-01 01:45:53 +00001980 if (&LU != &Uses.back())
Dan Gohman5ce6d052010-05-20 15:17:54 +00001981 std::swap(LU, Uses.back());
1982 Uses.pop_back();
Dan Gohmanc6897702010-10-07 23:33:43 +00001983
1984 // Update RegUses.
1985 RegUses.SwapAndDropUse(LUIdx, Uses.size());
Dan Gohman5ce6d052010-05-20 15:17:54 +00001986}
1987
Dan Gohmana2086b32010-05-19 23:43:12 +00001988/// FindUseWithFormula - Look for a use distinct from OrigLU which is has
1989/// a formula that has the same registers as the given formula.
1990LSRUse *
1991LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
Dan Gohman191bd642010-09-01 01:45:53 +00001992 const LSRUse &OrigLU) {
1993 // Search all uses for the formula. This could be more clever.
Dan Gohmana2086b32010-05-19 23:43:12 +00001994 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
1995 LSRUse &LU = Uses[LUIdx];
Dan Gohman6a832712010-08-29 15:27:08 +00001996 // Check whether this use is close enough to OrigLU, to see whether it's
1997 // worthwhile looking through its formulae.
1998 // Ignore ICmpZero uses because they may contain formulae generated by
1999 // GenerateICmpZeroScales, in which case adding fixup offsets may
2000 // be invalid.
Dan Gohmana2086b32010-05-19 23:43:12 +00002001 if (&LU != &OrigLU &&
2002 LU.Kind != LSRUse::ICmpZero &&
2003 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
Dan Gohmana9db1292010-07-15 20:24:58 +00002004 LU.WidestFixupType == OrigLU.WidestFixupType &&
Dan Gohmana2086b32010-05-19 23:43:12 +00002005 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohman6a832712010-08-29 15:27:08 +00002006 // Scan through this use's formulae.
Dan Gohman402d4352010-05-20 20:33:18 +00002007 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2008 E = LU.Formulae.end(); I != E; ++I) {
2009 const Formula &F = *I;
Dan Gohman6a832712010-08-29 15:27:08 +00002010 // Check to see if this formula has the same registers and symbols
2011 // as OrigF.
Dan Gohmana2086b32010-05-19 23:43:12 +00002012 if (F.BaseRegs == OrigF.BaseRegs &&
2013 F.ScaledReg == OrigF.ScaledReg &&
2014 F.AM.BaseGV == OrigF.AM.BaseGV &&
Dan Gohmancca82142011-05-03 00:46:49 +00002015 F.AM.Scale == OrigF.AM.Scale &&
2016 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
Dan Gohman191bd642010-09-01 01:45:53 +00002017 if (F.AM.BaseOffs == 0)
Dan Gohmana2086b32010-05-19 23:43:12 +00002018 return &LU;
Dan Gohman6a832712010-08-29 15:27:08 +00002019 // This is the formula where all the registers and symbols matched;
2020 // there aren't going to be any others. Since we declined it, we
2021 // can skip the rest of the formulae and procede to the next LSRUse.
Dan Gohmana2086b32010-05-19 23:43:12 +00002022 break;
2023 }
2024 }
2025 }
2026 }
2027
Dan Gohman6a832712010-08-29 15:27:08 +00002028 // Nothing looked good.
Dan Gohmana2086b32010-05-19 23:43:12 +00002029 return 0;
2030}
2031
Dan Gohman572645c2010-02-12 10:34:29 +00002032void LSRInstance::CollectInterestingTypesAndFactors() {
2033 SmallSetVector<const SCEV *, 4> Strides;
2034
Dan Gohman1b7bf182010-02-19 00:05:23 +00002035 // Collect interesting types and strides.
Dan Gohman448db1c2010-04-07 22:27:08 +00002036 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00002037 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohmanc0564542010-04-19 21:48:58 +00002038 const SCEV *Expr = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00002039
2040 // Collect interesting types.
Dan Gohman448db1c2010-04-07 22:27:08 +00002041 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman572645c2010-02-12 10:34:29 +00002042
Dan Gohman448db1c2010-04-07 22:27:08 +00002043 // Add strides for mentioned loops.
2044 Worklist.push_back(Expr);
2045 do {
2046 const SCEV *S = Worklist.pop_back_val();
2047 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2048 Strides.insert(AR->getStepRecurrence(SE));
2049 Worklist.push_back(AR->getStart());
2050 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00002051 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohman448db1c2010-04-07 22:27:08 +00002052 }
2053 } while (!Worklist.empty());
Dan Gohman1b7bf182010-02-19 00:05:23 +00002054 }
2055
2056 // Compute interesting factors from the set of interesting strides.
2057 for (SmallSetVector<const SCEV *, 4>::const_iterator
2058 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00002059 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Oscar Fuentesee56c422010-08-02 06:00:15 +00002060 llvm::next(I); NewStrideIter != E; ++NewStrideIter) {
Dan Gohman1b7bf182010-02-19 00:05:23 +00002061 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00002062 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00002063
2064 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2065 SE.getTypeSizeInBits(NewStride->getType())) {
2066 if (SE.getTypeSizeInBits(OldStride->getType()) >
2067 SE.getTypeSizeInBits(NewStride->getType()))
2068 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2069 else
2070 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2071 }
2072 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00002073 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2074 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00002075 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2076 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2077 } else if (const SCEVConstant *Factor =
Dan Gohman454d26d2010-02-22 04:11:59 +00002078 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2079 NewStride,
Dan Gohmanf09b7122010-02-19 19:35:48 +00002080 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00002081 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2082 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2083 }
2084 }
Dan Gohman572645c2010-02-12 10:34:29 +00002085
2086 // If all uses use the same type, don't bother looking for truncation-based
2087 // reuse.
2088 if (Types.size() == 1)
2089 Types.clear();
2090
2091 DEBUG(print_factors_and_types(dbgs()));
2092}
2093
2094void LSRInstance::CollectFixupsAndInitialFormulae() {
2095 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2096 // Record the uses.
2097 LSRFixup &LF = getNewFixup();
2098 LF.UserInst = UI->getUser();
2099 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohman448db1c2010-04-07 22:27:08 +00002100 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman572645c2010-02-12 10:34:29 +00002101
2102 LSRUse::KindType Kind = LSRUse::Basic;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002103 Type *AccessTy = 0;
Dan Gohman572645c2010-02-12 10:34:29 +00002104 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2105 Kind = LSRUse::Address;
2106 AccessTy = getAccessType(LF.UserInst);
2107 }
2108
Dan Gohmanc0564542010-04-19 21:48:58 +00002109 const SCEV *S = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00002110
2111 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2112 // (N - i == 0), and this allows (N - i) to be the expression that we work
2113 // with rather than just N or i, so we can consider the register
2114 // requirements for both N and i at the same time. Limiting this code to
2115 // equality icmps is not a problem because all interesting loops use
2116 // equality icmps, thanks to IndVarSimplify.
2117 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2118 if (CI->isEquality()) {
2119 // Swap the operands if needed to put the OperandValToReplace on the
2120 // left, for consistency.
2121 Value *NV = CI->getOperand(1);
2122 if (NV == LF.OperandValToReplace) {
2123 CI->setOperand(1, CI->getOperand(0));
2124 CI->setOperand(0, NV);
Dan Gohmanf182b232010-05-20 19:26:52 +00002125 NV = CI->getOperand(1);
Dan Gohman9da1bf42010-05-20 19:16:03 +00002126 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002127 }
2128
2129 // x == y --> x - y == 0
2130 const SCEV *N = SE.getSCEV(NV);
Dan Gohman17ead4f2010-11-17 21:23:15 +00002131 if (SE.isLoopInvariant(N, L)) {
Dan Gohman673968a2011-05-18 21:02:18 +00002132 // S is normalized, so normalize N before folding it into S
2133 // to keep the result normalized.
2134 N = TransformForPostIncUse(Normalize, N, CI, 0,
2135 LF.PostIncLoops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00002136 Kind = LSRUse::ICmpZero;
2137 S = SE.getMinusSCEV(N, S);
2138 }
2139
2140 // -1 and the negations of all interesting strides (except the negation
2141 // of -1) are now also interesting.
2142 for (size_t i = 0, e = Factors.size(); i != e; ++i)
2143 if (Factors[i] != -1)
2144 Factors.insert(-(uint64_t)Factors[i]);
2145 Factors.insert(-1);
2146 }
2147
2148 // Set up the initial formula for this use.
2149 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
2150 LF.LUIdx = P.first;
2151 LF.Offset = P.second;
2152 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002153 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohmana9db1292010-07-15 20:24:58 +00002154 if (!LU.WidestFixupType ||
2155 SE.getTypeSizeInBits(LU.WidestFixupType) <
2156 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2157 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002158
2159 // If this is the first use of this LSRUse, give it a formula.
2160 if (LU.Formulae.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002161 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00002162 CountRegisters(LU.Formulae.back(), LF.LUIdx);
2163 }
2164 }
2165
2166 DEBUG(print_fixups(dbgs()));
2167}
2168
Dan Gohman76c315a2010-05-20 20:52:00 +00002169/// InsertInitialFormula - Insert a formula for the given expression into
2170/// the given use, separating out loop-variant portions from loop-invariant
2171/// and loop-computable portions.
Dan Gohman572645c2010-02-12 10:34:29 +00002172void
Dan Gohman454d26d2010-02-22 04:11:59 +00002173LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Dan Gohman572645c2010-02-12 10:34:29 +00002174 Formula F;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00002175 F.InitialMatch(S, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002176 bool Inserted = InsertFormula(LU, LUIdx, F);
2177 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
2178}
2179
Dan Gohman76c315a2010-05-20 20:52:00 +00002180/// InsertSupplementalFormula - Insert a simple single-register formula for
2181/// the given expression into the given use.
Dan Gohman572645c2010-02-12 10:34:29 +00002182void
2183LSRInstance::InsertSupplementalFormula(const SCEV *S,
2184 LSRUse &LU, size_t LUIdx) {
2185 Formula F;
2186 F.BaseRegs.push_back(S);
2187 F.AM.HasBaseReg = true;
2188 bool Inserted = InsertFormula(LU, LUIdx, F);
2189 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
2190}
2191
2192/// CountRegisters - Note which registers are used by the given formula,
2193/// updating RegUses.
2194void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
2195 if (F.ScaledReg)
2196 RegUses.CountRegister(F.ScaledReg, LUIdx);
2197 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2198 E = F.BaseRegs.end(); I != E; ++I)
2199 RegUses.CountRegister(*I, LUIdx);
2200}
2201
2202/// InsertFormula - If the given formula has not yet been inserted, add it to
2203/// the list, and return true. Return false otherwise.
2204bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002205 if (!LU.InsertFormula(F))
Dan Gohman572645c2010-02-12 10:34:29 +00002206 return false;
2207
2208 CountRegisters(F, LUIdx);
2209 return true;
2210}
2211
2212/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
2213/// loop-invariant values which we're tracking. These other uses will pin these
2214/// values in registers, making them less profitable for elimination.
2215/// TODO: This currently misses non-constant addrec step registers.
2216/// TODO: Should this give more weight to users inside the loop?
2217void
2218LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
2219 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
2220 SmallPtrSet<const SCEV *, 8> Inserted;
2221
2222 while (!Worklist.empty()) {
2223 const SCEV *S = Worklist.pop_back_val();
2224
2225 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohman403a8cd2010-06-21 19:47:52 +00002226 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman572645c2010-02-12 10:34:29 +00002227 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2228 Worklist.push_back(C->getOperand());
2229 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2230 Worklist.push_back(D->getLHS());
2231 Worklist.push_back(D->getRHS());
2232 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2233 if (!Inserted.insert(U)) continue;
2234 const Value *V = U->getValue();
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002235 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2236 // Look for instructions defined outside the loop.
Dan Gohman572645c2010-02-12 10:34:29 +00002237 if (L->contains(Inst)) continue;
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002238 } else if (isa<UndefValue>(V))
2239 // Undef doesn't have a live range, so it doesn't matter.
2240 continue;
Gabor Greif60ad7812010-03-25 23:06:16 +00002241 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
Dan Gohman572645c2010-02-12 10:34:29 +00002242 UI != UE; ++UI) {
2243 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2244 // Ignore non-instructions.
2245 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00002246 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002247 // Ignore instructions in other functions (as can happen with
2248 // Constants).
2249 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00002250 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002251 // Ignore instructions not dominated by the loop.
2252 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2253 UserInst->getParent() :
2254 cast<PHINode>(UserInst)->getIncomingBlock(
2255 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2256 if (!DT.dominates(L->getHeader(), UseBB))
2257 continue;
2258 // Ignore uses which are part of other SCEV expressions, to avoid
2259 // analyzing them multiple times.
Dan Gohman4a2a6832010-04-09 19:12:34 +00002260 if (SE.isSCEVable(UserInst->getType())) {
2261 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2262 // If the user is a no-op, look through to its uses.
2263 if (!isa<SCEVUnknown>(UserS))
2264 continue;
2265 if (UserS == U) {
2266 Worklist.push_back(
2267 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2268 continue;
2269 }
2270 }
Dan Gohman572645c2010-02-12 10:34:29 +00002271 // Ignore icmp instructions which are already being analyzed.
2272 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2273 unsigned OtherIdx = !UI.getOperandNo();
2274 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
Dan Gohman17ead4f2010-11-17 21:23:15 +00002275 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
Dan Gohman572645c2010-02-12 10:34:29 +00002276 continue;
2277 }
2278
2279 LSRFixup &LF = getNewFixup();
2280 LF.UserInst = const_cast<Instruction *>(UserInst);
2281 LF.OperandValToReplace = UI.getUse();
2282 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2283 LF.LUIdx = P.first;
2284 LF.Offset = P.second;
2285 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002286 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohmana9db1292010-07-15 20:24:58 +00002287 if (!LU.WidestFixupType ||
2288 SE.getTypeSizeInBits(LU.WidestFixupType) <
2289 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2290 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002291 InsertSupplementalFormula(U, LU, LF.LUIdx);
2292 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2293 break;
2294 }
2295 }
2296 }
2297}
2298
2299/// CollectSubexprs - Split S into subexpressions which can be pulled out into
2300/// separate registers. If C is non-null, multiply each subexpression by C.
2301static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2302 SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman3e3f15b2010-06-25 22:32:18 +00002303 const Loop *L,
Dan Gohman572645c2010-02-12 10:34:29 +00002304 ScalarEvolution &SE) {
2305 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2306 // Break out add operands.
2307 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2308 I != E; ++I)
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002309 CollectSubexprs(*I, C, Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002310 return;
2311 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2312 // Split a non-zero base out of an addrec.
2313 if (!AR->getStart()->isZero()) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002314 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +00002315 AR->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +00002316 AR->getLoop(),
2317 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
2318 SCEV::FlagAnyWrap),
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002319 C, Ops, L, SE);
2320 CollectSubexprs(AR->getStart(), C, Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002321 return;
2322 }
2323 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2324 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2325 if (Mul->getNumOperands() == 2)
2326 if (const SCEVConstant *Op0 =
2327 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2328 CollectSubexprs(Mul->getOperand(1),
2329 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002330 Ops, L, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002331 return;
2332 }
2333 }
2334
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002335 // Otherwise use the value itself, optionally with a scale applied.
2336 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
Dan Gohman572645c2010-02-12 10:34:29 +00002337}
2338
2339/// GenerateReassociations - Split out subexpressions from adds and the bases of
2340/// addrecs.
2341void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2342 Formula Base,
2343 unsigned Depth) {
2344 // Arbitrarily cap recursion to protect compile time.
2345 if (Depth >= 3) return;
2346
2347 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2348 const SCEV *BaseReg = Base.BaseRegs[i];
2349
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002350 SmallVector<const SCEV *, 8> AddOps;
2351 CollectSubexprs(BaseReg, 0, AddOps, L, SE);
Dan Gohman3e3f15b2010-06-25 22:32:18 +00002352
Dan Gohman572645c2010-02-12 10:34:29 +00002353 if (AddOps.size() == 1) continue;
2354
2355 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2356 JE = AddOps.end(); J != JE; ++J) {
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002357
2358 // Loop-variant "unknown" values are uninteresting; we won't be able to
2359 // do anything meaningful with them.
Dan Gohman17ead4f2010-11-17 21:23:15 +00002360 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
Dan Gohman3e22b7c2010-08-16 15:50:00 +00002361 continue;
2362
Dan Gohman572645c2010-02-12 10:34:29 +00002363 // Don't pull a constant into a register if the constant could be folded
2364 // into an immediate field.
2365 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2366 Base.getNumRegs() > 1,
2367 LU.Kind, LU.AccessTy, TLI, SE))
2368 continue;
2369
2370 // Collect all operands except *J.
Dan Gohman403a8cd2010-06-21 19:47:52 +00002371 SmallVector<const SCEV *, 8> InnerAddOps
Dan Gohman4eaee282010-08-04 17:43:57 +00002372 (((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
Dan Gohman403a8cd2010-06-21 19:47:52 +00002373 InnerAddOps.append
Oscar Fuentesee56c422010-08-02 06:00:15 +00002374 (llvm::next(J), ((const SmallVector<const SCEV *, 8> &)AddOps).end());
Dan Gohman572645c2010-02-12 10:34:29 +00002375
2376 // Don't leave just a constant behind in a register if the constant could
2377 // be folded into an immediate field.
2378 if (InnerAddOps.size() == 1 &&
2379 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2380 Base.getNumRegs() > 1,
2381 LU.Kind, LU.AccessTy, TLI, SE))
2382 continue;
2383
Dan Gohmanfafb8902010-04-23 01:55:05 +00002384 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2385 if (InnerSum->isZero())
2386 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002387 Formula F = Base;
Dan Gohmancca82142011-05-03 00:46:49 +00002388
2389 // Add the remaining pieces of the add back into the new formula.
2390 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
2391 if (TLI && InnerSumSC &&
2392 SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
2393 TLI->isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
2394 InnerSumSC->getValue()->getZExtValue())) {
2395 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset +
2396 InnerSumSC->getValue()->getZExtValue();
2397 F.BaseRegs.erase(F.BaseRegs.begin() + i);
2398 } else
2399 F.BaseRegs[i] = InnerSum;
2400
2401 // Add J as its own register, or an unfolded immediate.
2402 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
2403 if (TLI && SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
2404 TLI->isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
2405 SC->getValue()->getZExtValue()))
2406 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset +
2407 SC->getValue()->getZExtValue();
2408 else
2409 F.BaseRegs.push_back(*J);
2410
Dan Gohman572645c2010-02-12 10:34:29 +00002411 if (InsertFormula(LU, LUIdx, F))
2412 // If that formula hadn't been seen before, recurse to find more like
2413 // it.
2414 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2415 }
2416 }
2417}
2418
2419/// GenerateCombinations - Generate a formula consisting of all of the
2420/// loop-dominating registers added into a single register.
2421void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002422 Formula Base) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002423 // This method is only interesting on a plurality of registers.
Dan Gohman572645c2010-02-12 10:34:29 +00002424 if (Base.BaseRegs.size() <= 1) return;
2425
2426 Formula F = Base;
2427 F.BaseRegs.clear();
2428 SmallVector<const SCEV *, 4> Ops;
2429 for (SmallVectorImpl<const SCEV *>::const_iterator
2430 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2431 const SCEV *BaseReg = *I;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00002432 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
Dan Gohman17ead4f2010-11-17 21:23:15 +00002433 !SE.hasComputableLoopEvolution(BaseReg, L))
Dan Gohman572645c2010-02-12 10:34:29 +00002434 Ops.push_back(BaseReg);
2435 else
2436 F.BaseRegs.push_back(BaseReg);
2437 }
2438 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002439 const SCEV *Sum = SE.getAddExpr(Ops);
2440 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2441 // opportunity to fold something. For now, just ignore such cases
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002442 // rather than proceed with zero in a register.
Dan Gohmance947362010-02-14 18:50:49 +00002443 if (!Sum->isZero()) {
2444 F.BaseRegs.push_back(Sum);
2445 (void)InsertFormula(LU, LUIdx, F);
2446 }
Dan Gohman572645c2010-02-12 10:34:29 +00002447 }
2448}
2449
2450/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2451void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2452 Formula Base) {
2453 // We can't add a symbolic offset if the address already contains one.
2454 if (Base.AM.BaseGV) return;
2455
2456 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2457 const SCEV *G = Base.BaseRegs[i];
2458 GlobalValue *GV = ExtractSymbol(G, SE);
2459 if (G->isZero() || !GV)
2460 continue;
2461 Formula F = Base;
2462 F.AM.BaseGV = GV;
2463 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2464 LU.Kind, LU.AccessTy, TLI))
2465 continue;
2466 F.BaseRegs[i] = G;
2467 (void)InsertFormula(LU, LUIdx, F);
2468 }
2469}
2470
2471/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2472void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2473 Formula Base) {
2474 // TODO: For now, just add the min and max offset, because it usually isn't
2475 // worthwhile looking at everything inbetween.
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002476 SmallVector<int64_t, 2> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00002477 Worklist.push_back(LU.MinOffset);
2478 if (LU.MaxOffset != LU.MinOffset)
2479 Worklist.push_back(LU.MaxOffset);
2480
2481 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2482 const SCEV *G = Base.BaseRegs[i];
2483
2484 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2485 E = Worklist.end(); I != E; ++I) {
2486 Formula F = Base;
2487 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2488 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2489 LU.Kind, LU.AccessTy, TLI)) {
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002490 // Add the offset to the base register.
Dan Gohman4065f602010-08-16 15:39:27 +00002491 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
Dan Gohmanc88c1a42010-07-15 15:14:45 +00002492 // If it cancelled out, drop the base register, otherwise update it.
2493 if (NewG->isZero()) {
2494 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2495 F.BaseRegs.pop_back();
2496 } else
2497 F.BaseRegs[i] = NewG;
Dan Gohman572645c2010-02-12 10:34:29 +00002498
2499 (void)InsertFormula(LU, LUIdx, F);
2500 }
2501 }
2502
2503 int64_t Imm = ExtractImmediate(G, SE);
2504 if (G->isZero() || Imm == 0)
2505 continue;
2506 Formula F = Base;
2507 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2508 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2509 LU.Kind, LU.AccessTy, TLI))
2510 continue;
2511 F.BaseRegs[i] = G;
2512 (void)InsertFormula(LU, LUIdx, F);
2513 }
2514}
2515
2516/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2517/// the comparison. For example, x == y -> x*c == y*c.
2518void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2519 Formula Base) {
2520 if (LU.Kind != LSRUse::ICmpZero) return;
2521
2522 // Determine the integer type for the base formula.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002523 Type *IntTy = Base.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002524 if (!IntTy) return;
2525 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2526
2527 // Don't do this if there is more than one offset.
2528 if (LU.MinOffset != LU.MaxOffset) return;
2529
2530 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2531
2532 // Check each interesting stride.
2533 for (SmallSetVector<int64_t, 8>::const_iterator
2534 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2535 int64_t Factor = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00002536
2537 // Check that the multiplication doesn't overflow.
Dan Gohman2ea09e02010-06-24 16:57:52 +00002538 if (Base.AM.BaseOffs == INT64_MIN && Factor == -1)
Dan Gohman968cb932010-02-17 00:41:53 +00002539 continue;
Dan Gohman2ea09e02010-06-24 16:57:52 +00002540 int64_t NewBaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2541 if (NewBaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002542 continue;
2543
2544 // Check that multiplying with the use offset doesn't overflow.
2545 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002546 if (Offset == INT64_MIN && Factor == -1)
2547 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002548 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002549 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002550 continue;
2551
Dan Gohman2ea09e02010-06-24 16:57:52 +00002552 Formula F = Base;
2553 F.AM.BaseOffs = NewBaseOffs;
2554
Dan Gohman572645c2010-02-12 10:34:29 +00002555 // Check that this scale is legal.
2556 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2557 continue;
2558
2559 // Compensate for the use having MinOffset built into it.
2560 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2561
Dan Gohmandeff6212010-05-03 22:09:21 +00002562 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002563
2564 // Check that multiplying with each base register doesn't overflow.
2565 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2566 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002567 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002568 goto next;
2569 }
2570
2571 // Check that multiplying with the scaled register doesn't overflow.
2572 if (F.ScaledReg) {
2573 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002574 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002575 continue;
2576 }
2577
Dan Gohmancca82142011-05-03 00:46:49 +00002578 // Check that multiplying with the unfolded offset doesn't overflow.
2579 if (F.UnfoldedOffset != 0) {
Dan Gohman1b58d452011-05-23 21:07:39 +00002580 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
2581 continue;
Dan Gohmancca82142011-05-03 00:46:49 +00002582 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
2583 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
2584 continue;
2585 }
2586
Dan Gohman572645c2010-02-12 10:34:29 +00002587 // If we make it here and it's legal, add it.
2588 (void)InsertFormula(LU, LUIdx, F);
2589 next:;
2590 }
2591}
2592
2593/// GenerateScales - Generate stride factor reuse formulae by making use of
2594/// scaled-offset address modes, for example.
Dan Gohmanea507f52010-05-20 19:44:23 +00002595void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002596 // Determine the integer type for the base formula.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002597 Type *IntTy = Base.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002598 if (!IntTy) return;
2599
2600 // If this Formula already has a scaled register, we can't add another one.
2601 if (Base.AM.Scale != 0) return;
2602
2603 // Check each interesting stride.
2604 for (SmallSetVector<int64_t, 8>::const_iterator
2605 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2606 int64_t Factor = *I;
2607
2608 Base.AM.Scale = Factor;
2609 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2610 // Check whether this scale is going to be legal.
2611 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2612 LU.Kind, LU.AccessTy, TLI)) {
2613 // As a special-case, handle special out-of-loop Basic users specially.
2614 // TODO: Reconsider this special case.
2615 if (LU.Kind == LSRUse::Basic &&
2616 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2617 LSRUse::Special, LU.AccessTy, TLI) &&
2618 LU.AllFixupsOutsideLoop)
2619 LU.Kind = LSRUse::Special;
2620 else
2621 continue;
2622 }
2623 // For an ICmpZero, negating a solitary base register won't lead to
2624 // new solutions.
2625 if (LU.Kind == LSRUse::ICmpZero &&
2626 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2627 continue;
2628 // For each addrec base reg, apply the scale, if possible.
2629 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2630 if (const SCEVAddRecExpr *AR =
2631 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002632 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002633 if (FactorS->isZero())
2634 continue;
2635 // Divide out the factor, ignoring high bits, since we'll be
2636 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002637 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002638 // TODO: This could be optimized to avoid all the copying.
2639 Formula F = Base;
2640 F.ScaledReg = Quotient;
Dan Gohman5ce6d052010-05-20 15:17:54 +00002641 F.DeleteBaseReg(F.BaseRegs[i]);
Dan Gohman572645c2010-02-12 10:34:29 +00002642 (void)InsertFormula(LU, LUIdx, F);
2643 }
2644 }
2645 }
2646}
2647
2648/// GenerateTruncates - Generate reuse formulae from different IV types.
Dan Gohmanea507f52010-05-20 19:44:23 +00002649void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002650 // This requires TargetLowering to tell us which truncates are free.
2651 if (!TLI) return;
2652
2653 // Don't bother truncating symbolic values.
2654 if (Base.AM.BaseGV) return;
2655
2656 // Determine the integer type for the base formula.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002657 Type *DstTy = Base.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00002658 if (!DstTy) return;
2659 DstTy = SE.getEffectiveSCEVType(DstTy);
2660
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002661 for (SmallSetVector<Type *, 4>::const_iterator
Dan Gohman572645c2010-02-12 10:34:29 +00002662 I = Types.begin(), E = Types.end(); I != E; ++I) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002663 Type *SrcTy = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00002664 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2665 Formula F = Base;
2666
2667 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2668 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2669 JE = F.BaseRegs.end(); J != JE; ++J)
2670 *J = SE.getAnyExtendExpr(*J, SrcTy);
2671
2672 // TODO: This assumes we've done basic processing on all uses and
2673 // have an idea what the register usage is.
2674 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2675 continue;
2676
2677 (void)InsertFormula(LU, LUIdx, F);
2678 }
2679 }
2680}
2681
2682namespace {
2683
Dan Gohman6020d852010-02-14 18:51:20 +00002684/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002685/// defer modifications so that the search phase doesn't have to worry about
2686/// the data structures moving underneath it.
2687struct WorkItem {
2688 size_t LUIdx;
2689 int64_t Imm;
2690 const SCEV *OrigReg;
2691
2692 WorkItem(size_t LI, int64_t I, const SCEV *R)
2693 : LUIdx(LI), Imm(I), OrigReg(R) {}
2694
2695 void print(raw_ostream &OS) const;
2696 void dump() const;
2697};
2698
2699}
2700
2701void WorkItem::print(raw_ostream &OS) const {
2702 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2703 << " , add offset " << Imm;
2704}
2705
2706void WorkItem::dump() const {
2707 print(errs()); errs() << '\n';
2708}
2709
2710/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2711/// distance apart and try to form reuse opportunities between them.
2712void LSRInstance::GenerateCrossUseConstantOffsets() {
2713 // Group the registers by their value without any added constant offset.
2714 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2715 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2716 RegMapTy Map;
2717 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2718 SmallVector<const SCEV *, 8> Sequence;
2719 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2720 I != E; ++I) {
2721 const SCEV *Reg = *I;
2722 int64_t Imm = ExtractImmediate(Reg, SE);
2723 std::pair<RegMapTy::iterator, bool> Pair =
2724 Map.insert(std::make_pair(Reg, ImmMapTy()));
2725 if (Pair.second)
2726 Sequence.push_back(Reg);
2727 Pair.first->second.insert(std::make_pair(Imm, *I));
2728 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2729 }
2730
2731 // Now examine each set of registers with the same base value. Build up
2732 // a list of work to do and do the work in a separate step so that we're
2733 // not adding formulae and register counts while we're searching.
Dan Gohman191bd642010-09-01 01:45:53 +00002734 SmallVector<WorkItem, 32> WorkItems;
2735 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
Dan Gohman572645c2010-02-12 10:34:29 +00002736 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2737 E = Sequence.end(); I != E; ++I) {
2738 const SCEV *Reg = *I;
2739 const ImmMapTy &Imms = Map.find(Reg)->second;
2740
Dan Gohmancd045c02010-02-12 19:20:37 +00002741 // It's not worthwhile looking for reuse if there's only one offset.
2742 if (Imms.size() == 1)
2743 continue;
2744
Dan Gohman572645c2010-02-12 10:34:29 +00002745 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2746 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2747 J != JE; ++J)
2748 dbgs() << ' ' << J->first;
2749 dbgs() << '\n');
2750
2751 // Examine each offset.
2752 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2753 J != JE; ++J) {
2754 const SCEV *OrigReg = J->second;
2755
2756 int64_t JImm = J->first;
2757 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2758
2759 if (!isa<SCEVConstant>(OrigReg) &&
2760 UsedByIndicesMap[Reg].count() == 1) {
2761 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2762 continue;
2763 }
2764
2765 // Conservatively examine offsets between this orig reg a few selected
2766 // other orig regs.
2767 ImmMapTy::const_iterator OtherImms[] = {
2768 Imms.begin(), prior(Imms.end()),
Dan Gohmancca82142011-05-03 00:46:49 +00002769 Imms.lower_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
Dan Gohman572645c2010-02-12 10:34:29 +00002770 };
2771 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2772 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002773 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002774
2775 // Compute the difference between the two.
2776 int64_t Imm = (uint64_t)JImm - M->first;
2777 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
Dan Gohman191bd642010-09-01 01:45:53 +00002778 LUIdx = UsedByIndices.find_next(LUIdx))
Dan Gohman572645c2010-02-12 10:34:29 +00002779 // Make a memo of this use, offset, and register tuple.
Dan Gohman191bd642010-09-01 01:45:53 +00002780 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2781 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002782 }
2783 }
2784 }
2785
Dan Gohman572645c2010-02-12 10:34:29 +00002786 Map.clear();
2787 Sequence.clear();
2788 UsedByIndicesMap.clear();
Dan Gohman191bd642010-09-01 01:45:53 +00002789 UniqueItems.clear();
Dan Gohman572645c2010-02-12 10:34:29 +00002790
2791 // Now iterate through the worklist and add new formulae.
2792 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2793 E = WorkItems.end(); I != E; ++I) {
2794 const WorkItem &WI = *I;
2795 size_t LUIdx = WI.LUIdx;
2796 LSRUse &LU = Uses[LUIdx];
2797 int64_t Imm = WI.Imm;
2798 const SCEV *OrigReg = WI.OrigReg;
2799
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002800 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
Dan Gohman572645c2010-02-12 10:34:29 +00002801 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2802 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2803
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002804 // TODO: Use a more targeted data structure.
Dan Gohman572645c2010-02-12 10:34:29 +00002805 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00002806 const Formula &F = LU.Formulae[L];
Dan Gohman572645c2010-02-12 10:34:29 +00002807 // Use the immediate in the scaled register.
2808 if (F.ScaledReg == OrigReg) {
2809 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2810 Imm * (uint64_t)F.AM.Scale;
2811 // Don't create 50 + reg(-50).
2812 if (F.referencesReg(SE.getSCEV(
2813 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2814 continue;
2815 Formula NewF = F;
2816 NewF.AM.BaseOffs = Offs;
2817 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2818 LU.Kind, LU.AccessTy, TLI))
2819 continue;
2820 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2821
2822 // If the new scale is a constant in a register, and adding the constant
2823 // value to the immediate would produce a value closer to zero than the
2824 // immediate itself, then the formula isn't worthwhile.
2825 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
Chris Lattnerc73b24d2011-07-15 06:08:15 +00002826 if (C->getValue()->isNegative() !=
Dan Gohman572645c2010-02-12 10:34:29 +00002827 (NewF.AM.BaseOffs < 0) &&
2828 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
Dan Gohmane0567812010-04-08 23:03:40 +00002829 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002830 continue;
2831
2832 // OK, looks good.
2833 (void)InsertFormula(LU, LUIdx, NewF);
2834 } else {
2835 // Use the immediate in a base register.
2836 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2837 const SCEV *BaseReg = F.BaseRegs[N];
2838 if (BaseReg != OrigReg)
2839 continue;
2840 Formula NewF = F;
2841 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2842 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
Dan Gohmancca82142011-05-03 00:46:49 +00002843 LU.Kind, LU.AccessTy, TLI)) {
2844 if (!TLI ||
2845 !TLI->isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
2846 continue;
2847 NewF = F;
2848 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
2849 }
Dan Gohman572645c2010-02-12 10:34:29 +00002850 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2851
2852 // If the new formula has a constant in a register, and adding the
2853 // constant value to the immediate would produce a value closer to
2854 // zero than the immediate itself, then the formula isn't worthwhile.
2855 for (SmallVectorImpl<const SCEV *>::const_iterator
2856 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2857 J != JE; ++J)
2858 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
Dan Gohman360026f2010-05-18 23:48:08 +00002859 if ((C->getValue()->getValue() + NewF.AM.BaseOffs).abs().slt(
2860 abs64(NewF.AM.BaseOffs)) &&
2861 (C->getValue()->getValue() +
2862 NewF.AM.BaseOffs).countTrailingZeros() >=
2863 CountTrailingZeros_64(NewF.AM.BaseOffs))
Dan Gohman572645c2010-02-12 10:34:29 +00002864 goto skip_formula;
2865
2866 // Ok, looks good.
2867 (void)InsertFormula(LU, LUIdx, NewF);
2868 break;
2869 skip_formula:;
2870 }
2871 }
2872 }
2873 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002874}
2875
Dan Gohman572645c2010-02-12 10:34:29 +00002876/// GenerateAllReuseFormulae - Generate formulae for each use.
2877void
2878LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002879 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002880 // queries are more precise.
2881 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2882 LSRUse &LU = Uses[LUIdx];
2883 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2884 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2885 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2886 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2887 }
2888 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2889 LSRUse &LU = Uses[LUIdx];
2890 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2891 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2892 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2893 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2894 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2895 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2896 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2897 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002898 }
2899 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2900 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002901 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2902 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2903 }
2904
2905 GenerateCrossUseConstantOffsets();
Dan Gohman3902f9f2010-08-29 15:21:38 +00002906
2907 DEBUG(dbgs() << "\n"
2908 "After generating reuse formulae:\n";
2909 print_uses(dbgs()));
Dan Gohman572645c2010-02-12 10:34:29 +00002910}
2911
Dan Gohmanf63d70f2010-10-07 23:43:09 +00002912/// If there are multiple formulae with the same set of registers used
Dan Gohman572645c2010-02-12 10:34:29 +00002913/// by other uses, pick the best one and delete the others.
2914void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
Dan Gohmanfc7744b2010-10-07 23:52:18 +00002915 DenseSet<const SCEV *> VisitedRegs;
2916 SmallPtrSet<const SCEV *, 16> Regs;
Dan Gohman572645c2010-02-12 10:34:29 +00002917#ifndef NDEBUG
Dan Gohmanc6519f92010-05-20 20:05:31 +00002918 bool ChangedFormulae = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002919#endif
2920
2921 // Collect the best formula for each unique set of shared registers. This
2922 // is reset for each use.
2923 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2924 BestFormulaeTy;
2925 BestFormulaeTy BestFormulae;
2926
2927 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2928 LSRUse &LU = Uses[LUIdx];
Dan Gohmanea507f52010-05-20 19:44:23 +00002929 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman572645c2010-02-12 10:34:29 +00002930
Dan Gohmanb2df4332010-05-18 23:42:37 +00002931 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002932 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2933 FIdx != NumForms; ++FIdx) {
2934 Formula &F = LU.Formulae[FIdx];
2935
2936 SmallVector<const SCEV *, 2> Key;
2937 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2938 JE = F.BaseRegs.end(); J != JE; ++J) {
2939 const SCEV *Reg = *J;
2940 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2941 Key.push_back(Reg);
2942 }
2943 if (F.ScaledReg &&
2944 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2945 Key.push_back(F.ScaledReg);
2946 // Unstable sort by host order ok, because this is only used for
2947 // uniquifying.
2948 std::sort(Key.begin(), Key.end());
2949
2950 std::pair<BestFormulaeTy::const_iterator, bool> P =
2951 BestFormulae.insert(std::make_pair(Key, FIdx));
2952 if (!P.second) {
2953 Formula &Best = LU.Formulae[P.first->second];
Dan Gohmanfc7744b2010-10-07 23:52:18 +00002954
2955 Cost CostF;
2956 CostF.RateFormula(F, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2957 Regs.clear();
2958 Cost CostBest;
2959 CostBest.RateFormula(Best, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2960 Regs.clear();
2961 if (CostF < CostBest)
Dan Gohman572645c2010-02-12 10:34:29 +00002962 std::swap(F, Best);
Dan Gohman6458ff92010-05-18 22:37:37 +00002963 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002964 dbgs() << "\n"
Dan Gohman6458ff92010-05-18 22:37:37 +00002965 " in favor of formula "; Best.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002966 dbgs() << '\n');
2967#ifndef NDEBUG
Dan Gohmanc6519f92010-05-20 20:05:31 +00002968 ChangedFormulae = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002969#endif
Dan Gohmand69d6282010-05-18 22:39:15 +00002970 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00002971 --FIdx;
2972 --NumForms;
Dan Gohmanb2df4332010-05-18 23:42:37 +00002973 Any = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002974 continue;
2975 }
Dan Gohman59dc6032010-05-07 23:36:59 +00002976 }
2977
Dan Gohman57aaa0b2010-05-18 23:55:57 +00002978 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohmanb2df4332010-05-18 23:42:37 +00002979 if (Any)
2980 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman59dc6032010-05-07 23:36:59 +00002981
2982 // Reset this to prepare for the next use.
Dan Gohman572645c2010-02-12 10:34:29 +00002983 BestFormulae.clear();
2984 }
2985
Dan Gohmanc6519f92010-05-20 20:05:31 +00002986 DEBUG(if (ChangedFormulae) {
Dan Gohman9214b822010-02-13 02:06:02 +00002987 dbgs() << "\n"
2988 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002989 print_uses(dbgs());
2990 });
2991}
2992
Dan Gohmand079c302010-05-18 22:51:59 +00002993// This is a rough guess that seems to work fairly well.
2994static const size_t ComplexityLimit = UINT16_MAX;
2995
2996/// EstimateSearchSpaceComplexity - Estimate the worst-case number of
2997/// solutions the solver might have to consider. It almost never considers
2998/// this many solutions because it prune the search space, but the pruning
2999/// isn't always sufficient.
3000size_t LSRInstance::EstimateSearchSpaceComplexity() const {
Dan Gohman0d6715a2010-10-07 23:37:58 +00003001 size_t Power = 1;
Dan Gohmand079c302010-05-18 22:51:59 +00003002 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3003 E = Uses.end(); I != E; ++I) {
3004 size_t FSize = I->Formulae.size();
3005 if (FSize >= ComplexityLimit) {
3006 Power = ComplexityLimit;
3007 break;
3008 }
3009 Power *= FSize;
3010 if (Power >= ComplexityLimit)
3011 break;
3012 }
3013 return Power;
3014}
3015
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003016/// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
3017/// of the registers of another formula, it won't help reduce register
3018/// pressure (though it may not necessarily hurt register pressure); remove
3019/// it to simplify the system.
3020void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
Dan Gohmana2086b32010-05-19 23:43:12 +00003021 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3022 DEBUG(dbgs() << "The search space is too complex.\n");
3023
3024 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
3025 "which use a superset of registers used by other "
3026 "formulae.\n");
3027
3028 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3029 LSRUse &LU = Uses[LUIdx];
3030 bool Any = false;
3031 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3032 Formula &F = LU.Formulae[i];
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003033 // Look for a formula with a constant or GV in a register. If the use
3034 // also has a formula with that same value in an immediate field,
3035 // delete the one that uses a register.
Dan Gohmana2086b32010-05-19 23:43:12 +00003036 for (SmallVectorImpl<const SCEV *>::const_iterator
3037 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
3038 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
3039 Formula NewF = F;
3040 NewF.AM.BaseOffs += C->getValue()->getSExtValue();
3041 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
3042 (I - F.BaseRegs.begin()));
3043 if (LU.HasFormulaWithSameRegs(NewF)) {
3044 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
3045 LU.DeleteFormula(F);
3046 --i;
3047 --e;
3048 Any = true;
3049 break;
3050 }
3051 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
3052 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
3053 if (!F.AM.BaseGV) {
3054 Formula NewF = F;
3055 NewF.AM.BaseGV = GV;
3056 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
3057 (I - F.BaseRegs.begin()));
3058 if (LU.HasFormulaWithSameRegs(NewF)) {
3059 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
3060 dbgs() << '\n');
3061 LU.DeleteFormula(F);
3062 --i;
3063 --e;
3064 Any = true;
3065 break;
3066 }
3067 }
3068 }
3069 }
3070 }
3071 if (Any)
3072 LU.RecomputeRegs(LUIdx, RegUses);
3073 }
3074
3075 DEBUG(dbgs() << "After pre-selection:\n";
3076 print_uses(dbgs()));
3077 }
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003078}
Dan Gohmana2086b32010-05-19 23:43:12 +00003079
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003080/// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
3081/// for expressions like A, A+1, A+2, etc., allocate a single register for
3082/// them.
3083void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
Dan Gohmana2086b32010-05-19 23:43:12 +00003084 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3085 DEBUG(dbgs() << "The search space is too complex.\n");
3086
3087 DEBUG(dbgs() << "Narrowing the search space by assuming that uses "
3088 "separated by a constant offset will use the same "
3089 "registers.\n");
3090
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003091 // This is especially useful for unrolled loops.
3092
Dan Gohmana2086b32010-05-19 23:43:12 +00003093 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3094 LSRUse &LU = Uses[LUIdx];
Dan Gohman402d4352010-05-20 20:33:18 +00003095 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3096 E = LU.Formulae.end(); I != E; ++I) {
3097 const Formula &F = *I;
Dan Gohmana2086b32010-05-19 23:43:12 +00003098 if (F.AM.BaseOffs != 0 && F.AM.Scale == 0) {
Dan Gohman191bd642010-09-01 01:45:53 +00003099 if (LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU)) {
3100 if (reconcileNewOffset(*LUThatHas, F.AM.BaseOffs,
Dan Gohmana2086b32010-05-19 23:43:12 +00003101 /*HasBaseReg=*/false,
3102 LU.Kind, LU.AccessTy)) {
3103 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs());
3104 dbgs() << '\n');
3105
3106 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
3107
Dan Gohman191bd642010-09-01 01:45:53 +00003108 // Update the relocs to reference the new use.
3109 for (SmallVectorImpl<LSRFixup>::iterator I = Fixups.begin(),
3110 E = Fixups.end(); I != E; ++I) {
3111 LSRFixup &Fixup = *I;
3112 if (Fixup.LUIdx == LUIdx) {
3113 Fixup.LUIdx = LUThatHas - &Uses.front();
3114 Fixup.Offset += F.AM.BaseOffs;
Dan Gohmandd3db0e2010-10-07 23:36:45 +00003115 // Add the new offset to LUThatHas' offset list.
3116 if (LUThatHas->Offsets.back() != Fixup.Offset) {
3117 LUThatHas->Offsets.push_back(Fixup.Offset);
3118 if (Fixup.Offset > LUThatHas->MaxOffset)
3119 LUThatHas->MaxOffset = Fixup.Offset;
3120 if (Fixup.Offset < LUThatHas->MinOffset)
3121 LUThatHas->MinOffset = Fixup.Offset;
3122 }
Dan Gohman191bd642010-09-01 01:45:53 +00003123 DEBUG(dbgs() << "New fixup has offset "
3124 << Fixup.Offset << '\n');
3125 }
3126 if (Fixup.LUIdx == NumUses-1)
3127 Fixup.LUIdx = LUIdx;
3128 }
3129
Dan Gohmanc2921ea2010-10-08 19:33:26 +00003130 // Delete formulae from the new use which are no longer legal.
3131 bool Any = false;
3132 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
3133 Formula &F = LUThatHas->Formulae[i];
3134 if (!isLegalUse(F.AM,
3135 LUThatHas->MinOffset, LUThatHas->MaxOffset,
3136 LUThatHas->Kind, LUThatHas->AccessTy, TLI)) {
3137 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
3138 dbgs() << '\n');
3139 LUThatHas->DeleteFormula(F);
3140 --i;
3141 --e;
3142 Any = true;
3143 }
3144 }
3145 if (Any)
3146 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
3147
Dan Gohmana2086b32010-05-19 23:43:12 +00003148 // Delete the old use.
Dan Gohmanc6897702010-10-07 23:33:43 +00003149 DeleteUse(LU, LUIdx);
Dan Gohmana2086b32010-05-19 23:43:12 +00003150 --LUIdx;
3151 --NumUses;
3152 break;
3153 }
3154 }
3155 }
3156 }
3157 }
3158
3159 DEBUG(dbgs() << "After pre-selection:\n";
3160 print_uses(dbgs()));
3161 }
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003162}
Dan Gohmana2086b32010-05-19 23:43:12 +00003163
Andrew Trick3228cc22011-03-14 16:50:06 +00003164/// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
Dan Gohman4f7e18d2010-08-29 16:39:22 +00003165/// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
3166/// we've done more filtering, as it may be able to find more formulae to
3167/// eliminate.
3168void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
3169 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3170 DEBUG(dbgs() << "The search space is too complex.\n");
3171
3172 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
3173 "undesirable dedicated registers.\n");
3174
3175 FilterOutUndesirableDedicatedRegisters();
3176
3177 DEBUG(dbgs() << "After pre-selection:\n";
3178 print_uses(dbgs()));
3179 }
3180}
3181
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003182/// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
3183/// to be profitable, and then in any use which has any reference to that
3184/// register, delete all formulae which do not reference that register.
3185void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
Dan Gohman76c315a2010-05-20 20:52:00 +00003186 // With all other options exhausted, loop until the system is simple
3187 // enough to handle.
Dan Gohman572645c2010-02-12 10:34:29 +00003188 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmand079c302010-05-18 22:51:59 +00003189 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman572645c2010-02-12 10:34:29 +00003190 // Ok, we have too many of formulae on our hands to conveniently handle.
3191 // Use a rough heuristic to thin out the list.
Dan Gohman0da751b2010-05-18 22:41:32 +00003192 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003193
3194 // Pick the register which is used by the most LSRUses, which is likely
3195 // to be a good reuse register candidate.
3196 const SCEV *Best = 0;
3197 unsigned BestNum = 0;
3198 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
3199 I != E; ++I) {
3200 const SCEV *Reg = *I;
3201 if (Taken.count(Reg))
3202 continue;
3203 if (!Best)
3204 Best = Reg;
3205 else {
3206 unsigned Count = RegUses.getUsedByIndices(Reg).count();
3207 if (Count > BestNum) {
3208 Best = Reg;
3209 BestNum = Count;
3210 }
3211 }
3212 }
3213
3214 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003215 << " will yield profitable reuse.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003216 Taken.insert(Best);
3217
3218 // In any use with formulae which references this register, delete formulae
3219 // which don't reference it.
Dan Gohmanb2df4332010-05-18 23:42:37 +00003220 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3221 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00003222 if (!LU.Regs.count(Best)) continue;
3223
Dan Gohmanb2df4332010-05-18 23:42:37 +00003224 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003225 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3226 Formula &F = LU.Formulae[i];
3227 if (!F.referencesReg(Best)) {
3228 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmand69d6282010-05-18 22:39:15 +00003229 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00003230 --e;
3231 --i;
Dan Gohmanb2df4332010-05-18 23:42:37 +00003232 Any = true;
Dan Gohman59dc6032010-05-07 23:36:59 +00003233 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman572645c2010-02-12 10:34:29 +00003234 continue;
3235 }
Dan Gohman572645c2010-02-12 10:34:29 +00003236 }
Dan Gohmanb2df4332010-05-18 23:42:37 +00003237
3238 if (Any)
3239 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman572645c2010-02-12 10:34:29 +00003240 }
3241
3242 DEBUG(dbgs() << "After pre-selection:\n";
3243 print_uses(dbgs()));
3244 }
3245}
3246
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003247/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
3248/// formulae to choose from, use some rough heuristics to prune down the number
3249/// of formulae. This keeps the main solver from taking an extraordinary amount
3250/// of time in some worst-case scenarios.
3251void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
3252 NarrowSearchSpaceByDetectingSupersets();
3253 NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman4f7e18d2010-08-29 16:39:22 +00003254 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohman4aa5c2e2010-08-29 16:09:42 +00003255 NarrowSearchSpaceByPickingWinnerRegs();
3256}
3257
Dan Gohman572645c2010-02-12 10:34:29 +00003258/// SolveRecurse - This is the recursive solver.
3259void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
3260 Cost &SolutionCost,
3261 SmallVectorImpl<const Formula *> &Workspace,
3262 const Cost &CurCost,
3263 const SmallPtrSet<const SCEV *, 16> &CurRegs,
3264 DenseSet<const SCEV *> &VisitedRegs) const {
3265 // Some ideas:
3266 // - prune more:
3267 // - use more aggressive filtering
3268 // - sort the formula so that the most profitable solutions are found first
3269 // - sort the uses too
3270 // - search faster:
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003271 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman572645c2010-02-12 10:34:29 +00003272 // and bail early.
3273 // - track register sets with SmallBitVector
3274
3275 const LSRUse &LU = Uses[Workspace.size()];
3276
3277 // If this use references any register that's already a part of the
3278 // in-progress solution, consider it a requirement that a formula must
3279 // reference that register in order to be considered. This prunes out
3280 // unprofitable searching.
3281 SmallSetVector<const SCEV *, 4> ReqRegs;
3282 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
3283 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00003284 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00003285 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00003286
Dan Gohman9214b822010-02-13 02:06:02 +00003287 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003288 SmallPtrSet<const SCEV *, 16> NewRegs;
3289 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00003290retry:
Dan Gohman572645c2010-02-12 10:34:29 +00003291 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3292 E = LU.Formulae.end(); I != E; ++I) {
3293 const Formula &F = *I;
3294
3295 // Ignore formulae which do not use any of the required registers.
3296 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
3297 JE = ReqRegs.end(); J != JE; ++J) {
3298 const SCEV *Reg = *J;
3299 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
3300 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
3301 F.BaseRegs.end())
3302 goto skip;
3303 }
Dan Gohman9214b822010-02-13 02:06:02 +00003304 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00003305
3306 // Evaluate the cost of the current formula. If it's already worse than
3307 // the current best, prune the search at that point.
3308 NewCost = CurCost;
3309 NewRegs = CurRegs;
3310 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
3311 if (NewCost < SolutionCost) {
3312 Workspace.push_back(&F);
3313 if (Workspace.size() != Uses.size()) {
3314 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
3315 NewRegs, VisitedRegs);
3316 if (F.getNumRegs() == 1 && Workspace.size() == 1)
3317 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
3318 } else {
3319 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
3320 dbgs() << ". Regs:";
3321 for (SmallPtrSet<const SCEV *, 16>::const_iterator
3322 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
3323 dbgs() << ' ' << **I;
3324 dbgs() << '\n');
3325
3326 SolutionCost = NewCost;
3327 Solution = Workspace;
3328 }
3329 Workspace.pop_back();
3330 }
3331 skip:;
3332 }
Dan Gohman9214b822010-02-13 02:06:02 +00003333
Andrew Trick80ef1b22011-09-27 00:44:14 +00003334 if (!EnableRetry && !AnySatisfiedReqRegs)
3335 return;
3336
Dan Gohman9214b822010-02-13 02:06:02 +00003337 // If none of the formulae had all of the required registers, relax the
3338 // constraint so that we don't exclude all formulae.
3339 if (!AnySatisfiedReqRegs) {
Dan Gohman59dc6032010-05-07 23:36:59 +00003340 assert(!ReqRegs.empty() && "Solver failed even without required registers");
Dan Gohman9214b822010-02-13 02:06:02 +00003341 ReqRegs.clear();
3342 goto retry;
3343 }
Dan Gohman572645c2010-02-12 10:34:29 +00003344}
3345
Dan Gohman76c315a2010-05-20 20:52:00 +00003346/// Solve - Choose one formula from each use. Return the results in the given
3347/// Solution vector.
Dan Gohman572645c2010-02-12 10:34:29 +00003348void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
3349 SmallVector<const Formula *, 8> Workspace;
3350 Cost SolutionCost;
3351 SolutionCost.Loose();
3352 Cost CurCost;
3353 SmallPtrSet<const SCEV *, 16> CurRegs;
3354 DenseSet<const SCEV *> VisitedRegs;
3355 Workspace.reserve(Uses.size());
3356
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003357 // SolveRecurse does all the work.
Dan Gohman572645c2010-02-12 10:34:29 +00003358 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
3359 CurRegs, VisitedRegs);
Andrew Trick80ef1b22011-09-27 00:44:14 +00003360 if (Solution.empty()) {
3361 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
3362 return;
3363 }
Dan Gohman572645c2010-02-12 10:34:29 +00003364
3365 // Ok, we've now made all our decisions.
3366 DEBUG(dbgs() << "\n"
3367 "The chosen solution requires "; SolutionCost.print(dbgs());
3368 dbgs() << ":\n";
3369 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
3370 dbgs() << " ";
3371 Uses[i].print(dbgs());
3372 dbgs() << "\n"
3373 " ";
3374 Solution[i]->print(dbgs());
3375 dbgs() << '\n';
3376 });
Dan Gohmana5528782010-05-20 20:59:23 +00003377
3378 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman572645c2010-02-12 10:34:29 +00003379}
3380
Dan Gohmane5f76872010-04-09 22:07:05 +00003381/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
3382/// the dominator tree far as we can go while still being dominated by the
3383/// input positions. This helps canonicalize the insert position, which
3384/// encourages sharing.
3385BasicBlock::iterator
3386LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
3387 const SmallVectorImpl<Instruction *> &Inputs)
3388 const {
3389 for (;;) {
3390 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
3391 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
3392
3393 BasicBlock *IDom;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003394 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman0fe46d92010-05-20 22:46:54 +00003395 if (!Rung) return IP;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003396 Rung = Rung->getIDom();
3397 if (!Rung) return IP;
3398 IDom = Rung->getBlock();
Dan Gohmane5f76872010-04-09 22:07:05 +00003399
3400 // Don't climb into a loop though.
3401 const Loop *IDomLoop = LI.getLoopFor(IDom);
3402 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
3403 if (IDomDepth <= IPLoopDepth &&
3404 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
3405 break;
3406 }
3407
3408 bool AllDominate = true;
3409 Instruction *BetterPos = 0;
3410 Instruction *Tentative = IDom->getTerminator();
3411 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
3412 E = Inputs.end(); I != E; ++I) {
3413 Instruction *Inst = *I;
3414 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
3415 AllDominate = false;
3416 break;
3417 }
3418 // Attempt to find an insert position in the middle of the block,
3419 // instead of at the end, so that it can be used for other expansions.
3420 if (IDom == Inst->getParent() &&
3421 (!BetterPos || DT.dominates(BetterPos, Inst)))
Douglas Gregor7d9663c2010-05-11 06:17:44 +00003422 BetterPos = llvm::next(BasicBlock::iterator(Inst));
Dan Gohmane5f76872010-04-09 22:07:05 +00003423 }
3424 if (!AllDominate)
3425 break;
3426 if (BetterPos)
3427 IP = BetterPos;
3428 else
3429 IP = Tentative;
3430 }
3431
3432 return IP;
3433}
3434
3435/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand96eae82010-04-09 02:00:38 +00003436/// dominated by the operands and which will dominate the result.
3437BasicBlock::iterator
Dan Gohmane5f76872010-04-09 22:07:05 +00003438LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
3439 const LSRFixup &LF,
3440 const LSRUse &LU) const {
Dan Gohmand96eae82010-04-09 02:00:38 +00003441 // Collect some instructions which must be dominated by the
Dan Gohman448db1c2010-04-07 22:27:08 +00003442 // expanding replacement. These must be dominated by any operands that
Dan Gohman572645c2010-02-12 10:34:29 +00003443 // will be required in the expansion.
3444 SmallVector<Instruction *, 4> Inputs;
3445 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
3446 Inputs.push_back(I);
3447 if (LU.Kind == LSRUse::ICmpZero)
3448 if (Instruction *I =
3449 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
3450 Inputs.push_back(I);
Dan Gohman448db1c2010-04-07 22:27:08 +00003451 if (LF.PostIncLoops.count(L)) {
3452 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman069d6f32010-03-02 01:59:21 +00003453 Inputs.push_back(L->getLoopLatch()->getTerminator());
3454 else
3455 Inputs.push_back(IVIncInsertPos);
3456 }
Dan Gohman701a4ae2010-04-08 05:57:57 +00003457 // The expansion must also be dominated by the increment positions of any
3458 // loops it for which it is using post-inc mode.
3459 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
3460 E = LF.PostIncLoops.end(); I != E; ++I) {
3461 const Loop *PIL = *I;
3462 if (PIL == L) continue;
3463
Dan Gohmane5f76872010-04-09 22:07:05 +00003464 // Be dominated by the loop exit.
Dan Gohman701a4ae2010-04-08 05:57:57 +00003465 SmallVector<BasicBlock *, 4> ExitingBlocks;
3466 PIL->getExitingBlocks(ExitingBlocks);
3467 if (!ExitingBlocks.empty()) {
3468 BasicBlock *BB = ExitingBlocks[0];
3469 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
3470 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
3471 Inputs.push_back(BB->getTerminator());
3472 }
3473 }
Dan Gohman572645c2010-02-12 10:34:29 +00003474
3475 // Then, climb up the immediate dominator tree as far as we can go while
3476 // still being dominated by the input positions.
Dan Gohmane5f76872010-04-09 22:07:05 +00003477 IP = HoistInsertPosition(IP, Inputs);
Dan Gohmand96eae82010-04-09 02:00:38 +00003478
3479 // Don't insert instructions before PHI nodes.
Dan Gohman572645c2010-02-12 10:34:29 +00003480 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand96eae82010-04-09 02:00:38 +00003481
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00003482 // Ignore landingpad instructions.
3483 while (isa<LandingPadInst>(IP)) ++IP;
3484
Dan Gohmand96eae82010-04-09 02:00:38 +00003485 // Ignore debug intrinsics.
Dan Gohman449f31c2010-03-26 00:33:27 +00003486 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman572645c2010-02-12 10:34:29 +00003487
Dan Gohmand96eae82010-04-09 02:00:38 +00003488 return IP;
3489}
3490
Dan Gohman76c315a2010-05-20 20:52:00 +00003491/// Expand - Emit instructions for the leading candidate expression for this
3492/// LSRUse (this is called "expanding").
Dan Gohmand96eae82010-04-09 02:00:38 +00003493Value *LSRInstance::Expand(const LSRFixup &LF,
3494 const Formula &F,
3495 BasicBlock::iterator IP,
3496 SCEVExpander &Rewriter,
3497 SmallVectorImpl<WeakVH> &DeadInsts) const {
3498 const LSRUse &LU = Uses[LF.LUIdx];
3499
3500 // Determine an input position which will be dominated by the operands and
3501 // which will dominate the result.
Dan Gohmane5f76872010-04-09 22:07:05 +00003502 IP = AdjustInsertPositionForExpand(IP, LF, LU);
Dan Gohmand96eae82010-04-09 02:00:38 +00003503
Dan Gohman572645c2010-02-12 10:34:29 +00003504 // Inform the Rewriter if we have a post-increment use, so that it can
3505 // perform an advantageous expansion.
Dan Gohman448db1c2010-04-07 22:27:08 +00003506 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman572645c2010-02-12 10:34:29 +00003507
3508 // This is the type that the user actually needs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003509 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003510 // This will be the type that we'll initially expand to.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003511 Type *Ty = F.getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003512 if (!Ty)
3513 // No type known; just expand directly to the ultimate type.
3514 Ty = OpTy;
3515 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3516 // Expand directly to the ultimate type if it's the right size.
3517 Ty = OpTy;
3518 // This is the type to do integer arithmetic in.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003519 Type *IntTy = SE.getEffectiveSCEVType(Ty);
Dan Gohman572645c2010-02-12 10:34:29 +00003520
3521 // Build up a list of operands to add together to form the full base.
3522 SmallVector<const SCEV *, 8> Ops;
3523
3524 // Expand the BaseRegs portion.
3525 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3526 E = F.BaseRegs.end(); I != E; ++I) {
3527 const SCEV *Reg = *I;
3528 assert(!Reg->isZero() && "Zero allocated in a base register!");
3529
Dan Gohman448db1c2010-04-07 22:27:08 +00003530 // If we're expanding for a post-inc user, make the post-inc adjustment.
3531 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3532 Reg = TransformForPostIncUse(Denormalize, Reg,
3533 LF.UserInst, LF.OperandValToReplace,
3534 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003535
3536 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3537 }
3538
Dan Gohman087bd1e2010-03-03 05:29:13 +00003539 // Flush the operand list to suppress SCEVExpander hoisting.
3540 if (!Ops.empty()) {
3541 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3542 Ops.clear();
3543 Ops.push_back(SE.getUnknown(FullV));
3544 }
3545
Dan Gohman572645c2010-02-12 10:34:29 +00003546 // Expand the ScaledReg portion.
3547 Value *ICmpScaledV = 0;
3548 if (F.AM.Scale != 0) {
3549 const SCEV *ScaledS = F.ScaledReg;
3550
Dan Gohman448db1c2010-04-07 22:27:08 +00003551 // If we're expanding for a post-inc user, make the post-inc adjustment.
3552 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3553 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3554 LF.UserInst, LF.OperandValToReplace,
3555 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003556
3557 if (LU.Kind == LSRUse::ICmpZero) {
3558 // An interesting way of "folding" with an icmp is to use a negated
3559 // scale, which we'll implement by inserting it into the other operand
3560 // of the icmp.
3561 assert(F.AM.Scale == -1 &&
3562 "The only scale supported by ICmpZero uses is -1!");
3563 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3564 } else {
3565 // Otherwise just expand the scaled register and an explicit scale,
3566 // which is expected to be matched as part of the address.
3567 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3568 ScaledS = SE.getMulExpr(ScaledS,
Dan Gohmandeff6212010-05-03 22:09:21 +00003569 SE.getConstant(ScaledS->getType(), F.AM.Scale));
Dan Gohman572645c2010-02-12 10:34:29 +00003570 Ops.push_back(ScaledS);
Dan Gohman087bd1e2010-03-03 05:29:13 +00003571
3572 // Flush the operand list to suppress SCEVExpander hoisting.
3573 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3574 Ops.clear();
3575 Ops.push_back(SE.getUnknown(FullV));
Dan Gohman572645c2010-02-12 10:34:29 +00003576 }
3577 }
3578
Dan Gohman087bd1e2010-03-03 05:29:13 +00003579 // Expand the GV portion.
3580 if (F.AM.BaseGV) {
3581 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3582
3583 // Flush the operand list to suppress SCEVExpander hoisting.
3584 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3585 Ops.clear();
3586 Ops.push_back(SE.getUnknown(FullV));
3587 }
3588
3589 // Expand the immediate portion.
Dan Gohman572645c2010-02-12 10:34:29 +00003590 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3591 if (Offset != 0) {
3592 if (LU.Kind == LSRUse::ICmpZero) {
3593 // The other interesting way of "folding" with an ICmpZero is to use a
3594 // negated immediate.
3595 if (!ICmpScaledV)
3596 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3597 else {
3598 Ops.push_back(SE.getUnknown(ICmpScaledV));
3599 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3600 }
3601 } else {
3602 // Just add the immediate values. These again are expected to be matched
3603 // as part of the address.
Dan Gohman087bd1e2010-03-03 05:29:13 +00003604 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman572645c2010-02-12 10:34:29 +00003605 }
3606 }
3607
Dan Gohmancca82142011-05-03 00:46:49 +00003608 // Expand the unfolded offset portion.
3609 int64_t UnfoldedOffset = F.UnfoldedOffset;
3610 if (UnfoldedOffset != 0) {
3611 // Just add the immediate values.
3612 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
3613 UnfoldedOffset)));
3614 }
3615
Dan Gohman572645c2010-02-12 10:34:29 +00003616 // Emit instructions summing all the operands.
3617 const SCEV *FullS = Ops.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +00003618 SE.getConstant(IntTy, 0) :
Dan Gohman572645c2010-02-12 10:34:29 +00003619 SE.getAddExpr(Ops);
3620 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3621
3622 // We're done expanding now, so reset the rewriter.
Dan Gohman448db1c2010-04-07 22:27:08 +00003623 Rewriter.clearPostInc();
Dan Gohman572645c2010-02-12 10:34:29 +00003624
3625 // An ICmpZero Formula represents an ICmp which we're handling as a
3626 // comparison against zero. Now that we've expanded an expression for that
3627 // form, update the ICmp's other operand.
3628 if (LU.Kind == LSRUse::ICmpZero) {
3629 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3630 DeadInsts.push_back(CI->getOperand(1));
3631 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3632 "a scale at the same time!");
3633 if (F.AM.Scale == -1) {
3634 if (ICmpScaledV->getType() != OpTy) {
3635 Instruction *Cast =
3636 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3637 OpTy, false),
3638 ICmpScaledV, OpTy, "tmp", CI);
3639 ICmpScaledV = Cast;
3640 }
3641 CI->setOperand(1, ICmpScaledV);
3642 } else {
3643 assert(F.AM.Scale == 0 &&
3644 "ICmp does not support folding a global value and "
3645 "a scale at the same time!");
3646 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3647 -(uint64_t)Offset);
3648 if (C->getType() != OpTy)
3649 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3650 OpTy, false),
3651 C, OpTy);
3652
3653 CI->setOperand(1, C);
3654 }
3655 }
3656
3657 return FullV;
3658}
3659
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003660/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3661/// of their operands effectively happens in their predecessor blocks, so the
3662/// expression may need to be expanded in multiple places.
3663void LSRInstance::RewriteForPHI(PHINode *PN,
3664 const LSRFixup &LF,
3665 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003666 SCEVExpander &Rewriter,
3667 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003668 Pass *P) const {
3669 DenseMap<BasicBlock *, Value *> Inserted;
3670 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3671 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3672 BasicBlock *BB = PN->getIncomingBlock(i);
3673
3674 // If this is a critical edge, split the edge so that we do not insert
3675 // the code on all predecessor/successor paths. We do this unless this
3676 // is the canonical backedge for this loop, which complicates post-inc
3677 // users.
3678 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
Dan Gohman3ef98382011-02-08 00:55:13 +00003679 !isa<IndirectBrInst>(BB->getTerminator())) {
Bill Wendling89d44112011-08-25 01:08:34 +00003680 BasicBlock *Parent = PN->getParent();
3681 Loop *PNLoop = LI.getLoopFor(Parent);
3682 if (!PNLoop || Parent != PNLoop->getHeader()) {
Dan Gohman3ef98382011-02-08 00:55:13 +00003683 // Split the critical edge.
Bill Wendling8b6af8a2011-08-25 05:55:40 +00003684 BasicBlock *NewBB = 0;
3685 if (!Parent->isLandingPad()) {
Andrew Trickf143b792011-10-04 03:50:44 +00003686 NewBB = SplitCriticalEdge(BB, Parent, P,
3687 /*MergeIdenticalEdges=*/true,
3688 /*DontDeleteUselessPhis=*/true);
Bill Wendling8b6af8a2011-08-25 05:55:40 +00003689 } else {
3690 SmallVector<BasicBlock*, 2> NewBBs;
3691 SplitLandingPadPredecessors(Parent, BB, "", "", P, NewBBs);
3692 NewBB = NewBBs[0];
3693 }
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003694
Dan Gohman3ef98382011-02-08 00:55:13 +00003695 // If PN is outside of the loop and BB is in the loop, we want to
3696 // move the block to be immediately before the PHI block, not
3697 // immediately after BB.
3698 if (L->contains(BB) && !L->contains(PN))
3699 NewBB->moveBefore(PN->getParent());
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003700
Dan Gohman3ef98382011-02-08 00:55:13 +00003701 // Splitting the edge can reduce the number of PHI entries we have.
3702 e = PN->getNumIncomingValues();
3703 BB = NewBB;
3704 i = PN->getBasicBlockIndex(BB);
3705 }
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003706 }
3707
3708 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3709 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3710 if (!Pair.second)
3711 PN->setIncomingValue(i, Pair.first->second);
3712 else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003713 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003714
3715 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003716 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003717 if (FullV->getType() != OpTy)
3718 FullV =
3719 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3720 OpTy, false),
3721 FullV, LF.OperandValToReplace->getType(),
3722 "tmp", BB->getTerminator());
3723
3724 PN->setIncomingValue(i, FullV);
3725 Pair.first->second = FullV;
3726 }
3727 }
3728}
3729
Dan Gohman572645c2010-02-12 10:34:29 +00003730/// Rewrite - Emit instructions for the leading candidate expression for this
3731/// LSRUse (this is called "expanding"), and update the UserInst to reference
3732/// the newly expanded value.
3733void LSRInstance::Rewrite(const LSRFixup &LF,
3734 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00003735 SCEVExpander &Rewriter,
3736 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00003737 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003738 // First, find an insertion point that dominates UserInst. For PHI nodes,
3739 // find the nearest block which dominates all the relevant uses.
3740 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman454d26d2010-02-22 04:11:59 +00003741 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003742 } else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003743 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman572645c2010-02-12 10:34:29 +00003744
3745 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003746 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003747 if (FullV->getType() != OpTy) {
3748 Instruction *Cast =
3749 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3750 FullV, OpTy, "tmp", LF.UserInst);
3751 FullV = Cast;
3752 }
3753
3754 // Update the user. ICmpZero is handled specially here (for now) because
3755 // Expand may have updated one of the operands of the icmp already, and
3756 // its new value may happen to be equal to LF.OperandValToReplace, in
3757 // which case doing replaceUsesOfWith leads to replacing both operands
3758 // with the same value. TODO: Reorganize this.
3759 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3760 LF.UserInst->setOperand(0, FullV);
3761 else
3762 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3763 }
3764
3765 DeadInsts.push_back(LF.OperandValToReplace);
3766}
3767
Dan Gohman76c315a2010-05-20 20:52:00 +00003768/// ImplementSolution - Rewrite all the fixup locations with new values,
3769/// following the chosen solution.
Dan Gohman572645c2010-02-12 10:34:29 +00003770void
3771LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3772 Pass *P) {
3773 // Keep track of instructions we may have made dead, so that
3774 // we can remove them after we are done working.
3775 SmallVector<WeakVH, 16> DeadInsts;
3776
Andrew Trick5e7645b2011-06-28 05:07:32 +00003777 SCEVExpander Rewriter(SE, "lsr");
Dan Gohman572645c2010-02-12 10:34:29 +00003778 Rewriter.disableCanonicalMode();
Andrew Trickc5701912011-10-07 23:46:21 +00003779 Rewriter.enableLSRMode();
Dan Gohman572645c2010-02-12 10:34:29 +00003780 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3781
3782 // Expand the new value definitions and update the users.
Dan Gohman402d4352010-05-20 20:33:18 +00003783 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3784 E = Fixups.end(); I != E; ++I) {
3785 const LSRFixup &Fixup = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00003786
Dan Gohman402d4352010-05-20 20:33:18 +00003787 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003788
3789 Changed = true;
3790 }
3791
3792 // Clean up after ourselves. This must be done before deleting any
3793 // instructions.
3794 Rewriter.clear();
3795
3796 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3797}
3798
3799LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3800 : IU(P->getAnalysis<IVUsers>()),
3801 SE(P->getAnalysis<ScalarEvolution>()),
3802 DT(P->getAnalysis<DominatorTree>()),
Dan Gohmane5f76872010-04-09 22:07:05 +00003803 LI(P->getAnalysis<LoopInfo>()),
Dan Gohman572645c2010-02-12 10:34:29 +00003804 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003805
Dan Gohman03e896b2009-11-05 21:11:53 +00003806 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003807 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003808
Dan Gohman572645c2010-02-12 10:34:29 +00003809 // If there's no interesting work to be done, bail early.
3810 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003811
Dan Gohman572645c2010-02-12 10:34:29 +00003812 DEBUG(dbgs() << "\nLSR on loop ";
3813 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3814 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003815
Dan Gohman402d4352010-05-20 20:33:18 +00003816 // First, perform some low-level loop optimizations.
Dan Gohman572645c2010-02-12 10:34:29 +00003817 OptimizeShadowIV();
Dan Gohmanc6519f92010-05-20 20:05:31 +00003818 OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003819
Andrew Trick37eb38d2011-07-21 00:40:04 +00003820 // If loop preparation eliminates all interesting IV users, bail.
3821 if (IU.empty()) return;
3822
Andrew Trick5219f862011-09-29 01:53:08 +00003823 // Skip nested loops until we can model them better with formulae.
Andrew Trick0c01bc32011-09-29 01:33:38 +00003824 if (!EnableNested && !L->empty()) {
Andrew Tricka02bfce2011-10-11 02:30:45 +00003825
3826 if (EnablePhiElim) {
3827 // Remove any extra phis created by processing inner loops.
3828 SmallVector<WeakVH, 16> DeadInsts;
3829 SCEVExpander Rewriter(SE, "lsr");
3830 Changed |= Rewriter.replaceCongruentIVs(L, &DT, DeadInsts);
3831 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3832 }
Andrew Trick0c01bc32011-09-29 01:33:38 +00003833 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
Andrew Trick5219f862011-09-29 01:53:08 +00003834 return;
Andrew Trick0c01bc32011-09-29 01:33:38 +00003835 }
3836
Dan Gohman402d4352010-05-20 20:33:18 +00003837 // Start collecting data and preparing for the solver.
Dan Gohman572645c2010-02-12 10:34:29 +00003838 CollectInterestingTypesAndFactors();
3839 CollectFixupsAndInitialFormulae();
3840 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003841
Dan Gohman572645c2010-02-12 10:34:29 +00003842 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3843 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003844
Dan Gohman572645c2010-02-12 10:34:29 +00003845 // Now use the reuse data to generate a bunch of interesting ways
3846 // to formulate the values needed for the uses.
3847 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003848
Dan Gohman572645c2010-02-12 10:34:29 +00003849 FilterOutUndesirableDedicatedRegisters();
3850 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003851
Dan Gohman572645c2010-02-12 10:34:29 +00003852 SmallVector<const Formula *, 8> Solution;
3853 Solve(Solution);
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003854
Dan Gohman572645c2010-02-12 10:34:29 +00003855 // Release memory that is no longer needed.
3856 Factors.clear();
3857 Types.clear();
3858 RegUses.clear();
3859
Andrew Trick80ef1b22011-09-27 00:44:14 +00003860 if (Solution.empty())
3861 return;
3862
Dan Gohman572645c2010-02-12 10:34:29 +00003863#ifndef NDEBUG
3864 // Formulae should be legal.
3865 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3866 E = Uses.end(); I != E; ++I) {
3867 const LSRUse &LU = *I;
3868 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3869 JE = LU.Formulae.end(); J != JE; ++J)
3870 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3871 LU.Kind, LU.AccessTy, TLI) &&
3872 "Illegal formula generated!");
3873 };
3874#endif
3875
3876 // Now that we've decided what we want, make it so.
3877 ImplementSolution(Solution, P);
Andrew Tricka02bfce2011-10-11 02:30:45 +00003878
3879 if (EnablePhiElim) {
3880 // Remove any extra phis created by processing inner loops.
3881 SmallVector<WeakVH, 16> DeadInsts;
3882 SCEVExpander Rewriter(SE, "lsr");
3883 Changed |= Rewriter.replaceCongruentIVs(L, &DT, DeadInsts);
3884 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3885 }
Dan Gohman572645c2010-02-12 10:34:29 +00003886}
3887
3888void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3889 if (Factors.empty() && Types.empty()) return;
3890
3891 OS << "LSR has identified the following interesting factors and types: ";
3892 bool First = true;
3893
3894 for (SmallSetVector<int64_t, 8>::const_iterator
3895 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3896 if (!First) OS << ", ";
3897 First = false;
3898 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003899 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003900
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003901 for (SmallSetVector<Type *, 4>::const_iterator
Dan Gohman572645c2010-02-12 10:34:29 +00003902 I = Types.begin(), E = Types.end(); I != E; ++I) {
3903 if (!First) OS << ", ";
3904 First = false;
3905 OS << '(' << **I << ')';
3906 }
3907 OS << '\n';
3908}
3909
3910void LSRInstance::print_fixups(raw_ostream &OS) const {
3911 OS << "LSR is examining the following fixup sites:\n";
3912 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3913 E = Fixups.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +00003914 dbgs() << " ";
Dan Gohman9f383eb2010-05-20 22:25:20 +00003915 I->print(OS);
Dan Gohman572645c2010-02-12 10:34:29 +00003916 OS << '\n';
3917 }
3918}
3919
3920void LSRInstance::print_uses(raw_ostream &OS) const {
3921 OS << "LSR is examining the following uses:\n";
3922 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3923 E = Uses.end(); I != E; ++I) {
3924 const LSRUse &LU = *I;
3925 dbgs() << " ";
3926 LU.print(OS);
3927 OS << '\n';
3928 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3929 JE = LU.Formulae.end(); J != JE; ++J) {
3930 OS << " ";
3931 J->print(OS);
3932 OS << '\n';
3933 }
3934 }
3935}
3936
3937void LSRInstance::print(raw_ostream &OS) const {
3938 print_factors_and_types(OS);
3939 print_fixups(OS);
3940 print_uses(OS);
3941}
3942
3943void LSRInstance::dump() const {
3944 print(errs()); errs() << '\n';
3945}
3946
3947namespace {
3948
3949class LoopStrengthReduce : public LoopPass {
3950 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3951 /// transformation profitability.
3952 const TargetLowering *const TLI;
3953
3954public:
3955 static char ID; // Pass ID, replacement for typeid
3956 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3957
3958private:
3959 bool runOnLoop(Loop *L, LPPassManager &LPM);
3960 void getAnalysisUsage(AnalysisUsage &AU) const;
3961};
3962
3963}
3964
3965char LoopStrengthReduce::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +00003966INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
Owen Andersonce665bd2010-10-07 22:25:06 +00003967 "Loop Strength Reduction", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +00003968INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3969INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3970INITIALIZE_PASS_DEPENDENCY(IVUsers)
Owen Anderson205942a2010-10-19 20:08:44 +00003971INITIALIZE_PASS_DEPENDENCY(LoopInfo)
3972INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Owen Anderson2ab36d32010-10-12 19:48:12 +00003973INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
3974 "Loop Strength Reduction", false, false)
3975
Dan Gohman572645c2010-02-12 10:34:29 +00003976
3977Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3978 return new LoopStrengthReduce(TLI);
3979}
3980
3981LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +00003982 : LoopPass(ID), TLI(tli) {
3983 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
3984 }
Dan Gohman572645c2010-02-12 10:34:29 +00003985
3986void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3987 // We split critical edges, so we change the CFG. However, we do update
3988 // many analyses if they are around.
Eric Christopher6793c492011-02-10 01:48:24 +00003989 AU.addPreservedID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00003990
Eric Christopher6793c492011-02-10 01:48:24 +00003991 AU.addRequired<LoopInfo>();
3992 AU.addPreserved<LoopInfo>();
3993 AU.addRequiredID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00003994 AU.addRequired<DominatorTree>();
3995 AU.addPreserved<DominatorTree>();
3996 AU.addRequired<ScalarEvolution>();
3997 AU.addPreserved<ScalarEvolution>();
Cameron Zwarich2c2b9332011-02-10 23:53:14 +00003998 // Requiring LoopSimplify a second time here prevents IVUsers from running
3999 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
4000 AU.addRequiredID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00004001 AU.addRequired<IVUsers>();
4002 AU.addPreserved<IVUsers>();
4003}
4004
4005bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
4006 bool Changed = false;
4007
4008 // Run the main LSR transformation.
4009 Changed |= LSRInstance(TLI, L, this).getChanged();
4010
Dan Gohmanafc36a92009-05-02 18:29:22 +00004011 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00004012 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00004013 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00004014
Evan Cheng1ce75dc2008-07-07 19:51:32 +00004015 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00004016}