blob: 73436f13c94e40f8c3b34dc98c843a9353da7833 [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
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +0000132// The flag adds instruction count to solutions cost comparision.
133static cl::opt<bool> InsnsCost(
Hans Wennborgca69fc12017-06-19 17:57:15 +0000134 "lsr-insns-cost", cl::Hidden, cl::init(false),
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +0000135 cl::desc("Add instruction count to a LSR cost model"));
136
Evgeny Stupachenko9909872e302017-02-21 07:34:40 +0000137// Flag to choose how to narrow complex lsr solution
138static cl::opt<bool> LSRExpNarrow(
Evgeny Stupachenkod6aa0d02017-03-04 03:14:05 +0000139 "lsr-exp-narrow", cl::Hidden, cl::init(false),
Evgeny Stupachenko9909872e302017-02-21 07:34:40 +0000140 cl::desc("Narrow LSR complex solution using"
141 " expectation of registers number"));
142
Andrew Trick248d4102012-01-09 21:18:52 +0000143#ifndef NDEBUG
144// Stress test IV chain generation.
145static cl::opt<bool> StressIVChain(
146 "stress-ivchain", cl::Hidden, cl::init(false),
147 cl::desc("Stress test LSR IV chains"));
148#else
149static bool StressIVChain = false;
150#endif
151
Dan Gohman45774ce2010-02-12 10:34:29 +0000152namespace {
Nate Begemanb18121e2004-10-18 21:08:22 +0000153
Matt Arsenault427a0fd2015-08-15 00:53:06 +0000154struct MemAccessTy {
155 /// Used in situations where the accessed memory type is unknown.
156 static const unsigned UnknownAddressSpace = ~0u;
157
158 Type *MemTy;
159 unsigned AddrSpace;
160
161 MemAccessTy() : MemTy(nullptr), AddrSpace(UnknownAddressSpace) {}
162
163 MemAccessTy(Type *Ty, unsigned AS) :
164 MemTy(Ty), AddrSpace(AS) {}
165
166 bool operator==(MemAccessTy Other) const {
167 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
168 }
169
170 bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
171
Matt Arsenault1f2ca662017-01-30 19:50:17 +0000172 static MemAccessTy getUnknown(LLVMContext &Ctx,
173 unsigned AS = UnknownAddressSpace) {
174 return MemAccessTy(Type::getVoidTy(Ctx), AS);
Matt Arsenault427a0fd2015-08-15 00:53:06 +0000175 }
176};
177
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000178/// This class holds data which is used to order reuse candidates.
Dan Gohman45774ce2010-02-12 10:34:29 +0000179class RegSortData {
180public:
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000181 /// This represents the set of LSRUse indices which reference
Dan Gohman45774ce2010-02-12 10:34:29 +0000182 /// a particular register.
183 SmallBitVector UsedByIndices;
184
Dan Gohman45774ce2010-02-12 10:34:29 +0000185 void print(raw_ostream &OS) const;
186 void dump() const;
187};
188
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000189} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +0000190
191void RegSortData::print(raw_ostream &OS) const {
192 OS << "[NumUses=" << UsedByIndices.count() << ']';
193}
194
Matthias Braun8c209aa2017-01-28 02:02:38 +0000195#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
196LLVM_DUMP_METHOD void RegSortData::dump() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000197 print(errs()); errs() << '\n';
198}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000199#endif
Dan Gohman2a12ae72009-02-20 04:17:46 +0000200
Chris Lattner79a42ac2006-12-19 21:40:18 +0000201namespace {
Dale Johannesene3a02be2007-03-20 00:47:50 +0000202
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000203/// Map register candidates to information about how they are used.
Dan Gohman45774ce2010-02-12 10:34:29 +0000204class RegUseTracker {
205 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
Dale Johannesene3a02be2007-03-20 00:47:50 +0000206
Dan Gohman248c41d2010-05-18 22:33:00 +0000207 RegUsesTy RegUsesMap;
Dan Gohman45774ce2010-02-12 10:34:29 +0000208 SmallVector<const SCEV *, 16> RegSequence;
Evan Cheng3df447d2006-03-16 21:53:05 +0000209
Dan Gohman45774ce2010-02-12 10:34:29 +0000210public:
Sanjoy Das302bfd02015-08-16 18:22:43 +0000211 void countRegister(const SCEV *Reg, size_t LUIdx);
212 void dropRegister(const SCEV *Reg, size_t LUIdx);
213 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000214
Dan Gohman45774ce2010-02-12 10:34:29 +0000215 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000216
Dan Gohman45774ce2010-02-12 10:34:29 +0000217 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000218
Dan Gohman45774ce2010-02-12 10:34:29 +0000219 void clear();
Dan Gohman51ad99d2010-01-21 02:09:26 +0000220
Dan Gohman45774ce2010-02-12 10:34:29 +0000221 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
222 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
223 iterator begin() { return RegSequence.begin(); }
224 iterator end() { return RegSequence.end(); }
225 const_iterator begin() const { return RegSequence.begin(); }
226 const_iterator end() const { return RegSequence.end(); }
227};
Dan Gohman51ad99d2010-01-21 02:09:26 +0000228
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000229} // end anonymous namespace
Dan Gohman51ad99d2010-01-21 02:09:26 +0000230
Dan Gohman45774ce2010-02-12 10:34:29 +0000231void
Sanjoy Das302bfd02015-08-16 18:22:43 +0000232RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000233 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman248c41d2010-05-18 22:33:00 +0000234 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman45774ce2010-02-12 10:34:29 +0000235 RegSortData &RSD = Pair.first->second;
236 if (Pair.second)
237 RegSequence.push_back(Reg);
238 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
239 RSD.UsedByIndices.set(LUIdx);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000240}
241
Dan Gohman4cf99b52010-05-18 23:42:37 +0000242void
Sanjoy Das302bfd02015-08-16 18:22:43 +0000243RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
Dan Gohman4cf99b52010-05-18 23:42:37 +0000244 RegUsesTy::iterator It = RegUsesMap.find(Reg);
245 assert(It != RegUsesMap.end());
246 RegSortData &RSD = It->second;
247 assert(RSD.UsedByIndices.size() > LUIdx);
248 RSD.UsedByIndices.reset(LUIdx);
249}
250
Dan Gohman20fab452010-05-19 23:43:12 +0000251void
Sanjoy Das302bfd02015-08-16 18:22:43 +0000252RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
Dan Gohmana7b68d62010-10-07 23:33:43 +0000253 assert(LUIdx <= LastLUIdx);
254
255 // Update RegUses. The data structure is not optimized for this purpose;
256 // we must iterate through it and update each of the bit vectors.
Craig Topper10949ae2015-05-23 08:45:10 +0000257 for (auto &Pair : RegUsesMap) {
258 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
Dan Gohmana7b68d62010-10-07 23:33:43 +0000259 if (LUIdx < UsedByIndices.size())
260 UsedByIndices[LUIdx] =
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000261 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
Dan Gohmana7b68d62010-10-07 23:33:43 +0000262 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
263 }
Dan Gohman20fab452010-05-19 23:43:12 +0000264}
265
Dan Gohman45774ce2010-02-12 10:34:29 +0000266bool
267RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman4f13bbf2010-08-29 15:18:49 +0000268 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
269 if (I == RegUsesMap.end())
270 return false;
271 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
Dan Gohman45774ce2010-02-12 10:34:29 +0000272 int i = UsedByIndices.find_first();
273 if (i == -1) return false;
274 if ((size_t)i != LUIdx) return true;
275 return UsedByIndices.find_next(i) != -1;
276}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000277
Dan Gohman45774ce2010-02-12 10:34:29 +0000278const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman248c41d2010-05-18 22:33:00 +0000279 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
280 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman45774ce2010-02-12 10:34:29 +0000281 return I->second.UsedByIndices;
282}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000283
Dan Gohman45774ce2010-02-12 10:34:29 +0000284void RegUseTracker::clear() {
Dan Gohman248c41d2010-05-18 22:33:00 +0000285 RegUsesMap.clear();
Dan Gohman45774ce2010-02-12 10:34:29 +0000286 RegSequence.clear();
287}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000288
Dan Gohman45774ce2010-02-12 10:34:29 +0000289namespace {
290
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000291/// This class holds information that describes a formula for computing
292/// satisfying a use. It may include broken-out immediates and scaled registers.
Dan Gohman45774ce2010-02-12 10:34:29 +0000293struct Formula {
Chandler Carruth6e479322013-01-07 15:04:40 +0000294 /// Global base address used for complex addressing.
295 GlobalValue *BaseGV;
296
297 /// Base offset for complex addressing.
298 int64_t BaseOffset;
299
300 /// Whether any complex addressing has a base register.
301 bool HasBaseReg;
302
303 /// The scale of any complex addressing.
304 int64_t Scale;
Dan Gohman45774ce2010-02-12 10:34:29 +0000305
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000306 /// The list of "base" registers for this use. When this is non-empty. The
307 /// canonical representation of a formula is
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000308 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
309 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
Wei Mi74d5a902017-02-22 21:47:08 +0000310 /// 3. The reg containing recurrent expr related with currect loop in the
311 /// formula should be put in the ScaledReg.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000312 /// #1 enforces that the scaled register is always used when at least two
313 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
314 /// #2 enforces that 1 * reg is reg.
Wei Mi74d5a902017-02-22 21:47:08 +0000315 /// #3 ensures invariant regs with respect to current loop can be combined
316 /// together in LSR codegen.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000317 /// This invariant can be temporarly broken while building a formula.
318 /// However, every formula inserted into the LSRInstance must be in canonical
319 /// form.
Preston Gurd25c3b6a2013-02-01 20:41:27 +0000320 SmallVector<const SCEV *, 4> BaseRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +0000321
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000322 /// The 'scaled' register for this use. This should be non-null when Scale is
323 /// not zero.
Dan Gohman45774ce2010-02-12 10:34:29 +0000324 const SCEV *ScaledReg;
325
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000326 /// An additional constant offset which added near the use. This requires a
327 /// temporary register, but the offset itself can live in an add immediate
328 /// field rather than a register.
Dan Gohman6136e942011-05-03 00:46:49 +0000329 int64_t UnfoldedOffset;
330
Chandler Carruth6e479322013-01-07 15:04:40 +0000331 Formula()
Craig Topperf40110f2014-04-25 05:29:35 +0000332 : BaseGV(nullptr), BaseOffset(0), HasBaseReg(false), Scale(0),
Sanjoy Das215df9e2015-08-04 01:52:05 +0000333 ScaledReg(nullptr), UnfoldedOffset(0) {}
Dan Gohman45774ce2010-02-12 10:34:29 +0000334
Sanjoy Das302bfd02015-08-16 18:22:43 +0000335 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000336
Wei Mi74d5a902017-02-22 21:47:08 +0000337 bool isCanonical(const Loop &L) const;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000338
Wei Mi74d5a902017-02-22 21:47:08 +0000339 void canonicalize(const Loop &L);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000340
Sanjoy Das302bfd02015-08-16 18:22:43 +0000341 bool unscale();
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000342
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +0000343 bool hasZeroEnd() const;
344
Adam Nemetdeab6f92014-04-29 18:25:28 +0000345 size_t getNumRegs() const;
Chris Lattner229907c2011-07-18 04:54:35 +0000346 Type *getType() const;
Dan Gohman45774ce2010-02-12 10:34:29 +0000347
Sanjoy Das302bfd02015-08-16 18:22:43 +0000348 void deleteBaseReg(const SCEV *&S);
Dan Gohman80a96082010-05-20 15:17:54 +0000349
Dan Gohman45774ce2010-02-12 10:34:29 +0000350 bool referencesReg(const SCEV *S) const;
351 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
352 const RegUseTracker &RegUses) const;
353
354 void print(raw_ostream &OS) const;
355 void dump() const;
356};
357
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000358} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +0000359
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000360/// Recursion helper for initialMatch.
Dan Gohman45774ce2010-02-12 10:34:29 +0000361static void DoInitialMatch(const SCEV *S, Loop *L,
362 SmallVectorImpl<const SCEV *> &Good,
363 SmallVectorImpl<const SCEV *> &Bad,
Dan Gohman20d9ce22010-11-17 21:41:58 +0000364 ScalarEvolution &SE) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000365 // Collect expressions which properly dominate the loop header.
Dan Gohman20d9ce22010-11-17 21:41:58 +0000366 if (SE.properlyDominates(S, L->getHeader())) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000367 Good.push_back(S);
368 return;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000369 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000370
371 // Look at add operands.
372 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Craig Topper77b99412015-05-23 08:01:41 +0000373 for (const SCEV *S : Add->operands())
374 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000375 return;
376 }
377
378 // Look at addrec operands.
379 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
Alexandros Lamprineas0ee3ec22016-11-09 08:53:07 +0000380 if (!AR->getStart()->isZero() && AR->isAffine()) {
Dan Gohman20d9ce22010-11-17 21:41:58 +0000381 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000382 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman45774ce2010-02-12 10:34:29 +0000383 AR->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000384 // FIXME: AR->getNoWrapFlags()
385 AR->getLoop(), SCEV::FlagAnyWrap),
Dan Gohman20d9ce22010-11-17 21:41:58 +0000386 L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000387 return;
388 }
389
390 // Handle a multiplication by -1 (negation) if it didn't fold.
391 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
392 if (Mul->getOperand(0)->isAllOnesValue()) {
393 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
394 const SCEV *NewMul = SE.getMulExpr(Ops);
395
396 SmallVector<const SCEV *, 4> MyGood;
397 SmallVector<const SCEV *, 4> MyBad;
Dan Gohman20d9ce22010-11-17 21:41:58 +0000398 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000399 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
400 SE.getEffectiveSCEVType(NewMul->getType())));
Craig Topper042a3922015-05-25 20:01:18 +0000401 for (const SCEV *S : MyGood)
402 Good.push_back(SE.getMulExpr(NegOne, S));
403 for (const SCEV *S : MyBad)
404 Bad.push_back(SE.getMulExpr(NegOne, S));
Dan Gohman45774ce2010-02-12 10:34:29 +0000405 return;
406 }
407
408 // Ok, we can't do anything interesting. Just stuff the whole thing into a
409 // register and hope for the best.
410 Bad.push_back(S);
411}
412
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000413/// Incorporate loop-variant parts of S into this Formula, attempting to keep
414/// all loop-invariant and loop-computable values in a single base register.
Sanjoy Das302bfd02015-08-16 18:22:43 +0000415void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000416 SmallVector<const SCEV *, 4> Good;
417 SmallVector<const SCEV *, 4> Bad;
Dan Gohman20d9ce22010-11-17 21:41:58 +0000418 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000419 if (!Good.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000420 const SCEV *Sum = SE.getAddExpr(Good);
421 if (!Sum->isZero())
422 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000423 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000424 }
425 if (!Bad.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000426 const SCEV *Sum = SE.getAddExpr(Bad);
427 if (!Sum->isZero())
428 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000429 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000430 }
Wei Mi74d5a902017-02-22 21:47:08 +0000431 canonicalize(*L);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000432}
433
434/// \brief Check whether or not this formula statisfies the canonical
435/// representation.
436/// \see Formula::BaseRegs.
Wei Mi74d5a902017-02-22 21:47:08 +0000437bool Formula::isCanonical(const Loop &L) const {
438 if (!ScaledReg)
439 return BaseRegs.size() <= 1;
440
441 if (Scale != 1)
442 return true;
443
444 if (Scale == 1 && BaseRegs.empty())
445 return false;
446
447 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
448 if (SAR && SAR->getLoop() == &L)
449 return true;
450
451 // If ScaledReg is not a recurrent expr, or it is but its loop is not current
452 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
453 // loop, we want to swap the reg in BaseRegs with ScaledReg.
454 auto I =
455 find_if(make_range(BaseRegs.begin(), BaseRegs.end()), [&](const SCEV *S) {
456 return isa<const SCEVAddRecExpr>(S) &&
457 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
458 });
459 return I == BaseRegs.end();
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000460}
461
462/// \brief Helper method to morph a formula into its canonical representation.
463/// \see Formula::BaseRegs.
464/// Every formula having more than one base register, must use the ScaledReg
465/// field. Otherwise, we would have to do special cases everywhere in LSR
466/// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
467/// On the other hand, 1*reg should be canonicalized into reg.
Wei Mi74d5a902017-02-22 21:47:08 +0000468void Formula::canonicalize(const Loop &L) {
469 if (isCanonical(L))
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000470 return;
471 // So far we did not need this case. This is easy to implement but it is
472 // useless to maintain dead code. Beside it could hurt compile time.
473 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
Wei Mi74d5a902017-02-22 21:47:08 +0000474
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000475 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
Wei Mi74d5a902017-02-22 21:47:08 +0000476 if (!ScaledReg) {
477 ScaledReg = BaseRegs.back();
478 BaseRegs.pop_back();
479 Scale = 1;
480 }
481
482 // If ScaledReg is an invariant with respect to L, find the reg from
483 // BaseRegs containing the recurrent expr related with Loop L. Swap the
484 // reg with ScaledReg.
485 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
486 if (!SAR || SAR->getLoop() != &L) {
487 auto I = find_if(make_range(BaseRegs.begin(), BaseRegs.end()),
488 [&](const SCEV *S) {
489 return isa<const SCEVAddRecExpr>(S) &&
490 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
491 });
492 if (I != BaseRegs.end())
493 std::swap(ScaledReg, *I);
494 }
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000495}
496
497/// \brief Get rid of the scale in the formula.
498/// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
499/// \return true if it was possible to get rid of the scale, false otherwise.
500/// \note After this operation the formula may not be in the canonical form.
Sanjoy Das302bfd02015-08-16 18:22:43 +0000501bool Formula::unscale() {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000502 if (Scale != 1)
503 return false;
504 Scale = 0;
505 BaseRegs.push_back(ScaledReg);
506 ScaledReg = nullptr;
507 return true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000508}
509
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +0000510bool Formula::hasZeroEnd() const {
511 if (UnfoldedOffset || BaseOffset)
512 return false;
513 if (BaseRegs.size() != 1 || ScaledReg)
514 return false;
515 return true;
516}
517
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000518/// Return the total number of register operands used by this formula. This does
519/// not include register uses implied by non-constant addrec strides.
Adam Nemetdeab6f92014-04-29 18:25:28 +0000520size_t Formula::getNumRegs() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000521 return !!ScaledReg + BaseRegs.size();
522}
523
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000524/// Return the type of this formula, if it has one, or null otherwise. This type
525/// is meaningless except for the bit size.
Chris Lattner229907c2011-07-18 04:54:35 +0000526Type *Formula::getType() const {
Sanjoy Das215df9e2015-08-04 01:52:05 +0000527 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
528 ScaledReg ? ScaledReg->getType() :
529 BaseGV ? BaseGV->getType() :
530 nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000531}
532
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000533/// Delete the given base reg from the BaseRegs list.
Sanjoy Das302bfd02015-08-16 18:22:43 +0000534void Formula::deleteBaseReg(const SCEV *&S) {
Dan Gohman80a96082010-05-20 15:17:54 +0000535 if (&S != &BaseRegs.back())
536 std::swap(S, BaseRegs.back());
537 BaseRegs.pop_back();
538}
539
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000540/// Test if this formula references the given register.
Dan Gohman45774ce2010-02-12 10:34:29 +0000541bool Formula::referencesReg(const SCEV *S) const {
David Majnemer0d955d02016-08-11 22:21:41 +0000542 return S == ScaledReg || is_contained(BaseRegs, S);
Dan Gohman45774ce2010-02-12 10:34:29 +0000543}
544
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000545/// Test whether this formula uses registers which are used by uses other than
546/// the use with the given index.
Dan Gohman45774ce2010-02-12 10:34:29 +0000547bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
548 const RegUseTracker &RegUses) const {
549 if (ScaledReg)
550 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
551 return true;
Craig Topper042a3922015-05-25 20:01:18 +0000552 for (const SCEV *BaseReg : BaseRegs)
553 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
Dan Gohman45774ce2010-02-12 10:34:29 +0000554 return true;
555 return false;
556}
557
558void Formula::print(raw_ostream &OS) const {
559 bool First = true;
Chandler Carruth6e479322013-01-07 15:04:40 +0000560 if (BaseGV) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000561 if (!First) OS << " + "; else First = false;
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000562 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +0000563 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000564 if (BaseOffset != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000565 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000566 OS << BaseOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +0000567 }
Craig Topper042a3922015-05-25 20:01:18 +0000568 for (const SCEV *BaseReg : BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000569 if (!First) OS << " + "; else First = false;
Sanjoy Das215df9e2015-08-04 01:52:05 +0000570 OS << "reg(" << *BaseReg << ')';
Dan Gohman45774ce2010-02-12 10:34:29 +0000571 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000572 if (HasBaseReg && BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000573 if (!First) OS << " + "; else First = false;
574 OS << "**error: HasBaseReg**";
Chandler Carruth6e479322013-01-07 15:04:40 +0000575 } else if (!HasBaseReg && !BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000576 if (!First) OS << " + "; else First = false;
577 OS << "**error: !HasBaseReg**";
578 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000579 if (Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000580 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000581 OS << Scale << "*reg(";
Sanjoy Das215df9e2015-08-04 01:52:05 +0000582 if (ScaledReg)
583 OS << *ScaledReg;
584 else
Dan Gohman45774ce2010-02-12 10:34:29 +0000585 OS << "<unknown>";
586 OS << ')';
587 }
Dan Gohman6136e942011-05-03 00:46:49 +0000588 if (UnfoldedOffset != 0) {
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +0000589 if (!First) OS << " + ";
Dan Gohman6136e942011-05-03 00:46:49 +0000590 OS << "imm(" << UnfoldedOffset << ')';
591 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000592}
593
Matthias Braun8c209aa2017-01-28 02:02:38 +0000594#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
595LLVM_DUMP_METHOD void Formula::dump() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000596 print(errs()); errs() << '\n';
597}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000598#endif
Dan Gohman45774ce2010-02-12 10:34:29 +0000599
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000600/// Return true if the given addrec can be sign-extended without changing its
601/// value.
Dan Gohman85af2562010-02-19 19:32:49 +0000602static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000603 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000604 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000605 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
606}
607
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000608/// Return true if the given add can be sign-extended without changing its
609/// value.
Dan Gohman85af2562010-02-19 19:32:49 +0000610static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000611 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000612 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000613 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
614}
615
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000616/// Return true if the given mul can be sign-extended without changing its
617/// value.
Dan Gohmanab542222010-06-24 16:45:11 +0000618static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000619 Type *WideTy =
Dan Gohmanab542222010-06-24 16:45:11 +0000620 IntegerType::get(SE.getContext(),
621 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
622 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohman85af2562010-02-19 19:32:49 +0000623}
624
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000625/// Return an expression for LHS /s RHS, if it can be determined and if the
626/// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
627/// is true, expressions like (X * Y) /s Y are simplified to Y, ignoring that
628/// the multiplication may overflow, which is useful when the result will be
629/// used in a context where the most significant bits are ignored.
Dan Gohman4eebb942010-02-19 19:35:48 +0000630static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
631 ScalarEvolution &SE,
632 bool IgnoreSignificantBits = false) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000633 // Handle the trivial case, which works for any SCEV type.
634 if (LHS == RHS)
Dan Gohman1d2ded72010-05-03 22:09:21 +0000635 return SE.getConstant(LHS->getType(), 1);
Dan Gohman45774ce2010-02-12 10:34:29 +0000636
Dan Gohman47ddf762010-06-24 16:51:25 +0000637 // Handle a few RHS special cases.
638 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
639 if (RC) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000640 const APInt &RA = RC->getAPInt();
Dan Gohman47ddf762010-06-24 16:51:25 +0000641 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
642 // some folding.
643 if (RA.isAllOnesValue())
644 return SE.getMulExpr(LHS, RC);
645 // Handle x /s 1 as x.
646 if (RA == 1)
647 return LHS;
648 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000649
650 // Check for a division of a constant by a constant.
651 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000652 if (!RC)
Craig Topperf40110f2014-04-25 05:29:35 +0000653 return nullptr;
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000654 const APInt &LA = C->getAPInt();
655 const APInt &RA = RC->getAPInt();
Dan Gohman47ddf762010-06-24 16:51:25 +0000656 if (LA.srem(RA) != 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000657 return nullptr;
Dan Gohman47ddf762010-06-24 16:51:25 +0000658 return SE.getConstant(LA.sdiv(RA));
Dan Gohman45774ce2010-02-12 10:34:29 +0000659 }
660
Dan Gohman85af2562010-02-19 19:32:49 +0000661 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000662 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Alexandros Lamprineas0ee3ec22016-11-09 08:53:07 +0000663 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
Dan Gohman4eebb942010-02-19 19:35:48 +0000664 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
665 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000666 if (!Step) return nullptr;
Dan Gohman129a8162010-08-19 01:02:31 +0000667 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
668 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000669 if (!Start) return nullptr;
Andrew Trick8b55b732011-03-14 16:50:06 +0000670 // FlagNW is independent of the start value, step direction, and is
671 // preserved with smaller magnitude steps.
672 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
673 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman85af2562010-02-19 19:32:49 +0000674 }
Craig Topperf40110f2014-04-25 05:29:35 +0000675 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000676 }
677
Dan Gohman85af2562010-02-19 19:32:49 +0000678 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000679 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000680 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
681 SmallVector<const SCEV *, 8> Ops;
Craig Topper042a3922015-05-25 20:01:18 +0000682 for (const SCEV *S : Add->operands()) {
683 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000684 if (!Op) return nullptr;
Dan Gohman85af2562010-02-19 19:32:49 +0000685 Ops.push_back(Op);
686 }
687 return SE.getAddExpr(Ops);
Dan Gohman45774ce2010-02-12 10:34:29 +0000688 }
Craig Topperf40110f2014-04-25 05:29:35 +0000689 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000690 }
691
692 // Check for a multiply operand that we can pull RHS out of.
Dan Gohman963b1c12010-06-24 16:57:52 +0000693 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000694 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000695 SmallVector<const SCEV *, 4> Ops;
696 bool Found = false;
Craig Topper042a3922015-05-25 20:01:18 +0000697 for (const SCEV *S : Mul->operands()) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000698 if (!Found)
Dan Gohman6b733fc2010-05-20 16:23:28 +0000699 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohman4eebb942010-02-19 19:35:48 +0000700 IgnoreSignificantBits)) {
Dan Gohman6b733fc2010-05-20 16:23:28 +0000701 S = Q;
Dan Gohman45774ce2010-02-12 10:34:29 +0000702 Found = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000703 }
Dan Gohman6b733fc2010-05-20 16:23:28 +0000704 Ops.push_back(S);
Dan Gohman45774ce2010-02-12 10:34:29 +0000705 }
Craig Topperf40110f2014-04-25 05:29:35 +0000706 return Found ? SE.getMulExpr(Ops) : nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000707 }
Craig Topperf40110f2014-04-25 05:29:35 +0000708 return nullptr;
Dan Gohman963b1c12010-06-24 16:57:52 +0000709 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000710
711 // Otherwise we don't know.
Craig Topperf40110f2014-04-25 05:29:35 +0000712 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000713}
714
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000715/// If S involves the addition of a constant integer value, return that integer
716/// value, and mutate S to point to a new SCEV with that value excluded.
Dan Gohman45774ce2010-02-12 10:34:29 +0000717static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
718 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000719 if (C->getAPInt().getMinSignedBits() <= 64) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000720 S = SE.getConstant(C->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000721 return C->getValue()->getSExtValue();
722 }
723 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
724 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
725 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000726 if (Result != 0)
727 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000728 return Result;
729 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
730 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
731 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000732 if (Result != 0)
Andrew Trick8b55b732011-03-14 16:50:06 +0000733 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
734 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
735 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000736 return Result;
737 }
738 return 0;
739}
740
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000741/// If S involves the addition of a GlobalValue address, return that symbol, and
742/// mutate S to point to a new SCEV with that value excluded.
Dan Gohman45774ce2010-02-12 10:34:29 +0000743static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
744 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
745 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000746 S = SE.getConstant(GV->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000747 return GV;
748 }
749 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
750 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
751 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000752 if (Result)
753 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000754 return Result;
755 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
756 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
757 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000758 if (Result)
Andrew Trick8b55b732011-03-14 16:50:06 +0000759 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
760 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
761 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000762 return Result;
763 }
Craig Topperf40110f2014-04-25 05:29:35 +0000764 return nullptr;
Nate Begemanb18121e2004-10-18 21:08:22 +0000765}
766
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000767/// Returns true if the specified instruction is using the specified value as an
768/// address.
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000769static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
770 bool isAddress = isa<LoadInst>(Inst);
771 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Matt Arsenaultcb3fa372017-02-08 06:44:58 +0000772 if (SI->getPointerOperand() == OperandVal)
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000773 isAddress = true;
774 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
775 // Addressing modes can also be folded into prefetches and a variety
776 // of intrinsics.
777 switch (II->getIntrinsicID()) {
778 default: break;
779 case Intrinsic::prefetch:
Gabor Greif8ae30952010-06-30 09:15:28 +0000780 if (II->getArgOperand(0) == OperandVal)
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000781 isAddress = true;
782 break;
783 }
Matt Arsenaultcb3fa372017-02-08 06:44:58 +0000784 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
785 if (RMW->getPointerOperand() == OperandVal)
786 isAddress = true;
787 } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
788 if (CmpX->getPointerOperand() == OperandVal)
789 isAddress = true;
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000790 }
791 return isAddress;
792}
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000793
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000794/// Return the type of the memory being accessed.
Matt Arsenault427a0fd2015-08-15 00:53:06 +0000795static MemAccessTy getAccessType(const Instruction *Inst) {
796 MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace);
797 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
798 AccessTy.MemTy = SI->getOperand(0)->getType();
799 AccessTy.AddrSpace = SI->getPointerAddressSpace();
800 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
801 AccessTy.AddrSpace = LI->getPointerAddressSpace();
Matt Arsenaultcb3fa372017-02-08 06:44:58 +0000802 } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
803 AccessTy.AddrSpace = RMW->getPointerAddressSpace();
804 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
805 AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
Dan Gohman917ffe42009-03-09 21:01:17 +0000806 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000807
808 // All pointers have the same requirements, so canonicalize them to an
809 // arbitrary pointer type to minimize variation.
Matt Arsenault427a0fd2015-08-15 00:53:06 +0000810 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
811 AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
812 PTy->getAddressSpace());
Dan Gohman45774ce2010-02-12 10:34:29 +0000813
Dan Gohman14d13392009-05-18 16:45:28 +0000814 return AccessTy;
Dan Gohman917ffe42009-03-09 21:01:17 +0000815}
816
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000817/// Return true if this AddRec is already a phi in its loop.
Andrew Trick5df90962011-12-06 03:13:31 +0000818static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
819 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
820 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
821 if (SE.isSCEVable(PN->getType()) &&
822 (SE.getEffectiveSCEVType(PN->getType()) ==
823 SE.getEffectiveSCEVType(AR->getType())) &&
824 SE.getSCEV(PN) == AR)
825 return true;
826 }
827 return false;
828}
829
Andrew Trickd5d2db92012-01-10 01:45:08 +0000830/// Check if expanding this expression is likely to incur significant cost. This
831/// is tricky because SCEV doesn't track which expressions are actually computed
832/// by the current IR.
833///
834/// We currently allow expansion of IV increments that involve adds,
835/// multiplication by constants, and AddRecs from existing phis.
836///
837/// TODO: Allow UDivExpr if we can find an existing IV increment that is an
838/// obvious multiple of the UDivExpr.
839static bool isHighCostExpansion(const SCEV *S,
Craig Topper71b7b682014-08-21 05:55:13 +0000840 SmallPtrSetImpl<const SCEV*> &Processed,
Andrew Trickd5d2db92012-01-10 01:45:08 +0000841 ScalarEvolution &SE) {
842 // Zero/One operand expressions
843 switch (S->getSCEVType()) {
844 case scUnknown:
845 case scConstant:
846 return false;
847 case scTruncate:
848 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
849 Processed, SE);
850 case scZeroExtend:
851 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
852 Processed, SE);
853 case scSignExtend:
854 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
855 Processed, SE);
856 }
857
David Blaikie70573dc2014-11-19 07:49:26 +0000858 if (!Processed.insert(S).second)
Andrew Trickd5d2db92012-01-10 01:45:08 +0000859 return false;
860
861 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Craig Topper042a3922015-05-25 20:01:18 +0000862 for (const SCEV *S : Add->operands()) {
863 if (isHighCostExpansion(S, Processed, SE))
Andrew Trickd5d2db92012-01-10 01:45:08 +0000864 return true;
865 }
866 return false;
867 }
868
869 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
870 if (Mul->getNumOperands() == 2) {
871 // Multiplication by a constant is ok
872 if (isa<SCEVConstant>(Mul->getOperand(0)))
873 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
874
875 // If we have the value of one operand, check if an existing
876 // multiplication already generates this expression.
877 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
878 Value *UVal = U->getValue();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000879 for (User *UR : UVal->users()) {
Andrew Trick14779cc2012-03-26 20:28:37 +0000880 // If U is a constant, it may be used by a ConstantExpr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000881 Instruction *UI = dyn_cast<Instruction>(UR);
882 if (UI && UI->getOpcode() == Instruction::Mul &&
883 SE.isSCEVable(UI->getType())) {
884 return SE.getSCEV(UI) == Mul;
Andrew Trickd5d2db92012-01-10 01:45:08 +0000885 }
886 }
887 }
888 }
889 }
890
891 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
892 if (isExistingPhi(AR, SE))
893 return false;
894 }
895
896 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
897 return true;
898}
899
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000900/// If any of the instructions is the specified set are trivially dead, delete
901/// them and see if this makes any of their operands subsequently dead.
Dan Gohman45774ce2010-02-12 10:34:29 +0000902static bool
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000903DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000904 bool Changed = false;
905
906 while (!DeadInsts.empty()) {
Richard Smithad9c8e82012-08-21 20:35:14 +0000907 Value *V = DeadInsts.pop_back_val();
908 Instruction *I = dyn_cast_or_null<Instruction>(V);
Dan Gohman45774ce2010-02-12 10:34:29 +0000909
Craig Topperf40110f2014-04-25 05:29:35 +0000910 if (!I || !isInstructionTriviallyDead(I))
Dan Gohman45774ce2010-02-12 10:34:29 +0000911 continue;
912
Craig Topper042a3922015-05-25 20:01:18 +0000913 for (Use &O : I->operands())
914 if (Instruction *U = dyn_cast<Instruction>(O)) {
915 O = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000916 if (U->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000917 DeadInsts.emplace_back(U);
Dan Gohman45774ce2010-02-12 10:34:29 +0000918 }
919
920 I->eraseFromParent();
921 Changed = true;
922 }
923
924 return Changed;
925}
926
Dan Gohman045f8192010-01-22 00:46:49 +0000927namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000928
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000929class LSRUse;
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000930
931} // end anonymous namespace
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000932
933/// \brief Check if the addressing mode defined by \p F is completely
934/// folded in \p LU at isel time.
935/// This includes address-mode folding and special icmp tricks.
936/// This function returns true if \p LU can accommodate what \p F
937/// defines and up to 1 base + 1 scaled + offset.
938/// In other words, if \p F has several base registers, this function may
939/// still return true. Therefore, users still need to account for
940/// additional base registers and/or unfolded offsets to derive an
941/// accurate cost model.
942static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
943 const LSRUse &LU, const Formula &F);
Quentin Colombetbf490d42013-05-31 21:29:03 +0000944// Get the cost of the scaling factor used in F for LU.
945static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
Wei Mi74d5a902017-02-22 21:47:08 +0000946 const LSRUse &LU, const Formula &F,
947 const Loop &L);
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000948
949namespace {
Jim Grosbach60f48542009-11-17 17:53:56 +0000950
Sanjoy Das94c4aec2015-08-16 18:22:46 +0000951/// This class is used to measure and compare candidate formulae.
Dan Gohman45774ce2010-02-12 10:34:29 +0000952class Cost {
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +0000953 TargetTransformInfo::LSRCost C;
Nate Begemane68bcd12005-07-30 00:15:07 +0000954
Dan Gohman45774ce2010-02-12 10:34:29 +0000955public:
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +0000956 Cost() {
957 C.Insns = 0;
958 C.NumRegs = 0;
959 C.AddRecCost = 0;
960 C.NumIVMuls = 0;
961 C.NumBaseAdds = 0;
962 C.ImmCost = 0;
963 C.SetupCost = 0;
964 C.ScaleCost = 0;
965 }
Jim Grosbach60f48542009-11-17 17:53:56 +0000966
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +0000967 bool isLess(Cost &Other, const TargetTransformInfo &TTI);
Dan Gohman045f8192010-01-22 00:46:49 +0000968
Tim Northoverbc6659c2014-01-22 13:27:00 +0000969 void Lose();
Dan Gohman045f8192010-01-22 00:46:49 +0000970
Andrew Trick784729d2011-09-26 23:11:04 +0000971#ifndef NDEBUG
972 // Once any of the metrics loses, they must all remain losers.
973 bool isValid() {
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +0000974 return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds
975 | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)
976 || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds
977 & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);
Andrew Trick784729d2011-09-26 23:11:04 +0000978 }
979#endif
980
981 bool isLoser() {
982 assert(isValid() && "invalid cost");
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +0000983 return C.NumRegs == ~0u;
Andrew Trick784729d2011-09-26 23:11:04 +0000984 }
985
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000986 void RateFormula(const TargetTransformInfo &TTI,
987 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +0000988 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000989 const DenseSet<const SCEV *> &VisitedRegs,
990 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +0000991 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000992 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +0000993 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
Dan Gohman045f8192010-01-22 00:46:49 +0000994
Dan Gohman45774ce2010-02-12 10:34:29 +0000995 void print(raw_ostream &OS) const;
996 void dump() const;
Dan Gohman045f8192010-01-22 00:46:49 +0000997
Dan Gohman45774ce2010-02-12 10:34:29 +0000998private:
999 void RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +00001000 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +00001001 const Loop *L,
1002 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman5b18f032010-02-13 02:06:02 +00001003 void RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +00001004 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman5b18f032010-02-13 02:06:02 +00001005 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +00001006 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +00001007 SmallPtrSetImpl<const SCEV *> *LoserRegs);
Dan Gohman45774ce2010-02-12 10:34:29 +00001008};
Jonas Paulsson7a794222016-08-17 13:24:19 +00001009
1010/// An operand value in an instruction which is to be replaced with some
1011/// equivalent, possibly strength-reduced, replacement.
1012struct LSRFixup {
1013 /// The instruction which will be updated.
1014 Instruction *UserInst;
1015
1016 /// The operand of the instruction which will be replaced. The operand may be
1017 /// used more than once; every instance will be replaced.
1018 Value *OperandValToReplace;
1019
1020 /// If this user is to use the post-incremented value of an induction
1021 /// variable, this variable is non-null and holds the loop associated with the
1022 /// induction variable.
1023 PostIncLoopSet PostIncLoops;
1024
1025 /// A constant offset to be added to the LSRUse expression. This allows
1026 /// multiple fixups to share the same LSRUse with different offsets, for
1027 /// example in an unrolled loop.
1028 int64_t Offset;
1029
1030 bool isUseFullyOutsideLoop(const Loop *L) const;
1031
1032 LSRFixup();
1033
1034 void print(raw_ostream &OS) const;
1035 void dump() const;
1036};
1037
Jonas Paulsson7a794222016-08-17 13:24:19 +00001038/// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
1039/// SmallVectors of const SCEV*.
1040struct UniquifierDenseMapInfo {
1041 static SmallVector<const SCEV *, 4> getEmptyKey() {
1042 SmallVector<const SCEV *, 4> V;
1043 V.push_back(reinterpret_cast<const SCEV *>(-1));
1044 return V;
1045 }
1046
1047 static SmallVector<const SCEV *, 4> getTombstoneKey() {
1048 SmallVector<const SCEV *, 4> V;
1049 V.push_back(reinterpret_cast<const SCEV *>(-2));
1050 return V;
1051 }
1052
1053 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
1054 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1055 }
1056
1057 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1058 const SmallVector<const SCEV *, 4> &RHS) {
1059 return LHS == RHS;
1060 }
1061};
1062
1063/// This class holds the state that LSR keeps for each use in IVUsers, as well
1064/// as uses invented by LSR itself. It includes information about what kinds of
1065/// things can be folded into the user, information about the user itself, and
1066/// information about how the use may be satisfied. TODO: Represent multiple
1067/// users of the same expression in common?
1068class LSRUse {
1069 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1070
1071public:
1072 /// An enum for a kind of use, indicating what types of scaled and immediate
1073 /// operands it might support.
1074 enum KindType {
1075 Basic, ///< A normal use, with no folding.
1076 Special, ///< A special case of basic, allowing -1 scales.
1077 Address, ///< An address use; folding according to TargetLowering
1078 ICmpZero ///< An equality icmp with both operands folded into one.
1079 // TODO: Add a generic icmp too?
1080 };
1081
1082 typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
1083
1084 KindType Kind;
1085 MemAccessTy AccessTy;
1086
1087 /// The list of operands which are to be replaced.
1088 SmallVector<LSRFixup, 8> Fixups;
1089
1090 /// Keep track of the min and max offsets of the fixups.
1091 int64_t MinOffset;
1092 int64_t MaxOffset;
1093
1094 /// This records whether all of the fixups using this LSRUse are outside of
1095 /// the loop, in which case some special-case heuristics may be used.
1096 bool AllFixupsOutsideLoop;
1097
1098 /// RigidFormula is set to true to guarantee that this use will be associated
1099 /// with a single formula--the one that initially matched. Some SCEV
1100 /// expressions cannot be expanded. This allows LSR to consider the registers
1101 /// used by those expressions without the need to expand them later after
1102 /// changing the formula.
1103 bool RigidFormula;
1104
1105 /// This records the widest use type for any fixup using this
1106 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
1107 /// fixup widths to be equivalent, because the narrower one may be relying on
1108 /// the implicit truncation to truncate away bogus bits.
1109 Type *WidestFixupType;
1110
1111 /// A list of ways to build a value that can satisfy this user. After the
1112 /// list is populated, one of these is selected heuristically and used to
1113 /// formulate a replacement for OperandValToReplace in UserInst.
1114 SmallVector<Formula, 12> Formulae;
1115
1116 /// The set of register candidates used by all formulae in this LSRUse.
1117 SmallPtrSet<const SCEV *, 4> Regs;
1118
1119 LSRUse(KindType K, MemAccessTy AT)
1120 : Kind(K), AccessTy(AT), MinOffset(INT64_MAX), MaxOffset(INT64_MIN),
1121 AllFixupsOutsideLoop(true), RigidFormula(false),
1122 WidestFixupType(nullptr) {}
1123
1124 LSRFixup &getNewFixup() {
1125 Fixups.push_back(LSRFixup());
1126 return Fixups.back();
1127 }
1128
1129 void pushFixup(LSRFixup &f) {
1130 Fixups.push_back(f);
1131 if (f.Offset > MaxOffset)
1132 MaxOffset = f.Offset;
1133 if (f.Offset < MinOffset)
1134 MinOffset = f.Offset;
1135 }
1136
1137 bool HasFormulaWithSameRegs(const Formula &F) const;
Evgeny Stupachenko9909872e302017-02-21 07:34:40 +00001138 float getNotSelectedProbability(const SCEV *Reg) const;
Wei Mi74d5a902017-02-22 21:47:08 +00001139 bool InsertFormula(const Formula &F, const Loop &L);
Jonas Paulsson7a794222016-08-17 13:24:19 +00001140 void DeleteFormula(Formula &F);
1141 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1142
1143 void print(raw_ostream &OS) const;
1144 void dump() const;
1145};
Dan Gohman45774ce2010-02-12 10:34:29 +00001146
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001147} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00001148
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001149/// Tally up interesting quantities from the given register.
Dan Gohman45774ce2010-02-12 10:34:29 +00001150void Cost::RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +00001151 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +00001152 const Loop *L,
1153 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman5b18f032010-02-13 02:06:02 +00001154 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
Wei Mi8f20e632017-02-11 00:50:23 +00001155 // If this is an addrec for another loop, it should be an invariant
1156 // with respect to L since L is the innermost loop (at least
1157 // for now LSR only handles innermost loops).
Andrew Trickd97b83e2012-03-22 22:42:45 +00001158 if (AR->getLoop() != L) {
1159 // If the AddRec exists, consider it's register free and leave it alone.
Andrew Trick5df90962011-12-06 03:13:31 +00001160 if (isExistingPhi(AR, SE))
1161 return;
1162
Wei Mi493fb262017-02-16 21:27:31 +00001163 // It is bad to allow LSR for current loop to add induction variables
1164 // for its sibling loops.
1165 if (!AR->getLoop()->contains(L)) {
1166 Lose();
1167 return;
1168 }
1169
Wei Mi8f20e632017-02-11 00:50:23 +00001170 // Otherwise, it will be an invariant with respect to Loop L.
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001171 ++C.NumRegs;
Andrew Trickd97b83e2012-03-22 22:42:45 +00001172 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001173 }
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001174 C.AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman45774ce2010-02-12 10:34:29 +00001175
Dan Gohman5b18f032010-02-13 02:06:02 +00001176 // Add the step value register, if it needs one.
1177 // TODO: The non-affine case isn't precisely modeled here.
Andrew Trick8868fae2011-09-26 23:35:25 +00001178 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1179 if (!Regs.count(AR->getOperand(1))) {
Dan Gohman5b18f032010-02-13 02:06:02 +00001180 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Andrew Trick8868fae2011-09-26 23:35:25 +00001181 if (isLoser())
1182 return;
1183 }
1184 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001185 }
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001186 ++C.NumRegs;
Dan Gohman5b18f032010-02-13 02:06:02 +00001187
1188 // Rough heuristic; favor registers which don't require extra setup
1189 // instructions in the preheader.
1190 if (!isa<SCEVUnknown>(Reg) &&
1191 !isa<SCEVConstant>(Reg) &&
1192 !(isa<SCEVAddRecExpr>(Reg) &&
1193 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
1194 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001195 ++C.SetupCost;
Dan Gohman34f37e02010-10-07 23:41:58 +00001196
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001197 C.NumIVMuls += isa<SCEVMulExpr>(Reg) &&
Davide Italiano709d4182016-07-07 17:44:38 +00001198 SE.hasComputableLoopEvolution(Reg, L);
Dan Gohman5b18f032010-02-13 02:06:02 +00001199}
1200
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001201/// Record this register in the set. If we haven't seen it before, rate
1202/// it. Optional LoserRegs provides a way to declare any formula that refers to
1203/// one of those regs an instant loser.
Dan Gohman5b18f032010-02-13 02:06:02 +00001204void Cost::RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +00001205 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman0849ed52010-02-16 19:42:34 +00001206 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +00001207 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +00001208 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +00001209 if (LoserRegs && LoserRegs->count(Reg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +00001210 Lose();
Andrew Trick5df90962011-12-06 03:13:31 +00001211 return;
1212 }
David Blaikie70573dc2014-11-19 07:49:26 +00001213 if (Regs.insert(Reg).second) {
Dan Gohman5b18f032010-02-13 02:06:02 +00001214 RateRegister(Reg, Regs, L, SE, DT);
Andrew Tricka1c01ba2013-03-19 04:14:57 +00001215 if (LoserRegs && isLoser())
Andrew Trick5df90962011-12-06 03:13:31 +00001216 LoserRegs->insert(Reg);
1217 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001218}
1219
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001220void Cost::RateFormula(const TargetTransformInfo &TTI,
1221 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +00001222 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +00001223 const DenseSet<const SCEV *> &VisitedRegs,
1224 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +00001225 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001226 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +00001227 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Wei Mi74d5a902017-02-22 21:47:08 +00001228 assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");
Dan Gohman45774ce2010-02-12 10:34:29 +00001229 // Tally up the registers.
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001230 unsigned PrevAddRecCost = C.AddRecCost;
1231 unsigned PrevNumRegs = C.NumRegs;
1232 unsigned PrevNumBaseAdds = C.NumBaseAdds;
Dan Gohman45774ce2010-02-12 10:34:29 +00001233 if (const SCEV *ScaledReg = F.ScaledReg) {
1234 if (VisitedRegs.count(ScaledReg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +00001235 Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00001236 return;
1237 }
Andrew Trick5df90962011-12-06 03:13:31 +00001238 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick784729d2011-09-26 23:11:04 +00001239 if (isLoser())
1240 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001241 }
Craig Topper042a3922015-05-25 20:01:18 +00001242 for (const SCEV *BaseReg : F.BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001243 if (VisitedRegs.count(BaseReg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +00001244 Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00001245 return;
1246 }
Andrew Trick5df90962011-12-06 03:13:31 +00001247 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick784729d2011-09-26 23:11:04 +00001248 if (isLoser())
1249 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001250 }
1251
Dan Gohman6136e942011-05-03 00:46:49 +00001252 // Determine how many (unfolded) adds we'll need inside the loop.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001253 size_t NumBaseParts = F.getNumRegs();
Dan Gohman6136e942011-05-03 00:46:49 +00001254 if (NumBaseParts > 1)
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001255 // Do not count the base and a possible second register if the target
1256 // allows to fold 2 registers.
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001257 C.NumBaseAdds +=
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001258 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001259 C.NumBaseAdds += (F.UnfoldedOffset != 0);
Dan Gohman45774ce2010-02-12 10:34:29 +00001260
Quentin Colombetbf490d42013-05-31 21:29:03 +00001261 // Accumulate non-free scaling amounts.
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001262 C.ScaleCost += getScalingFactorCost(TTI, LU, F, *L);
Quentin Colombetbf490d42013-05-31 21:29:03 +00001263
Dan Gohman45774ce2010-02-12 10:34:29 +00001264 // Tally up the non-zero immediates.
Jonas Paulsson7a794222016-08-17 13:24:19 +00001265 for (const LSRFixup &Fixup : LU.Fixups) {
1266 int64_t O = Fixup.Offset;
Craig Topper042a3922015-05-25 20:01:18 +00001267 int64_t Offset = (uint64_t)O + F.BaseOffset;
Chandler Carruth6e479322013-01-07 15:04:40 +00001268 if (F.BaseGV)
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001269 C.ImmCost += 64; // Handle symbolic values conservatively.
Dan Gohman45774ce2010-02-12 10:34:29 +00001270 // TODO: This should probably be the pointer size.
1271 else if (Offset != 0)
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001272 C.ImmCost += APInt(64, Offset, true).getMinSignedBits();
Jonas Paulsson7a794222016-08-17 13:24:19 +00001273
1274 // Check with target if this offset with this instruction is
1275 // specifically not supported.
1276 if ((isa<LoadInst>(Fixup.UserInst) || isa<StoreInst>(Fixup.UserInst)) &&
1277 !TTI.isFoldableMemAccessOffset(Fixup.UserInst, Offset))
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001278 C.NumBaseAdds++;
Dan Gohman45774ce2010-02-12 10:34:29 +00001279 }
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +00001280
Evgeny Stupachenko4d94e992017-06-05 22:44:18 +00001281 // If we don't count instruction cost exit here.
1282 if (!InsnsCost) {
1283 assert(isValid() && "invalid cost");
1284 return;
1285 }
1286
1287 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
1288 // additional instruction (at least fill).
1289 unsigned TTIRegNum = TTI.getNumberOfRegisters(false) - 1;
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001290 if (C.NumRegs > TTIRegNum) {
Evgeny Stupachenko4d94e992017-06-05 22:44:18 +00001291 // Cost already exceeded TTIRegNum, then only newly added register can add
1292 // new instructions.
1293 if (PrevNumRegs > TTIRegNum)
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001294 C.Insns += (C.NumRegs - PrevNumRegs);
Evgeny Stupachenko4d94e992017-06-05 22:44:18 +00001295 else
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001296 C.Insns += (C.NumRegs - TTIRegNum);
Evgeny Stupachenko4d94e992017-06-05 22:44:18 +00001297 }
1298
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +00001299 // If ICmpZero formula ends with not 0, it could not be replaced by
1300 // just add or sub. We'll need to compare final result of AddRec.
1301 // That means we'll need an additional instruction.
1302 // For -10 + {0, +, 1}:
1303 // i = i + 1;
1304 // cmp i, 10
1305 //
1306 // For {-10, +, 1}:
1307 // i = i + 1;
1308 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd())
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001309 C.Insns++;
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +00001310 // Each new AddRec adds 1 instruction to calculation.
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001311 C.Insns += (C.AddRecCost - PrevAddRecCost);
Evgeny Stupachenkofe6f5482017-02-11 02:57:43 +00001312
1313 // BaseAdds adds instructions for unfolded registers.
1314 if (LU.Kind != LSRUse::ICmpZero)
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001315 C.Insns += C.NumBaseAdds - PrevNumBaseAdds;
Andrew Trick784729d2011-09-26 23:11:04 +00001316 assert(isValid() && "invalid cost");
Dan Gohman45774ce2010-02-12 10:34:29 +00001317}
1318
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001319/// Set this cost to a losing value.
Tim Northoverbc6659c2014-01-22 13:27:00 +00001320void Cost::Lose() {
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001321 C.Insns = ~0u;
1322 C.NumRegs = ~0u;
1323 C.AddRecCost = ~0u;
1324 C.NumIVMuls = ~0u;
1325 C.NumBaseAdds = ~0u;
1326 C.ImmCost = ~0u;
1327 C.SetupCost = ~0u;
1328 C.ScaleCost = ~0u;
Dan Gohman45774ce2010-02-12 10:34:29 +00001329}
1330
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001331/// Choose the lower cost.
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001332bool Cost::isLess(Cost &Other, const TargetTransformInfo &TTI) {
1333 if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&
1334 C.Insns != Other.C.Insns)
1335 return C.Insns < Other.C.Insns;
1336 return TTI.isLSRCostLess(C, Other.C);
Dan Gohman45774ce2010-02-12 10:34:29 +00001337}
1338
1339void Cost::print(raw_ostream &OS) const {
Evgeny Stupachenko4d94e992017-06-05 22:44:18 +00001340 if (InsnsCost)
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00001341 OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");
1342 OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");
1343 if (C.AddRecCost != 0)
1344 OS << ", with addrec cost " << C.AddRecCost;
1345 if (C.NumIVMuls != 0)
1346 OS << ", plus " << C.NumIVMuls << " IV mul"
1347 << (C.NumIVMuls == 1 ? "" : "s");
1348 if (C.NumBaseAdds != 0)
1349 OS << ", plus " << C.NumBaseAdds << " base add"
1350 << (C.NumBaseAdds == 1 ? "" : "s");
1351 if (C.ScaleCost != 0)
1352 OS << ", plus " << C.ScaleCost << " scale cost";
1353 if (C.ImmCost != 0)
1354 OS << ", plus " << C.ImmCost << " imm cost";
1355 if (C.SetupCost != 0)
1356 OS << ", plus " << C.SetupCost << " setup cost";
Dan Gohman45774ce2010-02-12 10:34:29 +00001357}
1358
Matthias Braun8c209aa2017-01-28 02:02:38 +00001359#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1360LLVM_DUMP_METHOD void Cost::dump() const {
Dan Gohman45774ce2010-02-12 10:34:29 +00001361 print(errs()); errs() << '\n';
1362}
Matthias Braun8c209aa2017-01-28 02:02:38 +00001363#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00001364
Dan Gohman45774ce2010-02-12 10:34:29 +00001365LSRFixup::LSRFixup()
Jonas Paulsson7a794222016-08-17 13:24:19 +00001366 : UserInst(nullptr), OperandValToReplace(nullptr),
Craig Topperf40110f2014-04-25 05:29:35 +00001367 Offset(0) {}
Dan Gohman45774ce2010-02-12 10:34:29 +00001368
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001369/// Test whether this fixup always uses its value outside of the given loop.
Dan Gohmand006ab92010-04-07 22:27:08 +00001370bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1371 // PHI nodes use their value in their incoming blocks.
1372 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1373 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1374 if (PN->getIncomingValue(i) == OperandValToReplace &&
1375 L->contains(PN->getIncomingBlock(i)))
1376 return false;
1377 return true;
1378 }
1379
1380 return !L->contains(UserInst);
1381}
1382
Dan Gohman45774ce2010-02-12 10:34:29 +00001383void LSRFixup::print(raw_ostream &OS) const {
1384 OS << "UserInst=";
1385 // Store is common and interesting enough to be worth special-casing.
1386 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1387 OS << "store ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001388 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001389 } else if (UserInst->getType()->isVoidTy())
1390 OS << UserInst->getOpcodeName();
1391 else
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001392 UserInst->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001393
1394 OS << ", OperandValToReplace=";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001395 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001396
Craig Topper042a3922015-05-25 20:01:18 +00001397 for (const Loop *PIL : PostIncLoops) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001398 OS << ", PostIncLoop=";
Craig Topper042a3922015-05-25 20:01:18 +00001399 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001400 }
1401
Dan Gohman45774ce2010-02-12 10:34:29 +00001402 if (Offset != 0)
1403 OS << ", Offset=" << Offset;
1404}
1405
Matthias Braun8c209aa2017-01-28 02:02:38 +00001406#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1407LLVM_DUMP_METHOD void LSRFixup::dump() const {
Dan Gohman45774ce2010-02-12 10:34:29 +00001408 print(errs()); errs() << '\n';
1409}
Matthias Braun8c209aa2017-01-28 02:02:38 +00001410#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00001411
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001412/// Test whether this use as a formula which has the same registers as the given
1413/// formula.
Dan Gohman20fab452010-05-19 23:43:12 +00001414bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001415 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman20fab452010-05-19 23:43:12 +00001416 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1417 // Unstable sort by host order ok, because this is only used for uniquifying.
1418 std::sort(Key.begin(), Key.end());
1419 return Uniquifier.count(Key);
1420}
1421
Evgeny Stupachenko9909872e302017-02-21 07:34:40 +00001422/// The function returns a probability of selecting formula without Reg.
1423float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {
1424 unsigned FNum = 0;
1425 for (const Formula &F : Formulae)
1426 if (F.referencesReg(Reg))
1427 FNum++;
1428 return ((float)(Formulae.size() - FNum)) / Formulae.size();
1429}
1430
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001431/// If the given formula has not yet been inserted, add it to the list, and
1432/// return true. Return false otherwise. The formula must be in canonical form.
Wei Mi74d5a902017-02-22 21:47:08 +00001433bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {
1434 assert(F.isCanonical(L) && "Invalid canonical representation");
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001435
Andrew Trick57243da2013-10-25 21:35:56 +00001436 if (!Formulae.empty() && RigidFormula)
1437 return false;
1438
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001439 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00001440 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1441 // Unstable sort by host order ok, because this is only used for uniquifying.
1442 std::sort(Key.begin(), Key.end());
1443
1444 if (!Uniquifier.insert(Key).second)
1445 return false;
1446
1447 // Using a register to hold the value of 0 is not profitable.
1448 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1449 "Zero allocated in a scaled register!");
1450#ifndef NDEBUG
Craig Topper042a3922015-05-25 20:01:18 +00001451 for (const SCEV *BaseReg : F.BaseRegs)
1452 assert(!BaseReg->isZero() && "Zero allocated in a base register!");
Dan Gohman45774ce2010-02-12 10:34:29 +00001453#endif
1454
1455 // Add the formula to the list.
1456 Formulae.push_back(F);
1457
1458 // Record registers now being used by this use.
Dan Gohman45774ce2010-02-12 10:34:29 +00001459 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001460 if (F.ScaledReg)
1461 Regs.insert(F.ScaledReg);
Dan Gohman45774ce2010-02-12 10:34:29 +00001462
1463 return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001464}
1465
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001466/// Remove the given formula from this use's list.
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001467void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman80a96082010-05-20 15:17:54 +00001468 if (&F != &Formulae.back())
1469 std::swap(F, Formulae.back());
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001470 Formulae.pop_back();
1471}
1472
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001473/// Recompute the Regs field, and update RegUses.
Dan Gohman4cf99b52010-05-18 23:42:37 +00001474void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1475 // Now that we've filtered out some formulae, recompute the Regs set.
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001476 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001477 Regs.clear();
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001478 for (const Formula &F : Formulae) {
Dan Gohman4cf99b52010-05-18 23:42:37 +00001479 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1480 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1481 }
1482
1483 // Update the RegTracker.
Craig Topper46276792014-08-24 23:23:06 +00001484 for (const SCEV *S : OldRegs)
1485 if (!Regs.count(S))
Sanjoy Das302bfd02015-08-16 18:22:43 +00001486 RegUses.dropRegister(S, LUIdx);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001487}
1488
Dan Gohman45774ce2010-02-12 10:34:29 +00001489void LSRUse::print(raw_ostream &OS) const {
1490 OS << "LSR Use: Kind=";
1491 switch (Kind) {
1492 case Basic: OS << "Basic"; break;
1493 case Special: OS << "Special"; break;
1494 case ICmpZero: OS << "ICmpZero"; break;
1495 case Address:
1496 OS << "Address of ";
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001497 if (AccessTy.MemTy->isPointerTy())
Dan Gohman45774ce2010-02-12 10:34:29 +00001498 OS << "pointer"; // the full pointer type could be really verbose
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001499 else {
1500 OS << *AccessTy.MemTy;
1501 }
1502
1503 OS << " in addrspace(" << AccessTy.AddrSpace << ')';
Evan Cheng133694d2007-10-25 09:11:16 +00001504 }
1505
Dan Gohman45774ce2010-02-12 10:34:29 +00001506 OS << ", Offsets={";
Craig Topper042a3922015-05-25 20:01:18 +00001507 bool NeedComma = false;
Jonas Paulsson7a794222016-08-17 13:24:19 +00001508 for (const LSRFixup &Fixup : Fixups) {
Craig Topper042a3922015-05-25 20:01:18 +00001509 if (NeedComma) OS << ',';
Jonas Paulsson7a794222016-08-17 13:24:19 +00001510 OS << Fixup.Offset;
Craig Topper042a3922015-05-25 20:01:18 +00001511 NeedComma = true;
Dan Gohman045f8192010-01-22 00:46:49 +00001512 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001513 OS << '}';
Dan Gohman045f8192010-01-22 00:46:49 +00001514
Dan Gohman45774ce2010-02-12 10:34:29 +00001515 if (AllFixupsOutsideLoop)
1516 OS << ", all-fixups-outside-loop";
Dan Gohman14152082010-07-15 20:24:58 +00001517
1518 if (WidestFixupType)
1519 OS << ", widest fixup type: " << *WidestFixupType;
Dan Gohman045f8192010-01-22 00:46:49 +00001520}
1521
Matthias Braun8c209aa2017-01-28 02:02:38 +00001522#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1523LLVM_DUMP_METHOD void LSRUse::dump() const {
Dan Gohman45774ce2010-02-12 10:34:29 +00001524 print(errs()); errs() << '\n';
1525}
Matthias Braun8c209aa2017-01-28 02:02:38 +00001526#endif
Dan Gohman045f8192010-01-22 00:46:49 +00001527
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001528static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001529 LSRUse::KindType Kind, MemAccessTy AccessTy,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001530 GlobalValue *BaseGV, int64_t BaseOffset,
1531 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001532 switch (Kind) {
1533 case LSRUse::Address:
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001534 return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset,
1535 HasBaseReg, Scale, AccessTy.AddrSpace);
Dan Gohman45774ce2010-02-12 10:34:29 +00001536
Dan Gohman45774ce2010-02-12 10:34:29 +00001537 case LSRUse::ICmpZero:
1538 // There's not even a target hook for querying whether it would be legal to
1539 // fold a GV into an ICmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001540 if (BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00001541 return false;
1542
1543 // ICmp only has two operands; don't allow more than two non-trivial parts.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001544 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
Dan Gohman45774ce2010-02-12 10:34:29 +00001545 return false;
1546
1547 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1548 // putting the scaled register in the other operand of the icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001549 if (Scale != 0 && Scale != -1)
Dan Gohman45774ce2010-02-12 10:34:29 +00001550 return false;
1551
1552 // If we have low-level target information, ask the target if it can fold an
1553 // integer immediate on an icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001554 if (BaseOffset != 0) {
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001555 // We have one of:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001556 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1557 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001558 // Offs is the ICmp immediate.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001559 if (Scale == 0)
1560 // The cast does the right thing with INT64_MIN.
1561 BaseOffset = -(uint64_t)BaseOffset;
1562 return TTI.isLegalICmpImmediate(BaseOffset);
Dan Gohman045f8192010-01-22 00:46:49 +00001563 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001564
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001565 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
Dan Gohman45774ce2010-02-12 10:34:29 +00001566 return true;
1567
1568 case LSRUse::Basic:
1569 // Only handle single-register values.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001570 return !BaseGV && Scale == 0 && BaseOffset == 0;
Dan Gohman45774ce2010-02-12 10:34:29 +00001571
1572 case LSRUse::Special:
Andrew Trickaca8fb32012-06-15 20:07:26 +00001573 // Special case Basic to handle -1 scales.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001574 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
Dan Gohman045f8192010-01-22 00:46:49 +00001575 }
1576
David Blaikie46a9f012012-01-20 21:51:11 +00001577 llvm_unreachable("Invalid LSRUse Kind!");
Dan Gohman045f8192010-01-22 00:46:49 +00001578}
1579
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001580static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1581 int64_t MinOffset, int64_t MaxOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001582 LSRUse::KindType Kind, MemAccessTy AccessTy,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001583 GlobalValue *BaseGV, int64_t BaseOffset,
1584 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001585 // Check for overflow.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001586 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
Dan Gohman45774ce2010-02-12 10:34:29 +00001587 (MinOffset > 0))
1588 return false;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001589 MinOffset = (uint64_t)BaseOffset + MinOffset;
1590 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1591 (MaxOffset > 0))
1592 return false;
1593 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1594
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001595 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1596 HasBaseReg, Scale) &&
1597 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1598 HasBaseReg, Scale);
1599}
1600
1601static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1602 int64_t MinOffset, int64_t MaxOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001603 LSRUse::KindType Kind, MemAccessTy AccessTy,
Wei Mi74d5a902017-02-22 21:47:08 +00001604 const Formula &F, const Loop &L) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001605 // For the purpose of isAMCompletelyFolded either having a canonical formula
1606 // or a scale not equal to zero is correct.
1607 // Problems may arise from non canonical formulae having a scale == 0.
1608 // Strictly speaking it would best to just rely on canonical formulae.
1609 // However, when we generate the scaled formulae, we first check that the
1610 // scaling factor is profitable before computing the actual ScaledReg for
1611 // compile time sake.
Wei Mi74d5a902017-02-22 21:47:08 +00001612 assert((F.isCanonical(L) || F.Scale != 0));
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001613 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1614 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1615}
1616
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001617/// Test whether we know how to expand the current formula.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001618static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001619 int64_t MaxOffset, LSRUse::KindType Kind,
1620 MemAccessTy AccessTy, GlobalValue *BaseGV,
1621 int64_t BaseOffset, bool HasBaseReg, int64_t Scale) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001622 // We know how to expand completely foldable formulae.
1623 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1624 BaseOffset, HasBaseReg, Scale) ||
1625 // Or formulae that use a base register produced by a sum of base
1626 // registers.
1627 (Scale == 1 &&
1628 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1629 BaseGV, BaseOffset, true, 0));
Dan Gohman045f8192010-01-22 00:46:49 +00001630}
1631
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001632static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001633 int64_t MaxOffset, LSRUse::KindType Kind,
1634 MemAccessTy AccessTy, const Formula &F) {
Chandler Carruth6e479322013-01-07 15:04:40 +00001635 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1636 F.BaseOffset, F.HasBaseReg, F.Scale);
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001637}
1638
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001639static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1640 const LSRUse &LU, const Formula &F) {
1641 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1642 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1643 F.Scale);
1644}
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001645
Quentin Colombetbf490d42013-05-31 21:29:03 +00001646static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
Wei Mi74d5a902017-02-22 21:47:08 +00001647 const LSRUse &LU, const Formula &F,
1648 const Loop &L) {
Quentin Colombetbf490d42013-05-31 21:29:03 +00001649 if (!F.Scale)
1650 return 0;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001651
1652 // If the use is not completely folded in that instruction, we will have to
1653 // pay an extra cost only for scale != 1.
1654 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
Wei Mi74d5a902017-02-22 21:47:08 +00001655 LU.AccessTy, F, L))
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001656 return F.Scale != 1;
Quentin Colombetbf490d42013-05-31 21:29:03 +00001657
1658 switch (LU.Kind) {
1659 case LSRUse::Address: {
Quentin Colombet145eb972013-06-19 19:59:41 +00001660 // Check the scaling factor cost with both the min and max offsets.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001661 int ScaleCostMinOffset = TTI.getScalingFactorCost(
1662 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1663 F.Scale, LU.AccessTy.AddrSpace);
1664 int ScaleCostMaxOffset = TTI.getScalingFactorCost(
1665 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1666 F.Scale, LU.AccessTy.AddrSpace);
Quentin Colombet145eb972013-06-19 19:59:41 +00001667
1668 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1669 "Legal addressing mode has an illegal cost!");
1670 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
Quentin Colombetbf490d42013-05-31 21:29:03 +00001671 }
1672 case LSRUse::ICmpZero:
Quentin Colombetbf490d42013-05-31 21:29:03 +00001673 case LSRUse::Basic:
1674 case LSRUse::Special:
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001675 // The use is completely folded, i.e., everything is folded into the
1676 // instruction.
Quentin Colombetbf490d42013-05-31 21:29:03 +00001677 return 0;
1678 }
1679
1680 llvm_unreachable("Invalid LSRUse Kind!");
1681}
1682
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001683static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001684 LSRUse::KindType Kind, MemAccessTy AccessTy,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001685 GlobalValue *BaseGV, int64_t BaseOffset,
1686 bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001687 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001688 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001689
Dan Gohman45774ce2010-02-12 10:34:29 +00001690 // Conservatively, create an address with an immediate and a
1691 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001692 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman045f8192010-01-22 00:46:49 +00001693
Dan Gohman20fab452010-05-19 23:43:12 +00001694 // Canonicalize a scale of 1 to a base register if the formula doesn't
1695 // already have a base register.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001696 if (!HasBaseReg && Scale == 1) {
1697 Scale = 0;
1698 HasBaseReg = true;
Dan Gohman20fab452010-05-19 23:43:12 +00001699 }
1700
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001701 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1702 HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001703}
1704
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001705static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1706 ScalarEvolution &SE, int64_t MinOffset,
1707 int64_t MaxOffset, LSRUse::KindType Kind,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001708 MemAccessTy AccessTy, const SCEV *S,
1709 bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001710 // Fast-path: zero is always foldable.
1711 if (S->isZero()) return true;
1712
1713 // Conservatively, create an address with an immediate and a
1714 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001715 int64_t BaseOffset = ExtractImmediate(S, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00001716 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1717
1718 // If there's anything else involved, it's not foldable.
1719 if (!S->isZero()) return false;
1720
1721 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001722 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001723
1724 // Conservatively, create an address with an immediate and a
1725 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001726 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00001727
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001728 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1729 BaseOffset, HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001730}
1731
Dan Gohman297fb8b2010-06-19 21:21:39 +00001732namespace {
1733
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001734/// An individual increment in a Chain of IV increments. Relate an IV user to
1735/// an expression that computes the IV it uses from the IV used by the previous
1736/// link in the Chain.
Andrew Trick29fe5f02012-01-09 19:50:34 +00001737///
1738/// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1739/// original IVOperand. The head of the chain's IVOperand is only valid during
1740/// chain collection, before LSR replaces IV users. During chain generation,
1741/// IncExpr can be used to find the new IVOperand that computes the same
1742/// expression.
1743struct IVInc {
1744 Instruction *UserInst;
1745 Value* IVOperand;
1746 const SCEV *IncExpr;
1747
1748 IVInc(Instruction *U, Value *O, const SCEV *E):
1749 UserInst(U), IVOperand(O), IncExpr(E) {}
1750};
1751
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001752// The list of IV increments in program order. We typically add the head of a
1753// chain without finding subsequent links.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001754struct IVChain {
1755 SmallVector<IVInc,1> Incs;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001756 const SCEV *ExprBase;
1757
Craig Topperf40110f2014-04-25 05:29:35 +00001758 IVChain() : ExprBase(nullptr) {}
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001759
1760 IVChain(const IVInc &Head, const SCEV *Base)
1761 : Incs(1, Head), ExprBase(Base) {}
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001762
1763 typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
1764
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001765 // Return the first increment in the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001766 const_iterator begin() const {
1767 assert(!Incs.empty());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001768 return std::next(Incs.begin());
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001769 }
1770 const_iterator end() const {
1771 return Incs.end();
1772 }
1773
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001774 // Returns true if this chain contains any increments.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001775 bool hasIncs() const { return Incs.size() >= 2; }
1776
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001777 // Add an IVInc to the end of this chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001778 void add(const IVInc &X) { Incs.push_back(X); }
1779
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001780 // Returns the last UserInst in the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001781 Instruction *tailUserInst() const { return Incs.back().UserInst; }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001782
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001783 // Returns true if IncExpr can be profitably added to this chain.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001784 bool isProfitableIncrement(const SCEV *OperExpr,
1785 const SCEV *IncExpr,
1786 ScalarEvolution&);
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001787};
Andrew Trick29fe5f02012-01-09 19:50:34 +00001788
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001789/// Helper for CollectChains to track multiple IV increment uses. Distinguish
1790/// between FarUsers that definitely cross IV increments and NearUsers that may
1791/// be used between IV increments.
Andrew Trick29fe5f02012-01-09 19:50:34 +00001792struct ChainUsers {
1793 SmallPtrSet<Instruction*, 4> FarUsers;
1794 SmallPtrSet<Instruction*, 4> NearUsers;
1795};
1796
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001797/// This class holds state for the main loop strength reduction logic.
Dan Gohman45774ce2010-02-12 10:34:29 +00001798class LSRInstance {
1799 IVUsers &IU;
1800 ScalarEvolution &SE;
1801 DominatorTree &DT;
Dan Gohman607e02b2010-04-09 22:07:05 +00001802 LoopInfo &LI;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001803 const TargetTransformInfo &TTI;
Dan Gohman45774ce2010-02-12 10:34:29 +00001804 Loop *const L;
1805 bool Changed;
1806
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001807 /// This is the insert position that the current loop's induction variable
1808 /// increment should be placed. In simple loops, this is the latch block's
1809 /// terminator. But in more complicated cases, this is a position which will
1810 /// dominate all the in-loop post-increment users.
Dan Gohman45774ce2010-02-12 10:34:29 +00001811 Instruction *IVIncInsertPos;
1812
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001813 /// Interesting factors between use strides.
Justin Lebar54b0be02016-11-05 16:47:25 +00001814 ///
1815 /// We explicitly use a SetVector which contains a SmallSet, instead of the
1816 /// default, a SmallDenseSet, because we need to use the full range of
1817 /// int64_ts, and there's currently no good way of doing that with
1818 /// SmallDenseSet.
1819 SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors;
Dan Gohman45774ce2010-02-12 10:34:29 +00001820
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001821 /// Interesting use types, to facilitate truncation reuse.
Chris Lattner229907c2011-07-18 04:54:35 +00001822 SmallSetVector<Type *, 4> Types;
Dan Gohman45774ce2010-02-12 10:34:29 +00001823
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001824 /// The list of interesting uses.
Dan Gohman45774ce2010-02-12 10:34:29 +00001825 SmallVector<LSRUse, 16> Uses;
1826
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001827 /// Track which uses use which register candidates.
Dan Gohman45774ce2010-02-12 10:34:29 +00001828 RegUseTracker RegUses;
1829
Andrew Trick29fe5f02012-01-09 19:50:34 +00001830 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1831 // have more than a few IV increment chains in a loop. Missing a Chain falls
1832 // back to normal LSR behavior for those uses.
1833 static const unsigned MaxChains = 8;
1834
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001835 /// IV users can form a chain of IV increments.
Andrew Trick29fe5f02012-01-09 19:50:34 +00001836 SmallVector<IVChain, MaxChains> IVChainVec;
1837
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001838 /// IV users that belong to profitable IVChains.
Andrew Trick248d4102012-01-09 21:18:52 +00001839 SmallPtrSet<Use*, MaxChains> IVIncSet;
1840
Dan Gohman45774ce2010-02-12 10:34:29 +00001841 void OptimizeShadowIV();
1842 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1843 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohman4c4043c2010-05-20 20:05:31 +00001844 void OptimizeLoopTermCond();
Dan Gohman45774ce2010-02-12 10:34:29 +00001845
Andrew Trick29fe5f02012-01-09 19:50:34 +00001846 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1847 SmallVectorImpl<ChainUsers> &ChainUsersVec);
Andrew Trick248d4102012-01-09 21:18:52 +00001848 void FinalizeChain(IVChain &Chain);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001849 void CollectChains();
Andrew Trick248d4102012-01-09 21:18:52 +00001850 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001851 SmallVectorImpl<WeakTrackingVH> &DeadInsts);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001852
Dan Gohman45774ce2010-02-12 10:34:29 +00001853 void CollectInterestingTypesAndFactors();
1854 void CollectFixupsAndInitialFormulae();
1855
Dan Gohman45774ce2010-02-12 10:34:29 +00001856 // Support for sharing of LSRUses between LSRFixups.
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001857 typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
Dan Gohman45774ce2010-02-12 10:34:29 +00001858 UseMapTy UseMap;
1859
Dan Gohman110ed642010-09-01 01:45:53 +00001860 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001861 LSRUse::KindType Kind, MemAccessTy AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001862
Matt Arsenault427a0fd2015-08-15 00:53:06 +00001863 std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
1864 MemAccessTy AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001865
Dan Gohmana7b68d62010-10-07 23:33:43 +00001866 void DeleteUse(LSRUse &LU, size_t LUIdx);
Dan Gohman80a96082010-05-20 15:17:54 +00001867
Dan Gohman110ed642010-09-01 01:45:53 +00001868 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
Dan Gohman20fab452010-05-19 23:43:12 +00001869
Dan Gohman8c16b382010-02-22 04:11:59 +00001870 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00001871 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1872 void CountRegisters(const Formula &F, size_t LUIdx);
1873 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1874
1875 void CollectLoopInvariantFixupsAndFormulae();
1876
1877 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1878 unsigned Depth = 0);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001879
1880 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1881 const Formula &Base, unsigned Depth,
1882 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001883 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001884 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1885 const Formula &Base, size_t Idx,
1886 bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001887 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001888 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1889 const Formula &Base,
1890 const SmallVectorImpl<int64_t> &Worklist,
1891 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001892 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1893 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1894 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1895 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1896 void GenerateCrossUseConstantOffsets();
1897 void GenerateAllReuseFormulae();
1898
1899 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmana4eca052010-05-18 22:51:59 +00001900
1901 size_t EstimateSearchSpaceComplexity() const;
Dan Gohmane9e08732010-08-29 16:09:42 +00001902 void NarrowSearchSpaceByDetectingSupersets();
1903 void NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00001904 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Evgeny Stupachenko9909872e302017-02-21 07:34:40 +00001905 void NarrowSearchSpaceByDeletingCostlyFormulas();
Dan Gohmane9e08732010-08-29 16:09:42 +00001906 void NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohman45774ce2010-02-12 10:34:29 +00001907 void NarrowSearchSpaceUsingHeuristics();
1908
1909 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1910 Cost &SolutionCost,
1911 SmallVectorImpl<const Formula *> &Workspace,
1912 const Cost &CurCost,
1913 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1914 DenseSet<const SCEV *> &VisitedRegs) const;
1915 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1916
Dan Gohman607e02b2010-04-09 22:07:05 +00001917 BasicBlock::iterator
1918 HoistInsertPosition(BasicBlock::iterator IP,
1919 const SmallVectorImpl<Instruction *> &Inputs) const;
Andrew Trickc908b432012-01-20 07:41:13 +00001920 BasicBlock::iterator
1921 AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1922 const LSRFixup &LF,
1923 const LSRUse &LU,
1924 SCEVExpander &Rewriter) const;
Dan Gohmand2df6432010-04-09 02:00:38 +00001925
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001926 Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
1927 BasicBlock::iterator IP, SCEVExpander &Rewriter,
1928 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
Jonas Paulsson7a794222016-08-17 13:24:19 +00001929 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001930 const Formula &F, SCEVExpander &Rewriter,
1931 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
1932 void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
Dan Gohman45774ce2010-02-12 10:34:29 +00001933 SCEVExpander &Rewriter,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001934 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
Justin Bogner843fb202015-12-15 19:40:57 +00001935 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
Dan Gohman45774ce2010-02-12 10:34:29 +00001936
Andrew Trickdc18e382011-12-13 00:55:33 +00001937public:
Justin Bogner843fb202015-12-15 19:40:57 +00001938 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
1939 LoopInfo &LI, const TargetTransformInfo &TTI);
Dan Gohman45774ce2010-02-12 10:34:29 +00001940
1941 bool getChanged() const { return Changed; }
1942
1943 void print_factors_and_types(raw_ostream &OS) const;
1944 void print_fixups(raw_ostream &OS) const;
1945 void print_uses(raw_ostream &OS) const;
1946 void print(raw_ostream &OS) const;
1947 void dump() const;
1948};
1949
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001950} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00001951
Sanjoy Das94c4aec2015-08-16 18:22:46 +00001952/// If IV is used in a int-to-float cast inside the loop then try to eliminate
1953/// the cast operation.
Dan Gohman45774ce2010-02-12 10:34:29 +00001954void LSRInstance::OptimizeShadowIV() {
1955 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1956 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1957 return;
1958
1959 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1960 UI != E; /* empty */) {
1961 IVUsers::const_iterator CandidateUI = UI;
1962 ++UI;
1963 Instruction *ShadowUse = CandidateUI->getUser();
Craig Topperf40110f2014-04-25 05:29:35 +00001964 Type *DestTy = nullptr;
Andrew Trick858e9f02011-07-21 01:05:01 +00001965 bool IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001966
1967 /* If shadow use is a int->float cast then insert a second IV
1968 to eliminate this cast.
1969
1970 for (unsigned i = 0; i < n; ++i)
1971 foo((double)i);
1972
1973 is transformed into
1974
1975 double d = 0.0;
1976 for (unsigned i = 0; i < n; ++i, ++d)
1977 foo(d);
1978 */
Andrew Trick858e9f02011-07-21 01:05:01 +00001979 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1980 IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001981 DestTy = UCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001982 }
1983 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1984 IsSigned = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001985 DestTy = SCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001986 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001987 if (!DestTy) continue;
1988
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001989 // If target does not support DestTy natively then do not apply
1990 // this transformation.
1991 if (!TTI.isTypeLegal(DestTy)) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001992
1993 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1994 if (!PH) continue;
1995 if (PH->getNumIncomingValues() != 2) continue;
1996
Chris Lattner229907c2011-07-18 04:54:35 +00001997 Type *SrcTy = PH->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00001998 int Mantissa = DestTy->getFPMantissaWidth();
1999 if (Mantissa == -1) continue;
2000 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
2001 continue;
2002
2003 unsigned Entry, Latch;
2004 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2005 Entry = 0;
2006 Latch = 1;
Dan Gohman045f8192010-01-22 00:46:49 +00002007 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00002008 Entry = 1;
2009 Latch = 0;
Dan Gohman045f8192010-01-22 00:46:49 +00002010 }
Dan Gohman045f8192010-01-22 00:46:49 +00002011
Dan Gohman45774ce2010-02-12 10:34:29 +00002012 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2013 if (!Init) continue;
Andrew Trick858e9f02011-07-21 01:05:01 +00002014 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
Andrew Trickbd243d02011-07-21 01:45:54 +00002015 (double)Init->getSExtValue() :
2016 (double)Init->getZExtValue());
Dan Gohman045f8192010-01-22 00:46:49 +00002017
Dan Gohman45774ce2010-02-12 10:34:29 +00002018 BinaryOperator *Incr =
2019 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2020 if (!Incr) continue;
2021 if (Incr->getOpcode() != Instruction::Add
2022 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman045f8192010-01-22 00:46:49 +00002023 continue;
Dan Gohman045f8192010-01-22 00:46:49 +00002024
Dan Gohman45774ce2010-02-12 10:34:29 +00002025 /* Initialize new IV, double d = 0.0 in above example. */
Craig Topperf40110f2014-04-25 05:29:35 +00002026 ConstantInt *C = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00002027 if (Incr->getOperand(0) == PH)
2028 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2029 else if (Incr->getOperand(1) == PH)
2030 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00002031 else
Dan Gohman045f8192010-01-22 00:46:49 +00002032 continue;
2033
Dan Gohman45774ce2010-02-12 10:34:29 +00002034 if (!C) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00002035
Dan Gohman45774ce2010-02-12 10:34:29 +00002036 // Ignore negative constants, as the code below doesn't handle them
2037 // correctly. TODO: Remove this restriction.
2038 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00002039
Dan Gohman45774ce2010-02-12 10:34:29 +00002040 /* Add new PHINode. */
Jay Foad52131342011-03-30 11:28:46 +00002041 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
Dan Gohman045f8192010-01-22 00:46:49 +00002042
Dan Gohman45774ce2010-02-12 10:34:29 +00002043 /* create new increment. '++d' in above example. */
2044 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2045 BinaryOperator *NewIncr =
2046 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
2047 Instruction::FAdd : Instruction::FSub,
2048 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman045f8192010-01-22 00:46:49 +00002049
Dan Gohman45774ce2010-02-12 10:34:29 +00002050 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2051 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman045f8192010-01-22 00:46:49 +00002052
Dan Gohman45774ce2010-02-12 10:34:29 +00002053 /* Remove cast operation */
2054 ShadowUse->replaceAllUsesWith(NewPH);
2055 ShadowUse->eraseFromParent();
Dan Gohman4c4043c2010-05-20 20:05:31 +00002056 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00002057 break;
Dan Gohman045f8192010-01-22 00:46:49 +00002058 }
2059}
2060
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002061/// If Cond has an operand that is an expression of an IV, set the IV user and
2062/// stride information and return true, otherwise return false.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00002063bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Craig Topper042a3922015-05-25 20:01:18 +00002064 for (IVStrideUse &U : IU)
2065 if (U.getUser() == Cond) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002066 // NOTE: we could handle setcc instructions with multiple uses here, but
2067 // InstCombine does it as well for simple uses, it's not clear that it
2068 // occurs enough in real life to handle.
Craig Topper042a3922015-05-25 20:01:18 +00002069 CondUse = &U;
Dan Gohman45774ce2010-02-12 10:34:29 +00002070 return true;
2071 }
Dan Gohman045f8192010-01-22 00:46:49 +00002072 return false;
Evan Cheng133694d2007-10-25 09:11:16 +00002073}
2074
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002075/// Rewrite the loop's terminating condition if it uses a max computation.
Dan Gohman045f8192010-01-22 00:46:49 +00002076///
2077/// This is a narrow solution to a specific, but acute, problem. For loops
2078/// like this:
2079///
2080/// i = 0;
2081/// do {
2082/// p[i] = 0.0;
2083/// } while (++i < n);
2084///
2085/// the trip count isn't just 'n', because 'n' might not be positive. And
2086/// unfortunately this can come up even for loops where the user didn't use
2087/// a C do-while loop. For example, seemingly well-behaved top-test loops
2088/// will commonly be lowered like this:
2089//
2090/// if (n > 0) {
2091/// i = 0;
2092/// do {
2093/// p[i] = 0.0;
2094/// } while (++i < n);
2095/// }
2096///
2097/// and then it's possible for subsequent optimization to obscure the if
2098/// test in such a way that indvars can't find it.
2099///
2100/// When indvars can't find the if test in loops like this, it creates a
2101/// max expression, which allows it to give the loop a canonical
2102/// induction variable:
2103///
2104/// i = 0;
2105/// max = n < 1 ? 1 : n;
2106/// do {
2107/// p[i] = 0.0;
2108/// } while (++i != max);
2109///
2110/// Canonical induction variables are necessary because the loop passes
2111/// are designed around them. The most obvious example of this is the
2112/// LoopInfo analysis, which doesn't remember trip count values. It
2113/// expects to be able to rediscover the trip count each time it is
Dan Gohman45774ce2010-02-12 10:34:29 +00002114/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman045f8192010-01-22 00:46:49 +00002115/// the loop has a canonical induction variable.
2116///
2117/// However, when it comes time to generate code, the maximum operation
2118/// can be quite costly, especially if it's inside of an outer loop.
2119///
2120/// This function solves this problem by detecting this type of loop and
2121/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2122/// the instructions for the maximum computation.
2123///
Dan Gohman45774ce2010-02-12 10:34:29 +00002124ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman045f8192010-01-22 00:46:49 +00002125 // Check that the loop matches the pattern we're looking for.
2126 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2127 Cond->getPredicate() != CmpInst::ICMP_NE)
2128 return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002129
Dan Gohman045f8192010-01-22 00:46:49 +00002130 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2131 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002132
Dan Gohman45774ce2010-02-12 10:34:29 +00002133 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman045f8192010-01-22 00:46:49 +00002134 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2135 return Cond;
Dan Gohman1d2ded72010-05-03 22:09:21 +00002136 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002137
Dan Gohman045f8192010-01-22 00:46:49 +00002138 // Add one to the backedge-taken count to get the trip count.
Dan Gohman9b7632d2010-08-16 15:39:27 +00002139 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
Dan Gohman534ba372010-04-24 03:13:44 +00002140 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00002141
Dan Gohman534ba372010-04-24 03:13:44 +00002142 // Check for a max calculation that matches the pattern. There's no check
2143 // for ICMP_ULE here because the comparison would be with zero, which
2144 // isn't interesting.
2145 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
Craig Topperf40110f2014-04-25 05:29:35 +00002146 const SCEVNAryExpr *Max = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00002147 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2148 Pred = ICmpInst::ICMP_SLE;
2149 Max = S;
2150 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2151 Pred = ICmpInst::ICMP_SLT;
2152 Max = S;
2153 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2154 Pred = ICmpInst::ICMP_ULT;
2155 Max = U;
2156 } else {
2157 // No match; bail.
Dan Gohman045f8192010-01-22 00:46:49 +00002158 return Cond;
Dan Gohman534ba372010-04-24 03:13:44 +00002159 }
Dan Gohman045f8192010-01-22 00:46:49 +00002160
2161 // To handle a max with more than two operands, this optimization would
2162 // require additional checking and setup.
2163 if (Max->getNumOperands() != 2)
2164 return Cond;
2165
2166 const SCEV *MaxLHS = Max->getOperand(0);
2167 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman534ba372010-04-24 03:13:44 +00002168
2169 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2170 // for a comparison with 1. For <= and >=, a comparison with zero.
2171 if (!MaxLHS ||
2172 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2173 return Cond;
2174
Dan Gohman045f8192010-01-22 00:46:49 +00002175 // Check the relevant induction variable for conformance to
2176 // the pattern.
Dan Gohman45774ce2010-02-12 10:34:29 +00002177 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00002178 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2179 if (!AR || !AR->isAffine() ||
2180 AR->getStart() != One ||
Dan Gohman45774ce2010-02-12 10:34:29 +00002181 AR->getStepRecurrence(SE) != One)
Dan Gohman045f8192010-01-22 00:46:49 +00002182 return Cond;
2183
2184 assert(AR->getLoop() == L &&
2185 "Loop condition operand is an addrec in a different loop!");
2186
2187 // Check the right operand of the select, and remember it, as it will
2188 // be used in the new comparison instruction.
Craig Topperf40110f2014-04-25 05:29:35 +00002189 Value *NewRHS = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00002190 if (ICmpInst::isTrueWhenEqual(Pred)) {
2191 // Look for n+1, and grab n.
2192 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002193 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2194 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2195 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002196 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002197 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2198 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2199 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002200 if (!NewRHS)
2201 return Cond;
2202 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002203 NewRHS = Sel->getOperand(1);
Dan Gohman45774ce2010-02-12 10:34:29 +00002204 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002205 NewRHS = Sel->getOperand(2);
Dan Gohman1081f1a2010-06-22 23:07:13 +00002206 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2207 NewRHS = SU->getValue();
Dan Gohman534ba372010-04-24 03:13:44 +00002208 else
Dan Gohman1081f1a2010-06-22 23:07:13 +00002209 // Max doesn't match expected pattern.
2210 return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00002211
2212 // Determine the new comparison opcode. It may be signed or unsigned,
2213 // and the original comparison may be either equality or inequality.
Dan Gohman045f8192010-01-22 00:46:49 +00002214 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2215 Pred = CmpInst::getInversePredicate(Pred);
2216
2217 // Ok, everything looks ok to change the condition into an SLT or SGE and
2218 // delete the max calculation.
2219 ICmpInst *NewCond =
2220 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2221
2222 // Delete the max calculation instructions.
2223 Cond->replaceAllUsesWith(NewCond);
2224 CondUse->setUser(NewCond);
2225 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2226 Cond->eraseFromParent();
2227 Sel->eraseFromParent();
2228 if (Cmp->use_empty())
2229 Cmp->eraseFromParent();
2230 return NewCond;
Dan Gohman68e77352008-09-15 21:22:06 +00002231}
2232
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002233/// Change loop terminating condition to use the postinc iv when possible.
Dan Gohman4c4043c2010-05-20 20:05:31 +00002234void
Dan Gohman45774ce2010-02-12 10:34:29 +00002235LSRInstance::OptimizeLoopTermCond() {
2236 SmallPtrSet<Instruction *, 4> PostIncs;
2237
James Molloy196ad082016-08-15 07:53:03 +00002238 // We need a different set of heuristics for rotated and non-rotated loops.
2239 // If a loop is rotated then the latch is also the backedge, so inserting
2240 // post-inc expressions just before the latch is ideal. To reduce live ranges
2241 // it also makes sense to rewrite terminating conditions to use post-inc
2242 // expressions.
2243 //
2244 // If the loop is not rotated then the latch is not a backedge; the latch
2245 // check is done in the loop head. Adding post-inc expressions before the
2246 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2247 // in the loop body. In this case we do *not* want to use post-inc expressions
2248 // in the latch check, and we want to insert post-inc expressions before
2249 // the backedge.
Evan Cheng85a9f432009-11-12 07:35:05 +00002250 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengba4e5da72009-11-17 18:10:11 +00002251 SmallVector<BasicBlock*, 8> ExitingBlocks;
2252 L->getExitingBlocks(ExitingBlocks);
James Molloy196ad082016-08-15 07:53:03 +00002253 if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) {
2254 return LatchBlock != BB;
2255 })) {
2256 // The backedge doesn't exit the loop; treat this as a head-tested loop.
2257 IVIncInsertPos = LatchBlock->getTerminator();
2258 return;
2259 }
Jim Grosbach60f48542009-11-17 17:53:56 +00002260
James Molloy196ad082016-08-15 07:53:03 +00002261 // Otherwise treat this as a rotated loop.
Craig Topper042a3922015-05-25 20:01:18 +00002262 for (BasicBlock *ExitingBlock : ExitingBlocks) {
Evan Cheng85a9f432009-11-12 07:35:05 +00002263
Dan Gohman45774ce2010-02-12 10:34:29 +00002264 // Get the terminating condition for the loop if possible. If we
Evan Chengba4e5da72009-11-17 18:10:11 +00002265 // can, we want to change it to use a post-incremented version of its
2266 // induction variable, to allow coalescing the live ranges for the IV into
2267 // one register value.
Evan Cheng85a9f432009-11-12 07:35:05 +00002268
Evan Chengba4e5da72009-11-17 18:10:11 +00002269 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2270 if (!TermBr)
2271 continue;
2272 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2273 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2274 continue;
Evan Cheng85a9f432009-11-12 07:35:05 +00002275
Evan Chengba4e5da72009-11-17 18:10:11 +00002276 // Search IVUsesByStride to find Cond's IVUse if there is one.
Craig Topperf40110f2014-04-25 05:29:35 +00002277 IVStrideUse *CondUse = nullptr;
Evan Chengba4e5da72009-11-17 18:10:11 +00002278 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman45774ce2010-02-12 10:34:29 +00002279 if (!FindIVUserForCond(Cond, CondUse))
Evan Chengba4e5da72009-11-17 18:10:11 +00002280 continue;
2281
Evan Chengba4e5da72009-11-17 18:10:11 +00002282 // If the trip count is computed in terms of a max (due to ScalarEvolution
2283 // being unable to find a sufficient guard, for example), change the loop
2284 // comparison to use SLT or ULT instead of NE.
Dan Gohman45774ce2010-02-12 10:34:29 +00002285 // One consequence of doing this now is that it disrupts the count-down
2286 // optimization. That's not always a bad thing though, because in such
2287 // cases it may still be worthwhile to avoid a max.
2288 Cond = OptimizeMax(Cond, CondUse);
Evan Chengba4e5da72009-11-17 18:10:11 +00002289
Dan Gohman45774ce2010-02-12 10:34:29 +00002290 // If this exiting block dominates the latch block, it may also use
2291 // the post-inc value if it won't be shared with other uses.
2292 // Check for dominance.
2293 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman045f8192010-01-22 00:46:49 +00002294 continue;
Evan Chengba4e5da72009-11-17 18:10:11 +00002295
Dan Gohman45774ce2010-02-12 10:34:29 +00002296 // Conservatively avoid trying to use the post-inc value in non-latch
2297 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman2d0f96d2010-02-14 03:21:49 +00002298 if (LatchBlock != ExitingBlock)
Dan Gohman45774ce2010-02-12 10:34:29 +00002299 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2300 // Test if the use is reachable from the exiting block. This dominator
2301 // query is a conservative approximation of reachability.
2302 if (&*UI != CondUse &&
2303 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2304 // Conservatively assume there may be reuse if the quotient of their
2305 // strides could be a legal scale.
Dan Gohmane637ff52010-04-19 21:48:58 +00002306 const SCEV *A = IU.getStride(*CondUse, L);
2307 const SCEV *B = IU.getStride(*UI, L);
Dan Gohmand006ab92010-04-07 22:27:08 +00002308 if (!A || !B) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00002309 if (SE.getTypeSizeInBits(A->getType()) !=
2310 SE.getTypeSizeInBits(B->getType())) {
2311 if (SE.getTypeSizeInBits(A->getType()) >
2312 SE.getTypeSizeInBits(B->getType()))
2313 B = SE.getSignExtendExpr(B, A->getType());
2314 else
2315 A = SE.getSignExtendExpr(A, B->getType());
2316 }
2317 if (const SCEVConstant *D =
Dan Gohman4eebb942010-02-19 19:35:48 +00002318 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman86110fa2010-05-20 22:25:20 +00002319 const ConstantInt *C = D->getValue();
Dan Gohman45774ce2010-02-12 10:34:29 +00002320 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman86110fa2010-05-20 22:25:20 +00002321 if (C->isOne() || C->isAllOnesValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002322 goto decline_post_inc;
2323 // Avoid weird situations.
Dan Gohman86110fa2010-05-20 22:25:20 +00002324 if (C->getValue().getMinSignedBits() >= 64 ||
2325 C->getValue().isMinSignedValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002326 goto decline_post_inc;
2327 // Check for possible scaled-address reuse.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002328 MemAccessTy AccessTy = getAccessType(UI->getUser());
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002329 int64_t Scale = C->getSExtValue();
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002330 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2331 /*BaseOffset=*/0,
2332 /*HasBaseReg=*/false, Scale,
2333 AccessTy.AddrSpace))
Dan Gohman45774ce2010-02-12 10:34:29 +00002334 goto decline_post_inc;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002335 Scale = -Scale;
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002336 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2337 /*BaseOffset=*/0,
2338 /*HasBaseReg=*/false, Scale,
2339 AccessTy.AddrSpace))
Dan Gohman45774ce2010-02-12 10:34:29 +00002340 goto decline_post_inc;
2341 }
2342 }
2343
David Greene2330f782009-12-23 22:58:38 +00002344 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman45774ce2010-02-12 10:34:29 +00002345 << *Cond << '\n');
Evan Chengba4e5da72009-11-17 18:10:11 +00002346
2347 // It's possible for the setcc instruction to be anywhere in the loop, and
2348 // possible for it to have multiple users. If it is not immediately before
2349 // the exiting block branch, move it.
Dan Gohman45774ce2010-02-12 10:34:29 +00002350 if (&*++BasicBlock::iterator(Cond) != TermBr) {
2351 if (Cond->hasOneUse()) {
Evan Chengba4e5da72009-11-17 18:10:11 +00002352 Cond->moveBefore(TermBr);
2353 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00002354 // Clone the terminating condition and insert into the loopend.
2355 ICmpInst *OldCond = Cond;
Evan Chengba4e5da72009-11-17 18:10:11 +00002356 Cond = cast<ICmpInst>(Cond->clone());
2357 Cond->setName(L->getHeader()->getName() + ".termcond");
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002358 ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
Evan Chengba4e5da72009-11-17 18:10:11 +00002359
2360 // Clone the IVUse, as the old use still exists!
Andrew Trickfc4ccb22011-06-21 15:43:52 +00002361 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman45774ce2010-02-12 10:34:29 +00002362 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Chengba4e5da72009-11-17 18:10:11 +00002363 }
Evan Cheng85a9f432009-11-12 07:35:05 +00002364 }
2365
Evan Chengba4e5da72009-11-17 18:10:11 +00002366 // If we get to here, we know that we can transform the setcc instruction to
2367 // use the post-incremented version of the IV, allowing us to coalesce the
2368 // live ranges for the IV correctly.
Dan Gohmand006ab92010-04-07 22:27:08 +00002369 CondUse->transformToPostInc(L);
Evan Chengba4e5da72009-11-17 18:10:11 +00002370 Changed = true;
2371
Dan Gohman45774ce2010-02-12 10:34:29 +00002372 PostIncs.insert(Cond);
2373 decline_post_inc:;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002374 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002375
2376 // Determine an insertion point for the loop induction variable increment. It
2377 // must dominate all the post-inc comparisons we just set up, and it must
2378 // dominate the loop latch edge.
2379 IVIncInsertPos = L->getLoopLatch()->getTerminator();
Craig Topper46276792014-08-24 23:23:06 +00002380 for (Instruction *Inst : PostIncs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002381 BasicBlock *BB =
2382 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
Craig Topper46276792014-08-24 23:23:06 +00002383 Inst->getParent());
2384 if (BB == Inst->getParent())
2385 IVIncInsertPos = Inst;
Dan Gohman45774ce2010-02-12 10:34:29 +00002386 else if (BB != IVIncInsertPos->getParent())
2387 IVIncInsertPos = BB->getTerminator();
2388 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00002389}
2390
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002391/// Determine if the given use can accommodate a fixup at the given offset and
2392/// other details. If so, update the use and return true.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002393bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2394 bool HasBaseReg, LSRUse::KindType Kind,
2395 MemAccessTy AccessTy) {
Dan Gohman110ed642010-09-01 01:45:53 +00002396 int64_t NewMinOffset = LU.MinOffset;
2397 int64_t NewMaxOffset = LU.MaxOffset;
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002398 MemAccessTy NewAccessTy = AccessTy;
Dan Gohman045f8192010-01-22 00:46:49 +00002399
Dan Gohman45774ce2010-02-12 10:34:29 +00002400 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2401 // something conservative, however this can pessimize in the case that one of
2402 // the uses will have all its uses outside the loop, for example.
2403 if (LU.Kind != Kind)
Dan Gohman045f8192010-01-22 00:46:49 +00002404 return false;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002405
Dan Gohman45774ce2010-02-12 10:34:29 +00002406 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman32655902010-06-19 21:30:18 +00002407 // TODO: Be less conservative when the type is similar and can use the same
2408 // addressing modes.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002409 if (Kind == LSRUse::Address) {
Matt Arsenault1f2ca662017-01-30 19:50:17 +00002410 if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2411 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2412 AccessTy.AddrSpace);
2413 }
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002414 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00002415
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002416 // Conservatively assume HasBaseReg is true for now.
2417 if (NewOffset < LU.MinOffset) {
2418 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2419 LU.MaxOffset - NewOffset, HasBaseReg))
2420 return false;
2421 NewMinOffset = NewOffset;
2422 } else if (NewOffset > LU.MaxOffset) {
2423 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2424 NewOffset - LU.MinOffset, HasBaseReg))
2425 return false;
2426 NewMaxOffset = NewOffset;
2427 }
2428
Dan Gohman45774ce2010-02-12 10:34:29 +00002429 // Update the use.
Dan Gohman110ed642010-09-01 01:45:53 +00002430 LU.MinOffset = NewMinOffset;
2431 LU.MaxOffset = NewMaxOffset;
2432 LU.AccessTy = NewAccessTy;
Dan Gohman29916e02010-01-21 22:42:49 +00002433 return true;
2434}
2435
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002436/// Return an LSRUse index and an offset value for a fixup which needs the given
2437/// expression, with the given kind and optional access type. Either reuse an
2438/// existing use or create a new one, as needed.
Matt Arsenault427a0fd2015-08-15 00:53:06 +00002439std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr,
2440 LSRUse::KindType Kind,
2441 MemAccessTy AccessTy) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002442 const SCEV *Copy = Expr;
2443 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng85a9f432009-11-12 07:35:05 +00002444
Dan Gohman45774ce2010-02-12 10:34:29 +00002445 // Basic uses can't accept any offset, for example.
Craig Topperf40110f2014-04-25 05:29:35 +00002446 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002447 Offset, /*HasBaseReg=*/ true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002448 Expr = Copy;
2449 Offset = 0;
2450 }
2451
2452 std::pair<UseMapTy::iterator, bool> P =
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00002453 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
Dan Gohman45774ce2010-02-12 10:34:29 +00002454 if (!P.second) {
2455 // A use already existed with this base.
2456 size_t LUIdx = P.first->second;
2457 LSRUse &LU = Uses[LUIdx];
Dan Gohman110ed642010-09-01 01:45:53 +00002458 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman45774ce2010-02-12 10:34:29 +00002459 // Reuse this use.
2460 return std::make_pair(LUIdx, Offset);
2461 }
2462
2463 // Create a new use.
2464 size_t LUIdx = Uses.size();
2465 P.first->second = LUIdx;
2466 Uses.push_back(LSRUse(Kind, AccessTy));
2467 LSRUse &LU = Uses[LUIdx];
2468
Dan Gohman45774ce2010-02-12 10:34:29 +00002469 LU.MinOffset = Offset;
2470 LU.MaxOffset = Offset;
2471 return std::make_pair(LUIdx, Offset);
2472}
2473
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002474/// Delete the given use from the Uses list.
Dan Gohmana7b68d62010-10-07 23:33:43 +00002475void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
Dan Gohman110ed642010-09-01 01:45:53 +00002476 if (&LU != &Uses.back())
Dan Gohman80a96082010-05-20 15:17:54 +00002477 std::swap(LU, Uses.back());
2478 Uses.pop_back();
Dan Gohmana7b68d62010-10-07 23:33:43 +00002479
2480 // Update RegUses.
Sanjoy Das302bfd02015-08-16 18:22:43 +00002481 RegUses.swapAndDropUse(LUIdx, Uses.size());
Dan Gohman80a96082010-05-20 15:17:54 +00002482}
2483
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002484/// Look for a use distinct from OrigLU which is has a formula that has the same
2485/// registers as the given formula.
Dan Gohman20fab452010-05-19 23:43:12 +00002486LSRUse *
2487LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
Dan Gohman110ed642010-09-01 01:45:53 +00002488 const LSRUse &OrigLU) {
2489 // Search all uses for the formula. This could be more clever.
Dan Gohman20fab452010-05-19 23:43:12 +00002490 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2491 LSRUse &LU = Uses[LUIdx];
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002492 // Check whether this use is close enough to OrigLU, to see whether it's
2493 // worthwhile looking through its formulae.
2494 // Ignore ICmpZero uses because they may contain formulae generated by
2495 // GenerateICmpZeroScales, in which case adding fixup offsets may
2496 // be invalid.
Dan Gohman20fab452010-05-19 23:43:12 +00002497 if (&LU != &OrigLU &&
2498 LU.Kind != LSRUse::ICmpZero &&
2499 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
Dan Gohman14152082010-07-15 20:24:58 +00002500 LU.WidestFixupType == OrigLU.WidestFixupType &&
Dan Gohman20fab452010-05-19 23:43:12 +00002501 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002502 // Scan through this use's formulae.
Craig Topper042a3922015-05-25 20:01:18 +00002503 for (const Formula &F : LU.Formulae) {
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002504 // Check to see if this formula has the same registers and symbols
2505 // as OrigF.
Dan Gohman20fab452010-05-19 23:43:12 +00002506 if (F.BaseRegs == OrigF.BaseRegs &&
2507 F.ScaledReg == OrigF.ScaledReg &&
Chandler Carruth6e479322013-01-07 15:04:40 +00002508 F.BaseGV == OrigF.BaseGV &&
2509 F.Scale == OrigF.Scale &&
Dan Gohman6136e942011-05-03 00:46:49 +00002510 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
Chandler Carruth6e479322013-01-07 15:04:40 +00002511 if (F.BaseOffset == 0)
Dan Gohman20fab452010-05-19 23:43:12 +00002512 return &LU;
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002513 // This is the formula where all the registers and symbols matched;
2514 // there aren't going to be any others. Since we declined it, we
Benjamin Kramerbde91762012-06-02 10:20:22 +00002515 // can skip the rest of the formulae and proceed to the next LSRUse.
Dan Gohman20fab452010-05-19 23:43:12 +00002516 break;
2517 }
2518 }
2519 }
2520 }
2521
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002522 // Nothing looked good.
Craig Topperf40110f2014-04-25 05:29:35 +00002523 return nullptr;
Dan Gohman20fab452010-05-19 23:43:12 +00002524}
2525
Dan Gohman45774ce2010-02-12 10:34:29 +00002526void LSRInstance::CollectInterestingTypesAndFactors() {
2527 SmallSetVector<const SCEV *, 4> Strides;
2528
Dan Gohman2446f572010-02-19 00:05:23 +00002529 // Collect interesting types and strides.
Dan Gohmand006ab92010-04-07 22:27:08 +00002530 SmallVector<const SCEV *, 4> Worklist;
Craig Topper042a3922015-05-25 20:01:18 +00002531 for (const IVStrideUse &U : IU) {
2532 const SCEV *Expr = IU.getExpr(U);
Dan Gohman45774ce2010-02-12 10:34:29 +00002533
2534 // Collect interesting types.
Dan Gohmand006ab92010-04-07 22:27:08 +00002535 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman45774ce2010-02-12 10:34:29 +00002536
Dan Gohmand006ab92010-04-07 22:27:08 +00002537 // Add strides for mentioned loops.
2538 Worklist.push_back(Expr);
2539 do {
2540 const SCEV *S = Worklist.pop_back_val();
2541 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
Andrew Trickd97b83e2012-03-22 22:42:45 +00002542 if (AR->getLoop() == L)
Andrew Tricke8b4f402011-12-10 00:25:00 +00002543 Strides.insert(AR->getStepRecurrence(SE));
Dan Gohmand006ab92010-04-07 22:27:08 +00002544 Worklist.push_back(AR->getStart());
2545 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002546 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohmand006ab92010-04-07 22:27:08 +00002547 }
2548 } while (!Worklist.empty());
Dan Gohman2446f572010-02-19 00:05:23 +00002549 }
2550
2551 // Compute interesting factors from the set of interesting strides.
2552 for (SmallSetVector<const SCEV *, 4>::const_iterator
2553 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman45774ce2010-02-12 10:34:29 +00002554 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002555 std::next(I); NewStrideIter != E; ++NewStrideIter) {
Dan Gohman2446f572010-02-19 00:05:23 +00002556 const SCEV *OldStride = *I;
Dan Gohman45774ce2010-02-12 10:34:29 +00002557 const SCEV *NewStride = *NewStrideIter;
Dan Gohman45774ce2010-02-12 10:34:29 +00002558
2559 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2560 SE.getTypeSizeInBits(NewStride->getType())) {
2561 if (SE.getTypeSizeInBits(OldStride->getType()) >
2562 SE.getTypeSizeInBits(NewStride->getType()))
2563 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2564 else
2565 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2566 }
2567 if (const SCEVConstant *Factor =
Dan Gohman4eebb942010-02-19 19:35:48 +00002568 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2569 SE, true))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002570 if (Factor->getAPInt().getMinSignedBits() <= 64)
2571 Factors.insert(Factor->getAPInt().getSExtValue());
Dan Gohman45774ce2010-02-12 10:34:29 +00002572 } else if (const SCEVConstant *Factor =
Dan Gohman8c16b382010-02-22 04:11:59 +00002573 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2574 NewStride,
Dan Gohman4eebb942010-02-19 19:35:48 +00002575 SE, true))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002576 if (Factor->getAPInt().getMinSignedBits() <= 64)
2577 Factors.insert(Factor->getAPInt().getSExtValue());
Dan Gohman45774ce2010-02-12 10:34:29 +00002578 }
2579 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002580
2581 // If all uses use the same type, don't bother looking for truncation-based
2582 // reuse.
2583 if (Types.size() == 1)
2584 Types.clear();
2585
2586 DEBUG(print_factors_and_types(dbgs()));
2587}
2588
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002589/// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2590/// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2591/// IVStrideUses, we could partially skip this.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002592static User::op_iterator
2593findIVOperand(User::op_iterator OI, User::op_iterator OE,
2594 Loop *L, ScalarEvolution &SE) {
2595 for(; OI != OE; ++OI) {
2596 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2597 if (!SE.isSCEVable(Oper->getType()))
2598 continue;
2599
2600 if (const SCEVAddRecExpr *AR =
2601 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2602 if (AR->getLoop() == L)
2603 break;
2604 }
2605 }
2606 }
2607 return OI;
2608}
2609
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002610/// IVChain logic must consistenctly peek base TruncInst operands, so wrap it in
2611/// a convenient helper.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002612static Value *getWideOperand(Value *Oper) {
2613 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2614 return Trunc->getOperand(0);
2615 return Oper;
2616}
2617
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002618/// Return true if we allow an IV chain to include both types.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002619static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2620 Type *LType = LVal->getType();
2621 Type *RType = RVal->getType();
Mikael Holmenece84cd2017-02-14 06:37:42 +00002622 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() &&
2623 // Different address spaces means (possibly)
2624 // different types of the pointer implementation,
2625 // e.g. i16 vs i32 so disallow that.
2626 (LType->getPointerAddressSpace() ==
2627 RType->getPointerAddressSpace()));
Andrew Trick29fe5f02012-01-09 19:50:34 +00002628}
2629
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002630/// Return an approximation of this SCEV expression's "base", or NULL for any
2631/// constant. Returning the expression itself is conservative. Returning a
2632/// deeper subexpression is more precise and valid as long as it isn't less
2633/// complex than another subexpression. For expressions involving multiple
2634/// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2635/// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2636/// IVInc==b-a.
Andrew Trickd5d2db92012-01-10 01:45:08 +00002637///
2638/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2639/// SCEVUnknown, we simply return the rightmost SCEV operand.
2640static const SCEV *getExprBase(const SCEV *S) {
2641 switch (S->getSCEVType()) {
2642 default: // uncluding scUnknown.
2643 return S;
2644 case scConstant:
Craig Topperf40110f2014-04-25 05:29:35 +00002645 return nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002646 case scTruncate:
2647 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2648 case scZeroExtend:
2649 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2650 case scSignExtend:
2651 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2652 case scAddExpr: {
2653 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2654 // there's nothing more complex.
2655 // FIXME: not sure if we want to recognize negation.
2656 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2657 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2658 E(Add->op_begin()); I != E; ++I) {
2659 const SCEV *SubExpr = *I;
2660 if (SubExpr->getSCEVType() == scAddExpr)
2661 return getExprBase(SubExpr);
2662
2663 if (SubExpr->getSCEVType() != scMulExpr)
2664 return SubExpr;
2665 }
2666 return S; // all operands are scaled, be conservative.
2667 }
2668 case scAddRecExpr:
2669 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2670 }
2671}
2672
Andrew Trick248d4102012-01-09 21:18:52 +00002673/// Return true if the chain increment is profitable to expand into a loop
2674/// invariant value, which may require its own register. A profitable chain
2675/// increment will be an offset relative to the same base. We allow such offsets
2676/// to potentially be used as chain increment as long as it's not obviously
2677/// expensive to expand using real instructions.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002678bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2679 const SCEV *IncExpr,
2680 ScalarEvolution &SE) {
2681 // Aggressively form chains when -stress-ivchain.
Andrew Trick248d4102012-01-09 21:18:52 +00002682 if (StressIVChain)
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002683 return true;
Andrew Trick248d4102012-01-09 21:18:52 +00002684
Andrew Trickd5d2db92012-01-10 01:45:08 +00002685 // Do not replace a constant offset from IV head with a nonconstant IV
2686 // increment.
2687 if (!isa<SCEVConstant>(IncExpr)) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002688 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
Andrew Trickd5d2db92012-01-10 01:45:08 +00002689 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00002690 return false;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002691 }
2692
2693 SmallPtrSet<const SCEV*, 8> Processed;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002694 return !isHighCostExpansion(IncExpr, Processed, SE);
Andrew Trick248d4102012-01-09 21:18:52 +00002695}
2696
2697/// Return true if the number of registers needed for the chain is estimated to
2698/// be less than the number required for the individual IV users. First prohibit
2699/// any IV users that keep the IV live across increments (the Users set should
2700/// be empty). Next count the number and type of increments in the chain.
2701///
2702/// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2703/// effectively use postinc addressing modes. Only consider it profitable it the
2704/// increments can be computed in fewer registers when chained.
2705///
2706/// TODO: Consider IVInc free if it's already used in another chains.
2707static bool
Craig Topper71b7b682014-08-21 05:55:13 +00002708isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002709 ScalarEvolution &SE, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002710 if (StressIVChain)
2711 return true;
2712
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002713 if (!Chain.hasIncs())
Andrew Trickd5d2db92012-01-10 01:45:08 +00002714 return false;
2715
2716 if (!Users.empty()) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002717 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
Craig Topper46276792014-08-24 23:23:06 +00002718 for (Instruction *Inst : Users) {
2719 dbgs() << " " << *Inst << "\n";
Andrew Trickd5d2db92012-01-10 01:45:08 +00002720 });
2721 return false;
2722 }
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002723 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002724
2725 // The chain itself may require a register, so intialize cost to 1.
2726 int cost = 1;
2727
2728 // A complete chain likely eliminates the need for keeping the original IV in
2729 // a register. LSR does not currently know how to form a complete chain unless
2730 // the header phi already exists.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002731 if (isa<PHINode>(Chain.tailUserInst())
2732 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
Andrew Trickd5d2db92012-01-10 01:45:08 +00002733 --cost;
2734 }
Craig Topperf40110f2014-04-25 05:29:35 +00002735 const SCEV *LastIncExpr = nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002736 unsigned NumConstIncrements = 0;
2737 unsigned NumVarIncrements = 0;
2738 unsigned NumReusedIncrements = 0;
Craig Topper042a3922015-05-25 20:01:18 +00002739 for (const IVInc &Inc : Chain) {
2740 if (Inc.IncExpr->isZero())
Andrew Trickd5d2db92012-01-10 01:45:08 +00002741 continue;
2742
2743 // Incrementing by zero or some constant is neutral. We assume constants can
2744 // be folded into an addressing mode or an add's immediate operand.
Craig Topper042a3922015-05-25 20:01:18 +00002745 if (isa<SCEVConstant>(Inc.IncExpr)) {
Andrew Trickd5d2db92012-01-10 01:45:08 +00002746 ++NumConstIncrements;
2747 continue;
2748 }
2749
Craig Topper042a3922015-05-25 20:01:18 +00002750 if (Inc.IncExpr == LastIncExpr)
Andrew Trickd5d2db92012-01-10 01:45:08 +00002751 ++NumReusedIncrements;
2752 else
2753 ++NumVarIncrements;
2754
Craig Topper042a3922015-05-25 20:01:18 +00002755 LastIncExpr = Inc.IncExpr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002756 }
2757 // An IV chain with a single increment is handled by LSR's postinc
2758 // uses. However, a chain with multiple increments requires keeping the IV's
2759 // value live longer than it needs to be if chained.
2760 if (NumConstIncrements > 1)
2761 --cost;
2762
2763 // Materializing increment expressions in the preheader that didn't exist in
2764 // the original code may cost a register. For example, sign-extended array
2765 // indices can produce ridiculous increments like this:
2766 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2767 cost += NumVarIncrements;
2768
2769 // Reusing variable increments likely saves a register to hold the multiple of
2770 // the stride.
2771 cost -= NumReusedIncrements;
2772
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002773 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2774 << "\n");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002775
2776 return cost < 0;
Andrew Trick248d4102012-01-09 21:18:52 +00002777}
2778
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002779/// Add this IV user to an existing chain or make it the head of a new chain.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002780void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2781 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2782 // When IVs are used as types of varying widths, they are generally converted
2783 // to a wider type with some uses remaining narrow under a (free) trunc.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002784 Value *const NextIV = getWideOperand(IVOper);
2785 const SCEV *const OperExpr = SE.getSCEV(NextIV);
2786 const SCEV *const OperExprBase = getExprBase(OperExpr);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002787
2788 // Visit all existing chains. Check if its IVOper can be computed as a
2789 // profitable loop invariant increment from the last link in the Chain.
2790 unsigned ChainIdx = 0, NChains = IVChainVec.size();
Craig Topperf40110f2014-04-25 05:29:35 +00002791 const SCEV *LastIncExpr = nullptr;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002792 for (; ChainIdx < NChains; ++ChainIdx) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002793 IVChain &Chain = IVChainVec[ChainIdx];
2794
2795 // Prune the solution space aggressively by checking that both IV operands
2796 // are expressions that operate on the same unscaled SCEVUnknown. This
2797 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2798 // first avoids creating extra SCEV expressions.
2799 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2800 continue;
2801
2802 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002803 if (!isCompatibleIVType(PrevIV, NextIV))
2804 continue;
2805
Andrew Trick356a8962012-03-26 20:28:35 +00002806 // A phi node terminates a chain.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002807 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002808 continue;
2809
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002810 // The increment must be loop-invariant so it can be kept in a register.
2811 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2812 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2813 if (!SE.isLoopInvariant(IncExpr, L))
2814 continue;
2815
2816 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002817 LastIncExpr = IncExpr;
2818 break;
2819 }
2820 }
2821 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2822 // bother for phi nodes, because they must be last in the chain.
2823 if (ChainIdx == NChains) {
2824 if (isa<PHINode>(UserInst))
2825 return;
Andrew Trick248d4102012-01-09 21:18:52 +00002826 if (NChains >= MaxChains && !StressIVChain) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002827 DEBUG(dbgs() << "IV Chain Limit\n");
2828 return;
2829 }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002830 LastIncExpr = OperExpr;
Andrew Trickb9c822a2012-01-20 21:23:40 +00002831 // IVUsers may have skipped over sign/zero extensions. We don't currently
2832 // attempt to form chains involving extensions unless they can be hoisted
2833 // into this loop's AddRec.
2834 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2835 return;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002836 ++NChains;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002837 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2838 OperExprBase));
Andrew Trick29fe5f02012-01-09 19:50:34 +00002839 ChainUsersVec.resize(NChains);
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002840 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2841 << ") IV=" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002842 } else {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002843 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2844 << ") IV+" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002845 // Add this IV user to the end of the chain.
2846 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2847 }
Andrew Trickbc705902013-02-09 01:11:01 +00002848 IVChain &Chain = IVChainVec[ChainIdx];
Andrew Trick29fe5f02012-01-09 19:50:34 +00002849
2850 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2851 // This chain's NearUsers become FarUsers.
2852 if (!LastIncExpr->isZero()) {
2853 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2854 NearUsers.end());
2855 NearUsers.clear();
2856 }
2857
2858 // All other uses of IVOperand become near uses of the chain.
2859 // We currently ignore intermediate values within SCEV expressions, assuming
2860 // they will eventually be used be the current chain, or can be computed
2861 // from one of the chain increments. To be more precise we could
2862 // transitively follow its user and only add leaf IV users to the set.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002863 for (User *U : IVOper->users()) {
2864 Instruction *OtherUse = dyn_cast<Instruction>(U);
Andrew Trickbc705902013-02-09 01:11:01 +00002865 if (!OtherUse)
Andrew Tricke51feea2012-03-26 18:03:16 +00002866 continue;
Andrew Trickbc705902013-02-09 01:11:01 +00002867 // Uses in the chain will no longer be uses if the chain is formed.
2868 // Include the head of the chain in this iteration (not Chain.begin()).
2869 IVChain::const_iterator IncIter = Chain.Incs.begin();
2870 IVChain::const_iterator IncEnd = Chain.Incs.end();
2871 for( ; IncIter != IncEnd; ++IncIter) {
2872 if (IncIter->UserInst == OtherUse)
2873 break;
2874 }
2875 if (IncIter != IncEnd)
2876 continue;
2877
Andrew Trick29fe5f02012-01-09 19:50:34 +00002878 if (SE.isSCEVable(OtherUse->getType())
2879 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2880 && IU.isIVUserOrOperand(OtherUse)) {
2881 continue;
2882 }
Andrew Tricke51feea2012-03-26 18:03:16 +00002883 NearUsers.insert(OtherUse);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002884 }
2885
2886 // Since this user is part of the chain, it's no longer considered a use
2887 // of the chain.
2888 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2889}
2890
Sanjoy Das94c4aec2015-08-16 18:22:46 +00002891/// Populate the vector of Chains.
Andrew Trick29fe5f02012-01-09 19:50:34 +00002892///
2893/// This decreases ILP at the architecture level. Targets with ample registers,
2894/// multiple memory ports, and no register renaming probably don't want
2895/// this. However, such targets should probably disable LSR altogether.
2896///
2897/// The job of LSR is to make a reasonable choice of induction variables across
2898/// the loop. Subsequent passes can easily "unchain" computation exposing more
2899/// ILP *within the loop* if the target wants it.
2900///
2901/// Finding the best IV chain is potentially a scheduling problem. Since LSR
2902/// will not reorder memory operations, it will recognize this as a chain, but
2903/// will generate redundant IV increments. Ideally this would be corrected later
2904/// by a smart scheduler:
2905/// = A[i]
2906/// = A[i+x]
2907/// A[i] =
2908/// A[i+x] =
2909///
2910/// TODO: Walk the entire domtree within this loop, not just the path to the
2911/// loop latch. This will discover chains on side paths, but requires
2912/// maintaining multiple copies of the Chains state.
2913void LSRInstance::CollectChains() {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002914 DEBUG(dbgs() << "Collecting IV Chains.\n");
Andrew Trick29fe5f02012-01-09 19:50:34 +00002915 SmallVector<ChainUsers, 8> ChainUsersVec;
2916
2917 SmallVector<BasicBlock *,8> LatchPath;
2918 BasicBlock *LoopHeader = L->getHeader();
2919 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
2920 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2921 LatchPath.push_back(Rung->getBlock());
2922 }
2923 LatchPath.push_back(LoopHeader);
2924
2925 // Walk the instruction stream from the loop header to the loop latch.
David Majnemerd7708772016-06-24 04:05:21 +00002926 for (BasicBlock *BB : reverse(LatchPath)) {
2927 for (Instruction &I : *BB) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002928 // Skip instructions that weren't seen by IVUsers analysis.
David Majnemerd7708772016-06-24 04:05:21 +00002929 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002930 continue;
2931
2932 // Ignore users that are part of a SCEV expression. This way we only
2933 // consider leaf IV Users. This effectively rediscovers a portion of
2934 // IVUsers analysis but in program order this time.
David Majnemerd7708772016-06-24 04:05:21 +00002935 if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002936 continue;
2937
2938 // Remove this instruction from any NearUsers set it may be in.
2939 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
2940 ChainIdx < NChains; ++ChainIdx) {
David Majnemerd7708772016-06-24 04:05:21 +00002941 ChainUsersVec[ChainIdx].NearUsers.erase(&I);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002942 }
2943 // Search for operands that can be chained.
2944 SmallPtrSet<Instruction*, 4> UniqueOperands;
David Majnemerd7708772016-06-24 04:05:21 +00002945 User::op_iterator IVOpEnd = I.op_end();
2946 User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002947 while (IVOpIter != IVOpEnd) {
2948 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
David Blaikie70573dc2014-11-19 07:49:26 +00002949 if (UniqueOperands.insert(IVOpInst).second)
David Majnemerd7708772016-06-24 04:05:21 +00002950 ChainInstruction(&I, IVOpInst, ChainUsersVec);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002951 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002952 }
2953 } // Continue walking down the instructions.
2954 } // Continue walking down the domtree.
2955 // Visit phi backedges to determine if the chain can generate the IV postinc.
2956 for (BasicBlock::iterator I = L->getHeader()->begin();
2957 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2958 if (!SE.isSCEVable(PN->getType()))
2959 continue;
2960
2961 Instruction *IncV =
2962 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
2963 if (IncV)
2964 ChainInstruction(PN, IncV, ChainUsersVec);
2965 }
Andrew Trick248d4102012-01-09 21:18:52 +00002966 // Remove any unprofitable chains.
2967 unsigned ChainIdx = 0;
2968 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
2969 UsersIdx < NChains; ++UsersIdx) {
2970 if (!isProfitableChain(IVChainVec[UsersIdx],
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002971 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
Andrew Trick248d4102012-01-09 21:18:52 +00002972 continue;
2973 // Preserve the chain at UsesIdx.
2974 if (ChainIdx != UsersIdx)
2975 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
2976 FinalizeChain(IVChainVec[ChainIdx]);
2977 ++ChainIdx;
2978 }
2979 IVChainVec.resize(ChainIdx);
2980}
2981
2982void LSRInstance::FinalizeChain(IVChain &Chain) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002983 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2984 DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
Andrew Trick248d4102012-01-09 21:18:52 +00002985
Craig Topper042a3922015-05-25 20:01:18 +00002986 for (const IVInc &Inc : Chain) {
Evgeny Stupachenko8efbe6a2016-11-21 21:55:03 +00002987 DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");
David Majnemer42531262016-08-12 03:55:06 +00002988 auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);
Craig Topper042a3922015-05-25 20:01:18 +00002989 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
Andrew Trick248d4102012-01-09 21:18:52 +00002990 IVIncSet.insert(UseI);
2991 }
2992}
2993
2994/// Return true if the IVInc can be folded into an addressing mode.
2995static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002996 Value *Operand, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002997 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
2998 if (!IncConst || !isAddressUse(UserInst, Operand))
2999 return false;
3000
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003001 if (IncConst->getAPInt().getMinSignedBits() > 64)
Andrew Trick248d4102012-01-09 21:18:52 +00003002 return false;
3003
Matt Arsenault427a0fd2015-08-15 00:53:06 +00003004 MemAccessTy AccessTy = getAccessType(UserInst);
Andrew Trick248d4102012-01-09 21:18:52 +00003005 int64_t IncOffset = IncConst->getValue()->getSExtValue();
Matt Arsenault427a0fd2015-08-15 00:53:06 +00003006 if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
3007 IncOffset, /*HaseBaseReg=*/false))
Andrew Trick248d4102012-01-09 21:18:52 +00003008 return false;
3009
3010 return true;
3011}
3012
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003013/// Generate an add or subtract for each IVInc in a chain to materialize the IV
3014/// user's operand from the previous IV user's operand.
Andrew Trick248d4102012-01-09 21:18:52 +00003015void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00003016 SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
Andrew Trick248d4102012-01-09 21:18:52 +00003017 // Find the new IVOperand for the head of the chain. It may have been replaced
3018 // by LSR.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00003019 const IVInc &Head = Chain.Incs[0];
Andrew Trick248d4102012-01-09 21:18:52 +00003020 User::op_iterator IVOpEnd = Head.UserInst->op_end();
Andrew Trickf3a25442013-03-19 05:10:27 +00003021 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
Andrew Trick248d4102012-01-09 21:18:52 +00003022 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
3023 IVOpEnd, L, SE);
Craig Topperf40110f2014-04-25 05:29:35 +00003024 Value *IVSrc = nullptr;
Andrew Trickf3a25442013-03-19 05:10:27 +00003025 while (IVOpIter != IVOpEnd) {
Andrew Trick248d4102012-01-09 21:18:52 +00003026 IVSrc = getWideOperand(*IVOpIter);
3027
3028 // If this operand computes the expression that the chain needs, we may use
3029 // it. (Check this after setting IVSrc which is used below.)
3030 //
3031 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
3032 // narrow for the chain, so we can no longer use it. We do allow using a
3033 // wider phi, assuming the LSR checked for free truncation. In that case we
3034 // should already have a truncate on this operand such that
3035 // getSCEV(IVSrc) == IncExpr.
3036 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
3037 || SE.getSCEV(IVSrc) == Head.IncExpr) {
3038 break;
3039 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003040 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trickf3a25442013-03-19 05:10:27 +00003041 }
Andrew Trick248d4102012-01-09 21:18:52 +00003042 if (IVOpIter == IVOpEnd) {
3043 // Gracefully give up on this chain.
3044 DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
3045 return;
3046 }
3047
3048 DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
3049 Type *IVTy = IVSrc->getType();
3050 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
Craig Topperf40110f2014-04-25 05:29:35 +00003051 const SCEV *LeftOverExpr = nullptr;
Craig Topper042a3922015-05-25 20:01:18 +00003052 for (const IVInc &Inc : Chain) {
3053 Instruction *InsertPt = Inc.UserInst;
Andrew Trick248d4102012-01-09 21:18:52 +00003054 if (isa<PHINode>(InsertPt))
3055 InsertPt = L->getLoopLatch()->getTerminator();
3056
3057 // IVOper will replace the current IV User's operand. IVSrc is the IV
3058 // value currently held in a register.
3059 Value *IVOper = IVSrc;
Craig Topper042a3922015-05-25 20:01:18 +00003060 if (!Inc.IncExpr->isZero()) {
Andrew Trick248d4102012-01-09 21:18:52 +00003061 // IncExpr was the result of subtraction of two narrow values, so must
3062 // be signed.
Craig Topper042a3922015-05-25 20:01:18 +00003063 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
Andrew Trick248d4102012-01-09 21:18:52 +00003064 LeftOverExpr = LeftOverExpr ?
3065 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3066 }
3067 if (LeftOverExpr && !LeftOverExpr->isZero()) {
3068 // Expand the IV increment.
3069 Rewriter.clearPostInc();
3070 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
3071 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
3072 SE.getUnknown(IncV));
3073 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
3074
3075 // If an IV increment can't be folded, use it as the next IV value.
Craig Topper042a3922015-05-25 20:01:18 +00003076 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
Andrew Trick248d4102012-01-09 21:18:52 +00003077 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
3078 IVSrc = IVOper;
Craig Topperf40110f2014-04-25 05:29:35 +00003079 LeftOverExpr = nullptr;
Andrew Trick248d4102012-01-09 21:18:52 +00003080 }
3081 }
Craig Topper042a3922015-05-25 20:01:18 +00003082 Type *OperTy = Inc.IVOperand->getType();
Andrew Trick248d4102012-01-09 21:18:52 +00003083 if (IVTy != OperTy) {
3084 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
3085 "cannot extend a chained IV");
3086 IRBuilder<> Builder(InsertPt);
3087 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
3088 }
Craig Topper042a3922015-05-25 20:01:18 +00003089 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00003090 DeadInsts.emplace_back(Inc.IVOperand);
Andrew Trick248d4102012-01-09 21:18:52 +00003091 }
3092 // If LSR created a new, wider phi, we may also replace its postinc. We only
3093 // do this if we also found a wide value for the head of the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00003094 if (isa<PHINode>(Chain.tailUserInst())) {
Andrew Trick248d4102012-01-09 21:18:52 +00003095 for (BasicBlock::iterator I = L->getHeader()->begin();
3096 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
3097 if (!isCompatibleIVType(Phi, IVSrc))
3098 continue;
3099 Instruction *PostIncV = dyn_cast<Instruction>(
3100 Phi->getIncomingValueForBlock(L->getLoopLatch()));
3101 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
3102 continue;
3103 Value *IVOper = IVSrc;
3104 Type *PostIncTy = PostIncV->getType();
3105 if (IVTy != PostIncTy) {
3106 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
3107 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3108 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
3109 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
3110 }
3111 Phi->replaceUsesOfWith(PostIncV, IVOper);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00003112 DeadInsts.emplace_back(PostIncV);
Andrew Trick248d4102012-01-09 21:18:52 +00003113 }
3114 }
Andrew Trick29fe5f02012-01-09 19:50:34 +00003115}
3116
Dan Gohman45774ce2010-02-12 10:34:29 +00003117void LSRInstance::CollectFixupsAndInitialFormulae() {
Craig Topper042a3922015-05-25 20:01:18 +00003118 for (const IVStrideUse &U : IU) {
3119 Instruction *UserInst = U.getUser();
Andrew Trick248d4102012-01-09 21:18:52 +00003120 // Skip IV users that are part of profitable IV Chains.
David Majnemer42531262016-08-12 03:55:06 +00003121 User::op_iterator UseI =
3122 find(UserInst->operands(), U.getOperandValToReplace());
Andrew Trick248d4102012-01-09 21:18:52 +00003123 assert(UseI != UserInst->op_end() && "cannot find IV operand");
Quentin Colombet35109902017-01-28 01:05:27 +00003124 if (IVIncSet.count(UseI)) {
3125 DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');
Andrew Trick248d4102012-01-09 21:18:52 +00003126 continue;
Quentin Colombet35109902017-01-28 01:05:27 +00003127 }
Andrew Trick248d4102012-01-09 21:18:52 +00003128
Dan Gohman45774ce2010-02-12 10:34:29 +00003129 LSRUse::KindType Kind = LSRUse::Basic;
Matt Arsenault427a0fd2015-08-15 00:53:06 +00003130 MemAccessTy AccessTy;
Jonas Paulsson7a794222016-08-17 13:24:19 +00003131 if (isAddressUse(UserInst, U.getOperandValToReplace())) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003132 Kind = LSRUse::Address;
Jonas Paulsson7a794222016-08-17 13:24:19 +00003133 AccessTy = getAccessType(UserInst);
Dan Gohman45774ce2010-02-12 10:34:29 +00003134 }
3135
Craig Topper042a3922015-05-25 20:01:18 +00003136 const SCEV *S = IU.getExpr(U);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003137 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
3138
Dan Gohman45774ce2010-02-12 10:34:29 +00003139 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3140 // (N - i == 0), and this allows (N - i) to be the expression that we work
3141 // with rather than just N or i, so we can consider the register
3142 // requirements for both N and i at the same time. Limiting this code to
3143 // equality icmps is not a problem because all interesting loops use
3144 // equality icmps, thanks to IndVarSimplify.
Jonas Paulsson7a794222016-08-17 13:24:19 +00003145 if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst))
Dan Gohman45774ce2010-02-12 10:34:29 +00003146 if (CI->isEquality()) {
3147 // Swap the operands if needed to put the OperandValToReplace on the
3148 // left, for consistency.
3149 Value *NV = CI->getOperand(1);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003150 if (NV == U.getOperandValToReplace()) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003151 CI->setOperand(1, CI->getOperand(0));
3152 CI->setOperand(0, NV);
Dan Gohmanee2fea32010-05-20 19:26:52 +00003153 NV = CI->getOperand(1);
Dan Gohmanfdf98742010-05-20 19:16:03 +00003154 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00003155 }
3156
3157 // x == y --> x - y == 0
3158 const SCEV *N = SE.getSCEV(NV);
Andrew Trick57243da2013-10-25 21:35:56 +00003159 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
Dan Gohman3268e4d2011-05-18 21:02:18 +00003160 // S is normalized, so normalize N before folding it into S
3161 // to keep the result normalized.
Sanjoy Dase3a15e82017-04-14 15:49:59 +00003162 N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00003163 Kind = LSRUse::ICmpZero;
3164 S = SE.getMinusSCEV(N, S);
3165 }
3166
3167 // -1 and the negations of all interesting strides (except the negation
3168 // of -1) are now also interesting.
3169 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3170 if (Factors[i] != -1)
3171 Factors.insert(-(uint64_t)Factors[i]);
3172 Factors.insert(-1);
3173 }
3174
Jonas Paulsson7a794222016-08-17 13:24:19 +00003175 // Get or create an LSRUse.
Dan Gohman45774ce2010-02-12 10:34:29 +00003176 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003177 size_t LUIdx = P.first;
3178 int64_t Offset = P.second;
3179 LSRUse &LU = Uses[LUIdx];
3180
3181 // Record the fixup.
3182 LSRFixup &LF = LU.getNewFixup();
3183 LF.UserInst = UserInst;
3184 LF.OperandValToReplace = U.getOperandValToReplace();
3185 LF.PostIncLoops = TmpPostIncLoops;
3186 LF.Offset = Offset;
Dan Gohmand006ab92010-04-07 22:27:08 +00003187 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Jonas Paulsson7a794222016-08-17 13:24:19 +00003188
Dan Gohman14152082010-07-15 20:24:58 +00003189 if (!LU.WidestFixupType ||
3190 SE.getTypeSizeInBits(LU.WidestFixupType) <
3191 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3192 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003193
3194 // If this is the first use of this LSRUse, give it a formula.
3195 if (LU.Formulae.empty()) {
Jonas Paulsson7a794222016-08-17 13:24:19 +00003196 InsertInitialFormula(S, LU, LUIdx);
3197 CountRegisters(LU.Formulae.back(), LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003198 }
3199 }
3200
3201 DEBUG(print_fixups(dbgs()));
3202}
3203
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003204/// Insert a formula for the given expression into the given use, separating out
3205/// loop-variant portions from loop-invariant and loop-computable portions.
Dan Gohman45774ce2010-02-12 10:34:29 +00003206void
Dan Gohman8c16b382010-02-22 04:11:59 +00003207LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Andrew Trick57243da2013-10-25 21:35:56 +00003208 // Mark uses whose expressions cannot be expanded.
3209 if (!isSafeToExpand(S, SE))
3210 LU.RigidFormula = true;
3211
Dan Gohman45774ce2010-02-12 10:34:29 +00003212 Formula F;
Sanjoy Das302bfd02015-08-16 18:22:43 +00003213 F.initialMatch(S, L, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00003214 bool Inserted = InsertFormula(LU, LUIdx, F);
3215 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3216}
3217
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003218/// Insert a simple single-register formula for the given expression into the
3219/// given use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003220void
3221LSRInstance::InsertSupplementalFormula(const SCEV *S,
3222 LSRUse &LU, size_t LUIdx) {
3223 Formula F;
3224 F.BaseRegs.push_back(S);
Chandler Carruth7e31c8f2013-01-12 23:46:04 +00003225 F.HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00003226 bool Inserted = InsertFormula(LU, LUIdx, F);
3227 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3228}
3229
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003230/// Note which registers are used by the given formula, updating RegUses.
Dan Gohman45774ce2010-02-12 10:34:29 +00003231void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3232 if (F.ScaledReg)
Sanjoy Das302bfd02015-08-16 18:22:43 +00003233 RegUses.countRegister(F.ScaledReg, LUIdx);
Craig Topper042a3922015-05-25 20:01:18 +00003234 for (const SCEV *BaseReg : F.BaseRegs)
Sanjoy Das302bfd02015-08-16 18:22:43 +00003235 RegUses.countRegister(BaseReg, LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003236}
3237
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003238/// If the given formula has not yet been inserted, add it to the list, and
3239/// return true. Return false otherwise.
Dan Gohman45774ce2010-02-12 10:34:29 +00003240bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003241 // Do not insert formula that we will not be able to expand.
3242 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3243 "Formula is illegal");
Wei Mi74d5a902017-02-22 21:47:08 +00003244
3245 if (!LU.InsertFormula(F, *L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003246 return false;
3247
3248 CountRegisters(F, LUIdx);
3249 return true;
3250}
3251
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003252/// Check for other uses of loop-invariant values which we're tracking. These
3253/// other uses will pin these values in registers, making them less profitable
3254/// for elimination.
Dan Gohman45774ce2010-02-12 10:34:29 +00003255/// TODO: This currently misses non-constant addrec step registers.
3256/// TODO: Should this give more weight to users inside the loop?
3257void
3258LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3259 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
Andrew Trickdd925ad2014-10-25 19:59:30 +00003260 SmallPtrSet<const SCEV *, 32> Visited;
Dan Gohman45774ce2010-02-12 10:34:29 +00003261
3262 while (!Worklist.empty()) {
3263 const SCEV *S = Worklist.pop_back_val();
3264
Andrew Trick9ccbed52014-10-25 19:42:07 +00003265 // Don't process the same SCEV twice
David Blaikie70573dc2014-11-19 07:49:26 +00003266 if (!Visited.insert(S).second)
Andrew Trick9ccbed52014-10-25 19:42:07 +00003267 continue;
3268
Dan Gohman45774ce2010-02-12 10:34:29 +00003269 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohmandd41bba2010-06-21 19:47:52 +00003270 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman45774ce2010-02-12 10:34:29 +00003271 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3272 Worklist.push_back(C->getOperand());
3273 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3274 Worklist.push_back(D->getLHS());
3275 Worklist.push_back(D->getRHS());
Chandler Carruthcdf47882014-03-09 03:16:01 +00003276 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003277 const Value *V = US->getValue();
Dan Gohman67b44032010-06-04 23:16:05 +00003278 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3279 // Look for instructions defined outside the loop.
Dan Gohman45774ce2010-02-12 10:34:29 +00003280 if (L->contains(Inst)) continue;
Dan Gohman67b44032010-06-04 23:16:05 +00003281 } else if (isa<UndefValue>(V))
3282 // Undef doesn't have a live range, so it doesn't matter.
3283 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003284 for (const Use &U : V->uses()) {
3285 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
Dan Gohman45774ce2010-02-12 10:34:29 +00003286 // Ignore non-instructions.
3287 if (!UserInst)
Dan Gohman045f8192010-01-22 00:46:49 +00003288 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003289 // Ignore instructions in other functions (as can happen with
3290 // Constants).
3291 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman045f8192010-01-22 00:46:49 +00003292 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003293 // Ignore instructions not dominated by the loop.
3294 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3295 UserInst->getParent() :
3296 cast<PHINode>(UserInst)->getIncomingBlock(
Chandler Carruthcdf47882014-03-09 03:16:01 +00003297 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003298 if (!DT.dominates(L->getHeader(), UseBB))
3299 continue;
David Majnemerb2221842015-11-08 05:04:07 +00003300 // Don't bother if the instruction is in a BB which ends in an EHPad.
3301 if (UseBB->getTerminator()->isEHPad())
3302 continue;
David Majnemerbba17392017-01-13 22:24:27 +00003303 // Don't bother rewriting PHIs in catchswitch blocks.
3304 if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))
3305 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003306 // Ignore uses which are part of other SCEV expressions, to avoid
3307 // analyzing them multiple times.
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003308 if (SE.isSCEVable(UserInst->getType())) {
3309 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3310 // If the user is a no-op, look through to its uses.
3311 if (!isa<SCEVUnknown>(UserS))
3312 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003313 if (UserS == US) {
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003314 Worklist.push_back(
3315 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3316 continue;
3317 }
3318 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003319 // Ignore icmp instructions which are already being analyzed.
3320 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003321 unsigned OtherIdx = !U.getOperandNo();
Dan Gohman45774ce2010-02-12 10:34:29 +00003322 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
Dan Gohmanafd6db92010-11-17 21:23:15 +00003323 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003324 continue;
3325 }
3326
Matt Arsenault427a0fd2015-08-15 00:53:06 +00003327 std::pair<size_t, int64_t> P = getUse(
3328 S, LSRUse::Basic, MemAccessTy());
Jonas Paulsson7a794222016-08-17 13:24:19 +00003329 size_t LUIdx = P.first;
3330 int64_t Offset = P.second;
3331 LSRUse &LU = Uses[LUIdx];
3332 LSRFixup &LF = LU.getNewFixup();
3333 LF.UserInst = const_cast<Instruction *>(UserInst);
3334 LF.OperandValToReplace = U;
3335 LF.Offset = Offset;
Dan Gohmand006ab92010-04-07 22:27:08 +00003336 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman14152082010-07-15 20:24:58 +00003337 if (!LU.WidestFixupType ||
3338 SE.getTypeSizeInBits(LU.WidestFixupType) <
3339 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3340 LU.WidestFixupType = LF.OperandValToReplace->getType();
Jonas Paulsson7a794222016-08-17 13:24:19 +00003341 InsertSupplementalFormula(US, LU, LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003342 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3343 break;
3344 }
3345 }
3346 }
3347}
3348
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003349/// Split S into subexpressions which can be pulled out into separate
3350/// registers. If C is non-null, multiply each subexpression by C.
Andrew Trickc8037062012-07-17 05:30:37 +00003351///
3352/// Return remainder expression after factoring the subexpressions captured by
3353/// Ops. If Ops is complete, return NULL.
3354static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3355 SmallVectorImpl<const SCEV *> &Ops,
3356 const Loop *L,
3357 ScalarEvolution &SE,
3358 unsigned Depth = 0) {
3359 // Arbitrarily cap recursion to protect compile time.
3360 if (Depth >= 3)
3361 return S;
3362
Dan Gohman45774ce2010-02-12 10:34:29 +00003363 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3364 // Break out add operands.
Craig Topper042a3922015-05-25 20:01:18 +00003365 for (const SCEV *S : Add->operands()) {
3366 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
Andrew Trickc8037062012-07-17 05:30:37 +00003367 if (Remainder)
3368 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3369 }
Craig Topperf40110f2014-04-25 05:29:35 +00003370 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00003371 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3372 // Split a non-zero base out of an addrec.
Alexandros Lamprineas0ee3ec22016-11-09 08:53:07 +00003373 if (AR->getStart()->isZero() || !AR->isAffine())
Andrew Trickc8037062012-07-17 05:30:37 +00003374 return S;
3375
3376 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3377 C, Ops, L, SE, Depth+1);
3378 // Split the non-zero AddRec unless it is part of a nested recurrence that
3379 // does not pertain to this loop.
3380 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3381 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
Craig Topperf40110f2014-04-25 05:29:35 +00003382 Remainder = nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003383 }
3384 if (Remainder != AR->getStart()) {
3385 if (!Remainder)
3386 Remainder = SE.getConstant(AR->getType(), 0);
3387 return SE.getAddRecExpr(Remainder,
3388 AR->getStepRecurrence(SE),
3389 AR->getLoop(),
3390 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3391 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +00003392 }
3393 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3394 // Break (C * (a + b + c)) into C*a + C*b + C*c.
Andrew Trickc8037062012-07-17 05:30:37 +00003395 if (Mul->getNumOperands() != 2)
3396 return S;
3397 if (const SCEVConstant *Op0 =
3398 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3399 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3400 const SCEV *Remainder =
3401 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3402 if (Remainder)
3403 Ops.push_back(SE.getMulExpr(C, Remainder));
Craig Topperf40110f2014-04-25 05:29:35 +00003404 return nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003405 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003406 }
Andrew Trickc8037062012-07-17 05:30:37 +00003407 return S;
Dan Gohman45774ce2010-02-12 10:34:29 +00003408}
3409
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003410/// \brief Helper function for LSRInstance::GenerateReassociations.
3411void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3412 const Formula &Base,
3413 unsigned Depth, size_t Idx,
3414 bool IsScaledReg) {
3415 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3416 SmallVector<const SCEV *, 8> AddOps;
3417 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3418 if (Remainder)
3419 AddOps.push_back(Remainder);
3420
3421 if (AddOps.size() == 1)
3422 return;
3423
3424 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3425 JE = AddOps.end();
3426 J != JE; ++J) {
3427
3428 // Loop-variant "unknown" values are uninteresting; we won't be able to
3429 // do anything meaningful with them.
3430 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3431 continue;
3432
3433 // Don't pull a constant into a register if the constant could be folded
3434 // into an immediate field.
3435 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3436 LU.AccessTy, *J, Base.getNumRegs() > 1))
3437 continue;
3438
3439 // Collect all operands except *J.
3440 SmallVector<const SCEV *, 8> InnerAddOps(
3441 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3442 InnerAddOps.append(std::next(J),
3443 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3444
3445 // Don't leave just a constant behind in a register if the constant could
3446 // be folded into an immediate field.
3447 if (InnerAddOps.size() == 1 &&
3448 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3449 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3450 continue;
3451
3452 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3453 if (InnerSum->isZero())
3454 continue;
3455 Formula F = Base;
3456
3457 // Add the remaining pieces of the add back into the new formula.
3458 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3459 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3460 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3461 InnerSumSC->getValue()->getZExtValue())) {
3462 F.UnfoldedOffset =
3463 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3464 if (IsScaledReg)
3465 F.ScaledReg = nullptr;
3466 else
3467 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3468 } else if (IsScaledReg)
3469 F.ScaledReg = InnerSum;
3470 else
3471 F.BaseRegs[Idx] = InnerSum;
3472
3473 // Add J as its own register, or an unfolded immediate.
3474 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3475 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3476 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3477 SC->getValue()->getZExtValue()))
3478 F.UnfoldedOffset =
3479 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3480 else
3481 F.BaseRegs.push_back(*J);
3482 // We may have changed the number of register in base regs, adjust the
3483 // formula accordingly.
Wei Mi74d5a902017-02-22 21:47:08 +00003484 F.canonicalize(*L);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003485
3486 if (InsertFormula(LU, LUIdx, F))
3487 // If that formula hadn't been seen before, recurse to find more like
3488 // it.
3489 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3490 }
3491}
3492
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003493/// Split out subexpressions from adds and the bases of addrecs.
Dan Gohman45774ce2010-02-12 10:34:29 +00003494void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003495 Formula Base, unsigned Depth) {
Wei Mi74d5a902017-02-22 21:47:08 +00003496 assert(Base.isCanonical(*L) && "Input must be in the canonical form");
Dan Gohman45774ce2010-02-12 10:34:29 +00003497 // Arbitrarily cap recursion to protect compile time.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003498 if (Depth >= 3)
3499 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003500
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003501 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3502 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
Dan Gohman45774ce2010-02-12 10:34:29 +00003503
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003504 if (Base.Scale == 1)
3505 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3506 /* Idx */ -1, /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003507}
3508
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003509/// Generate a formula consisting of all of the loop-dominating registers added
3510/// into a single register.
Dan Gohman45774ce2010-02-12 10:34:29 +00003511void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohmane4e51a62010-02-14 18:51:39 +00003512 Formula Base) {
Dan Gohman8b0a4192010-03-01 17:49:51 +00003513 // This method is only interesting on a plurality of registers.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003514 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3515 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003516
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003517 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3518 // processing the formula.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003519 Base.unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003520 Formula F = Base;
3521 F.BaseRegs.clear();
3522 SmallVector<const SCEV *, 4> Ops;
Craig Topper042a3922015-05-25 20:01:18 +00003523 for (const SCEV *BaseReg : Base.BaseRegs) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00003524 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
Dan Gohmanafd6db92010-11-17 21:23:15 +00003525 !SE.hasComputableLoopEvolution(BaseReg, L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003526 Ops.push_back(BaseReg);
3527 else
3528 F.BaseRegs.push_back(BaseReg);
3529 }
3530 if (Ops.size() > 1) {
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003531 const SCEV *Sum = SE.getAddExpr(Ops);
3532 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3533 // opportunity to fold something. For now, just ignore such cases
Dan Gohman8b0a4192010-03-01 17:49:51 +00003534 // rather than proceed with zero in a register.
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003535 if (!Sum->isZero()) {
3536 F.BaseRegs.push_back(Sum);
Wei Mi74d5a902017-02-22 21:47:08 +00003537 F.canonicalize(*L);
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003538 (void)InsertFormula(LU, LUIdx, F);
3539 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003540 }
3541}
3542
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003543/// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
3544void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3545 const Formula &Base, size_t Idx,
3546 bool IsScaledReg) {
3547 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3548 GlobalValue *GV = ExtractSymbol(G, SE);
3549 if (G->isZero() || !GV)
3550 return;
3551 Formula F = Base;
3552 F.BaseGV = GV;
3553 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3554 return;
3555 if (IsScaledReg)
3556 F.ScaledReg = G;
3557 else
3558 F.BaseRegs[Idx] = G;
3559 (void)InsertFormula(LU, LUIdx, F);
3560}
3561
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003562/// Generate reuse formulae using symbolic offsets.
Dan Gohman45774ce2010-02-12 10:34:29 +00003563void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3564 Formula Base) {
3565 // We can't add a symbolic offset if the address already contains one.
Chandler Carruth6e479322013-01-07 15:04:40 +00003566 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003567
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003568 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3569 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3570 if (Base.Scale == 1)
3571 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3572 /* IsScaledReg */ true);
3573}
3574
3575/// \brief Helper function for LSRInstance::GenerateConstantOffsets.
3576void LSRInstance::GenerateConstantOffsetsImpl(
3577 LSRUse &LU, unsigned LUIdx, const Formula &Base,
3578 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3579 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
Craig Topper042a3922015-05-25 20:01:18 +00003580 for (int64_t Offset : Worklist) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003581 Formula F = Base;
Craig Topper042a3922015-05-25 20:01:18 +00003582 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3583 if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003584 LU.AccessTy, F)) {
3585 // Add the offset to the base register.
Craig Topper042a3922015-05-25 20:01:18 +00003586 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003587 // If it cancelled out, drop the base register, otherwise update it.
3588 if (NewG->isZero()) {
3589 if (IsScaledReg) {
3590 F.Scale = 0;
3591 F.ScaledReg = nullptr;
3592 } else
Sanjoy Das302bfd02015-08-16 18:22:43 +00003593 F.deleteBaseReg(F.BaseRegs[Idx]);
Wei Mi74d5a902017-02-22 21:47:08 +00003594 F.canonicalize(*L);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003595 } else if (IsScaledReg)
3596 F.ScaledReg = NewG;
3597 else
3598 F.BaseRegs[Idx] = NewG;
3599
3600 (void)InsertFormula(LU, LUIdx, F);
3601 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003602 }
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003603
3604 int64_t Imm = ExtractImmediate(G, SE);
3605 if (G->isZero() || Imm == 0)
3606 return;
3607 Formula F = Base;
3608 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3609 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3610 return;
3611 if (IsScaledReg)
3612 F.ScaledReg = G;
3613 else
3614 F.BaseRegs[Idx] = G;
3615 (void)InsertFormula(LU, LUIdx, F);
Dan Gohman45774ce2010-02-12 10:34:29 +00003616}
3617
3618/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3619void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3620 Formula Base) {
3621 // TODO: For now, just add the min and max offset, because it usually isn't
3622 // worthwhile looking at everything inbetween.
Dan Gohman4afd4122010-07-15 15:14:45 +00003623 SmallVector<int64_t, 2> Worklist;
Dan Gohman45774ce2010-02-12 10:34:29 +00003624 Worklist.push_back(LU.MinOffset);
3625 if (LU.MaxOffset != LU.MinOffset)
3626 Worklist.push_back(LU.MaxOffset);
3627
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003628 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3629 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3630 if (Base.Scale == 1)
3631 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3632 /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003633}
3634
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003635/// For ICmpZero, check to see if we can scale up the comparison. For example, x
3636/// == y -> x*c == y*c.
Dan Gohman45774ce2010-02-12 10:34:29 +00003637void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3638 Formula Base) {
3639 if (LU.Kind != LSRUse::ICmpZero) return;
3640
3641 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003642 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003643 if (!IntTy) return;
3644 if (SE.getTypeSizeInBits(IntTy) > 64) return;
3645
3646 // Don't do this if there is more than one offset.
3647 if (LU.MinOffset != LU.MaxOffset) return;
3648
Chandler Carruth6e479322013-01-07 15:04:40 +00003649 assert(!Base.BaseGV && "ICmpZero use is not legal!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003650
3651 // Check each interesting stride.
Craig Topper042a3922015-05-25 20:01:18 +00003652 for (int64_t Factor : Factors) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003653 // Check that the multiplication doesn't overflow.
Chandler Carruth6e479322013-01-07 15:04:40 +00003654 if (Base.BaseOffset == INT64_MIN && Factor == -1)
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003655 continue;
Chandler Carruth6e479322013-01-07 15:04:40 +00003656 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3657 if (NewBaseOffset / Factor != Base.BaseOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003658 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003659 // If the offset will be truncated at this use, check that it is in bounds.
3660 if (!IntTy->isPointerTy() &&
3661 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3662 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003663
3664 // Check that multiplying with the use offset doesn't overflow.
3665 int64_t Offset = LU.MinOffset;
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003666 if (Offset == INT64_MIN && Factor == -1)
3667 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003668 Offset = (uint64_t)Offset * Factor;
Dan Gohman13ac3b22010-02-17 00:42:19 +00003669 if (Offset / Factor != LU.MinOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003670 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003671 // If the offset will be truncated at this use, check that it is in bounds.
3672 if (!IntTy->isPointerTy() &&
3673 !ConstantInt::isValueValidForType(IntTy, Offset))
3674 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003675
Dan Gohman963b1c12010-06-24 16:57:52 +00003676 Formula F = Base;
Chandler Carruth6e479322013-01-07 15:04:40 +00003677 F.BaseOffset = NewBaseOffset;
Dan Gohman963b1c12010-06-24 16:57:52 +00003678
Dan Gohman45774ce2010-02-12 10:34:29 +00003679 // Check that this scale is legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003680 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
Dan Gohman45774ce2010-02-12 10:34:29 +00003681 continue;
3682
3683 // Compensate for the use having MinOffset built into it.
Chandler Carruth6e479322013-01-07 15:04:40 +00003684 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +00003685
Dan Gohman1d2ded72010-05-03 22:09:21 +00003686 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003687
3688 // Check that multiplying with each base register doesn't overflow.
3689 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3690 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003691 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman45774ce2010-02-12 10:34:29 +00003692 goto next;
3693 }
3694
3695 // Check that multiplying with the scaled register doesn't overflow.
3696 if (F.ScaledReg) {
3697 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003698 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman45774ce2010-02-12 10:34:29 +00003699 continue;
3700 }
3701
Dan Gohman6136e942011-05-03 00:46:49 +00003702 // Check that multiplying with the unfolded offset doesn't overflow.
3703 if (F.UnfoldedOffset != 0) {
Dan Gohman6c4a3192011-05-23 21:07:39 +00003704 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
3705 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003706 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3707 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3708 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003709 // If the offset will be truncated, check that it is in bounds.
3710 if (!IntTy->isPointerTy() &&
3711 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3712 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003713 }
3714
Dan Gohman45774ce2010-02-12 10:34:29 +00003715 // If we make it here and it's legal, add it.
3716 (void)InsertFormula(LU, LUIdx, F);
3717 next:;
3718 }
3719}
3720
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003721/// Generate stride factor reuse formulae by making use of scaled-offset address
3722/// modes, for example.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003723void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003724 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003725 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003726 if (!IntTy) return;
3727
3728 // If this Formula already has a scaled register, we can't add another one.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003729 // Try to unscale the formula to generate a better scale.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003730 if (Base.Scale != 0 && !Base.unscale())
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003731 return;
3732
Sanjoy Das302bfd02015-08-16 18:22:43 +00003733 assert(Base.Scale == 0 && "unscale did not did its job!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003734
3735 // Check each interesting stride.
Craig Topper042a3922015-05-25 20:01:18 +00003736 for (int64_t Factor : Factors) {
Chandler Carruth6e479322013-01-07 15:04:40 +00003737 Base.Scale = Factor;
3738 Base.HasBaseReg = Base.BaseRegs.size() > 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00003739 // Check whether this scale is going to be legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003740 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3741 Base)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003742 // As a special-case, handle special out-of-loop Basic users specially.
3743 // TODO: Reconsider this special case.
3744 if (LU.Kind == LSRUse::Basic &&
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003745 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3746 LU.AccessTy, Base) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00003747 LU.AllFixupsOutsideLoop)
3748 LU.Kind = LSRUse::Special;
3749 else
3750 continue;
3751 }
3752 // For an ICmpZero, negating a solitary base register won't lead to
3753 // new solutions.
3754 if (LU.Kind == LSRUse::ICmpZero &&
Chandler Carruth6e479322013-01-07 15:04:40 +00003755 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00003756 continue;
Wei Mi74d5a902017-02-22 21:47:08 +00003757 // For each addrec base reg, if its loop is current loop, apply the scale.
3758 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
3759 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]);
3760 if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00003761 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003762 if (FactorS->isZero())
3763 continue;
3764 // Divide out the factor, ignoring high bits, since we'll be
3765 // scaling the value back up in the end.
Dan Gohman4eebb942010-02-19 19:35:48 +00003766 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003767 // TODO: This could be optimized to avoid all the copying.
3768 Formula F = Base;
3769 F.ScaledReg = Quotient;
Sanjoy Das302bfd02015-08-16 18:22:43 +00003770 F.deleteBaseReg(F.BaseRegs[i]);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003771 // The canonical representation of 1*reg is reg, which is already in
3772 // Base. In that case, do not try to insert the formula, it will be
3773 // rejected anyway.
Wei Mi74d5a902017-02-22 21:47:08 +00003774 if (F.Scale == 1 && (F.BaseRegs.empty() ||
3775 (AR->getLoop() != L && LU.AllFixupsOutsideLoop)))
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003776 continue;
Wei Mi74d5a902017-02-22 21:47:08 +00003777 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
3778 // non canonical Formula with ScaledReg's loop not being L.
3779 if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
3780 F.canonicalize(*L);
Dan Gohman45774ce2010-02-12 10:34:29 +00003781 (void)InsertFormula(LU, LUIdx, F);
3782 }
3783 }
Wei Mi74d5a902017-02-22 21:47:08 +00003784 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003785 }
3786}
3787
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003788/// Generate reuse formulae from different IV types.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003789void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003790 // Don't bother truncating symbolic values.
Chandler Carruth6e479322013-01-07 15:04:40 +00003791 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003792
3793 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003794 Type *DstTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003795 if (!DstTy) return;
3796 DstTy = SE.getEffectiveSCEVType(DstTy);
3797
Craig Topper042a3922015-05-25 20:01:18 +00003798 for (Type *SrcTy : Types) {
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003799 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003800 Formula F = Base;
3801
Craig Topper042a3922015-05-25 20:01:18 +00003802 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
3803 for (const SCEV *&BaseReg : F.BaseRegs)
3804 BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00003805
3806 // TODO: This assumes we've done basic processing on all uses and
3807 // have an idea what the register usage is.
3808 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3809 continue;
3810
Wei Mi8848c1e2017-05-18 17:21:22 +00003811 F.canonicalize(*L);
Dan Gohman45774ce2010-02-12 10:34:29 +00003812 (void)InsertFormula(LU, LUIdx, F);
3813 }
3814 }
3815}
3816
3817namespace {
3818
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003819/// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
3820/// modifications so that the search phase doesn't have to worry about the data
3821/// structures moving underneath it.
Dan Gohman45774ce2010-02-12 10:34:29 +00003822struct WorkItem {
3823 size_t LUIdx;
3824 int64_t Imm;
3825 const SCEV *OrigReg;
3826
3827 WorkItem(size_t LI, int64_t I, const SCEV *R)
3828 : LUIdx(LI), Imm(I), OrigReg(R) {}
3829
3830 void print(raw_ostream &OS) const;
3831 void dump() const;
3832};
3833
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00003834} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00003835
3836void WorkItem::print(raw_ostream &OS) const {
3837 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
3838 << " , add offset " << Imm;
3839}
3840
Matthias Braun8c209aa2017-01-28 02:02:38 +00003841#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3842LLVM_DUMP_METHOD void WorkItem::dump() const {
Dan Gohman45774ce2010-02-12 10:34:29 +00003843 print(errs()); errs() << '\n';
3844}
Matthias Braun8c209aa2017-01-28 02:02:38 +00003845#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00003846
Sanjoy Das94c4aec2015-08-16 18:22:46 +00003847/// Look for registers which are a constant distance apart and try to form reuse
3848/// opportunities between them.
Dan Gohman45774ce2010-02-12 10:34:29 +00003849void LSRInstance::GenerateCrossUseConstantOffsets() {
3850 // Group the registers by their value without any added constant offset.
3851 typedef std::map<int64_t, const SCEV *> ImmMapTy;
Craig Topper042a3922015-05-25 20:01:18 +00003852 DenseMap<const SCEV *, ImmMapTy> Map;
Dan Gohman45774ce2010-02-12 10:34:29 +00003853 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
3854 SmallVector<const SCEV *, 8> Sequence;
Craig Topper042a3922015-05-25 20:01:18 +00003855 for (const SCEV *Use : RegUses) {
3856 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
Dan Gohman45774ce2010-02-12 10:34:29 +00003857 int64_t Imm = ExtractImmediate(Reg, SE);
Craig Topper042a3922015-05-25 20:01:18 +00003858 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003859 if (Pair.second)
3860 Sequence.push_back(Reg);
Craig Topper042a3922015-05-25 20:01:18 +00003861 Pair.first->second.insert(std::make_pair(Imm, Use));
3862 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
Dan Gohman45774ce2010-02-12 10:34:29 +00003863 }
3864
3865 // Now examine each set of registers with the same base value. Build up
3866 // a list of work to do and do the work in a separate step so that we're
3867 // not adding formulae and register counts while we're searching.
Dan Gohman110ed642010-09-01 01:45:53 +00003868 SmallVector<WorkItem, 32> WorkItems;
3869 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
Craig Topper042a3922015-05-25 20:01:18 +00003870 for (const SCEV *Reg : Sequence) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003871 const ImmMapTy &Imms = Map.find(Reg)->second;
3872
Dan Gohman363f8472010-02-12 19:20:37 +00003873 // It's not worthwhile looking for reuse if there's only one offset.
3874 if (Imms.size() == 1)
3875 continue;
3876
Dan Gohman45774ce2010-02-12 10:34:29 +00003877 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
Craig Topper042a3922015-05-25 20:01:18 +00003878 for (const auto &Entry : Imms)
3879 dbgs() << ' ' << Entry.first;
Dan Gohman45774ce2010-02-12 10:34:29 +00003880 dbgs() << '\n');
3881
3882 // Examine each offset.
3883 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3884 J != JE; ++J) {
3885 const SCEV *OrigReg = J->second;
3886
3887 int64_t JImm = J->first;
3888 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3889
3890 if (!isa<SCEVConstant>(OrigReg) &&
3891 UsedByIndicesMap[Reg].count() == 1) {
3892 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
3893 continue;
3894 }
3895
3896 // Conservatively examine offsets between this orig reg a few selected
3897 // other orig regs.
3898 ImmMapTy::const_iterator OtherImms[] = {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003899 Imms.begin(), std::prev(Imms.end()),
3900 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
3901 2)
Dan Gohman45774ce2010-02-12 10:34:29 +00003902 };
3903 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
3904 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohman363f8472010-02-12 19:20:37 +00003905 if (M == J || M == JE) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003906
3907 // Compute the difference between the two.
3908 int64_t Imm = (uint64_t)JImm - M->first;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003909 for (unsigned LUIdx : UsedByIndices.set_bits())
Dan Gohman45774ce2010-02-12 10:34:29 +00003910 // Make a memo of this use, offset, and register tuple.
David Blaikie70573dc2014-11-19 07:49:26 +00003911 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
Dan Gohman110ed642010-09-01 01:45:53 +00003912 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng85a9f432009-11-12 07:35:05 +00003913 }
3914 }
3915 }
3916
Dan Gohman45774ce2010-02-12 10:34:29 +00003917 Map.clear();
3918 Sequence.clear();
3919 UsedByIndicesMap.clear();
Dan Gohman110ed642010-09-01 01:45:53 +00003920 UniqueItems.clear();
Dan Gohman45774ce2010-02-12 10:34:29 +00003921
3922 // Now iterate through the worklist and add new formulae.
Craig Topper042a3922015-05-25 20:01:18 +00003923 for (const WorkItem &WI : WorkItems) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003924 size_t LUIdx = WI.LUIdx;
3925 LSRUse &LU = Uses[LUIdx];
3926 int64_t Imm = WI.Imm;
3927 const SCEV *OrigReg = WI.OrigReg;
3928
Chris Lattner229907c2011-07-18 04:54:35 +00003929 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
Dan Gohman45774ce2010-02-12 10:34:29 +00003930 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3931 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
3932
Dan Gohman8b0a4192010-03-01 17:49:51 +00003933 // TODO: Use a more targeted data structure.
Dan Gohman45774ce2010-02-12 10:34:29 +00003934 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003935 Formula F = LU.Formulae[L];
3936 // FIXME: The code for the scaled and unscaled registers looks
3937 // very similar but slightly different. Investigate if they
3938 // could be merged. That way, we would not have to unscale the
3939 // Formula.
Sanjoy Das302bfd02015-08-16 18:22:43 +00003940 F.unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003941 // Use the immediate in the scaled register.
3942 if (F.ScaledReg == OrigReg) {
Chandler Carruth6e479322013-01-07 15:04:40 +00003943 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
Dan Gohman45774ce2010-02-12 10:34:29 +00003944 // Don't create 50 + reg(-50).
3945 if (F.referencesReg(SE.getSCEV(
Chandler Carruth6e479322013-01-07 15:04:40 +00003946 ConstantInt::get(IntTy, -(uint64_t)Offset))))
Dan Gohman45774ce2010-02-12 10:34:29 +00003947 continue;
3948 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003949 NewF.BaseOffset = Offset;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003950 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3951 NewF))
Dan Gohman45774ce2010-02-12 10:34:29 +00003952 continue;
3953 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
3954
3955 // If the new scale is a constant in a register, and adding the constant
3956 // value to the immediate would produce a value closer to zero than the
3957 // immediate itself, then the formula isn't worthwhile.
3958 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003959 if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
3960 (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
3961 .ule(std::abs(NewF.BaseOffset)))
Dan Gohman45774ce2010-02-12 10:34:29 +00003962 continue;
3963
3964 // OK, looks good.
Wei Mi74d5a902017-02-22 21:47:08 +00003965 NewF.canonicalize(*this->L);
Dan Gohman45774ce2010-02-12 10:34:29 +00003966 (void)InsertFormula(LU, LUIdx, NewF);
3967 } else {
3968 // Use the immediate in a base register.
3969 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
3970 const SCEV *BaseReg = F.BaseRegs[N];
3971 if (BaseReg != OrigReg)
3972 continue;
3973 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003974 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003975 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
3976 LU.Kind, LU.AccessTy, NewF)) {
3977 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
Dan Gohman6136e942011-05-03 00:46:49 +00003978 continue;
3979 NewF = F;
3980 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3981 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003982 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
3983
3984 // If the new formula has a constant in a register, and adding the
3985 // constant value to the immediate would produce a value closer to
3986 // zero than the immediate itself, then the formula isn't worthwhile.
Craig Topper10949ae2015-05-23 08:45:10 +00003987 for (const SCEV *NewReg : NewF.BaseRegs)
3988 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003989 if ((C->getAPInt() + NewF.BaseOffset)
3990 .abs()
3991 .slt(std::abs(NewF.BaseOffset)) &&
3992 (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >=
3993 countTrailingZeros<uint64_t>(NewF.BaseOffset))
Dan Gohman45774ce2010-02-12 10:34:29 +00003994 goto skip_formula;
3995
3996 // Ok, looks good.
Wei Mi74d5a902017-02-22 21:47:08 +00003997 NewF.canonicalize(*this->L);
Dan Gohman45774ce2010-02-12 10:34:29 +00003998 (void)InsertFormula(LU, LUIdx, NewF);
3999 break;
4000 skip_formula:;
4001 }
4002 }
4003 }
4004 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00004005}
4006
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004007/// Generate formulae for each use.
Dan Gohman45774ce2010-02-12 10:34:29 +00004008void
4009LSRInstance::GenerateAllReuseFormulae() {
Dan Gohman521efe62010-02-16 01:42:53 +00004010 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman45774ce2010-02-12 10:34:29 +00004011 // queries are more precise.
4012 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4013 LSRUse &LU = Uses[LUIdx];
4014 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4015 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4016 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4017 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4018 }
4019 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4020 LSRUse &LU = Uses[LUIdx];
4021 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4022 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4023 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4024 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4025 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4026 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4027 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4028 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohman521efe62010-02-16 01:42:53 +00004029 }
4030 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4031 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00004032 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4033 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4034 }
4035
4036 GenerateCrossUseConstantOffsets();
Dan Gohmanbf673e02010-08-29 15:21:38 +00004037
4038 DEBUG(dbgs() << "\n"
4039 "After generating reuse formulae:\n";
4040 print_uses(dbgs()));
Dan Gohman45774ce2010-02-12 10:34:29 +00004041}
4042
Dan Gohman1b61fd92010-10-07 23:43:09 +00004043/// If there are multiple formulae with the same set of registers used
Dan Gohman45774ce2010-02-12 10:34:29 +00004044/// by other uses, pick the best one and delete the others.
4045void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
Dan Gohman5947e162010-10-07 23:52:18 +00004046 DenseSet<const SCEV *> VisitedRegs;
4047 SmallPtrSet<const SCEV *, 16> Regs;
Andrew Trick5df90962011-12-06 03:13:31 +00004048 SmallPtrSet<const SCEV *, 16> LoserRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00004049#ifndef NDEBUG
Dan Gohman4c4043c2010-05-20 20:05:31 +00004050 bool ChangedFormulae = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00004051#endif
4052
4053 // Collect the best formula for each unique set of shared registers. This
4054 // is reset for each use.
Preston Gurd25c3b6a2013-02-01 20:41:27 +00004055 typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
Dan Gohman45774ce2010-02-12 10:34:29 +00004056 BestFormulaeTy;
4057 BestFormulaeTy BestFormulae;
4058
4059 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4060 LSRUse &LU = Uses[LUIdx];
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00004061 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00004062
Dan Gohman4cf99b52010-05-18 23:42:37 +00004063 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00004064 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
4065 FIdx != NumForms; ++FIdx) {
4066 Formula &F = LU.Formulae[FIdx];
4067
Andrew Trick5df90962011-12-06 03:13:31 +00004068 // Some formulas are instant losers. For example, they may depend on
4069 // nonexistent AddRecs from other loops. These need to be filtered
4070 // immediately, otherwise heuristics could choose them over others leading
4071 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
4072 // avoids the need to recompute this information across formulae using the
4073 // same bad AddRec. Passing LoserRegs is also essential unless we remove
4074 // the corresponding bad register from the Regs set.
4075 Cost CostF;
4076 Regs.clear();
Jonas Paulsson7a794222016-08-17 13:24:19 +00004077 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, SE, DT, LU, &LoserRegs);
Andrew Trick5df90962011-12-06 03:13:31 +00004078 if (CostF.isLoser()) {
4079 // During initial formula generation, undesirable formulae are generated
4080 // by uses within other loops that have some non-trivial address mode or
4081 // use the postinc form of the IV. LSR needs to provide these formulae
4082 // as the basis of rediscovering the desired formula that uses an AddRec
4083 // corresponding to the existing phi. Once all formulae have been
4084 // generated, these initial losers may be pruned.
4085 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
4086 dbgs() << "\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004087 }
Andrew Trick5df90962011-12-06 03:13:31 +00004088 else {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00004089 SmallVector<const SCEV *, 4> Key;
Craig Topper77b99412015-05-23 08:01:41 +00004090 for (const SCEV *Reg : F.BaseRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +00004091 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4092 Key.push_back(Reg);
4093 }
4094 if (F.ScaledReg &&
4095 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4096 Key.push_back(F.ScaledReg);
4097 // Unstable sort by host order ok, because this is only used for
4098 // uniquifying.
4099 std::sort(Key.begin(), Key.end());
Dan Gohman45774ce2010-02-12 10:34:29 +00004100
Andrew Trick5df90962011-12-06 03:13:31 +00004101 std::pair<BestFormulaeTy::const_iterator, bool> P =
4102 BestFormulae.insert(std::make_pair(Key, FIdx));
4103 if (P.second)
4104 continue;
4105
Dan Gohman45774ce2010-02-12 10:34:29 +00004106 Formula &Best = LU.Formulae[P.first->second];
Dan Gohman5947e162010-10-07 23:52:18 +00004107
Dan Gohman5947e162010-10-07 23:52:18 +00004108 Cost CostBest;
Dan Gohman5947e162010-10-07 23:52:18 +00004109 Regs.clear();
Jonas Paulsson7a794222016-08-17 13:24:19 +00004110 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, SE, DT, LU);
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00004111 if (CostF.isLess(CostBest, TTI))
Dan Gohman45774ce2010-02-12 10:34:29 +00004112 std::swap(F, Best);
Dan Gohman8aca7ef2010-05-18 22:37:37 +00004113 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00004114 dbgs() << "\n"
Dan Gohman8aca7ef2010-05-18 22:37:37 +00004115 " in favor of formula "; Best.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00004116 dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00004117 }
Andrew Trick5df90962011-12-06 03:13:31 +00004118#ifndef NDEBUG
4119 ChangedFormulae = true;
4120#endif
4121 LU.DeleteFormula(F);
4122 --FIdx;
4123 --NumForms;
4124 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00004125 }
4126
Dan Gohmanbeebef42010-05-18 23:55:57 +00004127 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohman4cf99b52010-05-18 23:42:37 +00004128 if (Any)
4129 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohmand0800242010-05-07 23:36:59 +00004130
4131 // Reset this to prepare for the next use.
Dan Gohman45774ce2010-02-12 10:34:29 +00004132 BestFormulae.clear();
4133 }
4134
Dan Gohman4c4043c2010-05-20 20:05:31 +00004135 DEBUG(if (ChangedFormulae) {
Dan Gohman5b18f032010-02-13 02:06:02 +00004136 dbgs() << "\n"
4137 "After filtering out undesirable candidates:\n";
Dan Gohman45774ce2010-02-12 10:34:29 +00004138 print_uses(dbgs());
4139 });
4140}
4141
Dan Gohmana4eca052010-05-18 22:51:59 +00004142// This is a rough guess that seems to work fairly well.
4143static const size_t ComplexityLimit = UINT16_MAX;
4144
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004145/// Estimate the worst-case number of solutions the solver might have to
4146/// consider. It almost never considers this many solutions because it prune the
4147/// search space, but the pruning isn't always sufficient.
Dan Gohmana4eca052010-05-18 22:51:59 +00004148size_t LSRInstance::EstimateSearchSpaceComplexity() const {
Dan Gohman49d638b2010-10-07 23:37:58 +00004149 size_t Power = 1;
Craig Topper10949ae2015-05-23 08:45:10 +00004150 for (const LSRUse &LU : Uses) {
4151 size_t FSize = LU.Formulae.size();
Dan Gohmana4eca052010-05-18 22:51:59 +00004152 if (FSize >= ComplexityLimit) {
4153 Power = ComplexityLimit;
4154 break;
4155 }
4156 Power *= FSize;
4157 if (Power >= ComplexityLimit)
4158 break;
4159 }
4160 return Power;
4161}
4162
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004163/// When one formula uses a superset of the registers of another formula, it
4164/// won't help reduce register pressure (though it may not necessarily hurt
4165/// register pressure); remove it to simplify the system.
Dan Gohmane9e08732010-08-29 16:09:42 +00004166void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
Dan Gohman20fab452010-05-19 23:43:12 +00004167 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4168 DEBUG(dbgs() << "The search space is too complex.\n");
4169
4170 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4171 "which use a superset of registers used by other "
4172 "formulae.\n");
4173
4174 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4175 LSRUse &LU = Uses[LUIdx];
4176 bool Any = false;
4177 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4178 Formula &F = LU.Formulae[i];
Dan Gohman8ec018c2010-05-20 20:00:41 +00004179 // Look for a formula with a constant or GV in a register. If the use
4180 // also has a formula with that same value in an immediate field,
4181 // delete the one that uses a register.
Dan Gohman20fab452010-05-19 23:43:12 +00004182 for (SmallVectorImpl<const SCEV *>::const_iterator
4183 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4184 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4185 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004186 NewF.BaseOffset += C->getValue()->getSExtValue();
Dan Gohman20fab452010-05-19 23:43:12 +00004187 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4188 (I - F.BaseRegs.begin()));
4189 if (LU.HasFormulaWithSameRegs(NewF)) {
4190 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4191 LU.DeleteFormula(F);
4192 --i;
4193 --e;
4194 Any = true;
4195 break;
4196 }
4197 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4198 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
Chandler Carruth6e479322013-01-07 15:04:40 +00004199 if (!F.BaseGV) {
Dan Gohman20fab452010-05-19 23:43:12 +00004200 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004201 NewF.BaseGV = GV;
Dan Gohman20fab452010-05-19 23:43:12 +00004202 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4203 (I - F.BaseRegs.begin()));
4204 if (LU.HasFormulaWithSameRegs(NewF)) {
4205 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4206 dbgs() << '\n');
4207 LU.DeleteFormula(F);
4208 --i;
4209 --e;
4210 Any = true;
4211 break;
4212 }
4213 }
4214 }
4215 }
4216 }
4217 if (Any)
4218 LU.RecomputeRegs(LUIdx, RegUses);
4219 }
4220
4221 DEBUG(dbgs() << "After pre-selection:\n";
4222 print_uses(dbgs()));
4223 }
Dan Gohmane9e08732010-08-29 16:09:42 +00004224}
Dan Gohman20fab452010-05-19 23:43:12 +00004225
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004226/// When there are many registers for expressions like A, A+1, A+2, etc.,
4227/// allocate a single register for them.
Dan Gohmane9e08732010-08-29 16:09:42 +00004228void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
Jakub Staszak11bd8352013-02-16 16:08:15 +00004229 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4230 return;
Dan Gohman20fab452010-05-19 23:43:12 +00004231
Jakub Staszak11bd8352013-02-16 16:08:15 +00004232 DEBUG(dbgs() << "The search space is too complex.\n"
4233 "Narrowing the search space by assuming that uses separated "
4234 "by a constant offset will use the same registers.\n");
Dan Gohman20fab452010-05-19 23:43:12 +00004235
Jakub Staszak11bd8352013-02-16 16:08:15 +00004236 // This is especially useful for unrolled loops.
Dan Gohman8ec018c2010-05-20 20:00:41 +00004237
Jakub Staszak11bd8352013-02-16 16:08:15 +00004238 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4239 LSRUse &LU = Uses[LUIdx];
Craig Topper77b99412015-05-23 08:01:41 +00004240 for (const Formula &F : LU.Formulae) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004241 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
Jakub Staszak11bd8352013-02-16 16:08:15 +00004242 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004243
Jakub Staszak11bd8352013-02-16 16:08:15 +00004244 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4245 if (!LUThatHas)
4246 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004247
Jakub Staszak11bd8352013-02-16 16:08:15 +00004248 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4249 LU.Kind, LU.AccessTy))
4250 continue;
Dan Gohman110ed642010-09-01 01:45:53 +00004251
Jakub Staszak11bd8352013-02-16 16:08:15 +00004252 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman2fd85d72010-10-08 19:33:26 +00004253
Jakub Staszak11bd8352013-02-16 16:08:15 +00004254 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4255
Jonas Paulsson7a794222016-08-17 13:24:19 +00004256 // Transfer the fixups of LU to LUThatHas.
4257 for (LSRFixup &Fixup : LU.Fixups) {
4258 Fixup.Offset += F.BaseOffset;
4259 LUThatHas->pushFixup(Fixup);
4260 DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
Jakub Staszak11bd8352013-02-16 16:08:15 +00004261 }
Jonas Paulsson7a794222016-08-17 13:24:19 +00004262
Jakub Staszak11bd8352013-02-16 16:08:15 +00004263 // Delete formulae from the new use which are no longer legal.
4264 bool Any = false;
4265 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4266 Formula &F = LUThatHas->Formulae[i];
4267 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4268 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4269 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4270 dbgs() << '\n');
4271 LUThatHas->DeleteFormula(F);
4272 --i;
4273 --e;
4274 Any = true;
Dan Gohman20fab452010-05-19 23:43:12 +00004275 }
4276 }
Dan Gohman20fab452010-05-19 23:43:12 +00004277
Jakub Staszak11bd8352013-02-16 16:08:15 +00004278 if (Any)
4279 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4280
4281 // Delete the old use.
4282 DeleteUse(LU, LUIdx);
4283 --LUIdx;
4284 --NumUses;
4285 break;
4286 }
Dan Gohman20fab452010-05-19 23:43:12 +00004287 }
Jakub Staszak11bd8352013-02-16 16:08:15 +00004288
4289 DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
Dan Gohmane9e08732010-08-29 16:09:42 +00004290}
Dan Gohman20fab452010-05-19 23:43:12 +00004291
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004292/// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
Dan Gohman002ff892010-08-29 16:39:22 +00004293/// we've done more filtering, as it may be able to find more formulae to
4294/// eliminate.
4295void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4296 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4297 DEBUG(dbgs() << "The search space is too complex.\n");
4298
4299 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4300 "undesirable dedicated registers.\n");
4301
4302 FilterOutUndesirableDedicatedRegisters();
4303
4304 DEBUG(dbgs() << "After pre-selection:\n";
4305 print_uses(dbgs()));
4306 }
4307}
4308
Evgeny Stupachenko9909872e302017-02-21 07:34:40 +00004309/// The function delete formulas with high registers number expectation.
4310/// Assuming we don't know the value of each formula (already delete
4311/// all inefficient), generate probability of not selecting for each
4312/// register.
4313/// For example,
4314/// Use1:
4315/// reg(a) + reg({0,+,1})
4316/// reg(a) + reg({-1,+,1}) + 1
4317/// reg({a,+,1})
4318/// Use2:
4319/// reg(b) + reg({0,+,1})
4320/// reg(b) + reg({-1,+,1}) + 1
4321/// reg({b,+,1})
4322/// Use3:
4323/// reg(c) + reg(b) + reg({0,+,1})
4324/// reg(c) + reg({b,+,1})
4325///
4326/// Probability of not selecting
4327/// Use1 Use2 Use3
4328/// reg(a) (1/3) * 1 * 1
4329/// reg(b) 1 * (1/3) * (1/2)
4330/// reg({0,+,1}) (2/3) * (2/3) * (1/2)
4331/// reg({-1,+,1}) (2/3) * (2/3) * 1
4332/// reg({a,+,1}) (2/3) * 1 * 1
4333/// reg({b,+,1}) 1 * (2/3) * (2/3)
4334/// reg(c) 1 * 1 * 0
4335///
4336/// Now count registers number mathematical expectation for each formula:
4337/// Note that for each use we exclude probability if not selecting for the use.
4338/// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding
4339/// probabilty 1/3 of not selecting for Use1).
4340/// Use1:
4341/// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted
4342/// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted
4343/// reg({a,+,1}) 1
4344/// Use2:
4345/// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted
4346/// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted
4347/// reg({b,+,1}) 2/3
4348/// Use3:
4349/// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted
4350/// reg(c) + reg({b,+,1}) 1 + 2/3
4351
4352void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4353 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4354 return;
4355 // Ok, we have too many of formulae on our hands to conveniently handle.
4356 // Use a rough heuristic to thin out the list.
4357
4358 // Set of Regs wich will be 100% used in final solution.
4359 // Used in each formula of a solution (in example above this is reg(c)).
4360 // We can skip them in calculations.
4361 SmallPtrSet<const SCEV *, 4> UniqRegs;
4362 DEBUG(dbgs() << "The search space is too complex.\n");
4363
4364 // Map each register to probability of not selecting
4365 DenseMap <const SCEV *, float> RegNumMap;
4366 for (const SCEV *Reg : RegUses) {
4367 if (UniqRegs.count(Reg))
4368 continue;
4369 float PNotSel = 1;
4370 for (const LSRUse &LU : Uses) {
4371 if (!LU.Regs.count(Reg))
4372 continue;
4373 float P = LU.getNotSelectedProbability(Reg);
4374 if (P != 0.0)
4375 PNotSel *= P;
4376 else
4377 UniqRegs.insert(Reg);
4378 }
4379 RegNumMap.insert(std::make_pair(Reg, PNotSel));
4380 }
4381
4382 DEBUG(dbgs() << "Narrowing the search space by deleting costly formulas\n");
4383
4384 // Delete formulas where registers number expectation is high.
4385 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4386 LSRUse &LU = Uses[LUIdx];
4387 // If nothing to delete - continue.
4388 if (LU.Formulae.size() < 2)
4389 continue;
4390 // This is temporary solution to test performance. Float should be
4391 // replaced with round independent type (based on integers) to avoid
4392 // different results for different target builds.
4393 float FMinRegNum = LU.Formulae[0].getNumRegs();
4394 float FMinARegNum = LU.Formulae[0].getNumRegs();
4395 size_t MinIdx = 0;
4396 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4397 Formula &F = LU.Formulae[i];
4398 float FRegNum = 0;
4399 float FARegNum = 0;
4400 for (const SCEV *BaseReg : F.BaseRegs) {
4401 if (UniqRegs.count(BaseReg))
4402 continue;
4403 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4404 if (isa<SCEVAddRecExpr>(BaseReg))
4405 FARegNum +=
4406 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4407 }
4408 if (const SCEV *ScaledReg = F.ScaledReg) {
4409 if (!UniqRegs.count(ScaledReg)) {
4410 FRegNum +=
4411 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4412 if (isa<SCEVAddRecExpr>(ScaledReg))
4413 FARegNum +=
4414 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4415 }
4416 }
4417 if (FMinRegNum > FRegNum ||
4418 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
4419 FMinRegNum = FRegNum;
4420 FMinARegNum = FARegNum;
4421 MinIdx = i;
4422 }
4423 }
4424 DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs());
4425 dbgs() << " with min reg num " << FMinRegNum << '\n');
4426 if (MinIdx != 0)
4427 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
4428 while (LU.Formulae.size() != 1) {
4429 DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs());
4430 dbgs() << '\n');
4431 LU.Formulae.pop_back();
4432 }
4433 LU.RecomputeRegs(LUIdx, RegUses);
4434 assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula");
4435 Formula &F = LU.Formulae[0];
4436 DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n');
4437 // When we choose the formula, the regs become unique.
4438 UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
4439 if (F.ScaledReg)
4440 UniqRegs.insert(F.ScaledReg);
4441 }
4442 DEBUG(dbgs() << "After pre-selection:\n";
4443 print_uses(dbgs()));
4444}
4445
4446
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004447/// Pick a register which seems likely to be profitable, and then in any use
4448/// which has any reference to that register, delete all formulae which do not
4449/// reference that register.
Dan Gohmane9e08732010-08-29 16:09:42 +00004450void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004451 // With all other options exhausted, loop until the system is simple
4452 // enough to handle.
Dan Gohman45774ce2010-02-12 10:34:29 +00004453 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmana4eca052010-05-18 22:51:59 +00004454 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004455 // Ok, we have too many of formulae on our hands to conveniently handle.
4456 // Use a rough heuristic to thin out the list.
Dan Gohman63e90152010-05-18 22:41:32 +00004457 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004458
4459 // Pick the register which is used by the most LSRUses, which is likely
4460 // to be a good reuse register candidate.
Craig Topperf40110f2014-04-25 05:29:35 +00004461 const SCEV *Best = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00004462 unsigned BestNum = 0;
Craig Topper77b99412015-05-23 08:01:41 +00004463 for (const SCEV *Reg : RegUses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004464 if (Taken.count(Reg))
4465 continue;
Evgeny Stupachenko0c4300f2016-11-30 22:23:51 +00004466 if (!Best) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004467 Best = Reg;
Evgeny Stupachenko0c4300f2016-11-30 22:23:51 +00004468 BestNum = RegUses.getUsedByIndices(Reg).count();
4469 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00004470 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4471 if (Count > BestNum) {
4472 Best = Reg;
4473 BestNum = Count;
4474 }
4475 }
4476 }
4477
4478 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman8b0a4192010-03-01 17:49:51 +00004479 << " will yield profitable reuse.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004480 Taken.insert(Best);
4481
4482 // In any use with formulae which references this register, delete formulae
4483 // which don't reference it.
Dan Gohman4cf99b52010-05-18 23:42:37 +00004484 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4485 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00004486 if (!LU.Regs.count(Best)) continue;
4487
Dan Gohman4cf99b52010-05-18 23:42:37 +00004488 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00004489 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4490 Formula &F = LU.Formulae[i];
4491 if (!F.referencesReg(Best)) {
4492 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00004493 LU.DeleteFormula(F);
Dan Gohman45774ce2010-02-12 10:34:29 +00004494 --e;
4495 --i;
Dan Gohman4cf99b52010-05-18 23:42:37 +00004496 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00004497 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman45774ce2010-02-12 10:34:29 +00004498 continue;
4499 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004500 }
Dan Gohman4cf99b52010-05-18 23:42:37 +00004501
4502 if (Any)
4503 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman45774ce2010-02-12 10:34:29 +00004504 }
4505
4506 DEBUG(dbgs() << "After pre-selection:\n";
4507 print_uses(dbgs()));
4508 }
4509}
4510
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004511/// If there are an extraordinary number of formulae to choose from, use some
4512/// rough heuristics to prune down the number of formulae. This keeps the main
4513/// solver from taking an extraordinary amount of time in some worst-case
4514/// scenarios.
Dan Gohmane9e08732010-08-29 16:09:42 +00004515void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4516 NarrowSearchSpaceByDetectingSupersets();
4517 NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00004518 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Evgeny Stupachenko9909872e302017-02-21 07:34:40 +00004519 if (LSRExpNarrow)
4520 NarrowSearchSpaceByDeletingCostlyFormulas();
4521 else
4522 NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohmane9e08732010-08-29 16:09:42 +00004523}
4524
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004525/// This is the recursive solver.
Dan Gohman45774ce2010-02-12 10:34:29 +00004526void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4527 Cost &SolutionCost,
4528 SmallVectorImpl<const Formula *> &Workspace,
4529 const Cost &CurCost,
4530 const SmallPtrSet<const SCEV *, 16> &CurRegs,
4531 DenseSet<const SCEV *> &VisitedRegs) const {
4532 // Some ideas:
4533 // - prune more:
4534 // - use more aggressive filtering
4535 // - sort the formula so that the most profitable solutions are found first
4536 // - sort the uses too
4537 // - search faster:
Dan Gohman8b0a4192010-03-01 17:49:51 +00004538 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman45774ce2010-02-12 10:34:29 +00004539 // and bail early.
4540 // - track register sets with SmallBitVector
4541
4542 const LSRUse &LU = Uses[Workspace.size()];
4543
4544 // If this use references any register that's already a part of the
4545 // in-progress solution, consider it a requirement that a formula must
4546 // reference that register in order to be considered. This prunes out
4547 // unprofitable searching.
4548 SmallSetVector<const SCEV *, 4> ReqRegs;
Craig Topper46276792014-08-24 23:23:06 +00004549 for (const SCEV *S : CurRegs)
4550 if (LU.Regs.count(S))
4551 ReqRegs.insert(S);
Dan Gohman45774ce2010-02-12 10:34:29 +00004552
4553 SmallPtrSet<const SCEV *, 16> NewRegs;
4554 Cost NewCost;
Craig Topper77b99412015-05-23 08:01:41 +00004555 for (const Formula &F : LU.Formulae) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004556 // Ignore formulae which may not be ideal in terms of register reuse of
4557 // ReqRegs. The formula should use all required registers before
4558 // introducing new ones.
4559 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
Craig Topper77b99412015-05-23 08:01:41 +00004560 for (const SCEV *Reg : ReqRegs) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004561 if ((F.ScaledReg && F.ScaledReg == Reg) ||
David Majnemer0d955d02016-08-11 22:21:41 +00004562 is_contained(F.BaseRegs, Reg)) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004563 --NumReqRegsToFind;
4564 if (NumReqRegsToFind == 0)
4565 break;
Andrew Tricke3502cb2012-03-22 22:42:51 +00004566 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004567 }
Adam Nemetdeab6f92014-04-29 18:25:28 +00004568 if (NumReqRegsToFind != 0) {
Andrew Tricke3502cb2012-03-22 22:42:51 +00004569 // If none of the formulae satisfied the required registers, then we could
4570 // clear ReqRegs and try again. Currently, we simply give up in this case.
4571 continue;
4572 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004573
4574 // Evaluate the cost of the current formula. If it's already worse than
4575 // the current best, prune the search at that point.
4576 NewCost = CurCost;
4577 NewRegs = CurRegs;
Jonas Paulsson7a794222016-08-17 13:24:19 +00004578 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, SE, DT, LU);
Evgeny Stupachenkof2b3b462017-06-05 23:37:00 +00004579 if (NewCost.isLess(SolutionCost, TTI)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004580 Workspace.push_back(&F);
4581 if (Workspace.size() != Uses.size()) {
4582 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4583 NewRegs, VisitedRegs);
4584 if (F.getNumRegs() == 1 && Workspace.size() == 1)
4585 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4586 } else {
4587 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
Andrew Trick4dc3eff2012-01-09 18:58:16 +00004588 dbgs() << ".\n Regs:";
Craig Topper46276792014-08-24 23:23:06 +00004589 for (const SCEV *S : NewRegs)
4590 dbgs() << ' ' << *S;
Dan Gohman45774ce2010-02-12 10:34:29 +00004591 dbgs() << '\n');
4592
4593 SolutionCost = NewCost;
4594 Solution = Workspace;
4595 }
4596 Workspace.pop_back();
4597 }
Dan Gohman5b18f032010-02-13 02:06:02 +00004598 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004599}
4600
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004601/// Choose one formula from each use. Return the results in the given Solution
4602/// vector.
Dan Gohman45774ce2010-02-12 10:34:29 +00004603void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
4604 SmallVector<const Formula *, 8> Workspace;
4605 Cost SolutionCost;
Tim Northoverbc6659c2014-01-22 13:27:00 +00004606 SolutionCost.Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00004607 Cost CurCost;
4608 SmallPtrSet<const SCEV *, 16> CurRegs;
4609 DenseSet<const SCEV *> VisitedRegs;
4610 Workspace.reserve(Uses.size());
4611
Dan Gohman8ec018c2010-05-20 20:00:41 +00004612 // SolveRecurse does all the work.
Dan Gohman45774ce2010-02-12 10:34:29 +00004613 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4614 CurRegs, VisitedRegs);
Andrew Trick58124392011-09-27 00:44:14 +00004615 if (Solution.empty()) {
4616 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
4617 return;
4618 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004619
4620 // Ok, we've now made all our decisions.
4621 DEBUG(dbgs() << "\n"
4622 "The chosen solution requires "; SolutionCost.print(dbgs());
4623 dbgs() << ":\n";
4624 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
4625 dbgs() << " ";
4626 Uses[i].print(dbgs());
4627 dbgs() << "\n"
4628 " ";
4629 Solution[i]->print(dbgs());
4630 dbgs() << '\n';
4631 });
Dan Gohman6295f2e2010-05-20 20:59:23 +00004632
4633 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman45774ce2010-02-12 10:34:29 +00004634}
4635
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004636/// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
4637/// we can go while still being dominated by the input positions. This helps
4638/// canonicalize the insert position, which encourages sharing.
Dan Gohman607e02b2010-04-09 22:07:05 +00004639BasicBlock::iterator
4640LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
4641 const SmallVectorImpl<Instruction *> &Inputs)
4642 const {
Geoff Berry43e51602016-06-06 19:10:46 +00004643 Instruction *Tentative = &*IP;
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004644 while (true) {
Geoff Berry43e51602016-06-06 19:10:46 +00004645 bool AllDominate = true;
4646 Instruction *BetterPos = nullptr;
4647 // Don't bother attempting to insert before a catchswitch, their basic block
4648 // cannot have other non-PHI instructions.
4649 if (isa<CatchSwitchInst>(Tentative))
4650 return IP;
4651
4652 for (Instruction *Inst : Inputs) {
4653 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
4654 AllDominate = false;
4655 break;
4656 }
4657 // Attempt to find an insert position in the middle of the block,
4658 // instead of at the end, so that it can be used for other expansions.
4659 if (Tentative->getParent() == Inst->getParent() &&
4660 (!BetterPos || !DT.dominates(Inst, BetterPos)))
4661 BetterPos = &*std::next(BasicBlock::iterator(Inst));
4662 }
4663 if (!AllDominate)
4664 break;
4665 if (BetterPos)
4666 IP = BetterPos->getIterator();
4667 else
4668 IP = Tentative->getIterator();
4669
Dan Gohman607e02b2010-04-09 22:07:05 +00004670 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4671 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
4672
4673 BasicBlock *IDom;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004674 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman9b48b852010-05-20 22:46:54 +00004675 if (!Rung) return IP;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004676 Rung = Rung->getIDom();
4677 if (!Rung) return IP;
4678 IDom = Rung->getBlock();
Dan Gohman607e02b2010-04-09 22:07:05 +00004679
4680 // Don't climb into a loop though.
4681 const Loop *IDomLoop = LI.getLoopFor(IDom);
4682 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
4683 if (IDomDepth <= IPLoopDepth &&
4684 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4685 break;
4686 }
4687
Geoff Berry43e51602016-06-06 19:10:46 +00004688 Tentative = IDom->getTerminator();
Dan Gohman607e02b2010-04-09 22:07:05 +00004689 }
4690
4691 return IP;
4692}
4693
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004694/// Determine an input position which will be dominated by the operands and
4695/// which will dominate the result.
Dan Gohmand2df6432010-04-09 02:00:38 +00004696BasicBlock::iterator
Andrew Trickc908b432012-01-20 07:41:13 +00004697LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
Dan Gohman607e02b2010-04-09 22:07:05 +00004698 const LSRFixup &LF,
Andrew Trickc908b432012-01-20 07:41:13 +00004699 const LSRUse &LU,
4700 SCEVExpander &Rewriter) const {
Dan Gohmand2df6432010-04-09 02:00:38 +00004701 // Collect some instructions which must be dominated by the
Dan Gohmand006ab92010-04-07 22:27:08 +00004702 // expanding replacement. These must be dominated by any operands that
Dan Gohman45774ce2010-02-12 10:34:29 +00004703 // will be required in the expansion.
4704 SmallVector<Instruction *, 4> Inputs;
4705 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4706 Inputs.push_back(I);
4707 if (LU.Kind == LSRUse::ICmpZero)
4708 if (Instruction *I =
4709 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4710 Inputs.push_back(I);
Dan Gohmand006ab92010-04-07 22:27:08 +00004711 if (LF.PostIncLoops.count(L)) {
4712 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman52f55632010-03-02 01:59:21 +00004713 Inputs.push_back(L->getLoopLatch()->getTerminator());
4714 else
4715 Inputs.push_back(IVIncInsertPos);
4716 }
Dan Gohman45065392010-04-08 05:57:57 +00004717 // The expansion must also be dominated by the increment positions of any
4718 // loops it for which it is using post-inc mode.
Craig Topper77b99412015-05-23 08:01:41 +00004719 for (const Loop *PIL : LF.PostIncLoops) {
Dan Gohman45065392010-04-08 05:57:57 +00004720 if (PIL == L) continue;
4721
Dan Gohman607e02b2010-04-09 22:07:05 +00004722 // Be dominated by the loop exit.
Dan Gohman45065392010-04-08 05:57:57 +00004723 SmallVector<BasicBlock *, 4> ExitingBlocks;
4724 PIL->getExitingBlocks(ExitingBlocks);
4725 if (!ExitingBlocks.empty()) {
4726 BasicBlock *BB = ExitingBlocks[0];
4727 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
4728 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
4729 Inputs.push_back(BB->getTerminator());
4730 }
4731 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004732
David Majnemerba275f92015-08-19 19:54:02 +00004733 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
Andrew Trickc908b432012-01-20 07:41:13 +00004734 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4735 "Insertion point must be a normal instruction");
4736
Dan Gohman45774ce2010-02-12 10:34:29 +00004737 // Then, climb up the immediate dominator tree as far as we can go while
4738 // still being dominated by the input positions.
Andrew Trickc908b432012-01-20 07:41:13 +00004739 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
Dan Gohmand2df6432010-04-09 02:00:38 +00004740
4741 // Don't insert instructions before PHI nodes.
Dan Gohman45774ce2010-02-12 10:34:29 +00004742 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand2df6432010-04-09 02:00:38 +00004743
Bill Wendling86c5cbe2011-08-24 21:06:46 +00004744 // Ignore landingpad instructions.
David Majnemere09d0352016-03-24 21:40:22 +00004745 while (IP->isEHPad()) ++IP;
Bill Wendling86c5cbe2011-08-24 21:06:46 +00004746
Dan Gohmand2df6432010-04-09 02:00:38 +00004747 // Ignore debug intrinsics.
Dan Gohmand42e09d2010-03-26 00:33:27 +00004748 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman45774ce2010-02-12 10:34:29 +00004749
Andrew Trickc908b432012-01-20 07:41:13 +00004750 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
4751 // IP consistent across expansions and allows the previously inserted
4752 // instructions to be reused by subsequent expansion.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004753 while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
4754 ++IP;
Andrew Trickc908b432012-01-20 07:41:13 +00004755
Dan Gohmand2df6432010-04-09 02:00:38 +00004756 return IP;
4757}
4758
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004759/// Emit instructions for the leading candidate expression for this LSRUse (this
4760/// is called "expanding").
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004761Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF,
4762 const Formula &F, BasicBlock::iterator IP,
Dan Gohmand2df6432010-04-09 02:00:38 +00004763 SCEVExpander &Rewriter,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004764 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
Andrew Trick57243da2013-10-25 21:35:56 +00004765 if (LU.RigidFormula)
4766 return LF.OperandValToReplace;
Dan Gohmand2df6432010-04-09 02:00:38 +00004767
4768 // Determine an input position which will be dominated by the operands and
4769 // which will dominate the result.
Andrew Trickc908b432012-01-20 07:41:13 +00004770 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
Geoff Berryd0182802016-08-11 21:05:17 +00004771 Rewriter.setInsertPoint(&*IP);
Dan Gohmand2df6432010-04-09 02:00:38 +00004772
Dan Gohman45774ce2010-02-12 10:34:29 +00004773 // Inform the Rewriter if we have a post-increment use, so that it can
4774 // perform an advantageous expansion.
Dan Gohmand006ab92010-04-07 22:27:08 +00004775 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman45774ce2010-02-12 10:34:29 +00004776
4777 // This is the type that the user actually needs.
Chris Lattner229907c2011-07-18 04:54:35 +00004778 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004779 // This will be the type that we'll initially expand to.
Chris Lattner229907c2011-07-18 04:54:35 +00004780 Type *Ty = F.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004781 if (!Ty)
4782 // No type known; just expand directly to the ultimate type.
4783 Ty = OpTy;
4784 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
4785 // Expand directly to the ultimate type if it's the right size.
4786 Ty = OpTy;
4787 // This is the type to do integer arithmetic in.
Chris Lattner229907c2011-07-18 04:54:35 +00004788 Type *IntTy = SE.getEffectiveSCEVType(Ty);
Dan Gohman45774ce2010-02-12 10:34:29 +00004789
4790 // Build up a list of operands to add together to form the full base.
4791 SmallVector<const SCEV *, 8> Ops;
4792
4793 // Expand the BaseRegs portion.
Craig Topper77b99412015-05-23 08:01:41 +00004794 for (const SCEV *Reg : F.BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004795 assert(!Reg->isZero() && "Zero allocated in a base register!");
4796
Dan Gohmand006ab92010-04-07 22:27:08 +00004797 // If we're expanding for a post-inc user, make the post-inc adjustment.
Sanjoy Dase3a15e82017-04-14 15:49:59 +00004798 Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE);
Geoff Berryd0182802016-08-11 21:05:17 +00004799 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004800 }
4801
4802 // Expand the ScaledReg portion.
Craig Topperf40110f2014-04-25 05:29:35 +00004803 Value *ICmpScaledV = nullptr;
Chandler Carruth6e479322013-01-07 15:04:40 +00004804 if (F.Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004805 const SCEV *ScaledS = F.ScaledReg;
4806
Dan Gohmand006ab92010-04-07 22:27:08 +00004807 // If we're expanding for a post-inc user, make the post-inc adjustment.
4808 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
Sanjoy Dase3a15e82017-04-14 15:49:59 +00004809 ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00004810
4811 if (LU.Kind == LSRUse::ICmpZero) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004812 // Expand ScaleReg as if it was part of the base regs.
4813 if (F.Scale == 1)
Sanjoy Das215df9e2015-08-04 01:52:05 +00004814 Ops.push_back(
Geoff Berryd0182802016-08-11 21:05:17 +00004815 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)));
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004816 else {
4817 // An interesting way of "folding" with an icmp is to use a negated
4818 // scale, which we'll implement by inserting it into the other operand
4819 // of the icmp.
4820 assert(F.Scale == -1 &&
4821 "The only scale supported by ICmpZero uses is -1!");
Geoff Berryd0182802016-08-11 21:05:17 +00004822 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004823 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004824 } else {
4825 // Otherwise just expand the scaled register and an explicit scale,
4826 // which is expected to be matched as part of the address.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004827
4828 // Flush the operand list to suppress SCEVExpander hoisting address modes.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004829 // Unless the addressing mode will not be folded.
4830 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
4831 isAMCompletelyFolded(TTI, LU, F)) {
Geoff Berryd0182802016-08-11 21:05:17 +00004832 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
Andrew Trick8370c7c2012-06-15 20:07:29 +00004833 Ops.clear();
4834 Ops.push_back(SE.getUnknown(FullV));
4835 }
Geoff Berryd0182802016-08-11 21:05:17 +00004836 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr));
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004837 if (F.Scale != 1)
4838 ScaledS =
4839 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
Dan Gohman45774ce2010-02-12 10:34:29 +00004840 Ops.push_back(ScaledS);
4841 }
4842 }
4843
Dan Gohman29707de2010-03-03 05:29:13 +00004844 // Expand the GV portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004845 if (F.BaseGV) {
Dan Gohman29707de2010-03-03 05:29:13 +00004846 // Flush the operand list to suppress SCEVExpander hoisting.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004847 if (!Ops.empty()) {
Geoff Berryd0182802016-08-11 21:05:17 +00004848 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
Andrew Trick8370c7c2012-06-15 20:07:29 +00004849 Ops.clear();
4850 Ops.push_back(SE.getUnknown(FullV));
4851 }
Chandler Carruth6e479322013-01-07 15:04:40 +00004852 Ops.push_back(SE.getUnknown(F.BaseGV));
Andrew Trick8370c7c2012-06-15 20:07:29 +00004853 }
4854
4855 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
4856 // unfolded offsets. LSR assumes they both live next to their uses.
4857 if (!Ops.empty()) {
Geoff Berryd0182802016-08-11 21:05:17 +00004858 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +00004859 Ops.clear();
4860 Ops.push_back(SE.getUnknown(FullV));
4861 }
4862
4863 // Expand the immediate portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004864 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
Dan Gohman45774ce2010-02-12 10:34:29 +00004865 if (Offset != 0) {
4866 if (LU.Kind == LSRUse::ICmpZero) {
4867 // The other interesting way of "folding" with an ICmpZero is to use a
4868 // negated immediate.
4869 if (!ICmpScaledV)
Eli Friedmanb46345d2011-10-13 23:48:33 +00004870 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
Dan Gohman45774ce2010-02-12 10:34:29 +00004871 else {
4872 Ops.push_back(SE.getUnknown(ICmpScaledV));
4873 ICmpScaledV = ConstantInt::get(IntTy, Offset);
4874 }
4875 } else {
4876 // Just add the immediate values. These again are expected to be matched
4877 // as part of the address.
Dan Gohman29707de2010-03-03 05:29:13 +00004878 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004879 }
4880 }
4881
Dan Gohman6136e942011-05-03 00:46:49 +00004882 // Expand the unfolded offset portion.
4883 int64_t UnfoldedOffset = F.UnfoldedOffset;
4884 if (UnfoldedOffset != 0) {
4885 // Just add the immediate values.
4886 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
4887 UnfoldedOffset)));
4888 }
4889
Dan Gohman45774ce2010-02-12 10:34:29 +00004890 // Emit instructions summing all the operands.
4891 const SCEV *FullS = Ops.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +00004892 SE.getConstant(IntTy, 0) :
Dan Gohman45774ce2010-02-12 10:34:29 +00004893 SE.getAddExpr(Ops);
Geoff Berryd0182802016-08-11 21:05:17 +00004894 Value *FullV = Rewriter.expandCodeFor(FullS, Ty);
Dan Gohman45774ce2010-02-12 10:34:29 +00004895
4896 // We're done expanding now, so reset the rewriter.
Dan Gohmand006ab92010-04-07 22:27:08 +00004897 Rewriter.clearPostInc();
Dan Gohman45774ce2010-02-12 10:34:29 +00004898
4899 // An ICmpZero Formula represents an ICmp which we're handling as a
4900 // comparison against zero. Now that we've expanded an expression for that
4901 // form, update the ICmp's other operand.
4902 if (LU.Kind == LSRUse::ICmpZero) {
4903 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004904 DeadInsts.emplace_back(CI->getOperand(1));
Chandler Carruth6e479322013-01-07 15:04:40 +00004905 assert(!F.BaseGV && "ICmp does not support folding a global value and "
Dan Gohman45774ce2010-02-12 10:34:29 +00004906 "a scale at the same time!");
Chandler Carruth6e479322013-01-07 15:04:40 +00004907 if (F.Scale == -1) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004908 if (ICmpScaledV->getType() != OpTy) {
4909 Instruction *Cast =
4910 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
4911 OpTy, false),
4912 ICmpScaledV, OpTy, "tmp", CI);
4913 ICmpScaledV = Cast;
4914 }
4915 CI->setOperand(1, ICmpScaledV);
4916 } else {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004917 // A scale of 1 means that the scale has been expanded as part of the
4918 // base regs.
4919 assert((F.Scale == 0 || F.Scale == 1) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00004920 "ICmp does not support folding a global value and "
4921 "a scale at the same time!");
4922 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
4923 -(uint64_t)Offset);
4924 if (C->getType() != OpTy)
4925 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4926 OpTy, false),
4927 C, OpTy);
4928
4929 CI->setOperand(1, C);
4930 }
4931 }
4932
4933 return FullV;
4934}
4935
Sanjoy Das94c4aec2015-08-16 18:22:46 +00004936/// Helper for Rewrite. PHI nodes are special because the use of their operands
4937/// effectively happens in their predecessor blocks, so the expression may need
4938/// to be expanded in multiple places.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004939void LSRInstance::RewriteForPHI(
4940 PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F,
4941 SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
Dan Gohman6deab962010-02-16 20:25:07 +00004942 DenseMap<BasicBlock *, Value *> Inserted;
4943 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4944 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
4945 BasicBlock *BB = PN->getIncomingBlock(i);
4946
4947 // If this is a critical edge, split the edge so that we do not insert
4948 // the code on all predecessor/successor paths. We do this unless this
4949 // is the canonical backedge for this loop, which complicates post-inc
4950 // users.
4951 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
David Majnemerbba17392017-01-13 22:24:27 +00004952 !isa<IndirectBrInst>(BB->getTerminator()) &&
4953 !isa<CatchSwitchInst>(BB->getTerminator())) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004954 BasicBlock *Parent = PN->getParent();
4955 Loop *PNLoop = LI.getLoopFor(Parent);
4956 if (!PNLoop || Parent != PNLoop->getHeader()) {
Dan Gohmande7f6992011-02-08 00:55:13 +00004957 // Split the critical edge.
Craig Topperf40110f2014-04-25 05:29:35 +00004958 BasicBlock *NewBB = nullptr;
Bill Wendling3fb137f2011-08-25 05:55:40 +00004959 if (!Parent->isLandingPad()) {
Chandler Carruth37df2cf2015-01-19 12:09:11 +00004960 NewBB = SplitCriticalEdge(BB, Parent,
4961 CriticalEdgeSplittingOptions(&DT, &LI)
4962 .setMergeIdenticalEdges()
4963 .setDontDeleteUselessPHIs());
Bill Wendling3fb137f2011-08-25 05:55:40 +00004964 } else {
4965 SmallVector<BasicBlock*, 2> NewBBs;
Chandler Carruth96ada252015-07-22 09:52:54 +00004966 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI);
Bill Wendling3fb137f2011-08-25 05:55:40 +00004967 NewBB = NewBBs[0];
4968 }
Andrew Trick402edbb2012-09-18 17:51:33 +00004969 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
4970 // phi predecessors are identical. The simple thing to do is skip
4971 // splitting in this case rather than complicate the API.
4972 if (NewBB) {
4973 // If PN is outside of the loop and BB is in the loop, we want to
4974 // move the block to be immediately before the PHI block, not
4975 // immediately after BB.
4976 if (L->contains(BB) && !L->contains(PN))
4977 NewBB->moveBefore(PN->getParent());
Dan Gohman6deab962010-02-16 20:25:07 +00004978
Andrew Trick402edbb2012-09-18 17:51:33 +00004979 // Splitting the edge can reduce the number of PHI entries we have.
4980 e = PN->getNumIncomingValues();
4981 BB = NewBB;
4982 i = PN->getBasicBlockIndex(BB);
4983 }
Dan Gohmande7f6992011-02-08 00:55:13 +00004984 }
Dan Gohman6deab962010-02-16 20:25:07 +00004985 }
4986
4987 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
Craig Topperf40110f2014-04-25 05:29:35 +00004988 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
Dan Gohman6deab962010-02-16 20:25:07 +00004989 if (!Pair.second)
4990 PN->setIncomingValue(i, Pair.first->second);
4991 else {
Jonas Paulsson7a794222016-08-17 13:24:19 +00004992 Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004993 Rewriter, DeadInsts);
Dan Gohman6deab962010-02-16 20:25:07 +00004994
4995 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00004996 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman6deab962010-02-16 20:25:07 +00004997 if (FullV->getType() != OpTy)
4998 FullV =
4999 CastInst::Create(CastInst::getCastOpcode(FullV, false,
5000 OpTy, false),
5001 FullV, LF.OperandValToReplace->getType(),
5002 "tmp", BB->getTerminator());
5003
5004 PN->setIncomingValue(i, FullV);
5005 Pair.first->second = FullV;
5006 }
5007 }
5008}
5009
Sanjoy Das94c4aec2015-08-16 18:22:46 +00005010/// Emit instructions for the leading candidate expression for this LSRUse (this
5011/// is called "expanding"), and update the UserInst to reference the newly
5012/// expanded value.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00005013void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF,
5014 const Formula &F, SCEVExpander &Rewriter,
5015 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
Dan Gohman45774ce2010-02-12 10:34:29 +00005016 // First, find an insertion point that dominates UserInst. For PHI nodes,
5017 // find the nearest block which dominates all the relevant uses.
5018 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Jonas Paulsson7a794222016-08-17 13:24:19 +00005019 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
Dan Gohman45774ce2010-02-12 10:34:29 +00005020 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00005021 Value *FullV =
Jonas Paulsson7a794222016-08-17 13:24:19 +00005022 Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
Dan Gohman45774ce2010-02-12 10:34:29 +00005023
5024 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00005025 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00005026 if (FullV->getType() != OpTy) {
5027 Instruction *Cast =
5028 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
5029 FullV, OpTy, "tmp", LF.UserInst);
5030 FullV = Cast;
5031 }
5032
5033 // Update the user. ICmpZero is handled specially here (for now) because
5034 // Expand may have updated one of the operands of the icmp already, and
5035 // its new value may happen to be equal to LF.OperandValToReplace, in
5036 // which case doing replaceUsesOfWith leads to replacing both operands
5037 // with the same value. TODO: Reorganize this.
Jonas Paulsson7a794222016-08-17 13:24:19 +00005038 if (LU.Kind == LSRUse::ICmpZero)
Dan Gohman45774ce2010-02-12 10:34:29 +00005039 LF.UserInst->setOperand(0, FullV);
5040 else
5041 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
5042 }
5043
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005044 DeadInsts.emplace_back(LF.OperandValToReplace);
Dan Gohman45774ce2010-02-12 10:34:29 +00005045}
5046
Sanjoy Das94c4aec2015-08-16 18:22:46 +00005047/// Rewrite all the fixup locations with new values, following the chosen
5048/// solution.
Justin Bogner843fb202015-12-15 19:40:57 +00005049void LSRInstance::ImplementSolution(
5050 const SmallVectorImpl<const Formula *> &Solution) {
Dan Gohman45774ce2010-02-12 10:34:29 +00005051 // Keep track of instructions we may have made dead, so that
5052 // we can remove them after we are done working.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00005053 SmallVector<WeakTrackingVH, 16> DeadInsts;
Dan Gohman45774ce2010-02-12 10:34:29 +00005054
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005055 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
5056 "lsr");
Andrew Trick4dc3eff2012-01-09 18:58:16 +00005057#ifndef NDEBUG
5058 Rewriter.setDebugType(DEBUG_TYPE);
5059#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00005060 Rewriter.disableCanonicalMode();
Andrew Trick7fb669a2011-10-07 23:46:21 +00005061 Rewriter.enableLSRMode();
Dan Gohman45774ce2010-02-12 10:34:29 +00005062 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
5063
Andrew Trickd5d2db92012-01-10 01:45:08 +00005064 // Mark phi nodes that terminate chains so the expander tries to reuse them.
Craig Topper77b99412015-05-23 08:01:41 +00005065 for (const IVChain &Chain : IVChainVec) {
5066 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
Andrew Trickd5d2db92012-01-10 01:45:08 +00005067 Rewriter.setChainedPhi(PN);
5068 }
5069
Dan Gohman45774ce2010-02-12 10:34:29 +00005070 // Expand the new value definitions and update the users.
Jonas Paulsson7a794222016-08-17 13:24:19 +00005071 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5072 for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
5073 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
5074 Changed = true;
5075 }
Dan Gohman45774ce2010-02-12 10:34:29 +00005076
Craig Topper77b99412015-05-23 08:01:41 +00005077 for (const IVChain &Chain : IVChainVec) {
5078 GenerateIVChain(Chain, Rewriter, DeadInsts);
Andrew Trick248d4102012-01-09 21:18:52 +00005079 Changed = true;
5080 }
Dan Gohman45774ce2010-02-12 10:34:29 +00005081 // Clean up after ourselves. This must be done before deleting any
5082 // instructions.
5083 Rewriter.clear();
5084
5085 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
5086}
5087
Justin Bogner843fb202015-12-15 19:40:57 +00005088LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5089 DominatorTree &DT, LoopInfo &LI,
5090 const TargetTransformInfo &TTI)
5091 : IU(IU), SE(SE), DT(DT), LI(LI), TTI(TTI), L(L), Changed(false),
5092 IVIncInsertPos(nullptr) {
Dan Gohmana83ac2d2009-11-05 21:11:53 +00005093 // If LoopSimplify form is not available, stay out of trouble.
Andrew Trick732ad802012-01-07 03:16:50 +00005094 if (!L->isLoopSimplifyForm())
5095 return;
Dan Gohmana83ac2d2009-11-05 21:11:53 +00005096
Andrew Trick070e5402012-03-16 03:16:56 +00005097 // If there's no interesting work to be done, bail early.
5098 if (IU.empty()) return;
5099
Andrew Trick19f80c12012-04-18 04:00:10 +00005100 // If there's too much analysis to be done, bail early. We won't be able to
5101 // model the problem anyway.
5102 unsigned NumUsers = 0;
Craig Topper77b99412015-05-23 08:01:41 +00005103 for (const IVStrideUse &U : IU) {
Andrew Trick19f80c12012-04-18 04:00:10 +00005104 if (++NumUsers > MaxIVUsers) {
Craig Topper37d0d862015-05-23 08:20:33 +00005105 (void)U;
Craig Topper77b99412015-05-23 08:01:41 +00005106 DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
Andrew Trick19f80c12012-04-18 04:00:10 +00005107 return;
5108 }
David Majnemera53b5bb2016-02-03 21:30:34 +00005109 // Bail out if we have a PHI on an EHPad that gets a value from a
5110 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is
5111 // no good place to stick any instructions.
5112 if (auto *PN = dyn_cast<PHINode>(U.getUser())) {
5113 auto *FirstNonPHI = PN->getParent()->getFirstNonPHI();
5114 if (isa<FuncletPadInst>(FirstNonPHI) ||
5115 isa<CatchSwitchInst>(FirstNonPHI))
5116 for (BasicBlock *PredBB : PN->blocks())
5117 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
5118 return;
5119 }
Andrew Trick19f80c12012-04-18 04:00:10 +00005120 }
5121
Andrew Trick070e5402012-03-16 03:16:56 +00005122#ifndef NDEBUG
Andrew Trick12728f02012-01-17 06:45:52 +00005123 // All dominating loops must have preheaders, or SCEVExpander may not be able
5124 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
5125 //
Andrew Trick070e5402012-03-16 03:16:56 +00005126 // IVUsers analysis should only create users that are dominated by simple loop
5127 // headers. Since this loop should dominate all of its users, its user list
5128 // should be empty if this loop itself is not within a simple loop nest.
Andrew Trick12728f02012-01-17 06:45:52 +00005129 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
5130 Rung; Rung = Rung->getIDom()) {
5131 BasicBlock *BB = Rung->getBlock();
5132 const Loop *DomLoop = LI.getLoopFor(BB);
5133 if (DomLoop && DomLoop->getHeader() == BB) {
Andrew Trick070e5402012-03-16 03:16:56 +00005134 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
Andrew Trick12728f02012-01-17 06:45:52 +00005135 }
Andrew Trick732ad802012-01-07 03:16:50 +00005136 }
Andrew Trick070e5402012-03-16 03:16:56 +00005137#endif // DEBUG
Dan Gohman85875f72009-03-09 20:34:59 +00005138
Dan Gohman45774ce2010-02-12 10:34:29 +00005139 DEBUG(dbgs() << "\nLSR on loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00005140 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00005141 dbgs() << ":\n");
Dan Gohmane201f8f2009-03-09 20:46:50 +00005142
Dan Gohman927bcaa2010-05-20 20:33:18 +00005143 // First, perform some low-level loop optimizations.
Dan Gohman45774ce2010-02-12 10:34:29 +00005144 OptimizeShadowIV();
Dan Gohman4c4043c2010-05-20 20:05:31 +00005145 OptimizeLoopTermCond();
Evan Cheng78a4eb82009-05-11 22:33:01 +00005146
Andrew Trick8acb4342011-07-21 00:40:04 +00005147 // If loop preparation eliminates all interesting IV users, bail.
5148 if (IU.empty()) return;
5149
Andrew Trick168dfff2011-09-29 01:53:08 +00005150 // Skip nested loops until we can model them better with formulae.
Andrew Trickd97b83e2012-03-22 22:42:45 +00005151 if (!L->empty()) {
Andrew Trickbc6de902011-09-29 01:33:38 +00005152 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
Andrew Trick168dfff2011-09-29 01:53:08 +00005153 return;
Andrew Trickbc6de902011-09-29 01:33:38 +00005154 }
5155
Dan Gohman927bcaa2010-05-20 20:33:18 +00005156 // Start collecting data and preparing for the solver.
Andrew Trick29fe5f02012-01-09 19:50:34 +00005157 CollectChains();
Dan Gohman45774ce2010-02-12 10:34:29 +00005158 CollectInterestingTypesAndFactors();
5159 CollectFixupsAndInitialFormulae();
5160 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00005161
Andrew Trick248d4102012-01-09 21:18:52 +00005162 assert(!Uses.empty() && "IVUsers reported at least one use");
Dan Gohman45774ce2010-02-12 10:34:29 +00005163 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
5164 print_uses(dbgs()));
Misha Brukmanb1c93172005-04-21 23:48:37 +00005165
Dan Gohman45774ce2010-02-12 10:34:29 +00005166 // Now use the reuse data to generate a bunch of interesting ways
5167 // to formulate the values needed for the uses.
5168 GenerateAllReuseFormulae();
Evan Cheng3df447d2006-03-16 21:53:05 +00005169
Dan Gohman45774ce2010-02-12 10:34:29 +00005170 FilterOutUndesirableDedicatedRegisters();
5171 NarrowSearchSpaceUsingHeuristics();
Dan Gohman92c36962009-12-18 00:06:20 +00005172
Dan Gohman45774ce2010-02-12 10:34:29 +00005173 SmallVector<const Formula *, 8> Solution;
5174 Solve(Solution);
Dan Gohman92c36962009-12-18 00:06:20 +00005175
Dan Gohman45774ce2010-02-12 10:34:29 +00005176 // Release memory that is no longer needed.
5177 Factors.clear();
5178 Types.clear();
5179 RegUses.clear();
5180
Andrew Trick58124392011-09-27 00:44:14 +00005181 if (Solution.empty())
5182 return;
5183
Dan Gohman45774ce2010-02-12 10:34:29 +00005184#ifndef NDEBUG
5185 // Formulae should be legal.
Craig Topper77b99412015-05-23 08:01:41 +00005186 for (const LSRUse &LU : Uses) {
5187 for (const Formula &F : LU.Formulae)
Chandler Carruth26c59fa2013-01-07 14:41:08 +00005188 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
Craig Topper77b99412015-05-23 08:01:41 +00005189 F) && "Illegal formula generated!");
Dan Gohman45774ce2010-02-12 10:34:29 +00005190 };
5191#endif
5192
5193 // Now that we've decided what we want, make it so.
Justin Bogner843fb202015-12-15 19:40:57 +00005194 ImplementSolution(Solution);
Dan Gohman45774ce2010-02-12 10:34:29 +00005195}
5196
5197void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
5198 if (Factors.empty() && Types.empty()) return;
5199
5200 OS << "LSR has identified the following interesting factors and types: ";
5201 bool First = true;
5202
Craig Topper10949ae2015-05-23 08:45:10 +00005203 for (int64_t Factor : Factors) {
Dan Gohman45774ce2010-02-12 10:34:29 +00005204 if (!First) OS << ", ";
5205 First = false;
Craig Topper10949ae2015-05-23 08:45:10 +00005206 OS << '*' << Factor;
Evan Cheng87fe40b2009-11-10 21:14:05 +00005207 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00005208
Craig Topper10949ae2015-05-23 08:45:10 +00005209 for (Type *Ty : Types) {
Dan Gohman45774ce2010-02-12 10:34:29 +00005210 if (!First) OS << ", ";
5211 First = false;
Craig Topper10949ae2015-05-23 08:45:10 +00005212 OS << '(' << *Ty << ')';
Dan Gohman45774ce2010-02-12 10:34:29 +00005213 }
5214 OS << '\n';
5215}
5216
5217void LSRInstance::print_fixups(raw_ostream &OS) const {
5218 OS << "LSR is examining the following fixup sites:\n";
Jonas Paulsson7a794222016-08-17 13:24:19 +00005219 for (const LSRUse &LU : Uses)
5220 for (const LSRFixup &LF : LU.Fixups) {
5221 dbgs() << " ";
5222 LF.print(OS);
5223 OS << '\n';
5224 }
Dan Gohman45774ce2010-02-12 10:34:29 +00005225}
5226
5227void LSRInstance::print_uses(raw_ostream &OS) const {
5228 OS << "LSR is examining the following uses:\n";
Craig Topper77b99412015-05-23 08:01:41 +00005229 for (const LSRUse &LU : Uses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00005230 dbgs() << " ";
5231 LU.print(OS);
5232 OS << '\n';
Craig Topper77b99412015-05-23 08:01:41 +00005233 for (const Formula &F : LU.Formulae) {
Dan Gohman45774ce2010-02-12 10:34:29 +00005234 OS << " ";
Craig Topper77b99412015-05-23 08:01:41 +00005235 F.print(OS);
Dan Gohman45774ce2010-02-12 10:34:29 +00005236 OS << '\n';
5237 }
5238 }
5239}
5240
5241void LSRInstance::print(raw_ostream &OS) const {
5242 print_factors_and_types(OS);
5243 print_fixups(OS);
5244 print_uses(OS);
5245}
5246
Matthias Braun8c209aa2017-01-28 02:02:38 +00005247#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5248LLVM_DUMP_METHOD void LSRInstance::dump() const {
Dan Gohman45774ce2010-02-12 10:34:29 +00005249 print(errs()); errs() << '\n';
5250}
Matthias Braun8c209aa2017-01-28 02:02:38 +00005251#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00005252
5253namespace {
5254
5255class LoopStrengthReduce : public LoopPass {
Dan Gohman45774ce2010-02-12 10:34:29 +00005256public:
5257 static char ID; // Pass ID, replacement for typeid
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005258
Chandler Carruth26c59fa2013-01-07 14:41:08 +00005259 LoopStrengthReduce();
Dan Gohman45774ce2010-02-12 10:34:29 +00005260
5261private:
Craig Topper3e4c6972014-03-05 09:10:37 +00005262 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
5263 void getAnalysisUsage(AnalysisUsage &AU) const override;
Dan Gohman45774ce2010-02-12 10:34:29 +00005264};
Dan Gohman45774ce2010-02-12 10:34:29 +00005265
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005266} // end anonymous namespace
Dan Gohman45774ce2010-02-12 10:34:29 +00005267
Chandler Carruth26c59fa2013-01-07 14:41:08 +00005268LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
5269 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
5270}
Dan Gohman45774ce2010-02-12 10:34:29 +00005271
5272void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
5273 // We split critical edges, so we change the CFG. However, we do update
5274 // many analyses if they are around.
Eric Christopherda6bd452011-02-10 01:48:24 +00005275 AU.addPreservedID(LoopSimplifyID);
Dan Gohman45774ce2010-02-12 10:34:29 +00005276
Chandler Carruth4f8f3072015-01-17 14:16:18 +00005277 AU.addRequired<LoopInfoWrapperPass>();
5278 AU.addPreserved<LoopInfoWrapperPass>();
Eric Christopherda6bd452011-02-10 01:48:24 +00005279 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth73523022014-01-13 13:07:17 +00005280 AU.addRequired<DominatorTreeWrapperPass>();
5281 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005282 AU.addRequired<ScalarEvolutionWrapperPass>();
5283 AU.addPreserved<ScalarEvolutionWrapperPass>();
Cameron Zwarich97dae4d2011-02-10 23:53:14 +00005284 // Requiring LoopSimplify a second time here prevents IVUsers from running
5285 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5286 AU.addRequiredID(LoopSimplifyID);
Dehao Chen1a444522016-07-16 22:51:33 +00005287 AU.addRequired<IVUsersWrapperPass>();
5288 AU.addPreserved<IVUsersWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00005289 AU.addRequired<TargetTransformInfoWrapperPass>();
Dan Gohman45774ce2010-02-12 10:34:29 +00005290}
5291
Dehao Chen6132ee82016-07-18 21:41:50 +00005292static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5293 DominatorTree &DT, LoopInfo &LI,
5294 const TargetTransformInfo &TTI) {
Dan Gohman45774ce2010-02-12 10:34:29 +00005295 bool Changed = false;
5296
5297 // Run the main LSR transformation.
Justin Bogner843fb202015-12-15 19:40:57 +00005298 Changed |= LSRInstance(L, IU, SE, DT, LI, TTI).getChanged();
Dan Gohman45774ce2010-02-12 10:34:29 +00005299
Andrew Trick2ec61a82012-01-07 01:36:44 +00005300 // Remove any extra phis created by processing inner loops.
Dan Gohmanb5358002010-01-05 16:31:45 +00005301 Changed |= DeleteDeadPHIs(L->getHeader());
Andrew Trickf950ce82013-01-06 05:59:39 +00005302 if (EnablePhiElim && L->isLoopSimplifyForm()) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00005303 SmallVector<WeakTrackingVH, 16> DeadInsts;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005304 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
Dehao Chen6132ee82016-07-18 21:41:50 +00005305 SCEVExpander Rewriter(SE, DL, "lsr");
Andrew Trick2ec61a82012-01-07 01:36:44 +00005306#ifndef NDEBUG
5307 Rewriter.setDebugType(DEBUG_TYPE);
5308#endif
Dehao Chen6132ee82016-07-18 21:41:50 +00005309 unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI);
Andrew Trick2ec61a82012-01-07 01:36:44 +00005310 if (numFolded) {
5311 Changed = true;
5312 DeleteTriviallyDeadInstructions(DeadInsts);
5313 DeleteDeadPHIs(L->getHeader());
5314 }
5315 }
Evan Cheng03001cb2008-07-07 19:51:32 +00005316 return Changed;
Nate Begemanb18121e2004-10-18 21:08:22 +00005317}
Dehao Chen6132ee82016-07-18 21:41:50 +00005318
5319bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
5320 if (skipLoop(L))
5321 return false;
5322
5323 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5324 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5325 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5326 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5327 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5328 *L->getHeader()->getParent());
5329 return ReduceLoopStrength(L, IU, SE, DT, LI, TTI);
5330}
5331
Chandler Carruth410eaeb2017-01-11 06:23:21 +00005332PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,
5333 LoopStandardAnalysisResults &AR,
5334 LPMUpdater &) {
5335 if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE,
5336 AR.DT, AR.LI, AR.TTI))
Dehao Chen6132ee82016-07-18 21:41:50 +00005337 return PreservedAnalyses::all();
5338
5339 return getLoopPassPreservedAnalyses();
5340}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005341
5342char LoopStrengthReduce::ID = 0;
5343INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
5344 "Loop Strength Reduction", false, false)
5345INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5346INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5347INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5348INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass)
5349INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5350INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5351INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
5352 "Loop Strength Reduction", false, false)
5353
5354Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }