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