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