blob: 01728ae680de7fec9126896c0aec465bab9ea205 [file] [log] [blame]
Dan Gohman0a40ad92009-04-16 03:18:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
Dan Gohman97f70ad2009-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 Begemanb18121e2004-10-18 21:08:22 +000014// This pass performs a strength reduction on array references inside loops that
Dan Gohman97f70ad2009-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 Begemanb18121e2004-10-18 21:08:22 +000019//
Dan Gohman45774ce2010-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
Sanjoy Das7041fb12015-03-27 06:01:56 +000031// the value of the register before the add and some using it after. In this
Dan Gohman45774ce2010-02-12 10:34:29 +000032// 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//
Chandler Carruth26c59fa2013-01-07 14:41:08 +000040// TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
41// of a GlobalValue?
Dan Gohman45774ce2010-02-12 10:34:29 +000042//
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 Begemanb18121e2004-10-18 21:08:22 +000054//===----------------------------------------------------------------------===//
55
Dehao Chen6132ee82016-07-18 21:41:50 +000056#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000057#include "llvm/ADT/APInt.h"
58#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include "llvm/ADT/DenseSet.h"
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +000060#include "llvm/ADT/Hashing.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000061#include "llvm/ADT/PointerIntPair.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000062#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/ADT/SetVector.h"
64#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000065#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/SmallSet.h"
67#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000068#include "llvm/Analysis/IVUsers.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000069#include "llvm/Analysis/LoopInfo.h"
Devang Patelb0743b52007-03-06 21:14:09 +000070#include "llvm/Analysis/LoopPass.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000071#include "llvm/Analysis/ScalarEvolution.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000072#include "llvm/Analysis/ScalarEvolutionExpander.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000073#include "llvm/Analysis/ScalarEvolutionExpressions.h"
74#include "llvm/Analysis/ScalarEvolutionNormalization.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000075#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000076#include "llvm/IR/BasicBlock.h"
77#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000078#include "llvm/IR/Constants.h"
79#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000080#include "llvm/IR/Dominators.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000081#include "llvm/IR/GlobalValue.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000082#include "llvm/IR/IRBuilder.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000083#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000084#include "llvm/IR/Instructions.h"
85#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000086#include "llvm/IR/Module.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000087#include "llvm/IR/OperandTraits.h"
88#include "llvm/IR/Operator.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000089#include "llvm/IR/Type.h"
90#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000091#include "llvm/IR/ValueHandle.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000092#include "llvm/Pass.h"
93#include "llvm/Support/Casting.h"
Andrew Trick58124392011-09-27 00:44:14 +000094#include "llvm/Support/CommandLine.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000095#include "llvm/Support/Compiler.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000096#include "llvm/Support/Debug.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000097#include "llvm/Support/ErrorHandling.h"
98#include "llvm/Support/MathExtras.h"
Daniel Dunbar6115b392009-07-26 09:48:23 +000099#include "llvm/Support/raw_ostream.h"
Dehao Chen6132ee82016-07-18 21:41:50 +0000100#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +0000101#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000102#include "llvm/Transforms/Utils/BasicBlockUtils.h"
103#include "llvm/Transforms/Utils/Local.h"
Jeff Cohenc5009912005-07-30 18:22:27 +0000104#include <algorithm>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000105#include <cassert>
106#include <cstddef>
107#include <cstdint>
108#include <cstdlib>
109#include <iterator>
110#include <map>
111#include <tuple>
112#include <utility>
113
Nate Begemanb18121e2004-10-18 21:08:22 +0000114using namespace llvm;
115
Chandler Carruth964daaa2014-04-22 02:55:47 +0000116#define DEBUG_TYPE "loop-reduce"
117
Andrew Trick19f80c12012-04-18 04:00:10 +0000118/// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for
119/// bail out. This threshold is far beyond the number of users that LSR can
120/// conceivably solve, so it should not affect generated code, but catches the
121/// worst cases before LSR burns too much compile time and stack space.
122static const unsigned MaxIVUsers = 200;
123
Andrew Trickecbe22b2011-10-11 02:30:45 +0000124// Temporary flag to cleanup congruent phis after LSR phi expansion.
125// It's currently disabled until we can determine whether it's truly useful or
126// not. The flag should be removed after the v3.0 release.
Andrew Trick06f6c052012-01-07 07:08:17 +0000127// This is now needed for ivchains.
Benjamin Kramer7ba71be2011-11-26 23:01:57 +0000128static cl::opt<bool> EnablePhiElim(
Andrew Trick06f6c052012-01-07 07:08:17 +0000129 "enable-lsr-phielim", cl::Hidden, cl::init(true),
130 cl::desc("Enable LSR phi elimination"));
Andrew Trick58124392011-09-27 00:44:14 +0000131
Andrew Trick248d4102012-01-09 21:18:52 +0000132#ifndef NDEBUG
133// Stress test IV chain generation.
134static cl::opt<bool> StressIVChain(
135 "stress-ivchain", cl::Hidden, cl::init(false),
136 cl::desc("Stress test LSR IV chains"));
137#else
138static bool StressIVChain = false;
139#endif
140
Dan Gohman45774ce2010-02-12 10:34:29 +0000141namespace {
Nate Begemanb18121e2004-10-18 21:08:22 +0000142
Matt Arsenault427a0fd2015-08-15 00:53:06 +0000143struct MemAccessTy {
144 /// Used in situations where the accessed memory type is unknown.
145 static const unsigned UnknownAddressSpace = ~0u;
146
147 Type *MemTy;
148 unsigned AddrSpace;
149
150 MemAccessTy() : MemTy(nullptr), AddrSpace(UnknownAddressSpace) {}
151
152 MemAccessTy(Type *Ty, unsigned AS) :
153 MemTy(Ty), AddrSpace(AS) {}
154
155 bool operator==(MemAccessTy Other) const {
156 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
157 }
158
159 bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
160
161 static MemAccessTy getUnknown(LLVMContext &Ctx) {
162 return MemAccessTy(Type::getVoidTy(Ctx), UnknownAddressSpace);
163 }
164};
165
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000166/// This class holds data which is used to order reuse candidates.
Dan Gohman45774ce2010-02-12 10:34:29 +0000167class RegSortData {
168public:
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000169 /// This represents the set of LSRUse indices which reference
Dan Gohman45774ce2010-02-12 10:34:29 +0000170 /// a particular register.
171 SmallBitVector UsedByIndices;
172
Dan Gohman45774ce2010-02-12 10:34:29 +0000173 void print(raw_ostream &OS) const;
174 void dump() const;
175};
176
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000177} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +0000178
179void RegSortData::print(raw_ostream &OS) const {
180 OS << "[NumUses=" << UsedByIndices.count() << ']';
181}
182
Davide Italiano945d05f2015-11-23 02:47:30 +0000183LLVM_DUMP_METHOD
Dan Gohman45774ce2010-02-12 10:34:29 +0000184void RegSortData::dump() const {
185 print(errs()); errs() << '\n';
186}
Dan Gohman2a12ae72009-02-20 04:17:46 +0000187
Chris Lattner79a42ac2006-12-19 21:40:18 +0000188namespace {
Dale Johannesene3a02be2007-03-20 00:47:50 +0000189
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000190/// Map register candidates to information about how they are used.
Dan Gohman45774ce2010-02-12 10:34:29 +0000191class RegUseTracker {
192 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
Dale Johannesene3a02be2007-03-20 00:47:50 +0000193
Dan Gohman248c41d2010-05-18 22:33:00 +0000194 RegUsesTy RegUsesMap;
Dan Gohman45774ce2010-02-12 10:34:29 +0000195 SmallVector<const SCEV *, 16> RegSequence;
Evan Cheng3df447d2006-03-16 21:53:05 +0000196
Dan Gohman45774ce2010-02-12 10:34:29 +0000197public:
Sanjoy Das302bfd02015-08-16 18:22:43 +0000198 void countRegister(const SCEV *Reg, size_t LUIdx);
199 void dropRegister(const SCEV *Reg, size_t LUIdx);
200 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000201
Dan Gohman45774ce2010-02-12 10:34:29 +0000202 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000203
Dan Gohman45774ce2010-02-12 10:34:29 +0000204 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000205
Dan Gohman45774ce2010-02-12 10:34:29 +0000206 void clear();
Dan Gohman51ad99d2010-01-21 02:09:26 +0000207
Dan Gohman45774ce2010-02-12 10:34:29 +0000208 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
209 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
210 iterator begin() { return RegSequence.begin(); }
211 iterator end() { return RegSequence.end(); }
212 const_iterator begin() const { return RegSequence.begin(); }
213 const_iterator end() const { return RegSequence.end(); }
214};
Dan Gohman51ad99d2010-01-21 02:09:26 +0000215
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000216} // end anonymous namespace
Dan Gohman51ad99d2010-01-21 02:09:26 +0000217
Dan Gohman45774ce2010-02-12 10:34:29 +0000218void
Sanjoy Das302bfd02015-08-16 18:22:43 +0000219RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000220 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman248c41d2010-05-18 22:33:00 +0000221 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman45774ce2010-02-12 10:34:29 +0000222 RegSortData &RSD = Pair.first->second;
223 if (Pair.second)
224 RegSequence.push_back(Reg);
225 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
226 RSD.UsedByIndices.set(LUIdx);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000227}
228
Dan Gohman4cf99b52010-05-18 23:42:37 +0000229void
Sanjoy Das302bfd02015-08-16 18:22:43 +0000230RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
Dan Gohman4cf99b52010-05-18 23:42:37 +0000231 RegUsesTy::iterator It = RegUsesMap.find(Reg);
232 assert(It != RegUsesMap.end());
233 RegSortData &RSD = It->second;
234 assert(RSD.UsedByIndices.size() > LUIdx);
235 RSD.UsedByIndices.reset(LUIdx);
236}
237
Dan Gohman20fab452010-05-19 23:43:12 +0000238void
Sanjoy Das302bfd02015-08-16 18:22:43 +0000239RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
Dan Gohmana7b68d62010-10-07 23:33:43 +0000240 assert(LUIdx <= LastLUIdx);
241
242 // Update RegUses. The data structure is not optimized for this purpose;
243 // we must iterate through it and update each of the bit vectors.
Craig Topper10949ae2015-05-23 08:45:10 +0000244 for (auto &Pair : RegUsesMap) {
245 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
Dan Gohmana7b68d62010-10-07 23:33:43 +0000246 if (LUIdx < UsedByIndices.size())
247 UsedByIndices[LUIdx] =
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000248 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
Dan Gohmana7b68d62010-10-07 23:33:43 +0000249 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
250 }
Dan Gohman20fab452010-05-19 23:43:12 +0000251}
252
Dan Gohman45774ce2010-02-12 10:34:29 +0000253bool
254RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman4f13bbf2010-08-29 15:18:49 +0000255 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
256 if (I == RegUsesMap.end())
257 return false;
258 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
Dan Gohman45774ce2010-02-12 10:34:29 +0000259 int i = UsedByIndices.find_first();
260 if (i == -1) return false;
261 if ((size_t)i != LUIdx) return true;
262 return UsedByIndices.find_next(i) != -1;
263}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000264
Dan Gohman45774ce2010-02-12 10:34:29 +0000265const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman248c41d2010-05-18 22:33:00 +0000266 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
267 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman45774ce2010-02-12 10:34:29 +0000268 return I->second.UsedByIndices;
269}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000270
Dan Gohman45774ce2010-02-12 10:34:29 +0000271void RegUseTracker::clear() {
Dan Gohman248c41d2010-05-18 22:33:00 +0000272 RegUsesMap.clear();
Dan Gohman45774ce2010-02-12 10:34:29 +0000273 RegSequence.clear();
274}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000275
Dan Gohman45774ce2010-02-12 10:34:29 +0000276namespace {
277
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000278/// This class holds information that describes a formula for computing
279/// satisfying a use. It may include broken-out immediates and scaled registers.
Dan Gohman45774ce2010-02-12 10:34:29 +0000280struct Formula {
Chandler Carruth6e479322013-01-07 15:04:40 +0000281 /// Global base address used for complex addressing.
282 GlobalValue *BaseGV;
283
284 /// Base offset for complex addressing.
285 int64_t BaseOffset;
286
287 /// Whether any complex addressing has a base register.
288 bool HasBaseReg;
289
290 /// The scale of any complex addressing.
291 int64_t Scale;
Dan Gohman45774ce2010-02-12 10:34:29 +0000292
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000293 /// The list of "base" registers for this use. When this is non-empty. The
294 /// canonical representation of a formula is
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000295 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
296 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
297 /// #1 enforces that the scaled register is always used when at least two
298 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
299 /// #2 enforces that 1 * reg is reg.
300 /// This invariant can be temporarly broken while building a formula.
301 /// However, every formula inserted into the LSRInstance must be in canonical
302 /// form.
Preston Gurd25c3b6a2013-02-01 20:41:27 +0000303 SmallVector<const SCEV *, 4> BaseRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +0000304
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000305 /// The 'scaled' register for this use. This should be non-null when Scale is
306 /// not zero.
Dan Gohman45774ce2010-02-12 10:34:29 +0000307 const SCEV *ScaledReg;
308
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000309 /// An additional constant offset which added near the use. This requires a
310 /// temporary register, but the offset itself can live in an add immediate
311 /// field rather than a register.
Dan Gohman6136e942011-05-03 00:46:49 +0000312 int64_t UnfoldedOffset;
313
Chandler Carruth6e479322013-01-07 15:04:40 +0000314 Formula()
Craig Topperf40110f2014-04-25 05:29:35 +0000315 : BaseGV(nullptr), BaseOffset(0), HasBaseReg(false), Scale(0),
Sanjoy Das215df9e2015-08-04 01:52:05 +0000316 ScaledReg(nullptr), UnfoldedOffset(0) {}
Dan Gohman45774ce2010-02-12 10:34:29 +0000317
Sanjoy Das302bfd02015-08-16 18:22:43 +0000318 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000319
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000320 bool isCanonical() const;
321
Sanjoy Das302bfd02015-08-16 18:22:43 +0000322 void canonicalize();
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000323
Sanjoy Das302bfd02015-08-16 18:22:43 +0000324 bool unscale();
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000325
Adam Nemetdeab6f92014-04-29 18:25:28 +0000326 size_t getNumRegs() const;
Chris Lattner229907c2011-07-18 04:54:35 +0000327 Type *getType() const;
Dan Gohman45774ce2010-02-12 10:34:29 +0000328
Sanjoy Das302bfd02015-08-16 18:22:43 +0000329 void deleteBaseReg(const SCEV *&S);
Dan Gohman80a96082010-05-20 15:17:54 +0000330
Dan Gohman45774ce2010-02-12 10:34:29 +0000331 bool referencesReg(const SCEV *S) const;
332 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
333 const RegUseTracker &RegUses) const;
334
335 void print(raw_ostream &OS) const;
336 void dump() const;
337};
338
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000339} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +0000340
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000341/// Recursion helper for initialMatch.
Dan Gohman45774ce2010-02-12 10:34:29 +0000342static void DoInitialMatch(const SCEV *S, Loop *L,
343 SmallVectorImpl<const SCEV *> &Good,
344 SmallVectorImpl<const SCEV *> &Bad,
Dan Gohman20d9ce22010-11-17 21:41:58 +0000345 ScalarEvolution &SE) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000346 // Collect expressions which properly dominate the loop header.
Dan Gohman20d9ce22010-11-17 21:41:58 +0000347 if (SE.properlyDominates(S, L->getHeader())) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000348 Good.push_back(S);
349 return;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000350 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000351
352 // Look at add operands.
353 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Craig Topper77b99412015-05-23 08:01:41 +0000354 for (const SCEV *S : Add->operands())
355 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000356 return;
357 }
358
359 // Look at addrec operands.
360 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
Alexandros Lamprineas0ee3ec22016-11-09 08:53:07 +0000361 if (!AR->getStart()->isZero() && AR->isAffine()) {
Dan Gohman20d9ce22010-11-17 21:41:58 +0000362 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000363 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman45774ce2010-02-12 10:34:29 +0000364 AR->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000365 // FIXME: AR->getNoWrapFlags()
366 AR->getLoop(), SCEV::FlagAnyWrap),
Dan Gohman20d9ce22010-11-17 21:41:58 +0000367 L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000368 return;
369 }
370
371 // Handle a multiplication by -1 (negation) if it didn't fold.
372 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
373 if (Mul->getOperand(0)->isAllOnesValue()) {
374 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
375 const SCEV *NewMul = SE.getMulExpr(Ops);
376
377 SmallVector<const SCEV *, 4> MyGood;
378 SmallVector<const SCEV *, 4> MyBad;
Dan Gohman20d9ce22010-11-17 21:41:58 +0000379 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000380 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
381 SE.getEffectiveSCEVType(NewMul->getType())));
Craig Topper042a3922015-05-25 20:01:18 +0000382 for (const SCEV *S : MyGood)
383 Good.push_back(SE.getMulExpr(NegOne, S));
384 for (const SCEV *S : MyBad)
385 Bad.push_back(SE.getMulExpr(NegOne, S));
Dan Gohman45774ce2010-02-12 10:34:29 +0000386 return;
387 }
388
389 // Ok, we can't do anything interesting. Just stuff the whole thing into a
390 // register and hope for the best.
391 Bad.push_back(S);
392}
393
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000394/// Incorporate loop-variant parts of S into this Formula, attempting to keep
395/// all loop-invariant and loop-computable values in a single base register.
Sanjoy Das302bfd02015-08-16 18:22:43 +0000396void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000397 SmallVector<const SCEV *, 4> Good;
398 SmallVector<const SCEV *, 4> Bad;
Dan Gohman20d9ce22010-11-17 21:41:58 +0000399 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000400 if (!Good.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000401 const SCEV *Sum = SE.getAddExpr(Good);
402 if (!Sum->isZero())
403 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000404 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000405 }
406 if (!Bad.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000407 const SCEV *Sum = SE.getAddExpr(Bad);
408 if (!Sum->isZero())
409 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000410 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000411 }
Sanjoy Das302bfd02015-08-16 18:22:43 +0000412 canonicalize();
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000413}
414
415/// \brief Check whether or not this formula statisfies the canonical
416/// representation.
417/// \see Formula::BaseRegs.
418bool Formula::isCanonical() const {
419 if (ScaledReg)
420 return Scale != 1 || !BaseRegs.empty();
421 return BaseRegs.size() <= 1;
422}
423
424/// \brief Helper method to morph a formula into its canonical representation.
425/// \see Formula::BaseRegs.
426/// Every formula having more than one base register, must use the ScaledReg
427/// field. Otherwise, we would have to do special cases everywhere in LSR
428/// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
429/// On the other hand, 1*reg should be canonicalized into reg.
Sanjoy Das302bfd02015-08-16 18:22:43 +0000430void Formula::canonicalize() {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000431 if (isCanonical())
432 return;
433 // So far we did not need this case. This is easy to implement but it is
434 // useless to maintain dead code. Beside it could hurt compile time.
435 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
436 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
437 ScaledReg = BaseRegs.back();
438 BaseRegs.pop_back();
439 Scale = 1;
440 size_t BaseRegsSize = BaseRegs.size();
441 size_t Try = 0;
442 // If ScaledReg is an invariant, try to find a variant expression.
443 while (Try < BaseRegsSize && !isa<SCEVAddRecExpr>(ScaledReg))
444 std::swap(ScaledReg, BaseRegs[Try++]);
445}
446
447/// \brief Get rid of the scale in the formula.
448/// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
449/// \return true if it was possible to get rid of the scale, false otherwise.
450/// \note After this operation the formula may not be in the canonical form.
Sanjoy Das302bfd02015-08-16 18:22:43 +0000451bool Formula::unscale() {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000452 if (Scale != 1)
453 return false;
454 Scale = 0;
455 BaseRegs.push_back(ScaledReg);
456 ScaledReg = nullptr;
457 return true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000458}
459
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000460/// Return the total number of register operands used by this formula. This does
461/// not include register uses implied by non-constant addrec strides.
Adam Nemetdeab6f92014-04-29 18:25:28 +0000462size_t Formula::getNumRegs() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000463 return !!ScaledReg + BaseRegs.size();
464}
465
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000466/// Return the type of this formula, if it has one, or null otherwise. This type
467/// is meaningless except for the bit size.
Chris Lattner229907c2011-07-18 04:54:35 +0000468Type *Formula::getType() const {
Sanjoy Das215df9e2015-08-04 01:52:05 +0000469 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
470 ScaledReg ? ScaledReg->getType() :
471 BaseGV ? BaseGV->getType() :
472 nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000473}
474
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000475/// Delete the given base reg from the BaseRegs list.
Sanjoy Das302bfd02015-08-16 18:22:43 +0000476void Formula::deleteBaseReg(const SCEV *&S) {
Dan Gohman80a96082010-05-20 15:17:54 +0000477 if (&S != &BaseRegs.back())
478 std::swap(S, BaseRegs.back());
479 BaseRegs.pop_back();
480}
481
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000482/// Test if this formula references the given register.
Dan Gohman45774ce2010-02-12 10:34:29 +0000483bool Formula::referencesReg(const SCEV *S) const {
David Majnemer0d955d02016-08-11 22:21:41 +0000484 return S == ScaledReg || is_contained(BaseRegs, S);
Dan Gohman45774ce2010-02-12 10:34:29 +0000485}
486
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000487/// Test whether this formula uses registers which are used by uses other than
488/// the use with the given index.
Dan Gohman45774ce2010-02-12 10:34:29 +0000489bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
490 const RegUseTracker &RegUses) const {
491 if (ScaledReg)
492 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
493 return true;
Craig Topper042a3922015-05-25 20:01:18 +0000494 for (const SCEV *BaseReg : BaseRegs)
495 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
Dan Gohman45774ce2010-02-12 10:34:29 +0000496 return true;
497 return false;
498}
499
500void Formula::print(raw_ostream &OS) const {
501 bool First = true;
Chandler Carruth6e479322013-01-07 15:04:40 +0000502 if (BaseGV) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000503 if (!First) OS << " + "; else First = false;
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000504 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +0000505 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000506 if (BaseOffset != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000507 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000508 OS << BaseOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +0000509 }
Craig Topper042a3922015-05-25 20:01:18 +0000510 for (const SCEV *BaseReg : BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000511 if (!First) OS << " + "; else First = false;
Sanjoy Das215df9e2015-08-04 01:52:05 +0000512 OS << "reg(" << *BaseReg << ')';
Dan Gohman45774ce2010-02-12 10:34:29 +0000513 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000514 if (HasBaseReg && BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000515 if (!First) OS << " + "; else First = false;
516 OS << "**error: HasBaseReg**";
Chandler Carruth6e479322013-01-07 15:04:40 +0000517 } else if (!HasBaseReg && !BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000518 if (!First) OS << " + "; else First = false;
519 OS << "**error: !HasBaseReg**";
520 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000521 if (Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000522 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000523 OS << Scale << "*reg(";
Sanjoy Das215df9e2015-08-04 01:52:05 +0000524 if (ScaledReg)
525 OS << *ScaledReg;
526 else
Dan Gohman45774ce2010-02-12 10:34:29 +0000527 OS << "<unknown>";
528 OS << ')';
529 }
Dan Gohman6136e942011-05-03 00:46:49 +0000530 if (UnfoldedOffset != 0) {
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +0000531 if (!First) OS << " + ";
Dan Gohman6136e942011-05-03 00:46:49 +0000532 OS << "imm(" << UnfoldedOffset << ')';
533 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000534}
535
Davide Italiano945d05f2015-11-23 02:47:30 +0000536LLVM_DUMP_METHOD
Dan Gohman45774ce2010-02-12 10:34:29 +0000537void Formula::dump() const {
538 print(errs()); errs() << '\n';
539}
540
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000541/// Return true if the given addrec can be sign-extended without changing its
542/// value.
Dan Gohman85af2562010-02-19 19:32:49 +0000543static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000544 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000545 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000546 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
547}
548
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000549/// Return true if the given add can be sign-extended without changing its
550/// value.
Dan Gohman85af2562010-02-19 19:32:49 +0000551static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000552 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000553 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000554 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
555}
556
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000557/// Return true if the given mul can be sign-extended without changing its
558/// value.
Dan Gohmanab542222010-06-24 16:45:11 +0000559static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000560 Type *WideTy =
Dan Gohmanab542222010-06-24 16:45:11 +0000561 IntegerType::get(SE.getContext(),
562 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
563 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohman85af2562010-02-19 19:32:49 +0000564}
565
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000566/// Return an expression for LHS /s RHS, if it can be determined and if the
567/// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
568/// is true, expressions like (X * Y) /s Y are simplified to Y, ignoring that
569/// the multiplication may overflow, which is useful when the result will be
570/// used in a context where the most significant bits are ignored.
Dan Gohman4eebb942010-02-19 19:35:48 +0000571static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
572 ScalarEvolution &SE,
573 bool IgnoreSignificantBits = false) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000574 // Handle the trivial case, which works for any SCEV type.
575 if (LHS == RHS)
Dan Gohman1d2ded72010-05-03 22:09:21 +0000576 return SE.getConstant(LHS->getType(), 1);
Dan Gohman45774ce2010-02-12 10:34:29 +0000577
Dan Gohman47ddf762010-06-24 16:51:25 +0000578 // Handle a few RHS special cases.
579 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
580 if (RC) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000581 const APInt &RA = RC->getAPInt();
Dan Gohman47ddf762010-06-24 16:51:25 +0000582 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
583 // some folding.
584 if (RA.isAllOnesValue())
585 return SE.getMulExpr(LHS, RC);
586 // Handle x /s 1 as x.
587 if (RA == 1)
588 return LHS;
589 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000590
591 // Check for a division of a constant by a constant.
592 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000593 if (!RC)
Craig Topperf40110f2014-04-25 05:29:35 +0000594 return nullptr;
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000595 const APInt &LA = C->getAPInt();
596 const APInt &RA = RC->getAPInt();
Dan Gohman47ddf762010-06-24 16:51:25 +0000597 if (LA.srem(RA) != 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000598 return nullptr;
Dan Gohman47ddf762010-06-24 16:51:25 +0000599 return SE.getConstant(LA.sdiv(RA));
Dan Gohman45774ce2010-02-12 10:34:29 +0000600 }
601
Dan Gohman85af2562010-02-19 19:32:49 +0000602 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000603 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Alexandros Lamprineas0ee3ec22016-11-09 08:53:07 +0000604 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
Dan Gohman4eebb942010-02-19 19:35:48 +0000605 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
606 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000607 if (!Step) return nullptr;
Dan Gohman129a8162010-08-19 01:02:31 +0000608 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
609 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000610 if (!Start) return nullptr;
Andrew Trick8b55b732011-03-14 16:50:06 +0000611 // FlagNW is independent of the start value, step direction, and is
612 // preserved with smaller magnitude steps.
613 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
614 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman85af2562010-02-19 19:32:49 +0000615 }
Craig Topperf40110f2014-04-25 05:29:35 +0000616 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000617 }
618
Dan Gohman85af2562010-02-19 19:32:49 +0000619 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000620 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000621 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
622 SmallVector<const SCEV *, 8> Ops;
Craig Topper042a3922015-05-25 20:01:18 +0000623 for (const SCEV *S : Add->operands()) {
624 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000625 if (!Op) return nullptr;
Dan Gohman85af2562010-02-19 19:32:49 +0000626 Ops.push_back(Op);
627 }
628 return SE.getAddExpr(Ops);
Dan Gohman45774ce2010-02-12 10:34:29 +0000629 }
Craig Topperf40110f2014-04-25 05:29:35 +0000630 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000631 }
632
633 // Check for a multiply operand that we can pull RHS out of.
Dan Gohman963b1c12010-06-24 16:57:52 +0000634 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000635 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000636 SmallVector<const SCEV *, 4> Ops;
637 bool Found = false;
Craig Topper042a3922015-05-25 20:01:18 +0000638 for (const SCEV *S : Mul->operands()) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000639 if (!Found)
Dan Gohman6b733fc2010-05-20 16:23:28 +0000640 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohman4eebb942010-02-19 19:35:48 +0000641 IgnoreSignificantBits)) {
Dan Gohman6b733fc2010-05-20 16:23:28 +0000642 S = Q;
Dan Gohman45774ce2010-02-12 10:34:29 +0000643 Found = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000644 }
Dan Gohman6b733fc2010-05-20 16:23:28 +0000645 Ops.push_back(S);
Dan Gohman45774ce2010-02-12 10:34:29 +0000646 }
Craig Topperf40110f2014-04-25 05:29:35 +0000647 return Found ? SE.getMulExpr(Ops) : nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000648 }
Craig Topperf40110f2014-04-25 05:29:35 +0000649 return nullptr;
Dan Gohman963b1c12010-06-24 16:57:52 +0000650 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000651
652 // Otherwise we don't know.
Craig Topperf40110f2014-04-25 05:29:35 +0000653 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000654}
655
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000656/// If S involves the addition of a constant integer value, return that integer
657/// value, and mutate S to point to a new SCEV with that value excluded.
Dan Gohman45774ce2010-02-12 10:34:29 +0000658static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
659 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000660 if (C->getAPInt().getMinSignedBits() <= 64) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000661 S = SE.getConstant(C->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000662 return C->getValue()->getSExtValue();
663 }
664 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
665 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
666 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000667 if (Result != 0)
668 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000669 return Result;
670 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
671 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
672 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000673 if (Result != 0)
Andrew Trick8b55b732011-03-14 16:50:06 +0000674 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
675 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
676 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000677 return Result;
678 }
679 return 0;
680}
681
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000682/// If S involves the addition of a GlobalValue address, return that symbol, and
683/// mutate S to point to a new SCEV with that value excluded.
Dan Gohman45774ce2010-02-12 10:34:29 +0000684static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
685 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
686 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000687 S = SE.getConstant(GV->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000688 return GV;
689 }
690 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
691 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
692 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000693 if (Result)
694 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000695 return Result;
696 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
697 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
698 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000699 if (Result)
Andrew Trick8b55b732011-03-14 16:50:06 +0000700 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
701 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
702 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000703 return Result;
704 }
Craig Topperf40110f2014-04-25 05:29:35 +0000705 return nullptr;
Nate Begemanb18121e2004-10-18 21:08:22 +0000706}
707
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000708/// Returns true if the specified instruction is using the specified value as an
709/// address.
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000710static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
711 bool isAddress = isa<LoadInst>(Inst);
712 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
713 if (SI->getOperand(1) == OperandVal)
714 isAddress = true;
715 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
716 // Addressing modes can also be folded into prefetches and a variety
717 // of intrinsics.
718 switch (II->getIntrinsicID()) {
719 default: break;
720 case Intrinsic::prefetch:
Gabor Greif8ae30952010-06-30 09:15:28 +0000721 if (II->getArgOperand(0) == OperandVal)
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000722 isAddress = true;
723 break;
724 }
725 }
726 return isAddress;
727}
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000728
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000729/// Return the type of the memory being accessed.
Matt Arsenault427a0fd2015-08-15 00:53:06 +0000730static MemAccessTy getAccessType(const Instruction *Inst) {
731 MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace);
732 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
733 AccessTy.MemTy = SI->getOperand(0)->getType();
734 AccessTy.AddrSpace = SI->getPointerAddressSpace();
735 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
736 AccessTy.AddrSpace = LI->getPointerAddressSpace();
Dan Gohman917ffe42009-03-09 21:01:17 +0000737 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000738
739 // All pointers have the same requirements, so canonicalize them to an
740 // arbitrary pointer type to minimize variation.
Matt Arsenault427a0fd2015-08-15 00:53:06 +0000741 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
742 AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
743 PTy->getAddressSpace());
Dan Gohman45774ce2010-02-12 10:34:29 +0000744
Dan Gohman14d13392009-05-18 16:45:28 +0000745 return AccessTy;
Dan Gohman917ffe42009-03-09 21:01:17 +0000746}
747
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000748/// Return true if this AddRec is already a phi in its loop.
Andrew Trick5df90962011-12-06 03:13:31 +0000749static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
750 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
751 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
752 if (SE.isSCEVable(PN->getType()) &&
753 (SE.getEffectiveSCEVType(PN->getType()) ==
754 SE.getEffectiveSCEVType(AR->getType())) &&
755 SE.getSCEV(PN) == AR)
756 return true;
757 }
758 return false;
759}
760
Andrew Trickd5d2db92012-01-10 01:45:08 +0000761/// Check if expanding this expression is likely to incur significant cost. This
762/// is tricky because SCEV doesn't track which expressions are actually computed
763/// by the current IR.
764///
765/// We currently allow expansion of IV increments that involve adds,
766/// multiplication by constants, and AddRecs from existing phis.
767///
768/// TODO: Allow UDivExpr if we can find an existing IV increment that is an
769/// obvious multiple of the UDivExpr.
770static bool isHighCostExpansion(const SCEV *S,
Craig Topper71b7b682014-08-21 05:55:13 +0000771 SmallPtrSetImpl<const SCEV*> &Processed,
Andrew Trickd5d2db92012-01-10 01:45:08 +0000772 ScalarEvolution &SE) {
773 // Zero/One operand expressions
774 switch (S->getSCEVType()) {
775 case scUnknown:
776 case scConstant:
777 return false;
778 case scTruncate:
779 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
780 Processed, SE);
781 case scZeroExtend:
782 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
783 Processed, SE);
784 case scSignExtend:
785 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
786 Processed, SE);
787 }
788
David Blaikie70573dc2014-11-19 07:49:26 +0000789 if (!Processed.insert(S).second)
Andrew Trickd5d2db92012-01-10 01:45:08 +0000790 return false;
791
792 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Craig Topper042a3922015-05-25 20:01:18 +0000793 for (const SCEV *S : Add->operands()) {
794 if (isHighCostExpansion(S, Processed, SE))
Andrew Trickd5d2db92012-01-10 01:45:08 +0000795 return true;
796 }
797 return false;
798 }
799
800 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
801 if (Mul->getNumOperands() == 2) {
802 // Multiplication by a constant is ok
803 if (isa<SCEVConstant>(Mul->getOperand(0)))
804 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
805
806 // If we have the value of one operand, check if an existing
807 // multiplication already generates this expression.
808 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
809 Value *UVal = U->getValue();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000810 for (User *UR : UVal->users()) {
Andrew Trick14779cc2012-03-26 20:28:37 +0000811 // If U is a constant, it may be used by a ConstantExpr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000812 Instruction *UI = dyn_cast<Instruction>(UR);
813 if (UI && UI->getOpcode() == Instruction::Mul &&
814 SE.isSCEVable(UI->getType())) {
815 return SE.getSCEV(UI) == Mul;
Andrew Trickd5d2db92012-01-10 01:45:08 +0000816 }
817 }
818 }
819 }
820 }
821
822 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
823 if (isExistingPhi(AR, SE))
824 return false;
825 }
826
827 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
828 return true;
829}
830
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000831/// If any of the instructions is the specified set are trivially dead, delete
832/// them and see if this makes any of their operands subsequently dead.
Dan Gohman45774ce2010-02-12 10:34:29 +0000833static bool
834DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
835 bool Changed = false;
836
837 while (!DeadInsts.empty()) {
Richard Smithad9c8e82012-08-21 20:35:14 +0000838 Value *V = DeadInsts.pop_back_val();
839 Instruction *I = dyn_cast_or_null<Instruction>(V);
Dan Gohman45774ce2010-02-12 10:34:29 +0000840
Craig Topperf40110f2014-04-25 05:29:35 +0000841 if (!I || !isInstructionTriviallyDead(I))
Dan Gohman45774ce2010-02-12 10:34:29 +0000842 continue;
843
Craig Topper042a3922015-05-25 20:01:18 +0000844 for (Use &O : I->operands())
845 if (Instruction *U = dyn_cast<Instruction>(O)) {
846 O = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000847 if (U->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000848 DeadInsts.emplace_back(U);
Dan Gohman45774ce2010-02-12 10:34:29 +0000849 }
850
851 I->eraseFromParent();
852 Changed = true;
853 }
854
855 return Changed;
856}
857
Dan Gohman045f8192010-01-22 00:46:49 +0000858namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000859
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000860class LSRUse;
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000861
862} // end anonymous namespace
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000863
864/// \brief Check if the addressing mode defined by \p F is completely
865/// folded in \p LU at isel time.
866/// This includes address-mode folding and special icmp tricks.
867/// This function returns true if \p LU can accommodate what \p F
868/// defines and up to 1 base + 1 scaled + offset.
869/// In other words, if \p F has several base registers, this function may
870/// still return true. Therefore, users still need to account for
871/// additional base registers and/or unfolded offsets to derive an
872/// accurate cost model.
873static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
874 const LSRUse &LU, const Formula &F);
Quentin Colombetbf490d42013-05-31 21:29:03 +0000875// Get the cost of the scaling factor used in F for LU.
876static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
877 const LSRUse &LU, const Formula &F);
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000878
879namespace {
Jim Grosbach60f48542009-11-17 17:53:56 +0000880
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000881/// This class is used to measure and compare candidate formulae.
Dan Gohman45774ce2010-02-12 10:34:29 +0000882class Cost {
883 /// TODO: Some of these could be merged. Also, a lexical ordering
884 /// isn't always optimal.
885 unsigned NumRegs;
886 unsigned AddRecCost;
887 unsigned NumIVMuls;
888 unsigned NumBaseAdds;
889 unsigned ImmCost;
890 unsigned SetupCost;
Quentin Colombetbf490d42013-05-31 21:29:03 +0000891 unsigned ScaleCost;
Nate Begemane68bcd12005-07-30 00:15:07 +0000892
Dan Gohman45774ce2010-02-12 10:34:29 +0000893public:
894 Cost()
895 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
Quentin Colombetbf490d42013-05-31 21:29:03 +0000896 SetupCost(0), ScaleCost(0) {}
Jim Grosbach60f48542009-11-17 17:53:56 +0000897
Dan Gohman45774ce2010-02-12 10:34:29 +0000898 bool operator<(const Cost &Other) const;
Dan Gohman045f8192010-01-22 00:46:49 +0000899
Tim Northoverbc6659c2014-01-22 13:27:00 +0000900 void Lose();
Dan Gohman045f8192010-01-22 00:46:49 +0000901
Andrew Trick784729d2011-09-26 23:11:04 +0000902#ifndef NDEBUG
903 // Once any of the metrics loses, they must all remain losers.
904 bool isValid() {
905 return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
Quentin Colombetbf490d42013-05-31 21:29:03 +0000906 | ImmCost | SetupCost | ScaleCost) != ~0u)
Andrew Trick784729d2011-09-26 23:11:04 +0000907 || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
Quentin Colombetbf490d42013-05-31 21:29:03 +0000908 & ImmCost & SetupCost & ScaleCost) == ~0u);
Andrew Trick784729d2011-09-26 23:11:04 +0000909 }
910#endif
911
912 bool isLoser() {
913 assert(isValid() && "invalid cost");
914 return NumRegs == ~0u;
915 }
916
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000917 void RateFormula(const TargetTransformInfo &TTI,
918 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +0000919 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000920 const DenseSet<const SCEV *> &VisitedRegs,
921 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +0000922 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000923 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +0000924 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
Dan Gohman045f8192010-01-22 00:46:49 +0000925
Dan Gohman45774ce2010-02-12 10:34:29 +0000926 void print(raw_ostream &OS) const;
927 void dump() const;
Dan Gohman045f8192010-01-22 00:46:49 +0000928
Dan Gohman45774ce2010-02-12 10:34:29 +0000929private:
930 void RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000931 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000932 const Loop *L,
933 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman5b18f032010-02-13 02:06:02 +0000934 void RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000935 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman5b18f032010-02-13 02:06:02 +0000936 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +0000937 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +0000938 SmallPtrSetImpl<const SCEV *> *LoserRegs);
Dan Gohman45774ce2010-02-12 10:34:29 +0000939};
Jonas Paulsson7a794222016-08-17 13:24:19 +0000940
941/// An operand value in an instruction which is to be replaced with some
942/// equivalent, possibly strength-reduced, replacement.
943struct LSRFixup {
944 /// The instruction which will be updated.
945 Instruction *UserInst;
946
947 /// The operand of the instruction which will be replaced. The operand may be
948 /// used more than once; every instance will be replaced.
949 Value *OperandValToReplace;
950
951 /// If this user is to use the post-incremented value of an induction
952 /// variable, this variable is non-null and holds the loop associated with the
953 /// induction variable.
954 PostIncLoopSet PostIncLoops;
955
956 /// A constant offset to be added to the LSRUse expression. This allows
957 /// multiple fixups to share the same LSRUse with different offsets, for
958 /// example in an unrolled loop.
959 int64_t Offset;
960
961 bool isUseFullyOutsideLoop(const Loop *L) const;
962
963 LSRFixup();
964
965 void print(raw_ostream &OS) const;
966 void dump() const;
967};
968
Jonas Paulsson7a794222016-08-17 13:24:19 +0000969/// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
970/// SmallVectors of const SCEV*.
971struct UniquifierDenseMapInfo {
972 static SmallVector<const SCEV *, 4> getEmptyKey() {
973 SmallVector<const SCEV *, 4> V;
974 V.push_back(reinterpret_cast<const SCEV *>(-1));
975 return V;
976 }
977
978 static SmallVector<const SCEV *, 4> getTombstoneKey() {
979 SmallVector<const SCEV *, 4> V;
980 V.push_back(reinterpret_cast<const SCEV *>(-2));
981 return V;
982 }
983
984 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
985 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
986 }
987
988 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
989 const SmallVector<const SCEV *, 4> &RHS) {
990 return LHS == RHS;
991 }
992};
993
994/// This class holds the state that LSR keeps for each use in IVUsers, as well
995/// as uses invented by LSR itself. It includes information about what kinds of
996/// things can be folded into the user, information about the user itself, and
997/// information about how the use may be satisfied. TODO: Represent multiple
998/// users of the same expression in common?
999class LSRUse {
1000 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1001
1002public:
1003 /// An enum for a kind of use, indicating what types of scaled and immediate
1004 /// operands it might support.
1005 enum KindType {
1006 Basic, ///< A normal use, with no folding.
1007 Special, ///< A special case of basic, allowing -1 scales.
1008 Address, ///< An address use; folding according to TargetLowering
1009 ICmpZero ///< An equality icmp with both operands folded into one.
1010 // TODO: Add a generic icmp too?
1011 };
1012
1013 typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
1014
1015 KindType Kind;
1016 MemAccessTy AccessTy;
1017
1018 /// The list of operands which are to be replaced.
1019 SmallVector<LSRFixup, 8> Fixups;
1020
1021 /// Keep track of the min and max offsets of the fixups.
1022 int64_t MinOffset;
1023 int64_t MaxOffset;
1024
1025 /// This records whether all of the fixups using this LSRUse are outside of
1026 /// the loop, in which case some special-case heuristics may be used.
1027 bool AllFixupsOutsideLoop;
1028
1029 /// RigidFormula is set to true to guarantee that this use will be associated
1030 /// with a single formula--the one that initially matched. Some SCEV
1031 /// expressions cannot be expanded. This allows LSR to consider the registers
1032 /// used by those expressions without the need to expand them later after
1033 /// changing the formula.
1034 bool RigidFormula;
1035
1036 /// This records the widest use type for any fixup using this
1037 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
1038 /// fixup widths to be equivalent, because the narrower one may be relying on
1039 /// the implicit truncation to truncate away bogus bits.
1040 Type *WidestFixupType;
1041
1042 /// A list of ways to build a value that can satisfy this user. After the
1043 /// list is populated, one of these is selected heuristically and used to
1044 /// formulate a replacement for OperandValToReplace in UserInst.
1045 SmallVector<Formula, 12> Formulae;
1046
1047 /// The set of register candidates used by all formulae in this LSRUse.
1048 SmallPtrSet<const SCEV *, 4> Regs;
1049
1050 LSRUse(KindType K, MemAccessTy AT)
1051 : Kind(K), AccessTy(AT), MinOffset(INT64_MAX), MaxOffset(INT64_MIN),
1052 AllFixupsOutsideLoop(true), RigidFormula(false),
1053 WidestFixupType(nullptr) {}
1054
1055 LSRFixup &getNewFixup() {
1056 Fixups.push_back(LSRFixup());
1057 return Fixups.back();
1058 }
1059
1060 void pushFixup(LSRFixup &f) {
1061 Fixups.push_back(f);
1062 if (f.Offset > MaxOffset)
1063 MaxOffset = f.Offset;
1064 if (f.Offset < MinOffset)
1065 MinOffset = f.Offset;
1066 }
1067
1068 bool HasFormulaWithSameRegs(const Formula &F) const;
1069 bool InsertFormula(const Formula &F);
1070 void DeleteFormula(Formula &F);
1071 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1072
1073 void print(raw_ostream &OS) const;
1074 void dump() const;
1075};
Dan Gohman45774ce2010-02-12 10:34:29 +00001076
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001077} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00001078
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001079/// Tally up interesting quantities from the given register.
Dan Gohman45774ce2010-02-12 10:34:29 +00001080void Cost::RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +00001081 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +00001082 const Loop *L,
1083 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman5b18f032010-02-13 02:06:02 +00001084 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
Wei Mi37c4aaa2016-11-15 19:42:05 +00001085 // If this is an addrec for another loop, don't second-guess its addrec phi
1086 // nodes. LSR isn't currently smart enough to reason about more than one
1087 // loop at a time. LSR has already run on inner loops, will not run on outer
1088 // loops, and cannot be expected to change sibling loops.
Andrew Trickd97b83e2012-03-22 22:42:45 +00001089 if (AR->getLoop() != L) {
1090 // If the AddRec exists, consider it's register free and leave it alone.
Andrew Trick5df90962011-12-06 03:13:31 +00001091 if (isExistingPhi(AR, SE))
1092 return;
1093
Wei Mi37c4aaa2016-11-15 19:42:05 +00001094 // Otherwise, do not consider this formula at all.
1095 Lose();
Andrew Trickd97b83e2012-03-22 22:42:45 +00001096 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001097 }
Andrew Trickd97b83e2012-03-22 22:42:45 +00001098 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman45774ce2010-02-12 10:34:29 +00001099
Dan Gohman5b18f032010-02-13 02:06:02 +00001100 // Add the step value register, if it needs one.
1101 // TODO: The non-affine case isn't precisely modeled here.
Andrew Trick8868fae2011-09-26 23:35:25 +00001102 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1103 if (!Regs.count(AR->getOperand(1))) {
Dan Gohman5b18f032010-02-13 02:06:02 +00001104 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Andrew Trick8868fae2011-09-26 23:35:25 +00001105 if (isLoser())
1106 return;
1107 }
1108 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001109 }
Dan Gohman5b18f032010-02-13 02:06:02 +00001110 ++NumRegs;
1111
1112 // Rough heuristic; favor registers which don't require extra setup
1113 // instructions in the preheader.
1114 if (!isa<SCEVUnknown>(Reg) &&
1115 !isa<SCEVConstant>(Reg) &&
1116 !(isa<SCEVAddRecExpr>(Reg) &&
1117 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
1118 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
1119 ++SetupCost;
Dan Gohman34f37e02010-10-07 23:41:58 +00001120
Davide Italiano709d4182016-07-07 17:44:38 +00001121 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
1122 SE.hasComputableLoopEvolution(Reg, L);
Dan Gohman5b18f032010-02-13 02:06:02 +00001123}
1124
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001125/// Record this register in the set. If we haven't seen it before, rate
1126/// it. Optional LoserRegs provides a way to declare any formula that refers to
1127/// one of those regs an instant loser.
Dan Gohman5b18f032010-02-13 02:06:02 +00001128void Cost::RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +00001129 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman0849ed52010-02-16 19:42:34 +00001130 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +00001131 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +00001132 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +00001133 if (LoserRegs && LoserRegs->count(Reg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +00001134 Lose();
Andrew Trick5df90962011-12-06 03:13:31 +00001135 return;
1136 }
David Blaikie70573dc2014-11-19 07:49:26 +00001137 if (Regs.insert(Reg).second) {
Dan Gohman5b18f032010-02-13 02:06:02 +00001138 RateRegister(Reg, Regs, L, SE, DT);
Andrew Tricka1c01ba2013-03-19 04:14:57 +00001139 if (LoserRegs && isLoser())
Andrew Trick5df90962011-12-06 03:13:31 +00001140 LoserRegs->insert(Reg);
1141 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001142}
1143
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001144void Cost::RateFormula(const TargetTransformInfo &TTI,
1145 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +00001146 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +00001147 const DenseSet<const SCEV *> &VisitedRegs,
1148 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +00001149 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001150 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +00001151 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001152 assert(F.isCanonical() && "Cost is accurate only for canonical formula");
Dan Gohman45774ce2010-02-12 10:34:29 +00001153 // Tally up the registers.
1154 if (const SCEV *ScaledReg = F.ScaledReg) {
1155 if (VisitedRegs.count(ScaledReg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +00001156 Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00001157 return;
1158 }
Andrew Trick5df90962011-12-06 03:13:31 +00001159 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick784729d2011-09-26 23:11:04 +00001160 if (isLoser())
1161 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001162 }
Craig Topper042a3922015-05-25 20:01:18 +00001163 for (const SCEV *BaseReg : F.BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001164 if (VisitedRegs.count(BaseReg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +00001165 Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00001166 return;
1167 }
Andrew Trick5df90962011-12-06 03:13:31 +00001168 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick784729d2011-09-26 23:11:04 +00001169 if (isLoser())
1170 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001171 }
1172
Dan Gohman6136e942011-05-03 00:46:49 +00001173 // Determine how many (unfolded) adds we'll need inside the loop.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001174 size_t NumBaseParts = F.getNumRegs();
Dan Gohman6136e942011-05-03 00:46:49 +00001175 if (NumBaseParts > 1)
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001176 // Do not count the base and a possible second register if the target
1177 // allows to fold 2 registers.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001178 NumBaseAdds +=
1179 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
1180 NumBaseAdds += (F.UnfoldedOffset != 0);
Dan Gohman45774ce2010-02-12 10:34:29 +00001181
Quentin Colombetbf490d42013-05-31 21:29:03 +00001182 // Accumulate non-free scaling amounts.
1183 ScaleCost += getScalingFactorCost(TTI, LU, F);
1184
Dan Gohman45774ce2010-02-12 10:34:29 +00001185 // Tally up the non-zero immediates.
Jonas Paulsson7a794222016-08-17 13:24:19 +00001186 for (const LSRFixup &Fixup : LU.Fixups) {
1187 int64_t O = Fixup.Offset;
Craig Topper042a3922015-05-25 20:01:18 +00001188 int64_t Offset = (uint64_t)O + F.BaseOffset;
Chandler Carruth6e479322013-01-07 15:04:40 +00001189 if (F.BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00001190 ImmCost += 64; // Handle symbolic values conservatively.
1191 // TODO: This should probably be the pointer size.
1192 else if (Offset != 0)
1193 ImmCost += APInt(64, Offset, true).getMinSignedBits();
Jonas Paulsson7a794222016-08-17 13:24:19 +00001194
1195 // Check with target if this offset with this instruction is
1196 // specifically not supported.
1197 if ((isa<LoadInst>(Fixup.UserInst) || isa<StoreInst>(Fixup.UserInst)) &&
1198 !TTI.isFoldableMemAccessOffset(Fixup.UserInst, Offset))
1199 NumBaseAdds++;
Dan Gohman45774ce2010-02-12 10:34:29 +00001200 }
Andrew Trick784729d2011-09-26 23:11:04 +00001201 assert(isValid() && "invalid cost");
Dan Gohman45774ce2010-02-12 10:34:29 +00001202}
1203
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001204/// Set this cost to a losing value.
Tim Northoverbc6659c2014-01-22 13:27:00 +00001205void Cost::Lose() {
Dan Gohman45774ce2010-02-12 10:34:29 +00001206 NumRegs = ~0u;
1207 AddRecCost = ~0u;
1208 NumIVMuls = ~0u;
1209 NumBaseAdds = ~0u;
1210 ImmCost = ~0u;
1211 SetupCost = ~0u;
Quentin Colombetbf490d42013-05-31 21:29:03 +00001212 ScaleCost = ~0u;
Dan Gohman45774ce2010-02-12 10:34:29 +00001213}
1214
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001215/// Choose the lower cost.
Dan Gohman45774ce2010-02-12 10:34:29 +00001216bool Cost::operator<(const Cost &Other) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +00001217 return std::tie(NumRegs, AddRecCost, NumIVMuls, NumBaseAdds, ScaleCost,
1218 ImmCost, SetupCost) <
1219 std::tie(Other.NumRegs, Other.AddRecCost, Other.NumIVMuls,
1220 Other.NumBaseAdds, Other.ScaleCost, Other.ImmCost,
1221 Other.SetupCost);
Dan Gohman45774ce2010-02-12 10:34:29 +00001222}
1223
1224void Cost::print(raw_ostream &OS) const {
1225 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
1226 if (AddRecCost != 0)
1227 OS << ", with addrec cost " << AddRecCost;
1228 if (NumIVMuls != 0)
1229 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
1230 if (NumBaseAdds != 0)
1231 OS << ", plus " << NumBaseAdds << " base add"
1232 << (NumBaseAdds == 1 ? "" : "s");
Quentin Colombetbf490d42013-05-31 21:29:03 +00001233 if (ScaleCost != 0)
1234 OS << ", plus " << ScaleCost << " scale cost";
Dan Gohman45774ce2010-02-12 10:34:29 +00001235 if (ImmCost != 0)
1236 OS << ", plus " << ImmCost << " imm cost";
1237 if (SetupCost != 0)
1238 OS << ", plus " << SetupCost << " setup cost";
1239}
1240
Davide Italiano945d05f2015-11-23 02:47:30 +00001241LLVM_DUMP_METHOD
Dan Gohman45774ce2010-02-12 10:34:29 +00001242void Cost::dump() const {
1243 print(errs()); errs() << '\n';
1244}
1245
Dan Gohman45774ce2010-02-12 10:34:29 +00001246LSRFixup::LSRFixup()
Jonas Paulsson7a794222016-08-17 13:24:19 +00001247 : UserInst(nullptr), OperandValToReplace(nullptr),
Craig Topperf40110f2014-04-25 05:29:35 +00001248 Offset(0) {}
Dan Gohman45774ce2010-02-12 10:34:29 +00001249
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001250/// Test whether this fixup always uses its value outside of the given loop.
Dan Gohmand006ab92010-04-07 22:27:08 +00001251bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1252 // PHI nodes use their value in their incoming blocks.
1253 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1254 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1255 if (PN->getIncomingValue(i) == OperandValToReplace &&
1256 L->contains(PN->getIncomingBlock(i)))
1257 return false;
1258 return true;
1259 }
1260
1261 return !L->contains(UserInst);
1262}
1263
Dan Gohman45774ce2010-02-12 10:34:29 +00001264void LSRFixup::print(raw_ostream &OS) const {
1265 OS << "UserInst=";
1266 // Store is common and interesting enough to be worth special-casing.
1267 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1268 OS << "store ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001269 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001270 } else if (UserInst->getType()->isVoidTy())
1271 OS << UserInst->getOpcodeName();
1272 else
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001273 UserInst->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001274
1275 OS << ", OperandValToReplace=";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001276 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001277
Craig Topper042a3922015-05-25 20:01:18 +00001278 for (const Loop *PIL : PostIncLoops) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001279 OS << ", PostIncLoop=";
Craig Topper042a3922015-05-25 20:01:18 +00001280 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001281 }
1282
Dan Gohman45774ce2010-02-12 10:34:29 +00001283 if (Offset != 0)
1284 OS << ", Offset=" << Offset;
1285}
1286
Davide Italiano945d05f2015-11-23 02:47:30 +00001287LLVM_DUMP_METHOD
Dan Gohman45774ce2010-02-12 10:34:29 +00001288void LSRFixup::dump() const {
1289 print(errs()); errs() << '\n';
1290}
1291
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001292/// Test whether this use as a formula which has the same registers as the given
1293/// formula.
Dan Gohman20fab452010-05-19 23:43:12 +00001294bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001295 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman20fab452010-05-19 23:43:12 +00001296 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1297 // Unstable sort by host order ok, because this is only used for uniquifying.
1298 std::sort(Key.begin(), Key.end());
1299 return Uniquifier.count(Key);
1300}
1301
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001302/// If the given formula has not yet been inserted, add it to the list, and
1303/// return true. Return false otherwise. The formula must be in canonical form.
Dan Gohman8c16b382010-02-22 04:11:59 +00001304bool LSRUse::InsertFormula(const Formula &F) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001305 assert(F.isCanonical() && "Invalid canonical representation");
1306
Andrew Trick57243da2013-10-25 21:35:56 +00001307 if (!Formulae.empty() && RigidFormula)
1308 return false;
1309
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001310 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00001311 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1312 // Unstable sort by host order ok, because this is only used for uniquifying.
1313 std::sort(Key.begin(), Key.end());
1314
1315 if (!Uniquifier.insert(Key).second)
1316 return false;
1317
1318 // Using a register to hold the value of 0 is not profitable.
1319 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1320 "Zero allocated in a scaled register!");
1321#ifndef NDEBUG
Craig Topper042a3922015-05-25 20:01:18 +00001322 for (const SCEV *BaseReg : F.BaseRegs)
1323 assert(!BaseReg->isZero() && "Zero allocated in a base register!");
Dan Gohman45774ce2010-02-12 10:34:29 +00001324#endif
1325
1326 // Add the formula to the list.
1327 Formulae.push_back(F);
1328
1329 // Record registers now being used by this use.
Dan Gohman45774ce2010-02-12 10:34:29 +00001330 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001331 if (F.ScaledReg)
1332 Regs.insert(F.ScaledReg);
Dan Gohman45774ce2010-02-12 10:34:29 +00001333
1334 return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001335}
1336
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001337/// Remove the given formula from this use's list.
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001338void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman80a96082010-05-20 15:17:54 +00001339 if (&F != &Formulae.back())
1340 std::swap(F, Formulae.back());
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001341 Formulae.pop_back();
1342}
1343
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001344/// Recompute the Regs field, and update RegUses.
Dan Gohman4cf99b52010-05-18 23:42:37 +00001345void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1346 // Now that we've filtered out some formulae, recompute the Regs set.
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001347 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001348 Regs.clear();
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001349 for (const Formula &F : Formulae) {
Dan Gohman4cf99b52010-05-18 23:42:37 +00001350 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1351 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1352 }
1353
1354 // Update the RegTracker.
Craig Topper46276792014-08-24 23:23:06 +00001355 for (const SCEV *S : OldRegs)
1356 if (!Regs.count(S))
Sanjoy Das302bfd02015-08-16 18:22:43 +00001357 RegUses.dropRegister(S, LUIdx);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001358}
1359
Dan Gohman45774ce2010-02-12 10:34:29 +00001360void LSRUse::print(raw_ostream &OS) const {
1361 OS << "LSR Use: Kind=";
1362 switch (Kind) {
1363 case Basic: OS << "Basic"; break;
1364 case Special: OS << "Special"; break;
1365 case ICmpZero: OS << "ICmpZero"; break;
1366 case Address:
1367 OS << "Address of ";
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001368 if (AccessTy.MemTy->isPointerTy())
Dan Gohman45774ce2010-02-12 10:34:29 +00001369 OS << "pointer"; // the full pointer type could be really verbose
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001370 else {
1371 OS << *AccessTy.MemTy;
1372 }
1373
1374 OS << " in addrspace(" << AccessTy.AddrSpace << ')';
Evan Cheng133694d2007-10-25 09:11:16 +00001375 }
1376
Dan Gohman45774ce2010-02-12 10:34:29 +00001377 OS << ", Offsets={";
Craig Topper042a3922015-05-25 20:01:18 +00001378 bool NeedComma = false;
Jonas Paulsson7a794222016-08-17 13:24:19 +00001379 for (const LSRFixup &Fixup : Fixups) {
Craig Topper042a3922015-05-25 20:01:18 +00001380 if (NeedComma) OS << ',';
Jonas Paulsson7a794222016-08-17 13:24:19 +00001381 OS << Fixup.Offset;
Craig Topper042a3922015-05-25 20:01:18 +00001382 NeedComma = true;
Dan Gohman045f8192010-01-22 00:46:49 +00001383 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001384 OS << '}';
Dan Gohman045f8192010-01-22 00:46:49 +00001385
Dan Gohman45774ce2010-02-12 10:34:29 +00001386 if (AllFixupsOutsideLoop)
1387 OS << ", all-fixups-outside-loop";
Dan Gohman14152082010-07-15 20:24:58 +00001388
1389 if (WidestFixupType)
1390 OS << ", widest fixup type: " << *WidestFixupType;
Dan Gohman045f8192010-01-22 00:46:49 +00001391}
1392
Davide Italiano945d05f2015-11-23 02:47:30 +00001393LLVM_DUMP_METHOD
Dan Gohman45774ce2010-02-12 10:34:29 +00001394void LSRUse::dump() const {
1395 print(errs()); errs() << '\n';
1396}
Dan Gohman045f8192010-01-22 00:46:49 +00001397
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001398static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001399 LSRUse::KindType Kind, MemAccessTy AccessTy,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001400 GlobalValue *BaseGV, int64_t BaseOffset,
1401 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001402 switch (Kind) {
1403 case LSRUse::Address:
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001404 return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset,
1405 HasBaseReg, Scale, AccessTy.AddrSpace);
Dan Gohman45774ce2010-02-12 10:34:29 +00001406
Dan Gohman45774ce2010-02-12 10:34:29 +00001407 case LSRUse::ICmpZero:
1408 // There's not even a target hook for querying whether it would be legal to
1409 // fold a GV into an ICmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001410 if (BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00001411 return false;
1412
1413 // ICmp only has two operands; don't allow more than two non-trivial parts.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001414 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
Dan Gohman45774ce2010-02-12 10:34:29 +00001415 return false;
1416
1417 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1418 // putting the scaled register in the other operand of the icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001419 if (Scale != 0 && Scale != -1)
Dan Gohman45774ce2010-02-12 10:34:29 +00001420 return false;
1421
1422 // If we have low-level target information, ask the target if it can fold an
1423 // integer immediate on an icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001424 if (BaseOffset != 0) {
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001425 // We have one of:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001426 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1427 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001428 // Offs is the ICmp immediate.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001429 if (Scale == 0)
1430 // The cast does the right thing with INT64_MIN.
1431 BaseOffset = -(uint64_t)BaseOffset;
1432 return TTI.isLegalICmpImmediate(BaseOffset);
Dan Gohman045f8192010-01-22 00:46:49 +00001433 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001434
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001435 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
Dan Gohman45774ce2010-02-12 10:34:29 +00001436 return true;
1437
1438 case LSRUse::Basic:
1439 // Only handle single-register values.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001440 return !BaseGV && Scale == 0 && BaseOffset == 0;
Dan Gohman45774ce2010-02-12 10:34:29 +00001441
1442 case LSRUse::Special:
Andrew Trickaca8fb32012-06-15 20:07:26 +00001443 // Special case Basic to handle -1 scales.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001444 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
Dan Gohman045f8192010-01-22 00:46:49 +00001445 }
1446
David Blaikie46a9f012012-01-20 21:51:11 +00001447 llvm_unreachable("Invalid LSRUse Kind!");
Dan Gohman045f8192010-01-22 00:46:49 +00001448}
1449
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001450static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1451 int64_t MinOffset, int64_t MaxOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001452 LSRUse::KindType Kind, MemAccessTy AccessTy,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001453 GlobalValue *BaseGV, int64_t BaseOffset,
1454 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001455 // Check for overflow.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001456 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
Dan Gohman45774ce2010-02-12 10:34:29 +00001457 (MinOffset > 0))
1458 return false;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001459 MinOffset = (uint64_t)BaseOffset + MinOffset;
1460 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1461 (MaxOffset > 0))
1462 return false;
1463 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1464
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001465 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1466 HasBaseReg, Scale) &&
1467 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1468 HasBaseReg, Scale);
1469}
1470
1471static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1472 int64_t MinOffset, int64_t MaxOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001473 LSRUse::KindType Kind, MemAccessTy AccessTy,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001474 const Formula &F) {
1475 // For the purpose of isAMCompletelyFolded either having a canonical formula
1476 // or a scale not equal to zero is correct.
1477 // Problems may arise from non canonical formulae having a scale == 0.
1478 // Strictly speaking it would best to just rely on canonical formulae.
1479 // However, when we generate the scaled formulae, we first check that the
1480 // scaling factor is profitable before computing the actual ScaledReg for
1481 // compile time sake.
1482 assert((F.isCanonical() || F.Scale != 0));
1483 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1484 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1485}
1486
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001487/// Test whether we know how to expand the current formula.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001488static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001489 int64_t MaxOffset, LSRUse::KindType Kind,
1490 MemAccessTy AccessTy, GlobalValue *BaseGV,
1491 int64_t BaseOffset, bool HasBaseReg, int64_t Scale) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001492 // We know how to expand completely foldable formulae.
1493 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1494 BaseOffset, HasBaseReg, Scale) ||
1495 // Or formulae that use a base register produced by a sum of base
1496 // registers.
1497 (Scale == 1 &&
1498 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1499 BaseGV, BaseOffset, true, 0));
Dan Gohman045f8192010-01-22 00:46:49 +00001500}
1501
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001502static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001503 int64_t MaxOffset, LSRUse::KindType Kind,
1504 MemAccessTy AccessTy, const Formula &F) {
Chandler Carruth6e479322013-01-07 15:04:40 +00001505 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1506 F.BaseOffset, F.HasBaseReg, F.Scale);
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001507}
1508
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001509static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1510 const LSRUse &LU, const Formula &F) {
1511 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1512 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1513 F.Scale);
1514}
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001515
Quentin Colombetbf490d42013-05-31 21:29:03 +00001516static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1517 const LSRUse &LU, const Formula &F) {
1518 if (!F.Scale)
1519 return 0;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001520
1521 // If the use is not completely folded in that instruction, we will have to
1522 // pay an extra cost only for scale != 1.
1523 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1524 LU.AccessTy, F))
1525 return F.Scale != 1;
Quentin Colombetbf490d42013-05-31 21:29:03 +00001526
1527 switch (LU.Kind) {
1528 case LSRUse::Address: {
Quentin Colombet145eb972013-06-19 19:59:41 +00001529 // Check the scaling factor cost with both the min and max offsets.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001530 int ScaleCostMinOffset = TTI.getScalingFactorCost(
1531 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1532 F.Scale, LU.AccessTy.AddrSpace);
1533 int ScaleCostMaxOffset = TTI.getScalingFactorCost(
1534 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1535 F.Scale, LU.AccessTy.AddrSpace);
Quentin Colombet145eb972013-06-19 19:59:41 +00001536
1537 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1538 "Legal addressing mode has an illegal cost!");
1539 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
Quentin Colombetbf490d42013-05-31 21:29:03 +00001540 }
1541 case LSRUse::ICmpZero:
Quentin Colombetbf490d42013-05-31 21:29:03 +00001542 case LSRUse::Basic:
1543 case LSRUse::Special:
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001544 // The use is completely folded, i.e., everything is folded into the
1545 // instruction.
Quentin Colombetbf490d42013-05-31 21:29:03 +00001546 return 0;
1547 }
1548
1549 llvm_unreachable("Invalid LSRUse Kind!");
1550}
1551
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001552static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001553 LSRUse::KindType Kind, MemAccessTy AccessTy,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001554 GlobalValue *BaseGV, int64_t BaseOffset,
1555 bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001556 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001557 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001558
Dan Gohman45774ce2010-02-12 10:34:29 +00001559 // Conservatively, create an address with an immediate and a
1560 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001561 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman045f8192010-01-22 00:46:49 +00001562
Dan Gohman20fab452010-05-19 23:43:12 +00001563 // Canonicalize a scale of 1 to a base register if the formula doesn't
1564 // already have a base register.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001565 if (!HasBaseReg && Scale == 1) {
1566 Scale = 0;
1567 HasBaseReg = true;
Dan Gohman20fab452010-05-19 23:43:12 +00001568 }
1569
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001570 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1571 HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001572}
1573
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001574static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1575 ScalarEvolution &SE, int64_t MinOffset,
1576 int64_t MaxOffset, LSRUse::KindType Kind,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001577 MemAccessTy AccessTy, const SCEV *S,
1578 bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001579 // Fast-path: zero is always foldable.
1580 if (S->isZero()) return true;
1581
1582 // Conservatively, create an address with an immediate and a
1583 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001584 int64_t BaseOffset = ExtractImmediate(S, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00001585 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1586
1587 // If there's anything else involved, it's not foldable.
1588 if (!S->isZero()) return false;
1589
1590 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001591 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001592
1593 // Conservatively, create an address with an immediate and a
1594 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001595 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00001596
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001597 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1598 BaseOffset, HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001599}
1600
Dan Gohman297fb8b2010-06-19 21:21:39 +00001601namespace {
1602
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001603/// An individual increment in a Chain of IV increments. Relate an IV user to
1604/// an expression that computes the IV it uses from the IV used by the previous
1605/// link in the Chain.
Andrew Trick29fe5f02012-01-09 19:50:34 +00001606///
1607/// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1608/// original IVOperand. The head of the chain's IVOperand is only valid during
1609/// chain collection, before LSR replaces IV users. During chain generation,
1610/// IncExpr can be used to find the new IVOperand that computes the same
1611/// expression.
1612struct IVInc {
1613 Instruction *UserInst;
1614 Value* IVOperand;
1615 const SCEV *IncExpr;
1616
1617 IVInc(Instruction *U, Value *O, const SCEV *E):
1618 UserInst(U), IVOperand(O), IncExpr(E) {}
1619};
1620
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001621// The list of IV increments in program order. We typically add the head of a
1622// chain without finding subsequent links.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001623struct IVChain {
1624 SmallVector<IVInc,1> Incs;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001625 const SCEV *ExprBase;
1626
Craig Topperf40110f2014-04-25 05:29:35 +00001627 IVChain() : ExprBase(nullptr) {}
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001628
1629 IVChain(const IVInc &Head, const SCEV *Base)
1630 : Incs(1, Head), ExprBase(Base) {}
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001631
1632 typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
1633
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001634 // Return the first increment in the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001635 const_iterator begin() const {
1636 assert(!Incs.empty());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001637 return std::next(Incs.begin());
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001638 }
1639 const_iterator end() const {
1640 return Incs.end();
1641 }
1642
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001643 // Returns true if this chain contains any increments.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001644 bool hasIncs() const { return Incs.size() >= 2; }
1645
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001646 // Add an IVInc to the end of this chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001647 void add(const IVInc &X) { Incs.push_back(X); }
1648
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001649 // Returns the last UserInst in the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001650 Instruction *tailUserInst() const { return Incs.back().UserInst; }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001651
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001652 // Returns true if IncExpr can be profitably added to this chain.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001653 bool isProfitableIncrement(const SCEV *OperExpr,
1654 const SCEV *IncExpr,
1655 ScalarEvolution&);
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001656};
Andrew Trick29fe5f02012-01-09 19:50:34 +00001657
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001658/// Helper for CollectChains to track multiple IV increment uses. Distinguish
1659/// between FarUsers that definitely cross IV increments and NearUsers that may
1660/// be used between IV increments.
Andrew Trick29fe5f02012-01-09 19:50:34 +00001661struct ChainUsers {
1662 SmallPtrSet<Instruction*, 4> FarUsers;
1663 SmallPtrSet<Instruction*, 4> NearUsers;
1664};
1665
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001666/// This class holds state for the main loop strength reduction logic.
Dan Gohman45774ce2010-02-12 10:34:29 +00001667class LSRInstance {
1668 IVUsers &IU;
1669 ScalarEvolution &SE;
1670 DominatorTree &DT;
Dan Gohman607e02b2010-04-09 22:07:05 +00001671 LoopInfo &LI;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001672 const TargetTransformInfo &TTI;
Dan Gohman45774ce2010-02-12 10:34:29 +00001673 Loop *const L;
1674 bool Changed;
1675
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001676 /// This is the insert position that the current loop's induction variable
1677 /// increment should be placed. In simple loops, this is the latch block's
1678 /// terminator. But in more complicated cases, this is a position which will
1679 /// dominate all the in-loop post-increment users.
Dan Gohman45774ce2010-02-12 10:34:29 +00001680 Instruction *IVIncInsertPos;
1681
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001682 /// Interesting factors between use strides.
Justin Lebar54b0be02016-11-05 16:47:25 +00001683 ///
1684 /// We explicitly use a SetVector which contains a SmallSet, instead of the
1685 /// default, a SmallDenseSet, because we need to use the full range of
1686 /// int64_ts, and there's currently no good way of doing that with
1687 /// SmallDenseSet.
1688 SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors;
Dan Gohman45774ce2010-02-12 10:34:29 +00001689
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001690 /// Interesting use types, to facilitate truncation reuse.
Chris Lattner229907c2011-07-18 04:54:35 +00001691 SmallSetVector<Type *, 4> Types;
Dan Gohman45774ce2010-02-12 10:34:29 +00001692
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001693 /// The list of interesting uses.
Dan Gohman45774ce2010-02-12 10:34:29 +00001694 SmallVector<LSRUse, 16> Uses;
1695
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001696 /// Track which uses use which register candidates.
Dan Gohman45774ce2010-02-12 10:34:29 +00001697 RegUseTracker RegUses;
1698
Andrew Trick29fe5f02012-01-09 19:50:34 +00001699 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1700 // have more than a few IV increment chains in a loop. Missing a Chain falls
1701 // back to normal LSR behavior for those uses.
1702 static const unsigned MaxChains = 8;
1703
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001704 /// IV users can form a chain of IV increments.
Andrew Trick29fe5f02012-01-09 19:50:34 +00001705 SmallVector<IVChain, MaxChains> IVChainVec;
1706
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001707 /// IV users that belong to profitable IVChains.
Andrew Trick248d4102012-01-09 21:18:52 +00001708 SmallPtrSet<Use*, MaxChains> IVIncSet;
1709
Dan Gohman45774ce2010-02-12 10:34:29 +00001710 void OptimizeShadowIV();
1711 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1712 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohman4c4043c2010-05-20 20:05:31 +00001713 void OptimizeLoopTermCond();
Dan Gohman45774ce2010-02-12 10:34:29 +00001714
Andrew Trick29fe5f02012-01-09 19:50:34 +00001715 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1716 SmallVectorImpl<ChainUsers> &ChainUsersVec);
Andrew Trick248d4102012-01-09 21:18:52 +00001717 void FinalizeChain(IVChain &Chain);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001718 void CollectChains();
Andrew Trick248d4102012-01-09 21:18:52 +00001719 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1720 SmallVectorImpl<WeakVH> &DeadInsts);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001721
Dan Gohman45774ce2010-02-12 10:34:29 +00001722 void CollectInterestingTypesAndFactors();
1723 void CollectFixupsAndInitialFormulae();
1724
Dan Gohman45774ce2010-02-12 10:34:29 +00001725 // Support for sharing of LSRUses between LSRFixups.
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001726 typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
Dan Gohman45774ce2010-02-12 10:34:29 +00001727 UseMapTy UseMap;
1728
Dan Gohman110ed642010-09-01 01:45:53 +00001729 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001730 LSRUse::KindType Kind, MemAccessTy AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001731
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001732 std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
1733 MemAccessTy AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001734
Dan Gohmana7b68d62010-10-07 23:33:43 +00001735 void DeleteUse(LSRUse &LU, size_t LUIdx);
Dan Gohman80a96082010-05-20 15:17:54 +00001736
Dan Gohman110ed642010-09-01 01:45:53 +00001737 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
Dan Gohman20fab452010-05-19 23:43:12 +00001738
Dan Gohman8c16b382010-02-22 04:11:59 +00001739 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00001740 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1741 void CountRegisters(const Formula &F, size_t LUIdx);
1742 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1743
1744 void CollectLoopInvariantFixupsAndFormulae();
1745
1746 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1747 unsigned Depth = 0);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001748
1749 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1750 const Formula &Base, unsigned Depth,
1751 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001752 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001753 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1754 const Formula &Base, size_t Idx,
1755 bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001756 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001757 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1758 const Formula &Base,
1759 const SmallVectorImpl<int64_t> &Worklist,
1760 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001761 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1762 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1763 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1764 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1765 void GenerateCrossUseConstantOffsets();
1766 void GenerateAllReuseFormulae();
1767
1768 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmana4eca052010-05-18 22:51:59 +00001769
1770 size_t EstimateSearchSpaceComplexity() const;
Dan Gohmane9e08732010-08-29 16:09:42 +00001771 void NarrowSearchSpaceByDetectingSupersets();
1772 void NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00001773 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohmane9e08732010-08-29 16:09:42 +00001774 void NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohman45774ce2010-02-12 10:34:29 +00001775 void NarrowSearchSpaceUsingHeuristics();
1776
1777 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1778 Cost &SolutionCost,
1779 SmallVectorImpl<const Formula *> &Workspace,
1780 const Cost &CurCost,
1781 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1782 DenseSet<const SCEV *> &VisitedRegs) const;
1783 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1784
Dan Gohman607e02b2010-04-09 22:07:05 +00001785 BasicBlock::iterator
1786 HoistInsertPosition(BasicBlock::iterator IP,
1787 const SmallVectorImpl<Instruction *> &Inputs) const;
Andrew Trickc908b432012-01-20 07:41:13 +00001788 BasicBlock::iterator
1789 AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1790 const LSRFixup &LF,
1791 const LSRUse &LU,
1792 SCEVExpander &Rewriter) const;
Dan Gohmand2df6432010-04-09 02:00:38 +00001793
Jonas Paulsson7a794222016-08-17 13:24:19 +00001794 Value *Expand(const LSRUse &LU, const LSRFixup &LF,
Dan Gohman45774ce2010-02-12 10:34:29 +00001795 const Formula &F,
Dan Gohman8c16b382010-02-22 04:11:59 +00001796 BasicBlock::iterator IP,
Dan Gohman45774ce2010-02-12 10:34:29 +00001797 SCEVExpander &Rewriter,
Dan Gohman8c16b382010-02-22 04:11:59 +00001798 SmallVectorImpl<WeakVH> &DeadInsts) const;
Jonas Paulsson7a794222016-08-17 13:24:19 +00001799 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
Dan Gohman6deab962010-02-16 20:25:07 +00001800 const Formula &F,
Dan Gohman6deab962010-02-16 20:25:07 +00001801 SCEVExpander &Rewriter,
Justin Bogner843fb202015-12-15 19:40:57 +00001802 SmallVectorImpl<WeakVH> &DeadInsts) const;
Jonas Paulsson7a794222016-08-17 13:24:19 +00001803 void Rewrite(const LSRUse &LU, const LSRFixup &LF,
Dan Gohman45774ce2010-02-12 10:34:29 +00001804 const Formula &F,
Dan Gohman45774ce2010-02-12 10:34:29 +00001805 SCEVExpander &Rewriter,
Justin Bogner843fb202015-12-15 19:40:57 +00001806 SmallVectorImpl<WeakVH> &DeadInsts) const;
1807 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
Dan Gohman45774ce2010-02-12 10:34:29 +00001808
Andrew Trickdc18e382011-12-13 00:55:33 +00001809public:
Justin Bogner843fb202015-12-15 19:40:57 +00001810 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
1811 LoopInfo &LI, const TargetTransformInfo &TTI);
Dan Gohman45774ce2010-02-12 10:34:29 +00001812
1813 bool getChanged() const { return Changed; }
1814
1815 void print_factors_and_types(raw_ostream &OS) const;
1816 void print_fixups(raw_ostream &OS) const;
1817 void print_uses(raw_ostream &OS) const;
1818 void print(raw_ostream &OS) const;
1819 void dump() const;
1820};
1821
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001822} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00001823
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001824/// If IV is used in a int-to-float cast inside the loop then try to eliminate
1825/// the cast operation.
Dan Gohman45774ce2010-02-12 10:34:29 +00001826void LSRInstance::OptimizeShadowIV() {
1827 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1828 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1829 return;
1830
1831 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1832 UI != E; /* empty */) {
1833 IVUsers::const_iterator CandidateUI = UI;
1834 ++UI;
1835 Instruction *ShadowUse = CandidateUI->getUser();
Craig Topperf40110f2014-04-25 05:29:35 +00001836 Type *DestTy = nullptr;
Andrew Trick858e9f02011-07-21 01:05:01 +00001837 bool IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001838
1839 /* If shadow use is a int->float cast then insert a second IV
1840 to eliminate this cast.
1841
1842 for (unsigned i = 0; i < n; ++i)
1843 foo((double)i);
1844
1845 is transformed into
1846
1847 double d = 0.0;
1848 for (unsigned i = 0; i < n; ++i, ++d)
1849 foo(d);
1850 */
Andrew Trick858e9f02011-07-21 01:05:01 +00001851 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1852 IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001853 DestTy = UCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001854 }
1855 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1856 IsSigned = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001857 DestTy = SCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001858 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001859 if (!DestTy) continue;
1860
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001861 // If target does not support DestTy natively then do not apply
1862 // this transformation.
1863 if (!TTI.isTypeLegal(DestTy)) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001864
1865 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1866 if (!PH) continue;
1867 if (PH->getNumIncomingValues() != 2) continue;
1868
Chris Lattner229907c2011-07-18 04:54:35 +00001869 Type *SrcTy = PH->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00001870 int Mantissa = DestTy->getFPMantissaWidth();
1871 if (Mantissa == -1) continue;
1872 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1873 continue;
1874
1875 unsigned Entry, Latch;
1876 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1877 Entry = 0;
1878 Latch = 1;
Dan Gohman045f8192010-01-22 00:46:49 +00001879 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00001880 Entry = 1;
1881 Latch = 0;
Dan Gohman045f8192010-01-22 00:46:49 +00001882 }
Dan Gohman045f8192010-01-22 00:46:49 +00001883
Dan Gohman45774ce2010-02-12 10:34:29 +00001884 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1885 if (!Init) continue;
Andrew Trick858e9f02011-07-21 01:05:01 +00001886 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
Andrew Trickbd243d02011-07-21 01:45:54 +00001887 (double)Init->getSExtValue() :
1888 (double)Init->getZExtValue());
Dan Gohman045f8192010-01-22 00:46:49 +00001889
Dan Gohman45774ce2010-02-12 10:34:29 +00001890 BinaryOperator *Incr =
1891 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1892 if (!Incr) continue;
1893 if (Incr->getOpcode() != Instruction::Add
1894 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman045f8192010-01-22 00:46:49 +00001895 continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001896
Dan Gohman45774ce2010-02-12 10:34:29 +00001897 /* Initialize new IV, double d = 0.0 in above example. */
Craig Topperf40110f2014-04-25 05:29:35 +00001898 ConstantInt *C = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00001899 if (Incr->getOperand(0) == PH)
1900 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1901 else if (Incr->getOperand(1) == PH)
1902 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00001903 else
Dan Gohman045f8192010-01-22 00:46:49 +00001904 continue;
1905
Dan Gohman45774ce2010-02-12 10:34:29 +00001906 if (!C) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001907
Dan Gohman45774ce2010-02-12 10:34:29 +00001908 // Ignore negative constants, as the code below doesn't handle them
1909 // correctly. TODO: Remove this restriction.
1910 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001911
Dan Gohman45774ce2010-02-12 10:34:29 +00001912 /* Add new PHINode. */
Jay Foad52131342011-03-30 11:28:46 +00001913 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
Dan Gohman045f8192010-01-22 00:46:49 +00001914
Dan Gohman45774ce2010-02-12 10:34:29 +00001915 /* create new increment. '++d' in above example. */
1916 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1917 BinaryOperator *NewIncr =
1918 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1919 Instruction::FAdd : Instruction::FSub,
1920 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman045f8192010-01-22 00:46:49 +00001921
Dan Gohman45774ce2010-02-12 10:34:29 +00001922 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1923 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman045f8192010-01-22 00:46:49 +00001924
Dan Gohman45774ce2010-02-12 10:34:29 +00001925 /* Remove cast operation */
1926 ShadowUse->replaceAllUsesWith(NewPH);
1927 ShadowUse->eraseFromParent();
Dan Gohman4c4043c2010-05-20 20:05:31 +00001928 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001929 break;
Dan Gohman045f8192010-01-22 00:46:49 +00001930 }
1931}
1932
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001933/// If Cond has an operand that is an expression of an IV, set the IV user and
1934/// stride information and return true, otherwise return false.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00001935bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Craig Topper042a3922015-05-25 20:01:18 +00001936 for (IVStrideUse &U : IU)
1937 if (U.getUser() == Cond) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001938 // NOTE: we could handle setcc instructions with multiple uses here, but
1939 // InstCombine does it as well for simple uses, it's not clear that it
1940 // occurs enough in real life to handle.
Craig Topper042a3922015-05-25 20:01:18 +00001941 CondUse = &U;
Dan Gohman45774ce2010-02-12 10:34:29 +00001942 return true;
1943 }
Dan Gohman045f8192010-01-22 00:46:49 +00001944 return false;
Evan Cheng133694d2007-10-25 09:11:16 +00001945}
1946
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001947/// Rewrite the loop's terminating condition if it uses a max computation.
Dan Gohman045f8192010-01-22 00:46:49 +00001948///
1949/// This is a narrow solution to a specific, but acute, problem. For loops
1950/// like this:
1951///
1952/// i = 0;
1953/// do {
1954/// p[i] = 0.0;
1955/// } while (++i < n);
1956///
1957/// the trip count isn't just 'n', because 'n' might not be positive. And
1958/// unfortunately this can come up even for loops where the user didn't use
1959/// a C do-while loop. For example, seemingly well-behaved top-test loops
1960/// will commonly be lowered like this:
1961//
1962/// if (n > 0) {
1963/// i = 0;
1964/// do {
1965/// p[i] = 0.0;
1966/// } while (++i < n);
1967/// }
1968///
1969/// and then it's possible for subsequent optimization to obscure the if
1970/// test in such a way that indvars can't find it.
1971///
1972/// When indvars can't find the if test in loops like this, it creates a
1973/// max expression, which allows it to give the loop a canonical
1974/// induction variable:
1975///
1976/// i = 0;
1977/// max = n < 1 ? 1 : n;
1978/// do {
1979/// p[i] = 0.0;
1980/// } while (++i != max);
1981///
1982/// Canonical induction variables are necessary because the loop passes
1983/// are designed around them. The most obvious example of this is the
1984/// LoopInfo analysis, which doesn't remember trip count values. It
1985/// expects to be able to rediscover the trip count each time it is
Dan Gohman45774ce2010-02-12 10:34:29 +00001986/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman045f8192010-01-22 00:46:49 +00001987/// the loop has a canonical induction variable.
1988///
1989/// However, when it comes time to generate code, the maximum operation
1990/// can be quite costly, especially if it's inside of an outer loop.
1991///
1992/// This function solves this problem by detecting this type of loop and
1993/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1994/// the instructions for the maximum computation.
1995///
Dan Gohman45774ce2010-02-12 10:34:29 +00001996ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman045f8192010-01-22 00:46:49 +00001997 // Check that the loop matches the pattern we're looking for.
1998 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1999 Cond->getPredicate() != CmpInst::ICMP_NE)
2000 return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002001
Dan Gohman045f8192010-01-22 00:46:49 +00002002 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2003 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002004
Dan Gohman45774ce2010-02-12 10:34:29 +00002005 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman045f8192010-01-22 00:46:49 +00002006 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2007 return Cond;
Dan Gohman1d2ded72010-05-03 22:09:21 +00002008 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002009
Dan Gohman045f8192010-01-22 00:46:49 +00002010 // Add one to the backedge-taken count to get the trip count.
Dan Gohman9b7632d2010-08-16 15:39:27 +00002011 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
Dan Gohman534ba372010-04-24 03:13:44 +00002012 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00002013
Dan Gohman534ba372010-04-24 03:13:44 +00002014 // Check for a max calculation that matches the pattern. There's no check
2015 // for ICMP_ULE here because the comparison would be with zero, which
2016 // isn't interesting.
2017 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
Craig Topperf40110f2014-04-25 05:29:35 +00002018 const SCEVNAryExpr *Max = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00002019 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2020 Pred = ICmpInst::ICMP_SLE;
2021 Max = S;
2022 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2023 Pred = ICmpInst::ICMP_SLT;
2024 Max = S;
2025 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2026 Pred = ICmpInst::ICMP_ULT;
2027 Max = U;
2028 } else {
2029 // No match; bail.
Dan Gohman045f8192010-01-22 00:46:49 +00002030 return Cond;
Dan Gohman534ba372010-04-24 03:13:44 +00002031 }
Dan Gohman045f8192010-01-22 00:46:49 +00002032
2033 // To handle a max with more than two operands, this optimization would
2034 // require additional checking and setup.
2035 if (Max->getNumOperands() != 2)
2036 return Cond;
2037
2038 const SCEV *MaxLHS = Max->getOperand(0);
2039 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman534ba372010-04-24 03:13:44 +00002040
2041 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2042 // for a comparison with 1. For <= and >=, a comparison with zero.
2043 if (!MaxLHS ||
2044 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2045 return Cond;
2046
Dan Gohman045f8192010-01-22 00:46:49 +00002047 // Check the relevant induction variable for conformance to
2048 // the pattern.
Dan Gohman45774ce2010-02-12 10:34:29 +00002049 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00002050 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2051 if (!AR || !AR->isAffine() ||
2052 AR->getStart() != One ||
Dan Gohman45774ce2010-02-12 10:34:29 +00002053 AR->getStepRecurrence(SE) != One)
Dan Gohman045f8192010-01-22 00:46:49 +00002054 return Cond;
2055
2056 assert(AR->getLoop() == L &&
2057 "Loop condition operand is an addrec in a different loop!");
2058
2059 // Check the right operand of the select, and remember it, as it will
2060 // be used in the new comparison instruction.
Craig Topperf40110f2014-04-25 05:29:35 +00002061 Value *NewRHS = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00002062 if (ICmpInst::isTrueWhenEqual(Pred)) {
2063 // Look for n+1, and grab n.
2064 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002065 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2066 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2067 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002068 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002069 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2070 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2071 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002072 if (!NewRHS)
2073 return Cond;
2074 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002075 NewRHS = Sel->getOperand(1);
Dan Gohman45774ce2010-02-12 10:34:29 +00002076 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002077 NewRHS = Sel->getOperand(2);
Dan Gohman1081f1a2010-06-22 23:07:13 +00002078 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2079 NewRHS = SU->getValue();
Dan Gohman534ba372010-04-24 03:13:44 +00002080 else
Dan Gohman1081f1a2010-06-22 23:07:13 +00002081 // Max doesn't match expected pattern.
2082 return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00002083
2084 // Determine the new comparison opcode. It may be signed or unsigned,
2085 // and the original comparison may be either equality or inequality.
Dan Gohman045f8192010-01-22 00:46:49 +00002086 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2087 Pred = CmpInst::getInversePredicate(Pred);
2088
2089 // Ok, everything looks ok to change the condition into an SLT or SGE and
2090 // delete the max calculation.
2091 ICmpInst *NewCond =
2092 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2093
2094 // Delete the max calculation instructions.
2095 Cond->replaceAllUsesWith(NewCond);
2096 CondUse->setUser(NewCond);
2097 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2098 Cond->eraseFromParent();
2099 Sel->eraseFromParent();
2100 if (Cmp->use_empty())
2101 Cmp->eraseFromParent();
2102 return NewCond;
Dan Gohman68e77352008-09-15 21:22:06 +00002103}
2104
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002105/// Change loop terminating condition to use the postinc iv when possible.
Dan Gohman4c4043c2010-05-20 20:05:31 +00002106void
Dan Gohman45774ce2010-02-12 10:34:29 +00002107LSRInstance::OptimizeLoopTermCond() {
2108 SmallPtrSet<Instruction *, 4> PostIncs;
2109
James Molloy196ad082016-08-15 07:53:03 +00002110 // We need a different set of heuristics for rotated and non-rotated loops.
2111 // If a loop is rotated then the latch is also the backedge, so inserting
2112 // post-inc expressions just before the latch is ideal. To reduce live ranges
2113 // it also makes sense to rewrite terminating conditions to use post-inc
2114 // expressions.
2115 //
2116 // If the loop is not rotated then the latch is not a backedge; the latch
2117 // check is done in the loop head. Adding post-inc expressions before the
2118 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2119 // in the loop body. In this case we do *not* want to use post-inc expressions
2120 // in the latch check, and we want to insert post-inc expressions before
2121 // the backedge.
Evan Cheng85a9f432009-11-12 07:35:05 +00002122 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengba4e5da72009-11-17 18:10:11 +00002123 SmallVector<BasicBlock*, 8> ExitingBlocks;
2124 L->getExitingBlocks(ExitingBlocks);
James Molloy196ad082016-08-15 07:53:03 +00002125 if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) {
2126 return LatchBlock != BB;
2127 })) {
2128 // The backedge doesn't exit the loop; treat this as a head-tested loop.
2129 IVIncInsertPos = LatchBlock->getTerminator();
2130 return;
2131 }
Jim Grosbach60f48542009-11-17 17:53:56 +00002132
James Molloy196ad082016-08-15 07:53:03 +00002133 // Otherwise treat this as a rotated loop.
Craig Topper042a3922015-05-25 20:01:18 +00002134 for (BasicBlock *ExitingBlock : ExitingBlocks) {
Evan Cheng85a9f432009-11-12 07:35:05 +00002135
Dan Gohman45774ce2010-02-12 10:34:29 +00002136 // Get the terminating condition for the loop if possible. If we
Evan Chengba4e5da72009-11-17 18:10:11 +00002137 // can, we want to change it to use a post-incremented version of its
2138 // induction variable, to allow coalescing the live ranges for the IV into
2139 // one register value.
Evan Cheng85a9f432009-11-12 07:35:05 +00002140
Evan Chengba4e5da72009-11-17 18:10:11 +00002141 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2142 if (!TermBr)
2143 continue;
2144 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2145 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2146 continue;
Evan Cheng85a9f432009-11-12 07:35:05 +00002147
Evan Chengba4e5da72009-11-17 18:10:11 +00002148 // Search IVUsesByStride to find Cond's IVUse if there is one.
Craig Topperf40110f2014-04-25 05:29:35 +00002149 IVStrideUse *CondUse = nullptr;
Evan Chengba4e5da72009-11-17 18:10:11 +00002150 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman45774ce2010-02-12 10:34:29 +00002151 if (!FindIVUserForCond(Cond, CondUse))
Evan Chengba4e5da72009-11-17 18:10:11 +00002152 continue;
2153
Evan Chengba4e5da72009-11-17 18:10:11 +00002154 // If the trip count is computed in terms of a max (due to ScalarEvolution
2155 // being unable to find a sufficient guard, for example), change the loop
2156 // comparison to use SLT or ULT instead of NE.
Dan Gohman45774ce2010-02-12 10:34:29 +00002157 // One consequence of doing this now is that it disrupts the count-down
2158 // optimization. That's not always a bad thing though, because in such
2159 // cases it may still be worthwhile to avoid a max.
2160 Cond = OptimizeMax(Cond, CondUse);
Evan Chengba4e5da72009-11-17 18:10:11 +00002161
Dan Gohman45774ce2010-02-12 10:34:29 +00002162 // If this exiting block dominates the latch block, it may also use
2163 // the post-inc value if it won't be shared with other uses.
2164 // Check for dominance.
2165 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman045f8192010-01-22 00:46:49 +00002166 continue;
Evan Chengba4e5da72009-11-17 18:10:11 +00002167
Dan Gohman45774ce2010-02-12 10:34:29 +00002168 // Conservatively avoid trying to use the post-inc value in non-latch
2169 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman2d0f96d2010-02-14 03:21:49 +00002170 if (LatchBlock != ExitingBlock)
Dan Gohman45774ce2010-02-12 10:34:29 +00002171 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2172 // Test if the use is reachable from the exiting block. This dominator
2173 // query is a conservative approximation of reachability.
2174 if (&*UI != CondUse &&
2175 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2176 // Conservatively assume there may be reuse if the quotient of their
2177 // strides could be a legal scale.
Dan Gohmane637ff52010-04-19 21:48:58 +00002178 const SCEV *A = IU.getStride(*CondUse, L);
2179 const SCEV *B = IU.getStride(*UI, L);
Dan Gohmand006ab92010-04-07 22:27:08 +00002180 if (!A || !B) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00002181 if (SE.getTypeSizeInBits(A->getType()) !=
2182 SE.getTypeSizeInBits(B->getType())) {
2183 if (SE.getTypeSizeInBits(A->getType()) >
2184 SE.getTypeSizeInBits(B->getType()))
2185 B = SE.getSignExtendExpr(B, A->getType());
2186 else
2187 A = SE.getSignExtendExpr(A, B->getType());
2188 }
2189 if (const SCEVConstant *D =
Dan Gohman4eebb942010-02-19 19:35:48 +00002190 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman86110fa2010-05-20 22:25:20 +00002191 const ConstantInt *C = D->getValue();
Dan Gohman45774ce2010-02-12 10:34:29 +00002192 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman86110fa2010-05-20 22:25:20 +00002193 if (C->isOne() || C->isAllOnesValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002194 goto decline_post_inc;
2195 // Avoid weird situations.
Dan Gohman86110fa2010-05-20 22:25:20 +00002196 if (C->getValue().getMinSignedBits() >= 64 ||
2197 C->getValue().isMinSignedValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002198 goto decline_post_inc;
2199 // Check for possible scaled-address reuse.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002200 MemAccessTy AccessTy = getAccessType(UI->getUser());
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002201 int64_t Scale = C->getSExtValue();
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002202 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2203 /*BaseOffset=*/0,
2204 /*HasBaseReg=*/false, Scale,
2205 AccessTy.AddrSpace))
Dan Gohman45774ce2010-02-12 10:34:29 +00002206 goto decline_post_inc;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002207 Scale = -Scale;
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002208 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2209 /*BaseOffset=*/0,
2210 /*HasBaseReg=*/false, Scale,
2211 AccessTy.AddrSpace))
Dan Gohman45774ce2010-02-12 10:34:29 +00002212 goto decline_post_inc;
2213 }
2214 }
2215
David Greene2330f782009-12-23 22:58:38 +00002216 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman45774ce2010-02-12 10:34:29 +00002217 << *Cond << '\n');
Evan Chengba4e5da72009-11-17 18:10:11 +00002218
2219 // It's possible for the setcc instruction to be anywhere in the loop, and
2220 // possible for it to have multiple users. If it is not immediately before
2221 // the exiting block branch, move it.
Dan Gohman45774ce2010-02-12 10:34:29 +00002222 if (&*++BasicBlock::iterator(Cond) != TermBr) {
2223 if (Cond->hasOneUse()) {
Evan Chengba4e5da72009-11-17 18:10:11 +00002224 Cond->moveBefore(TermBr);
2225 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00002226 // Clone the terminating condition and insert into the loopend.
2227 ICmpInst *OldCond = Cond;
Evan Chengba4e5da72009-11-17 18:10:11 +00002228 Cond = cast<ICmpInst>(Cond->clone());
2229 Cond->setName(L->getHeader()->getName() + ".termcond");
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002230 ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
Evan Chengba4e5da72009-11-17 18:10:11 +00002231
2232 // Clone the IVUse, as the old use still exists!
Andrew Trickfc4ccb22011-06-21 15:43:52 +00002233 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman45774ce2010-02-12 10:34:29 +00002234 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Chengba4e5da72009-11-17 18:10:11 +00002235 }
Evan Cheng85a9f432009-11-12 07:35:05 +00002236 }
2237
Evan Chengba4e5da72009-11-17 18:10:11 +00002238 // If we get to here, we know that we can transform the setcc instruction to
2239 // use the post-incremented version of the IV, allowing us to coalesce the
2240 // live ranges for the IV correctly.
Dan Gohmand006ab92010-04-07 22:27:08 +00002241 CondUse->transformToPostInc(L);
Evan Chengba4e5da72009-11-17 18:10:11 +00002242 Changed = true;
2243
Dan Gohman45774ce2010-02-12 10:34:29 +00002244 PostIncs.insert(Cond);
2245 decline_post_inc:;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002246 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002247
2248 // Determine an insertion point for the loop induction variable increment. It
2249 // must dominate all the post-inc comparisons we just set up, and it must
2250 // dominate the loop latch edge.
2251 IVIncInsertPos = L->getLoopLatch()->getTerminator();
Craig Topper46276792014-08-24 23:23:06 +00002252 for (Instruction *Inst : PostIncs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002253 BasicBlock *BB =
2254 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
Craig Topper46276792014-08-24 23:23:06 +00002255 Inst->getParent());
2256 if (BB == Inst->getParent())
2257 IVIncInsertPos = Inst;
Dan Gohman45774ce2010-02-12 10:34:29 +00002258 else if (BB != IVIncInsertPos->getParent())
2259 IVIncInsertPos = BB->getTerminator();
2260 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00002261}
2262
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002263/// Determine if the given use can accommodate a fixup at the given offset and
2264/// other details. If so, update the use and return true.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002265bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2266 bool HasBaseReg, LSRUse::KindType Kind,
2267 MemAccessTy AccessTy) {
Dan Gohman110ed642010-09-01 01:45:53 +00002268 int64_t NewMinOffset = LU.MinOffset;
2269 int64_t NewMaxOffset = LU.MaxOffset;
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002270 MemAccessTy NewAccessTy = AccessTy;
Dan Gohman045f8192010-01-22 00:46:49 +00002271
Dan Gohman45774ce2010-02-12 10:34:29 +00002272 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2273 // something conservative, however this can pessimize in the case that one of
2274 // the uses will have all its uses outside the loop, for example.
2275 if (LU.Kind != Kind)
Dan Gohman045f8192010-01-22 00:46:49 +00002276 return false;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002277
Dan Gohman45774ce2010-02-12 10:34:29 +00002278 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman32655902010-06-19 21:30:18 +00002279 // TODO: Be less conservative when the type is similar and can use the same
2280 // addressing modes.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002281 if (Kind == LSRUse::Address) {
2282 if (AccessTy != LU.AccessTy)
2283 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext());
2284 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00002285
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002286 // Conservatively assume HasBaseReg is true for now.
2287 if (NewOffset < LU.MinOffset) {
2288 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2289 LU.MaxOffset - NewOffset, HasBaseReg))
2290 return false;
2291 NewMinOffset = NewOffset;
2292 } else if (NewOffset > LU.MaxOffset) {
2293 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2294 NewOffset - LU.MinOffset, HasBaseReg))
2295 return false;
2296 NewMaxOffset = NewOffset;
2297 }
2298
Dan Gohman45774ce2010-02-12 10:34:29 +00002299 // Update the use.
Dan Gohman110ed642010-09-01 01:45:53 +00002300 LU.MinOffset = NewMinOffset;
2301 LU.MaxOffset = NewMaxOffset;
2302 LU.AccessTy = NewAccessTy;
Dan Gohman29916e02010-01-21 22:42:49 +00002303 return true;
2304}
2305
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002306/// Return an LSRUse index and an offset value for a fixup which needs the given
2307/// expression, with the given kind and optional access type. Either reuse an
2308/// existing use or create a new one, as needed.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002309std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr,
2310 LSRUse::KindType Kind,
2311 MemAccessTy AccessTy) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002312 const SCEV *Copy = Expr;
2313 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng85a9f432009-11-12 07:35:05 +00002314
Dan Gohman45774ce2010-02-12 10:34:29 +00002315 // Basic uses can't accept any offset, for example.
Craig Topperf40110f2014-04-25 05:29:35 +00002316 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002317 Offset, /*HasBaseReg=*/ true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002318 Expr = Copy;
2319 Offset = 0;
2320 }
2321
2322 std::pair<UseMapTy::iterator, bool> P =
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00002323 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
Dan Gohman45774ce2010-02-12 10:34:29 +00002324 if (!P.second) {
2325 // A use already existed with this base.
2326 size_t LUIdx = P.first->second;
2327 LSRUse &LU = Uses[LUIdx];
Dan Gohman110ed642010-09-01 01:45:53 +00002328 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman45774ce2010-02-12 10:34:29 +00002329 // Reuse this use.
2330 return std::make_pair(LUIdx, Offset);
2331 }
2332
2333 // Create a new use.
2334 size_t LUIdx = Uses.size();
2335 P.first->second = LUIdx;
2336 Uses.push_back(LSRUse(Kind, AccessTy));
2337 LSRUse &LU = Uses[LUIdx];
2338
Dan Gohman45774ce2010-02-12 10:34:29 +00002339 LU.MinOffset = Offset;
2340 LU.MaxOffset = Offset;
2341 return std::make_pair(LUIdx, Offset);
2342}
2343
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002344/// Delete the given use from the Uses list.
Dan Gohmana7b68d62010-10-07 23:33:43 +00002345void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
Dan Gohman110ed642010-09-01 01:45:53 +00002346 if (&LU != &Uses.back())
Dan Gohman80a96082010-05-20 15:17:54 +00002347 std::swap(LU, Uses.back());
2348 Uses.pop_back();
Dan Gohmana7b68d62010-10-07 23:33:43 +00002349
2350 // Update RegUses.
Sanjoy Das302bfd02015-08-16 18:22:43 +00002351 RegUses.swapAndDropUse(LUIdx, Uses.size());
Dan Gohman80a96082010-05-20 15:17:54 +00002352}
2353
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002354/// Look for a use distinct from OrigLU which is has a formula that has the same
2355/// registers as the given formula.
Dan Gohman20fab452010-05-19 23:43:12 +00002356LSRUse *
2357LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
Dan Gohman110ed642010-09-01 01:45:53 +00002358 const LSRUse &OrigLU) {
2359 // Search all uses for the formula. This could be more clever.
Dan Gohman20fab452010-05-19 23:43:12 +00002360 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2361 LSRUse &LU = Uses[LUIdx];
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002362 // Check whether this use is close enough to OrigLU, to see whether it's
2363 // worthwhile looking through its formulae.
2364 // Ignore ICmpZero uses because they may contain formulae generated by
2365 // GenerateICmpZeroScales, in which case adding fixup offsets may
2366 // be invalid.
Dan Gohman20fab452010-05-19 23:43:12 +00002367 if (&LU != &OrigLU &&
2368 LU.Kind != LSRUse::ICmpZero &&
2369 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
Dan Gohman14152082010-07-15 20:24:58 +00002370 LU.WidestFixupType == OrigLU.WidestFixupType &&
Dan Gohman20fab452010-05-19 23:43:12 +00002371 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002372 // Scan through this use's formulae.
Craig Topper042a3922015-05-25 20:01:18 +00002373 for (const Formula &F : LU.Formulae) {
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002374 // Check to see if this formula has the same registers and symbols
2375 // as OrigF.
Dan Gohman20fab452010-05-19 23:43:12 +00002376 if (F.BaseRegs == OrigF.BaseRegs &&
2377 F.ScaledReg == OrigF.ScaledReg &&
Chandler Carruth6e479322013-01-07 15:04:40 +00002378 F.BaseGV == OrigF.BaseGV &&
2379 F.Scale == OrigF.Scale &&
Dan Gohman6136e942011-05-03 00:46:49 +00002380 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
Chandler Carruth6e479322013-01-07 15:04:40 +00002381 if (F.BaseOffset == 0)
Dan Gohman20fab452010-05-19 23:43:12 +00002382 return &LU;
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002383 // This is the formula where all the registers and symbols matched;
2384 // there aren't going to be any others. Since we declined it, we
Benjamin Kramerbde91762012-06-02 10:20:22 +00002385 // can skip the rest of the formulae and proceed to the next LSRUse.
Dan Gohman20fab452010-05-19 23:43:12 +00002386 break;
2387 }
2388 }
2389 }
2390 }
2391
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002392 // Nothing looked good.
Craig Topperf40110f2014-04-25 05:29:35 +00002393 return nullptr;
Dan Gohman20fab452010-05-19 23:43:12 +00002394}
2395
Dan Gohman45774ce2010-02-12 10:34:29 +00002396void LSRInstance::CollectInterestingTypesAndFactors() {
2397 SmallSetVector<const SCEV *, 4> Strides;
2398
Dan Gohman2446f572010-02-19 00:05:23 +00002399 // Collect interesting types and strides.
Dan Gohmand006ab92010-04-07 22:27:08 +00002400 SmallVector<const SCEV *, 4> Worklist;
Craig Topper042a3922015-05-25 20:01:18 +00002401 for (const IVStrideUse &U : IU) {
2402 const SCEV *Expr = IU.getExpr(U);
Dan Gohman45774ce2010-02-12 10:34:29 +00002403
2404 // Collect interesting types.
Dan Gohmand006ab92010-04-07 22:27:08 +00002405 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman45774ce2010-02-12 10:34:29 +00002406
Dan Gohmand006ab92010-04-07 22:27:08 +00002407 // Add strides for mentioned loops.
2408 Worklist.push_back(Expr);
2409 do {
2410 const SCEV *S = Worklist.pop_back_val();
2411 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
Andrew Trickd97b83e2012-03-22 22:42:45 +00002412 if (AR->getLoop() == L)
Andrew Tricke8b4f402011-12-10 00:25:00 +00002413 Strides.insert(AR->getStepRecurrence(SE));
Dan Gohmand006ab92010-04-07 22:27:08 +00002414 Worklist.push_back(AR->getStart());
2415 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002416 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohmand006ab92010-04-07 22:27:08 +00002417 }
2418 } while (!Worklist.empty());
Dan Gohman2446f572010-02-19 00:05:23 +00002419 }
2420
2421 // Compute interesting factors from the set of interesting strides.
2422 for (SmallSetVector<const SCEV *, 4>::const_iterator
2423 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman45774ce2010-02-12 10:34:29 +00002424 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002425 std::next(I); NewStrideIter != E; ++NewStrideIter) {
Dan Gohman2446f572010-02-19 00:05:23 +00002426 const SCEV *OldStride = *I;
Dan Gohman45774ce2010-02-12 10:34:29 +00002427 const SCEV *NewStride = *NewStrideIter;
Dan Gohman45774ce2010-02-12 10:34:29 +00002428
2429 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2430 SE.getTypeSizeInBits(NewStride->getType())) {
2431 if (SE.getTypeSizeInBits(OldStride->getType()) >
2432 SE.getTypeSizeInBits(NewStride->getType()))
2433 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2434 else
2435 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2436 }
2437 if (const SCEVConstant *Factor =
Dan Gohman4eebb942010-02-19 19:35:48 +00002438 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2439 SE, true))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002440 if (Factor->getAPInt().getMinSignedBits() <= 64)
2441 Factors.insert(Factor->getAPInt().getSExtValue());
Dan Gohman45774ce2010-02-12 10:34:29 +00002442 } else if (const SCEVConstant *Factor =
Dan Gohman8c16b382010-02-22 04:11:59 +00002443 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2444 NewStride,
Dan Gohman4eebb942010-02-19 19:35:48 +00002445 SE, true))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002446 if (Factor->getAPInt().getMinSignedBits() <= 64)
2447 Factors.insert(Factor->getAPInt().getSExtValue());
Dan Gohman45774ce2010-02-12 10:34:29 +00002448 }
2449 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002450
2451 // If all uses use the same type, don't bother looking for truncation-based
2452 // reuse.
2453 if (Types.size() == 1)
2454 Types.clear();
2455
2456 DEBUG(print_factors_and_types(dbgs()));
2457}
2458
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002459/// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2460/// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2461/// IVStrideUses, we could partially skip this.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002462static User::op_iterator
2463findIVOperand(User::op_iterator OI, User::op_iterator OE,
2464 Loop *L, ScalarEvolution &SE) {
2465 for(; OI != OE; ++OI) {
2466 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2467 if (!SE.isSCEVable(Oper->getType()))
2468 continue;
2469
2470 if (const SCEVAddRecExpr *AR =
2471 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2472 if (AR->getLoop() == L)
2473 break;
2474 }
2475 }
2476 }
2477 return OI;
2478}
2479
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002480/// IVChain logic must consistenctly peek base TruncInst operands, so wrap it in
2481/// a convenient helper.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002482static Value *getWideOperand(Value *Oper) {
2483 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2484 return Trunc->getOperand(0);
2485 return Oper;
2486}
2487
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002488/// Return true if we allow an IV chain to include both types.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002489static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2490 Type *LType = LVal->getType();
2491 Type *RType = RVal->getType();
2492 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
2493}
2494
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002495/// Return an approximation of this SCEV expression's "base", or NULL for any
2496/// constant. Returning the expression itself is conservative. Returning a
2497/// deeper subexpression is more precise and valid as long as it isn't less
2498/// complex than another subexpression. For expressions involving multiple
2499/// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2500/// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2501/// IVInc==b-a.
Andrew Trickd5d2db92012-01-10 01:45:08 +00002502///
2503/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2504/// SCEVUnknown, we simply return the rightmost SCEV operand.
2505static const SCEV *getExprBase(const SCEV *S) {
2506 switch (S->getSCEVType()) {
2507 default: // uncluding scUnknown.
2508 return S;
2509 case scConstant:
Craig Topperf40110f2014-04-25 05:29:35 +00002510 return nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002511 case scTruncate:
2512 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2513 case scZeroExtend:
2514 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2515 case scSignExtend:
2516 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2517 case scAddExpr: {
2518 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2519 // there's nothing more complex.
2520 // FIXME: not sure if we want to recognize negation.
2521 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2522 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2523 E(Add->op_begin()); I != E; ++I) {
2524 const SCEV *SubExpr = *I;
2525 if (SubExpr->getSCEVType() == scAddExpr)
2526 return getExprBase(SubExpr);
2527
2528 if (SubExpr->getSCEVType() != scMulExpr)
2529 return SubExpr;
2530 }
2531 return S; // all operands are scaled, be conservative.
2532 }
2533 case scAddRecExpr:
2534 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2535 }
2536}
2537
Andrew Trick248d4102012-01-09 21:18:52 +00002538/// Return true if the chain increment is profitable to expand into a loop
2539/// invariant value, which may require its own register. A profitable chain
2540/// increment will be an offset relative to the same base. We allow such offsets
2541/// to potentially be used as chain increment as long as it's not obviously
2542/// expensive to expand using real instructions.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002543bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2544 const SCEV *IncExpr,
2545 ScalarEvolution &SE) {
2546 // Aggressively form chains when -stress-ivchain.
Andrew Trick248d4102012-01-09 21:18:52 +00002547 if (StressIVChain)
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002548 return true;
Andrew Trick248d4102012-01-09 21:18:52 +00002549
Andrew Trickd5d2db92012-01-10 01:45:08 +00002550 // Do not replace a constant offset from IV head with a nonconstant IV
2551 // increment.
2552 if (!isa<SCEVConstant>(IncExpr)) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002553 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
Andrew Trickd5d2db92012-01-10 01:45:08 +00002554 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00002555 return false;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002556 }
2557
2558 SmallPtrSet<const SCEV*, 8> Processed;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002559 return !isHighCostExpansion(IncExpr, Processed, SE);
Andrew Trick248d4102012-01-09 21:18:52 +00002560}
2561
2562/// Return true if the number of registers needed for the chain is estimated to
2563/// be less than the number required for the individual IV users. First prohibit
2564/// any IV users that keep the IV live across increments (the Users set should
2565/// be empty). Next count the number and type of increments in the chain.
2566///
2567/// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2568/// effectively use postinc addressing modes. Only consider it profitable it the
2569/// increments can be computed in fewer registers when chained.
2570///
2571/// TODO: Consider IVInc free if it's already used in another chains.
2572static bool
Craig Topper71b7b682014-08-21 05:55:13 +00002573isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002574 ScalarEvolution &SE, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002575 if (StressIVChain)
2576 return true;
2577
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002578 if (!Chain.hasIncs())
Andrew Trickd5d2db92012-01-10 01:45:08 +00002579 return false;
2580
2581 if (!Users.empty()) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002582 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
Craig Topper46276792014-08-24 23:23:06 +00002583 for (Instruction *Inst : Users) {
2584 dbgs() << " " << *Inst << "\n";
Andrew Trickd5d2db92012-01-10 01:45:08 +00002585 });
2586 return false;
2587 }
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002588 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002589
2590 // The chain itself may require a register, so intialize cost to 1.
2591 int cost = 1;
2592
2593 // A complete chain likely eliminates the need for keeping the original IV in
2594 // a register. LSR does not currently know how to form a complete chain unless
2595 // the header phi already exists.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002596 if (isa<PHINode>(Chain.tailUserInst())
2597 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
Andrew Trickd5d2db92012-01-10 01:45:08 +00002598 --cost;
2599 }
Craig Topperf40110f2014-04-25 05:29:35 +00002600 const SCEV *LastIncExpr = nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002601 unsigned NumConstIncrements = 0;
2602 unsigned NumVarIncrements = 0;
2603 unsigned NumReusedIncrements = 0;
Craig Topper042a3922015-05-25 20:01:18 +00002604 for (const IVInc &Inc : Chain) {
2605 if (Inc.IncExpr->isZero())
Andrew Trickd5d2db92012-01-10 01:45:08 +00002606 continue;
2607
2608 // Incrementing by zero or some constant is neutral. We assume constants can
2609 // be folded into an addressing mode or an add's immediate operand.
Craig Topper042a3922015-05-25 20:01:18 +00002610 if (isa<SCEVConstant>(Inc.IncExpr)) {
Andrew Trickd5d2db92012-01-10 01:45:08 +00002611 ++NumConstIncrements;
2612 continue;
2613 }
2614
Craig Topper042a3922015-05-25 20:01:18 +00002615 if (Inc.IncExpr == LastIncExpr)
Andrew Trickd5d2db92012-01-10 01:45:08 +00002616 ++NumReusedIncrements;
2617 else
2618 ++NumVarIncrements;
2619
Craig Topper042a3922015-05-25 20:01:18 +00002620 LastIncExpr = Inc.IncExpr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002621 }
2622 // An IV chain with a single increment is handled by LSR's postinc
2623 // uses. However, a chain with multiple increments requires keeping the IV's
2624 // value live longer than it needs to be if chained.
2625 if (NumConstIncrements > 1)
2626 --cost;
2627
2628 // Materializing increment expressions in the preheader that didn't exist in
2629 // the original code may cost a register. For example, sign-extended array
2630 // indices can produce ridiculous increments like this:
2631 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2632 cost += NumVarIncrements;
2633
2634 // Reusing variable increments likely saves a register to hold the multiple of
2635 // the stride.
2636 cost -= NumReusedIncrements;
2637
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002638 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2639 << "\n");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002640
2641 return cost < 0;
Andrew Trick248d4102012-01-09 21:18:52 +00002642}
2643
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002644/// Add this IV user to an existing chain or make it the head of a new chain.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002645void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2646 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2647 // When IVs are used as types of varying widths, they are generally converted
2648 // to a wider type with some uses remaining narrow under a (free) trunc.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002649 Value *const NextIV = getWideOperand(IVOper);
2650 const SCEV *const OperExpr = SE.getSCEV(NextIV);
2651 const SCEV *const OperExprBase = getExprBase(OperExpr);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002652
2653 // Visit all existing chains. Check if its IVOper can be computed as a
2654 // profitable loop invariant increment from the last link in the Chain.
2655 unsigned ChainIdx = 0, NChains = IVChainVec.size();
Craig Topperf40110f2014-04-25 05:29:35 +00002656 const SCEV *LastIncExpr = nullptr;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002657 for (; ChainIdx < NChains; ++ChainIdx) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002658 IVChain &Chain = IVChainVec[ChainIdx];
2659
2660 // Prune the solution space aggressively by checking that both IV operands
2661 // are expressions that operate on the same unscaled SCEVUnknown. This
2662 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2663 // first avoids creating extra SCEV expressions.
2664 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2665 continue;
2666
2667 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002668 if (!isCompatibleIVType(PrevIV, NextIV))
2669 continue;
2670
Andrew Trick356a8962012-03-26 20:28:35 +00002671 // A phi node terminates a chain.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002672 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002673 continue;
2674
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002675 // The increment must be loop-invariant so it can be kept in a register.
2676 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2677 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2678 if (!SE.isLoopInvariant(IncExpr, L))
2679 continue;
2680
2681 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002682 LastIncExpr = IncExpr;
2683 break;
2684 }
2685 }
2686 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2687 // bother for phi nodes, because they must be last in the chain.
2688 if (ChainIdx == NChains) {
2689 if (isa<PHINode>(UserInst))
2690 return;
Andrew Trick248d4102012-01-09 21:18:52 +00002691 if (NChains >= MaxChains && !StressIVChain) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002692 DEBUG(dbgs() << "IV Chain Limit\n");
2693 return;
2694 }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002695 LastIncExpr = OperExpr;
Andrew Trickb9c822a2012-01-20 21:23:40 +00002696 // IVUsers may have skipped over sign/zero extensions. We don't currently
2697 // attempt to form chains involving extensions unless they can be hoisted
2698 // into this loop's AddRec.
2699 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2700 return;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002701 ++NChains;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002702 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2703 OperExprBase));
Andrew Trick29fe5f02012-01-09 19:50:34 +00002704 ChainUsersVec.resize(NChains);
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002705 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2706 << ") IV=" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002707 } else {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002708 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2709 << ") IV+" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002710 // Add this IV user to the end of the chain.
2711 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2712 }
Andrew Trickbc705902013-02-09 01:11:01 +00002713 IVChain &Chain = IVChainVec[ChainIdx];
Andrew Trick29fe5f02012-01-09 19:50:34 +00002714
2715 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2716 // This chain's NearUsers become FarUsers.
2717 if (!LastIncExpr->isZero()) {
2718 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2719 NearUsers.end());
2720 NearUsers.clear();
2721 }
2722
2723 // All other uses of IVOperand become near uses of the chain.
2724 // We currently ignore intermediate values within SCEV expressions, assuming
2725 // they will eventually be used be the current chain, or can be computed
2726 // from one of the chain increments. To be more precise we could
2727 // transitively follow its user and only add leaf IV users to the set.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002728 for (User *U : IVOper->users()) {
2729 Instruction *OtherUse = dyn_cast<Instruction>(U);
Andrew Trickbc705902013-02-09 01:11:01 +00002730 if (!OtherUse)
Andrew Tricke51feea2012-03-26 18:03:16 +00002731 continue;
Andrew Trickbc705902013-02-09 01:11:01 +00002732 // Uses in the chain will no longer be uses if the chain is formed.
2733 // Include the head of the chain in this iteration (not Chain.begin()).
2734 IVChain::const_iterator IncIter = Chain.Incs.begin();
2735 IVChain::const_iterator IncEnd = Chain.Incs.end();
2736 for( ; IncIter != IncEnd; ++IncIter) {
2737 if (IncIter->UserInst == OtherUse)
2738 break;
2739 }
2740 if (IncIter != IncEnd)
2741 continue;
2742
Andrew Trick29fe5f02012-01-09 19:50:34 +00002743 if (SE.isSCEVable(OtherUse->getType())
2744 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2745 && IU.isIVUserOrOperand(OtherUse)) {
2746 continue;
2747 }
Andrew Tricke51feea2012-03-26 18:03:16 +00002748 NearUsers.insert(OtherUse);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002749 }
2750
2751 // Since this user is part of the chain, it's no longer considered a use
2752 // of the chain.
2753 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2754}
2755
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002756/// Populate the vector of Chains.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002757///
2758/// This decreases ILP at the architecture level. Targets with ample registers,
2759/// multiple memory ports, and no register renaming probably don't want
2760/// this. However, such targets should probably disable LSR altogether.
2761///
2762/// The job of LSR is to make a reasonable choice of induction variables across
2763/// the loop. Subsequent passes can easily "unchain" computation exposing more
2764/// ILP *within the loop* if the target wants it.
2765///
2766/// Finding the best IV chain is potentially a scheduling problem. Since LSR
2767/// will not reorder memory operations, it will recognize this as a chain, but
2768/// will generate redundant IV increments. Ideally this would be corrected later
2769/// by a smart scheduler:
2770/// = A[i]
2771/// = A[i+x]
2772/// A[i] =
2773/// A[i+x] =
2774///
2775/// TODO: Walk the entire domtree within this loop, not just the path to the
2776/// loop latch. This will discover chains on side paths, but requires
2777/// maintaining multiple copies of the Chains state.
2778void LSRInstance::CollectChains() {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002779 DEBUG(dbgs() << "Collecting IV Chains.\n");
Andrew Trick29fe5f02012-01-09 19:50:34 +00002780 SmallVector<ChainUsers, 8> ChainUsersVec;
2781
2782 SmallVector<BasicBlock *,8> LatchPath;
2783 BasicBlock *LoopHeader = L->getHeader();
2784 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
2785 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2786 LatchPath.push_back(Rung->getBlock());
2787 }
2788 LatchPath.push_back(LoopHeader);
2789
2790 // Walk the instruction stream from the loop header to the loop latch.
David Majnemerd7708772016-06-24 04:05:21 +00002791 for (BasicBlock *BB : reverse(LatchPath)) {
2792 for (Instruction &I : *BB) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002793 // Skip instructions that weren't seen by IVUsers analysis.
David Majnemerd7708772016-06-24 04:05:21 +00002794 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002795 continue;
2796
2797 // Ignore users that are part of a SCEV expression. This way we only
2798 // consider leaf IV Users. This effectively rediscovers a portion of
2799 // IVUsers analysis but in program order this time.
David Majnemerd7708772016-06-24 04:05:21 +00002800 if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002801 continue;
2802
2803 // Remove this instruction from any NearUsers set it may be in.
2804 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
2805 ChainIdx < NChains; ++ChainIdx) {
David Majnemerd7708772016-06-24 04:05:21 +00002806 ChainUsersVec[ChainIdx].NearUsers.erase(&I);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002807 }
2808 // Search for operands that can be chained.
2809 SmallPtrSet<Instruction*, 4> UniqueOperands;
David Majnemerd7708772016-06-24 04:05:21 +00002810 User::op_iterator IVOpEnd = I.op_end();
2811 User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002812 while (IVOpIter != IVOpEnd) {
2813 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
David Blaikie70573dc2014-11-19 07:49:26 +00002814 if (UniqueOperands.insert(IVOpInst).second)
David Majnemerd7708772016-06-24 04:05:21 +00002815 ChainInstruction(&I, IVOpInst, ChainUsersVec);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002816 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002817 }
2818 } // Continue walking down the instructions.
2819 } // Continue walking down the domtree.
2820 // Visit phi backedges to determine if the chain can generate the IV postinc.
2821 for (BasicBlock::iterator I = L->getHeader()->begin();
2822 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2823 if (!SE.isSCEVable(PN->getType()))
2824 continue;
2825
2826 Instruction *IncV =
2827 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
2828 if (IncV)
2829 ChainInstruction(PN, IncV, ChainUsersVec);
2830 }
Andrew Trick248d4102012-01-09 21:18:52 +00002831 // Remove any unprofitable chains.
2832 unsigned ChainIdx = 0;
2833 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
2834 UsersIdx < NChains; ++UsersIdx) {
2835 if (!isProfitableChain(IVChainVec[UsersIdx],
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002836 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
Andrew Trick248d4102012-01-09 21:18:52 +00002837 continue;
2838 // Preserve the chain at UsesIdx.
2839 if (ChainIdx != UsersIdx)
2840 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
2841 FinalizeChain(IVChainVec[ChainIdx]);
2842 ++ChainIdx;
2843 }
2844 IVChainVec.resize(ChainIdx);
2845}
2846
2847void LSRInstance::FinalizeChain(IVChain &Chain) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002848 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2849 DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
Andrew Trick248d4102012-01-09 21:18:52 +00002850
Craig Topper042a3922015-05-25 20:01:18 +00002851 for (const IVInc &Inc : Chain) {
Evgeny Stupachenko8efbe6a2016-11-21 21:55:03 +00002852 DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");
David Majnemer42531262016-08-12 03:55:06 +00002853 auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);
Craig Topper042a3922015-05-25 20:01:18 +00002854 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
Andrew Trick248d4102012-01-09 21:18:52 +00002855 IVIncSet.insert(UseI);
2856 }
2857}
2858
2859/// Return true if the IVInc can be folded into an addressing mode.
2860static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002861 Value *Operand, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002862 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
2863 if (!IncConst || !isAddressUse(UserInst, Operand))
2864 return false;
2865
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002866 if (IncConst->getAPInt().getMinSignedBits() > 64)
Andrew Trick248d4102012-01-09 21:18:52 +00002867 return false;
2868
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002869 MemAccessTy AccessTy = getAccessType(UserInst);
Andrew Trick248d4102012-01-09 21:18:52 +00002870 int64_t IncOffset = IncConst->getValue()->getSExtValue();
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002871 if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
2872 IncOffset, /*HaseBaseReg=*/false))
Andrew Trick248d4102012-01-09 21:18:52 +00002873 return false;
2874
2875 return true;
2876}
2877
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002878/// Generate an add or subtract for each IVInc in a chain to materialize the IV
2879/// user's operand from the previous IV user's operand.
Andrew Trick248d4102012-01-09 21:18:52 +00002880void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
2881 SmallVectorImpl<WeakVH> &DeadInsts) {
2882 // Find the new IVOperand for the head of the chain. It may have been replaced
2883 // by LSR.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002884 const IVInc &Head = Chain.Incs[0];
Andrew Trick248d4102012-01-09 21:18:52 +00002885 User::op_iterator IVOpEnd = Head.UserInst->op_end();
Andrew Trickf3a25442013-03-19 05:10:27 +00002886 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
Andrew Trick248d4102012-01-09 21:18:52 +00002887 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
2888 IVOpEnd, L, SE);
Craig Topperf40110f2014-04-25 05:29:35 +00002889 Value *IVSrc = nullptr;
Andrew Trickf3a25442013-03-19 05:10:27 +00002890 while (IVOpIter != IVOpEnd) {
Andrew Trick248d4102012-01-09 21:18:52 +00002891 IVSrc = getWideOperand(*IVOpIter);
2892
2893 // If this operand computes the expression that the chain needs, we may use
2894 // it. (Check this after setting IVSrc which is used below.)
2895 //
2896 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
2897 // narrow for the chain, so we can no longer use it. We do allow using a
2898 // wider phi, assuming the LSR checked for free truncation. In that case we
2899 // should already have a truncate on this operand such that
2900 // getSCEV(IVSrc) == IncExpr.
2901 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
2902 || SE.getSCEV(IVSrc) == Head.IncExpr) {
2903 break;
2904 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002905 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trickf3a25442013-03-19 05:10:27 +00002906 }
Andrew Trick248d4102012-01-09 21:18:52 +00002907 if (IVOpIter == IVOpEnd) {
2908 // Gracefully give up on this chain.
2909 DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
2910 return;
2911 }
2912
2913 DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
2914 Type *IVTy = IVSrc->getType();
2915 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
Craig Topperf40110f2014-04-25 05:29:35 +00002916 const SCEV *LeftOverExpr = nullptr;
Craig Topper042a3922015-05-25 20:01:18 +00002917 for (const IVInc &Inc : Chain) {
2918 Instruction *InsertPt = Inc.UserInst;
Andrew Trick248d4102012-01-09 21:18:52 +00002919 if (isa<PHINode>(InsertPt))
2920 InsertPt = L->getLoopLatch()->getTerminator();
2921
2922 // IVOper will replace the current IV User's operand. IVSrc is the IV
2923 // value currently held in a register.
2924 Value *IVOper = IVSrc;
Craig Topper042a3922015-05-25 20:01:18 +00002925 if (!Inc.IncExpr->isZero()) {
Andrew Trick248d4102012-01-09 21:18:52 +00002926 // IncExpr was the result of subtraction of two narrow values, so must
2927 // be signed.
Craig Topper042a3922015-05-25 20:01:18 +00002928 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
Andrew Trick248d4102012-01-09 21:18:52 +00002929 LeftOverExpr = LeftOverExpr ?
2930 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
2931 }
2932 if (LeftOverExpr && !LeftOverExpr->isZero()) {
2933 // Expand the IV increment.
2934 Rewriter.clearPostInc();
2935 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
2936 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
2937 SE.getUnknown(IncV));
2938 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
2939
2940 // If an IV increment can't be folded, use it as the next IV value.
Craig Topper042a3922015-05-25 20:01:18 +00002941 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
Andrew Trick248d4102012-01-09 21:18:52 +00002942 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
2943 IVSrc = IVOper;
Craig Topperf40110f2014-04-25 05:29:35 +00002944 LeftOverExpr = nullptr;
Andrew Trick248d4102012-01-09 21:18:52 +00002945 }
2946 }
Craig Topper042a3922015-05-25 20:01:18 +00002947 Type *OperTy = Inc.IVOperand->getType();
Andrew Trick248d4102012-01-09 21:18:52 +00002948 if (IVTy != OperTy) {
2949 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
2950 "cannot extend a chained IV");
2951 IRBuilder<> Builder(InsertPt);
2952 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
2953 }
Craig Topper042a3922015-05-25 20:01:18 +00002954 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002955 DeadInsts.emplace_back(Inc.IVOperand);
Andrew Trick248d4102012-01-09 21:18:52 +00002956 }
2957 // If LSR created a new, wider phi, we may also replace its postinc. We only
2958 // do this if we also found a wide value for the head of the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002959 if (isa<PHINode>(Chain.tailUserInst())) {
Andrew Trick248d4102012-01-09 21:18:52 +00002960 for (BasicBlock::iterator I = L->getHeader()->begin();
2961 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
2962 if (!isCompatibleIVType(Phi, IVSrc))
2963 continue;
2964 Instruction *PostIncV = dyn_cast<Instruction>(
2965 Phi->getIncomingValueForBlock(L->getLoopLatch()));
2966 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
2967 continue;
2968 Value *IVOper = IVSrc;
2969 Type *PostIncTy = PostIncV->getType();
2970 if (IVTy != PostIncTy) {
2971 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
2972 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
2973 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
2974 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
2975 }
2976 Phi->replaceUsesOfWith(PostIncV, IVOper);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002977 DeadInsts.emplace_back(PostIncV);
Andrew Trick248d4102012-01-09 21:18:52 +00002978 }
2979 }
Andrew Trick29fe5f02012-01-09 19:50:34 +00002980}
2981
Dan Gohman45774ce2010-02-12 10:34:29 +00002982void LSRInstance::CollectFixupsAndInitialFormulae() {
Craig Topper042a3922015-05-25 20:01:18 +00002983 for (const IVStrideUse &U : IU) {
2984 Instruction *UserInst = U.getUser();
Andrew Trick248d4102012-01-09 21:18:52 +00002985 // Skip IV users that are part of profitable IV Chains.
David Majnemer42531262016-08-12 03:55:06 +00002986 User::op_iterator UseI =
2987 find(UserInst->operands(), U.getOperandValToReplace());
Andrew Trick248d4102012-01-09 21:18:52 +00002988 assert(UseI != UserInst->op_end() && "cannot find IV operand");
2989 if (IVIncSet.count(UseI))
2990 continue;
2991
Dan Gohman45774ce2010-02-12 10:34:29 +00002992 LSRUse::KindType Kind = LSRUse::Basic;
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002993 MemAccessTy AccessTy;
Jonas Paulsson7a794222016-08-17 13:24:19 +00002994 if (isAddressUse(UserInst, U.getOperandValToReplace())) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002995 Kind = LSRUse::Address;
Jonas Paulsson7a794222016-08-17 13:24:19 +00002996 AccessTy = getAccessType(UserInst);
Dan Gohman45774ce2010-02-12 10:34:29 +00002997 }
2998
Craig Topper042a3922015-05-25 20:01:18 +00002999 const SCEV *S = IU.getExpr(U);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003000 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
3001
Dan Gohman45774ce2010-02-12 10:34:29 +00003002 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3003 // (N - i == 0), and this allows (N - i) to be the expression that we work
3004 // with rather than just N or i, so we can consider the register
3005 // requirements for both N and i at the same time. Limiting this code to
3006 // equality icmps is not a problem because all interesting loops use
3007 // equality icmps, thanks to IndVarSimplify.
Jonas Paulsson7a794222016-08-17 13:24:19 +00003008 if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst))
Dan Gohman45774ce2010-02-12 10:34:29 +00003009 if (CI->isEquality()) {
3010 // Swap the operands if needed to put the OperandValToReplace on the
3011 // left, for consistency.
3012 Value *NV = CI->getOperand(1);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003013 if (NV == U.getOperandValToReplace()) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003014 CI->setOperand(1, CI->getOperand(0));
3015 CI->setOperand(0, NV);
Dan Gohmanee2fea32010-05-20 19:26:52 +00003016 NV = CI->getOperand(1);
Dan Gohmanfdf98742010-05-20 19:16:03 +00003017 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00003018 }
3019
3020 // x == y --> x - y == 0
3021 const SCEV *N = SE.getSCEV(NV);
Andrew Trick57243da2013-10-25 21:35:56 +00003022 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
Dan Gohman3268e4d2011-05-18 21:02:18 +00003023 // S is normalized, so normalize N before folding it into S
3024 // to keep the result normalized.
Craig Topperf40110f2014-04-25 05:29:35 +00003025 N = TransformForPostIncUse(Normalize, N, CI, nullptr,
Jonas Paulsson7a794222016-08-17 13:24:19 +00003026 TmpPostIncLoops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00003027 Kind = LSRUse::ICmpZero;
3028 S = SE.getMinusSCEV(N, S);
3029 }
3030
3031 // -1 and the negations of all interesting strides (except the negation
3032 // of -1) are now also interesting.
3033 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3034 if (Factors[i] != -1)
3035 Factors.insert(-(uint64_t)Factors[i]);
3036 Factors.insert(-1);
3037 }
3038
Jonas Paulsson7a794222016-08-17 13:24:19 +00003039 // Get or create an LSRUse.
Dan Gohman45774ce2010-02-12 10:34:29 +00003040 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003041 size_t LUIdx = P.first;
3042 int64_t Offset = P.second;
3043 LSRUse &LU = Uses[LUIdx];
3044
3045 // Record the fixup.
3046 LSRFixup &LF = LU.getNewFixup();
3047 LF.UserInst = UserInst;
3048 LF.OperandValToReplace = U.getOperandValToReplace();
3049 LF.PostIncLoops = TmpPostIncLoops;
3050 LF.Offset = Offset;
Dan Gohmand006ab92010-04-07 22:27:08 +00003051 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003052
Dan Gohman14152082010-07-15 20:24:58 +00003053 if (!LU.WidestFixupType ||
3054 SE.getTypeSizeInBits(LU.WidestFixupType) <
3055 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3056 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003057
3058 // If this is the first use of this LSRUse, give it a formula.
3059 if (LU.Formulae.empty()) {
Jonas Paulsson7a794222016-08-17 13:24:19 +00003060 InsertInitialFormula(S, LU, LUIdx);
3061 CountRegisters(LU.Formulae.back(), LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003062 }
3063 }
3064
3065 DEBUG(print_fixups(dbgs()));
3066}
3067
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003068/// Insert a formula for the given expression into the given use, separating out
3069/// loop-variant portions from loop-invariant and loop-computable portions.
Dan Gohman45774ce2010-02-12 10:34:29 +00003070void
Dan Gohman8c16b382010-02-22 04:11:59 +00003071LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Andrew Trick57243da2013-10-25 21:35:56 +00003072 // Mark uses whose expressions cannot be expanded.
3073 if (!isSafeToExpand(S, SE))
3074 LU.RigidFormula = true;
3075
Dan Gohman45774ce2010-02-12 10:34:29 +00003076 Formula F;
Sanjoy Das302bfd02015-08-16 18:22:43 +00003077 F.initialMatch(S, L, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00003078 bool Inserted = InsertFormula(LU, LUIdx, F);
3079 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3080}
3081
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003082/// Insert a simple single-register formula for the given expression into the
3083/// given use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003084void
3085LSRInstance::InsertSupplementalFormula(const SCEV *S,
3086 LSRUse &LU, size_t LUIdx) {
3087 Formula F;
3088 F.BaseRegs.push_back(S);
Chandler Carruth7e31c8f2013-01-12 23:46:04 +00003089 F.HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00003090 bool Inserted = InsertFormula(LU, LUIdx, F);
3091 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3092}
3093
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003094/// Note which registers are used by the given formula, updating RegUses.
Dan Gohman45774ce2010-02-12 10:34:29 +00003095void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3096 if (F.ScaledReg)
Sanjoy Das302bfd02015-08-16 18:22:43 +00003097 RegUses.countRegister(F.ScaledReg, LUIdx);
Craig Topper042a3922015-05-25 20:01:18 +00003098 for (const SCEV *BaseReg : F.BaseRegs)
Sanjoy Das302bfd02015-08-16 18:22:43 +00003099 RegUses.countRegister(BaseReg, LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003100}
3101
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003102/// If the given formula has not yet been inserted, add it to the list, and
3103/// return true. Return false otherwise.
Dan Gohman45774ce2010-02-12 10:34:29 +00003104bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003105 // Do not insert formula that we will not be able to expand.
3106 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3107 "Formula is illegal");
Dan Gohman8c16b382010-02-22 04:11:59 +00003108 if (!LU.InsertFormula(F))
Dan Gohman45774ce2010-02-12 10:34:29 +00003109 return false;
3110
3111 CountRegisters(F, LUIdx);
3112 return true;
3113}
3114
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003115/// Check for other uses of loop-invariant values which we're tracking. These
3116/// other uses will pin these values in registers, making them less profitable
3117/// for elimination.
Dan Gohman45774ce2010-02-12 10:34:29 +00003118/// TODO: This currently misses non-constant addrec step registers.
3119/// TODO: Should this give more weight to users inside the loop?
3120void
3121LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3122 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
Andrew Trickdd925ad2014-10-25 19:59:30 +00003123 SmallPtrSet<const SCEV *, 32> Visited;
Dan Gohman45774ce2010-02-12 10:34:29 +00003124
3125 while (!Worklist.empty()) {
3126 const SCEV *S = Worklist.pop_back_val();
3127
Andrew Trick9ccbed52014-10-25 19:42:07 +00003128 // Don't process the same SCEV twice
David Blaikie70573dc2014-11-19 07:49:26 +00003129 if (!Visited.insert(S).second)
Andrew Trick9ccbed52014-10-25 19:42:07 +00003130 continue;
3131
Dan Gohman45774ce2010-02-12 10:34:29 +00003132 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohmandd41bba2010-06-21 19:47:52 +00003133 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman45774ce2010-02-12 10:34:29 +00003134 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3135 Worklist.push_back(C->getOperand());
3136 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3137 Worklist.push_back(D->getLHS());
3138 Worklist.push_back(D->getRHS());
Chandler Carruthcdf47882014-03-09 03:16:01 +00003139 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003140 const Value *V = US->getValue();
Dan Gohman67b44032010-06-04 23:16:05 +00003141 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3142 // Look for instructions defined outside the loop.
Dan Gohman45774ce2010-02-12 10:34:29 +00003143 if (L->contains(Inst)) continue;
Dan Gohman67b44032010-06-04 23:16:05 +00003144 } else if (isa<UndefValue>(V))
3145 // Undef doesn't have a live range, so it doesn't matter.
3146 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003147 for (const Use &U : V->uses()) {
3148 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
Dan Gohman45774ce2010-02-12 10:34:29 +00003149 // Ignore non-instructions.
3150 if (!UserInst)
Dan Gohman045f8192010-01-22 00:46:49 +00003151 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003152 // Ignore instructions in other functions (as can happen with
3153 // Constants).
3154 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman045f8192010-01-22 00:46:49 +00003155 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003156 // Ignore instructions not dominated by the loop.
3157 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3158 UserInst->getParent() :
3159 cast<PHINode>(UserInst)->getIncomingBlock(
Chandler Carruthcdf47882014-03-09 03:16:01 +00003160 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003161 if (!DT.dominates(L->getHeader(), UseBB))
3162 continue;
David Majnemerb2221842015-11-08 05:04:07 +00003163 // Don't bother if the instruction is in a BB which ends in an EHPad.
3164 if (UseBB->getTerminator()->isEHPad())
3165 continue;
David Majnemerbba17392017-01-13 22:24:27 +00003166 // Don't bother rewriting PHIs in catchswitch blocks.
3167 if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))
3168 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003169 // Ignore uses which are part of other SCEV expressions, to avoid
3170 // analyzing them multiple times.
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003171 if (SE.isSCEVable(UserInst->getType())) {
3172 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3173 // If the user is a no-op, look through to its uses.
3174 if (!isa<SCEVUnknown>(UserS))
3175 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003176 if (UserS == US) {
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003177 Worklist.push_back(
3178 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3179 continue;
3180 }
3181 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003182 // Ignore icmp instructions which are already being analyzed.
3183 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003184 unsigned OtherIdx = !U.getOperandNo();
Dan Gohman45774ce2010-02-12 10:34:29 +00003185 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
Dan Gohmanafd6db92010-11-17 21:23:15 +00003186 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003187 continue;
3188 }
3189
Matt Arsenault427a0fd2015-08-15 00:53:06 +00003190 std::pair<size_t, int64_t> P = getUse(
3191 S, LSRUse::Basic, MemAccessTy());
Jonas Paulsson7a794222016-08-17 13:24:19 +00003192 size_t LUIdx = P.first;
3193 int64_t Offset = P.second;
3194 LSRUse &LU = Uses[LUIdx];
3195 LSRFixup &LF = LU.getNewFixup();
3196 LF.UserInst = const_cast<Instruction *>(UserInst);
3197 LF.OperandValToReplace = U;
3198 LF.Offset = Offset;
Dan Gohmand006ab92010-04-07 22:27:08 +00003199 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman14152082010-07-15 20:24:58 +00003200 if (!LU.WidestFixupType ||
3201 SE.getTypeSizeInBits(LU.WidestFixupType) <
3202 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3203 LU.WidestFixupType = LF.OperandValToReplace->getType();
Jonas Paulsson7a794222016-08-17 13:24:19 +00003204 InsertSupplementalFormula(US, LU, LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003205 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3206 break;
3207 }
3208 }
3209 }
3210}
3211
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003212/// Split S into subexpressions which can be pulled out into separate
3213/// registers. If C is non-null, multiply each subexpression by C.
Andrew Trickc8037062012-07-17 05:30:37 +00003214///
3215/// Return remainder expression after factoring the subexpressions captured by
3216/// Ops. If Ops is complete, return NULL.
3217static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3218 SmallVectorImpl<const SCEV *> &Ops,
3219 const Loop *L,
3220 ScalarEvolution &SE,
3221 unsigned Depth = 0) {
3222 // Arbitrarily cap recursion to protect compile time.
3223 if (Depth >= 3)
3224 return S;
3225
Dan Gohman45774ce2010-02-12 10:34:29 +00003226 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3227 // Break out add operands.
Craig Topper042a3922015-05-25 20:01:18 +00003228 for (const SCEV *S : Add->operands()) {
3229 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
Andrew Trickc8037062012-07-17 05:30:37 +00003230 if (Remainder)
3231 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3232 }
Craig Topperf40110f2014-04-25 05:29:35 +00003233 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00003234 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3235 // Split a non-zero base out of an addrec.
Alexandros Lamprineas0ee3ec22016-11-09 08:53:07 +00003236 if (AR->getStart()->isZero() || !AR->isAffine())
Andrew Trickc8037062012-07-17 05:30:37 +00003237 return S;
3238
3239 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3240 C, Ops, L, SE, Depth+1);
3241 // Split the non-zero AddRec unless it is part of a nested recurrence that
3242 // does not pertain to this loop.
3243 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3244 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
Craig Topperf40110f2014-04-25 05:29:35 +00003245 Remainder = nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003246 }
3247 if (Remainder != AR->getStart()) {
3248 if (!Remainder)
3249 Remainder = SE.getConstant(AR->getType(), 0);
3250 return SE.getAddRecExpr(Remainder,
3251 AR->getStepRecurrence(SE),
3252 AR->getLoop(),
3253 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3254 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +00003255 }
3256 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3257 // Break (C * (a + b + c)) into C*a + C*b + C*c.
Andrew Trickc8037062012-07-17 05:30:37 +00003258 if (Mul->getNumOperands() != 2)
3259 return S;
3260 if (const SCEVConstant *Op0 =
3261 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3262 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3263 const SCEV *Remainder =
3264 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3265 if (Remainder)
3266 Ops.push_back(SE.getMulExpr(C, Remainder));
Craig Topperf40110f2014-04-25 05:29:35 +00003267 return nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003268 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003269 }
Andrew Trickc8037062012-07-17 05:30:37 +00003270 return S;
Dan Gohman45774ce2010-02-12 10:34:29 +00003271}
3272
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003273/// \brief Helper function for LSRInstance::GenerateReassociations.
3274void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3275 const Formula &Base,
3276 unsigned Depth, size_t Idx,
3277 bool IsScaledReg) {
3278 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3279 SmallVector<const SCEV *, 8> AddOps;
3280 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3281 if (Remainder)
3282 AddOps.push_back(Remainder);
3283
3284 if (AddOps.size() == 1)
3285 return;
3286
3287 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3288 JE = AddOps.end();
3289 J != JE; ++J) {
3290
3291 // Loop-variant "unknown" values are uninteresting; we won't be able to
3292 // do anything meaningful with them.
3293 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3294 continue;
3295
3296 // Don't pull a constant into a register if the constant could be folded
3297 // into an immediate field.
3298 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3299 LU.AccessTy, *J, Base.getNumRegs() > 1))
3300 continue;
3301
3302 // Collect all operands except *J.
3303 SmallVector<const SCEV *, 8> InnerAddOps(
3304 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3305 InnerAddOps.append(std::next(J),
3306 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3307
3308 // Don't leave just a constant behind in a register if the constant could
3309 // be folded into an immediate field.
3310 if (InnerAddOps.size() == 1 &&
3311 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3312 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3313 continue;
3314
3315 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3316 if (InnerSum->isZero())
3317 continue;
3318 Formula F = Base;
3319
3320 // Add the remaining pieces of the add back into the new formula.
3321 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3322 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3323 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3324 InnerSumSC->getValue()->getZExtValue())) {
3325 F.UnfoldedOffset =
3326 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3327 if (IsScaledReg)
3328 F.ScaledReg = nullptr;
3329 else
3330 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3331 } else if (IsScaledReg)
3332 F.ScaledReg = InnerSum;
3333 else
3334 F.BaseRegs[Idx] = InnerSum;
3335
3336 // Add J as its own register, or an unfolded immediate.
3337 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3338 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3339 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3340 SC->getValue()->getZExtValue()))
3341 F.UnfoldedOffset =
3342 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3343 else
3344 F.BaseRegs.push_back(*J);
3345 // We may have changed the number of register in base regs, adjust the
3346 // formula accordingly.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003347 F.canonicalize();
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003348
3349 if (InsertFormula(LU, LUIdx, F))
3350 // If that formula hadn't been seen before, recurse to find more like
3351 // it.
3352 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3353 }
3354}
3355
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003356/// Split out subexpressions from adds and the bases of addrecs.
Dan Gohman45774ce2010-02-12 10:34:29 +00003357void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003358 Formula Base, unsigned Depth) {
3359 assert(Base.isCanonical() && "Input must be in the canonical form");
Dan Gohman45774ce2010-02-12 10:34:29 +00003360 // Arbitrarily cap recursion to protect compile time.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003361 if (Depth >= 3)
3362 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003363
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003364 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3365 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
Dan Gohman45774ce2010-02-12 10:34:29 +00003366
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003367 if (Base.Scale == 1)
3368 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3369 /* Idx */ -1, /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003370}
3371
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003372/// Generate a formula consisting of all of the loop-dominating registers added
3373/// into a single register.
Dan Gohman45774ce2010-02-12 10:34:29 +00003374void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohmane4e51a62010-02-14 18:51:39 +00003375 Formula Base) {
Dan Gohman8b0a4192010-03-01 17:49:51 +00003376 // This method is only interesting on a plurality of registers.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003377 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3378 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003379
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003380 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3381 // processing the formula.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003382 Base.unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003383 Formula F = Base;
3384 F.BaseRegs.clear();
3385 SmallVector<const SCEV *, 4> Ops;
Craig Topper042a3922015-05-25 20:01:18 +00003386 for (const SCEV *BaseReg : Base.BaseRegs) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00003387 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
Dan Gohmanafd6db92010-11-17 21:23:15 +00003388 !SE.hasComputableLoopEvolution(BaseReg, L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003389 Ops.push_back(BaseReg);
3390 else
3391 F.BaseRegs.push_back(BaseReg);
3392 }
3393 if (Ops.size() > 1) {
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003394 const SCEV *Sum = SE.getAddExpr(Ops);
3395 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3396 // opportunity to fold something. For now, just ignore such cases
Dan Gohman8b0a4192010-03-01 17:49:51 +00003397 // rather than proceed with zero in a register.
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003398 if (!Sum->isZero()) {
3399 F.BaseRegs.push_back(Sum);
Sanjoy Das302bfd02015-08-16 18:22:43 +00003400 F.canonicalize();
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003401 (void)InsertFormula(LU, LUIdx, F);
3402 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003403 }
3404}
3405
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003406/// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
3407void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3408 const Formula &Base, size_t Idx,
3409 bool IsScaledReg) {
3410 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3411 GlobalValue *GV = ExtractSymbol(G, SE);
3412 if (G->isZero() || !GV)
3413 return;
3414 Formula F = Base;
3415 F.BaseGV = GV;
3416 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3417 return;
3418 if (IsScaledReg)
3419 F.ScaledReg = G;
3420 else
3421 F.BaseRegs[Idx] = G;
3422 (void)InsertFormula(LU, LUIdx, F);
3423}
3424
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003425/// Generate reuse formulae using symbolic offsets.
Dan Gohman45774ce2010-02-12 10:34:29 +00003426void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3427 Formula Base) {
3428 // We can't add a symbolic offset if the address already contains one.
Chandler Carruth6e479322013-01-07 15:04:40 +00003429 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003430
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003431 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3432 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3433 if (Base.Scale == 1)
3434 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3435 /* IsScaledReg */ true);
3436}
3437
3438/// \brief Helper function for LSRInstance::GenerateConstantOffsets.
3439void LSRInstance::GenerateConstantOffsetsImpl(
3440 LSRUse &LU, unsigned LUIdx, const Formula &Base,
3441 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3442 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
Craig Topper042a3922015-05-25 20:01:18 +00003443 for (int64_t Offset : Worklist) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003444 Formula F = Base;
Craig Topper042a3922015-05-25 20:01:18 +00003445 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3446 if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003447 LU.AccessTy, F)) {
3448 // Add the offset to the base register.
Craig Topper042a3922015-05-25 20:01:18 +00003449 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003450 // If it cancelled out, drop the base register, otherwise update it.
3451 if (NewG->isZero()) {
3452 if (IsScaledReg) {
3453 F.Scale = 0;
3454 F.ScaledReg = nullptr;
3455 } else
Sanjoy Das302bfd02015-08-16 18:22:43 +00003456 F.deleteBaseReg(F.BaseRegs[Idx]);
3457 F.canonicalize();
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003458 } else if (IsScaledReg)
3459 F.ScaledReg = NewG;
3460 else
3461 F.BaseRegs[Idx] = NewG;
3462
3463 (void)InsertFormula(LU, LUIdx, F);
3464 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003465 }
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003466
3467 int64_t Imm = ExtractImmediate(G, SE);
3468 if (G->isZero() || Imm == 0)
3469 return;
3470 Formula F = Base;
3471 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3472 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3473 return;
3474 if (IsScaledReg)
3475 F.ScaledReg = G;
3476 else
3477 F.BaseRegs[Idx] = G;
3478 (void)InsertFormula(LU, LUIdx, F);
Dan Gohman45774ce2010-02-12 10:34:29 +00003479}
3480
3481/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3482void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3483 Formula Base) {
3484 // TODO: For now, just add the min and max offset, because it usually isn't
3485 // worthwhile looking at everything inbetween.
Dan Gohman4afd4122010-07-15 15:14:45 +00003486 SmallVector<int64_t, 2> Worklist;
Dan Gohman45774ce2010-02-12 10:34:29 +00003487 Worklist.push_back(LU.MinOffset);
3488 if (LU.MaxOffset != LU.MinOffset)
3489 Worklist.push_back(LU.MaxOffset);
3490
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003491 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3492 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3493 if (Base.Scale == 1)
3494 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3495 /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003496}
3497
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003498/// For ICmpZero, check to see if we can scale up the comparison. For example, x
3499/// == y -> x*c == y*c.
Dan Gohman45774ce2010-02-12 10:34:29 +00003500void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3501 Formula Base) {
3502 if (LU.Kind != LSRUse::ICmpZero) return;
3503
3504 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003505 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003506 if (!IntTy) return;
3507 if (SE.getTypeSizeInBits(IntTy) > 64) return;
3508
3509 // Don't do this if there is more than one offset.
3510 if (LU.MinOffset != LU.MaxOffset) return;
3511
Chandler Carruth6e479322013-01-07 15:04:40 +00003512 assert(!Base.BaseGV && "ICmpZero use is not legal!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003513
3514 // Check each interesting stride.
Craig Topper042a3922015-05-25 20:01:18 +00003515 for (int64_t Factor : Factors) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003516 // Check that the multiplication doesn't overflow.
Chandler Carruth6e479322013-01-07 15:04:40 +00003517 if (Base.BaseOffset == INT64_MIN && Factor == -1)
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003518 continue;
Chandler Carruth6e479322013-01-07 15:04:40 +00003519 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3520 if (NewBaseOffset / Factor != Base.BaseOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003521 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003522 // If the offset will be truncated at this use, check that it is in bounds.
3523 if (!IntTy->isPointerTy() &&
3524 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3525 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003526
3527 // Check that multiplying with the use offset doesn't overflow.
3528 int64_t Offset = LU.MinOffset;
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003529 if (Offset == INT64_MIN && Factor == -1)
3530 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003531 Offset = (uint64_t)Offset * Factor;
Dan Gohman13ac3b22010-02-17 00:42:19 +00003532 if (Offset / Factor != LU.MinOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003533 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003534 // If the offset will be truncated at this use, check that it is in bounds.
3535 if (!IntTy->isPointerTy() &&
3536 !ConstantInt::isValueValidForType(IntTy, Offset))
3537 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003538
Dan Gohman963b1c12010-06-24 16:57:52 +00003539 Formula F = Base;
Chandler Carruth6e479322013-01-07 15:04:40 +00003540 F.BaseOffset = NewBaseOffset;
Dan Gohman963b1c12010-06-24 16:57:52 +00003541
Dan Gohman45774ce2010-02-12 10:34:29 +00003542 // Check that this scale is legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003543 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
Dan Gohman45774ce2010-02-12 10:34:29 +00003544 continue;
3545
3546 // Compensate for the use having MinOffset built into it.
Chandler Carruth6e479322013-01-07 15:04:40 +00003547 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +00003548
Dan Gohman1d2ded72010-05-03 22:09:21 +00003549 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003550
3551 // Check that multiplying with each base register doesn't overflow.
3552 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3553 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003554 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman45774ce2010-02-12 10:34:29 +00003555 goto next;
3556 }
3557
3558 // Check that multiplying with the scaled register doesn't overflow.
3559 if (F.ScaledReg) {
3560 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003561 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman45774ce2010-02-12 10:34:29 +00003562 continue;
3563 }
3564
Dan Gohman6136e942011-05-03 00:46:49 +00003565 // Check that multiplying with the unfolded offset doesn't overflow.
3566 if (F.UnfoldedOffset != 0) {
Dan Gohman6c4a3192011-05-23 21:07:39 +00003567 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
3568 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003569 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3570 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3571 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003572 // If the offset will be truncated, check that it is in bounds.
3573 if (!IntTy->isPointerTy() &&
3574 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3575 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003576 }
3577
Dan Gohman45774ce2010-02-12 10:34:29 +00003578 // If we make it here and it's legal, add it.
3579 (void)InsertFormula(LU, LUIdx, F);
3580 next:;
3581 }
3582}
3583
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003584/// Generate stride factor reuse formulae by making use of scaled-offset address
3585/// modes, for example.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003586void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003587 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003588 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003589 if (!IntTy) return;
3590
3591 // If this Formula already has a scaled register, we can't add another one.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003592 // Try to unscale the formula to generate a better scale.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003593 if (Base.Scale != 0 && !Base.unscale())
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003594 return;
3595
Sanjoy Das302bfd02015-08-16 18:22:43 +00003596 assert(Base.Scale == 0 && "unscale did not did its job!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003597
3598 // Check each interesting stride.
Craig Topper042a3922015-05-25 20:01:18 +00003599 for (int64_t Factor : Factors) {
Chandler Carruth6e479322013-01-07 15:04:40 +00003600 Base.Scale = Factor;
3601 Base.HasBaseReg = Base.BaseRegs.size() > 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00003602 // Check whether this scale is going to be legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003603 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3604 Base)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003605 // As a special-case, handle special out-of-loop Basic users specially.
3606 // TODO: Reconsider this special case.
3607 if (LU.Kind == LSRUse::Basic &&
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003608 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3609 LU.AccessTy, Base) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00003610 LU.AllFixupsOutsideLoop)
3611 LU.Kind = LSRUse::Special;
3612 else
3613 continue;
3614 }
3615 // For an ICmpZero, negating a solitary base register won't lead to
3616 // new solutions.
3617 if (LU.Kind == LSRUse::ICmpZero &&
Chandler Carruth6e479322013-01-07 15:04:40 +00003618 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00003619 continue;
3620 // For each addrec base reg, apply the scale, if possible.
3621 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3622 if (const SCEVAddRecExpr *AR =
3623 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00003624 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003625 if (FactorS->isZero())
3626 continue;
3627 // Divide out the factor, ignoring high bits, since we'll be
3628 // scaling the value back up in the end.
Dan Gohman4eebb942010-02-19 19:35:48 +00003629 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003630 // TODO: This could be optimized to avoid all the copying.
3631 Formula F = Base;
3632 F.ScaledReg = Quotient;
Sanjoy Das302bfd02015-08-16 18:22:43 +00003633 F.deleteBaseReg(F.BaseRegs[i]);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003634 // The canonical representation of 1*reg is reg, which is already in
3635 // Base. In that case, do not try to insert the formula, it will be
3636 // rejected anyway.
3637 if (F.Scale == 1 && F.BaseRegs.empty())
3638 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003639 (void)InsertFormula(LU, LUIdx, F);
3640 }
3641 }
3642 }
3643}
3644
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003645/// Generate reuse formulae from different IV types.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003646void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003647 // Don't bother truncating symbolic values.
Chandler Carruth6e479322013-01-07 15:04:40 +00003648 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003649
3650 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003651 Type *DstTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003652 if (!DstTy) return;
3653 DstTy = SE.getEffectiveSCEVType(DstTy);
3654
Craig Topper042a3922015-05-25 20:01:18 +00003655 for (Type *SrcTy : Types) {
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003656 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003657 Formula F = Base;
3658
Craig Topper042a3922015-05-25 20:01:18 +00003659 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
3660 for (const SCEV *&BaseReg : F.BaseRegs)
3661 BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00003662
3663 // TODO: This assumes we've done basic processing on all uses and
3664 // have an idea what the register usage is.
3665 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3666 continue;
3667
3668 (void)InsertFormula(LU, LUIdx, F);
3669 }
3670 }
3671}
3672
3673namespace {
3674
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003675/// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
3676/// modifications so that the search phase doesn't have to worry about the data
3677/// structures moving underneath it.
Dan Gohman45774ce2010-02-12 10:34:29 +00003678struct WorkItem {
3679 size_t LUIdx;
3680 int64_t Imm;
3681 const SCEV *OrigReg;
3682
3683 WorkItem(size_t LI, int64_t I, const SCEV *R)
3684 : LUIdx(LI), Imm(I), OrigReg(R) {}
3685
3686 void print(raw_ostream &OS) const;
3687 void dump() const;
3688};
3689
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00003690} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00003691
3692void WorkItem::print(raw_ostream &OS) const {
3693 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
3694 << " , add offset " << Imm;
3695}
3696
Davide Italiano945d05f2015-11-23 02:47:30 +00003697LLVM_DUMP_METHOD
Dan Gohman45774ce2010-02-12 10:34:29 +00003698void WorkItem::dump() const {
3699 print(errs()); errs() << '\n';
3700}
3701
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003702/// Look for registers which are a constant distance apart and try to form reuse
3703/// opportunities between them.
Dan Gohman45774ce2010-02-12 10:34:29 +00003704void LSRInstance::GenerateCrossUseConstantOffsets() {
3705 // Group the registers by their value without any added constant offset.
3706 typedef std::map<int64_t, const SCEV *> ImmMapTy;
Craig Topper042a3922015-05-25 20:01:18 +00003707 DenseMap<const SCEV *, ImmMapTy> Map;
Dan Gohman45774ce2010-02-12 10:34:29 +00003708 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
3709 SmallVector<const SCEV *, 8> Sequence;
Craig Topper042a3922015-05-25 20:01:18 +00003710 for (const SCEV *Use : RegUses) {
3711 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
Dan Gohman45774ce2010-02-12 10:34:29 +00003712 int64_t Imm = ExtractImmediate(Reg, SE);
Craig Topper042a3922015-05-25 20:01:18 +00003713 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003714 if (Pair.second)
3715 Sequence.push_back(Reg);
Craig Topper042a3922015-05-25 20:01:18 +00003716 Pair.first->second.insert(std::make_pair(Imm, Use));
3717 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
Dan Gohman45774ce2010-02-12 10:34:29 +00003718 }
3719
3720 // Now examine each set of registers with the same base value. Build up
3721 // a list of work to do and do the work in a separate step so that we're
3722 // not adding formulae and register counts while we're searching.
Dan Gohman110ed642010-09-01 01:45:53 +00003723 SmallVector<WorkItem, 32> WorkItems;
3724 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
Craig Topper042a3922015-05-25 20:01:18 +00003725 for (const SCEV *Reg : Sequence) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003726 const ImmMapTy &Imms = Map.find(Reg)->second;
3727
Dan Gohman363f8472010-02-12 19:20:37 +00003728 // It's not worthwhile looking for reuse if there's only one offset.
3729 if (Imms.size() == 1)
3730 continue;
3731
Dan Gohman45774ce2010-02-12 10:34:29 +00003732 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
Craig Topper042a3922015-05-25 20:01:18 +00003733 for (const auto &Entry : Imms)
3734 dbgs() << ' ' << Entry.first;
Dan Gohman45774ce2010-02-12 10:34:29 +00003735 dbgs() << '\n');
3736
3737 // Examine each offset.
3738 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3739 J != JE; ++J) {
3740 const SCEV *OrigReg = J->second;
3741
3742 int64_t JImm = J->first;
3743 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3744
3745 if (!isa<SCEVConstant>(OrigReg) &&
3746 UsedByIndicesMap[Reg].count() == 1) {
3747 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
3748 continue;
3749 }
3750
3751 // Conservatively examine offsets between this orig reg a few selected
3752 // other orig regs.
3753 ImmMapTy::const_iterator OtherImms[] = {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003754 Imms.begin(), std::prev(Imms.end()),
3755 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
3756 2)
Dan Gohman45774ce2010-02-12 10:34:29 +00003757 };
3758 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
3759 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohman363f8472010-02-12 19:20:37 +00003760 if (M == J || M == JE) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003761
3762 // Compute the difference between the two.
3763 int64_t Imm = (uint64_t)JImm - M->first;
3764 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
Dan Gohman110ed642010-09-01 01:45:53 +00003765 LUIdx = UsedByIndices.find_next(LUIdx))
Dan Gohman45774ce2010-02-12 10:34:29 +00003766 // Make a memo of this use, offset, and register tuple.
David Blaikie70573dc2014-11-19 07:49:26 +00003767 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
Dan Gohman110ed642010-09-01 01:45:53 +00003768 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng85a9f432009-11-12 07:35:05 +00003769 }
3770 }
3771 }
3772
Dan Gohman45774ce2010-02-12 10:34:29 +00003773 Map.clear();
3774 Sequence.clear();
3775 UsedByIndicesMap.clear();
Dan Gohman110ed642010-09-01 01:45:53 +00003776 UniqueItems.clear();
Dan Gohman45774ce2010-02-12 10:34:29 +00003777
3778 // Now iterate through the worklist and add new formulae.
Craig Topper042a3922015-05-25 20:01:18 +00003779 for (const WorkItem &WI : WorkItems) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003780 size_t LUIdx = WI.LUIdx;
3781 LSRUse &LU = Uses[LUIdx];
3782 int64_t Imm = WI.Imm;
3783 const SCEV *OrigReg = WI.OrigReg;
3784
Chris Lattner229907c2011-07-18 04:54:35 +00003785 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
Dan Gohman45774ce2010-02-12 10:34:29 +00003786 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3787 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
3788
Dan Gohman8b0a4192010-03-01 17:49:51 +00003789 // TODO: Use a more targeted data structure.
Dan Gohman45774ce2010-02-12 10:34:29 +00003790 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003791 Formula F = LU.Formulae[L];
3792 // FIXME: The code for the scaled and unscaled registers looks
3793 // very similar but slightly different. Investigate if they
3794 // could be merged. That way, we would not have to unscale the
3795 // Formula.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003796 F.unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003797 // Use the immediate in the scaled register.
3798 if (F.ScaledReg == OrigReg) {
Chandler Carruth6e479322013-01-07 15:04:40 +00003799 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
Dan Gohman45774ce2010-02-12 10:34:29 +00003800 // Don't create 50 + reg(-50).
3801 if (F.referencesReg(SE.getSCEV(
Chandler Carruth6e479322013-01-07 15:04:40 +00003802 ConstantInt::get(IntTy, -(uint64_t)Offset))))
Dan Gohman45774ce2010-02-12 10:34:29 +00003803 continue;
3804 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003805 NewF.BaseOffset = Offset;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003806 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3807 NewF))
Dan Gohman45774ce2010-02-12 10:34:29 +00003808 continue;
3809 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
3810
3811 // If the new scale is a constant in a register, and adding the constant
3812 // value to the immediate would produce a value closer to zero than the
3813 // immediate itself, then the formula isn't worthwhile.
3814 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003815 if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
3816 (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
3817 .ule(std::abs(NewF.BaseOffset)))
Dan Gohman45774ce2010-02-12 10:34:29 +00003818 continue;
3819
3820 // OK, looks good.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003821 NewF.canonicalize();
Dan Gohman45774ce2010-02-12 10:34:29 +00003822 (void)InsertFormula(LU, LUIdx, NewF);
3823 } else {
3824 // Use the immediate in a base register.
3825 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
3826 const SCEV *BaseReg = F.BaseRegs[N];
3827 if (BaseReg != OrigReg)
3828 continue;
3829 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003830 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003831 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
3832 LU.Kind, LU.AccessTy, NewF)) {
3833 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
Dan Gohman6136e942011-05-03 00:46:49 +00003834 continue;
3835 NewF = F;
3836 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3837 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003838 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
3839
3840 // If the new formula has a constant in a register, and adding the
3841 // constant value to the immediate would produce a value closer to
3842 // zero than the immediate itself, then the formula isn't worthwhile.
Craig Topper10949ae2015-05-23 08:45:10 +00003843 for (const SCEV *NewReg : NewF.BaseRegs)
3844 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003845 if ((C->getAPInt() + NewF.BaseOffset)
3846 .abs()
3847 .slt(std::abs(NewF.BaseOffset)) &&
3848 (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >=
3849 countTrailingZeros<uint64_t>(NewF.BaseOffset))
Dan Gohman45774ce2010-02-12 10:34:29 +00003850 goto skip_formula;
3851
3852 // Ok, looks good.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003853 NewF.canonicalize();
Dan Gohman45774ce2010-02-12 10:34:29 +00003854 (void)InsertFormula(LU, LUIdx, NewF);
3855 break;
3856 skip_formula:;
3857 }
3858 }
3859 }
3860 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00003861}
3862
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003863/// Generate formulae for each use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003864void
3865LSRInstance::GenerateAllReuseFormulae() {
Dan Gohman521efe62010-02-16 01:42:53 +00003866 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman45774ce2010-02-12 10:34:29 +00003867 // queries are more precise.
3868 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3869 LSRUse &LU = Uses[LUIdx];
3870 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3871 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
3872 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3873 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
3874 }
3875 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3876 LSRUse &LU = Uses[LUIdx];
3877 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3878 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
3879 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3880 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
3881 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3882 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
3883 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3884 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohman521efe62010-02-16 01:42:53 +00003885 }
3886 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3887 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00003888 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3889 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
3890 }
3891
3892 GenerateCrossUseConstantOffsets();
Dan Gohmanbf673e02010-08-29 15:21:38 +00003893
3894 DEBUG(dbgs() << "\n"
3895 "After generating reuse formulae:\n";
3896 print_uses(dbgs()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003897}
3898
Dan Gohman1b61fd92010-10-07 23:43:09 +00003899/// If there are multiple formulae with the same set of registers used
Dan Gohman45774ce2010-02-12 10:34:29 +00003900/// by other uses, pick the best one and delete the others.
3901void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
Dan Gohman5947e162010-10-07 23:52:18 +00003902 DenseSet<const SCEV *> VisitedRegs;
3903 SmallPtrSet<const SCEV *, 16> Regs;
Andrew Trick5df90962011-12-06 03:13:31 +00003904 SmallPtrSet<const SCEV *, 16> LoserRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00003905#ifndef NDEBUG
Dan Gohman4c4043c2010-05-20 20:05:31 +00003906 bool ChangedFormulae = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00003907#endif
3908
3909 // Collect the best formula for each unique set of shared registers. This
3910 // is reset for each use.
Preston Gurd25c3b6a2013-02-01 20:41:27 +00003911 typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
Dan Gohman45774ce2010-02-12 10:34:29 +00003912 BestFormulaeTy;
3913 BestFormulaeTy BestFormulae;
3914
3915 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3916 LSRUse &LU = Uses[LUIdx];
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003917 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00003918
Dan Gohman4cf99b52010-05-18 23:42:37 +00003919 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00003920 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
3921 FIdx != NumForms; ++FIdx) {
3922 Formula &F = LU.Formulae[FIdx];
3923
Andrew Trick5df90962011-12-06 03:13:31 +00003924 // Some formulas are instant losers. For example, they may depend on
3925 // nonexistent AddRecs from other loops. These need to be filtered
3926 // immediately, otherwise heuristics could choose them over others leading
3927 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
3928 // avoids the need to recompute this information across formulae using the
3929 // same bad AddRec. Passing LoserRegs is also essential unless we remove
3930 // the corresponding bad register from the Regs set.
3931 Cost CostF;
3932 Regs.clear();
Jonas Paulsson7a794222016-08-17 13:24:19 +00003933 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, SE, DT, LU, &LoserRegs);
Andrew Trick5df90962011-12-06 03:13:31 +00003934 if (CostF.isLoser()) {
3935 // During initial formula generation, undesirable formulae are generated
3936 // by uses within other loops that have some non-trivial address mode or
3937 // use the postinc form of the IV. LSR needs to provide these formulae
3938 // as the basis of rediscovering the desired formula that uses an AddRec
3939 // corresponding to the existing phi. Once all formulae have been
3940 // generated, these initial losers may be pruned.
3941 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
3942 dbgs() << "\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00003943 }
Andrew Trick5df90962011-12-06 03:13:31 +00003944 else {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00003945 SmallVector<const SCEV *, 4> Key;
Craig Topper77b99412015-05-23 08:01:41 +00003946 for (const SCEV *Reg : F.BaseRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +00003947 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
3948 Key.push_back(Reg);
3949 }
3950 if (F.ScaledReg &&
3951 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
3952 Key.push_back(F.ScaledReg);
3953 // Unstable sort by host order ok, because this is only used for
3954 // uniquifying.
3955 std::sort(Key.begin(), Key.end());
Dan Gohman45774ce2010-02-12 10:34:29 +00003956
Andrew Trick5df90962011-12-06 03:13:31 +00003957 std::pair<BestFormulaeTy::const_iterator, bool> P =
3958 BestFormulae.insert(std::make_pair(Key, FIdx));
3959 if (P.second)
3960 continue;
3961
Dan Gohman45774ce2010-02-12 10:34:29 +00003962 Formula &Best = LU.Formulae[P.first->second];
Dan Gohman5947e162010-10-07 23:52:18 +00003963
Dan Gohman5947e162010-10-07 23:52:18 +00003964 Cost CostBest;
Dan Gohman5947e162010-10-07 23:52:18 +00003965 Regs.clear();
Jonas Paulsson7a794222016-08-17 13:24:19 +00003966 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, SE, DT, LU);
Dan Gohman5947e162010-10-07 23:52:18 +00003967 if (CostF < CostBest)
Dan Gohman45774ce2010-02-12 10:34:29 +00003968 std::swap(F, Best);
Dan Gohman8aca7ef2010-05-18 22:37:37 +00003969 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00003970 dbgs() << "\n"
Dan Gohman8aca7ef2010-05-18 22:37:37 +00003971 " in favor of formula "; Best.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00003972 dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00003973 }
Andrew Trick5df90962011-12-06 03:13:31 +00003974#ifndef NDEBUG
3975 ChangedFormulae = true;
3976#endif
3977 LU.DeleteFormula(F);
3978 --FIdx;
3979 --NumForms;
3980 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00003981 }
3982
Dan Gohmanbeebef42010-05-18 23:55:57 +00003983 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohman4cf99b52010-05-18 23:42:37 +00003984 if (Any)
3985 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohmand0800242010-05-07 23:36:59 +00003986
3987 // Reset this to prepare for the next use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003988 BestFormulae.clear();
3989 }
3990
Dan Gohman4c4043c2010-05-20 20:05:31 +00003991 DEBUG(if (ChangedFormulae) {
Dan Gohman5b18f032010-02-13 02:06:02 +00003992 dbgs() << "\n"
3993 "After filtering out undesirable candidates:\n";
Dan Gohman45774ce2010-02-12 10:34:29 +00003994 print_uses(dbgs());
3995 });
3996}
3997
Dan Gohmana4eca052010-05-18 22:51:59 +00003998// This is a rough guess that seems to work fairly well.
3999static const size_t ComplexityLimit = UINT16_MAX;
4000
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004001/// Estimate the worst-case number of solutions the solver might have to
4002/// consider. It almost never considers this many solutions because it prune the
4003/// search space, but the pruning isn't always sufficient.
Dan Gohmana4eca052010-05-18 22:51:59 +00004004size_t LSRInstance::EstimateSearchSpaceComplexity() const {
Dan Gohman49d638b2010-10-07 23:37:58 +00004005 size_t Power = 1;
Craig Topper10949ae2015-05-23 08:45:10 +00004006 for (const LSRUse &LU : Uses) {
4007 size_t FSize = LU.Formulae.size();
Dan Gohmana4eca052010-05-18 22:51:59 +00004008 if (FSize >= ComplexityLimit) {
4009 Power = ComplexityLimit;
4010 break;
4011 }
4012 Power *= FSize;
4013 if (Power >= ComplexityLimit)
4014 break;
4015 }
4016 return Power;
4017}
4018
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004019/// When one formula uses a superset of the registers of another formula, it
4020/// won't help reduce register pressure (though it may not necessarily hurt
4021/// register pressure); remove it to simplify the system.
Dan Gohmane9e08732010-08-29 16:09:42 +00004022void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
Dan Gohman20fab452010-05-19 23:43:12 +00004023 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4024 DEBUG(dbgs() << "The search space is too complex.\n");
4025
4026 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4027 "which use a superset of registers used by other "
4028 "formulae.\n");
4029
4030 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4031 LSRUse &LU = Uses[LUIdx];
4032 bool Any = false;
4033 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4034 Formula &F = LU.Formulae[i];
Dan Gohman8ec018c2010-05-20 20:00:41 +00004035 // Look for a formula with a constant or GV in a register. If the use
4036 // also has a formula with that same value in an immediate field,
4037 // delete the one that uses a register.
Dan Gohman20fab452010-05-19 23:43:12 +00004038 for (SmallVectorImpl<const SCEV *>::const_iterator
4039 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4040 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4041 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004042 NewF.BaseOffset += C->getValue()->getSExtValue();
Dan Gohman20fab452010-05-19 23:43:12 +00004043 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4044 (I - F.BaseRegs.begin()));
4045 if (LU.HasFormulaWithSameRegs(NewF)) {
4046 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4047 LU.DeleteFormula(F);
4048 --i;
4049 --e;
4050 Any = true;
4051 break;
4052 }
4053 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4054 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
Chandler Carruth6e479322013-01-07 15:04:40 +00004055 if (!F.BaseGV) {
Dan Gohman20fab452010-05-19 23:43:12 +00004056 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004057 NewF.BaseGV = GV;
Dan Gohman20fab452010-05-19 23:43:12 +00004058 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4059 (I - F.BaseRegs.begin()));
4060 if (LU.HasFormulaWithSameRegs(NewF)) {
4061 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4062 dbgs() << '\n');
4063 LU.DeleteFormula(F);
4064 --i;
4065 --e;
4066 Any = true;
4067 break;
4068 }
4069 }
4070 }
4071 }
4072 }
4073 if (Any)
4074 LU.RecomputeRegs(LUIdx, RegUses);
4075 }
4076
4077 DEBUG(dbgs() << "After pre-selection:\n";
4078 print_uses(dbgs()));
4079 }
Dan Gohmane9e08732010-08-29 16:09:42 +00004080}
Dan Gohman20fab452010-05-19 23:43:12 +00004081
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004082/// When there are many registers for expressions like A, A+1, A+2, etc.,
4083/// allocate a single register for them.
Dan Gohmane9e08732010-08-29 16:09:42 +00004084void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
Jakub Staszak11bd8352013-02-16 16:08:15 +00004085 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4086 return;
Dan Gohman20fab452010-05-19 23:43:12 +00004087
Jakub Staszak11bd8352013-02-16 16:08:15 +00004088 DEBUG(dbgs() << "The search space is too complex.\n"
4089 "Narrowing the search space by assuming that uses separated "
4090 "by a constant offset will use the same registers.\n");
Dan Gohman20fab452010-05-19 23:43:12 +00004091
Jakub Staszak11bd8352013-02-16 16:08:15 +00004092 // This is especially useful for unrolled loops.
Dan Gohman8ec018c2010-05-20 20:00:41 +00004093
Jakub Staszak11bd8352013-02-16 16:08:15 +00004094 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4095 LSRUse &LU = Uses[LUIdx];
Craig Topper77b99412015-05-23 08:01:41 +00004096 for (const Formula &F : LU.Formulae) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004097 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
Jakub Staszak11bd8352013-02-16 16:08:15 +00004098 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004099
Jakub Staszak11bd8352013-02-16 16:08:15 +00004100 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4101 if (!LUThatHas)
4102 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004103
Jakub Staszak11bd8352013-02-16 16:08:15 +00004104 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4105 LU.Kind, LU.AccessTy))
4106 continue;
Dan Gohman110ed642010-09-01 01:45:53 +00004107
Jakub Staszak11bd8352013-02-16 16:08:15 +00004108 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman2fd85d72010-10-08 19:33:26 +00004109
Jakub Staszak11bd8352013-02-16 16:08:15 +00004110 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4111
Jonas Paulsson7a794222016-08-17 13:24:19 +00004112 // Transfer the fixups of LU to LUThatHas.
4113 for (LSRFixup &Fixup : LU.Fixups) {
4114 Fixup.Offset += F.BaseOffset;
4115 LUThatHas->pushFixup(Fixup);
4116 DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
Jakub Staszak11bd8352013-02-16 16:08:15 +00004117 }
Jonas Paulsson7a794222016-08-17 13:24:19 +00004118
Jakub Staszak11bd8352013-02-16 16:08:15 +00004119 // Delete formulae from the new use which are no longer legal.
4120 bool Any = false;
4121 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4122 Formula &F = LUThatHas->Formulae[i];
4123 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4124 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4125 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4126 dbgs() << '\n');
4127 LUThatHas->DeleteFormula(F);
4128 --i;
4129 --e;
4130 Any = true;
Dan Gohman20fab452010-05-19 23:43:12 +00004131 }
4132 }
Dan Gohman20fab452010-05-19 23:43:12 +00004133
Jakub Staszak11bd8352013-02-16 16:08:15 +00004134 if (Any)
4135 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4136
4137 // Delete the old use.
4138 DeleteUse(LU, LUIdx);
4139 --LUIdx;
4140 --NumUses;
4141 break;
4142 }
Dan Gohman20fab452010-05-19 23:43:12 +00004143 }
Jakub Staszak11bd8352013-02-16 16:08:15 +00004144
4145 DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
Dan Gohmane9e08732010-08-29 16:09:42 +00004146}
Dan Gohman20fab452010-05-19 23:43:12 +00004147
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004148/// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
Dan Gohman002ff892010-08-29 16:39:22 +00004149/// we've done more filtering, as it may be able to find more formulae to
4150/// eliminate.
4151void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4152 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4153 DEBUG(dbgs() << "The search space is too complex.\n");
4154
4155 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4156 "undesirable dedicated registers.\n");
4157
4158 FilterOutUndesirableDedicatedRegisters();
4159
4160 DEBUG(dbgs() << "After pre-selection:\n";
4161 print_uses(dbgs()));
4162 }
4163}
4164
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004165/// Pick a register which seems likely to be profitable, and then in any use
4166/// which has any reference to that register, delete all formulae which do not
4167/// reference that register.
Dan Gohmane9e08732010-08-29 16:09:42 +00004168void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004169 // With all other options exhausted, loop until the system is simple
4170 // enough to handle.
Dan Gohman45774ce2010-02-12 10:34:29 +00004171 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmana4eca052010-05-18 22:51:59 +00004172 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004173 // Ok, we have too many of formulae on our hands to conveniently handle.
4174 // Use a rough heuristic to thin out the list.
Dan Gohman63e90152010-05-18 22:41:32 +00004175 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004176
4177 // Pick the register which is used by the most LSRUses, which is likely
4178 // to be a good reuse register candidate.
Craig Topperf40110f2014-04-25 05:29:35 +00004179 const SCEV *Best = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00004180 unsigned BestNum = 0;
Craig Topper77b99412015-05-23 08:01:41 +00004181 for (const SCEV *Reg : RegUses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004182 if (Taken.count(Reg))
4183 continue;
Evgeny Stupachenko0c4300f2016-11-30 22:23:51 +00004184 if (!Best) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004185 Best = Reg;
Evgeny Stupachenko0c4300f2016-11-30 22:23:51 +00004186 BestNum = RegUses.getUsedByIndices(Reg).count();
4187 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00004188 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4189 if (Count > BestNum) {
4190 Best = Reg;
4191 BestNum = Count;
4192 }
4193 }
4194 }
4195
4196 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman8b0a4192010-03-01 17:49:51 +00004197 << " will yield profitable reuse.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004198 Taken.insert(Best);
4199
4200 // In any use with formulae which references this register, delete formulae
4201 // which don't reference it.
Dan Gohman4cf99b52010-05-18 23:42:37 +00004202 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4203 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00004204 if (!LU.Regs.count(Best)) continue;
4205
Dan Gohman4cf99b52010-05-18 23:42:37 +00004206 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00004207 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4208 Formula &F = LU.Formulae[i];
4209 if (!F.referencesReg(Best)) {
4210 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00004211 LU.DeleteFormula(F);
Dan Gohman45774ce2010-02-12 10:34:29 +00004212 --e;
4213 --i;
Dan Gohman4cf99b52010-05-18 23:42:37 +00004214 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00004215 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman45774ce2010-02-12 10:34:29 +00004216 continue;
4217 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004218 }
Dan Gohman4cf99b52010-05-18 23:42:37 +00004219
4220 if (Any)
4221 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman45774ce2010-02-12 10:34:29 +00004222 }
4223
4224 DEBUG(dbgs() << "After pre-selection:\n";
4225 print_uses(dbgs()));
4226 }
4227}
4228
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004229/// If there are an extraordinary number of formulae to choose from, use some
4230/// rough heuristics to prune down the number of formulae. This keeps the main
4231/// solver from taking an extraordinary amount of time in some worst-case
4232/// scenarios.
Dan Gohmane9e08732010-08-29 16:09:42 +00004233void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4234 NarrowSearchSpaceByDetectingSupersets();
4235 NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00004236 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohmane9e08732010-08-29 16:09:42 +00004237 NarrowSearchSpaceByPickingWinnerRegs();
4238}
4239
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004240/// This is the recursive solver.
Dan Gohman45774ce2010-02-12 10:34:29 +00004241void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4242 Cost &SolutionCost,
4243 SmallVectorImpl<const Formula *> &Workspace,
4244 const Cost &CurCost,
4245 const SmallPtrSet<const SCEV *, 16> &CurRegs,
4246 DenseSet<const SCEV *> &VisitedRegs) const {
4247 // Some ideas:
4248 // - prune more:
4249 // - use more aggressive filtering
4250 // - sort the formula so that the most profitable solutions are found first
4251 // - sort the uses too
4252 // - search faster:
Dan Gohman8b0a4192010-03-01 17:49:51 +00004253 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman45774ce2010-02-12 10:34:29 +00004254 // and bail early.
4255 // - track register sets with SmallBitVector
4256
4257 const LSRUse &LU = Uses[Workspace.size()];
4258
4259 // If this use references any register that's already a part of the
4260 // in-progress solution, consider it a requirement that a formula must
4261 // reference that register in order to be considered. This prunes out
4262 // unprofitable searching.
4263 SmallSetVector<const SCEV *, 4> ReqRegs;
Craig Topper46276792014-08-24 23:23:06 +00004264 for (const SCEV *S : CurRegs)
4265 if (LU.Regs.count(S))
4266 ReqRegs.insert(S);
Dan Gohman45774ce2010-02-12 10:34:29 +00004267
4268 SmallPtrSet<const SCEV *, 16> NewRegs;
4269 Cost NewCost;
Craig Topper77b99412015-05-23 08:01:41 +00004270 for (const Formula &F : LU.Formulae) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004271 // Ignore formulae which may not be ideal in terms of register reuse of
4272 // ReqRegs. The formula should use all required registers before
4273 // introducing new ones.
4274 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
Craig Topper77b99412015-05-23 08:01:41 +00004275 for (const SCEV *Reg : ReqRegs) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004276 if ((F.ScaledReg && F.ScaledReg == Reg) ||
David Majnemer0d955d02016-08-11 22:21:41 +00004277 is_contained(F.BaseRegs, Reg)) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004278 --NumReqRegsToFind;
4279 if (NumReqRegsToFind == 0)
4280 break;
Andrew Tricke3502cb2012-03-22 22:42:51 +00004281 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004282 }
Adam Nemetdeab6f92014-04-29 18:25:28 +00004283 if (NumReqRegsToFind != 0) {
Andrew Tricke3502cb2012-03-22 22:42:51 +00004284 // If none of the formulae satisfied the required registers, then we could
4285 // clear ReqRegs and try again. Currently, we simply give up in this case.
4286 continue;
4287 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004288
4289 // Evaluate the cost of the current formula. If it's already worse than
4290 // the current best, prune the search at that point.
4291 NewCost = CurCost;
4292 NewRegs = CurRegs;
Jonas Paulsson7a794222016-08-17 13:24:19 +00004293 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, SE, DT, LU);
Dan Gohman45774ce2010-02-12 10:34:29 +00004294 if (NewCost < SolutionCost) {
4295 Workspace.push_back(&F);
4296 if (Workspace.size() != Uses.size()) {
4297 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4298 NewRegs, VisitedRegs);
4299 if (F.getNumRegs() == 1 && Workspace.size() == 1)
4300 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4301 } else {
4302 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
Andrew Trick4dc3eff2012-01-09 18:58:16 +00004303 dbgs() << ".\n Regs:";
Craig Topper46276792014-08-24 23:23:06 +00004304 for (const SCEV *S : NewRegs)
4305 dbgs() << ' ' << *S;
Dan Gohman45774ce2010-02-12 10:34:29 +00004306 dbgs() << '\n');
4307
4308 SolutionCost = NewCost;
4309 Solution = Workspace;
4310 }
4311 Workspace.pop_back();
4312 }
Dan Gohman5b18f032010-02-13 02:06:02 +00004313 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004314}
4315
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004316/// Choose one formula from each use. Return the results in the given Solution
4317/// vector.
Dan Gohman45774ce2010-02-12 10:34:29 +00004318void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
4319 SmallVector<const Formula *, 8> Workspace;
4320 Cost SolutionCost;
Tim Northoverbc6659c2014-01-22 13:27:00 +00004321 SolutionCost.Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00004322 Cost CurCost;
4323 SmallPtrSet<const SCEV *, 16> CurRegs;
4324 DenseSet<const SCEV *> VisitedRegs;
4325 Workspace.reserve(Uses.size());
4326
Dan Gohman8ec018c2010-05-20 20:00:41 +00004327 // SolveRecurse does all the work.
Dan Gohman45774ce2010-02-12 10:34:29 +00004328 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4329 CurRegs, VisitedRegs);
Andrew Trick58124392011-09-27 00:44:14 +00004330 if (Solution.empty()) {
4331 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
4332 return;
4333 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004334
4335 // Ok, we've now made all our decisions.
4336 DEBUG(dbgs() << "\n"
4337 "The chosen solution requires "; SolutionCost.print(dbgs());
4338 dbgs() << ":\n";
4339 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
4340 dbgs() << " ";
4341 Uses[i].print(dbgs());
4342 dbgs() << "\n"
4343 " ";
4344 Solution[i]->print(dbgs());
4345 dbgs() << '\n';
4346 });
Dan Gohman6295f2e2010-05-20 20:59:23 +00004347
4348 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman45774ce2010-02-12 10:34:29 +00004349}
4350
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004351/// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
4352/// we can go while still being dominated by the input positions. This helps
4353/// canonicalize the insert position, which encourages sharing.
Dan Gohman607e02b2010-04-09 22:07:05 +00004354BasicBlock::iterator
4355LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
4356 const SmallVectorImpl<Instruction *> &Inputs)
4357 const {
Geoff Berry43e51602016-06-06 19:10:46 +00004358 Instruction *Tentative = &*IP;
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004359 while (true) {
Geoff Berry43e51602016-06-06 19:10:46 +00004360 bool AllDominate = true;
4361 Instruction *BetterPos = nullptr;
4362 // Don't bother attempting to insert before a catchswitch, their basic block
4363 // cannot have other non-PHI instructions.
4364 if (isa<CatchSwitchInst>(Tentative))
4365 return IP;
4366
4367 for (Instruction *Inst : Inputs) {
4368 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
4369 AllDominate = false;
4370 break;
4371 }
4372 // Attempt to find an insert position in the middle of the block,
4373 // instead of at the end, so that it can be used for other expansions.
4374 if (Tentative->getParent() == Inst->getParent() &&
4375 (!BetterPos || !DT.dominates(Inst, BetterPos)))
4376 BetterPos = &*std::next(BasicBlock::iterator(Inst));
4377 }
4378 if (!AllDominate)
4379 break;
4380 if (BetterPos)
4381 IP = BetterPos->getIterator();
4382 else
4383 IP = Tentative->getIterator();
4384
Dan Gohman607e02b2010-04-09 22:07:05 +00004385 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4386 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
4387
4388 BasicBlock *IDom;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004389 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman9b48b852010-05-20 22:46:54 +00004390 if (!Rung) return IP;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004391 Rung = Rung->getIDom();
4392 if (!Rung) return IP;
4393 IDom = Rung->getBlock();
Dan Gohman607e02b2010-04-09 22:07:05 +00004394
4395 // Don't climb into a loop though.
4396 const Loop *IDomLoop = LI.getLoopFor(IDom);
4397 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
4398 if (IDomDepth <= IPLoopDepth &&
4399 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4400 break;
4401 }
4402
Geoff Berry43e51602016-06-06 19:10:46 +00004403 Tentative = IDom->getTerminator();
Dan Gohman607e02b2010-04-09 22:07:05 +00004404 }
4405
4406 return IP;
4407}
4408
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004409/// Determine an input position which will be dominated by the operands and
4410/// which will dominate the result.
Dan Gohmand2df6432010-04-09 02:00:38 +00004411BasicBlock::iterator
Andrew Trickc908b432012-01-20 07:41:13 +00004412LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
Dan Gohman607e02b2010-04-09 22:07:05 +00004413 const LSRFixup &LF,
Andrew Trickc908b432012-01-20 07:41:13 +00004414 const LSRUse &LU,
4415 SCEVExpander &Rewriter) const {
Dan Gohmand2df6432010-04-09 02:00:38 +00004416 // Collect some instructions which must be dominated by the
Dan Gohmand006ab92010-04-07 22:27:08 +00004417 // expanding replacement. These must be dominated by any operands that
Dan Gohman45774ce2010-02-12 10:34:29 +00004418 // will be required in the expansion.
4419 SmallVector<Instruction *, 4> Inputs;
4420 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4421 Inputs.push_back(I);
4422 if (LU.Kind == LSRUse::ICmpZero)
4423 if (Instruction *I =
4424 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4425 Inputs.push_back(I);
Dan Gohmand006ab92010-04-07 22:27:08 +00004426 if (LF.PostIncLoops.count(L)) {
4427 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman52f55632010-03-02 01:59:21 +00004428 Inputs.push_back(L->getLoopLatch()->getTerminator());
4429 else
4430 Inputs.push_back(IVIncInsertPos);
4431 }
Dan Gohman45065392010-04-08 05:57:57 +00004432 // The expansion must also be dominated by the increment positions of any
4433 // loops it for which it is using post-inc mode.
Craig Topper77b99412015-05-23 08:01:41 +00004434 for (const Loop *PIL : LF.PostIncLoops) {
Dan Gohman45065392010-04-08 05:57:57 +00004435 if (PIL == L) continue;
4436
Dan Gohman607e02b2010-04-09 22:07:05 +00004437 // Be dominated by the loop exit.
Dan Gohman45065392010-04-08 05:57:57 +00004438 SmallVector<BasicBlock *, 4> ExitingBlocks;
4439 PIL->getExitingBlocks(ExitingBlocks);
4440 if (!ExitingBlocks.empty()) {
4441 BasicBlock *BB = ExitingBlocks[0];
4442 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
4443 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
4444 Inputs.push_back(BB->getTerminator());
4445 }
4446 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004447
David Majnemerba275f92015-08-19 19:54:02 +00004448 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
Andrew Trickc908b432012-01-20 07:41:13 +00004449 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4450 "Insertion point must be a normal instruction");
4451
Dan Gohman45774ce2010-02-12 10:34:29 +00004452 // Then, climb up the immediate dominator tree as far as we can go while
4453 // still being dominated by the input positions.
Andrew Trickc908b432012-01-20 07:41:13 +00004454 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
Dan Gohmand2df6432010-04-09 02:00:38 +00004455
4456 // Don't insert instructions before PHI nodes.
Dan Gohman45774ce2010-02-12 10:34:29 +00004457 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand2df6432010-04-09 02:00:38 +00004458
Bill Wendling86c5cbe2011-08-24 21:06:46 +00004459 // Ignore landingpad instructions.
David Majnemere09d0352016-03-24 21:40:22 +00004460 while (IP->isEHPad()) ++IP;
Bill Wendling86c5cbe2011-08-24 21:06:46 +00004461
Dan Gohmand2df6432010-04-09 02:00:38 +00004462 // Ignore debug intrinsics.
Dan Gohmand42e09d2010-03-26 00:33:27 +00004463 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman45774ce2010-02-12 10:34:29 +00004464
Andrew Trickc908b432012-01-20 07:41:13 +00004465 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
4466 // IP consistent across expansions and allows the previously inserted
4467 // instructions to be reused by subsequent expansion.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004468 while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
4469 ++IP;
Andrew Trickc908b432012-01-20 07:41:13 +00004470
Dan Gohmand2df6432010-04-09 02:00:38 +00004471 return IP;
4472}
4473
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004474/// Emit instructions for the leading candidate expression for this LSRUse (this
4475/// is called "expanding").
Jonas Paulsson7a794222016-08-17 13:24:19 +00004476Value *LSRInstance::Expand(const LSRUse &LU,
4477 const LSRFixup &LF,
Dan Gohmand2df6432010-04-09 02:00:38 +00004478 const Formula &F,
4479 BasicBlock::iterator IP,
4480 SCEVExpander &Rewriter,
4481 SmallVectorImpl<WeakVH> &DeadInsts) const {
Andrew Trick57243da2013-10-25 21:35:56 +00004482 if (LU.RigidFormula)
4483 return LF.OperandValToReplace;
Dan Gohmand2df6432010-04-09 02:00:38 +00004484
4485 // Determine an input position which will be dominated by the operands and
4486 // which will dominate the result.
Andrew Trickc908b432012-01-20 07:41:13 +00004487 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
Geoff Berryd0182802016-08-11 21:05:17 +00004488 Rewriter.setInsertPoint(&*IP);
Dan Gohmand2df6432010-04-09 02:00:38 +00004489
Dan Gohman45774ce2010-02-12 10:34:29 +00004490 // Inform the Rewriter if we have a post-increment use, so that it can
4491 // perform an advantageous expansion.
Dan Gohmand006ab92010-04-07 22:27:08 +00004492 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman45774ce2010-02-12 10:34:29 +00004493
4494 // This is the type that the user actually needs.
Chris Lattner229907c2011-07-18 04:54:35 +00004495 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004496 // This will be the type that we'll initially expand to.
Chris Lattner229907c2011-07-18 04:54:35 +00004497 Type *Ty = F.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004498 if (!Ty)
4499 // No type known; just expand directly to the ultimate type.
4500 Ty = OpTy;
4501 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
4502 // Expand directly to the ultimate type if it's the right size.
4503 Ty = OpTy;
4504 // This is the type to do integer arithmetic in.
Chris Lattner229907c2011-07-18 04:54:35 +00004505 Type *IntTy = SE.getEffectiveSCEVType(Ty);
Dan Gohman45774ce2010-02-12 10:34:29 +00004506
4507 // Build up a list of operands to add together to form the full base.
4508 SmallVector<const SCEV *, 8> Ops;
4509
4510 // Expand the BaseRegs portion.
Craig Topper77b99412015-05-23 08:01:41 +00004511 for (const SCEV *Reg : F.BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004512 assert(!Reg->isZero() && "Zero allocated in a base register!");
4513
Dan Gohmand006ab92010-04-07 22:27:08 +00004514 // If we're expanding for a post-inc user, make the post-inc adjustment.
4515 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
Sanjoy Das215df9e2015-08-04 01:52:05 +00004516 Reg = TransformForPostIncUse(Denormalize, Reg,
4517 LF.UserInst, LF.OperandValToReplace,
4518 Loops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00004519
Geoff Berryd0182802016-08-11 21:05:17 +00004520 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004521 }
4522
4523 // Expand the ScaledReg portion.
Craig Topperf40110f2014-04-25 05:29:35 +00004524 Value *ICmpScaledV = nullptr;
Chandler Carruth6e479322013-01-07 15:04:40 +00004525 if (F.Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004526 const SCEV *ScaledS = F.ScaledReg;
4527
Dan Gohmand006ab92010-04-07 22:27:08 +00004528 // If we're expanding for a post-inc user, make the post-inc adjustment.
4529 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
Sanjoy Das215df9e2015-08-04 01:52:05 +00004530 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
4531 LF.UserInst, LF.OperandValToReplace,
4532 Loops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00004533
4534 if (LU.Kind == LSRUse::ICmpZero) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004535 // Expand ScaleReg as if it was part of the base regs.
4536 if (F.Scale == 1)
Sanjoy Das215df9e2015-08-04 01:52:05 +00004537 Ops.push_back(
Geoff Berryd0182802016-08-11 21:05:17 +00004538 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)));
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004539 else {
4540 // An interesting way of "folding" with an icmp is to use a negated
4541 // scale, which we'll implement by inserting it into the other operand
4542 // of the icmp.
4543 assert(F.Scale == -1 &&
4544 "The only scale supported by ICmpZero uses is -1!");
Geoff Berryd0182802016-08-11 21:05:17 +00004545 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004546 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004547 } else {
4548 // Otherwise just expand the scaled register and an explicit scale,
4549 // which is expected to be matched as part of the address.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004550
4551 // Flush the operand list to suppress SCEVExpander hoisting address modes.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004552 // Unless the addressing mode will not be folded.
4553 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
4554 isAMCompletelyFolded(TTI, LU, F)) {
Geoff Berryd0182802016-08-11 21:05:17 +00004555 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
Andrew Trick8370c7c2012-06-15 20:07:29 +00004556 Ops.clear();
4557 Ops.push_back(SE.getUnknown(FullV));
4558 }
Geoff Berryd0182802016-08-11 21:05:17 +00004559 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr));
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004560 if (F.Scale != 1)
4561 ScaledS =
4562 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
Dan Gohman45774ce2010-02-12 10:34:29 +00004563 Ops.push_back(ScaledS);
4564 }
4565 }
4566
Dan Gohman29707de2010-03-03 05:29:13 +00004567 // Expand the GV portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004568 if (F.BaseGV) {
Dan Gohman29707de2010-03-03 05:29:13 +00004569 // Flush the operand list to suppress SCEVExpander hoisting.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004570 if (!Ops.empty()) {
Geoff Berryd0182802016-08-11 21:05:17 +00004571 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
Andrew Trick8370c7c2012-06-15 20:07:29 +00004572 Ops.clear();
4573 Ops.push_back(SE.getUnknown(FullV));
4574 }
Chandler Carruth6e479322013-01-07 15:04:40 +00004575 Ops.push_back(SE.getUnknown(F.BaseGV));
Andrew Trick8370c7c2012-06-15 20:07:29 +00004576 }
4577
4578 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
4579 // unfolded offsets. LSR assumes they both live next to their uses.
4580 if (!Ops.empty()) {
Geoff Berryd0182802016-08-11 21:05:17 +00004581 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +00004582 Ops.clear();
4583 Ops.push_back(SE.getUnknown(FullV));
4584 }
4585
4586 // Expand the immediate portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004587 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
Dan Gohman45774ce2010-02-12 10:34:29 +00004588 if (Offset != 0) {
4589 if (LU.Kind == LSRUse::ICmpZero) {
4590 // The other interesting way of "folding" with an ICmpZero is to use a
4591 // negated immediate.
4592 if (!ICmpScaledV)
Eli Friedmanb46345d2011-10-13 23:48:33 +00004593 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
Dan Gohman45774ce2010-02-12 10:34:29 +00004594 else {
4595 Ops.push_back(SE.getUnknown(ICmpScaledV));
4596 ICmpScaledV = ConstantInt::get(IntTy, Offset);
4597 }
4598 } else {
4599 // Just add the immediate values. These again are expected to be matched
4600 // as part of the address.
Dan Gohman29707de2010-03-03 05:29:13 +00004601 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004602 }
4603 }
4604
Dan Gohman6136e942011-05-03 00:46:49 +00004605 // Expand the unfolded offset portion.
4606 int64_t UnfoldedOffset = F.UnfoldedOffset;
4607 if (UnfoldedOffset != 0) {
4608 // Just add the immediate values.
4609 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
4610 UnfoldedOffset)));
4611 }
4612
Dan Gohman45774ce2010-02-12 10:34:29 +00004613 // Emit instructions summing all the operands.
4614 const SCEV *FullS = Ops.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +00004615 SE.getConstant(IntTy, 0) :
Dan Gohman45774ce2010-02-12 10:34:29 +00004616 SE.getAddExpr(Ops);
Geoff Berryd0182802016-08-11 21:05:17 +00004617 Value *FullV = Rewriter.expandCodeFor(FullS, Ty);
Dan Gohman45774ce2010-02-12 10:34:29 +00004618
4619 // We're done expanding now, so reset the rewriter.
Dan Gohmand006ab92010-04-07 22:27:08 +00004620 Rewriter.clearPostInc();
Dan Gohman45774ce2010-02-12 10:34:29 +00004621
4622 // An ICmpZero Formula represents an ICmp which we're handling as a
4623 // comparison against zero. Now that we've expanded an expression for that
4624 // form, update the ICmp's other operand.
4625 if (LU.Kind == LSRUse::ICmpZero) {
4626 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004627 DeadInsts.emplace_back(CI->getOperand(1));
Chandler Carruth6e479322013-01-07 15:04:40 +00004628 assert(!F.BaseGV && "ICmp does not support folding a global value and "
Dan Gohman45774ce2010-02-12 10:34:29 +00004629 "a scale at the same time!");
Chandler Carruth6e479322013-01-07 15:04:40 +00004630 if (F.Scale == -1) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004631 if (ICmpScaledV->getType() != OpTy) {
4632 Instruction *Cast =
4633 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
4634 OpTy, false),
4635 ICmpScaledV, OpTy, "tmp", CI);
4636 ICmpScaledV = Cast;
4637 }
4638 CI->setOperand(1, ICmpScaledV);
4639 } else {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004640 // A scale of 1 means that the scale has been expanded as part of the
4641 // base regs.
4642 assert((F.Scale == 0 || F.Scale == 1) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00004643 "ICmp does not support folding a global value and "
4644 "a scale at the same time!");
4645 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
4646 -(uint64_t)Offset);
4647 if (C->getType() != OpTy)
4648 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4649 OpTy, false),
4650 C, OpTy);
4651
4652 CI->setOperand(1, C);
4653 }
4654 }
4655
4656 return FullV;
4657}
4658
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004659/// Helper for Rewrite. PHI nodes are special because the use of their operands
4660/// effectively happens in their predecessor blocks, so the expression may need
4661/// to be expanded in multiple places.
Dan Gohman6deab962010-02-16 20:25:07 +00004662void LSRInstance::RewriteForPHI(PHINode *PN,
Jonas Paulsson7a794222016-08-17 13:24:19 +00004663 const LSRUse &LU,
Dan Gohman6deab962010-02-16 20:25:07 +00004664 const LSRFixup &LF,
4665 const Formula &F,
Dan Gohman6deab962010-02-16 20:25:07 +00004666 SCEVExpander &Rewriter,
Justin Bogner843fb202015-12-15 19:40:57 +00004667 SmallVectorImpl<WeakVH> &DeadInsts) const {
Dan Gohman6deab962010-02-16 20:25:07 +00004668 DenseMap<BasicBlock *, Value *> Inserted;
4669 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4670 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
4671 BasicBlock *BB = PN->getIncomingBlock(i);
4672
4673 // If this is a critical edge, split the edge so that we do not insert
4674 // the code on all predecessor/successor paths. We do this unless this
4675 // is the canonical backedge for this loop, which complicates post-inc
4676 // users.
4677 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
David Majnemerbba17392017-01-13 22:24:27 +00004678 !isa<IndirectBrInst>(BB->getTerminator()) &&
4679 !isa<CatchSwitchInst>(BB->getTerminator())) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004680 BasicBlock *Parent = PN->getParent();
4681 Loop *PNLoop = LI.getLoopFor(Parent);
4682 if (!PNLoop || Parent != PNLoop->getHeader()) {
Dan Gohmande7f6992011-02-08 00:55:13 +00004683 // Split the critical edge.
Craig Topperf40110f2014-04-25 05:29:35 +00004684 BasicBlock *NewBB = nullptr;
Bill Wendling3fb137f2011-08-25 05:55:40 +00004685 if (!Parent->isLandingPad()) {
Chandler Carruth37df2cf2015-01-19 12:09:11 +00004686 NewBB = SplitCriticalEdge(BB, Parent,
4687 CriticalEdgeSplittingOptions(&DT, &LI)
4688 .setMergeIdenticalEdges()
4689 .setDontDeleteUselessPHIs());
Bill Wendling3fb137f2011-08-25 05:55:40 +00004690 } else {
4691 SmallVector<BasicBlock*, 2> NewBBs;
Chandler Carruth96ada252015-07-22 09:52:54 +00004692 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI);
Bill Wendling3fb137f2011-08-25 05:55:40 +00004693 NewBB = NewBBs[0];
4694 }
Andrew Trick402edbb2012-09-18 17:51:33 +00004695 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
4696 // phi predecessors are identical. The simple thing to do is skip
4697 // splitting in this case rather than complicate the API.
4698 if (NewBB) {
4699 // If PN is outside of the loop and BB is in the loop, we want to
4700 // move the block to be immediately before the PHI block, not
4701 // immediately after BB.
4702 if (L->contains(BB) && !L->contains(PN))
4703 NewBB->moveBefore(PN->getParent());
Dan Gohman6deab962010-02-16 20:25:07 +00004704
Andrew Trick402edbb2012-09-18 17:51:33 +00004705 // Splitting the edge can reduce the number of PHI entries we have.
4706 e = PN->getNumIncomingValues();
4707 BB = NewBB;
4708 i = PN->getBasicBlockIndex(BB);
4709 }
Dan Gohmande7f6992011-02-08 00:55:13 +00004710 }
Dan Gohman6deab962010-02-16 20:25:07 +00004711 }
4712
4713 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
Craig Topperf40110f2014-04-25 05:29:35 +00004714 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
Dan Gohman6deab962010-02-16 20:25:07 +00004715 if (!Pair.second)
4716 PN->setIncomingValue(i, Pair.first->second);
4717 else {
Jonas Paulsson7a794222016-08-17 13:24:19 +00004718 Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004719 Rewriter, DeadInsts);
Dan Gohman6deab962010-02-16 20:25:07 +00004720
4721 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00004722 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman6deab962010-02-16 20:25:07 +00004723 if (FullV->getType() != OpTy)
4724 FullV =
4725 CastInst::Create(CastInst::getCastOpcode(FullV, false,
4726 OpTy, false),
4727 FullV, LF.OperandValToReplace->getType(),
4728 "tmp", BB->getTerminator());
4729
4730 PN->setIncomingValue(i, FullV);
4731 Pair.first->second = FullV;
4732 }
4733 }
4734}
4735
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004736/// Emit instructions for the leading candidate expression for this LSRUse (this
4737/// is called "expanding"), and update the UserInst to reference the newly
4738/// expanded value.
Jonas Paulsson7a794222016-08-17 13:24:19 +00004739void LSRInstance::Rewrite(const LSRUse &LU,
4740 const LSRFixup &LF,
Dan Gohman45774ce2010-02-12 10:34:29 +00004741 const Formula &F,
Dan Gohman45774ce2010-02-12 10:34:29 +00004742 SCEVExpander &Rewriter,
Justin Bogner843fb202015-12-15 19:40:57 +00004743 SmallVectorImpl<WeakVH> &DeadInsts) const {
Dan Gohman45774ce2010-02-12 10:34:29 +00004744 // First, find an insertion point that dominates UserInst. For PHI nodes,
4745 // find the nearest block which dominates all the relevant uses.
4746 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Jonas Paulsson7a794222016-08-17 13:24:19 +00004747 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
Dan Gohman45774ce2010-02-12 10:34:29 +00004748 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004749 Value *FullV =
Jonas Paulsson7a794222016-08-17 13:24:19 +00004750 Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
Dan Gohman45774ce2010-02-12 10:34:29 +00004751
4752 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00004753 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004754 if (FullV->getType() != OpTy) {
4755 Instruction *Cast =
4756 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
4757 FullV, OpTy, "tmp", LF.UserInst);
4758 FullV = Cast;
4759 }
4760
4761 // Update the user. ICmpZero is handled specially here (for now) because
4762 // Expand may have updated one of the operands of the icmp already, and
4763 // its new value may happen to be equal to LF.OperandValToReplace, in
4764 // which case doing replaceUsesOfWith leads to replacing both operands
4765 // with the same value. TODO: Reorganize this.
Jonas Paulsson7a794222016-08-17 13:24:19 +00004766 if (LU.Kind == LSRUse::ICmpZero)
Dan Gohman45774ce2010-02-12 10:34:29 +00004767 LF.UserInst->setOperand(0, FullV);
4768 else
4769 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
4770 }
4771
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004772 DeadInsts.emplace_back(LF.OperandValToReplace);
Dan Gohman45774ce2010-02-12 10:34:29 +00004773}
4774
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004775/// Rewrite all the fixup locations with new values, following the chosen
4776/// solution.
Justin Bogner843fb202015-12-15 19:40:57 +00004777void LSRInstance::ImplementSolution(
4778 const SmallVectorImpl<const Formula *> &Solution) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004779 // Keep track of instructions we may have made dead, so that
4780 // we can remove them after we are done working.
4781 SmallVector<WeakVH, 16> DeadInsts;
4782
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004783 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
4784 "lsr");
Andrew Trick4dc3eff2012-01-09 18:58:16 +00004785#ifndef NDEBUG
4786 Rewriter.setDebugType(DEBUG_TYPE);
4787#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00004788 Rewriter.disableCanonicalMode();
Andrew Trick7fb669a2011-10-07 23:46:21 +00004789 Rewriter.enableLSRMode();
Dan Gohman45774ce2010-02-12 10:34:29 +00004790 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
4791
Andrew Trickd5d2db92012-01-10 01:45:08 +00004792 // Mark phi nodes that terminate chains so the expander tries to reuse them.
Craig Topper77b99412015-05-23 08:01:41 +00004793 for (const IVChain &Chain : IVChainVec) {
4794 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
Andrew Trickd5d2db92012-01-10 01:45:08 +00004795 Rewriter.setChainedPhi(PN);
4796 }
4797
Dan Gohman45774ce2010-02-12 10:34:29 +00004798 // Expand the new value definitions and update the users.
Jonas Paulsson7a794222016-08-17 13:24:19 +00004799 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
4800 for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
4801 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
4802 Changed = true;
4803 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004804
Craig Topper77b99412015-05-23 08:01:41 +00004805 for (const IVChain &Chain : IVChainVec) {
4806 GenerateIVChain(Chain, Rewriter, DeadInsts);
Andrew Trick248d4102012-01-09 21:18:52 +00004807 Changed = true;
4808 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004809 // Clean up after ourselves. This must be done before deleting any
4810 // instructions.
4811 Rewriter.clear();
4812
4813 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
4814}
4815
Justin Bogner843fb202015-12-15 19:40:57 +00004816LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,
4817 DominatorTree &DT, LoopInfo &LI,
4818 const TargetTransformInfo &TTI)
4819 : IU(IU), SE(SE), DT(DT), LI(LI), TTI(TTI), L(L), Changed(false),
4820 IVIncInsertPos(nullptr) {
Dan Gohmana83ac2d2009-11-05 21:11:53 +00004821 // If LoopSimplify form is not available, stay out of trouble.
Andrew Trick732ad802012-01-07 03:16:50 +00004822 if (!L->isLoopSimplifyForm())
4823 return;
Dan Gohmana83ac2d2009-11-05 21:11:53 +00004824
Andrew Trick070e5402012-03-16 03:16:56 +00004825 // If there's no interesting work to be done, bail early.
4826 if (IU.empty()) return;
4827
Andrew Trick19f80c12012-04-18 04:00:10 +00004828 // If there's too much analysis to be done, bail early. We won't be able to
4829 // model the problem anyway.
4830 unsigned NumUsers = 0;
Craig Topper77b99412015-05-23 08:01:41 +00004831 for (const IVStrideUse &U : IU) {
Andrew Trick19f80c12012-04-18 04:00:10 +00004832 if (++NumUsers > MaxIVUsers) {
Craig Topper37d0d862015-05-23 08:20:33 +00004833 (void)U;
Craig Topper77b99412015-05-23 08:01:41 +00004834 DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
Andrew Trick19f80c12012-04-18 04:00:10 +00004835 return;
4836 }
David Majnemera53b5bb2016-02-03 21:30:34 +00004837 // Bail out if we have a PHI on an EHPad that gets a value from a
4838 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is
4839 // no good place to stick any instructions.
4840 if (auto *PN = dyn_cast<PHINode>(U.getUser())) {
4841 auto *FirstNonPHI = PN->getParent()->getFirstNonPHI();
4842 if (isa<FuncletPadInst>(FirstNonPHI) ||
4843 isa<CatchSwitchInst>(FirstNonPHI))
4844 for (BasicBlock *PredBB : PN->blocks())
4845 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
4846 return;
4847 }
Andrew Trick19f80c12012-04-18 04:00:10 +00004848 }
4849
Andrew Trick070e5402012-03-16 03:16:56 +00004850#ifndef NDEBUG
Andrew Trick12728f02012-01-17 06:45:52 +00004851 // All dominating loops must have preheaders, or SCEVExpander may not be able
4852 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
4853 //
Andrew Trick070e5402012-03-16 03:16:56 +00004854 // IVUsers analysis should only create users that are dominated by simple loop
4855 // headers. Since this loop should dominate all of its users, its user list
4856 // should be empty if this loop itself is not within a simple loop nest.
Andrew Trick12728f02012-01-17 06:45:52 +00004857 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
4858 Rung; Rung = Rung->getIDom()) {
4859 BasicBlock *BB = Rung->getBlock();
4860 const Loop *DomLoop = LI.getLoopFor(BB);
4861 if (DomLoop && DomLoop->getHeader() == BB) {
Andrew Trick070e5402012-03-16 03:16:56 +00004862 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
Andrew Trick12728f02012-01-17 06:45:52 +00004863 }
Andrew Trick732ad802012-01-07 03:16:50 +00004864 }
Andrew Trick070e5402012-03-16 03:16:56 +00004865#endif // DEBUG
Dan Gohman85875f72009-03-09 20:34:59 +00004866
Dan Gohman45774ce2010-02-12 10:34:29 +00004867 DEBUG(dbgs() << "\nLSR on loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004868 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00004869 dbgs() << ":\n");
Dan Gohmane201f8f2009-03-09 20:46:50 +00004870
Dan Gohman927bcaa2010-05-20 20:33:18 +00004871 // First, perform some low-level loop optimizations.
Dan Gohman45774ce2010-02-12 10:34:29 +00004872 OptimizeShadowIV();
Dan Gohman4c4043c2010-05-20 20:05:31 +00004873 OptimizeLoopTermCond();
Evan Cheng78a4eb82009-05-11 22:33:01 +00004874
Andrew Trick8acb4342011-07-21 00:40:04 +00004875 // If loop preparation eliminates all interesting IV users, bail.
4876 if (IU.empty()) return;
4877
Andrew Trick168dfff2011-09-29 01:53:08 +00004878 // Skip nested loops until we can model them better with formulae.
Andrew Trickd97b83e2012-03-22 22:42:45 +00004879 if (!L->empty()) {
Andrew Trickbc6de902011-09-29 01:33:38 +00004880 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
Andrew Trick168dfff2011-09-29 01:53:08 +00004881 return;
Andrew Trickbc6de902011-09-29 01:33:38 +00004882 }
4883
Dan Gohman927bcaa2010-05-20 20:33:18 +00004884 // Start collecting data and preparing for the solver.
Andrew Trick29fe5f02012-01-09 19:50:34 +00004885 CollectChains();
Dan Gohman45774ce2010-02-12 10:34:29 +00004886 CollectInterestingTypesAndFactors();
4887 CollectFixupsAndInitialFormulae();
4888 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00004889
Andrew Trick248d4102012-01-09 21:18:52 +00004890 assert(!Uses.empty() && "IVUsers reported at least one use");
Dan Gohman45774ce2010-02-12 10:34:29 +00004891 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
4892 print_uses(dbgs()));
Misha Brukmanb1c93172005-04-21 23:48:37 +00004893
Dan Gohman45774ce2010-02-12 10:34:29 +00004894 // Now use the reuse data to generate a bunch of interesting ways
4895 // to formulate the values needed for the uses.
4896 GenerateAllReuseFormulae();
Evan Cheng3df447d2006-03-16 21:53:05 +00004897
Dan Gohman45774ce2010-02-12 10:34:29 +00004898 FilterOutUndesirableDedicatedRegisters();
4899 NarrowSearchSpaceUsingHeuristics();
Dan Gohman92c36962009-12-18 00:06:20 +00004900
Dan Gohman45774ce2010-02-12 10:34:29 +00004901 SmallVector<const Formula *, 8> Solution;
4902 Solve(Solution);
Dan Gohman92c36962009-12-18 00:06:20 +00004903
Dan Gohman45774ce2010-02-12 10:34:29 +00004904 // Release memory that is no longer needed.
4905 Factors.clear();
4906 Types.clear();
4907 RegUses.clear();
4908
Andrew Trick58124392011-09-27 00:44:14 +00004909 if (Solution.empty())
4910 return;
4911
Dan Gohman45774ce2010-02-12 10:34:29 +00004912#ifndef NDEBUG
4913 // Formulae should be legal.
Craig Topper77b99412015-05-23 08:01:41 +00004914 for (const LSRUse &LU : Uses) {
4915 for (const Formula &F : LU.Formulae)
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004916 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
Craig Topper77b99412015-05-23 08:01:41 +00004917 F) && "Illegal formula generated!");
Dan Gohman45774ce2010-02-12 10:34:29 +00004918 };
4919#endif
4920
4921 // Now that we've decided what we want, make it so.
Justin Bogner843fb202015-12-15 19:40:57 +00004922 ImplementSolution(Solution);
Dan Gohman45774ce2010-02-12 10:34:29 +00004923}
4924
4925void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
4926 if (Factors.empty() && Types.empty()) return;
4927
4928 OS << "LSR has identified the following interesting factors and types: ";
4929 bool First = true;
4930
Craig Topper10949ae2015-05-23 08:45:10 +00004931 for (int64_t Factor : Factors) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004932 if (!First) OS << ", ";
4933 First = false;
Craig Topper10949ae2015-05-23 08:45:10 +00004934 OS << '*' << Factor;
Evan Cheng87fe40b2009-11-10 21:14:05 +00004935 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00004936
Craig Topper10949ae2015-05-23 08:45:10 +00004937 for (Type *Ty : Types) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004938 if (!First) OS << ", ";
4939 First = false;
Craig Topper10949ae2015-05-23 08:45:10 +00004940 OS << '(' << *Ty << ')';
Dan Gohman45774ce2010-02-12 10:34:29 +00004941 }
4942 OS << '\n';
4943}
4944
4945void LSRInstance::print_fixups(raw_ostream &OS) const {
4946 OS << "LSR is examining the following fixup sites:\n";
Jonas Paulsson7a794222016-08-17 13:24:19 +00004947 for (const LSRUse &LU : Uses)
4948 for (const LSRFixup &LF : LU.Fixups) {
4949 dbgs() << " ";
4950 LF.print(OS);
4951 OS << '\n';
4952 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004953}
4954
4955void LSRInstance::print_uses(raw_ostream &OS) const {
4956 OS << "LSR is examining the following uses:\n";
Craig Topper77b99412015-05-23 08:01:41 +00004957 for (const LSRUse &LU : Uses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004958 dbgs() << " ";
4959 LU.print(OS);
4960 OS << '\n';
Craig Topper77b99412015-05-23 08:01:41 +00004961 for (const Formula &F : LU.Formulae) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004962 OS << " ";
Craig Topper77b99412015-05-23 08:01:41 +00004963 F.print(OS);
Dan Gohman45774ce2010-02-12 10:34:29 +00004964 OS << '\n';
4965 }
4966 }
4967}
4968
4969void LSRInstance::print(raw_ostream &OS) const {
4970 print_factors_and_types(OS);
4971 print_fixups(OS);
4972 print_uses(OS);
4973}
4974
Davide Italiano945d05f2015-11-23 02:47:30 +00004975LLVM_DUMP_METHOD
Dan Gohman45774ce2010-02-12 10:34:29 +00004976void LSRInstance::dump() const {
4977 print(errs()); errs() << '\n';
4978}
4979
4980namespace {
4981
4982class LoopStrengthReduce : public LoopPass {
Dan Gohman45774ce2010-02-12 10:34:29 +00004983public:
4984 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004985
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004986 LoopStrengthReduce();
Dan Gohman45774ce2010-02-12 10:34:29 +00004987
4988private:
Craig Topper3e4c6972014-03-05 09:10:37 +00004989 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
4990 void getAnalysisUsage(AnalysisUsage &AU) const override;
Dan Gohman45774ce2010-02-12 10:34:29 +00004991};
Dan Gohman45774ce2010-02-12 10:34:29 +00004992
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004993} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00004994
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004995LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
4996 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
4997}
Dan Gohman45774ce2010-02-12 10:34:29 +00004998
4999void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
5000 // We split critical edges, so we change the CFG. However, we do update
5001 // many analyses if they are around.
Eric Christopherda6bd452011-02-10 01:48:24 +00005002 AU.addPreservedID(LoopSimplifyID);
Dan Gohman45774ce2010-02-12 10:34:29 +00005003
Chandler Carruth4f8f3072015-01-17 14:16:18 +00005004 AU.addRequired<LoopInfoWrapperPass>();
5005 AU.addPreserved<LoopInfoWrapperPass>();
Eric Christopherda6bd452011-02-10 01:48:24 +00005006 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth73523022014-01-13 13:07:17 +00005007 AU.addRequired<DominatorTreeWrapperPass>();
5008 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005009 AU.addRequired<ScalarEvolutionWrapperPass>();
5010 AU.addPreserved<ScalarEvolutionWrapperPass>();
Cameron Zwarich97dae4d2011-02-10 23:53:14 +00005011 // Requiring LoopSimplify a second time here prevents IVUsers from running
5012 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5013 AU.addRequiredID(LoopSimplifyID);
Dehao Chen1a444522016-07-16 22:51:33 +00005014 AU.addRequired<IVUsersWrapperPass>();
5015 AU.addPreserved<IVUsersWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00005016 AU.addRequired<TargetTransformInfoWrapperPass>();
Dan Gohman45774ce2010-02-12 10:34:29 +00005017}
5018
Dehao Chen6132ee82016-07-18 21:41:50 +00005019static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5020 DominatorTree &DT, LoopInfo &LI,
5021 const TargetTransformInfo &TTI) {
Dan Gohman45774ce2010-02-12 10:34:29 +00005022 bool Changed = false;
5023
5024 // Run the main LSR transformation.
Justin Bogner843fb202015-12-15 19:40:57 +00005025 Changed |= LSRInstance(L, IU, SE, DT, LI, TTI).getChanged();
Dan Gohman45774ce2010-02-12 10:34:29 +00005026
Andrew Trick2ec61a82012-01-07 01:36:44 +00005027 // Remove any extra phis created by processing inner loops.
Dan Gohmanb5358002010-01-05 16:31:45 +00005028 Changed |= DeleteDeadPHIs(L->getHeader());
Andrew Trickf950ce82013-01-06 05:59:39 +00005029 if (EnablePhiElim && L->isLoopSimplifyForm()) {
Andrew Trick2ec61a82012-01-07 01:36:44 +00005030 SmallVector<WeakVH, 16> DeadInsts;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005031 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Dehao Chen6132ee82016-07-18 21:41:50 +00005032 SCEVExpander Rewriter(SE, DL, "lsr");
Andrew Trick2ec61a82012-01-07 01:36:44 +00005033#ifndef NDEBUG
5034 Rewriter.setDebugType(DEBUG_TYPE);
5035#endif
Dehao Chen6132ee82016-07-18 21:41:50 +00005036 unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI);
Andrew Trick2ec61a82012-01-07 01:36:44 +00005037 if (numFolded) {
5038 Changed = true;
5039 DeleteTriviallyDeadInstructions(DeadInsts);
5040 DeleteDeadPHIs(L->getHeader());
5041 }
5042 }
Evan Cheng03001cb2008-07-07 19:51:32 +00005043 return Changed;
Nate Begemanb18121e2004-10-18 21:08:22 +00005044}
Dehao Chen6132ee82016-07-18 21:41:50 +00005045
5046bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
5047 if (skipLoop(L))
5048 return false;
5049
5050 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5051 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5052 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5053 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5054 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5055 *L->getHeader()->getParent());
5056 return ReduceLoopStrength(L, IU, SE, DT, LI, TTI);
5057}
5058
Chandler Carruth410eaeb2017-01-11 06:23:21 +00005059PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,
5060 LoopStandardAnalysisResults &AR,
5061 LPMUpdater &) {
5062 if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE,
5063 AR.DT, AR.LI, AR.TTI))
Dehao Chen6132ee82016-07-18 21:41:50 +00005064 return PreservedAnalyses::all();
5065
5066 return getLoopPassPreservedAnalyses();
5067}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005068
5069char LoopStrengthReduce::ID = 0;
5070INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
5071 "Loop Strength Reduction", false, false)
5072INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5073INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5074INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5075INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass)
5076INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5077INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5078INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
5079 "Loop Strength Reduction", false, false)
5080
5081Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }