blob: eaf8d945bbe536564abb9f0268fccf028ea807d9 [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 Lattnere0391be2005-08-12 22:06:11 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Nate Begemaneaa13852004-10-18 21:08:22 +000067#include "llvm/Transforms/Utils/Local.h"
Dan Gohman572645c2010-02-12 10:34:29 +000068#include "llvm/ADT/SmallBitVector.h"
69#include "llvm/ADT/SetVector.h"
70#include "llvm/ADT/DenseSet.h"
Nate Begeman16997482005-07-30 00:15:07 +000071#include "llvm/Support/Debug.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000072#include "llvm/Support/ValueHandle.h"
Daniel Dunbar460f6562009-07-26 09:48:23 +000073#include "llvm/Support/raw_ostream.h"
Evan Chengd277f2c2006-03-13 23:14:23 +000074#include "llvm/Target/TargetLowering.h"
Jeff Cohencfb1d422005-07-30 18:22:27 +000075#include <algorithm>
Nate Begemaneaa13852004-10-18 21:08:22 +000076using namespace llvm;
77
Dan Gohman572645c2010-02-12 10:34:29 +000078namespace {
Nate Begemaneaa13852004-10-18 21:08:22 +000079
Dan Gohman572645c2010-02-12 10:34:29 +000080/// RegSortData - This class holds data which is used to order reuse candidates.
81class RegSortData {
82public:
83 /// UsedByIndices - This represents the set of LSRUse indices which reference
84 /// a particular register.
85 SmallBitVector UsedByIndices;
86
87 RegSortData() {}
88
89 void print(raw_ostream &OS) const;
90 void dump() const;
91};
92
93}
94
95void RegSortData::print(raw_ostream &OS) const {
96 OS << "[NumUses=" << UsedByIndices.count() << ']';
97}
98
99void RegSortData::dump() const {
100 print(errs()); errs() << '\n';
101}
Dan Gohmanc17e0cf2009-02-20 04:17:46 +0000102
Chris Lattner0e5f4992006-12-19 21:40:18 +0000103namespace {
Dale Johannesendc42f482007-03-20 00:47:50 +0000104
Dan Gohman572645c2010-02-12 10:34:29 +0000105/// RegUseTracker - Map register candidates to information about how they are
106/// used.
107class RegUseTracker {
108 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
Dale Johannesendc42f482007-03-20 00:47:50 +0000109
Dan Gohman90bb3552010-05-18 22:33:00 +0000110 RegUsesTy RegUsesMap;
Dan Gohman572645c2010-02-12 10:34:29 +0000111 SmallVector<const SCEV *, 16> RegSequence;
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000112
Dan Gohman572645c2010-02-12 10:34:29 +0000113public:
114 void CountRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000115
Dan Gohman572645c2010-02-12 10:34:29 +0000116 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000117
Dan Gohman572645c2010-02-12 10:34:29 +0000118 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000119
Dan Gohman572645c2010-02-12 10:34:29 +0000120 void clear();
Dan Gohmana10756e2010-01-21 02:09:26 +0000121
Dan Gohman572645c2010-02-12 10:34:29 +0000122 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
123 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
124 iterator begin() { return RegSequence.begin(); }
125 iterator end() { return RegSequence.end(); }
126 const_iterator begin() const { return RegSequence.begin(); }
127 const_iterator end() const { return RegSequence.end(); }
128};
Dan Gohmana10756e2010-01-21 02:09:26 +0000129
Dan Gohmana10756e2010-01-21 02:09:26 +0000130}
131
Dan Gohman572645c2010-02-12 10:34:29 +0000132void
133RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
134 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman90bb3552010-05-18 22:33:00 +0000135 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman572645c2010-02-12 10:34:29 +0000136 RegSortData &RSD = Pair.first->second;
137 if (Pair.second)
138 RegSequence.push_back(Reg);
139 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
140 RSD.UsedByIndices.set(LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000141}
142
Dan Gohman572645c2010-02-12 10:34:29 +0000143bool
144RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman90bb3552010-05-18 22:33:00 +0000145 if (!RegUsesMap.count(Reg)) return false;
Dan Gohman572645c2010-02-12 10:34:29 +0000146 const SmallBitVector &UsedByIndices =
Dan Gohman90bb3552010-05-18 22:33:00 +0000147 RegUsesMap.find(Reg)->second.UsedByIndices;
Dan Gohman572645c2010-02-12 10:34:29 +0000148 int i = UsedByIndices.find_first();
149 if (i == -1) return false;
150 if ((size_t)i != LUIdx) return true;
151 return UsedByIndices.find_next(i) != -1;
152}
Dan Gohmana10756e2010-01-21 02:09:26 +0000153
Dan Gohman572645c2010-02-12 10:34:29 +0000154const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman90bb3552010-05-18 22:33:00 +0000155 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
156 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman572645c2010-02-12 10:34:29 +0000157 return I->second.UsedByIndices;
158}
Dan Gohmana10756e2010-01-21 02:09:26 +0000159
Dan Gohman572645c2010-02-12 10:34:29 +0000160void RegUseTracker::clear() {
Dan Gohman90bb3552010-05-18 22:33:00 +0000161 RegUsesMap.clear();
Dan Gohman572645c2010-02-12 10:34:29 +0000162 RegSequence.clear();
163}
Dan Gohmana10756e2010-01-21 02:09:26 +0000164
Dan Gohman572645c2010-02-12 10:34:29 +0000165namespace {
166
167/// Formula - This class holds information that describes a formula for
168/// computing satisfying a use. It may include broken-out immediates and scaled
169/// registers.
170struct Formula {
171 /// AM - This is used to represent complex addressing, as well as other kinds
172 /// of interesting uses.
173 TargetLowering::AddrMode AM;
174
175 /// BaseRegs - The list of "base" registers for this use. When this is
176 /// non-empty, AM.HasBaseReg should be set to true.
177 SmallVector<const SCEV *, 2> BaseRegs;
178
179 /// ScaledReg - The 'scaled' register for this use. This should be non-null
180 /// when AM.Scale is not zero.
181 const SCEV *ScaledReg;
182
183 Formula() : ScaledReg(0) {}
184
185 void InitialMatch(const SCEV *S, Loop *L,
186 ScalarEvolution &SE, DominatorTree &DT);
187
188 unsigned getNumRegs() const;
189 const Type *getType() const;
190
191 bool referencesReg(const SCEV *S) const;
192 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
193 const RegUseTracker &RegUses) const;
194
195 void print(raw_ostream &OS) const;
196 void dump() const;
197};
198
199}
200
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000201/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman572645c2010-02-12 10:34:29 +0000202static void DoInitialMatch(const SCEV *S, Loop *L,
203 SmallVectorImpl<const SCEV *> &Good,
204 SmallVectorImpl<const SCEV *> &Bad,
205 ScalarEvolution &SE, DominatorTree &DT) {
206 // Collect expressions which properly dominate the loop header.
207 if (S->properlyDominates(L->getHeader(), &DT)) {
208 Good.push_back(S);
209 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000210 }
Dan Gohman572645c2010-02-12 10:34:29 +0000211
212 // Look at add operands.
213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
214 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
215 I != E; ++I)
216 DoInitialMatch(*I, L, Good, Bad, SE, DT);
217 return;
218 }
219
220 // Look at addrec operands.
221 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
222 if (!AR->getStart()->isZero()) {
223 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
Dan Gohmandeff6212010-05-03 22:09:21 +0000224 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +0000225 AR->getStepRecurrence(SE),
226 AR->getLoop()),
227 L, Good, Bad, SE, DT);
228 return;
229 }
230
231 // Handle a multiplication by -1 (negation) if it didn't fold.
232 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
233 if (Mul->getOperand(0)->isAllOnesValue()) {
234 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
235 const SCEV *NewMul = SE.getMulExpr(Ops);
236
237 SmallVector<const SCEV *, 4> MyGood;
238 SmallVector<const SCEV *, 4> MyBad;
239 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
240 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
241 SE.getEffectiveSCEVType(NewMul->getType())));
242 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
243 E = MyGood.end(); I != E; ++I)
244 Good.push_back(SE.getMulExpr(NegOne, *I));
245 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
246 E = MyBad.end(); I != E; ++I)
247 Bad.push_back(SE.getMulExpr(NegOne, *I));
248 return;
249 }
250
251 // Ok, we can't do anything interesting. Just stuff the whole thing into a
252 // register and hope for the best.
253 Bad.push_back(S);
254}
255
256/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
257/// attempting to keep all loop-invariant and loop-computable values in a
258/// single base register.
259void Formula::InitialMatch(const SCEV *S, Loop *L,
260 ScalarEvolution &SE, DominatorTree &DT) {
261 SmallVector<const SCEV *, 4> Good;
262 SmallVector<const SCEV *, 4> Bad;
263 DoInitialMatch(S, L, Good, Bad, SE, DT);
264 if (!Good.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000265 const SCEV *Sum = SE.getAddExpr(Good);
266 if (!Sum->isZero())
267 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000268 AM.HasBaseReg = true;
269 }
270 if (!Bad.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000271 const SCEV *Sum = SE.getAddExpr(Bad);
272 if (!Sum->isZero())
273 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000274 AM.HasBaseReg = true;
275 }
276}
277
278/// getNumRegs - Return the total number of register operands used by this
279/// formula. This does not include register uses implied by non-constant
280/// addrec strides.
281unsigned Formula::getNumRegs() const {
282 return !!ScaledReg + BaseRegs.size();
283}
284
285/// getType - Return the type of this formula, if it has one, or null
286/// otherwise. This type is meaningless except for the bit size.
287const Type *Formula::getType() const {
288 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
289 ScaledReg ? ScaledReg->getType() :
290 AM.BaseGV ? AM.BaseGV->getType() :
291 0;
292}
293
294/// referencesReg - Test if this formula references the given register.
295bool Formula::referencesReg(const SCEV *S) const {
296 return S == ScaledReg ||
297 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
298}
299
300/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
301/// which are used by uses other than the use with the given index.
302bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
303 const RegUseTracker &RegUses) const {
304 if (ScaledReg)
305 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
306 return true;
307 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
308 E = BaseRegs.end(); I != E; ++I)
309 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
310 return true;
311 return false;
312}
313
314void Formula::print(raw_ostream &OS) const {
315 bool First = true;
316 if (AM.BaseGV) {
317 if (!First) OS << " + "; else First = false;
318 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
319 }
320 if (AM.BaseOffs != 0) {
321 if (!First) OS << " + "; else First = false;
322 OS << AM.BaseOffs;
323 }
324 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
325 E = BaseRegs.end(); I != E; ++I) {
326 if (!First) OS << " + "; else First = false;
327 OS << "reg(" << **I << ')';
328 }
Dan Gohmanc4cfbaf2010-05-18 22:35:55 +0000329 if (AM.HasBaseReg && BaseRegs.empty()) {
330 if (!First) OS << " + "; else First = false;
331 OS << "**error: HasBaseReg**";
332 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
333 if (!First) OS << " + "; else First = false;
334 OS << "**error: !HasBaseReg**";
335 }
Dan Gohman572645c2010-02-12 10:34:29 +0000336 if (AM.Scale != 0) {
337 if (!First) OS << " + "; else First = false;
338 OS << AM.Scale << "*reg(";
339 if (ScaledReg)
340 OS << *ScaledReg;
341 else
342 OS << "<unknown>";
343 OS << ')';
344 }
345}
346
347void Formula::dump() const {
348 print(errs()); errs() << '\n';
349}
350
Dan Gohmanaae01f12010-02-19 19:32:49 +0000351/// isAddRecSExtable - Return true if the given addrec can be sign-extended
352/// without changing its value.
353static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
354 const Type *WideTy =
355 IntegerType::get(SE.getContext(),
356 SE.getTypeSizeInBits(AR->getType()) + 1);
357 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
358}
359
360/// isAddSExtable - Return true if the given add can be sign-extended
361/// without changing its value.
362static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
363 const Type *WideTy =
364 IntegerType::get(SE.getContext(),
365 SE.getTypeSizeInBits(A->getType()) + 1);
366 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
367}
368
369/// isMulSExtable - Return true if the given add can be sign-extended
370/// without changing its value.
371static bool isMulSExtable(const SCEVMulExpr *A, ScalarEvolution &SE) {
372 const Type *WideTy =
373 IntegerType::get(SE.getContext(),
374 SE.getTypeSizeInBits(A->getType()) + 1);
375 return isa<SCEVMulExpr>(SE.getSignExtendExpr(A, WideTy));
376}
377
Dan Gohmanf09b7122010-02-19 19:35:48 +0000378/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
379/// and if the remainder is known to be zero, or null otherwise. If
380/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
381/// to Y, ignoring that the multiplication may overflow, which is useful when
382/// the result will be used in a context where the most significant bits are
383/// ignored.
384static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
385 ScalarEvolution &SE,
386 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000387 // Handle the trivial case, which works for any SCEV type.
388 if (LHS == RHS)
Dan Gohmandeff6212010-05-03 22:09:21 +0000389 return SE.getConstant(LHS->getType(), 1);
Dan Gohman572645c2010-02-12 10:34:29 +0000390
391 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
392 // folding.
393 if (RHS->isAllOnesValue())
394 return SE.getMulExpr(LHS, RHS);
395
396 // Check for a division of a constant by a constant.
397 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
398 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
399 if (!RC)
400 return 0;
401 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
402 return 0;
403 return SE.getConstant(C->getValue()->getValue()
404 .sdiv(RC->getValue()->getValue()));
405 }
406
Dan Gohmanaae01f12010-02-19 19:32:49 +0000407 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000408 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000409 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000410 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
411 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000412 if (!Start) return 0;
Dan Gohmanf09b7122010-02-19 19:35:48 +0000413 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
414 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000415 if (!Step) return 0;
416 return SE.getAddRecExpr(Start, Step, AR->getLoop());
417 }
Dan Gohman572645c2010-02-12 10:34:29 +0000418 }
419
Dan Gohmanaae01f12010-02-19 19:32:49 +0000420 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000421 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000422 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
423 SmallVector<const SCEV *, 8> Ops;
424 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
425 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000426 const SCEV *Op = getExactSDiv(*I, RHS, SE,
427 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000428 if (!Op) return 0;
429 Ops.push_back(Op);
430 }
431 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000432 }
Dan Gohman572645c2010-02-12 10:34:29 +0000433 }
434
435 // Check for a multiply operand that we can pull RHS out of.
436 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
Dan Gohmanaae01f12010-02-19 19:32:49 +0000437 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000438 SmallVector<const SCEV *, 4> Ops;
439 bool Found = false;
440 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
441 I != E; ++I) {
442 if (!Found)
Dan Gohmanf09b7122010-02-19 19:35:48 +0000443 if (const SCEV *Q = getExactSDiv(*I, RHS, SE,
444 IgnoreSignificantBits)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000445 Ops.push_back(Q);
446 Found = true;
447 continue;
448 }
449 Ops.push_back(*I);
450 }
451 return Found ? SE.getMulExpr(Ops) : 0;
452 }
453
454 // Otherwise we don't know.
455 return 0;
456}
457
458/// ExtractImmediate - If S involves the addition of a constant integer value,
459/// return that integer value, and mutate S to point to a new SCEV with that
460/// value excluded.
461static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
462 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
463 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000464 S = SE.getConstant(C->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000465 return C->getValue()->getSExtValue();
466 }
467 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
468 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
469 int64_t Result = ExtractImmediate(NewOps.front(), SE);
470 S = SE.getAddExpr(NewOps);
471 return Result;
472 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
473 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
474 int64_t Result = ExtractImmediate(NewOps.front(), SE);
475 S = SE.getAddRecExpr(NewOps, AR->getLoop());
476 return Result;
477 }
478 return 0;
479}
480
481/// ExtractSymbol - If S involves the addition of a GlobalValue address,
482/// return that symbol, and mutate S to point to a new SCEV with that
483/// value excluded.
484static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
485 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
486 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000487 S = SE.getConstant(GV->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000488 return GV;
489 }
490 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
491 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
492 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
493 S = SE.getAddExpr(NewOps);
494 return Result;
495 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
496 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
497 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
498 S = SE.getAddRecExpr(NewOps, AR->getLoop());
499 return Result;
500 }
501 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000502}
503
Dan Gohmanf284ce22009-02-18 00:08:39 +0000504/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000505/// specified value as an address.
506static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
507 bool isAddress = isa<LoadInst>(Inst);
508 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
509 if (SI->getOperand(1) == OperandVal)
510 isAddress = true;
511 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
512 // Addressing modes can also be folded into prefetches and a variety
513 // of intrinsics.
514 switch (II->getIntrinsicID()) {
515 default: break;
516 case Intrinsic::prefetch:
517 case Intrinsic::x86_sse2_loadu_dq:
518 case Intrinsic::x86_sse2_loadu_pd:
519 case Intrinsic::x86_sse_loadu_ps:
520 case Intrinsic::x86_sse_storeu_ps:
521 case Intrinsic::x86_sse2_storeu_pd:
522 case Intrinsic::x86_sse2_storeu_dq:
523 case Intrinsic::x86_sse2_storel_dq:
524 if (II->getOperand(1) == OperandVal)
525 isAddress = true;
526 break;
527 }
528 }
529 return isAddress;
530}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000531
Dan Gohman21e77222009-03-09 21:01:17 +0000532/// getAccessType - Return the type of the memory being accessed.
533static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000534 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000535 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000536 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000537 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
538 // Addressing modes can also be folded into prefetches and a variety
539 // of intrinsics.
540 switch (II->getIntrinsicID()) {
541 default: break;
542 case Intrinsic::x86_sse_storeu_ps:
543 case Intrinsic::x86_sse2_storeu_pd:
544 case Intrinsic::x86_sse2_storeu_dq:
545 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmana537bf82009-05-18 16:45:28 +0000546 AccessTy = II->getOperand(1)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000547 break;
548 }
549 }
Dan Gohman572645c2010-02-12 10:34:29 +0000550
551 // All pointers have the same requirements, so canonicalize them to an
552 // arbitrary pointer type to minimize variation.
553 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
554 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
555 PTy->getAddressSpace());
556
Dan Gohmana537bf82009-05-18 16:45:28 +0000557 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000558}
559
Dan Gohman572645c2010-02-12 10:34:29 +0000560/// DeleteTriviallyDeadInstructions - If any of the instructions is the
561/// specified set are trivially dead, delete them and see if this makes any of
562/// their operands subsequently dead.
563static bool
564DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
565 bool Changed = false;
566
567 while (!DeadInsts.empty()) {
568 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
569
570 if (I == 0 || !isInstructionTriviallyDead(I))
571 continue;
572
573 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
574 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
575 *OI = 0;
576 if (U->use_empty())
577 DeadInsts.push_back(U);
578 }
579
580 I->eraseFromParent();
581 Changed = true;
582 }
583
584 return Changed;
585}
586
Dan Gohman7979b722010-01-22 00:46:49 +0000587namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000588
Dan Gohman572645c2010-02-12 10:34:29 +0000589/// Cost - This class is used to measure and compare candidate formulae.
590class Cost {
591 /// TODO: Some of these could be merged. Also, a lexical ordering
592 /// isn't always optimal.
593 unsigned NumRegs;
594 unsigned AddRecCost;
595 unsigned NumIVMuls;
596 unsigned NumBaseAdds;
597 unsigned ImmCost;
598 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000599
Dan Gohman572645c2010-02-12 10:34:29 +0000600public:
601 Cost()
602 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
603 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000604
Dan Gohman572645c2010-02-12 10:34:29 +0000605 unsigned getNumRegs() const { return NumRegs; }
Dan Gohman7979b722010-01-22 00:46:49 +0000606
Dan Gohman572645c2010-02-12 10:34:29 +0000607 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000608
Dan Gohman572645c2010-02-12 10:34:29 +0000609 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000610
Dan Gohman572645c2010-02-12 10:34:29 +0000611 void RateFormula(const Formula &F,
612 SmallPtrSet<const SCEV *, 16> &Regs,
613 const DenseSet<const SCEV *> &VisitedRegs,
614 const Loop *L,
615 const SmallVectorImpl<int64_t> &Offsets,
616 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000617
Dan Gohman572645c2010-02-12 10:34:29 +0000618 void print(raw_ostream &OS) const;
619 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000620
Dan Gohman572645c2010-02-12 10:34:29 +0000621private:
622 void RateRegister(const SCEV *Reg,
623 SmallPtrSet<const SCEV *, 16> &Regs,
624 const Loop *L,
625 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000626 void RatePrimaryRegister(const SCEV *Reg,
627 SmallPtrSet<const SCEV *, 16> &Regs,
628 const Loop *L,
629 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000630};
631
632}
633
634/// RateRegister - Tally up interesting quantities from the given register.
635void Cost::RateRegister(const SCEV *Reg,
636 SmallPtrSet<const SCEV *, 16> &Regs,
637 const Loop *L,
638 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000639 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
640 if (AR->getLoop() == L)
641 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000642
Dan Gohman9214b822010-02-13 02:06:02 +0000643 // If this is an addrec for a loop that's already been visited by LSR,
644 // don't second-guess its addrec phi nodes. LSR isn't currently smart
645 // enough to reason about more than one loop at a time. Consider these
646 // registers free and leave them alone.
647 else if (L->contains(AR->getLoop()) ||
648 (!AR->getLoop()->contains(L) &&
649 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
650 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
651 PHINode *PN = dyn_cast<PHINode>(I); ++I)
652 if (SE.isSCEVable(PN->getType()) &&
653 (SE.getEffectiveSCEVType(PN->getType()) ==
654 SE.getEffectiveSCEVType(AR->getType())) &&
655 SE.getSCEV(PN) == AR)
656 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000657
Dan Gohman9214b822010-02-13 02:06:02 +0000658 // If this isn't one of the addrecs that the loop already has, it
659 // would require a costly new phi and add. TODO: This isn't
660 // precisely modeled right now.
661 ++NumBaseAdds;
662 if (!Regs.count(AR->getStart()))
Dan Gohman572645c2010-02-12 10:34:29 +0000663 RateRegister(AR->getStart(), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000664 }
Dan Gohman572645c2010-02-12 10:34:29 +0000665
Dan Gohman9214b822010-02-13 02:06:02 +0000666 // Add the step value register, if it needs one.
667 // TODO: The non-affine case isn't precisely modeled here.
668 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
669 if (!Regs.count(AR->getStart()))
670 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000671 }
Dan Gohman9214b822010-02-13 02:06:02 +0000672 ++NumRegs;
673
674 // Rough heuristic; favor registers which don't require extra setup
675 // instructions in the preheader.
676 if (!isa<SCEVUnknown>(Reg) &&
677 !isa<SCEVConstant>(Reg) &&
678 !(isa<SCEVAddRecExpr>(Reg) &&
679 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
680 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
681 ++SetupCost;
682}
683
684/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
685/// before, rate it.
686void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000687 SmallPtrSet<const SCEV *, 16> &Regs,
688 const Loop *L,
689 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000690 if (Regs.insert(Reg))
691 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000692}
693
694void Cost::RateFormula(const Formula &F,
695 SmallPtrSet<const SCEV *, 16> &Regs,
696 const DenseSet<const SCEV *> &VisitedRegs,
697 const Loop *L,
698 const SmallVectorImpl<int64_t> &Offsets,
699 ScalarEvolution &SE, DominatorTree &DT) {
700 // Tally up the registers.
701 if (const SCEV *ScaledReg = F.ScaledReg) {
702 if (VisitedRegs.count(ScaledReg)) {
703 Loose();
704 return;
705 }
Dan Gohman9214b822010-02-13 02:06:02 +0000706 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000707 }
708 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
709 E = F.BaseRegs.end(); I != E; ++I) {
710 const SCEV *BaseReg = *I;
711 if (VisitedRegs.count(BaseReg)) {
712 Loose();
713 return;
714 }
Dan Gohman9214b822010-02-13 02:06:02 +0000715 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000716
717 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
718 BaseReg->hasComputableLoopEvolution(L);
719 }
720
721 if (F.BaseRegs.size() > 1)
722 NumBaseAdds += F.BaseRegs.size() - 1;
723
724 // Tally up the non-zero immediates.
725 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
726 E = Offsets.end(); I != E; ++I) {
727 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
728 if (F.AM.BaseGV)
729 ImmCost += 64; // Handle symbolic values conservatively.
730 // TODO: This should probably be the pointer size.
731 else if (Offset != 0)
732 ImmCost += APInt(64, Offset, true).getMinSignedBits();
733 }
734}
735
736/// Loose - Set this cost to a loosing value.
737void Cost::Loose() {
738 NumRegs = ~0u;
739 AddRecCost = ~0u;
740 NumIVMuls = ~0u;
741 NumBaseAdds = ~0u;
742 ImmCost = ~0u;
743 SetupCost = ~0u;
744}
745
746/// operator< - Choose the lower cost.
747bool Cost::operator<(const Cost &Other) const {
748 if (NumRegs != Other.NumRegs)
749 return NumRegs < Other.NumRegs;
750 if (AddRecCost != Other.AddRecCost)
751 return AddRecCost < Other.AddRecCost;
752 if (NumIVMuls != Other.NumIVMuls)
753 return NumIVMuls < Other.NumIVMuls;
754 if (NumBaseAdds != Other.NumBaseAdds)
755 return NumBaseAdds < Other.NumBaseAdds;
756 if (ImmCost != Other.ImmCost)
757 return ImmCost < Other.ImmCost;
758 if (SetupCost != Other.SetupCost)
759 return SetupCost < Other.SetupCost;
760 return false;
761}
762
763void Cost::print(raw_ostream &OS) const {
764 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
765 if (AddRecCost != 0)
766 OS << ", with addrec cost " << AddRecCost;
767 if (NumIVMuls != 0)
768 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
769 if (NumBaseAdds != 0)
770 OS << ", plus " << NumBaseAdds << " base add"
771 << (NumBaseAdds == 1 ? "" : "s");
772 if (ImmCost != 0)
773 OS << ", plus " << ImmCost << " imm cost";
774 if (SetupCost != 0)
775 OS << ", plus " << SetupCost << " setup cost";
776}
777
778void Cost::dump() const {
779 print(errs()); errs() << '\n';
780}
781
782namespace {
783
784/// LSRFixup - An operand value in an instruction which is to be replaced
785/// with some equivalent, possibly strength-reduced, replacement.
786struct LSRFixup {
787 /// UserInst - The instruction which will be updated.
788 Instruction *UserInst;
789
790 /// OperandValToReplace - The operand of the instruction which will
791 /// be replaced. The operand may be used more than once; every instance
792 /// will be replaced.
793 Value *OperandValToReplace;
794
Dan Gohman448db1c2010-04-07 22:27:08 +0000795 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman572645c2010-02-12 10:34:29 +0000796 /// induction variable, this variable is non-null and holds the loop
797 /// associated with the induction variable.
Dan Gohman448db1c2010-04-07 22:27:08 +0000798 PostIncLoopSet PostIncLoops;
Dan Gohman572645c2010-02-12 10:34:29 +0000799
800 /// LUIdx - The index of the LSRUse describing the expression which
801 /// this fixup needs, minus an offset (below).
802 size_t LUIdx;
803
804 /// Offset - A constant offset to be added to the LSRUse expression.
805 /// This allows multiple fixups to share the same LSRUse with different
806 /// offsets, for example in an unrolled loop.
807 int64_t Offset;
808
Dan Gohman448db1c2010-04-07 22:27:08 +0000809 bool isUseFullyOutsideLoop(const Loop *L) const;
810
Dan Gohman572645c2010-02-12 10:34:29 +0000811 LSRFixup();
812
813 void print(raw_ostream &OS) const;
814 void dump() const;
815};
816
817}
818
819LSRFixup::LSRFixup()
Dan Gohman448db1c2010-04-07 22:27:08 +0000820 : UserInst(0), OperandValToReplace(0),
Dan Gohman572645c2010-02-12 10:34:29 +0000821 LUIdx(~size_t(0)), Offset(0) {}
822
Dan Gohman448db1c2010-04-07 22:27:08 +0000823/// isUseFullyOutsideLoop - Test whether this fixup always uses its
824/// value outside of the given loop.
825bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
826 // PHI nodes use their value in their incoming blocks.
827 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
828 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
829 if (PN->getIncomingValue(i) == OperandValToReplace &&
830 L->contains(PN->getIncomingBlock(i)))
831 return false;
832 return true;
833 }
834
835 return !L->contains(UserInst);
836}
837
Dan Gohman572645c2010-02-12 10:34:29 +0000838void LSRFixup::print(raw_ostream &OS) const {
839 OS << "UserInst=";
840 // Store is common and interesting enough to be worth special-casing.
841 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
842 OS << "store ";
843 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
844 } else if (UserInst->getType()->isVoidTy())
845 OS << UserInst->getOpcodeName();
846 else
847 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
848
849 OS << ", OperandValToReplace=";
850 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
851
Dan Gohman448db1c2010-04-07 22:27:08 +0000852 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
853 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +0000854 OS << ", PostIncLoop=";
Dan Gohman448db1c2010-04-07 22:27:08 +0000855 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
Dan Gohman572645c2010-02-12 10:34:29 +0000856 }
857
858 if (LUIdx != ~size_t(0))
859 OS << ", LUIdx=" << LUIdx;
860
861 if (Offset != 0)
862 OS << ", Offset=" << Offset;
863}
864
865void LSRFixup::dump() const {
866 print(errs()); errs() << '\n';
867}
868
869namespace {
870
871/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
872/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
873struct UniquifierDenseMapInfo {
874 static SmallVector<const SCEV *, 2> getEmptyKey() {
875 SmallVector<const SCEV *, 2> V;
876 V.push_back(reinterpret_cast<const SCEV *>(-1));
877 return V;
878 }
879
880 static SmallVector<const SCEV *, 2> getTombstoneKey() {
881 SmallVector<const SCEV *, 2> V;
882 V.push_back(reinterpret_cast<const SCEV *>(-2));
883 return V;
884 }
885
886 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
887 unsigned Result = 0;
888 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
889 E = V.end(); I != E; ++I)
890 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
891 return Result;
892 }
893
894 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
895 const SmallVector<const SCEV *, 2> &RHS) {
896 return LHS == RHS;
897 }
898};
899
900/// LSRUse - This class holds the state that LSR keeps for each use in
901/// IVUsers, as well as uses invented by LSR itself. It includes information
902/// about what kinds of things can be folded into the user, information about
903/// the user itself, and information about how the use may be satisfied.
904/// TODO: Represent multiple users of the same expression in common?
905class LSRUse {
906 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
907
908public:
909 /// KindType - An enum for a kind of use, indicating what types of
910 /// scaled and immediate operands it might support.
911 enum KindType {
912 Basic, ///< A normal use, with no folding.
913 Special, ///< A special case of basic, allowing -1 scales.
914 Address, ///< An address use; folding according to TargetLowering
915 ICmpZero ///< An equality icmp with both operands folded into one.
916 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000917 };
Dan Gohman572645c2010-02-12 10:34:29 +0000918
919 KindType Kind;
920 const Type *AccessTy;
921
922 SmallVector<int64_t, 8> Offsets;
923 int64_t MinOffset;
924 int64_t MaxOffset;
925
926 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
927 /// LSRUse are outside of the loop, in which case some special-case heuristics
928 /// may be used.
929 bool AllFixupsOutsideLoop;
930
931 /// Formulae - A list of ways to build a value that can satisfy this user.
932 /// After the list is populated, one of these is selected heuristically and
933 /// used to formulate a replacement for OperandValToReplace in UserInst.
934 SmallVector<Formula, 12> Formulae;
935
936 /// Regs - The set of register candidates used by all formulae in this LSRUse.
937 SmallPtrSet<const SCEV *, 4> Regs;
938
939 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
940 MinOffset(INT64_MAX),
941 MaxOffset(INT64_MIN),
942 AllFixupsOutsideLoop(true) {}
943
Dan Gohman454d26d2010-02-22 04:11:59 +0000944 bool InsertFormula(const Formula &F);
Dan Gohman572645c2010-02-12 10:34:29 +0000945
946 void check() const;
947
948 void print(raw_ostream &OS) const;
949 void dump() const;
950};
951
952/// InsertFormula - If the given formula has not yet been inserted, add it to
953/// the list, and return true. Return false otherwise.
Dan Gohman454d26d2010-02-22 04:11:59 +0000954bool LSRUse::InsertFormula(const Formula &F) {
Dan Gohman572645c2010-02-12 10:34:29 +0000955 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
956 if (F.ScaledReg) Key.push_back(F.ScaledReg);
957 // Unstable sort by host order ok, because this is only used for uniquifying.
958 std::sort(Key.begin(), Key.end());
959
960 if (!Uniquifier.insert(Key).second)
961 return false;
962
963 // Using a register to hold the value of 0 is not profitable.
964 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
965 "Zero allocated in a scaled register!");
966#ifndef NDEBUG
967 for (SmallVectorImpl<const SCEV *>::const_iterator I =
968 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
969 assert(!(*I)->isZero() && "Zero allocated in a base register!");
970#endif
971
972 // Add the formula to the list.
973 Formulae.push_back(F);
974
975 // Record registers now being used by this use.
976 if (F.ScaledReg) Regs.insert(F.ScaledReg);
977 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
978
979 return true;
Dan Gohman7979b722010-01-22 00:46:49 +0000980}
981
Dan Gohman572645c2010-02-12 10:34:29 +0000982void LSRUse::print(raw_ostream &OS) const {
983 OS << "LSR Use: Kind=";
984 switch (Kind) {
985 case Basic: OS << "Basic"; break;
986 case Special: OS << "Special"; break;
987 case ICmpZero: OS << "ICmpZero"; break;
988 case Address:
989 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +0000990 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +0000991 OS << "pointer"; // the full pointer type could be really verbose
992 else
993 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +0000994 }
995
Dan Gohman572645c2010-02-12 10:34:29 +0000996 OS << ", Offsets={";
997 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
998 E = Offsets.end(); I != E; ++I) {
999 OS << *I;
1000 if (next(I) != E)
1001 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +00001002 }
Dan Gohman572645c2010-02-12 10:34:29 +00001003 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +00001004
Dan Gohman572645c2010-02-12 10:34:29 +00001005 if (AllFixupsOutsideLoop)
1006 OS << ", all-fixups-outside-loop";
Dan Gohman7979b722010-01-22 00:46:49 +00001007}
1008
Dan Gohman572645c2010-02-12 10:34:29 +00001009void LSRUse::dump() const {
1010 print(errs()); errs() << '\n';
1011}
Dan Gohman7979b722010-01-22 00:46:49 +00001012
Dan Gohman572645c2010-02-12 10:34:29 +00001013/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1014/// be completely folded into the user instruction at isel time. This includes
1015/// address-mode folding and special icmp tricks.
1016static bool isLegalUse(const TargetLowering::AddrMode &AM,
1017 LSRUse::KindType Kind, const Type *AccessTy,
1018 const TargetLowering *TLI) {
1019 switch (Kind) {
1020 case LSRUse::Address:
1021 // If we have low-level target information, ask the target if it can
1022 // completely fold this address.
1023 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1024
1025 // Otherwise, just guess that reg+reg addressing is legal.
1026 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1027
1028 case LSRUse::ICmpZero:
1029 // There's not even a target hook for querying whether it would be legal to
1030 // fold a GV into an ICmp.
1031 if (AM.BaseGV)
1032 return false;
1033
1034 // ICmp only has two operands; don't allow more than two non-trivial parts.
1035 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1036 return false;
1037
1038 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1039 // putting the scaled register in the other operand of the icmp.
1040 if (AM.Scale != 0 && AM.Scale != -1)
1041 return false;
1042
1043 // If we have low-level target information, ask the target if it can fold an
1044 // integer immediate on an icmp.
1045 if (AM.BaseOffs != 0) {
1046 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1047 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001048 }
Dan Gohman572645c2010-02-12 10:34:29 +00001049
1050 return true;
1051
1052 case LSRUse::Basic:
1053 // Only handle single-register values.
1054 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1055
1056 case LSRUse::Special:
1057 // Only handle -1 scales, or no scale.
1058 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001059 }
1060
Dan Gohman7979b722010-01-22 00:46:49 +00001061 return false;
1062}
1063
Dan Gohman572645c2010-02-12 10:34:29 +00001064static bool isLegalUse(TargetLowering::AddrMode AM,
1065 int64_t MinOffset, int64_t MaxOffset,
1066 LSRUse::KindType Kind, const Type *AccessTy,
1067 const TargetLowering *TLI) {
1068 // Check for overflow.
1069 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1070 (MinOffset > 0))
1071 return false;
1072 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1073 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1074 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1075 // Check for overflow.
1076 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1077 (MaxOffset > 0))
1078 return false;
1079 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1080 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001081 }
Dan Gohman572645c2010-02-12 10:34:29 +00001082 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001083}
1084
Dan Gohman572645c2010-02-12 10:34:29 +00001085static bool isAlwaysFoldable(int64_t BaseOffs,
1086 GlobalValue *BaseGV,
1087 bool HasBaseReg,
1088 LSRUse::KindType Kind, const Type *AccessTy,
Dan Gohman454d26d2010-02-22 04:11:59 +00001089 const TargetLowering *TLI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001090 // Fast-path: zero is always foldable.
1091 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001092
Dan Gohman572645c2010-02-12 10:34:29 +00001093 // Conservatively, create an address with an immediate and a
1094 // base and a scale.
1095 TargetLowering::AddrMode AM;
1096 AM.BaseOffs = BaseOffs;
1097 AM.BaseGV = BaseGV;
1098 AM.HasBaseReg = HasBaseReg;
1099 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001100
Dan Gohman572645c2010-02-12 10:34:29 +00001101 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001102}
1103
Dan Gohman572645c2010-02-12 10:34:29 +00001104static bool isAlwaysFoldable(const SCEV *S,
1105 int64_t MinOffset, int64_t MaxOffset,
1106 bool HasBaseReg,
1107 LSRUse::KindType Kind, const Type *AccessTy,
1108 const TargetLowering *TLI,
1109 ScalarEvolution &SE) {
1110 // Fast-path: zero is always foldable.
1111 if (S->isZero()) return true;
1112
1113 // Conservatively, create an address with an immediate and a
1114 // base and a scale.
1115 int64_t BaseOffs = ExtractImmediate(S, SE);
1116 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1117
1118 // If there's anything else involved, it's not foldable.
1119 if (!S->isZero()) return false;
1120
1121 // Fast-path: zero is always foldable.
1122 if (BaseOffs == 0 && !BaseGV) return true;
1123
1124 // Conservatively, create an address with an immediate and a
1125 // base and a scale.
1126 TargetLowering::AddrMode AM;
1127 AM.BaseOffs = BaseOffs;
1128 AM.BaseGV = BaseGV;
1129 AM.HasBaseReg = HasBaseReg;
1130 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1131
1132 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001133}
1134
Dan Gohman572645c2010-02-12 10:34:29 +00001135/// FormulaSorter - This class implements an ordering for formulae which sorts
1136/// the by their standalone cost.
1137class FormulaSorter {
1138 /// These two sets are kept empty, so that we compute standalone costs.
1139 DenseSet<const SCEV *> VisitedRegs;
1140 SmallPtrSet<const SCEV *, 16> Regs;
1141 Loop *L;
1142 LSRUse *LU;
1143 ScalarEvolution &SE;
1144 DominatorTree &DT;
1145
1146public:
1147 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1148 : L(l), LU(&lu), SE(se), DT(dt) {}
1149
1150 bool operator()(const Formula &A, const Formula &B) {
1151 Cost CostA;
1152 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1153 Regs.clear();
1154 Cost CostB;
1155 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1156 Regs.clear();
1157 return CostA < CostB;
1158 }
1159};
1160
1161/// LSRInstance - This class holds state for the main loop strength reduction
1162/// logic.
1163class LSRInstance {
1164 IVUsers &IU;
1165 ScalarEvolution &SE;
1166 DominatorTree &DT;
Dan Gohmane5f76872010-04-09 22:07:05 +00001167 LoopInfo &LI;
Dan Gohman572645c2010-02-12 10:34:29 +00001168 const TargetLowering *const TLI;
1169 Loop *const L;
1170 bool Changed;
1171
1172 /// IVIncInsertPos - This is the insert position that the current loop's
1173 /// induction variable increment should be placed. In simple loops, this is
1174 /// the latch block's terminator. But in more complicated cases, this is a
1175 /// position which will dominate all the in-loop post-increment users.
1176 Instruction *IVIncInsertPos;
1177
1178 /// Factors - Interesting factors between use strides.
1179 SmallSetVector<int64_t, 8> Factors;
1180
1181 /// Types - Interesting use types, to facilitate truncation reuse.
1182 SmallSetVector<const Type *, 4> Types;
1183
1184 /// Fixups - The list of operands which are to be replaced.
1185 SmallVector<LSRFixup, 16> Fixups;
1186
1187 /// Uses - The list of interesting uses.
1188 SmallVector<LSRUse, 16> Uses;
1189
1190 /// RegUses - Track which uses use which register candidates.
1191 RegUseTracker RegUses;
1192
1193 void OptimizeShadowIV();
1194 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1195 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1196 bool OptimizeLoopTermCond();
1197
1198 void CollectInterestingTypesAndFactors();
1199 void CollectFixupsAndInitialFormulae();
1200
1201 LSRFixup &getNewFixup() {
1202 Fixups.push_back(LSRFixup());
1203 return Fixups.back();
1204 }
1205
1206 // Support for sharing of LSRUses between LSRFixups.
1207 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1208 UseMapTy UseMap;
1209
1210 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1211 LSRUse::KindType Kind, const Type *AccessTy);
1212
1213 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1214 LSRUse::KindType Kind,
1215 const Type *AccessTy);
1216
1217public:
Dan Gohman454d26d2010-02-22 04:11:59 +00001218 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001219 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1220 void CountRegisters(const Formula &F, size_t LUIdx);
1221 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1222
1223 void CollectLoopInvariantFixupsAndFormulae();
1224
1225 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1226 unsigned Depth = 0);
1227 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1228 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1229 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1230 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1231 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1232 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1233 void GenerateCrossUseConstantOffsets();
1234 void GenerateAllReuseFormulae();
1235
1236 void FilterOutUndesirableDedicatedRegisters();
1237 void NarrowSearchSpaceUsingHeuristics();
1238
1239 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1240 Cost &SolutionCost,
1241 SmallVectorImpl<const Formula *> &Workspace,
1242 const Cost &CurCost,
1243 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1244 DenseSet<const SCEV *> &VisitedRegs) const;
1245 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1246
Dan Gohmane5f76872010-04-09 22:07:05 +00001247 BasicBlock::iterator
1248 HoistInsertPosition(BasicBlock::iterator IP,
1249 const SmallVectorImpl<Instruction *> &Inputs) const;
1250 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1251 const LSRFixup &LF,
1252 const LSRUse &LU) const;
Dan Gohmand96eae82010-04-09 02:00:38 +00001253
Dan Gohman572645c2010-02-12 10:34:29 +00001254 Value *Expand(const LSRFixup &LF,
1255 const Formula &F,
Dan Gohman454d26d2010-02-22 04:11:59 +00001256 BasicBlock::iterator IP,
Dan Gohman572645c2010-02-12 10:34:29 +00001257 SCEVExpander &Rewriter,
Dan Gohman454d26d2010-02-22 04:11:59 +00001258 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001259 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1260 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001261 SCEVExpander &Rewriter,
1262 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001263 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001264 void Rewrite(const LSRFixup &LF,
1265 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00001266 SCEVExpander &Rewriter,
1267 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00001268 Pass *P) const;
1269 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1270 Pass *P);
1271
1272 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1273
1274 bool getChanged() const { return Changed; }
1275
1276 void print_factors_and_types(raw_ostream &OS) const;
1277 void print_fixups(raw_ostream &OS) const;
1278 void print_uses(raw_ostream &OS) const;
1279 void print(raw_ostream &OS) const;
1280 void dump() const;
1281};
1282
1283}
1284
1285/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001286/// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00001287void LSRInstance::OptimizeShadowIV() {
1288 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1289 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1290 return;
1291
1292 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1293 UI != E; /* empty */) {
1294 IVUsers::const_iterator CandidateUI = UI;
1295 ++UI;
1296 Instruction *ShadowUse = CandidateUI->getUser();
1297 const Type *DestTy = NULL;
1298
1299 /* If shadow use is a int->float cast then insert a second IV
1300 to eliminate this cast.
1301
1302 for (unsigned i = 0; i < n; ++i)
1303 foo((double)i);
1304
1305 is transformed into
1306
1307 double d = 0.0;
1308 for (unsigned i = 0; i < n; ++i, ++d)
1309 foo(d);
1310 */
1311 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1312 DestTy = UCast->getDestTy();
1313 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1314 DestTy = SCast->getDestTy();
1315 if (!DestTy) continue;
1316
1317 if (TLI) {
1318 // If target does not support DestTy natively then do not apply
1319 // this transformation.
1320 EVT DVT = TLI->getValueType(DestTy);
1321 if (!TLI->isTypeLegal(DVT)) continue;
1322 }
1323
1324 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1325 if (!PH) continue;
1326 if (PH->getNumIncomingValues() != 2) continue;
1327
1328 const Type *SrcTy = PH->getType();
1329 int Mantissa = DestTy->getFPMantissaWidth();
1330 if (Mantissa == -1) continue;
1331 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1332 continue;
1333
1334 unsigned Entry, Latch;
1335 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1336 Entry = 0;
1337 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001338 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001339 Entry = 1;
1340 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001341 }
Dan Gohman7979b722010-01-22 00:46:49 +00001342
Dan Gohman572645c2010-02-12 10:34:29 +00001343 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1344 if (!Init) continue;
1345 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001346
Dan Gohman572645c2010-02-12 10:34:29 +00001347 BinaryOperator *Incr =
1348 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1349 if (!Incr) continue;
1350 if (Incr->getOpcode() != Instruction::Add
1351 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001352 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001353
Dan Gohman572645c2010-02-12 10:34:29 +00001354 /* Initialize new IV, double d = 0.0 in above example. */
1355 ConstantInt *C = NULL;
1356 if (Incr->getOperand(0) == PH)
1357 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1358 else if (Incr->getOperand(1) == PH)
1359 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001360 else
Dan Gohman7979b722010-01-22 00:46:49 +00001361 continue;
1362
Dan Gohman572645c2010-02-12 10:34:29 +00001363 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001364
Dan Gohman572645c2010-02-12 10:34:29 +00001365 // Ignore negative constants, as the code below doesn't handle them
1366 // correctly. TODO: Remove this restriction.
1367 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001368
Dan Gohman572645c2010-02-12 10:34:29 +00001369 /* Add new PHINode. */
1370 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001371
Dan Gohman572645c2010-02-12 10:34:29 +00001372 /* create new increment. '++d' in above example. */
1373 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1374 BinaryOperator *NewIncr =
1375 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1376 Instruction::FAdd : Instruction::FSub,
1377 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001378
Dan Gohman572645c2010-02-12 10:34:29 +00001379 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1380 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001381
Dan Gohman572645c2010-02-12 10:34:29 +00001382 /* Remove cast operation */
1383 ShadowUse->replaceAllUsesWith(NewPH);
1384 ShadowUse->eraseFromParent();
1385 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001386 }
1387}
1388
1389/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1390/// set the IV user and stride information and return true, otherwise return
1391/// false.
Dan Gohman572645c2010-02-12 10:34:29 +00001392bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1393 IVStrideUse *&CondUse) {
1394 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1395 if (UI->getUser() == Cond) {
1396 // NOTE: we could handle setcc instructions with multiple uses here, but
1397 // InstCombine does it as well for simple uses, it's not clear that it
1398 // occurs enough in real life to handle.
1399 CondUse = UI;
1400 return true;
1401 }
Dan Gohman7979b722010-01-22 00:46:49 +00001402 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001403}
1404
Dan Gohman7979b722010-01-22 00:46:49 +00001405/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1406/// a max computation.
1407///
1408/// This is a narrow solution to a specific, but acute, problem. For loops
1409/// like this:
1410///
1411/// i = 0;
1412/// do {
1413/// p[i] = 0.0;
1414/// } while (++i < n);
1415///
1416/// the trip count isn't just 'n', because 'n' might not be positive. And
1417/// unfortunately this can come up even for loops where the user didn't use
1418/// a C do-while loop. For example, seemingly well-behaved top-test loops
1419/// will commonly be lowered like this:
1420//
1421/// if (n > 0) {
1422/// i = 0;
1423/// do {
1424/// p[i] = 0.0;
1425/// } while (++i < n);
1426/// }
1427///
1428/// and then it's possible for subsequent optimization to obscure the if
1429/// test in such a way that indvars can't find it.
1430///
1431/// When indvars can't find the if test in loops like this, it creates a
1432/// max expression, which allows it to give the loop a canonical
1433/// induction variable:
1434///
1435/// i = 0;
1436/// max = n < 1 ? 1 : n;
1437/// do {
1438/// p[i] = 0.0;
1439/// } while (++i != max);
1440///
1441/// Canonical induction variables are necessary because the loop passes
1442/// are designed around them. The most obvious example of this is the
1443/// LoopInfo analysis, which doesn't remember trip count values. It
1444/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001445/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001446/// the loop has a canonical induction variable.
1447///
1448/// However, when it comes time to generate code, the maximum operation
1449/// can be quite costly, especially if it's inside of an outer loop.
1450///
1451/// This function solves this problem by detecting this type of loop and
1452/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1453/// the instructions for the maximum computation.
1454///
Dan Gohman572645c2010-02-12 10:34:29 +00001455ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001456 // Check that the loop matches the pattern we're looking for.
1457 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1458 Cond->getPredicate() != CmpInst::ICMP_NE)
1459 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001460
Dan Gohman7979b722010-01-22 00:46:49 +00001461 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1462 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001463
Dan Gohman572645c2010-02-12 10:34:29 +00001464 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001465 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1466 return Cond;
Dan Gohmandeff6212010-05-03 22:09:21 +00001467 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001468
Dan Gohman7979b722010-01-22 00:46:49 +00001469 // Add one to the backedge-taken count to get the trip count.
Dan Gohman572645c2010-02-12 10:34:29 +00001470 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
Dan Gohman1d367982010-04-24 03:13:44 +00001471 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001472
Dan Gohman1d367982010-04-24 03:13:44 +00001473 // Check for a max calculation that matches the pattern. There's no check
1474 // for ICMP_ULE here because the comparison would be with zero, which
1475 // isn't interesting.
1476 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1477 const SCEVNAryExpr *Max = 0;
1478 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1479 Pred = ICmpInst::ICMP_SLE;
1480 Max = S;
1481 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1482 Pred = ICmpInst::ICMP_SLT;
1483 Max = S;
1484 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1485 Pred = ICmpInst::ICMP_ULT;
1486 Max = U;
1487 } else {
1488 // No match; bail.
Dan Gohman7979b722010-01-22 00:46:49 +00001489 return Cond;
Dan Gohman1d367982010-04-24 03:13:44 +00001490 }
Dan Gohman7979b722010-01-22 00:46:49 +00001491
1492 // To handle a max with more than two operands, this optimization would
1493 // require additional checking and setup.
1494 if (Max->getNumOperands() != 2)
1495 return Cond;
1496
1497 const SCEV *MaxLHS = Max->getOperand(0);
1498 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman1d367982010-04-24 03:13:44 +00001499
1500 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1501 // for a comparison with 1. For <= and >=, a comparison with zero.
1502 if (!MaxLHS ||
1503 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1504 return Cond;
1505
Dan Gohman7979b722010-01-22 00:46:49 +00001506 // Check the relevant induction variable for conformance to
1507 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001508 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001509 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1510 if (!AR || !AR->isAffine() ||
1511 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001512 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001513 return Cond;
1514
1515 assert(AR->getLoop() == L &&
1516 "Loop condition operand is an addrec in a different loop!");
1517
1518 // Check the right operand of the select, and remember it, as it will
1519 // be used in the new comparison instruction.
1520 Value *NewRHS = 0;
Dan Gohman1d367982010-04-24 03:13:44 +00001521 if (ICmpInst::isTrueWhenEqual(Pred)) {
1522 // Look for n+1, and grab n.
1523 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1524 if (isa<ConstantInt>(BO->getOperand(1)) &&
1525 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1526 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1527 NewRHS = BO->getOperand(0);
1528 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1529 if (isa<ConstantInt>(BO->getOperand(1)) &&
1530 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1531 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1532 NewRHS = BO->getOperand(0);
1533 if (!NewRHS)
1534 return Cond;
1535 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001536 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001537 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001538 NewRHS = Sel->getOperand(2);
Dan Gohman1d367982010-04-24 03:13:44 +00001539 else
1540 llvm_unreachable("Max doesn't match expected pattern!");
Dan Gohman7979b722010-01-22 00:46:49 +00001541
1542 // Determine the new comparison opcode. It may be signed or unsigned,
1543 // and the original comparison may be either equality or inequality.
Dan Gohman7979b722010-01-22 00:46:49 +00001544 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1545 Pred = CmpInst::getInversePredicate(Pred);
1546
1547 // Ok, everything looks ok to change the condition into an SLT or SGE and
1548 // delete the max calculation.
1549 ICmpInst *NewCond =
1550 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1551
1552 // Delete the max calculation instructions.
1553 Cond->replaceAllUsesWith(NewCond);
1554 CondUse->setUser(NewCond);
1555 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1556 Cond->eraseFromParent();
1557 Sel->eraseFromParent();
1558 if (Cmp->use_empty())
1559 Cmp->eraseFromParent();
1560 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001561}
1562
Jim Grosbach56a1f802009-11-17 17:53:56 +00001563/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001564/// postinc iv when possible.
Dan Gohman572645c2010-02-12 10:34:29 +00001565bool
1566LSRInstance::OptimizeLoopTermCond() {
1567 SmallPtrSet<Instruction *, 4> PostIncs;
1568
Evan Cheng586f69a2009-11-12 07:35:05 +00001569 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001570 SmallVector<BasicBlock*, 8> ExitingBlocks;
1571 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001572
Evan Cheng076e0852009-11-17 18:10:11 +00001573 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1574 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001575
Dan Gohman572645c2010-02-12 10:34:29 +00001576 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001577 // can, we want to change it to use a post-incremented version of its
1578 // induction variable, to allow coalescing the live ranges for the IV into
1579 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001580
Evan Cheng076e0852009-11-17 18:10:11 +00001581 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1582 if (!TermBr)
1583 continue;
1584 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1585 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1586 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001587
Evan Cheng076e0852009-11-17 18:10:11 +00001588 // Search IVUsesByStride to find Cond's IVUse if there is one.
1589 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001590 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001591 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001592 continue;
1593
Evan Cheng076e0852009-11-17 18:10:11 +00001594 // If the trip count is computed in terms of a max (due to ScalarEvolution
1595 // being unable to find a sufficient guard, for example), change the loop
1596 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001597 // One consequence of doing this now is that it disrupts the count-down
1598 // optimization. That's not always a bad thing though, because in such
1599 // cases it may still be worthwhile to avoid a max.
1600 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001601
Dan Gohman572645c2010-02-12 10:34:29 +00001602 // If this exiting block dominates the latch block, it may also use
1603 // the post-inc value if it won't be shared with other uses.
1604 // Check for dominance.
1605 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001606 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001607
Dan Gohman572645c2010-02-12 10:34:29 +00001608 // Conservatively avoid trying to use the post-inc value in non-latch
1609 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001610 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001611 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1612 // Test if the use is reachable from the exiting block. This dominator
1613 // query is a conservative approximation of reachability.
1614 if (&*UI != CondUse &&
1615 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1616 // Conservatively assume there may be reuse if the quotient of their
1617 // strides could be a legal scale.
Dan Gohmanc0564542010-04-19 21:48:58 +00001618 const SCEV *A = IU.getStride(*CondUse, L);
1619 const SCEV *B = IU.getStride(*UI, L);
Dan Gohman448db1c2010-04-07 22:27:08 +00001620 if (!A || !B) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001621 if (SE.getTypeSizeInBits(A->getType()) !=
1622 SE.getTypeSizeInBits(B->getType())) {
1623 if (SE.getTypeSizeInBits(A->getType()) >
1624 SE.getTypeSizeInBits(B->getType()))
1625 B = SE.getSignExtendExpr(B, A->getType());
1626 else
1627 A = SE.getSignExtendExpr(A, B->getType());
1628 }
1629 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001630 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001631 // Stride of one or negative one can have reuse with non-addresses.
1632 if (D->getValue()->isOne() ||
1633 D->getValue()->isAllOnesValue())
1634 goto decline_post_inc;
1635 // Avoid weird situations.
1636 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1637 D->getValue()->getValue().isMinSignedValue())
1638 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001639 // Without TLI, assume that any stride might be valid, and so any
1640 // use might be shared.
1641 if (!TLI)
1642 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001643 // Check for possible scaled-address reuse.
1644 const Type *AccessTy = getAccessType(UI->getUser());
1645 TargetLowering::AddrMode AM;
1646 AM.Scale = D->getValue()->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001647 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001648 goto decline_post_inc;
1649 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001650 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001651 goto decline_post_inc;
1652 }
1653 }
1654
David Greene63c94632009-12-23 22:58:38 +00001655 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001656 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001657
1658 // It's possible for the setcc instruction to be anywhere in the loop, and
1659 // possible for it to have multiple users. If it is not immediately before
1660 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001661 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1662 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001663 Cond->moveBefore(TermBr);
1664 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001665 // Clone the terminating condition and insert into the loopend.
1666 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001667 Cond = cast<ICmpInst>(Cond->clone());
1668 Cond->setName(L->getHeader()->getName() + ".termcond");
1669 ExitingBlock->getInstList().insert(TermBr, Cond);
1670
1671 // Clone the IVUse, as the old use still exists!
Dan Gohmanc0564542010-04-19 21:48:58 +00001672 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman572645c2010-02-12 10:34:29 +00001673 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001674 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001675 }
1676
Evan Cheng076e0852009-11-17 18:10:11 +00001677 // If we get to here, we know that we can transform the setcc instruction to
1678 // use the post-incremented version of the IV, allowing us to coalesce the
1679 // live ranges for the IV correctly.
Dan Gohman448db1c2010-04-07 22:27:08 +00001680 CondUse->transformToPostInc(L);
Evan Cheng076e0852009-11-17 18:10:11 +00001681 Changed = true;
1682
Dan Gohman572645c2010-02-12 10:34:29 +00001683 PostIncs.insert(Cond);
1684 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001685 }
Dan Gohman572645c2010-02-12 10:34:29 +00001686
1687 // Determine an insertion point for the loop induction variable increment. It
1688 // must dominate all the post-inc comparisons we just set up, and it must
1689 // dominate the loop latch edge.
1690 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1691 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1692 E = PostIncs.end(); I != E; ++I) {
1693 BasicBlock *BB =
1694 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1695 (*I)->getParent());
1696 if (BB == (*I)->getParent())
1697 IVIncInsertPos = *I;
1698 else if (BB != IVIncInsertPos->getParent())
1699 IVIncInsertPos = BB->getTerminator();
1700 }
1701
1702 return Changed;
Dan Gohmana10756e2010-01-21 02:09:26 +00001703}
1704
Dan Gohman572645c2010-02-12 10:34:29 +00001705bool
1706LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1707 LSRUse::KindType Kind, const Type *AccessTy) {
1708 int64_t NewMinOffset = LU.MinOffset;
1709 int64_t NewMaxOffset = LU.MaxOffset;
1710 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001711
Dan Gohman572645c2010-02-12 10:34:29 +00001712 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1713 // something conservative, however this can pessimize in the case that one of
1714 // the uses will have all its uses outside the loop, for example.
1715 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001716 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001717 // Conservatively assume HasBaseReg is true for now.
1718 if (NewOffset < LU.MinOffset) {
1719 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
Dan Gohman454d26d2010-02-22 04:11:59 +00001720 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001721 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001722 NewMinOffset = NewOffset;
1723 } else if (NewOffset > LU.MaxOffset) {
1724 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
Dan Gohman454d26d2010-02-22 04:11:59 +00001725 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001726 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001727 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001728 }
Dan Gohman572645c2010-02-12 10:34:29 +00001729 // Check for a mismatched access type, and fall back conservatively as needed.
1730 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1731 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001732
Dan Gohman572645c2010-02-12 10:34:29 +00001733 // Update the use.
1734 LU.MinOffset = NewMinOffset;
1735 LU.MaxOffset = NewMaxOffset;
1736 LU.AccessTy = NewAccessTy;
1737 if (NewOffset != LU.Offsets.back())
1738 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001739 return true;
1740}
1741
Dan Gohman572645c2010-02-12 10:34:29 +00001742/// getUse - Return an LSRUse index and an offset value for a fixup which
1743/// needs the given expression, with the given kind and optional access type.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001744/// Either reuse an existing use or create a new one, as needed.
Dan Gohman572645c2010-02-12 10:34:29 +00001745std::pair<size_t, int64_t>
1746LSRInstance::getUse(const SCEV *&Expr,
1747 LSRUse::KindType Kind, const Type *AccessTy) {
1748 const SCEV *Copy = Expr;
1749 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001750
Dan Gohman572645c2010-02-12 10:34:29 +00001751 // Basic uses can't accept any offset, for example.
Dan Gohman454d26d2010-02-22 04:11:59 +00001752 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
Dan Gohman572645c2010-02-12 10:34:29 +00001753 Expr = Copy;
1754 Offset = 0;
1755 }
1756
1757 std::pair<UseMapTy::iterator, bool> P =
1758 UseMap.insert(std::make_pair(Expr, 0));
1759 if (!P.second) {
1760 // A use already existed with this base.
1761 size_t LUIdx = P.first->second;
1762 LSRUse &LU = Uses[LUIdx];
1763 if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1764 // Reuse this use.
1765 return std::make_pair(LUIdx, Offset);
1766 }
1767
1768 // Create a new use.
1769 size_t LUIdx = Uses.size();
1770 P.first->second = LUIdx;
1771 Uses.push_back(LSRUse(Kind, AccessTy));
1772 LSRUse &LU = Uses[LUIdx];
1773
1774 // We don't need to track redundant offsets, but we don't need to go out
1775 // of our way here to avoid them.
1776 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1777 LU.Offsets.push_back(Offset);
1778
1779 LU.MinOffset = Offset;
1780 LU.MaxOffset = Offset;
1781 return std::make_pair(LUIdx, Offset);
1782}
1783
1784void LSRInstance::CollectInterestingTypesAndFactors() {
1785 SmallSetVector<const SCEV *, 4> Strides;
1786
Dan Gohman1b7bf182010-02-19 00:05:23 +00001787 // Collect interesting types and strides.
Dan Gohman448db1c2010-04-07 22:27:08 +00001788 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00001789 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohmanc0564542010-04-19 21:48:58 +00001790 const SCEV *Expr = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00001791
1792 // Collect interesting types.
Dan Gohman448db1c2010-04-07 22:27:08 +00001793 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman572645c2010-02-12 10:34:29 +00001794
Dan Gohman448db1c2010-04-07 22:27:08 +00001795 // Add strides for mentioned loops.
1796 Worklist.push_back(Expr);
1797 do {
1798 const SCEV *S = Worklist.pop_back_val();
1799 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1800 Strides.insert(AR->getStepRecurrence(SE));
1801 Worklist.push_back(AR->getStart());
1802 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1803 Worklist.insert(Worklist.end(), Add->op_begin(), Add->op_end());
1804 }
1805 } while (!Worklist.empty());
Dan Gohman1b7bf182010-02-19 00:05:23 +00001806 }
1807
1808 // Compute interesting factors from the set of interesting strides.
1809 for (SmallSetVector<const SCEV *, 4>::const_iterator
1810 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00001811 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Dan Gohman1b7bf182010-02-19 00:05:23 +00001812 next(I); NewStrideIter != E; ++NewStrideIter) {
1813 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00001814 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00001815
1816 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1817 SE.getTypeSizeInBits(NewStride->getType())) {
1818 if (SE.getTypeSizeInBits(OldStride->getType()) >
1819 SE.getTypeSizeInBits(NewStride->getType()))
1820 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1821 else
1822 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1823 }
1824 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001825 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1826 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001827 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1828 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1829 } else if (const SCEVConstant *Factor =
Dan Gohman454d26d2010-02-22 04:11:59 +00001830 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
1831 NewStride,
Dan Gohmanf09b7122010-02-19 19:35:48 +00001832 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001833 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1834 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1835 }
1836 }
Dan Gohman572645c2010-02-12 10:34:29 +00001837
1838 // If all uses use the same type, don't bother looking for truncation-based
1839 // reuse.
1840 if (Types.size() == 1)
1841 Types.clear();
1842
1843 DEBUG(print_factors_and_types(dbgs()));
1844}
1845
1846void LSRInstance::CollectFixupsAndInitialFormulae() {
1847 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1848 // Record the uses.
1849 LSRFixup &LF = getNewFixup();
1850 LF.UserInst = UI->getUser();
1851 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohman448db1c2010-04-07 22:27:08 +00001852 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman572645c2010-02-12 10:34:29 +00001853
1854 LSRUse::KindType Kind = LSRUse::Basic;
1855 const Type *AccessTy = 0;
1856 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1857 Kind = LSRUse::Address;
1858 AccessTy = getAccessType(LF.UserInst);
1859 }
1860
Dan Gohmanc0564542010-04-19 21:48:58 +00001861 const SCEV *S = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00001862
1863 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1864 // (N - i == 0), and this allows (N - i) to be the expression that we work
1865 // with rather than just N or i, so we can consider the register
1866 // requirements for both N and i at the same time. Limiting this code to
1867 // equality icmps is not a problem because all interesting loops use
1868 // equality icmps, thanks to IndVarSimplify.
1869 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1870 if (CI->isEquality()) {
1871 // Swap the operands if needed to put the OperandValToReplace on the
1872 // left, for consistency.
1873 Value *NV = CI->getOperand(1);
1874 if (NV == LF.OperandValToReplace) {
1875 CI->setOperand(1, CI->getOperand(0));
1876 CI->setOperand(0, NV);
1877 }
1878
1879 // x == y --> x - y == 0
1880 const SCEV *N = SE.getSCEV(NV);
1881 if (N->isLoopInvariant(L)) {
1882 Kind = LSRUse::ICmpZero;
1883 S = SE.getMinusSCEV(N, S);
1884 }
1885
1886 // -1 and the negations of all interesting strides (except the negation
1887 // of -1) are now also interesting.
1888 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1889 if (Factors[i] != -1)
1890 Factors.insert(-(uint64_t)Factors[i]);
1891 Factors.insert(-1);
1892 }
1893
1894 // Set up the initial formula for this use.
1895 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1896 LF.LUIdx = P.first;
1897 LF.Offset = P.second;
1898 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00001899 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00001900
1901 // If this is the first use of this LSRUse, give it a formula.
1902 if (LU.Formulae.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00001903 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001904 CountRegisters(LU.Formulae.back(), LF.LUIdx);
1905 }
1906 }
1907
1908 DEBUG(print_fixups(dbgs()));
1909}
1910
1911void
Dan Gohman454d26d2010-02-22 04:11:59 +00001912LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Dan Gohman572645c2010-02-12 10:34:29 +00001913 Formula F;
1914 F.InitialMatch(S, L, SE, DT);
1915 bool Inserted = InsertFormula(LU, LUIdx, F);
1916 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1917}
1918
1919void
1920LSRInstance::InsertSupplementalFormula(const SCEV *S,
1921 LSRUse &LU, size_t LUIdx) {
1922 Formula F;
1923 F.BaseRegs.push_back(S);
1924 F.AM.HasBaseReg = true;
1925 bool Inserted = InsertFormula(LU, LUIdx, F);
1926 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1927}
1928
1929/// CountRegisters - Note which registers are used by the given formula,
1930/// updating RegUses.
1931void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1932 if (F.ScaledReg)
1933 RegUses.CountRegister(F.ScaledReg, LUIdx);
1934 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1935 E = F.BaseRegs.end(); I != E; ++I)
1936 RegUses.CountRegister(*I, LUIdx);
1937}
1938
1939/// InsertFormula - If the given formula has not yet been inserted, add it to
1940/// the list, and return true. Return false otherwise.
1941bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Dan Gohman454d26d2010-02-22 04:11:59 +00001942 if (!LU.InsertFormula(F))
Dan Gohman572645c2010-02-12 10:34:29 +00001943 return false;
1944
1945 CountRegisters(F, LUIdx);
1946 return true;
1947}
1948
1949/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1950/// loop-invariant values which we're tracking. These other uses will pin these
1951/// values in registers, making them less profitable for elimination.
1952/// TODO: This currently misses non-constant addrec step registers.
1953/// TODO: Should this give more weight to users inside the loop?
1954void
1955LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1956 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1957 SmallPtrSet<const SCEV *, 8> Inserted;
1958
1959 while (!Worklist.empty()) {
1960 const SCEV *S = Worklist.pop_back_val();
1961
1962 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
1963 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
1964 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1965 Worklist.push_back(C->getOperand());
1966 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1967 Worklist.push_back(D->getLHS());
1968 Worklist.push_back(D->getRHS());
1969 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
1970 if (!Inserted.insert(U)) continue;
1971 const Value *V = U->getValue();
1972 if (const Instruction *Inst = dyn_cast<Instruction>(V))
1973 if (L->contains(Inst)) continue;
Gabor Greif60ad7812010-03-25 23:06:16 +00001974 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
Dan Gohman572645c2010-02-12 10:34:29 +00001975 UI != UE; ++UI) {
1976 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
1977 // Ignore non-instructions.
1978 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00001979 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001980 // Ignore instructions in other functions (as can happen with
1981 // Constants).
1982 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00001983 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001984 // Ignore instructions not dominated by the loop.
1985 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
1986 UserInst->getParent() :
1987 cast<PHINode>(UserInst)->getIncomingBlock(
1988 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
1989 if (!DT.dominates(L->getHeader(), UseBB))
1990 continue;
1991 // Ignore uses which are part of other SCEV expressions, to avoid
1992 // analyzing them multiple times.
Dan Gohman4a2a6832010-04-09 19:12:34 +00001993 if (SE.isSCEVable(UserInst->getType())) {
1994 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
1995 // If the user is a no-op, look through to its uses.
1996 if (!isa<SCEVUnknown>(UserS))
1997 continue;
1998 if (UserS == U) {
1999 Worklist.push_back(
2000 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2001 continue;
2002 }
2003 }
Dan Gohman572645c2010-02-12 10:34:29 +00002004 // Ignore icmp instructions which are already being analyzed.
2005 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2006 unsigned OtherIdx = !UI.getOperandNo();
2007 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
2008 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
2009 continue;
2010 }
2011
2012 LSRFixup &LF = getNewFixup();
2013 LF.UserInst = const_cast<Instruction *>(UserInst);
2014 LF.OperandValToReplace = UI.getUse();
2015 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2016 LF.LUIdx = P.first;
2017 LF.Offset = P.second;
2018 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002019 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00002020 InsertSupplementalFormula(U, LU, LF.LUIdx);
2021 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2022 break;
2023 }
2024 }
2025 }
2026}
2027
2028/// CollectSubexprs - Split S into subexpressions which can be pulled out into
2029/// separate registers. If C is non-null, multiply each subexpression by C.
2030static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2031 SmallVectorImpl<const SCEV *> &Ops,
2032 ScalarEvolution &SE) {
2033 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2034 // Break out add operands.
2035 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2036 I != E; ++I)
2037 CollectSubexprs(*I, C, Ops, SE);
2038 return;
2039 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2040 // Split a non-zero base out of an addrec.
2041 if (!AR->getStart()->isZero()) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002042 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +00002043 AR->getStepRecurrence(SE),
2044 AR->getLoop()), C, Ops, SE);
Dan Gohman68d6da12010-02-12 19:35:25 +00002045 CollectSubexprs(AR->getStart(), C, Ops, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002046 return;
2047 }
2048 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2049 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2050 if (Mul->getNumOperands() == 2)
2051 if (const SCEVConstant *Op0 =
2052 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2053 CollectSubexprs(Mul->getOperand(1),
2054 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2055 Ops, SE);
2056 return;
2057 }
2058 }
2059
2060 // Otherwise use the value itself.
2061 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2062}
2063
2064/// GenerateReassociations - Split out subexpressions from adds and the bases of
2065/// addrecs.
2066void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2067 Formula Base,
2068 unsigned Depth) {
2069 // Arbitrarily cap recursion to protect compile time.
2070 if (Depth >= 3) return;
2071
2072 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2073 const SCEV *BaseReg = Base.BaseRegs[i];
2074
2075 SmallVector<const SCEV *, 8> AddOps;
2076 CollectSubexprs(BaseReg, 0, AddOps, SE);
2077 if (AddOps.size() == 1) continue;
2078
2079 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2080 JE = AddOps.end(); J != JE; ++J) {
2081 // Don't pull a constant into a register if the constant could be folded
2082 // into an immediate field.
2083 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2084 Base.getNumRegs() > 1,
2085 LU.Kind, LU.AccessTy, TLI, SE))
2086 continue;
2087
2088 // Collect all operands except *J.
2089 SmallVector<const SCEV *, 8> InnerAddOps;
2090 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2091 KE = AddOps.end(); K != KE; ++K)
2092 if (K != J)
2093 InnerAddOps.push_back(*K);
2094
2095 // Don't leave just a constant behind in a register if the constant could
2096 // be folded into an immediate field.
2097 if (InnerAddOps.size() == 1 &&
2098 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2099 Base.getNumRegs() > 1,
2100 LU.Kind, LU.AccessTy, TLI, SE))
2101 continue;
2102
Dan Gohmanfafb8902010-04-23 01:55:05 +00002103 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2104 if (InnerSum->isZero())
2105 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002106 Formula F = Base;
Dan Gohmanfafb8902010-04-23 01:55:05 +00002107 F.BaseRegs[i] = InnerSum;
Dan Gohman572645c2010-02-12 10:34:29 +00002108 F.BaseRegs.push_back(*J);
2109 if (InsertFormula(LU, LUIdx, F))
2110 // If that formula hadn't been seen before, recurse to find more like
2111 // it.
2112 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2113 }
2114 }
2115}
2116
2117/// GenerateCombinations - Generate a formula consisting of all of the
2118/// loop-dominating registers added into a single register.
2119void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002120 Formula Base) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002121 // This method is only interesting on a plurality of registers.
Dan Gohman572645c2010-02-12 10:34:29 +00002122 if (Base.BaseRegs.size() <= 1) return;
2123
2124 Formula F = Base;
2125 F.BaseRegs.clear();
2126 SmallVector<const SCEV *, 4> Ops;
2127 for (SmallVectorImpl<const SCEV *>::const_iterator
2128 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2129 const SCEV *BaseReg = *I;
2130 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2131 !BaseReg->hasComputableLoopEvolution(L))
2132 Ops.push_back(BaseReg);
2133 else
2134 F.BaseRegs.push_back(BaseReg);
2135 }
2136 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002137 const SCEV *Sum = SE.getAddExpr(Ops);
2138 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2139 // opportunity to fold something. For now, just ignore such cases
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002140 // rather than proceed with zero in a register.
Dan Gohmance947362010-02-14 18:50:49 +00002141 if (!Sum->isZero()) {
2142 F.BaseRegs.push_back(Sum);
2143 (void)InsertFormula(LU, LUIdx, F);
2144 }
Dan Gohman572645c2010-02-12 10:34:29 +00002145 }
2146}
2147
2148/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2149void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2150 Formula Base) {
2151 // We can't add a symbolic offset if the address already contains one.
2152 if (Base.AM.BaseGV) return;
2153
2154 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2155 const SCEV *G = Base.BaseRegs[i];
2156 GlobalValue *GV = ExtractSymbol(G, SE);
2157 if (G->isZero() || !GV)
2158 continue;
2159 Formula F = Base;
2160 F.AM.BaseGV = GV;
2161 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2162 LU.Kind, LU.AccessTy, TLI))
2163 continue;
2164 F.BaseRegs[i] = G;
2165 (void)InsertFormula(LU, LUIdx, F);
2166 }
2167}
2168
2169/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2170void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2171 Formula Base) {
2172 // TODO: For now, just add the min and max offset, because it usually isn't
2173 // worthwhile looking at everything inbetween.
2174 SmallVector<int64_t, 4> Worklist;
2175 Worklist.push_back(LU.MinOffset);
2176 if (LU.MaxOffset != LU.MinOffset)
2177 Worklist.push_back(LU.MaxOffset);
2178
2179 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2180 const SCEV *G = Base.BaseRegs[i];
2181
2182 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2183 E = Worklist.end(); I != E; ++I) {
2184 Formula F = Base;
2185 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2186 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2187 LU.Kind, LU.AccessTy, TLI)) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002188 F.BaseRegs[i] = SE.getAddExpr(G, SE.getConstant(G->getType(), *I));
Dan Gohman572645c2010-02-12 10:34:29 +00002189
2190 (void)InsertFormula(LU, LUIdx, F);
2191 }
2192 }
2193
2194 int64_t Imm = ExtractImmediate(G, SE);
2195 if (G->isZero() || Imm == 0)
2196 continue;
2197 Formula F = Base;
2198 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2199 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2200 LU.Kind, LU.AccessTy, TLI))
2201 continue;
2202 F.BaseRegs[i] = G;
2203 (void)InsertFormula(LU, LUIdx, F);
2204 }
2205}
2206
2207/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2208/// the comparison. For example, x == y -> x*c == y*c.
2209void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2210 Formula Base) {
2211 if (LU.Kind != LSRUse::ICmpZero) return;
2212
2213 // Determine the integer type for the base formula.
2214 const Type *IntTy = Base.getType();
2215 if (!IntTy) return;
2216 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2217
2218 // Don't do this if there is more than one offset.
2219 if (LU.MinOffset != LU.MaxOffset) return;
2220
2221 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2222
2223 // Check each interesting stride.
2224 for (SmallSetVector<int64_t, 8>::const_iterator
2225 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2226 int64_t Factor = *I;
2227 Formula F = Base;
2228
2229 // Check that the multiplication doesn't overflow.
Dan Gohman968cb932010-02-17 00:41:53 +00002230 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2231 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002232 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002233 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002234 continue;
2235
2236 // Check that multiplying with the use offset doesn't overflow.
2237 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002238 if (Offset == INT64_MIN && Factor == -1)
2239 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002240 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002241 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002242 continue;
2243
2244 // Check that this scale is legal.
2245 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2246 continue;
2247
2248 // Compensate for the use having MinOffset built into it.
2249 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2250
Dan Gohmandeff6212010-05-03 22:09:21 +00002251 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002252
2253 // Check that multiplying with each base register doesn't overflow.
2254 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2255 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002256 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002257 goto next;
2258 }
2259
2260 // Check that multiplying with the scaled register doesn't overflow.
2261 if (F.ScaledReg) {
2262 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002263 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002264 continue;
2265 }
2266
2267 // If we make it here and it's legal, add it.
2268 (void)InsertFormula(LU, LUIdx, F);
2269 next:;
2270 }
2271}
2272
2273/// GenerateScales - Generate stride factor reuse formulae by making use of
2274/// scaled-offset address modes, for example.
2275void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2276 Formula Base) {
2277 // Determine the integer type for the base formula.
2278 const Type *IntTy = Base.getType();
2279 if (!IntTy) return;
2280
2281 // If this Formula already has a scaled register, we can't add another one.
2282 if (Base.AM.Scale != 0) return;
2283
2284 // Check each interesting stride.
2285 for (SmallSetVector<int64_t, 8>::const_iterator
2286 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2287 int64_t Factor = *I;
2288
2289 Base.AM.Scale = Factor;
2290 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2291 // Check whether this scale is going to be legal.
2292 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2293 LU.Kind, LU.AccessTy, TLI)) {
2294 // As a special-case, handle special out-of-loop Basic users specially.
2295 // TODO: Reconsider this special case.
2296 if (LU.Kind == LSRUse::Basic &&
2297 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2298 LSRUse::Special, LU.AccessTy, TLI) &&
2299 LU.AllFixupsOutsideLoop)
2300 LU.Kind = LSRUse::Special;
2301 else
2302 continue;
2303 }
2304 // For an ICmpZero, negating a solitary base register won't lead to
2305 // new solutions.
2306 if (LU.Kind == LSRUse::ICmpZero &&
2307 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2308 continue;
2309 // For each addrec base reg, apply the scale, if possible.
2310 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2311 if (const SCEVAddRecExpr *AR =
2312 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002313 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002314 if (FactorS->isZero())
2315 continue;
2316 // Divide out the factor, ignoring high bits, since we'll be
2317 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002318 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002319 // TODO: This could be optimized to avoid all the copying.
2320 Formula F = Base;
2321 F.ScaledReg = Quotient;
2322 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2323 F.BaseRegs.pop_back();
2324 (void)InsertFormula(LU, LUIdx, F);
2325 }
2326 }
2327 }
2328}
2329
2330/// GenerateTruncates - Generate reuse formulae from different IV types.
2331void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2332 Formula Base) {
2333 // This requires TargetLowering to tell us which truncates are free.
2334 if (!TLI) return;
2335
2336 // Don't bother truncating symbolic values.
2337 if (Base.AM.BaseGV) return;
2338
2339 // Determine the integer type for the base formula.
2340 const Type *DstTy = Base.getType();
2341 if (!DstTy) return;
2342 DstTy = SE.getEffectiveSCEVType(DstTy);
2343
2344 for (SmallSetVector<const Type *, 4>::const_iterator
2345 I = Types.begin(), E = Types.end(); I != E; ++I) {
2346 const Type *SrcTy = *I;
2347 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2348 Formula F = Base;
2349
2350 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2351 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2352 JE = F.BaseRegs.end(); J != JE; ++J)
2353 *J = SE.getAnyExtendExpr(*J, SrcTy);
2354
2355 // TODO: This assumes we've done basic processing on all uses and
2356 // have an idea what the register usage is.
2357 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2358 continue;
2359
2360 (void)InsertFormula(LU, LUIdx, F);
2361 }
2362 }
2363}
2364
2365namespace {
2366
Dan Gohman6020d852010-02-14 18:51:20 +00002367/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002368/// defer modifications so that the search phase doesn't have to worry about
2369/// the data structures moving underneath it.
2370struct WorkItem {
2371 size_t LUIdx;
2372 int64_t Imm;
2373 const SCEV *OrigReg;
2374
2375 WorkItem(size_t LI, int64_t I, const SCEV *R)
2376 : LUIdx(LI), Imm(I), OrigReg(R) {}
2377
2378 void print(raw_ostream &OS) const;
2379 void dump() const;
2380};
2381
2382}
2383
2384void WorkItem::print(raw_ostream &OS) const {
2385 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2386 << " , add offset " << Imm;
2387}
2388
2389void WorkItem::dump() const {
2390 print(errs()); errs() << '\n';
2391}
2392
2393/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2394/// distance apart and try to form reuse opportunities between them.
2395void LSRInstance::GenerateCrossUseConstantOffsets() {
2396 // Group the registers by their value without any added constant offset.
2397 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2398 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2399 RegMapTy Map;
2400 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2401 SmallVector<const SCEV *, 8> Sequence;
2402 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2403 I != E; ++I) {
2404 const SCEV *Reg = *I;
2405 int64_t Imm = ExtractImmediate(Reg, SE);
2406 std::pair<RegMapTy::iterator, bool> Pair =
2407 Map.insert(std::make_pair(Reg, ImmMapTy()));
2408 if (Pair.second)
2409 Sequence.push_back(Reg);
2410 Pair.first->second.insert(std::make_pair(Imm, *I));
2411 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2412 }
2413
2414 // Now examine each set of registers with the same base value. Build up
2415 // a list of work to do and do the work in a separate step so that we're
2416 // not adding formulae and register counts while we're searching.
2417 SmallVector<WorkItem, 32> WorkItems;
2418 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2419 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2420 E = Sequence.end(); I != E; ++I) {
2421 const SCEV *Reg = *I;
2422 const ImmMapTy &Imms = Map.find(Reg)->second;
2423
Dan Gohmancd045c02010-02-12 19:20:37 +00002424 // It's not worthwhile looking for reuse if there's only one offset.
2425 if (Imms.size() == 1)
2426 continue;
2427
Dan Gohman572645c2010-02-12 10:34:29 +00002428 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2429 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2430 J != JE; ++J)
2431 dbgs() << ' ' << J->first;
2432 dbgs() << '\n');
2433
2434 // Examine each offset.
2435 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2436 J != JE; ++J) {
2437 const SCEV *OrigReg = J->second;
2438
2439 int64_t JImm = J->first;
2440 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2441
2442 if (!isa<SCEVConstant>(OrigReg) &&
2443 UsedByIndicesMap[Reg].count() == 1) {
2444 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2445 continue;
2446 }
2447
2448 // Conservatively examine offsets between this orig reg a few selected
2449 // other orig regs.
2450 ImmMapTy::const_iterator OtherImms[] = {
2451 Imms.begin(), prior(Imms.end()),
2452 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2453 };
2454 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2455 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002456 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002457
2458 // Compute the difference between the two.
2459 int64_t Imm = (uint64_t)JImm - M->first;
2460 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2461 LUIdx = UsedByIndices.find_next(LUIdx))
2462 // Make a memo of this use, offset, and register tuple.
2463 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2464 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002465 }
2466 }
2467 }
2468
Dan Gohman572645c2010-02-12 10:34:29 +00002469 Map.clear();
2470 Sequence.clear();
2471 UsedByIndicesMap.clear();
2472 UniqueItems.clear();
2473
2474 // Now iterate through the worklist and add new formulae.
2475 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2476 E = WorkItems.end(); I != E; ++I) {
2477 const WorkItem &WI = *I;
2478 size_t LUIdx = WI.LUIdx;
2479 LSRUse &LU = Uses[LUIdx];
2480 int64_t Imm = WI.Imm;
2481 const SCEV *OrigReg = WI.OrigReg;
2482
2483 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2484 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2485 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2486
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002487 // TODO: Use a more targeted data structure.
Dan Gohman572645c2010-02-12 10:34:29 +00002488 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2489 Formula F = LU.Formulae[L];
2490 // Use the immediate in the scaled register.
2491 if (F.ScaledReg == OrigReg) {
2492 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2493 Imm * (uint64_t)F.AM.Scale;
2494 // Don't create 50 + reg(-50).
2495 if (F.referencesReg(SE.getSCEV(
2496 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2497 continue;
2498 Formula NewF = F;
2499 NewF.AM.BaseOffs = Offs;
2500 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2501 LU.Kind, LU.AccessTy, TLI))
2502 continue;
2503 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2504
2505 // If the new scale is a constant in a register, and adding the constant
2506 // value to the immediate would produce a value closer to zero than the
2507 // immediate itself, then the formula isn't worthwhile.
2508 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2509 if (C->getValue()->getValue().isNegative() !=
2510 (NewF.AM.BaseOffs < 0) &&
2511 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
Dan Gohmane0567812010-04-08 23:03:40 +00002512 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002513 continue;
2514
2515 // OK, looks good.
2516 (void)InsertFormula(LU, LUIdx, NewF);
2517 } else {
2518 // Use the immediate in a base register.
2519 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2520 const SCEV *BaseReg = F.BaseRegs[N];
2521 if (BaseReg != OrigReg)
2522 continue;
2523 Formula NewF = F;
2524 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2525 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2526 LU.Kind, LU.AccessTy, TLI))
2527 continue;
2528 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2529
2530 // If the new formula has a constant in a register, and adding the
2531 // constant value to the immediate would produce a value closer to
2532 // zero than the immediate itself, then the formula isn't worthwhile.
2533 for (SmallVectorImpl<const SCEV *>::const_iterator
2534 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2535 J != JE; ++J)
2536 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2537 if (C->getValue()->getValue().isNegative() !=
2538 (NewF.AM.BaseOffs < 0) &&
2539 C->getValue()->getValue().abs()
Dan Gohmane0567812010-04-08 23:03:40 +00002540 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002541 goto skip_formula;
2542
2543 // Ok, looks good.
2544 (void)InsertFormula(LU, LUIdx, NewF);
2545 break;
2546 skip_formula:;
2547 }
2548 }
2549 }
2550 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002551}
2552
Dan Gohman572645c2010-02-12 10:34:29 +00002553/// GenerateAllReuseFormulae - Generate formulae for each use.
2554void
2555LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002556 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002557 // queries are more precise.
2558 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2559 LSRUse &LU = Uses[LUIdx];
2560 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2561 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2562 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2563 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2564 }
2565 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2566 LSRUse &LU = Uses[LUIdx];
2567 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2568 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2569 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2570 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2571 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2572 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2573 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2574 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002575 }
2576 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2577 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002578 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2579 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2580 }
2581
2582 GenerateCrossUseConstantOffsets();
2583}
2584
2585/// If their are multiple formulae with the same set of registers used
2586/// by other uses, pick the best one and delete the others.
2587void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2588#ifndef NDEBUG
2589 bool Changed = false;
2590#endif
2591
2592 // Collect the best formula for each unique set of shared registers. This
2593 // is reset for each use.
2594 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2595 BestFormulaeTy;
2596 BestFormulaeTy BestFormulae;
2597
2598 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2599 LSRUse &LU = Uses[LUIdx];
2600 FormulaSorter Sorter(L, LU, SE, DT);
Dan Gohman6458ff92010-05-18 22:37:37 +00002601 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << "\n");
Dan Gohman572645c2010-02-12 10:34:29 +00002602
Dan Gohman572645c2010-02-12 10:34:29 +00002603 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2604 FIdx != NumForms; ++FIdx) {
2605 Formula &F = LU.Formulae[FIdx];
2606
2607 SmallVector<const SCEV *, 2> Key;
2608 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2609 JE = F.BaseRegs.end(); J != JE; ++J) {
2610 const SCEV *Reg = *J;
2611 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2612 Key.push_back(Reg);
2613 }
2614 if (F.ScaledReg &&
2615 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2616 Key.push_back(F.ScaledReg);
2617 // Unstable sort by host order ok, because this is only used for
2618 // uniquifying.
2619 std::sort(Key.begin(), Key.end());
2620
2621 std::pair<BestFormulaeTy::const_iterator, bool> P =
2622 BestFormulae.insert(std::make_pair(Key, FIdx));
2623 if (!P.second) {
2624 Formula &Best = LU.Formulae[P.first->second];
2625 if (Sorter.operator()(F, Best))
2626 std::swap(F, Best);
Dan Gohman6458ff92010-05-18 22:37:37 +00002627 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002628 dbgs() << "\n"
Dan Gohman6458ff92010-05-18 22:37:37 +00002629 " in favor of formula "; Best.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002630 dbgs() << '\n');
2631#ifndef NDEBUG
2632 Changed = true;
2633#endif
2634 std::swap(F, LU.Formulae.back());
2635 LU.Formulae.pop_back();
2636 --FIdx;
2637 --NumForms;
2638 continue;
2639 }
Dan Gohman59dc6032010-05-07 23:36:59 +00002640 }
2641
2642 // Now that we've filtered out some formulae, recompute the Regs set.
2643 LU.Regs.clear();
2644 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2645 FIdx != NumForms; ++FIdx) {
2646 Formula &F = LU.Formulae[FIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002647 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2648 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2649 }
Dan Gohman59dc6032010-05-07 23:36:59 +00002650
2651 // Reset this to prepare for the next use.
Dan Gohman572645c2010-02-12 10:34:29 +00002652 BestFormulae.clear();
2653 }
2654
2655 DEBUG(if (Changed) {
Dan Gohman9214b822010-02-13 02:06:02 +00002656 dbgs() << "\n"
2657 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002658 print_uses(dbgs());
2659 });
2660}
2661
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002662/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
Dan Gohman572645c2010-02-12 10:34:29 +00002663/// formulae to choose from, use some rough heuristics to prune down the number
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002664/// of formulae. This keeps the main solver from taking an extraordinary amount
Dan Gohman572645c2010-02-12 10:34:29 +00002665/// of time in some worst-case scenarios.
2666void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2667 // This is a rough guess that seems to work fairly well.
2668 const size_t Limit = UINT16_MAX;
2669
2670 SmallPtrSet<const SCEV *, 4> Taken;
2671 for (;;) {
2672 // Estimate the worst-case number of solutions we might consider. We almost
2673 // never consider this many solutions because we prune the search space,
2674 // but the pruning isn't always sufficient.
2675 uint32_t Power = 1;
2676 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2677 E = Uses.end(); I != E; ++I) {
2678 size_t FSize = I->Formulae.size();
2679 if (FSize >= Limit) {
2680 Power = Limit;
2681 break;
2682 }
2683 Power *= FSize;
2684 if (Power >= Limit)
2685 break;
2686 }
2687 if (Power < Limit)
2688 break;
2689
2690 // Ok, we have too many of formulae on our hands to conveniently handle.
2691 // Use a rough heuristic to thin out the list.
2692
2693 // Pick the register which is used by the most LSRUses, which is likely
2694 // to be a good reuse register candidate.
2695 const SCEV *Best = 0;
2696 unsigned BestNum = 0;
2697 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2698 I != E; ++I) {
2699 const SCEV *Reg = *I;
2700 if (Taken.count(Reg))
2701 continue;
2702 if (!Best)
2703 Best = Reg;
2704 else {
2705 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2706 if (Count > BestNum) {
2707 Best = Reg;
2708 BestNum = Count;
2709 }
2710 }
2711 }
2712
2713 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002714 << " will yield profitable reuse.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00002715 Taken.insert(Best);
2716
2717 // In any use with formulae which references this register, delete formulae
2718 // which don't reference it.
2719 for (SmallVectorImpl<LSRUse>::iterator I = Uses.begin(),
2720 E = Uses.end(); I != E; ++I) {
2721 LSRUse &LU = *I;
2722 if (!LU.Regs.count(Best)) continue;
2723
2724 // Clear out the set of used regs; it will be recomputed.
2725 LU.Regs.clear();
2726
2727 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2728 Formula &F = LU.Formulae[i];
2729 if (!F.referencesReg(Best)) {
2730 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2731 std::swap(LU.Formulae.back(), F);
2732 LU.Formulae.pop_back();
2733 --e;
2734 --i;
Dan Gohman59dc6032010-05-07 23:36:59 +00002735 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman572645c2010-02-12 10:34:29 +00002736 continue;
2737 }
2738
2739 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2740 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2741 }
2742 }
2743
2744 DEBUG(dbgs() << "After pre-selection:\n";
2745 print_uses(dbgs()));
2746 }
2747}
2748
2749/// SolveRecurse - This is the recursive solver.
2750void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2751 Cost &SolutionCost,
2752 SmallVectorImpl<const Formula *> &Workspace,
2753 const Cost &CurCost,
2754 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2755 DenseSet<const SCEV *> &VisitedRegs) const {
2756 // Some ideas:
2757 // - prune more:
2758 // - use more aggressive filtering
2759 // - sort the formula so that the most profitable solutions are found first
2760 // - sort the uses too
2761 // - search faster:
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002762 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman572645c2010-02-12 10:34:29 +00002763 // and bail early.
2764 // - track register sets with SmallBitVector
2765
2766 const LSRUse &LU = Uses[Workspace.size()];
2767
2768 // If this use references any register that's already a part of the
2769 // in-progress solution, consider it a requirement that a formula must
2770 // reference that register in order to be considered. This prunes out
2771 // unprofitable searching.
2772 SmallSetVector<const SCEV *, 4> ReqRegs;
2773 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2774 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00002775 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00002776 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00002777
Dan Gohman9214b822010-02-13 02:06:02 +00002778 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002779 SmallPtrSet<const SCEV *, 16> NewRegs;
2780 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00002781retry:
Dan Gohman572645c2010-02-12 10:34:29 +00002782 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2783 E = LU.Formulae.end(); I != E; ++I) {
2784 const Formula &F = *I;
2785
2786 // Ignore formulae which do not use any of the required registers.
2787 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2788 JE = ReqRegs.end(); J != JE; ++J) {
2789 const SCEV *Reg = *J;
2790 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2791 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2792 F.BaseRegs.end())
2793 goto skip;
2794 }
Dan Gohman9214b822010-02-13 02:06:02 +00002795 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002796
2797 // Evaluate the cost of the current formula. If it's already worse than
2798 // the current best, prune the search at that point.
2799 NewCost = CurCost;
2800 NewRegs = CurRegs;
2801 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2802 if (NewCost < SolutionCost) {
2803 Workspace.push_back(&F);
2804 if (Workspace.size() != Uses.size()) {
2805 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2806 NewRegs, VisitedRegs);
2807 if (F.getNumRegs() == 1 && Workspace.size() == 1)
2808 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2809 } else {
2810 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2811 dbgs() << ". Regs:";
2812 for (SmallPtrSet<const SCEV *, 16>::const_iterator
2813 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2814 dbgs() << ' ' << **I;
2815 dbgs() << '\n');
2816
2817 SolutionCost = NewCost;
2818 Solution = Workspace;
2819 }
2820 Workspace.pop_back();
2821 }
2822 skip:;
2823 }
Dan Gohman9214b822010-02-13 02:06:02 +00002824
2825 // If none of the formulae had all of the required registers, relax the
2826 // constraint so that we don't exclude all formulae.
2827 if (!AnySatisfiedReqRegs) {
Dan Gohman59dc6032010-05-07 23:36:59 +00002828 assert(!ReqRegs.empty() && "Solver failed even without required registers");
Dan Gohman9214b822010-02-13 02:06:02 +00002829 ReqRegs.clear();
2830 goto retry;
2831 }
Dan Gohman572645c2010-02-12 10:34:29 +00002832}
2833
2834void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2835 SmallVector<const Formula *, 8> Workspace;
2836 Cost SolutionCost;
2837 SolutionCost.Loose();
2838 Cost CurCost;
2839 SmallPtrSet<const SCEV *, 16> CurRegs;
2840 DenseSet<const SCEV *> VisitedRegs;
2841 Workspace.reserve(Uses.size());
2842
2843 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2844 CurRegs, VisitedRegs);
2845
2846 // Ok, we've now made all our decisions.
2847 DEBUG(dbgs() << "\n"
2848 "The chosen solution requires "; SolutionCost.print(dbgs());
2849 dbgs() << ":\n";
2850 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2851 dbgs() << " ";
2852 Uses[i].print(dbgs());
2853 dbgs() << "\n"
2854 " ";
2855 Solution[i]->print(dbgs());
2856 dbgs() << '\n';
2857 });
2858}
2859
2860/// getImmediateDominator - A handy utility for the specific DominatorTree
2861/// query that we need here.
2862///
2863static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2864 DomTreeNode *Node = DT.getNode(BB);
2865 if (!Node) return 0;
2866 Node = Node->getIDom();
2867 if (!Node) return 0;
2868 return Node->getBlock();
2869}
2870
Dan Gohmane5f76872010-04-09 22:07:05 +00002871/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
2872/// the dominator tree far as we can go while still being dominated by the
2873/// input positions. This helps canonicalize the insert position, which
2874/// encourages sharing.
2875BasicBlock::iterator
2876LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
2877 const SmallVectorImpl<Instruction *> &Inputs)
2878 const {
2879 for (;;) {
2880 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
2881 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
2882
2883 BasicBlock *IDom;
2884 for (BasicBlock *Rung = IP->getParent(); ; Rung = IDom) {
2885 IDom = getImmediateDominator(Rung, DT);
2886 if (!IDom) return IP;
2887
2888 // Don't climb into a loop though.
2889 const Loop *IDomLoop = LI.getLoopFor(IDom);
2890 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
2891 if (IDomDepth <= IPLoopDepth &&
2892 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
2893 break;
2894 }
2895
2896 bool AllDominate = true;
2897 Instruction *BetterPos = 0;
2898 Instruction *Tentative = IDom->getTerminator();
2899 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2900 E = Inputs.end(); I != E; ++I) {
2901 Instruction *Inst = *I;
2902 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2903 AllDominate = false;
2904 break;
2905 }
2906 // Attempt to find an insert position in the middle of the block,
2907 // instead of at the end, so that it can be used for other expansions.
2908 if (IDom == Inst->getParent() &&
2909 (!BetterPos || DT.dominates(BetterPos, Inst)))
Douglas Gregor7d9663c2010-05-11 06:17:44 +00002910 BetterPos = llvm::next(BasicBlock::iterator(Inst));
Dan Gohmane5f76872010-04-09 22:07:05 +00002911 }
2912 if (!AllDominate)
2913 break;
2914 if (BetterPos)
2915 IP = BetterPos;
2916 else
2917 IP = Tentative;
2918 }
2919
2920 return IP;
2921}
2922
2923/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand96eae82010-04-09 02:00:38 +00002924/// dominated by the operands and which will dominate the result.
2925BasicBlock::iterator
Dan Gohmane5f76872010-04-09 22:07:05 +00002926LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2927 const LSRFixup &LF,
2928 const LSRUse &LU) const {
Dan Gohmand96eae82010-04-09 02:00:38 +00002929 // Collect some instructions which must be dominated by the
Dan Gohman448db1c2010-04-07 22:27:08 +00002930 // expanding replacement. These must be dominated by any operands that
Dan Gohman572645c2010-02-12 10:34:29 +00002931 // will be required in the expansion.
2932 SmallVector<Instruction *, 4> Inputs;
2933 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2934 Inputs.push_back(I);
2935 if (LU.Kind == LSRUse::ICmpZero)
2936 if (Instruction *I =
2937 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2938 Inputs.push_back(I);
Dan Gohman448db1c2010-04-07 22:27:08 +00002939 if (LF.PostIncLoops.count(L)) {
2940 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman069d6f32010-03-02 01:59:21 +00002941 Inputs.push_back(L->getLoopLatch()->getTerminator());
2942 else
2943 Inputs.push_back(IVIncInsertPos);
2944 }
Dan Gohman701a4ae2010-04-08 05:57:57 +00002945 // The expansion must also be dominated by the increment positions of any
2946 // loops it for which it is using post-inc mode.
2947 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
2948 E = LF.PostIncLoops.end(); I != E; ++I) {
2949 const Loop *PIL = *I;
2950 if (PIL == L) continue;
2951
Dan Gohmane5f76872010-04-09 22:07:05 +00002952 // Be dominated by the loop exit.
Dan Gohman701a4ae2010-04-08 05:57:57 +00002953 SmallVector<BasicBlock *, 4> ExitingBlocks;
2954 PIL->getExitingBlocks(ExitingBlocks);
2955 if (!ExitingBlocks.empty()) {
2956 BasicBlock *BB = ExitingBlocks[0];
2957 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
2958 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
2959 Inputs.push_back(BB->getTerminator());
2960 }
2961 }
Dan Gohman572645c2010-02-12 10:34:29 +00002962
2963 // Then, climb up the immediate dominator tree as far as we can go while
2964 // still being dominated by the input positions.
Dan Gohmane5f76872010-04-09 22:07:05 +00002965 IP = HoistInsertPosition(IP, Inputs);
Dan Gohmand96eae82010-04-09 02:00:38 +00002966
2967 // Don't insert instructions before PHI nodes.
Dan Gohman572645c2010-02-12 10:34:29 +00002968 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand96eae82010-04-09 02:00:38 +00002969
2970 // Ignore debug intrinsics.
Dan Gohman449f31c2010-03-26 00:33:27 +00002971 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman572645c2010-02-12 10:34:29 +00002972
Dan Gohmand96eae82010-04-09 02:00:38 +00002973 return IP;
2974}
2975
2976Value *LSRInstance::Expand(const LSRFixup &LF,
2977 const Formula &F,
2978 BasicBlock::iterator IP,
2979 SCEVExpander &Rewriter,
2980 SmallVectorImpl<WeakVH> &DeadInsts) const {
2981 const LSRUse &LU = Uses[LF.LUIdx];
2982
2983 // Determine an input position which will be dominated by the operands and
2984 // which will dominate the result.
Dan Gohmane5f76872010-04-09 22:07:05 +00002985 IP = AdjustInsertPositionForExpand(IP, LF, LU);
Dan Gohmand96eae82010-04-09 02:00:38 +00002986
Dan Gohman572645c2010-02-12 10:34:29 +00002987 // Inform the Rewriter if we have a post-increment use, so that it can
2988 // perform an advantageous expansion.
Dan Gohman448db1c2010-04-07 22:27:08 +00002989 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman572645c2010-02-12 10:34:29 +00002990
2991 // This is the type that the user actually needs.
2992 const Type *OpTy = LF.OperandValToReplace->getType();
2993 // This will be the type that we'll initially expand to.
2994 const Type *Ty = F.getType();
2995 if (!Ty)
2996 // No type known; just expand directly to the ultimate type.
2997 Ty = OpTy;
2998 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
2999 // Expand directly to the ultimate type if it's the right size.
3000 Ty = OpTy;
3001 // This is the type to do integer arithmetic in.
3002 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3003
3004 // Build up a list of operands to add together to form the full base.
3005 SmallVector<const SCEV *, 8> Ops;
3006
3007 // Expand the BaseRegs portion.
3008 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3009 E = F.BaseRegs.end(); I != E; ++I) {
3010 const SCEV *Reg = *I;
3011 assert(!Reg->isZero() && "Zero allocated in a base register!");
3012
Dan Gohman448db1c2010-04-07 22:27:08 +00003013 // If we're expanding for a post-inc user, make the post-inc adjustment.
3014 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3015 Reg = TransformForPostIncUse(Denormalize, Reg,
3016 LF.UserInst, LF.OperandValToReplace,
3017 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003018
3019 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3020 }
3021
Dan Gohman087bd1e2010-03-03 05:29:13 +00003022 // Flush the operand list to suppress SCEVExpander hoisting.
3023 if (!Ops.empty()) {
3024 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3025 Ops.clear();
3026 Ops.push_back(SE.getUnknown(FullV));
3027 }
3028
Dan Gohman572645c2010-02-12 10:34:29 +00003029 // Expand the ScaledReg portion.
3030 Value *ICmpScaledV = 0;
3031 if (F.AM.Scale != 0) {
3032 const SCEV *ScaledS = F.ScaledReg;
3033
Dan Gohman448db1c2010-04-07 22:27:08 +00003034 // If we're expanding for a post-inc user, make the post-inc adjustment.
3035 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3036 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3037 LF.UserInst, LF.OperandValToReplace,
3038 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003039
3040 if (LU.Kind == LSRUse::ICmpZero) {
3041 // An interesting way of "folding" with an icmp is to use a negated
3042 // scale, which we'll implement by inserting it into the other operand
3043 // of the icmp.
3044 assert(F.AM.Scale == -1 &&
3045 "The only scale supported by ICmpZero uses is -1!");
3046 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3047 } else {
3048 // Otherwise just expand the scaled register and an explicit scale,
3049 // which is expected to be matched as part of the address.
3050 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3051 ScaledS = SE.getMulExpr(ScaledS,
Dan Gohmandeff6212010-05-03 22:09:21 +00003052 SE.getConstant(ScaledS->getType(), F.AM.Scale));
Dan Gohman572645c2010-02-12 10:34:29 +00003053 Ops.push_back(ScaledS);
Dan Gohman087bd1e2010-03-03 05:29:13 +00003054
3055 // Flush the operand list to suppress SCEVExpander hoisting.
3056 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3057 Ops.clear();
3058 Ops.push_back(SE.getUnknown(FullV));
Dan Gohman572645c2010-02-12 10:34:29 +00003059 }
3060 }
3061
Dan Gohman087bd1e2010-03-03 05:29:13 +00003062 // Expand the GV portion.
3063 if (F.AM.BaseGV) {
3064 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3065
3066 // Flush the operand list to suppress SCEVExpander hoisting.
3067 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3068 Ops.clear();
3069 Ops.push_back(SE.getUnknown(FullV));
3070 }
3071
3072 // Expand the immediate portion.
Dan Gohman572645c2010-02-12 10:34:29 +00003073 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3074 if (Offset != 0) {
3075 if (LU.Kind == LSRUse::ICmpZero) {
3076 // The other interesting way of "folding" with an ICmpZero is to use a
3077 // negated immediate.
3078 if (!ICmpScaledV)
3079 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3080 else {
3081 Ops.push_back(SE.getUnknown(ICmpScaledV));
3082 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3083 }
3084 } else {
3085 // Just add the immediate values. These again are expected to be matched
3086 // as part of the address.
Dan Gohman087bd1e2010-03-03 05:29:13 +00003087 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman572645c2010-02-12 10:34:29 +00003088 }
3089 }
3090
3091 // Emit instructions summing all the operands.
3092 const SCEV *FullS = Ops.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +00003093 SE.getConstant(IntTy, 0) :
Dan Gohman572645c2010-02-12 10:34:29 +00003094 SE.getAddExpr(Ops);
3095 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3096
3097 // We're done expanding now, so reset the rewriter.
Dan Gohman448db1c2010-04-07 22:27:08 +00003098 Rewriter.clearPostInc();
Dan Gohman572645c2010-02-12 10:34:29 +00003099
3100 // An ICmpZero Formula represents an ICmp which we're handling as a
3101 // comparison against zero. Now that we've expanded an expression for that
3102 // form, update the ICmp's other operand.
3103 if (LU.Kind == LSRUse::ICmpZero) {
3104 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3105 DeadInsts.push_back(CI->getOperand(1));
3106 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3107 "a scale at the same time!");
3108 if (F.AM.Scale == -1) {
3109 if (ICmpScaledV->getType() != OpTy) {
3110 Instruction *Cast =
3111 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3112 OpTy, false),
3113 ICmpScaledV, OpTy, "tmp", CI);
3114 ICmpScaledV = Cast;
3115 }
3116 CI->setOperand(1, ICmpScaledV);
3117 } else {
3118 assert(F.AM.Scale == 0 &&
3119 "ICmp does not support folding a global value and "
3120 "a scale at the same time!");
3121 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3122 -(uint64_t)Offset);
3123 if (C->getType() != OpTy)
3124 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3125 OpTy, false),
3126 C, OpTy);
3127
3128 CI->setOperand(1, C);
3129 }
3130 }
3131
3132 return FullV;
3133}
3134
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003135/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3136/// of their operands effectively happens in their predecessor blocks, so the
3137/// expression may need to be expanded in multiple places.
3138void LSRInstance::RewriteForPHI(PHINode *PN,
3139 const LSRFixup &LF,
3140 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003141 SCEVExpander &Rewriter,
3142 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003143 Pass *P) const {
3144 DenseMap<BasicBlock *, Value *> Inserted;
3145 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3146 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3147 BasicBlock *BB = PN->getIncomingBlock(i);
3148
3149 // If this is a critical edge, split the edge so that we do not insert
3150 // the code on all predecessor/successor paths. We do this unless this
3151 // is the canonical backedge for this loop, which complicates post-inc
3152 // users.
3153 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3154 !isa<IndirectBrInst>(BB->getTerminator()) &&
3155 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3156 // Split the critical edge.
3157 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3158
3159 // If PN is outside of the loop and BB is in the loop, we want to
3160 // move the block to be immediately before the PHI block, not
3161 // immediately after BB.
3162 if (L->contains(BB) && !L->contains(PN))
3163 NewBB->moveBefore(PN->getParent());
3164
3165 // Splitting the edge can reduce the number of PHI entries we have.
3166 e = PN->getNumIncomingValues();
3167 BB = NewBB;
3168 i = PN->getBasicBlockIndex(BB);
3169 }
3170
3171 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3172 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3173 if (!Pair.second)
3174 PN->setIncomingValue(i, Pair.first->second);
3175 else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003176 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003177
3178 // If this is reuse-by-noop-cast, insert the noop cast.
3179 const Type *OpTy = LF.OperandValToReplace->getType();
3180 if (FullV->getType() != OpTy)
3181 FullV =
3182 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3183 OpTy, false),
3184 FullV, LF.OperandValToReplace->getType(),
3185 "tmp", BB->getTerminator());
3186
3187 PN->setIncomingValue(i, FullV);
3188 Pair.first->second = FullV;
3189 }
3190 }
3191}
3192
Dan Gohman572645c2010-02-12 10:34:29 +00003193/// Rewrite - Emit instructions for the leading candidate expression for this
3194/// LSRUse (this is called "expanding"), and update the UserInst to reference
3195/// the newly expanded value.
3196void LSRInstance::Rewrite(const LSRFixup &LF,
3197 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00003198 SCEVExpander &Rewriter,
3199 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00003200 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003201 // First, find an insertion point that dominates UserInst. For PHI nodes,
3202 // find the nearest block which dominates all the relevant uses.
3203 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman454d26d2010-02-22 04:11:59 +00003204 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003205 } else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003206 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman572645c2010-02-12 10:34:29 +00003207
3208 // If this is reuse-by-noop-cast, insert the noop cast.
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003209 const Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003210 if (FullV->getType() != OpTy) {
3211 Instruction *Cast =
3212 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3213 FullV, OpTy, "tmp", LF.UserInst);
3214 FullV = Cast;
3215 }
3216
3217 // Update the user. ICmpZero is handled specially here (for now) because
3218 // Expand may have updated one of the operands of the icmp already, and
3219 // its new value may happen to be equal to LF.OperandValToReplace, in
3220 // which case doing replaceUsesOfWith leads to replacing both operands
3221 // with the same value. TODO: Reorganize this.
3222 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3223 LF.UserInst->setOperand(0, FullV);
3224 else
3225 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3226 }
3227
3228 DeadInsts.push_back(LF.OperandValToReplace);
3229}
3230
3231void
3232LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3233 Pass *P) {
3234 // Keep track of instructions we may have made dead, so that
3235 // we can remove them after we are done working.
3236 SmallVector<WeakVH, 16> DeadInsts;
3237
3238 SCEVExpander Rewriter(SE);
3239 Rewriter.disableCanonicalMode();
3240 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3241
3242 // Expand the new value definitions and update the users.
3243 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3244 size_t LUIdx = Fixups[i].LUIdx;
3245
Dan Gohman454d26d2010-02-22 04:11:59 +00003246 Rewrite(Fixups[i], *Solution[LUIdx], Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003247
3248 Changed = true;
3249 }
3250
3251 // Clean up after ourselves. This must be done before deleting any
3252 // instructions.
3253 Rewriter.clear();
3254
3255 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3256}
3257
3258LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3259 : IU(P->getAnalysis<IVUsers>()),
3260 SE(P->getAnalysis<ScalarEvolution>()),
3261 DT(P->getAnalysis<DominatorTree>()),
Dan Gohmane5f76872010-04-09 22:07:05 +00003262 LI(P->getAnalysis<LoopInfo>()),
Dan Gohman572645c2010-02-12 10:34:29 +00003263 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003264
Dan Gohman03e896b2009-11-05 21:11:53 +00003265 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003266 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003267
Dan Gohman572645c2010-02-12 10:34:29 +00003268 // If there's no interesting work to be done, bail early.
3269 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003270
Dan Gohman572645c2010-02-12 10:34:29 +00003271 DEBUG(dbgs() << "\nLSR on loop ";
3272 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3273 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003274
Dan Gohman572645c2010-02-12 10:34:29 +00003275 /// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003276 /// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00003277 OptimizeShadowIV();
Chris Lattner010de252005-08-08 05:28:22 +00003278
Dan Gohman572645c2010-02-12 10:34:29 +00003279 // Change loop terminating condition to use the postinc iv when possible.
3280 Changed |= OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003281
Dan Gohman572645c2010-02-12 10:34:29 +00003282 CollectInterestingTypesAndFactors();
3283 CollectFixupsAndInitialFormulae();
3284 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003285
Dan Gohman572645c2010-02-12 10:34:29 +00003286 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3287 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003288
Dan Gohman572645c2010-02-12 10:34:29 +00003289 // Now use the reuse data to generate a bunch of interesting ways
3290 // to formulate the values needed for the uses.
3291 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003292
Dan Gohman572645c2010-02-12 10:34:29 +00003293 DEBUG(dbgs() << "\n"
3294 "After generating reuse formulae:\n";
3295 print_uses(dbgs()));
Nate Begemaneaa13852004-10-18 21:08:22 +00003296
Dan Gohman572645c2010-02-12 10:34:29 +00003297 FilterOutUndesirableDedicatedRegisters();
3298 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003299
Dan Gohman572645c2010-02-12 10:34:29 +00003300 SmallVector<const Formula *, 8> Solution;
3301 Solve(Solution);
3302 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003303
Dan Gohman572645c2010-02-12 10:34:29 +00003304 // Release memory that is no longer needed.
3305 Factors.clear();
3306 Types.clear();
3307 RegUses.clear();
3308
3309#ifndef NDEBUG
3310 // Formulae should be legal.
3311 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3312 E = Uses.end(); I != E; ++I) {
3313 const LSRUse &LU = *I;
3314 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3315 JE = LU.Formulae.end(); J != JE; ++J)
3316 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3317 LU.Kind, LU.AccessTy, TLI) &&
3318 "Illegal formula generated!");
3319 };
3320#endif
3321
3322 // Now that we've decided what we want, make it so.
3323 ImplementSolution(Solution, P);
3324}
3325
3326void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3327 if (Factors.empty() && Types.empty()) return;
3328
3329 OS << "LSR has identified the following interesting factors and types: ";
3330 bool First = true;
3331
3332 for (SmallSetVector<int64_t, 8>::const_iterator
3333 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3334 if (!First) OS << ", ";
3335 First = false;
3336 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003337 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003338
Dan Gohman572645c2010-02-12 10:34:29 +00003339 for (SmallSetVector<const Type *, 4>::const_iterator
3340 I = Types.begin(), E = Types.end(); I != E; ++I) {
3341 if (!First) OS << ", ";
3342 First = false;
3343 OS << '(' << **I << ')';
3344 }
3345 OS << '\n';
3346}
3347
3348void LSRInstance::print_fixups(raw_ostream &OS) const {
3349 OS << "LSR is examining the following fixup sites:\n";
3350 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3351 E = Fixups.end(); I != E; ++I) {
3352 const LSRFixup &LF = *I;
3353 dbgs() << " ";
3354 LF.print(OS);
3355 OS << '\n';
3356 }
3357}
3358
3359void LSRInstance::print_uses(raw_ostream &OS) const {
3360 OS << "LSR is examining the following uses:\n";
3361 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3362 E = Uses.end(); I != E; ++I) {
3363 const LSRUse &LU = *I;
3364 dbgs() << " ";
3365 LU.print(OS);
3366 OS << '\n';
3367 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3368 JE = LU.Formulae.end(); J != JE; ++J) {
3369 OS << " ";
3370 J->print(OS);
3371 OS << '\n';
3372 }
3373 }
3374}
3375
3376void LSRInstance::print(raw_ostream &OS) const {
3377 print_factors_and_types(OS);
3378 print_fixups(OS);
3379 print_uses(OS);
3380}
3381
3382void LSRInstance::dump() const {
3383 print(errs()); errs() << '\n';
3384}
3385
3386namespace {
3387
3388class LoopStrengthReduce : public LoopPass {
3389 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3390 /// transformation profitability.
3391 const TargetLowering *const TLI;
3392
3393public:
3394 static char ID; // Pass ID, replacement for typeid
3395 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3396
3397private:
3398 bool runOnLoop(Loop *L, LPPassManager &LPM);
3399 void getAnalysisUsage(AnalysisUsage &AU) const;
3400};
3401
3402}
3403
3404char LoopStrengthReduce::ID = 0;
3405static RegisterPass<LoopStrengthReduce>
3406X("loop-reduce", "Loop Strength Reduction");
3407
3408Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3409 return new LoopStrengthReduce(TLI);
3410}
3411
3412LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3413 : LoopPass(&ID), TLI(tli) {}
3414
3415void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3416 // We split critical edges, so we change the CFG. However, we do update
3417 // many analyses if they are around.
3418 AU.addPreservedID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00003419 AU.addPreserved("domfrontier");
3420
Dan Gohmane5f76872010-04-09 22:07:05 +00003421 AU.addRequired<LoopInfo>();
3422 AU.addPreserved<LoopInfo>();
Dan Gohman572645c2010-02-12 10:34:29 +00003423 AU.addRequiredID(LoopSimplifyID);
3424 AU.addRequired<DominatorTree>();
3425 AU.addPreserved<DominatorTree>();
3426 AU.addRequired<ScalarEvolution>();
3427 AU.addPreserved<ScalarEvolution>();
3428 AU.addRequired<IVUsers>();
3429 AU.addPreserved<IVUsers>();
3430}
3431
3432bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3433 bool Changed = false;
3434
3435 // Run the main LSR transformation.
3436 Changed |= LSRInstance(TLI, L, this).getChanged();
3437
Dan Gohmanafc36a92009-05-02 18:29:22 +00003438 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003439 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003440 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003441
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003442 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003443}