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