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