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