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