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