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