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