blob: 9982f1d71f63d2f31be29b99ead3c327107cceb9 [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 Gohmanb2df4332010-05-18 23:42:37 +0000115 void DropRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmana2086b32010-05-19 23:43:12 +0000116 void DropUse(size_t LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000117
Dan Gohman572645c2010-02-12 10:34:29 +0000118 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000119
Dan Gohman572645c2010-02-12 10:34:29 +0000120 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000121
Dan Gohman572645c2010-02-12 10:34:29 +0000122 void clear();
Dan Gohmana10756e2010-01-21 02:09:26 +0000123
Dan Gohman572645c2010-02-12 10:34:29 +0000124 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
125 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
126 iterator begin() { return RegSequence.begin(); }
127 iterator end() { return RegSequence.end(); }
128 const_iterator begin() const { return RegSequence.begin(); }
129 const_iterator end() const { return RegSequence.end(); }
130};
Dan Gohmana10756e2010-01-21 02:09:26 +0000131
Dan Gohmana10756e2010-01-21 02:09:26 +0000132}
133
Dan Gohman572645c2010-02-12 10:34:29 +0000134void
135RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
136 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman90bb3552010-05-18 22:33:00 +0000137 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman572645c2010-02-12 10:34:29 +0000138 RegSortData &RSD = Pair.first->second;
139 if (Pair.second)
140 RegSequence.push_back(Reg);
141 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
142 RSD.UsedByIndices.set(LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000143}
144
Dan Gohmanb2df4332010-05-18 23:42:37 +0000145void
146RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
147 RegUsesTy::iterator It = RegUsesMap.find(Reg);
148 assert(It != RegUsesMap.end());
149 RegSortData &RSD = It->second;
150 assert(RSD.UsedByIndices.size() > LUIdx);
151 RSD.UsedByIndices.reset(LUIdx);
152}
153
Dan Gohmana2086b32010-05-19 23:43:12 +0000154void
155RegUseTracker::DropUse(size_t LUIdx) {
156 // Remove the use index from every register's use list.
157 for (RegUsesTy::iterator I = RegUsesMap.begin(), E = RegUsesMap.end();
158 I != E; ++I)
159 I->second.UsedByIndices.reset(LUIdx);
160}
161
Dan Gohman572645c2010-02-12 10:34:29 +0000162bool
163RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman90bb3552010-05-18 22:33:00 +0000164 if (!RegUsesMap.count(Reg)) return false;
Dan Gohman572645c2010-02-12 10:34:29 +0000165 const SmallBitVector &UsedByIndices =
Dan Gohman90bb3552010-05-18 22:33:00 +0000166 RegUsesMap.find(Reg)->second.UsedByIndices;
Dan Gohman572645c2010-02-12 10:34:29 +0000167 int i = UsedByIndices.find_first();
168 if (i == -1) return false;
169 if ((size_t)i != LUIdx) return true;
170 return UsedByIndices.find_next(i) != -1;
171}
Dan Gohmana10756e2010-01-21 02:09:26 +0000172
Dan Gohman572645c2010-02-12 10:34:29 +0000173const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman90bb3552010-05-18 22:33:00 +0000174 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
175 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman572645c2010-02-12 10:34:29 +0000176 return I->second.UsedByIndices;
177}
Dan Gohmana10756e2010-01-21 02:09:26 +0000178
Dan Gohman572645c2010-02-12 10:34:29 +0000179void RegUseTracker::clear() {
Dan Gohman90bb3552010-05-18 22:33:00 +0000180 RegUsesMap.clear();
Dan Gohman572645c2010-02-12 10:34:29 +0000181 RegSequence.clear();
182}
Dan Gohmana10756e2010-01-21 02:09:26 +0000183
Dan Gohman572645c2010-02-12 10:34:29 +0000184namespace {
185
186/// Formula - This class holds information that describes a formula for
187/// computing satisfying a use. It may include broken-out immediates and scaled
188/// registers.
189struct Formula {
190 /// AM - This is used to represent complex addressing, as well as other kinds
191 /// of interesting uses.
192 TargetLowering::AddrMode AM;
193
194 /// BaseRegs - The list of "base" registers for this use. When this is
195 /// non-empty, AM.HasBaseReg should be set to true.
196 SmallVector<const SCEV *, 2> BaseRegs;
197
198 /// ScaledReg - The 'scaled' register for this use. This should be non-null
199 /// when AM.Scale is not zero.
200 const SCEV *ScaledReg;
201
202 Formula() : ScaledReg(0) {}
203
204 void InitialMatch(const SCEV *S, Loop *L,
205 ScalarEvolution &SE, DominatorTree &DT);
206
207 unsigned getNumRegs() const;
208 const Type *getType() const;
209
Dan Gohman5ce6d052010-05-20 15:17:54 +0000210 void DeleteBaseReg(const SCEV *&S);
211
Dan Gohman572645c2010-02-12 10:34:29 +0000212 bool referencesReg(const SCEV *S) const;
213 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
214 const RegUseTracker &RegUses) const;
215
216 void print(raw_ostream &OS) const;
217 void dump() const;
218};
219
220}
221
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000222/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman572645c2010-02-12 10:34:29 +0000223static void DoInitialMatch(const SCEV *S, Loop *L,
224 SmallVectorImpl<const SCEV *> &Good,
225 SmallVectorImpl<const SCEV *> &Bad,
226 ScalarEvolution &SE, DominatorTree &DT) {
227 // Collect expressions which properly dominate the loop header.
228 if (S->properlyDominates(L->getHeader(), &DT)) {
229 Good.push_back(S);
230 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000231 }
Dan Gohman572645c2010-02-12 10:34:29 +0000232
233 // Look at add operands.
234 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
235 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
236 I != E; ++I)
237 DoInitialMatch(*I, L, Good, Bad, SE, DT);
238 return;
239 }
240
241 // Look at addrec operands.
242 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
243 if (!AR->getStart()->isZero()) {
244 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
Dan Gohmandeff6212010-05-03 22:09:21 +0000245 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +0000246 AR->getStepRecurrence(SE),
247 AR->getLoop()),
248 L, Good, Bad, SE, DT);
249 return;
250 }
251
252 // Handle a multiplication by -1 (negation) if it didn't fold.
253 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
254 if (Mul->getOperand(0)->isAllOnesValue()) {
255 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
256 const SCEV *NewMul = SE.getMulExpr(Ops);
257
258 SmallVector<const SCEV *, 4> MyGood;
259 SmallVector<const SCEV *, 4> MyBad;
260 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
261 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
262 SE.getEffectiveSCEVType(NewMul->getType())));
263 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
264 E = MyGood.end(); I != E; ++I)
265 Good.push_back(SE.getMulExpr(NegOne, *I));
266 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
267 E = MyBad.end(); I != E; ++I)
268 Bad.push_back(SE.getMulExpr(NegOne, *I));
269 return;
270 }
271
272 // Ok, we can't do anything interesting. Just stuff the whole thing into a
273 // register and hope for the best.
274 Bad.push_back(S);
275}
276
277/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
278/// attempting to keep all loop-invariant and loop-computable values in a
279/// single base register.
280void Formula::InitialMatch(const SCEV *S, Loop *L,
281 ScalarEvolution &SE, DominatorTree &DT) {
282 SmallVector<const SCEV *, 4> Good;
283 SmallVector<const SCEV *, 4> Bad;
284 DoInitialMatch(S, L, Good, Bad, SE, DT);
285 if (!Good.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000286 const SCEV *Sum = SE.getAddExpr(Good);
287 if (!Sum->isZero())
288 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000289 AM.HasBaseReg = true;
290 }
291 if (!Bad.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000292 const SCEV *Sum = SE.getAddExpr(Bad);
293 if (!Sum->isZero())
294 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000295 AM.HasBaseReg = true;
296 }
297}
298
299/// getNumRegs - Return the total number of register operands used by this
300/// formula. This does not include register uses implied by non-constant
301/// addrec strides.
302unsigned Formula::getNumRegs() const {
303 return !!ScaledReg + BaseRegs.size();
304}
305
306/// getType - Return the type of this formula, if it has one, or null
307/// otherwise. This type is meaningless except for the bit size.
308const Type *Formula::getType() const {
309 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
310 ScaledReg ? ScaledReg->getType() :
311 AM.BaseGV ? AM.BaseGV->getType() :
312 0;
313}
314
Dan Gohman5ce6d052010-05-20 15:17:54 +0000315/// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
316void Formula::DeleteBaseReg(const SCEV *&S) {
317 if (&S != &BaseRegs.back())
318 std::swap(S, BaseRegs.back());
319 BaseRegs.pop_back();
320}
321
Dan Gohman572645c2010-02-12 10:34:29 +0000322/// referencesReg - Test if this formula references the given register.
323bool Formula::referencesReg(const SCEV *S) const {
324 return S == ScaledReg ||
325 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
326}
327
328/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
329/// which are used by uses other than the use with the given index.
330bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
331 const RegUseTracker &RegUses) const {
332 if (ScaledReg)
333 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
334 return true;
335 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
336 E = BaseRegs.end(); I != E; ++I)
337 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
338 return true;
339 return false;
340}
341
342void Formula::print(raw_ostream &OS) const {
343 bool First = true;
344 if (AM.BaseGV) {
345 if (!First) OS << " + "; else First = false;
346 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
347 }
348 if (AM.BaseOffs != 0) {
349 if (!First) OS << " + "; else First = false;
350 OS << AM.BaseOffs;
351 }
352 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
353 E = BaseRegs.end(); I != E; ++I) {
354 if (!First) OS << " + "; else First = false;
355 OS << "reg(" << **I << ')';
356 }
Dan Gohmanc4cfbaf2010-05-18 22:35:55 +0000357 if (AM.HasBaseReg && BaseRegs.empty()) {
358 if (!First) OS << " + "; else First = false;
359 OS << "**error: HasBaseReg**";
360 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
361 if (!First) OS << " + "; else First = false;
362 OS << "**error: !HasBaseReg**";
363 }
Dan Gohman572645c2010-02-12 10:34:29 +0000364 if (AM.Scale != 0) {
365 if (!First) OS << " + "; else First = false;
366 OS << AM.Scale << "*reg(";
367 if (ScaledReg)
368 OS << *ScaledReg;
369 else
370 OS << "<unknown>";
371 OS << ')';
372 }
373}
374
375void Formula::dump() const {
376 print(errs()); errs() << '\n';
377}
378
Dan Gohmanaae01f12010-02-19 19:32:49 +0000379/// isAddRecSExtable - Return true if the given addrec can be sign-extended
380/// without changing its value.
381static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
382 const Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000383 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000384 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
385}
386
387/// isAddSExtable - Return true if the given add can be sign-extended
388/// without changing its value.
389static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
390 const Type *WideTy =
Dan Gohmanea507f52010-05-20 19:44:23 +0000391 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000392 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
393}
394
Dan Gohman473e6352010-06-24 16:45:11 +0000395/// isMulSExtable - Return true if the given mul can be sign-extended
Dan Gohmanaae01f12010-02-19 19:32:49 +0000396/// without changing its value.
Dan Gohman473e6352010-06-24 16:45:11 +0000397static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000398 const Type *WideTy =
Dan Gohman473e6352010-06-24 16:45:11 +0000399 IntegerType::get(SE.getContext(),
400 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
401 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohmanaae01f12010-02-19 19:32:49 +0000402}
403
Dan Gohmanf09b7122010-02-19 19:35:48 +0000404/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
405/// and if the remainder is known to be zero, or null otherwise. If
406/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
407/// to Y, ignoring that the multiplication may overflow, which is useful when
408/// the result will be used in a context where the most significant bits are
409/// ignored.
410static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
411 ScalarEvolution &SE,
412 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000413 // Handle the trivial case, which works for any SCEV type.
414 if (LHS == RHS)
Dan Gohmandeff6212010-05-03 22:09:21 +0000415 return SE.getConstant(LHS->getType(), 1);
Dan Gohman572645c2010-02-12 10:34:29 +0000416
417 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
418 // folding.
419 if (RHS->isAllOnesValue())
420 return SE.getMulExpr(LHS, RHS);
421
422 // Check for a division of a constant by a constant.
423 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
424 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
425 if (!RC)
426 return 0;
427 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
428 return 0;
429 return SE.getConstant(C->getValue()->getValue()
430 .sdiv(RC->getValue()->getValue()));
431 }
432
Dan Gohmanaae01f12010-02-19 19:32:49 +0000433 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000434 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000435 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000436 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
437 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000438 if (!Start) return 0;
Dan Gohmanf09b7122010-02-19 19:35:48 +0000439 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
440 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000441 if (!Step) return 0;
442 return SE.getAddRecExpr(Start, Step, AR->getLoop());
443 }
Dan Gohman572645c2010-02-12 10:34:29 +0000444 }
445
Dan Gohmanaae01f12010-02-19 19:32:49 +0000446 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000447 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000448 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
449 SmallVector<const SCEV *, 8> Ops;
450 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
451 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000452 const SCEV *Op = getExactSDiv(*I, RHS, SE,
453 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000454 if (!Op) return 0;
455 Ops.push_back(Op);
456 }
457 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000458 }
Dan Gohman572645c2010-02-12 10:34:29 +0000459 }
460
461 // Check for a multiply operand that we can pull RHS out of.
462 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
Dan Gohmanaae01f12010-02-19 19:32:49 +0000463 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000464 SmallVector<const SCEV *, 4> Ops;
465 bool Found = false;
466 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
467 I != E; ++I) {
Dan Gohman47667442010-05-20 16:23:28 +0000468 const SCEV *S = *I;
Dan Gohman572645c2010-02-12 10:34:29 +0000469 if (!Found)
Dan Gohman47667442010-05-20 16:23:28 +0000470 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohmanf09b7122010-02-19 19:35:48 +0000471 IgnoreSignificantBits)) {
Dan Gohman47667442010-05-20 16:23:28 +0000472 S = Q;
Dan Gohman572645c2010-02-12 10:34:29 +0000473 Found = true;
Dan Gohman572645c2010-02-12 10:34:29 +0000474 }
Dan Gohman47667442010-05-20 16:23:28 +0000475 Ops.push_back(S);
Dan Gohman572645c2010-02-12 10:34:29 +0000476 }
477 return Found ? SE.getMulExpr(Ops) : 0;
478 }
479
480 // Otherwise we don't know.
481 return 0;
482}
483
484/// ExtractImmediate - If S involves the addition of a constant integer value,
485/// return that integer value, and mutate S to point to a new SCEV with that
486/// value excluded.
487static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
488 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
489 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000490 S = SE.getConstant(C->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000491 return C->getValue()->getSExtValue();
492 }
493 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
494 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
495 int64_t Result = ExtractImmediate(NewOps.front(), SE);
496 S = SE.getAddExpr(NewOps);
497 return Result;
498 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
499 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
500 int64_t Result = ExtractImmediate(NewOps.front(), SE);
501 S = SE.getAddRecExpr(NewOps, AR->getLoop());
502 return Result;
503 }
504 return 0;
505}
506
507/// ExtractSymbol - If S involves the addition of a GlobalValue address,
508/// return that symbol, and mutate S to point to a new SCEV with that
509/// value excluded.
510static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
511 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
512 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000513 S = SE.getConstant(GV->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000514 return GV;
515 }
516 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
517 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
518 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
519 S = SE.getAddExpr(NewOps);
520 return Result;
521 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
522 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
523 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
524 S = SE.getAddRecExpr(NewOps, AR->getLoop());
525 return Result;
526 }
527 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000528}
529
Dan Gohmanf284ce22009-02-18 00:08:39 +0000530/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000531/// specified value as an address.
532static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
533 bool isAddress = isa<LoadInst>(Inst);
534 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
535 if (SI->getOperand(1) == OperandVal)
536 isAddress = true;
537 } else if (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::prefetch:
543 case Intrinsic::x86_sse2_loadu_dq:
544 case Intrinsic::x86_sse2_loadu_pd:
545 case Intrinsic::x86_sse_loadu_ps:
546 case Intrinsic::x86_sse_storeu_ps:
547 case Intrinsic::x86_sse2_storeu_pd:
548 case Intrinsic::x86_sse2_storeu_dq:
549 case Intrinsic::x86_sse2_storel_dq:
550 if (II->getOperand(1) == OperandVal)
551 isAddress = true;
552 break;
553 }
554 }
555 return isAddress;
556}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000557
Dan Gohman21e77222009-03-09 21:01:17 +0000558/// getAccessType - Return the type of the memory being accessed.
559static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000560 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000561 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000562 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000563 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
564 // Addressing modes can also be folded into prefetches and a variety
565 // of intrinsics.
566 switch (II->getIntrinsicID()) {
567 default: break;
568 case Intrinsic::x86_sse_storeu_ps:
569 case Intrinsic::x86_sse2_storeu_pd:
570 case Intrinsic::x86_sse2_storeu_dq:
571 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmana537bf82009-05-18 16:45:28 +0000572 AccessTy = II->getOperand(1)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000573 break;
574 }
575 }
Dan Gohman572645c2010-02-12 10:34:29 +0000576
577 // All pointers have the same requirements, so canonicalize them to an
578 // arbitrary pointer type to minimize variation.
579 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
580 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
581 PTy->getAddressSpace());
582
Dan Gohmana537bf82009-05-18 16:45:28 +0000583 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000584}
585
Dan Gohman572645c2010-02-12 10:34:29 +0000586/// DeleteTriviallyDeadInstructions - If any of the instructions is the
587/// specified set are trivially dead, delete them and see if this makes any of
588/// their operands subsequently dead.
589static bool
590DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
591 bool Changed = false;
592
593 while (!DeadInsts.empty()) {
594 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
595
596 if (I == 0 || !isInstructionTriviallyDead(I))
597 continue;
598
599 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
600 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
601 *OI = 0;
602 if (U->use_empty())
603 DeadInsts.push_back(U);
604 }
605
606 I->eraseFromParent();
607 Changed = true;
608 }
609
610 return Changed;
611}
612
Dan Gohman7979b722010-01-22 00:46:49 +0000613namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000614
Dan Gohman572645c2010-02-12 10:34:29 +0000615/// Cost - This class is used to measure and compare candidate formulae.
616class Cost {
617 /// TODO: Some of these could be merged. Also, a lexical ordering
618 /// isn't always optimal.
619 unsigned NumRegs;
620 unsigned AddRecCost;
621 unsigned NumIVMuls;
622 unsigned NumBaseAdds;
623 unsigned ImmCost;
624 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000625
Dan Gohman572645c2010-02-12 10:34:29 +0000626public:
627 Cost()
628 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
629 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000630
Dan Gohman572645c2010-02-12 10:34:29 +0000631 unsigned getNumRegs() const { return NumRegs; }
Dan Gohman7979b722010-01-22 00:46:49 +0000632
Dan Gohman572645c2010-02-12 10:34:29 +0000633 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000634
Dan Gohman572645c2010-02-12 10:34:29 +0000635 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000636
Dan Gohman572645c2010-02-12 10:34:29 +0000637 void RateFormula(const Formula &F,
638 SmallPtrSet<const SCEV *, 16> &Regs,
639 const DenseSet<const SCEV *> &VisitedRegs,
640 const Loop *L,
641 const SmallVectorImpl<int64_t> &Offsets,
642 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000643
Dan Gohman572645c2010-02-12 10:34:29 +0000644 void print(raw_ostream &OS) const;
645 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000646
Dan Gohman572645c2010-02-12 10:34:29 +0000647private:
648 void RateRegister(const SCEV *Reg,
649 SmallPtrSet<const SCEV *, 16> &Regs,
650 const Loop *L,
651 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000652 void RatePrimaryRegister(const SCEV *Reg,
653 SmallPtrSet<const SCEV *, 16> &Regs,
654 const Loop *L,
655 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000656};
657
658}
659
660/// RateRegister - Tally up interesting quantities from the given register.
661void Cost::RateRegister(const SCEV *Reg,
662 SmallPtrSet<const SCEV *, 16> &Regs,
663 const Loop *L,
664 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000665 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
666 if (AR->getLoop() == L)
667 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000668
Dan Gohman9214b822010-02-13 02:06:02 +0000669 // If this is an addrec for a loop that's already been visited by LSR,
670 // don't second-guess its addrec phi nodes. LSR isn't currently smart
671 // enough to reason about more than one loop at a time. Consider these
672 // registers free and leave them alone.
673 else if (L->contains(AR->getLoop()) ||
674 (!AR->getLoop()->contains(L) &&
675 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
676 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
677 PHINode *PN = dyn_cast<PHINode>(I); ++I)
678 if (SE.isSCEVable(PN->getType()) &&
679 (SE.getEffectiveSCEVType(PN->getType()) ==
680 SE.getEffectiveSCEVType(AR->getType())) &&
681 SE.getSCEV(PN) == AR)
682 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000683
Dan Gohman9214b822010-02-13 02:06:02 +0000684 // If this isn't one of the addrecs that the loop already has, it
685 // would require a costly new phi and add. TODO: This isn't
686 // precisely modeled right now.
687 ++NumBaseAdds;
688 if (!Regs.count(AR->getStart()))
Dan Gohman572645c2010-02-12 10:34:29 +0000689 RateRegister(AR->getStart(), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000690 }
Dan Gohman572645c2010-02-12 10:34:29 +0000691
Dan Gohman9214b822010-02-13 02:06:02 +0000692 // Add the step value register, if it needs one.
693 // TODO: The non-affine case isn't precisely modeled here.
694 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
695 if (!Regs.count(AR->getStart()))
696 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000697 }
Dan Gohman9214b822010-02-13 02:06:02 +0000698 ++NumRegs;
699
700 // Rough heuristic; favor registers which don't require extra setup
701 // instructions in the preheader.
702 if (!isa<SCEVUnknown>(Reg) &&
703 !isa<SCEVConstant>(Reg) &&
704 !(isa<SCEVAddRecExpr>(Reg) &&
705 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
706 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
707 ++SetupCost;
708}
709
710/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
711/// before, rate it.
712void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000713 SmallPtrSet<const SCEV *, 16> &Regs,
714 const Loop *L,
715 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000716 if (Regs.insert(Reg))
717 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000718}
719
720void Cost::RateFormula(const Formula &F,
721 SmallPtrSet<const SCEV *, 16> &Regs,
722 const DenseSet<const SCEV *> &VisitedRegs,
723 const Loop *L,
724 const SmallVectorImpl<int64_t> &Offsets,
725 ScalarEvolution &SE, DominatorTree &DT) {
726 // Tally up the registers.
727 if (const SCEV *ScaledReg = F.ScaledReg) {
728 if (VisitedRegs.count(ScaledReg)) {
729 Loose();
730 return;
731 }
Dan Gohman9214b822010-02-13 02:06:02 +0000732 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000733 }
734 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
735 E = F.BaseRegs.end(); I != E; ++I) {
736 const SCEV *BaseReg = *I;
737 if (VisitedRegs.count(BaseReg)) {
738 Loose();
739 return;
740 }
Dan Gohman9214b822010-02-13 02:06:02 +0000741 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000742
743 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
744 BaseReg->hasComputableLoopEvolution(L);
745 }
746
747 if (F.BaseRegs.size() > 1)
748 NumBaseAdds += F.BaseRegs.size() - 1;
749
750 // Tally up the non-zero immediates.
751 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
752 E = Offsets.end(); I != E; ++I) {
753 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
754 if (F.AM.BaseGV)
755 ImmCost += 64; // Handle symbolic values conservatively.
756 // TODO: This should probably be the pointer size.
757 else if (Offset != 0)
758 ImmCost += APInt(64, Offset, true).getMinSignedBits();
759 }
760}
761
762/// Loose - Set this cost to a loosing value.
763void Cost::Loose() {
764 NumRegs = ~0u;
765 AddRecCost = ~0u;
766 NumIVMuls = ~0u;
767 NumBaseAdds = ~0u;
768 ImmCost = ~0u;
769 SetupCost = ~0u;
770}
771
772/// operator< - Choose the lower cost.
773bool Cost::operator<(const Cost &Other) const {
774 if (NumRegs != Other.NumRegs)
775 return NumRegs < Other.NumRegs;
776 if (AddRecCost != Other.AddRecCost)
777 return AddRecCost < Other.AddRecCost;
778 if (NumIVMuls != Other.NumIVMuls)
779 return NumIVMuls < Other.NumIVMuls;
780 if (NumBaseAdds != Other.NumBaseAdds)
781 return NumBaseAdds < Other.NumBaseAdds;
782 if (ImmCost != Other.ImmCost)
783 return ImmCost < Other.ImmCost;
784 if (SetupCost != Other.SetupCost)
785 return SetupCost < Other.SetupCost;
786 return false;
787}
788
789void Cost::print(raw_ostream &OS) const {
790 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
791 if (AddRecCost != 0)
792 OS << ", with addrec cost " << AddRecCost;
793 if (NumIVMuls != 0)
794 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
795 if (NumBaseAdds != 0)
796 OS << ", plus " << NumBaseAdds << " base add"
797 << (NumBaseAdds == 1 ? "" : "s");
798 if (ImmCost != 0)
799 OS << ", plus " << ImmCost << " imm cost";
800 if (SetupCost != 0)
801 OS << ", plus " << SetupCost << " setup cost";
802}
803
804void Cost::dump() const {
805 print(errs()); errs() << '\n';
806}
807
808namespace {
809
810/// LSRFixup - An operand value in an instruction which is to be replaced
811/// with some equivalent, possibly strength-reduced, replacement.
812struct LSRFixup {
813 /// UserInst - The instruction which will be updated.
814 Instruction *UserInst;
815
816 /// OperandValToReplace - The operand of the instruction which will
817 /// be replaced. The operand may be used more than once; every instance
818 /// will be replaced.
819 Value *OperandValToReplace;
820
Dan Gohman448db1c2010-04-07 22:27:08 +0000821 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman572645c2010-02-12 10:34:29 +0000822 /// induction variable, this variable is non-null and holds the loop
823 /// associated with the induction variable.
Dan Gohman448db1c2010-04-07 22:27:08 +0000824 PostIncLoopSet PostIncLoops;
Dan Gohman572645c2010-02-12 10:34:29 +0000825
826 /// LUIdx - The index of the LSRUse describing the expression which
827 /// this fixup needs, minus an offset (below).
828 size_t LUIdx;
829
830 /// Offset - A constant offset to be added to the LSRUse expression.
831 /// This allows multiple fixups to share the same LSRUse with different
832 /// offsets, for example in an unrolled loop.
833 int64_t Offset;
834
Dan Gohman448db1c2010-04-07 22:27:08 +0000835 bool isUseFullyOutsideLoop(const Loop *L) const;
836
Dan Gohman572645c2010-02-12 10:34:29 +0000837 LSRFixup();
838
839 void print(raw_ostream &OS) const;
840 void dump() const;
841};
842
843}
844
845LSRFixup::LSRFixup()
Dan Gohmanea507f52010-05-20 19:44:23 +0000846 : UserInst(0), OperandValToReplace(0), LUIdx(~size_t(0)), Offset(0) {}
Dan Gohman572645c2010-02-12 10:34:29 +0000847
Dan Gohman448db1c2010-04-07 22:27:08 +0000848/// isUseFullyOutsideLoop - Test whether this fixup always uses its
849/// value outside of the given loop.
850bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
851 // PHI nodes use their value in their incoming blocks.
852 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
853 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
854 if (PN->getIncomingValue(i) == OperandValToReplace &&
855 L->contains(PN->getIncomingBlock(i)))
856 return false;
857 return true;
858 }
859
860 return !L->contains(UserInst);
861}
862
Dan Gohman572645c2010-02-12 10:34:29 +0000863void LSRFixup::print(raw_ostream &OS) const {
864 OS << "UserInst=";
865 // Store is common and interesting enough to be worth special-casing.
866 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
867 OS << "store ";
868 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
869 } else if (UserInst->getType()->isVoidTy())
870 OS << UserInst->getOpcodeName();
871 else
872 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
873
874 OS << ", OperandValToReplace=";
875 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
876
Dan Gohman448db1c2010-04-07 22:27:08 +0000877 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
878 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +0000879 OS << ", PostIncLoop=";
Dan Gohman448db1c2010-04-07 22:27:08 +0000880 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
Dan Gohman572645c2010-02-12 10:34:29 +0000881 }
882
883 if (LUIdx != ~size_t(0))
884 OS << ", LUIdx=" << LUIdx;
885
886 if (Offset != 0)
887 OS << ", Offset=" << Offset;
888}
889
890void LSRFixup::dump() const {
891 print(errs()); errs() << '\n';
892}
893
894namespace {
895
896/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
897/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
898struct UniquifierDenseMapInfo {
899 static SmallVector<const SCEV *, 2> getEmptyKey() {
900 SmallVector<const SCEV *, 2> V;
901 V.push_back(reinterpret_cast<const SCEV *>(-1));
902 return V;
903 }
904
905 static SmallVector<const SCEV *, 2> getTombstoneKey() {
906 SmallVector<const SCEV *, 2> V;
907 V.push_back(reinterpret_cast<const SCEV *>(-2));
908 return V;
909 }
910
911 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
912 unsigned Result = 0;
913 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
914 E = V.end(); I != E; ++I)
915 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
916 return Result;
917 }
918
919 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
920 const SmallVector<const SCEV *, 2> &RHS) {
921 return LHS == RHS;
922 }
923};
924
925/// LSRUse - This class holds the state that LSR keeps for each use in
926/// IVUsers, as well as uses invented by LSR itself. It includes information
927/// about what kinds of things can be folded into the user, information about
928/// the user itself, and information about how the use may be satisfied.
929/// TODO: Represent multiple users of the same expression in common?
930class LSRUse {
931 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
932
933public:
934 /// KindType - An enum for a kind of use, indicating what types of
935 /// scaled and immediate operands it might support.
936 enum KindType {
937 Basic, ///< A normal use, with no folding.
938 Special, ///< A special case of basic, allowing -1 scales.
939 Address, ///< An address use; folding according to TargetLowering
940 ICmpZero ///< An equality icmp with both operands folded into one.
941 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000942 };
Dan Gohman572645c2010-02-12 10:34:29 +0000943
944 KindType Kind;
945 const Type *AccessTy;
946
947 SmallVector<int64_t, 8> Offsets;
948 int64_t MinOffset;
949 int64_t MaxOffset;
950
951 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
952 /// LSRUse are outside of the loop, in which case some special-case heuristics
953 /// may be used.
954 bool AllFixupsOutsideLoop;
955
956 /// Formulae - A list of ways to build a value that can satisfy this user.
957 /// After the list is populated, one of these is selected heuristically and
958 /// used to formulate a replacement for OperandValToReplace in UserInst.
959 SmallVector<Formula, 12> Formulae;
960
961 /// Regs - The set of register candidates used by all formulae in this LSRUse.
962 SmallPtrSet<const SCEV *, 4> Regs;
963
964 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
965 MinOffset(INT64_MAX),
966 MaxOffset(INT64_MIN),
967 AllFixupsOutsideLoop(true) {}
968
Dan Gohmana2086b32010-05-19 23:43:12 +0000969 bool HasFormulaWithSameRegs(const Formula &F) const;
Dan Gohman454d26d2010-02-22 04:11:59 +0000970 bool InsertFormula(const Formula &F);
Dan Gohmand69d6282010-05-18 22:39:15 +0000971 void DeleteFormula(Formula &F);
Dan Gohmanb2df4332010-05-18 23:42:37 +0000972 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
Dan Gohman572645c2010-02-12 10:34:29 +0000973
974 void check() const;
975
976 void print(raw_ostream &OS) const;
977 void dump() const;
978};
979
Dan Gohmanb6211712010-06-19 21:21:39 +0000980}
981
Dan Gohmana2086b32010-05-19 23:43:12 +0000982/// HasFormula - Test whether this use as a formula which has the same
983/// registers as the given formula.
984bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
985 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
986 if (F.ScaledReg) Key.push_back(F.ScaledReg);
987 // Unstable sort by host order ok, because this is only used for uniquifying.
988 std::sort(Key.begin(), Key.end());
989 return Uniquifier.count(Key);
990}
991
Dan Gohman572645c2010-02-12 10:34:29 +0000992/// InsertFormula - If the given formula has not yet been inserted, add it to
993/// the list, and return true. Return false otherwise.
Dan Gohman454d26d2010-02-22 04:11:59 +0000994bool LSRUse::InsertFormula(const Formula &F) {
Dan Gohman572645c2010-02-12 10:34:29 +0000995 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
996 if (F.ScaledReg) Key.push_back(F.ScaledReg);
997 // Unstable sort by host order ok, because this is only used for uniquifying.
998 std::sort(Key.begin(), Key.end());
999
1000 if (!Uniquifier.insert(Key).second)
1001 return false;
1002
1003 // Using a register to hold the value of 0 is not profitable.
1004 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1005 "Zero allocated in a scaled register!");
1006#ifndef NDEBUG
1007 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1008 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1009 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1010#endif
1011
1012 // Add the formula to the list.
1013 Formulae.push_back(F);
1014
1015 // Record registers now being used by this use.
1016 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1017 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1018
1019 return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001020}
1021
Dan Gohmand69d6282010-05-18 22:39:15 +00001022/// DeleteFormula - Remove the given formula from this use's list.
1023void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman5ce6d052010-05-20 15:17:54 +00001024 if (&F != &Formulae.back())
1025 std::swap(F, Formulae.back());
Dan Gohmand69d6282010-05-18 22:39:15 +00001026 Formulae.pop_back();
Dan Gohmana2086b32010-05-19 23:43:12 +00001027 assert(!Formulae.empty() && "LSRUse has no formulae left!");
Dan Gohmand69d6282010-05-18 22:39:15 +00001028}
1029
Dan Gohmanb2df4332010-05-18 23:42:37 +00001030/// RecomputeRegs - Recompute the Regs field, and update RegUses.
1031void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1032 // Now that we've filtered out some formulae, recompute the Regs set.
1033 SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1034 Regs.clear();
Dan Gohman402d4352010-05-20 20:33:18 +00001035 for (SmallVectorImpl<Formula>::const_iterator I = Formulae.begin(),
1036 E = Formulae.end(); I != E; ++I) {
1037 const Formula &F = *I;
Dan Gohmanb2df4332010-05-18 23:42:37 +00001038 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1039 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1040 }
1041
1042 // Update the RegTracker.
1043 for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1044 E = OldRegs.end(); I != E; ++I)
1045 if (!Regs.count(*I))
1046 RegUses.DropRegister(*I, LUIdx);
1047}
1048
Dan Gohman572645c2010-02-12 10:34:29 +00001049void LSRUse::print(raw_ostream &OS) const {
1050 OS << "LSR Use: Kind=";
1051 switch (Kind) {
1052 case Basic: OS << "Basic"; break;
1053 case Special: OS << "Special"; break;
1054 case ICmpZero: OS << "ICmpZero"; break;
1055 case Address:
1056 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +00001057 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +00001058 OS << "pointer"; // the full pointer type could be really verbose
1059 else
1060 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +00001061 }
1062
Dan Gohman572645c2010-02-12 10:34:29 +00001063 OS << ", Offsets={";
1064 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1065 E = Offsets.end(); I != E; ++I) {
1066 OS << *I;
1067 if (next(I) != E)
1068 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +00001069 }
Dan Gohman572645c2010-02-12 10:34:29 +00001070 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +00001071
Dan Gohman572645c2010-02-12 10:34:29 +00001072 if (AllFixupsOutsideLoop)
1073 OS << ", all-fixups-outside-loop";
Dan Gohman7979b722010-01-22 00:46:49 +00001074}
1075
Dan Gohman572645c2010-02-12 10:34:29 +00001076void LSRUse::dump() const {
1077 print(errs()); errs() << '\n';
1078}
Dan Gohman7979b722010-01-22 00:46:49 +00001079
Dan Gohman572645c2010-02-12 10:34:29 +00001080/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1081/// be completely folded into the user instruction at isel time. This includes
1082/// address-mode folding and special icmp tricks.
1083static bool isLegalUse(const TargetLowering::AddrMode &AM,
1084 LSRUse::KindType Kind, const Type *AccessTy,
1085 const TargetLowering *TLI) {
1086 switch (Kind) {
1087 case LSRUse::Address:
1088 // If we have low-level target information, ask the target if it can
1089 // completely fold this address.
1090 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1091
1092 // Otherwise, just guess that reg+reg addressing is legal.
1093 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1094
1095 case LSRUse::ICmpZero:
1096 // There's not even a target hook for querying whether it would be legal to
1097 // fold a GV into an ICmp.
1098 if (AM.BaseGV)
1099 return false;
1100
1101 // ICmp only has two operands; don't allow more than two non-trivial parts.
1102 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1103 return false;
1104
1105 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1106 // putting the scaled register in the other operand of the icmp.
1107 if (AM.Scale != 0 && AM.Scale != -1)
1108 return false;
1109
1110 // If we have low-level target information, ask the target if it can fold an
1111 // integer immediate on an icmp.
1112 if (AM.BaseOffs != 0) {
1113 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1114 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001115 }
Dan Gohman572645c2010-02-12 10:34:29 +00001116
1117 return true;
1118
1119 case LSRUse::Basic:
1120 // Only handle single-register values.
1121 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1122
1123 case LSRUse::Special:
1124 // Only handle -1 scales, or no scale.
1125 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001126 }
1127
Dan Gohman7979b722010-01-22 00:46:49 +00001128 return false;
1129}
1130
Dan Gohman572645c2010-02-12 10:34:29 +00001131static bool isLegalUse(TargetLowering::AddrMode AM,
1132 int64_t MinOffset, int64_t MaxOffset,
1133 LSRUse::KindType Kind, const Type *AccessTy,
1134 const TargetLowering *TLI) {
1135 // Check for overflow.
1136 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1137 (MinOffset > 0))
1138 return false;
1139 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1140 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1141 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1142 // Check for overflow.
1143 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1144 (MaxOffset > 0))
1145 return false;
1146 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1147 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001148 }
Dan Gohman572645c2010-02-12 10:34:29 +00001149 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001150}
1151
Dan Gohman572645c2010-02-12 10:34:29 +00001152static bool isAlwaysFoldable(int64_t BaseOffs,
1153 GlobalValue *BaseGV,
1154 bool HasBaseReg,
1155 LSRUse::KindType Kind, const Type *AccessTy,
Dan Gohman454d26d2010-02-22 04:11:59 +00001156 const TargetLowering *TLI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001157 // Fast-path: zero is always foldable.
1158 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001159
Dan Gohman572645c2010-02-12 10:34:29 +00001160 // Conservatively, create an address with an immediate and a
1161 // base and a scale.
1162 TargetLowering::AddrMode AM;
1163 AM.BaseOffs = BaseOffs;
1164 AM.BaseGV = BaseGV;
1165 AM.HasBaseReg = HasBaseReg;
1166 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001167
Dan Gohmana2086b32010-05-19 23:43:12 +00001168 // Canonicalize a scale of 1 to a base register if the formula doesn't
1169 // already have a base register.
1170 if (!AM.HasBaseReg && AM.Scale == 1) {
1171 AM.Scale = 0;
1172 AM.HasBaseReg = true;
1173 }
1174
Dan Gohman572645c2010-02-12 10:34:29 +00001175 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001176}
1177
Dan Gohman572645c2010-02-12 10:34:29 +00001178static bool isAlwaysFoldable(const SCEV *S,
1179 int64_t MinOffset, int64_t MaxOffset,
1180 bool HasBaseReg,
1181 LSRUse::KindType Kind, const Type *AccessTy,
1182 const TargetLowering *TLI,
1183 ScalarEvolution &SE) {
1184 // Fast-path: zero is always foldable.
1185 if (S->isZero()) return true;
1186
1187 // Conservatively, create an address with an immediate and a
1188 // base and a scale.
1189 int64_t BaseOffs = ExtractImmediate(S, SE);
1190 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1191
1192 // If there's anything else involved, it's not foldable.
1193 if (!S->isZero()) return false;
1194
1195 // Fast-path: zero is always foldable.
1196 if (BaseOffs == 0 && !BaseGV) return true;
1197
1198 // Conservatively, create an address with an immediate and a
1199 // base and a scale.
1200 TargetLowering::AddrMode AM;
1201 AM.BaseOffs = BaseOffs;
1202 AM.BaseGV = BaseGV;
1203 AM.HasBaseReg = HasBaseReg;
1204 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1205
1206 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001207}
1208
Dan Gohmanb6211712010-06-19 21:21:39 +00001209namespace {
1210
Dan Gohman1e3121c2010-06-19 21:29:59 +00001211/// UseMapDenseMapInfo - A DenseMapInfo implementation for holding
1212/// DenseMaps and DenseSets of pairs of const SCEV* and LSRUse::Kind.
1213struct UseMapDenseMapInfo {
1214 static std::pair<const SCEV *, LSRUse::KindType> getEmptyKey() {
1215 return std::make_pair(reinterpret_cast<const SCEV *>(-1), LSRUse::Basic);
1216 }
1217
1218 static std::pair<const SCEV *, LSRUse::KindType> getTombstoneKey() {
1219 return std::make_pair(reinterpret_cast<const SCEV *>(-2), LSRUse::Basic);
1220 }
1221
1222 static unsigned
1223 getHashValue(const std::pair<const SCEV *, LSRUse::KindType> &V) {
1224 unsigned Result = DenseMapInfo<const SCEV *>::getHashValue(V.first);
1225 Result ^= DenseMapInfo<unsigned>::getHashValue(unsigned(V.second));
1226 return Result;
1227 }
1228
1229 static bool isEqual(const std::pair<const SCEV *, LSRUse::KindType> &LHS,
1230 const std::pair<const SCEV *, LSRUse::KindType> &RHS) {
1231 return LHS == RHS;
1232 }
1233};
1234
Dan Gohman572645c2010-02-12 10:34:29 +00001235/// FormulaSorter - This class implements an ordering for formulae which sorts
1236/// the by their standalone cost.
1237class FormulaSorter {
1238 /// These two sets are kept empty, so that we compute standalone costs.
1239 DenseSet<const SCEV *> VisitedRegs;
1240 SmallPtrSet<const SCEV *, 16> Regs;
1241 Loop *L;
1242 LSRUse *LU;
1243 ScalarEvolution &SE;
1244 DominatorTree &DT;
1245
1246public:
1247 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1248 : L(l), LU(&lu), SE(se), DT(dt) {}
1249
1250 bool operator()(const Formula &A, const Formula &B) {
1251 Cost CostA;
1252 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1253 Regs.clear();
1254 Cost CostB;
1255 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1256 Regs.clear();
1257 return CostA < CostB;
1258 }
1259};
1260
1261/// LSRInstance - This class holds state for the main loop strength reduction
1262/// logic.
1263class LSRInstance {
1264 IVUsers &IU;
1265 ScalarEvolution &SE;
1266 DominatorTree &DT;
Dan Gohmane5f76872010-04-09 22:07:05 +00001267 LoopInfo &LI;
Dan Gohman572645c2010-02-12 10:34:29 +00001268 const TargetLowering *const TLI;
1269 Loop *const L;
1270 bool Changed;
1271
1272 /// IVIncInsertPos - This is the insert position that the current loop's
1273 /// induction variable increment should be placed. In simple loops, this is
1274 /// the latch block's terminator. But in more complicated cases, this is a
1275 /// position which will dominate all the in-loop post-increment users.
1276 Instruction *IVIncInsertPos;
1277
1278 /// Factors - Interesting factors between use strides.
1279 SmallSetVector<int64_t, 8> Factors;
1280
1281 /// Types - Interesting use types, to facilitate truncation reuse.
1282 SmallSetVector<const Type *, 4> Types;
1283
1284 /// Fixups - The list of operands which are to be replaced.
1285 SmallVector<LSRFixup, 16> Fixups;
1286
1287 /// Uses - The list of interesting uses.
1288 SmallVector<LSRUse, 16> Uses;
1289
1290 /// RegUses - Track which uses use which register candidates.
1291 RegUseTracker RegUses;
1292
1293 void OptimizeShadowIV();
1294 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1295 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohmanc6519f92010-05-20 20:05:31 +00001296 void OptimizeLoopTermCond();
Dan Gohman572645c2010-02-12 10:34:29 +00001297
1298 void CollectInterestingTypesAndFactors();
1299 void CollectFixupsAndInitialFormulae();
1300
1301 LSRFixup &getNewFixup() {
1302 Fixups.push_back(LSRFixup());
1303 return Fixups.back();
1304 }
1305
1306 // Support for sharing of LSRUses between LSRFixups.
Dan Gohman1e3121c2010-06-19 21:29:59 +00001307 typedef DenseMap<std::pair<const SCEV *, LSRUse::KindType>,
1308 size_t,
1309 UseMapDenseMapInfo> UseMapTy;
Dan Gohman572645c2010-02-12 10:34:29 +00001310 UseMapTy UseMap;
1311
Dan Gohmanea507f52010-05-20 19:44:23 +00001312 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Dan Gohman572645c2010-02-12 10:34:29 +00001313 LSRUse::KindType Kind, const Type *AccessTy);
1314
1315 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1316 LSRUse::KindType Kind,
1317 const Type *AccessTy);
1318
Dan Gohman5ce6d052010-05-20 15:17:54 +00001319 void DeleteUse(LSRUse &LU);
1320
Dan Gohmana2086b32010-05-19 23:43:12 +00001321 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1322
Dan Gohman572645c2010-02-12 10:34:29 +00001323public:
Dan Gohman454d26d2010-02-22 04:11:59 +00001324 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001325 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1326 void CountRegisters(const Formula &F, size_t LUIdx);
1327 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1328
1329 void CollectLoopInvariantFixupsAndFormulae();
1330
1331 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1332 unsigned Depth = 0);
1333 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1334 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1335 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1336 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1337 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1338 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1339 void GenerateCrossUseConstantOffsets();
1340 void GenerateAllReuseFormulae();
1341
1342 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmand079c302010-05-18 22:51:59 +00001343
1344 size_t EstimateSearchSpaceComplexity() const;
Dan Gohman572645c2010-02-12 10:34:29 +00001345 void NarrowSearchSpaceUsingHeuristics();
1346
1347 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1348 Cost &SolutionCost,
1349 SmallVectorImpl<const Formula *> &Workspace,
1350 const Cost &CurCost,
1351 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1352 DenseSet<const SCEV *> &VisitedRegs) const;
1353 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1354
Dan Gohmane5f76872010-04-09 22:07:05 +00001355 BasicBlock::iterator
1356 HoistInsertPosition(BasicBlock::iterator IP,
1357 const SmallVectorImpl<Instruction *> &Inputs) const;
1358 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1359 const LSRFixup &LF,
1360 const LSRUse &LU) const;
Dan Gohmand96eae82010-04-09 02:00:38 +00001361
Dan Gohman572645c2010-02-12 10:34:29 +00001362 Value *Expand(const LSRFixup &LF,
1363 const Formula &F,
Dan Gohman454d26d2010-02-22 04:11:59 +00001364 BasicBlock::iterator IP,
Dan Gohman572645c2010-02-12 10:34:29 +00001365 SCEVExpander &Rewriter,
Dan Gohman454d26d2010-02-22 04:11:59 +00001366 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001367 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1368 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001369 SCEVExpander &Rewriter,
1370 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001371 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001372 void Rewrite(const LSRFixup &LF,
1373 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00001374 SCEVExpander &Rewriter,
1375 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00001376 Pass *P) const;
1377 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1378 Pass *P);
1379
1380 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1381
1382 bool getChanged() const { return Changed; }
1383
1384 void print_factors_and_types(raw_ostream &OS) const;
1385 void print_fixups(raw_ostream &OS) const;
1386 void print_uses(raw_ostream &OS) const;
1387 void print(raw_ostream &OS) const;
1388 void dump() const;
1389};
1390
1391}
1392
1393/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001394/// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00001395void LSRInstance::OptimizeShadowIV() {
1396 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1397 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1398 return;
1399
1400 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1401 UI != E; /* empty */) {
1402 IVUsers::const_iterator CandidateUI = UI;
1403 ++UI;
1404 Instruction *ShadowUse = CandidateUI->getUser();
1405 const Type *DestTy = NULL;
1406
1407 /* If shadow use is a int->float cast then insert a second IV
1408 to eliminate this cast.
1409
1410 for (unsigned i = 0; i < n; ++i)
1411 foo((double)i);
1412
1413 is transformed into
1414
1415 double d = 0.0;
1416 for (unsigned i = 0; i < n; ++i, ++d)
1417 foo(d);
1418 */
1419 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1420 DestTy = UCast->getDestTy();
1421 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1422 DestTy = SCast->getDestTy();
1423 if (!DestTy) continue;
1424
1425 if (TLI) {
1426 // If target does not support DestTy natively then do not apply
1427 // this transformation.
1428 EVT DVT = TLI->getValueType(DestTy);
1429 if (!TLI->isTypeLegal(DVT)) continue;
1430 }
1431
1432 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1433 if (!PH) continue;
1434 if (PH->getNumIncomingValues() != 2) continue;
1435
1436 const Type *SrcTy = PH->getType();
1437 int Mantissa = DestTy->getFPMantissaWidth();
1438 if (Mantissa == -1) continue;
1439 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1440 continue;
1441
1442 unsigned Entry, Latch;
1443 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1444 Entry = 0;
1445 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001446 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001447 Entry = 1;
1448 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001449 }
Dan Gohman7979b722010-01-22 00:46:49 +00001450
Dan Gohman572645c2010-02-12 10:34:29 +00001451 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1452 if (!Init) continue;
1453 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001454
Dan Gohman572645c2010-02-12 10:34:29 +00001455 BinaryOperator *Incr =
1456 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1457 if (!Incr) continue;
1458 if (Incr->getOpcode() != Instruction::Add
1459 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001460 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001461
Dan Gohman572645c2010-02-12 10:34:29 +00001462 /* Initialize new IV, double d = 0.0 in above example. */
1463 ConstantInt *C = NULL;
1464 if (Incr->getOperand(0) == PH)
1465 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1466 else if (Incr->getOperand(1) == PH)
1467 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001468 else
Dan Gohman7979b722010-01-22 00:46:49 +00001469 continue;
1470
Dan Gohman572645c2010-02-12 10:34:29 +00001471 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001472
Dan Gohman572645c2010-02-12 10:34:29 +00001473 // Ignore negative constants, as the code below doesn't handle them
1474 // correctly. TODO: Remove this restriction.
1475 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001476
Dan Gohman572645c2010-02-12 10:34:29 +00001477 /* Add new PHINode. */
1478 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001479
Dan Gohman572645c2010-02-12 10:34:29 +00001480 /* create new increment. '++d' in above example. */
1481 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1482 BinaryOperator *NewIncr =
1483 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1484 Instruction::FAdd : Instruction::FSub,
1485 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001486
Dan Gohman572645c2010-02-12 10:34:29 +00001487 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1488 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001489
Dan Gohman572645c2010-02-12 10:34:29 +00001490 /* Remove cast operation */
1491 ShadowUse->replaceAllUsesWith(NewPH);
1492 ShadowUse->eraseFromParent();
Dan Gohmanc6519f92010-05-20 20:05:31 +00001493 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00001494 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001495 }
1496}
1497
1498/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1499/// set the IV user and stride information and return true, otherwise return
1500/// false.
Dan Gohmanea507f52010-05-20 19:44:23 +00001501bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Dan Gohman572645c2010-02-12 10:34:29 +00001502 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1503 if (UI->getUser() == Cond) {
1504 // NOTE: we could handle setcc instructions with multiple uses here, but
1505 // InstCombine does it as well for simple uses, it's not clear that it
1506 // occurs enough in real life to handle.
1507 CondUse = UI;
1508 return true;
1509 }
Dan Gohman7979b722010-01-22 00:46:49 +00001510 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001511}
1512
Dan Gohman7979b722010-01-22 00:46:49 +00001513/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1514/// a max computation.
1515///
1516/// This is a narrow solution to a specific, but acute, problem. For loops
1517/// like this:
1518///
1519/// i = 0;
1520/// do {
1521/// p[i] = 0.0;
1522/// } while (++i < n);
1523///
1524/// the trip count isn't just 'n', because 'n' might not be positive. And
1525/// unfortunately this can come up even for loops where the user didn't use
1526/// a C do-while loop. For example, seemingly well-behaved top-test loops
1527/// will commonly be lowered like this:
1528//
1529/// if (n > 0) {
1530/// i = 0;
1531/// do {
1532/// p[i] = 0.0;
1533/// } while (++i < n);
1534/// }
1535///
1536/// and then it's possible for subsequent optimization to obscure the if
1537/// test in such a way that indvars can't find it.
1538///
1539/// When indvars can't find the if test in loops like this, it creates a
1540/// max expression, which allows it to give the loop a canonical
1541/// induction variable:
1542///
1543/// i = 0;
1544/// max = n < 1 ? 1 : n;
1545/// do {
1546/// p[i] = 0.0;
1547/// } while (++i != max);
1548///
1549/// Canonical induction variables are necessary because the loop passes
1550/// are designed around them. The most obvious example of this is the
1551/// LoopInfo analysis, which doesn't remember trip count values. It
1552/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001553/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001554/// the loop has a canonical induction variable.
1555///
1556/// However, when it comes time to generate code, the maximum operation
1557/// can be quite costly, especially if it's inside of an outer loop.
1558///
1559/// This function solves this problem by detecting this type of loop and
1560/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1561/// the instructions for the maximum computation.
1562///
Dan Gohman572645c2010-02-12 10:34:29 +00001563ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001564 // Check that the loop matches the pattern we're looking for.
1565 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1566 Cond->getPredicate() != CmpInst::ICMP_NE)
1567 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001568
Dan Gohman7979b722010-01-22 00:46:49 +00001569 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1570 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001571
Dan Gohman572645c2010-02-12 10:34:29 +00001572 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001573 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1574 return Cond;
Dan Gohmandeff6212010-05-03 22:09:21 +00001575 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001576
Dan Gohman7979b722010-01-22 00:46:49 +00001577 // Add one to the backedge-taken count to get the trip count.
Dan Gohman572645c2010-02-12 10:34:29 +00001578 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
Dan Gohman1d367982010-04-24 03:13:44 +00001579 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001580
Dan Gohman1d367982010-04-24 03:13:44 +00001581 // Check for a max calculation that matches the pattern. There's no check
1582 // for ICMP_ULE here because the comparison would be with zero, which
1583 // isn't interesting.
1584 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1585 const SCEVNAryExpr *Max = 0;
1586 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1587 Pred = ICmpInst::ICMP_SLE;
1588 Max = S;
1589 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1590 Pred = ICmpInst::ICMP_SLT;
1591 Max = S;
1592 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1593 Pred = ICmpInst::ICMP_ULT;
1594 Max = U;
1595 } else {
1596 // No match; bail.
Dan Gohman7979b722010-01-22 00:46:49 +00001597 return Cond;
Dan Gohman1d367982010-04-24 03:13:44 +00001598 }
Dan Gohman7979b722010-01-22 00:46:49 +00001599
1600 // To handle a max with more than two operands, this optimization would
1601 // require additional checking and setup.
1602 if (Max->getNumOperands() != 2)
1603 return Cond;
1604
1605 const SCEV *MaxLHS = Max->getOperand(0);
1606 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman1d367982010-04-24 03:13:44 +00001607
1608 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1609 // for a comparison with 1. For <= and >=, a comparison with zero.
1610 if (!MaxLHS ||
1611 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1612 return Cond;
1613
Dan Gohman7979b722010-01-22 00:46:49 +00001614 // Check the relevant induction variable for conformance to
1615 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001616 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001617 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1618 if (!AR || !AR->isAffine() ||
1619 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001620 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001621 return Cond;
1622
1623 assert(AR->getLoop() == L &&
1624 "Loop condition operand is an addrec in a different loop!");
1625
1626 // Check the right operand of the select, and remember it, as it will
1627 // be used in the new comparison instruction.
1628 Value *NewRHS = 0;
Dan Gohman1d367982010-04-24 03:13:44 +00001629 if (ICmpInst::isTrueWhenEqual(Pred)) {
1630 // Look for n+1, and grab n.
1631 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1632 if (isa<ConstantInt>(BO->getOperand(1)) &&
1633 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1634 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1635 NewRHS = BO->getOperand(0);
1636 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1637 if (isa<ConstantInt>(BO->getOperand(1)) &&
1638 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1639 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1640 NewRHS = BO->getOperand(0);
1641 if (!NewRHS)
1642 return Cond;
1643 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001644 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001645 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001646 NewRHS = Sel->getOperand(2);
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001647 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
1648 NewRHS = SU->getValue();
Dan Gohman1d367982010-04-24 03:13:44 +00001649 else
Dan Gohmancaf71ab2010-06-22 23:07:13 +00001650 // Max doesn't match expected pattern.
1651 return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001652
1653 // Determine the new comparison opcode. It may be signed or unsigned,
1654 // and the original comparison may be either equality or inequality.
Dan Gohman7979b722010-01-22 00:46:49 +00001655 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1656 Pred = CmpInst::getInversePredicate(Pred);
1657
1658 // Ok, everything looks ok to change the condition into an SLT or SGE and
1659 // delete the max calculation.
1660 ICmpInst *NewCond =
1661 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1662
1663 // Delete the max calculation instructions.
1664 Cond->replaceAllUsesWith(NewCond);
1665 CondUse->setUser(NewCond);
1666 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1667 Cond->eraseFromParent();
1668 Sel->eraseFromParent();
1669 if (Cmp->use_empty())
1670 Cmp->eraseFromParent();
1671 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001672}
1673
Jim Grosbach56a1f802009-11-17 17:53:56 +00001674/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001675/// postinc iv when possible.
Dan Gohmanc6519f92010-05-20 20:05:31 +00001676void
Dan Gohman572645c2010-02-12 10:34:29 +00001677LSRInstance::OptimizeLoopTermCond() {
1678 SmallPtrSet<Instruction *, 4> PostIncs;
1679
Evan Cheng586f69a2009-11-12 07:35:05 +00001680 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001681 SmallVector<BasicBlock*, 8> ExitingBlocks;
1682 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001683
Evan Cheng076e0852009-11-17 18:10:11 +00001684 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1685 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001686
Dan Gohman572645c2010-02-12 10:34:29 +00001687 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001688 // can, we want to change it to use a post-incremented version of its
1689 // induction variable, to allow coalescing the live ranges for the IV into
1690 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001691
Evan Cheng076e0852009-11-17 18:10:11 +00001692 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1693 if (!TermBr)
1694 continue;
1695 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1696 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1697 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001698
Evan Cheng076e0852009-11-17 18:10:11 +00001699 // Search IVUsesByStride to find Cond's IVUse if there is one.
1700 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001701 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001702 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001703 continue;
1704
Evan Cheng076e0852009-11-17 18:10:11 +00001705 // If the trip count is computed in terms of a max (due to ScalarEvolution
1706 // being unable to find a sufficient guard, for example), change the loop
1707 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001708 // One consequence of doing this now is that it disrupts the count-down
1709 // optimization. That's not always a bad thing though, because in such
1710 // cases it may still be worthwhile to avoid a max.
1711 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001712
Dan Gohman572645c2010-02-12 10:34:29 +00001713 // If this exiting block dominates the latch block, it may also use
1714 // the post-inc value if it won't be shared with other uses.
1715 // Check for dominance.
1716 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001717 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001718
Dan Gohman572645c2010-02-12 10:34:29 +00001719 // Conservatively avoid trying to use the post-inc value in non-latch
1720 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001721 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001722 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1723 // Test if the use is reachable from the exiting block. This dominator
1724 // query is a conservative approximation of reachability.
1725 if (&*UI != CondUse &&
1726 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1727 // Conservatively assume there may be reuse if the quotient of their
1728 // strides could be a legal scale.
Dan Gohmanc0564542010-04-19 21:48:58 +00001729 const SCEV *A = IU.getStride(*CondUse, L);
1730 const SCEV *B = IU.getStride(*UI, L);
Dan Gohman448db1c2010-04-07 22:27:08 +00001731 if (!A || !B) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001732 if (SE.getTypeSizeInBits(A->getType()) !=
1733 SE.getTypeSizeInBits(B->getType())) {
1734 if (SE.getTypeSizeInBits(A->getType()) >
1735 SE.getTypeSizeInBits(B->getType()))
1736 B = SE.getSignExtendExpr(B, A->getType());
1737 else
1738 A = SE.getSignExtendExpr(A, B->getType());
1739 }
1740 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001741 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00001742 const ConstantInt *C = D->getValue();
Dan Gohman572645c2010-02-12 10:34:29 +00001743 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001744 if (C->isOne() || C->isAllOnesValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001745 goto decline_post_inc;
1746 // Avoid weird situations.
Dan Gohman9f383eb2010-05-20 22:25:20 +00001747 if (C->getValue().getMinSignedBits() >= 64 ||
1748 C->getValue().isMinSignedValue())
Dan Gohman572645c2010-02-12 10:34:29 +00001749 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001750 // Without TLI, assume that any stride might be valid, and so any
1751 // use might be shared.
1752 if (!TLI)
1753 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001754 // Check for possible scaled-address reuse.
1755 const Type *AccessTy = getAccessType(UI->getUser());
1756 TargetLowering::AddrMode AM;
Dan Gohman9f383eb2010-05-20 22:25:20 +00001757 AM.Scale = C->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001758 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001759 goto decline_post_inc;
1760 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001761 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001762 goto decline_post_inc;
1763 }
1764 }
1765
David Greene63c94632009-12-23 22:58:38 +00001766 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001767 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001768
1769 // It's possible for the setcc instruction to be anywhere in the loop, and
1770 // possible for it to have multiple users. If it is not immediately before
1771 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001772 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1773 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001774 Cond->moveBefore(TermBr);
1775 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001776 // Clone the terminating condition and insert into the loopend.
1777 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001778 Cond = cast<ICmpInst>(Cond->clone());
1779 Cond->setName(L->getHeader()->getName() + ".termcond");
1780 ExitingBlock->getInstList().insert(TermBr, Cond);
1781
1782 // Clone the IVUse, as the old use still exists!
Dan Gohmanc0564542010-04-19 21:48:58 +00001783 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman572645c2010-02-12 10:34:29 +00001784 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001785 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001786 }
1787
Evan Cheng076e0852009-11-17 18:10:11 +00001788 // If we get to here, we know that we can transform the setcc instruction to
1789 // use the post-incremented version of the IV, allowing us to coalesce the
1790 // live ranges for the IV correctly.
Dan Gohman448db1c2010-04-07 22:27:08 +00001791 CondUse->transformToPostInc(L);
Evan Cheng076e0852009-11-17 18:10:11 +00001792 Changed = true;
1793
Dan Gohman572645c2010-02-12 10:34:29 +00001794 PostIncs.insert(Cond);
1795 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001796 }
Dan Gohman572645c2010-02-12 10:34:29 +00001797
1798 // Determine an insertion point for the loop induction variable increment. It
1799 // must dominate all the post-inc comparisons we just set up, and it must
1800 // dominate the loop latch edge.
1801 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1802 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1803 E = PostIncs.end(); I != E; ++I) {
1804 BasicBlock *BB =
1805 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1806 (*I)->getParent());
1807 if (BB == (*I)->getParent())
1808 IVIncInsertPos = *I;
1809 else if (BB != IVIncInsertPos->getParent())
1810 IVIncInsertPos = BB->getTerminator();
1811 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001812}
1813
Dan Gohman76c315a2010-05-20 20:52:00 +00001814/// reconcileNewOffset - Determine if the given use can accomodate a fixup
1815/// at the given offset and other details. If so, update the use and
1816/// return true.
Dan Gohman572645c2010-02-12 10:34:29 +00001817bool
Dan Gohmanea507f52010-05-20 19:44:23 +00001818LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Dan Gohman572645c2010-02-12 10:34:29 +00001819 LSRUse::KindType Kind, const Type *AccessTy) {
1820 int64_t NewMinOffset = LU.MinOffset;
1821 int64_t NewMaxOffset = LU.MaxOffset;
1822 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001823
Dan Gohman572645c2010-02-12 10:34:29 +00001824 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1825 // something conservative, however this can pessimize in the case that one of
1826 // the uses will have all its uses outside the loop, for example.
1827 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001828 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001829 // Conservatively assume HasBaseReg is true for now.
1830 if (NewOffset < LU.MinOffset) {
Dan Gohmana2086b32010-05-19 23:43:12 +00001831 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001832 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001833 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001834 NewMinOffset = NewOffset;
1835 } else if (NewOffset > LU.MaxOffset) {
Dan Gohmana2086b32010-05-19 23:43:12 +00001836 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001837 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001838 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001839 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001840 }
Dan Gohman572645c2010-02-12 10:34:29 +00001841 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman74e5ef02010-06-19 21:30:18 +00001842 // TODO: Be less conservative when the type is similar and can use the same
1843 // addressing modes.
Dan Gohman572645c2010-02-12 10:34:29 +00001844 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1845 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001846
Dan Gohman572645c2010-02-12 10:34:29 +00001847 // Update the use.
1848 LU.MinOffset = NewMinOffset;
1849 LU.MaxOffset = NewMaxOffset;
1850 LU.AccessTy = NewAccessTy;
1851 if (NewOffset != LU.Offsets.back())
1852 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001853 return true;
1854}
1855
Dan Gohman572645c2010-02-12 10:34:29 +00001856/// getUse - Return an LSRUse index and an offset value for a fixup which
1857/// needs the given expression, with the given kind and optional access type.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001858/// Either reuse an existing use or create a new one, as needed.
Dan Gohman572645c2010-02-12 10:34:29 +00001859std::pair<size_t, int64_t>
1860LSRInstance::getUse(const SCEV *&Expr,
1861 LSRUse::KindType Kind, const Type *AccessTy) {
1862 const SCEV *Copy = Expr;
1863 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001864
Dan Gohman572645c2010-02-12 10:34:29 +00001865 // Basic uses can't accept any offset, for example.
Dan Gohman454d26d2010-02-22 04:11:59 +00001866 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
Dan Gohman572645c2010-02-12 10:34:29 +00001867 Expr = Copy;
1868 Offset = 0;
1869 }
1870
1871 std::pair<UseMapTy::iterator, bool> P =
Dan Gohman1e3121c2010-06-19 21:29:59 +00001872 UseMap.insert(std::make_pair(std::make_pair(Expr, Kind), 0));
Dan Gohman572645c2010-02-12 10:34:29 +00001873 if (!P.second) {
1874 // A use already existed with this base.
1875 size_t LUIdx = P.first->second;
1876 LSRUse &LU = Uses[LUIdx];
Dan Gohmana2086b32010-05-19 23:43:12 +00001877 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001878 // Reuse this use.
1879 return std::make_pair(LUIdx, Offset);
1880 }
1881
1882 // Create a new use.
1883 size_t LUIdx = Uses.size();
1884 P.first->second = LUIdx;
1885 Uses.push_back(LSRUse(Kind, AccessTy));
1886 LSRUse &LU = Uses[LUIdx];
1887
1888 // We don't need to track redundant offsets, but we don't need to go out
1889 // of our way here to avoid them.
1890 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1891 LU.Offsets.push_back(Offset);
1892
1893 LU.MinOffset = Offset;
1894 LU.MaxOffset = Offset;
1895 return std::make_pair(LUIdx, Offset);
1896}
1897
Dan Gohman5ce6d052010-05-20 15:17:54 +00001898/// DeleteUse - Delete the given use from the Uses list.
1899void LSRInstance::DeleteUse(LSRUse &LU) {
1900 if (&LU != &Uses.back())
1901 std::swap(LU, Uses.back());
1902 Uses.pop_back();
1903}
1904
Dan Gohmana2086b32010-05-19 23:43:12 +00001905/// FindUseWithFormula - Look for a use distinct from OrigLU which is has
1906/// a formula that has the same registers as the given formula.
1907LSRUse *
1908LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
1909 const LSRUse &OrigLU) {
1910 // Search all uses for the formula. This could be more clever. Ignore
1911 // ICmpZero uses because they may contain formulae generated by
1912 // GenerateICmpZeroScales, in which case adding fixup offsets may
1913 // be invalid.
1914 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
1915 LSRUse &LU = Uses[LUIdx];
1916 if (&LU != &OrigLU &&
1917 LU.Kind != LSRUse::ICmpZero &&
1918 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
1919 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohman402d4352010-05-20 20:33:18 +00001920 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
1921 E = LU.Formulae.end(); I != E; ++I) {
1922 const Formula &F = *I;
Dan Gohmana2086b32010-05-19 23:43:12 +00001923 if (F.BaseRegs == OrigF.BaseRegs &&
1924 F.ScaledReg == OrigF.ScaledReg &&
1925 F.AM.BaseGV == OrigF.AM.BaseGV &&
1926 F.AM.Scale == OrigF.AM.Scale &&
1927 LU.Kind) {
1928 if (F.AM.BaseOffs == 0)
1929 return &LU;
1930 break;
1931 }
1932 }
1933 }
1934 }
1935
1936 return 0;
1937}
1938
Dan Gohman572645c2010-02-12 10:34:29 +00001939void LSRInstance::CollectInterestingTypesAndFactors() {
1940 SmallSetVector<const SCEV *, 4> Strides;
1941
Dan Gohman1b7bf182010-02-19 00:05:23 +00001942 // Collect interesting types and strides.
Dan Gohman448db1c2010-04-07 22:27:08 +00001943 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00001944 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohmanc0564542010-04-19 21:48:58 +00001945 const SCEV *Expr = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00001946
1947 // Collect interesting types.
Dan Gohman448db1c2010-04-07 22:27:08 +00001948 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman572645c2010-02-12 10:34:29 +00001949
Dan Gohman448db1c2010-04-07 22:27:08 +00001950 // Add strides for mentioned loops.
1951 Worklist.push_back(Expr);
1952 do {
1953 const SCEV *S = Worklist.pop_back_val();
1954 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1955 Strides.insert(AR->getStepRecurrence(SE));
1956 Worklist.push_back(AR->getStart());
1957 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohman403a8cd2010-06-21 19:47:52 +00001958 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohman448db1c2010-04-07 22:27:08 +00001959 }
1960 } while (!Worklist.empty());
Dan Gohman1b7bf182010-02-19 00:05:23 +00001961 }
1962
1963 // Compute interesting factors from the set of interesting strides.
1964 for (SmallSetVector<const SCEV *, 4>::const_iterator
1965 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00001966 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Dan Gohman1b7bf182010-02-19 00:05:23 +00001967 next(I); NewStrideIter != E; ++NewStrideIter) {
1968 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00001969 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00001970
1971 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1972 SE.getTypeSizeInBits(NewStride->getType())) {
1973 if (SE.getTypeSizeInBits(OldStride->getType()) >
1974 SE.getTypeSizeInBits(NewStride->getType()))
1975 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1976 else
1977 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1978 }
1979 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001980 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1981 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001982 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1983 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1984 } else if (const SCEVConstant *Factor =
Dan Gohman454d26d2010-02-22 04:11:59 +00001985 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
1986 NewStride,
Dan Gohmanf09b7122010-02-19 19:35:48 +00001987 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001988 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1989 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1990 }
1991 }
Dan Gohman572645c2010-02-12 10:34:29 +00001992
1993 // If all uses use the same type, don't bother looking for truncation-based
1994 // reuse.
1995 if (Types.size() == 1)
1996 Types.clear();
1997
1998 DEBUG(print_factors_and_types(dbgs()));
1999}
2000
2001void LSRInstance::CollectFixupsAndInitialFormulae() {
2002 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2003 // Record the uses.
2004 LSRFixup &LF = getNewFixup();
2005 LF.UserInst = UI->getUser();
2006 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohman448db1c2010-04-07 22:27:08 +00002007 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman572645c2010-02-12 10:34:29 +00002008
2009 LSRUse::KindType Kind = LSRUse::Basic;
2010 const Type *AccessTy = 0;
2011 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2012 Kind = LSRUse::Address;
2013 AccessTy = getAccessType(LF.UserInst);
2014 }
2015
Dan Gohmanc0564542010-04-19 21:48:58 +00002016 const SCEV *S = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00002017
2018 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2019 // (N - i == 0), and this allows (N - i) to be the expression that we work
2020 // with rather than just N or i, so we can consider the register
2021 // requirements for both N and i at the same time. Limiting this code to
2022 // equality icmps is not a problem because all interesting loops use
2023 // equality icmps, thanks to IndVarSimplify.
2024 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2025 if (CI->isEquality()) {
2026 // Swap the operands if needed to put the OperandValToReplace on the
2027 // left, for consistency.
2028 Value *NV = CI->getOperand(1);
2029 if (NV == LF.OperandValToReplace) {
2030 CI->setOperand(1, CI->getOperand(0));
2031 CI->setOperand(0, NV);
Dan Gohmanf182b232010-05-20 19:26:52 +00002032 NV = CI->getOperand(1);
Dan Gohman9da1bf42010-05-20 19:16:03 +00002033 Changed = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002034 }
2035
2036 // x == y --> x - y == 0
2037 const SCEV *N = SE.getSCEV(NV);
2038 if (N->isLoopInvariant(L)) {
2039 Kind = LSRUse::ICmpZero;
2040 S = SE.getMinusSCEV(N, S);
2041 }
2042
2043 // -1 and the negations of all interesting strides (except the negation
2044 // of -1) are now also interesting.
2045 for (size_t i = 0, e = Factors.size(); i != e; ++i)
2046 if (Factors[i] != -1)
2047 Factors.insert(-(uint64_t)Factors[i]);
2048 Factors.insert(-1);
2049 }
2050
2051 // Set up the initial formula for this use.
2052 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
2053 LF.LUIdx = P.first;
2054 LF.Offset = P.second;
2055 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002056 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00002057
2058 // If this is the first use of this LSRUse, give it a formula.
2059 if (LU.Formulae.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002060 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00002061 CountRegisters(LU.Formulae.back(), LF.LUIdx);
2062 }
2063 }
2064
2065 DEBUG(print_fixups(dbgs()));
2066}
2067
Dan Gohman76c315a2010-05-20 20:52:00 +00002068/// InsertInitialFormula - Insert a formula for the given expression into
2069/// the given use, separating out loop-variant portions from loop-invariant
2070/// and loop-computable portions.
Dan Gohman572645c2010-02-12 10:34:29 +00002071void
Dan Gohman454d26d2010-02-22 04:11:59 +00002072LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Dan Gohman572645c2010-02-12 10:34:29 +00002073 Formula F;
2074 F.InitialMatch(S, L, SE, DT);
2075 bool Inserted = InsertFormula(LU, LUIdx, F);
2076 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
2077}
2078
Dan Gohman76c315a2010-05-20 20:52:00 +00002079/// InsertSupplementalFormula - Insert a simple single-register formula for
2080/// the given expression into the given use.
Dan Gohman572645c2010-02-12 10:34:29 +00002081void
2082LSRInstance::InsertSupplementalFormula(const SCEV *S,
2083 LSRUse &LU, size_t LUIdx) {
2084 Formula F;
2085 F.BaseRegs.push_back(S);
2086 F.AM.HasBaseReg = true;
2087 bool Inserted = InsertFormula(LU, LUIdx, F);
2088 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
2089}
2090
2091/// CountRegisters - Note which registers are used by the given formula,
2092/// updating RegUses.
2093void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
2094 if (F.ScaledReg)
2095 RegUses.CountRegister(F.ScaledReg, LUIdx);
2096 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2097 E = F.BaseRegs.end(); I != E; ++I)
2098 RegUses.CountRegister(*I, LUIdx);
2099}
2100
2101/// InsertFormula - If the given formula has not yet been inserted, add it to
2102/// the list, and return true. Return false otherwise.
2103bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002104 if (!LU.InsertFormula(F))
Dan Gohman572645c2010-02-12 10:34:29 +00002105 return false;
2106
2107 CountRegisters(F, LUIdx);
2108 return true;
2109}
2110
2111/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
2112/// loop-invariant values which we're tracking. These other uses will pin these
2113/// values in registers, making them less profitable for elimination.
2114/// TODO: This currently misses non-constant addrec step registers.
2115/// TODO: Should this give more weight to users inside the loop?
2116void
2117LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
2118 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
2119 SmallPtrSet<const SCEV *, 8> Inserted;
2120
2121 while (!Worklist.empty()) {
2122 const SCEV *S = Worklist.pop_back_val();
2123
2124 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohman403a8cd2010-06-21 19:47:52 +00002125 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman572645c2010-02-12 10:34:29 +00002126 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2127 Worklist.push_back(C->getOperand());
2128 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2129 Worklist.push_back(D->getLHS());
2130 Worklist.push_back(D->getRHS());
2131 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2132 if (!Inserted.insert(U)) continue;
2133 const Value *V = U->getValue();
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002134 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2135 // Look for instructions defined outside the loop.
Dan Gohman572645c2010-02-12 10:34:29 +00002136 if (L->contains(Inst)) continue;
Dan Gohmana15ec5d2010-06-04 23:16:05 +00002137 } else if (isa<UndefValue>(V))
2138 // Undef doesn't have a live range, so it doesn't matter.
2139 continue;
Gabor Greif60ad7812010-03-25 23:06:16 +00002140 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
Dan Gohman572645c2010-02-12 10:34:29 +00002141 UI != UE; ++UI) {
2142 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2143 // Ignore non-instructions.
2144 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00002145 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002146 // Ignore instructions in other functions (as can happen with
2147 // Constants).
2148 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00002149 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002150 // Ignore instructions not dominated by the loop.
2151 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2152 UserInst->getParent() :
2153 cast<PHINode>(UserInst)->getIncomingBlock(
2154 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2155 if (!DT.dominates(L->getHeader(), UseBB))
2156 continue;
2157 // Ignore uses which are part of other SCEV expressions, to avoid
2158 // analyzing them multiple times.
Dan Gohman4a2a6832010-04-09 19:12:34 +00002159 if (SE.isSCEVable(UserInst->getType())) {
2160 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2161 // If the user is a no-op, look through to its uses.
2162 if (!isa<SCEVUnknown>(UserS))
2163 continue;
2164 if (UserS == U) {
2165 Worklist.push_back(
2166 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2167 continue;
2168 }
2169 }
Dan Gohman572645c2010-02-12 10:34:29 +00002170 // Ignore icmp instructions which are already being analyzed.
2171 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2172 unsigned OtherIdx = !UI.getOperandNo();
2173 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
2174 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
2175 continue;
2176 }
2177
2178 LSRFixup &LF = getNewFixup();
2179 LF.UserInst = const_cast<Instruction *>(UserInst);
2180 LF.OperandValToReplace = UI.getUse();
2181 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2182 LF.LUIdx = P.first;
2183 LF.Offset = P.second;
2184 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002185 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00002186 InsertSupplementalFormula(U, LU, LF.LUIdx);
2187 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2188 break;
2189 }
2190 }
2191 }
2192}
2193
2194/// CollectSubexprs - Split S into subexpressions which can be pulled out into
2195/// separate registers. If C is non-null, multiply each subexpression by C.
2196static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2197 SmallVectorImpl<const SCEV *> &Ops,
2198 ScalarEvolution &SE) {
2199 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2200 // Break out add operands.
2201 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2202 I != E; ++I)
2203 CollectSubexprs(*I, C, Ops, SE);
2204 return;
2205 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2206 // Split a non-zero base out of an addrec.
2207 if (!AR->getStart()->isZero()) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002208 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +00002209 AR->getStepRecurrence(SE),
2210 AR->getLoop()), C, Ops, SE);
Dan Gohman68d6da12010-02-12 19:35:25 +00002211 CollectSubexprs(AR->getStart(), C, Ops, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002212 return;
2213 }
2214 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2215 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2216 if (Mul->getNumOperands() == 2)
2217 if (const SCEVConstant *Op0 =
2218 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2219 CollectSubexprs(Mul->getOperand(1),
2220 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2221 Ops, SE);
2222 return;
2223 }
2224 }
2225
2226 // Otherwise use the value itself.
2227 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2228}
2229
2230/// GenerateReassociations - Split out subexpressions from adds and the bases of
2231/// addrecs.
2232void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2233 Formula Base,
2234 unsigned Depth) {
2235 // Arbitrarily cap recursion to protect compile time.
2236 if (Depth >= 3) return;
2237
2238 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2239 const SCEV *BaseReg = Base.BaseRegs[i];
2240
2241 SmallVector<const SCEV *, 8> AddOps;
2242 CollectSubexprs(BaseReg, 0, AddOps, SE);
2243 if (AddOps.size() == 1) continue;
2244
2245 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2246 JE = AddOps.end(); J != JE; ++J) {
2247 // Don't pull a constant into a register if the constant could be folded
2248 // into an immediate field.
2249 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2250 Base.getNumRegs() > 1,
2251 LU.Kind, LU.AccessTy, TLI, SE))
2252 continue;
2253
2254 // Collect all operands except *J.
Dan Gohman403a8cd2010-06-21 19:47:52 +00002255 SmallVector<const SCEV *, 8> InnerAddOps
2256 ( ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
2257 InnerAddOps.append
2258 (next(J), ((const SmallVector<const SCEV *, 8> &)AddOps).end());
Dan Gohman572645c2010-02-12 10:34:29 +00002259
2260 // Don't leave just a constant behind in a register if the constant could
2261 // be folded into an immediate field.
2262 if (InnerAddOps.size() == 1 &&
2263 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2264 Base.getNumRegs() > 1,
2265 LU.Kind, LU.AccessTy, TLI, SE))
2266 continue;
2267
Dan Gohmanfafb8902010-04-23 01:55:05 +00002268 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2269 if (InnerSum->isZero())
2270 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002271 Formula F = Base;
Dan Gohmanfafb8902010-04-23 01:55:05 +00002272 F.BaseRegs[i] = InnerSum;
Dan Gohman572645c2010-02-12 10:34:29 +00002273 F.BaseRegs.push_back(*J);
2274 if (InsertFormula(LU, LUIdx, F))
2275 // If that formula hadn't been seen before, recurse to find more like
2276 // it.
2277 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2278 }
2279 }
2280}
2281
2282/// GenerateCombinations - Generate a formula consisting of all of the
2283/// loop-dominating registers added into a single register.
2284void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002285 Formula Base) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002286 // This method is only interesting on a plurality of registers.
Dan Gohman572645c2010-02-12 10:34:29 +00002287 if (Base.BaseRegs.size() <= 1) return;
2288
2289 Formula F = Base;
2290 F.BaseRegs.clear();
2291 SmallVector<const SCEV *, 4> Ops;
2292 for (SmallVectorImpl<const SCEV *>::const_iterator
2293 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2294 const SCEV *BaseReg = *I;
2295 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2296 !BaseReg->hasComputableLoopEvolution(L))
2297 Ops.push_back(BaseReg);
2298 else
2299 F.BaseRegs.push_back(BaseReg);
2300 }
2301 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002302 const SCEV *Sum = SE.getAddExpr(Ops);
2303 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2304 // opportunity to fold something. For now, just ignore such cases
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002305 // rather than proceed with zero in a register.
Dan Gohmance947362010-02-14 18:50:49 +00002306 if (!Sum->isZero()) {
2307 F.BaseRegs.push_back(Sum);
2308 (void)InsertFormula(LU, LUIdx, F);
2309 }
Dan Gohman572645c2010-02-12 10:34:29 +00002310 }
2311}
2312
2313/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2314void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2315 Formula Base) {
2316 // We can't add a symbolic offset if the address already contains one.
2317 if (Base.AM.BaseGV) return;
2318
2319 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2320 const SCEV *G = Base.BaseRegs[i];
2321 GlobalValue *GV = ExtractSymbol(G, SE);
2322 if (G->isZero() || !GV)
2323 continue;
2324 Formula F = Base;
2325 F.AM.BaseGV = GV;
2326 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2327 LU.Kind, LU.AccessTy, TLI))
2328 continue;
2329 F.BaseRegs[i] = G;
2330 (void)InsertFormula(LU, LUIdx, F);
2331 }
2332}
2333
2334/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2335void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2336 Formula Base) {
2337 // TODO: For now, just add the min and max offset, because it usually isn't
2338 // worthwhile looking at everything inbetween.
2339 SmallVector<int64_t, 4> Worklist;
2340 Worklist.push_back(LU.MinOffset);
2341 if (LU.MaxOffset != LU.MinOffset)
2342 Worklist.push_back(LU.MaxOffset);
2343
2344 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2345 const SCEV *G = Base.BaseRegs[i];
2346
2347 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2348 E = Worklist.end(); I != E; ++I) {
2349 Formula F = Base;
2350 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2351 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2352 LU.Kind, LU.AccessTy, TLI)) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002353 F.BaseRegs[i] = SE.getAddExpr(G, SE.getConstant(G->getType(), *I));
Dan Gohman572645c2010-02-12 10:34:29 +00002354
2355 (void)InsertFormula(LU, LUIdx, F);
2356 }
2357 }
2358
2359 int64_t Imm = ExtractImmediate(G, SE);
2360 if (G->isZero() || Imm == 0)
2361 continue;
2362 Formula F = Base;
2363 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2364 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2365 LU.Kind, LU.AccessTy, TLI))
2366 continue;
2367 F.BaseRegs[i] = G;
2368 (void)InsertFormula(LU, LUIdx, F);
2369 }
2370}
2371
2372/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2373/// the comparison. For example, x == y -> x*c == y*c.
2374void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2375 Formula Base) {
2376 if (LU.Kind != LSRUse::ICmpZero) return;
2377
2378 // Determine the integer type for the base formula.
2379 const Type *IntTy = Base.getType();
2380 if (!IntTy) return;
2381 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2382
2383 // Don't do this if there is more than one offset.
2384 if (LU.MinOffset != LU.MaxOffset) return;
2385
2386 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2387
2388 // Check each interesting stride.
2389 for (SmallSetVector<int64_t, 8>::const_iterator
2390 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2391 int64_t Factor = *I;
2392 Formula F = Base;
2393
2394 // Check that the multiplication doesn't overflow.
Dan Gohman968cb932010-02-17 00:41:53 +00002395 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2396 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002397 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002398 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002399 continue;
2400
2401 // Check that multiplying with the use offset doesn't overflow.
2402 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002403 if (Offset == INT64_MIN && Factor == -1)
2404 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002405 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002406 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002407 continue;
2408
2409 // Check that this scale is legal.
2410 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2411 continue;
2412
2413 // Compensate for the use having MinOffset built into it.
2414 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2415
Dan Gohmandeff6212010-05-03 22:09:21 +00002416 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002417
2418 // Check that multiplying with each base register doesn't overflow.
2419 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2420 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002421 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002422 goto next;
2423 }
2424
2425 // Check that multiplying with the scaled register doesn't overflow.
2426 if (F.ScaledReg) {
2427 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002428 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002429 continue;
2430 }
2431
2432 // If we make it here and it's legal, add it.
2433 (void)InsertFormula(LU, LUIdx, F);
2434 next:;
2435 }
2436}
2437
2438/// GenerateScales - Generate stride factor reuse formulae by making use of
2439/// scaled-offset address modes, for example.
Dan Gohmanea507f52010-05-20 19:44:23 +00002440void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002441 // Determine the integer type for the base formula.
2442 const Type *IntTy = Base.getType();
2443 if (!IntTy) return;
2444
2445 // If this Formula already has a scaled register, we can't add another one.
2446 if (Base.AM.Scale != 0) return;
2447
2448 // Check each interesting stride.
2449 for (SmallSetVector<int64_t, 8>::const_iterator
2450 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2451 int64_t Factor = *I;
2452
2453 Base.AM.Scale = Factor;
2454 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2455 // Check whether this scale is going to be legal.
2456 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2457 LU.Kind, LU.AccessTy, TLI)) {
2458 // As a special-case, handle special out-of-loop Basic users specially.
2459 // TODO: Reconsider this special case.
2460 if (LU.Kind == LSRUse::Basic &&
2461 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2462 LSRUse::Special, LU.AccessTy, TLI) &&
2463 LU.AllFixupsOutsideLoop)
2464 LU.Kind = LSRUse::Special;
2465 else
2466 continue;
2467 }
2468 // For an ICmpZero, negating a solitary base register won't lead to
2469 // new solutions.
2470 if (LU.Kind == LSRUse::ICmpZero &&
2471 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2472 continue;
2473 // For each addrec base reg, apply the scale, if possible.
2474 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2475 if (const SCEVAddRecExpr *AR =
2476 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002477 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002478 if (FactorS->isZero())
2479 continue;
2480 // Divide out the factor, ignoring high bits, since we'll be
2481 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002482 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002483 // TODO: This could be optimized to avoid all the copying.
2484 Formula F = Base;
2485 F.ScaledReg = Quotient;
Dan Gohman5ce6d052010-05-20 15:17:54 +00002486 F.DeleteBaseReg(F.BaseRegs[i]);
Dan Gohman572645c2010-02-12 10:34:29 +00002487 (void)InsertFormula(LU, LUIdx, F);
2488 }
2489 }
2490 }
2491}
2492
2493/// GenerateTruncates - Generate reuse formulae from different IV types.
Dan Gohmanea507f52010-05-20 19:44:23 +00002494void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman572645c2010-02-12 10:34:29 +00002495 // This requires TargetLowering to tell us which truncates are free.
2496 if (!TLI) return;
2497
2498 // Don't bother truncating symbolic values.
2499 if (Base.AM.BaseGV) return;
2500
2501 // Determine the integer type for the base formula.
2502 const Type *DstTy = Base.getType();
2503 if (!DstTy) return;
2504 DstTy = SE.getEffectiveSCEVType(DstTy);
2505
2506 for (SmallSetVector<const Type *, 4>::const_iterator
2507 I = Types.begin(), E = Types.end(); I != E; ++I) {
2508 const Type *SrcTy = *I;
2509 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2510 Formula F = Base;
2511
2512 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2513 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2514 JE = F.BaseRegs.end(); J != JE; ++J)
2515 *J = SE.getAnyExtendExpr(*J, SrcTy);
2516
2517 // TODO: This assumes we've done basic processing on all uses and
2518 // have an idea what the register usage is.
2519 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2520 continue;
2521
2522 (void)InsertFormula(LU, LUIdx, F);
2523 }
2524 }
2525}
2526
2527namespace {
2528
Dan Gohman6020d852010-02-14 18:51:20 +00002529/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002530/// defer modifications so that the search phase doesn't have to worry about
2531/// the data structures moving underneath it.
2532struct WorkItem {
2533 size_t LUIdx;
2534 int64_t Imm;
2535 const SCEV *OrigReg;
2536
2537 WorkItem(size_t LI, int64_t I, const SCEV *R)
2538 : LUIdx(LI), Imm(I), OrigReg(R) {}
2539
2540 void print(raw_ostream &OS) const;
2541 void dump() const;
2542};
2543
2544}
2545
2546void WorkItem::print(raw_ostream &OS) const {
2547 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2548 << " , add offset " << Imm;
2549}
2550
2551void WorkItem::dump() const {
2552 print(errs()); errs() << '\n';
2553}
2554
2555/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2556/// distance apart and try to form reuse opportunities between them.
2557void LSRInstance::GenerateCrossUseConstantOffsets() {
2558 // Group the registers by their value without any added constant offset.
2559 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2560 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2561 RegMapTy Map;
2562 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2563 SmallVector<const SCEV *, 8> Sequence;
2564 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2565 I != E; ++I) {
2566 const SCEV *Reg = *I;
2567 int64_t Imm = ExtractImmediate(Reg, SE);
2568 std::pair<RegMapTy::iterator, bool> Pair =
2569 Map.insert(std::make_pair(Reg, ImmMapTy()));
2570 if (Pair.second)
2571 Sequence.push_back(Reg);
2572 Pair.first->second.insert(std::make_pair(Imm, *I));
2573 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2574 }
2575
2576 // Now examine each set of registers with the same base value. Build up
2577 // a list of work to do and do the work in a separate step so that we're
2578 // not adding formulae and register counts while we're searching.
2579 SmallVector<WorkItem, 32> WorkItems;
2580 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2581 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2582 E = Sequence.end(); I != E; ++I) {
2583 const SCEV *Reg = *I;
2584 const ImmMapTy &Imms = Map.find(Reg)->second;
2585
Dan Gohmancd045c02010-02-12 19:20:37 +00002586 // It's not worthwhile looking for reuse if there's only one offset.
2587 if (Imms.size() == 1)
2588 continue;
2589
Dan Gohman572645c2010-02-12 10:34:29 +00002590 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2591 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2592 J != JE; ++J)
2593 dbgs() << ' ' << J->first;
2594 dbgs() << '\n');
2595
2596 // Examine each offset.
2597 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2598 J != JE; ++J) {
2599 const SCEV *OrigReg = J->second;
2600
2601 int64_t JImm = J->first;
2602 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2603
2604 if (!isa<SCEVConstant>(OrigReg) &&
2605 UsedByIndicesMap[Reg].count() == 1) {
2606 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2607 continue;
2608 }
2609
2610 // Conservatively examine offsets between this orig reg a few selected
2611 // other orig regs.
2612 ImmMapTy::const_iterator OtherImms[] = {
2613 Imms.begin(), prior(Imms.end()),
2614 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2615 };
2616 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2617 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002618 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002619
2620 // Compute the difference between the two.
2621 int64_t Imm = (uint64_t)JImm - M->first;
2622 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2623 LUIdx = UsedByIndices.find_next(LUIdx))
2624 // Make a memo of this use, offset, and register tuple.
2625 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2626 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002627 }
2628 }
2629 }
2630
Dan Gohman572645c2010-02-12 10:34:29 +00002631 Map.clear();
2632 Sequence.clear();
2633 UsedByIndicesMap.clear();
2634 UniqueItems.clear();
2635
2636 // Now iterate through the worklist and add new formulae.
2637 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2638 E = WorkItems.end(); I != E; ++I) {
2639 const WorkItem &WI = *I;
2640 size_t LUIdx = WI.LUIdx;
2641 LSRUse &LU = Uses[LUIdx];
2642 int64_t Imm = WI.Imm;
2643 const SCEV *OrigReg = WI.OrigReg;
2644
2645 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2646 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2647 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2648
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002649 // TODO: Use a more targeted data structure.
Dan Gohman572645c2010-02-12 10:34:29 +00002650 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Dan Gohman9f383eb2010-05-20 22:25:20 +00002651 const Formula &F = LU.Formulae[L];
Dan Gohman572645c2010-02-12 10:34:29 +00002652 // Use the immediate in the scaled register.
2653 if (F.ScaledReg == OrigReg) {
2654 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2655 Imm * (uint64_t)F.AM.Scale;
2656 // Don't create 50 + reg(-50).
2657 if (F.referencesReg(SE.getSCEV(
2658 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2659 continue;
2660 Formula NewF = F;
2661 NewF.AM.BaseOffs = Offs;
2662 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2663 LU.Kind, LU.AccessTy, TLI))
2664 continue;
2665 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2666
2667 // If the new scale is a constant in a register, and adding the constant
2668 // value to the immediate would produce a value closer to zero than the
2669 // immediate itself, then the formula isn't worthwhile.
2670 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2671 if (C->getValue()->getValue().isNegative() !=
2672 (NewF.AM.BaseOffs < 0) &&
2673 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
Dan Gohmane0567812010-04-08 23:03:40 +00002674 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002675 continue;
2676
2677 // OK, looks good.
2678 (void)InsertFormula(LU, LUIdx, NewF);
2679 } else {
2680 // Use the immediate in a base register.
2681 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2682 const SCEV *BaseReg = F.BaseRegs[N];
2683 if (BaseReg != OrigReg)
2684 continue;
2685 Formula NewF = F;
2686 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2687 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2688 LU.Kind, LU.AccessTy, TLI))
2689 continue;
2690 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2691
2692 // If the new formula has a constant in a register, and adding the
2693 // constant value to the immediate would produce a value closer to
2694 // zero than the immediate itself, then the formula isn't worthwhile.
2695 for (SmallVectorImpl<const SCEV *>::const_iterator
2696 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2697 J != JE; ++J)
2698 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
Dan Gohman360026f2010-05-18 23:48:08 +00002699 if ((C->getValue()->getValue() + NewF.AM.BaseOffs).abs().slt(
2700 abs64(NewF.AM.BaseOffs)) &&
2701 (C->getValue()->getValue() +
2702 NewF.AM.BaseOffs).countTrailingZeros() >=
2703 CountTrailingZeros_64(NewF.AM.BaseOffs))
Dan Gohman572645c2010-02-12 10:34:29 +00002704 goto skip_formula;
2705
2706 // Ok, looks good.
2707 (void)InsertFormula(LU, LUIdx, NewF);
2708 break;
2709 skip_formula:;
2710 }
2711 }
2712 }
2713 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002714}
2715
Dan Gohman572645c2010-02-12 10:34:29 +00002716/// GenerateAllReuseFormulae - Generate formulae for each use.
2717void
2718LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002719 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002720 // queries are more precise.
2721 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2722 LSRUse &LU = Uses[LUIdx];
2723 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2724 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2725 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2726 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2727 }
2728 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2729 LSRUse &LU = Uses[LUIdx];
2730 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2731 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2732 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2733 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2734 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2735 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2736 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2737 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002738 }
2739 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2740 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002741 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2742 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2743 }
2744
2745 GenerateCrossUseConstantOffsets();
2746}
2747
2748/// If their are multiple formulae with the same set of registers used
2749/// by other uses, pick the best one and delete the others.
2750void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2751#ifndef NDEBUG
Dan Gohmanc6519f92010-05-20 20:05:31 +00002752 bool ChangedFormulae = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002753#endif
2754
2755 // Collect the best formula for each unique set of shared registers. This
2756 // is reset for each use.
2757 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2758 BestFormulaeTy;
2759 BestFormulaeTy BestFormulae;
2760
2761 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2762 LSRUse &LU = Uses[LUIdx];
2763 FormulaSorter Sorter(L, LU, SE, DT);
Dan Gohmanea507f52010-05-20 19:44:23 +00002764 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman572645c2010-02-12 10:34:29 +00002765
Dan Gohmanb2df4332010-05-18 23:42:37 +00002766 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002767 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2768 FIdx != NumForms; ++FIdx) {
2769 Formula &F = LU.Formulae[FIdx];
2770
2771 SmallVector<const SCEV *, 2> Key;
2772 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2773 JE = F.BaseRegs.end(); J != JE; ++J) {
2774 const SCEV *Reg = *J;
2775 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2776 Key.push_back(Reg);
2777 }
2778 if (F.ScaledReg &&
2779 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2780 Key.push_back(F.ScaledReg);
2781 // Unstable sort by host order ok, because this is only used for
2782 // uniquifying.
2783 std::sort(Key.begin(), Key.end());
2784
2785 std::pair<BestFormulaeTy::const_iterator, bool> P =
2786 BestFormulae.insert(std::make_pair(Key, FIdx));
2787 if (!P.second) {
2788 Formula &Best = LU.Formulae[P.first->second];
2789 if (Sorter.operator()(F, Best))
2790 std::swap(F, Best);
Dan Gohman6458ff92010-05-18 22:37:37 +00002791 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002792 dbgs() << "\n"
Dan Gohman6458ff92010-05-18 22:37:37 +00002793 " in favor of formula "; Best.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002794 dbgs() << '\n');
2795#ifndef NDEBUG
Dan Gohmanc6519f92010-05-20 20:05:31 +00002796 ChangedFormulae = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002797#endif
Dan Gohmand69d6282010-05-18 22:39:15 +00002798 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00002799 --FIdx;
2800 --NumForms;
Dan Gohmanb2df4332010-05-18 23:42:37 +00002801 Any = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002802 continue;
2803 }
Dan Gohman59dc6032010-05-07 23:36:59 +00002804 }
2805
Dan Gohman57aaa0b2010-05-18 23:55:57 +00002806 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohmanb2df4332010-05-18 23:42:37 +00002807 if (Any)
2808 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman59dc6032010-05-07 23:36:59 +00002809
2810 // Reset this to prepare for the next use.
Dan Gohman572645c2010-02-12 10:34:29 +00002811 BestFormulae.clear();
2812 }
2813
Dan Gohmanc6519f92010-05-20 20:05:31 +00002814 DEBUG(if (ChangedFormulae) {
Dan Gohman9214b822010-02-13 02:06:02 +00002815 dbgs() << "\n"
2816 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002817 print_uses(dbgs());
2818 });
2819}
2820
Dan Gohmand079c302010-05-18 22:51:59 +00002821// This is a rough guess that seems to work fairly well.
2822static const size_t ComplexityLimit = UINT16_MAX;
2823
2824/// EstimateSearchSpaceComplexity - Estimate the worst-case number of
2825/// solutions the solver might have to consider. It almost never considers
2826/// this many solutions because it prune the search space, but the pruning
2827/// isn't always sufficient.
2828size_t LSRInstance::EstimateSearchSpaceComplexity() const {
2829 uint32_t Power = 1;
2830 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2831 E = Uses.end(); I != E; ++I) {
2832 size_t FSize = I->Formulae.size();
2833 if (FSize >= ComplexityLimit) {
2834 Power = ComplexityLimit;
2835 break;
2836 }
2837 Power *= FSize;
2838 if (Power >= ComplexityLimit)
2839 break;
2840 }
2841 return Power;
2842}
2843
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002844/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
Dan Gohman572645c2010-02-12 10:34:29 +00002845/// formulae to choose from, use some rough heuristics to prune down the number
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002846/// of formulae. This keeps the main solver from taking an extraordinary amount
Dan Gohman572645c2010-02-12 10:34:29 +00002847/// of time in some worst-case scenarios.
2848void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
Dan Gohmana2086b32010-05-19 23:43:12 +00002849 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2850 DEBUG(dbgs() << "The search space is too complex.\n");
2851
2852 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
2853 "which use a superset of registers used by other "
2854 "formulae.\n");
2855
2856 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2857 LSRUse &LU = Uses[LUIdx];
2858 bool Any = false;
2859 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2860 Formula &F = LU.Formulae[i];
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00002861 // Look for a formula with a constant or GV in a register. If the use
2862 // also has a formula with that same value in an immediate field,
2863 // delete the one that uses a register.
Dan Gohmana2086b32010-05-19 23:43:12 +00002864 for (SmallVectorImpl<const SCEV *>::const_iterator
2865 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
2866 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
2867 Formula NewF = F;
2868 NewF.AM.BaseOffs += C->getValue()->getSExtValue();
2869 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2870 (I - F.BaseRegs.begin()));
2871 if (LU.HasFormulaWithSameRegs(NewF)) {
2872 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2873 LU.DeleteFormula(F);
2874 --i;
2875 --e;
2876 Any = true;
2877 break;
2878 }
2879 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
2880 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
2881 if (!F.AM.BaseGV) {
2882 Formula NewF = F;
2883 NewF.AM.BaseGV = GV;
2884 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2885 (I - F.BaseRegs.begin()));
2886 if (LU.HasFormulaWithSameRegs(NewF)) {
2887 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
2888 dbgs() << '\n');
2889 LU.DeleteFormula(F);
2890 --i;
2891 --e;
2892 Any = true;
2893 break;
2894 }
2895 }
2896 }
2897 }
2898 }
2899 if (Any)
2900 LU.RecomputeRegs(LUIdx, RegUses);
2901 }
2902
2903 DEBUG(dbgs() << "After pre-selection:\n";
2904 print_uses(dbgs()));
2905 }
2906
2907 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2908 DEBUG(dbgs() << "The search space is too complex.\n");
2909
2910 DEBUG(dbgs() << "Narrowing the search space by assuming that uses "
2911 "separated by a constant offset will use the same "
2912 "registers.\n");
2913
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00002914 // This is especially useful for unrolled loops.
2915
Dan Gohmana2086b32010-05-19 23:43:12 +00002916 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2917 LSRUse &LU = Uses[LUIdx];
Dan Gohman402d4352010-05-20 20:33:18 +00002918 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2919 E = LU.Formulae.end(); I != E; ++I) {
2920 const Formula &F = *I;
Dan Gohmana2086b32010-05-19 23:43:12 +00002921 if (F.AM.BaseOffs != 0 && F.AM.Scale == 0) {
2922 if (LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU)) {
2923 if (reconcileNewOffset(*LUThatHas, F.AM.BaseOffs,
2924 /*HasBaseReg=*/false,
2925 LU.Kind, LU.AccessTy)) {
2926 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs());
2927 dbgs() << '\n');
2928
2929 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
2930
2931 // Delete formulae from the new use which are no longer legal.
2932 bool Any = false;
2933 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
2934 Formula &F = LUThatHas->Formulae[i];
2935 if (!isLegalUse(F.AM,
2936 LUThatHas->MinOffset, LUThatHas->MaxOffset,
2937 LUThatHas->Kind, LUThatHas->AccessTy, TLI)) {
2938 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
2939 dbgs() << '\n');
2940 LUThatHas->DeleteFormula(F);
2941 --i;
2942 --e;
2943 Any = true;
2944 }
2945 }
2946 if (Any)
2947 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
2948
2949 // Update the relocs to reference the new use.
Dan Gohman402d4352010-05-20 20:33:18 +00002950 for (SmallVectorImpl<LSRFixup>::iterator I = Fixups.begin(),
2951 E = Fixups.end(); I != E; ++I) {
2952 LSRFixup &Fixup = *I;
2953 if (Fixup.LUIdx == LUIdx) {
2954 Fixup.LUIdx = LUThatHas - &Uses.front();
2955 Fixup.Offset += F.AM.BaseOffs;
Dan Gohmana2086b32010-05-19 23:43:12 +00002956 DEBUG(errs() << "New fixup has offset "
Dan Gohman402d4352010-05-20 20:33:18 +00002957 << Fixup.Offset << '\n');
Dan Gohmana2086b32010-05-19 23:43:12 +00002958 }
Dan Gohman402d4352010-05-20 20:33:18 +00002959 if (Fixup.LUIdx == NumUses-1)
2960 Fixup.LUIdx = LUIdx;
Dan Gohmana2086b32010-05-19 23:43:12 +00002961 }
2962
2963 // Delete the old use.
Dan Gohman5ce6d052010-05-20 15:17:54 +00002964 DeleteUse(LU);
Dan Gohmana2086b32010-05-19 23:43:12 +00002965 --LUIdx;
2966 --NumUses;
2967 break;
2968 }
2969 }
2970 }
2971 }
2972 }
2973
2974 DEBUG(dbgs() << "After pre-selection:\n";
2975 print_uses(dbgs()));
2976 }
2977
Dan Gohman76c315a2010-05-20 20:52:00 +00002978 // With all other options exhausted, loop until the system is simple
2979 // enough to handle.
Dan Gohman572645c2010-02-12 10:34:29 +00002980 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmand079c302010-05-18 22:51:59 +00002981 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman572645c2010-02-12 10:34:29 +00002982 // Ok, we have too many of formulae on our hands to conveniently handle.
2983 // Use a rough heuristic to thin out the list.
Dan Gohman0da751b2010-05-18 22:41:32 +00002984 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00002985
2986 // Pick the register which is used by the most LSRUses, which is likely
2987 // to be a good reuse register candidate.
2988 const SCEV *Best = 0;
2989 unsigned BestNum = 0;
2990 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2991 I != E; ++I) {
2992 const SCEV *Reg = *I;
2993 if (Taken.count(Reg))
2994 continue;
2995 if (!Best)
2996 Best = Reg;
2997 else {
2998 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2999 if (Count > BestNum) {
3000 Best = Reg;
3001 BestNum = Count;
3002 }
3003 }
3004 }
3005
3006 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003007 << " will yield profitable reuse.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00003008 Taken.insert(Best);
3009
3010 // In any use with formulae which references this register, delete formulae
3011 // which don't reference it.
Dan Gohmanb2df4332010-05-18 23:42:37 +00003012 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3013 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00003014 if (!LU.Regs.count(Best)) continue;
3015
Dan Gohmanb2df4332010-05-18 23:42:37 +00003016 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003017 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3018 Formula &F = LU.Formulae[i];
3019 if (!F.referencesReg(Best)) {
3020 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmand69d6282010-05-18 22:39:15 +00003021 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00003022 --e;
3023 --i;
Dan Gohmanb2df4332010-05-18 23:42:37 +00003024 Any = true;
Dan Gohman59dc6032010-05-07 23:36:59 +00003025 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman572645c2010-02-12 10:34:29 +00003026 continue;
3027 }
Dan Gohman572645c2010-02-12 10:34:29 +00003028 }
Dan Gohmanb2df4332010-05-18 23:42:37 +00003029
3030 if (Any)
3031 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman572645c2010-02-12 10:34:29 +00003032 }
3033
3034 DEBUG(dbgs() << "After pre-selection:\n";
3035 print_uses(dbgs()));
3036 }
3037}
3038
3039/// SolveRecurse - This is the recursive solver.
3040void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
3041 Cost &SolutionCost,
3042 SmallVectorImpl<const Formula *> &Workspace,
3043 const Cost &CurCost,
3044 const SmallPtrSet<const SCEV *, 16> &CurRegs,
3045 DenseSet<const SCEV *> &VisitedRegs) const {
3046 // Some ideas:
3047 // - prune more:
3048 // - use more aggressive filtering
3049 // - sort the formula so that the most profitable solutions are found first
3050 // - sort the uses too
3051 // - search faster:
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003052 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman572645c2010-02-12 10:34:29 +00003053 // and bail early.
3054 // - track register sets with SmallBitVector
3055
3056 const LSRUse &LU = Uses[Workspace.size()];
3057
3058 // If this use references any register that's already a part of the
3059 // in-progress solution, consider it a requirement that a formula must
3060 // reference that register in order to be considered. This prunes out
3061 // unprofitable searching.
3062 SmallSetVector<const SCEV *, 4> ReqRegs;
3063 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
3064 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00003065 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00003066 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00003067
Dan Gohman9214b822010-02-13 02:06:02 +00003068 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003069 SmallPtrSet<const SCEV *, 16> NewRegs;
3070 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00003071retry:
Dan Gohman572645c2010-02-12 10:34:29 +00003072 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3073 E = LU.Formulae.end(); I != E; ++I) {
3074 const Formula &F = *I;
3075
3076 // Ignore formulae which do not use any of the required registers.
3077 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
3078 JE = ReqRegs.end(); J != JE; ++J) {
3079 const SCEV *Reg = *J;
3080 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
3081 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
3082 F.BaseRegs.end())
3083 goto skip;
3084 }
Dan Gohman9214b822010-02-13 02:06:02 +00003085 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00003086
3087 // Evaluate the cost of the current formula. If it's already worse than
3088 // the current best, prune the search at that point.
3089 NewCost = CurCost;
3090 NewRegs = CurRegs;
3091 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
3092 if (NewCost < SolutionCost) {
3093 Workspace.push_back(&F);
3094 if (Workspace.size() != Uses.size()) {
3095 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
3096 NewRegs, VisitedRegs);
3097 if (F.getNumRegs() == 1 && Workspace.size() == 1)
3098 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
3099 } else {
3100 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
3101 dbgs() << ". Regs:";
3102 for (SmallPtrSet<const SCEV *, 16>::const_iterator
3103 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
3104 dbgs() << ' ' << **I;
3105 dbgs() << '\n');
3106
3107 SolutionCost = NewCost;
3108 Solution = Workspace;
3109 }
3110 Workspace.pop_back();
3111 }
3112 skip:;
3113 }
Dan Gohman9214b822010-02-13 02:06:02 +00003114
3115 // If none of the formulae had all of the required registers, relax the
3116 // constraint so that we don't exclude all formulae.
3117 if (!AnySatisfiedReqRegs) {
Dan Gohman59dc6032010-05-07 23:36:59 +00003118 assert(!ReqRegs.empty() && "Solver failed even without required registers");
Dan Gohman9214b822010-02-13 02:06:02 +00003119 ReqRegs.clear();
3120 goto retry;
3121 }
Dan Gohman572645c2010-02-12 10:34:29 +00003122}
3123
Dan Gohman76c315a2010-05-20 20:52:00 +00003124/// Solve - Choose one formula from each use. Return the results in the given
3125/// Solution vector.
Dan Gohman572645c2010-02-12 10:34:29 +00003126void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
3127 SmallVector<const Formula *, 8> Workspace;
3128 Cost SolutionCost;
3129 SolutionCost.Loose();
3130 Cost CurCost;
3131 SmallPtrSet<const SCEV *, 16> CurRegs;
3132 DenseSet<const SCEV *> VisitedRegs;
3133 Workspace.reserve(Uses.size());
3134
Dan Gohmanf7ff37d2010-05-20 20:00:41 +00003135 // SolveRecurse does all the work.
Dan Gohman572645c2010-02-12 10:34:29 +00003136 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
3137 CurRegs, VisitedRegs);
3138
3139 // Ok, we've now made all our decisions.
3140 DEBUG(dbgs() << "\n"
3141 "The chosen solution requires "; SolutionCost.print(dbgs());
3142 dbgs() << ":\n";
3143 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
3144 dbgs() << " ";
3145 Uses[i].print(dbgs());
3146 dbgs() << "\n"
3147 " ";
3148 Solution[i]->print(dbgs());
3149 dbgs() << '\n';
3150 });
Dan Gohmana5528782010-05-20 20:59:23 +00003151
3152 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman572645c2010-02-12 10:34:29 +00003153}
3154
Dan Gohmane5f76872010-04-09 22:07:05 +00003155/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
3156/// the dominator tree far as we can go while still being dominated by the
3157/// input positions. This helps canonicalize the insert position, which
3158/// encourages sharing.
3159BasicBlock::iterator
3160LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
3161 const SmallVectorImpl<Instruction *> &Inputs)
3162 const {
3163 for (;;) {
3164 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
3165 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
3166
3167 BasicBlock *IDom;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003168 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman0fe46d92010-05-20 22:46:54 +00003169 if (!Rung) return IP;
Dan Gohmand974a0e2010-05-20 20:00:25 +00003170 Rung = Rung->getIDom();
3171 if (!Rung) return IP;
3172 IDom = Rung->getBlock();
Dan Gohmane5f76872010-04-09 22:07:05 +00003173
3174 // Don't climb into a loop though.
3175 const Loop *IDomLoop = LI.getLoopFor(IDom);
3176 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
3177 if (IDomDepth <= IPLoopDepth &&
3178 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
3179 break;
3180 }
3181
3182 bool AllDominate = true;
3183 Instruction *BetterPos = 0;
3184 Instruction *Tentative = IDom->getTerminator();
3185 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
3186 E = Inputs.end(); I != E; ++I) {
3187 Instruction *Inst = *I;
3188 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
3189 AllDominate = false;
3190 break;
3191 }
3192 // Attempt to find an insert position in the middle of the block,
3193 // instead of at the end, so that it can be used for other expansions.
3194 if (IDom == Inst->getParent() &&
3195 (!BetterPos || DT.dominates(BetterPos, Inst)))
Douglas Gregor7d9663c2010-05-11 06:17:44 +00003196 BetterPos = llvm::next(BasicBlock::iterator(Inst));
Dan Gohmane5f76872010-04-09 22:07:05 +00003197 }
3198 if (!AllDominate)
3199 break;
3200 if (BetterPos)
3201 IP = BetterPos;
3202 else
3203 IP = Tentative;
3204 }
3205
3206 return IP;
3207}
3208
3209/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand96eae82010-04-09 02:00:38 +00003210/// dominated by the operands and which will dominate the result.
3211BasicBlock::iterator
Dan Gohmane5f76872010-04-09 22:07:05 +00003212LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
3213 const LSRFixup &LF,
3214 const LSRUse &LU) const {
Dan Gohmand96eae82010-04-09 02:00:38 +00003215 // Collect some instructions which must be dominated by the
Dan Gohman448db1c2010-04-07 22:27:08 +00003216 // expanding replacement. These must be dominated by any operands that
Dan Gohman572645c2010-02-12 10:34:29 +00003217 // will be required in the expansion.
3218 SmallVector<Instruction *, 4> Inputs;
3219 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
3220 Inputs.push_back(I);
3221 if (LU.Kind == LSRUse::ICmpZero)
3222 if (Instruction *I =
3223 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
3224 Inputs.push_back(I);
Dan Gohman448db1c2010-04-07 22:27:08 +00003225 if (LF.PostIncLoops.count(L)) {
3226 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman069d6f32010-03-02 01:59:21 +00003227 Inputs.push_back(L->getLoopLatch()->getTerminator());
3228 else
3229 Inputs.push_back(IVIncInsertPos);
3230 }
Dan Gohman701a4ae2010-04-08 05:57:57 +00003231 // The expansion must also be dominated by the increment positions of any
3232 // loops it for which it is using post-inc mode.
3233 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
3234 E = LF.PostIncLoops.end(); I != E; ++I) {
3235 const Loop *PIL = *I;
3236 if (PIL == L) continue;
3237
Dan Gohmane5f76872010-04-09 22:07:05 +00003238 // Be dominated by the loop exit.
Dan Gohman701a4ae2010-04-08 05:57:57 +00003239 SmallVector<BasicBlock *, 4> ExitingBlocks;
3240 PIL->getExitingBlocks(ExitingBlocks);
3241 if (!ExitingBlocks.empty()) {
3242 BasicBlock *BB = ExitingBlocks[0];
3243 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
3244 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
3245 Inputs.push_back(BB->getTerminator());
3246 }
3247 }
Dan Gohman572645c2010-02-12 10:34:29 +00003248
3249 // Then, climb up the immediate dominator tree as far as we can go while
3250 // still being dominated by the input positions.
Dan Gohmane5f76872010-04-09 22:07:05 +00003251 IP = HoistInsertPosition(IP, Inputs);
Dan Gohmand96eae82010-04-09 02:00:38 +00003252
3253 // Don't insert instructions before PHI nodes.
Dan Gohman572645c2010-02-12 10:34:29 +00003254 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand96eae82010-04-09 02:00:38 +00003255
3256 // Ignore debug intrinsics.
Dan Gohman449f31c2010-03-26 00:33:27 +00003257 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman572645c2010-02-12 10:34:29 +00003258
Dan Gohmand96eae82010-04-09 02:00:38 +00003259 return IP;
3260}
3261
Dan Gohman76c315a2010-05-20 20:52:00 +00003262/// Expand - Emit instructions for the leading candidate expression for this
3263/// LSRUse (this is called "expanding").
Dan Gohmand96eae82010-04-09 02:00:38 +00003264Value *LSRInstance::Expand(const LSRFixup &LF,
3265 const Formula &F,
3266 BasicBlock::iterator IP,
3267 SCEVExpander &Rewriter,
3268 SmallVectorImpl<WeakVH> &DeadInsts) const {
3269 const LSRUse &LU = Uses[LF.LUIdx];
3270
3271 // Determine an input position which will be dominated by the operands and
3272 // which will dominate the result.
Dan Gohmane5f76872010-04-09 22:07:05 +00003273 IP = AdjustInsertPositionForExpand(IP, LF, LU);
Dan Gohmand96eae82010-04-09 02:00:38 +00003274
Dan Gohman572645c2010-02-12 10:34:29 +00003275 // Inform the Rewriter if we have a post-increment use, so that it can
3276 // perform an advantageous expansion.
Dan Gohman448db1c2010-04-07 22:27:08 +00003277 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman572645c2010-02-12 10:34:29 +00003278
3279 // This is the type that the user actually needs.
3280 const Type *OpTy = LF.OperandValToReplace->getType();
3281 // This will be the type that we'll initially expand to.
3282 const Type *Ty = F.getType();
3283 if (!Ty)
3284 // No type known; just expand directly to the ultimate type.
3285 Ty = OpTy;
3286 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3287 // Expand directly to the ultimate type if it's the right size.
3288 Ty = OpTy;
3289 // This is the type to do integer arithmetic in.
3290 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3291
3292 // Build up a list of operands to add together to form the full base.
3293 SmallVector<const SCEV *, 8> Ops;
3294
3295 // Expand the BaseRegs portion.
3296 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3297 E = F.BaseRegs.end(); I != E; ++I) {
3298 const SCEV *Reg = *I;
3299 assert(!Reg->isZero() && "Zero allocated in a base register!");
3300
Dan Gohman448db1c2010-04-07 22:27:08 +00003301 // If we're expanding for a post-inc user, make the post-inc adjustment.
3302 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3303 Reg = TransformForPostIncUse(Denormalize, Reg,
3304 LF.UserInst, LF.OperandValToReplace,
3305 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003306
3307 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3308 }
3309
Dan Gohman087bd1e2010-03-03 05:29:13 +00003310 // Flush the operand list to suppress SCEVExpander hoisting.
3311 if (!Ops.empty()) {
3312 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3313 Ops.clear();
3314 Ops.push_back(SE.getUnknown(FullV));
3315 }
3316
Dan Gohman572645c2010-02-12 10:34:29 +00003317 // Expand the ScaledReg portion.
3318 Value *ICmpScaledV = 0;
3319 if (F.AM.Scale != 0) {
3320 const SCEV *ScaledS = F.ScaledReg;
3321
Dan Gohman448db1c2010-04-07 22:27:08 +00003322 // If we're expanding for a post-inc user, make the post-inc adjustment.
3323 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3324 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3325 LF.UserInst, LF.OperandValToReplace,
3326 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003327
3328 if (LU.Kind == LSRUse::ICmpZero) {
3329 // An interesting way of "folding" with an icmp is to use a negated
3330 // scale, which we'll implement by inserting it into the other operand
3331 // of the icmp.
3332 assert(F.AM.Scale == -1 &&
3333 "The only scale supported by ICmpZero uses is -1!");
3334 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3335 } else {
3336 // Otherwise just expand the scaled register and an explicit scale,
3337 // which is expected to be matched as part of the address.
3338 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3339 ScaledS = SE.getMulExpr(ScaledS,
Dan Gohmandeff6212010-05-03 22:09:21 +00003340 SE.getConstant(ScaledS->getType(), F.AM.Scale));
Dan Gohman572645c2010-02-12 10:34:29 +00003341 Ops.push_back(ScaledS);
Dan Gohman087bd1e2010-03-03 05:29:13 +00003342
3343 // Flush the operand list to suppress SCEVExpander hoisting.
3344 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3345 Ops.clear();
3346 Ops.push_back(SE.getUnknown(FullV));
Dan Gohman572645c2010-02-12 10:34:29 +00003347 }
3348 }
3349
Dan Gohman087bd1e2010-03-03 05:29:13 +00003350 // Expand the GV portion.
3351 if (F.AM.BaseGV) {
3352 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3353
3354 // Flush the operand list to suppress SCEVExpander hoisting.
3355 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3356 Ops.clear();
3357 Ops.push_back(SE.getUnknown(FullV));
3358 }
3359
3360 // Expand the immediate portion.
Dan Gohman572645c2010-02-12 10:34:29 +00003361 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3362 if (Offset != 0) {
3363 if (LU.Kind == LSRUse::ICmpZero) {
3364 // The other interesting way of "folding" with an ICmpZero is to use a
3365 // negated immediate.
3366 if (!ICmpScaledV)
3367 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3368 else {
3369 Ops.push_back(SE.getUnknown(ICmpScaledV));
3370 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3371 }
3372 } else {
3373 // Just add the immediate values. These again are expected to be matched
3374 // as part of the address.
Dan Gohman087bd1e2010-03-03 05:29:13 +00003375 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman572645c2010-02-12 10:34:29 +00003376 }
3377 }
3378
3379 // Emit instructions summing all the operands.
3380 const SCEV *FullS = Ops.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +00003381 SE.getConstant(IntTy, 0) :
Dan Gohman572645c2010-02-12 10:34:29 +00003382 SE.getAddExpr(Ops);
3383 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3384
3385 // We're done expanding now, so reset the rewriter.
Dan Gohman448db1c2010-04-07 22:27:08 +00003386 Rewriter.clearPostInc();
Dan Gohman572645c2010-02-12 10:34:29 +00003387
3388 // An ICmpZero Formula represents an ICmp which we're handling as a
3389 // comparison against zero. Now that we've expanded an expression for that
3390 // form, update the ICmp's other operand.
3391 if (LU.Kind == LSRUse::ICmpZero) {
3392 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3393 DeadInsts.push_back(CI->getOperand(1));
3394 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3395 "a scale at the same time!");
3396 if (F.AM.Scale == -1) {
3397 if (ICmpScaledV->getType() != OpTy) {
3398 Instruction *Cast =
3399 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3400 OpTy, false),
3401 ICmpScaledV, OpTy, "tmp", CI);
3402 ICmpScaledV = Cast;
3403 }
3404 CI->setOperand(1, ICmpScaledV);
3405 } else {
3406 assert(F.AM.Scale == 0 &&
3407 "ICmp does not support folding a global value and "
3408 "a scale at the same time!");
3409 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3410 -(uint64_t)Offset);
3411 if (C->getType() != OpTy)
3412 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3413 OpTy, false),
3414 C, OpTy);
3415
3416 CI->setOperand(1, C);
3417 }
3418 }
3419
3420 return FullV;
3421}
3422
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003423/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3424/// of their operands effectively happens in their predecessor blocks, so the
3425/// expression may need to be expanded in multiple places.
3426void LSRInstance::RewriteForPHI(PHINode *PN,
3427 const LSRFixup &LF,
3428 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003429 SCEVExpander &Rewriter,
3430 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003431 Pass *P) const {
3432 DenseMap<BasicBlock *, Value *> Inserted;
3433 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3434 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3435 BasicBlock *BB = PN->getIncomingBlock(i);
3436
3437 // If this is a critical edge, split the edge so that we do not insert
3438 // the code on all predecessor/successor paths. We do this unless this
3439 // is the canonical backedge for this loop, which complicates post-inc
3440 // users.
3441 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3442 !isa<IndirectBrInst>(BB->getTerminator()) &&
3443 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3444 // Split the critical edge.
3445 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3446
3447 // If PN is outside of the loop and BB is in the loop, we want to
3448 // move the block to be immediately before the PHI block, not
3449 // immediately after BB.
3450 if (L->contains(BB) && !L->contains(PN))
3451 NewBB->moveBefore(PN->getParent());
3452
3453 // Splitting the edge can reduce the number of PHI entries we have.
3454 e = PN->getNumIncomingValues();
3455 BB = NewBB;
3456 i = PN->getBasicBlockIndex(BB);
3457 }
3458
3459 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3460 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3461 if (!Pair.second)
3462 PN->setIncomingValue(i, Pair.first->second);
3463 else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003464 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003465
3466 // If this is reuse-by-noop-cast, insert the noop cast.
3467 const Type *OpTy = LF.OperandValToReplace->getType();
3468 if (FullV->getType() != OpTy)
3469 FullV =
3470 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3471 OpTy, false),
3472 FullV, LF.OperandValToReplace->getType(),
3473 "tmp", BB->getTerminator());
3474
3475 PN->setIncomingValue(i, FullV);
3476 Pair.first->second = FullV;
3477 }
3478 }
3479}
3480
Dan Gohman572645c2010-02-12 10:34:29 +00003481/// Rewrite - Emit instructions for the leading candidate expression for this
3482/// LSRUse (this is called "expanding"), and update the UserInst to reference
3483/// the newly expanded value.
3484void LSRInstance::Rewrite(const LSRFixup &LF,
3485 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00003486 SCEVExpander &Rewriter,
3487 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00003488 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003489 // First, find an insertion point that dominates UserInst. For PHI nodes,
3490 // find the nearest block which dominates all the relevant uses.
3491 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman454d26d2010-02-22 04:11:59 +00003492 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003493 } else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003494 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman572645c2010-02-12 10:34:29 +00003495
3496 // If this is reuse-by-noop-cast, insert the noop cast.
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003497 const Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003498 if (FullV->getType() != OpTy) {
3499 Instruction *Cast =
3500 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3501 FullV, OpTy, "tmp", LF.UserInst);
3502 FullV = Cast;
3503 }
3504
3505 // Update the user. ICmpZero is handled specially here (for now) because
3506 // Expand may have updated one of the operands of the icmp already, and
3507 // its new value may happen to be equal to LF.OperandValToReplace, in
3508 // which case doing replaceUsesOfWith leads to replacing both operands
3509 // with the same value. TODO: Reorganize this.
3510 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3511 LF.UserInst->setOperand(0, FullV);
3512 else
3513 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3514 }
3515
3516 DeadInsts.push_back(LF.OperandValToReplace);
3517}
3518
Dan Gohman76c315a2010-05-20 20:52:00 +00003519/// ImplementSolution - Rewrite all the fixup locations with new values,
3520/// following the chosen solution.
Dan Gohman572645c2010-02-12 10:34:29 +00003521void
3522LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3523 Pass *P) {
3524 // Keep track of instructions we may have made dead, so that
3525 // we can remove them after we are done working.
3526 SmallVector<WeakVH, 16> DeadInsts;
3527
3528 SCEVExpander Rewriter(SE);
3529 Rewriter.disableCanonicalMode();
3530 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3531
3532 // Expand the new value definitions and update the users.
Dan Gohman402d4352010-05-20 20:33:18 +00003533 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3534 E = Fixups.end(); I != E; ++I) {
3535 const LSRFixup &Fixup = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00003536
Dan Gohman402d4352010-05-20 20:33:18 +00003537 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003538
3539 Changed = true;
3540 }
3541
3542 // Clean up after ourselves. This must be done before deleting any
3543 // instructions.
3544 Rewriter.clear();
3545
3546 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3547}
3548
3549LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3550 : IU(P->getAnalysis<IVUsers>()),
3551 SE(P->getAnalysis<ScalarEvolution>()),
3552 DT(P->getAnalysis<DominatorTree>()),
Dan Gohmane5f76872010-04-09 22:07:05 +00003553 LI(P->getAnalysis<LoopInfo>()),
Dan Gohman572645c2010-02-12 10:34:29 +00003554 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003555
Dan Gohman03e896b2009-11-05 21:11:53 +00003556 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003557 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003558
Dan Gohman572645c2010-02-12 10:34:29 +00003559 // If there's no interesting work to be done, bail early.
3560 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003561
Dan Gohman572645c2010-02-12 10:34:29 +00003562 DEBUG(dbgs() << "\nLSR on loop ";
3563 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3564 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003565
Dan Gohman402d4352010-05-20 20:33:18 +00003566 // First, perform some low-level loop optimizations.
Dan Gohman572645c2010-02-12 10:34:29 +00003567 OptimizeShadowIV();
Dan Gohmanc6519f92010-05-20 20:05:31 +00003568 OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003569
Dan Gohman402d4352010-05-20 20:33:18 +00003570 // Start collecting data and preparing for the solver.
Dan Gohman572645c2010-02-12 10:34:29 +00003571 CollectInterestingTypesAndFactors();
3572 CollectFixupsAndInitialFormulae();
3573 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003574
Dan Gohman572645c2010-02-12 10:34:29 +00003575 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3576 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003577
Dan Gohman572645c2010-02-12 10:34:29 +00003578 // Now use the reuse data to generate a bunch of interesting ways
3579 // to formulate the values needed for the uses.
3580 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003581
Dan Gohman572645c2010-02-12 10:34:29 +00003582 DEBUG(dbgs() << "\n"
3583 "After generating reuse formulae:\n";
3584 print_uses(dbgs()));
Nate Begemaneaa13852004-10-18 21:08:22 +00003585
Dan Gohman572645c2010-02-12 10:34:29 +00003586 FilterOutUndesirableDedicatedRegisters();
3587 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003588
Dan Gohman572645c2010-02-12 10:34:29 +00003589 SmallVector<const Formula *, 8> Solution;
3590 Solve(Solution);
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003591
Dan Gohman572645c2010-02-12 10:34:29 +00003592 // Release memory that is no longer needed.
3593 Factors.clear();
3594 Types.clear();
3595 RegUses.clear();
3596
3597#ifndef NDEBUG
3598 // Formulae should be legal.
3599 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3600 E = Uses.end(); I != E; ++I) {
3601 const LSRUse &LU = *I;
3602 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3603 JE = LU.Formulae.end(); J != JE; ++J)
3604 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3605 LU.Kind, LU.AccessTy, TLI) &&
3606 "Illegal formula generated!");
3607 };
3608#endif
3609
3610 // Now that we've decided what we want, make it so.
3611 ImplementSolution(Solution, P);
3612}
3613
3614void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3615 if (Factors.empty() && Types.empty()) return;
3616
3617 OS << "LSR has identified the following interesting factors and types: ";
3618 bool First = true;
3619
3620 for (SmallSetVector<int64_t, 8>::const_iterator
3621 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3622 if (!First) OS << ", ";
3623 First = false;
3624 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003625 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003626
Dan Gohman572645c2010-02-12 10:34:29 +00003627 for (SmallSetVector<const Type *, 4>::const_iterator
3628 I = Types.begin(), E = Types.end(); I != E; ++I) {
3629 if (!First) OS << ", ";
3630 First = false;
3631 OS << '(' << **I << ')';
3632 }
3633 OS << '\n';
3634}
3635
3636void LSRInstance::print_fixups(raw_ostream &OS) const {
3637 OS << "LSR is examining the following fixup sites:\n";
3638 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3639 E = Fixups.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +00003640 dbgs() << " ";
Dan Gohman9f383eb2010-05-20 22:25:20 +00003641 I->print(OS);
Dan Gohman572645c2010-02-12 10:34:29 +00003642 OS << '\n';
3643 }
3644}
3645
3646void LSRInstance::print_uses(raw_ostream &OS) const {
3647 OS << "LSR is examining the following uses:\n";
3648 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3649 E = Uses.end(); I != E; ++I) {
3650 const LSRUse &LU = *I;
3651 dbgs() << " ";
3652 LU.print(OS);
3653 OS << '\n';
3654 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3655 JE = LU.Formulae.end(); J != JE; ++J) {
3656 OS << " ";
3657 J->print(OS);
3658 OS << '\n';
3659 }
3660 }
3661}
3662
3663void LSRInstance::print(raw_ostream &OS) const {
3664 print_factors_and_types(OS);
3665 print_fixups(OS);
3666 print_uses(OS);
3667}
3668
3669void LSRInstance::dump() const {
3670 print(errs()); errs() << '\n';
3671}
3672
3673namespace {
3674
3675class LoopStrengthReduce : public LoopPass {
3676 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3677 /// transformation profitability.
3678 const TargetLowering *const TLI;
3679
3680public:
3681 static char ID; // Pass ID, replacement for typeid
3682 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3683
3684private:
3685 bool runOnLoop(Loop *L, LPPassManager &LPM);
3686 void getAnalysisUsage(AnalysisUsage &AU) const;
3687};
3688
3689}
3690
3691char LoopStrengthReduce::ID = 0;
3692static RegisterPass<LoopStrengthReduce>
3693X("loop-reduce", "Loop Strength Reduction");
3694
3695Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3696 return new LoopStrengthReduce(TLI);
3697}
3698
3699LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3700 : LoopPass(&ID), TLI(tli) {}
3701
3702void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3703 // We split critical edges, so we change the CFG. However, we do update
3704 // many analyses if they are around.
3705 AU.addPreservedID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00003706 AU.addPreserved("domfrontier");
3707
Dan Gohmane5f76872010-04-09 22:07:05 +00003708 AU.addRequired<LoopInfo>();
3709 AU.addPreserved<LoopInfo>();
Dan Gohman572645c2010-02-12 10:34:29 +00003710 AU.addRequiredID(LoopSimplifyID);
3711 AU.addRequired<DominatorTree>();
3712 AU.addPreserved<DominatorTree>();
3713 AU.addRequired<ScalarEvolution>();
3714 AU.addPreserved<ScalarEvolution>();
3715 AU.addRequired<IVUsers>();
3716 AU.addPreserved<IVUsers>();
3717}
3718
3719bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3720 bool Changed = false;
3721
3722 // Run the main LSR transformation.
3723 Changed |= LSRInstance(TLI, L, this).getChanged();
3724
Dan Gohmanafc36a92009-05-02 18:29:22 +00003725 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003726 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003727 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003728
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003729 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003730}