LLVM  7.0.0svn
LoopStrengthReduce.cpp
Go to the documentation of this file.
1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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 //
14 // This pass performs a strength reduction on array references inside loops that
15 // 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.
19 //
20 // Terminology note: this code has a lot of handling for "post-increment" or
21 // "post-inc" users. This is not talking about post-increment addressing modes;
22 // it is instead talking about code like this:
23 //
24 // %i = phi [ 0, %entry ], [ %i.next, %latch ]
25 // ...
26 // %i.next = add %i, 1
27 // %c = icmp eq %i.next, %n
28 //
29 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
30 // it's useful to think about these as the same register, with some uses using
31 // the value of the register before the add and some using it after. In this
32 // example, the icmp is a post-increment user, since it uses %i.next, which is
33 // the value of the induction variable after the increment. The other common
34 // case of post-increment users is users outside the loop.
35 //
36 // TODO: More sophistication in the way Formulae are generated and filtered.
37 //
38 // TODO: Handle multiple loops at a time.
39 //
40 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
41 // of a GlobalValue?
42 //
43 // TODO: When truncation is free, truncate ICmp users' operands to make it a
44 // smaller encoding (on x86 at least).
45 //
46 // TODO: When a negated register is used by an add (such as in a list of
47 // multiple base registers, or as the increment expression in an addrec),
48 // we may not actually need both reg and (-1 * reg) in registers; the
49 // negation can be implemented by using a sub instead of an add. The
50 // lack of support for taking this into consideration when making
51 // register pressure decisions is partly worked around by the "Special"
52 // use kind.
53 //
54 //===----------------------------------------------------------------------===//
55 
57 #include "llvm/ADT/APInt.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/DenseSet.h"
60 #include "llvm/ADT/Hashing.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/ADT/SetVector.h"
65 #include "llvm/ADT/SmallPtrSet.h"
66 #include "llvm/ADT/SmallSet.h"
67 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/Analysis/IVUsers.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/LoopPass.h"
79 #include "llvm/IR/BasicBlock.h"
80 #include "llvm/IR/Constant.h"
81 #include "llvm/IR/Constants.h"
82 #include "llvm/IR/DerivedTypes.h"
83 #include "llvm/IR/Dominators.h"
84 #include "llvm/IR/GlobalValue.h"
85 #include "llvm/IR/IRBuilder.h"
86 #include "llvm/IR/InstrTypes.h"
87 #include "llvm/IR/Instruction.h"
88 #include "llvm/IR/Instructions.h"
89 #include "llvm/IR/IntrinsicInst.h"
90 #include "llvm/IR/Intrinsics.h"
91 #include "llvm/IR/Module.h"
92 #include "llvm/IR/OperandTraits.h"
93 #include "llvm/IR/Operator.h"
94 #include "llvm/IR/PassManager.h"
95 #include "llvm/IR/Type.h"
96 #include "llvm/IR/Use.h"
97 #include "llvm/IR/User.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/IR/ValueHandle.h"
100 #include "llvm/Pass.h"
101 #include "llvm/Support/Casting.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
106 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Transforms/Scalar.h"
109 #include "llvm/Transforms/Utils.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstdlib>
116 #include <iterator>
117 #include <limits>
118 #include <map>
119 #include <utility>
120 
121 using namespace llvm;
122 
123 #define DEBUG_TYPE "loop-reduce"
124 
125 /// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for
126 /// bail out. This threshold is far beyond the number of users that LSR can
127 /// conceivably solve, so it should not affect generated code, but catches the
128 /// worst cases before LSR burns too much compile time and stack space.
129 static const unsigned MaxIVUsers = 200;
130 
131 // Temporary flag to cleanup congruent phis after LSR phi expansion.
132 // It's currently disabled until we can determine whether it's truly useful or
133 // not. The flag should be removed after the v3.0 release.
134 // This is now needed for ivchains.
136  "enable-lsr-phielim", cl::Hidden, cl::init(true),
137  cl::desc("Enable LSR phi elimination"));
138 
139 // The flag adds instruction count to solutions cost comparision.
140 static cl::opt<bool> InsnsCost(
141  "lsr-insns-cost", cl::Hidden, cl::init(true),
142  cl::desc("Add instruction count to a LSR cost model"));
143 
144 // Flag to choose how to narrow complex lsr solution
146  "lsr-exp-narrow", cl::Hidden, cl::init(false),
147  cl::desc("Narrow LSR complex solution using"
148  " expectation of registers number"));
149 
150 // Flag to narrow search space by filtering non-optimal formulae with
151 // the same ScaledReg and Scale.
153  "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true),
154  cl::desc("Narrow LSR search space by filtering non-optimal formulae"
155  " with the same ScaledReg and Scale"));
156 
157 #ifndef NDEBUG
158 // Stress test IV chain generation.
160  "stress-ivchain", cl::Hidden, cl::init(false),
161  cl::desc("Stress test LSR IV chains"));
162 #else
163 static bool StressIVChain = false;
164 #endif
165 
166 namespace {
167 
168 struct MemAccessTy {
169  /// Used in situations where the accessed memory type is unknown.
170  static const unsigned UnknownAddressSpace =
172 
173  Type *MemTy = nullptr;
174  unsigned AddrSpace = UnknownAddressSpace;
175 
176  MemAccessTy() = default;
177  MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
178 
179  bool operator==(MemAccessTy Other) const {
180  return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
181  }
182 
183  bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
184 
185  static MemAccessTy getUnknown(LLVMContext &Ctx,
186  unsigned AS = UnknownAddressSpace) {
187  return MemAccessTy(Type::getVoidTy(Ctx), AS);
188  }
189 
190  Type *getType() { return MemTy; }
191 };
192 
193 /// This class holds data which is used to order reuse candidates.
194 class RegSortData {
195 public:
196  /// This represents the set of LSRUse indices which reference
197  /// a particular register.
198  SmallBitVector UsedByIndices;
199 
200  void print(raw_ostream &OS) const;
201  void dump() const;
202 };
203 
204 } // end anonymous namespace
205 
206 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
207 void RegSortData::print(raw_ostream &OS) const {
208  OS << "[NumUses=" << UsedByIndices.count() << ']';
209 }
210 
211 LLVM_DUMP_METHOD void RegSortData::dump() const {
212  print(errs()); errs() << '\n';
213 }
214 #endif
215 
216 namespace {
217 
218 /// Map register candidates to information about how they are used.
219 class RegUseTracker {
220  using RegUsesTy = DenseMap<const SCEV *, RegSortData>;
221 
222  RegUsesTy RegUsesMap;
224 
225 public:
226  void countRegister(const SCEV *Reg, size_t LUIdx);
227  void dropRegister(const SCEV *Reg, size_t LUIdx);
228  void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
229 
230  bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
231 
232  const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
233 
234  void clear();
235 
237  using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator;
238 
239  iterator begin() { return RegSequence.begin(); }
240  iterator end() { return RegSequence.end(); }
241  const_iterator begin() const { return RegSequence.begin(); }
242  const_iterator end() const { return RegSequence.end(); }
243 };
244 
245 } // end anonymous namespace
246 
247 void
248 RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
249  std::pair<RegUsesTy::iterator, bool> Pair =
250  RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
251  RegSortData &RSD = Pair.first->second;
252  if (Pair.second)
253  RegSequence.push_back(Reg);
254  RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
255  RSD.UsedByIndices.set(LUIdx);
256 }
257 
258 void
259 RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
260  RegUsesTy::iterator It = RegUsesMap.find(Reg);
261  assert(It != RegUsesMap.end());
262  RegSortData &RSD = It->second;
263  assert(RSD.UsedByIndices.size() > LUIdx);
264  RSD.UsedByIndices.reset(LUIdx);
265 }
266 
267 void
268 RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
269  assert(LUIdx <= LastLUIdx);
270 
271  // Update RegUses. The data structure is not optimized for this purpose;
272  // we must iterate through it and update each of the bit vectors.
273  for (auto &Pair : RegUsesMap) {
274  SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
275  if (LUIdx < UsedByIndices.size())
276  UsedByIndices[LUIdx] =
277  LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
278  UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
279  }
280 }
281 
282 bool
283 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
284  RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
285  if (I == RegUsesMap.end())
286  return false;
287  const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
288  int i = UsedByIndices.find_first();
289  if (i == -1) return false;
290  if ((size_t)i != LUIdx) return true;
291  return UsedByIndices.find_next(i) != -1;
292 }
293 
294 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
295  RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
296  assert(I != RegUsesMap.end() && "Unknown register!");
297  return I->second.UsedByIndices;
298 }
299 
300 void RegUseTracker::clear() {
301  RegUsesMap.clear();
302  RegSequence.clear();
303 }
304 
305 namespace {
306 
307 /// This class holds information that describes a formula for computing
308 /// satisfying a use. It may include broken-out immediates and scaled registers.
309 struct Formula {
310  /// Global base address used for complex addressing.
311  GlobalValue *BaseGV = nullptr;
312 
313  /// Base offset for complex addressing.
314  int64_t BaseOffset = 0;
315 
316  /// Whether any complex addressing has a base register.
317  bool HasBaseReg = false;
318 
319  /// The scale of any complex addressing.
320  int64_t Scale = 0;
321 
322  /// The list of "base" registers for this use. When this is non-empty. The
323  /// canonical representation of a formula is
324  /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
325  /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
326  /// 3. The reg containing recurrent expr related with currect loop in the
327  /// formula should be put in the ScaledReg.
328  /// #1 enforces that the scaled register is always used when at least two
329  /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
330  /// #2 enforces that 1 * reg is reg.
331  /// #3 ensures invariant regs with respect to current loop can be combined
332  /// together in LSR codegen.
333  /// This invariant can be temporarly broken while building a formula.
334  /// However, every formula inserted into the LSRInstance must be in canonical
335  /// form.
337 
338  /// The 'scaled' register for this use. This should be non-null when Scale is
339  /// not zero.
340  const SCEV *ScaledReg = nullptr;
341 
342  /// An additional constant offset which added near the use. This requires a
343  /// temporary register, but the offset itself can live in an add immediate
344  /// field rather than a register.
345  int64_t UnfoldedOffset = 0;
346 
347  Formula() = default;
348 
349  void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
350 
351  bool isCanonical(const Loop &L) const;
352 
353  void canonicalize(const Loop &L);
354 
355  bool unscale();
356 
357  bool hasZeroEnd() const;
358 
359  size_t getNumRegs() const;
360  Type *getType() const;
361 
362  void deleteBaseReg(const SCEV *&S);
363 
364  bool referencesReg(const SCEV *S) const;
365  bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
366  const RegUseTracker &RegUses) const;
367 
368  void print(raw_ostream &OS) const;
369  void dump() const;
370 };
371 
372 } // end anonymous namespace
373 
374 /// Recursion helper for initialMatch.
375 static void DoInitialMatch(const SCEV *S, Loop *L,
378  ScalarEvolution &SE) {
379  // Collect expressions which properly dominate the loop header.
380  if (SE.properlyDominates(S, L->getHeader())) {
381  Good.push_back(S);
382  return;
383  }
384 
385  // Look at add operands.
386  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
387  for (const SCEV *S : Add->operands())
388  DoInitialMatch(S, L, Good, Bad, SE);
389  return;
390  }
391 
392  // Look at addrec operands.
393  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
394  if (!AR->getStart()->isZero() && AR->isAffine()) {
395  DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
396  DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
397  AR->getStepRecurrence(SE),
398  // FIXME: AR->getNoWrapFlags()
399  AR->getLoop(), SCEV::FlagAnyWrap),
400  L, Good, Bad, SE);
401  return;
402  }
403 
404  // Handle a multiplication by -1 (negation) if it didn't fold.
405  if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
406  if (Mul->getOperand(0)->isAllOnesValue()) {
407  SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
408  const SCEV *NewMul = SE.getMulExpr(Ops);
409 
412  DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
413  const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
414  SE.getEffectiveSCEVType(NewMul->getType())));
415  for (const SCEV *S : MyGood)
416  Good.push_back(SE.getMulExpr(NegOne, S));
417  for (const SCEV *S : MyBad)
418  Bad.push_back(SE.getMulExpr(NegOne, S));
419  return;
420  }
421 
422  // Ok, we can't do anything interesting. Just stuff the whole thing into a
423  // register and hope for the best.
424  Bad.push_back(S);
425 }
426 
427 /// Incorporate loop-variant parts of S into this Formula, attempting to keep
428 /// all loop-invariant and loop-computable values in a single base register.
429 void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
432  DoInitialMatch(S, L, Good, Bad, SE);
433  if (!Good.empty()) {
434  const SCEV *Sum = SE.getAddExpr(Good);
435  if (!Sum->isZero())
436  BaseRegs.push_back(Sum);
437  HasBaseReg = true;
438  }
439  if (!Bad.empty()) {
440  const SCEV *Sum = SE.getAddExpr(Bad);
441  if (!Sum->isZero())
442  BaseRegs.push_back(Sum);
443  HasBaseReg = true;
444  }
445  canonicalize(*L);
446 }
447 
448 /// \brief Check whether or not this formula satisfies the canonical
449 /// representation.
450 /// \see Formula::BaseRegs.
451 bool Formula::isCanonical(const Loop &L) const {
452  if (!ScaledReg)
453  return BaseRegs.size() <= 1;
454 
455  if (Scale != 1)
456  return true;
457 
458  if (Scale == 1 && BaseRegs.empty())
459  return false;
460 
461  const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
462  if (SAR && SAR->getLoop() == &L)
463  return true;
464 
465  // If ScaledReg is not a recurrent expr, or it is but its loop is not current
466  // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
467  // loop, we want to swap the reg in BaseRegs with ScaledReg.
468  auto I =
469  find_if(make_range(BaseRegs.begin(), BaseRegs.end()), [&](const SCEV *S) {
470  return isa<const SCEVAddRecExpr>(S) &&
471  (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
472  });
473  return I == BaseRegs.end();
474 }
475 
476 /// \brief Helper method to morph a formula into its canonical representation.
477 /// \see Formula::BaseRegs.
478 /// Every formula having more than one base register, must use the ScaledReg
479 /// field. Otherwise, we would have to do special cases everywhere in LSR
480 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
481 /// On the other hand, 1*reg should be canonicalized into reg.
482 void Formula::canonicalize(const Loop &L) {
483  if (isCanonical(L))
484  return;
485  // So far we did not need this case. This is easy to implement but it is
486  // useless to maintain dead code. Beside it could hurt compile time.
487  assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
488 
489  // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
490  if (!ScaledReg) {
491  ScaledReg = BaseRegs.back();
492  BaseRegs.pop_back();
493  Scale = 1;
494  }
495 
496  // If ScaledReg is an invariant with respect to L, find the reg from
497  // BaseRegs containing the recurrent expr related with Loop L. Swap the
498  // reg with ScaledReg.
499  const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
500  if (!SAR || SAR->getLoop() != &L) {
501  auto I = find_if(make_range(BaseRegs.begin(), BaseRegs.end()),
502  [&](const SCEV *S) {
503  return isa<const SCEVAddRecExpr>(S) &&
504  (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
505  });
506  if (I != BaseRegs.end())
507  std::swap(ScaledReg, *I);
508  }
509 }
510 
511 /// \brief Get rid of the scale in the formula.
512 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
513 /// \return true if it was possible to get rid of the scale, false otherwise.
514 /// \note After this operation the formula may not be in the canonical form.
515 bool Formula::unscale() {
516  if (Scale != 1)
517  return false;
518  Scale = 0;
519  BaseRegs.push_back(ScaledReg);
520  ScaledReg = nullptr;
521  return true;
522 }
523 
524 bool Formula::hasZeroEnd() const {
525  if (UnfoldedOffset || BaseOffset)
526  return false;
527  if (BaseRegs.size() != 1 || ScaledReg)
528  return false;
529  return true;
530 }
531 
532 /// Return the total number of register operands used by this formula. This does
533 /// not include register uses implied by non-constant addrec strides.
534 size_t Formula::getNumRegs() const {
535  return !!ScaledReg + BaseRegs.size();
536 }
537 
538 /// Return the type of this formula, if it has one, or null otherwise. This type
539 /// is meaningless except for the bit size.
540 Type *Formula::getType() const {
541  return !BaseRegs.empty() ? BaseRegs.front()->getType() :
542  ScaledReg ? ScaledReg->getType() :
543  BaseGV ? BaseGV->getType() :
544  nullptr;
545 }
546 
547 /// Delete the given base reg from the BaseRegs list.
548 void Formula::deleteBaseReg(const SCEV *&S) {
549  if (&S != &BaseRegs.back())
550  std::swap(S, BaseRegs.back());
551  BaseRegs.pop_back();
552 }
553 
554 /// Test if this formula references the given register.
555 bool Formula::referencesReg(const SCEV *S) const {
556  return S == ScaledReg || is_contained(BaseRegs, S);
557 }
558 
559 /// Test whether this formula uses registers which are used by uses other than
560 /// the use with the given index.
561 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
562  const RegUseTracker &RegUses) const {
563  if (ScaledReg)
564  if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
565  return true;
566  for (const SCEV *BaseReg : BaseRegs)
567  if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
568  return true;
569  return false;
570 }
571 
572 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
573 void Formula::print(raw_ostream &OS) const {
574  bool First = true;
575  if (BaseGV) {
576  if (!First) OS << " + "; else First = false;
577  BaseGV->printAsOperand(OS, /*PrintType=*/false);
578  }
579  if (BaseOffset != 0) {
580  if (!First) OS << " + "; else First = false;
581  OS << BaseOffset;
582  }
583  for (const SCEV *BaseReg : BaseRegs) {
584  if (!First) OS << " + "; else First = false;
585  OS << "reg(" << *BaseReg << ')';
586  }
587  if (HasBaseReg && BaseRegs.empty()) {
588  if (!First) OS << " + "; else First = false;
589  OS << "**error: HasBaseReg**";
590  } else if (!HasBaseReg && !BaseRegs.empty()) {
591  if (!First) OS << " + "; else First = false;
592  OS << "**error: !HasBaseReg**";
593  }
594  if (Scale != 0) {
595  if (!First) OS << " + "; else First = false;
596  OS << Scale << "*reg(";
597  if (ScaledReg)
598  OS << *ScaledReg;
599  else
600  OS << "<unknown>";
601  OS << ')';
602  }
603  if (UnfoldedOffset != 0) {
604  if (!First) OS << " + ";
605  OS << "imm(" << UnfoldedOffset << ')';
606  }
607 }
608 
609 LLVM_DUMP_METHOD void Formula::dump() const {
610  print(errs()); errs() << '\n';
611 }
612 #endif
613 
614 /// Return true if the given addrec can be sign-extended without changing its
615 /// value.
616 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
617  Type *WideTy =
619  return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
620 }
621 
622 /// Return true if the given add can be sign-extended without changing its
623 /// value.
624 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
625  Type *WideTy =
627  return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
628 }
629 
630 /// Return true if the given mul can be sign-extended without changing its
631 /// value.
632 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
633  Type *WideTy =
635  SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
636  return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
637 }
638 
639 /// Return an expression for LHS /s RHS, if it can be determined and if the
640 /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
641 /// is true, expressions like (X * Y) /s Y are simplified to Y, ignoring that
642 /// the multiplication may overflow, which is useful when the result will be
643 /// used in a context where the most significant bits are ignored.
644 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
645  ScalarEvolution &SE,
646  bool IgnoreSignificantBits = false) {
647  // Handle the trivial case, which works for any SCEV type.
648  if (LHS == RHS)
649  return SE.getConstant(LHS->getType(), 1);
650 
651  // Handle a few RHS special cases.
652  const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
653  if (RC) {
654  const APInt &RA = RC->getAPInt();
655  // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
656  // some folding.
657  if (RA.isAllOnesValue())
658  return SE.getMulExpr(LHS, RC);
659  // Handle x /s 1 as x.
660  if (RA == 1)
661  return LHS;
662  }
663 
664  // Check for a division of a constant by a constant.
665  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
666  if (!RC)
667  return nullptr;
668  const APInt &LA = C->getAPInt();
669  const APInt &RA = RC->getAPInt();
670  if (LA.srem(RA) != 0)
671  return nullptr;
672  return SE.getConstant(LA.sdiv(RA));
673  }
674 
675  // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
676  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
677  if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
678  const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
679  IgnoreSignificantBits);
680  if (!Step) return nullptr;
681  const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
682  IgnoreSignificantBits);
683  if (!Start) return nullptr;
684  // FlagNW is independent of the start value, step direction, and is
685  // preserved with smaller magnitude steps.
686  // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
687  return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
688  }
689  return nullptr;
690  }
691 
692  // Distribute the sdiv over add operands, if the add doesn't overflow.
693  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
694  if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
696  for (const SCEV *S : Add->operands()) {
697  const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
698  if (!Op) return nullptr;
699  Ops.push_back(Op);
700  }
701  return SE.getAddExpr(Ops);
702  }
703  return nullptr;
704  }
705 
706  // Check for a multiply operand that we can pull RHS out of.
707  if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
708  if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
710  bool Found = false;
711  for (const SCEV *S : Mul->operands()) {
712  if (!Found)
713  if (const SCEV *Q = getExactSDiv(S, RHS, SE,
714  IgnoreSignificantBits)) {
715  S = Q;
716  Found = true;
717  }
718  Ops.push_back(S);
719  }
720  return Found ? SE.getMulExpr(Ops) : nullptr;
721  }
722  return nullptr;
723  }
724 
725  // Otherwise we don't know.
726  return nullptr;
727 }
728 
729 /// If S involves the addition of a constant integer value, return that integer
730 /// value, and mutate S to point to a new SCEV with that value excluded.
731 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
732  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
733  if (C->getAPInt().getMinSignedBits() <= 64) {
734  S = SE.getConstant(C->getType(), 0);
735  return C->getValue()->getSExtValue();
736  }
737  } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
738  SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
739  int64_t Result = ExtractImmediate(NewOps.front(), SE);
740  if (Result != 0)
741  S = SE.getAddExpr(NewOps);
742  return Result;
743  } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
744  SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
745  int64_t Result = ExtractImmediate(NewOps.front(), SE);
746  if (Result != 0)
747  S = SE.getAddRecExpr(NewOps, AR->getLoop(),
748  // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
750  return Result;
751  }
752  return 0;
753 }
754 
755 /// If S involves the addition of a GlobalValue address, return that symbol, and
756 /// mutate S to point to a new SCEV with that value excluded.
758  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
759  if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
760  S = SE.getConstant(GV->getType(), 0);
761  return GV;
762  }
763  } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
764  SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
765  GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
766  if (Result)
767  S = SE.getAddExpr(NewOps);
768  return Result;
769  } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
770  SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
771  GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
772  if (Result)
773  S = SE.getAddRecExpr(NewOps, AR->getLoop(),
774  // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
776  return Result;
777  }
778  return nullptr;
779 }
780 
781 /// Returns true if the specified instruction is using the specified value as an
782 /// address.
783 static bool isAddressUse(const TargetTransformInfo &TTI,
784  Instruction *Inst, Value *OperandVal) {
785  bool isAddress = isa<LoadInst>(Inst);
786  if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
787  if (SI->getPointerOperand() == OperandVal)
788  isAddress = true;
789  } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
790  // Addressing modes can also be folded into prefetches and a variety
791  // of intrinsics.
792  switch (II->getIntrinsicID()) {
793  case Intrinsic::memset:
794  case Intrinsic::prefetch:
795  if (II->getArgOperand(0) == OperandVal)
796  isAddress = true;
797  break;
798  case Intrinsic::memmove:
799  case Intrinsic::memcpy:
800  if (II->getArgOperand(0) == OperandVal ||
801  II->getArgOperand(1) == OperandVal)
802  isAddress = true;
803  break;
804  default: {
805  MemIntrinsicInfo IntrInfo;
806  if (TTI.getTgtMemIntrinsic(II, IntrInfo)) {
807  if (IntrInfo.PtrVal == OperandVal)
808  isAddress = true;
809  }
810  }
811  }
812  } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
813  if (RMW->getPointerOperand() == OperandVal)
814  isAddress = true;
815  } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
816  if (CmpX->getPointerOperand() == OperandVal)
817  isAddress = true;
818  }
819  return isAddress;
820 }
821 
822 /// Return the type of the memory being accessed.
823 static MemAccessTy getAccessType(const TargetTransformInfo &TTI,
824  Instruction *Inst) {
825  MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace);
826  if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
827  AccessTy.MemTy = SI->getOperand(0)->getType();
828  AccessTy.AddrSpace = SI->getPointerAddressSpace();
829  } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
830  AccessTy.AddrSpace = LI->getPointerAddressSpace();
831  } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
832  AccessTy.AddrSpace = RMW->getPointerAddressSpace();
833  } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
834  AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
835  } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
836  switch (II->getIntrinsicID()) {
837  case Intrinsic::prefetch:
838  AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();
839  break;
840  default: {
841  MemIntrinsicInfo IntrInfo;
842  if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) {
843  AccessTy.AddrSpace
844  = IntrInfo.PtrVal->getType()->getPointerAddressSpace();
845  }
846 
847  break;
848  }
849  }
850  }
851 
852  // All pointers have the same requirements, so canonicalize them to an
853  // arbitrary pointer type to minimize variation.
854  if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
855  AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
856  PTy->getAddressSpace());
857 
858  return AccessTy;
859 }
860 
861 /// Return true if this AddRec is already a phi in its loop.
862 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
863  for (PHINode &PN : AR->getLoop()->getHeader()->phis()) {
864  if (SE.isSCEVable(PN.getType()) &&
865  (SE.getEffectiveSCEVType(PN.getType()) ==
866  SE.getEffectiveSCEVType(AR->getType())) &&
867  SE.getSCEV(&PN) == AR)
868  return true;
869  }
870  return false;
871 }
872 
873 /// Check if expanding this expression is likely to incur significant cost. This
874 /// is tricky because SCEV doesn't track which expressions are actually computed
875 /// by the current IR.
876 ///
877 /// We currently allow expansion of IV increments that involve adds,
878 /// multiplication by constants, and AddRecs from existing phis.
879 ///
880 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
881 /// obvious multiple of the UDivExpr.
882 static bool isHighCostExpansion(const SCEV *S,
883  SmallPtrSetImpl<const SCEV*> &Processed,
884  ScalarEvolution &SE) {
885  // Zero/One operand expressions
886  switch (S->getSCEVType()) {
887  case scUnknown:
888  case scConstant:
889  return false;
890  case scTruncate:
891  return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
892  Processed, SE);
893  case scZeroExtend:
894  return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
895  Processed, SE);
896  case scSignExtend:
897  return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
898  Processed, SE);
899  }
900 
901  if (!Processed.insert(S).second)
902  return false;
903 
904  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
905  for (const SCEV *S : Add->operands()) {
906  if (isHighCostExpansion(S, Processed, SE))
907  return true;
908  }
909  return false;
910  }
911 
912  if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
913  if (Mul->getNumOperands() == 2) {
914  // Multiplication by a constant is ok
915  if (isa<SCEVConstant>(Mul->getOperand(0)))
916  return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
917 
918  // If we have the value of one operand, check if an existing
919  // multiplication already generates this expression.
920  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
921  Value *UVal = U->getValue();
922  for (User *UR : UVal->users()) {
923  // If U is a constant, it may be used by a ConstantExpr.
924  Instruction *UI = dyn_cast<Instruction>(UR);
925  if (UI && UI->getOpcode() == Instruction::Mul &&
926  SE.isSCEVable(UI->getType())) {
927  return SE.getSCEV(UI) == Mul;
928  }
929  }
930  }
931  }
932  }
933 
934  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
935  if (isExistingPhi(AR, SE))
936  return false;
937  }
938 
939  // Fow now, consider any other type of expression (div/mul/min/max) high cost.
940  return true;
941 }
942 
943 /// If any of the instructions in the specified set are trivially dead, delete
944 /// them and see if this makes any of their operands subsequently dead.
945 static bool
947  bool Changed = false;
948 
949  while (!DeadInsts.empty()) {
950  Value *V = DeadInsts.pop_back_val();
951  Instruction *I = dyn_cast_or_null<Instruction>(V);
952 
953  if (!I || !isInstructionTriviallyDead(I))
954  continue;
955 
956  for (Use &O : I->operands())
957  if (Instruction *U = dyn_cast<Instruction>(O)) {
958  O = nullptr;
959  if (U->use_empty())
960  DeadInsts.emplace_back(U);
961  }
962 
963  I->eraseFromParent();
964  Changed = true;
965  }
966 
967  return Changed;
968 }
969 
970 namespace {
971 
972 class LSRUse;
973 
974 } // end anonymous namespace
975 
976 /// \brief Check if the addressing mode defined by \p F is completely
977 /// folded in \p LU at isel time.
978 /// This includes address-mode folding and special icmp tricks.
979 /// This function returns true if \p LU can accommodate what \p F
980 /// defines and up to 1 base + 1 scaled + offset.
981 /// In other words, if \p F has several base registers, this function may
982 /// still return true. Therefore, users still need to account for
983 /// additional base registers and/or unfolded offsets to derive an
984 /// accurate cost model.
985 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
986  const LSRUse &LU, const Formula &F);
987 
988 // Get the cost of the scaling factor used in F for LU.
989 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
990  const LSRUse &LU, const Formula &F,
991  const Loop &L);
992 
993 namespace {
994 
995 /// This class is used to measure and compare candidate formulae.
996 class Cost {
998 
999 public:
1000  Cost() {
1001  C.Insns = 0;
1002  C.NumRegs = 0;
1003  C.AddRecCost = 0;
1004  C.NumIVMuls = 0;
1005  C.NumBaseAdds = 0;
1006  C.ImmCost = 0;
1007  C.SetupCost = 0;
1008  C.ScaleCost = 0;
1009  }
1010 
1011  bool isLess(Cost &Other, const TargetTransformInfo &TTI);
1012 
1013  void Lose();
1014 
1015 #ifndef NDEBUG
1016  // Once any of the metrics loses, they must all remain losers.
1017  bool isValid() {
1018  return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds
1019  | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)
1020  || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds
1021  & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);
1022  }
1023 #endif
1024 
1025  bool isLoser() {
1026  assert(isValid() && "invalid cost");
1027  return C.NumRegs == ~0u;
1028  }
1029 
1030  void RateFormula(const TargetTransformInfo &TTI,
1031  const Formula &F,
1033  const DenseSet<const SCEV *> &VisitedRegs,
1034  const Loop *L,
1035  ScalarEvolution &SE, DominatorTree &DT,
1036  const LSRUse &LU,
1037  SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
1038 
1039  void print(raw_ostream &OS) const;
1040  void dump() const;
1041 
1042 private:
1043  void RateRegister(const SCEV *Reg,
1045  const Loop *L,
1046  ScalarEvolution &SE, DominatorTree &DT,
1047  const TargetTransformInfo &TTI);
1048  void RatePrimaryRegister(const SCEV *Reg,
1050  const Loop *L,
1051  ScalarEvolution &SE, DominatorTree &DT,
1052  SmallPtrSetImpl<const SCEV *> *LoserRegs,
1053  const TargetTransformInfo &TTI);
1054 };
1055 
1056 /// An operand value in an instruction which is to be replaced with some
1057 /// equivalent, possibly strength-reduced, replacement.
1058 struct LSRFixup {
1059  /// The instruction which will be updated.
1060  Instruction *UserInst = nullptr;
1061 
1062  /// The operand of the instruction which will be replaced. The operand may be
1063  /// used more than once; every instance will be replaced.
1064  Value *OperandValToReplace = nullptr;
1065 
1066  /// If this user is to use the post-incremented value of an induction
1067  /// variable, this set is non-empty and holds the loops associated with the
1068  /// induction variable.
1069  PostIncLoopSet PostIncLoops;
1070 
1071  /// A constant offset to be added to the LSRUse expression. This allows
1072  /// multiple fixups to share the same LSRUse with different offsets, for
1073  /// example in an unrolled loop.
1074  int64_t Offset = 0;
1075 
1076  LSRFixup() = default;
1077 
1078  bool isUseFullyOutsideLoop(const Loop *L) const;
1079 
1080  void print(raw_ostream &OS) const;
1081  void dump() const;
1082 };
1083 
1084 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
1085 /// SmallVectors of const SCEV*.
1086 struct UniquifierDenseMapInfo {
1087  static SmallVector<const SCEV *, 4> getEmptyKey() {
1089  V.push_back(reinterpret_cast<const SCEV *>(-1));
1090  return V;
1091  }
1092 
1093  static SmallVector<const SCEV *, 4> getTombstoneKey() {
1095  V.push_back(reinterpret_cast<const SCEV *>(-2));
1096  return V;
1097  }
1098 
1099  static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
1100  return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1101  }
1102 
1103  static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1104  const SmallVector<const SCEV *, 4> &RHS) {
1105  return LHS == RHS;
1106  }
1107 };
1108 
1109 /// This class holds the state that LSR keeps for each use in IVUsers, as well
1110 /// as uses invented by LSR itself. It includes information about what kinds of
1111 /// things can be folded into the user, information about the user itself, and
1112 /// information about how the use may be satisfied. TODO: Represent multiple
1113 /// users of the same expression in common?
1114 class LSRUse {
1115  DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1116 
1117 public:
1118  /// An enum for a kind of use, indicating what types of scaled and immediate
1119  /// operands it might support.
1120  enum KindType {
1121  Basic, ///< A normal use, with no folding.
1122  Special, ///< A special case of basic, allowing -1 scales.
1123  Address, ///< An address use; folding according to TargetLowering
1124  ICmpZero ///< An equality icmp with both operands folded into one.
1125  // TODO: Add a generic icmp too?
1126  };
1127 
1128  using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>;
1129 
1130  KindType Kind;
1131  MemAccessTy AccessTy;
1132 
1133  /// The list of operands which are to be replaced.
1135 
1136  /// Keep track of the min and max offsets of the fixups.
1137  int64_t MinOffset = std::numeric_limits<int64_t>::max();
1138  int64_t MaxOffset = std::numeric_limits<int64_t>::min();
1139 
1140  /// This records whether all of the fixups using this LSRUse are outside of
1141  /// the loop, in which case some special-case heuristics may be used.
1142  bool AllFixupsOutsideLoop = true;
1143 
1144  /// RigidFormula is set to true to guarantee that this use will be associated
1145  /// with a single formula--the one that initially matched. Some SCEV
1146  /// expressions cannot be expanded. This allows LSR to consider the registers
1147  /// used by those expressions without the need to expand them later after
1148  /// changing the formula.
1149  bool RigidFormula = false;
1150 
1151  /// This records the widest use type for any fixup using this
1152  /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
1153  /// fixup widths to be equivalent, because the narrower one may be relying on
1154  /// the implicit truncation to truncate away bogus bits.
1155  Type *WidestFixupType = nullptr;
1156 
1157  /// A list of ways to build a value that can satisfy this user. After the
1158  /// list is populated, one of these is selected heuristically and used to
1159  /// formulate a replacement for OperandValToReplace in UserInst.
1160  SmallVector<Formula, 12> Formulae;
1161 
1162  /// The set of register candidates used by all formulae in this LSRUse.
1164 
1165  LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {}
1166 
1167  LSRFixup &getNewFixup() {
1168  Fixups.push_back(LSRFixup());
1169  return Fixups.back();
1170  }
1171 
1172  void pushFixup(LSRFixup &f) {
1173  Fixups.push_back(f);
1174  if (f.Offset > MaxOffset)
1175  MaxOffset = f.Offset;
1176  if (f.Offset < MinOffset)
1177  MinOffset = f.Offset;
1178  }
1179 
1180  bool HasFormulaWithSameRegs(const Formula &F) const;
1181  float getNotSelectedProbability(const SCEV *Reg) const;
1182  bool InsertFormula(const Formula &F, const Loop &L);
1183  void DeleteFormula(Formula &F);
1184  void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1185 
1186  void print(raw_ostream &OS) const;
1187  void dump() const;
1188 };
1189 
1190 } // end anonymous namespace
1191 
1192 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1193  LSRUse::KindType Kind, MemAccessTy AccessTy,
1194  GlobalValue *BaseGV, int64_t BaseOffset,
1195  bool HasBaseReg, int64_t Scale,
1196  Instruction *Fixup = nullptr);
1197 
1198 /// Tally up interesting quantities from the given register.
1199 void Cost::RateRegister(const SCEV *Reg,
1201  const Loop *L,
1202  ScalarEvolution &SE, DominatorTree &DT,
1203  const TargetTransformInfo &TTI) {
1204  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
1205  // If this is an addrec for another loop, it should be an invariant
1206  // with respect to L since L is the innermost loop (at least
1207  // for now LSR only handles innermost loops).
1208  if (AR->getLoop() != L) {
1209  // If the AddRec exists, consider it's register free and leave it alone.
1210  if (isExistingPhi(AR, SE))
1211  return;
1212 
1213  // It is bad to allow LSR for current loop to add induction variables
1214  // for its sibling loops.
1215  if (!AR->getLoop()->contains(L)) {
1216  Lose();
1217  return;
1218  }
1219 
1220  // Otherwise, it will be an invariant with respect to Loop L.
1221  ++C.NumRegs;
1222  return;
1223  }
1224 
1225  unsigned LoopCost = 1;
1226  if (TTI.shouldFavorPostInc()) {
1227  const SCEV *LoopStep = AR->getStepRecurrence(SE);
1228  if (isa<SCEVConstant>(LoopStep)) {
1229  // Check if a post-indexed load/store can be used.
1230  if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) ||
1231  TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) {
1232  const SCEV *LoopStart = AR->getStart();
1233  if (!isa<SCEVConstant>(LoopStart) &&
1234  SE.isLoopInvariant(LoopStart, L))
1235  LoopCost = 0;
1236  }
1237  }
1238  }
1239  C.AddRecCost += LoopCost;
1240 
1241  // Add the step value register, if it needs one.
1242  // TODO: The non-affine case isn't precisely modeled here.
1243  if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1244  if (!Regs.count(AR->getOperand(1))) {
1245  RateRegister(AR->getOperand(1), Regs, L, SE, DT, TTI);
1246  if (isLoser())
1247  return;
1248  }
1249  }
1250  }
1251  ++C.NumRegs;
1252 
1253  // Rough heuristic; favor registers which don't require extra setup
1254  // instructions in the preheader.
1255  if (!isa<SCEVUnknown>(Reg) &&
1256  !isa<SCEVConstant>(Reg) &&
1257  !(isa<SCEVAddRecExpr>(Reg) &&
1258  (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
1259  isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
1260  ++C.SetupCost;
1261 
1262  C.NumIVMuls += isa<SCEVMulExpr>(Reg) &&
1263  SE.hasComputableLoopEvolution(Reg, L);
1264 }
1265 
1266 /// Record this register in the set. If we haven't seen it before, rate
1267 /// it. Optional LoserRegs provides a way to declare any formula that refers to
1268 /// one of those regs an instant loser.
1269 void Cost::RatePrimaryRegister(const SCEV *Reg,
1271  const Loop *L,
1272  ScalarEvolution &SE, DominatorTree &DT,
1273  SmallPtrSetImpl<const SCEV *> *LoserRegs,
1274  const TargetTransformInfo &TTI) {
1275  if (LoserRegs && LoserRegs->count(Reg)) {
1276  Lose();
1277  return;
1278  }
1279  if (Regs.insert(Reg).second) {
1280  RateRegister(Reg, Regs, L, SE, DT, TTI);
1281  if (LoserRegs && isLoser())
1282  LoserRegs->insert(Reg);
1283  }
1284 }
1285 
1286 void Cost::RateFormula(const TargetTransformInfo &TTI,
1287  const Formula &F,
1289  const DenseSet<const SCEV *> &VisitedRegs,
1290  const Loop *L,
1291  ScalarEvolution &SE, DominatorTree &DT,
1292  const LSRUse &LU,
1293  SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1294  assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");
1295  // Tally up the registers.
1296  unsigned PrevAddRecCost = C.AddRecCost;
1297  unsigned PrevNumRegs = C.NumRegs;
1298  unsigned PrevNumBaseAdds = C.NumBaseAdds;
1299  if (const SCEV *ScaledReg = F.ScaledReg) {
1300  if (VisitedRegs.count(ScaledReg)) {
1301  Lose();
1302  return;
1303  }
1304  RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs, TTI);
1305  if (isLoser())
1306  return;
1307  }
1308  for (const SCEV *BaseReg : F.BaseRegs) {
1309  if (VisitedRegs.count(BaseReg)) {
1310  Lose();
1311  return;
1312  }
1313  RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs, TTI);
1314  if (isLoser())
1315  return;
1316  }
1317 
1318  // Determine how many (unfolded) adds we'll need inside the loop.
1319  size_t NumBaseParts = F.getNumRegs();
1320  if (NumBaseParts > 1)
1321  // Do not count the base and a possible second register if the target
1322  // allows to fold 2 registers.
1323  C.NumBaseAdds +=
1324  NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
1325  C.NumBaseAdds += (F.UnfoldedOffset != 0);
1326 
1327  // Accumulate non-free scaling amounts.
1328  C.ScaleCost += getScalingFactorCost(TTI, LU, F, *L);
1329 
1330  // Tally up the non-zero immediates.
1331  for (const LSRFixup &Fixup : LU.Fixups) {
1332  int64_t O = Fixup.Offset;
1333  int64_t Offset = (uint64_t)O + F.BaseOffset;
1334  if (F.BaseGV)
1335  C.ImmCost += 64; // Handle symbolic values conservatively.
1336  // TODO: This should probably be the pointer size.
1337  else if (Offset != 0)
1338  C.ImmCost += APInt(64, Offset, true).getMinSignedBits();
1339 
1340  // Check with target if this offset with this instruction is
1341  // specifically not supported.
1342  if (LU.Kind == LSRUse::Address && Offset != 0 &&
1343  !isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1344  Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))
1345  C.NumBaseAdds++;
1346  }
1347 
1348  // If we don't count instruction cost exit here.
1349  if (!InsnsCost) {
1350  assert(isValid() && "invalid cost");
1351  return;
1352  }
1353 
1354  // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
1355  // additional instruction (at least fill).
1356  unsigned TTIRegNum = TTI.getNumberOfRegisters(false) - 1;
1357  if (C.NumRegs > TTIRegNum) {
1358  // Cost already exceeded TTIRegNum, then only newly added register can add
1359  // new instructions.
1360  if (PrevNumRegs > TTIRegNum)
1361  C.Insns += (C.NumRegs - PrevNumRegs);
1362  else
1363  C.Insns += (C.NumRegs - TTIRegNum);
1364  }
1365 
1366  // If ICmpZero formula ends with not 0, it could not be replaced by
1367  // just add or sub. We'll need to compare final result of AddRec.
1368  // That means we'll need an additional instruction. But if the target can
1369  // macro-fuse a compare with a branch, don't count this extra instruction.
1370  // For -10 + {0, +, 1}:
1371  // i = i + 1;
1372  // cmp i, 10
1373  //
1374  // For {-10, +, 1}:
1375  // i = i + 1;
1376  if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() && !TTI.canMacroFuseCmp())
1377  C.Insns++;
1378  // Each new AddRec adds 1 instruction to calculation.
1379  C.Insns += (C.AddRecCost - PrevAddRecCost);
1380 
1381  // BaseAdds adds instructions for unfolded registers.
1382  if (LU.Kind != LSRUse::ICmpZero)
1383  C.Insns += C.NumBaseAdds - PrevNumBaseAdds;
1384  assert(isValid() && "invalid cost");
1385 }
1386 
1387 /// Set this cost to a losing value.
1388 void Cost::Lose() {
1391  C.AddRecCost = std::numeric_limits<unsigned>::max();
1392  C.NumIVMuls = std::numeric_limits<unsigned>::max();
1393  C.NumBaseAdds = std::numeric_limits<unsigned>::max();
1395  C.SetupCost = std::numeric_limits<unsigned>::max();
1396  C.ScaleCost = std::numeric_limits<unsigned>::max();
1397 }
1398 
1399 /// Choose the lower cost.
1400 bool Cost::isLess(Cost &Other, const TargetTransformInfo &TTI) {
1401  if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&
1402  C.Insns != Other.C.Insns)
1403  return C.Insns < Other.C.Insns;
1404  return TTI.isLSRCostLess(C, Other.C);
1405 }
1406 
1407 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1408 void Cost::print(raw_ostream &OS) const {
1409  if (InsnsCost)
1410  OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");
1411  OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");
1412  if (C.AddRecCost != 0)
1413  OS << ", with addrec cost " << C.AddRecCost;
1414  if (C.NumIVMuls != 0)
1415  OS << ", plus " << C.NumIVMuls << " IV mul"
1416  << (C.NumIVMuls == 1 ? "" : "s");
1417  if (C.NumBaseAdds != 0)
1418  OS << ", plus " << C.NumBaseAdds << " base add"
1419  << (C.NumBaseAdds == 1 ? "" : "s");
1420  if (C.ScaleCost != 0)
1421  OS << ", plus " << C.ScaleCost << " scale cost";
1422  if (C.ImmCost != 0)
1423  OS << ", plus " << C.ImmCost << " imm cost";
1424  if (C.SetupCost != 0)
1425  OS << ", plus " << C.SetupCost << " setup cost";
1426 }
1427 
1428 LLVM_DUMP_METHOD void Cost::dump() const {
1429  print(errs()); errs() << '\n';
1430 }
1431 #endif
1432 
1433 /// Test whether this fixup always uses its value outside of the given loop.
1434 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1435  // PHI nodes use their value in their incoming blocks.
1436  if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1437  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1438  if (PN->getIncomingValue(i) == OperandValToReplace &&
1439  L->contains(PN->getIncomingBlock(i)))
1440  return false;
1441  return true;
1442  }
1443 
1444  return !L->contains(UserInst);
1445 }
1446 
1447 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1448 void LSRFixup::print(raw_ostream &OS) const {
1449  OS << "UserInst=";
1450  // Store is common and interesting enough to be worth special-casing.
1451  if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1452  OS << "store ";
1453  Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
1454  } else if (UserInst->getType()->isVoidTy())
1455  OS << UserInst->getOpcodeName();
1456  else
1457  UserInst->printAsOperand(OS, /*PrintType=*/false);
1458 
1459  OS << ", OperandValToReplace=";
1460  OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
1461 
1462  for (const Loop *PIL : PostIncLoops) {
1463  OS << ", PostIncLoop=";
1464  PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
1465  }
1466 
1467  if (Offset != 0)
1468  OS << ", Offset=" << Offset;
1469 }
1470 
1471 LLVM_DUMP_METHOD void LSRFixup::dump() const {
1472  print(errs()); errs() << '\n';
1473 }
1474 #endif
1475 
1476 /// Test whether this use as a formula which has the same registers as the given
1477 /// formula.
1478 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1479  SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1480  if (F.ScaledReg) Key.push_back(F.ScaledReg);
1481  // Unstable sort by host order ok, because this is only used for uniquifying.
1482  llvm::sort(Key.begin(), Key.end());
1483  return Uniquifier.count(Key);
1484 }
1485 
1486 /// The function returns a probability of selecting formula without Reg.
1487 float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {
1488  unsigned FNum = 0;
1489  for (const Formula &F : Formulae)
1490  if (F.referencesReg(Reg))
1491  FNum++;
1492  return ((float)(Formulae.size() - FNum)) / Formulae.size();
1493 }
1494 
1495 /// If the given formula has not yet been inserted, add it to the list, and
1496 /// return true. Return false otherwise. The formula must be in canonical form.
1497 bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {
1498  assert(F.isCanonical(L) && "Invalid canonical representation");
1499 
1500  if (!Formulae.empty() && RigidFormula)
1501  return false;
1502 
1503  SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1504  if (F.ScaledReg) Key.push_back(F.ScaledReg);
1505  // Unstable sort by host order ok, because this is only used for uniquifying.
1506  llvm::sort(Key.begin(), Key.end());
1507 
1508  if (!Uniquifier.insert(Key).second)
1509  return false;
1510 
1511  // Using a register to hold the value of 0 is not profitable.
1512  assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1513  "Zero allocated in a scaled register!");
1514 #ifndef NDEBUG
1515  for (const SCEV *BaseReg : F.BaseRegs)
1516  assert(!BaseReg->isZero() && "Zero allocated in a base register!");
1517 #endif
1518 
1519  // Add the formula to the list.
1520  Formulae.push_back(F);
1521 
1522  // Record registers now being used by this use.
1523  Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1524  if (F.ScaledReg)
1525  Regs.insert(F.ScaledReg);
1526 
1527  return true;
1528 }
1529 
1530 /// Remove the given formula from this use's list.
1531 void LSRUse::DeleteFormula(Formula &F) {
1532  if (&F != &Formulae.back())
1533  std::swap(F, Formulae.back());
1534  Formulae.pop_back();
1535 }
1536 
1537 /// Recompute the Regs field, and update RegUses.
1538 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1539  // Now that we've filtered out some formulae, recompute the Regs set.
1540  SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
1541  Regs.clear();
1542  for (const Formula &F : Formulae) {
1543  if (F.ScaledReg) Regs.insert(F.ScaledReg);
1544  Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1545  }
1546 
1547  // Update the RegTracker.
1548  for (const SCEV *S : OldRegs)
1549  if (!Regs.count(S))
1550  RegUses.dropRegister(S, LUIdx);
1551 }
1552 
1553 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1554 void LSRUse::print(raw_ostream &OS) const {
1555  OS << "LSR Use: Kind=";
1556  switch (Kind) {
1557  case Basic: OS << "Basic"; break;
1558  case Special: OS << "Special"; break;
1559  case ICmpZero: OS << "ICmpZero"; break;
1560  case Address:
1561  OS << "Address of ";
1562  if (AccessTy.MemTy->isPointerTy())
1563  OS << "pointer"; // the full pointer type could be really verbose
1564  else {
1565  OS << *AccessTy.MemTy;
1566  }
1567 
1568  OS << " in addrspace(" << AccessTy.AddrSpace << ')';
1569  }
1570 
1571  OS << ", Offsets={";
1572  bool NeedComma = false;
1573  for (const LSRFixup &Fixup : Fixups) {
1574  if (NeedComma) OS << ',';
1575  OS << Fixup.Offset;
1576  NeedComma = true;
1577  }
1578  OS << '}';
1579 
1580  if (AllFixupsOutsideLoop)
1581  OS << ", all-fixups-outside-loop";
1582 
1583  if (WidestFixupType)
1584  OS << ", widest fixup type: " << *WidestFixupType;
1585 }
1586 
1587 LLVM_DUMP_METHOD void LSRUse::dump() const {
1588  print(errs()); errs() << '\n';
1589 }
1590 #endif
1591 
1593  LSRUse::KindType Kind, MemAccessTy AccessTy,
1594  GlobalValue *BaseGV, int64_t BaseOffset,
1595  bool HasBaseReg, int64_t Scale,
1596  Instruction *Fixup/*= nullptr*/) {
1597  switch (Kind) {
1598  case LSRUse::Address:
1599  return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset,
1600  HasBaseReg, Scale, AccessTy.AddrSpace, Fixup);
1601 
1602  case LSRUse::ICmpZero:
1603  // There's not even a target hook for querying whether it would be legal to
1604  // fold a GV into an ICmp.
1605  if (BaseGV)
1606  return false;
1607 
1608  // ICmp only has two operands; don't allow more than two non-trivial parts.
1609  if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1610  return false;
1611 
1612  // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1613  // putting the scaled register in the other operand of the icmp.
1614  if (Scale != 0 && Scale != -1)
1615  return false;
1616 
1617  // If we have low-level target information, ask the target if it can fold an
1618  // integer immediate on an icmp.
1619  if (BaseOffset != 0) {
1620  // We have one of:
1621  // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1622  // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1623  // Offs is the ICmp immediate.
1624  if (Scale == 0)
1625  // The cast does the right thing with
1626  // std::numeric_limits<int64_t>::min().
1627  BaseOffset = -(uint64_t)BaseOffset;
1628  return TTI.isLegalICmpImmediate(BaseOffset);
1629  }
1630 
1631  // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1632  return true;
1633 
1634  case LSRUse::Basic:
1635  // Only handle single-register values.
1636  return !BaseGV && Scale == 0 && BaseOffset == 0;
1637 
1638  case LSRUse::Special:
1639  // Special case Basic to handle -1 scales.
1640  return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1641  }
1642 
1643  llvm_unreachable("Invalid LSRUse Kind!");
1644 }
1645 
1647  int64_t MinOffset, int64_t MaxOffset,
1648  LSRUse::KindType Kind, MemAccessTy AccessTy,
1649  GlobalValue *BaseGV, int64_t BaseOffset,
1650  bool HasBaseReg, int64_t Scale) {
1651  // Check for overflow.
1652  if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1653  (MinOffset > 0))
1654  return false;
1655  MinOffset = (uint64_t)BaseOffset + MinOffset;
1656  if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1657  (MaxOffset > 0))
1658  return false;
1659  MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1660 
1661  return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1662  HasBaseReg, Scale) &&
1663  isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1664  HasBaseReg, Scale);
1665 }
1666 
1668  int64_t MinOffset, int64_t MaxOffset,
1669  LSRUse::KindType Kind, MemAccessTy AccessTy,
1670  const Formula &F, const Loop &L) {
1671  // For the purpose of isAMCompletelyFolded either having a canonical formula
1672  // or a scale not equal to zero is correct.
1673  // Problems may arise from non canonical formulae having a scale == 0.
1674  // Strictly speaking it would best to just rely on canonical formulae.
1675  // However, when we generate the scaled formulae, we first check that the
1676  // scaling factor is profitable before computing the actual ScaledReg for
1677  // compile time sake.
1678  assert((F.isCanonical(L) || F.Scale != 0));
1679  return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1680  F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1681 }
1682 
1683 /// Test whether we know how to expand the current formula.
1684 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1685  int64_t MaxOffset, LSRUse::KindType Kind,
1686  MemAccessTy AccessTy, GlobalValue *BaseGV,
1687  int64_t BaseOffset, bool HasBaseReg, int64_t Scale) {
1688  // We know how to expand completely foldable formulae.
1689  return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1690  BaseOffset, HasBaseReg, Scale) ||
1691  // Or formulae that use a base register produced by a sum of base
1692  // registers.
1693  (Scale == 1 &&
1694  isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1695  BaseGV, BaseOffset, true, 0));
1696 }
1697 
1698 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1699  int64_t MaxOffset, LSRUse::KindType Kind,
1700  MemAccessTy AccessTy, const Formula &F) {
1701  return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1702  F.BaseOffset, F.HasBaseReg, F.Scale);
1703 }
1704 
1706  const LSRUse &LU, const Formula &F) {
1707  // Target may want to look at the user instructions.
1708  if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) {
1709  for (const LSRFixup &Fixup : LU.Fixups)
1710  if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1711  (F.BaseOffset + Fixup.Offset), F.HasBaseReg,
1712  F.Scale, Fixup.UserInst))
1713  return false;
1714  return true;
1715  }
1716 
1717  return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1718  LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1719  F.Scale);
1720 }
1721 
1722 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1723  const LSRUse &LU, const Formula &F,
1724  const Loop &L) {
1725  if (!F.Scale)
1726  return 0;
1727 
1728  // If the use is not completely folded in that instruction, we will have to
1729  // pay an extra cost only for scale != 1.
1730  if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1731  LU.AccessTy, F, L))
1732  return F.Scale != 1;
1733 
1734  switch (LU.Kind) {
1735  case LSRUse::Address: {
1736  // Check the scaling factor cost with both the min and max offsets.
1737  int ScaleCostMinOffset = TTI.getScalingFactorCost(
1738  LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1739  F.Scale, LU.AccessTy.AddrSpace);
1740  int ScaleCostMaxOffset = TTI.getScalingFactorCost(
1741  LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1742  F.Scale, LU.AccessTy.AddrSpace);
1743 
1744  assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1745  "Legal addressing mode has an illegal cost!");
1746  return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1747  }
1748  case LSRUse::ICmpZero:
1749  case LSRUse::Basic:
1750  case LSRUse::Special:
1751  // The use is completely folded, i.e., everything is folded into the
1752  // instruction.
1753  return 0;
1754  }
1755 
1756  llvm_unreachable("Invalid LSRUse Kind!");
1757 }
1758 
1759 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1760  LSRUse::KindType Kind, MemAccessTy AccessTy,
1761  GlobalValue *BaseGV, int64_t BaseOffset,
1762  bool HasBaseReg) {
1763  // Fast-path: zero is always foldable.
1764  if (BaseOffset == 0 && !BaseGV) return true;
1765 
1766  // Conservatively, create an address with an immediate and a
1767  // base and a scale.
1768  int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1769 
1770  // Canonicalize a scale of 1 to a base register if the formula doesn't
1771  // already have a base register.
1772  if (!HasBaseReg && Scale == 1) {
1773  Scale = 0;
1774  HasBaseReg = true;
1775  }
1776 
1777  return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1778  HasBaseReg, Scale);
1779 }
1780 
1781 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1782  ScalarEvolution &SE, int64_t MinOffset,
1783  int64_t MaxOffset, LSRUse::KindType Kind,
1784  MemAccessTy AccessTy, const SCEV *S,
1785  bool HasBaseReg) {
1786  // Fast-path: zero is always foldable.
1787  if (S->isZero()) return true;
1788 
1789  // Conservatively, create an address with an immediate and a
1790  // base and a scale.
1791  int64_t BaseOffset = ExtractImmediate(S, SE);
1792  GlobalValue *BaseGV = ExtractSymbol(S, SE);
1793 
1794  // If there's anything else involved, it's not foldable.
1795  if (!S->isZero()) return false;
1796 
1797  // Fast-path: zero is always foldable.
1798  if (BaseOffset == 0 && !BaseGV) return true;
1799 
1800  // Conservatively, create an address with an immediate and a
1801  // base and a scale.
1802  int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1803 
1804  return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1805  BaseOffset, HasBaseReg, Scale);
1806 }
1807 
1808 namespace {
1809 
1810 /// An individual increment in a Chain of IV increments. Relate an IV user to
1811 /// an expression that computes the IV it uses from the IV used by the previous
1812 /// link in the Chain.
1813 ///
1814 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1815 /// original IVOperand. The head of the chain's IVOperand is only valid during
1816 /// chain collection, before LSR replaces IV users. During chain generation,
1817 /// IncExpr can be used to find the new IVOperand that computes the same
1818 /// expression.
1819 struct IVInc {
1820  Instruction *UserInst;
1821  Value* IVOperand;
1822  const SCEV *IncExpr;
1823 
1824  IVInc(Instruction *U, Value *O, const SCEV *E)
1825  : UserInst(U), IVOperand(O), IncExpr(E) {}
1826 };
1827 
1828 // The list of IV increments in program order. We typically add the head of a
1829 // chain without finding subsequent links.
1830 struct IVChain {
1831  SmallVector<IVInc, 1> Incs;
1832  const SCEV *ExprBase = nullptr;
1833 
1834  IVChain() = default;
1835  IVChain(const IVInc &Head, const SCEV *Base)
1836  : Incs(1, Head), ExprBase(Base) {}
1837 
1838  using const_iterator = SmallVectorImpl<IVInc>::const_iterator;
1839 
1840  // Return the first increment in the chain.
1841  const_iterator begin() const {
1842  assert(!Incs.empty());
1843  return std::next(Incs.begin());
1844  }
1845  const_iterator end() const {
1846  return Incs.end();
1847  }
1848 
1849  // Returns true if this chain contains any increments.
1850  bool hasIncs() const { return Incs.size() >= 2; }
1851 
1852  // Add an IVInc to the end of this chain.
1853  void add(const IVInc &X) { Incs.push_back(X); }
1854 
1855  // Returns the last UserInst in the chain.
1856  Instruction *tailUserInst() const { return Incs.back().UserInst; }
1857 
1858  // Returns true if IncExpr can be profitably added to this chain.
1859  bool isProfitableIncrement(const SCEV *OperExpr,
1860  const SCEV *IncExpr,
1861  ScalarEvolution&);
1862 };
1863 
1864 /// Helper for CollectChains to track multiple IV increment uses. Distinguish
1865 /// between FarUsers that definitely cross IV increments and NearUsers that may
1866 /// be used between IV increments.
1867 struct ChainUsers {
1869  SmallPtrSet<Instruction*, 4> NearUsers;
1870 };
1871 
1872 /// This class holds state for the main loop strength reduction logic.
1873 class LSRInstance {
1874  IVUsers &IU;
1875  ScalarEvolution &SE;
1876  DominatorTree &DT;
1877  LoopInfo &LI;
1878  const TargetTransformInfo &TTI;
1879  Loop *const L;
1880  bool Changed = false;
1881 
1882  /// This is the insert position that the current loop's induction variable
1883  /// increment should be placed. In simple loops, this is the latch block's
1884  /// terminator. But in more complicated cases, this is a position which will
1885  /// dominate all the in-loop post-increment users.
1886  Instruction *IVIncInsertPos = nullptr;
1887 
1888  /// Interesting factors between use strides.
1889  ///
1890  /// We explicitly use a SetVector which contains a SmallSet, instead of the
1891  /// default, a SmallDenseSet, because we need to use the full range of
1892  /// int64_ts, and there's currently no good way of doing that with
1893  /// SmallDenseSet.
1895 
1896  /// Interesting use types, to facilitate truncation reuse.
1898 
1899  /// The list of interesting uses.
1901 
1902  /// Track which uses use which register candidates.
1903  RegUseTracker RegUses;
1904 
1905  // Limit the number of chains to avoid quadratic behavior. We don't expect to
1906  // have more than a few IV increment chains in a loop. Missing a Chain falls
1907  // back to normal LSR behavior for those uses.
1908  static const unsigned MaxChains = 8;
1909 
1910  /// IV users can form a chain of IV increments.
1912 
1913  /// IV users that belong to profitable IVChains.
1915 
1916  void OptimizeShadowIV();
1917  bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1918  ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1919  void OptimizeLoopTermCond();
1920 
1921  void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1922  SmallVectorImpl<ChainUsers> &ChainUsersVec);
1923  void FinalizeChain(IVChain &Chain);
1924  void CollectChains();
1925  void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1926  SmallVectorImpl<WeakTrackingVH> &DeadInsts);
1927 
1928  void CollectInterestingTypesAndFactors();
1929  void CollectFixupsAndInitialFormulae();
1930 
1931  // Support for sharing of LSRUses between LSRFixups.
1933  UseMapTy UseMap;
1934 
1935  bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1936  LSRUse::KindType Kind, MemAccessTy AccessTy);
1937 
1938  std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
1939  MemAccessTy AccessTy);
1940 
1941  void DeleteUse(LSRUse &LU, size_t LUIdx);
1942 
1943  LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1944 
1945  void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1946  void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1947  void CountRegisters(const Formula &F, size_t LUIdx);
1948  bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1949 
1950  void CollectLoopInvariantFixupsAndFormulae();
1951 
1952  void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1953  unsigned Depth = 0);
1954 
1955  void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1956  const Formula &Base, unsigned Depth,
1957  size_t Idx, bool IsScaledReg = false);
1958  void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1959  void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1960  const Formula &Base, size_t Idx,
1961  bool IsScaledReg = false);
1962  void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1963  void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1964  const Formula &Base,
1965  const SmallVectorImpl<int64_t> &Worklist,
1966  size_t Idx, bool IsScaledReg = false);
1967  void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1968  void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1969  void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1970  void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1971  void GenerateCrossUseConstantOffsets();
1972  void GenerateAllReuseFormulae();
1973 
1974  void FilterOutUndesirableDedicatedRegisters();
1975 
1976  size_t EstimateSearchSpaceComplexity() const;
1977  void NarrowSearchSpaceByDetectingSupersets();
1978  void NarrowSearchSpaceByCollapsingUnrolledCode();
1979  void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
1980  void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
1981  void NarrowSearchSpaceByDeletingCostlyFormulas();
1982  void NarrowSearchSpaceByPickingWinnerRegs();
1983  void NarrowSearchSpaceUsingHeuristics();
1984 
1985  void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1986  Cost &SolutionCost,
1988  const Cost &CurCost,
1989  const SmallPtrSet<const SCEV *, 16> &CurRegs,
1990  DenseSet<const SCEV *> &VisitedRegs) const;
1991  void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1992 
1994  HoistInsertPosition(BasicBlock::iterator IP,
1995  const SmallVectorImpl<Instruction *> &Inputs) const;
1997  AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1998  const LSRFixup &LF,
1999  const LSRUse &LU,
2000  SCEVExpander &Rewriter) const;
2001 
2002  Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2003  BasicBlock::iterator IP, SCEVExpander &Rewriter,
2004  SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2005  void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
2006  const Formula &F, SCEVExpander &Rewriter,
2007  SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2008  void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2009  SCEVExpander &Rewriter,
2010  SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2011  void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
2012 
2013 public:
2014  LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
2015  LoopInfo &LI, const TargetTransformInfo &TTI);
2016 
2017  bool getChanged() const { return Changed; }
2018 
2019  void print_factors_and_types(raw_ostream &OS) const;
2020  void print_fixups(raw_ostream &OS) const;
2021  void print_uses(raw_ostream &OS) const;
2022  void print(raw_ostream &OS) const;
2023  void dump() const;
2024 };
2025 
2026 } // end anonymous namespace
2027 
2028 /// If IV is used in a int-to-float cast inside the loop then try to eliminate
2029 /// the cast operation.
2030 void LSRInstance::OptimizeShadowIV() {
2031  const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2032  if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2033  return;
2034 
2035  for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
2036  UI != E; /* empty */) {
2037  IVUsers::const_iterator CandidateUI = UI;
2038  ++UI;
2039  Instruction *ShadowUse = CandidateUI->getUser();
2040  Type *DestTy = nullptr;
2041  bool IsSigned = false;
2042 
2043  /* If shadow use is a int->float cast then insert a second IV
2044  to eliminate this cast.
2045 
2046  for (unsigned i = 0; i < n; ++i)
2047  foo((double)i);
2048 
2049  is transformed into
2050 
2051  double d = 0.0;
2052  for (unsigned i = 0; i < n; ++i, ++d)
2053  foo(d);
2054  */
2055  if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
2056  IsSigned = false;
2057  DestTy = UCast->getDestTy();
2058  }
2059  else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
2060  IsSigned = true;
2061  DestTy = SCast->getDestTy();
2062  }
2063  if (!DestTy) continue;
2064 
2065  // If target does not support DestTy natively then do not apply
2066  // this transformation.
2067  if (!TTI.isTypeLegal(DestTy)) continue;
2068 
2069  PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2070  if (!PH) continue;
2071  if (PH->getNumIncomingValues() != 2) continue;
2072 
2073  // If the calculation in integers overflows, the result in FP type will
2074  // differ. So we only can do this transformation if we are guaranteed to not
2075  // deal with overflowing values
2076  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH));
2077  if (!AR) continue;
2078  if (IsSigned && !AR->hasNoSignedWrap()) continue;
2079  if (!IsSigned && !AR->hasNoUnsignedWrap()) continue;
2080 
2081  Type *SrcTy = PH->getType();
2082  int Mantissa = DestTy->getFPMantissaWidth();
2083  if (Mantissa == -1) continue;
2084  if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
2085  continue;
2086 
2087  unsigned Entry, Latch;
2088  if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2089  Entry = 0;
2090  Latch = 1;
2091  } else {
2092  Entry = 1;
2093  Latch = 0;
2094  }
2095 
2097  if (!Init) continue;
2098  Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
2099  (double)Init->getSExtValue() :
2100  (double)Init->getZExtValue());
2101 
2102  BinaryOperator *Incr =
2104  if (!Incr) continue;
2105  if (Incr->getOpcode() != Instruction::Add
2106  && Incr->getOpcode() != Instruction::Sub)
2107  continue;
2108 
2109  /* Initialize new IV, double d = 0.0 in above example. */
2110  ConstantInt *C = nullptr;
2111  if (Incr->getOperand(0) == PH)
2112  C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2113  else if (Incr->getOperand(1) == PH)
2114  C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2115  else
2116  continue;
2117 
2118  if (!C) continue;
2119 
2120  // Ignore negative constants, as the code below doesn't handle them
2121  // correctly. TODO: Remove this restriction.
2122  if (!C->getValue().isStrictlyPositive()) continue;
2123 
2124  /* Add new PHINode. */
2125  PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
2126 
2127  /* create new increment. '++d' in above example. */
2128  Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2129  BinaryOperator *NewIncr =
2130  BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
2131  Instruction::FAdd : Instruction::FSub,
2132  NewPH, CFP, "IV.S.next.", Incr);
2133 
2134  NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2135  NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2136 
2137  /* Remove cast operation */
2138  ShadowUse->replaceAllUsesWith(NewPH);
2139  ShadowUse->eraseFromParent();
2140  Changed = true;
2141  break;
2142  }
2143 }
2144 
2145 /// If Cond has an operand that is an expression of an IV, set the IV user and
2146 /// stride information and return true, otherwise return false.
2147 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
2148  for (IVStrideUse &U : IU)
2149  if (U.getUser() == Cond) {
2150  // NOTE: we could handle setcc instructions with multiple uses here, but
2151  // InstCombine does it as well for simple uses, it's not clear that it
2152  // occurs enough in real life to handle.
2153  CondUse = &U;
2154  return true;
2155  }
2156  return false;
2157 }
2158 
2159 /// Rewrite the loop's terminating condition if it uses a max computation.
2160 ///
2161 /// This is a narrow solution to a specific, but acute, problem. For loops
2162 /// like this:
2163 ///
2164 /// i = 0;
2165 /// do {
2166 /// p[i] = 0.0;
2167 /// } while (++i < n);
2168 ///
2169 /// the trip count isn't just 'n', because 'n' might not be positive. And
2170 /// unfortunately this can come up even for loops where the user didn't use
2171 /// a C do-while loop. For example, seemingly well-behaved top-test loops
2172 /// will commonly be lowered like this:
2173 ///
2174 /// if (n > 0) {
2175 /// i = 0;
2176 /// do {
2177 /// p[i] = 0.0;
2178 /// } while (++i < n);
2179 /// }
2180 ///
2181 /// and then it's possible for subsequent optimization to obscure the if
2182 /// test in such a way that indvars can't find it.
2183 ///
2184 /// When indvars can't find the if test in loops like this, it creates a
2185 /// max expression, which allows it to give the loop a canonical
2186 /// induction variable:
2187 ///
2188 /// i = 0;
2189 /// max = n < 1 ? 1 : n;
2190 /// do {
2191 /// p[i] = 0.0;
2192 /// } while (++i != max);
2193 ///
2194 /// Canonical induction variables are necessary because the loop passes
2195 /// are designed around them. The most obvious example of this is the
2196 /// LoopInfo analysis, which doesn't remember trip count values. It
2197 /// expects to be able to rediscover the trip count each time it is
2198 /// needed, and it does this using a simple analysis that only succeeds if
2199 /// the loop has a canonical induction variable.
2200 ///
2201 /// However, when it comes time to generate code, the maximum operation
2202 /// can be quite costly, especially if it's inside of an outer loop.
2203 ///
2204 /// This function solves this problem by detecting this type of loop and
2205 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2206 /// the instructions for the maximum computation.
2207 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
2208  // Check that the loop matches the pattern we're looking for.
2209  if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2210  Cond->getPredicate() != CmpInst::ICMP_NE)
2211  return Cond;
2212 
2213  SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2214  if (!Sel || !Sel->hasOneUse()) return Cond;
2215 
2216  const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2217  if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2218  return Cond;
2219  const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
2220 
2221  // Add one to the backedge-taken count to get the trip count.
2222  const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
2223  if (IterationCount != SE.getSCEV(Sel)) return Cond;
2224 
2225  // Check for a max calculation that matches the pattern. There's no check
2226  // for ICMP_ULE here because the comparison would be with zero, which
2227  // isn't interesting.
2229  const SCEVNAryExpr *Max = nullptr;
2230  if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2231  Pred = ICmpInst::ICMP_SLE;
2232  Max = S;
2233  } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2234  Pred = ICmpInst::ICMP_SLT;
2235  Max = S;
2236  } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2237  Pred = ICmpInst::ICMP_ULT;
2238  Max = U;
2239  } else {
2240  // No match; bail.
2241  return Cond;
2242  }
2243 
2244  // To handle a max with more than two operands, this optimization would
2245  // require additional checking and setup.
2246  if (Max->getNumOperands() != 2)
2247  return Cond;
2248 
2249  const SCEV *MaxLHS = Max->getOperand(0);
2250  const SCEV *MaxRHS = Max->getOperand(1);
2251 
2252  // ScalarEvolution canonicalizes constants to the left. For < and >, look
2253  // for a comparison with 1. For <= and >=, a comparison with zero.
2254  if (!MaxLHS ||
2255  (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2256  return Cond;
2257 
2258  // Check the relevant induction variable for conformance to
2259  // the pattern.
2260  const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
2261  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2262  if (!AR || !AR->isAffine() ||
2263  AR->getStart() != One ||
2264  AR->getStepRecurrence(SE) != One)
2265  return Cond;
2266 
2267  assert(AR->getLoop() == L &&
2268  "Loop condition operand is an addrec in a different loop!");
2269 
2270  // Check the right operand of the select, and remember it, as it will
2271  // be used in the new comparison instruction.
2272  Value *NewRHS = nullptr;
2273  if (ICmpInst::isTrueWhenEqual(Pred)) {
2274  // Look for n+1, and grab n.
2275  if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
2276  if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2277  if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2278  NewRHS = BO->getOperand(0);
2279  if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
2280  if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2281  if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2282  NewRHS = BO->getOperand(0);
2283  if (!NewRHS)
2284  return Cond;
2285  } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
2286  NewRHS = Sel->getOperand(1);
2287  else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
2288  NewRHS = Sel->getOperand(2);
2289  else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2290  NewRHS = SU->getValue();
2291  else
2292  // Max doesn't match expected pattern.
2293  return Cond;
2294 
2295  // Determine the new comparison opcode. It may be signed or unsigned,
2296  // and the original comparison may be either equality or inequality.
2297  if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2298  Pred = CmpInst::getInversePredicate(Pred);
2299 
2300  // Ok, everything looks ok to change the condition into an SLT or SGE and
2301  // delete the max calculation.
2302  ICmpInst *NewCond =
2303  new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2304 
2305  // Delete the max calculation instructions.
2306  Cond->replaceAllUsesWith(NewCond);
2307  CondUse->setUser(NewCond);
2308  Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2309  Cond->eraseFromParent();
2310  Sel->eraseFromParent();
2311  if (Cmp->use_empty())
2312  Cmp->eraseFromParent();
2313  return NewCond;
2314 }
2315 
2316 /// Change loop terminating condition to use the postinc iv when possible.
2317 void
2318 LSRInstance::OptimizeLoopTermCond() {
2320 
2321  // We need a different set of heuristics for rotated and non-rotated loops.
2322  // If a loop is rotated then the latch is also the backedge, so inserting
2323  // post-inc expressions just before the latch is ideal. To reduce live ranges
2324  // it also makes sense to rewrite terminating conditions to use post-inc
2325  // expressions.
2326  //
2327  // If the loop is not rotated then the latch is not a backedge; the latch
2328  // check is done in the loop head. Adding post-inc expressions before the
2329  // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2330  // in the loop body. In this case we do *not* want to use post-inc expressions
2331  // in the latch check, and we want to insert post-inc expressions before
2332  // the backedge.
2333  BasicBlock *LatchBlock = L->getLoopLatch();
2334  SmallVector<BasicBlock*, 8> ExitingBlocks;
2335  L->getExitingBlocks(ExitingBlocks);
2336  if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) {
2337  return LatchBlock != BB;
2338  })) {
2339  // The backedge doesn't exit the loop; treat this as a head-tested loop.
2340  IVIncInsertPos = LatchBlock->getTerminator();
2341  return;
2342  }
2343 
2344  // Otherwise treat this as a rotated loop.
2345  for (BasicBlock *ExitingBlock : ExitingBlocks) {
2346  // Get the terminating condition for the loop if possible. If we
2347  // can, we want to change it to use a post-incremented version of its
2348  // induction variable, to allow coalescing the live ranges for the IV into
2349  // one register value.
2350 
2351  BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2352  if (!TermBr)
2353  continue;
2354  // FIXME: Overly conservative, termination condition could be an 'or' etc..
2355  if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2356  continue;
2357 
2358  // Search IVUsesByStride to find Cond's IVUse if there is one.
2359  IVStrideUse *CondUse = nullptr;
2360  ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2361  if (!FindIVUserForCond(Cond, CondUse))
2362  continue;
2363 
2364  // If the trip count is computed in terms of a max (due to ScalarEvolution
2365  // being unable to find a sufficient guard, for example), change the loop
2366  // comparison to use SLT or ULT instead of NE.
2367  // One consequence of doing this now is that it disrupts the count-down
2368  // optimization. That's not always a bad thing though, because in such
2369  // cases it may still be worthwhile to avoid a max.
2370  Cond = OptimizeMax(Cond, CondUse);
2371 
2372  // If this exiting block dominates the latch block, it may also use
2373  // the post-inc value if it won't be shared with other uses.
2374  // Check for dominance.
2375  if (!DT.dominates(ExitingBlock, LatchBlock))
2376  continue;
2377 
2378  // Conservatively avoid trying to use the post-inc value in non-latch
2379  // exits if there may be pre-inc users in intervening blocks.
2380  if (LatchBlock != ExitingBlock)
2381  for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2382  // Test if the use is reachable from the exiting block. This dominator
2383  // query is a conservative approximation of reachability.
2384  if (&*UI != CondUse &&
2385  !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2386  // Conservatively assume there may be reuse if the quotient of their
2387  // strides could be a legal scale.
2388  const SCEV *A = IU.getStride(*CondUse, L);
2389  const SCEV *B = IU.getStride(*UI, L);
2390  if (!A || !B) continue;
2391  if (SE.getTypeSizeInBits(A->getType()) !=
2392  SE.getTypeSizeInBits(B->getType())) {
2393  if (SE.getTypeSizeInBits(A->getType()) >
2394  SE.getTypeSizeInBits(B->getType()))
2395  B = SE.getSignExtendExpr(B, A->getType());
2396  else
2397  A = SE.getSignExtendExpr(A, B->getType());
2398  }
2399  if (const SCEVConstant *D =
2400  dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
2401  const ConstantInt *C = D->getValue();
2402  // Stride of one or negative one can have reuse with non-addresses.
2403  if (C->isOne() || C->isMinusOne())
2404  goto decline_post_inc;
2405  // Avoid weird situations.
2406  if (C->getValue().getMinSignedBits() >= 64 ||
2407  C->getValue().isMinSignedValue())
2408  goto decline_post_inc;
2409  // Check for possible scaled-address reuse.
2410  MemAccessTy AccessTy = getAccessType(TTI, UI->getUser());
2411  int64_t Scale = C->getSExtValue();
2412  if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2413  /*BaseOffset=*/0,
2414  /*HasBaseReg=*/false, Scale,
2415  AccessTy.AddrSpace))
2416  goto decline_post_inc;
2417  Scale = -Scale;
2418  if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2419  /*BaseOffset=*/0,
2420  /*HasBaseReg=*/false, Scale,
2421  AccessTy.AddrSpace))
2422  goto decline_post_inc;
2423  }
2424  }
2425 
2426  DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
2427  << *Cond << '\n');
2428 
2429  // It's possible for the setcc instruction to be anywhere in the loop, and
2430  // possible for it to have multiple users. If it is not immediately before
2431  // the exiting block branch, move it.
2432  if (&*++BasicBlock::iterator(Cond) != TermBr) {
2433  if (Cond->hasOneUse()) {
2434  Cond->moveBefore(TermBr);
2435  } else {
2436  // Clone the terminating condition and insert into the loopend.
2437  ICmpInst *OldCond = Cond;
2438  Cond = cast<ICmpInst>(Cond->clone());
2439  Cond->setName(L->getHeader()->getName() + ".termcond");
2440  ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
2441 
2442  // Clone the IVUse, as the old use still exists!
2443  CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
2444  TermBr->replaceUsesOfWith(OldCond, Cond);
2445  }
2446  }
2447 
2448  // If we get to here, we know that we can transform the setcc instruction to
2449  // use the post-incremented version of the IV, allowing us to coalesce the
2450  // live ranges for the IV correctly.
2451  CondUse->transformToPostInc(L);
2452  Changed = true;
2453 
2454  PostIncs.insert(Cond);
2455  decline_post_inc:;
2456  }
2457 
2458  // Determine an insertion point for the loop induction variable increment. It
2459  // must dominate all the post-inc comparisons we just set up, and it must
2460  // dominate the loop latch edge.
2461  IVIncInsertPos = L->getLoopLatch()->getTerminator();
2462  for (Instruction *Inst : PostIncs) {
2463  BasicBlock *BB =
2464  DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
2465  Inst->getParent());
2466  if (BB == Inst->getParent())
2467  IVIncInsertPos = Inst;
2468  else if (BB != IVIncInsertPos->getParent())
2469  IVIncInsertPos = BB->getTerminator();
2470  }
2471 }
2472 
2473 /// Determine if the given use can accommodate a fixup at the given offset and
2474 /// other details. If so, update the use and return true.
2475 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2476  bool HasBaseReg, LSRUse::KindType Kind,
2477  MemAccessTy AccessTy) {
2478  int64_t NewMinOffset = LU.MinOffset;
2479  int64_t NewMaxOffset = LU.MaxOffset;
2480  MemAccessTy NewAccessTy = AccessTy;
2481 
2482  // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2483  // something conservative, however this can pessimize in the case that one of
2484  // the uses will have all its uses outside the loop, for example.
2485  if (LU.Kind != Kind)
2486  return false;
2487 
2488  // Check for a mismatched access type, and fall back conservatively as needed.
2489  // TODO: Be less conservative when the type is similar and can use the same
2490  // addressing modes.
2491  if (Kind == LSRUse::Address) {
2492  if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2493  NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2494  AccessTy.AddrSpace);
2495  }
2496  }
2497 
2498  // Conservatively assume HasBaseReg is true for now.
2499  if (NewOffset < LU.MinOffset) {
2500  if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2501  LU.MaxOffset - NewOffset, HasBaseReg))
2502  return false;
2503  NewMinOffset = NewOffset;
2504  } else if (NewOffset > LU.MaxOffset) {
2505  if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2506  NewOffset - LU.MinOffset, HasBaseReg))
2507  return false;
2508  NewMaxOffset = NewOffset;
2509  }
2510 
2511  // Update the use.
2512  LU.MinOffset = NewMinOffset;
2513  LU.MaxOffset = NewMaxOffset;
2514  LU.AccessTy = NewAccessTy;
2515  return true;
2516 }
2517 
2518 /// Return an LSRUse index and an offset value for a fixup which needs the given
2519 /// expression, with the given kind and optional access type. Either reuse an
2520 /// existing use or create a new one, as needed.
2521 std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr,
2522  LSRUse::KindType Kind,
2523  MemAccessTy AccessTy) {
2524  const SCEV *Copy = Expr;
2525  int64_t Offset = ExtractImmediate(Expr, SE);
2526 
2527  // Basic uses can't accept any offset, for example.
2528  if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
2529  Offset, /*HasBaseReg=*/ true)) {
2530  Expr = Copy;
2531  Offset = 0;
2532  }
2533 
2534  std::pair<UseMapTy::iterator, bool> P =
2535  UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
2536  if (!P.second) {
2537  // A use already existed with this base.
2538  size_t LUIdx = P.first->second;
2539  LSRUse &LU = Uses[LUIdx];
2540  if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
2541  // Reuse this use.
2542  return std::make_pair(LUIdx, Offset);
2543  }
2544 
2545  // Create a new use.
2546  size_t LUIdx = Uses.size();
2547  P.first->second = LUIdx;
2548  Uses.push_back(LSRUse(Kind, AccessTy));
2549  LSRUse &LU = Uses[LUIdx];
2550 
2551  LU.MinOffset = Offset;
2552  LU.MaxOffset = Offset;
2553  return std::make_pair(LUIdx, Offset);
2554 }
2555 
2556 /// Delete the given use from the Uses list.
2557 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
2558  if (&LU != &Uses.back())
2559  std::swap(LU, Uses.back());
2560  Uses.pop_back();
2561 
2562  // Update RegUses.
2563  RegUses.swapAndDropUse(LUIdx, Uses.size());
2564 }
2565 
2566 /// Look for a use distinct from OrigLU which is has a formula that has the same
2567 /// registers as the given formula.
2568 LSRUse *
2569 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
2570  const LSRUse &OrigLU) {
2571  // Search all uses for the formula. This could be more clever.
2572  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2573  LSRUse &LU = Uses[LUIdx];
2574  // Check whether this use is close enough to OrigLU, to see whether it's
2575  // worthwhile looking through its formulae.
2576  // Ignore ICmpZero uses because they may contain formulae generated by
2577  // GenerateICmpZeroScales, in which case adding fixup offsets may
2578  // be invalid.
2579  if (&LU != &OrigLU &&
2580  LU.Kind != LSRUse::ICmpZero &&
2581  LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2582  LU.WidestFixupType == OrigLU.WidestFixupType &&
2583  LU.HasFormulaWithSameRegs(OrigF)) {
2584  // Scan through this use's formulae.
2585  for (const Formula &F : LU.Formulae) {
2586  // Check to see if this formula has the same registers and symbols
2587  // as OrigF.
2588  if (F.BaseRegs == OrigF.BaseRegs &&
2589  F.ScaledReg == OrigF.ScaledReg &&
2590  F.BaseGV == OrigF.BaseGV &&
2591  F.Scale == OrigF.Scale &&
2592  F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2593  if (F.BaseOffset == 0)
2594  return &LU;
2595  // This is the formula where all the registers and symbols matched;
2596  // there aren't going to be any others. Since we declined it, we
2597  // can skip the rest of the formulae and proceed to the next LSRUse.
2598  break;
2599  }
2600  }
2601  }
2602  }
2603 
2604  // Nothing looked good.
2605  return nullptr;
2606 }
2607 
2608 void LSRInstance::CollectInterestingTypesAndFactors() {
2610 
2611  // Collect interesting types and strides.
2613  for (const IVStrideUse &U : IU) {
2614  const SCEV *Expr = IU.getExpr(U);
2615 
2616  // Collect interesting types.
2617  Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
2618 
2619  // Add strides for mentioned loops.
2620  Worklist.push_back(Expr);
2621  do {
2622  const SCEV *S = Worklist.pop_back_val();
2623  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2624  if (AR->getLoop() == L)
2625  Strides.insert(AR->getStepRecurrence(SE));
2626  Worklist.push_back(AR->getStart());
2627  } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2628  Worklist.append(Add->op_begin(), Add->op_end());
2629  }
2630  } while (!Worklist.empty());
2631  }
2632 
2633  // Compute interesting factors from the set of interesting strides.
2635  I = Strides.begin(), E = Strides.end(); I != E; ++I)
2637  std::next(I); NewStrideIter != E; ++NewStrideIter) {
2638  const SCEV *OldStride = *I;
2639  const SCEV *NewStride = *NewStrideIter;
2640 
2641  if (SE.getTypeSizeInBits(OldStride->getType()) !=
2642  SE.getTypeSizeInBits(NewStride->getType())) {
2643  if (SE.getTypeSizeInBits(OldStride->getType()) >
2644  SE.getTypeSizeInBits(NewStride->getType()))
2645  NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2646  else
2647  OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2648  }
2649  if (const SCEVConstant *Factor =
2650  dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2651  SE, true))) {
2652  if (Factor->getAPInt().getMinSignedBits() <= 64)
2653  Factors.insert(Factor->getAPInt().getSExtValue());
2654  } else if (const SCEVConstant *Factor =
2655  dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2656  NewStride,
2657  SE, true))) {
2658  if (Factor->getAPInt().getMinSignedBits() <= 64)
2659  Factors.insert(Factor->getAPInt().getSExtValue());
2660  }
2661  }
2662 
2663  // If all uses use the same type, don't bother looking for truncation-based
2664  // reuse.
2665  if (Types.size() == 1)
2666  Types.clear();
2667 
2668  DEBUG(print_factors_and_types(dbgs()));
2669 }
2670 
2671 /// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2672 /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2673 /// IVStrideUses, we could partially skip this.
2674 static User::op_iterator
2676  Loop *L, ScalarEvolution &SE) {
2677  for(; OI != OE; ++OI) {
2678  if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2679  if (!SE.isSCEVable(Oper->getType()))
2680  continue;
2681 
2682  if (const SCEVAddRecExpr *AR =
2683  dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2684  if (AR->getLoop() == L)
2685  break;
2686  }
2687  }
2688  }
2689  return OI;
2690 }
2691 
2692 /// IVChain logic must consistenctly peek base TruncInst operands, so wrap it in
2693 /// a convenient helper.
2694 static Value *getWideOperand(Value *Oper) {
2695  if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2696  return Trunc->getOperand(0);
2697  return Oper;
2698 }
2699 
2700 /// Return true if we allow an IV chain to include both types.
2701 static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2702  Type *LType = LVal->getType();
2703  Type *RType = RVal->getType();
2704  return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() &&
2705  // Different address spaces means (possibly)
2706  // different types of the pointer implementation,
2707  // e.g. i16 vs i32 so disallow that.
2708  (LType->getPointerAddressSpace() ==
2709  RType->getPointerAddressSpace()));
2710 }
2711 
2712 /// Return an approximation of this SCEV expression's "base", or NULL for any
2713 /// constant. Returning the expression itself is conservative. Returning a
2714 /// deeper subexpression is more precise and valid as long as it isn't less
2715 /// complex than another subexpression. For expressions involving multiple
2716 /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2717 /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2718 /// IVInc==b-a.
2719 ///
2720 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2721 /// SCEVUnknown, we simply return the rightmost SCEV operand.
2722 static const SCEV *getExprBase(const SCEV *S) {
2723  switch (S->getSCEVType()) {
2724  default: // uncluding scUnknown.
2725  return S;
2726  case scConstant:
2727  return nullptr;
2728  case scTruncate:
2729  return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2730  case scZeroExtend:
2731  return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2732  case scSignExtend:
2733  return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2734  case scAddExpr: {
2735  // Skip over scaled operands (scMulExpr) to follow add operands as long as
2736  // there's nothing more complex.
2737  // FIXME: not sure if we want to recognize negation.
2738  const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2739  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2740  E(Add->op_begin()); I != E; ++I) {
2741  const SCEV *SubExpr = *I;
2742  if (SubExpr->getSCEVType() == scAddExpr)
2743  return getExprBase(SubExpr);
2744 
2745  if (SubExpr->getSCEVType() != scMulExpr)
2746  return SubExpr;
2747  }
2748  return S; // all operands are scaled, be conservative.
2749  }
2750  case scAddRecExpr:
2751  return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2752  }
2753 }
2754 
2755 /// Return true if the chain increment is profitable to expand into a loop
2756 /// invariant value, which may require its own register. A profitable chain
2757 /// increment will be an offset relative to the same base. We allow such offsets
2758 /// to potentially be used as chain increment as long as it's not obviously
2759 /// expensive to expand using real instructions.
2760 bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2761  const SCEV *IncExpr,
2762  ScalarEvolution &SE) {
2763  // Aggressively form chains when -stress-ivchain.
2764  if (StressIVChain)
2765  return true;
2766 
2767  // Do not replace a constant offset from IV head with a nonconstant IV
2768  // increment.
2769  if (!isa<SCEVConstant>(IncExpr)) {
2770  const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
2771  if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
2772  return false;
2773  }
2774 
2775  SmallPtrSet<const SCEV*, 8> Processed;
2776  return !isHighCostExpansion(IncExpr, Processed, SE);
2777 }
2778 
2779 /// Return true if the number of registers needed for the chain is estimated to
2780 /// be less than the number required for the individual IV users. First prohibit
2781 /// any IV users that keep the IV live across increments (the Users set should
2782 /// be empty). Next count the number and type of increments in the chain.
2783 ///
2784 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2785 /// effectively use postinc addressing modes. Only consider it profitable it the
2786 /// increments can be computed in fewer registers when chained.
2787 ///
2788 /// TODO: Consider IVInc free if it's already used in another chains.
2789 static bool
2791  ScalarEvolution &SE, const TargetTransformInfo &TTI) {
2792  if (StressIVChain)
2793  return true;
2794 
2795  if (!Chain.hasIncs())
2796  return false;
2797 
2798  if (!Users.empty()) {
2799  DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
2800  for (Instruction *Inst : Users) {
2801  dbgs() << " " << *Inst << "\n";
2802  });
2803  return false;
2804  }
2805  assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2806 
2807  // The chain itself may require a register, so intialize cost to 1.
2808  int cost = 1;
2809 
2810  // A complete chain likely eliminates the need for keeping the original IV in
2811  // a register. LSR does not currently know how to form a complete chain unless
2812  // the header phi already exists.
2813  if (isa<PHINode>(Chain.tailUserInst())
2814  && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2815  --cost;
2816  }
2817  const SCEV *LastIncExpr = nullptr;
2818  unsigned NumConstIncrements = 0;
2819  unsigned NumVarIncrements = 0;
2820  unsigned NumReusedIncrements = 0;
2821  for (const IVInc &Inc : Chain) {
2822  if (Inc.IncExpr->isZero())
2823  continue;
2824 
2825  // Incrementing by zero or some constant is neutral. We assume constants can
2826  // be folded into an addressing mode or an add's immediate operand.
2827  if (isa<SCEVConstant>(Inc.IncExpr)) {
2828  ++NumConstIncrements;
2829  continue;
2830  }
2831 
2832  if (Inc.IncExpr == LastIncExpr)
2833  ++NumReusedIncrements;
2834  else
2835  ++NumVarIncrements;
2836 
2837  LastIncExpr = Inc.IncExpr;
2838  }
2839  // An IV chain with a single increment is handled by LSR's postinc
2840  // uses. However, a chain with multiple increments requires keeping the IV's
2841  // value live longer than it needs to be if chained.
2842  if (NumConstIncrements > 1)
2843  --cost;
2844 
2845  // Materializing increment expressions in the preheader that didn't exist in
2846  // the original code may cost a register. For example, sign-extended array
2847  // indices can produce ridiculous increments like this:
2848  // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2849  cost += NumVarIncrements;
2850 
2851  // Reusing variable increments likely saves a register to hold the multiple of
2852  // the stride.
2853  cost -= NumReusedIncrements;
2854 
2855  DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2856  << "\n");
2857 
2858  return cost < 0;
2859 }
2860 
2861 /// Add this IV user to an existing chain or make it the head of a new chain.
2862 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2863  SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2864  // When IVs are used as types of varying widths, they are generally converted
2865  // to a wider type with some uses remaining narrow under a (free) trunc.
2866  Value *const NextIV = getWideOperand(IVOper);
2867  const SCEV *const OperExpr = SE.getSCEV(NextIV);
2868  const SCEV *const OperExprBase = getExprBase(OperExpr);
2869 
2870  // Visit all existing chains. Check if its IVOper can be computed as a
2871  // profitable loop invariant increment from the last link in the Chain.
2872  unsigned ChainIdx = 0, NChains = IVChainVec.size();
2873  const SCEV *LastIncExpr = nullptr;
2874  for (; ChainIdx < NChains; ++ChainIdx) {
2875  IVChain &Chain = IVChainVec[ChainIdx];
2876 
2877  // Prune the solution space aggressively by checking that both IV operands
2878  // are expressions that operate on the same unscaled SCEVUnknown. This
2879  // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2880  // first avoids creating extra SCEV expressions.
2881  if (!StressIVChain && Chain.ExprBase != OperExprBase)
2882  continue;
2883 
2884  Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
2885  if (!isCompatibleIVType(PrevIV, NextIV))
2886  continue;
2887 
2888  // A phi node terminates a chain.
2889  if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2890  continue;
2891 
2892  // The increment must be loop-invariant so it can be kept in a register.
2893  const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2894  const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2895  if (!SE.isLoopInvariant(IncExpr, L))
2896  continue;
2897 
2898  if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2899  LastIncExpr = IncExpr;
2900  break;
2901  }
2902  }
2903  // If we haven't found a chain, create a new one, unless we hit the max. Don't
2904  // bother for phi nodes, because they must be last in the chain.
2905  if (ChainIdx == NChains) {
2906  if (isa<PHINode>(UserInst))
2907  return;
2908  if (NChains >= MaxChains && !StressIVChain) {
2909  DEBUG(dbgs() << "IV Chain Limit\n");
2910  return;
2911  }
2912  LastIncExpr = OperExpr;
2913  // IVUsers may have skipped over sign/zero extensions. We don't currently
2914  // attempt to form chains involving extensions unless they can be hoisted
2915  // into this loop's AddRec.
2916  if (!isa<SCEVAddRecExpr>(LastIncExpr))
2917  return;
2918  ++NChains;
2919  IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2920  OperExprBase));
2921  ChainUsersVec.resize(NChains);
2922  DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2923  << ") IV=" << *LastIncExpr << "\n");
2924  } else {
2925  DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2926  << ") IV+" << *LastIncExpr << "\n");
2927  // Add this IV user to the end of the chain.
2928  IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2929  }
2930  IVChain &Chain = IVChainVec[ChainIdx];
2931 
2932  SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2933  // This chain's NearUsers become FarUsers.
2934  if (!LastIncExpr->isZero()) {
2935  ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2936  NearUsers.end());
2937  NearUsers.clear();
2938  }
2939 
2940  // All other uses of IVOperand become near uses of the chain.
2941  // We currently ignore intermediate values within SCEV expressions, assuming
2942  // they will eventually be used be the current chain, or can be computed
2943  // from one of the chain increments. To be more precise we could
2944  // transitively follow its user and only add leaf IV users to the set.
2945  for (User *U : IVOper->users()) {
2946  Instruction *OtherUse = dyn_cast<Instruction>(U);
2947  if (!OtherUse)
2948  continue;
2949  // Uses in the chain will no longer be uses if the chain is formed.
2950  // Include the head of the chain in this iteration (not Chain.begin()).
2951  IVChain::const_iterator IncIter = Chain.Incs.begin();
2952  IVChain::const_iterator IncEnd = Chain.Incs.end();
2953  for( ; IncIter != IncEnd; ++IncIter) {
2954  if (IncIter->UserInst == OtherUse)
2955  break;
2956  }
2957  if (IncIter != IncEnd)
2958  continue;
2959 
2960  if (SE.isSCEVable(OtherUse->getType())
2961  && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2962  && IU.isIVUserOrOperand(OtherUse)) {
2963  continue;
2964  }
2965  NearUsers.insert(OtherUse);
2966  }
2967 
2968  // Since this user is part of the chain, it's no longer considered a use
2969  // of the chain.
2970  ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2971 }
2972 
2973 /// Populate the vector of Chains.
2974 ///
2975 /// This decreases ILP at the architecture level. Targets with ample registers,
2976 /// multiple memory ports, and no register renaming probably don't want
2977 /// this. However, such targets should probably disable LSR altogether.
2978 ///
2979 /// The job of LSR is to make a reasonable choice of induction variables across
2980 /// the loop. Subsequent passes can easily "unchain" computation exposing more
2981 /// ILP *within the loop* if the target wants it.
2982 ///
2983 /// Finding the best IV chain is potentially a scheduling problem. Since LSR
2984 /// will not reorder memory operations, it will recognize this as a chain, but
2985 /// will generate redundant IV increments. Ideally this would be corrected later
2986 /// by a smart scheduler:
2987 /// = A[i]
2988 /// = A[i+x]
2989 /// A[i] =
2990 /// A[i+x] =
2991 ///
2992 /// TODO: Walk the entire domtree within this loop, not just the path to the
2993 /// loop latch. This will discover chains on side paths, but requires
2994 /// maintaining multiple copies of the Chains state.
2995 void LSRInstance::CollectChains() {
2996  DEBUG(dbgs() << "Collecting IV Chains.\n");
2997  SmallVector<ChainUsers, 8> ChainUsersVec;
2998 
2999  SmallVector<BasicBlock *,8> LatchPath;
3000  BasicBlock *LoopHeader = L->getHeader();
3001  for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
3002  Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
3003  LatchPath.push_back(Rung->getBlock());
3004  }
3005  LatchPath.push_back(LoopHeader);
3006 
3007  // Walk the instruction stream from the loop header to the loop latch.
3008  for (BasicBlock *BB : reverse(LatchPath)) {
3009  for (Instruction &I : *BB) {
3010  // Skip instructions that weren't seen by IVUsers analysis.
3011  if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
3012  continue;
3013 
3014  // Ignore users that are part of a SCEV expression. This way we only
3015  // consider leaf IV Users. This effectively rediscovers a portion of
3016  // IVUsers analysis but in program order this time.
3017  if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))
3018  continue;
3019 
3020  // Remove this instruction from any NearUsers set it may be in.
3021  for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
3022  ChainIdx < NChains; ++ChainIdx) {
3023  ChainUsersVec[ChainIdx].NearUsers.erase(&I);
3024  }
3025  // Search for operands that can be chained.
3026  SmallPtrSet<Instruction*, 4> UniqueOperands;
3027  User::op_iterator IVOpEnd = I.op_end();
3028  User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);
3029  while (IVOpIter != IVOpEnd) {
3030  Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
3031  if (UniqueOperands.insert(IVOpInst).second)
3032  ChainInstruction(&I, IVOpInst, ChainUsersVec);
3033  IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3034  }
3035  } // Continue walking down the instructions.
3036  } // Continue walking down the domtree.
3037  // Visit phi backedges to determine if the chain can generate the IV postinc.
3038  for (PHINode &PN : L->getHeader()->phis()) {
3039  if (!SE.isSCEVable(PN.getType()))
3040  continue;
3041 
3042  Instruction *IncV =
3043  dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch()));
3044  if (IncV)
3045  ChainInstruction(&PN, IncV, ChainUsersVec);
3046  }
3047  // Remove any unprofitable chains.
3048  unsigned ChainIdx = 0;
3049  for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
3050  UsersIdx < NChains; ++UsersIdx) {
3051  if (!isProfitableChain(IVChainVec[UsersIdx],
3052  ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
3053  continue;
3054  // Preserve the chain at UsesIdx.
3055  if (ChainIdx != UsersIdx)
3056  IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
3057  FinalizeChain(IVChainVec[ChainIdx]);
3058  ++ChainIdx;
3059  }
3060  IVChainVec.resize(ChainIdx);
3061 }
3062 
3063 void LSRInstance::FinalizeChain(IVChain &Chain) {
3064  assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
3065  DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
3066 
3067  for (const IVInc &Inc : Chain) {
3068  DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");
3069  auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);
3070  assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
3071  IVIncSet.insert(UseI);
3072  }
3073 }
3074 
3075 /// Return true if the IVInc can be folded into an addressing mode.
3076 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
3077  Value *Operand, const TargetTransformInfo &TTI) {
3078  const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
3079  if (!IncConst || !isAddressUse(TTI, UserInst, Operand))
3080  return false;
3081 
3082  if (IncConst->getAPInt().getMinSignedBits() > 64)
3083  return false;
3084 
3085  MemAccessTy AccessTy = getAccessType(TTI, UserInst);
3086  int64_t IncOffset = IncConst->getValue()->getSExtValue();
3087  if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
3088  IncOffset, /*HaseBaseReg=*/false))
3089  return false;
3090 
3091  return true;
3092 }
3093 
3094 /// Generate an add or subtract for each IVInc in a chain to materialize the IV
3095 /// user's operand from the previous IV user's operand.
3096 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
3097  SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
3098  // Find the new IVOperand for the head of the chain. It may have been replaced
3099  // by LSR.
3100  const IVInc &Head = Chain.Incs[0];
3101  User::op_iterator IVOpEnd = Head.UserInst->op_end();
3102  // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
3103  User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
3104  IVOpEnd, L, SE);
3105  Value *IVSrc = nullptr;
3106  while (IVOpIter != IVOpEnd) {
3107  IVSrc = getWideOperand(*IVOpIter);
3108 
3109  // If this operand computes the expression that the chain needs, we may use
3110  // it. (Check this after setting IVSrc which is used below.)
3111  //
3112  // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
3113  // narrow for the chain, so we can no longer use it. We do allow using a
3114  // wider phi, assuming the LSR checked for free truncation. In that case we
3115  // should already have a truncate on this operand such that
3116  // getSCEV(IVSrc) == IncExpr.
3117  if (SE.getSCEV(*IVOpIter) == Head.IncExpr
3118  || SE.getSCEV(IVSrc) == Head.IncExpr) {
3119  break;
3120  }
3121  IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3122  }
3123  if (IVOpIter == IVOpEnd) {
3124  // Gracefully give up on this chain.
3125  DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
3126  return;
3127  }
3128 
3129  DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
3130  Type *IVTy = IVSrc->getType();
3131  Type *IntTy = SE.getEffectiveSCEVType(IVTy);
3132  const SCEV *LeftOverExpr = nullptr;
3133  for (const IVInc &Inc : Chain) {
3134  Instruction *InsertPt = Inc.UserInst;
3135  if (isa<PHINode>(InsertPt))
3136  InsertPt = L->getLoopLatch()->getTerminator();
3137 
3138  // IVOper will replace the current IV User's operand. IVSrc is the IV
3139  // value currently held in a register.
3140  Value *IVOper = IVSrc;
3141  if (!Inc.IncExpr->isZero()) {
3142  // IncExpr was the result of subtraction of two narrow values, so must
3143  // be signed.
3144  const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
3145  LeftOverExpr = LeftOverExpr ?
3146  SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3147  }
3148  if (LeftOverExpr && !LeftOverExpr->isZero()) {
3149  // Expand the IV increment.
3150  Rewriter.clearPostInc();
3151  Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
3152  const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
3153  SE.getUnknown(IncV));
3154  IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
3155 
3156  // If an IV increment can't be folded, use it as the next IV value.
3157  if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
3158  assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
3159  IVSrc = IVOper;
3160  LeftOverExpr = nullptr;
3161  }
3162  }
3163  Type *OperTy = Inc.IVOperand->getType();
3164  if (IVTy != OperTy) {
3165  assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
3166  "cannot extend a chained IV");
3167  IRBuilder<> Builder(InsertPt);
3168  IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
3169  }
3170  Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
3171  DeadInsts.emplace_back(Inc.IVOperand);
3172  }
3173  // If LSR created a new, wider phi, we may also replace its postinc. We only
3174  // do this if we also found a wide value for the head of the chain.
3175  if (isa<PHINode>(Chain.tailUserInst())) {
3176  for (PHINode &Phi : L->getHeader()->phis()) {
3177  if (!isCompatibleIVType(&Phi, IVSrc))
3178  continue;
3179  Instruction *PostIncV = dyn_cast<Instruction>(
3180  Phi.getIncomingValueForBlock(L->getLoopLatch()));
3181  if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
3182  continue;
3183  Value *IVOper = IVSrc;
3184  Type *PostIncTy = PostIncV->getType();
3185  if (IVTy != PostIncTy) {
3186  assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
3187  IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3188  Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
3189  IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
3190  }
3191  Phi.replaceUsesOfWith(PostIncV, IVOper);
3192  DeadInsts.emplace_back(PostIncV);
3193  }
3194  }
3195 }
3196 
3197 void LSRInstance::CollectFixupsAndInitialFormulae() {
3198  for (const IVStrideUse &U : IU) {
3199  Instruction *UserInst = U.getUser();
3200  // Skip IV users that are part of profitable IV Chains.
3201  User::op_iterator UseI =
3202  find(UserInst->operands(), U.getOperandValToReplace());
3203  assert(UseI != UserInst->op_end() && "cannot find IV operand");
3204  if (IVIncSet.count(UseI)) {
3205  DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');
3206  continue;
3207  }
3208 
3209  LSRUse::KindType Kind = LSRUse::Basic;
3210  MemAccessTy AccessTy;
3211  if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {
3212  Kind = LSRUse::Address;
3213  AccessTy = getAccessType(TTI, UserInst);
3214  }
3215 
3216  const SCEV *S = IU.getExpr(U);
3217  PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
3218 
3219  // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3220  // (N - i == 0), and this allows (N - i) to be the expression that we work
3221  // with rather than just N or i, so we can consider the register
3222  // requirements for both N and i at the same time. Limiting this code to
3223  // equality icmps is not a problem because all interesting loops use
3224  // equality icmps, thanks to IndVarSimplify.
3225  if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst))
3226  if (CI->isEquality()) {
3227  // Swap the operands if needed to put the OperandValToReplace on the
3228  // left, for consistency.
3229  Value *NV = CI->getOperand(1);
3230  if (NV == U.getOperandValToReplace()) {
3231  CI->setOperand(1, CI->getOperand(0));
3232  CI->setOperand(0, NV);
3233  NV = CI->getOperand(1);
3234  Changed = true;
3235  }
3236 
3237  // x == y --> x - y == 0
3238  const SCEV *N = SE.getSCEV(NV);
3239  if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
3240  // S is normalized, so normalize N before folding it into S
3241  // to keep the result normalized.
3242  N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);
3243  Kind = LSRUse::ICmpZero;
3244  S = SE.getMinusSCEV(N, S);
3245  }
3246 
3247  // -1 and the negations of all interesting strides (except the negation
3248  // of -1) are now also interesting.
3249  for (size_t i = 0, e = Factors.size(); i != e; ++i)
3250  if (Factors[i] != -1)
3251  Factors.insert(-(uint64_t)Factors[i]);
3252  Factors.insert(-1);
3253  }
3254 
3255  // Get or create an LSRUse.
3256  std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3257  size_t LUIdx = P.first;
3258  int64_t Offset = P.second;
3259  LSRUse &LU = Uses[LUIdx];
3260 
3261  // Record the fixup.
3262  LSRFixup &LF = LU.getNewFixup();
3263  LF.UserInst = UserInst;
3264  LF.OperandValToReplace = U.getOperandValToReplace();
3265  LF.PostIncLoops = TmpPostIncLoops;
3266  LF.Offset = Offset;
3267  LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3268 
3269  if (!LU.WidestFixupType ||
3270  SE.getTypeSizeInBits(LU.WidestFixupType) <
3271  SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3272  LU.WidestFixupType = LF.OperandValToReplace->getType();
3273 
3274  // If this is the first use of this LSRUse, give it a formula.
3275  if (LU.Formulae.empty()) {
3276  InsertInitialFormula(S, LU, LUIdx);
3277  CountRegisters(LU.Formulae.back(), LUIdx);
3278  }
3279  }
3280 
3281  DEBUG(print_fixups(dbgs()));
3282 }
3283 
3284 /// Insert a formula for the given expression into the given use, separating out
3285 /// loop-variant portions from loop-invariant and loop-computable portions.
3286 void
3287 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
3288  // Mark uses whose expressions cannot be expanded.
3289  if (!isSafeToExpand(S, SE))
3290  LU.RigidFormula = true;
3291 
3292  Formula F;
3293  F.initialMatch(S, L, SE);
3294  bool Inserted = InsertFormula(LU, LUIdx, F);
3295  assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3296 }
3297 
3298 /// Insert a simple single-register formula for the given expression into the
3299 /// given use.
3300 void
3301 LSRInstance::InsertSupplementalFormula(const SCEV *S,
3302  LSRUse &LU, size_t LUIdx) {
3303  Formula F;
3304  F.BaseRegs.push_back(S);
3305  F.HasBaseReg = true;
3306  bool Inserted = InsertFormula(LU, LUIdx, F);
3307  assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3308 }
3309 
3310 /// Note which registers are used by the given formula, updating RegUses.
3311 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3312  if (F.ScaledReg)
3313  RegUses.countRegister(F.ScaledReg, LUIdx);
3314  for (const SCEV *BaseReg : F.BaseRegs)
3315  RegUses.countRegister(BaseReg, LUIdx);
3316 }
3317 
3318 /// If the given formula has not yet been inserted, add it to the list, and
3319 /// return true. Return false otherwise.
3320 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
3321  // Do not insert formula that we will not be able to expand.
3322  assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3323  "Formula is illegal");
3324 
3325  if (!LU.InsertFormula(F, *L))
3326  return false;
3327 
3328  CountRegisters(F, LUIdx);
3329  return true;
3330 }
3331 
3332 /// Check for other uses of loop-invariant values which we're tracking. These
3333 /// other uses will pin these values in registers, making them less profitable
3334 /// for elimination.
3335 /// TODO: This currently misses non-constant addrec step registers.
3336 /// TODO: Should this give more weight to users inside the loop?
3337 void
3338 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3339  SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
3341 
3342  while (!Worklist.empty()) {
3343  const SCEV *S = Worklist.pop_back_val();
3344 
3345  // Don't process the same SCEV twice
3346  if (!Visited.insert(S).second)
3347  continue;
3348 
3349  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
3350  Worklist.append(N->op_begin(), N->op_end());
3351  else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3352  Worklist.push_back(C->getOperand());
3353  else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3354  Worklist.push_back(D->getLHS());
3355  Worklist.push_back(D->getRHS());
3356  } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3357  const Value *V = US->getValue();
3358  if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3359  // Look for instructions defined outside the loop.
3360  if (L->contains(Inst)) continue;
3361  } else if (isa<UndefValue>(V))
3362  // Undef doesn't have a live range, so it doesn't matter.
3363  continue;
3364  for (const Use &U : V->uses()) {
3365  const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
3366  // Ignore non-instructions.
3367  if (!UserInst)
3368  continue;
3369  // Ignore instructions in other functions (as can happen with
3370  // Constants).
3371  if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
3372  continue;
3373  // Ignore instructions not dominated by the loop.
3374  const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3375  UserInst->getParent() :
3376  cast<PHINode>(UserInst)->getIncomingBlock(
3377  PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3378  if (!DT.dominates(L->getHeader(), UseBB))
3379  continue;
3380  // Don't bother if the instruction is in a BB which ends in an EHPad.
3381  if (UseBB->getTerminator()->isEHPad())
3382  continue;
3383  // Don't bother rewriting PHIs in catchswitch blocks.
3384  if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))
3385  continue;
3386  // Ignore uses which are part of other SCEV expressions, to avoid
3387  // analyzing them multiple times.
3388  if (SE.isSCEVable(UserInst->getType())) {
3389  const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3390  // If the user is a no-op, look through to its uses.
3391  if (!isa<SCEVUnknown>(UserS))
3392  continue;
3393  if (UserS == US) {
3394  Worklist.push_back(
3395  SE.getUnknown(const_cast<Instruction *>(UserInst)));
3396  continue;
3397  }
3398  }
3399  // Ignore icmp instructions which are already being analyzed.
3400  if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3401  unsigned OtherIdx = !U.getOperandNo();
3402  Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
3403  if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
3404  continue;
3405  }
3406 
3407  std::pair<size_t, int64_t> P = getUse(
3408  S, LSRUse::Basic, MemAccessTy());
3409  size_t LUIdx = P.first;
3410  int64_t Offset = P.second;
3411  LSRUse &LU = Uses[LUIdx];
3412  LSRFixup &LF = LU.getNewFixup();
3413  LF.UserInst = const_cast<Instruction *>(UserInst);
3414  LF.OperandValToReplace = U;
3415  LF.Offset = Offset;
3416  LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3417  if (!LU.WidestFixupType ||
3418  SE.getTypeSizeInBits(LU.WidestFixupType) <
3419  SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3420  LU.WidestFixupType = LF.OperandValToReplace->getType();
3421  InsertSupplementalFormula(US, LU, LUIdx);
3422  CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3423  break;
3424  }
3425  }
3426  }
3427 }
3428 
3429 /// Split S into subexpressions which can be pulled out into separate
3430 /// registers. If C is non-null, multiply each subexpression by C.
3431 ///
3432 /// Return remainder expression after factoring the subexpressions captured by
3433 /// Ops. If Ops is complete, return NULL.
3434 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3436  const Loop *L,
3437  ScalarEvolution &SE,
3438  unsigned Depth = 0) {
3439  // Arbitrarily cap recursion to protect compile time.
3440  if (Depth >= 3)
3441  return S;
3442 
3443  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3444  // Break out add operands.
3445  for (const SCEV *S : Add->operands()) {
3446  const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
3447  if (Remainder)
3448  Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3449  }
3450  return nullptr;
3451  } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3452  // Split a non-zero base out of an addrec.
3453  if (AR->getStart()->isZero() || !AR->isAffine())
3454  return S;
3455 
3456  const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3457  C, Ops, L, SE, Depth+1);
3458  // Split the non-zero AddRec unless it is part of a nested recurrence that
3459  // does not pertain to this loop.
3460  if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3461  Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3462  Remainder = nullptr;
3463  }
3464  if (Remainder != AR->getStart()) {
3465  if (!Remainder)
3466  Remainder = SE.getConstant(AR->getType(), 0);
3467  return SE.getAddRecExpr(Remainder,
3468  AR->getStepRecurrence(SE),
3469  AR->getLoop(),
3470  //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3472  }
3473  } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3474  // Break (C * (a + b + c)) into C*a + C*b + C*c.
3475  if (Mul->getNumOperands() != 2)
3476  return S;
3477  if (const SCEVConstant *Op0 =
3478  dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3479  C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3480  const SCEV *Remainder =
3481  CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3482  if (Remainder)
3483  Ops.push_back(SE.getMulExpr(C, Remainder));
3484  return nullptr;
3485  }
3486  }
3487  return S;
3488 }
3489 
3490 /// Return true if the SCEV represents a value that may end up as a
3491 /// post-increment operation.
3493  LSRUse &LU, const SCEV *S, const Loop *L,
3494  ScalarEvolution &SE) {
3495  if (LU.Kind != LSRUse::Address ||
3496  !LU.AccessTy.getType()->isIntOrIntVectorTy())
3497  return false;
3498  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
3499  if (!AR)
3500  return false;
3501  const SCEV *LoopStep = AR->getStepRecurrence(SE);
3502  if (!isa<SCEVConstant>(LoopStep))
3503  return false;
3504  if (LU.AccessTy.getType()->getScalarSizeInBits() !=
3505  LoopStep->getType()->getScalarSizeInBits())
3506  return false;
3507  // Check if a post-indexed load/store can be used.
3508  if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) ||
3509  TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) {
3510  const SCEV *LoopStart = AR->getStart();
3511  if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L))
3512  return true;
3513  }
3514  return false;
3515 }
3516 
3517 /// \brief Helper function for LSRInstance::GenerateReassociations.
3518 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3519  const Formula &Base,
3520  unsigned Depth, size_t Idx,
3521  bool IsScaledReg) {
3522  const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3523  // Don't generate reassociations for the base register of a value that
3524  // may generate a post-increment operator. The reason is that the
3525  // reassociations cause extra base+register formula to be created,
3526  // and possibly chosen, but the post-increment is more efficient.
3527  if (TTI.shouldFavorPostInc() && mayUsePostIncMode(TTI, LU, BaseReg, L, SE))
3528  return;
3530  const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3531  if (Remainder)
3532  AddOps.push_back(Remainder);
3533 
3534  if (AddOps.size() == 1)
3535  return;
3536 
3538  JE = AddOps.end();
3539  J != JE; ++J) {
3540  // Loop-variant "unknown" values are uninteresting; we won't be able to
3541  // do anything meaningful with them.
3542  if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3543  continue;
3544 
3545  // Don't pull a constant into a register if the constant could be folded
3546  // into an immediate field.
3547  if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3548  LU.AccessTy, *J, Base.getNumRegs() > 1))
3549  continue;
3550 
3551  // Collect all operands except *J.
3552  SmallVector<const SCEV *, 8> InnerAddOps(
3553  ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3554  InnerAddOps.append(std::next(J),
3555  ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3556 
3557  // Don't leave just a constant behind in a register if the constant could
3558  // be folded into an immediate field.
3559  if (InnerAddOps.size() == 1 &&
3560  isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3561  LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3562  continue;
3563 
3564  const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3565  if (InnerSum->isZero())
3566  continue;
3567  Formula F = Base;
3568 
3569  // Add the remaining pieces of the add back into the new formula.
3570  const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3571  if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3572  TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3573  InnerSumSC->getValue()->getZExtValue())) {
3574  F.UnfoldedOffset =
3575  (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3576  if (IsScaledReg)
3577  F.ScaledReg = nullptr;
3578  else
3579  F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3580  } else if (IsScaledReg)
3581  F.ScaledReg = InnerSum;
3582  else
3583  F.BaseRegs[Idx] = InnerSum;
3584 
3585  // Add J as its own register, or an unfolded immediate.
3586  const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3587  if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3588  TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3589  SC->getValue()->getZExtValue()))
3590  F.UnfoldedOffset =
3591  (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3592  else
3593  F.BaseRegs.push_back(*J);
3594  // We may have changed the number of register in base regs, adjust the
3595  // formula accordingly.
3596  F.canonicalize(*L);
3597 
3598  if (InsertFormula(LU, LUIdx, F))
3599  // If that formula hadn't been seen before, recurse to find more like
3600  // it.
3601  GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3602  }
3603 }
3604 
3605 /// Split out subexpressions from adds and the bases of addrecs.
3606 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
3607  Formula Base, unsigned Depth) {
3608  assert(Base.isCanonical(*L) && "Input must be in the canonical form");
3609  // Arbitrarily cap recursion to protect compile time.
3610  if (Depth >= 3)
3611  return;
3612 
3613  for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3614  GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3615 
3616  if (Base.Scale == 1)
3617  GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3618  /* Idx */ -1, /* IsScaledReg */ true);
3619 }
3620 
3621 /// Generate a formula consisting of all of the loop-dominating registers added
3622 /// into a single register.
3623 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
3624  Formula Base) {
3625  // This method is only interesting on a plurality of registers.
3626  if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3627  return;
3628 
3629  // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3630  // processing the formula.
3631  Base.unscale();
3632  Formula F = Base;
3633  F.BaseRegs.clear();
3635  for (const SCEV *BaseReg : Base.BaseRegs) {
3636  if (SE.properlyDominates(BaseReg, L->getHeader()) &&
3637  !SE.hasComputableLoopEvolution(BaseReg, L))
3638  Ops.push_back(BaseReg);
3639  else
3640  F.BaseRegs.push_back(BaseReg);
3641  }
3642  if (Ops.size() > 1) {
3643  const SCEV *Sum = SE.getAddExpr(Ops);
3644  // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3645  // opportunity to fold something. For now, just ignore such cases
3646  // rather than proceed with zero in a register.
3647  if (!Sum->isZero()) {
3648  F.BaseRegs.push_back(Sum);
3649  F.canonicalize(*L);
3650  (void)InsertFormula(LU, LUIdx, F);
3651  }
3652  }
3653 }
3654 
3655 /// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
3656 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3657  const Formula &Base, size_t Idx,
3658  bool IsScaledReg) {
3659  const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3660  GlobalValue *GV = ExtractSymbol(G, SE);
3661  if (G->isZero() || !GV)
3662  return;
3663  Formula F = Base;
3664  F.BaseGV = GV;
3665  if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3666  return;
3667  if (IsScaledReg)
3668  F.ScaledReg = G;
3669  else
3670  F.BaseRegs[Idx] = G;
3671  (void)InsertFormula(LU, LUIdx, F);
3672 }
3673 
3674 /// Generate reuse formulae using symbolic offsets.
3675 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3676  Formula Base) {
3677  // We can't add a symbolic offset if the address already contains one.
3678  if (Base.BaseGV) return;
3679 
3680  for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3681  GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3682  if (Base.Scale == 1)
3683  GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3684  /* IsScaledReg */ true);
3685 }
3686 
3687 /// \brief Helper function for LSRInstance::GenerateConstantOffsets.
3688 void LSRInstance::GenerateConstantOffsetsImpl(
3689  LSRUse &LU, unsigned LUIdx, const Formula &Base,
3690  const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3691  const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3692  for (int64_t Offset : Worklist) {
3693  Formula F = Base;
3694  F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3695  if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
3696  LU.AccessTy, F)) {
3697  // Add the offset to the base register.
3698  const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
3699  // If it cancelled out, drop the base register, otherwise update it.
3700  if (NewG->isZero()) {
3701  if (IsScaledReg) {
3702  F.Scale = 0;
3703  F.ScaledReg = nullptr;
3704  } else
3705  F.deleteBaseReg(F.BaseRegs[Idx]);
3706  F.canonicalize(*L);
3707  } else if (IsScaledReg)
3708  F.ScaledReg = NewG;
3709  else
3710  F.BaseRegs[Idx] = NewG;
3711 
3712  (void)InsertFormula(LU, LUIdx, F);
3713  }
3714  }
3715 
3716  int64_t Imm = ExtractImmediate(G, SE);
3717  if (G->isZero() || Imm == 0)
3718  return;
3719  Formula F = Base;
3720  F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3721  if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3722  return;
3723  if (IsScaledReg)
3724  F.ScaledReg = G;
3725  else
3726  F.BaseRegs[Idx] = G;
3727  (void)InsertFormula(LU, LUIdx, F);
3728 }
3729 
3730 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3731 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3732  Formula Base) {
3733  // TODO: For now, just add the min and max offset, because it usually isn't
3734  // worthwhile looking at everything inbetween.
3735  SmallVector<int64_t, 2> Worklist;
3736  Worklist.push_back(LU.MinOffset);
3737  if (LU.MaxOffset != LU.MinOffset)
3738  Worklist.push_back(LU.MaxOffset);
3739 
3740  for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3741  GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3742  if (Base.Scale == 1)
3743  GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3744  /* IsScaledReg */ true);
3745 }
3746 
3747 /// For ICmpZero, check to see if we can scale up the comparison. For example, x
3748 /// == y -> x*c == y*c.
3749 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3750  Formula Base) {
3751  if (LU.Kind != LSRUse::ICmpZero) return;
3752 
3753  // Determine the integer type for the base formula.
3754  Type *IntTy = Base.getType();
3755  if (!IntTy) return;
3756  if (SE.getTypeSizeInBits(IntTy) > 64) return;
3757 
3758  // Don't do this if there is more than one offset.
3759  if (LU.MinOffset != LU.MaxOffset) return;
3760 
3761  // Check if transformation is valid. It is illegal to multiply pointer.
3762  if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
3763  return;
3764  for (const SCEV *BaseReg : Base.BaseRegs)
3765  if (BaseReg->getType()->isPointerTy())
3766  return;
3767  assert(!Base.BaseGV && "ICmpZero use is not legal!");
3768 
3769  // Check each interesting stride.
3770  for (int64_t Factor : Factors) {
3771  // Check that the multiplication doesn't overflow.
3772  if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1)
3773  continue;
3774  int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3775  if (NewBaseOffset / Factor != Base.BaseOffset)
3776  continue;
3777  // If the offset will be truncated at this use, check that it is in bounds.
3778  if (!IntTy->isPointerTy() &&
3779  !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3780  continue;
3781 
3782  // Check that multiplying with the use offset doesn't overflow.
3783  int64_t Offset = LU.MinOffset;
3784  if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1)
3785  continue;
3786  Offset = (uint64_t)Offset * Factor;
3787  if (Offset / Factor != LU.MinOffset)
3788  continue;
3789  // If the offset will be truncated at this use, check that it is in bounds.
3790  if (!IntTy->isPointerTy() &&
3791  !ConstantInt::isValueValidForType(IntTy, Offset))
3792  continue;
3793 
3794  Formula F = Base;
3795  F.BaseOffset = NewBaseOffset;
3796 
3797  // Check that this scale is legal.
3798  if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3799  continue;
3800 
3801  // Compensate for the use having MinOffset built into it.
3802  F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3803 
3804  const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3805 
3806  // Check that multiplying with each base register doesn't overflow.
3807  for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3808  F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
3809  if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3810  goto next;
3811  }
3812 
3813  // Check that multiplying with the scaled register doesn't overflow.
3814  if (F.ScaledReg) {
3815  F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
3816  if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3817  continue;
3818  }
3819 
3820  // Check that multiplying with the unfolded offset doesn't overflow.
3821  if (F.UnfoldedOffset != 0) {
3822  if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() &&
3823  Factor == -1)
3824  continue;
3825  F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3826  if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3827  continue;
3828  // If the offset will be truncated, check that it is in bounds.
3829  if (!IntTy->isPointerTy() &&
3830  !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3831  continue;
3832  }
3833 
3834  // If we make it here and it's legal, add it.
3835  (void)InsertFormula(LU, LUIdx, F);
3836  next:;
3837  }
3838 }
3839 
3840 /// Generate stride factor reuse formulae by making use of scaled-offset address
3841 /// modes, for example.
3842 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
3843  // Determine the integer type for the base formula.
3844  Type *IntTy = Base.getType();
3845  if (!IntTy) return;
3846 
3847  // If this Formula already has a scaled register, we can't add another one.
3848  // Try to unscale the formula to generate a better scale.
3849  if (Base.Scale != 0 && !Base.unscale())
3850  return;
3851 
3852  assert(Base.Scale == 0 && "unscale did not did its job!");
3853 
3854  // Check each interesting stride.
3855  for (int64_t Factor : Factors) {
3856  Base.Scale = Factor;
3857  Base.HasBaseReg = Base.BaseRegs.size() > 1;
3858  // Check whether this scale is going to be legal.
3859  if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3860  Base)) {
3861  // As a special-case, handle special out-of-loop Basic users specially.
3862  // TODO: Reconsider this special case.
3863  if (LU.Kind == LSRUse::Basic &&
3864  isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3865  LU.AccessTy, Base) &&
3866  LU.AllFixupsOutsideLoop)
3867  LU.Kind = LSRUse::Special;
3868  else
3869  continue;
3870  }
3871  // For an ICmpZero, negating a solitary base register won't lead to
3872  // new solutions.
3873  if (LU.Kind == LSRUse::ICmpZero &&
3874  !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3875  continue;
3876  // For each addrec base reg, if its loop is current loop, apply the scale.
3877  for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
3878  const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]);
3879  if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {
3880  const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3881  if (FactorS->isZero())
3882  continue;
3883  // Divide out the factor, ignoring high bits, since we'll be
3884  // scaling the value back up in the end.
3885  if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
3886  // TODO: This could be optimized to avoid all the copying.
3887  Formula F = Base;
3888  F.ScaledReg = Quotient;
3889  F.deleteBaseReg(F.BaseRegs[i]);
3890  // The canonical representation of 1*reg is reg, which is already in
3891  // Base. In that case, do not try to insert the formula, it will be
3892  // rejected anyway.
3893  if (F.Scale == 1 && (F.BaseRegs.empty() ||
3894  (AR->getLoop() != L && LU.AllFixupsOutsideLoop)))
3895  continue;
3896  // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
3897  // non canonical Formula with ScaledReg's loop not being L.
3898  if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
3899  F.canonicalize(*L);
3900  (void)InsertFormula(LU, LUIdx, F);
3901  }
3902  }
3903  }
3904  }
3905 }
3906 
3907 /// Generate reuse formulae from different IV types.
3908 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
3909  // Don't bother truncating symbolic values.
3910  if (Base.BaseGV) return;
3911 
3912  // Determine the integer type for the base formula.
3913  Type *DstTy = Base.getType();
3914  if (!DstTy) return;
3915  DstTy = SE.getEffectiveSCEVType(DstTy);
3916 
3917  for (Type *SrcTy : Types) {
3918  if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
3919  Formula F = Base;
3920 
3921  if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
3922  for (const SCEV *&BaseReg : F.BaseRegs)
3923  BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
3924 
3925  // TODO: This assumes we've done basic processing on all uses and
3926  // have an idea what the register usage is.
3927  if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3928  continue;
3929 
3930  F.canonicalize(*L);
3931  (void)InsertFormula(LU, LUIdx, F);
3932  }
3933  }
3934 }
3935 
3936 namespace {
3937 
3938 /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
3939 /// modifications so that the search phase doesn't have to worry about the data
3940 /// structures moving underneath it.
3941 struct WorkItem {
3942  size_t LUIdx;
3943  int64_t Imm;
3944  const SCEV *OrigReg;
3945 
3946  WorkItem(size_t LI, int64_t I, const SCEV *R)
3947  : LUIdx(LI), Imm(I), OrigReg(R) {}
3948 
3949  void print(raw_ostream &OS) const;
3950  void dump() const;
3951 };
3952 
3953 } // end anonymous namespace
3954 
3955 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3956 void WorkItem::print(raw_ostream &OS) const {
3957  OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
3958  << " , add offset " << Imm;
3959 }
3960 
3961 LLVM_DUMP_METHOD void WorkItem::dump() const {
3962  print(errs()); errs() << '\n';
3963 }
3964 #endif
3965 
3966 /// Look for registers which are a constant distance apart and try to form reuse
3967 /// opportunities between them.
3968 void LSRInstance::GenerateCrossUseConstantOffsets() {
3969  // Group the registers by their value without any added constant offset.
3970  using ImmMapTy = std::map<int64_t, const SCEV *>;
3971 
3973  DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
3975  for (const SCEV *Use : RegUses) {
3976  const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
3977  int64_t Imm = ExtractImmediate(Reg, SE);
3978  auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
3979  if (Pair.second)
3980  Sequence.push_back(Reg);
3981  Pair.first->second.insert(std::make_pair(Imm, Use));
3982  UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
3983  }
3984 
3985  // Now examine each set of registers with the same base value. Build up
3986  // a list of work to do and do the work in a separate step so that we're
3987  // not adding formulae and register counts while we're searching.
3988  SmallVector<WorkItem, 32> WorkItems;
3989  SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
3990  for (const SCEV *Reg : Sequence) {
3991  const ImmMapTy &Imms = Map.find(Reg)->second;
3992 
3993  // It's not worthwhile looking for reuse if there's only one offset.
3994  if (Imms.size() == 1)
3995  continue;
3996 
3997  DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
3998  for (const auto &Entry : Imms)
3999  dbgs() << ' ' << Entry.first;
4000  dbgs() << '\n');
4001 
4002  // Examine each offset.
4003  for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
4004  J != JE; ++J) {
4005  const SCEV *OrigReg = J->second;
4006 
4007  int64_t JImm = J->first;
4008  const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
4009 
4010  if (!isa<SCEVConstant>(OrigReg) &&
4011  UsedByIndicesMap[Reg].count() == 1) {
4012  DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
4013  continue;
4014  }
4015 
4016  // Conservatively examine offsets between this orig reg a few selected
4017  // other orig regs.
4018  ImmMapTy::const_iterator OtherImms[] = {
4019  Imms.begin(), std::prev(Imms.end()),
4020  Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
4021  2)
4022  };
4023  for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
4024  ImmMapTy::const_iterator M = OtherImms[i];
4025  if (M == J || M == JE) continue;
4026 
4027  // Compute the difference between the two.
4028  int64_t Imm = (uint64_t)JImm - M->first;
4029  for (unsigned LUIdx : UsedByIndices.set_bits())
4030  // Make a memo of this use, offset, and register tuple.
4031  if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
4032  WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
4033  }
4034  }
4035  }
4036 
4037  Map.clear();
4038  Sequence.clear();
4039  UsedByIndicesMap.clear();
4040  UniqueItems.clear();
4041 
4042  // Now iterate through the worklist and add new formulae.
4043  for (const WorkItem &WI : WorkItems) {
4044  size_t LUIdx = WI.LUIdx;
4045  LSRUse &LU = Uses[LUIdx];
4046  int64_t Imm = WI.Imm;
4047  const SCEV *OrigReg = WI.OrigReg;
4048 
4049  Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
4050  const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
4051  unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
4052 
4053  // TODO: Use a more targeted data structure.
4054  for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
4055  Formula F = LU.Formulae[L];
4056  // FIXME: The code for the scaled and unscaled registers looks
4057  // very similar but slightly different. Investigate if they
4058  // could be merged. That way, we would not have to unscale the
4059  // Formula.
4060  F.unscale();
4061  // Use the immediate in the scaled register.
4062  if (F.ScaledReg == OrigReg) {
4063  int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
4064  // Don't create 50 + reg(-50).
4065  if (F.referencesReg(SE.getSCEV(
4066  ConstantInt::get(IntTy, -(uint64_t)Offset))))
4067  continue;
4068  Formula NewF = F;
4069  NewF.BaseOffset = Offset;
4070  if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4071  NewF))
4072  continue;
4073  NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
4074 
4075  // If the new scale is a constant in a register, and adding the constant
4076  // value to the immediate would produce a value closer to zero than the
4077  // immediate itself, then the formula isn't worthwhile.
4078  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
4079  if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
4080  (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
4081  .ule(std::abs(NewF.BaseOffset)))
4082  continue;
4083 
4084  // OK, looks good.
4085  NewF.canonicalize(*this->L);
4086  (void)InsertFormula(LU, LUIdx, NewF);
4087  } else {
4088  // Use the immediate in a base register.
4089  for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
4090  const SCEV *BaseReg = F.BaseRegs[N];
4091  if (BaseReg != OrigReg)
4092  continue;
4093  Formula NewF = F;
4094  NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
4095  if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
4096  LU.Kind, LU.AccessTy, NewF)) {
4097  if (TTI.shouldFavorPostInc() &&
4098  mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE))
4099  continue;
4100  if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
4101  continue;
4102  NewF = F;
4103  NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
4104  }
4105  NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
4106 
4107  // If the new formula has a constant in a register, and adding the
4108  // constant value to the immediate would produce a value closer to
4109  // zero than the immediate itself, then the formula isn't worthwhile.
4110  for (const SCEV *NewReg : NewF.BaseRegs)
4111  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
4112  if ((C->getAPInt() + NewF.BaseOffset)
4113  .abs()
4114  .slt(std::abs(NewF.BaseOffset)) &&
4115  (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >=
4116  countTrailingZeros<uint64_t>(NewF.BaseOffset))
4117  goto skip_formula;
4118 
4119  // Ok, looks good.
4120  NewF.canonicalize(*this->L);
4121  (void)InsertFormula(LU, LUIdx, NewF);
4122  break;
4123  skip_formula:;
4124  }
4125  }
4126  }
4127  }
4128 }
4129 
4130 /// Generate formulae for each use.
4131 void
4132 LSRInstance::GenerateAllReuseFormulae() {
4133  // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
4134  // queries are more precise.
4135  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4136  LSRUse &LU = Uses[LUIdx];
4137  for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4138  GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4139  for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4140  GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4141  }
4142  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4143  LSRUse &LU = Uses[LUIdx];
4144  for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4145  GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4146  for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4147  GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4148  for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4149  GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4150  for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4151  GenerateScales(LU, LUIdx, LU.Formulae[i]);
4152  }
4153  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4154  LSRUse &LU = Uses[LUIdx];
4155  for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4156  GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4157  }
4158 
4159  GenerateCrossUseConstantOffsets();
4160 
4161  DEBUG(dbgs() << "\n"
4162  "After generating reuse formulae:\n";
4163  print_uses(dbgs()));
4164 }
4165 
4166 /// If there are multiple formulae with the same set of registers used
4167 /// by other uses, pick the best one and delete the others.
4168 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4169  DenseSet<const SCEV *> VisitedRegs;
4172 #ifndef NDEBUG
4173  bool ChangedFormulae = false;
4174 #endif
4175 
4176  // Collect the best formula for each unique set of shared registers. This
4177  // is reset for each use.
4178  using BestFormulaeTy =
4179  DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>;
4180 
4181  BestFormulaeTy BestFormulae;
4182 
4183  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4184  LSRUse &LU = Uses[LUIdx];
4185  DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
4186 
4187  bool Any = false;
4188  for (size_t FIdx = 0, NumForms = LU.Formulae.size();
4189  FIdx != NumForms; ++FIdx) {
4190  Formula &F = LU.Formulae[FIdx];
4191 
4192  // Some formulas are instant losers. For example, they may depend on
4193  // nonexistent AddRecs from other loops. These need to be filtered
4194  // immediately, otherwise heuristics could choose them over others leading
4195  // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
4196  // avoids the need to recompute this information across formulae using the
4197  // same bad AddRec. Passing LoserRegs is also essential unless we remove
4198  // the corresponding bad register from the Regs set.
4199  Cost CostF;
4200  Regs.clear();
4201  CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, SE, DT, LU, &LoserRegs);
4202  if (CostF.isLoser()) {
4203  // During initial formula generation, undesirable formulae are generated
4204  // by uses within other loops that have some non-trivial address mode or
4205  // use the postinc form of the IV. LSR needs to provide these formulae
4206  // as the basis of rediscovering the desired formula that uses an AddRec
4207  // corresponding to the existing phi. Once all formulae have been
4208  // generated, these initial losers may be pruned.
4209  DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
4210  dbgs() << "\n");
4211  }
4212  else {
4214  for (const SCEV *Reg : F.BaseRegs) {
4215  if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4216  Key.push_back(Reg);
4217  }
4218  if (F.ScaledReg &&
4219  RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4220  Key.push_back(F.ScaledReg);
4221  // Unstable sort by host order ok, because this is only used for
4222  // uniquifying.
4223  llvm::sort(Key.begin(), Key.end());
4224 
4225  std::pair<BestFormulaeTy::const_iterator, bool> P =
4226  BestFormulae.insert(std::make_pair(Key, FIdx));
4227  if (P.second)
4228  continue;
4229 
4230  Formula &Best = LU.Formulae[P.first->second];
4231 
4232  Cost CostBest;
4233  Regs.clear();
4234  CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, SE, DT, LU);
4235  if (CostF.isLess(CostBest, TTI))
4236  std::swap(F, Best);
4237  DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
4238  dbgs() << "\n"
4239  " in favor of formula "; Best.print(dbgs());
4240  dbgs() << '\n');
4241  }
4242 #ifndef NDEBUG
4243  ChangedFormulae = true;
4244 #endif
4245  LU.DeleteFormula(F);
4246  --FIdx;
4247  --NumForms;
4248  Any = true;
4249  }
4250 
4251  // Now that we've filtered out some formulae, recompute the Regs set.
4252  if (Any)
4253  LU.RecomputeRegs(LUIdx, RegUses);
4254 
4255  // Reset this to prepare for the next use.
4256  BestFormulae.clear();
4257  }
4258 
4259  DEBUG(if (ChangedFormulae) {
4260  dbgs() << "\n"
4261  "After filtering out undesirable candidates:\n";
4262  print_uses(dbgs());
4263  });
4264 }
4265 
4266 // This is a rough guess that seems to work fairly well.
4268 
4269 /// Estimate the worst-case number of solutions the solver might have to
4270 /// consider. It almost never considers this many solutions because it prune the
4271 /// search space, but the pruning isn't always sufficient.
4272 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
4273  size_t Power = 1;
4274  for (const LSRUse &LU : Uses) {
4275  size_t FSize = LU.Formulae.size();
4276  if (FSize >= ComplexityLimit) {
4277  Power = ComplexityLimit;
4278  break;
4279  }
4280  Power *= FSize;
4281  if (Power >= ComplexityLimit)
4282  break;
4283  }
4284  return Power;
4285 }
4286 
4287 /// When one formula uses a superset of the registers of another formula, it
4288 /// won't help reduce register pressure (though it may not necessarily hurt
4289 /// register pressure); remove it to simplify the system.
4290 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4291  if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4292  DEBUG(dbgs() << "The search space is too complex.\n");
4293 
4294  DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4295  "which use a superset of registers used by other "
4296  "formulae.\n");
4297 
4298  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4299  LSRUse &LU = Uses[LUIdx];
4300  bool Any = false;
4301  for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4302  Formula &F = LU.Formulae[i];
4303  // Look for a formula with a constant or GV in a register. If the use
4304  // also has a formula with that same value in an immediate field,
4305  // delete the one that uses a register.
4307  I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4308  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4309  Formula NewF = F;
4310  NewF.BaseOffset += C->getValue()->getSExtValue();
4311  NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4312  (I - F.BaseRegs.begin()));
4313  if (LU.HasFormulaWithSameRegs(NewF)) {
4314  DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4315  LU.DeleteFormula(F);
4316  --i;
4317  --e;
4318  Any = true;
4319  break;
4320  }
4321  } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4322  if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4323  if (!F.BaseGV) {
4324  Formula NewF = F;
4325  NewF.BaseGV = GV;
4326  NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4327  (I - F.BaseRegs.begin()));
4328  if (LU.HasFormulaWithSameRegs(NewF)) {
4329  DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4330  dbgs() << '\n');
4331  LU.DeleteFormula(F);
4332  --i;
4333  --e;
4334  Any = true;
4335  break;
4336  }
4337  }
4338  }
4339  }
4340  }
4341  if (Any)
4342  LU.RecomputeRegs(LUIdx, RegUses);
4343  }
4344 
4345  DEBUG(dbgs() << "After pre-selection:\n";
4346  print_uses(dbgs()));
4347  }
4348 }
4349 
4350 /// When there are many registers for expressions like A, A+1, A+2, etc.,
4351 /// allocate a single register for them.
4352 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4353  if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4354  return;
4355 
4356  DEBUG(dbgs() << "The search space is too complex.\n"
4357  "Narrowing the search space by assuming that uses separated "
4358  "by a constant offset will use the same registers.\n");
4359 
4360  // This is especially useful for unrolled loops.
4361 
4362  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4363  LSRUse &LU = Uses[LUIdx];
4364  for (const Formula &F : LU.Formulae) {
4365  if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4366  continue;
4367 
4368  LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4369  if (!LUThatHas)
4370  continue;
4371 
4372  if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4373  LU.Kind, LU.AccessTy))
4374  continue;
4375 
4376  DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
4377 
4378  LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4379 
4380  // Transfer the fixups of LU to LUThatHas.
4381  for (LSRFixup &Fixup : LU.Fixups) {
4382  Fixup.Offset += F.BaseOffset;
4383  LUThatHas->pushFixup(Fixup);
4384  DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4385  }
4386 
4387  // Delete formulae from the new use which are no longer legal.
4388  bool Any = false;
4389  for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4390  Formula &F = LUThatHas->Formulae[i];
4391  if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4392  LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4393  DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4394  dbgs() << '\n');
4395  LUThatHas->DeleteFormula(F);
4396  --i;
4397  --e;
4398  Any = true;
4399  }
4400  }
4401 
4402  if (Any)
4403  LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4404 
4405  // Delete the old use.
4406  DeleteUse(LU, LUIdx);
4407  --LUIdx;
4408  --NumUses;
4409  break;
4410  }
4411  }
4412 
4413  DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4414 }
4415 
4416 /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4417 /// we've done more filtering, as it may be able to find more formulae to
4418 /// eliminate.
4419 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4420  if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4421  DEBUG(dbgs() << "The search space is too complex.\n");
4422 
4423  DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4424  "undesirable dedicated registers.\n");
4425 
4426  FilterOutUndesirableDedicatedRegisters();
4427 
4428  DEBUG(dbgs() << "After pre-selection:\n";
4429  print_uses(dbgs()));
4430  }
4431 }
4432 
4433 /// If a LSRUse has multiple formulae with the same ScaledReg and Scale.
4434 /// Pick the best one and delete the others.
4435 /// This narrowing heuristic is to keep as many formulae with different
4436 /// Scale and ScaledReg pair as possible while narrowing the search space.
4437 /// The benefit is that it is more likely to find out a better solution
4438 /// from a formulae set with more Scale and ScaledReg variations than
4439 /// a formulae set with the same Scale and ScaledReg. The picking winner
4440 /// reg heurstic will often keep the formulae with the same Scale and
4441 /// ScaledReg and filter others, and we want to avoid that if possible.
4442 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
4443  if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4444  return;
4445 
4446  DEBUG(dbgs() << "The search space is too complex.\n"
4447  "Narrowing the search space by choosing the best Formula "
4448  "from the Formulae with the same Scale and ScaledReg.\n");
4449 
4450  // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse.
4451  using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>;
4452 
4453  BestFormulaeTy BestFormulae;
4454 #ifndef NDEBUG
4455  bool ChangedFormulae = false;
4456 #endif
4457  DenseSet<const SCEV *> VisitedRegs;
4459 
4460  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4461  LSRUse &LU = Uses[LUIdx];
4462  DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
4463 
4464  // Return true if Formula FA is better than Formula FB.
4465  auto IsBetterThan = [&](Formula &FA, Formula &FB) {
4466  // First we will try to choose the Formula with fewer new registers.
4467  // For a register used by current Formula, the more the register is
4468  // shared among LSRUses, the less we increase the register number
4469  // counter of the formula.
4470  size_t FARegNum = 0;
4471  for (const SCEV *Reg : FA.BaseRegs) {
4472  const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4473  FARegNum += (NumUses - UsedByIndices.count() + 1);
4474  }
4475  size_t FBRegNum = 0;
4476  for (const SCEV *Reg : FB.BaseRegs) {
4477  const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4478  FBRegNum += (NumUses - UsedByIndices.count() + 1);
4479  }
4480  if (FARegNum != FBRegNum)
4481  return FARegNum < FBRegNum;
4482 
4483  // If the new register numbers are the same, choose the Formula with
4484  // less Cost.
4485  Cost CostFA, CostFB;
4486  Regs.clear();
4487  CostFA.RateFormula(TTI, FA, Regs, VisitedRegs, L, SE, DT, LU);
4488  Regs.clear();
4489  CostFB.RateFormula(TTI, FB, Regs, VisitedRegs, L, SE, DT, LU);
4490  return CostFA.isLess(CostFB, TTI);
4491  };
4492 
4493  bool Any = false;
4494  for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4495  ++FIdx) {
4496  Formula &F = LU.Formulae[FIdx];
4497  if (!F.ScaledReg)
4498  continue;
4499  auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});
4500  if (P.second)
4501  continue;
4502 
4503  Formula &Best = LU.Formulae[P.first->second];
4504  if (IsBetterThan(F, Best))
4505  std::swap(F, Best);
4506  DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
4507  dbgs() << "\n"
4508  " in favor of formula ";
4509  Best.print(dbgs()); dbgs() << '\n');
4510 #ifndef NDEBUG
4511  ChangedFormulae = true;
4512 #endif
4513  LU.DeleteFormula(F);
4514  --FIdx;
4515  --NumForms;
4516  Any = true;
4517  }
4518  if (Any)
4519  LU.RecomputeRegs(LUIdx, RegUses);
4520 
4521  // Reset this to prepare for the next use.
4522  BestFormulae.clear();
4523  }
4524 
4525  DEBUG(if (ChangedFormulae) {
4526  dbgs() << "\n"
4527  "After filtering out undesirable candidates:\n";
4528  print_uses(dbgs());
4529  });
4530 }
4531 
4532 /// The function delete formulas with high registers number expectation.
4533 /// Assuming we don't know the value of each formula (already delete
4534 /// all inefficient), generate probability of not selecting for each
4535 /// register.
4536 /// For example,
4537 /// Use1:
4538 /// reg(a) + reg({0,+,1})
4539 /// reg(a) + reg({-1,+,1}) + 1
4540 /// reg({a,+,1})
4541 /// Use2:
4542 /// reg(b) + reg({0,+,1})
4543 /// reg(b) + reg({-1,+,1}) + 1
4544 /// reg({b,+,1})
4545 /// Use3:
4546 /// reg(c) + reg(b) + reg({0,+,1})
4547 /// reg(c) + reg({b,+,1})
4548 ///
4549 /// Probability of not selecting
4550 /// Use1 Use2 Use3
4551 /// reg(a) (1/3) * 1 * 1
4552 /// reg(b) 1 * (1/3) * (1/2)
4553 /// reg({0,+,1}) (2/3) * (2/3) * (1/2)
4554 /// reg({-1,+,1}) (2/3) * (2/3) * 1
4555 /// reg({a,+,1}) (2/3) * 1 * 1
4556 /// reg({b,+,1}) 1 * (2/3) * (2/3)
4557 /// reg(c) 1 * 1 * 0
4558 ///
4559 /// Now count registers number mathematical expectation for each formula:
4560 /// Note that for each use we exclude probability if not selecting for the use.
4561 /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding
4562 /// probabilty 1/3 of not selecting for Use1).
4563 /// Use1:
4564 /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted
4565 /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted
4566 /// reg({a,+,1}) 1
4567 /// Use2:
4568 /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted
4569 /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted
4570 /// reg({b,+,1}) 2/3
4571 /// Use3:
4572 /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted
4573 /// reg(c) + reg({b,+,1}) 1 + 2/3
4574 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4575  if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4576  return;
4577  // Ok, we have too many of formulae on our hands to conveniently handle.
4578  // Use a rough heuristic to thin out the list.
4579 
4580  // Set of Regs wich will be 100% used in final solution.
4581  // Used in each formula of a solution (in example above this is reg(c)).
4582  // We can skip them in calculations.
4584  DEBUG(dbgs() << "The search space is too complex.\n");
4585 
4586  // Map each register to probability of not selecting
4588  for (const SCEV *Reg : RegUses) {
4589  if (UniqRegs.count(Reg))
4590  continue;
4591  float PNotSel = 1;
4592  for (const LSRUse &LU : Uses) {
4593  if (!LU.Regs.count(Reg))
4594  continue;
4595  float P = LU.getNotSelectedProbability(Reg);
4596  if (P != 0.0)
4597  PNotSel *= P;
4598  else
4599  UniqRegs.insert(Reg);
4600  }
4601  RegNumMap.insert(std::make_pair(Reg, PNotSel));
4602  }
4603 
4604  DEBUG(dbgs() << "Narrowing the search space by deleting costly formulas\n");
4605 
4606  // Delete formulas where registers number expectation is high.
4607  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4608  LSRUse &LU = Uses[LUIdx];
4609  // If nothing to delete - continue.
4610  if (LU.Formulae.size() < 2)
4611  continue;
4612  // This is temporary solution to test performance. Float should be
4613  // replaced with round independent type (based on integers) to avoid
4614  // different results for different target builds.
4615  float FMinRegNum = LU.Formulae[0].getNumRegs();
4616  float FMinARegNum = LU.Formulae[0].getNumRegs();
4617  size_t MinIdx = 0;
4618  for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4619  Formula &F = LU.Formulae[i];
4620  float FRegNum = 0;
4621  float FARegNum = 0;
4622  for (const SCEV *BaseReg : F.BaseRegs) {
4623  if (UniqRegs.count(BaseReg))
4624  continue;
4625  FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4626  if (isa<SCEVAddRecExpr>(BaseReg))
4627  FARegNum +=
4628  RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4629  }
4630  if (const SCEV *ScaledReg = F.ScaledReg) {
4631  if (!UniqRegs.count(ScaledReg)) {
4632  FRegNum +=
4633  RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4634  if (isa<SCEVAddRecExpr>(ScaledReg))
4635  FARegNum +=
4636  RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4637  }
4638  }
4639  if (FMinRegNum > FRegNum ||
4640  (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
4641  FMinRegNum = FRegNum;
4642  FMinARegNum = FARegNum;
4643  MinIdx = i;
4644  }
4645  }
4646  DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs());
4647  dbgs() << " with min reg num " << FMinRegNum << '\n');
4648  if (MinIdx != 0)
4649  std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
4650  while (LU.Formulae.size() != 1) {
4651  DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs());
4652  dbgs() << '\n');
4653  LU.Formulae.pop_back();
4654  }
4655  LU.RecomputeRegs(LUIdx, RegUses);
4656  assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula");
4657  Formula &F = LU.Formulae[0];
4658  DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n');
4659  // When we choose the formula, the regs become unique.
4660  UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
4661  if (F.ScaledReg)
4662  UniqRegs.insert(F.ScaledReg);
4663  }
4664  DEBUG(dbgs() << "After pre-selection:\n";
4665  print_uses(dbgs()));
4666 }
4667 
4668 /// Pick a register which seems likely to be profitable, and then in any use
4669 /// which has any reference to that register, delete all formulae which do not
4670 /// reference that register.
4671 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4672  // With all other options exhausted, loop until the system is simple
4673  // enough to handle.
4675  while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4676  // Ok, we have too many of formulae on our hands to conveniently handle.
4677  // Use a rough heuristic to thin out the list.
4678  DEBUG(dbgs() << "The search space is too complex.\n");
4679 
4680  // Pick the register which is used by the most LSRUses, which is likely
4681  // to be a good reuse register candidate.
4682  const SCEV *Best = nullptr;
4683  unsigned BestNum = 0;
4684  for (const SCEV *Reg : RegUses) {
4685  if (Taken.count(Reg))
4686  continue;
4687  if (!Best) {
4688  Best = Reg;
4689  BestNum = RegUses.getUsedByIndices(Reg).count();
4690  } else {
4691  unsigned Count = RegUses.getUsedByIndices(Reg).count();
4692  if (Count > BestNum) {
4693  Best = Reg;
4694  BestNum = Count;
4695  }
4696  }
4697  }
4698 
4699  DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
4700  << " will yield profitable reuse.\n");
4701  Taken.insert(Best);
4702 
4703  // In any use with formulae which references this register, delete formulae
4704  // which don't reference it.
4705  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4706  LSRUse &LU = Uses[LUIdx];
4707  if (!LU.Regs.count(Best)) continue;
4708 
4709  bool Any = false;
4710  for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4711  Formula &F = LU.Formulae[i];
4712  if (!F.referencesReg(Best)) {
4713  DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4714  LU.DeleteFormula(F);
4715  --e;
4716  --i;
4717  Any = true;
4718  assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
4719  continue;
4720  }
4721  }
4722 
4723  if (Any)
4724  LU.RecomputeRegs(LUIdx, RegUses);
4725  }
4726 
4727  DEBUG(dbgs() << "After pre-selection:\n";
4728  print_uses(dbgs()));
4729  }
4730 }
4731 
4732 /// If there are an extraordinary number of formulae to choose from, use some
4733 /// rough heuristics to prune down the number of formulae. This keeps the main
4734 /// solver from taking an extraordinary amount of time in some worst-case
4735 /// scenarios.
4736 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4737  NarrowSearchSpaceByDetectingSupersets();
4738  NarrowSearchSpaceByCollapsingUnrolledCode();
4739  NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4740  if (FilterSameScaledReg)
4741  NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
4742  if (LSRExpNarrow)
4743  NarrowSearchSpaceByDeletingCostlyFormulas();
4744  else
4745  NarrowSearchSpaceByPickingWinnerRegs();
4746 }
4747 
4748 /// This is the recursive solver.
4749 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4750  Cost &SolutionCost,
4752  const Cost &CurCost,
4753  const SmallPtrSet<const SCEV *, 16> &CurRegs,
4754  DenseSet<const SCEV *> &VisitedRegs) const {
4755  // Some ideas:
4756  // - prune more:
4757  // - use more aggressive filtering
4758  // - sort the formula so that the most profitable solutions are found first
4759  // - sort the uses too
4760  // - search faster:
4761  // - don't compute a cost, and then compare. compare while computing a cost
4762  // and bail early.
4763  // - track register sets with SmallBitVector
4764 
4765  const LSRUse &LU = Uses[Workspace.size()];
4766 
4767  // If this use references any register that's already a part of the
4768  // in-progress solution, consider it a requirement that a formula must
4769  // reference that register in order to be considered. This prunes out
4770  // unprofitable searching.
4772  for (const SCEV *S : CurRegs)
4773  if (LU.Regs.count(S))
4774  ReqRegs.insert(S);
4775 
4777  Cost NewCost;
4778  for (const Formula &F : LU.Formulae) {
4779  // Ignore formulae which may not be ideal in terms of register reuse of
4780  // ReqRegs. The formula should use all required registers before
4781  // introducing new ones.
4782  int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
4783  for (const SCEV *Reg : ReqRegs) {
4784  if ((F.ScaledReg && F.ScaledReg == Reg) ||
4785  is_contained(F.BaseRegs, Reg)) {
4786  --NumReqRegsToFind;
4787  if (NumReqRegsToFind == 0)
4788  break;
4789  }
4790  }
4791  if (NumReqRegsToFind != 0) {
4792  // If none of the formulae satisfied the required registers, then we could
4793  // clear ReqRegs and try again. Currently, we simply give up in this case.
4794  continue;
4795  }
4796 
4797  // Evaluate the cost of the current formula. If it's already worse than
4798  // the current best, prune the search at that point.
4799  NewCost = CurCost;
4800  NewRegs = CurRegs;
4801  NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, SE, DT, LU);
4802  if (NewCost.isLess(SolutionCost, TTI)) {
4803  Workspace.push_back(&F);
4804  if (Workspace.size() != Uses.size()) {
4805  SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4806  NewRegs, VisitedRegs);
4807  if (F.getNumRegs() == 1 && Workspace.size() == 1)
4808  VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4809  } else {
4810  DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
4811  dbgs() << ".\n Regs:";
4812  for (const SCEV *S : NewRegs)
4813  dbgs() << ' ' << *S;
4814  dbgs() << '\n');
4815 
4816  SolutionCost = NewCost;
4817  Solution = Workspace;
4818  }
4819  Workspace.pop_back();
4820  }
4821  }
4822 }
4823 
4824 /// Choose one formula from each use. Return the results in the given Solution
4825 /// vector.
4826 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
4828  Cost SolutionCost;
4829  SolutionCost.Lose();
4830  Cost CurCost;
4832  DenseSet<const SCEV *> VisitedRegs;
4833  Workspace.reserve(Uses.size());
4834 
4835  // SolveRecurse does all the work.
4836  SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4837  CurRegs, VisitedRegs);
4838  if (Solution.empty()) {
4839  DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
4840  return;
4841  }
4842 
4843  // Ok, we've now made all our decisions.
4844  DEBUG(dbgs() << "\n"
4845  "The chosen solution requires "; SolutionCost.print(dbgs());
4846  dbgs() << ":\n";
4847  for (size_t i = 0, e = Uses.size(); i != e; ++i) {
4848  dbgs() << " ";
4849  Uses[i].print(dbgs());
4850  dbgs() << "\n"
4851  " ";
4852  Solution[i]->print(dbgs());
4853  dbgs() << '\n';
4854  });
4855 
4856  assert(Solution.size() == Uses.size() && "Malformed solution!");
4857 }
4858 
4859 /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
4860 /// we can go while still being dominated by the input positions. This helps
4861 /// canonicalize the insert position, which encourages sharing.
4863 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
4864  const SmallVectorImpl<Instruction *> &Inputs)
4865  const {
4866  Instruction *Tentative = &*IP;
4867  while (true) {
4868  bool AllDominate = true;
4869  Instruction *BetterPos = nullptr;
4870  // Don't bother attempting to insert before a catchswitch, their basic block
4871  // cannot have other non-PHI instructions.
4872  if (isa<CatchSwitchInst>(Tentative))
4873  return IP;
4874 
4875  for (Instruction *Inst : Inputs) {
4876  if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
4877  AllDominate = false;
4878  break;
4879  }
4880  // Attempt to find an insert position in the middle of the block,
4881  // instead of at the end, so that it can be used for other expansions.
4882  if (Tentative->getParent() == Inst->getParent() &&
4883  (!BetterPos || !DT.dominates(Inst, BetterPos)))
4884  BetterPos = &*std::next(BasicBlock::iterator(Inst));
4885  }
4886  if (!AllDominate)
4887  break;
4888  if (BetterPos)
4889  IP = BetterPos->getIterator();
4890  else
4891  IP = Tentative->getIterator();
4892 
4893  const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4894  unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
4895 
4896  BasicBlock *IDom;
4897  for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
4898  if (!Rung) return IP;
4899  Rung = Rung->getIDom();
4900  if (!Rung) return IP;
4901  IDom = Rung->getBlock();
4902 
4903  // Don't climb into a loop though.
4904  const Loop *IDomLoop = LI.getLoopFor(IDom);
4905  unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
4906  if (IDomDepth <= IPLoopDepth &&
4907  (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4908  break;
4909  }
4910 
4911  Tentative = IDom->getTerminator();
4912  }
4913 
4914  return IP;
4915 }
4916 
4917 /// Determine an input position which will be dominated by the operands and
4918 /// which will dominate the result.
4920 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
4921  const LSRFixup &LF,
4922  const LSRUse &LU,
4923  SCEVExpander &Rewriter) const {
4924  // Collect some instructions which must be dominated by the
4925  // expanding replacement. These must be dominated by any operands that
4926  // will be required in the expansion.
4928  if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4929  Inputs.push_back(I);
4930  if (LU.Kind == LSRUse::ICmpZero)
4931  if (Instruction *I =
4932  dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4933  Inputs.push_back(I);
4934  if (LF.PostIncLoops.count(L)) {
4935  if (LF.isUseFullyOutsideLoop(L))
4936  Inputs.push_back(L->getLoopLatch()->getTerminator());
4937  else
4938  Inputs.push_back(IVIncInsertPos);
4939  }
4940  // The expansion must also be dominated by the increment positions of any
4941  // loops it for which it is using post-inc mode.
4942  for (const Loop *PIL : LF.PostIncLoops) {
4943  if (PIL == L) continue;
4944 
4945  // Be dominated by the loop exit.
4946  SmallVector<BasicBlock *, 4> ExitingBlocks;
4947  PIL->getExitingBlocks(ExitingBlocks);
4948  if (!ExitingBlocks.empty()) {
4949  BasicBlock *BB = ExitingBlocks[0];
4950  for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
4951  BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
4952  Inputs.push_back(BB->getTerminator());
4953  }
4954  }
4955 
4956  assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
4957  && !isa<DbgInfoIntrinsic>(LowestIP) &&
4958  "Insertion point must be a normal instruction");
4959 
4960  // Then, climb up the immediate dominator tree as far as we can go while
4961  // still being dominated by the input positions.
4962  BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
4963 
4964  // Don't insert instructions before PHI nodes.
4965  while (isa<PHINode>(IP)) ++IP;
4966 
4967  // Ignore landingpad instructions.
4968  while (IP->isEHPad()) ++IP;
4969 
4970  // Ignore debug intrinsics.
4971  while (isa<DbgInfoIntrinsic>(IP)) ++IP;
4972 
4973  // Set IP below instructions recently inserted by SCEVExpander. This keeps the
4974  // IP consistent across expansions and allows the previously inserted
4975  // instructions to be reused by subsequent expansion.
4976  while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
4977  ++IP;
4978 
4979  return IP;
4980 }
4981 
4982 /// Emit instructions for the leading candidate expression for this LSRUse (this
4983 /// is called "expanding").
4984 Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF,
4985  const Formula &F, BasicBlock::iterator IP,
4986  SCEVExpander &Rewriter,
4987  SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
4988  if (LU.RigidFormula)
4989  return LF.OperandValToReplace;
4990 
4991  // Determine an input position which will be dominated by the operands and
4992  // which will dominate the result.
4993  IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
4994  Rewriter.setInsertPoint(&*IP);
4995 
4996  // Inform the Rewriter if we have a post-increment use, so that it can
4997  // perform an advantageous expansion.
4998  Rewriter.setPostInc(LF.PostIncLoops);
4999 
5000  // This is the type that the user actually needs.
5001  Type *OpTy = LF.OperandValToReplace->getType();
5002  // This will be the type that we'll initially expand to.
5003  Type *Ty = F.getType();
5004  if (!Ty)
5005  // No type known; just expand directly to the ultimate type.
5006  Ty = OpTy;
5007  else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
5008  // Expand directly to the ultimate type if it's the right size.
5009  Ty = OpTy;
5010  // This is the type to do integer arithmetic in.
5011  Type *IntTy = SE.getEffectiveSCEVType(Ty);
5012 
5013  // Build up a list of operands to add together to form the full base.
5015 
5016  // Expand the BaseRegs portion.
5017  for (const SCEV *Reg : F.BaseRegs) {
5018  assert(!Reg->isZero() && "Zero allocated in a base register!");
5019 
5020  // If we're expanding for a post-inc user, make the post-inc adjustment.
5021  Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE);
5022  Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr)));
5023  }
5024 
5025  // Expand the ScaledReg portion.
5026  Value *ICmpScaledV = nullptr;
5027  if (F.Scale != 0) {
5028  const SCEV *ScaledS = F.ScaledReg;
5029 
5030  // If we're expanding for a post-inc user, make the post-inc adjustment.
5031  PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
5032  ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE);
5033 
5034  if (LU.Kind == LSRUse::ICmpZero) {
5035  // Expand ScaleReg as if it was part of the base regs.
5036  if (F.Scale == 1)
5037  Ops.push_back(
5038  SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)));
5039  else {
5040  // An interesting way of "folding" with an icmp is to use a negated
5041  // scale, which we'll implement by inserting it into the other operand
5042  // of the icmp.
5043  assert(F.Scale == -1 &&
5044  "The only scale supported by ICmpZero uses is -1!");
5045  ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr);
5046  }
5047  } else {
5048  // Otherwise just expand the scaled register and an explicit scale,
5049  // which is expected to be matched as part of the address.
5050 
5051  // Flush the operand list to suppress SCEVExpander hoisting address modes.
5052  // Unless the addressing mode will not be folded.
5053  if (!Ops.empty() && LU.Kind == LSRUse::Address &&
5054  isAMCompletelyFolded(TTI, LU, F)) {
5055  Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr);
5056  Ops.clear();
5057  Ops.push_back(SE.getUnknown(FullV));
5058  }
5059  ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr));
5060  if (F.Scale != 1)
5061  ScaledS =
5062  SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
5063  Ops.push_back(ScaledS);
5064  }
5065  }
5066 
5067  // Expand the GV portion.
5068  if (F.BaseGV) {
5069  // Flush the operand list to suppress SCEVExpander hoisting.
5070  if (!Ops.empty()) {
5071  Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
5072  Ops.clear();
5073  Ops.push_back(SE.getUnknown(FullV));
5074  }
5075  Ops.push_back(SE.getUnknown(F.BaseGV));
5076  }
5077 
5078  // Flush the operand list to suppress SCEVExpander hoisting of both folded and
5079  // unfolded offsets. LSR assumes they both live next to their uses.
5080  if (!Ops.empty()) {
5081  Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
5082  Ops.clear();
5083  Ops.push_back(SE.getUnknown(FullV));
5084  }
5085 
5086  // Expand the immediate portion.
5087  int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
5088  if (Offset != 0) {
5089  if (LU.Kind == LSRUse::ICmpZero) {
5090  // The other interesting way of "folding" with an ICmpZero is to use a
5091  // negated immediate.
5092  if (!ICmpScaledV)
5093  ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
5094  else {
5095  Ops.push_back(SE.getUnknown(ICmpScaledV));
5096  ICmpScaledV = ConstantInt::get(IntTy, Offset);
5097  }
5098  } else {
5099  // Just add the immediate values. These again are expected to be matched
5100  // as part of the address.
5101  Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
5102  }
5103  }
5104 
5105  // Expand the unfolded offset portion.
5106  int64_t UnfoldedOffset = F.UnfoldedOffset;
5107  if (UnfoldedOffset != 0) {
5108  // Just add the immediate values.
5110  UnfoldedOffset)));
5111  }
5112 
5113  // Emit instructions summing all the operands.
5114  const SCEV *FullS = Ops.empty() ?
5115  SE.getConstant(IntTy, 0) :
5116  SE.getAddExpr(Ops);
5117  Value *FullV = Rewriter.expandCodeFor(FullS, Ty);
5118 
5119  // We're done expanding now, so reset the rewriter.
5120  Rewriter.clearPostInc();
5121 
5122  // An ICmpZero Formula represents an ICmp which we're handling as a
5123  // comparison against zero. Now that we've expanded an expression for that
5124  // form, update the ICmp's other operand.
5125  if (LU.Kind == LSRUse::ICmpZero) {
5126  ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
5127  DeadInsts.emplace_back(CI->getOperand(1));
5128  assert(!F.BaseGV && "ICmp does not support folding a global value and "
5129  "a scale at the same time!");
5130  if (F.Scale == -1) {
5131  if (ICmpScaledV->getType() != OpTy) {
5132  Instruction *Cast =
5133  CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
5134  OpTy, false),
5135  ICmpScaledV, OpTy, "tmp", CI);
5136  ICmpScaledV = Cast;
5137  }
5138  CI->setOperand(1, ICmpScaledV);
5139  } else {
5140  // A scale of 1 means that the scale has been expanded as part of the
5141  // base regs.
5142  assert((F.Scale == 0 || F.Scale == 1) &&
5143  "ICmp does not support folding a global value and "
5144  "a scale at the same time!");
5146  -(uint64_t)Offset);
5147  if (C->getType() != OpTy)
5149  OpTy, false),
5150  C, OpTy);
5151 
5152  CI->setOperand(1, C);
5153  }
5154  }
5155 
5156  return FullV;
5157 }
5158 
5159 /// Helper for Rewrite. PHI nodes are special because the use of their operands
5160 /// effectively happens in their predecessor blocks, so the expression may need
5161 /// to be expanded in multiple places.
5162 void LSRInstance::RewriteForPHI(
5163  PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F,
5164  SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5166  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5167  if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
5168  BasicBlock *BB = PN->getIncomingBlock(i);
5169 
5170  // If this is a critical edge, split the edge so that we do not insert
5171  // the code on all predecessor/successor paths. We do this unless this
5172  // is the canonical backedge for this loop, which complicates post-inc
5173  // users.
5174  if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
5175  !isa<IndirectBrInst>(BB->getTerminator()) &&
5176  !isa<CatchSwitchInst>(BB->getTerminator())) {
5177  BasicBlock *Parent = PN->getParent();
5178  Loop *PNLoop = LI.getLoopFor(Parent);
5179  if (!PNLoop || Parent != PNLoop->getHeader()) {
5180  // Split the critical edge.
5181  BasicBlock *NewBB = nullptr;
5182  if (!Parent->isLandingPad()) {
5183  NewBB = SplitCriticalEdge(BB, Parent,
5185  .setMergeIdenticalEdges()
5186  .setDontDeleteUselessPHIs());
5187  } else {
5189  SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI);
5190  NewBB = NewBBs[0];
5191  }
5192  // If NewBB==NULL, then SplitCriticalEdge refused to split because all
5193  // phi predecessors are identical. The simple thing to do is skip
5194  // splitting in this case rather than complicate the API.
5195  if (NewBB) {
5196  // If PN is outside of the loop and BB is in the loop, we want to
5197  // move the block to be immediately before the PHI block, not
5198  // immediately after BB.
5199  if (L->contains(BB) && !L->contains(PN))
5200  NewBB->moveBefore(PN->getParent());
5201 
5202  // Splitting the edge can reduce the number of PHI entries we have.
5203  e = PN->getNumIncomingValues();
5204  BB = NewBB;
5205  i = PN->getBasicBlockIndex(BB);
5206  }
5207  }
5208  }
5209 
5210  std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
5211  Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
5212  if (!Pair.second)
5213  PN->setIncomingValue(i, Pair.first->second);
5214  else {
5215  Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(),
5216  Rewriter, DeadInsts);
5217 
5218  // If this is reuse-by-noop-cast, insert the noop cast.
5219  Type *OpTy = LF.OperandValToReplace->getType();
5220  if (FullV->getType() != OpTy)
5221  FullV =
5223  OpTy, false),
5224  FullV, LF.OperandValToReplace->getType(),
5225  "tmp", BB->getTerminator());
5226 
5227  PN->setIncomingValue(i, FullV);
5228  Pair.first->second = FullV;
5229  }
5230  }
5231 }
5232 
5233 /// Emit instructions for the leading candidate expression for this LSRUse (this
5234 /// is called "expanding"), and update the UserInst to reference the newly
5235 /// expanded value.
5236 void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF,
5237  const Formula &F, SCEVExpander &Rewriter,
5238  SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5239  // First, find an insertion point that dominates UserInst. For PHI nodes,
5240  // find the nearest block which dominates all the relevant uses.
5241  if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
5242  RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
5243  } else {
5244  Value *FullV =
5245  Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
5246 
5247  // If this is reuse-by-noop-cast, insert the noop cast.
5248  Type *OpTy = LF.OperandValToReplace->getType();
5249  if (FullV->getType() != OpTy) {
5250  Instruction *Cast =
5251  CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
5252  FullV, OpTy, "tmp", LF.UserInst);
5253  FullV = Cast;
5254  }
5255 
5256  // Update the user. ICmpZero is handled specially here (for now) because
5257  // Expand may have updated one of the operands of the icmp already, and
5258  // its new value may happen to be equal to LF.OperandValToReplace, in
5259  // which case doing replaceUsesOfWith leads to replacing both operands
5260  // with the same value. TODO: Reorganize this.
5261  if (LU.Kind == LSRUse::ICmpZero)
5262  LF.UserInst->setOperand(0, FullV);
5263  else
5264  LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
5265  }
5266 
5267  DeadInsts.emplace_back(LF.OperandValToReplace);
5268 }
5269 
5270 /// Rewrite all the fixup locations with new values, following the chosen
5271 /// solution.
5272 void LSRInstance::ImplementSolution(
5273  const SmallVectorImpl<const Formula *> &Solution) {
5274  // Keep track of instructions we may have made dead, so that
5275  // we can remove them after we are done working.
5277 
5279  "lsr");
5280 #ifndef NDEBUG
5281  Rewriter.setDebugType(DEBUG_TYPE);
5282 #endif
5283  Rewriter.disableCanonicalMode();
5284  Rewriter.enableLSRMode();
5285  Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
5286 
5287  // Mark phi nodes that terminate chains so the expander tries to reuse them.
5288  for (const IVChain &Chain : IVChainVec) {
5289  if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
5290  Rewriter.setChainedPhi(PN);
5291  }
5292 
5293  // Expand the new value definitions and update the users.
5294  for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5295  for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
5296  Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
5297  Changed = true;
5298  }
5299 
5300  for (const IVChain &Chain : IVChainVec) {
5301  GenerateIVChain(Chain, Rewriter, DeadInsts);
5302  Changed = true;
5303  }
5304  // Clean up after ourselves. This must be done before deleting any
5305  // instructions.
5306  Rewriter.clear();
5307 
5308  Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
5309 }
5310 
5311 LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5312  DominatorTree &DT, LoopInfo &LI,
5313  const TargetTransformInfo &TTI)
5314  : IU(IU), SE(SE), DT(DT), LI(LI), TTI(TTI), L(L) {
5315  // If LoopSimplify form is not available, stay out of trouble.
5316  if (!L->isLoopSimplifyForm())
5317  return;
5318 
5319  // If there's no interesting work to be done, bail early.
5320  if (IU.empty()) return;
5321 
5322  // If there's too much analysis to be done, bail early. We won't be able to
5323  // model the problem anyway.
5324  unsigned NumUsers = 0;
5325  for (const IVStrideUse &U : IU) {
5326  if (++NumUsers > MaxIVUsers) {
5327  (void)U;
5328  DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
5329  return;
5330  }
5331  // Bail out if we have a PHI on an EHPad that gets a value from a
5332  // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is
5333  // no good place to stick any instructions.
5334  if (auto *PN = dyn_cast<PHINode>(U.getUser())) {
5335  auto *FirstNonPHI = PN->getParent()->getFirstNonPHI();
5336  if (isa<FuncletPadInst>(FirstNonPHI) ||
5337  isa<CatchSwitchInst>(FirstNonPHI))
5338  for (BasicBlock *PredBB : PN->blocks())
5339  if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
5340  return;
5341  }
5342  }
5343 
5344 #ifndef NDEBUG
5345  // All dominating loops must have preheaders, or SCEVExpander may not be able
5346  // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
5347  //
5348  // IVUsers analysis should only create users that are dominated by simple loop
5349  // headers. Since this loop should dominate all of its users, its user list
5350  // should be empty if this loop itself is not within a simple loop nest.
5351  for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
5352  Rung; Rung = Rung->getIDom()) {
5353  BasicBlock *BB = Rung->getBlock();
5354  const Loop *DomLoop = LI.getLoopFor(BB);
5355  if (DomLoop && DomLoop->getHeader() == BB) {
5356  assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
5357  }
5358  }
5359 #endif // DEBUG
5360 
5361  DEBUG(dbgs() << "\nLSR on loop ";
5362  L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
5363  dbgs() << ":\n");
5364 
5365  // First, perform some low-level loop optimizations.
5366  OptimizeShadowIV();
5367  OptimizeLoopTermCond();
5368 
5369  // If loop preparation eliminates all interesting IV users, bail.
5370  if (IU.empty()) return;
5371 
5372  // Skip nested loops until we can model them better with formulae.
5373  if (!L->empty()) {
5374  DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
5375  return;
5376  }
5377 
5378  // Start collecting data and preparing for the solver.
5379  CollectChains();
5380  CollectInterestingTypesAndFactors();
5381  CollectFixupsAndInitialFormulae();
5382  CollectLoopInvariantFixupsAndFormulae();
5383 
5384  assert(!Uses.empty() && "IVUsers reported at least one use");
5385  DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
5386  print_uses(dbgs()));
5387 
5388  // Now use the reuse data to generate a bunch of interesting ways
5389  // to formulate the values needed for the uses.
5390  GenerateAllReuseFormulae();
5391 
5392  FilterOutUndesirableDedicatedRegisters();
5393  NarrowSearchSpaceUsingHeuristics();
5394 
5396  Solve(Solution);
5397 
5398  // Release memory that is no longer needed.
5399  Factors.clear();
5400  Types.clear();
5401  RegUses.clear();
5402 
5403  if (Solution.empty())
5404  return;
5405 
5406 #ifndef NDEBUG
5407  // Formulae should be legal.
5408  for (const LSRUse &LU : Uses) {
5409  for (const Formula &F : LU.Formulae)
5410  assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
5411  F) && "Illegal formula generated!");
5412  };
5413 #endif
5414 
5415  // Now that we've decided what we want, make it so.
5416  ImplementSolution(Solution);
5417 }
5418 
5419 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5420 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
5421  if (Factors.empty() && Types.empty()) return;
5422 
5423  OS << "LSR has identified the following interesting factors and types: ";
5424  bool First = true;
5425 
5426  for (int64_t Factor : Factors) {
5427  if (!First) OS << ", ";
5428  First = false;
5429  OS << '*' << Factor;
5430  }
5431 
5432  for (Type *Ty : Types) {
5433  if (!First) OS << ", ";
5434  First = false;
5435  OS << '(' << *Ty << ')';
5436  }
5437  OS << '\n';
5438 }
5439 
5440 void LSRInstance::print_fixups(raw_ostream &OS) const {
5441  OS << "LSR is examining the following fixup sites:\n";
5442  for (const LSRUse &LU : Uses)
5443  for (const LSRFixup &LF : LU.Fixups) {
5444  dbgs() << " ";
5445  LF.print(OS);
5446  OS << '\n';
5447  }
5448 }
5449 
5450 void LSRInstance::print_uses(raw_ostream &OS) const {
5451  OS << "LSR is examining the following uses:\n";
5452  for (const LSRUse &LU : Uses) {
5453  dbgs() << " ";
5454  LU.print(OS);
5455  OS << '\n';
5456  for (const Formula &F : LU.Formulae) {
5457  OS << " ";
5458  F.print(OS);
5459  OS << '\n';
5460  }
5461  }
5462 }
5463 
5464 void LSRInstance::print(raw_ostream &OS) const {
5465  print_factors_and_types(OS);
5466  print_fixups(OS);
5467  print_uses(OS);
5468 }
5469 
5470 LLVM_DUMP_METHOD void LSRInstance::dump() const {
5471  print(errs()); errs() << '\n';
5472 }
5473 #endif
5474 
5475 namespace {
5476 
5477 class LoopStrengthReduce : public LoopPass {
5478 public:
5479  static char ID; // Pass ID, replacement for typeid
5480 
5481  LoopStrengthReduce();
5482 
5483 private:
5484  bool runOnLoop(Loop *L, LPPassManager &LPM) override;
5485  void getAnalysisUsage(AnalysisUsage &AU) const override;
5486 };
5487 
5488 } // end anonymous namespace
5489 
5490 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
5491  initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
5492 }
5493 
5494 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
5495  // We split critical edges, so we change the CFG. However, we do update
5496  // many analyses if they are around.
5498 
5506  // Requiring LoopSimplify a second time here prevents IVUsers from running
5507  // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5512 }
5513 
5515  DominatorTree &DT, LoopInfo &LI,
5516  const TargetTransformInfo &TTI) {
5517  bool Changed = false;
5518 
5519  // Run the main LSR transformation.
5520  Changed |= LSRInstance(L, IU, SE, DT, LI, TTI).getChanged();
5521 
5522  // Remove any extra phis created by processing inner loops.
5523  Changed |= DeleteDeadPHIs(L->getHeader());
5524  if (EnablePhiElim && L->isLoopSimplifyForm()) {
5526  const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
5527  SCEVExpander Rewriter(SE, DL, "lsr");
5528 #ifndef NDEBUG
5529  Rewriter.setDebugType(DEBUG_TYPE);
5530 #endif
5531  unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI);
5532  if (numFolded) {
5533  Changed = true;
5535  DeleteDeadPHIs(L->getHeader());
5536  }
5537  }
5538  return Changed;
5539 }
5540 
5541 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
5542  if (skipLoop(L))
5543  return false;
5544 
5545  auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5546  auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5547  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5548  auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5549  const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5550  *L->getHeader()->getParent());
5551  return ReduceLoopStrength(L, IU, SE, DT, LI, TTI);
5552 }
5553 
5554 PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,
5556  LPMUpdater &) {
5557  if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE,
5558  AR.DT, AR.LI, AR.TTI))
5559  return PreservedAnalyses::all();
5560 
5562 }
5563 
5564 char LoopStrengthReduce::ID = 0;
5565 
5566 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
5567  "Loop Strength Reduction", false, false)
5573 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5574 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
5575  "Loop Strength Reduction", false, false)
5576 
5577 Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V...
Definition: Constants.cpp:1234
uint64_t CallInst * C
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:245
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
iterator_range< use_iterator > uses()
Definition: Value.h:360
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:157
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:236
DiagnosticInfoOptimizationBase::Argument NV
typename SuperClass::const_iterator const_iterator
Definition: SmallVector.h:329
static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Return true if this AddRec is already a phi in its loop.
Pass * createLoopStrengthReducePass()
This is a &#39;bitvector&#39; (really, a variable-sized bit array), optimized for the case when the array is ...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
const SCEV * getConstant(ConstantInt *V)
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
bool isLegalAddImmediate(int64_t Imm) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:78
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition: APInt.cpp:1598
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:514
const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE)
Normalize S to be post-increment for all loops present in Loops.
static const size_t ComplexityLimit
Implements a dense probed hash-table based set.
Definition: DenseSet.h:221
unsigned getLoopDepth() const
Return the nesting level of this loop.
Definition: LoopInfo.h:92
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
The main scalar evolution driver.
bool isZero() const
Return true if the expression is a constant zero.
unsigned getNumberOfRegisters(bool Vector) const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:106
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:617
unsigned less than
Definition: InstrTypes.h:910
static const unsigned MaxIVUsers
MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for bail out...
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block...
void initializeLoopStrengthReducePass(PassRegistry &)
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
void setDebugType(const char *s)
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:846
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
static void dump(StringRef Title, SpillInfo const &Spills)
Definition: CoroFrame.cpp:298
static bool isCanonical(const MDString *S)
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
F(f)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
An instruction for reading from memory.
Definition: Instructions.h:164
bool canMacroFuseCmp() const
Return true if the target can fuse a compare and branch.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:677
Value * getCondition() const
iv Induction Variable Users
Definition: IVUsers.cpp:51
This defines the Use class.
void reserve(size_type N)
Definition: SmallVector.h:378
loop data prefetch