blob: 43c1d06b65d242080f47647a4c2db5e05999e512 [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
210 bool referencesReg(const SCEV *S) const;
211 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
212 const RegUseTracker &RegUses) const;
213
214 void print(raw_ostream &OS) const;
215 void dump() const;
216};
217
218}
219
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000220/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman572645c2010-02-12 10:34:29 +0000221static void DoInitialMatch(const SCEV *S, Loop *L,
222 SmallVectorImpl<const SCEV *> &Good,
223 SmallVectorImpl<const SCEV *> &Bad,
224 ScalarEvolution &SE, DominatorTree &DT) {
225 // Collect expressions which properly dominate the loop header.
226 if (S->properlyDominates(L->getHeader(), &DT)) {
227 Good.push_back(S);
228 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000229 }
Dan Gohman572645c2010-02-12 10:34:29 +0000230
231 // Look at add operands.
232 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
233 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
234 I != E; ++I)
235 DoInitialMatch(*I, L, Good, Bad, SE, DT);
236 return;
237 }
238
239 // Look at addrec operands.
240 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
241 if (!AR->getStart()->isZero()) {
242 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
Dan Gohmandeff6212010-05-03 22:09:21 +0000243 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +0000244 AR->getStepRecurrence(SE),
245 AR->getLoop()),
246 L, Good, Bad, SE, DT);
247 return;
248 }
249
250 // Handle a multiplication by -1 (negation) if it didn't fold.
251 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
252 if (Mul->getOperand(0)->isAllOnesValue()) {
253 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
254 const SCEV *NewMul = SE.getMulExpr(Ops);
255
256 SmallVector<const SCEV *, 4> MyGood;
257 SmallVector<const SCEV *, 4> MyBad;
258 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
259 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
260 SE.getEffectiveSCEVType(NewMul->getType())));
261 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
262 E = MyGood.end(); I != E; ++I)
263 Good.push_back(SE.getMulExpr(NegOne, *I));
264 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
265 E = MyBad.end(); I != E; ++I)
266 Bad.push_back(SE.getMulExpr(NegOne, *I));
267 return;
268 }
269
270 // Ok, we can't do anything interesting. Just stuff the whole thing into a
271 // register and hope for the best.
272 Bad.push_back(S);
273}
274
275/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
276/// attempting to keep all loop-invariant and loop-computable values in a
277/// single base register.
278void Formula::InitialMatch(const SCEV *S, Loop *L,
279 ScalarEvolution &SE, DominatorTree &DT) {
280 SmallVector<const SCEV *, 4> Good;
281 SmallVector<const SCEV *, 4> Bad;
282 DoInitialMatch(S, L, Good, Bad, SE, DT);
283 if (!Good.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000284 const SCEV *Sum = SE.getAddExpr(Good);
285 if (!Sum->isZero())
286 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000287 AM.HasBaseReg = true;
288 }
289 if (!Bad.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000290 const SCEV *Sum = SE.getAddExpr(Bad);
291 if (!Sum->isZero())
292 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000293 AM.HasBaseReg = true;
294 }
295}
296
297/// getNumRegs - Return the total number of register operands used by this
298/// formula. This does not include register uses implied by non-constant
299/// addrec strides.
300unsigned Formula::getNumRegs() const {
301 return !!ScaledReg + BaseRegs.size();
302}
303
304/// getType - Return the type of this formula, if it has one, or null
305/// otherwise. This type is meaningless except for the bit size.
306const Type *Formula::getType() const {
307 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
308 ScaledReg ? ScaledReg->getType() :
309 AM.BaseGV ? AM.BaseGV->getType() :
310 0;
311}
312
313/// referencesReg - Test if this formula references the given register.
314bool Formula::referencesReg(const SCEV *S) const {
315 return S == ScaledReg ||
316 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
317}
318
319/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
320/// which are used by uses other than the use with the given index.
321bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
322 const RegUseTracker &RegUses) const {
323 if (ScaledReg)
324 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
325 return true;
326 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
327 E = BaseRegs.end(); I != E; ++I)
328 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
329 return true;
330 return false;
331}
332
333void Formula::print(raw_ostream &OS) const {
334 bool First = true;
335 if (AM.BaseGV) {
336 if (!First) OS << " + "; else First = false;
337 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
338 }
339 if (AM.BaseOffs != 0) {
340 if (!First) OS << " + "; else First = false;
341 OS << AM.BaseOffs;
342 }
343 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
344 E = BaseRegs.end(); I != E; ++I) {
345 if (!First) OS << " + "; else First = false;
346 OS << "reg(" << **I << ')';
347 }
Dan Gohmanc4cfbaf2010-05-18 22:35:55 +0000348 if (AM.HasBaseReg && BaseRegs.empty()) {
349 if (!First) OS << " + "; else First = false;
350 OS << "**error: HasBaseReg**";
351 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
352 if (!First) OS << " + "; else First = false;
353 OS << "**error: !HasBaseReg**";
354 }
Dan Gohman572645c2010-02-12 10:34:29 +0000355 if (AM.Scale != 0) {
356 if (!First) OS << " + "; else First = false;
357 OS << AM.Scale << "*reg(";
358 if (ScaledReg)
359 OS << *ScaledReg;
360 else
361 OS << "<unknown>";
362 OS << ')';
363 }
364}
365
366void Formula::dump() const {
367 print(errs()); errs() << '\n';
368}
369
Dan Gohmanaae01f12010-02-19 19:32:49 +0000370/// isAddRecSExtable - Return true if the given addrec can be sign-extended
371/// without changing its value.
372static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
373 const Type *WideTy =
374 IntegerType::get(SE.getContext(),
375 SE.getTypeSizeInBits(AR->getType()) + 1);
376 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
377}
378
379/// isAddSExtable - Return true if the given add can be sign-extended
380/// without changing its value.
381static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
382 const Type *WideTy =
383 IntegerType::get(SE.getContext(),
384 SE.getTypeSizeInBits(A->getType()) + 1);
385 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
386}
387
388/// isMulSExtable - Return true if the given add can be sign-extended
389/// without changing its value.
390static bool isMulSExtable(const SCEVMulExpr *A, ScalarEvolution &SE) {
391 const Type *WideTy =
392 IntegerType::get(SE.getContext(),
393 SE.getTypeSizeInBits(A->getType()) + 1);
394 return isa<SCEVMulExpr>(SE.getSignExtendExpr(A, WideTy));
395}
396
Dan Gohmanf09b7122010-02-19 19:35:48 +0000397/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
398/// and if the remainder is known to be zero, or null otherwise. If
399/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
400/// to Y, ignoring that the multiplication may overflow, which is useful when
401/// the result will be used in a context where the most significant bits are
402/// ignored.
403static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
404 ScalarEvolution &SE,
405 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000406 // Handle the trivial case, which works for any SCEV type.
407 if (LHS == RHS)
Dan Gohmandeff6212010-05-03 22:09:21 +0000408 return SE.getConstant(LHS->getType(), 1);
Dan Gohman572645c2010-02-12 10:34:29 +0000409
410 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
411 // folding.
412 if (RHS->isAllOnesValue())
413 return SE.getMulExpr(LHS, RHS);
414
415 // Check for a division of a constant by a constant.
416 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
417 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
418 if (!RC)
419 return 0;
420 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
421 return 0;
422 return SE.getConstant(C->getValue()->getValue()
423 .sdiv(RC->getValue()->getValue()));
424 }
425
Dan Gohmanaae01f12010-02-19 19:32:49 +0000426 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000427 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000428 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000429 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
430 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000431 if (!Start) return 0;
Dan Gohmanf09b7122010-02-19 19:35:48 +0000432 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
433 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000434 if (!Step) return 0;
435 return SE.getAddRecExpr(Start, Step, AR->getLoop());
436 }
Dan Gohman572645c2010-02-12 10:34:29 +0000437 }
438
Dan Gohmanaae01f12010-02-19 19:32:49 +0000439 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000440 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000441 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
442 SmallVector<const SCEV *, 8> Ops;
443 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
444 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000445 const SCEV *Op = getExactSDiv(*I, RHS, SE,
446 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000447 if (!Op) return 0;
448 Ops.push_back(Op);
449 }
450 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000451 }
Dan Gohman572645c2010-02-12 10:34:29 +0000452 }
453
454 // Check for a multiply operand that we can pull RHS out of.
455 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
Dan Gohmanaae01f12010-02-19 19:32:49 +0000456 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000457 SmallVector<const SCEV *, 4> Ops;
458 bool Found = false;
459 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
460 I != E; ++I) {
461 if (!Found)
Dan Gohmanf09b7122010-02-19 19:35:48 +0000462 if (const SCEV *Q = getExactSDiv(*I, RHS, SE,
463 IgnoreSignificantBits)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000464 Ops.push_back(Q);
465 Found = true;
466 continue;
467 }
468 Ops.push_back(*I);
469 }
470 return Found ? SE.getMulExpr(Ops) : 0;
471 }
472
473 // Otherwise we don't know.
474 return 0;
475}
476
477/// ExtractImmediate - If S involves the addition of a constant integer value,
478/// return that integer value, and mutate S to point to a new SCEV with that
479/// value excluded.
480static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
481 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
482 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000483 S = SE.getConstant(C->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000484 return C->getValue()->getSExtValue();
485 }
486 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
487 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
488 int64_t Result = ExtractImmediate(NewOps.front(), SE);
489 S = SE.getAddExpr(NewOps);
490 return Result;
491 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
492 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
493 int64_t Result = ExtractImmediate(NewOps.front(), SE);
494 S = SE.getAddRecExpr(NewOps, AR->getLoop());
495 return Result;
496 }
497 return 0;
498}
499
500/// ExtractSymbol - If S involves the addition of a GlobalValue address,
501/// return that symbol, and mutate S to point to a new SCEV with that
502/// value excluded.
503static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
504 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
505 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000506 S = SE.getConstant(GV->getType(), 0);
Dan Gohman572645c2010-02-12 10:34:29 +0000507 return GV;
508 }
509 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
510 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
511 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
512 S = SE.getAddExpr(NewOps);
513 return Result;
514 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
515 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
516 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
517 S = SE.getAddRecExpr(NewOps, AR->getLoop());
518 return Result;
519 }
520 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000521}
522
Dan Gohmanf284ce22009-02-18 00:08:39 +0000523/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000524/// specified value as an address.
525static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
526 bool isAddress = isa<LoadInst>(Inst);
527 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
528 if (SI->getOperand(1) == OperandVal)
529 isAddress = true;
530 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
531 // Addressing modes can also be folded into prefetches and a variety
532 // of intrinsics.
533 switch (II->getIntrinsicID()) {
534 default: break;
535 case Intrinsic::prefetch:
536 case Intrinsic::x86_sse2_loadu_dq:
537 case Intrinsic::x86_sse2_loadu_pd:
538 case Intrinsic::x86_sse_loadu_ps:
539 case Intrinsic::x86_sse_storeu_ps:
540 case Intrinsic::x86_sse2_storeu_pd:
541 case Intrinsic::x86_sse2_storeu_dq:
542 case Intrinsic::x86_sse2_storel_dq:
543 if (II->getOperand(1) == OperandVal)
544 isAddress = true;
545 break;
546 }
547 }
548 return isAddress;
549}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000550
Dan Gohman21e77222009-03-09 21:01:17 +0000551/// getAccessType - Return the type of the memory being accessed.
552static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000553 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000554 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000555 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000556 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
557 // Addressing modes can also be folded into prefetches and a variety
558 // of intrinsics.
559 switch (II->getIntrinsicID()) {
560 default: break;
561 case Intrinsic::x86_sse_storeu_ps:
562 case Intrinsic::x86_sse2_storeu_pd:
563 case Intrinsic::x86_sse2_storeu_dq:
564 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmana537bf82009-05-18 16:45:28 +0000565 AccessTy = II->getOperand(1)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000566 break;
567 }
568 }
Dan Gohman572645c2010-02-12 10:34:29 +0000569
570 // All pointers have the same requirements, so canonicalize them to an
571 // arbitrary pointer type to minimize variation.
572 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
573 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
574 PTy->getAddressSpace());
575
Dan Gohmana537bf82009-05-18 16:45:28 +0000576 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000577}
578
Dan Gohman572645c2010-02-12 10:34:29 +0000579/// DeleteTriviallyDeadInstructions - If any of the instructions is the
580/// specified set are trivially dead, delete them and see if this makes any of
581/// their operands subsequently dead.
582static bool
583DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
584 bool Changed = false;
585
586 while (!DeadInsts.empty()) {
587 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
588
589 if (I == 0 || !isInstructionTriviallyDead(I))
590 continue;
591
592 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
593 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
594 *OI = 0;
595 if (U->use_empty())
596 DeadInsts.push_back(U);
597 }
598
599 I->eraseFromParent();
600 Changed = true;
601 }
602
603 return Changed;
604}
605
Dan Gohman7979b722010-01-22 00:46:49 +0000606namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000607
Dan Gohman572645c2010-02-12 10:34:29 +0000608/// Cost - This class is used to measure and compare candidate formulae.
609class Cost {
610 /// TODO: Some of these could be merged. Also, a lexical ordering
611 /// isn't always optimal.
612 unsigned NumRegs;
613 unsigned AddRecCost;
614 unsigned NumIVMuls;
615 unsigned NumBaseAdds;
616 unsigned ImmCost;
617 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000618
Dan Gohman572645c2010-02-12 10:34:29 +0000619public:
620 Cost()
621 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
622 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000623
Dan Gohman572645c2010-02-12 10:34:29 +0000624 unsigned getNumRegs() const { return NumRegs; }
Dan Gohman7979b722010-01-22 00:46:49 +0000625
Dan Gohman572645c2010-02-12 10:34:29 +0000626 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000627
Dan Gohman572645c2010-02-12 10:34:29 +0000628 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000629
Dan Gohman572645c2010-02-12 10:34:29 +0000630 void RateFormula(const Formula &F,
631 SmallPtrSet<const SCEV *, 16> &Regs,
632 const DenseSet<const SCEV *> &VisitedRegs,
633 const Loop *L,
634 const SmallVectorImpl<int64_t> &Offsets,
635 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000636
Dan Gohman572645c2010-02-12 10:34:29 +0000637 void print(raw_ostream &OS) const;
638 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000639
Dan Gohman572645c2010-02-12 10:34:29 +0000640private:
641 void RateRegister(const SCEV *Reg,
642 SmallPtrSet<const SCEV *, 16> &Regs,
643 const Loop *L,
644 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000645 void RatePrimaryRegister(const SCEV *Reg,
646 SmallPtrSet<const SCEV *, 16> &Regs,
647 const Loop *L,
648 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000649};
650
651}
652
653/// RateRegister - Tally up interesting quantities from the given register.
654void Cost::RateRegister(const SCEV *Reg,
655 SmallPtrSet<const SCEV *, 16> &Regs,
656 const Loop *L,
657 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000658 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
659 if (AR->getLoop() == L)
660 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000661
Dan Gohman9214b822010-02-13 02:06:02 +0000662 // If this is an addrec for a loop that's already been visited by LSR,
663 // don't second-guess its addrec phi nodes. LSR isn't currently smart
664 // enough to reason about more than one loop at a time. Consider these
665 // registers free and leave them alone.
666 else if (L->contains(AR->getLoop()) ||
667 (!AR->getLoop()->contains(L) &&
668 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
669 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
670 PHINode *PN = dyn_cast<PHINode>(I); ++I)
671 if (SE.isSCEVable(PN->getType()) &&
672 (SE.getEffectiveSCEVType(PN->getType()) ==
673 SE.getEffectiveSCEVType(AR->getType())) &&
674 SE.getSCEV(PN) == AR)
675 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000676
Dan Gohman9214b822010-02-13 02:06:02 +0000677 // If this isn't one of the addrecs that the loop already has, it
678 // would require a costly new phi and add. TODO: This isn't
679 // precisely modeled right now.
680 ++NumBaseAdds;
681 if (!Regs.count(AR->getStart()))
Dan Gohman572645c2010-02-12 10:34:29 +0000682 RateRegister(AR->getStart(), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000683 }
Dan Gohman572645c2010-02-12 10:34:29 +0000684
Dan Gohman9214b822010-02-13 02:06:02 +0000685 // Add the step value register, if it needs one.
686 // TODO: The non-affine case isn't precisely modeled here.
687 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
688 if (!Regs.count(AR->getStart()))
689 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000690 }
Dan Gohman9214b822010-02-13 02:06:02 +0000691 ++NumRegs;
692
693 // Rough heuristic; favor registers which don't require extra setup
694 // instructions in the preheader.
695 if (!isa<SCEVUnknown>(Reg) &&
696 !isa<SCEVConstant>(Reg) &&
697 !(isa<SCEVAddRecExpr>(Reg) &&
698 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
699 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
700 ++SetupCost;
701}
702
703/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
704/// before, rate it.
705void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000706 SmallPtrSet<const SCEV *, 16> &Regs,
707 const Loop *L,
708 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000709 if (Regs.insert(Reg))
710 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000711}
712
713void Cost::RateFormula(const Formula &F,
714 SmallPtrSet<const SCEV *, 16> &Regs,
715 const DenseSet<const SCEV *> &VisitedRegs,
716 const Loop *L,
717 const SmallVectorImpl<int64_t> &Offsets,
718 ScalarEvolution &SE, DominatorTree &DT) {
719 // Tally up the registers.
720 if (const SCEV *ScaledReg = F.ScaledReg) {
721 if (VisitedRegs.count(ScaledReg)) {
722 Loose();
723 return;
724 }
Dan Gohman9214b822010-02-13 02:06:02 +0000725 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000726 }
727 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
728 E = F.BaseRegs.end(); I != E; ++I) {
729 const SCEV *BaseReg = *I;
730 if (VisitedRegs.count(BaseReg)) {
731 Loose();
732 return;
733 }
Dan Gohman9214b822010-02-13 02:06:02 +0000734 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000735
736 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
737 BaseReg->hasComputableLoopEvolution(L);
738 }
739
740 if (F.BaseRegs.size() > 1)
741 NumBaseAdds += F.BaseRegs.size() - 1;
742
743 // Tally up the non-zero immediates.
744 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
745 E = Offsets.end(); I != E; ++I) {
746 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
747 if (F.AM.BaseGV)
748 ImmCost += 64; // Handle symbolic values conservatively.
749 // TODO: This should probably be the pointer size.
750 else if (Offset != 0)
751 ImmCost += APInt(64, Offset, true).getMinSignedBits();
752 }
753}
754
755/// Loose - Set this cost to a loosing value.
756void Cost::Loose() {
757 NumRegs = ~0u;
758 AddRecCost = ~0u;
759 NumIVMuls = ~0u;
760 NumBaseAdds = ~0u;
761 ImmCost = ~0u;
762 SetupCost = ~0u;
763}
764
765/// operator< - Choose the lower cost.
766bool Cost::operator<(const Cost &Other) const {
767 if (NumRegs != Other.NumRegs)
768 return NumRegs < Other.NumRegs;
769 if (AddRecCost != Other.AddRecCost)
770 return AddRecCost < Other.AddRecCost;
771 if (NumIVMuls != Other.NumIVMuls)
772 return NumIVMuls < Other.NumIVMuls;
773 if (NumBaseAdds != Other.NumBaseAdds)
774 return NumBaseAdds < Other.NumBaseAdds;
775 if (ImmCost != Other.ImmCost)
776 return ImmCost < Other.ImmCost;
777 if (SetupCost != Other.SetupCost)
778 return SetupCost < Other.SetupCost;
779 return false;
780}
781
782void Cost::print(raw_ostream &OS) const {
783 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
784 if (AddRecCost != 0)
785 OS << ", with addrec cost " << AddRecCost;
786 if (NumIVMuls != 0)
787 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
788 if (NumBaseAdds != 0)
789 OS << ", plus " << NumBaseAdds << " base add"
790 << (NumBaseAdds == 1 ? "" : "s");
791 if (ImmCost != 0)
792 OS << ", plus " << ImmCost << " imm cost";
793 if (SetupCost != 0)
794 OS << ", plus " << SetupCost << " setup cost";
795}
796
797void Cost::dump() const {
798 print(errs()); errs() << '\n';
799}
800
801namespace {
802
803/// LSRFixup - An operand value in an instruction which is to be replaced
804/// with some equivalent, possibly strength-reduced, replacement.
805struct LSRFixup {
806 /// UserInst - The instruction which will be updated.
807 Instruction *UserInst;
808
809 /// OperandValToReplace - The operand of the instruction which will
810 /// be replaced. The operand may be used more than once; every instance
811 /// will be replaced.
812 Value *OperandValToReplace;
813
Dan Gohman448db1c2010-04-07 22:27:08 +0000814 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman572645c2010-02-12 10:34:29 +0000815 /// induction variable, this variable is non-null and holds the loop
816 /// associated with the induction variable.
Dan Gohman448db1c2010-04-07 22:27:08 +0000817 PostIncLoopSet PostIncLoops;
Dan Gohman572645c2010-02-12 10:34:29 +0000818
819 /// LUIdx - The index of the LSRUse describing the expression which
820 /// this fixup needs, minus an offset (below).
821 size_t LUIdx;
822
823 /// Offset - A constant offset to be added to the LSRUse expression.
824 /// This allows multiple fixups to share the same LSRUse with different
825 /// offsets, for example in an unrolled loop.
826 int64_t Offset;
827
Dan Gohman448db1c2010-04-07 22:27:08 +0000828 bool isUseFullyOutsideLoop(const Loop *L) const;
829
Dan Gohman572645c2010-02-12 10:34:29 +0000830 LSRFixup();
831
832 void print(raw_ostream &OS) const;
833 void dump() const;
834};
835
836}
837
838LSRFixup::LSRFixup()
Dan Gohman448db1c2010-04-07 22:27:08 +0000839 : UserInst(0), OperandValToReplace(0),
Dan Gohman572645c2010-02-12 10:34:29 +0000840 LUIdx(~size_t(0)), Offset(0) {}
841
Dan Gohman448db1c2010-04-07 22:27:08 +0000842/// isUseFullyOutsideLoop - Test whether this fixup always uses its
843/// value outside of the given loop.
844bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
845 // PHI nodes use their value in their incoming blocks.
846 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
847 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
848 if (PN->getIncomingValue(i) == OperandValToReplace &&
849 L->contains(PN->getIncomingBlock(i)))
850 return false;
851 return true;
852 }
853
854 return !L->contains(UserInst);
855}
856
Dan Gohman572645c2010-02-12 10:34:29 +0000857void LSRFixup::print(raw_ostream &OS) const {
858 OS << "UserInst=";
859 // Store is common and interesting enough to be worth special-casing.
860 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
861 OS << "store ";
862 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
863 } else if (UserInst->getType()->isVoidTy())
864 OS << UserInst->getOpcodeName();
865 else
866 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
867
868 OS << ", OperandValToReplace=";
869 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
870
Dan Gohman448db1c2010-04-07 22:27:08 +0000871 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
872 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +0000873 OS << ", PostIncLoop=";
Dan Gohman448db1c2010-04-07 22:27:08 +0000874 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
Dan Gohman572645c2010-02-12 10:34:29 +0000875 }
876
877 if (LUIdx != ~size_t(0))
878 OS << ", LUIdx=" << LUIdx;
879
880 if (Offset != 0)
881 OS << ", Offset=" << Offset;
882}
883
884void LSRFixup::dump() const {
885 print(errs()); errs() << '\n';
886}
887
888namespace {
889
890/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
891/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
892struct UniquifierDenseMapInfo {
893 static SmallVector<const SCEV *, 2> getEmptyKey() {
894 SmallVector<const SCEV *, 2> V;
895 V.push_back(reinterpret_cast<const SCEV *>(-1));
896 return V;
897 }
898
899 static SmallVector<const SCEV *, 2> getTombstoneKey() {
900 SmallVector<const SCEV *, 2> V;
901 V.push_back(reinterpret_cast<const SCEV *>(-2));
902 return V;
903 }
904
905 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
906 unsigned Result = 0;
907 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
908 E = V.end(); I != E; ++I)
909 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
910 return Result;
911 }
912
913 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
914 const SmallVector<const SCEV *, 2> &RHS) {
915 return LHS == RHS;
916 }
917};
918
919/// LSRUse - This class holds the state that LSR keeps for each use in
920/// IVUsers, as well as uses invented by LSR itself. It includes information
921/// about what kinds of things can be folded into the user, information about
922/// the user itself, and information about how the use may be satisfied.
923/// TODO: Represent multiple users of the same expression in common?
924class LSRUse {
925 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
926
927public:
928 /// KindType - An enum for a kind of use, indicating what types of
929 /// scaled and immediate operands it might support.
930 enum KindType {
931 Basic, ///< A normal use, with no folding.
932 Special, ///< A special case of basic, allowing -1 scales.
933 Address, ///< An address use; folding according to TargetLowering
934 ICmpZero ///< An equality icmp with both operands folded into one.
935 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000936 };
Dan Gohman572645c2010-02-12 10:34:29 +0000937
938 KindType Kind;
939 const Type *AccessTy;
940
941 SmallVector<int64_t, 8> Offsets;
942 int64_t MinOffset;
943 int64_t MaxOffset;
944
945 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
946 /// LSRUse are outside of the loop, in which case some special-case heuristics
947 /// may be used.
948 bool AllFixupsOutsideLoop;
949
950 /// Formulae - A list of ways to build a value that can satisfy this user.
951 /// After the list is populated, one of these is selected heuristically and
952 /// used to formulate a replacement for OperandValToReplace in UserInst.
953 SmallVector<Formula, 12> Formulae;
954
955 /// Regs - The set of register candidates used by all formulae in this LSRUse.
956 SmallPtrSet<const SCEV *, 4> Regs;
957
958 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
959 MinOffset(INT64_MAX),
960 MaxOffset(INT64_MIN),
961 AllFixupsOutsideLoop(true) {}
962
Dan Gohmana2086b32010-05-19 23:43:12 +0000963 bool HasFormulaWithSameRegs(const Formula &F) const;
Dan Gohman454d26d2010-02-22 04:11:59 +0000964 bool InsertFormula(const Formula &F);
Dan Gohmand69d6282010-05-18 22:39:15 +0000965 void DeleteFormula(Formula &F);
Dan Gohmanb2df4332010-05-18 23:42:37 +0000966 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
Dan Gohman572645c2010-02-12 10:34:29 +0000967
968 void check() const;
969
970 void print(raw_ostream &OS) const;
971 void dump() const;
972};
973
Dan Gohmana2086b32010-05-19 23:43:12 +0000974/// HasFormula - Test whether this use as a formula which has the same
975/// registers as the given formula.
976bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
977 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
978 if (F.ScaledReg) Key.push_back(F.ScaledReg);
979 // Unstable sort by host order ok, because this is only used for uniquifying.
980 std::sort(Key.begin(), Key.end());
981 return Uniquifier.count(Key);
982}
983
Dan Gohman572645c2010-02-12 10:34:29 +0000984/// InsertFormula - If the given formula has not yet been inserted, add it to
985/// the list, and return true. Return false otherwise.
Dan Gohman454d26d2010-02-22 04:11:59 +0000986bool LSRUse::InsertFormula(const Formula &F) {
Dan Gohman572645c2010-02-12 10:34:29 +0000987 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
988 if (F.ScaledReg) Key.push_back(F.ScaledReg);
989 // Unstable sort by host order ok, because this is only used for uniquifying.
990 std::sort(Key.begin(), Key.end());
991
992 if (!Uniquifier.insert(Key).second)
993 return false;
994
995 // Using a register to hold the value of 0 is not profitable.
996 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
997 "Zero allocated in a scaled register!");
998#ifndef NDEBUG
999 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1000 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1001 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1002#endif
1003
1004 // Add the formula to the list.
1005 Formulae.push_back(F);
1006
1007 // Record registers now being used by this use.
1008 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1009 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1010
1011 return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001012}
1013
Dan Gohmand69d6282010-05-18 22:39:15 +00001014/// DeleteFormula - Remove the given formula from this use's list.
1015void LSRUse::DeleteFormula(Formula &F) {
1016 std::swap(F, Formulae.back());
1017 Formulae.pop_back();
Dan Gohmana2086b32010-05-19 23:43:12 +00001018 assert(!Formulae.empty() && "LSRUse has no formulae left!");
Dan Gohmand69d6282010-05-18 22:39:15 +00001019}
1020
Dan Gohmanb2df4332010-05-18 23:42:37 +00001021/// RecomputeRegs - Recompute the Regs field, and update RegUses.
1022void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1023 // Now that we've filtered out some formulae, recompute the Regs set.
1024 SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1025 Regs.clear();
1026 for (size_t FIdx = 0, NumForms = Formulae.size(); FIdx != NumForms; ++FIdx) {
1027 Formula &F = Formulae[FIdx];
1028 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1029 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1030 }
1031
1032 // Update the RegTracker.
1033 for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1034 E = OldRegs.end(); I != E; ++I)
1035 if (!Regs.count(*I))
1036 RegUses.DropRegister(*I, LUIdx);
1037}
1038
Dan Gohman572645c2010-02-12 10:34:29 +00001039void LSRUse::print(raw_ostream &OS) const {
1040 OS << "LSR Use: Kind=";
1041 switch (Kind) {
1042 case Basic: OS << "Basic"; break;
1043 case Special: OS << "Special"; break;
1044 case ICmpZero: OS << "ICmpZero"; break;
1045 case Address:
1046 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +00001047 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +00001048 OS << "pointer"; // the full pointer type could be really verbose
1049 else
1050 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +00001051 }
1052
Dan Gohman572645c2010-02-12 10:34:29 +00001053 OS << ", Offsets={";
1054 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1055 E = Offsets.end(); I != E; ++I) {
1056 OS << *I;
1057 if (next(I) != E)
1058 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +00001059 }
Dan Gohman572645c2010-02-12 10:34:29 +00001060 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +00001061
Dan Gohman572645c2010-02-12 10:34:29 +00001062 if (AllFixupsOutsideLoop)
1063 OS << ", all-fixups-outside-loop";
Dan Gohman7979b722010-01-22 00:46:49 +00001064}
1065
Dan Gohman572645c2010-02-12 10:34:29 +00001066void LSRUse::dump() const {
1067 print(errs()); errs() << '\n';
1068}
Dan Gohman7979b722010-01-22 00:46:49 +00001069
Dan Gohman572645c2010-02-12 10:34:29 +00001070/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1071/// be completely folded into the user instruction at isel time. This includes
1072/// address-mode folding and special icmp tricks.
1073static bool isLegalUse(const TargetLowering::AddrMode &AM,
1074 LSRUse::KindType Kind, const Type *AccessTy,
1075 const TargetLowering *TLI) {
1076 switch (Kind) {
1077 case LSRUse::Address:
1078 // If we have low-level target information, ask the target if it can
1079 // completely fold this address.
1080 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1081
1082 // Otherwise, just guess that reg+reg addressing is legal.
1083 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1084
1085 case LSRUse::ICmpZero:
1086 // There's not even a target hook for querying whether it would be legal to
1087 // fold a GV into an ICmp.
1088 if (AM.BaseGV)
1089 return false;
1090
1091 // ICmp only has two operands; don't allow more than two non-trivial parts.
1092 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1093 return false;
1094
1095 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1096 // putting the scaled register in the other operand of the icmp.
1097 if (AM.Scale != 0 && AM.Scale != -1)
1098 return false;
1099
1100 // If we have low-level target information, ask the target if it can fold an
1101 // integer immediate on an icmp.
1102 if (AM.BaseOffs != 0) {
1103 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1104 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001105 }
Dan Gohman572645c2010-02-12 10:34:29 +00001106
1107 return true;
1108
1109 case LSRUse::Basic:
1110 // Only handle single-register values.
1111 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1112
1113 case LSRUse::Special:
1114 // Only handle -1 scales, or no scale.
1115 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001116 }
1117
Dan Gohman7979b722010-01-22 00:46:49 +00001118 return false;
1119}
1120
Dan Gohman572645c2010-02-12 10:34:29 +00001121static bool isLegalUse(TargetLowering::AddrMode AM,
1122 int64_t MinOffset, int64_t MaxOffset,
1123 LSRUse::KindType Kind, const Type *AccessTy,
1124 const TargetLowering *TLI) {
1125 // Check for overflow.
1126 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1127 (MinOffset > 0))
1128 return false;
1129 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1130 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1131 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1132 // Check for overflow.
1133 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1134 (MaxOffset > 0))
1135 return false;
1136 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1137 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001138 }
Dan Gohman572645c2010-02-12 10:34:29 +00001139 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001140}
1141
Dan Gohman572645c2010-02-12 10:34:29 +00001142static bool isAlwaysFoldable(int64_t BaseOffs,
1143 GlobalValue *BaseGV,
1144 bool HasBaseReg,
1145 LSRUse::KindType Kind, const Type *AccessTy,
Dan Gohman454d26d2010-02-22 04:11:59 +00001146 const TargetLowering *TLI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001147 // Fast-path: zero is always foldable.
1148 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001149
Dan Gohman572645c2010-02-12 10:34:29 +00001150 // Conservatively, create an address with an immediate and a
1151 // base and a scale.
1152 TargetLowering::AddrMode AM;
1153 AM.BaseOffs = BaseOffs;
1154 AM.BaseGV = BaseGV;
1155 AM.HasBaseReg = HasBaseReg;
1156 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001157
Dan Gohmana2086b32010-05-19 23:43:12 +00001158 // Canonicalize a scale of 1 to a base register if the formula doesn't
1159 // already have a base register.
1160 if (!AM.HasBaseReg && AM.Scale == 1) {
1161 AM.Scale = 0;
1162 AM.HasBaseReg = true;
1163 }
1164
Dan Gohman572645c2010-02-12 10:34:29 +00001165 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001166}
1167
Dan Gohman572645c2010-02-12 10:34:29 +00001168static bool isAlwaysFoldable(const SCEV *S,
1169 int64_t MinOffset, int64_t MaxOffset,
1170 bool HasBaseReg,
1171 LSRUse::KindType Kind, const Type *AccessTy,
1172 const TargetLowering *TLI,
1173 ScalarEvolution &SE) {
1174 // Fast-path: zero is always foldable.
1175 if (S->isZero()) return true;
1176
1177 // Conservatively, create an address with an immediate and a
1178 // base and a scale.
1179 int64_t BaseOffs = ExtractImmediate(S, SE);
1180 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1181
1182 // If there's anything else involved, it's not foldable.
1183 if (!S->isZero()) return false;
1184
1185 // Fast-path: zero is always foldable.
1186 if (BaseOffs == 0 && !BaseGV) return true;
1187
1188 // Conservatively, create an address with an immediate and a
1189 // base and a scale.
1190 TargetLowering::AddrMode AM;
1191 AM.BaseOffs = BaseOffs;
1192 AM.BaseGV = BaseGV;
1193 AM.HasBaseReg = HasBaseReg;
1194 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1195
1196 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001197}
1198
Dan Gohman572645c2010-02-12 10:34:29 +00001199/// FormulaSorter - This class implements an ordering for formulae which sorts
1200/// the by their standalone cost.
1201class FormulaSorter {
1202 /// These two sets are kept empty, so that we compute standalone costs.
1203 DenseSet<const SCEV *> VisitedRegs;
1204 SmallPtrSet<const SCEV *, 16> Regs;
1205 Loop *L;
1206 LSRUse *LU;
1207 ScalarEvolution &SE;
1208 DominatorTree &DT;
1209
1210public:
1211 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1212 : L(l), LU(&lu), SE(se), DT(dt) {}
1213
1214 bool operator()(const Formula &A, const Formula &B) {
1215 Cost CostA;
1216 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1217 Regs.clear();
1218 Cost CostB;
1219 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1220 Regs.clear();
1221 return CostA < CostB;
1222 }
1223};
1224
1225/// LSRInstance - This class holds state for the main loop strength reduction
1226/// logic.
1227class LSRInstance {
1228 IVUsers &IU;
1229 ScalarEvolution &SE;
1230 DominatorTree &DT;
Dan Gohmane5f76872010-04-09 22:07:05 +00001231 LoopInfo &LI;
Dan Gohman572645c2010-02-12 10:34:29 +00001232 const TargetLowering *const TLI;
1233 Loop *const L;
1234 bool Changed;
1235
1236 /// IVIncInsertPos - This is the insert position that the current loop's
1237 /// induction variable increment should be placed. In simple loops, this is
1238 /// the latch block's terminator. But in more complicated cases, this is a
1239 /// position which will dominate all the in-loop post-increment users.
1240 Instruction *IVIncInsertPos;
1241
1242 /// Factors - Interesting factors between use strides.
1243 SmallSetVector<int64_t, 8> Factors;
1244
1245 /// Types - Interesting use types, to facilitate truncation reuse.
1246 SmallSetVector<const Type *, 4> Types;
1247
1248 /// Fixups - The list of operands which are to be replaced.
1249 SmallVector<LSRFixup, 16> Fixups;
1250
1251 /// Uses - The list of interesting uses.
1252 SmallVector<LSRUse, 16> Uses;
1253
1254 /// RegUses - Track which uses use which register candidates.
1255 RegUseTracker RegUses;
1256
1257 void OptimizeShadowIV();
1258 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1259 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1260 bool OptimizeLoopTermCond();
1261
1262 void CollectInterestingTypesAndFactors();
1263 void CollectFixupsAndInitialFormulae();
1264
1265 LSRFixup &getNewFixup() {
1266 Fixups.push_back(LSRFixup());
1267 return Fixups.back();
1268 }
1269
1270 // Support for sharing of LSRUses between LSRFixups.
1271 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1272 UseMapTy UseMap;
1273
1274 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
Dan Gohmana2086b32010-05-19 23:43:12 +00001275 bool HasBaseReg,
Dan Gohman572645c2010-02-12 10:34:29 +00001276 LSRUse::KindType Kind, const Type *AccessTy);
1277
1278 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1279 LSRUse::KindType Kind,
1280 const Type *AccessTy);
1281
Dan Gohmana2086b32010-05-19 23:43:12 +00001282 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1283
Dan Gohman572645c2010-02-12 10:34:29 +00001284public:
Dan Gohman454d26d2010-02-22 04:11:59 +00001285 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001286 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1287 void CountRegisters(const Formula &F, size_t LUIdx);
1288 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1289
1290 void CollectLoopInvariantFixupsAndFormulae();
1291
1292 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1293 unsigned Depth = 0);
1294 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1295 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1296 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1297 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1298 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1299 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1300 void GenerateCrossUseConstantOffsets();
1301 void GenerateAllReuseFormulae();
1302
1303 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmand079c302010-05-18 22:51:59 +00001304
1305 size_t EstimateSearchSpaceComplexity() const;
Dan Gohman572645c2010-02-12 10:34:29 +00001306 void NarrowSearchSpaceUsingHeuristics();
1307
1308 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1309 Cost &SolutionCost,
1310 SmallVectorImpl<const Formula *> &Workspace,
1311 const Cost &CurCost,
1312 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1313 DenseSet<const SCEV *> &VisitedRegs) const;
1314 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1315
Dan Gohmane5f76872010-04-09 22:07:05 +00001316 BasicBlock::iterator
1317 HoistInsertPosition(BasicBlock::iterator IP,
1318 const SmallVectorImpl<Instruction *> &Inputs) const;
1319 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1320 const LSRFixup &LF,
1321 const LSRUse &LU) const;
Dan Gohmand96eae82010-04-09 02:00:38 +00001322
Dan Gohman572645c2010-02-12 10:34:29 +00001323 Value *Expand(const LSRFixup &LF,
1324 const Formula &F,
Dan Gohman454d26d2010-02-22 04:11:59 +00001325 BasicBlock::iterator IP,
Dan Gohman572645c2010-02-12 10:34:29 +00001326 SCEVExpander &Rewriter,
Dan Gohman454d26d2010-02-22 04:11:59 +00001327 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001328 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1329 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001330 SCEVExpander &Rewriter,
1331 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001332 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001333 void Rewrite(const LSRFixup &LF,
1334 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00001335 SCEVExpander &Rewriter,
1336 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00001337 Pass *P) const;
1338 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1339 Pass *P);
1340
1341 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1342
1343 bool getChanged() const { return Changed; }
1344
1345 void print_factors_and_types(raw_ostream &OS) const;
1346 void print_fixups(raw_ostream &OS) const;
1347 void print_uses(raw_ostream &OS) const;
1348 void print(raw_ostream &OS) const;
1349 void dump() const;
1350};
1351
1352}
1353
1354/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001355/// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00001356void LSRInstance::OptimizeShadowIV() {
1357 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1358 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1359 return;
1360
1361 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1362 UI != E; /* empty */) {
1363 IVUsers::const_iterator CandidateUI = UI;
1364 ++UI;
1365 Instruction *ShadowUse = CandidateUI->getUser();
1366 const Type *DestTy = NULL;
1367
1368 /* If shadow use is a int->float cast then insert a second IV
1369 to eliminate this cast.
1370
1371 for (unsigned i = 0; i < n; ++i)
1372 foo((double)i);
1373
1374 is transformed into
1375
1376 double d = 0.0;
1377 for (unsigned i = 0; i < n; ++i, ++d)
1378 foo(d);
1379 */
1380 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1381 DestTy = UCast->getDestTy();
1382 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1383 DestTy = SCast->getDestTy();
1384 if (!DestTy) continue;
1385
1386 if (TLI) {
1387 // If target does not support DestTy natively then do not apply
1388 // this transformation.
1389 EVT DVT = TLI->getValueType(DestTy);
1390 if (!TLI->isTypeLegal(DVT)) continue;
1391 }
1392
1393 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1394 if (!PH) continue;
1395 if (PH->getNumIncomingValues() != 2) continue;
1396
1397 const Type *SrcTy = PH->getType();
1398 int Mantissa = DestTy->getFPMantissaWidth();
1399 if (Mantissa == -1) continue;
1400 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1401 continue;
1402
1403 unsigned Entry, Latch;
1404 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1405 Entry = 0;
1406 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001407 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001408 Entry = 1;
1409 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001410 }
Dan Gohman7979b722010-01-22 00:46:49 +00001411
Dan Gohman572645c2010-02-12 10:34:29 +00001412 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1413 if (!Init) continue;
1414 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001415
Dan Gohman572645c2010-02-12 10:34:29 +00001416 BinaryOperator *Incr =
1417 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1418 if (!Incr) continue;
1419 if (Incr->getOpcode() != Instruction::Add
1420 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001421 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001422
Dan Gohman572645c2010-02-12 10:34:29 +00001423 /* Initialize new IV, double d = 0.0 in above example. */
1424 ConstantInt *C = NULL;
1425 if (Incr->getOperand(0) == PH)
1426 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1427 else if (Incr->getOperand(1) == PH)
1428 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001429 else
Dan Gohman7979b722010-01-22 00:46:49 +00001430 continue;
1431
Dan Gohman572645c2010-02-12 10:34:29 +00001432 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001433
Dan Gohman572645c2010-02-12 10:34:29 +00001434 // Ignore negative constants, as the code below doesn't handle them
1435 // correctly. TODO: Remove this restriction.
1436 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001437
Dan Gohman572645c2010-02-12 10:34:29 +00001438 /* Add new PHINode. */
1439 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001440
Dan Gohman572645c2010-02-12 10:34:29 +00001441 /* create new increment. '++d' in above example. */
1442 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1443 BinaryOperator *NewIncr =
1444 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1445 Instruction::FAdd : Instruction::FSub,
1446 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001447
Dan Gohman572645c2010-02-12 10:34:29 +00001448 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1449 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001450
Dan Gohman572645c2010-02-12 10:34:29 +00001451 /* Remove cast operation */
1452 ShadowUse->replaceAllUsesWith(NewPH);
1453 ShadowUse->eraseFromParent();
1454 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001455 }
1456}
1457
1458/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1459/// set the IV user and stride information and return true, otherwise return
1460/// false.
Dan Gohman572645c2010-02-12 10:34:29 +00001461bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1462 IVStrideUse *&CondUse) {
1463 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1464 if (UI->getUser() == Cond) {
1465 // NOTE: we could handle setcc instructions with multiple uses here, but
1466 // InstCombine does it as well for simple uses, it's not clear that it
1467 // occurs enough in real life to handle.
1468 CondUse = UI;
1469 return true;
1470 }
Dan Gohman7979b722010-01-22 00:46:49 +00001471 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001472}
1473
Dan Gohman7979b722010-01-22 00:46:49 +00001474/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1475/// a max computation.
1476///
1477/// This is a narrow solution to a specific, but acute, problem. For loops
1478/// like this:
1479///
1480/// i = 0;
1481/// do {
1482/// p[i] = 0.0;
1483/// } while (++i < n);
1484///
1485/// the trip count isn't just 'n', because 'n' might not be positive. And
1486/// unfortunately this can come up even for loops where the user didn't use
1487/// a C do-while loop. For example, seemingly well-behaved top-test loops
1488/// will commonly be lowered like this:
1489//
1490/// if (n > 0) {
1491/// i = 0;
1492/// do {
1493/// p[i] = 0.0;
1494/// } while (++i < n);
1495/// }
1496///
1497/// and then it's possible for subsequent optimization to obscure the if
1498/// test in such a way that indvars can't find it.
1499///
1500/// When indvars can't find the if test in loops like this, it creates a
1501/// max expression, which allows it to give the loop a canonical
1502/// induction variable:
1503///
1504/// i = 0;
1505/// max = n < 1 ? 1 : n;
1506/// do {
1507/// p[i] = 0.0;
1508/// } while (++i != max);
1509///
1510/// Canonical induction variables are necessary because the loop passes
1511/// are designed around them. The most obvious example of this is the
1512/// LoopInfo analysis, which doesn't remember trip count values. It
1513/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001514/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001515/// the loop has a canonical induction variable.
1516///
1517/// However, when it comes time to generate code, the maximum operation
1518/// can be quite costly, especially if it's inside of an outer loop.
1519///
1520/// This function solves this problem by detecting this type of loop and
1521/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1522/// the instructions for the maximum computation.
1523///
Dan Gohman572645c2010-02-12 10:34:29 +00001524ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001525 // Check that the loop matches the pattern we're looking for.
1526 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1527 Cond->getPredicate() != CmpInst::ICMP_NE)
1528 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001529
Dan Gohman7979b722010-01-22 00:46:49 +00001530 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1531 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001532
Dan Gohman572645c2010-02-12 10:34:29 +00001533 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001534 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1535 return Cond;
Dan Gohmandeff6212010-05-03 22:09:21 +00001536 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001537
Dan Gohman7979b722010-01-22 00:46:49 +00001538 // Add one to the backedge-taken count to get the trip count.
Dan Gohman572645c2010-02-12 10:34:29 +00001539 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
Dan Gohman1d367982010-04-24 03:13:44 +00001540 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001541
Dan Gohman1d367982010-04-24 03:13:44 +00001542 // Check for a max calculation that matches the pattern. There's no check
1543 // for ICMP_ULE here because the comparison would be with zero, which
1544 // isn't interesting.
1545 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1546 const SCEVNAryExpr *Max = 0;
1547 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1548 Pred = ICmpInst::ICMP_SLE;
1549 Max = S;
1550 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1551 Pred = ICmpInst::ICMP_SLT;
1552 Max = S;
1553 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1554 Pred = ICmpInst::ICMP_ULT;
1555 Max = U;
1556 } else {
1557 // No match; bail.
Dan Gohman7979b722010-01-22 00:46:49 +00001558 return Cond;
Dan Gohman1d367982010-04-24 03:13:44 +00001559 }
Dan Gohman7979b722010-01-22 00:46:49 +00001560
1561 // To handle a max with more than two operands, this optimization would
1562 // require additional checking and setup.
1563 if (Max->getNumOperands() != 2)
1564 return Cond;
1565
1566 const SCEV *MaxLHS = Max->getOperand(0);
1567 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman1d367982010-04-24 03:13:44 +00001568
1569 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1570 // for a comparison with 1. For <= and >=, a comparison with zero.
1571 if (!MaxLHS ||
1572 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1573 return Cond;
1574
Dan Gohman7979b722010-01-22 00:46:49 +00001575 // Check the relevant induction variable for conformance to
1576 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001577 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001578 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1579 if (!AR || !AR->isAffine() ||
1580 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001581 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001582 return Cond;
1583
1584 assert(AR->getLoop() == L &&
1585 "Loop condition operand is an addrec in a different loop!");
1586
1587 // Check the right operand of the select, and remember it, as it will
1588 // be used in the new comparison instruction.
1589 Value *NewRHS = 0;
Dan Gohman1d367982010-04-24 03:13:44 +00001590 if (ICmpInst::isTrueWhenEqual(Pred)) {
1591 // Look for n+1, and grab n.
1592 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1593 if (isa<ConstantInt>(BO->getOperand(1)) &&
1594 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1595 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1596 NewRHS = BO->getOperand(0);
1597 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1598 if (isa<ConstantInt>(BO->getOperand(1)) &&
1599 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1600 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1601 NewRHS = BO->getOperand(0);
1602 if (!NewRHS)
1603 return Cond;
1604 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001605 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001606 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001607 NewRHS = Sel->getOperand(2);
Dan Gohman1d367982010-04-24 03:13:44 +00001608 else
1609 llvm_unreachable("Max doesn't match expected pattern!");
Dan Gohman7979b722010-01-22 00:46:49 +00001610
1611 // Determine the new comparison opcode. It may be signed or unsigned,
1612 // and the original comparison may be either equality or inequality.
Dan Gohman7979b722010-01-22 00:46:49 +00001613 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1614 Pred = CmpInst::getInversePredicate(Pred);
1615
1616 // Ok, everything looks ok to change the condition into an SLT or SGE and
1617 // delete the max calculation.
1618 ICmpInst *NewCond =
1619 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1620
1621 // Delete the max calculation instructions.
1622 Cond->replaceAllUsesWith(NewCond);
1623 CondUse->setUser(NewCond);
1624 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1625 Cond->eraseFromParent();
1626 Sel->eraseFromParent();
1627 if (Cmp->use_empty())
1628 Cmp->eraseFromParent();
1629 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001630}
1631
Jim Grosbach56a1f802009-11-17 17:53:56 +00001632/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001633/// postinc iv when possible.
Dan Gohman572645c2010-02-12 10:34:29 +00001634bool
1635LSRInstance::OptimizeLoopTermCond() {
1636 SmallPtrSet<Instruction *, 4> PostIncs;
1637
Evan Cheng586f69a2009-11-12 07:35:05 +00001638 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001639 SmallVector<BasicBlock*, 8> ExitingBlocks;
1640 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001641
Evan Cheng076e0852009-11-17 18:10:11 +00001642 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1643 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001644
Dan Gohman572645c2010-02-12 10:34:29 +00001645 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001646 // can, we want to change it to use a post-incremented version of its
1647 // induction variable, to allow coalescing the live ranges for the IV into
1648 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001649
Evan Cheng076e0852009-11-17 18:10:11 +00001650 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1651 if (!TermBr)
1652 continue;
1653 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1654 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1655 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001656
Evan Cheng076e0852009-11-17 18:10:11 +00001657 // Search IVUsesByStride to find Cond's IVUse if there is one.
1658 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001659 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001660 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001661 continue;
1662
Evan Cheng076e0852009-11-17 18:10:11 +00001663 // If the trip count is computed in terms of a max (due to ScalarEvolution
1664 // being unable to find a sufficient guard, for example), change the loop
1665 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001666 // One consequence of doing this now is that it disrupts the count-down
1667 // optimization. That's not always a bad thing though, because in such
1668 // cases it may still be worthwhile to avoid a max.
1669 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001670
Dan Gohman572645c2010-02-12 10:34:29 +00001671 // If this exiting block dominates the latch block, it may also use
1672 // the post-inc value if it won't be shared with other uses.
1673 // Check for dominance.
1674 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001675 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001676
Dan Gohman572645c2010-02-12 10:34:29 +00001677 // Conservatively avoid trying to use the post-inc value in non-latch
1678 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001679 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001680 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1681 // Test if the use is reachable from the exiting block. This dominator
1682 // query is a conservative approximation of reachability.
1683 if (&*UI != CondUse &&
1684 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1685 // Conservatively assume there may be reuse if the quotient of their
1686 // strides could be a legal scale.
Dan Gohmanc0564542010-04-19 21:48:58 +00001687 const SCEV *A = IU.getStride(*CondUse, L);
1688 const SCEV *B = IU.getStride(*UI, L);
Dan Gohman448db1c2010-04-07 22:27:08 +00001689 if (!A || !B) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001690 if (SE.getTypeSizeInBits(A->getType()) !=
1691 SE.getTypeSizeInBits(B->getType())) {
1692 if (SE.getTypeSizeInBits(A->getType()) >
1693 SE.getTypeSizeInBits(B->getType()))
1694 B = SE.getSignExtendExpr(B, A->getType());
1695 else
1696 A = SE.getSignExtendExpr(A, B->getType());
1697 }
1698 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001699 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001700 // Stride of one or negative one can have reuse with non-addresses.
1701 if (D->getValue()->isOne() ||
1702 D->getValue()->isAllOnesValue())
1703 goto decline_post_inc;
1704 // Avoid weird situations.
1705 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1706 D->getValue()->getValue().isMinSignedValue())
1707 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001708 // Without TLI, assume that any stride might be valid, and so any
1709 // use might be shared.
1710 if (!TLI)
1711 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001712 // Check for possible scaled-address reuse.
1713 const Type *AccessTy = getAccessType(UI->getUser());
1714 TargetLowering::AddrMode AM;
1715 AM.Scale = D->getValue()->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001716 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001717 goto decline_post_inc;
1718 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001719 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001720 goto decline_post_inc;
1721 }
1722 }
1723
David Greene63c94632009-12-23 22:58:38 +00001724 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001725 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001726
1727 // It's possible for the setcc instruction to be anywhere in the loop, and
1728 // possible for it to have multiple users. If it is not immediately before
1729 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001730 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1731 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001732 Cond->moveBefore(TermBr);
1733 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001734 // Clone the terminating condition and insert into the loopend.
1735 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001736 Cond = cast<ICmpInst>(Cond->clone());
1737 Cond->setName(L->getHeader()->getName() + ".termcond");
1738 ExitingBlock->getInstList().insert(TermBr, Cond);
1739
1740 // Clone the IVUse, as the old use still exists!
Dan Gohmanc0564542010-04-19 21:48:58 +00001741 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman572645c2010-02-12 10:34:29 +00001742 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001743 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001744 }
1745
Evan Cheng076e0852009-11-17 18:10:11 +00001746 // If we get to here, we know that we can transform the setcc instruction to
1747 // use the post-incremented version of the IV, allowing us to coalesce the
1748 // live ranges for the IV correctly.
Dan Gohman448db1c2010-04-07 22:27:08 +00001749 CondUse->transformToPostInc(L);
Evan Cheng076e0852009-11-17 18:10:11 +00001750 Changed = true;
1751
Dan Gohman572645c2010-02-12 10:34:29 +00001752 PostIncs.insert(Cond);
1753 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001754 }
Dan Gohman572645c2010-02-12 10:34:29 +00001755
1756 // Determine an insertion point for the loop induction variable increment. It
1757 // must dominate all the post-inc comparisons we just set up, and it must
1758 // dominate the loop latch edge.
1759 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1760 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1761 E = PostIncs.end(); I != E; ++I) {
1762 BasicBlock *BB =
1763 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1764 (*I)->getParent());
1765 if (BB == (*I)->getParent())
1766 IVIncInsertPos = *I;
1767 else if (BB != IVIncInsertPos->getParent())
1768 IVIncInsertPos = BB->getTerminator();
1769 }
1770
1771 return Changed;
Dan Gohmana10756e2010-01-21 02:09:26 +00001772}
1773
Dan Gohman572645c2010-02-12 10:34:29 +00001774bool
1775LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
Dan Gohmana2086b32010-05-19 23:43:12 +00001776 bool HasBaseReg,
Dan Gohman572645c2010-02-12 10:34:29 +00001777 LSRUse::KindType Kind, const Type *AccessTy) {
1778 int64_t NewMinOffset = LU.MinOffset;
1779 int64_t NewMaxOffset = LU.MaxOffset;
1780 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001781
Dan Gohman572645c2010-02-12 10:34:29 +00001782 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1783 // something conservative, however this can pessimize in the case that one of
1784 // the uses will have all its uses outside the loop, for example.
1785 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001786 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001787 // Conservatively assume HasBaseReg is true for now.
1788 if (NewOffset < LU.MinOffset) {
Dan Gohmana2086b32010-05-19 23:43:12 +00001789 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001790 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001791 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001792 NewMinOffset = NewOffset;
1793 } else if (NewOffset > LU.MaxOffset) {
Dan Gohmana2086b32010-05-19 23:43:12 +00001794 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, HasBaseReg,
Dan Gohman454d26d2010-02-22 04:11:59 +00001795 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001796 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001797 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001798 }
Dan Gohman572645c2010-02-12 10:34:29 +00001799 // Check for a mismatched access type, and fall back conservatively as needed.
1800 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1801 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001802
Dan Gohman572645c2010-02-12 10:34:29 +00001803 // Update the use.
1804 LU.MinOffset = NewMinOffset;
1805 LU.MaxOffset = NewMaxOffset;
1806 LU.AccessTy = NewAccessTy;
1807 if (NewOffset != LU.Offsets.back())
1808 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001809 return true;
1810}
1811
Dan Gohman572645c2010-02-12 10:34:29 +00001812/// getUse - Return an LSRUse index and an offset value for a fixup which
1813/// needs the given expression, with the given kind and optional access type.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001814/// Either reuse an existing use or create a new one, as needed.
Dan Gohman572645c2010-02-12 10:34:29 +00001815std::pair<size_t, int64_t>
1816LSRInstance::getUse(const SCEV *&Expr,
1817 LSRUse::KindType Kind, const Type *AccessTy) {
1818 const SCEV *Copy = Expr;
1819 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001820
Dan Gohman572645c2010-02-12 10:34:29 +00001821 // Basic uses can't accept any offset, for example.
Dan Gohman454d26d2010-02-22 04:11:59 +00001822 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
Dan Gohman572645c2010-02-12 10:34:29 +00001823 Expr = Copy;
1824 Offset = 0;
1825 }
1826
1827 std::pair<UseMapTy::iterator, bool> P =
1828 UseMap.insert(std::make_pair(Expr, 0));
1829 if (!P.second) {
1830 // A use already existed with this base.
1831 size_t LUIdx = P.first->second;
1832 LSRUse &LU = Uses[LUIdx];
Dan Gohmana2086b32010-05-19 23:43:12 +00001833 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001834 // Reuse this use.
1835 return std::make_pair(LUIdx, Offset);
1836 }
1837
1838 // Create a new use.
1839 size_t LUIdx = Uses.size();
1840 P.first->second = LUIdx;
1841 Uses.push_back(LSRUse(Kind, AccessTy));
1842 LSRUse &LU = Uses[LUIdx];
1843
1844 // We don't need to track redundant offsets, but we don't need to go out
1845 // of our way here to avoid them.
1846 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1847 LU.Offsets.push_back(Offset);
1848
1849 LU.MinOffset = Offset;
1850 LU.MaxOffset = Offset;
1851 return std::make_pair(LUIdx, Offset);
1852}
1853
Dan Gohmana2086b32010-05-19 23:43:12 +00001854/// FindUseWithFormula - Look for a use distinct from OrigLU which is has
1855/// a formula that has the same registers as the given formula.
1856LSRUse *
1857LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
1858 const LSRUse &OrigLU) {
1859 // Search all uses for the formula. This could be more clever. Ignore
1860 // ICmpZero uses because they may contain formulae generated by
1861 // GenerateICmpZeroScales, in which case adding fixup offsets may
1862 // be invalid.
1863 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
1864 LSRUse &LU = Uses[LUIdx];
1865 if (&LU != &OrigLU &&
1866 LU.Kind != LSRUse::ICmpZero &&
1867 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
1868 LU.HasFormulaWithSameRegs(OrigF)) {
1869 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
1870 FIdx != NumForms; ++FIdx) {
1871 Formula &F = LU.Formulae[FIdx];
1872 if (F.BaseRegs == OrigF.BaseRegs &&
1873 F.ScaledReg == OrigF.ScaledReg &&
1874 F.AM.BaseGV == OrigF.AM.BaseGV &&
1875 F.AM.Scale == OrigF.AM.Scale &&
1876 LU.Kind) {
1877 if (F.AM.BaseOffs == 0)
1878 return &LU;
1879 break;
1880 }
1881 }
1882 }
1883 }
1884
1885 return 0;
1886}
1887
Dan Gohman572645c2010-02-12 10:34:29 +00001888void LSRInstance::CollectInterestingTypesAndFactors() {
1889 SmallSetVector<const SCEV *, 4> Strides;
1890
Dan Gohman1b7bf182010-02-19 00:05:23 +00001891 // Collect interesting types and strides.
Dan Gohman448db1c2010-04-07 22:27:08 +00001892 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00001893 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohmanc0564542010-04-19 21:48:58 +00001894 const SCEV *Expr = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00001895
1896 // Collect interesting types.
Dan Gohman448db1c2010-04-07 22:27:08 +00001897 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman572645c2010-02-12 10:34:29 +00001898
Dan Gohman448db1c2010-04-07 22:27:08 +00001899 // Add strides for mentioned loops.
1900 Worklist.push_back(Expr);
1901 do {
1902 const SCEV *S = Worklist.pop_back_val();
1903 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1904 Strides.insert(AR->getStepRecurrence(SE));
1905 Worklist.push_back(AR->getStart());
1906 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1907 Worklist.insert(Worklist.end(), Add->op_begin(), Add->op_end());
1908 }
1909 } while (!Worklist.empty());
Dan Gohman1b7bf182010-02-19 00:05:23 +00001910 }
1911
1912 // Compute interesting factors from the set of interesting strides.
1913 for (SmallSetVector<const SCEV *, 4>::const_iterator
1914 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00001915 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Dan Gohman1b7bf182010-02-19 00:05:23 +00001916 next(I); NewStrideIter != E; ++NewStrideIter) {
1917 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00001918 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00001919
1920 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1921 SE.getTypeSizeInBits(NewStride->getType())) {
1922 if (SE.getTypeSizeInBits(OldStride->getType()) >
1923 SE.getTypeSizeInBits(NewStride->getType()))
1924 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1925 else
1926 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1927 }
1928 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001929 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1930 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001931 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1932 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1933 } else if (const SCEVConstant *Factor =
Dan Gohman454d26d2010-02-22 04:11:59 +00001934 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
1935 NewStride,
Dan Gohmanf09b7122010-02-19 19:35:48 +00001936 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001937 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1938 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1939 }
1940 }
Dan Gohman572645c2010-02-12 10:34:29 +00001941
1942 // If all uses use the same type, don't bother looking for truncation-based
1943 // reuse.
1944 if (Types.size() == 1)
1945 Types.clear();
1946
1947 DEBUG(print_factors_and_types(dbgs()));
1948}
1949
1950void LSRInstance::CollectFixupsAndInitialFormulae() {
1951 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1952 // Record the uses.
1953 LSRFixup &LF = getNewFixup();
1954 LF.UserInst = UI->getUser();
1955 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohman448db1c2010-04-07 22:27:08 +00001956 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman572645c2010-02-12 10:34:29 +00001957
1958 LSRUse::KindType Kind = LSRUse::Basic;
1959 const Type *AccessTy = 0;
1960 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1961 Kind = LSRUse::Address;
1962 AccessTy = getAccessType(LF.UserInst);
1963 }
1964
Dan Gohmanc0564542010-04-19 21:48:58 +00001965 const SCEV *S = IU.getExpr(*UI);
Dan Gohman572645c2010-02-12 10:34:29 +00001966
1967 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1968 // (N - i == 0), and this allows (N - i) to be the expression that we work
1969 // with rather than just N or i, so we can consider the register
1970 // requirements for both N and i at the same time. Limiting this code to
1971 // equality icmps is not a problem because all interesting loops use
1972 // equality icmps, thanks to IndVarSimplify.
1973 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1974 if (CI->isEquality()) {
1975 // Swap the operands if needed to put the OperandValToReplace on the
1976 // left, for consistency.
1977 Value *NV = CI->getOperand(1);
1978 if (NV == LF.OperandValToReplace) {
1979 CI->setOperand(1, CI->getOperand(0));
1980 CI->setOperand(0, NV);
1981 }
1982
1983 // x == y --> x - y == 0
1984 const SCEV *N = SE.getSCEV(NV);
1985 if (N->isLoopInvariant(L)) {
1986 Kind = LSRUse::ICmpZero;
1987 S = SE.getMinusSCEV(N, S);
1988 }
1989
1990 // -1 and the negations of all interesting strides (except the negation
1991 // of -1) are now also interesting.
1992 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1993 if (Factors[i] != -1)
1994 Factors.insert(-(uint64_t)Factors[i]);
1995 Factors.insert(-1);
1996 }
1997
1998 // Set up the initial formula for this use.
1999 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
2000 LF.LUIdx = P.first;
2001 LF.Offset = P.second;
2002 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002003 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00002004
2005 // If this is the first use of this LSRUse, give it a formula.
2006 if (LU.Formulae.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002007 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00002008 CountRegisters(LU.Formulae.back(), LF.LUIdx);
2009 }
2010 }
2011
2012 DEBUG(print_fixups(dbgs()));
2013}
2014
2015void
Dan Gohman454d26d2010-02-22 04:11:59 +00002016LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Dan Gohman572645c2010-02-12 10:34:29 +00002017 Formula F;
2018 F.InitialMatch(S, L, SE, DT);
2019 bool Inserted = InsertFormula(LU, LUIdx, F);
2020 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
2021}
2022
2023void
2024LSRInstance::InsertSupplementalFormula(const SCEV *S,
2025 LSRUse &LU, size_t LUIdx) {
2026 Formula F;
2027 F.BaseRegs.push_back(S);
2028 F.AM.HasBaseReg = true;
2029 bool Inserted = InsertFormula(LU, LUIdx, F);
2030 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
2031}
2032
2033/// CountRegisters - Note which registers are used by the given formula,
2034/// updating RegUses.
2035void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
2036 if (F.ScaledReg)
2037 RegUses.CountRegister(F.ScaledReg, LUIdx);
2038 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2039 E = F.BaseRegs.end(); I != E; ++I)
2040 RegUses.CountRegister(*I, LUIdx);
2041}
2042
2043/// InsertFormula - If the given formula has not yet been inserted, add it to
2044/// the list, and return true. Return false otherwise.
2045bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Dan Gohman454d26d2010-02-22 04:11:59 +00002046 if (!LU.InsertFormula(F))
Dan Gohman572645c2010-02-12 10:34:29 +00002047 return false;
2048
2049 CountRegisters(F, LUIdx);
2050 return true;
2051}
2052
2053/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
2054/// loop-invariant values which we're tracking. These other uses will pin these
2055/// values in registers, making them less profitable for elimination.
2056/// TODO: This currently misses non-constant addrec step registers.
2057/// TODO: Should this give more weight to users inside the loop?
2058void
2059LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
2060 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
2061 SmallPtrSet<const SCEV *, 8> Inserted;
2062
2063 while (!Worklist.empty()) {
2064 const SCEV *S = Worklist.pop_back_val();
2065
2066 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
2067 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
2068 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2069 Worklist.push_back(C->getOperand());
2070 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2071 Worklist.push_back(D->getLHS());
2072 Worklist.push_back(D->getRHS());
2073 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2074 if (!Inserted.insert(U)) continue;
2075 const Value *V = U->getValue();
2076 if (const Instruction *Inst = dyn_cast<Instruction>(V))
2077 if (L->contains(Inst)) continue;
Gabor Greif60ad7812010-03-25 23:06:16 +00002078 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
Dan Gohman572645c2010-02-12 10:34:29 +00002079 UI != UE; ++UI) {
2080 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2081 // Ignore non-instructions.
2082 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00002083 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002084 // Ignore instructions in other functions (as can happen with
2085 // Constants).
2086 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00002087 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002088 // Ignore instructions not dominated by the loop.
2089 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2090 UserInst->getParent() :
2091 cast<PHINode>(UserInst)->getIncomingBlock(
2092 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2093 if (!DT.dominates(L->getHeader(), UseBB))
2094 continue;
2095 // Ignore uses which are part of other SCEV expressions, to avoid
2096 // analyzing them multiple times.
Dan Gohman4a2a6832010-04-09 19:12:34 +00002097 if (SE.isSCEVable(UserInst->getType())) {
2098 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2099 // If the user is a no-op, look through to its uses.
2100 if (!isa<SCEVUnknown>(UserS))
2101 continue;
2102 if (UserS == U) {
2103 Worklist.push_back(
2104 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2105 continue;
2106 }
2107 }
Dan Gohman572645c2010-02-12 10:34:29 +00002108 // Ignore icmp instructions which are already being analyzed.
2109 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2110 unsigned OtherIdx = !UI.getOperandNo();
2111 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
2112 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
2113 continue;
2114 }
2115
2116 LSRFixup &LF = getNewFixup();
2117 LF.UserInst = const_cast<Instruction *>(UserInst);
2118 LF.OperandValToReplace = UI.getUse();
2119 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2120 LF.LUIdx = P.first;
2121 LF.Offset = P.second;
2122 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00002123 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00002124 InsertSupplementalFormula(U, LU, LF.LUIdx);
2125 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2126 break;
2127 }
2128 }
2129 }
2130}
2131
2132/// CollectSubexprs - Split S into subexpressions which can be pulled out into
2133/// separate registers. If C is non-null, multiply each subexpression by C.
2134static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2135 SmallVectorImpl<const SCEV *> &Ops,
2136 ScalarEvolution &SE) {
2137 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2138 // Break out add operands.
2139 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2140 I != E; ++I)
2141 CollectSubexprs(*I, C, Ops, SE);
2142 return;
2143 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2144 // Split a non-zero base out of an addrec.
2145 if (!AR->getStart()->isZero()) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002146 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman572645c2010-02-12 10:34:29 +00002147 AR->getStepRecurrence(SE),
2148 AR->getLoop()), C, Ops, SE);
Dan Gohman68d6da12010-02-12 19:35:25 +00002149 CollectSubexprs(AR->getStart(), C, Ops, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002150 return;
2151 }
2152 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2153 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2154 if (Mul->getNumOperands() == 2)
2155 if (const SCEVConstant *Op0 =
2156 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2157 CollectSubexprs(Mul->getOperand(1),
2158 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2159 Ops, SE);
2160 return;
2161 }
2162 }
2163
2164 // Otherwise use the value itself.
2165 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2166}
2167
2168/// GenerateReassociations - Split out subexpressions from adds and the bases of
2169/// addrecs.
2170void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2171 Formula Base,
2172 unsigned Depth) {
2173 // Arbitrarily cap recursion to protect compile time.
2174 if (Depth >= 3) return;
2175
2176 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2177 const SCEV *BaseReg = Base.BaseRegs[i];
2178
2179 SmallVector<const SCEV *, 8> AddOps;
2180 CollectSubexprs(BaseReg, 0, AddOps, SE);
2181 if (AddOps.size() == 1) continue;
2182
2183 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2184 JE = AddOps.end(); J != JE; ++J) {
2185 // Don't pull a constant into a register if the constant could be folded
2186 // into an immediate field.
2187 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2188 Base.getNumRegs() > 1,
2189 LU.Kind, LU.AccessTy, TLI, SE))
2190 continue;
2191
2192 // Collect all operands except *J.
2193 SmallVector<const SCEV *, 8> InnerAddOps;
2194 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2195 KE = AddOps.end(); K != KE; ++K)
2196 if (K != J)
2197 InnerAddOps.push_back(*K);
2198
2199 // Don't leave just a constant behind in a register if the constant could
2200 // be folded into an immediate field.
2201 if (InnerAddOps.size() == 1 &&
2202 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2203 Base.getNumRegs() > 1,
2204 LU.Kind, LU.AccessTy, TLI, SE))
2205 continue;
2206
Dan Gohmanfafb8902010-04-23 01:55:05 +00002207 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2208 if (InnerSum->isZero())
2209 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002210 Formula F = Base;
Dan Gohmanfafb8902010-04-23 01:55:05 +00002211 F.BaseRegs[i] = InnerSum;
Dan Gohman572645c2010-02-12 10:34:29 +00002212 F.BaseRegs.push_back(*J);
2213 if (InsertFormula(LU, LUIdx, F))
2214 // If that formula hadn't been seen before, recurse to find more like
2215 // it.
2216 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2217 }
2218 }
2219}
2220
2221/// GenerateCombinations - Generate a formula consisting of all of the
2222/// loop-dominating registers added into a single register.
2223void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002224 Formula Base) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002225 // This method is only interesting on a plurality of registers.
Dan Gohman572645c2010-02-12 10:34:29 +00002226 if (Base.BaseRegs.size() <= 1) return;
2227
2228 Formula F = Base;
2229 F.BaseRegs.clear();
2230 SmallVector<const SCEV *, 4> Ops;
2231 for (SmallVectorImpl<const SCEV *>::const_iterator
2232 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2233 const SCEV *BaseReg = *I;
2234 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2235 !BaseReg->hasComputableLoopEvolution(L))
2236 Ops.push_back(BaseReg);
2237 else
2238 F.BaseRegs.push_back(BaseReg);
2239 }
2240 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002241 const SCEV *Sum = SE.getAddExpr(Ops);
2242 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2243 // opportunity to fold something. For now, just ignore such cases
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002244 // rather than proceed with zero in a register.
Dan Gohmance947362010-02-14 18:50:49 +00002245 if (!Sum->isZero()) {
2246 F.BaseRegs.push_back(Sum);
2247 (void)InsertFormula(LU, LUIdx, F);
2248 }
Dan Gohman572645c2010-02-12 10:34:29 +00002249 }
2250}
2251
2252/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2253void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2254 Formula Base) {
2255 // We can't add a symbolic offset if the address already contains one.
2256 if (Base.AM.BaseGV) return;
2257
2258 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2259 const SCEV *G = Base.BaseRegs[i];
2260 GlobalValue *GV = ExtractSymbol(G, SE);
2261 if (G->isZero() || !GV)
2262 continue;
2263 Formula F = Base;
2264 F.AM.BaseGV = GV;
2265 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2266 LU.Kind, LU.AccessTy, TLI))
2267 continue;
2268 F.BaseRegs[i] = G;
2269 (void)InsertFormula(LU, LUIdx, F);
2270 }
2271}
2272
2273/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2274void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2275 Formula Base) {
2276 // TODO: For now, just add the min and max offset, because it usually isn't
2277 // worthwhile looking at everything inbetween.
2278 SmallVector<int64_t, 4> Worklist;
2279 Worklist.push_back(LU.MinOffset);
2280 if (LU.MaxOffset != LU.MinOffset)
2281 Worklist.push_back(LU.MaxOffset);
2282
2283 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2284 const SCEV *G = Base.BaseRegs[i];
2285
2286 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2287 E = Worklist.end(); I != E; ++I) {
2288 Formula F = Base;
2289 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2290 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2291 LU.Kind, LU.AccessTy, TLI)) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002292 F.BaseRegs[i] = SE.getAddExpr(G, SE.getConstant(G->getType(), *I));
Dan Gohman572645c2010-02-12 10:34:29 +00002293
2294 (void)InsertFormula(LU, LUIdx, F);
2295 }
2296 }
2297
2298 int64_t Imm = ExtractImmediate(G, SE);
2299 if (G->isZero() || Imm == 0)
2300 continue;
2301 Formula F = Base;
2302 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2303 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2304 LU.Kind, LU.AccessTy, TLI))
2305 continue;
2306 F.BaseRegs[i] = G;
2307 (void)InsertFormula(LU, LUIdx, F);
2308 }
2309}
2310
2311/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2312/// the comparison. For example, x == y -> x*c == y*c.
2313void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2314 Formula Base) {
2315 if (LU.Kind != LSRUse::ICmpZero) return;
2316
2317 // Determine the integer type for the base formula.
2318 const Type *IntTy = Base.getType();
2319 if (!IntTy) return;
2320 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2321
2322 // Don't do this if there is more than one offset.
2323 if (LU.MinOffset != LU.MaxOffset) return;
2324
2325 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2326
2327 // Check each interesting stride.
2328 for (SmallSetVector<int64_t, 8>::const_iterator
2329 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2330 int64_t Factor = *I;
2331 Formula F = Base;
2332
2333 // Check that the multiplication doesn't overflow.
Dan Gohman968cb932010-02-17 00:41:53 +00002334 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2335 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002336 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002337 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002338 continue;
2339
2340 // Check that multiplying with the use offset doesn't overflow.
2341 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002342 if (Offset == INT64_MIN && Factor == -1)
2343 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002344 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002345 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002346 continue;
2347
2348 // Check that this scale is legal.
2349 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2350 continue;
2351
2352 // Compensate for the use having MinOffset built into it.
2353 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2354
Dan Gohmandeff6212010-05-03 22:09:21 +00002355 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002356
2357 // Check that multiplying with each base register doesn't overflow.
2358 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2359 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002360 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002361 goto next;
2362 }
2363
2364 // Check that multiplying with the scaled register doesn't overflow.
2365 if (F.ScaledReg) {
2366 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002367 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002368 continue;
2369 }
2370
2371 // If we make it here and it's legal, add it.
2372 (void)InsertFormula(LU, LUIdx, F);
2373 next:;
2374 }
2375}
2376
2377/// GenerateScales - Generate stride factor reuse formulae by making use of
2378/// scaled-offset address modes, for example.
2379void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2380 Formula Base) {
2381 // Determine the integer type for the base formula.
2382 const Type *IntTy = Base.getType();
2383 if (!IntTy) return;
2384
2385 // If this Formula already has a scaled register, we can't add another one.
2386 if (Base.AM.Scale != 0) return;
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
2393 Base.AM.Scale = Factor;
2394 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2395 // Check whether this scale is going to be legal.
2396 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2397 LU.Kind, LU.AccessTy, TLI)) {
2398 // As a special-case, handle special out-of-loop Basic users specially.
2399 // TODO: Reconsider this special case.
2400 if (LU.Kind == LSRUse::Basic &&
2401 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2402 LSRUse::Special, LU.AccessTy, TLI) &&
2403 LU.AllFixupsOutsideLoop)
2404 LU.Kind = LSRUse::Special;
2405 else
2406 continue;
2407 }
2408 // For an ICmpZero, negating a solitary base register won't lead to
2409 // new solutions.
2410 if (LU.Kind == LSRUse::ICmpZero &&
2411 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2412 continue;
2413 // For each addrec base reg, apply the scale, if possible.
2414 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2415 if (const SCEVAddRecExpr *AR =
2416 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohmandeff6212010-05-03 22:09:21 +00002417 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman572645c2010-02-12 10:34:29 +00002418 if (FactorS->isZero())
2419 continue;
2420 // Divide out the factor, ignoring high bits, since we'll be
2421 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002422 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002423 // TODO: This could be optimized to avoid all the copying.
2424 Formula F = Base;
2425 F.ScaledReg = Quotient;
2426 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2427 F.BaseRegs.pop_back();
2428 (void)InsertFormula(LU, LUIdx, F);
2429 }
2430 }
2431 }
2432}
2433
2434/// GenerateTruncates - Generate reuse formulae from different IV types.
2435void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2436 Formula Base) {
2437 // This requires TargetLowering to tell us which truncates are free.
2438 if (!TLI) return;
2439
2440 // Don't bother truncating symbolic values.
2441 if (Base.AM.BaseGV) return;
2442
2443 // Determine the integer type for the base formula.
2444 const Type *DstTy = Base.getType();
2445 if (!DstTy) return;
2446 DstTy = SE.getEffectiveSCEVType(DstTy);
2447
2448 for (SmallSetVector<const Type *, 4>::const_iterator
2449 I = Types.begin(), E = Types.end(); I != E; ++I) {
2450 const Type *SrcTy = *I;
2451 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2452 Formula F = Base;
2453
2454 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2455 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2456 JE = F.BaseRegs.end(); J != JE; ++J)
2457 *J = SE.getAnyExtendExpr(*J, SrcTy);
2458
2459 // TODO: This assumes we've done basic processing on all uses and
2460 // have an idea what the register usage is.
2461 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2462 continue;
2463
2464 (void)InsertFormula(LU, LUIdx, F);
2465 }
2466 }
2467}
2468
2469namespace {
2470
Dan Gohman6020d852010-02-14 18:51:20 +00002471/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002472/// defer modifications so that the search phase doesn't have to worry about
2473/// the data structures moving underneath it.
2474struct WorkItem {
2475 size_t LUIdx;
2476 int64_t Imm;
2477 const SCEV *OrigReg;
2478
2479 WorkItem(size_t LI, int64_t I, const SCEV *R)
2480 : LUIdx(LI), Imm(I), OrigReg(R) {}
2481
2482 void print(raw_ostream &OS) const;
2483 void dump() const;
2484};
2485
2486}
2487
2488void WorkItem::print(raw_ostream &OS) const {
2489 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2490 << " , add offset " << Imm;
2491}
2492
2493void WorkItem::dump() const {
2494 print(errs()); errs() << '\n';
2495}
2496
2497/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2498/// distance apart and try to form reuse opportunities between them.
2499void LSRInstance::GenerateCrossUseConstantOffsets() {
2500 // Group the registers by their value without any added constant offset.
2501 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2502 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2503 RegMapTy Map;
2504 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2505 SmallVector<const SCEV *, 8> Sequence;
2506 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2507 I != E; ++I) {
2508 const SCEV *Reg = *I;
2509 int64_t Imm = ExtractImmediate(Reg, SE);
2510 std::pair<RegMapTy::iterator, bool> Pair =
2511 Map.insert(std::make_pair(Reg, ImmMapTy()));
2512 if (Pair.second)
2513 Sequence.push_back(Reg);
2514 Pair.first->second.insert(std::make_pair(Imm, *I));
2515 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2516 }
2517
2518 // Now examine each set of registers with the same base value. Build up
2519 // a list of work to do and do the work in a separate step so that we're
2520 // not adding formulae and register counts while we're searching.
2521 SmallVector<WorkItem, 32> WorkItems;
2522 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2523 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2524 E = Sequence.end(); I != E; ++I) {
2525 const SCEV *Reg = *I;
2526 const ImmMapTy &Imms = Map.find(Reg)->second;
2527
Dan Gohmancd045c02010-02-12 19:20:37 +00002528 // It's not worthwhile looking for reuse if there's only one offset.
2529 if (Imms.size() == 1)
2530 continue;
2531
Dan Gohman572645c2010-02-12 10:34:29 +00002532 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2533 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2534 J != JE; ++J)
2535 dbgs() << ' ' << J->first;
2536 dbgs() << '\n');
2537
2538 // Examine each offset.
2539 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2540 J != JE; ++J) {
2541 const SCEV *OrigReg = J->second;
2542
2543 int64_t JImm = J->first;
2544 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2545
2546 if (!isa<SCEVConstant>(OrigReg) &&
2547 UsedByIndicesMap[Reg].count() == 1) {
2548 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2549 continue;
2550 }
2551
2552 // Conservatively examine offsets between this orig reg a few selected
2553 // other orig regs.
2554 ImmMapTy::const_iterator OtherImms[] = {
2555 Imms.begin(), prior(Imms.end()),
2556 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2557 };
2558 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2559 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002560 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002561
2562 // Compute the difference between the two.
2563 int64_t Imm = (uint64_t)JImm - M->first;
2564 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2565 LUIdx = UsedByIndices.find_next(LUIdx))
2566 // Make a memo of this use, offset, and register tuple.
2567 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2568 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002569 }
2570 }
2571 }
2572
Dan Gohman572645c2010-02-12 10:34:29 +00002573 Map.clear();
2574 Sequence.clear();
2575 UsedByIndicesMap.clear();
2576 UniqueItems.clear();
2577
2578 // Now iterate through the worklist and add new formulae.
2579 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2580 E = WorkItems.end(); I != E; ++I) {
2581 const WorkItem &WI = *I;
2582 size_t LUIdx = WI.LUIdx;
2583 LSRUse &LU = Uses[LUIdx];
2584 int64_t Imm = WI.Imm;
2585 const SCEV *OrigReg = WI.OrigReg;
2586
2587 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2588 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2589 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2590
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002591 // TODO: Use a more targeted data structure.
Dan Gohman572645c2010-02-12 10:34:29 +00002592 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2593 Formula F = LU.Formulae[L];
2594 // Use the immediate in the scaled register.
2595 if (F.ScaledReg == OrigReg) {
2596 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2597 Imm * (uint64_t)F.AM.Scale;
2598 // Don't create 50 + reg(-50).
2599 if (F.referencesReg(SE.getSCEV(
2600 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2601 continue;
2602 Formula NewF = F;
2603 NewF.AM.BaseOffs = Offs;
2604 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2605 LU.Kind, LU.AccessTy, TLI))
2606 continue;
2607 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2608
2609 // If the new scale is a constant in a register, and adding the constant
2610 // value to the immediate would produce a value closer to zero than the
2611 // immediate itself, then the formula isn't worthwhile.
2612 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2613 if (C->getValue()->getValue().isNegative() !=
2614 (NewF.AM.BaseOffs < 0) &&
2615 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
Dan Gohmane0567812010-04-08 23:03:40 +00002616 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002617 continue;
2618
2619 // OK, looks good.
2620 (void)InsertFormula(LU, LUIdx, NewF);
2621 } else {
2622 // Use the immediate in a base register.
2623 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2624 const SCEV *BaseReg = F.BaseRegs[N];
2625 if (BaseReg != OrigReg)
2626 continue;
2627 Formula NewF = F;
2628 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2629 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2630 LU.Kind, LU.AccessTy, TLI))
2631 continue;
2632 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2633
2634 // If the new formula has a constant in a register, and adding the
2635 // constant value to the immediate would produce a value closer to
2636 // zero than the immediate itself, then the formula isn't worthwhile.
2637 for (SmallVectorImpl<const SCEV *>::const_iterator
2638 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2639 J != JE; ++J)
2640 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
Dan Gohman360026f2010-05-18 23:48:08 +00002641 if ((C->getValue()->getValue() + NewF.AM.BaseOffs).abs().slt(
2642 abs64(NewF.AM.BaseOffs)) &&
2643 (C->getValue()->getValue() +
2644 NewF.AM.BaseOffs).countTrailingZeros() >=
2645 CountTrailingZeros_64(NewF.AM.BaseOffs))
Dan Gohman572645c2010-02-12 10:34:29 +00002646 goto skip_formula;
2647
2648 // Ok, looks good.
2649 (void)InsertFormula(LU, LUIdx, NewF);
2650 break;
2651 skip_formula:;
2652 }
2653 }
2654 }
2655 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002656}
2657
Dan Gohman572645c2010-02-12 10:34:29 +00002658/// GenerateAllReuseFormulae - Generate formulae for each use.
2659void
2660LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002661 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002662 // queries are more precise.
2663 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2664 LSRUse &LU = Uses[LUIdx];
2665 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2666 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2667 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2668 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2669 }
2670 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2671 LSRUse &LU = Uses[LUIdx];
2672 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2673 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2674 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2675 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2676 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2677 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2678 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2679 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002680 }
2681 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2682 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002683 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2684 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2685 }
2686
2687 GenerateCrossUseConstantOffsets();
2688}
2689
2690/// If their are multiple formulae with the same set of registers used
2691/// by other uses, pick the best one and delete the others.
2692void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2693#ifndef NDEBUG
2694 bool Changed = false;
2695#endif
2696
2697 // Collect the best formula for each unique set of shared registers. This
2698 // is reset for each use.
2699 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2700 BestFormulaeTy;
2701 BestFormulaeTy BestFormulae;
2702
2703 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2704 LSRUse &LU = Uses[LUIdx];
2705 FormulaSorter Sorter(L, LU, SE, DT);
Dan Gohman6458ff92010-05-18 22:37:37 +00002706 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << "\n");
Dan Gohman572645c2010-02-12 10:34:29 +00002707
Dan Gohmanb2df4332010-05-18 23:42:37 +00002708 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002709 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2710 FIdx != NumForms; ++FIdx) {
2711 Formula &F = LU.Formulae[FIdx];
2712
2713 SmallVector<const SCEV *, 2> Key;
2714 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2715 JE = F.BaseRegs.end(); J != JE; ++J) {
2716 const SCEV *Reg = *J;
2717 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2718 Key.push_back(Reg);
2719 }
2720 if (F.ScaledReg &&
2721 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2722 Key.push_back(F.ScaledReg);
2723 // Unstable sort by host order ok, because this is only used for
2724 // uniquifying.
2725 std::sort(Key.begin(), Key.end());
2726
2727 std::pair<BestFormulaeTy::const_iterator, bool> P =
2728 BestFormulae.insert(std::make_pair(Key, FIdx));
2729 if (!P.second) {
2730 Formula &Best = LU.Formulae[P.first->second];
2731 if (Sorter.operator()(F, Best))
2732 std::swap(F, Best);
Dan Gohman6458ff92010-05-18 22:37:37 +00002733 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002734 dbgs() << "\n"
Dan Gohman6458ff92010-05-18 22:37:37 +00002735 " in favor of formula "; Best.print(dbgs());
Dan Gohman572645c2010-02-12 10:34:29 +00002736 dbgs() << '\n');
2737#ifndef NDEBUG
2738 Changed = true;
2739#endif
Dan Gohmand69d6282010-05-18 22:39:15 +00002740 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00002741 --FIdx;
2742 --NumForms;
Dan Gohmanb2df4332010-05-18 23:42:37 +00002743 Any = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002744 continue;
2745 }
Dan Gohman59dc6032010-05-07 23:36:59 +00002746 }
2747
Dan Gohman57aaa0b2010-05-18 23:55:57 +00002748 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohmanb2df4332010-05-18 23:42:37 +00002749 if (Any)
2750 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman59dc6032010-05-07 23:36:59 +00002751
2752 // Reset this to prepare for the next use.
Dan Gohman572645c2010-02-12 10:34:29 +00002753 BestFormulae.clear();
2754 }
2755
2756 DEBUG(if (Changed) {
Dan Gohman9214b822010-02-13 02:06:02 +00002757 dbgs() << "\n"
2758 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002759 print_uses(dbgs());
2760 });
2761}
2762
Dan Gohmand079c302010-05-18 22:51:59 +00002763// This is a rough guess that seems to work fairly well.
2764static const size_t ComplexityLimit = UINT16_MAX;
2765
2766/// EstimateSearchSpaceComplexity - Estimate the worst-case number of
2767/// solutions the solver might have to consider. It almost never considers
2768/// this many solutions because it prune the search space, but the pruning
2769/// isn't always sufficient.
2770size_t LSRInstance::EstimateSearchSpaceComplexity() const {
2771 uint32_t Power = 1;
2772 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2773 E = Uses.end(); I != E; ++I) {
2774 size_t FSize = I->Formulae.size();
2775 if (FSize >= ComplexityLimit) {
2776 Power = ComplexityLimit;
2777 break;
2778 }
2779 Power *= FSize;
2780 if (Power >= ComplexityLimit)
2781 break;
2782 }
2783 return Power;
2784}
2785
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002786/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
Dan Gohman572645c2010-02-12 10:34:29 +00002787/// formulae to choose from, use some rough heuristics to prune down the number
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002788/// of formulae. This keeps the main solver from taking an extraordinary amount
Dan Gohman572645c2010-02-12 10:34:29 +00002789/// of time in some worst-case scenarios.
2790void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
Dan Gohmana2086b32010-05-19 23:43:12 +00002791 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2792 DEBUG(dbgs() << "The search space is too complex.\n");
2793
2794 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
2795 "which use a superset of registers used by other "
2796 "formulae.\n");
2797
2798 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2799 LSRUse &LU = Uses[LUIdx];
2800 bool Any = false;
2801 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2802 Formula &F = LU.Formulae[i];
2803 for (SmallVectorImpl<const SCEV *>::const_iterator
2804 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
2805 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
2806 Formula NewF = F;
2807 NewF.AM.BaseOffs += C->getValue()->getSExtValue();
2808 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2809 (I - F.BaseRegs.begin()));
2810 if (LU.HasFormulaWithSameRegs(NewF)) {
2811 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2812 LU.DeleteFormula(F);
2813 --i;
2814 --e;
2815 Any = true;
2816 break;
2817 }
2818 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
2819 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
2820 if (!F.AM.BaseGV) {
2821 Formula NewF = F;
2822 NewF.AM.BaseGV = GV;
2823 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2824 (I - F.BaseRegs.begin()));
2825 if (LU.HasFormulaWithSameRegs(NewF)) {
2826 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
2827 dbgs() << '\n');
2828 LU.DeleteFormula(F);
2829 --i;
2830 --e;
2831 Any = true;
2832 break;
2833 }
2834 }
2835 }
2836 }
2837 }
2838 if (Any)
2839 LU.RecomputeRegs(LUIdx, RegUses);
2840 }
2841
2842 DEBUG(dbgs() << "After pre-selection:\n";
2843 print_uses(dbgs()));
2844 }
2845
2846 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2847 DEBUG(dbgs() << "The search space is too complex.\n");
2848
2849 DEBUG(dbgs() << "Narrowing the search space by assuming that uses "
2850 "separated by a constant offset will use the same "
2851 "registers.\n");
2852
2853 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2854 LSRUse &LU = Uses[LUIdx];
2855 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2856 Formula &F = LU.Formulae[i];
2857 if (F.AM.BaseOffs != 0 && F.AM.Scale == 0) {
2858 if (LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU)) {
2859 if (reconcileNewOffset(*LUThatHas, F.AM.BaseOffs,
2860 /*HasBaseReg=*/false,
2861 LU.Kind, LU.AccessTy)) {
2862 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs());
2863 dbgs() << '\n');
2864
2865 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
2866
2867 // Delete formulae from the new use which are no longer legal.
2868 bool Any = false;
2869 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
2870 Formula &F = LUThatHas->Formulae[i];
2871 if (!isLegalUse(F.AM,
2872 LUThatHas->MinOffset, LUThatHas->MaxOffset,
2873 LUThatHas->Kind, LUThatHas->AccessTy, TLI)) {
2874 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
2875 dbgs() << '\n');
2876 LUThatHas->DeleteFormula(F);
2877 --i;
2878 --e;
2879 Any = true;
2880 }
2881 }
2882 if (Any)
2883 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
2884
2885 // Update the relocs to reference the new use.
2886 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
2887 if (Fixups[i].LUIdx == LUIdx) {
2888 Fixups[i].LUIdx = LUThatHas - &Uses.front();
2889 Fixups[i].Offset += F.AM.BaseOffs;
2890 DEBUG(errs() << "New fixup has offset "
2891 << Fixups[i].Offset << "\n");
2892 }
2893 if (Fixups[i].LUIdx == NumUses-1)
2894 Fixups[i].LUIdx = LUIdx;
2895 }
2896
2897 // Delete the old use.
2898 std::swap(LU, Uses.back());
2899 Uses.pop_back();
2900 --LUIdx;
2901 --NumUses;
2902 break;
2903 }
2904 }
2905 }
2906 }
2907 }
2908
2909 DEBUG(dbgs() << "After pre-selection:\n";
2910 print_uses(dbgs()));
2911 }
2912
Dan Gohman572645c2010-02-12 10:34:29 +00002913 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmand079c302010-05-18 22:51:59 +00002914 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman572645c2010-02-12 10:34:29 +00002915 // Ok, we have too many of formulae on our hands to conveniently handle.
2916 // Use a rough heuristic to thin out the list.
Dan Gohman0da751b2010-05-18 22:41:32 +00002917 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00002918
2919 // Pick the register which is used by the most LSRUses, which is likely
2920 // to be a good reuse register candidate.
2921 const SCEV *Best = 0;
2922 unsigned BestNum = 0;
2923 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2924 I != E; ++I) {
2925 const SCEV *Reg = *I;
2926 if (Taken.count(Reg))
2927 continue;
2928 if (!Best)
2929 Best = Reg;
2930 else {
2931 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2932 if (Count > BestNum) {
2933 Best = Reg;
2934 BestNum = Count;
2935 }
2936 }
2937 }
2938
2939 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002940 << " will yield profitable reuse.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00002941 Taken.insert(Best);
2942
2943 // In any use with formulae which references this register, delete formulae
2944 // which don't reference it.
Dan Gohmanb2df4332010-05-18 23:42:37 +00002945 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2946 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002947 if (!LU.Regs.count(Best)) continue;
2948
Dan Gohmanb2df4332010-05-18 23:42:37 +00002949 bool Any = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002950 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2951 Formula &F = LU.Formulae[i];
2952 if (!F.referencesReg(Best)) {
2953 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmand69d6282010-05-18 22:39:15 +00002954 LU.DeleteFormula(F);
Dan Gohman572645c2010-02-12 10:34:29 +00002955 --e;
2956 --i;
Dan Gohmanb2df4332010-05-18 23:42:37 +00002957 Any = true;
Dan Gohman59dc6032010-05-07 23:36:59 +00002958 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman572645c2010-02-12 10:34:29 +00002959 continue;
2960 }
Dan Gohman572645c2010-02-12 10:34:29 +00002961 }
Dan Gohmanb2df4332010-05-18 23:42:37 +00002962
2963 if (Any)
2964 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman572645c2010-02-12 10:34:29 +00002965 }
2966
2967 DEBUG(dbgs() << "After pre-selection:\n";
2968 print_uses(dbgs()));
2969 }
2970}
2971
2972/// SolveRecurse - This is the recursive solver.
2973void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2974 Cost &SolutionCost,
2975 SmallVectorImpl<const Formula *> &Workspace,
2976 const Cost &CurCost,
2977 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2978 DenseSet<const SCEV *> &VisitedRegs) const {
2979 // Some ideas:
2980 // - prune more:
2981 // - use more aggressive filtering
2982 // - sort the formula so that the most profitable solutions are found first
2983 // - sort the uses too
2984 // - search faster:
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002985 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman572645c2010-02-12 10:34:29 +00002986 // and bail early.
2987 // - track register sets with SmallBitVector
2988
2989 const LSRUse &LU = Uses[Workspace.size()];
2990
2991 // If this use references any register that's already a part of the
2992 // in-progress solution, consider it a requirement that a formula must
2993 // reference that register in order to be considered. This prunes out
2994 // unprofitable searching.
2995 SmallSetVector<const SCEV *, 4> ReqRegs;
2996 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2997 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00002998 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00002999 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00003000
Dan Gohman9214b822010-02-13 02:06:02 +00003001 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00003002 SmallPtrSet<const SCEV *, 16> NewRegs;
3003 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00003004retry:
Dan Gohman572645c2010-02-12 10:34:29 +00003005 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3006 E = LU.Formulae.end(); I != E; ++I) {
3007 const Formula &F = *I;
3008
3009 // Ignore formulae which do not use any of the required registers.
3010 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
3011 JE = ReqRegs.end(); J != JE; ++J) {
3012 const SCEV *Reg = *J;
3013 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
3014 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
3015 F.BaseRegs.end())
3016 goto skip;
3017 }
Dan Gohman9214b822010-02-13 02:06:02 +00003018 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00003019
3020 // Evaluate the cost of the current formula. If it's already worse than
3021 // the current best, prune the search at that point.
3022 NewCost = CurCost;
3023 NewRegs = CurRegs;
3024 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
3025 if (NewCost < SolutionCost) {
3026 Workspace.push_back(&F);
3027 if (Workspace.size() != Uses.size()) {
3028 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
3029 NewRegs, VisitedRegs);
3030 if (F.getNumRegs() == 1 && Workspace.size() == 1)
3031 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
3032 } else {
3033 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
3034 dbgs() << ". Regs:";
3035 for (SmallPtrSet<const SCEV *, 16>::const_iterator
3036 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
3037 dbgs() << ' ' << **I;
3038 dbgs() << '\n');
3039
3040 SolutionCost = NewCost;
3041 Solution = Workspace;
3042 }
3043 Workspace.pop_back();
3044 }
3045 skip:;
3046 }
Dan Gohman9214b822010-02-13 02:06:02 +00003047
3048 // If none of the formulae had all of the required registers, relax the
3049 // constraint so that we don't exclude all formulae.
3050 if (!AnySatisfiedReqRegs) {
Dan Gohman59dc6032010-05-07 23:36:59 +00003051 assert(!ReqRegs.empty() && "Solver failed even without required registers");
Dan Gohman9214b822010-02-13 02:06:02 +00003052 ReqRegs.clear();
3053 goto retry;
3054 }
Dan Gohman572645c2010-02-12 10:34:29 +00003055}
3056
3057void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
3058 SmallVector<const Formula *, 8> Workspace;
3059 Cost SolutionCost;
3060 SolutionCost.Loose();
3061 Cost CurCost;
3062 SmallPtrSet<const SCEV *, 16> CurRegs;
3063 DenseSet<const SCEV *> VisitedRegs;
3064 Workspace.reserve(Uses.size());
3065
3066 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
3067 CurRegs, VisitedRegs);
3068
3069 // Ok, we've now made all our decisions.
3070 DEBUG(dbgs() << "\n"
3071 "The chosen solution requires "; SolutionCost.print(dbgs());
3072 dbgs() << ":\n";
3073 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
3074 dbgs() << " ";
3075 Uses[i].print(dbgs());
3076 dbgs() << "\n"
3077 " ";
3078 Solution[i]->print(dbgs());
3079 dbgs() << '\n';
3080 });
3081}
3082
3083/// getImmediateDominator - A handy utility for the specific DominatorTree
3084/// query that we need here.
3085///
3086static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
3087 DomTreeNode *Node = DT.getNode(BB);
3088 if (!Node) return 0;
3089 Node = Node->getIDom();
3090 if (!Node) return 0;
3091 return Node->getBlock();
3092}
3093
Dan Gohmane5f76872010-04-09 22:07:05 +00003094/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
3095/// the dominator tree far as we can go while still being dominated by the
3096/// input positions. This helps canonicalize the insert position, which
3097/// encourages sharing.
3098BasicBlock::iterator
3099LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
3100 const SmallVectorImpl<Instruction *> &Inputs)
3101 const {
3102 for (;;) {
3103 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
3104 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
3105
3106 BasicBlock *IDom;
3107 for (BasicBlock *Rung = IP->getParent(); ; Rung = IDom) {
3108 IDom = getImmediateDominator(Rung, DT);
3109 if (!IDom) return IP;
3110
3111 // Don't climb into a loop though.
3112 const Loop *IDomLoop = LI.getLoopFor(IDom);
3113 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
3114 if (IDomDepth <= IPLoopDepth &&
3115 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
3116 break;
3117 }
3118
3119 bool AllDominate = true;
3120 Instruction *BetterPos = 0;
3121 Instruction *Tentative = IDom->getTerminator();
3122 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
3123 E = Inputs.end(); I != E; ++I) {
3124 Instruction *Inst = *I;
3125 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
3126 AllDominate = false;
3127 break;
3128 }
3129 // Attempt to find an insert position in the middle of the block,
3130 // instead of at the end, so that it can be used for other expansions.
3131 if (IDom == Inst->getParent() &&
3132 (!BetterPos || DT.dominates(BetterPos, Inst)))
Douglas Gregor7d9663c2010-05-11 06:17:44 +00003133 BetterPos = llvm::next(BasicBlock::iterator(Inst));
Dan Gohmane5f76872010-04-09 22:07:05 +00003134 }
3135 if (!AllDominate)
3136 break;
3137 if (BetterPos)
3138 IP = BetterPos;
3139 else
3140 IP = Tentative;
3141 }
3142
3143 return IP;
3144}
3145
3146/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand96eae82010-04-09 02:00:38 +00003147/// dominated by the operands and which will dominate the result.
3148BasicBlock::iterator
Dan Gohmane5f76872010-04-09 22:07:05 +00003149LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
3150 const LSRFixup &LF,
3151 const LSRUse &LU) const {
Dan Gohmand96eae82010-04-09 02:00:38 +00003152 // Collect some instructions which must be dominated by the
Dan Gohman448db1c2010-04-07 22:27:08 +00003153 // expanding replacement. These must be dominated by any operands that
Dan Gohman572645c2010-02-12 10:34:29 +00003154 // will be required in the expansion.
3155 SmallVector<Instruction *, 4> Inputs;
3156 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
3157 Inputs.push_back(I);
3158 if (LU.Kind == LSRUse::ICmpZero)
3159 if (Instruction *I =
3160 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
3161 Inputs.push_back(I);
Dan Gohman448db1c2010-04-07 22:27:08 +00003162 if (LF.PostIncLoops.count(L)) {
3163 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman069d6f32010-03-02 01:59:21 +00003164 Inputs.push_back(L->getLoopLatch()->getTerminator());
3165 else
3166 Inputs.push_back(IVIncInsertPos);
3167 }
Dan Gohman701a4ae2010-04-08 05:57:57 +00003168 // The expansion must also be dominated by the increment positions of any
3169 // loops it for which it is using post-inc mode.
3170 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
3171 E = LF.PostIncLoops.end(); I != E; ++I) {
3172 const Loop *PIL = *I;
3173 if (PIL == L) continue;
3174
Dan Gohmane5f76872010-04-09 22:07:05 +00003175 // Be dominated by the loop exit.
Dan Gohman701a4ae2010-04-08 05:57:57 +00003176 SmallVector<BasicBlock *, 4> ExitingBlocks;
3177 PIL->getExitingBlocks(ExitingBlocks);
3178 if (!ExitingBlocks.empty()) {
3179 BasicBlock *BB = ExitingBlocks[0];
3180 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
3181 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
3182 Inputs.push_back(BB->getTerminator());
3183 }
3184 }
Dan Gohman572645c2010-02-12 10:34:29 +00003185
3186 // Then, climb up the immediate dominator tree as far as we can go while
3187 // still being dominated by the input positions.
Dan Gohmane5f76872010-04-09 22:07:05 +00003188 IP = HoistInsertPosition(IP, Inputs);
Dan Gohmand96eae82010-04-09 02:00:38 +00003189
3190 // Don't insert instructions before PHI nodes.
Dan Gohman572645c2010-02-12 10:34:29 +00003191 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand96eae82010-04-09 02:00:38 +00003192
3193 // Ignore debug intrinsics.
Dan Gohman449f31c2010-03-26 00:33:27 +00003194 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman572645c2010-02-12 10:34:29 +00003195
Dan Gohmand96eae82010-04-09 02:00:38 +00003196 return IP;
3197}
3198
3199Value *LSRInstance::Expand(const LSRFixup &LF,
3200 const Formula &F,
3201 BasicBlock::iterator IP,
3202 SCEVExpander &Rewriter,
3203 SmallVectorImpl<WeakVH> &DeadInsts) const {
3204 const LSRUse &LU = Uses[LF.LUIdx];
3205
3206 // Determine an input position which will be dominated by the operands and
3207 // which will dominate the result.
Dan Gohmane5f76872010-04-09 22:07:05 +00003208 IP = AdjustInsertPositionForExpand(IP, LF, LU);
Dan Gohmand96eae82010-04-09 02:00:38 +00003209
Dan Gohman572645c2010-02-12 10:34:29 +00003210 // Inform the Rewriter if we have a post-increment use, so that it can
3211 // perform an advantageous expansion.
Dan Gohman448db1c2010-04-07 22:27:08 +00003212 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman572645c2010-02-12 10:34:29 +00003213
3214 // This is the type that the user actually needs.
3215 const Type *OpTy = LF.OperandValToReplace->getType();
3216 // This will be the type that we'll initially expand to.
3217 const Type *Ty = F.getType();
3218 if (!Ty)
3219 // No type known; just expand directly to the ultimate type.
3220 Ty = OpTy;
3221 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3222 // Expand directly to the ultimate type if it's the right size.
3223 Ty = OpTy;
3224 // This is the type to do integer arithmetic in.
3225 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3226
3227 // Build up a list of operands to add together to form the full base.
3228 SmallVector<const SCEV *, 8> Ops;
3229
3230 // Expand the BaseRegs portion.
3231 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3232 E = F.BaseRegs.end(); I != E; ++I) {
3233 const SCEV *Reg = *I;
3234 assert(!Reg->isZero() && "Zero allocated in a base register!");
3235
Dan Gohman448db1c2010-04-07 22:27:08 +00003236 // If we're expanding for a post-inc user, make the post-inc adjustment.
3237 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3238 Reg = TransformForPostIncUse(Denormalize, Reg,
3239 LF.UserInst, LF.OperandValToReplace,
3240 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003241
3242 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3243 }
3244
Dan Gohman087bd1e2010-03-03 05:29:13 +00003245 // Flush the operand list to suppress SCEVExpander hoisting.
3246 if (!Ops.empty()) {
3247 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3248 Ops.clear();
3249 Ops.push_back(SE.getUnknown(FullV));
3250 }
3251
Dan Gohman572645c2010-02-12 10:34:29 +00003252 // Expand the ScaledReg portion.
3253 Value *ICmpScaledV = 0;
3254 if (F.AM.Scale != 0) {
3255 const SCEV *ScaledS = F.ScaledReg;
3256
Dan Gohman448db1c2010-04-07 22:27:08 +00003257 // If we're expanding for a post-inc user, make the post-inc adjustment.
3258 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3259 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3260 LF.UserInst, LF.OperandValToReplace,
3261 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00003262
3263 if (LU.Kind == LSRUse::ICmpZero) {
3264 // An interesting way of "folding" with an icmp is to use a negated
3265 // scale, which we'll implement by inserting it into the other operand
3266 // of the icmp.
3267 assert(F.AM.Scale == -1 &&
3268 "The only scale supported by ICmpZero uses is -1!");
3269 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3270 } else {
3271 // Otherwise just expand the scaled register and an explicit scale,
3272 // which is expected to be matched as part of the address.
3273 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3274 ScaledS = SE.getMulExpr(ScaledS,
Dan Gohmandeff6212010-05-03 22:09:21 +00003275 SE.getConstant(ScaledS->getType(), F.AM.Scale));
Dan Gohman572645c2010-02-12 10:34:29 +00003276 Ops.push_back(ScaledS);
Dan Gohman087bd1e2010-03-03 05:29:13 +00003277
3278 // Flush the operand list to suppress SCEVExpander hoisting.
3279 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3280 Ops.clear();
3281 Ops.push_back(SE.getUnknown(FullV));
Dan Gohman572645c2010-02-12 10:34:29 +00003282 }
3283 }
3284
Dan Gohman087bd1e2010-03-03 05:29:13 +00003285 // Expand the GV portion.
3286 if (F.AM.BaseGV) {
3287 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3288
3289 // Flush the operand list to suppress SCEVExpander hoisting.
3290 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3291 Ops.clear();
3292 Ops.push_back(SE.getUnknown(FullV));
3293 }
3294
3295 // Expand the immediate portion.
Dan Gohman572645c2010-02-12 10:34:29 +00003296 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3297 if (Offset != 0) {
3298 if (LU.Kind == LSRUse::ICmpZero) {
3299 // The other interesting way of "folding" with an ICmpZero is to use a
3300 // negated immediate.
3301 if (!ICmpScaledV)
3302 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3303 else {
3304 Ops.push_back(SE.getUnknown(ICmpScaledV));
3305 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3306 }
3307 } else {
3308 // Just add the immediate values. These again are expected to be matched
3309 // as part of the address.
Dan Gohman087bd1e2010-03-03 05:29:13 +00003310 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman572645c2010-02-12 10:34:29 +00003311 }
3312 }
3313
3314 // Emit instructions summing all the operands.
3315 const SCEV *FullS = Ops.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +00003316 SE.getConstant(IntTy, 0) :
Dan Gohman572645c2010-02-12 10:34:29 +00003317 SE.getAddExpr(Ops);
3318 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3319
3320 // We're done expanding now, so reset the rewriter.
Dan Gohman448db1c2010-04-07 22:27:08 +00003321 Rewriter.clearPostInc();
Dan Gohman572645c2010-02-12 10:34:29 +00003322
3323 // An ICmpZero Formula represents an ICmp which we're handling as a
3324 // comparison against zero. Now that we've expanded an expression for that
3325 // form, update the ICmp's other operand.
3326 if (LU.Kind == LSRUse::ICmpZero) {
3327 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3328 DeadInsts.push_back(CI->getOperand(1));
3329 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3330 "a scale at the same time!");
3331 if (F.AM.Scale == -1) {
3332 if (ICmpScaledV->getType() != OpTy) {
3333 Instruction *Cast =
3334 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3335 OpTy, false),
3336 ICmpScaledV, OpTy, "tmp", CI);
3337 ICmpScaledV = Cast;
3338 }
3339 CI->setOperand(1, ICmpScaledV);
3340 } else {
3341 assert(F.AM.Scale == 0 &&
3342 "ICmp does not support folding a global value and "
3343 "a scale at the same time!");
3344 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3345 -(uint64_t)Offset);
3346 if (C->getType() != OpTy)
3347 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3348 OpTy, false),
3349 C, OpTy);
3350
3351 CI->setOperand(1, C);
3352 }
3353 }
3354
3355 return FullV;
3356}
3357
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003358/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3359/// of their operands effectively happens in their predecessor blocks, so the
3360/// expression may need to be expanded in multiple places.
3361void LSRInstance::RewriteForPHI(PHINode *PN,
3362 const LSRFixup &LF,
3363 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003364 SCEVExpander &Rewriter,
3365 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003366 Pass *P) const {
3367 DenseMap<BasicBlock *, Value *> Inserted;
3368 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3369 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3370 BasicBlock *BB = PN->getIncomingBlock(i);
3371
3372 // If this is a critical edge, split the edge so that we do not insert
3373 // the code on all predecessor/successor paths. We do this unless this
3374 // is the canonical backedge for this loop, which complicates post-inc
3375 // users.
3376 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3377 !isa<IndirectBrInst>(BB->getTerminator()) &&
3378 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3379 // Split the critical edge.
3380 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3381
3382 // If PN is outside of the loop and BB is in the loop, we want to
3383 // move the block to be immediately before the PHI block, not
3384 // immediately after BB.
3385 if (L->contains(BB) && !L->contains(PN))
3386 NewBB->moveBefore(PN->getParent());
3387
3388 // Splitting the edge can reduce the number of PHI entries we have.
3389 e = PN->getNumIncomingValues();
3390 BB = NewBB;
3391 i = PN->getBasicBlockIndex(BB);
3392 }
3393
3394 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3395 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3396 if (!Pair.second)
3397 PN->setIncomingValue(i, Pair.first->second);
3398 else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003399 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003400
3401 // If this is reuse-by-noop-cast, insert the noop cast.
3402 const Type *OpTy = LF.OperandValToReplace->getType();
3403 if (FullV->getType() != OpTy)
3404 FullV =
3405 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3406 OpTy, false),
3407 FullV, LF.OperandValToReplace->getType(),
3408 "tmp", BB->getTerminator());
3409
3410 PN->setIncomingValue(i, FullV);
3411 Pair.first->second = FullV;
3412 }
3413 }
3414}
3415
Dan Gohman572645c2010-02-12 10:34:29 +00003416/// Rewrite - Emit instructions for the leading candidate expression for this
3417/// LSRUse (this is called "expanding"), and update the UserInst to reference
3418/// the newly expanded value.
3419void LSRInstance::Rewrite(const LSRFixup &LF,
3420 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00003421 SCEVExpander &Rewriter,
3422 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00003423 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003424 // First, find an insertion point that dominates UserInst. For PHI nodes,
3425 // find the nearest block which dominates all the relevant uses.
3426 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman454d26d2010-02-22 04:11:59 +00003427 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003428 } else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003429 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman572645c2010-02-12 10:34:29 +00003430
3431 // If this is reuse-by-noop-cast, insert the noop cast.
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003432 const Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003433 if (FullV->getType() != OpTy) {
3434 Instruction *Cast =
3435 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3436 FullV, OpTy, "tmp", LF.UserInst);
3437 FullV = Cast;
3438 }
3439
3440 // Update the user. ICmpZero is handled specially here (for now) because
3441 // Expand may have updated one of the operands of the icmp already, and
3442 // its new value may happen to be equal to LF.OperandValToReplace, in
3443 // which case doing replaceUsesOfWith leads to replacing both operands
3444 // with the same value. TODO: Reorganize this.
3445 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3446 LF.UserInst->setOperand(0, FullV);
3447 else
3448 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3449 }
3450
3451 DeadInsts.push_back(LF.OperandValToReplace);
3452}
3453
3454void
3455LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3456 Pass *P) {
3457 // Keep track of instructions we may have made dead, so that
3458 // we can remove them after we are done working.
3459 SmallVector<WeakVH, 16> DeadInsts;
3460
3461 SCEVExpander Rewriter(SE);
3462 Rewriter.disableCanonicalMode();
3463 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3464
3465 // Expand the new value definitions and update the users.
3466 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3467 size_t LUIdx = Fixups[i].LUIdx;
3468
Dan Gohman454d26d2010-02-22 04:11:59 +00003469 Rewrite(Fixups[i], *Solution[LUIdx], Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003470
3471 Changed = true;
3472 }
3473
3474 // Clean up after ourselves. This must be done before deleting any
3475 // instructions.
3476 Rewriter.clear();
3477
3478 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3479}
3480
3481LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3482 : IU(P->getAnalysis<IVUsers>()),
3483 SE(P->getAnalysis<ScalarEvolution>()),
3484 DT(P->getAnalysis<DominatorTree>()),
Dan Gohmane5f76872010-04-09 22:07:05 +00003485 LI(P->getAnalysis<LoopInfo>()),
Dan Gohman572645c2010-02-12 10:34:29 +00003486 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003487
Dan Gohman03e896b2009-11-05 21:11:53 +00003488 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003489 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003490
Dan Gohman572645c2010-02-12 10:34:29 +00003491 // If there's no interesting work to be done, bail early.
3492 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003493
Dan Gohman572645c2010-02-12 10:34:29 +00003494 DEBUG(dbgs() << "\nLSR on loop ";
3495 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3496 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003497
Dan Gohman572645c2010-02-12 10:34:29 +00003498 /// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003499 /// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00003500 OptimizeShadowIV();
Chris Lattner010de252005-08-08 05:28:22 +00003501
Dan Gohman572645c2010-02-12 10:34:29 +00003502 // Change loop terminating condition to use the postinc iv when possible.
3503 Changed |= OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003504
Dan Gohman572645c2010-02-12 10:34:29 +00003505 CollectInterestingTypesAndFactors();
3506 CollectFixupsAndInitialFormulae();
3507 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003508
Dan Gohman572645c2010-02-12 10:34:29 +00003509 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3510 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003511
Dan Gohman572645c2010-02-12 10:34:29 +00003512 // Now use the reuse data to generate a bunch of interesting ways
3513 // to formulate the values needed for the uses.
3514 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003515
Dan Gohman572645c2010-02-12 10:34:29 +00003516 DEBUG(dbgs() << "\n"
3517 "After generating reuse formulae:\n";
3518 print_uses(dbgs()));
Nate Begemaneaa13852004-10-18 21:08:22 +00003519
Dan Gohman572645c2010-02-12 10:34:29 +00003520 FilterOutUndesirableDedicatedRegisters();
3521 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003522
Dan Gohman572645c2010-02-12 10:34:29 +00003523 SmallVector<const Formula *, 8> Solution;
3524 Solve(Solution);
3525 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003526
Dan Gohman572645c2010-02-12 10:34:29 +00003527 // Release memory that is no longer needed.
3528 Factors.clear();
3529 Types.clear();
3530 RegUses.clear();
3531
3532#ifndef NDEBUG
3533 // Formulae should be legal.
3534 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3535 E = Uses.end(); I != E; ++I) {
3536 const LSRUse &LU = *I;
3537 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3538 JE = LU.Formulae.end(); J != JE; ++J)
3539 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3540 LU.Kind, LU.AccessTy, TLI) &&
3541 "Illegal formula generated!");
3542 };
3543#endif
3544
3545 // Now that we've decided what we want, make it so.
3546 ImplementSolution(Solution, P);
3547}
3548
3549void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3550 if (Factors.empty() && Types.empty()) return;
3551
3552 OS << "LSR has identified the following interesting factors and types: ";
3553 bool First = true;
3554
3555 for (SmallSetVector<int64_t, 8>::const_iterator
3556 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3557 if (!First) OS << ", ";
3558 First = false;
3559 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003560 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003561
Dan Gohman572645c2010-02-12 10:34:29 +00003562 for (SmallSetVector<const Type *, 4>::const_iterator
3563 I = Types.begin(), E = Types.end(); I != E; ++I) {
3564 if (!First) OS << ", ";
3565 First = false;
3566 OS << '(' << **I << ')';
3567 }
3568 OS << '\n';
3569}
3570
3571void LSRInstance::print_fixups(raw_ostream &OS) const {
3572 OS << "LSR is examining the following fixup sites:\n";
3573 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3574 E = Fixups.end(); I != E; ++I) {
3575 const LSRFixup &LF = *I;
3576 dbgs() << " ";
3577 LF.print(OS);
3578 OS << '\n';
3579 }
3580}
3581
3582void LSRInstance::print_uses(raw_ostream &OS) const {
3583 OS << "LSR is examining the following uses:\n";
3584 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3585 E = Uses.end(); I != E; ++I) {
3586 const LSRUse &LU = *I;
3587 dbgs() << " ";
3588 LU.print(OS);
3589 OS << '\n';
3590 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3591 JE = LU.Formulae.end(); J != JE; ++J) {
3592 OS << " ";
3593 J->print(OS);
3594 OS << '\n';
3595 }
3596 }
3597}
3598
3599void LSRInstance::print(raw_ostream &OS) const {
3600 print_factors_and_types(OS);
3601 print_fixups(OS);
3602 print_uses(OS);
3603}
3604
3605void LSRInstance::dump() const {
3606 print(errs()); errs() << '\n';
3607}
3608
3609namespace {
3610
3611class LoopStrengthReduce : public LoopPass {
3612 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3613 /// transformation profitability.
3614 const TargetLowering *const TLI;
3615
3616public:
3617 static char ID; // Pass ID, replacement for typeid
3618 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3619
3620private:
3621 bool runOnLoop(Loop *L, LPPassManager &LPM);
3622 void getAnalysisUsage(AnalysisUsage &AU) const;
3623};
3624
3625}
3626
3627char LoopStrengthReduce::ID = 0;
3628static RegisterPass<LoopStrengthReduce>
3629X("loop-reduce", "Loop Strength Reduction");
3630
3631Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3632 return new LoopStrengthReduce(TLI);
3633}
3634
3635LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3636 : LoopPass(&ID), TLI(tli) {}
3637
3638void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3639 // We split critical edges, so we change the CFG. However, we do update
3640 // many analyses if they are around.
3641 AU.addPreservedID(LoopSimplifyID);
Dan Gohman572645c2010-02-12 10:34:29 +00003642 AU.addPreserved("domfrontier");
3643
Dan Gohmane5f76872010-04-09 22:07:05 +00003644 AU.addRequired<LoopInfo>();
3645 AU.addPreserved<LoopInfo>();
Dan Gohman572645c2010-02-12 10:34:29 +00003646 AU.addRequiredID(LoopSimplifyID);
3647 AU.addRequired<DominatorTree>();
3648 AU.addPreserved<DominatorTree>();
3649 AU.addRequired<ScalarEvolution>();
3650 AU.addPreserved<ScalarEvolution>();
3651 AU.addRequired<IVUsers>();
3652 AU.addPreserved<IVUsers>();
3653}
3654
3655bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3656 bool Changed = false;
3657
3658 // Run the main LSR transformation.
3659 Changed |= LSRInstance(TLI, L, this).getChanged();
3660
Dan Gohmanafc36a92009-05-02 18:29:22 +00003661 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003662 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003663 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003664
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003665 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003666}