blob: 04f388477bcb6dec3f93f38d1eb2e6175c9745f7 [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 Gohman572645c2010-02-12 10:34:29 +0000110 RegUsesTy RegUses;
111 SmallVector<const SCEV *, 16> RegSequence;
Evan Chengd1d6b5c2006-03-16 21:53:05 +0000112
Dan Gohman572645c2010-02-12 10:34:29 +0000113public:
114 void CountRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000115
Dan Gohman572645c2010-02-12 10:34:29 +0000116 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000117
Dan Gohman572645c2010-02-12 10:34:29 +0000118 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohmana10756e2010-01-21 02:09:26 +0000119
Dan Gohman572645c2010-02-12 10:34:29 +0000120 void clear();
Dan Gohmana10756e2010-01-21 02:09:26 +0000121
Dan Gohman572645c2010-02-12 10:34:29 +0000122 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
123 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
124 iterator begin() { return RegSequence.begin(); }
125 iterator end() { return RegSequence.end(); }
126 const_iterator begin() const { return RegSequence.begin(); }
127 const_iterator end() const { return RegSequence.end(); }
128};
Dan Gohmana10756e2010-01-21 02:09:26 +0000129
Dan Gohmana10756e2010-01-21 02:09:26 +0000130}
131
Dan Gohman572645c2010-02-12 10:34:29 +0000132void
133RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
134 std::pair<RegUsesTy::iterator, bool> Pair =
135 RegUses.insert(std::make_pair(Reg, RegSortData()));
136 RegSortData &RSD = Pair.first->second;
137 if (Pair.second)
138 RegSequence.push_back(Reg);
139 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
140 RSD.UsedByIndices.set(LUIdx);
Dan Gohmana10756e2010-01-21 02:09:26 +0000141}
142
Dan Gohman572645c2010-02-12 10:34:29 +0000143bool
144RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
145 if (!RegUses.count(Reg)) return false;
146 const SmallBitVector &UsedByIndices =
147 RegUses.find(Reg)->second.UsedByIndices;
148 int i = UsedByIndices.find_first();
149 if (i == -1) return false;
150 if ((size_t)i != LUIdx) return true;
151 return UsedByIndices.find_next(i) != -1;
152}
Dan Gohmana10756e2010-01-21 02:09:26 +0000153
Dan Gohman572645c2010-02-12 10:34:29 +0000154const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
155 RegUsesTy::const_iterator I = RegUses.find(Reg);
156 assert(I != RegUses.end() && "Unknown register!");
157 return I->second.UsedByIndices;
158}
Dan Gohmana10756e2010-01-21 02:09:26 +0000159
Dan Gohman572645c2010-02-12 10:34:29 +0000160void RegUseTracker::clear() {
161 RegUses.clear();
162 RegSequence.clear();
163}
Dan Gohmana10756e2010-01-21 02:09:26 +0000164
Dan Gohman572645c2010-02-12 10:34:29 +0000165namespace {
166
167/// Formula - This class holds information that describes a formula for
168/// computing satisfying a use. It may include broken-out immediates and scaled
169/// registers.
170struct Formula {
171 /// AM - This is used to represent complex addressing, as well as other kinds
172 /// of interesting uses.
173 TargetLowering::AddrMode AM;
174
175 /// BaseRegs - The list of "base" registers for this use. When this is
176 /// non-empty, AM.HasBaseReg should be set to true.
177 SmallVector<const SCEV *, 2> BaseRegs;
178
179 /// ScaledReg - The 'scaled' register for this use. This should be non-null
180 /// when AM.Scale is not zero.
181 const SCEV *ScaledReg;
182
183 Formula() : ScaledReg(0) {}
184
185 void InitialMatch(const SCEV *S, Loop *L,
186 ScalarEvolution &SE, DominatorTree &DT);
187
188 unsigned getNumRegs() const;
189 const Type *getType() const;
190
191 bool referencesReg(const SCEV *S) const;
192 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
193 const RegUseTracker &RegUses) const;
194
195 void print(raw_ostream &OS) const;
196 void dump() const;
197};
198
199}
200
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000201/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman572645c2010-02-12 10:34:29 +0000202static void DoInitialMatch(const SCEV *S, Loop *L,
203 SmallVectorImpl<const SCEV *> &Good,
204 SmallVectorImpl<const SCEV *> &Bad,
205 ScalarEvolution &SE, DominatorTree &DT) {
206 // Collect expressions which properly dominate the loop header.
207 if (S->properlyDominates(L->getHeader(), &DT)) {
208 Good.push_back(S);
209 return;
Dan Gohmana10756e2010-01-21 02:09:26 +0000210 }
Dan Gohman572645c2010-02-12 10:34:29 +0000211
212 // Look at add operands.
213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
214 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
215 I != E; ++I)
216 DoInitialMatch(*I, L, Good, Bad, SE, DT);
217 return;
218 }
219
220 // Look at addrec operands.
221 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
222 if (!AR->getStart()->isZero()) {
223 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
224 DoInitialMatch(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
225 AR->getStepRecurrence(SE),
226 AR->getLoop()),
227 L, Good, Bad, SE, DT);
228 return;
229 }
230
231 // Handle a multiplication by -1 (negation) if it didn't fold.
232 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
233 if (Mul->getOperand(0)->isAllOnesValue()) {
234 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
235 const SCEV *NewMul = SE.getMulExpr(Ops);
236
237 SmallVector<const SCEV *, 4> MyGood;
238 SmallVector<const SCEV *, 4> MyBad;
239 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
240 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
241 SE.getEffectiveSCEVType(NewMul->getType())));
242 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
243 E = MyGood.end(); I != E; ++I)
244 Good.push_back(SE.getMulExpr(NegOne, *I));
245 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
246 E = MyBad.end(); I != E; ++I)
247 Bad.push_back(SE.getMulExpr(NegOne, *I));
248 return;
249 }
250
251 // Ok, we can't do anything interesting. Just stuff the whole thing into a
252 // register and hope for the best.
253 Bad.push_back(S);
254}
255
256/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
257/// attempting to keep all loop-invariant and loop-computable values in a
258/// single base register.
259void Formula::InitialMatch(const SCEV *S, Loop *L,
260 ScalarEvolution &SE, DominatorTree &DT) {
261 SmallVector<const SCEV *, 4> Good;
262 SmallVector<const SCEV *, 4> Bad;
263 DoInitialMatch(S, L, Good, Bad, SE, DT);
264 if (!Good.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000265 const SCEV *Sum = SE.getAddExpr(Good);
266 if (!Sum->isZero())
267 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000268 AM.HasBaseReg = true;
269 }
270 if (!Bad.empty()) {
Dan Gohmane60bb152010-04-08 23:36:27 +0000271 const SCEV *Sum = SE.getAddExpr(Bad);
272 if (!Sum->isZero())
273 BaseRegs.push_back(Sum);
Dan Gohman572645c2010-02-12 10:34:29 +0000274 AM.HasBaseReg = true;
275 }
276}
277
278/// getNumRegs - Return the total number of register operands used by this
279/// formula. This does not include register uses implied by non-constant
280/// addrec strides.
281unsigned Formula::getNumRegs() const {
282 return !!ScaledReg + BaseRegs.size();
283}
284
285/// getType - Return the type of this formula, if it has one, or null
286/// otherwise. This type is meaningless except for the bit size.
287const Type *Formula::getType() const {
288 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
289 ScaledReg ? ScaledReg->getType() :
290 AM.BaseGV ? AM.BaseGV->getType() :
291 0;
292}
293
294/// referencesReg - Test if this formula references the given register.
295bool Formula::referencesReg(const SCEV *S) const {
296 return S == ScaledReg ||
297 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
298}
299
300/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
301/// which are used by uses other than the use with the given index.
302bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
303 const RegUseTracker &RegUses) const {
304 if (ScaledReg)
305 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
306 return true;
307 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
308 E = BaseRegs.end(); I != E; ++I)
309 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
310 return true;
311 return false;
312}
313
314void Formula::print(raw_ostream &OS) const {
315 bool First = true;
316 if (AM.BaseGV) {
317 if (!First) OS << " + "; else First = false;
318 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
319 }
320 if (AM.BaseOffs != 0) {
321 if (!First) OS << " + "; else First = false;
322 OS << AM.BaseOffs;
323 }
324 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
325 E = BaseRegs.end(); I != E; ++I) {
326 if (!First) OS << " + "; else First = false;
327 OS << "reg(" << **I << ')';
328 }
329 if (AM.Scale != 0) {
330 if (!First) OS << " + "; else First = false;
331 OS << AM.Scale << "*reg(";
332 if (ScaledReg)
333 OS << *ScaledReg;
334 else
335 OS << "<unknown>";
336 OS << ')';
337 }
338}
339
340void Formula::dump() const {
341 print(errs()); errs() << '\n';
342}
343
Dan Gohmanaae01f12010-02-19 19:32:49 +0000344/// isAddRecSExtable - Return true if the given addrec can be sign-extended
345/// without changing its value.
346static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
347 const Type *WideTy =
348 IntegerType::get(SE.getContext(),
349 SE.getTypeSizeInBits(AR->getType()) + 1);
350 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
351}
352
353/// isAddSExtable - Return true if the given add can be sign-extended
354/// without changing its value.
355static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
356 const Type *WideTy =
357 IntegerType::get(SE.getContext(),
358 SE.getTypeSizeInBits(A->getType()) + 1);
359 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
360}
361
362/// isMulSExtable - Return true if the given add can be sign-extended
363/// without changing its value.
364static bool isMulSExtable(const SCEVMulExpr *A, ScalarEvolution &SE) {
365 const Type *WideTy =
366 IntegerType::get(SE.getContext(),
367 SE.getTypeSizeInBits(A->getType()) + 1);
368 return isa<SCEVMulExpr>(SE.getSignExtendExpr(A, WideTy));
369}
370
Dan Gohmanf09b7122010-02-19 19:35:48 +0000371/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
372/// and if the remainder is known to be zero, or null otherwise. If
373/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
374/// to Y, ignoring that the multiplication may overflow, which is useful when
375/// the result will be used in a context where the most significant bits are
376/// ignored.
377static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
378 ScalarEvolution &SE,
379 bool IgnoreSignificantBits = false) {
Dan Gohman572645c2010-02-12 10:34:29 +0000380 // Handle the trivial case, which works for any SCEV type.
381 if (LHS == RHS)
382 return SE.getIntegerSCEV(1, LHS->getType());
383
384 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
385 // folding.
386 if (RHS->isAllOnesValue())
387 return SE.getMulExpr(LHS, RHS);
388
389 // Check for a division of a constant by a constant.
390 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
391 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
392 if (!RC)
393 return 0;
394 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
395 return 0;
396 return SE.getConstant(C->getValue()->getValue()
397 .sdiv(RC->getValue()->getValue()));
398 }
399
Dan Gohmanaae01f12010-02-19 19:32:49 +0000400 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000401 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000402 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000403 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
404 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000405 if (!Start) return 0;
Dan Gohmanf09b7122010-02-19 19:35:48 +0000406 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
407 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000408 if (!Step) return 0;
409 return SE.getAddRecExpr(Start, Step, AR->getLoop());
410 }
Dan Gohman572645c2010-02-12 10:34:29 +0000411 }
412
Dan Gohmanaae01f12010-02-19 19:32:49 +0000413 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman572645c2010-02-12 10:34:29 +0000414 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanaae01f12010-02-19 19:32:49 +0000415 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
416 SmallVector<const SCEV *, 8> Ops;
417 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
418 I != E; ++I) {
Dan Gohmanf09b7122010-02-19 19:35:48 +0000419 const SCEV *Op = getExactSDiv(*I, RHS, SE,
420 IgnoreSignificantBits);
Dan Gohmanaae01f12010-02-19 19:32:49 +0000421 if (!Op) return 0;
422 Ops.push_back(Op);
423 }
424 return SE.getAddExpr(Ops);
Dan Gohman572645c2010-02-12 10:34:29 +0000425 }
Dan Gohman572645c2010-02-12 10:34:29 +0000426 }
427
428 // Check for a multiply operand that we can pull RHS out of.
429 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
Dan Gohmanaae01f12010-02-19 19:32:49 +0000430 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000431 SmallVector<const SCEV *, 4> Ops;
432 bool Found = false;
433 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
434 I != E; ++I) {
435 if (!Found)
Dan Gohmanf09b7122010-02-19 19:35:48 +0000436 if (const SCEV *Q = getExactSDiv(*I, RHS, SE,
437 IgnoreSignificantBits)) {
Dan Gohman572645c2010-02-12 10:34:29 +0000438 Ops.push_back(Q);
439 Found = true;
440 continue;
441 }
442 Ops.push_back(*I);
443 }
444 return Found ? SE.getMulExpr(Ops) : 0;
445 }
446
447 // Otherwise we don't know.
448 return 0;
449}
450
451/// ExtractImmediate - If S involves the addition of a constant integer value,
452/// return that integer value, and mutate S to point to a new SCEV with that
453/// value excluded.
454static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
455 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
456 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
457 S = SE.getIntegerSCEV(0, C->getType());
458 return C->getValue()->getSExtValue();
459 }
460 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
461 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
462 int64_t Result = ExtractImmediate(NewOps.front(), SE);
463 S = SE.getAddExpr(NewOps);
464 return Result;
465 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
466 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
467 int64_t Result = ExtractImmediate(NewOps.front(), SE);
468 S = SE.getAddRecExpr(NewOps, AR->getLoop());
469 return Result;
470 }
471 return 0;
472}
473
474/// ExtractSymbol - If S involves the addition of a GlobalValue address,
475/// return that symbol, and mutate S to point to a new SCEV with that
476/// value excluded.
477static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
478 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
479 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
480 S = SE.getIntegerSCEV(0, GV->getType());
481 return GV;
482 }
483 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
484 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
485 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
486 S = SE.getAddExpr(NewOps);
487 return Result;
488 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
489 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
490 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
491 S = SE.getAddRecExpr(NewOps, AR->getLoop());
492 return Result;
493 }
494 return 0;
Nate Begemaneaa13852004-10-18 21:08:22 +0000495}
496
Dan Gohmanf284ce22009-02-18 00:08:39 +0000497/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen203af582008-12-05 21:47:27 +0000498/// specified value as an address.
499static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
500 bool isAddress = isa<LoadInst>(Inst);
501 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
502 if (SI->getOperand(1) == OperandVal)
503 isAddress = true;
504 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
505 // Addressing modes can also be folded into prefetches and a variety
506 // of intrinsics.
507 switch (II->getIntrinsicID()) {
508 default: break;
509 case Intrinsic::prefetch:
510 case Intrinsic::x86_sse2_loadu_dq:
511 case Intrinsic::x86_sse2_loadu_pd:
512 case Intrinsic::x86_sse_loadu_ps:
513 case Intrinsic::x86_sse_storeu_ps:
514 case Intrinsic::x86_sse2_storeu_pd:
515 case Intrinsic::x86_sse2_storeu_dq:
516 case Intrinsic::x86_sse2_storel_dq:
517 if (II->getOperand(1) == OperandVal)
518 isAddress = true;
519 break;
520 }
521 }
522 return isAddress;
523}
Chris Lattner0ae33eb2005-10-03 01:04:44 +0000524
Dan Gohman21e77222009-03-09 21:01:17 +0000525/// getAccessType - Return the type of the memory being accessed.
526static const Type *getAccessType(const Instruction *Inst) {
Dan Gohmana537bf82009-05-18 16:45:28 +0000527 const Type *AccessTy = Inst->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000528 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohmana537bf82009-05-18 16:45:28 +0000529 AccessTy = SI->getOperand(0)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000530 else if (const 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::x86_sse_storeu_ps:
536 case Intrinsic::x86_sse2_storeu_pd:
537 case Intrinsic::x86_sse2_storeu_dq:
538 case Intrinsic::x86_sse2_storel_dq:
Dan Gohmana537bf82009-05-18 16:45:28 +0000539 AccessTy = II->getOperand(1)->getType();
Dan Gohman21e77222009-03-09 21:01:17 +0000540 break;
541 }
542 }
Dan Gohman572645c2010-02-12 10:34:29 +0000543
544 // All pointers have the same requirements, so canonicalize them to an
545 // arbitrary pointer type to minimize variation.
546 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
547 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
548 PTy->getAddressSpace());
549
Dan Gohmana537bf82009-05-18 16:45:28 +0000550 return AccessTy;
Dan Gohman21e77222009-03-09 21:01:17 +0000551}
552
Dan Gohman572645c2010-02-12 10:34:29 +0000553/// DeleteTriviallyDeadInstructions - If any of the instructions is the
554/// specified set are trivially dead, delete them and see if this makes any of
555/// their operands subsequently dead.
556static bool
557DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
558 bool Changed = false;
559
560 while (!DeadInsts.empty()) {
561 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
562
563 if (I == 0 || !isInstructionTriviallyDead(I))
564 continue;
565
566 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
567 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
568 *OI = 0;
569 if (U->use_empty())
570 DeadInsts.push_back(U);
571 }
572
573 I->eraseFromParent();
574 Changed = true;
575 }
576
577 return Changed;
578}
579
Dan Gohman7979b722010-01-22 00:46:49 +0000580namespace {
Jim Grosbach56a1f802009-11-17 17:53:56 +0000581
Dan Gohman572645c2010-02-12 10:34:29 +0000582/// Cost - This class is used to measure and compare candidate formulae.
583class Cost {
584 /// TODO: Some of these could be merged. Also, a lexical ordering
585 /// isn't always optimal.
586 unsigned NumRegs;
587 unsigned AddRecCost;
588 unsigned NumIVMuls;
589 unsigned NumBaseAdds;
590 unsigned ImmCost;
591 unsigned SetupCost;
Nate Begeman16997482005-07-30 00:15:07 +0000592
Dan Gohman572645c2010-02-12 10:34:29 +0000593public:
594 Cost()
595 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
596 SetupCost(0) {}
Jim Grosbach56a1f802009-11-17 17:53:56 +0000597
Dan Gohman572645c2010-02-12 10:34:29 +0000598 unsigned getNumRegs() const { return NumRegs; }
Dan Gohman7979b722010-01-22 00:46:49 +0000599
Dan Gohman572645c2010-02-12 10:34:29 +0000600 bool operator<(const Cost &Other) const;
Dan Gohman7979b722010-01-22 00:46:49 +0000601
Dan Gohman572645c2010-02-12 10:34:29 +0000602 void Loose();
Dan Gohman7979b722010-01-22 00:46:49 +0000603
Dan Gohman572645c2010-02-12 10:34:29 +0000604 void RateFormula(const Formula &F,
605 SmallPtrSet<const SCEV *, 16> &Regs,
606 const DenseSet<const SCEV *> &VisitedRegs,
607 const Loop *L,
608 const SmallVectorImpl<int64_t> &Offsets,
609 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman7979b722010-01-22 00:46:49 +0000610
Dan Gohman572645c2010-02-12 10:34:29 +0000611 void print(raw_ostream &OS) const;
612 void dump() const;
Dan Gohman7979b722010-01-22 00:46:49 +0000613
Dan Gohman572645c2010-02-12 10:34:29 +0000614private:
615 void RateRegister(const SCEV *Reg,
616 SmallPtrSet<const SCEV *, 16> &Regs,
617 const Loop *L,
618 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman9214b822010-02-13 02:06:02 +0000619 void RatePrimaryRegister(const SCEV *Reg,
620 SmallPtrSet<const SCEV *, 16> &Regs,
621 const Loop *L,
622 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000623};
624
625}
626
627/// RateRegister - Tally up interesting quantities from the given register.
628void Cost::RateRegister(const SCEV *Reg,
629 SmallPtrSet<const SCEV *, 16> &Regs,
630 const Loop *L,
631 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000632 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
633 if (AR->getLoop() == L)
634 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman572645c2010-02-12 10:34:29 +0000635
Dan Gohman9214b822010-02-13 02:06:02 +0000636 // If this is an addrec for a loop that's already been visited by LSR,
637 // don't second-guess its addrec phi nodes. LSR isn't currently smart
638 // enough to reason about more than one loop at a time. Consider these
639 // registers free and leave them alone.
640 else if (L->contains(AR->getLoop()) ||
641 (!AR->getLoop()->contains(L) &&
642 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
643 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
644 PHINode *PN = dyn_cast<PHINode>(I); ++I)
645 if (SE.isSCEVable(PN->getType()) &&
646 (SE.getEffectiveSCEVType(PN->getType()) ==
647 SE.getEffectiveSCEVType(AR->getType())) &&
648 SE.getSCEV(PN) == AR)
649 return;
Dan Gohman572645c2010-02-12 10:34:29 +0000650
Dan Gohman9214b822010-02-13 02:06:02 +0000651 // If this isn't one of the addrecs that the loop already has, it
652 // would require a costly new phi and add. TODO: This isn't
653 // precisely modeled right now.
654 ++NumBaseAdds;
655 if (!Regs.count(AR->getStart()))
Dan Gohman572645c2010-02-12 10:34:29 +0000656 RateRegister(AR->getStart(), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000657 }
Dan Gohman572645c2010-02-12 10:34:29 +0000658
Dan Gohman9214b822010-02-13 02:06:02 +0000659 // Add the step value register, if it needs one.
660 // TODO: The non-affine case isn't precisely modeled here.
661 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
662 if (!Regs.count(AR->getStart()))
663 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000664 }
Dan Gohman9214b822010-02-13 02:06:02 +0000665 ++NumRegs;
666
667 // Rough heuristic; favor registers which don't require extra setup
668 // instructions in the preheader.
669 if (!isa<SCEVUnknown>(Reg) &&
670 !isa<SCEVConstant>(Reg) &&
671 !(isa<SCEVAddRecExpr>(Reg) &&
672 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
673 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
674 ++SetupCost;
675}
676
677/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
678/// before, rate it.
679void Cost::RatePrimaryRegister(const SCEV *Reg,
Dan Gohman7fca2292010-02-16 19:42:34 +0000680 SmallPtrSet<const SCEV *, 16> &Regs,
681 const Loop *L,
682 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman9214b822010-02-13 02:06:02 +0000683 if (Regs.insert(Reg))
684 RateRegister(Reg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000685}
686
687void Cost::RateFormula(const Formula &F,
688 SmallPtrSet<const SCEV *, 16> &Regs,
689 const DenseSet<const SCEV *> &VisitedRegs,
690 const Loop *L,
691 const SmallVectorImpl<int64_t> &Offsets,
692 ScalarEvolution &SE, DominatorTree &DT) {
693 // Tally up the registers.
694 if (const SCEV *ScaledReg = F.ScaledReg) {
695 if (VisitedRegs.count(ScaledReg)) {
696 Loose();
697 return;
698 }
Dan Gohman9214b822010-02-13 02:06:02 +0000699 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000700 }
701 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
702 E = F.BaseRegs.end(); I != E; ++I) {
703 const SCEV *BaseReg = *I;
704 if (VisitedRegs.count(BaseReg)) {
705 Loose();
706 return;
707 }
Dan Gohman9214b822010-02-13 02:06:02 +0000708 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +0000709
710 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
711 BaseReg->hasComputableLoopEvolution(L);
712 }
713
714 if (F.BaseRegs.size() > 1)
715 NumBaseAdds += F.BaseRegs.size() - 1;
716
717 // Tally up the non-zero immediates.
718 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
719 E = Offsets.end(); I != E; ++I) {
720 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
721 if (F.AM.BaseGV)
722 ImmCost += 64; // Handle symbolic values conservatively.
723 // TODO: This should probably be the pointer size.
724 else if (Offset != 0)
725 ImmCost += APInt(64, Offset, true).getMinSignedBits();
726 }
727}
728
729/// Loose - Set this cost to a loosing value.
730void Cost::Loose() {
731 NumRegs = ~0u;
732 AddRecCost = ~0u;
733 NumIVMuls = ~0u;
734 NumBaseAdds = ~0u;
735 ImmCost = ~0u;
736 SetupCost = ~0u;
737}
738
739/// operator< - Choose the lower cost.
740bool Cost::operator<(const Cost &Other) const {
741 if (NumRegs != Other.NumRegs)
742 return NumRegs < Other.NumRegs;
743 if (AddRecCost != Other.AddRecCost)
744 return AddRecCost < Other.AddRecCost;
745 if (NumIVMuls != Other.NumIVMuls)
746 return NumIVMuls < Other.NumIVMuls;
747 if (NumBaseAdds != Other.NumBaseAdds)
748 return NumBaseAdds < Other.NumBaseAdds;
749 if (ImmCost != Other.ImmCost)
750 return ImmCost < Other.ImmCost;
751 if (SetupCost != Other.SetupCost)
752 return SetupCost < Other.SetupCost;
753 return false;
754}
755
756void Cost::print(raw_ostream &OS) const {
757 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
758 if (AddRecCost != 0)
759 OS << ", with addrec cost " << AddRecCost;
760 if (NumIVMuls != 0)
761 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
762 if (NumBaseAdds != 0)
763 OS << ", plus " << NumBaseAdds << " base add"
764 << (NumBaseAdds == 1 ? "" : "s");
765 if (ImmCost != 0)
766 OS << ", plus " << ImmCost << " imm cost";
767 if (SetupCost != 0)
768 OS << ", plus " << SetupCost << " setup cost";
769}
770
771void Cost::dump() const {
772 print(errs()); errs() << '\n';
773}
774
775namespace {
776
777/// LSRFixup - An operand value in an instruction which is to be replaced
778/// with some equivalent, possibly strength-reduced, replacement.
779struct LSRFixup {
780 /// UserInst - The instruction which will be updated.
781 Instruction *UserInst;
782
783 /// OperandValToReplace - The operand of the instruction which will
784 /// be replaced. The operand may be used more than once; every instance
785 /// will be replaced.
786 Value *OperandValToReplace;
787
Dan Gohman448db1c2010-04-07 22:27:08 +0000788 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman572645c2010-02-12 10:34:29 +0000789 /// induction variable, this variable is non-null and holds the loop
790 /// associated with the induction variable.
Dan Gohman448db1c2010-04-07 22:27:08 +0000791 PostIncLoopSet PostIncLoops;
Dan Gohman572645c2010-02-12 10:34:29 +0000792
793 /// LUIdx - The index of the LSRUse describing the expression which
794 /// this fixup needs, minus an offset (below).
795 size_t LUIdx;
796
797 /// Offset - A constant offset to be added to the LSRUse expression.
798 /// This allows multiple fixups to share the same LSRUse with different
799 /// offsets, for example in an unrolled loop.
800 int64_t Offset;
801
Dan Gohman448db1c2010-04-07 22:27:08 +0000802 bool isUseFullyOutsideLoop(const Loop *L) const;
803
Dan Gohman572645c2010-02-12 10:34:29 +0000804 LSRFixup();
805
806 void print(raw_ostream &OS) const;
807 void dump() const;
808};
809
810}
811
812LSRFixup::LSRFixup()
Dan Gohman448db1c2010-04-07 22:27:08 +0000813 : UserInst(0), OperandValToReplace(0),
Dan Gohman572645c2010-02-12 10:34:29 +0000814 LUIdx(~size_t(0)), Offset(0) {}
815
Dan Gohman448db1c2010-04-07 22:27:08 +0000816/// isUseFullyOutsideLoop - Test whether this fixup always uses its
817/// value outside of the given loop.
818bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
819 // PHI nodes use their value in their incoming blocks.
820 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
821 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
822 if (PN->getIncomingValue(i) == OperandValToReplace &&
823 L->contains(PN->getIncomingBlock(i)))
824 return false;
825 return true;
826 }
827
828 return !L->contains(UserInst);
829}
830
Dan Gohman572645c2010-02-12 10:34:29 +0000831void LSRFixup::print(raw_ostream &OS) const {
832 OS << "UserInst=";
833 // Store is common and interesting enough to be worth special-casing.
834 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
835 OS << "store ";
836 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
837 } else if (UserInst->getType()->isVoidTy())
838 OS << UserInst->getOpcodeName();
839 else
840 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
841
842 OS << ", OperandValToReplace=";
843 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
844
Dan Gohman448db1c2010-04-07 22:27:08 +0000845 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
846 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman572645c2010-02-12 10:34:29 +0000847 OS << ", PostIncLoop=";
Dan Gohman448db1c2010-04-07 22:27:08 +0000848 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
Dan Gohman572645c2010-02-12 10:34:29 +0000849 }
850
851 if (LUIdx != ~size_t(0))
852 OS << ", LUIdx=" << LUIdx;
853
854 if (Offset != 0)
855 OS << ", Offset=" << Offset;
856}
857
858void LSRFixup::dump() const {
859 print(errs()); errs() << '\n';
860}
861
862namespace {
863
864/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
865/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
866struct UniquifierDenseMapInfo {
867 static SmallVector<const SCEV *, 2> getEmptyKey() {
868 SmallVector<const SCEV *, 2> V;
869 V.push_back(reinterpret_cast<const SCEV *>(-1));
870 return V;
871 }
872
873 static SmallVector<const SCEV *, 2> getTombstoneKey() {
874 SmallVector<const SCEV *, 2> V;
875 V.push_back(reinterpret_cast<const SCEV *>(-2));
876 return V;
877 }
878
879 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
880 unsigned Result = 0;
881 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
882 E = V.end(); I != E; ++I)
883 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
884 return Result;
885 }
886
887 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
888 const SmallVector<const SCEV *, 2> &RHS) {
889 return LHS == RHS;
890 }
891};
892
893/// LSRUse - This class holds the state that LSR keeps for each use in
894/// IVUsers, as well as uses invented by LSR itself. It includes information
895/// about what kinds of things can be folded into the user, information about
896/// the user itself, and information about how the use may be satisfied.
897/// TODO: Represent multiple users of the same expression in common?
898class LSRUse {
899 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
900
901public:
902 /// KindType - An enum for a kind of use, indicating what types of
903 /// scaled and immediate operands it might support.
904 enum KindType {
905 Basic, ///< A normal use, with no folding.
906 Special, ///< A special case of basic, allowing -1 scales.
907 Address, ///< An address use; folding according to TargetLowering
908 ICmpZero ///< An equality icmp with both operands folded into one.
909 // TODO: Add a generic icmp too?
Dan Gohman7979b722010-01-22 00:46:49 +0000910 };
Dan Gohman572645c2010-02-12 10:34:29 +0000911
912 KindType Kind;
913 const Type *AccessTy;
914
915 SmallVector<int64_t, 8> Offsets;
916 int64_t MinOffset;
917 int64_t MaxOffset;
918
919 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
920 /// LSRUse are outside of the loop, in which case some special-case heuristics
921 /// may be used.
922 bool AllFixupsOutsideLoop;
923
924 /// Formulae - A list of ways to build a value that can satisfy this user.
925 /// After the list is populated, one of these is selected heuristically and
926 /// used to formulate a replacement for OperandValToReplace in UserInst.
927 SmallVector<Formula, 12> Formulae;
928
929 /// Regs - The set of register candidates used by all formulae in this LSRUse.
930 SmallPtrSet<const SCEV *, 4> Regs;
931
932 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
933 MinOffset(INT64_MAX),
934 MaxOffset(INT64_MIN),
935 AllFixupsOutsideLoop(true) {}
936
Dan Gohman454d26d2010-02-22 04:11:59 +0000937 bool InsertFormula(const Formula &F);
Dan Gohman572645c2010-02-12 10:34:29 +0000938
939 void check() const;
940
941 void print(raw_ostream &OS) const;
942 void dump() const;
943};
944
945/// InsertFormula - If the given formula has not yet been inserted, add it to
946/// the list, and return true. Return false otherwise.
Dan Gohman454d26d2010-02-22 04:11:59 +0000947bool LSRUse::InsertFormula(const Formula &F) {
Dan Gohman572645c2010-02-12 10:34:29 +0000948 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
949 if (F.ScaledReg) Key.push_back(F.ScaledReg);
950 // Unstable sort by host order ok, because this is only used for uniquifying.
951 std::sort(Key.begin(), Key.end());
952
953 if (!Uniquifier.insert(Key).second)
954 return false;
955
956 // Using a register to hold the value of 0 is not profitable.
957 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
958 "Zero allocated in a scaled register!");
959#ifndef NDEBUG
960 for (SmallVectorImpl<const SCEV *>::const_iterator I =
961 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
962 assert(!(*I)->isZero() && "Zero allocated in a base register!");
963#endif
964
965 // Add the formula to the list.
966 Formulae.push_back(F);
967
968 // Record registers now being used by this use.
969 if (F.ScaledReg) Regs.insert(F.ScaledReg);
970 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
971
972 return true;
Dan Gohman7979b722010-01-22 00:46:49 +0000973}
974
Dan Gohman572645c2010-02-12 10:34:29 +0000975void LSRUse::print(raw_ostream &OS) const {
976 OS << "LSR Use: Kind=";
977 switch (Kind) {
978 case Basic: OS << "Basic"; break;
979 case Special: OS << "Special"; break;
980 case ICmpZero: OS << "ICmpZero"; break;
981 case Address:
982 OS << "Address of ";
Duncan Sands1df98592010-02-16 11:11:14 +0000983 if (AccessTy->isPointerTy())
Dan Gohman572645c2010-02-12 10:34:29 +0000984 OS << "pointer"; // the full pointer type could be really verbose
985 else
986 OS << *AccessTy;
Evan Chengcdf43b12007-10-25 09:11:16 +0000987 }
988
Dan Gohman572645c2010-02-12 10:34:29 +0000989 OS << ", Offsets={";
990 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
991 E = Offsets.end(); I != E; ++I) {
992 OS << *I;
993 if (next(I) != E)
994 OS << ',';
Dan Gohman7979b722010-01-22 00:46:49 +0000995 }
Dan Gohman572645c2010-02-12 10:34:29 +0000996 OS << '}';
Dan Gohman7979b722010-01-22 00:46:49 +0000997
Dan Gohman572645c2010-02-12 10:34:29 +0000998 if (AllFixupsOutsideLoop)
999 OS << ", all-fixups-outside-loop";
Dan Gohman7979b722010-01-22 00:46:49 +00001000}
1001
Dan Gohman572645c2010-02-12 10:34:29 +00001002void LSRUse::dump() const {
1003 print(errs()); errs() << '\n';
1004}
Dan Gohman7979b722010-01-22 00:46:49 +00001005
Dan Gohman572645c2010-02-12 10:34:29 +00001006/// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1007/// be completely folded into the user instruction at isel time. This includes
1008/// address-mode folding and special icmp tricks.
1009static bool isLegalUse(const TargetLowering::AddrMode &AM,
1010 LSRUse::KindType Kind, const Type *AccessTy,
1011 const TargetLowering *TLI) {
1012 switch (Kind) {
1013 case LSRUse::Address:
1014 // If we have low-level target information, ask the target if it can
1015 // completely fold this address.
1016 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1017
1018 // Otherwise, just guess that reg+reg addressing is legal.
1019 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1020
1021 case LSRUse::ICmpZero:
1022 // There's not even a target hook for querying whether it would be legal to
1023 // fold a GV into an ICmp.
1024 if (AM.BaseGV)
1025 return false;
1026
1027 // ICmp only has two operands; don't allow more than two non-trivial parts.
1028 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1029 return false;
1030
1031 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1032 // putting the scaled register in the other operand of the icmp.
1033 if (AM.Scale != 0 && AM.Scale != -1)
1034 return false;
1035
1036 // If we have low-level target information, ask the target if it can fold an
1037 // integer immediate on an icmp.
1038 if (AM.BaseOffs != 0) {
1039 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1040 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001041 }
Dan Gohman572645c2010-02-12 10:34:29 +00001042
1043 return true;
1044
1045 case LSRUse::Basic:
1046 // Only handle single-register values.
1047 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1048
1049 case LSRUse::Special:
1050 // Only handle -1 scales, or no scale.
1051 return AM.Scale == 0 || AM.Scale == -1;
Dan Gohman7979b722010-01-22 00:46:49 +00001052 }
1053
Dan Gohman7979b722010-01-22 00:46:49 +00001054 return false;
1055}
1056
Dan Gohman572645c2010-02-12 10:34:29 +00001057static bool isLegalUse(TargetLowering::AddrMode AM,
1058 int64_t MinOffset, int64_t MaxOffset,
1059 LSRUse::KindType Kind, const Type *AccessTy,
1060 const TargetLowering *TLI) {
1061 // Check for overflow.
1062 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1063 (MinOffset > 0))
1064 return false;
1065 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1066 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1067 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1068 // Check for overflow.
1069 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1070 (MaxOffset > 0))
1071 return false;
1072 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1073 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001074 }
Dan Gohman572645c2010-02-12 10:34:29 +00001075 return false;
Dan Gohman7979b722010-01-22 00:46:49 +00001076}
1077
Dan Gohman572645c2010-02-12 10:34:29 +00001078static bool isAlwaysFoldable(int64_t BaseOffs,
1079 GlobalValue *BaseGV,
1080 bool HasBaseReg,
1081 LSRUse::KindType Kind, const Type *AccessTy,
Dan Gohman454d26d2010-02-22 04:11:59 +00001082 const TargetLowering *TLI) {
Dan Gohman572645c2010-02-12 10:34:29 +00001083 // Fast-path: zero is always foldable.
1084 if (BaseOffs == 0 && !BaseGV) return true;
Dan Gohman7979b722010-01-22 00:46:49 +00001085
Dan Gohman572645c2010-02-12 10:34:29 +00001086 // Conservatively, create an address with an immediate and a
1087 // base and a scale.
1088 TargetLowering::AddrMode AM;
1089 AM.BaseOffs = BaseOffs;
1090 AM.BaseGV = BaseGV;
1091 AM.HasBaseReg = HasBaseReg;
1092 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001093
Dan Gohman572645c2010-02-12 10:34:29 +00001094 return isLegalUse(AM, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001095}
1096
Dan Gohman572645c2010-02-12 10:34:29 +00001097static bool isAlwaysFoldable(const SCEV *S,
1098 int64_t MinOffset, int64_t MaxOffset,
1099 bool HasBaseReg,
1100 LSRUse::KindType Kind, const Type *AccessTy,
1101 const TargetLowering *TLI,
1102 ScalarEvolution &SE) {
1103 // Fast-path: zero is always foldable.
1104 if (S->isZero()) return true;
1105
1106 // Conservatively, create an address with an immediate and a
1107 // base and a scale.
1108 int64_t BaseOffs = ExtractImmediate(S, SE);
1109 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1110
1111 // If there's anything else involved, it's not foldable.
1112 if (!S->isZero()) return false;
1113
1114 // Fast-path: zero is always foldable.
1115 if (BaseOffs == 0 && !BaseGV) return true;
1116
1117 // Conservatively, create an address with an immediate and a
1118 // base and a scale.
1119 TargetLowering::AddrMode AM;
1120 AM.BaseOffs = BaseOffs;
1121 AM.BaseGV = BaseGV;
1122 AM.HasBaseReg = HasBaseReg;
1123 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1124
1125 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
Dan Gohman7979b722010-01-22 00:46:49 +00001126}
1127
Dan Gohman572645c2010-02-12 10:34:29 +00001128/// FormulaSorter - This class implements an ordering for formulae which sorts
1129/// the by their standalone cost.
1130class FormulaSorter {
1131 /// These two sets are kept empty, so that we compute standalone costs.
1132 DenseSet<const SCEV *> VisitedRegs;
1133 SmallPtrSet<const SCEV *, 16> Regs;
1134 Loop *L;
1135 LSRUse *LU;
1136 ScalarEvolution &SE;
1137 DominatorTree &DT;
1138
1139public:
1140 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1141 : L(l), LU(&lu), SE(se), DT(dt) {}
1142
1143 bool operator()(const Formula &A, const Formula &B) {
1144 Cost CostA;
1145 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1146 Regs.clear();
1147 Cost CostB;
1148 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1149 Regs.clear();
1150 return CostA < CostB;
1151 }
1152};
1153
1154/// LSRInstance - This class holds state for the main loop strength reduction
1155/// logic.
1156class LSRInstance {
1157 IVUsers &IU;
1158 ScalarEvolution &SE;
1159 DominatorTree &DT;
1160 const TargetLowering *const TLI;
1161 Loop *const L;
1162 bool Changed;
1163
1164 /// IVIncInsertPos - This is the insert position that the current loop's
1165 /// induction variable increment should be placed. In simple loops, this is
1166 /// the latch block's terminator. But in more complicated cases, this is a
1167 /// position which will dominate all the in-loop post-increment users.
1168 Instruction *IVIncInsertPos;
1169
1170 /// Factors - Interesting factors between use strides.
1171 SmallSetVector<int64_t, 8> Factors;
1172
1173 /// Types - Interesting use types, to facilitate truncation reuse.
1174 SmallSetVector<const Type *, 4> Types;
1175
1176 /// Fixups - The list of operands which are to be replaced.
1177 SmallVector<LSRFixup, 16> Fixups;
1178
1179 /// Uses - The list of interesting uses.
1180 SmallVector<LSRUse, 16> Uses;
1181
1182 /// RegUses - Track which uses use which register candidates.
1183 RegUseTracker RegUses;
1184
1185 void OptimizeShadowIV();
1186 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1187 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1188 bool OptimizeLoopTermCond();
1189
1190 void CollectInterestingTypesAndFactors();
1191 void CollectFixupsAndInitialFormulae();
1192
1193 LSRFixup &getNewFixup() {
1194 Fixups.push_back(LSRFixup());
1195 return Fixups.back();
1196 }
1197
1198 // Support for sharing of LSRUses between LSRFixups.
1199 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1200 UseMapTy UseMap;
1201
1202 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1203 LSRUse::KindType Kind, const Type *AccessTy);
1204
1205 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1206 LSRUse::KindType Kind,
1207 const Type *AccessTy);
1208
1209public:
Dan Gohman454d26d2010-02-22 04:11:59 +00001210 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001211 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1212 void CountRegisters(const Formula &F, size_t LUIdx);
1213 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1214
1215 void CollectLoopInvariantFixupsAndFormulae();
1216
1217 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1218 unsigned Depth = 0);
1219 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1220 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1221 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1222 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1223 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1224 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1225 void GenerateCrossUseConstantOffsets();
1226 void GenerateAllReuseFormulae();
1227
1228 void FilterOutUndesirableDedicatedRegisters();
1229 void NarrowSearchSpaceUsingHeuristics();
1230
1231 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1232 Cost &SolutionCost,
1233 SmallVectorImpl<const Formula *> &Workspace,
1234 const Cost &CurCost,
1235 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1236 DenseSet<const SCEV *> &VisitedRegs) const;
1237 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1238
Dan Gohmand96eae82010-04-09 02:00:38 +00001239 BasicBlock::iterator AdjustInputPositionForExpand(BasicBlock::iterator IP,
1240 const LSRFixup &LF,
1241 const LSRUse &LU) const;
1242
Dan Gohman572645c2010-02-12 10:34:29 +00001243 Value *Expand(const LSRFixup &LF,
1244 const Formula &F,
Dan Gohman454d26d2010-02-22 04:11:59 +00001245 BasicBlock::iterator IP,
Dan Gohman572645c2010-02-12 10:34:29 +00001246 SCEVExpander &Rewriter,
Dan Gohman454d26d2010-02-22 04:11:59 +00001247 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001248 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1249 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001250 SCEVExpander &Rewriter,
1251 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00001252 Pass *P) const;
Dan Gohman572645c2010-02-12 10:34:29 +00001253 void Rewrite(const LSRFixup &LF,
1254 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00001255 SCEVExpander &Rewriter,
1256 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00001257 Pass *P) const;
1258 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1259 Pass *P);
1260
1261 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1262
1263 bool getChanged() const { return Changed; }
1264
1265 void print_factors_and_types(raw_ostream &OS) const;
1266 void print_fixups(raw_ostream &OS) const;
1267 void print_uses(raw_ostream &OS) const;
1268 void print(raw_ostream &OS) const;
1269 void dump() const;
1270};
1271
1272}
1273
1274/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001275/// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00001276void LSRInstance::OptimizeShadowIV() {
1277 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1278 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1279 return;
1280
1281 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1282 UI != E; /* empty */) {
1283 IVUsers::const_iterator CandidateUI = UI;
1284 ++UI;
1285 Instruction *ShadowUse = CandidateUI->getUser();
1286 const Type *DestTy = NULL;
1287
1288 /* If shadow use is a int->float cast then insert a second IV
1289 to eliminate this cast.
1290
1291 for (unsigned i = 0; i < n; ++i)
1292 foo((double)i);
1293
1294 is transformed into
1295
1296 double d = 0.0;
1297 for (unsigned i = 0; i < n; ++i, ++d)
1298 foo(d);
1299 */
1300 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1301 DestTy = UCast->getDestTy();
1302 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1303 DestTy = SCast->getDestTy();
1304 if (!DestTy) continue;
1305
1306 if (TLI) {
1307 // If target does not support DestTy natively then do not apply
1308 // this transformation.
1309 EVT DVT = TLI->getValueType(DestTy);
1310 if (!TLI->isTypeLegal(DVT)) continue;
1311 }
1312
1313 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1314 if (!PH) continue;
1315 if (PH->getNumIncomingValues() != 2) continue;
1316
1317 const Type *SrcTy = PH->getType();
1318 int Mantissa = DestTy->getFPMantissaWidth();
1319 if (Mantissa == -1) continue;
1320 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1321 continue;
1322
1323 unsigned Entry, Latch;
1324 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1325 Entry = 0;
1326 Latch = 1;
Dan Gohman7979b722010-01-22 00:46:49 +00001327 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001328 Entry = 1;
1329 Latch = 0;
Dan Gohman7979b722010-01-22 00:46:49 +00001330 }
Dan Gohman7979b722010-01-22 00:46:49 +00001331
Dan Gohman572645c2010-02-12 10:34:29 +00001332 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1333 if (!Init) continue;
1334 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
Dan Gohman7979b722010-01-22 00:46:49 +00001335
Dan Gohman572645c2010-02-12 10:34:29 +00001336 BinaryOperator *Incr =
1337 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1338 if (!Incr) continue;
1339 if (Incr->getOpcode() != Instruction::Add
1340 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman7979b722010-01-22 00:46:49 +00001341 continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001342
Dan Gohman572645c2010-02-12 10:34:29 +00001343 /* Initialize new IV, double d = 0.0 in above example. */
1344 ConstantInt *C = NULL;
1345 if (Incr->getOperand(0) == PH)
1346 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1347 else if (Incr->getOperand(1) == PH)
1348 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001349 else
Dan Gohman7979b722010-01-22 00:46:49 +00001350 continue;
1351
Dan Gohman572645c2010-02-12 10:34:29 +00001352 if (!C) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001353
Dan Gohman572645c2010-02-12 10:34:29 +00001354 // Ignore negative constants, as the code below doesn't handle them
1355 // correctly. TODO: Remove this restriction.
1356 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman7979b722010-01-22 00:46:49 +00001357
Dan Gohman572645c2010-02-12 10:34:29 +00001358 /* Add new PHINode. */
1359 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
Dan Gohman7979b722010-01-22 00:46:49 +00001360
Dan Gohman572645c2010-02-12 10:34:29 +00001361 /* create new increment. '++d' in above example. */
1362 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1363 BinaryOperator *NewIncr =
1364 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1365 Instruction::FAdd : Instruction::FSub,
1366 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman7979b722010-01-22 00:46:49 +00001367
Dan Gohman572645c2010-02-12 10:34:29 +00001368 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1369 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman7979b722010-01-22 00:46:49 +00001370
Dan Gohman572645c2010-02-12 10:34:29 +00001371 /* Remove cast operation */
1372 ShadowUse->replaceAllUsesWith(NewPH);
1373 ShadowUse->eraseFromParent();
1374 break;
Dan Gohman7979b722010-01-22 00:46:49 +00001375 }
1376}
1377
1378/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1379/// set the IV user and stride information and return true, otherwise return
1380/// false.
Dan Gohman572645c2010-02-12 10:34:29 +00001381bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1382 IVStrideUse *&CondUse) {
1383 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1384 if (UI->getUser() == Cond) {
1385 // NOTE: we could handle setcc instructions with multiple uses here, but
1386 // InstCombine does it as well for simple uses, it's not clear that it
1387 // occurs enough in real life to handle.
1388 CondUse = UI;
1389 return true;
1390 }
Dan Gohman7979b722010-01-22 00:46:49 +00001391 return false;
Evan Chengcdf43b12007-10-25 09:11:16 +00001392}
1393
Dan Gohman7979b722010-01-22 00:46:49 +00001394/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1395/// a max computation.
1396///
1397/// This is a narrow solution to a specific, but acute, problem. For loops
1398/// like this:
1399///
1400/// i = 0;
1401/// do {
1402/// p[i] = 0.0;
1403/// } while (++i < n);
1404///
1405/// the trip count isn't just 'n', because 'n' might not be positive. And
1406/// unfortunately this can come up even for loops where the user didn't use
1407/// a C do-while loop. For example, seemingly well-behaved top-test loops
1408/// will commonly be lowered like this:
1409//
1410/// if (n > 0) {
1411/// i = 0;
1412/// do {
1413/// p[i] = 0.0;
1414/// } while (++i < n);
1415/// }
1416///
1417/// and then it's possible for subsequent optimization to obscure the if
1418/// test in such a way that indvars can't find it.
1419///
1420/// When indvars can't find the if test in loops like this, it creates a
1421/// max expression, which allows it to give the loop a canonical
1422/// induction variable:
1423///
1424/// i = 0;
1425/// max = n < 1 ? 1 : n;
1426/// do {
1427/// p[i] = 0.0;
1428/// } while (++i != max);
1429///
1430/// Canonical induction variables are necessary because the loop passes
1431/// are designed around them. The most obvious example of this is the
1432/// LoopInfo analysis, which doesn't remember trip count values. It
1433/// expects to be able to rediscover the trip count each time it is
Dan Gohman572645c2010-02-12 10:34:29 +00001434/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman7979b722010-01-22 00:46:49 +00001435/// the loop has a canonical induction variable.
1436///
1437/// However, when it comes time to generate code, the maximum operation
1438/// can be quite costly, especially if it's inside of an outer loop.
1439///
1440/// This function solves this problem by detecting this type of loop and
1441/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1442/// the instructions for the maximum computation.
1443///
Dan Gohman572645c2010-02-12 10:34:29 +00001444ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman7979b722010-01-22 00:46:49 +00001445 // Check that the loop matches the pattern we're looking for.
1446 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1447 Cond->getPredicate() != CmpInst::ICMP_NE)
1448 return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001449
Dan Gohman7979b722010-01-22 00:46:49 +00001450 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1451 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohmana10756e2010-01-21 02:09:26 +00001452
Dan Gohman572645c2010-02-12 10:34:29 +00001453 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman7979b722010-01-22 00:46:49 +00001454 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1455 return Cond;
Dan Gohman572645c2010-02-12 10:34:29 +00001456 const SCEV *One = SE.getIntegerSCEV(1, BackedgeTakenCount->getType());
Dan Gohmana10756e2010-01-21 02:09:26 +00001457
Dan Gohman7979b722010-01-22 00:46:49 +00001458 // Add one to the backedge-taken count to get the trip count.
Dan Gohman572645c2010-02-12 10:34:29 +00001459 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
Dan Gohman7979b722010-01-22 00:46:49 +00001460
1461 // Check for a max calculation that matches the pattern.
1462 if (!isa<SCEVSMaxExpr>(IterationCount) && !isa<SCEVUMaxExpr>(IterationCount))
1463 return Cond;
1464 const SCEVNAryExpr *Max = cast<SCEVNAryExpr>(IterationCount);
Dan Gohman572645c2010-02-12 10:34:29 +00001465 if (Max != SE.getSCEV(Sel)) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001466
1467 // To handle a max with more than two operands, this optimization would
1468 // require additional checking and setup.
1469 if (Max->getNumOperands() != 2)
1470 return Cond;
1471
1472 const SCEV *MaxLHS = Max->getOperand(0);
1473 const SCEV *MaxRHS = Max->getOperand(1);
1474 if (!MaxLHS || MaxLHS != One) return Cond;
Dan Gohman7979b722010-01-22 00:46:49 +00001475 // Check the relevant induction variable for conformance to
1476 // the pattern.
Dan Gohman572645c2010-02-12 10:34:29 +00001477 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman7979b722010-01-22 00:46:49 +00001478 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1479 if (!AR || !AR->isAffine() ||
1480 AR->getStart() != One ||
Dan Gohman572645c2010-02-12 10:34:29 +00001481 AR->getStepRecurrence(SE) != One)
Dan Gohman7979b722010-01-22 00:46:49 +00001482 return Cond;
1483
1484 assert(AR->getLoop() == L &&
1485 "Loop condition operand is an addrec in a different loop!");
1486
1487 // Check the right operand of the select, and remember it, as it will
1488 // be used in the new comparison instruction.
1489 Value *NewRHS = 0;
Dan Gohman572645c2010-02-12 10:34:29 +00001490 if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001491 NewRHS = Sel->getOperand(1);
Dan Gohman572645c2010-02-12 10:34:29 +00001492 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman7979b722010-01-22 00:46:49 +00001493 NewRHS = Sel->getOperand(2);
1494 if (!NewRHS) return Cond;
1495
1496 // Determine the new comparison opcode. It may be signed or unsigned,
1497 // and the original comparison may be either equality or inequality.
1498 CmpInst::Predicate Pred =
1499 isa<SCEVSMaxExpr>(Max) ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
1500 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1501 Pred = CmpInst::getInversePredicate(Pred);
1502
1503 // Ok, everything looks ok to change the condition into an SLT or SGE and
1504 // delete the max calculation.
1505 ICmpInst *NewCond =
1506 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1507
1508 // Delete the max calculation instructions.
1509 Cond->replaceAllUsesWith(NewCond);
1510 CondUse->setUser(NewCond);
1511 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1512 Cond->eraseFromParent();
1513 Sel->eraseFromParent();
1514 if (Cmp->use_empty())
1515 Cmp->eraseFromParent();
1516 return NewCond;
Dan Gohmanad7321f2008-09-15 21:22:06 +00001517}
1518
Jim Grosbach56a1f802009-11-17 17:53:56 +00001519/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng586f69a2009-11-12 07:35:05 +00001520/// postinc iv when possible.
Dan Gohman572645c2010-02-12 10:34:29 +00001521bool
1522LSRInstance::OptimizeLoopTermCond() {
1523 SmallPtrSet<Instruction *, 4> PostIncs;
1524
Evan Cheng586f69a2009-11-12 07:35:05 +00001525 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Cheng076e0852009-11-17 18:10:11 +00001526 SmallVector<BasicBlock*, 8> ExitingBlocks;
1527 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach56a1f802009-11-17 17:53:56 +00001528
Evan Cheng076e0852009-11-17 18:10:11 +00001529 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1530 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng586f69a2009-11-12 07:35:05 +00001531
Dan Gohman572645c2010-02-12 10:34:29 +00001532 // Get the terminating condition for the loop if possible. If we
Evan Cheng076e0852009-11-17 18:10:11 +00001533 // can, we want to change it to use a post-incremented version of its
1534 // induction variable, to allow coalescing the live ranges for the IV into
1535 // one register value.
Evan Cheng586f69a2009-11-12 07:35:05 +00001536
Evan Cheng076e0852009-11-17 18:10:11 +00001537 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1538 if (!TermBr)
1539 continue;
1540 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1541 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1542 continue;
Evan Cheng586f69a2009-11-12 07:35:05 +00001543
Evan Cheng076e0852009-11-17 18:10:11 +00001544 // Search IVUsesByStride to find Cond's IVUse if there is one.
1545 IVStrideUse *CondUse = 0;
Evan Cheng076e0852009-11-17 18:10:11 +00001546 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman572645c2010-02-12 10:34:29 +00001547 if (!FindIVUserForCond(Cond, CondUse))
Evan Cheng076e0852009-11-17 18:10:11 +00001548 continue;
1549
Evan Cheng076e0852009-11-17 18:10:11 +00001550 // If the trip count is computed in terms of a max (due to ScalarEvolution
1551 // being unable to find a sufficient guard, for example), change the loop
1552 // comparison to use SLT or ULT instead of NE.
Dan Gohman572645c2010-02-12 10:34:29 +00001553 // One consequence of doing this now is that it disrupts the count-down
1554 // optimization. That's not always a bad thing though, because in such
1555 // cases it may still be worthwhile to avoid a max.
1556 Cond = OptimizeMax(Cond, CondUse);
Evan Cheng076e0852009-11-17 18:10:11 +00001557
Dan Gohman572645c2010-02-12 10:34:29 +00001558 // If this exiting block dominates the latch block, it may also use
1559 // the post-inc value if it won't be shared with other uses.
1560 // Check for dominance.
1561 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman7979b722010-01-22 00:46:49 +00001562 continue;
Evan Cheng076e0852009-11-17 18:10:11 +00001563
Dan Gohman572645c2010-02-12 10:34:29 +00001564 // Conservatively avoid trying to use the post-inc value in non-latch
1565 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman590bfe82010-02-14 03:21:49 +00001566 if (LatchBlock != ExitingBlock)
Dan Gohman572645c2010-02-12 10:34:29 +00001567 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1568 // Test if the use is reachable from the exiting block. This dominator
1569 // query is a conservative approximation of reachability.
1570 if (&*UI != CondUse &&
1571 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1572 // Conservatively assume there may be reuse if the quotient of their
1573 // strides could be a legal scale.
Dan Gohman448db1c2010-04-07 22:27:08 +00001574 const SCEV *A = CondUse->getStride(L);
1575 const SCEV *B = UI->getStride(L);
1576 if (!A || !B) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001577 if (SE.getTypeSizeInBits(A->getType()) !=
1578 SE.getTypeSizeInBits(B->getType())) {
1579 if (SE.getTypeSizeInBits(A->getType()) >
1580 SE.getTypeSizeInBits(B->getType()))
1581 B = SE.getSignExtendExpr(B, A->getType());
1582 else
1583 A = SE.getSignExtendExpr(A, B->getType());
1584 }
1585 if (const SCEVConstant *D =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001586 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001587 // Stride of one or negative one can have reuse with non-addresses.
1588 if (D->getValue()->isOne() ||
1589 D->getValue()->isAllOnesValue())
1590 goto decline_post_inc;
1591 // Avoid weird situations.
1592 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1593 D->getValue()->getValue().isMinSignedValue())
1594 goto decline_post_inc;
Dan Gohman590bfe82010-02-14 03:21:49 +00001595 // Without TLI, assume that any stride might be valid, and so any
1596 // use might be shared.
1597 if (!TLI)
1598 goto decline_post_inc;
Dan Gohman572645c2010-02-12 10:34:29 +00001599 // Check for possible scaled-address reuse.
1600 const Type *AccessTy = getAccessType(UI->getUser());
1601 TargetLowering::AddrMode AM;
1602 AM.Scale = D->getValue()->getSExtValue();
Dan Gohman2763dfd2010-02-14 02:45:21 +00001603 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001604 goto decline_post_inc;
1605 AM.Scale = -AM.Scale;
Dan Gohman2763dfd2010-02-14 02:45:21 +00001606 if (TLI->isLegalAddressingMode(AM, AccessTy))
Dan Gohman572645c2010-02-12 10:34:29 +00001607 goto decline_post_inc;
1608 }
1609 }
1610
David Greene63c94632009-12-23 22:58:38 +00001611 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman572645c2010-02-12 10:34:29 +00001612 << *Cond << '\n');
Evan Cheng076e0852009-11-17 18:10:11 +00001613
1614 // It's possible for the setcc instruction to be anywhere in the loop, and
1615 // possible for it to have multiple users. If it is not immediately before
1616 // the exiting block branch, move it.
Dan Gohman572645c2010-02-12 10:34:29 +00001617 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1618 if (Cond->hasOneUse()) {
Evan Cheng076e0852009-11-17 18:10:11 +00001619 Cond->moveBefore(TermBr);
1620 } else {
Dan Gohman572645c2010-02-12 10:34:29 +00001621 // Clone the terminating condition and insert into the loopend.
1622 ICmpInst *OldCond = Cond;
Evan Cheng076e0852009-11-17 18:10:11 +00001623 Cond = cast<ICmpInst>(Cond->clone());
1624 Cond->setName(L->getHeader()->getName() + ".termcond");
1625 ExitingBlock->getInstList().insert(TermBr, Cond);
1626
1627 // Clone the IVUse, as the old use still exists!
Dan Gohman448db1c2010-04-07 22:27:08 +00001628 CondUse = &IU.AddUser(CondUse->getExpr(),
Dan Gohman572645c2010-02-12 10:34:29 +00001629 Cond, CondUse->getOperandValToReplace());
1630 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Cheng076e0852009-11-17 18:10:11 +00001631 }
Evan Cheng586f69a2009-11-12 07:35:05 +00001632 }
1633
Evan Cheng076e0852009-11-17 18:10:11 +00001634 // If we get to here, we know that we can transform the setcc instruction to
1635 // use the post-incremented version of the IV, allowing us to coalesce the
1636 // live ranges for the IV correctly.
Dan Gohman448db1c2010-04-07 22:27:08 +00001637 CondUse->transformToPostInc(L);
Evan Cheng076e0852009-11-17 18:10:11 +00001638 Changed = true;
1639
Dan Gohman572645c2010-02-12 10:34:29 +00001640 PostIncs.insert(Cond);
1641 decline_post_inc:;
Dan Gohmana10756e2010-01-21 02:09:26 +00001642 }
Dan Gohman572645c2010-02-12 10:34:29 +00001643
1644 // Determine an insertion point for the loop induction variable increment. It
1645 // must dominate all the post-inc comparisons we just set up, and it must
1646 // dominate the loop latch edge.
1647 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1648 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1649 E = PostIncs.end(); I != E; ++I) {
1650 BasicBlock *BB =
1651 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1652 (*I)->getParent());
1653 if (BB == (*I)->getParent())
1654 IVIncInsertPos = *I;
1655 else if (BB != IVIncInsertPos->getParent())
1656 IVIncInsertPos = BB->getTerminator();
1657 }
1658
1659 return Changed;
Dan Gohmana10756e2010-01-21 02:09:26 +00001660}
1661
Dan Gohman572645c2010-02-12 10:34:29 +00001662bool
1663LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1664 LSRUse::KindType Kind, const Type *AccessTy) {
1665 int64_t NewMinOffset = LU.MinOffset;
1666 int64_t NewMaxOffset = LU.MaxOffset;
1667 const Type *NewAccessTy = AccessTy;
Dan Gohman7979b722010-01-22 00:46:49 +00001668
Dan Gohman572645c2010-02-12 10:34:29 +00001669 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1670 // something conservative, however this can pessimize in the case that one of
1671 // the uses will have all its uses outside the loop, for example.
1672 if (LU.Kind != Kind)
Dan Gohman7979b722010-01-22 00:46:49 +00001673 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001674 // Conservatively assume HasBaseReg is true for now.
1675 if (NewOffset < LU.MinOffset) {
1676 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
Dan Gohman454d26d2010-02-22 04:11:59 +00001677 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001678 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001679 NewMinOffset = NewOffset;
1680 } else if (NewOffset > LU.MaxOffset) {
1681 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
Dan Gohman454d26d2010-02-22 04:11:59 +00001682 Kind, AccessTy, TLI))
Dan Gohman7979b722010-01-22 00:46:49 +00001683 return false;
Dan Gohman572645c2010-02-12 10:34:29 +00001684 NewMaxOffset = NewOffset;
Dan Gohmana10756e2010-01-21 02:09:26 +00001685 }
Dan Gohman572645c2010-02-12 10:34:29 +00001686 // Check for a mismatched access type, and fall back conservatively as needed.
1687 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1688 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohmana10756e2010-01-21 02:09:26 +00001689
Dan Gohman572645c2010-02-12 10:34:29 +00001690 // Update the use.
1691 LU.MinOffset = NewMinOffset;
1692 LU.MaxOffset = NewMaxOffset;
1693 LU.AccessTy = NewAccessTy;
1694 if (NewOffset != LU.Offsets.back())
1695 LU.Offsets.push_back(NewOffset);
Dan Gohman8b0ade32010-01-21 22:42:49 +00001696 return true;
1697}
1698
Dan Gohman572645c2010-02-12 10:34:29 +00001699/// getUse - Return an LSRUse index and an offset value for a fixup which
1700/// needs the given expression, with the given kind and optional access type.
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001701/// Either reuse an existing use or create a new one, as needed.
Dan Gohman572645c2010-02-12 10:34:29 +00001702std::pair<size_t, int64_t>
1703LSRInstance::getUse(const SCEV *&Expr,
1704 LSRUse::KindType Kind, const Type *AccessTy) {
1705 const SCEV *Copy = Expr;
1706 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng586f69a2009-11-12 07:35:05 +00001707
Dan Gohman572645c2010-02-12 10:34:29 +00001708 // Basic uses can't accept any offset, for example.
Dan Gohman454d26d2010-02-22 04:11:59 +00001709 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
Dan Gohman572645c2010-02-12 10:34:29 +00001710 Expr = Copy;
1711 Offset = 0;
1712 }
1713
1714 std::pair<UseMapTy::iterator, bool> P =
1715 UseMap.insert(std::make_pair(Expr, 0));
1716 if (!P.second) {
1717 // A use already existed with this base.
1718 size_t LUIdx = P.first->second;
1719 LSRUse &LU = Uses[LUIdx];
1720 if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1721 // Reuse this use.
1722 return std::make_pair(LUIdx, Offset);
1723 }
1724
1725 // Create a new use.
1726 size_t LUIdx = Uses.size();
1727 P.first->second = LUIdx;
1728 Uses.push_back(LSRUse(Kind, AccessTy));
1729 LSRUse &LU = Uses[LUIdx];
1730
1731 // We don't need to track redundant offsets, but we don't need to go out
1732 // of our way here to avoid them.
1733 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1734 LU.Offsets.push_back(Offset);
1735
1736 LU.MinOffset = Offset;
1737 LU.MaxOffset = Offset;
1738 return std::make_pair(LUIdx, Offset);
1739}
1740
1741void LSRInstance::CollectInterestingTypesAndFactors() {
1742 SmallSetVector<const SCEV *, 4> Strides;
1743
Dan Gohman1b7bf182010-02-19 00:05:23 +00001744 // Collect interesting types and strides.
Dan Gohman448db1c2010-04-07 22:27:08 +00001745 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman572645c2010-02-12 10:34:29 +00001746 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohman448db1c2010-04-07 22:27:08 +00001747 const SCEV *Expr = UI->getExpr();
Dan Gohman572645c2010-02-12 10:34:29 +00001748
1749 // Collect interesting types.
Dan Gohman448db1c2010-04-07 22:27:08 +00001750 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman572645c2010-02-12 10:34:29 +00001751
Dan Gohman448db1c2010-04-07 22:27:08 +00001752 // Add strides for mentioned loops.
1753 Worklist.push_back(Expr);
1754 do {
1755 const SCEV *S = Worklist.pop_back_val();
1756 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1757 Strides.insert(AR->getStepRecurrence(SE));
1758 Worklist.push_back(AR->getStart());
1759 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1760 Worklist.insert(Worklist.end(), Add->op_begin(), Add->op_end());
1761 }
1762 } while (!Worklist.empty());
Dan Gohman1b7bf182010-02-19 00:05:23 +00001763 }
1764
1765 // Compute interesting factors from the set of interesting strides.
1766 for (SmallSetVector<const SCEV *, 4>::const_iterator
1767 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman572645c2010-02-12 10:34:29 +00001768 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Dan Gohman1b7bf182010-02-19 00:05:23 +00001769 next(I); NewStrideIter != E; ++NewStrideIter) {
1770 const SCEV *OldStride = *I;
Dan Gohman572645c2010-02-12 10:34:29 +00001771 const SCEV *NewStride = *NewStrideIter;
Dan Gohman572645c2010-02-12 10:34:29 +00001772
1773 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1774 SE.getTypeSizeInBits(NewStride->getType())) {
1775 if (SE.getTypeSizeInBits(OldStride->getType()) >
1776 SE.getTypeSizeInBits(NewStride->getType()))
1777 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1778 else
1779 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1780 }
1781 if (const SCEVConstant *Factor =
Dan Gohmanf09b7122010-02-19 19:35:48 +00001782 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1783 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001784 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1785 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1786 } else if (const SCEVConstant *Factor =
Dan Gohman454d26d2010-02-22 04:11:59 +00001787 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
1788 NewStride,
Dan Gohmanf09b7122010-02-19 19:35:48 +00001789 SE, true))) {
Dan Gohman572645c2010-02-12 10:34:29 +00001790 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1791 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1792 }
1793 }
Dan Gohman572645c2010-02-12 10:34:29 +00001794
1795 // If all uses use the same type, don't bother looking for truncation-based
1796 // reuse.
1797 if (Types.size() == 1)
1798 Types.clear();
1799
1800 DEBUG(print_factors_and_types(dbgs()));
1801}
1802
1803void LSRInstance::CollectFixupsAndInitialFormulae() {
1804 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1805 // Record the uses.
1806 LSRFixup &LF = getNewFixup();
1807 LF.UserInst = UI->getUser();
1808 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohman448db1c2010-04-07 22:27:08 +00001809 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman572645c2010-02-12 10:34:29 +00001810
1811 LSRUse::KindType Kind = LSRUse::Basic;
1812 const Type *AccessTy = 0;
1813 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1814 Kind = LSRUse::Address;
1815 AccessTy = getAccessType(LF.UserInst);
1816 }
1817
Dan Gohman448db1c2010-04-07 22:27:08 +00001818 const SCEV *S = UI->getExpr();
Dan Gohman572645c2010-02-12 10:34:29 +00001819
1820 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1821 // (N - i == 0), and this allows (N - i) to be the expression that we work
1822 // with rather than just N or i, so we can consider the register
1823 // requirements for both N and i at the same time. Limiting this code to
1824 // equality icmps is not a problem because all interesting loops use
1825 // equality icmps, thanks to IndVarSimplify.
1826 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1827 if (CI->isEquality()) {
1828 // Swap the operands if needed to put the OperandValToReplace on the
1829 // left, for consistency.
1830 Value *NV = CI->getOperand(1);
1831 if (NV == LF.OperandValToReplace) {
1832 CI->setOperand(1, CI->getOperand(0));
1833 CI->setOperand(0, NV);
1834 }
1835
1836 // x == y --> x - y == 0
1837 const SCEV *N = SE.getSCEV(NV);
1838 if (N->isLoopInvariant(L)) {
1839 Kind = LSRUse::ICmpZero;
1840 S = SE.getMinusSCEV(N, S);
1841 }
1842
1843 // -1 and the negations of all interesting strides (except the negation
1844 // of -1) are now also interesting.
1845 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1846 if (Factors[i] != -1)
1847 Factors.insert(-(uint64_t)Factors[i]);
1848 Factors.insert(-1);
1849 }
1850
1851 // Set up the initial formula for this use.
1852 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1853 LF.LUIdx = P.first;
1854 LF.Offset = P.second;
1855 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00001856 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00001857
1858 // If this is the first use of this LSRUse, give it a formula.
1859 if (LU.Formulae.empty()) {
Dan Gohman454d26d2010-02-22 04:11:59 +00001860 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman572645c2010-02-12 10:34:29 +00001861 CountRegisters(LU.Formulae.back(), LF.LUIdx);
1862 }
1863 }
1864
1865 DEBUG(print_fixups(dbgs()));
1866}
1867
1868void
Dan Gohman454d26d2010-02-22 04:11:59 +00001869LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Dan Gohman572645c2010-02-12 10:34:29 +00001870 Formula F;
1871 F.InitialMatch(S, L, SE, DT);
1872 bool Inserted = InsertFormula(LU, LUIdx, F);
1873 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1874}
1875
1876void
1877LSRInstance::InsertSupplementalFormula(const SCEV *S,
1878 LSRUse &LU, size_t LUIdx) {
1879 Formula F;
1880 F.BaseRegs.push_back(S);
1881 F.AM.HasBaseReg = true;
1882 bool Inserted = InsertFormula(LU, LUIdx, F);
1883 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1884}
1885
1886/// CountRegisters - Note which registers are used by the given formula,
1887/// updating RegUses.
1888void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1889 if (F.ScaledReg)
1890 RegUses.CountRegister(F.ScaledReg, LUIdx);
1891 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1892 E = F.BaseRegs.end(); I != E; ++I)
1893 RegUses.CountRegister(*I, LUIdx);
1894}
1895
1896/// InsertFormula - If the given formula has not yet been inserted, add it to
1897/// the list, and return true. Return false otherwise.
1898bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Dan Gohman454d26d2010-02-22 04:11:59 +00001899 if (!LU.InsertFormula(F))
Dan Gohman572645c2010-02-12 10:34:29 +00001900 return false;
1901
1902 CountRegisters(F, LUIdx);
1903 return true;
1904}
1905
1906/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1907/// loop-invariant values which we're tracking. These other uses will pin these
1908/// values in registers, making them less profitable for elimination.
1909/// TODO: This currently misses non-constant addrec step registers.
1910/// TODO: Should this give more weight to users inside the loop?
1911void
1912LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1913 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1914 SmallPtrSet<const SCEV *, 8> Inserted;
1915
1916 while (!Worklist.empty()) {
1917 const SCEV *S = Worklist.pop_back_val();
1918
1919 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
1920 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
1921 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1922 Worklist.push_back(C->getOperand());
1923 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1924 Worklist.push_back(D->getLHS());
1925 Worklist.push_back(D->getRHS());
1926 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
1927 if (!Inserted.insert(U)) continue;
1928 const Value *V = U->getValue();
1929 if (const Instruction *Inst = dyn_cast<Instruction>(V))
1930 if (L->contains(Inst)) continue;
Gabor Greif60ad7812010-03-25 23:06:16 +00001931 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
Dan Gohman572645c2010-02-12 10:34:29 +00001932 UI != UE; ++UI) {
1933 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
1934 // Ignore non-instructions.
1935 if (!UserInst)
Dan Gohman7979b722010-01-22 00:46:49 +00001936 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001937 // Ignore instructions in other functions (as can happen with
1938 // Constants).
1939 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman7979b722010-01-22 00:46:49 +00001940 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001941 // Ignore instructions not dominated by the loop.
1942 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
1943 UserInst->getParent() :
1944 cast<PHINode>(UserInst)->getIncomingBlock(
1945 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
1946 if (!DT.dominates(L->getHeader(), UseBB))
1947 continue;
1948 // Ignore uses which are part of other SCEV expressions, to avoid
1949 // analyzing them multiple times.
Dan Gohman4a2a6832010-04-09 19:12:34 +00001950 if (SE.isSCEVable(UserInst->getType())) {
1951 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
1952 // If the user is a no-op, look through to its uses.
1953 if (!isa<SCEVUnknown>(UserS))
1954 continue;
1955 if (UserS == U) {
1956 Worklist.push_back(
1957 SE.getUnknown(const_cast<Instruction *>(UserInst)));
1958 continue;
1959 }
1960 }
Dan Gohman572645c2010-02-12 10:34:29 +00001961 // Ignore icmp instructions which are already being analyzed.
1962 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
1963 unsigned OtherIdx = !UI.getOperandNo();
1964 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
1965 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
1966 continue;
1967 }
1968
1969 LSRFixup &LF = getNewFixup();
1970 LF.UserInst = const_cast<Instruction *>(UserInst);
1971 LF.OperandValToReplace = UI.getUse();
1972 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
1973 LF.LUIdx = P.first;
1974 LF.Offset = P.second;
1975 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohman448db1c2010-04-07 22:27:08 +00001976 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman572645c2010-02-12 10:34:29 +00001977 InsertSupplementalFormula(U, LU, LF.LUIdx);
1978 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
1979 break;
1980 }
1981 }
1982 }
1983}
1984
1985/// CollectSubexprs - Split S into subexpressions which can be pulled out into
1986/// separate registers. If C is non-null, multiply each subexpression by C.
1987static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
1988 SmallVectorImpl<const SCEV *> &Ops,
1989 ScalarEvolution &SE) {
1990 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1991 // Break out add operands.
1992 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1993 I != E; ++I)
1994 CollectSubexprs(*I, C, Ops, SE);
1995 return;
1996 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1997 // Split a non-zero base out of an addrec.
1998 if (!AR->getStart()->isZero()) {
Dan Gohman572645c2010-02-12 10:34:29 +00001999 CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
2000 AR->getStepRecurrence(SE),
2001 AR->getLoop()), C, Ops, SE);
Dan Gohman68d6da12010-02-12 19:35:25 +00002002 CollectSubexprs(AR->getStart(), C, Ops, SE);
Dan Gohman572645c2010-02-12 10:34:29 +00002003 return;
2004 }
2005 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2006 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2007 if (Mul->getNumOperands() == 2)
2008 if (const SCEVConstant *Op0 =
2009 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2010 CollectSubexprs(Mul->getOperand(1),
2011 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2012 Ops, SE);
2013 return;
2014 }
2015 }
2016
2017 // Otherwise use the value itself.
2018 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2019}
2020
2021/// GenerateReassociations - Split out subexpressions from adds and the bases of
2022/// addrecs.
2023void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2024 Formula Base,
2025 unsigned Depth) {
2026 // Arbitrarily cap recursion to protect compile time.
2027 if (Depth >= 3) return;
2028
2029 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2030 const SCEV *BaseReg = Base.BaseRegs[i];
2031
2032 SmallVector<const SCEV *, 8> AddOps;
2033 CollectSubexprs(BaseReg, 0, AddOps, SE);
2034 if (AddOps.size() == 1) continue;
2035
2036 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2037 JE = AddOps.end(); J != JE; ++J) {
2038 // Don't pull a constant into a register if the constant could be folded
2039 // into an immediate field.
2040 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2041 Base.getNumRegs() > 1,
2042 LU.Kind, LU.AccessTy, TLI, SE))
2043 continue;
2044
2045 // Collect all operands except *J.
2046 SmallVector<const SCEV *, 8> InnerAddOps;
2047 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2048 KE = AddOps.end(); K != KE; ++K)
2049 if (K != J)
2050 InnerAddOps.push_back(*K);
2051
2052 // Don't leave just a constant behind in a register if the constant could
2053 // be folded into an immediate field.
2054 if (InnerAddOps.size() == 1 &&
2055 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2056 Base.getNumRegs() > 1,
2057 LU.Kind, LU.AccessTy, TLI, SE))
2058 continue;
2059
2060 Formula F = Base;
2061 F.BaseRegs[i] = SE.getAddExpr(InnerAddOps);
2062 F.BaseRegs.push_back(*J);
2063 if (InsertFormula(LU, LUIdx, F))
2064 // If that formula hadn't been seen before, recurse to find more like
2065 // it.
2066 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2067 }
2068 }
2069}
2070
2071/// GenerateCombinations - Generate a formula consisting of all of the
2072/// loop-dominating registers added into a single register.
2073void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohman441a3892010-02-14 18:51:39 +00002074 Formula Base) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002075 // This method is only interesting on a plurality of registers.
Dan Gohman572645c2010-02-12 10:34:29 +00002076 if (Base.BaseRegs.size() <= 1) return;
2077
2078 Formula F = Base;
2079 F.BaseRegs.clear();
2080 SmallVector<const SCEV *, 4> Ops;
2081 for (SmallVectorImpl<const SCEV *>::const_iterator
2082 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2083 const SCEV *BaseReg = *I;
2084 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2085 !BaseReg->hasComputableLoopEvolution(L))
2086 Ops.push_back(BaseReg);
2087 else
2088 F.BaseRegs.push_back(BaseReg);
2089 }
2090 if (Ops.size() > 1) {
Dan Gohmance947362010-02-14 18:50:49 +00002091 const SCEV *Sum = SE.getAddExpr(Ops);
2092 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2093 // opportunity to fold something. For now, just ignore such cases
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002094 // rather than proceed with zero in a register.
Dan Gohmance947362010-02-14 18:50:49 +00002095 if (!Sum->isZero()) {
2096 F.BaseRegs.push_back(Sum);
2097 (void)InsertFormula(LU, LUIdx, F);
2098 }
Dan Gohman572645c2010-02-12 10:34:29 +00002099 }
2100}
2101
2102/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2103void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2104 Formula Base) {
2105 // We can't add a symbolic offset if the address already contains one.
2106 if (Base.AM.BaseGV) return;
2107
2108 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2109 const SCEV *G = Base.BaseRegs[i];
2110 GlobalValue *GV = ExtractSymbol(G, SE);
2111 if (G->isZero() || !GV)
2112 continue;
2113 Formula F = Base;
2114 F.AM.BaseGV = GV;
2115 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2116 LU.Kind, LU.AccessTy, TLI))
2117 continue;
2118 F.BaseRegs[i] = G;
2119 (void)InsertFormula(LU, LUIdx, F);
2120 }
2121}
2122
2123/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2124void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2125 Formula Base) {
2126 // TODO: For now, just add the min and max offset, because it usually isn't
2127 // worthwhile looking at everything inbetween.
2128 SmallVector<int64_t, 4> Worklist;
2129 Worklist.push_back(LU.MinOffset);
2130 if (LU.MaxOffset != LU.MinOffset)
2131 Worklist.push_back(LU.MaxOffset);
2132
2133 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2134 const SCEV *G = Base.BaseRegs[i];
2135
2136 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2137 E = Worklist.end(); I != E; ++I) {
2138 Formula F = Base;
2139 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2140 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2141 LU.Kind, LU.AccessTy, TLI)) {
2142 F.BaseRegs[i] = SE.getAddExpr(G, SE.getIntegerSCEV(*I, G->getType()));
2143
2144 (void)InsertFormula(LU, LUIdx, F);
2145 }
2146 }
2147
2148 int64_t Imm = ExtractImmediate(G, SE);
2149 if (G->isZero() || Imm == 0)
2150 continue;
2151 Formula F = Base;
2152 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2153 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2154 LU.Kind, LU.AccessTy, TLI))
2155 continue;
2156 F.BaseRegs[i] = G;
2157 (void)InsertFormula(LU, LUIdx, F);
2158 }
2159}
2160
2161/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2162/// the comparison. For example, x == y -> x*c == y*c.
2163void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2164 Formula Base) {
2165 if (LU.Kind != LSRUse::ICmpZero) return;
2166
2167 // Determine the integer type for the base formula.
2168 const Type *IntTy = Base.getType();
2169 if (!IntTy) return;
2170 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2171
2172 // Don't do this if there is more than one offset.
2173 if (LU.MinOffset != LU.MaxOffset) return;
2174
2175 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2176
2177 // Check each interesting stride.
2178 for (SmallSetVector<int64_t, 8>::const_iterator
2179 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2180 int64_t Factor = *I;
2181 Formula F = Base;
2182
2183 // Check that the multiplication doesn't overflow.
Dan Gohman968cb932010-02-17 00:41:53 +00002184 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2185 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002186 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002187 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
Dan Gohman572645c2010-02-12 10:34:29 +00002188 continue;
2189
2190 // Check that multiplying with the use offset doesn't overflow.
2191 int64_t Offset = LU.MinOffset;
Dan Gohman968cb932010-02-17 00:41:53 +00002192 if (Offset == INT64_MIN && Factor == -1)
2193 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002194 Offset = (uint64_t)Offset * Factor;
Dan Gohman378c0b32010-02-17 00:42:19 +00002195 if (Offset / Factor != LU.MinOffset)
Dan Gohman572645c2010-02-12 10:34:29 +00002196 continue;
2197
2198 // Check that this scale is legal.
2199 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2200 continue;
2201
2202 // Compensate for the use having MinOffset built into it.
2203 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2204
2205 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2206
2207 // Check that multiplying with each base register doesn't overflow.
2208 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2209 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002210 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman572645c2010-02-12 10:34:29 +00002211 goto next;
2212 }
2213
2214 // Check that multiplying with the scaled register doesn't overflow.
2215 if (F.ScaledReg) {
2216 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohmanf09b7122010-02-19 19:35:48 +00002217 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman572645c2010-02-12 10:34:29 +00002218 continue;
2219 }
2220
2221 // If we make it here and it's legal, add it.
2222 (void)InsertFormula(LU, LUIdx, F);
2223 next:;
2224 }
2225}
2226
2227/// GenerateScales - Generate stride factor reuse formulae by making use of
2228/// scaled-offset address modes, for example.
2229void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2230 Formula Base) {
2231 // Determine the integer type for the base formula.
2232 const Type *IntTy = Base.getType();
2233 if (!IntTy) return;
2234
2235 // If this Formula already has a scaled register, we can't add another one.
2236 if (Base.AM.Scale != 0) return;
2237
2238 // Check each interesting stride.
2239 for (SmallSetVector<int64_t, 8>::const_iterator
2240 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2241 int64_t Factor = *I;
2242
2243 Base.AM.Scale = Factor;
2244 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2245 // Check whether this scale is going to be legal.
2246 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2247 LU.Kind, LU.AccessTy, TLI)) {
2248 // As a special-case, handle special out-of-loop Basic users specially.
2249 // TODO: Reconsider this special case.
2250 if (LU.Kind == LSRUse::Basic &&
2251 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2252 LSRUse::Special, LU.AccessTy, TLI) &&
2253 LU.AllFixupsOutsideLoop)
2254 LU.Kind = LSRUse::Special;
2255 else
2256 continue;
2257 }
2258 // For an ICmpZero, negating a solitary base register won't lead to
2259 // new solutions.
2260 if (LU.Kind == LSRUse::ICmpZero &&
2261 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2262 continue;
2263 // For each addrec base reg, apply the scale, if possible.
2264 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2265 if (const SCEVAddRecExpr *AR =
2266 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2267 const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2268 if (FactorS->isZero())
2269 continue;
2270 // Divide out the factor, ignoring high bits, since we'll be
2271 // scaling the value back up in the end.
Dan Gohmanf09b7122010-02-19 19:35:48 +00002272 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman572645c2010-02-12 10:34:29 +00002273 // TODO: This could be optimized to avoid all the copying.
2274 Formula F = Base;
2275 F.ScaledReg = Quotient;
2276 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2277 F.BaseRegs.pop_back();
2278 (void)InsertFormula(LU, LUIdx, F);
2279 }
2280 }
2281 }
2282}
2283
2284/// GenerateTruncates - Generate reuse formulae from different IV types.
2285void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2286 Formula Base) {
2287 // This requires TargetLowering to tell us which truncates are free.
2288 if (!TLI) return;
2289
2290 // Don't bother truncating symbolic values.
2291 if (Base.AM.BaseGV) return;
2292
2293 // Determine the integer type for the base formula.
2294 const Type *DstTy = Base.getType();
2295 if (!DstTy) return;
2296 DstTy = SE.getEffectiveSCEVType(DstTy);
2297
2298 for (SmallSetVector<const Type *, 4>::const_iterator
2299 I = Types.begin(), E = Types.end(); I != E; ++I) {
2300 const Type *SrcTy = *I;
2301 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2302 Formula F = Base;
2303
2304 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2305 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2306 JE = F.BaseRegs.end(); J != JE; ++J)
2307 *J = SE.getAnyExtendExpr(*J, SrcTy);
2308
2309 // TODO: This assumes we've done basic processing on all uses and
2310 // have an idea what the register usage is.
2311 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2312 continue;
2313
2314 (void)InsertFormula(LU, LUIdx, F);
2315 }
2316 }
2317}
2318
2319namespace {
2320
Dan Gohman6020d852010-02-14 18:51:20 +00002321/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman572645c2010-02-12 10:34:29 +00002322/// defer modifications so that the search phase doesn't have to worry about
2323/// the data structures moving underneath it.
2324struct WorkItem {
2325 size_t LUIdx;
2326 int64_t Imm;
2327 const SCEV *OrigReg;
2328
2329 WorkItem(size_t LI, int64_t I, const SCEV *R)
2330 : LUIdx(LI), Imm(I), OrigReg(R) {}
2331
2332 void print(raw_ostream &OS) const;
2333 void dump() const;
2334};
2335
2336}
2337
2338void WorkItem::print(raw_ostream &OS) const {
2339 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2340 << " , add offset " << Imm;
2341}
2342
2343void WorkItem::dump() const {
2344 print(errs()); errs() << '\n';
2345}
2346
2347/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2348/// distance apart and try to form reuse opportunities between them.
2349void LSRInstance::GenerateCrossUseConstantOffsets() {
2350 // Group the registers by their value without any added constant offset.
2351 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2352 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2353 RegMapTy Map;
2354 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2355 SmallVector<const SCEV *, 8> Sequence;
2356 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2357 I != E; ++I) {
2358 const SCEV *Reg = *I;
2359 int64_t Imm = ExtractImmediate(Reg, SE);
2360 std::pair<RegMapTy::iterator, bool> Pair =
2361 Map.insert(std::make_pair(Reg, ImmMapTy()));
2362 if (Pair.second)
2363 Sequence.push_back(Reg);
2364 Pair.first->second.insert(std::make_pair(Imm, *I));
2365 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2366 }
2367
2368 // Now examine each set of registers with the same base value. Build up
2369 // a list of work to do and do the work in a separate step so that we're
2370 // not adding formulae and register counts while we're searching.
2371 SmallVector<WorkItem, 32> WorkItems;
2372 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2373 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2374 E = Sequence.end(); I != E; ++I) {
2375 const SCEV *Reg = *I;
2376 const ImmMapTy &Imms = Map.find(Reg)->second;
2377
Dan Gohmancd045c02010-02-12 19:20:37 +00002378 // It's not worthwhile looking for reuse if there's only one offset.
2379 if (Imms.size() == 1)
2380 continue;
2381
Dan Gohman572645c2010-02-12 10:34:29 +00002382 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2383 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2384 J != JE; ++J)
2385 dbgs() << ' ' << J->first;
2386 dbgs() << '\n');
2387
2388 // Examine each offset.
2389 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2390 J != JE; ++J) {
2391 const SCEV *OrigReg = J->second;
2392
2393 int64_t JImm = J->first;
2394 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2395
2396 if (!isa<SCEVConstant>(OrigReg) &&
2397 UsedByIndicesMap[Reg].count() == 1) {
2398 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2399 continue;
2400 }
2401
2402 // Conservatively examine offsets between this orig reg a few selected
2403 // other orig regs.
2404 ImmMapTy::const_iterator OtherImms[] = {
2405 Imms.begin(), prior(Imms.end()),
2406 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2407 };
2408 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2409 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohmancd045c02010-02-12 19:20:37 +00002410 if (M == J || M == JE) continue;
Dan Gohman572645c2010-02-12 10:34:29 +00002411
2412 // Compute the difference between the two.
2413 int64_t Imm = (uint64_t)JImm - M->first;
2414 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2415 LUIdx = UsedByIndices.find_next(LUIdx))
2416 // Make a memo of this use, offset, and register tuple.
2417 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2418 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng586f69a2009-11-12 07:35:05 +00002419 }
2420 }
2421 }
2422
Dan Gohman572645c2010-02-12 10:34:29 +00002423 Map.clear();
2424 Sequence.clear();
2425 UsedByIndicesMap.clear();
2426 UniqueItems.clear();
2427
2428 // Now iterate through the worklist and add new formulae.
2429 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2430 E = WorkItems.end(); I != E; ++I) {
2431 const WorkItem &WI = *I;
2432 size_t LUIdx = WI.LUIdx;
2433 LSRUse &LU = Uses[LUIdx];
2434 int64_t Imm = WI.Imm;
2435 const SCEV *OrigReg = WI.OrigReg;
2436
2437 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2438 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2439 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2440
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002441 // TODO: Use a more targeted data structure.
Dan Gohman572645c2010-02-12 10:34:29 +00002442 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2443 Formula F = LU.Formulae[L];
2444 // Use the immediate in the scaled register.
2445 if (F.ScaledReg == OrigReg) {
2446 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2447 Imm * (uint64_t)F.AM.Scale;
2448 // Don't create 50 + reg(-50).
2449 if (F.referencesReg(SE.getSCEV(
2450 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2451 continue;
2452 Formula NewF = F;
2453 NewF.AM.BaseOffs = Offs;
2454 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2455 LU.Kind, LU.AccessTy, TLI))
2456 continue;
2457 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2458
2459 // If the new scale is a constant in a register, and adding the constant
2460 // value to the immediate would produce a value closer to zero than the
2461 // immediate itself, then the formula isn't worthwhile.
2462 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2463 if (C->getValue()->getValue().isNegative() !=
2464 (NewF.AM.BaseOffs < 0) &&
2465 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
Dan Gohmane0567812010-04-08 23:03:40 +00002466 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002467 continue;
2468
2469 // OK, looks good.
2470 (void)InsertFormula(LU, LUIdx, NewF);
2471 } else {
2472 // Use the immediate in a base register.
2473 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2474 const SCEV *BaseReg = F.BaseRegs[N];
2475 if (BaseReg != OrigReg)
2476 continue;
2477 Formula NewF = F;
2478 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2479 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2480 LU.Kind, LU.AccessTy, TLI))
2481 continue;
2482 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2483
2484 // If the new formula has a constant in a register, and adding the
2485 // constant value to the immediate would produce a value closer to
2486 // zero than the immediate itself, then the formula isn't worthwhile.
2487 for (SmallVectorImpl<const SCEV *>::const_iterator
2488 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2489 J != JE; ++J)
2490 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2491 if (C->getValue()->getValue().isNegative() !=
2492 (NewF.AM.BaseOffs < 0) &&
2493 C->getValue()->getValue().abs()
Dan Gohmane0567812010-04-08 23:03:40 +00002494 .ule(abs64(NewF.AM.BaseOffs)))
Dan Gohman572645c2010-02-12 10:34:29 +00002495 goto skip_formula;
2496
2497 // Ok, looks good.
2498 (void)InsertFormula(LU, LUIdx, NewF);
2499 break;
2500 skip_formula:;
2501 }
2502 }
2503 }
2504 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00002505}
2506
Dan Gohman572645c2010-02-12 10:34:29 +00002507/// GenerateAllReuseFormulae - Generate formulae for each use.
2508void
2509LSRInstance::GenerateAllReuseFormulae() {
Dan Gohmanc2385a02010-02-16 01:42:53 +00002510 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman572645c2010-02-12 10:34:29 +00002511 // queries are more precise.
2512 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2513 LSRUse &LU = Uses[LUIdx];
2514 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2515 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2516 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2517 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2518 }
2519 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2520 LSRUse &LU = Uses[LUIdx];
2521 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2522 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2523 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2524 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2525 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2526 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2527 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2528 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohmanc2385a02010-02-16 01:42:53 +00002529 }
2530 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2531 LSRUse &LU = Uses[LUIdx];
Dan Gohman572645c2010-02-12 10:34:29 +00002532 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2533 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2534 }
2535
2536 GenerateCrossUseConstantOffsets();
2537}
2538
2539/// If their are multiple formulae with the same set of registers used
2540/// by other uses, pick the best one and delete the others.
2541void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2542#ifndef NDEBUG
2543 bool Changed = false;
2544#endif
2545
2546 // Collect the best formula for each unique set of shared registers. This
2547 // is reset for each use.
2548 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2549 BestFormulaeTy;
2550 BestFormulaeTy BestFormulae;
2551
2552 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2553 LSRUse &LU = Uses[LUIdx];
2554 FormulaSorter Sorter(L, LU, SE, DT);
2555
2556 // Clear out the set of used regs; it will be recomputed.
2557 LU.Regs.clear();
2558
2559 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2560 FIdx != NumForms; ++FIdx) {
2561 Formula &F = LU.Formulae[FIdx];
2562
2563 SmallVector<const SCEV *, 2> Key;
2564 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2565 JE = F.BaseRegs.end(); J != JE; ++J) {
2566 const SCEV *Reg = *J;
2567 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2568 Key.push_back(Reg);
2569 }
2570 if (F.ScaledReg &&
2571 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2572 Key.push_back(F.ScaledReg);
2573 // Unstable sort by host order ok, because this is only used for
2574 // uniquifying.
2575 std::sort(Key.begin(), Key.end());
2576
2577 std::pair<BestFormulaeTy::const_iterator, bool> P =
2578 BestFormulae.insert(std::make_pair(Key, FIdx));
2579 if (!P.second) {
2580 Formula &Best = LU.Formulae[P.first->second];
2581 if (Sorter.operator()(F, Best))
2582 std::swap(F, Best);
2583 DEBUG(dbgs() << "Filtering out "; F.print(dbgs());
2584 dbgs() << "\n"
2585 " in favor of "; Best.print(dbgs());
2586 dbgs() << '\n');
2587#ifndef NDEBUG
2588 Changed = true;
2589#endif
2590 std::swap(F, LU.Formulae.back());
2591 LU.Formulae.pop_back();
2592 --FIdx;
2593 --NumForms;
2594 continue;
2595 }
2596 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2597 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2598 }
2599 BestFormulae.clear();
2600 }
2601
2602 DEBUG(if (Changed) {
Dan Gohman9214b822010-02-13 02:06:02 +00002603 dbgs() << "\n"
2604 "After filtering out undesirable candidates:\n";
Dan Gohman572645c2010-02-12 10:34:29 +00002605 print_uses(dbgs());
2606 });
2607}
2608
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002609/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
Dan Gohman572645c2010-02-12 10:34:29 +00002610/// formulae to choose from, use some rough heuristics to prune down the number
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002611/// of formulae. This keeps the main solver from taking an extraordinary amount
Dan Gohman572645c2010-02-12 10:34:29 +00002612/// of time in some worst-case scenarios.
2613void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2614 // This is a rough guess that seems to work fairly well.
2615 const size_t Limit = UINT16_MAX;
2616
2617 SmallPtrSet<const SCEV *, 4> Taken;
2618 for (;;) {
2619 // Estimate the worst-case number of solutions we might consider. We almost
2620 // never consider this many solutions because we prune the search space,
2621 // but the pruning isn't always sufficient.
2622 uint32_t Power = 1;
2623 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2624 E = Uses.end(); I != E; ++I) {
2625 size_t FSize = I->Formulae.size();
2626 if (FSize >= Limit) {
2627 Power = Limit;
2628 break;
2629 }
2630 Power *= FSize;
2631 if (Power >= Limit)
2632 break;
2633 }
2634 if (Power < Limit)
2635 break;
2636
2637 // Ok, we have too many of formulae on our hands to conveniently handle.
2638 // Use a rough heuristic to thin out the list.
2639
2640 // Pick the register which is used by the most LSRUses, which is likely
2641 // to be a good reuse register candidate.
2642 const SCEV *Best = 0;
2643 unsigned BestNum = 0;
2644 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2645 I != E; ++I) {
2646 const SCEV *Reg = *I;
2647 if (Taken.count(Reg))
2648 continue;
2649 if (!Best)
2650 Best = Reg;
2651 else {
2652 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2653 if (Count > BestNum) {
2654 Best = Reg;
2655 BestNum = Count;
2656 }
2657 }
2658 }
2659
2660 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002661 << " will yield profitable reuse.\n");
Dan Gohman572645c2010-02-12 10:34:29 +00002662 Taken.insert(Best);
2663
2664 // In any use with formulae which references this register, delete formulae
2665 // which don't reference it.
2666 for (SmallVectorImpl<LSRUse>::iterator I = Uses.begin(),
2667 E = Uses.end(); I != E; ++I) {
2668 LSRUse &LU = *I;
2669 if (!LU.Regs.count(Best)) continue;
2670
2671 // Clear out the set of used regs; it will be recomputed.
2672 LU.Regs.clear();
2673
2674 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2675 Formula &F = LU.Formulae[i];
2676 if (!F.referencesReg(Best)) {
2677 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2678 std::swap(LU.Formulae.back(), F);
2679 LU.Formulae.pop_back();
2680 --e;
2681 --i;
2682 continue;
2683 }
2684
2685 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2686 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2687 }
2688 }
2689
2690 DEBUG(dbgs() << "After pre-selection:\n";
2691 print_uses(dbgs()));
2692 }
2693}
2694
2695/// SolveRecurse - This is the recursive solver.
2696void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2697 Cost &SolutionCost,
2698 SmallVectorImpl<const Formula *> &Workspace,
2699 const Cost &CurCost,
2700 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2701 DenseSet<const SCEV *> &VisitedRegs) const {
2702 // Some ideas:
2703 // - prune more:
2704 // - use more aggressive filtering
2705 // - sort the formula so that the most profitable solutions are found first
2706 // - sort the uses too
2707 // - search faster:
Dan Gohman3f46a3a2010-03-01 17:49:51 +00002708 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman572645c2010-02-12 10:34:29 +00002709 // and bail early.
2710 // - track register sets with SmallBitVector
2711
2712 const LSRUse &LU = Uses[Workspace.size()];
2713
2714 // If this use references any register that's already a part of the
2715 // in-progress solution, consider it a requirement that a formula must
2716 // reference that register in order to be considered. This prunes out
2717 // unprofitable searching.
2718 SmallSetVector<const SCEV *, 4> ReqRegs;
2719 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2720 E = CurRegs.end(); I != E; ++I)
Dan Gohman9214b822010-02-13 02:06:02 +00002721 if (LU.Regs.count(*I))
Dan Gohman572645c2010-02-12 10:34:29 +00002722 ReqRegs.insert(*I);
Dan Gohman572645c2010-02-12 10:34:29 +00002723
Dan Gohman9214b822010-02-13 02:06:02 +00002724 bool AnySatisfiedReqRegs = false;
Dan Gohman572645c2010-02-12 10:34:29 +00002725 SmallPtrSet<const SCEV *, 16> NewRegs;
2726 Cost NewCost;
Dan Gohman9214b822010-02-13 02:06:02 +00002727retry:
Dan Gohman572645c2010-02-12 10:34:29 +00002728 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2729 E = LU.Formulae.end(); I != E; ++I) {
2730 const Formula &F = *I;
2731
2732 // Ignore formulae which do not use any of the required registers.
2733 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2734 JE = ReqRegs.end(); J != JE; ++J) {
2735 const SCEV *Reg = *J;
2736 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2737 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2738 F.BaseRegs.end())
2739 goto skip;
2740 }
Dan Gohman9214b822010-02-13 02:06:02 +00002741 AnySatisfiedReqRegs = true;
Dan Gohman572645c2010-02-12 10:34:29 +00002742
2743 // Evaluate the cost of the current formula. If it's already worse than
2744 // the current best, prune the search at that point.
2745 NewCost = CurCost;
2746 NewRegs = CurRegs;
2747 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2748 if (NewCost < SolutionCost) {
2749 Workspace.push_back(&F);
2750 if (Workspace.size() != Uses.size()) {
2751 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2752 NewRegs, VisitedRegs);
2753 if (F.getNumRegs() == 1 && Workspace.size() == 1)
2754 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2755 } else {
2756 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2757 dbgs() << ". Regs:";
2758 for (SmallPtrSet<const SCEV *, 16>::const_iterator
2759 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2760 dbgs() << ' ' << **I;
2761 dbgs() << '\n');
2762
2763 SolutionCost = NewCost;
2764 Solution = Workspace;
2765 }
2766 Workspace.pop_back();
2767 }
2768 skip:;
2769 }
Dan Gohman9214b822010-02-13 02:06:02 +00002770
2771 // If none of the formulae had all of the required registers, relax the
2772 // constraint so that we don't exclude all formulae.
2773 if (!AnySatisfiedReqRegs) {
2774 ReqRegs.clear();
2775 goto retry;
2776 }
Dan Gohman572645c2010-02-12 10:34:29 +00002777}
2778
2779void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2780 SmallVector<const Formula *, 8> Workspace;
2781 Cost SolutionCost;
2782 SolutionCost.Loose();
2783 Cost CurCost;
2784 SmallPtrSet<const SCEV *, 16> CurRegs;
2785 DenseSet<const SCEV *> VisitedRegs;
2786 Workspace.reserve(Uses.size());
2787
2788 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2789 CurRegs, VisitedRegs);
2790
2791 // Ok, we've now made all our decisions.
2792 DEBUG(dbgs() << "\n"
2793 "The chosen solution requires "; SolutionCost.print(dbgs());
2794 dbgs() << ":\n";
2795 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2796 dbgs() << " ";
2797 Uses[i].print(dbgs());
2798 dbgs() << "\n"
2799 " ";
2800 Solution[i]->print(dbgs());
2801 dbgs() << '\n';
2802 });
2803}
2804
2805/// getImmediateDominator - A handy utility for the specific DominatorTree
2806/// query that we need here.
2807///
2808static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2809 DomTreeNode *Node = DT.getNode(BB);
2810 if (!Node) return 0;
2811 Node = Node->getIDom();
2812 if (!Node) return 0;
2813 return Node->getBlock();
2814}
2815
Dan Gohmand96eae82010-04-09 02:00:38 +00002816/// AdjustInputPositionForExpand - Determine an input position which will be
2817/// dominated by the operands and which will dominate the result.
2818BasicBlock::iterator
2819LSRInstance::AdjustInputPositionForExpand(BasicBlock::iterator IP,
2820 const LSRFixup &LF,
2821 const LSRUse &LU) const {
2822 // Collect some instructions which must be dominated by the
Dan Gohman448db1c2010-04-07 22:27:08 +00002823 // expanding replacement. These must be dominated by any operands that
Dan Gohman572645c2010-02-12 10:34:29 +00002824 // will be required in the expansion.
2825 SmallVector<Instruction *, 4> Inputs;
2826 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2827 Inputs.push_back(I);
2828 if (LU.Kind == LSRUse::ICmpZero)
2829 if (Instruction *I =
2830 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2831 Inputs.push_back(I);
Dan Gohman448db1c2010-04-07 22:27:08 +00002832 if (LF.PostIncLoops.count(L)) {
2833 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman069d6f32010-03-02 01:59:21 +00002834 Inputs.push_back(L->getLoopLatch()->getTerminator());
2835 else
2836 Inputs.push_back(IVIncInsertPos);
2837 }
Dan Gohman701a4ae2010-04-08 05:57:57 +00002838 // The expansion must also be dominated by the increment positions of any
2839 // loops it for which it is using post-inc mode.
2840 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
2841 E = LF.PostIncLoops.end(); I != E; ++I) {
2842 const Loop *PIL = *I;
2843 if (PIL == L) continue;
2844
2845 SmallVector<BasicBlock *, 4> ExitingBlocks;
2846 PIL->getExitingBlocks(ExitingBlocks);
2847 if (!ExitingBlocks.empty()) {
2848 BasicBlock *BB = ExitingBlocks[0];
2849 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
2850 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
2851 Inputs.push_back(BB->getTerminator());
2852 }
2853 }
Dan Gohman572645c2010-02-12 10:34:29 +00002854
2855 // Then, climb up the immediate dominator tree as far as we can go while
2856 // still being dominated by the input positions.
2857 for (;;) {
2858 bool AllDominate = true;
2859 Instruction *BetterPos = 0;
2860 BasicBlock *IDom = getImmediateDominator(IP->getParent(), DT);
2861 if (!IDom) break;
2862 Instruction *Tentative = IDom->getTerminator();
2863 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2864 E = Inputs.end(); I != E; ++I) {
2865 Instruction *Inst = *I;
2866 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2867 AllDominate = false;
2868 break;
2869 }
2870 if (IDom == Inst->getParent() &&
2871 (!BetterPos || DT.dominates(BetterPos, Inst)))
2872 BetterPos = next(BasicBlock::iterator(Inst));
2873 }
2874 if (!AllDominate)
2875 break;
2876 if (BetterPos)
2877 IP = BetterPos;
2878 else
2879 IP = Tentative;
2880 }
Dan Gohmand96eae82010-04-09 02:00:38 +00002881
2882 // Don't insert instructions before PHI nodes.
Dan Gohman572645c2010-02-12 10:34:29 +00002883 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand96eae82010-04-09 02:00:38 +00002884
2885 // Ignore debug intrinsics.
Dan Gohman449f31c2010-03-26 00:33:27 +00002886 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman572645c2010-02-12 10:34:29 +00002887
Dan Gohmand96eae82010-04-09 02:00:38 +00002888 return IP;
2889}
2890
2891Value *LSRInstance::Expand(const LSRFixup &LF,
2892 const Formula &F,
2893 BasicBlock::iterator IP,
2894 SCEVExpander &Rewriter,
2895 SmallVectorImpl<WeakVH> &DeadInsts) const {
2896 const LSRUse &LU = Uses[LF.LUIdx];
2897
2898 // Determine an input position which will be dominated by the operands and
2899 // which will dominate the result.
2900 IP = AdjustInputPositionForExpand(IP, LF, LU);
2901
Dan Gohman572645c2010-02-12 10:34:29 +00002902 // Inform the Rewriter if we have a post-increment use, so that it can
2903 // perform an advantageous expansion.
Dan Gohman448db1c2010-04-07 22:27:08 +00002904 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman572645c2010-02-12 10:34:29 +00002905
2906 // This is the type that the user actually needs.
2907 const Type *OpTy = LF.OperandValToReplace->getType();
2908 // This will be the type that we'll initially expand to.
2909 const Type *Ty = F.getType();
2910 if (!Ty)
2911 // No type known; just expand directly to the ultimate type.
2912 Ty = OpTy;
2913 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
2914 // Expand directly to the ultimate type if it's the right size.
2915 Ty = OpTy;
2916 // This is the type to do integer arithmetic in.
2917 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
2918
2919 // Build up a list of operands to add together to form the full base.
2920 SmallVector<const SCEV *, 8> Ops;
2921
2922 // Expand the BaseRegs portion.
2923 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2924 E = F.BaseRegs.end(); I != E; ++I) {
2925 const SCEV *Reg = *I;
2926 assert(!Reg->isZero() && "Zero allocated in a base register!");
2927
Dan Gohman448db1c2010-04-07 22:27:08 +00002928 // If we're expanding for a post-inc user, make the post-inc adjustment.
2929 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
2930 Reg = TransformForPostIncUse(Denormalize, Reg,
2931 LF.UserInst, LF.OperandValToReplace,
2932 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00002933
2934 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
2935 }
2936
Dan Gohman087bd1e2010-03-03 05:29:13 +00002937 // Flush the operand list to suppress SCEVExpander hoisting.
2938 if (!Ops.empty()) {
2939 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
2940 Ops.clear();
2941 Ops.push_back(SE.getUnknown(FullV));
2942 }
2943
Dan Gohman572645c2010-02-12 10:34:29 +00002944 // Expand the ScaledReg portion.
2945 Value *ICmpScaledV = 0;
2946 if (F.AM.Scale != 0) {
2947 const SCEV *ScaledS = F.ScaledReg;
2948
Dan Gohman448db1c2010-04-07 22:27:08 +00002949 // If we're expanding for a post-inc user, make the post-inc adjustment.
2950 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
2951 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
2952 LF.UserInst, LF.OperandValToReplace,
2953 Loops, SE, DT);
Dan Gohman572645c2010-02-12 10:34:29 +00002954
2955 if (LU.Kind == LSRUse::ICmpZero) {
2956 // An interesting way of "folding" with an icmp is to use a negated
2957 // scale, which we'll implement by inserting it into the other operand
2958 // of the icmp.
2959 assert(F.AM.Scale == -1 &&
2960 "The only scale supported by ICmpZero uses is -1!");
2961 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
2962 } else {
2963 // Otherwise just expand the scaled register and an explicit scale,
2964 // which is expected to be matched as part of the address.
2965 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
2966 ScaledS = SE.getMulExpr(ScaledS,
2967 SE.getIntegerSCEV(F.AM.Scale,
2968 ScaledS->getType()));
2969 Ops.push_back(ScaledS);
Dan Gohman087bd1e2010-03-03 05:29:13 +00002970
2971 // Flush the operand list to suppress SCEVExpander hoisting.
2972 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
2973 Ops.clear();
2974 Ops.push_back(SE.getUnknown(FullV));
Dan Gohman572645c2010-02-12 10:34:29 +00002975 }
2976 }
2977
Dan Gohman087bd1e2010-03-03 05:29:13 +00002978 // Expand the GV portion.
2979 if (F.AM.BaseGV) {
2980 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
2981
2982 // Flush the operand list to suppress SCEVExpander hoisting.
2983 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
2984 Ops.clear();
2985 Ops.push_back(SE.getUnknown(FullV));
2986 }
2987
2988 // Expand the immediate portion.
Dan Gohman572645c2010-02-12 10:34:29 +00002989 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
2990 if (Offset != 0) {
2991 if (LU.Kind == LSRUse::ICmpZero) {
2992 // The other interesting way of "folding" with an ICmpZero is to use a
2993 // negated immediate.
2994 if (!ICmpScaledV)
2995 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
2996 else {
2997 Ops.push_back(SE.getUnknown(ICmpScaledV));
2998 ICmpScaledV = ConstantInt::get(IntTy, Offset);
2999 }
3000 } else {
3001 // Just add the immediate values. These again are expected to be matched
3002 // as part of the address.
Dan Gohman087bd1e2010-03-03 05:29:13 +00003003 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman572645c2010-02-12 10:34:29 +00003004 }
3005 }
3006
3007 // Emit instructions summing all the operands.
3008 const SCEV *FullS = Ops.empty() ?
3009 SE.getIntegerSCEV(0, IntTy) :
3010 SE.getAddExpr(Ops);
3011 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3012
3013 // We're done expanding now, so reset the rewriter.
Dan Gohman448db1c2010-04-07 22:27:08 +00003014 Rewriter.clearPostInc();
Dan Gohman572645c2010-02-12 10:34:29 +00003015
3016 // An ICmpZero Formula represents an ICmp which we're handling as a
3017 // comparison against zero. Now that we've expanded an expression for that
3018 // form, update the ICmp's other operand.
3019 if (LU.Kind == LSRUse::ICmpZero) {
3020 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3021 DeadInsts.push_back(CI->getOperand(1));
3022 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3023 "a scale at the same time!");
3024 if (F.AM.Scale == -1) {
3025 if (ICmpScaledV->getType() != OpTy) {
3026 Instruction *Cast =
3027 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3028 OpTy, false),
3029 ICmpScaledV, OpTy, "tmp", CI);
3030 ICmpScaledV = Cast;
3031 }
3032 CI->setOperand(1, ICmpScaledV);
3033 } else {
3034 assert(F.AM.Scale == 0 &&
3035 "ICmp does not support folding a global value and "
3036 "a scale at the same time!");
3037 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3038 -(uint64_t)Offset);
3039 if (C->getType() != OpTy)
3040 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3041 OpTy, false),
3042 C, OpTy);
3043
3044 CI->setOperand(1, C);
3045 }
3046 }
3047
3048 return FullV;
3049}
3050
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003051/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3052/// of their operands effectively happens in their predecessor blocks, so the
3053/// expression may need to be expanded in multiple places.
3054void LSRInstance::RewriteForPHI(PHINode *PN,
3055 const LSRFixup &LF,
3056 const Formula &F,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003057 SCEVExpander &Rewriter,
3058 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003059 Pass *P) const {
3060 DenseMap<BasicBlock *, Value *> Inserted;
3061 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3062 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3063 BasicBlock *BB = PN->getIncomingBlock(i);
3064
3065 // If this is a critical edge, split the edge so that we do not insert
3066 // the code on all predecessor/successor paths. We do this unless this
3067 // is the canonical backedge for this loop, which complicates post-inc
3068 // users.
3069 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3070 !isa<IndirectBrInst>(BB->getTerminator()) &&
3071 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3072 // Split the critical edge.
3073 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3074
3075 // If PN is outside of the loop and BB is in the loop, we want to
3076 // move the block to be immediately before the PHI block, not
3077 // immediately after BB.
3078 if (L->contains(BB) && !L->contains(PN))
3079 NewBB->moveBefore(PN->getParent());
3080
3081 // Splitting the edge can reduce the number of PHI entries we have.
3082 e = PN->getNumIncomingValues();
3083 BB = NewBB;
3084 i = PN->getBasicBlockIndex(BB);
3085 }
3086
3087 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3088 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3089 if (!Pair.second)
3090 PN->setIncomingValue(i, Pair.first->second);
3091 else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003092 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003093
3094 // If this is reuse-by-noop-cast, insert the noop cast.
3095 const Type *OpTy = LF.OperandValToReplace->getType();
3096 if (FullV->getType() != OpTy)
3097 FullV =
3098 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3099 OpTy, false),
3100 FullV, LF.OperandValToReplace->getType(),
3101 "tmp", BB->getTerminator());
3102
3103 PN->setIncomingValue(i, FullV);
3104 Pair.first->second = FullV;
3105 }
3106 }
3107}
3108
Dan Gohman572645c2010-02-12 10:34:29 +00003109/// Rewrite - Emit instructions for the leading candidate expression for this
3110/// LSRUse (this is called "expanding"), and update the UserInst to reference
3111/// the newly expanded value.
3112void LSRInstance::Rewrite(const LSRFixup &LF,
3113 const Formula &F,
Dan Gohman572645c2010-02-12 10:34:29 +00003114 SCEVExpander &Rewriter,
3115 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman572645c2010-02-12 10:34:29 +00003116 Pass *P) const {
Dan Gohman572645c2010-02-12 10:34:29 +00003117 // First, find an insertion point that dominates UserInst. For PHI nodes,
3118 // find the nearest block which dominates all the relevant uses.
3119 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman454d26d2010-02-22 04:11:59 +00003120 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003121 } else {
Dan Gohman454d26d2010-02-22 04:11:59 +00003122 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman572645c2010-02-12 10:34:29 +00003123
3124 // If this is reuse-by-noop-cast, insert the noop cast.
Dan Gohman3a02cbc2010-02-16 20:25:07 +00003125 const Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman572645c2010-02-12 10:34:29 +00003126 if (FullV->getType() != OpTy) {
3127 Instruction *Cast =
3128 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3129 FullV, OpTy, "tmp", LF.UserInst);
3130 FullV = Cast;
3131 }
3132
3133 // Update the user. ICmpZero is handled specially here (for now) because
3134 // Expand may have updated one of the operands of the icmp already, and
3135 // its new value may happen to be equal to LF.OperandValToReplace, in
3136 // which case doing replaceUsesOfWith leads to replacing both operands
3137 // with the same value. TODO: Reorganize this.
3138 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3139 LF.UserInst->setOperand(0, FullV);
3140 else
3141 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3142 }
3143
3144 DeadInsts.push_back(LF.OperandValToReplace);
3145}
3146
3147void
3148LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3149 Pass *P) {
3150 // Keep track of instructions we may have made dead, so that
3151 // we can remove them after we are done working.
3152 SmallVector<WeakVH, 16> DeadInsts;
3153
3154 SCEVExpander Rewriter(SE);
3155 Rewriter.disableCanonicalMode();
3156 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3157
3158 // Expand the new value definitions and update the users.
3159 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3160 size_t LUIdx = Fixups[i].LUIdx;
3161
Dan Gohman454d26d2010-02-22 04:11:59 +00003162 Rewrite(Fixups[i], *Solution[LUIdx], Rewriter, DeadInsts, P);
Dan Gohman572645c2010-02-12 10:34:29 +00003163
3164 Changed = true;
3165 }
3166
3167 // Clean up after ourselves. This must be done before deleting any
3168 // instructions.
3169 Rewriter.clear();
3170
3171 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3172}
3173
3174LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3175 : IU(P->getAnalysis<IVUsers>()),
3176 SE(P->getAnalysis<ScalarEvolution>()),
3177 DT(P->getAnalysis<DominatorTree>()),
3178 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
Devang Patel0f54dcb2007-03-06 21:14:09 +00003179
Dan Gohman03e896b2009-11-05 21:11:53 +00003180 // If LoopSimplify form is not available, stay out of trouble.
Dan Gohman572645c2010-02-12 10:34:29 +00003181 if (!L->isLoopSimplifyForm()) return;
Dan Gohman03e896b2009-11-05 21:11:53 +00003182
Dan Gohman572645c2010-02-12 10:34:29 +00003183 // If there's no interesting work to be done, bail early.
3184 if (IU.empty()) return;
Dan Gohman80b0f8c2009-03-09 20:34:59 +00003185
Dan Gohman572645c2010-02-12 10:34:29 +00003186 DEBUG(dbgs() << "\nLSR on loop ";
3187 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3188 dbgs() << ":\n");
Dan Gohmanf7912df2009-03-09 20:46:50 +00003189
Dan Gohman572645c2010-02-12 10:34:29 +00003190 /// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman3f46a3a2010-03-01 17:49:51 +00003191 /// inside the loop then try to eliminate the cast operation.
Dan Gohman572645c2010-02-12 10:34:29 +00003192 OptimizeShadowIV();
Chris Lattner010de252005-08-08 05:28:22 +00003193
Dan Gohman572645c2010-02-12 10:34:29 +00003194 // Change loop terminating condition to use the postinc iv when possible.
3195 Changed |= OptimizeLoopTermCond();
Evan Cheng5792f512009-05-11 22:33:01 +00003196
Dan Gohman572645c2010-02-12 10:34:29 +00003197 CollectInterestingTypesAndFactors();
3198 CollectFixupsAndInitialFormulae();
3199 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner010de252005-08-08 05:28:22 +00003200
Dan Gohman572645c2010-02-12 10:34:29 +00003201 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3202 print_uses(dbgs()));
Misha Brukmanfd939082005-04-21 23:48:37 +00003203
Dan Gohman572645c2010-02-12 10:34:29 +00003204 // Now use the reuse data to generate a bunch of interesting ways
3205 // to formulate the values needed for the uses.
3206 GenerateAllReuseFormulae();
Evan Chengd1d6b5c2006-03-16 21:53:05 +00003207
Dan Gohman572645c2010-02-12 10:34:29 +00003208 DEBUG(dbgs() << "\n"
3209 "After generating reuse formulae:\n";
3210 print_uses(dbgs()));
Nate Begemaneaa13852004-10-18 21:08:22 +00003211
Dan Gohman572645c2010-02-12 10:34:29 +00003212 FilterOutUndesirableDedicatedRegisters();
3213 NarrowSearchSpaceUsingHeuristics();
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003214
Dan Gohman572645c2010-02-12 10:34:29 +00003215 SmallVector<const Formula *, 8> Solution;
3216 Solve(Solution);
3217 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman6bec5bb2009-12-18 00:06:20 +00003218
Dan Gohman572645c2010-02-12 10:34:29 +00003219 // Release memory that is no longer needed.
3220 Factors.clear();
3221 Types.clear();
3222 RegUses.clear();
3223
3224#ifndef NDEBUG
3225 // Formulae should be legal.
3226 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3227 E = Uses.end(); I != E; ++I) {
3228 const LSRUse &LU = *I;
3229 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3230 JE = LU.Formulae.end(); J != JE; ++J)
3231 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3232 LU.Kind, LU.AccessTy, TLI) &&
3233 "Illegal formula generated!");
3234 };
3235#endif
3236
3237 // Now that we've decided what we want, make it so.
3238 ImplementSolution(Solution, P);
3239}
3240
3241void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3242 if (Factors.empty() && Types.empty()) return;
3243
3244 OS << "LSR has identified the following interesting factors and types: ";
3245 bool First = true;
3246
3247 for (SmallSetVector<int64_t, 8>::const_iterator
3248 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3249 if (!First) OS << ", ";
3250 First = false;
3251 OS << '*' << *I;
Evan Cheng81ebdcf2009-11-10 21:14:05 +00003252 }
Dale Johannesenc1acc3f2009-05-11 17:15:42 +00003253
Dan Gohman572645c2010-02-12 10:34:29 +00003254 for (SmallSetVector<const Type *, 4>::const_iterator
3255 I = Types.begin(), E = Types.end(); I != E; ++I) {
3256 if (!First) OS << ", ";
3257 First = false;
3258 OS << '(' << **I << ')';
3259 }
3260 OS << '\n';
3261}
3262
3263void LSRInstance::print_fixups(raw_ostream &OS) const {
3264 OS << "LSR is examining the following fixup sites:\n";
3265 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3266 E = Fixups.end(); I != E; ++I) {
3267 const LSRFixup &LF = *I;
3268 dbgs() << " ";
3269 LF.print(OS);
3270 OS << '\n';
3271 }
3272}
3273
3274void LSRInstance::print_uses(raw_ostream &OS) const {
3275 OS << "LSR is examining the following uses:\n";
3276 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3277 E = Uses.end(); I != E; ++I) {
3278 const LSRUse &LU = *I;
3279 dbgs() << " ";
3280 LU.print(OS);
3281 OS << '\n';
3282 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3283 JE = LU.Formulae.end(); J != JE; ++J) {
3284 OS << " ";
3285 J->print(OS);
3286 OS << '\n';
3287 }
3288 }
3289}
3290
3291void LSRInstance::print(raw_ostream &OS) const {
3292 print_factors_and_types(OS);
3293 print_fixups(OS);
3294 print_uses(OS);
3295}
3296
3297void LSRInstance::dump() const {
3298 print(errs()); errs() << '\n';
3299}
3300
3301namespace {
3302
3303class LoopStrengthReduce : public LoopPass {
3304 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3305 /// transformation profitability.
3306 const TargetLowering *const TLI;
3307
3308public:
3309 static char ID; // Pass ID, replacement for typeid
3310 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3311
3312private:
3313 bool runOnLoop(Loop *L, LPPassManager &LPM);
3314 void getAnalysisUsage(AnalysisUsage &AU) const;
3315};
3316
3317}
3318
3319char LoopStrengthReduce::ID = 0;
3320static RegisterPass<LoopStrengthReduce>
3321X("loop-reduce", "Loop Strength Reduction");
3322
3323Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3324 return new LoopStrengthReduce(TLI);
3325}
3326
3327LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3328 : LoopPass(&ID), TLI(tli) {}
3329
3330void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3331 // We split critical edges, so we change the CFG. However, we do update
3332 // many analyses if they are around.
3333 AU.addPreservedID(LoopSimplifyID);
3334 AU.addPreserved<LoopInfo>();
3335 AU.addPreserved("domfrontier");
3336
3337 AU.addRequiredID(LoopSimplifyID);
3338 AU.addRequired<DominatorTree>();
3339 AU.addPreserved<DominatorTree>();
3340 AU.addRequired<ScalarEvolution>();
3341 AU.addPreserved<ScalarEvolution>();
3342 AU.addRequired<IVUsers>();
3343 AU.addPreserved<IVUsers>();
3344}
3345
3346bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3347 bool Changed = false;
3348
3349 // Run the main LSR transformation.
3350 Changed |= LSRInstance(TLI, L, this).getChanged();
3351
Dan Gohmanafc36a92009-05-02 18:29:22 +00003352 // At this point, it is worth checking to see if any recurrence PHIs are also
Dan Gohman35738ac2009-05-04 22:30:44 +00003353 // dead, so that we can remove them as well.
Dan Gohman9fff2182010-01-05 16:31:45 +00003354 Changed |= DeleteDeadPHIs(L->getHeader());
Dan Gohmanafc36a92009-05-02 18:29:22 +00003355
Evan Cheng1ce75dc2008-07-07 19:51:32 +00003356 return Changed;
Nate Begemaneaa13852004-10-18 21:08:22 +00003357}