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