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