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