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