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