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