1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This transformation analyzes and transforms the induction variables (and
10 // computations derived from them) into forms suitable for efficient execution
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.
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:
23 // %i = phi [ 0, %entry ], [ %i.next, %latch ]
25 // %i.next = add %i, 1
26 // %c = icmp eq %i.next, %n
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.
35 // TODO: More sophistication in the way Formulae are generated and filtered.
37 // TODO: Handle multiple loops at a time.
39 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
42 // TODO: When truncation is free, truncate ICmp users' operands to make it a
43 // smaller encoding (on x86 at least).
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"
53 //===----------------------------------------------------------------------===//
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/TargetTransformInfo.h"
79 #include "llvm/Config/llvm-config.h"
80 #include "llvm/IR/BasicBlock.h"
81 #include "llvm/IR/Constant.h"
82 #include "llvm/IR/Constants.h"
83 #include "llvm/IR/DerivedTypes.h"
84 #include "llvm/IR/Dominators.h"
85 #include "llvm/IR/GlobalValue.h"
86 #include "llvm/IR/IRBuilder.h"
87 #include "llvm/IR/InstrTypes.h"
88 #include "llvm/IR/Instruction.h"
89 #include "llvm/IR/Instructions.h"
90 #include "llvm/IR/IntrinsicInst.h"
91 #include "llvm/IR/Intrinsics.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/OperandTraits.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PassManager.h"
96 #include "llvm/IR/Type.h"
97 #include "llvm/IR/Use.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/IR/ValueHandle.h"
101 #include "llvm/InitializePasses.h"
102 #include "llvm/Pass.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/Compiler.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/ErrorHandling.h"
108 #include "llvm/Support/MathExtras.h"
109 #include "llvm/Support/raw_ostream.h"
110 #include "llvm/Transforms/Scalar.h"
111 #include "llvm/Transforms/Utils.h"
112 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
113 #include "llvm/Transforms/Utils/Local.h"
114 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
126 using namespace llvm;
128 #define DEBUG_TYPE "loop-reduce"
130 /// MaxIVUsers is an arbitrary threshold that provides an early opportunity for
131 /// bail out. This threshold is far beyond the number of users that LSR can
132 /// conceivably solve, so it should not affect generated code, but catches the
133 /// worst cases before LSR burns too much compile time and stack space.
134 static const unsigned MaxIVUsers = 200;
136 // Temporary flag to cleanup congruent phis after LSR phi expansion.
137 // It's currently disabled until we can determine whether it's truly useful or
138 // not. The flag should be removed after the v3.0 release.
139 // This is now needed for ivchains.
140 static cl::opt<bool> EnablePhiElim(
141 "enable-lsr-phielim", cl::Hidden, cl::init(true),
142 cl::desc("Enable LSR phi elimination"));
144 // The flag adds instruction count to solutions cost comparision.
145 static cl::opt<bool> InsnsCost(
146 "lsr-insns-cost", cl::Hidden, cl::init(true),
147 cl::desc("Add instruction count to a LSR cost model"));
149 // Flag to choose how to narrow complex lsr solution
150 static cl::opt<bool> LSRExpNarrow(
151 "lsr-exp-narrow", cl::Hidden, cl::init(false),
152 cl::desc("Narrow LSR complex solution using"
153 " expectation of registers number"));
155 // Flag to narrow search space by filtering non-optimal formulae with
156 // the same ScaledReg and Scale.
157 static cl::opt<bool> FilterSameScaledReg(
158 "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true),
159 cl::desc("Narrow LSR search space by filtering non-optimal formulae"
160 " with the same ScaledReg and Scale"));
162 static cl::opt<bool> EnableBackedgeIndexing(
163 "lsr-backedge-indexing", cl::Hidden, cl::init(true),
164 cl::desc("Enable the generation of cross iteration indexed memops"));
166 static cl::opt<unsigned> ComplexityLimit(
167 "lsr-complexity-limit", cl::Hidden,
168 cl::init(std::numeric_limits<uint16_t>::max()),
169 cl::desc("LSR search space complexity limit"));
171 static cl::opt<unsigned> SetupCostDepthLimit(
172 "lsr-setupcost-depth-limit", cl::Hidden, cl::init(7),
173 cl::desc("The limit on recursion depth for LSRs setup cost"));
176 // Stress test IV chain generation.
177 static cl::opt<bool> StressIVChain(
178 "stress-ivchain", cl::Hidden, cl::init(false),
179 cl::desc("Stress test LSR IV chains"));
181 static bool StressIVChain = false;
187 /// Used in situations where the accessed memory type is unknown.
188 static const unsigned UnknownAddressSpace =
189 std::numeric_limits<unsigned>::max();
191 Type *MemTy = nullptr;
192 unsigned AddrSpace = UnknownAddressSpace;
194 MemAccessTy() = default;
195 MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
197 bool operator==(MemAccessTy Other) const {
198 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
201 bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
203 static MemAccessTy getUnknown(LLVMContext &Ctx,
204 unsigned AS = UnknownAddressSpace) {
205 return MemAccessTy(Type::getVoidTy(Ctx), AS);
208 Type *getType() { return MemTy; }
211 /// This class holds data which is used to order reuse candidates.
214 /// This represents the set of LSRUse indices which reference
215 /// a particular register.
216 SmallBitVector UsedByIndices;
218 void print(raw_ostream &OS) const;
222 } // end anonymous namespace
224 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
225 void RegSortData::print(raw_ostream &OS) const {
226 OS << "[NumUses=" << UsedByIndices.count() << ']';
229 LLVM_DUMP_METHOD void RegSortData::dump() const {
230 print(errs()); errs() << '\n';
236 /// Map register candidates to information about how they are used.
237 class RegUseTracker {
238 using RegUsesTy = DenseMap<const SCEV *, RegSortData>;
240 RegUsesTy RegUsesMap;
241 SmallVector<const SCEV *, 16> RegSequence;
244 void countRegister(const SCEV *Reg, size_t LUIdx);
245 void dropRegister(const SCEV *Reg, size_t LUIdx);
246 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
248 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
250 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
254 using iterator = SmallVectorImpl<const SCEV *>::iterator;
255 using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator;
257 iterator begin() { return RegSequence.begin(); }
258 iterator end() { return RegSequence.end(); }
259 const_iterator begin() const { return RegSequence.begin(); }
260 const_iterator end() const { return RegSequence.end(); }
263 } // end anonymous namespace
266 RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
267 std::pair<RegUsesTy::iterator, bool> Pair =
268 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
269 RegSortData &RSD = Pair.first->second;
271 RegSequence.push_back(Reg);
272 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
273 RSD.UsedByIndices.set(LUIdx);
277 RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
278 RegUsesTy::iterator It = RegUsesMap.find(Reg);
279 assert(It != RegUsesMap.end());
280 RegSortData &RSD = It->second;
281 assert(RSD.UsedByIndices.size() > LUIdx);
282 RSD.UsedByIndices.reset(LUIdx);
286 RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
287 assert(LUIdx <= LastLUIdx);
289 // Update RegUses. The data structure is not optimized for this purpose;
290 // we must iterate through it and update each of the bit vectors.
291 for (auto &Pair : RegUsesMap) {
292 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
293 if (LUIdx < UsedByIndices.size())
294 UsedByIndices[LUIdx] =
295 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
296 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
301 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
302 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
303 if (I == RegUsesMap.end())
305 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
306 int i = UsedByIndices.find_first();
307 if (i == -1) return false;
308 if ((size_t)i != LUIdx) return true;
309 return UsedByIndices.find_next(i) != -1;
312 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
313 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
314 assert(I != RegUsesMap.end() && "Unknown register!");
315 return I->second.UsedByIndices;
318 void RegUseTracker::clear() {
325 /// This class holds information that describes a formula for computing
326 /// satisfying a use. It may include broken-out immediates and scaled registers.
328 /// Global base address used for complex addressing.
329 GlobalValue *BaseGV = nullptr;
331 /// Base offset for complex addressing.
332 int64_t BaseOffset = 0;
334 /// Whether any complex addressing has a base register.
335 bool HasBaseReg = false;
337 /// The scale of any complex addressing.
340 /// The list of "base" registers for this use. When this is non-empty. The
341 /// canonical representation of a formula is
342 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
343 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
344 /// 3. The reg containing recurrent expr related with currect loop in the
345 /// formula should be put in the ScaledReg.
346 /// #1 enforces that the scaled register is always used when at least two
347 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
348 /// #2 enforces that 1 * reg is reg.
349 /// #3 ensures invariant regs with respect to current loop can be combined
350 /// together in LSR codegen.
351 /// This invariant can be temporarily broken while building a formula.
352 /// However, every formula inserted into the LSRInstance must be in canonical
354 SmallVector<const SCEV *, 4> BaseRegs;
356 /// The 'scaled' register for this use. This should be non-null when Scale is
358 const SCEV *ScaledReg = nullptr;
360 /// An additional constant offset which added near the use. This requires a
361 /// temporary register, but the offset itself can live in an add immediate
362 /// field rather than a register.
363 int64_t UnfoldedOffset = 0;
367 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
369 bool isCanonical(const Loop &L) const;
371 void canonicalize(const Loop &L);
375 bool hasZeroEnd() const;
377 size_t getNumRegs() const;
378 Type *getType() const;
380 void deleteBaseReg(const SCEV *&S);
382 bool referencesReg(const SCEV *S) const;
383 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
384 const RegUseTracker &RegUses) const;
386 void print(raw_ostream &OS) const;
390 } // end anonymous namespace
392 /// Recursion helper for initialMatch.
393 static void DoInitialMatch(const SCEV *S, Loop *L,
394 SmallVectorImpl<const SCEV *> &Good,
395 SmallVectorImpl<const SCEV *> &Bad,
396 ScalarEvolution &SE) {
397 // Collect expressions which properly dominate the loop header.
398 if (SE.properlyDominates(S, L->getHeader())) {
403 // Look at add operands.
404 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
405 for (const SCEV *S : Add->operands())
406 DoInitialMatch(S, L, Good, Bad, SE);
410 // Look at addrec operands.
411 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
412 if (!AR->getStart()->isZero() && AR->isAffine()) {
413 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
414 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
415 AR->getStepRecurrence(SE),
416 // FIXME: AR->getNoWrapFlags()
417 AR->getLoop(), SCEV::FlagAnyWrap),
422 // Handle a multiplication by -1 (negation) if it didn't fold.
423 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
424 if (Mul->getOperand(0)->isAllOnesValue()) {
425 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
426 const SCEV *NewMul = SE.getMulExpr(Ops);
428 SmallVector<const SCEV *, 4> MyGood;
429 SmallVector<const SCEV *, 4> MyBad;
430 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
431 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
432 SE.getEffectiveSCEVType(NewMul->getType())));
433 for (const SCEV *S : MyGood)
434 Good.push_back(SE.getMulExpr(NegOne, S));
435 for (const SCEV *S : MyBad)
436 Bad.push_back(SE.getMulExpr(NegOne, S));
440 // Ok, we can't do anything interesting. Just stuff the whole thing into a
441 // register and hope for the best.
445 /// Incorporate loop-variant parts of S into this Formula, attempting to keep
446 /// all loop-invariant and loop-computable values in a single base register.
447 void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
448 SmallVector<const SCEV *, 4> Good;
449 SmallVector<const SCEV *, 4> Bad;
450 DoInitialMatch(S, L, Good, Bad, SE);
452 const SCEV *Sum = SE.getAddExpr(Good);
454 BaseRegs.push_back(Sum);
458 const SCEV *Sum = SE.getAddExpr(Bad);
460 BaseRegs.push_back(Sum);
466 /// Check whether or not this formula satisfies the canonical
468 /// \see Formula::BaseRegs.
469 bool Formula::isCanonical(const Loop &L) const {
471 return BaseRegs.size() <= 1;
476 if (Scale == 1 && BaseRegs.empty())
479 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
480 if (SAR && SAR->getLoop() == &L)
483 // If ScaledReg is not a recurrent expr, or it is but its loop is not current
484 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
485 // loop, we want to swap the reg in BaseRegs with ScaledReg.
487 find_if(make_range(BaseRegs.begin(), BaseRegs.end()), [&](const SCEV *S) {
488 return isa<const SCEVAddRecExpr>(S) &&
489 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
491 return I == BaseRegs.end();
494 /// Helper method to morph a formula into its canonical representation.
495 /// \see Formula::BaseRegs.
496 /// Every formula having more than one base register, must use the ScaledReg
497 /// field. Otherwise, we would have to do special cases everywhere in LSR
498 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
499 /// On the other hand, 1*reg should be canonicalized into reg.
500 void Formula::canonicalize(const Loop &L) {
503 // So far we did not need this case. This is easy to implement but it is
504 // useless to maintain dead code. Beside it could hurt compile time.
505 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
507 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
509 ScaledReg = BaseRegs.back();
514 // If ScaledReg is an invariant with respect to L, find the reg from
515 // BaseRegs containing the recurrent expr related with Loop L. Swap the
516 // reg with ScaledReg.
517 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
518 if (!SAR || SAR->getLoop() != &L) {
519 auto I = find_if(make_range(BaseRegs.begin(), BaseRegs.end()),
521 return isa<const SCEVAddRecExpr>(S) &&
522 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
524 if (I != BaseRegs.end())
525 std::swap(ScaledReg, *I);
529 /// Get rid of the scale in the formula.
530 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
531 /// \return true if it was possible to get rid of the scale, false otherwise.
532 /// \note After this operation the formula may not be in the canonical form.
533 bool Formula::unscale() {
537 BaseRegs.push_back(ScaledReg);
542 bool Formula::hasZeroEnd() const {
543 if (UnfoldedOffset || BaseOffset)
545 if (BaseRegs.size() != 1 || ScaledReg)
550 /// Return the total number of register operands used by this formula. This does
551 /// not include register uses implied by non-constant addrec strides.
552 size_t Formula::getNumRegs() const {
553 return !!ScaledReg + BaseRegs.size();
556 /// Return the type of this formula, if it has one, or null otherwise. This type
557 /// is meaningless except for the bit size.
558 Type *Formula::getType() const {
559 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
560 ScaledReg ? ScaledReg->getType() :
561 BaseGV ? BaseGV->getType() :
565 /// Delete the given base reg from the BaseRegs list.
566 void Formula::deleteBaseReg(const SCEV *&S) {
567 if (&S != &BaseRegs.back())
568 std::swap(S, BaseRegs.back());
572 /// Test if this formula references the given register.
573 bool Formula::referencesReg(const SCEV *S) const {
574 return S == ScaledReg || is_contained(BaseRegs, S);
577 /// Test whether this formula uses registers which are used by uses other than
578 /// the use with the given index.
579 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
580 const RegUseTracker &RegUses) const {
582 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
584 for (const SCEV *BaseReg : BaseRegs)
585 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
590 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
591 void Formula::print(raw_ostream &OS) const {
594 if (!First) OS << " + "; else First = false;
595 BaseGV->printAsOperand(OS, /*PrintType=*/false);
597 if (BaseOffset != 0) {
598 if (!First) OS << " + "; else First = false;
601 for (const SCEV *BaseReg : BaseRegs) {
602 if (!First) OS << " + "; else First = false;
603 OS << "reg(" << *BaseReg << ')';
605 if (HasBaseReg && BaseRegs.empty()) {
606 if (!First) OS << " + "; else First = false;
607 OS << "**error: HasBaseReg**";
608 } else if (!HasBaseReg && !BaseRegs.empty()) {
609 if (!First) OS << " + "; else First = false;
610 OS << "**error: !HasBaseReg**";
613 if (!First) OS << " + "; else First = false;
614 OS << Scale << "*reg(";
621 if (UnfoldedOffset != 0) {
622 if (!First) OS << " + ";
623 OS << "imm(" << UnfoldedOffset << ')';
627 LLVM_DUMP_METHOD void Formula::dump() const {
628 print(errs()); errs() << '\n';
632 /// Return true if the given addrec can be sign-extended without changing its
634 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
636 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
637 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
640 /// Return true if the given add can be sign-extended without changing its
642 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
644 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
645 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
648 /// Return true if the given mul can be sign-extended without changing its
650 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
652 IntegerType::get(SE.getContext(),
653 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
654 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
657 /// Return an expression for LHS /s RHS, if it can be determined and if the
658 /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
659 /// is true, expressions like (X * Y) /s Y are simplified to Y, ignoring that
660 /// the multiplication may overflow, which is useful when the result will be
661 /// used in a context where the most significant bits are ignored.
662 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
664 bool IgnoreSignificantBits = false) {
665 // Handle the trivial case, which works for any SCEV type.
667 return SE.getConstant(LHS->getType(), 1);
669 // Handle a few RHS special cases.
670 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
672 const APInt &RA = RC->getAPInt();
673 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
675 if (RA.isAllOnesValue())
676 return SE.getMulExpr(LHS, RC);
677 // Handle x /s 1 as x.
682 // Check for a division of a constant by a constant.
683 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
686 const APInt &LA = C->getAPInt();
687 const APInt &RA = RC->getAPInt();
688 if (LA.srem(RA) != 0)
690 return SE.getConstant(LA.sdiv(RA));
693 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
694 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
695 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
696 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
697 IgnoreSignificantBits);
698 if (!Step) return nullptr;
699 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
700 IgnoreSignificantBits);
701 if (!Start) return nullptr;
702 // FlagNW is independent of the start value, step direction, and is
703 // preserved with smaller magnitude steps.
704 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
705 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
710 // Distribute the sdiv over add operands, if the add doesn't overflow.
711 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
712 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
713 SmallVector<const SCEV *, 8> Ops;
714 for (const SCEV *S : Add->operands()) {
715 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
716 if (!Op) return nullptr;
719 return SE.getAddExpr(Ops);
724 // Check for a multiply operand that we can pull RHS out of.
725 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
726 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
727 SmallVector<const SCEV *, 4> Ops;
729 for (const SCEV *S : Mul->operands()) {
731 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
732 IgnoreSignificantBits)) {
738 return Found ? SE.getMulExpr(Ops) : nullptr;
743 // Otherwise we don't know.
747 /// If S involves the addition of a constant integer value, return that integer
748 /// value, and mutate S to point to a new SCEV with that value excluded.
749 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
750 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
751 if (C->getAPInt().getMinSignedBits() <= 64) {
752 S = SE.getConstant(C->getType(), 0);
753 return C->getValue()->getSExtValue();
755 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
756 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
757 int64_t Result = ExtractImmediate(NewOps.front(), SE);
759 S = SE.getAddExpr(NewOps);
761 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
762 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
763 int64_t Result = ExtractImmediate(NewOps.front(), SE);
765 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
766 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
773 /// If S involves the addition of a GlobalValue address, return that symbol, and
774 /// mutate S to point to a new SCEV with that value excluded.
775 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
776 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
777 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
778 S = SE.getConstant(GV->getType(), 0);
781 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
782 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
783 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
785 S = SE.getAddExpr(NewOps);
787 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
788 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
789 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
791 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
792 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
799 /// Returns true if the specified instruction is using the specified value as an
801 static bool isAddressUse(const TargetTransformInfo &TTI,
802 Instruction *Inst, Value *OperandVal) {
803 bool isAddress = isa<LoadInst>(Inst);
804 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
805 if (SI->getPointerOperand() == OperandVal)
807 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
808 // Addressing modes can also be folded into prefetches and a variety
810 switch (II->getIntrinsicID()) {
811 case Intrinsic::memset:
812 case Intrinsic::prefetch:
813 case Intrinsic::masked_load:
814 if (II->getArgOperand(0) == OperandVal)
817 case Intrinsic::masked_store:
818 if (II->getArgOperand(1) == OperandVal)
821 case Intrinsic::memmove:
822 case Intrinsic::memcpy:
823 if (II->getArgOperand(0) == OperandVal ||
824 II->getArgOperand(1) == OperandVal)
828 MemIntrinsicInfo IntrInfo;
829 if (TTI.getTgtMemIntrinsic(II, IntrInfo)) {
830 if (IntrInfo.PtrVal == OperandVal)
835 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
836 if (RMW->getPointerOperand() == OperandVal)
838 } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
839 if (CmpX->getPointerOperand() == OperandVal)
845 /// Return the type of the memory being accessed.
846 static MemAccessTy getAccessType(const TargetTransformInfo &TTI,
847 Instruction *Inst, Value *OperandVal) {
848 MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace);
849 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
850 AccessTy.MemTy = SI->getOperand(0)->getType();
851 AccessTy.AddrSpace = SI->getPointerAddressSpace();
852 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
853 AccessTy.AddrSpace = LI->getPointerAddressSpace();
854 } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
855 AccessTy.AddrSpace = RMW->getPointerAddressSpace();
856 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
857 AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
858 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
859 switch (II->getIntrinsicID()) {
860 case Intrinsic::prefetch:
861 case Intrinsic::memset:
862 AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();
863 AccessTy.MemTy = OperandVal->getType();
865 case Intrinsic::memmove:
866 case Intrinsic::memcpy:
867 AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace();
868 AccessTy.MemTy = OperandVal->getType();
870 case Intrinsic::masked_load:
872 II->getArgOperand(0)->getType()->getPointerAddressSpace();
874 case Intrinsic::masked_store:
875 AccessTy.MemTy = II->getOperand(0)->getType();
877 II->getArgOperand(1)->getType()->getPointerAddressSpace();
880 MemIntrinsicInfo IntrInfo;
881 if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) {
883 = IntrInfo.PtrVal->getType()->getPointerAddressSpace();
891 // All pointers have the same requirements, so canonicalize them to an
892 // arbitrary pointer type to minimize variation.
893 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
894 AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
895 PTy->getAddressSpace());
900 /// Return true if this AddRec is already a phi in its loop.
901 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
902 for (PHINode &PN : AR->getLoop()->getHeader()->phis()) {
903 if (SE.isSCEVable(PN.getType()) &&
904 (SE.getEffectiveSCEVType(PN.getType()) ==
905 SE.getEffectiveSCEVType(AR->getType())) &&
906 SE.getSCEV(&PN) == AR)
912 /// Check if expanding this expression is likely to incur significant cost. This
913 /// is tricky because SCEV doesn't track which expressions are actually computed
914 /// by the current IR.
916 /// We currently allow expansion of IV increments that involve adds,
917 /// multiplication by constants, and AddRecs from existing phis.
919 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
920 /// obvious multiple of the UDivExpr.
921 static bool isHighCostExpansion(const SCEV *S,
922 SmallPtrSetImpl<const SCEV*> &Processed,
923 ScalarEvolution &SE) {
924 // Zero/One operand expressions
925 switch (S->getSCEVType()) {
930 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
933 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
936 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
940 if (!Processed.insert(S).second)
943 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
944 for (const SCEV *S : Add->operands()) {
945 if (isHighCostExpansion(S, Processed, SE))
951 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
952 if (Mul->getNumOperands() == 2) {
953 // Multiplication by a constant is ok
954 if (isa<SCEVConstant>(Mul->getOperand(0)))
955 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
957 // If we have the value of one operand, check if an existing
958 // multiplication already generates this expression.
959 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
960 Value *UVal = U->getValue();
961 for (User *UR : UVal->users()) {
962 // If U is a constant, it may be used by a ConstantExpr.
963 Instruction *UI = dyn_cast<Instruction>(UR);
964 if (UI && UI->getOpcode() == Instruction::Mul &&
965 SE.isSCEVable(UI->getType())) {
966 return SE.getSCEV(UI) == Mul;
973 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
974 if (isExistingPhi(AR, SE))
978 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
986 } // end anonymous namespace
988 /// Check if the addressing mode defined by \p F is completely
989 /// folded in \p LU at isel time.
990 /// This includes address-mode folding and special icmp tricks.
991 /// This function returns true if \p LU can accommodate what \p F
992 /// defines and up to 1 base + 1 scaled + offset.
993 /// In other words, if \p F has several base registers, this function may
994 /// still return true. Therefore, users still need to account for
995 /// additional base registers and/or unfolded offsets to derive an
996 /// accurate cost model.
997 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
998 const LSRUse &LU, const Formula &F);
1000 // Get the cost of the scaling factor used in F for LU.
1001 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1002 const LSRUse &LU, const Formula &F,
1007 /// This class is used to measure and compare candidate formulae.
1009 const Loop *L = nullptr;
1010 ScalarEvolution *SE = nullptr;
1011 const TargetTransformInfo *TTI = nullptr;
1012 TargetTransformInfo::LSRCost C;
1016 Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI) :
1017 L(L), SE(&SE), TTI(&TTI) {
1028 bool isLess(Cost &Other);
1033 // Once any of the metrics loses, they must all remain losers.
1035 return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds
1036 | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)
1037 || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds
1038 & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);
1043 assert(isValid() && "invalid cost");
1044 return C.NumRegs == ~0u;
1047 void RateFormula(const Formula &F,
1048 SmallPtrSetImpl<const SCEV *> &Regs,
1049 const DenseSet<const SCEV *> &VisitedRegs,
1051 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
1053 void print(raw_ostream &OS) const;
1057 void RateRegister(const Formula &F, const SCEV *Reg,
1058 SmallPtrSetImpl<const SCEV *> &Regs);
1059 void RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1060 SmallPtrSetImpl<const SCEV *> &Regs,
1061 SmallPtrSetImpl<const SCEV *> *LoserRegs);
1064 /// An operand value in an instruction which is to be replaced with some
1065 /// equivalent, possibly strength-reduced, replacement.
1067 /// The instruction which will be updated.
1068 Instruction *UserInst = nullptr;
1070 /// The operand of the instruction which will be replaced. The operand may be
1071 /// used more than once; every instance will be replaced.
1072 Value *OperandValToReplace = nullptr;
1074 /// If this user is to use the post-incremented value of an induction
1075 /// variable, this set is non-empty and holds the loops associated with the
1076 /// induction variable.
1077 PostIncLoopSet PostIncLoops;
1079 /// A constant offset to be added to the LSRUse expression. This allows
1080 /// multiple fixups to share the same LSRUse with different offsets, for
1081 /// example in an unrolled loop.
1084 LSRFixup() = default;
1086 bool isUseFullyOutsideLoop(const Loop *L) const;
1088 void print(raw_ostream &OS) const;
1092 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
1093 /// SmallVectors of const SCEV*.
1094 struct UniquifierDenseMapInfo {
1095 static SmallVector<const SCEV *, 4> getEmptyKey() {
1096 SmallVector<const SCEV *, 4> V;
1097 V.push_back(reinterpret_cast<const SCEV *>(-1));
1101 static SmallVector<const SCEV *, 4> getTombstoneKey() {
1102 SmallVector<const SCEV *, 4> V;
1103 V.push_back(reinterpret_cast<const SCEV *>(-2));
1107 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
1108 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1111 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1112 const SmallVector<const SCEV *, 4> &RHS) {
1117 /// This class holds the state that LSR keeps for each use in IVUsers, as well
1118 /// as uses invented by LSR itself. It includes information about what kinds of
1119 /// things can be folded into the user, information about the user itself, and
1120 /// information about how the use may be satisfied. TODO: Represent multiple
1121 /// users of the same expression in common?
1123 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1126 /// An enum for a kind of use, indicating what types of scaled and immediate
1127 /// operands it might support.
1129 Basic, ///< A normal use, with no folding.
1130 Special, ///< A special case of basic, allowing -1 scales.
1131 Address, ///< An address use; folding according to TargetLowering
1132 ICmpZero ///< An equality icmp with both operands folded into one.
1133 // TODO: Add a generic icmp too?
1136 using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>;
1139 MemAccessTy AccessTy;
1141 /// The list of operands which are to be replaced.
1142 SmallVector<LSRFixup, 8> Fixups;
1144 /// Keep track of the min and max offsets of the fixups.
1145 int64_t MinOffset = std::numeric_limits<int64_t>::max();
1146 int64_t MaxOffset = std::numeric_limits<int64_t>::min();
1148 /// This records whether all of the fixups using this LSRUse are outside of
1149 /// the loop, in which case some special-case heuristics may be used.
1150 bool AllFixupsOutsideLoop = true;
1152 /// RigidFormula is set to true to guarantee that this use will be associated
1153 /// with a single formula--the one that initially matched. Some SCEV
1154 /// expressions cannot be expanded. This allows LSR to consider the registers
1155 /// used by those expressions without the need to expand them later after
1156 /// changing the formula.
1157 bool RigidFormula = false;
1159 /// This records the widest use type for any fixup using this
1160 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
1161 /// fixup widths to be equivalent, because the narrower one may be relying on
1162 /// the implicit truncation to truncate away bogus bits.
1163 Type *WidestFixupType = nullptr;
1165 /// A list of ways to build a value that can satisfy this user. After the
1166 /// list is populated, one of these is selected heuristically and used to
1167 /// formulate a replacement for OperandValToReplace in UserInst.
1168 SmallVector<Formula, 12> Formulae;
1170 /// The set of register candidates used by all formulae in this LSRUse.
1171 SmallPtrSet<const SCEV *, 4> Regs;
1173 LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {}
1175 LSRFixup &getNewFixup() {
1176 Fixups.push_back(LSRFixup());
1177 return Fixups.back();
1180 void pushFixup(LSRFixup &f) {
1181 Fixups.push_back(f);
1182 if (f.Offset > MaxOffset)
1183 MaxOffset = f.Offset;
1184 if (f.Offset < MinOffset)
1185 MinOffset = f.Offset;
1188 bool HasFormulaWithSameRegs(const Formula &F) const;
1189 float getNotSelectedProbability(const SCEV *Reg) const;
1190 bool InsertFormula(const Formula &F, const Loop &L);
1191 void DeleteFormula(Formula &F);
1192 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1194 void print(raw_ostream &OS) const;
1198 } // end anonymous namespace
1200 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1201 LSRUse::KindType Kind, MemAccessTy AccessTy,
1202 GlobalValue *BaseGV, int64_t BaseOffset,
1203 bool HasBaseReg, int64_t Scale,
1204 Instruction *Fixup = nullptr);
1206 static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) {
1207 if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg))
1211 if (const auto *S = dyn_cast<SCEVAddRecExpr>(Reg))
1212 return getSetupCost(S->getStart(), Depth - 1);
1213 if (auto S = dyn_cast<SCEVCastExpr>(Reg))
1214 return getSetupCost(S->getOperand(), Depth - 1);
1215 if (auto S = dyn_cast<SCEVNAryExpr>(Reg))
1216 return std::accumulate(S->op_begin(), S->op_end(), 0,
1217 [&](unsigned i, const SCEV *Reg) {
1218 return i + getSetupCost(Reg, Depth - 1);
1220 if (auto S = dyn_cast<SCEVUDivExpr>(Reg))
1221 return getSetupCost(S->getLHS(), Depth - 1) +
1222 getSetupCost(S->getRHS(), Depth - 1);
1226 /// Tally up interesting quantities from the given register.
1227 void Cost::RateRegister(const Formula &F, const SCEV *Reg,
1228 SmallPtrSetImpl<const SCEV *> &Regs) {
1229 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
1230 // If this is an addrec for another loop, it should be an invariant
1231 // with respect to L since L is the innermost loop (at least
1232 // for now LSR only handles innermost loops).
1233 if (AR->getLoop() != L) {
1234 // If the AddRec exists, consider it's register free and leave it alone.
1235 if (isExistingPhi(AR, *SE) && !TTI->shouldFavorPostInc())
1238 // It is bad to allow LSR for current loop to add induction variables
1239 // for its sibling loops.
1240 if (!AR->getLoop()->contains(L)) {
1245 // Otherwise, it will be an invariant with respect to Loop L.
1250 unsigned LoopCost = 1;
1251 if (TTI->isIndexedLoadLegal(TTI->MIM_PostInc, AR->getType()) ||
1252 TTI->isIndexedStoreLegal(TTI->MIM_PostInc, AR->getType())) {
1254 // If the step size matches the base offset, we could use pre-indexed
1256 if (TTI->shouldFavorBackedgeIndex(L)) {
1257 if (auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)))
1258 if (Step->getAPInt() == F.BaseOffset)
1262 if (TTI->shouldFavorPostInc()) {
1263 const SCEV *LoopStep = AR->getStepRecurrence(*SE);
1264 if (isa<SCEVConstant>(LoopStep)) {
1265 const SCEV *LoopStart = AR->getStart();
1266 if (!isa<SCEVConstant>(LoopStart) &&
1267 SE->isLoopInvariant(LoopStart, L))
1272 C.AddRecCost += LoopCost;
1274 // Add the step value register, if it needs one.
1275 // TODO: The non-affine case isn't precisely modeled here.
1276 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1277 if (!Regs.count(AR->getOperand(1))) {
1278 RateRegister(F, AR->getOperand(1), Regs);
1286 // Rough heuristic; favor registers which don't require extra setup
1287 // instructions in the preheader.
1288 C.SetupCost += getSetupCost(Reg, SetupCostDepthLimit);
1289 // Ensure we don't, even with the recusion limit, produce invalid costs.
1290 C.SetupCost = std::min<unsigned>(C.SetupCost, 1 << 16);
1292 C.NumIVMuls += isa<SCEVMulExpr>(Reg) &&
1293 SE->hasComputableLoopEvolution(Reg, L);
1296 /// Record this register in the set. If we haven't seen it before, rate
1297 /// it. Optional LoserRegs provides a way to declare any formula that refers to
1298 /// one of those regs an instant loser.
1299 void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1300 SmallPtrSetImpl<const SCEV *> &Regs,
1301 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1302 if (LoserRegs && LoserRegs->count(Reg)) {
1306 if (Regs.insert(Reg).second) {
1307 RateRegister(F, Reg, Regs);
1308 if (LoserRegs && isLoser())
1309 LoserRegs->insert(Reg);
1313 void Cost::RateFormula(const Formula &F,
1314 SmallPtrSetImpl<const SCEV *> &Regs,
1315 const DenseSet<const SCEV *> &VisitedRegs,
1317 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1318 assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");
1319 // Tally up the registers.
1320 unsigned PrevAddRecCost = C.AddRecCost;
1321 unsigned PrevNumRegs = C.NumRegs;
1322 unsigned PrevNumBaseAdds = C.NumBaseAdds;
1323 if (const SCEV *ScaledReg = F.ScaledReg) {
1324 if (VisitedRegs.count(ScaledReg)) {
1328 RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs);
1332 for (const SCEV *BaseReg : F.BaseRegs) {
1333 if (VisitedRegs.count(BaseReg)) {
1337 RatePrimaryRegister(F, BaseReg, Regs, LoserRegs);
1342 // Determine how many (unfolded) adds we'll need inside the loop.
1343 size_t NumBaseParts = F.getNumRegs();
1344 if (NumBaseParts > 1)
1345 // Do not count the base and a possible second register if the target
1346 // allows to fold 2 registers.
1348 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(*TTI, LU, F)));
1349 C.NumBaseAdds += (F.UnfoldedOffset != 0);
1351 // Accumulate non-free scaling amounts.
1352 C.ScaleCost += getScalingFactorCost(*TTI, LU, F, *L);
1354 // Tally up the non-zero immediates.
1355 for (const LSRFixup &Fixup : LU.Fixups) {
1356 int64_t O = Fixup.Offset;
1357 int64_t Offset = (uint64_t)O + F.BaseOffset;
1359 C.ImmCost += 64; // Handle symbolic values conservatively.
1360 // TODO: This should probably be the pointer size.
1361 else if (Offset != 0)
1362 C.ImmCost += APInt(64, Offset, true).getMinSignedBits();
1364 // Check with target if this offset with this instruction is
1365 // specifically not supported.
1366 if (LU.Kind == LSRUse::Address && Offset != 0 &&
1367 !isAMCompletelyFolded(*TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1368 Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))
1372 // If we don't count instruction cost exit here.
1374 assert(isValid() && "invalid cost");
1378 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
1379 // additional instruction (at least fill).
1380 // TODO: Need distinguish register class?
1381 unsigned TTIRegNum = TTI->getNumberOfRegisters(
1382 TTI->getRegisterClassForType(false, F.getType())) - 1;
1383 if (C.NumRegs > TTIRegNum) {
1384 // Cost already exceeded TTIRegNum, then only newly added register can add
1385 // new instructions.
1386 if (PrevNumRegs > TTIRegNum)
1387 C.Insns += (C.NumRegs - PrevNumRegs);
1389 C.Insns += (C.NumRegs - TTIRegNum);
1392 // If ICmpZero formula ends with not 0, it could not be replaced by
1393 // just add or sub. We'll need to compare final result of AddRec.
1394 // That means we'll need an additional instruction. But if the target can
1395 // macro-fuse a compare with a branch, don't count this extra instruction.
1396 // For -10 + {0, +, 1}:
1402 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() &&
1403 !TTI->canMacroFuseCmp())
1405 // Each new AddRec adds 1 instruction to calculation.
1406 C.Insns += (C.AddRecCost - PrevAddRecCost);
1408 // BaseAdds adds instructions for unfolded registers.
1409 if (LU.Kind != LSRUse::ICmpZero)
1410 C.Insns += C.NumBaseAdds - PrevNumBaseAdds;
1411 assert(isValid() && "invalid cost");
1414 /// Set this cost to a losing value.
1416 C.Insns = std::numeric_limits<unsigned>::max();
1417 C.NumRegs = std::numeric_limits<unsigned>::max();
1418 C.AddRecCost = std::numeric_limits<unsigned>::max();
1419 C.NumIVMuls = std::numeric_limits<unsigned>::max();
1420 C.NumBaseAdds = std::numeric_limits<unsigned>::max();
1421 C.ImmCost = std::numeric_limits<unsigned>::max();
1422 C.SetupCost = std::numeric_limits<unsigned>::max();
1423 C.ScaleCost = std::numeric_limits<unsigned>::max();
1426 /// Choose the lower cost.
1427 bool Cost::isLess(Cost &Other) {
1428 if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&
1429 C.Insns != Other.C.Insns)
1430 return C.Insns < Other.C.Insns;
1431 return TTI->isLSRCostLess(C, Other.C);
1434 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1435 void Cost::print(raw_ostream &OS) const {
1437 OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");
1438 OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");
1439 if (C.AddRecCost != 0)
1440 OS << ", with addrec cost " << C.AddRecCost;
1441 if (C.NumIVMuls != 0)
1442 OS << ", plus " << C.NumIVMuls << " IV mul"
1443 << (C.NumIVMuls == 1 ? "" : "s");
1444 if (C.NumBaseAdds != 0)
1445 OS << ", plus " << C.NumBaseAdds << " base add"
1446 << (C.NumBaseAdds == 1 ? "" : "s");
1447 if (C.ScaleCost != 0)
1448 OS << ", plus " << C.ScaleCost << " scale cost";
1450 OS << ", plus " << C.ImmCost << " imm cost";
1451 if (C.SetupCost != 0)
1452 OS << ", plus " << C.SetupCost << " setup cost";
1455 LLVM_DUMP_METHOD void Cost::dump() const {
1456 print(errs()); errs() << '\n';
1460 /// Test whether this fixup always uses its value outside of the given loop.
1461 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1462 // PHI nodes use their value in their incoming blocks.
1463 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1464 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1465 if (PN->getIncomingValue(i) == OperandValToReplace &&
1466 L->contains(PN->getIncomingBlock(i)))
1471 return !L->contains(UserInst);
1474 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1475 void LSRFixup::print(raw_ostream &OS) const {
1477 // Store is common and interesting enough to be worth special-casing.
1478 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1480 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
1481 } else if (UserInst->getType()->isVoidTy())
1482 OS << UserInst->getOpcodeName();
1484 UserInst->printAsOperand(OS, /*PrintType=*/false);
1486 OS << ", OperandValToReplace=";
1487 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
1489 for (const Loop *PIL : PostIncLoops) {
1490 OS << ", PostIncLoop=";
1491 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
1495 OS << ", Offset=" << Offset;
1498 LLVM_DUMP_METHOD void LSRFixup::dump() const {
1499 print(errs()); errs() << '\n';
1503 /// Test whether this use as a formula which has the same registers as the given
1505 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1506 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1507 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1508 // Unstable sort by host order ok, because this is only used for uniquifying.
1510 return Uniquifier.count(Key);
1513 /// The function returns a probability of selecting formula without Reg.
1514 float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {
1516 for (const Formula &F : Formulae)
1517 if (F.referencesReg(Reg))
1519 return ((float)(Formulae.size() - FNum)) / Formulae.size();
1522 /// If the given formula has not yet been inserted, add it to the list, and
1523 /// return true. Return false otherwise. The formula must be in canonical form.
1524 bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {
1525 assert(F.isCanonical(L) && "Invalid canonical representation");
1527 if (!Formulae.empty() && RigidFormula)
1530 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1531 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1532 // Unstable sort by host order ok, because this is only used for uniquifying.
1535 if (!Uniquifier.insert(Key).second)
1538 // Using a register to hold the value of 0 is not profitable.
1539 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1540 "Zero allocated in a scaled register!");
1542 for (const SCEV *BaseReg : F.BaseRegs)
1543 assert(!BaseReg->isZero() && "Zero allocated in a base register!");
1546 // Add the formula to the list.
1547 Formulae.push_back(F);
1549 // Record registers now being used by this use.
1550 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1552 Regs.insert(F.ScaledReg);
1557 /// Remove the given formula from this use's list.
1558 void LSRUse::DeleteFormula(Formula &F) {
1559 if (&F != &Formulae.back())
1560 std::swap(F, Formulae.back());
1561 Formulae.pop_back();
1564 /// Recompute the Regs field, and update RegUses.
1565 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1566 // Now that we've filtered out some formulae, recompute the Regs set.
1567 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
1569 for (const Formula &F : Formulae) {
1570 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1571 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1574 // Update the RegTracker.
1575 for (const SCEV *S : OldRegs)
1577 RegUses.dropRegister(S, LUIdx);
1580 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1581 void LSRUse::print(raw_ostream &OS) const {
1582 OS << "LSR Use: Kind=";
1584 case Basic: OS << "Basic"; break;
1585 case Special: OS << "Special"; break;
1586 case ICmpZero: OS << "ICmpZero"; break;
1588 OS << "Address of ";
1589 if (AccessTy.MemTy->isPointerTy())
1590 OS << "pointer"; // the full pointer type could be really verbose
1592 OS << *AccessTy.MemTy;
1595 OS << " in addrspace(" << AccessTy.AddrSpace << ')';
1598 OS << ", Offsets={";
1599 bool NeedComma = false;
1600 for (const LSRFixup &Fixup : Fixups) {
1601 if (NeedComma) OS << ',';
1607 if (AllFixupsOutsideLoop)
1608 OS << ", all-fixups-outside-loop";
1610 if (WidestFixupType)
1611 OS << ", widest fixup type: " << *WidestFixupType;
1614 LLVM_DUMP_METHOD void LSRUse::dump() const {
1615 print(errs()); errs() << '\n';
1619 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1620 LSRUse::KindType Kind, MemAccessTy AccessTy,
1621 GlobalValue *BaseGV, int64_t BaseOffset,
1622 bool HasBaseReg, int64_t Scale,
1623 Instruction *Fixup/*= nullptr*/) {
1625 case LSRUse::Address:
1626 return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset,
1627 HasBaseReg, Scale, AccessTy.AddrSpace, Fixup);
1629 case LSRUse::ICmpZero:
1630 // There's not even a target hook for querying whether it would be legal to
1631 // fold a GV into an ICmp.
1635 // ICmp only has two operands; don't allow more than two non-trivial parts.
1636 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1639 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1640 // putting the scaled register in the other operand of the icmp.
1641 if (Scale != 0 && Scale != -1)
1644 // If we have low-level target information, ask the target if it can fold an
1645 // integer immediate on an icmp.
1646 if (BaseOffset != 0) {
1648 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1649 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1650 // Offs is the ICmp immediate.
1652 // The cast does the right thing with
1653 // std::numeric_limits<int64_t>::min().
1654 BaseOffset = -(uint64_t)BaseOffset;
1655 return TTI.isLegalICmpImmediate(BaseOffset);
1658 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1662 // Only handle single-register values.
1663 return !BaseGV && Scale == 0 && BaseOffset == 0;
1665 case LSRUse::Special:
1666 // Special case Basic to handle -1 scales.
1667 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1670 llvm_unreachable("Invalid LSRUse Kind!");
1673 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1674 int64_t MinOffset, int64_t MaxOffset,
1675 LSRUse::KindType Kind, MemAccessTy AccessTy,
1676 GlobalValue *BaseGV, int64_t BaseOffset,
1677 bool HasBaseReg, int64_t Scale) {
1678 // Check for overflow.
1679 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1682 MinOffset = (uint64_t)BaseOffset + MinOffset;
1683 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1686 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1688 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1689 HasBaseReg, Scale) &&
1690 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1694 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1695 int64_t MinOffset, int64_t MaxOffset,
1696 LSRUse::KindType Kind, MemAccessTy AccessTy,
1697 const Formula &F, const Loop &L) {
1698 // For the purpose of isAMCompletelyFolded either having a canonical formula
1699 // or a scale not equal to zero is correct.
1700 // Problems may arise from non canonical formulae having a scale == 0.
1701 // Strictly speaking it would best to just rely on canonical formulae.
1702 // However, when we generate the scaled formulae, we first check that the
1703 // scaling factor is profitable before computing the actual ScaledReg for
1704 // compile time sake.
1705 assert((F.isCanonical(L) || F.Scale != 0));
1706 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1707 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1710 /// Test whether we know how to expand the current formula.
1711 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1712 int64_t MaxOffset, LSRUse::KindType Kind,
1713 MemAccessTy AccessTy, GlobalValue *BaseGV,
1714 int64_t BaseOffset, bool HasBaseReg, int64_t Scale) {
1715 // We know how to expand completely foldable formulae.
1716 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1717 BaseOffset, HasBaseReg, Scale) ||
1718 // Or formulae that use a base register produced by a sum of base
1721 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1722 BaseGV, BaseOffset, true, 0));
1725 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1726 int64_t MaxOffset, LSRUse::KindType Kind,
1727 MemAccessTy AccessTy, const Formula &F) {
1728 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1729 F.BaseOffset, F.HasBaseReg, F.Scale);
1732 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1733 const LSRUse &LU, const Formula &F) {
1734 // Target may want to look at the user instructions.
1735 if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) {
1736 for (const LSRFixup &Fixup : LU.Fixups)
1737 if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1738 (F.BaseOffset + Fixup.Offset), F.HasBaseReg,
1739 F.Scale, Fixup.UserInst))
1744 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1745 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1749 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1750 const LSRUse &LU, const Formula &F,
1755 // If the use is not completely folded in that instruction, we will have to
1756 // pay an extra cost only for scale != 1.
1757 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1759 return F.Scale != 1;
1762 case LSRUse::Address: {
1763 // Check the scaling factor cost with both the min and max offsets.
1764 int ScaleCostMinOffset = TTI.getScalingFactorCost(
1765 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1766 F.Scale, LU.AccessTy.AddrSpace);
1767 int ScaleCostMaxOffset = TTI.getScalingFactorCost(
1768 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1769 F.Scale, LU.AccessTy.AddrSpace);
1771 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1772 "Legal addressing mode has an illegal cost!");
1773 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1775 case LSRUse::ICmpZero:
1777 case LSRUse::Special:
1778 // The use is completely folded, i.e., everything is folded into the
1783 llvm_unreachable("Invalid LSRUse Kind!");
1786 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1787 LSRUse::KindType Kind, MemAccessTy AccessTy,
1788 GlobalValue *BaseGV, int64_t BaseOffset,
1790 // Fast-path: zero is always foldable.
1791 if (BaseOffset == 0 && !BaseGV) return true;
1793 // Conservatively, create an address with an immediate and a
1794 // base and a scale.
1795 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1797 // Canonicalize a scale of 1 to a base register if the formula doesn't
1798 // already have a base register.
1799 if (!HasBaseReg && Scale == 1) {
1804 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1808 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1809 ScalarEvolution &SE, int64_t MinOffset,
1810 int64_t MaxOffset, LSRUse::KindType Kind,
1811 MemAccessTy AccessTy, const SCEV *S,
1813 // Fast-path: zero is always foldable.
1814 if (S->isZero()) return true;
1816 // Conservatively, create an address with an immediate and a
1817 // base and a scale.
1818 int64_t BaseOffset = ExtractImmediate(S, SE);
1819 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1821 // If there's anything else involved, it's not foldable.
1822 if (!S->isZero()) return false;
1824 // Fast-path: zero is always foldable.
1825 if (BaseOffset == 0 && !BaseGV) return true;
1827 // Conservatively, create an address with an immediate and a
1828 // base and a scale.
1829 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1831 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1832 BaseOffset, HasBaseReg, Scale);
1837 /// An individual increment in a Chain of IV increments. Relate an IV user to
1838 /// an expression that computes the IV it uses from the IV used by the previous
1839 /// link in the Chain.
1841 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1842 /// original IVOperand. The head of the chain's IVOperand is only valid during
1843 /// chain collection, before LSR replaces IV users. During chain generation,
1844 /// IncExpr can be used to find the new IVOperand that computes the same
1847 Instruction *UserInst;
1849 const SCEV *IncExpr;
1851 IVInc(Instruction *U, Value *O, const SCEV *E)
1852 : UserInst(U), IVOperand(O), IncExpr(E) {}
1855 // The list of IV increments in program order. We typically add the head of a
1856 // chain without finding subsequent links.
1858 SmallVector<IVInc, 1> Incs;
1859 const SCEV *ExprBase = nullptr;
1861 IVChain() = default;
1862 IVChain(const IVInc &Head, const SCEV *Base)
1863 : Incs(1, Head), ExprBase(Base) {}
1865 using const_iterator = SmallVectorImpl<IVInc>::const_iterator;
1867 // Return the first increment in the chain.
1868 const_iterator begin() const {
1869 assert(!Incs.empty());
1870 return std::next(Incs.begin());
1872 const_iterator end() const {
1876 // Returns true if this chain contains any increments.
1877 bool hasIncs() const { return Incs.size() >= 2; }
1879 // Add an IVInc to the end of this chain.
1880 void add(const IVInc &X) { Incs.push_back(X); }
1882 // Returns the last UserInst in the chain.
1883 Instruction *tailUserInst() const { return Incs.back().UserInst; }
1885 // Returns true if IncExpr can be profitably added to this chain.
1886 bool isProfitableIncrement(const SCEV *OperExpr,
1887 const SCEV *IncExpr,
1891 /// Helper for CollectChains to track multiple IV increment uses. Distinguish
1892 /// between FarUsers that definitely cross IV increments and NearUsers that may
1893 /// be used between IV increments.
1895 SmallPtrSet<Instruction*, 4> FarUsers;
1896 SmallPtrSet<Instruction*, 4> NearUsers;
1899 /// This class holds state for the main loop strength reduction logic.
1902 ScalarEvolution &SE;
1905 AssumptionCache &AC;
1906 TargetLibraryInfo &TLI;
1907 const TargetTransformInfo &TTI;
1909 MemorySSAUpdater *MSSAU;
1910 bool FavorBackedgeIndex = false;
1911 bool Changed = false;
1913 /// This is the insert position that the current loop's induction variable
1914 /// increment should be placed. In simple loops, this is the latch block's
1915 /// terminator. But in more complicated cases, this is a position which will
1916 /// dominate all the in-loop post-increment users.
1917 Instruction *IVIncInsertPos = nullptr;
1919 /// Interesting factors between use strides.
1921 /// We explicitly use a SetVector which contains a SmallSet, instead of the
1922 /// default, a SmallDenseSet, because we need to use the full range of
1923 /// int64_ts, and there's currently no good way of doing that with
1925 SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors;
1927 /// Interesting use types, to facilitate truncation reuse.
1928 SmallSetVector<Type *, 4> Types;
1930 /// The list of interesting uses.
1931 mutable SmallVector<LSRUse, 16> Uses;
1933 /// Track which uses use which register candidates.
1934 RegUseTracker RegUses;
1936 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1937 // have more than a few IV increment chains in a loop. Missing a Chain falls
1938 // back to normal LSR behavior for those uses.
1939 static const unsigned MaxChains = 8;
1941 /// IV users can form a chain of IV increments.
1942 SmallVector<IVChain, MaxChains> IVChainVec;
1944 /// IV users that belong to profitable IVChains.
1945 SmallPtrSet<Use*, MaxChains> IVIncSet;
1947 void OptimizeShadowIV();
1948 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1949 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1950 void OptimizeLoopTermCond();
1952 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1953 SmallVectorImpl<ChainUsers> &ChainUsersVec);
1954 void FinalizeChain(IVChain &Chain);
1955 void CollectChains();
1956 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1957 SmallVectorImpl<WeakTrackingVH> &DeadInsts);
1959 void CollectInterestingTypesAndFactors();
1960 void CollectFixupsAndInitialFormulae();
1962 // Support for sharing of LSRUses between LSRFixups.
1963 using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>;
1966 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1967 LSRUse::KindType Kind, MemAccessTy AccessTy);
1969 std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
1970 MemAccessTy AccessTy);
1972 void DeleteUse(LSRUse &LU, size_t LUIdx);
1974 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1976 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1977 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1978 void CountRegisters(const Formula &F, size_t LUIdx);
1979 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1981 void CollectLoopInvariantFixupsAndFormulae();
1983 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1984 unsigned Depth = 0);
1986 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1987 const Formula &Base, unsigned Depth,
1988 size_t Idx, bool IsScaledReg = false);
1989 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1990 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1991 const Formula &Base, size_t Idx,
1992 bool IsScaledReg = false);
1993 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1994 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1995 const Formula &Base,
1996 const SmallVectorImpl<int64_t> &Worklist,
1997 size_t Idx, bool IsScaledReg = false);
1998 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1999 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2000 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2001 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
2002 void GenerateCrossUseConstantOffsets();
2003 void GenerateAllReuseFormulae();
2005 void FilterOutUndesirableDedicatedRegisters();
2007 size_t EstimateSearchSpaceComplexity() const;
2008 void NarrowSearchSpaceByDetectingSupersets();
2009 void NarrowSearchSpaceByCollapsingUnrolledCode();
2010 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
2011 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
2012 void NarrowSearchSpaceByFilterPostInc();
2013 void NarrowSearchSpaceByDeletingCostlyFormulas();
2014 void NarrowSearchSpaceByPickingWinnerRegs();
2015 void NarrowSearchSpaceUsingHeuristics();
2017 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2019 SmallVectorImpl<const Formula *> &Workspace,
2020 const Cost &CurCost,
2021 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2022 DenseSet<const SCEV *> &VisitedRegs) const;
2023 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
2025 BasicBlock::iterator
2026 HoistInsertPosition(BasicBlock::iterator IP,
2027 const SmallVectorImpl<Instruction *> &Inputs) const;
2028 BasicBlock::iterator
2029 AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2032 SCEVExpander &Rewriter) const;
2034 Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2035 BasicBlock::iterator IP, SCEVExpander &Rewriter,
2036 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2037 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
2038 const Formula &F, SCEVExpander &Rewriter,
2039 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2040 void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2041 SCEVExpander &Rewriter,
2042 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2043 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
2046 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
2047 LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC,
2048 TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU);
2050 bool getChanged() const { return Changed; }
2052 void print_factors_and_types(raw_ostream &OS) const;
2053 void print_fixups(raw_ostream &OS) const;
2054 void print_uses(raw_ostream &OS) const;
2055 void print(raw_ostream &OS) const;
2059 } // end anonymous namespace
2061 /// If IV is used in a int-to-float cast inside the loop then try to eliminate
2062 /// the cast operation.
2063 void LSRInstance::OptimizeShadowIV() {
2064 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2065 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2068 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
2069 UI != E; /* empty */) {
2070 IVUsers::const_iterator CandidateUI = UI;
2072 Instruction *ShadowUse = CandidateUI->getUser();
2073 Type *DestTy = nullptr;
2074 bool IsSigned = false;
2076 /* If shadow use is a int->float cast then insert a second IV
2077 to eliminate this cast.
2079 for (unsigned i = 0; i < n; ++i)
2085 for (unsigned i = 0; i < n; ++i, ++d)
2088 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
2090 DestTy = UCast->getDestTy();
2092 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
2094 DestTy = SCast->getDestTy();
2096 if (!DestTy) continue;
2098 // If target does not support DestTy natively then do not apply
2099 // this transformation.
2100 if (!TTI.isTypeLegal(DestTy)) continue;
2102 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2104 if (PH->getNumIncomingValues() != 2) continue;
2106 // If the calculation in integers overflows, the result in FP type will
2107 // differ. So we only can do this transformation if we are guaranteed to not
2108 // deal with overflowing values
2109 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH));
2111 if (IsSigned && !AR->hasNoSignedWrap()) continue;
2112 if (!IsSigned && !AR->hasNoUnsignedWrap()) continue;
2114 Type *SrcTy = PH->getType();
2115 int Mantissa = DestTy->getFPMantissaWidth();
2116 if (Mantissa == -1) continue;
2117 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
2120 unsigned Entry, Latch;
2121 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2129 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2130 if (!Init) continue;
2131 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
2132 (double)Init->getSExtValue() :
2133 (double)Init->getZExtValue());
2135 BinaryOperator *Incr =
2136 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2137 if (!Incr) continue;
2138 if (Incr->getOpcode() != Instruction::Add
2139 && Incr->getOpcode() != Instruction::Sub)
2142 /* Initialize new IV, double d = 0.0 in above example. */
2143 ConstantInt *C = nullptr;
2144 if (Incr->getOperand(0) == PH)
2145 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2146 else if (Incr->getOperand(1) == PH)
2147 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2153 // Ignore negative constants, as the code below doesn't handle them
2154 // correctly. TODO: Remove this restriction.
2155 if (!C->getValue().isStrictlyPositive()) continue;
2157 /* Add new PHINode. */
2158 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
2160 /* create new increment. '++d' in above example. */
2161 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2162 BinaryOperator *NewIncr =
2163 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
2164 Instruction::FAdd : Instruction::FSub,
2165 NewPH, CFP, "IV.S.next.", Incr);
2167 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2168 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2170 /* Remove cast operation */
2171 ShadowUse->replaceAllUsesWith(NewPH);
2172 ShadowUse->eraseFromParent();
2178 /// If Cond has an operand that is an expression of an IV, set the IV user and
2179 /// stride information and return true, otherwise return false.
2180 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
2181 for (IVStrideUse &U : IU)
2182 if (U.getUser() == Cond) {
2183 // NOTE: we could handle setcc instructions with multiple uses here, but
2184 // InstCombine does it as well for simple uses, it's not clear that it
2185 // occurs enough in real life to handle.
2192 /// Rewrite the loop's terminating condition if it uses a max computation.
2194 /// This is a narrow solution to a specific, but acute, problem. For loops
2200 /// } while (++i < n);
2202 /// the trip count isn't just 'n', because 'n' might not be positive. And
2203 /// unfortunately this can come up even for loops where the user didn't use
2204 /// a C do-while loop. For example, seemingly well-behaved top-test loops
2205 /// will commonly be lowered like this:
2211 /// } while (++i < n);
2214 /// and then it's possible for subsequent optimization to obscure the if
2215 /// test in such a way that indvars can't find it.
2217 /// When indvars can't find the if test in loops like this, it creates a
2218 /// max expression, which allows it to give the loop a canonical
2219 /// induction variable:
2222 /// max = n < 1 ? 1 : n;
2225 /// } while (++i != max);
2227 /// Canonical induction variables are necessary because the loop passes
2228 /// are designed around them. The most obvious example of this is the
2229 /// LoopInfo analysis, which doesn't remember trip count values. It
2230 /// expects to be able to rediscover the trip count each time it is
2231 /// needed, and it does this using a simple analysis that only succeeds if
2232 /// the loop has a canonical induction variable.
2234 /// However, when it comes time to generate code, the maximum operation
2235 /// can be quite costly, especially if it's inside of an outer loop.
2237 /// This function solves this problem by detecting this type of loop and
2238 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2239 /// the instructions for the maximum computation.
2240 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
2241 // Check that the loop matches the pattern we're looking for.
2242 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2243 Cond->getPredicate() != CmpInst::ICMP_NE)
2246 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2247 if (!Sel || !Sel->hasOneUse()) return Cond;
2249 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2250 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2252 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
2254 // Add one to the backedge-taken count to get the trip count.
2255 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
2256 if (IterationCount != SE.getSCEV(Sel)) return Cond;
2258 // Check for a max calculation that matches the pattern. There's no check
2259 // for ICMP_ULE here because the comparison would be with zero, which
2260 // isn't interesting.
2261 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
2262 const SCEVNAryExpr *Max = nullptr;
2263 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2264 Pred = ICmpInst::ICMP_SLE;
2266 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2267 Pred = ICmpInst::ICMP_SLT;
2269 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2270 Pred = ICmpInst::ICMP_ULT;
2277 // To handle a max with more than two operands, this optimization would
2278 // require additional checking and setup.
2279 if (Max->getNumOperands() != 2)
2282 const SCEV *MaxLHS = Max->getOperand(0);
2283 const SCEV *MaxRHS = Max->getOperand(1);
2285 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2286 // for a comparison with 1. For <= and >=, a comparison with zero.
2288 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2291 // Check the relevant induction variable for conformance to
2293 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
2294 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2295 if (!AR || !AR->isAffine() ||
2296 AR->getStart() != One ||
2297 AR->getStepRecurrence(SE) != One)
2300 assert(AR->getLoop() == L &&
2301 "Loop condition operand is an addrec in a different loop!");
2303 // Check the right operand of the select, and remember it, as it will
2304 // be used in the new comparison instruction.
2305 Value *NewRHS = nullptr;
2306 if (ICmpInst::isTrueWhenEqual(Pred)) {
2307 // Look for n+1, and grab n.
2308 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
2309 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2310 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2311 NewRHS = BO->getOperand(0);
2312 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
2313 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2314 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2315 NewRHS = BO->getOperand(0);
2318 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
2319 NewRHS = Sel->getOperand(1);
2320 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
2321 NewRHS = Sel->getOperand(2);
2322 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2323 NewRHS = SU->getValue();
2325 // Max doesn't match expected pattern.
2328 // Determine the new comparison opcode. It may be signed or unsigned,
2329 // and the original comparison may be either equality or inequality.
2330 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2331 Pred = CmpInst::getInversePredicate(Pred);
2333 // Ok, everything looks ok to change the condition into an SLT or SGE and
2334 // delete the max calculation.
2336 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2338 // Delete the max calculation instructions.
2339 Cond->replaceAllUsesWith(NewCond);
2340 CondUse->setUser(NewCond);
2341 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2342 Cond->eraseFromParent();
2343 Sel->eraseFromParent();
2344 if (Cmp->use_empty())
2345 Cmp->eraseFromParent();
2349 /// Change loop terminating condition to use the postinc iv when possible.
2351 LSRInstance::OptimizeLoopTermCond() {
2352 SmallPtrSet<Instruction *, 4> PostIncs;
2354 // We need a different set of heuristics for rotated and non-rotated loops.
2355 // If a loop is rotated then the latch is also the backedge, so inserting
2356 // post-inc expressions just before the latch is ideal. To reduce live ranges
2357 // it also makes sense to rewrite terminating conditions to use post-inc
2360 // If the loop is not rotated then the latch is not a backedge; the latch
2361 // check is done in the loop head. Adding post-inc expressions before the
2362 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2363 // in the loop body. In this case we do *not* want to use post-inc expressions
2364 // in the latch check, and we want to insert post-inc expressions before
2366 BasicBlock *LatchBlock = L->getLoopLatch();
2367 SmallVector<BasicBlock*, 8> ExitingBlocks;
2368 L->getExitingBlocks(ExitingBlocks);
2369 if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) {
2370 return LatchBlock != BB;
2372 // The backedge doesn't exit the loop; treat this as a head-tested loop.
2373 IVIncInsertPos = LatchBlock->getTerminator();
2377 // Otherwise treat this as a rotated loop.
2378 for (BasicBlock *ExitingBlock : ExitingBlocks) {
2379 // Get the terminating condition for the loop if possible. If we
2380 // can, we want to change it to use a post-incremented version of its
2381 // induction variable, to allow coalescing the live ranges for the IV into
2382 // one register value.
2384 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2387 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2388 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2391 // Search IVUsesByStride to find Cond's IVUse if there is one.
2392 IVStrideUse *CondUse = nullptr;
2393 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2394 if (!FindIVUserForCond(Cond, CondUse))
2397 // If the trip count is computed in terms of a max (due to ScalarEvolution
2398 // being unable to find a sufficient guard, for example), change the loop
2399 // comparison to use SLT or ULT instead of NE.
2400 // One consequence of doing this now is that it disrupts the count-down
2401 // optimization. That's not always a bad thing though, because in such
2402 // cases it may still be worthwhile to avoid a max.
2403 Cond = OptimizeMax(Cond, CondUse);
2405 // If this exiting block dominates the latch block, it may also use
2406 // the post-inc value if it won't be shared with other uses.
2407 // Check for dominance.
2408 if (!DT.dominates(ExitingBlock, LatchBlock))
2411 // Conservatively avoid trying to use the post-inc value in non-latch
2412 // exits if there may be pre-inc users in intervening blocks.
2413 if (LatchBlock != ExitingBlock)
2414 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2415 // Test if the use is reachable from the exiting block. This dominator
2416 // query is a conservative approximation of reachability.
2417 if (&*UI != CondUse &&
2418 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2419 // Conservatively assume there may be reuse if the quotient of their
2420 // strides could be a legal scale.
2421 const SCEV *A = IU.getStride(*CondUse, L);
2422 const SCEV *B = IU.getStride(*UI, L);
2423 if (!A || !B) continue;
2424 if (SE.getTypeSizeInBits(A->getType()) !=
2425 SE.getTypeSizeInBits(B->getType())) {
2426 if (SE.getTypeSizeInBits(A->getType()) >
2427 SE.getTypeSizeInBits(B->getType()))
2428 B = SE.getSignExtendExpr(B, A->getType());
2430 A = SE.getSignExtendExpr(A, B->getType());
2432 if (const SCEVConstant *D =
2433 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
2434 const ConstantInt *C = D->getValue();
2435 // Stride of one or negative one can have reuse with non-addresses.
2436 if (C->isOne() || C->isMinusOne())
2437 goto decline_post_inc;
2438 // Avoid weird situations.
2439 if (C->getValue().getMinSignedBits() >= 64 ||
2440 C->getValue().isMinSignedValue())
2441 goto decline_post_inc;
2442 // Check for possible scaled-address reuse.
2443 if (isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) {
2444 MemAccessTy AccessTy = getAccessType(
2445 TTI, UI->getUser(), UI->getOperandValToReplace());
2446 int64_t Scale = C->getSExtValue();
2447 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2449 /*HasBaseReg=*/false, Scale,
2450 AccessTy.AddrSpace))
2451 goto decline_post_inc;
2453 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2455 /*HasBaseReg=*/false, Scale,
2456 AccessTy.AddrSpace))
2457 goto decline_post_inc;
2462 LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
2465 // It's possible for the setcc instruction to be anywhere in the loop, and
2466 // possible for it to have multiple users. If it is not immediately before
2467 // the exiting block branch, move it.
2468 if (&*++BasicBlock::iterator(Cond) != TermBr) {
2469 if (Cond->hasOneUse()) {
2470 Cond->moveBefore(TermBr);
2472 // Clone the terminating condition and insert into the loopend.
2473 ICmpInst *OldCond = Cond;
2474 Cond = cast<ICmpInst>(Cond->clone());
2475 Cond->setName(L->getHeader()->getName() + ".termcond");
2476 ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
2478 // Clone the IVUse, as the old use still exists!
2479 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
2480 TermBr->replaceUsesOfWith(OldCond, Cond);
2484 // If we get to here, we know that we can transform the setcc instruction to
2485 // use the post-incremented version of the IV, allowing us to coalesce the
2486 // live ranges for the IV correctly.
2487 CondUse->transformToPostInc(L);
2490 PostIncs.insert(Cond);
2494 // Determine an insertion point for the loop induction variable increment. It
2495 // must dominate all the post-inc comparisons we just set up, and it must
2496 // dominate the loop latch edge.
2497 IVIncInsertPos = L->getLoopLatch()->getTerminator();
2498 for (Instruction *Inst : PostIncs) {
2500 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
2502 if (BB == Inst->getParent())
2503 IVIncInsertPos = Inst;
2504 else if (BB != IVIncInsertPos->getParent())
2505 IVIncInsertPos = BB->getTerminator();
2509 /// Determine if the given use can accommodate a fixup at the given offset and
2510 /// other details. If so, update the use and return true.
2511 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2512 bool HasBaseReg, LSRUse::KindType Kind,
2513 MemAccessTy AccessTy) {
2514 int64_t NewMinOffset = LU.MinOffset;
2515 int64_t NewMaxOffset = LU.MaxOffset;
2516 MemAccessTy NewAccessTy = AccessTy;
2518 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2519 // something conservative, however this can pessimize in the case that one of
2520 // the uses will have all its uses outside the loop, for example.
2521 if (LU.Kind != Kind)
2524 // Check for a mismatched access type, and fall back conservatively as needed.
2525 // TODO: Be less conservative when the type is similar and can use the same
2526 // addressing modes.
2527 if (Kind == LSRUse::Address) {
2528 if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2529 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2530 AccessTy.AddrSpace);
2534 // Conservatively assume HasBaseReg is true for now.
2535 if (NewOffset < LU.MinOffset) {
2536 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2537 LU.MaxOffset - NewOffset, HasBaseReg))
2539 NewMinOffset = NewOffset;
2540 } else if (NewOffset > LU.MaxOffset) {
2541 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2542 NewOffset - LU.MinOffset, HasBaseReg))
2544 NewMaxOffset = NewOffset;
2548 LU.MinOffset = NewMinOffset;
2549 LU.MaxOffset = NewMaxOffset;
2550 LU.AccessTy = NewAccessTy;
2554 /// Return an LSRUse index and an offset value for a fixup which needs the given
2555 /// expression, with the given kind and optional access type. Either reuse an
2556 /// existing use or create a new one, as needed.
2557 std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr,
2558 LSRUse::KindType Kind,
2559 MemAccessTy AccessTy) {
2560 const SCEV *Copy = Expr;
2561 int64_t Offset = ExtractImmediate(Expr, SE);
2563 // Basic uses can't accept any offset, for example.
2564 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
2565 Offset, /*HasBaseReg=*/ true)) {
2570 std::pair<UseMapTy::iterator, bool> P =
2571 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
2573 // A use already existed with this base.
2574 size_t LUIdx = P.first->second;
2575 LSRUse &LU = Uses[LUIdx];
2576 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
2578 return std::make_pair(LUIdx, Offset);
2581 // Create a new use.
2582 size_t LUIdx = Uses.size();
2583 P.first->second = LUIdx;
2584 Uses.push_back(LSRUse(Kind, AccessTy));
2585 LSRUse &LU = Uses[LUIdx];
2587 LU.MinOffset = Offset;
2588 LU.MaxOffset = Offset;
2589 return std::make_pair(LUIdx, Offset);
2592 /// Delete the given use from the Uses list.
2593 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
2594 if (&LU != &Uses.back())
2595 std::swap(LU, Uses.back());
2599 RegUses.swapAndDropUse(LUIdx, Uses.size());
2602 /// Look for a use distinct from OrigLU which is has a formula that has the same
2603 /// registers as the given formula.
2605 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
2606 const LSRUse &OrigLU) {
2607 // Search all uses for the formula. This could be more clever.
2608 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2609 LSRUse &LU = Uses[LUIdx];
2610 // Check whether this use is close enough to OrigLU, to see whether it's
2611 // worthwhile looking through its formulae.
2612 // Ignore ICmpZero uses because they may contain formulae generated by
2613 // GenerateICmpZeroScales, in which case adding fixup offsets may
2615 if (&LU != &OrigLU &&
2616 LU.Kind != LSRUse::ICmpZero &&
2617 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2618 LU.WidestFixupType == OrigLU.WidestFixupType &&
2619 LU.HasFormulaWithSameRegs(OrigF)) {
2620 // Scan through this use's formulae.
2621 for (const Formula &F : LU.Formulae) {
2622 // Check to see if this formula has the same registers and symbols
2624 if (F.BaseRegs == OrigF.BaseRegs &&
2625 F.ScaledReg == OrigF.ScaledReg &&
2626 F.BaseGV == OrigF.BaseGV &&
2627 F.Scale == OrigF.Scale &&
2628 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2629 if (F.BaseOffset == 0)
2631 // This is the formula where all the registers and symbols matched;
2632 // there aren't going to be any others. Since we declined it, we
2633 // can skip the rest of the formulae and proceed to the next LSRUse.
2640 // Nothing looked good.
2644 void LSRInstance::CollectInterestingTypesAndFactors() {
2645 SmallSetVector<const SCEV *, 4> Strides;
2647 // Collect interesting types and strides.
2648 SmallVector<const SCEV *, 4> Worklist;
2649 for (const IVStrideUse &U : IU) {
2650 const SCEV *Expr = IU.getExpr(U);
2652 // Collect interesting types.
2653 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
2655 // Add strides for mentioned loops.
2656 Worklist.push_back(Expr);
2658 const SCEV *S = Worklist.pop_back_val();
2659 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2660 if (AR->getLoop() == L)
2661 Strides.insert(AR->getStepRecurrence(SE));
2662 Worklist.push_back(AR->getStart());
2663 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2664 Worklist.append(Add->op_begin(), Add->op_end());
2666 } while (!Worklist.empty());
2669 // Compute interesting factors from the set of interesting strides.
2670 for (SmallSetVector<const SCEV *, 4>::const_iterator
2671 I = Strides.begin(), E = Strides.end(); I != E; ++I)
2672 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
2673 std::next(I); NewStrideIter != E; ++NewStrideIter) {
2674 const SCEV *OldStride = *I;
2675 const SCEV *NewStride = *NewStrideIter;
2677 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2678 SE.getTypeSizeInBits(NewStride->getType())) {
2679 if (SE.getTypeSizeInBits(OldStride->getType()) >
2680 SE.getTypeSizeInBits(NewStride->getType()))
2681 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2683 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2685 if (const SCEVConstant *Factor =
2686 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2688 if (Factor->getAPInt().getMinSignedBits() <= 64)
2689 Factors.insert(Factor->getAPInt().getSExtValue());
2690 } else if (const SCEVConstant *Factor =
2691 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2694 if (Factor->getAPInt().getMinSignedBits() <= 64)
2695 Factors.insert(Factor->getAPInt().getSExtValue());
2699 // If all uses use the same type, don't bother looking for truncation-based
2701 if (Types.size() == 1)
2704 LLVM_DEBUG(print_factors_and_types(dbgs()));
2707 /// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2708 /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2709 /// IVStrideUses, we could partially skip this.
2710 static User::op_iterator
2711 findIVOperand(User::op_iterator OI, User::op_iterator OE,
2712 Loop *L, ScalarEvolution &SE) {
2713 for(; OI != OE; ++OI) {
2714 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2715 if (!SE.isSCEVable(Oper->getType()))
2718 if (const SCEVAddRecExpr *AR =
2719 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2720 if (AR->getLoop() == L)
2728 /// IVChain logic must consistently peek base TruncInst operands, so wrap it in
2729 /// a convenient helper.
2730 static Value *getWideOperand(Value *Oper) {
2731 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2732 return Trunc->getOperand(0);
2736 /// Return true if we allow an IV chain to include both types.
2737 static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2738 Type *LType = LVal->getType();
2739 Type *RType = RVal->getType();
2740 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() &&
2741 // Different address spaces means (possibly)
2742 // different types of the pointer implementation,
2743 // e.g. i16 vs i32 so disallow that.
2744 (LType->getPointerAddressSpace() ==
2745 RType->getPointerAddressSpace()));
2748 /// Return an approximation of this SCEV expression's "base", or NULL for any
2749 /// constant. Returning the expression itself is conservative. Returning a
2750 /// deeper subexpression is more precise and valid as long as it isn't less
2751 /// complex than another subexpression. For expressions involving multiple
2752 /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2753 /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2756 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2757 /// SCEVUnknown, we simply return the rightmost SCEV operand.
2758 static const SCEV *getExprBase(const SCEV *S) {
2759 switch (S->getSCEVType()) {
2760 default: // uncluding scUnknown.
2765 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2767 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2769 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2771 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2772 // there's nothing more complex.
2773 // FIXME: not sure if we want to recognize negation.
2774 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2775 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2776 E(Add->op_begin()); I != E; ++I) {
2777 const SCEV *SubExpr = *I;
2778 if (SubExpr->getSCEVType() == scAddExpr)
2779 return getExprBase(SubExpr);
2781 if (SubExpr->getSCEVType() != scMulExpr)
2784 return S; // all operands are scaled, be conservative.
2787 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2791 /// Return true if the chain increment is profitable to expand into a loop
2792 /// invariant value, which may require its own register. A profitable chain
2793 /// increment will be an offset relative to the same base. We allow such offsets
2794 /// to potentially be used as chain increment as long as it's not obviously
2795 /// expensive to expand using real instructions.
2796 bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2797 const SCEV *IncExpr,
2798 ScalarEvolution &SE) {
2799 // Aggressively form chains when -stress-ivchain.
2803 // Do not replace a constant offset from IV head with a nonconstant IV
2805 if (!isa<SCEVConstant>(IncExpr)) {
2806 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
2807 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
2811 SmallPtrSet<const SCEV*, 8> Processed;
2812 return !isHighCostExpansion(IncExpr, Processed, SE);
2815 /// Return true if the number of registers needed for the chain is estimated to
2816 /// be less than the number required for the individual IV users. First prohibit
2817 /// any IV users that keep the IV live across increments (the Users set should
2818 /// be empty). Next count the number and type of increments in the chain.
2820 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2821 /// effectively use postinc addressing modes. Only consider it profitable it the
2822 /// increments can be computed in fewer registers when chained.
2824 /// TODO: Consider IVInc free if it's already used in another chains.
2825 static bool isProfitableChain(IVChain &Chain,
2826 SmallPtrSetImpl<Instruction *> &Users,
2827 ScalarEvolution &SE,
2828 const TargetTransformInfo &TTI) {
2832 if (!Chain.hasIncs())
2835 if (!Users.empty()) {
2836 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
2837 for (Instruction *Inst
2838 : Users) { dbgs() << " " << *Inst << "\n"; });
2841 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2843 // The chain itself may require a register, so intialize cost to 1.
2846 // A complete chain likely eliminates the need for keeping the original IV in
2847 // a register. LSR does not currently know how to form a complete chain unless
2848 // the header phi already exists.
2849 if (isa<PHINode>(Chain.tailUserInst())
2850 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2853 const SCEV *LastIncExpr = nullptr;
2854 unsigned NumConstIncrements = 0;
2855 unsigned NumVarIncrements = 0;
2856 unsigned NumReusedIncrements = 0;
2858 if (TTI.isProfitableLSRChainElement(Chain.Incs[0].UserInst))
2861 for (const IVInc &Inc : Chain) {
2862 if (TTI.isProfitableLSRChainElement(Inc.UserInst))
2865 if (Inc.IncExpr->isZero())
2868 // Incrementing by zero or some constant is neutral. We assume constants can
2869 // be folded into an addressing mode or an add's immediate operand.
2870 if (isa<SCEVConstant>(Inc.IncExpr)) {
2871 ++NumConstIncrements;
2875 if (Inc.IncExpr == LastIncExpr)
2876 ++NumReusedIncrements;
2880 LastIncExpr = Inc.IncExpr;
2882 // An IV chain with a single increment is handled by LSR's postinc
2883 // uses. However, a chain with multiple increments requires keeping the IV's
2884 // value live longer than it needs to be if chained.
2885 if (NumConstIncrements > 1)
2888 // Materializing increment expressions in the preheader that didn't exist in
2889 // the original code may cost a register. For example, sign-extended array
2890 // indices can produce ridiculous increments like this:
2891 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2892 cost += NumVarIncrements;
2894 // Reusing variable increments likely saves a register to hold the multiple of
2896 cost -= NumReusedIncrements;
2898 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2904 /// Add this IV user to an existing chain or make it the head of a new chain.
2905 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2906 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2907 // When IVs are used as types of varying widths, they are generally converted
2908 // to a wider type with some uses remaining narrow under a (free) trunc.
2909 Value *const NextIV = getWideOperand(IVOper);
2910 const SCEV *const OperExpr = SE.getSCEV(NextIV);
2911 const SCEV *const OperExprBase = getExprBase(OperExpr);
2913 // Visit all existing chains. Check if its IVOper can be computed as a
2914 // profitable loop invariant increment from the last link in the Chain.
2915 unsigned ChainIdx = 0, NChains = IVChainVec.size();
2916 const SCEV *LastIncExpr = nullptr;
2917 for (; ChainIdx < NChains; ++ChainIdx) {
2918 IVChain &Chain = IVChainVec[ChainIdx];
2920 // Prune the solution space aggressively by checking that both IV operands
2921 // are expressions that operate on the same unscaled SCEVUnknown. This
2922 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2923 // first avoids creating extra SCEV expressions.
2924 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2927 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
2928 if (!isCompatibleIVType(PrevIV, NextIV))
2931 // A phi node terminates a chain.
2932 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2935 // The increment must be loop-invariant so it can be kept in a register.
2936 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2937 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2938 if (!SE.isLoopInvariant(IncExpr, L))
2941 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2942 LastIncExpr = IncExpr;
2946 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2947 // bother for phi nodes, because they must be last in the chain.
2948 if (ChainIdx == NChains) {
2949 if (isa<PHINode>(UserInst))
2951 if (NChains >= MaxChains && !StressIVChain) {
2952 LLVM_DEBUG(dbgs() << "IV Chain Limit\n");
2955 LastIncExpr = OperExpr;
2956 // IVUsers may have skipped over sign/zero extensions. We don't currently
2957 // attempt to form chains involving extensions unless they can be hoisted
2958 // into this loop's AddRec.
2959 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2962 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2964 ChainUsersVec.resize(NChains);
2965 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2966 << ") IV=" << *LastIncExpr << "\n");
2968 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2969 << ") IV+" << *LastIncExpr << "\n");
2970 // Add this IV user to the end of the chain.
2971 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2973 IVChain &Chain = IVChainVec[ChainIdx];
2975 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2976 // This chain's NearUsers become FarUsers.
2977 if (!LastIncExpr->isZero()) {
2978 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2983 // All other uses of IVOperand become near uses of the chain.
2984 // We currently ignore intermediate values within SCEV expressions, assuming
2985 // they will eventually be used be the current chain, or can be computed
2986 // from one of the chain increments. To be more precise we could
2987 // transitively follow its user and only add leaf IV users to the set.
2988 for (User *U : IVOper->users()) {
2989 Instruction *OtherUse = dyn_cast<Instruction>(U);
2992 // Uses in the chain will no longer be uses if the chain is formed.
2993 // Include the head of the chain in this iteration (not Chain.begin()).
2994 IVChain::const_iterator IncIter = Chain.Incs.begin();
2995 IVChain::const_iterator IncEnd = Chain.Incs.end();
2996 for( ; IncIter != IncEnd; ++IncIter) {
2997 if (IncIter->UserInst == OtherUse)
3000 if (IncIter != IncEnd)
3003 if (SE.isSCEVable(OtherUse->getType())
3004 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
3005 && IU.isIVUserOrOperand(OtherUse)) {
3008 NearUsers.insert(OtherUse);
3011 // Since this user is part of the chain, it's no longer considered a use
3013 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
3016 /// Populate the vector of Chains.
3018 /// This decreases ILP at the architecture level. Targets with ample registers,
3019 /// multiple memory ports, and no register renaming probably don't want
3020 /// this. However, such targets should probably disable LSR altogether.
3022 /// The job of LSR is to make a reasonable choice of induction variables across
3023 /// the loop. Subsequent passes can easily "unchain" computation exposing more
3024 /// ILP *within the loop* if the target wants it.
3026 /// Finding the best IV chain is potentially a scheduling problem. Since LSR
3027 /// will not reorder memory operations, it will recognize this as a chain, but
3028 /// will generate redundant IV increments. Ideally this would be corrected later
3029 /// by a smart scheduler:
3035 /// TODO: Walk the entire domtree within this loop, not just the path to the
3036 /// loop latch. This will discover chains on side paths, but requires
3037 /// maintaining multiple copies of the Chains state.
3038 void LSRInstance::CollectChains() {
3039 LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n");
3040 SmallVector<ChainUsers, 8> ChainUsersVec;
3042 SmallVector<BasicBlock *,8> LatchPath;
3043 BasicBlock *LoopHeader = L->getHeader();
3044 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
3045 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
3046 LatchPath.push_back(Rung->getBlock());
3048 LatchPath.push_back(LoopHeader);
3050 // Walk the instruction stream from the loop header to the loop latch.
3051 for (BasicBlock *BB : reverse(LatchPath)) {
3052 for (Instruction &I : *BB) {
3053 // Skip instructions that weren't seen by IVUsers analysis.
3054 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
3057 // Ignore users that are part of a SCEV expression. This way we only
3058 // consider leaf IV Users. This effectively rediscovers a portion of
3059 // IVUsers analysis but in program order this time.
3060 if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))
3063 // Remove this instruction from any NearUsers set it may be in.
3064 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
3065 ChainIdx < NChains; ++ChainIdx) {
3066 ChainUsersVec[ChainIdx].NearUsers.erase(&I);
3068 // Search for operands that can be chained.
3069 SmallPtrSet<Instruction*, 4> UniqueOperands;
3070 User::op_iterator IVOpEnd = I.op_end();
3071 User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);
3072 while (IVOpIter != IVOpEnd) {
3073 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
3074 if (UniqueOperands.insert(IVOpInst).second)
3075 ChainInstruction(&I, IVOpInst, ChainUsersVec);
3076 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3078 } // Continue walking down the instructions.
3079 } // Continue walking down the domtree.
3080 // Visit phi backedges to determine if the chain can generate the IV postinc.
3081 for (PHINode &PN : L->getHeader()->phis()) {
3082 if (!SE.isSCEVable(PN.getType()))
3086 dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch()));
3088 ChainInstruction(&PN, IncV, ChainUsersVec);
3090 // Remove any unprofitable chains.
3091 unsigned ChainIdx = 0;
3092 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
3093 UsersIdx < NChains; ++UsersIdx) {
3094 if (!isProfitableChain(IVChainVec[UsersIdx],
3095 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
3097 // Preserve the chain at UsesIdx.
3098 if (ChainIdx != UsersIdx)
3099 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
3100 FinalizeChain(IVChainVec[ChainIdx]);
3103 IVChainVec.resize(ChainIdx);
3106 void LSRInstance::FinalizeChain(IVChain &Chain) {
3107 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
3108 LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
3110 for (const IVInc &Inc : Chain) {
3111 LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");
3112 auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);
3113 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
3114 IVIncSet.insert(UseI);
3118 /// Return true if the IVInc can be folded into an addressing mode.
3119 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
3120 Value *Operand, const TargetTransformInfo &TTI) {
3121 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
3122 if (!IncConst || !isAddressUse(TTI, UserInst, Operand))
3125 if (IncConst->getAPInt().getMinSignedBits() > 64)
3128 MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand);
3129 int64_t IncOffset = IncConst->getValue()->getSExtValue();
3130 if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
3131 IncOffset, /*HasBaseReg=*/false))
3137 /// Generate an add or subtract for each IVInc in a chain to materialize the IV
3138 /// user's operand from the previous IV user's operand.
3139 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
3140 SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
3141 // Find the new IVOperand for the head of the chain. It may have been replaced
3143 const IVInc &Head = Chain.Incs[0];
3144 User::op_iterator IVOpEnd = Head.UserInst->op_end();
3145 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
3146 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
3148 Value *IVSrc = nullptr;
3149 while (IVOpIter != IVOpEnd) {
3150 IVSrc = getWideOperand(*IVOpIter);
3152 // If this operand computes the expression that the chain needs, we may use
3153 // it. (Check this after setting IVSrc which is used below.)
3155 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
3156 // narrow for the chain, so we can no longer use it. We do allow using a
3157 // wider phi, assuming the LSR checked for free truncation. In that case we
3158 // should already have a truncate on this operand such that
3159 // getSCEV(IVSrc) == IncExpr.
3160 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
3161 || SE.getSCEV(IVSrc) == Head.IncExpr) {
3164 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3166 if (IVOpIter == IVOpEnd) {
3167 // Gracefully give up on this chain.
3168 LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
3171 assert(IVSrc && "Failed to find IV chain source");
3173 LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
3174 Type *IVTy = IVSrc->getType();
3175 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
3176 const SCEV *LeftOverExpr = nullptr;
3177 for (const IVInc &Inc : Chain) {
3178 Instruction *InsertPt = Inc.UserInst;
3179 if (isa<PHINode>(InsertPt))
3180 InsertPt = L->getLoopLatch()->getTerminator();
3182 // IVOper will replace the current IV User's operand. IVSrc is the IV
3183 // value currently held in a register.
3184 Value *IVOper = IVSrc;
3185 if (!Inc.IncExpr->isZero()) {
3186 // IncExpr was the result of subtraction of two narrow values, so must
3188 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
3189 LeftOverExpr = LeftOverExpr ?
3190 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3192 if (LeftOverExpr && !LeftOverExpr->isZero()) {
3193 // Expand the IV increment.
3194 Rewriter.clearPostInc();
3195 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
3196 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
3197 SE.getUnknown(IncV));
3198 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
3200 // If an IV increment can't be folded, use it as the next IV value.
3201 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
3202 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
3204 LeftOverExpr = nullptr;
3207 Type *OperTy = Inc.IVOperand->getType();
3208 if (IVTy != OperTy) {
3209 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
3210 "cannot extend a chained IV");
3211 IRBuilder<> Builder(InsertPt);
3212 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
3214 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
3215 if (auto *OperandIsInstr = dyn_cast<Instruction>(Inc.IVOperand))
3216 DeadInsts.emplace_back(OperandIsInstr);
3218 // If LSR created a new, wider phi, we may also replace its postinc. We only
3219 // do this if we also found a wide value for the head of the chain.
3220 if (isa<PHINode>(Chain.tailUserInst())) {
3221 for (PHINode &Phi : L->getHeader()->phis()) {
3222 if (!isCompatibleIVType(&Phi, IVSrc))
3224 Instruction *PostIncV = dyn_cast<Instruction>(
3225 Phi.getIncomingValueForBlock(L->getLoopLatch()));
3226 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
3228 Value *IVOper = IVSrc;
3229 Type *PostIncTy = PostIncV->getType();
3230 if (IVTy != PostIncTy) {
3231 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
3232 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3233 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
3234 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
3236 Phi.replaceUsesOfWith(PostIncV, IVOper);
3237 DeadInsts.emplace_back(PostIncV);
3242 void LSRInstance::CollectFixupsAndInitialFormulae() {
3243 BranchInst *ExitBranch = nullptr;
3244 bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI);
3246 for (const IVStrideUse &U : IU) {
3247 Instruction *UserInst = U.getUser();
3248 // Skip IV users that are part of profitable IV Chains.
3249 User::op_iterator UseI =
3250 find(UserInst->operands(), U.getOperandValToReplace());
3251 assert(UseI != UserInst->op_end() && "cannot find IV operand");
3252 if (IVIncSet.count(UseI)) {
3253 LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');
3257 LSRUse::KindType Kind = LSRUse::Basic;
3258 MemAccessTy AccessTy;
3259 if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {
3260 Kind = LSRUse::Address;
3261 AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace());
3264 const SCEV *S = IU.getExpr(U);
3265 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
3267 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3268 // (N - i == 0), and this allows (N - i) to be the expression that we work
3269 // with rather than just N or i, so we can consider the register
3270 // requirements for both N and i at the same time. Limiting this code to
3271 // equality icmps is not a problem because all interesting loops use
3272 // equality icmps, thanks to IndVarSimplify.
3273 if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) {
3274 // If CI can be saved in some target, like replaced inside hardware loop
3275 // in PowerPC, no need to generate initial formulae for it.
3276 if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->getCondition()))
3278 if (CI->isEquality()) {
3279 // Swap the operands if needed to put the OperandValToReplace on the
3280 // left, for consistency.
3281 Value *NV = CI->getOperand(1);
3282 if (NV == U.getOperandValToReplace()) {
3283 CI->setOperand(1, CI->getOperand(0));
3284 CI->setOperand(0, NV);
3285 NV = CI->getOperand(1);
3289 // x == y --> x - y == 0
3290 const SCEV *N = SE.getSCEV(NV);
3291 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
3292 // S is normalized, so normalize N before folding it into S
3293 // to keep the result normalized.
3294 N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);
3295 Kind = LSRUse::ICmpZero;
3296 S = SE.getMinusSCEV(N, S);
3299 // -1 and the negations of all interesting strides (except the negation
3300 // of -1) are now also interesting.
3301 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3302 if (Factors[i] != -1)
3303 Factors.insert(-(uint64_t)Factors[i]);
3308 // Get or create an LSRUse.
3309 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3310 size_t LUIdx = P.first;
3311 int64_t Offset = P.second;
3312 LSRUse &LU = Uses[LUIdx];
3314 // Record the fixup.
3315 LSRFixup &LF = LU.getNewFixup();
3316 LF.UserInst = UserInst;
3317 LF.OperandValToReplace = U.getOperandValToReplace();
3318 LF.PostIncLoops = TmpPostIncLoops;
3320 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3322 if (!LU.WidestFixupType ||
3323 SE.getTypeSizeInBits(LU.WidestFixupType) <
3324 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3325 LU.WidestFixupType = LF.OperandValToReplace->getType();
3327 // If this is the first use of this LSRUse, give it a formula.
3328 if (LU.Formulae.empty()) {
3329 InsertInitialFormula(S, LU, LUIdx);
3330 CountRegisters(LU.Formulae.back(), LUIdx);
3334 LLVM_DEBUG(print_fixups(dbgs()));
3337 /// Insert a formula for the given expression into the given use, separating out
3338 /// loop-variant portions from loop-invariant and loop-computable portions.
3340 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
3341 // Mark uses whose expressions cannot be expanded.
3342 if (!isSafeToExpand(S, SE))
3343 LU.RigidFormula = true;
3346 F.initialMatch(S, L, SE);
3347 bool Inserted = InsertFormula(LU, LUIdx, F);
3348 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3351 /// Insert a simple single-register formula for the given expression into the
3354 LSRInstance::InsertSupplementalFormula(const SCEV *S,
3355 LSRUse &LU, size_t LUIdx) {
3357 F.BaseRegs.push_back(S);
3358 F.HasBaseReg = true;
3359 bool Inserted = InsertFormula(LU, LUIdx, F);
3360 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3363 /// Note which registers are used by the given formula, updating RegUses.
3364 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3366 RegUses.countRegister(F.ScaledReg, LUIdx);
3367 for (const SCEV *BaseReg : F.BaseRegs)
3368 RegUses.countRegister(BaseReg, LUIdx);
3371 /// If the given formula has not yet been inserted, add it to the list, and
3372 /// return true. Return false otherwise.
3373 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
3374 // Do not insert formula that we will not be able to expand.
3375 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3376 "Formula is illegal");
3378 if (!LU.InsertFormula(F, *L))
3381 CountRegisters(F, LUIdx);
3385 /// Check for other uses of loop-invariant values which we're tracking. These
3386 /// other uses will pin these values in registers, making them less profitable
3387 /// for elimination.
3388 /// TODO: This currently misses non-constant addrec step registers.
3389 /// TODO: Should this give more weight to users inside the loop?
3391 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3392 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
3393 SmallPtrSet<const SCEV *, 32> Visited;
3395 while (!Worklist.empty()) {
3396 const SCEV *S = Worklist.pop_back_val();
3398 // Don't process the same SCEV twice
3399 if (!Visited.insert(S).second)
3402 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
3403 Worklist.append(N->op_begin(), N->op_end());
3404 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3405 Worklist.push_back(C->getOperand());
3406 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3407 Worklist.push_back(D->getLHS());
3408 Worklist.push_back(D->getRHS());
3409 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3410 const Value *V = US->getValue();
3411 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3412 // Look for instructions defined outside the loop.
3413 if (L->contains(Inst)) continue;
3414 } else if (isa<UndefValue>(V))
3415 // Undef doesn't have a live range, so it doesn't matter.
3417 for (const Use &U : V->uses()) {
3418 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
3419 // Ignore non-instructions.
3422 // Ignore instructions in other functions (as can happen with
3424 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
3426 // Ignore instructions not dominated by the loop.
3427 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3428 UserInst->getParent() :
3429 cast<PHINode>(UserInst)->getIncomingBlock(
3430 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3431 if (!DT.dominates(L->getHeader(), UseBB))
3433 // Don't bother if the instruction is in a BB which ends in an EHPad.
3434 if (UseBB->getTerminator()->isEHPad())
3436 // Don't bother rewriting PHIs in catchswitch blocks.
3437 if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))
3439 // Ignore uses which are part of other SCEV expressions, to avoid
3440 // analyzing them multiple times.
3441 if (SE.isSCEVable(UserInst->getType())) {
3442 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3443 // If the user is a no-op, look through to its uses.
3444 if (!isa<SCEVUnknown>(UserS))
3448 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3452 // Ignore icmp instructions which are already being analyzed.
3453 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3454 unsigned OtherIdx = !U.getOperandNo();
3455 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
3456 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
3460 std::pair<size_t, int64_t> P = getUse(
3461 S, LSRUse::Basic, MemAccessTy());
3462 size_t LUIdx = P.first;
3463 int64_t Offset = P.second;
3464 LSRUse &LU = Uses[LUIdx];
3465 LSRFixup &LF = LU.getNewFixup();
3466 LF.UserInst = const_cast<Instruction *>(UserInst);
3467 LF.OperandValToReplace = U;
3469 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3470 if (!LU.WidestFixupType ||
3471 SE.getTypeSizeInBits(LU.WidestFixupType) <
3472 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3473 LU.WidestFixupType = LF.OperandValToReplace->getType();
3474 InsertSupplementalFormula(US, LU, LUIdx);
3475 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3482 /// Split S into subexpressions which can be pulled out into separate
3483 /// registers. If C is non-null, multiply each subexpression by C.
3485 /// Return remainder expression after factoring the subexpressions captured by
3486 /// Ops. If Ops is complete, return NULL.
3487 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3488 SmallVectorImpl<const SCEV *> &Ops,
3490 ScalarEvolution &SE,
3491 unsigned Depth = 0) {
3492 // Arbitrarily cap recursion to protect compile time.
3496 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3497 // Break out add operands.
3498 for (const SCEV *S : Add->operands()) {
3499 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
3501 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3504 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3505 // Split a non-zero base out of an addrec.
3506 if (AR->getStart()->isZero() || !AR->isAffine())
3509 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3510 C, Ops, L, SE, Depth+1);
3511 // Split the non-zero AddRec unless it is part of a nested recurrence that
3512 // does not pertain to this loop.
3513 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3514 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3515 Remainder = nullptr;
3517 if (Remainder != AR->getStart()) {
3519 Remainder = SE.getConstant(AR->getType(), 0);
3520 return SE.getAddRecExpr(Remainder,
3521 AR->getStepRecurrence(SE),
3523 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3526 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3527 // Break (C * (a + b + c)) into C*a + C*b + C*c.
3528 if (Mul->getNumOperands() != 2)
3530 if (const SCEVConstant *Op0 =
3531 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3532 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3533 const SCEV *Remainder =
3534 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3536 Ops.push_back(SE.getMulExpr(C, Remainder));
3543 /// Return true if the SCEV represents a value that may end up as a
3544 /// post-increment operation.
3545 static bool mayUsePostIncMode(const TargetTransformInfo &TTI,
3546 LSRUse &LU, const SCEV *S, const Loop *L,
3547 ScalarEvolution &SE) {
3548 if (LU.Kind != LSRUse::Address ||
3549 !LU.AccessTy.getType()->isIntOrIntVectorTy())
3551 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
3554 const SCEV *LoopStep = AR->getStepRecurrence(SE);
3555 if (!isa<SCEVConstant>(LoopStep))
3557 // Check if a post-indexed load/store can be used.
3558 if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) ||
3559 TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) {
3560 const SCEV *LoopStart = AR->getStart();
3561 if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L))
3567 /// Helper function for LSRInstance::GenerateReassociations.
3568 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3569 const Formula &Base,
3570 unsigned Depth, size_t Idx,
3572 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3573 // Don't generate reassociations for the base register of a value that
3574 // may generate a post-increment operator. The reason is that the
3575 // reassociations cause extra base+register formula to be created,
3576 // and possibly chosen, but the post-increment is more efficient.
3577 if (TTI.shouldFavorPostInc() && mayUsePostIncMode(TTI, LU, BaseReg, L, SE))
3579 SmallVector<const SCEV *, 8> AddOps;
3580 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3582 AddOps.push_back(Remainder);
3584 if (AddOps.size() == 1)
3587 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3590 // Loop-variant "unknown" values are uninteresting; we won't be able to
3591 // do anything meaningful with them.
3592 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3595 // Don't pull a constant into a register if the constant could be folded
3596 // into an immediate field.
3597 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3598 LU.AccessTy, *J, Base.getNumRegs() > 1))
3601 // Collect all operands except *J.
3602 SmallVector<const SCEV *, 8> InnerAddOps(
3603 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3604 InnerAddOps.append(std::next(J),
3605 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3607 // Don't leave just a constant behind in a register if the constant could
3608 // be folded into an immediate field.
3609 if (InnerAddOps.size() == 1 &&
3610 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3611 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3614 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3615 if (InnerSum->isZero())
3619 // Add the remaining pieces of the add back into the new formula.
3620 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3621 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3622 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3623 InnerSumSC->getValue()->getZExtValue())) {
3625 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3627 F.ScaledReg = nullptr;
3629 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3630 } else if (IsScaledReg)
3631 F.ScaledReg = InnerSum;
3633 F.BaseRegs[Idx] = InnerSum;
3635 // Add J as its own register, or an unfolded immediate.
3636 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3637 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3638 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3639 SC->getValue()->getZExtValue()))
3641 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3643 F.BaseRegs.push_back(*J);
3644 // We may have changed the number of register in base regs, adjust the
3645 // formula accordingly.
3648 if (InsertFormula(LU, LUIdx, F))
3649 // If that formula hadn't been seen before, recurse to find more like
3651 // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2)
3652 // Because just Depth is not enough to bound compile time.
3653 // This means that every time AddOps.size() is greater 16^x we will add
3655 GenerateReassociations(LU, LUIdx, LU.Formulae.back(),
3656 Depth + 1 + (Log2_32(AddOps.size()) >> 2));
3660 /// Split out subexpressions from adds and the bases of addrecs.
3661 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
3662 Formula Base, unsigned Depth) {
3663 assert(Base.isCanonical(*L) && "Input must be in the canonical form");
3664 // Arbitrarily cap recursion to protect compile time.
3668 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3669 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3671 if (Base.Scale == 1)
3672 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3673 /* Idx */ -1, /* IsScaledReg */ true);
3676 /// Generate a formula consisting of all of the loop-dominating registers added
3677 /// into a single register.
3678 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
3680 // This method is only interesting on a plurality of registers.
3681 if (Base.BaseRegs.size() + (Base.Scale == 1) +
3682 (Base.UnfoldedOffset != 0) <= 1)
3685 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3686 // processing the formula.
3688 SmallVector<const SCEV *, 4> Ops;
3689 Formula NewBase = Base;
3690 NewBase.BaseRegs.clear();
3691 Type *CombinedIntegerType = nullptr;
3692 for (const SCEV *BaseReg : Base.BaseRegs) {
3693 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
3694 !SE.hasComputableLoopEvolution(BaseReg, L)) {
3695 if (!CombinedIntegerType)
3696 CombinedIntegerType = SE.getEffectiveSCEVType(BaseReg->getType());
3697 Ops.push_back(BaseReg);
3700 NewBase.BaseRegs.push_back(BaseReg);
3703 // If no register is relevant, we're done.
3704 if (Ops.size() == 0)
3707 // Utility function for generating the required variants of the combined
3709 auto GenerateFormula = [&](const SCEV *Sum) {
3710 Formula F = NewBase;
3712 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3713 // opportunity to fold something. For now, just ignore such cases
3714 // rather than proceed with zero in a register.
3718 F.BaseRegs.push_back(Sum);
3720 (void)InsertFormula(LU, LUIdx, F);
3723 // If we collected at least two registers, generate a formula combining them.
3724 if (Ops.size() > 1) {
3725 SmallVector<const SCEV *, 4> OpsCopy(Ops); // Don't let SE modify Ops.
3726 GenerateFormula(SE.getAddExpr(OpsCopy));
3729 // If we have an unfolded offset, generate a formula combining it with the
3730 // registers collected.
3731 if (NewBase.UnfoldedOffset) {
3732 assert(CombinedIntegerType && "Missing a type for the unfolded offset");
3733 Ops.push_back(SE.getConstant(CombinedIntegerType, NewBase.UnfoldedOffset,
3735 NewBase.UnfoldedOffset = 0;
3736 GenerateFormula(SE.getAddExpr(Ops));
3740 /// Helper function for LSRInstance::GenerateSymbolicOffsets.
3741 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3742 const Formula &Base, size_t Idx,
3744 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3745 GlobalValue *GV = ExtractSymbol(G, SE);
3746 if (G->isZero() || !GV)
3750 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3755 F.BaseRegs[Idx] = G;
3756 (void)InsertFormula(LU, LUIdx, F);
3759 /// Generate reuse formulae using symbolic offsets.
3760 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3762 // We can't add a symbolic offset if the address already contains one.
3763 if (Base.BaseGV) return;
3765 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3766 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3767 if (Base.Scale == 1)
3768 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3769 /* IsScaledReg */ true);
3772 /// Helper function for LSRInstance::GenerateConstantOffsets.
3773 void LSRInstance::GenerateConstantOffsetsImpl(
3774 LSRUse &LU, unsigned LUIdx, const Formula &Base,
3775 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3777 auto GenerateOffset = [&](const SCEV *G, int64_t Offset) {
3779 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3781 if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
3783 // Add the offset to the base register.
3784 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
3785 // If it cancelled out, drop the base register, otherwise update it.
3786 if (NewG->isZero()) {
3789 F.ScaledReg = nullptr;
3791 F.deleteBaseReg(F.BaseRegs[Idx]);
3793 } else if (IsScaledReg)
3796 F.BaseRegs[Idx] = NewG;
3798 (void)InsertFormula(LU, LUIdx, F);
3802 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3804 // With constant offsets and constant steps, we can generate pre-inc
3805 // accesses by having the offset equal the step. So, for access #0 with a
3806 // step of 8, we generate a G - 8 base which would require the first access
3807 // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer
3808 // for itself and hopefully becomes the base for other accesses. This means
3809 // means that a single pre-indexed access can be generated to become the new
3810 // base pointer for each iteration of the loop, resulting in no extra add/sub
3811 // instructions for pointer updating.
3812 if (FavorBackedgeIndex && LU.Kind == LSRUse::Address) {
3813 if (auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) {
3815 dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) {
3816 const APInt &StepInt = StepRec->getAPInt();
3817 int64_t Step = StepInt.isNegative() ?
3818 StepInt.getSExtValue() : StepInt.getZExtValue();
3820 for (int64_t Offset : Worklist) {
3822 GenerateOffset(G, Offset);
3827 for (int64_t Offset : Worklist)
3828 GenerateOffset(G, Offset);
3830 int64_t Imm = ExtractImmediate(G, SE);
3831 if (G->isZero() || Imm == 0)
3834 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3835 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3840 F.BaseRegs[Idx] = G;
3841 (void)InsertFormula(LU, LUIdx, F);
3844 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3845 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3847 // TODO: For now, just add the min and max offset, because it usually isn't
3848 // worthwhile looking at everything inbetween.
3849 SmallVector<int64_t, 2> Worklist;
3850 Worklist.push_back(LU.MinOffset);
3851 if (LU.MaxOffset != LU.MinOffset)
3852 Worklist.push_back(LU.MaxOffset);
3854 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3855 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3856 if (Base.Scale == 1)
3857 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3858 /* IsScaledReg */ true);
3861 /// For ICmpZero, check to see if we can scale up the comparison. For example, x
3862 /// == y -> x*c == y*c.
3863 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3865 if (LU.Kind != LSRUse::ICmpZero) return;
3867 // Determine the integer type for the base formula.
3868 Type *IntTy = Base.getType();
3870 if (SE.getTypeSizeInBits(IntTy) > 64) return;
3872 // Don't do this if there is more than one offset.
3873 if (LU.MinOffset != LU.MaxOffset) return;
3875 // Check if transformation is valid. It is illegal to multiply pointer.
3876 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
3878 for (const SCEV *BaseReg : Base.BaseRegs)
3879 if (BaseReg->getType()->isPointerTy())
3881 assert(!Base.BaseGV && "ICmpZero use is not legal!");
3883 // Check each interesting stride.
3884 for (int64_t Factor : Factors) {
3885 // Check that the multiplication doesn't overflow.
3886 if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1)
3888 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3889 if (NewBaseOffset / Factor != Base.BaseOffset)
3891 // If the offset will be truncated at this use, check that it is in bounds.
3892 if (!IntTy->isPointerTy() &&
3893 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3896 // Check that multiplying with the use offset doesn't overflow.
3897 int64_t Offset = LU.MinOffset;
3898 if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1)
3900 Offset = (uint64_t)Offset * Factor;
3901 if (Offset / Factor != LU.MinOffset)
3903 // If the offset will be truncated at this use, check that it is in bounds.
3904 if (!IntTy->isPointerTy() &&
3905 !ConstantInt::isValueValidForType(IntTy, Offset))
3909 F.BaseOffset = NewBaseOffset;
3911 // Check that this scale is legal.
3912 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3915 // Compensate for the use having MinOffset built into it.
3916 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3918 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3920 // Check that multiplying with each base register doesn't overflow.
3921 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3922 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
3923 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3927 // Check that multiplying with the scaled register doesn't overflow.
3929 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
3930 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3934 // Check that multiplying with the unfolded offset doesn't overflow.
3935 if (F.UnfoldedOffset != 0) {
3936 if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() &&
3939 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3940 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3942 // If the offset will be truncated, check that it is in bounds.
3943 if (!IntTy->isPointerTy() &&
3944 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3948 // If we make it here and it's legal, add it.
3949 (void)InsertFormula(LU, LUIdx, F);
3954 /// Generate stride factor reuse formulae by making use of scaled-offset address
3955 /// modes, for example.
3956 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
3957 // Determine the integer type for the base formula.
3958 Type *IntTy = Base.getType();
3961 // If this Formula already has a scaled register, we can't add another one.
3962 // Try to unscale the formula to generate a better scale.
3963 if (Base.Scale != 0 && !Base.unscale())
3966 assert(Base.Scale == 0 && "unscale did not did its job!");
3968 // Check each interesting stride.
3969 for (int64_t Factor : Factors) {
3970 Base.Scale = Factor;
3971 Base.HasBaseReg = Base.BaseRegs.size() > 1;
3972 // Check whether this scale is going to be legal.
3973 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3975 // As a special-case, handle special out-of-loop Basic users specially.
3976 // TODO: Reconsider this special case.
3977 if (LU.Kind == LSRUse::Basic &&
3978 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3979 LU.AccessTy, Base) &&
3980 LU.AllFixupsOutsideLoop)
3981 LU.Kind = LSRUse::Special;
3985 // For an ICmpZero, negating a solitary base register won't lead to
3987 if (LU.Kind == LSRUse::ICmpZero &&
3988 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3990 // For each addrec base reg, if its loop is current loop, apply the scale.
3991 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
3992 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]);
3993 if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {
3994 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3995 if (FactorS->isZero())
3997 // Divide out the factor, ignoring high bits, since we'll be
3998 // scaling the value back up in the end.
3999 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
4000 // TODO: This could be optimized to avoid all the copying.
4002 F.ScaledReg = Quotient;
4003 F.deleteBaseReg(F.BaseRegs[i]);
4004 // The canonical representation of 1*reg is reg, which is already in
4005 // Base. In that case, do not try to insert the formula, it will be
4007 if (F.Scale == 1 && (F.BaseRegs.empty() ||
4008 (AR->getLoop() != L && LU.AllFixupsOutsideLoop)))
4010 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
4011 // non canonical Formula with ScaledReg's loop not being L.
4012 if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
4014 (void)InsertFormula(LU, LUIdx, F);
4021 /// Generate reuse formulae from different IV types.
4022 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
4023 // Don't bother truncating symbolic values.
4024 if (Base.BaseGV) return;
4026 // Determine the integer type for the base formula.
4027 Type *DstTy = Base.getType();
4029 DstTy = SE.getEffectiveSCEVType(DstTy);
4031 for (Type *SrcTy : Types) {
4032 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
4035 // Sometimes SCEV is able to prove zero during ext transform. It may
4036 // happen if SCEV did not do all possible transforms while creating the
4037 // initial node (maybe due to depth limitations), but it can do them while
4040 const SCEV *NewScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
4041 if (NewScaledReg->isZero())
4043 F.ScaledReg = NewScaledReg;
4045 bool HasZeroBaseReg = false;
4046 for (const SCEV *&BaseReg : F.BaseRegs) {
4047 const SCEV *NewBaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
4048 if (NewBaseReg->isZero()) {
4049 HasZeroBaseReg = true;
4052 BaseReg = NewBaseReg;
4057 // TODO: This assumes we've done basic processing on all uses and
4058 // have an idea what the register usage is.
4059 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
4063 (void)InsertFormula(LU, LUIdx, F);
4070 /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
4071 /// modifications so that the search phase doesn't have to worry about the data
4072 /// structures moving underneath it.
4076 const SCEV *OrigReg;
4078 WorkItem(size_t LI, int64_t I, const SCEV *R)
4079 : LUIdx(LI), Imm(I), OrigReg(R) {}
4081 void print(raw_ostream &OS) const;
4085 } // end anonymous namespace
4087 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4088 void WorkItem::print(raw_ostream &OS) const {
4089 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
4090 << " , add offset " << Imm;
4093 LLVM_DUMP_METHOD void WorkItem::dump() const {
4094 print(errs()); errs() << '\n';
4098 /// Look for registers which are a constant distance apart and try to form reuse
4099 /// opportunities between them.
4100 void LSRInstance::GenerateCrossUseConstantOffsets() {
4101 // Group the registers by their value without any added constant offset.
4102 using ImmMapTy = std::map<int64_t, const SCEV *>;
4104 DenseMap<const SCEV *, ImmMapTy> Map;
4105 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
4106 SmallVector<const SCEV *, 8> Sequence;
4107 for (const SCEV *Use : RegUses) {
4108 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
4109 int64_t Imm = ExtractImmediate(Reg, SE);
4110 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
4112 Sequence.push_back(Reg);
4113 Pair.first->second.insert(std::make_pair(Imm, Use));
4114 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
4117 // Now examine each set of registers with the same base value. Build up
4118 // a list of work to do and do the work in a separate step so that we're
4119 // not adding formulae and register counts while we're searching.
4120 SmallVector<WorkItem, 32> WorkItems;
4121 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
4122 for (const SCEV *Reg : Sequence) {
4123 const ImmMapTy &Imms = Map.find(Reg)->second;
4125 // It's not worthwhile looking for reuse if there's only one offset.
4126 if (Imms.size() == 1)
4129 LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
4130 for (const auto &Entry
4132 << ' ' << Entry.first;
4135 // Examine each offset.
4136 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
4138 const SCEV *OrigReg = J->second;
4140 int64_t JImm = J->first;
4141 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
4143 if (!isa<SCEVConstant>(OrigReg) &&
4144 UsedByIndicesMap[Reg].count() == 1) {
4145 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
4150 // Conservatively examine offsets between this orig reg a few selected
4152 int64_t First = Imms.begin()->first;
4153 int64_t Last = std::prev(Imms.end())->first;
4154 // Compute (First + Last) / 2 without overflow using the fact that
4155 // First + Last = 2 * (First + Last) + (First ^ Last).
4156 int64_t Avg = (First & Last) + ((First ^ Last) >> 1);
4157 // If the result is negative and First is odd and Last even (or vice versa),
4158 // we rounded towards -inf. Add 1 in that case, to round towards 0.
4159 Avg = Avg + ((First ^ Last) & ((uint64_t)Avg >> 63));
4160 ImmMapTy::const_iterator OtherImms[] = {
4161 Imms.begin(), std::prev(Imms.end()),
4162 Imms.lower_bound(Avg)};
4163 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
4164 ImmMapTy::const_iterator M = OtherImms[i];
4165 if (M == J || M == JE) continue;
4167 // Compute the difference between the two.
4168 int64_t Imm = (uint64_t)JImm - M->first;
4169 for (unsigned LUIdx : UsedByIndices.set_bits())
4170 // Make a memo of this use, offset, and register tuple.
4171 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
4172 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
4179 UsedByIndicesMap.clear();
4180 UniqueItems.clear();
4182 // Now iterate through the worklist and add new formulae.
4183 for (const WorkItem &WI : WorkItems) {
4184 size_t LUIdx = WI.LUIdx;
4185 LSRUse &LU = Uses[LUIdx];
4186 int64_t Imm = WI.Imm;
4187 const SCEV *OrigReg = WI.OrigReg;
4189 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
4190 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
4191 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
4193 // TODO: Use a more targeted data structure.
4194 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
4195 Formula F = LU.Formulae[L];
4196 // FIXME: The code for the scaled and unscaled registers looks
4197 // very similar but slightly different. Investigate if they
4198 // could be merged. That way, we would not have to unscale the
4201 // Use the immediate in the scaled register.
4202 if (F.ScaledReg == OrigReg) {
4203 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
4204 // Don't create 50 + reg(-50).
4205 if (F.referencesReg(SE.getSCEV(
4206 ConstantInt::get(IntTy, -(uint64_t)Offset))))
4209 NewF.BaseOffset = Offset;
4210 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4213 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
4215 // If the new scale is a constant in a register, and adding the constant
4216 // value to the immediate would produce a value closer to zero than the
4217 // immediate itself, then the formula isn't worthwhile.
4218 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
4219 if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
4220 (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
4221 .ule(std::abs(NewF.BaseOffset)))
4225 NewF.canonicalize(*this->L);
4226 (void)InsertFormula(LU, LUIdx, NewF);
4228 // Use the immediate in a base register.
4229 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
4230 const SCEV *BaseReg = F.BaseRegs[N];
4231 if (BaseReg != OrigReg)
4234 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
4235 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
4236 LU.Kind, LU.AccessTy, NewF)) {
4237 if (TTI.shouldFavorPostInc() &&
4238 mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE))
4240 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
4243 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
4245 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
4247 // If the new formula has a constant in a register, and adding the
4248 // constant value to the immediate would produce a value closer to
4249 // zero than the immediate itself, then the formula isn't worthwhile.
4250 for (const SCEV *NewReg : NewF.BaseRegs)
4251 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
4252 if ((C->getAPInt() + NewF.BaseOffset)
4254 .slt(std::abs(NewF.BaseOffset)) &&
4255 (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >=
4256 countTrailingZeros<uint64_t>(NewF.BaseOffset))
4260 NewF.canonicalize(*this->L);
4261 (void)InsertFormula(LU, LUIdx, NewF);
4270 /// Generate formulae for each use.
4272 LSRInstance::GenerateAllReuseFormulae() {
4273 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
4274 // queries are more precise.
4275 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4276 LSRUse &LU = Uses[LUIdx];
4277 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4278 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4279 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4280 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4282 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4283 LSRUse &LU = Uses[LUIdx];
4284 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4285 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4286 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4287 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4288 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4289 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4290 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4291 GenerateScales(LU, LUIdx, LU.Formulae[i]);
4293 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4294 LSRUse &LU = Uses[LUIdx];
4295 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4296 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4299 GenerateCrossUseConstantOffsets();
4301 LLVM_DEBUG(dbgs() << "\n"
4302 "After generating reuse formulae:\n";
4303 print_uses(dbgs()));
4306 /// If there are multiple formulae with the same set of registers used
4307 /// by other uses, pick the best one and delete the others.
4308 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4309 DenseSet<const SCEV *> VisitedRegs;
4310 SmallPtrSet<const SCEV *, 16> Regs;
4311 SmallPtrSet<const SCEV *, 16> LoserRegs;
4313 bool ChangedFormulae = false;
4316 // Collect the best formula for each unique set of shared registers. This
4317 // is reset for each use.
4318 using BestFormulaeTy =
4319 DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>;
4321 BestFormulaeTy BestFormulae;
4323 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4324 LSRUse &LU = Uses[LUIdx];
4325 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
4329 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
4330 FIdx != NumForms; ++FIdx) {
4331 Formula &F = LU.Formulae[FIdx];
4333 // Some formulas are instant losers. For example, they may depend on
4334 // nonexistent AddRecs from other loops. These need to be filtered
4335 // immediately, otherwise heuristics could choose them over others leading
4336 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
4337 // avoids the need to recompute this information across formulae using the
4338 // same bad AddRec. Passing LoserRegs is also essential unless we remove
4339 // the corresponding bad register from the Regs set.
4340 Cost CostF(L, SE, TTI);
4342 CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs);
4343 if (CostF.isLoser()) {
4344 // During initial formula generation, undesirable formulae are generated
4345 // by uses within other loops that have some non-trivial address mode or
4346 // use the postinc form of the IV. LSR needs to provide these formulae
4347 // as the basis of rediscovering the desired formula that uses an AddRec
4348 // corresponding to the existing phi. Once all formulae have been
4349 // generated, these initial losers may be pruned.
4350 LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
4354 SmallVector<const SCEV *, 4> Key;
4355 for (const SCEV *Reg : F.BaseRegs) {
4356 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4360 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4361 Key.push_back(F.ScaledReg);
4362 // Unstable sort by host order ok, because this is only used for
4366 std::pair<BestFormulaeTy::const_iterator, bool> P =
4367 BestFormulae.insert(std::make_pair(Key, FIdx));
4371 Formula &Best = LU.Formulae[P.first->second];
4373 Cost CostBest(L, SE, TTI);
4375 CostBest.RateFormula(Best, Regs, VisitedRegs, LU);
4376 if (CostF.isLess(CostBest))
4378 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
4380 " in favor of formula ";
4381 Best.print(dbgs()); dbgs() << '\n');
4384 ChangedFormulae = true;
4386 LU.DeleteFormula(F);
4392 // Now that we've filtered out some formulae, recompute the Regs set.
4394 LU.RecomputeRegs(LUIdx, RegUses);
4396 // Reset this to prepare for the next use.
4397 BestFormulae.clear();
4400 LLVM_DEBUG(if (ChangedFormulae) {
4402 "After filtering out undesirable candidates:\n";
4407 /// Estimate the worst-case number of solutions the solver might have to
4408 /// consider. It almost never considers this many solutions because it prune the
4409 /// search space, but the pruning isn't always sufficient.
4410 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
4412 for (const LSRUse &LU : Uses) {
4413 size_t FSize = LU.Formulae.size();
4414 if (FSize >= ComplexityLimit) {
4415 Power = ComplexityLimit;
4419 if (Power >= ComplexityLimit)
4425 /// When one formula uses a superset of the registers of another formula, it
4426 /// won't help reduce register pressure (though it may not necessarily hurt
4427 /// register pressure); remove it to simplify the system.
4428 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4429 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4430 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4432 LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4433 "which use a superset of registers used by other "
4436 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4437 LSRUse &LU = Uses[LUIdx];
4439 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4440 Formula &F = LU.Formulae[i];
4441 // Look for a formula with a constant or GV in a register. If the use
4442 // also has a formula with that same value in an immediate field,
4443 // delete the one that uses a register.
4444 for (SmallVectorImpl<const SCEV *>::const_iterator
4445 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4446 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4448 //FIXME: Formulas should store bitwidth to do wrapping properly.
4450 NewF.BaseOffset += (uint64_t)C->getValue()->getSExtValue();
4451 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4452 (I - F.BaseRegs.begin()));
4453 if (LU.HasFormulaWithSameRegs(NewF)) {
4454 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4456 LU.DeleteFormula(F);
4462 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4463 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4467 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4468 (I - F.BaseRegs.begin()));
4469 if (LU.HasFormulaWithSameRegs(NewF)) {
4470 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4472 LU.DeleteFormula(F);
4483 LU.RecomputeRegs(LUIdx, RegUses);
4486 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4490 /// When there are many registers for expressions like A, A+1, A+2, etc.,
4491 /// allocate a single register for them.
4492 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4493 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4497 dbgs() << "The search space is too complex.\n"
4498 "Narrowing the search space by assuming that uses separated "
4499 "by a constant offset will use the same registers.\n");
4501 // This is especially useful for unrolled loops.
4503 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4504 LSRUse &LU = Uses[LUIdx];
4505 for (const Formula &F : LU.Formulae) {
4506 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4509 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4513 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4514 LU.Kind, LU.AccessTy))
4517 LLVM_DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
4519 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4521 // Transfer the fixups of LU to LUThatHas.
4522 for (LSRFixup &Fixup : LU.Fixups) {
4523 Fixup.Offset += F.BaseOffset;
4524 LUThatHas->pushFixup(Fixup);
4525 LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4528 // Delete formulae from the new use which are no longer legal.
4530 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4531 Formula &F = LUThatHas->Formulae[i];
4532 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4533 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4534 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4535 LUThatHas->DeleteFormula(F);
4543 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4545 // Delete the old use.
4546 DeleteUse(LU, LUIdx);
4553 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4556 /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4557 /// we've done more filtering, as it may be able to find more formulae to
4559 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4560 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4561 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4563 LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4564 "undesirable dedicated registers.\n");
4566 FilterOutUndesirableDedicatedRegisters();
4568 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4572 /// If a LSRUse has multiple formulae with the same ScaledReg and Scale.
4573 /// Pick the best one and delete the others.
4574 /// This narrowing heuristic is to keep as many formulae with different
4575 /// Scale and ScaledReg pair as possible while narrowing the search space.
4576 /// The benefit is that it is more likely to find out a better solution
4577 /// from a formulae set with more Scale and ScaledReg variations than
4578 /// a formulae set with the same Scale and ScaledReg. The picking winner
4579 /// reg heuristic will often keep the formulae with the same Scale and
4580 /// ScaledReg and filter others, and we want to avoid that if possible.
4581 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
4582 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4586 dbgs() << "The search space is too complex.\n"
4587 "Narrowing the search space by choosing the best Formula "
4588 "from the Formulae with the same Scale and ScaledReg.\n");
4590 // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse.
4591 using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>;
4593 BestFormulaeTy BestFormulae;
4595 bool ChangedFormulae = false;
4597 DenseSet<const SCEV *> VisitedRegs;
4598 SmallPtrSet<const SCEV *, 16> Regs;
4600 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4601 LSRUse &LU = Uses[LUIdx];
4602 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
4605 // Return true if Formula FA is better than Formula FB.
4606 auto IsBetterThan = [&](Formula &FA, Formula &FB) {
4607 // First we will try to choose the Formula with fewer new registers.
4608 // For a register used by current Formula, the more the register is
4609 // shared among LSRUses, the less we increase the register number
4610 // counter of the formula.
4611 size_t FARegNum = 0;
4612 for (const SCEV *Reg : FA.BaseRegs) {
4613 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4614 FARegNum += (NumUses - UsedByIndices.count() + 1);
4616 size_t FBRegNum = 0;
4617 for (const SCEV *Reg : FB.BaseRegs) {
4618 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4619 FBRegNum += (NumUses - UsedByIndices.count() + 1);
4621 if (FARegNum != FBRegNum)
4622 return FARegNum < FBRegNum;
4624 // If the new register numbers are the same, choose the Formula with
4626 Cost CostFA(L, SE, TTI);
4627 Cost CostFB(L, SE, TTI);
4629 CostFA.RateFormula(FA, Regs, VisitedRegs, LU);
4631 CostFB.RateFormula(FB, Regs, VisitedRegs, LU);
4632 return CostFA.isLess(CostFB);
4636 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4638 Formula &F = LU.Formulae[FIdx];
4641 auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});
4645 Formula &Best = LU.Formulae[P.first->second];
4646 if (IsBetterThan(F, Best))
4648 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
4650 " in favor of formula ";
4651 Best.print(dbgs()); dbgs() << '\n');
4653 ChangedFormulae = true;
4655 LU.DeleteFormula(F);
4661 LU.RecomputeRegs(LUIdx, RegUses);
4663 // Reset this to prepare for the next use.
4664 BestFormulae.clear();
4667 LLVM_DEBUG(if (ChangedFormulae) {
4669 "After filtering out undesirable candidates:\n";
4674 /// If we are over the complexity limit, filter out any post-inc prefering
4675 /// variables to only post-inc values.
4676 void LSRInstance::NarrowSearchSpaceByFilterPostInc() {
4677 if (!TTI.shouldFavorPostInc())
4679 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4682 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"
4683 "Narrowing the search space by choosing the lowest "
4684 "register Formula for PostInc Uses.\n");
4686 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4687 LSRUse &LU = Uses[LUIdx];
4689 if (LU.Kind != LSRUse::Address)
4691 if (!TTI.isIndexedLoadLegal(TTI.MIM_PostInc, LU.AccessTy.getType()) &&
4692 !TTI.isIndexedStoreLegal(TTI.MIM_PostInc, LU.AccessTy.getType()))
4695 size_t MinRegs = std::numeric_limits<size_t>::max();
4696 for (const Formula &F : LU.Formulae)
4697 MinRegs = std::min(F.getNumRegs(), MinRegs);
4700 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4702 Formula &F = LU.Formulae[FIdx];
4703 if (F.getNumRegs() > MinRegs) {
4704 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
4706 LU.DeleteFormula(F);
4713 LU.RecomputeRegs(LUIdx, RegUses);
4715 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4719 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4722 /// The function delete formulas with high registers number expectation.
4723 /// Assuming we don't know the value of each formula (already delete
4724 /// all inefficient), generate probability of not selecting for each
4728 /// reg(a) + reg({0,+,1})
4729 /// reg(a) + reg({-1,+,1}) + 1
4732 /// reg(b) + reg({0,+,1})
4733 /// reg(b) + reg({-1,+,1}) + 1
4736 /// reg(c) + reg(b) + reg({0,+,1})
4737 /// reg(c) + reg({b,+,1})
4739 /// Probability of not selecting
4741 /// reg(a) (1/3) * 1 * 1
4742 /// reg(b) 1 * (1/3) * (1/2)
4743 /// reg({0,+,1}) (2/3) * (2/3) * (1/2)
4744 /// reg({-1,+,1}) (2/3) * (2/3) * 1
4745 /// reg({a,+,1}) (2/3) * 1 * 1
4746 /// reg({b,+,1}) 1 * (2/3) * (2/3)
4747 /// reg(c) 1 * 1 * 0
4749 /// Now count registers number mathematical expectation for each formula:
4750 /// Note that for each use we exclude probability if not selecting for the use.
4751 /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding
4752 /// probabilty 1/3 of not selecting for Use1).
4754 /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted
4755 /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted
4758 /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted
4759 /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted
4760 /// reg({b,+,1}) 2/3
4762 /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted
4763 /// reg(c) + reg({b,+,1}) 1 + 2/3
4764 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4765 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4767 // Ok, we have too many of formulae on our hands to conveniently handle.
4768 // Use a rough heuristic to thin out the list.
4770 // Set of Regs wich will be 100% used in final solution.
4771 // Used in each formula of a solution (in example above this is reg(c)).
4772 // We can skip them in calculations.
4773 SmallPtrSet<const SCEV *, 4> UniqRegs;
4774 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4776 // Map each register to probability of not selecting
4777 DenseMap <const SCEV *, float> RegNumMap;
4778 for (const SCEV *Reg : RegUses) {
4779 if (UniqRegs.count(Reg))
4782 for (const LSRUse &LU : Uses) {
4783 if (!LU.Regs.count(Reg))
4785 float P = LU.getNotSelectedProbability(Reg);
4789 UniqRegs.insert(Reg);
4791 RegNumMap.insert(std::make_pair(Reg, PNotSel));
4795 dbgs() << "Narrowing the search space by deleting costly formulas\n");
4797 // Delete formulas where registers number expectation is high.
4798 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4799 LSRUse &LU = Uses[LUIdx];
4800 // If nothing to delete - continue.
4801 if (LU.Formulae.size() < 2)
4803 // This is temporary solution to test performance. Float should be
4804 // replaced with round independent type (based on integers) to avoid
4805 // different results for different target builds.
4806 float FMinRegNum = LU.Formulae[0].getNumRegs();
4807 float FMinARegNum = LU.Formulae[0].getNumRegs();
4809 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4810 Formula &F = LU.Formulae[i];
4813 for (const SCEV *BaseReg : F.BaseRegs) {
4814 if (UniqRegs.count(BaseReg))
4816 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4817 if (isa<SCEVAddRecExpr>(BaseReg))
4819 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4821 if (const SCEV *ScaledReg = F.ScaledReg) {
4822 if (!UniqRegs.count(ScaledReg)) {
4824 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4825 if (isa<SCEVAddRecExpr>(ScaledReg))
4827 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4830 if (FMinRegNum > FRegNum ||
4831 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
4832 FMinRegNum = FRegNum;
4833 FMinARegNum = FARegNum;
4837 LLVM_DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs());
4838 dbgs() << " with min reg num " << FMinRegNum << '\n');
4840 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
4841 while (LU.Formulae.size() != 1) {
4842 LLVM_DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs());
4844 LU.Formulae.pop_back();
4846 LU.RecomputeRegs(LUIdx, RegUses);
4847 assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula");
4848 Formula &F = LU.Formulae[0];
4849 LLVM_DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n');
4850 // When we choose the formula, the regs become unique.
4851 UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
4853 UniqRegs.insert(F.ScaledReg);
4855 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4858 /// Pick a register which seems likely to be profitable, and then in any use
4859 /// which has any reference to that register, delete all formulae which do not
4860 /// reference that register.
4861 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4862 // With all other options exhausted, loop until the system is simple
4863 // enough to handle.
4864 SmallPtrSet<const SCEV *, 4> Taken;
4865 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4866 // Ok, we have too many of formulae on our hands to conveniently handle.
4867 // Use a rough heuristic to thin out the list.
4868 LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4870 // Pick the register which is used by the most LSRUses, which is likely
4871 // to be a good reuse register candidate.
4872 const SCEV *Best = nullptr;
4873 unsigned BestNum = 0;
4874 for (const SCEV *Reg : RegUses) {
4875 if (Taken.count(Reg))
4879 BestNum = RegUses.getUsedByIndices(Reg).count();
4881 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4882 if (Count > BestNum) {
4888 assert(Best && "Failed to find best LSRUse candidate");
4890 LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
4891 << " will yield profitable reuse.\n");
4894 // In any use with formulae which references this register, delete formulae
4895 // which don't reference it.
4896 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4897 LSRUse &LU = Uses[LUIdx];
4898 if (!LU.Regs.count(Best)) continue;
4901 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4902 Formula &F = LU.Formulae[i];
4903 if (!F.referencesReg(Best)) {
4904 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4905 LU.DeleteFormula(F);
4909 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
4915 LU.RecomputeRegs(LUIdx, RegUses);
4918 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4922 /// If there are an extraordinary number of formulae to choose from, use some
4923 /// rough heuristics to prune down the number of formulae. This keeps the main
4924 /// solver from taking an extraordinary amount of time in some worst-case
4926 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4927 NarrowSearchSpaceByDetectingSupersets();
4928 NarrowSearchSpaceByCollapsingUnrolledCode();
4929 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4930 if (FilterSameScaledReg)
4931 NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
4932 NarrowSearchSpaceByFilterPostInc();
4934 NarrowSearchSpaceByDeletingCostlyFormulas();
4936 NarrowSearchSpaceByPickingWinnerRegs();
4939 /// This is the recursive solver.
4940 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4942 SmallVectorImpl<const Formula *> &Workspace,
4943 const Cost &CurCost,
4944 const SmallPtrSet<const SCEV *, 16> &CurRegs,
4945 DenseSet<const SCEV *> &VisitedRegs) const {
4948 // - use more aggressive filtering
4949 // - sort the formula so that the most profitable solutions are found first
4950 // - sort the uses too
4952 // - don't compute a cost, and then compare. compare while computing a cost
4954 // - track register sets with SmallBitVector
4956 const LSRUse &LU = Uses[Workspace.size()];
4958 // If this use references any register that's already a part of the
4959 // in-progress solution, consider it a requirement that a formula must
4960 // reference that register in order to be considered. This prunes out
4961 // unprofitable searching.
4962 SmallSetVector<const SCEV *, 4> ReqRegs;
4963 for (const SCEV *S : CurRegs)
4964 if (LU.Regs.count(S))
4967 SmallPtrSet<const SCEV *, 16> NewRegs;
4968 Cost NewCost(L, SE, TTI);
4969 for (const Formula &F : LU.Formulae) {
4970 // Ignore formulae which may not be ideal in terms of register reuse of
4971 // ReqRegs. The formula should use all required registers before
4972 // introducing new ones.
4973 // This can sometimes (notably when trying to favour postinc) lead to
4974 // sub-optimial decisions. There it is best left to the cost modelling to
4976 if (!TTI.shouldFavorPostInc() || LU.Kind != LSRUse::Address) {
4977 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
4978 for (const SCEV *Reg : ReqRegs) {
4979 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4980 is_contained(F.BaseRegs, Reg)) {
4982 if (NumReqRegsToFind == 0)
4986 if (NumReqRegsToFind != 0) {
4987 // If none of the formulae satisfied the required registers, then we could
4988 // clear ReqRegs and try again. Currently, we simply give up in this case.
4993 // Evaluate the cost of the current formula. If it's already worse than
4994 // the current best, prune the search at that point.
4997 NewCost.RateFormula(F, NewRegs, VisitedRegs, LU);
4998 if (NewCost.isLess(SolutionCost)) {
4999 Workspace.push_back(&F);
5000 if (Workspace.size() != Uses.size()) {
5001 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
5002 NewRegs, VisitedRegs);
5003 if (F.getNumRegs() == 1 && Workspace.size() == 1)
5004 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
5006 LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
5007 dbgs() << ".\nRegs:\n";
5008 for (const SCEV *S : NewRegs) dbgs()
5009 << "- " << *S << "\n";
5012 SolutionCost = NewCost;
5013 Solution = Workspace;
5015 Workspace.pop_back();
5020 /// Choose one formula from each use. Return the results in the given Solution
5022 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
5023 SmallVector<const Formula *, 8> Workspace;
5024 Cost SolutionCost(L, SE, TTI);
5025 SolutionCost.Lose();
5026 Cost CurCost(L, SE, TTI);
5027 SmallPtrSet<const SCEV *, 16> CurRegs;
5028 DenseSet<const SCEV *> VisitedRegs;
5029 Workspace.reserve(Uses.size());
5031 // SolveRecurse does all the work.
5032 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
5033 CurRegs, VisitedRegs);
5034 if (Solution.empty()) {
5035 LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
5039 // Ok, we've now made all our decisions.
5040 LLVM_DEBUG(dbgs() << "\n"
5041 "The chosen solution requires ";
5042 SolutionCost.print(dbgs()); dbgs() << ":\n";
5043 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
5045 Uses[i].print(dbgs());
5048 Solution[i]->print(dbgs());
5052 assert(Solution.size() == Uses.size() && "Malformed solution!");
5055 /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
5056 /// we can go while still being dominated by the input positions. This helps
5057 /// canonicalize the insert position, which encourages sharing.
5058 BasicBlock::iterator
5059 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
5060 const SmallVectorImpl<Instruction *> &Inputs)
5062 Instruction *Tentative = &*IP;
5064 bool AllDominate = true;
5065 Instruction *BetterPos = nullptr;
5066 // Don't bother attempting to insert before a catchswitch, their basic block
5067 // cannot have other non-PHI instructions.
5068 if (isa<CatchSwitchInst>(Tentative))
5071 for (Instruction *Inst : Inputs) {
5072 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
5073 AllDominate = false;
5076 // Attempt to find an insert position in the middle of the block,
5077 // instead of at the end, so that it can be used for other expansions.
5078 if (Tentative->getParent() == Inst->getParent() &&
5079 (!BetterPos || !DT.dominates(Inst, BetterPos)))
5080 BetterPos = &*std::next(BasicBlock::iterator(Inst));
5085 IP = BetterPos->getIterator();
5087 IP = Tentative->getIterator();
5089 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
5090 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
5093 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
5094 if (!Rung) return IP;
5095 Rung = Rung->getIDom();
5096 if (!Rung) return IP;
5097 IDom = Rung->getBlock();
5099 // Don't climb into a loop though.
5100 const Loop *IDomLoop = LI.getLoopFor(IDom);
5101 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
5102 if (IDomDepth <= IPLoopDepth &&
5103 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
5107 Tentative = IDom->getTerminator();
5113 /// Determine an input position which will be dominated by the operands and
5114 /// which will dominate the result.
5115 BasicBlock::iterator
5116 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
5119 SCEVExpander &Rewriter) const {
5120 // Collect some instructions which must be dominated by the
5121 // expanding replacement. These must be dominated by any operands that
5122 // will be required in the expansion.
5123 SmallVector<Instruction *, 4> Inputs;
5124 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
5125 Inputs.push_back(I);
5126 if (LU.Kind == LSRUse::ICmpZero)
5127 if (Instruction *I =
5128 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
5129 Inputs.push_back(I);
5130 if (LF.PostIncLoops.count(L)) {
5131 if (LF.isUseFullyOutsideLoop(L))
5132 Inputs.push_back(L->getLoopLatch()->getTerminator());
5134 Inputs.push_back(IVIncInsertPos);
5136 // The expansion must also be dominated by the increment positions of any
5137 // loops it for which it is using post-inc mode.
5138 for (const Loop *PIL : LF.PostIncLoops) {
5139 if (PIL == L) continue;
5141 // Be dominated by the loop exit.
5142 SmallVector<BasicBlock *, 4> ExitingBlocks;
5143 PIL->getExitingBlocks(ExitingBlocks);
5144 if (!ExitingBlocks.empty()) {
5145 BasicBlock *BB = ExitingBlocks[0];
5146 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
5147 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
5148 Inputs.push_back(BB->getTerminator());
5152 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
5153 && !isa<DbgInfoIntrinsic>(LowestIP) &&
5154 "Insertion point must be a normal instruction");
5156 // Then, climb up the immediate dominator tree as far as we can go while
5157 // still being dominated by the input positions.
5158 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
5160 // Don't insert instructions before PHI nodes.
5161 while (isa<PHINode>(IP)) ++IP;
5163 // Ignore landingpad instructions.
5164 while (IP->isEHPad()) ++IP;
5166 // Ignore debug intrinsics.
5167 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
5169 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
5170 // IP consistent across expansions and allows the previously inserted
5171 // instructions to be reused by subsequent expansion.
5172 while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
5178 /// Emit instructions for the leading candidate expression for this LSRUse (this
5179 /// is called "expanding").
5180 Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF,
5181 const Formula &F, BasicBlock::iterator IP,
5182 SCEVExpander &Rewriter,
5183 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5184 if (LU.RigidFormula)
5185 return LF.OperandValToReplace;
5187 // Determine an input position which will be dominated by the operands and
5188 // which will dominate the result.
5189 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
5190 Rewriter.setInsertPoint(&*IP);
5192 // Inform the Rewriter if we have a post-increment use, so that it can
5193 // perform an advantageous expansion.
5194 Rewriter.setPostInc(LF.PostIncLoops);
5196 // This is the type that the user actually needs.
5197 Type *OpTy = LF.OperandValToReplace->getType();
5198 // This will be the type that we'll initially expand to.
5199 Type *Ty = F.getType();
5201 // No type known; just expand directly to the ultimate type.
5203 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
5204 // Expand directly to the ultimate type if it's the right size.
5206 // This is the type to do integer arithmetic in.
5207 Type *IntTy = SE.getEffectiveSCEVType(Ty);
5209 // Build up a list of operands to add together to form the full base.
5210 SmallVector<const SCEV *, 8> Ops;
5212 // Expand the BaseRegs portion.
5213 for (const SCEV *Reg : F.BaseRegs) {
5214 assert(!Reg->isZero() && "Zero allocated in a base register!");
5216 // If we're expanding for a post-inc user, make the post-inc adjustment.
5217 Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE);
5218 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr)));
5221 // Expand the ScaledReg portion.
5222 Value *ICmpScaledV = nullptr;
5224 const SCEV *ScaledS = F.ScaledReg;
5226 // If we're expanding for a post-inc user, make the post-inc adjustment.
5227 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
5228 ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE);
5230 if (LU.Kind == LSRUse::ICmpZero) {
5231 // Expand ScaleReg as if it was part of the base regs.
5234 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)));
5236 // An interesting way of "folding" with an icmp is to use a negated
5237 // scale, which we'll implement by inserting it into the other operand
5239 assert(F.Scale == -1 &&
5240 "The only scale supported by ICmpZero uses is -1!");
5241 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr);
5244 // Otherwise just expand the scaled register and an explicit scale,
5245 // which is expected to be matched as part of the address.
5247 // Flush the operand list to suppress SCEVExpander hoisting address modes.
5248 // Unless the addressing mode will not be folded.
5249 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
5250 isAMCompletelyFolded(TTI, LU, F)) {
5251 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr);
5253 Ops.push_back(SE.getUnknown(FullV));
5255 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr));
5258 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
5259 Ops.push_back(ScaledS);
5263 // Expand the GV portion.
5265 // Flush the operand list to suppress SCEVExpander hoisting.
5267 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
5269 Ops.push_back(SE.getUnknown(FullV));
5271 Ops.push_back(SE.getUnknown(F.BaseGV));
5274 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
5275 // unfolded offsets. LSR assumes they both live next to their uses.
5277 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
5279 Ops.push_back(SE.getUnknown(FullV));
5282 // Expand the immediate portion.
5283 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
5285 if (LU.Kind == LSRUse::ICmpZero) {
5286 // The other interesting way of "folding" with an ICmpZero is to use a
5287 // negated immediate.
5289 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
5291 Ops.push_back(SE.getUnknown(ICmpScaledV));
5292 ICmpScaledV = ConstantInt::get(IntTy, Offset);
5295 // Just add the immediate values. These again are expected to be matched
5296 // as part of the address.
5297 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
5301 // Expand the unfolded offset portion.
5302 int64_t UnfoldedOffset = F.UnfoldedOffset;
5303 if (UnfoldedOffset != 0) {
5304 // Just add the immediate values.
5305 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
5309 // Emit instructions summing all the operands.
5310 const SCEV *FullS = Ops.empty() ?
5311 SE.getConstant(IntTy, 0) :
5313 Value *FullV = Rewriter.expandCodeFor(FullS, Ty);
5315 // We're done expanding now, so reset the rewriter.
5316 Rewriter.clearPostInc();
5318 // An ICmpZero Formula represents an ICmp which we're handling as a
5319 // comparison against zero. Now that we've expanded an expression for that
5320 // form, update the ICmp's other operand.
5321 if (LU.Kind == LSRUse::ICmpZero) {
5322 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
5323 if (auto *OperandIsInstr = dyn_cast<Instruction>(CI->getOperand(1)))
5324 DeadInsts.emplace_back(OperandIsInstr);
5325 assert(!F.BaseGV && "ICmp does not support folding a global value and "
5326 "a scale at the same time!");
5327 if (F.Scale == -1) {
5328 if (ICmpScaledV->getType() != OpTy) {
5330 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
5332 ICmpScaledV, OpTy, "tmp", CI);
5335 CI->setOperand(1, ICmpScaledV);
5337 // A scale of 1 means that the scale has been expanded as part of the
5339 assert((F.Scale == 0 || F.Scale == 1) &&
5340 "ICmp does not support folding a global value and "
5341 "a scale at the same time!");
5342 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
5344 if (C->getType() != OpTy)
5345 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5349 CI->setOperand(1, C);
5356 /// Helper for Rewrite. PHI nodes are special because the use of their operands
5357 /// effectively happens in their predecessor blocks, so the expression may need
5358 /// to be expanded in multiple places.
5359 void LSRInstance::RewriteForPHI(
5360 PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F,
5361 SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5362 DenseMap<BasicBlock *, Value *> Inserted;
5363 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5364 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
5365 bool needUpdateFixups = false;
5366 BasicBlock *BB = PN->getIncomingBlock(i);
5368 // If this is a critical edge, split the edge so that we do not insert
5369 // the code on all predecessor/successor paths. We do this unless this
5370 // is the canonical backedge for this loop, which complicates post-inc
5372 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
5373 !isa<IndirectBrInst>(BB->getTerminator()) &&
5374 !isa<CatchSwitchInst>(BB->getTerminator())) {
5375 BasicBlock *Parent = PN->getParent();
5376 Loop *PNLoop = LI.getLoopFor(Parent);
5377 if (!PNLoop || Parent != PNLoop->getHeader()) {
5378 // Split the critical edge.
5379 BasicBlock *NewBB = nullptr;
5380 if (!Parent->isLandingPad()) {
5381 NewBB = SplitCriticalEdge(BB, Parent,
5382 CriticalEdgeSplittingOptions(&DT, &LI)
5383 .setMergeIdenticalEdges()
5384 .setKeepOneInputPHIs());
5386 SmallVector<BasicBlock*, 2> NewBBs;
5387 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI);
5390 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
5391 // phi predecessors are identical. The simple thing to do is skip
5392 // splitting in this case rather than complicate the API.
5394 // If PN is outside of the loop and BB is in the loop, we want to
5395 // move the block to be immediately before the PHI block, not
5396 // immediately after BB.
5397 if (L->contains(BB) && !L->contains(PN))
5398 NewBB->moveBefore(PN->getParent());
5400 // Splitting the edge can reduce the number of PHI entries we have.
5401 e = PN->getNumIncomingValues();
5403 i = PN->getBasicBlockIndex(BB);
5405 needUpdateFixups = true;
5410 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
5411 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
5413 PN->setIncomingValue(i, Pair.first->second);
5415 Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(),
5416 Rewriter, DeadInsts);
5418 // If this is reuse-by-noop-cast, insert the noop cast.
5419 Type *OpTy = LF.OperandValToReplace->getType();
5420 if (FullV->getType() != OpTy)
5422 CastInst::Create(CastInst::getCastOpcode(FullV, false,
5424 FullV, LF.OperandValToReplace->getType(),
5425 "tmp", BB->getTerminator());
5427 PN->setIncomingValue(i, FullV);
5428 Pair.first->second = FullV;
5431 // If LSR splits critical edge and phi node has other pending
5432 // fixup operands, we need to update those pending fixups. Otherwise
5433 // formulae will not be implemented completely and some instructions
5434 // will not be eliminated.
5435 if (needUpdateFixups) {
5436 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5437 for (LSRFixup &Fixup : Uses[LUIdx].Fixups)
5438 // If fixup is supposed to rewrite some operand in the phi
5439 // that was just updated, it may be already moved to
5440 // another phi node. Such fixup requires update.
5441 if (Fixup.UserInst == PN) {
5442 // Check if the operand we try to replace still exists in the
5444 bool foundInOriginalPHI = false;
5445 for (const auto &val : PN->incoming_values())
5446 if (val == Fixup.OperandValToReplace) {
5447 foundInOriginalPHI = true;
5451 // If fixup operand found in original PHI - nothing to do.
5452 if (foundInOriginalPHI)
5455 // Otherwise it might be moved to another PHI and requires update.
5456 // If fixup operand not found in any of the incoming blocks that
5457 // means we have already rewritten it - nothing to do.
5458 for (const auto &Block : PN->blocks())
5459 for (BasicBlock::iterator I = Block->begin(); isa<PHINode>(I);
5461 PHINode *NewPN = cast<PHINode>(I);
5462 for (const auto &val : NewPN->incoming_values())
5463 if (val == Fixup.OperandValToReplace)
5464 Fixup.UserInst = NewPN;
5471 /// Emit instructions for the leading candidate expression for this LSRUse (this
5472 /// is called "expanding"), and update the UserInst to reference the newly
5474 void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF,
5475 const Formula &F, SCEVExpander &Rewriter,
5476 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5477 // First, find an insertion point that dominates UserInst. For PHI nodes,
5478 // find the nearest block which dominates all the relevant uses.
5479 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
5480 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
5483 Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
5485 // If this is reuse-by-noop-cast, insert the noop cast.
5486 Type *OpTy = LF.OperandValToReplace->getType();
5487 if (FullV->getType() != OpTy) {
5489 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
5490 FullV, OpTy, "tmp", LF.UserInst);
5494 // Update the user. ICmpZero is handled specially here (for now) because
5495 // Expand may have updated one of the operands of the icmp already, and
5496 // its new value may happen to be equal to LF.OperandValToReplace, in
5497 // which case doing replaceUsesOfWith leads to replacing both operands
5498 // with the same value. TODO: Reorganize this.
5499 if (LU.Kind == LSRUse::ICmpZero)
5500 LF.UserInst->setOperand(0, FullV);
5502 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
5505 if (auto *OperandIsInstr = dyn_cast<Instruction>(LF.OperandValToReplace))
5506 DeadInsts.emplace_back(OperandIsInstr);
5509 /// Rewrite all the fixup locations with new values, following the chosen
5511 void LSRInstance::ImplementSolution(
5512 const SmallVectorImpl<const Formula *> &Solution) {
5513 // Keep track of instructions we may have made dead, so that
5514 // we can remove them after we are done working.
5515 SmallVector<WeakTrackingVH, 16> DeadInsts;
5517 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
5520 Rewriter.setDebugType(DEBUG_TYPE);
5522 Rewriter.disableCanonicalMode();
5523 Rewriter.enableLSRMode();
5524 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
5526 // Mark phi nodes that terminate chains so the expander tries to reuse them.
5527 for (const IVChain &Chain : IVChainVec) {
5528 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
5529 Rewriter.setChainedPhi(PN);
5532 // Expand the new value definitions and update the users.
5533 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5534 for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
5535 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
5539 for (const IVChain &Chain : IVChainVec) {
5540 GenerateIVChain(Chain, Rewriter, DeadInsts);
5543 // Clean up after ourselves. This must be done before deleting any
5547 Changed |= RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts,
5551 LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5552 DominatorTree &DT, LoopInfo &LI,
5553 const TargetTransformInfo &TTI, AssumptionCache &AC,
5554 TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU)
5555 : IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), TLI(TLI), TTI(TTI), L(L),
5556 MSSAU(MSSAU), FavorBackedgeIndex(EnableBackedgeIndexing &&
5557 TTI.shouldFavorBackedgeIndex(L)) {
5558 // If LoopSimplify form is not available, stay out of trouble.
5559 if (!L->isLoopSimplifyForm())
5562 // If there's no interesting work to be done, bail early.
5563 if (IU.empty()) return;
5565 // If there's too much analysis to be done, bail early. We won't be able to
5566 // model the problem anyway.
5567 unsigned NumUsers = 0;
5568 for (const IVStrideUse &U : IU) {
5569 if (++NumUsers > MaxIVUsers) {
5571 LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U
5575 // Bail out if we have a PHI on an EHPad that gets a value from a
5576 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is
5577 // no good place to stick any instructions.
5578 if (auto *PN = dyn_cast<PHINode>(U.getUser())) {
5579 auto *FirstNonPHI = PN->getParent()->getFirstNonPHI();
5580 if (isa<FuncletPadInst>(FirstNonPHI) ||
5581 isa<CatchSwitchInst>(FirstNonPHI))
5582 for (BasicBlock *PredBB : PN->blocks())
5583 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
5589 // All dominating loops must have preheaders, or SCEVExpander may not be able
5590 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
5592 // IVUsers analysis should only create users that are dominated by simple loop
5593 // headers. Since this loop should dominate all of its users, its user list
5594 // should be empty if this loop itself is not within a simple loop nest.
5595 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
5596 Rung; Rung = Rung->getIDom()) {
5597 BasicBlock *BB = Rung->getBlock();
5598 const Loop *DomLoop = LI.getLoopFor(BB);
5599 if (DomLoop && DomLoop->getHeader() == BB) {
5600 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
5605 LLVM_DEBUG(dbgs() << "\nLSR on loop ";
5606 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
5609 // First, perform some low-level loop optimizations.
5611 OptimizeLoopTermCond();
5613 // If loop preparation eliminates all interesting IV users, bail.
5614 if (IU.empty()) return;
5616 // Skip nested loops until we can model them better with formulae.
5618 LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
5622 // Start collecting data and preparing for the solver.
5624 CollectInterestingTypesAndFactors();
5625 CollectFixupsAndInitialFormulae();
5626 CollectLoopInvariantFixupsAndFormulae();
5631 LLVM_DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
5632 print_uses(dbgs()));
5634 // Now use the reuse data to generate a bunch of interesting ways
5635 // to formulate the values needed for the uses.
5636 GenerateAllReuseFormulae();
5638 FilterOutUndesirableDedicatedRegisters();
5639 NarrowSearchSpaceUsingHeuristics();
5641 SmallVector<const Formula *, 8> Solution;
5644 // Release memory that is no longer needed.
5649 if (Solution.empty())
5653 // Formulae should be legal.
5654 for (const LSRUse &LU : Uses) {
5655 for (const Formula &F : LU.Formulae)
5656 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
5657 F) && "Illegal formula generated!");
5661 // Now that we've decided what we want, make it so.
5662 ImplementSolution(Solution);
5665 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5666 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
5667 if (Factors.empty() && Types.empty()) return;
5669 OS << "LSR has identified the following interesting factors and types: ";
5672 for (int64_t Factor : Factors) {
5673 if (!First) OS << ", ";
5675 OS << '*' << Factor;
5678 for (Type *Ty : Types) {
5679 if (!First) OS << ", ";
5681 OS << '(' << *Ty << ')';
5686 void LSRInstance::print_fixups(raw_ostream &OS) const {
5687 OS << "LSR is examining the following fixup sites:\n";
5688 for (const LSRUse &LU : Uses)
5689 for (const LSRFixup &LF : LU.Fixups) {
5696 void LSRInstance::print_uses(raw_ostream &OS) const {
5697 OS << "LSR is examining the following uses:\n";
5698 for (const LSRUse &LU : Uses) {
5702 for (const Formula &F : LU.Formulae) {
5710 void LSRInstance::print(raw_ostream &OS) const {
5711 print_factors_and_types(OS);
5716 LLVM_DUMP_METHOD void LSRInstance::dump() const {
5717 print(errs()); errs() << '\n';
5723 class LoopStrengthReduce : public LoopPass {
5725 static char ID; // Pass ID, replacement for typeid
5727 LoopStrengthReduce();
5730 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
5731 void getAnalysisUsage(AnalysisUsage &AU) const override;
5734 } // end anonymous namespace
5736 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
5737 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
5740 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
5741 // We split critical edges, so we change the CFG. However, we do update
5742 // many analyses if they are around.
5743 AU.addPreservedID(LoopSimplifyID);
5745 AU.addRequired<LoopInfoWrapperPass>();
5746 AU.addPreserved<LoopInfoWrapperPass>();
5747 AU.addRequiredID(LoopSimplifyID);
5748 AU.addRequired<DominatorTreeWrapperPass>();
5749 AU.addPreserved<DominatorTreeWrapperPass>();
5750 AU.addRequired<ScalarEvolutionWrapperPass>();
5751 AU.addPreserved<ScalarEvolutionWrapperPass>();
5752 AU.addRequired<AssumptionCacheTracker>();
5753 AU.addRequired<TargetLibraryInfoWrapperPass>();
5754 // Requiring LoopSimplify a second time here prevents IVUsers from running
5755 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5756 AU.addRequiredID(LoopSimplifyID);
5757 AU.addRequired<IVUsersWrapperPass>();
5758 AU.addPreserved<IVUsersWrapperPass>();
5759 AU.addRequired<TargetTransformInfoWrapperPass>();
5760 AU.addPreserved<MemorySSAWrapperPass>();
5763 static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5764 DominatorTree &DT, LoopInfo &LI,
5765 const TargetTransformInfo &TTI,
5766 AssumptionCache &AC, TargetLibraryInfo &TLI,
5769 bool Changed = false;
5770 std::unique_ptr<MemorySSAUpdater> MSSAU;
5772 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
5774 // Run the main LSR transformation.
5776 LSRInstance(L, IU, SE, DT, LI, TTI, AC, TLI, MSSAU.get()).getChanged();
5778 // Remove any extra phis created by processing inner loops.
5779 Changed |= DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());
5780 if (EnablePhiElim && L->isLoopSimplifyForm()) {
5781 SmallVector<WeakTrackingVH, 16> DeadInsts;
5782 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
5783 SCEVExpander Rewriter(SE, DL, "lsr");
5785 Rewriter.setDebugType(DEBUG_TYPE);
5787 unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI);
5790 RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, &TLI,
5792 DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());
5798 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
5802 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5803 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5804 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5805 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5806 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5807 *L->getHeader()->getParent());
5808 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
5809 *L->getHeader()->getParent());
5810 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
5811 *L->getHeader()->getParent());
5812 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
5813 MemorySSA *MSSA = nullptr;
5815 MSSA = &MSSAAnalysis->getMSSA();
5816 return ReduceLoopStrength(L, IU, SE, DT, LI, TTI, AC, TLI, MSSA);
5819 PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,
5820 LoopStandardAnalysisResults &AR,
5822 if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE,
5823 AR.DT, AR.LI, AR.TTI, AR.AC, AR.TLI, AR.MSSA))
5824 return PreservedAnalyses::all();
5826 auto PA = getLoopPassPreservedAnalyses();
5828 PA.preserve<MemorySSAAnalysis>();
5832 char LoopStrengthReduce::ID = 0;
5834 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
5835 "Loop Strength Reduction", false, false)
5836 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5837 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5838 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5839 INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass)
5840 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5841 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5842 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
5843 "Loop Strength Reduction", false, false)
5845 Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }