1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into forms suitable for efficient execution
14 // This pass performs a strength reduction on array references inside loops that
15 // have as one or more of their components the loop induction variable, it
16 // rewrites expressions to take advantage of scaled-index addressing modes
17 // available on the target, and it performs a variety of other optimizations
18 // related to loop induction variables.
20 // Terminology note: this code has a lot of handling for "post-increment" or
21 // "post-inc" users. This is not talking about post-increment addressing modes;
22 // it is instead talking about code like this:
24 // %i = phi [ 0, %entry ], [ %i.next, %latch ]
26 // %i.next = add %i, 1
27 // %c = icmp eq %i.next, %n
29 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
30 // it's useful to think about these as the same register, with some uses using
31 // the value of the register before the add and some using // it after. In this
32 // example, the icmp is a post-increment user, since it uses %i.next, which is
33 // the value of the induction variable after the increment. The other common
34 // case of post-increment users is users outside the loop.
36 // TODO: More sophistication in the way Formulae are generated and filtered.
38 // TODO: Handle multiple loops at a time.
40 // TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
41 // instead of a GlobalValue?
43 // TODO: When truncation is free, truncate ICmp users' operands to make it a
44 // smaller encoding (on x86 at least).
46 // TODO: When a negated register is used by an add (such as in a list of
47 // multiple base registers, or as the increment expression in an addrec),
48 // we may not actually need both reg and (-1 * reg) in registers; the
49 // negation can be implemented by using a sub instead of an add. The
50 // lack of support for taking this into consideration when making
51 // register pressure decisions is partly worked around by the "Special"
54 //===----------------------------------------------------------------------===//
56 #define DEBUG_TYPE "loop-reduce"
57 #include "llvm/Transforms/Scalar.h"
58 #include "llvm/Constants.h"
59 #include "llvm/Instructions.h"
60 #include "llvm/IntrinsicInst.h"
61 #include "llvm/DerivedTypes.h"
62 #include "llvm/Analysis/IVUsers.h"
63 #include "llvm/Analysis/Dominators.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolutionExpander.h"
66 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
67 #include "llvm/Transforms/Utils/Local.h"
68 #include "llvm/ADT/SmallBitVector.h"
69 #include "llvm/ADT/SetVector.h"
70 #include "llvm/ADT/DenseSet.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ValueHandle.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetLowering.h"
80 /// RegSortData - This class holds data which is used to order reuse candidates.
83 /// UsedByIndices - This represents the set of LSRUse indices which reference
84 /// a particular register.
85 SmallBitVector UsedByIndices;
89 void print(raw_ostream &OS) const;
95 void RegSortData::print(raw_ostream &OS) const {
96 OS << "[NumUses=" << UsedByIndices.count() << ']';
99 void RegSortData::dump() const {
100 print(errs()); errs() << '\n';
105 /// RegUseTracker - Map register candidates to information about how they are
107 class RegUseTracker {
108 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
110 RegUsesTy RegUsesMap;
111 SmallVector<const SCEV *, 16> RegSequence;
114 void CountRegister(const SCEV *Reg, size_t LUIdx);
115 void DropRegister(const SCEV *Reg, size_t LUIdx);
116 void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
118 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
120 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
124 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
125 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
126 iterator begin() { return RegSequence.begin(); }
127 iterator end() { return RegSequence.end(); }
128 const_iterator begin() const { return RegSequence.begin(); }
129 const_iterator end() const { return RegSequence.end(); }
135 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
136 std::pair<RegUsesTy::iterator, bool> Pair =
137 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
138 RegSortData &RSD = Pair.first->second;
140 RegSequence.push_back(Reg);
141 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
142 RSD.UsedByIndices.set(LUIdx);
146 RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
147 RegUsesTy::iterator It = RegUsesMap.find(Reg);
148 assert(It != RegUsesMap.end());
149 RegSortData &RSD = It->second;
150 assert(RSD.UsedByIndices.size() > LUIdx);
151 RSD.UsedByIndices.reset(LUIdx);
155 RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
156 assert(LUIdx <= LastLUIdx);
158 // Update RegUses. The data structure is not optimized for this purpose;
159 // we must iterate through it and update each of the bit vectors.
160 for (RegUsesTy::iterator I = RegUsesMap.begin(), E = RegUsesMap.end();
162 SmallBitVector &UsedByIndices = I->second.UsedByIndices;
163 if (LUIdx < UsedByIndices.size())
164 UsedByIndices[LUIdx] =
165 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
166 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
171 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
172 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
173 if (I == RegUsesMap.end())
175 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
176 int i = UsedByIndices.find_first();
177 if (i == -1) return false;
178 if ((size_t)i != LUIdx) return true;
179 return UsedByIndices.find_next(i) != -1;
182 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
183 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
184 assert(I != RegUsesMap.end() && "Unknown register!");
185 return I->second.UsedByIndices;
188 void RegUseTracker::clear() {
195 /// Formula - This class holds information that describes a formula for
196 /// computing satisfying a use. It may include broken-out immediates and scaled
199 /// AM - This is used to represent complex addressing, as well as other kinds
200 /// of interesting uses.
201 TargetLowering::AddrMode AM;
203 /// BaseRegs - The list of "base" registers for this use. When this is
204 /// non-empty, AM.HasBaseReg should be set to true.
205 SmallVector<const SCEV *, 2> BaseRegs;
207 /// ScaledReg - The 'scaled' register for this use. This should be non-null
208 /// when AM.Scale is not zero.
209 const SCEV *ScaledReg;
211 Formula() : ScaledReg(0) {}
213 void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
215 unsigned getNumRegs() const;
216 const Type *getType() const;
218 void DeleteBaseReg(const SCEV *&S);
220 bool referencesReg(const SCEV *S) const;
221 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
222 const RegUseTracker &RegUses) const;
224 void print(raw_ostream &OS) const;
230 /// DoInitialMatch - Recursion helper for InitialMatch.
231 static void DoInitialMatch(const SCEV *S, Loop *L,
232 SmallVectorImpl<const SCEV *> &Good,
233 SmallVectorImpl<const SCEV *> &Bad,
234 ScalarEvolution &SE) {
235 // Collect expressions which properly dominate the loop header.
236 if (SE.properlyDominates(S, L->getHeader())) {
241 // Look at add operands.
242 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
243 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
245 DoInitialMatch(*I, L, Good, Bad, SE);
249 // Look at addrec operands.
250 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
251 if (!AR->getStart()->isZero()) {
252 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
253 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
254 AR->getStepRecurrence(SE),
260 // Handle a multiplication by -1 (negation) if it didn't fold.
261 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
262 if (Mul->getOperand(0)->isAllOnesValue()) {
263 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
264 const SCEV *NewMul = SE.getMulExpr(Ops);
266 SmallVector<const SCEV *, 4> MyGood;
267 SmallVector<const SCEV *, 4> MyBad;
268 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
269 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
270 SE.getEffectiveSCEVType(NewMul->getType())));
271 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
272 E = MyGood.end(); I != E; ++I)
273 Good.push_back(SE.getMulExpr(NegOne, *I));
274 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
275 E = MyBad.end(); I != E; ++I)
276 Bad.push_back(SE.getMulExpr(NegOne, *I));
280 // Ok, we can't do anything interesting. Just stuff the whole thing into a
281 // register and hope for the best.
285 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
286 /// attempting to keep all loop-invariant and loop-computable values in a
287 /// single base register.
288 void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
289 SmallVector<const SCEV *, 4> Good;
290 SmallVector<const SCEV *, 4> Bad;
291 DoInitialMatch(S, L, Good, Bad, SE);
293 const SCEV *Sum = SE.getAddExpr(Good);
295 BaseRegs.push_back(Sum);
296 AM.HasBaseReg = true;
299 const SCEV *Sum = SE.getAddExpr(Bad);
301 BaseRegs.push_back(Sum);
302 AM.HasBaseReg = true;
306 /// getNumRegs - Return the total number of register operands used by this
307 /// formula. This does not include register uses implied by non-constant
309 unsigned Formula::getNumRegs() const {
310 return !!ScaledReg + BaseRegs.size();
313 /// getType - Return the type of this formula, if it has one, or null
314 /// otherwise. This type is meaningless except for the bit size.
315 const Type *Formula::getType() const {
316 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
317 ScaledReg ? ScaledReg->getType() :
318 AM.BaseGV ? AM.BaseGV->getType() :
322 /// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
323 void Formula::DeleteBaseReg(const SCEV *&S) {
324 if (&S != &BaseRegs.back())
325 std::swap(S, BaseRegs.back());
329 /// referencesReg - Test if this formula references the given register.
330 bool Formula::referencesReg(const SCEV *S) const {
331 return S == ScaledReg ||
332 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
335 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
336 /// which are used by uses other than the use with the given index.
337 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
338 const RegUseTracker &RegUses) const {
340 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
342 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
343 E = BaseRegs.end(); I != E; ++I)
344 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
349 void Formula::print(raw_ostream &OS) const {
352 if (!First) OS << " + "; else First = false;
353 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
355 if (AM.BaseOffs != 0) {
356 if (!First) OS << " + "; else First = false;
359 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
360 E = BaseRegs.end(); I != E; ++I) {
361 if (!First) OS << " + "; else First = false;
362 OS << "reg(" << **I << ')';
364 if (AM.HasBaseReg && BaseRegs.empty()) {
365 if (!First) OS << " + "; else First = false;
366 OS << "**error: HasBaseReg**";
367 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
368 if (!First) OS << " + "; else First = false;
369 OS << "**error: !HasBaseReg**";
372 if (!First) OS << " + "; else First = false;
373 OS << AM.Scale << "*reg(";
382 void Formula::dump() const {
383 print(errs()); errs() << '\n';
386 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
387 /// without changing its value.
388 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
390 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
391 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
394 /// isAddSExtable - Return true if the given add can be sign-extended
395 /// without changing its value.
396 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
398 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
399 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
402 /// isMulSExtable - Return true if the given mul can be sign-extended
403 /// without changing its value.
404 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
406 IntegerType::get(SE.getContext(),
407 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
408 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
411 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
412 /// and if the remainder is known to be zero, or null otherwise. If
413 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
414 /// to Y, ignoring that the multiplication may overflow, which is useful when
415 /// the result will be used in a context where the most significant bits are
417 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
419 bool IgnoreSignificantBits = false) {
420 // Handle the trivial case, which works for any SCEV type.
422 return SE.getConstant(LHS->getType(), 1);
424 // Handle a few RHS special cases.
425 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
427 const APInt &RA = RC->getValue()->getValue();
428 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
430 if (RA.isAllOnesValue())
431 return SE.getMulExpr(LHS, RC);
432 // Handle x /s 1 as x.
437 // Check for a division of a constant by a constant.
438 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
441 const APInt &LA = C->getValue()->getValue();
442 const APInt &RA = RC->getValue()->getValue();
443 if (LA.srem(RA) != 0)
445 return SE.getConstant(LA.sdiv(RA));
448 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
449 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
450 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
451 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
452 IgnoreSignificantBits);
454 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
455 IgnoreSignificantBits);
456 if (!Start) return 0;
457 return SE.getAddRecExpr(Start, Step, AR->getLoop());
462 // Distribute the sdiv over add operands, if the add doesn't overflow.
463 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
464 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
465 SmallVector<const SCEV *, 8> Ops;
466 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
468 const SCEV *Op = getExactSDiv(*I, RHS, SE,
469 IgnoreSignificantBits);
473 return SE.getAddExpr(Ops);
478 // Check for a multiply operand that we can pull RHS out of.
479 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
480 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
481 SmallVector<const SCEV *, 4> Ops;
483 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
487 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
488 IgnoreSignificantBits)) {
494 return Found ? SE.getMulExpr(Ops) : 0;
499 // Otherwise we don't know.
503 /// ExtractImmediate - If S involves the addition of a constant integer value,
504 /// return that integer value, and mutate S to point to a new SCEV with that
506 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
507 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
508 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
509 S = SE.getConstant(C->getType(), 0);
510 return C->getValue()->getSExtValue();
512 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
513 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
514 int64_t Result = ExtractImmediate(NewOps.front(), SE);
516 S = SE.getAddExpr(NewOps);
518 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
519 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
520 int64_t Result = ExtractImmediate(NewOps.front(), SE);
522 S = SE.getAddRecExpr(NewOps, AR->getLoop());
528 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
529 /// return that symbol, and mutate S to point to a new SCEV with that
531 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
532 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
533 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
534 S = SE.getConstant(GV->getType(), 0);
537 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
538 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
539 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
541 S = SE.getAddExpr(NewOps);
543 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
544 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
545 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
547 S = SE.getAddRecExpr(NewOps, AR->getLoop());
553 /// isAddressUse - Returns true if the specified instruction is using the
554 /// specified value as an address.
555 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
556 bool isAddress = isa<LoadInst>(Inst);
557 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
558 if (SI->getOperand(1) == OperandVal)
560 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
561 // Addressing modes can also be folded into prefetches and a variety
563 switch (II->getIntrinsicID()) {
565 case Intrinsic::prefetch:
566 case Intrinsic::x86_sse2_loadu_dq:
567 case Intrinsic::x86_sse2_loadu_pd:
568 case Intrinsic::x86_sse_loadu_ps:
569 case Intrinsic::x86_sse_storeu_ps:
570 case Intrinsic::x86_sse2_storeu_pd:
571 case Intrinsic::x86_sse2_storeu_dq:
572 case Intrinsic::x86_sse2_storel_dq:
573 if (II->getArgOperand(0) == OperandVal)
581 /// getAccessType - Return the type of the memory being accessed.
582 static const Type *getAccessType(const Instruction *Inst) {
583 const Type *AccessTy = Inst->getType();
584 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
585 AccessTy = SI->getOperand(0)->getType();
586 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
587 // Addressing modes can also be folded into prefetches and a variety
589 switch (II->getIntrinsicID()) {
591 case Intrinsic::x86_sse_storeu_ps:
592 case Intrinsic::x86_sse2_storeu_pd:
593 case Intrinsic::x86_sse2_storeu_dq:
594 case Intrinsic::x86_sse2_storel_dq:
595 AccessTy = II->getArgOperand(0)->getType();
600 // All pointers have the same requirements, so canonicalize them to an
601 // arbitrary pointer type to minimize variation.
602 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
603 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
604 PTy->getAddressSpace());
609 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
610 /// specified set are trivially dead, delete them and see if this makes any of
611 /// their operands subsequently dead.
613 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
614 bool Changed = false;
616 while (!DeadInsts.empty()) {
617 Instruction *I = dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val());
619 if (I == 0 || !isInstructionTriviallyDead(I))
622 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
623 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
626 DeadInsts.push_back(U);
629 I->eraseFromParent();
638 /// Cost - This class is used to measure and compare candidate formulae.
640 /// TODO: Some of these could be merged. Also, a lexical ordering
641 /// isn't always optimal.
645 unsigned NumBaseAdds;
651 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
654 bool operator<(const Cost &Other) const;
658 void RateFormula(const Formula &F,
659 SmallPtrSet<const SCEV *, 16> &Regs,
660 const DenseSet<const SCEV *> &VisitedRegs,
662 const SmallVectorImpl<int64_t> &Offsets,
663 ScalarEvolution &SE, DominatorTree &DT);
665 void print(raw_ostream &OS) const;
669 void RateRegister(const SCEV *Reg,
670 SmallPtrSet<const SCEV *, 16> &Regs,
672 ScalarEvolution &SE, DominatorTree &DT);
673 void RatePrimaryRegister(const SCEV *Reg,
674 SmallPtrSet<const SCEV *, 16> &Regs,
676 ScalarEvolution &SE, DominatorTree &DT);
681 /// RateRegister - Tally up interesting quantities from the given register.
682 void Cost::RateRegister(const SCEV *Reg,
683 SmallPtrSet<const SCEV *, 16> &Regs,
685 ScalarEvolution &SE, DominatorTree &DT) {
686 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
687 if (AR->getLoop() == L)
688 AddRecCost += 1; /// TODO: This should be a function of the stride.
690 // If this is an addrec for a loop that's already been visited by LSR,
691 // don't second-guess its addrec phi nodes. LSR isn't currently smart
692 // enough to reason about more than one loop at a time. Consider these
693 // registers free and leave them alone.
694 else if (L->contains(AR->getLoop()) ||
695 (!AR->getLoop()->contains(L) &&
696 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
697 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
698 PHINode *PN = dyn_cast<PHINode>(I); ++I)
699 if (SE.isSCEVable(PN->getType()) &&
700 (SE.getEffectiveSCEVType(PN->getType()) ==
701 SE.getEffectiveSCEVType(AR->getType())) &&
702 SE.getSCEV(PN) == AR)
705 // If this isn't one of the addrecs that the loop already has, it
706 // would require a costly new phi and add. TODO: This isn't
707 // precisely modeled right now.
709 if (!Regs.count(AR->getStart()))
710 RateRegister(AR->getStart(), Regs, L, SE, DT);
713 // Add the step value register, if it needs one.
714 // TODO: The non-affine case isn't precisely modeled here.
715 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
716 if (!Regs.count(AR->getStart()))
717 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
721 // Rough heuristic; favor registers which don't require extra setup
722 // instructions in the preheader.
723 if (!isa<SCEVUnknown>(Reg) &&
724 !isa<SCEVConstant>(Reg) &&
725 !(isa<SCEVAddRecExpr>(Reg) &&
726 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
727 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
730 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
731 SE.hasComputableLoopEvolution(Reg, L);
734 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
736 void Cost::RatePrimaryRegister(const SCEV *Reg,
737 SmallPtrSet<const SCEV *, 16> &Regs,
739 ScalarEvolution &SE, DominatorTree &DT) {
740 if (Regs.insert(Reg))
741 RateRegister(Reg, Regs, L, SE, DT);
744 void Cost::RateFormula(const Formula &F,
745 SmallPtrSet<const SCEV *, 16> &Regs,
746 const DenseSet<const SCEV *> &VisitedRegs,
748 const SmallVectorImpl<int64_t> &Offsets,
749 ScalarEvolution &SE, DominatorTree &DT) {
750 // Tally up the registers.
751 if (const SCEV *ScaledReg = F.ScaledReg) {
752 if (VisitedRegs.count(ScaledReg)) {
756 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
758 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
759 E = F.BaseRegs.end(); I != E; ++I) {
760 const SCEV *BaseReg = *I;
761 if (VisitedRegs.count(BaseReg)) {
765 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
768 if (F.BaseRegs.size() > 1)
769 NumBaseAdds += F.BaseRegs.size() - 1;
771 // Tally up the non-zero immediates.
772 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
773 E = Offsets.end(); I != E; ++I) {
774 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
776 ImmCost += 64; // Handle symbolic values conservatively.
777 // TODO: This should probably be the pointer size.
778 else if (Offset != 0)
779 ImmCost += APInt(64, Offset, true).getMinSignedBits();
783 /// Loose - Set this cost to a loosing value.
793 /// operator< - Choose the lower cost.
794 bool Cost::operator<(const Cost &Other) const {
795 if (NumRegs != Other.NumRegs)
796 return NumRegs < Other.NumRegs;
797 if (AddRecCost != Other.AddRecCost)
798 return AddRecCost < Other.AddRecCost;
799 if (NumIVMuls != Other.NumIVMuls)
800 return NumIVMuls < Other.NumIVMuls;
801 if (NumBaseAdds != Other.NumBaseAdds)
802 return NumBaseAdds < Other.NumBaseAdds;
803 if (ImmCost != Other.ImmCost)
804 return ImmCost < Other.ImmCost;
805 if (SetupCost != Other.SetupCost)
806 return SetupCost < Other.SetupCost;
810 void Cost::print(raw_ostream &OS) const {
811 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
813 OS << ", with addrec cost " << AddRecCost;
815 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
816 if (NumBaseAdds != 0)
817 OS << ", plus " << NumBaseAdds << " base add"
818 << (NumBaseAdds == 1 ? "" : "s");
820 OS << ", plus " << ImmCost << " imm cost";
822 OS << ", plus " << SetupCost << " setup cost";
825 void Cost::dump() const {
826 print(errs()); errs() << '\n';
831 /// LSRFixup - An operand value in an instruction which is to be replaced
832 /// with some equivalent, possibly strength-reduced, replacement.
834 /// UserInst - The instruction which will be updated.
835 Instruction *UserInst;
837 /// OperandValToReplace - The operand of the instruction which will
838 /// be replaced. The operand may be used more than once; every instance
839 /// will be replaced.
840 Value *OperandValToReplace;
842 /// PostIncLoops - If this user is to use the post-incremented value of an
843 /// induction variable, this variable is non-null and holds the loop
844 /// associated with the induction variable.
845 PostIncLoopSet PostIncLoops;
847 /// LUIdx - The index of the LSRUse describing the expression which
848 /// this fixup needs, minus an offset (below).
851 /// Offset - A constant offset to be added to the LSRUse expression.
852 /// This allows multiple fixups to share the same LSRUse with different
853 /// offsets, for example in an unrolled loop.
856 bool isUseFullyOutsideLoop(const Loop *L) const;
860 void print(raw_ostream &OS) const;
867 : UserInst(0), OperandValToReplace(0), LUIdx(~size_t(0)), Offset(0) {}
869 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
870 /// value outside of the given loop.
871 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
872 // PHI nodes use their value in their incoming blocks.
873 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
875 if (PN->getIncomingValue(i) == OperandValToReplace &&
876 L->contains(PN->getIncomingBlock(i)))
881 return !L->contains(UserInst);
884 void LSRFixup::print(raw_ostream &OS) const {
886 // Store is common and interesting enough to be worth special-casing.
887 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
889 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
890 } else if (UserInst->getType()->isVoidTy())
891 OS << UserInst->getOpcodeName();
893 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
895 OS << ", OperandValToReplace=";
896 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
898 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
899 E = PostIncLoops.end(); I != E; ++I) {
900 OS << ", PostIncLoop=";
901 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
904 if (LUIdx != ~size_t(0))
905 OS << ", LUIdx=" << LUIdx;
908 OS << ", Offset=" << Offset;
911 void LSRFixup::dump() const {
912 print(errs()); errs() << '\n';
917 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
918 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
919 struct UniquifierDenseMapInfo {
920 static SmallVector<const SCEV *, 2> getEmptyKey() {
921 SmallVector<const SCEV *, 2> V;
922 V.push_back(reinterpret_cast<const SCEV *>(-1));
926 static SmallVector<const SCEV *, 2> getTombstoneKey() {
927 SmallVector<const SCEV *, 2> V;
928 V.push_back(reinterpret_cast<const SCEV *>(-2));
932 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
934 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
935 E = V.end(); I != E; ++I)
936 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
940 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
941 const SmallVector<const SCEV *, 2> &RHS) {
946 /// LSRUse - This class holds the state that LSR keeps for each use in
947 /// IVUsers, as well as uses invented by LSR itself. It includes information
948 /// about what kinds of things can be folded into the user, information about
949 /// the user itself, and information about how the use may be satisfied.
950 /// TODO: Represent multiple users of the same expression in common?
952 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
955 /// KindType - An enum for a kind of use, indicating what types of
956 /// scaled and immediate operands it might support.
958 Basic, ///< A normal use, with no folding.
959 Special, ///< A special case of basic, allowing -1 scales.
960 Address, ///< An address use; folding according to TargetLowering
961 ICmpZero ///< An equality icmp with both operands folded into one.
962 // TODO: Add a generic icmp too?
966 const Type *AccessTy;
968 SmallVector<int64_t, 8> Offsets;
972 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
973 /// LSRUse are outside of the loop, in which case some special-case heuristics
975 bool AllFixupsOutsideLoop;
977 /// WidestFixupType - This records the widest use type for any fixup using
978 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
979 /// max fixup widths to be equivalent, because the narrower one may be relying
980 /// on the implicit truncation to truncate away bogus bits.
981 const Type *WidestFixupType;
983 /// Formulae - A list of ways to build a value that can satisfy this user.
984 /// After the list is populated, one of these is selected heuristically and
985 /// used to formulate a replacement for OperandValToReplace in UserInst.
986 SmallVector<Formula, 12> Formulae;
988 /// Regs - The set of register candidates used by all formulae in this LSRUse.
989 SmallPtrSet<const SCEV *, 4> Regs;
991 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
992 MinOffset(INT64_MAX),
993 MaxOffset(INT64_MIN),
994 AllFixupsOutsideLoop(true),
995 WidestFixupType(0) {}
997 bool HasFormulaWithSameRegs(const Formula &F) const;
998 bool InsertFormula(const Formula &F);
999 void DeleteFormula(Formula &F);
1000 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1002 void print(raw_ostream &OS) const;
1008 /// HasFormula - Test whether this use as a formula which has the same
1009 /// registers as the given formula.
1010 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1011 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1012 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1013 // Unstable sort by host order ok, because this is only used for uniquifying.
1014 std::sort(Key.begin(), Key.end());
1015 return Uniquifier.count(Key);
1018 /// InsertFormula - If the given formula has not yet been inserted, add it to
1019 /// the list, and return true. Return false otherwise.
1020 bool LSRUse::InsertFormula(const Formula &F) {
1021 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1022 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1023 // Unstable sort by host order ok, because this is only used for uniquifying.
1024 std::sort(Key.begin(), Key.end());
1026 if (!Uniquifier.insert(Key).second)
1029 // Using a register to hold the value of 0 is not profitable.
1030 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1031 "Zero allocated in a scaled register!");
1033 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1034 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1035 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1038 // Add the formula to the list.
1039 Formulae.push_back(F);
1041 // Record registers now being used by this use.
1042 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1043 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1048 /// DeleteFormula - Remove the given formula from this use's list.
1049 void LSRUse::DeleteFormula(Formula &F) {
1050 if (&F != &Formulae.back())
1051 std::swap(F, Formulae.back());
1052 Formulae.pop_back();
1053 assert(!Formulae.empty() && "LSRUse has no formulae left!");
1056 /// RecomputeRegs - Recompute the Regs field, and update RegUses.
1057 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1058 // Now that we've filtered out some formulae, recompute the Regs set.
1059 SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1061 for (SmallVectorImpl<Formula>::const_iterator I = Formulae.begin(),
1062 E = Formulae.end(); I != E; ++I) {
1063 const Formula &F = *I;
1064 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1065 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1068 // Update the RegTracker.
1069 for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1070 E = OldRegs.end(); I != E; ++I)
1071 if (!Regs.count(*I))
1072 RegUses.DropRegister(*I, LUIdx);
1075 void LSRUse::print(raw_ostream &OS) const {
1076 OS << "LSR Use: Kind=";
1078 case Basic: OS << "Basic"; break;
1079 case Special: OS << "Special"; break;
1080 case ICmpZero: OS << "ICmpZero"; break;
1082 OS << "Address of ";
1083 if (AccessTy->isPointerTy())
1084 OS << "pointer"; // the full pointer type could be really verbose
1089 OS << ", Offsets={";
1090 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1091 E = Offsets.end(); I != E; ++I) {
1093 if (llvm::next(I) != E)
1098 if (AllFixupsOutsideLoop)
1099 OS << ", all-fixups-outside-loop";
1101 if (WidestFixupType)
1102 OS << ", widest fixup type: " << *WidestFixupType;
1105 void LSRUse::dump() const {
1106 print(errs()); errs() << '\n';
1109 /// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1110 /// be completely folded into the user instruction at isel time. This includes
1111 /// address-mode folding and special icmp tricks.
1112 static bool isLegalUse(const TargetLowering::AddrMode &AM,
1113 LSRUse::KindType Kind, const Type *AccessTy,
1114 const TargetLowering *TLI) {
1116 case LSRUse::Address:
1117 // If we have low-level target information, ask the target if it can
1118 // completely fold this address.
1119 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1121 // Otherwise, just guess that reg+reg addressing is legal.
1122 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1124 case LSRUse::ICmpZero:
1125 // There's not even a target hook for querying whether it would be legal to
1126 // fold a GV into an ICmp.
1130 // ICmp only has two operands; don't allow more than two non-trivial parts.
1131 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1134 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1135 // putting the scaled register in the other operand of the icmp.
1136 if (AM.Scale != 0 && AM.Scale != -1)
1139 // If we have low-level target information, ask the target if it can fold an
1140 // integer immediate on an icmp.
1141 if (AM.BaseOffs != 0) {
1142 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1149 // Only handle single-register values.
1150 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1152 case LSRUse::Special:
1153 // Only handle -1 scales, or no scale.
1154 return AM.Scale == 0 || AM.Scale == -1;
1160 static bool isLegalUse(TargetLowering::AddrMode AM,
1161 int64_t MinOffset, int64_t MaxOffset,
1162 LSRUse::KindType Kind, const Type *AccessTy,
1163 const TargetLowering *TLI) {
1164 // Check for overflow.
1165 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1168 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1169 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1170 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1171 // Check for overflow.
1172 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1175 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1176 return isLegalUse(AM, Kind, AccessTy, TLI);
1181 static bool isAlwaysFoldable(int64_t BaseOffs,
1182 GlobalValue *BaseGV,
1184 LSRUse::KindType Kind, const Type *AccessTy,
1185 const TargetLowering *TLI) {
1186 // Fast-path: zero is always foldable.
1187 if (BaseOffs == 0 && !BaseGV) return true;
1189 // Conservatively, create an address with an immediate and a
1190 // base and a scale.
1191 TargetLowering::AddrMode AM;
1192 AM.BaseOffs = BaseOffs;
1194 AM.HasBaseReg = HasBaseReg;
1195 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1197 // Canonicalize a scale of 1 to a base register if the formula doesn't
1198 // already have a base register.
1199 if (!AM.HasBaseReg && AM.Scale == 1) {
1201 AM.HasBaseReg = true;
1204 return isLegalUse(AM, Kind, AccessTy, TLI);
1207 static bool isAlwaysFoldable(const SCEV *S,
1208 int64_t MinOffset, int64_t MaxOffset,
1210 LSRUse::KindType Kind, const Type *AccessTy,
1211 const TargetLowering *TLI,
1212 ScalarEvolution &SE) {
1213 // Fast-path: zero is always foldable.
1214 if (S->isZero()) return true;
1216 // Conservatively, create an address with an immediate and a
1217 // base and a scale.
1218 int64_t BaseOffs = ExtractImmediate(S, SE);
1219 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1221 // If there's anything else involved, it's not foldable.
1222 if (!S->isZero()) return false;
1224 // Fast-path: zero is always foldable.
1225 if (BaseOffs == 0 && !BaseGV) return true;
1227 // Conservatively, create an address with an immediate and a
1228 // base and a scale.
1229 TargetLowering::AddrMode AM;
1230 AM.BaseOffs = BaseOffs;
1232 AM.HasBaseReg = HasBaseReg;
1233 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1235 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
1240 /// UseMapDenseMapInfo - A DenseMapInfo implementation for holding
1241 /// DenseMaps and DenseSets of pairs of const SCEV* and LSRUse::Kind.
1242 struct UseMapDenseMapInfo {
1243 static std::pair<const SCEV *, LSRUse::KindType> getEmptyKey() {
1244 return std::make_pair(reinterpret_cast<const SCEV *>(-1), LSRUse::Basic);
1247 static std::pair<const SCEV *, LSRUse::KindType> getTombstoneKey() {
1248 return std::make_pair(reinterpret_cast<const SCEV *>(-2), LSRUse::Basic);
1252 getHashValue(const std::pair<const SCEV *, LSRUse::KindType> &V) {
1253 unsigned Result = DenseMapInfo<const SCEV *>::getHashValue(V.first);
1254 Result ^= DenseMapInfo<unsigned>::getHashValue(unsigned(V.second));
1258 static bool isEqual(const std::pair<const SCEV *, LSRUse::KindType> &LHS,
1259 const std::pair<const SCEV *, LSRUse::KindType> &RHS) {
1264 /// LSRInstance - This class holds state for the main loop strength reduction
1268 ScalarEvolution &SE;
1271 const TargetLowering *const TLI;
1275 /// IVIncInsertPos - This is the insert position that the current loop's
1276 /// induction variable increment should be placed. In simple loops, this is
1277 /// the latch block's terminator. But in more complicated cases, this is a
1278 /// position which will dominate all the in-loop post-increment users.
1279 Instruction *IVIncInsertPos;
1281 /// Factors - Interesting factors between use strides.
1282 SmallSetVector<int64_t, 8> Factors;
1284 /// Types - Interesting use types, to facilitate truncation reuse.
1285 SmallSetVector<const Type *, 4> Types;
1287 /// Fixups - The list of operands which are to be replaced.
1288 SmallVector<LSRFixup, 16> Fixups;
1290 /// Uses - The list of interesting uses.
1291 SmallVector<LSRUse, 16> Uses;
1293 /// RegUses - Track which uses use which register candidates.
1294 RegUseTracker RegUses;
1296 void OptimizeShadowIV();
1297 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1298 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1299 void OptimizeLoopTermCond();
1301 void CollectInterestingTypesAndFactors();
1302 void CollectFixupsAndInitialFormulae();
1304 LSRFixup &getNewFixup() {
1305 Fixups.push_back(LSRFixup());
1306 return Fixups.back();
1309 // Support for sharing of LSRUses between LSRFixups.
1310 typedef DenseMap<std::pair<const SCEV *, LSRUse::KindType>,
1312 UseMapDenseMapInfo> UseMapTy;
1315 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1316 LSRUse::KindType Kind, const Type *AccessTy);
1318 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1319 LSRUse::KindType Kind,
1320 const Type *AccessTy);
1322 void DeleteUse(LSRUse &LU, size_t LUIdx);
1324 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1327 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1328 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1329 void CountRegisters(const Formula &F, size_t LUIdx);
1330 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1332 void CollectLoopInvariantFixupsAndFormulae();
1334 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1335 unsigned Depth = 0);
1336 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1337 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1338 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1339 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1340 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1341 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1342 void GenerateCrossUseConstantOffsets();
1343 void GenerateAllReuseFormulae();
1345 void FilterOutUndesirableDedicatedRegisters();
1347 size_t EstimateSearchSpaceComplexity() const;
1348 void NarrowSearchSpaceByDetectingSupersets();
1349 void NarrowSearchSpaceByCollapsingUnrolledCode();
1350 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
1351 void NarrowSearchSpaceByPickingWinnerRegs();
1352 void NarrowSearchSpaceUsingHeuristics();
1354 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1356 SmallVectorImpl<const Formula *> &Workspace,
1357 const Cost &CurCost,
1358 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1359 DenseSet<const SCEV *> &VisitedRegs) const;
1360 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1362 BasicBlock::iterator
1363 HoistInsertPosition(BasicBlock::iterator IP,
1364 const SmallVectorImpl<Instruction *> &Inputs) const;
1365 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1367 const LSRUse &LU) const;
1369 Value *Expand(const LSRFixup &LF,
1371 BasicBlock::iterator IP,
1372 SCEVExpander &Rewriter,
1373 SmallVectorImpl<WeakVH> &DeadInsts) const;
1374 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1376 SCEVExpander &Rewriter,
1377 SmallVectorImpl<WeakVH> &DeadInsts,
1379 void Rewrite(const LSRFixup &LF,
1381 SCEVExpander &Rewriter,
1382 SmallVectorImpl<WeakVH> &DeadInsts,
1384 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1387 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1389 bool getChanged() const { return Changed; }
1391 void print_factors_and_types(raw_ostream &OS) const;
1392 void print_fixups(raw_ostream &OS) const;
1393 void print_uses(raw_ostream &OS) const;
1394 void print(raw_ostream &OS) const;
1400 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1401 /// inside the loop then try to eliminate the cast operation.
1402 void LSRInstance::OptimizeShadowIV() {
1403 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1404 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1407 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1408 UI != E; /* empty */) {
1409 IVUsers::const_iterator CandidateUI = UI;
1411 Instruction *ShadowUse = CandidateUI->getUser();
1412 const Type *DestTy = NULL;
1414 /* If shadow use is a int->float cast then insert a second IV
1415 to eliminate this cast.
1417 for (unsigned i = 0; i < n; ++i)
1423 for (unsigned i = 0; i < n; ++i, ++d)
1426 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1427 DestTy = UCast->getDestTy();
1428 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1429 DestTy = SCast->getDestTy();
1430 if (!DestTy) continue;
1433 // If target does not support DestTy natively then do not apply
1434 // this transformation.
1435 EVT DVT = TLI->getValueType(DestTy);
1436 if (!TLI->isTypeLegal(DVT)) continue;
1439 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1441 if (PH->getNumIncomingValues() != 2) continue;
1443 const Type *SrcTy = PH->getType();
1444 int Mantissa = DestTy->getFPMantissaWidth();
1445 if (Mantissa == -1) continue;
1446 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1449 unsigned Entry, Latch;
1450 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1458 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1459 if (!Init) continue;
1460 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
1462 BinaryOperator *Incr =
1463 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1464 if (!Incr) continue;
1465 if (Incr->getOpcode() != Instruction::Add
1466 && Incr->getOpcode() != Instruction::Sub)
1469 /* Initialize new IV, double d = 0.0 in above example. */
1470 ConstantInt *C = NULL;
1471 if (Incr->getOperand(0) == PH)
1472 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1473 else if (Incr->getOperand(1) == PH)
1474 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
1480 // Ignore negative constants, as the code below doesn't handle them
1481 // correctly. TODO: Remove this restriction.
1482 if (!C->getValue().isStrictlyPositive()) continue;
1484 /* Add new PHINode. */
1485 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
1487 /* create new increment. '++d' in above example. */
1488 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1489 BinaryOperator *NewIncr =
1490 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1491 Instruction::FAdd : Instruction::FSub,
1492 NewPH, CFP, "IV.S.next.", Incr);
1494 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1495 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1497 /* Remove cast operation */
1498 ShadowUse->replaceAllUsesWith(NewPH);
1499 ShadowUse->eraseFromParent();
1505 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1506 /// set the IV user and stride information and return true, otherwise return
1508 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
1509 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1510 if (UI->getUser() == Cond) {
1511 // NOTE: we could handle setcc instructions with multiple uses here, but
1512 // InstCombine does it as well for simple uses, it's not clear that it
1513 // occurs enough in real life to handle.
1520 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
1521 /// a max computation.
1523 /// This is a narrow solution to a specific, but acute, problem. For loops
1529 /// } while (++i < n);
1531 /// the trip count isn't just 'n', because 'n' might not be positive. And
1532 /// unfortunately this can come up even for loops where the user didn't use
1533 /// a C do-while loop. For example, seemingly well-behaved top-test loops
1534 /// will commonly be lowered like this:
1540 /// } while (++i < n);
1543 /// and then it's possible for subsequent optimization to obscure the if
1544 /// test in such a way that indvars can't find it.
1546 /// When indvars can't find the if test in loops like this, it creates a
1547 /// max expression, which allows it to give the loop a canonical
1548 /// induction variable:
1551 /// max = n < 1 ? 1 : n;
1554 /// } while (++i != max);
1556 /// Canonical induction variables are necessary because the loop passes
1557 /// are designed around them. The most obvious example of this is the
1558 /// LoopInfo analysis, which doesn't remember trip count values. It
1559 /// expects to be able to rediscover the trip count each time it is
1560 /// needed, and it does this using a simple analysis that only succeeds if
1561 /// the loop has a canonical induction variable.
1563 /// However, when it comes time to generate code, the maximum operation
1564 /// can be quite costly, especially if it's inside of an outer loop.
1566 /// This function solves this problem by detecting this type of loop and
1567 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1568 /// the instructions for the maximum computation.
1570 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
1571 // Check that the loop matches the pattern we're looking for.
1572 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1573 Cond->getPredicate() != CmpInst::ICMP_NE)
1576 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1577 if (!Sel || !Sel->hasOneUse()) return Cond;
1579 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1580 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1582 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
1584 // Add one to the backedge-taken count to get the trip count.
1585 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
1586 if (IterationCount != SE.getSCEV(Sel)) return Cond;
1588 // Check for a max calculation that matches the pattern. There's no check
1589 // for ICMP_ULE here because the comparison would be with zero, which
1590 // isn't interesting.
1591 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1592 const SCEVNAryExpr *Max = 0;
1593 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1594 Pred = ICmpInst::ICMP_SLE;
1596 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1597 Pred = ICmpInst::ICMP_SLT;
1599 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1600 Pred = ICmpInst::ICMP_ULT;
1607 // To handle a max with more than two operands, this optimization would
1608 // require additional checking and setup.
1609 if (Max->getNumOperands() != 2)
1612 const SCEV *MaxLHS = Max->getOperand(0);
1613 const SCEV *MaxRHS = Max->getOperand(1);
1615 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1616 // for a comparison with 1. For <= and >=, a comparison with zero.
1618 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1621 // Check the relevant induction variable for conformance to
1623 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
1624 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1625 if (!AR || !AR->isAffine() ||
1626 AR->getStart() != One ||
1627 AR->getStepRecurrence(SE) != One)
1630 assert(AR->getLoop() == L &&
1631 "Loop condition operand is an addrec in a different loop!");
1633 // Check the right operand of the select, and remember it, as it will
1634 // be used in the new comparison instruction.
1636 if (ICmpInst::isTrueWhenEqual(Pred)) {
1637 // Look for n+1, and grab n.
1638 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1639 if (isa<ConstantInt>(BO->getOperand(1)) &&
1640 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1641 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1642 NewRHS = BO->getOperand(0);
1643 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1644 if (isa<ConstantInt>(BO->getOperand(1)) &&
1645 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1646 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1647 NewRHS = BO->getOperand(0);
1650 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
1651 NewRHS = Sel->getOperand(1);
1652 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
1653 NewRHS = Sel->getOperand(2);
1654 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
1655 NewRHS = SU->getValue();
1657 // Max doesn't match expected pattern.
1660 // Determine the new comparison opcode. It may be signed or unsigned,
1661 // and the original comparison may be either equality or inequality.
1662 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1663 Pred = CmpInst::getInversePredicate(Pred);
1665 // Ok, everything looks ok to change the condition into an SLT or SGE and
1666 // delete the max calculation.
1668 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1670 // Delete the max calculation instructions.
1671 Cond->replaceAllUsesWith(NewCond);
1672 CondUse->setUser(NewCond);
1673 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1674 Cond->eraseFromParent();
1675 Sel->eraseFromParent();
1676 if (Cmp->use_empty())
1677 Cmp->eraseFromParent();
1681 /// OptimizeLoopTermCond - Change loop terminating condition to use the
1682 /// postinc iv when possible.
1684 LSRInstance::OptimizeLoopTermCond() {
1685 SmallPtrSet<Instruction *, 4> PostIncs;
1687 BasicBlock *LatchBlock = L->getLoopLatch();
1688 SmallVector<BasicBlock*, 8> ExitingBlocks;
1689 L->getExitingBlocks(ExitingBlocks);
1691 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1692 BasicBlock *ExitingBlock = ExitingBlocks[i];
1694 // Get the terminating condition for the loop if possible. If we
1695 // can, we want to change it to use a post-incremented version of its
1696 // induction variable, to allow coalescing the live ranges for the IV into
1697 // one register value.
1699 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1702 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1703 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1706 // Search IVUsesByStride to find Cond's IVUse if there is one.
1707 IVStrideUse *CondUse = 0;
1708 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1709 if (!FindIVUserForCond(Cond, CondUse))
1712 // If the trip count is computed in terms of a max (due to ScalarEvolution
1713 // being unable to find a sufficient guard, for example), change the loop
1714 // comparison to use SLT or ULT instead of NE.
1715 // One consequence of doing this now is that it disrupts the count-down
1716 // optimization. That's not always a bad thing though, because in such
1717 // cases it may still be worthwhile to avoid a max.
1718 Cond = OptimizeMax(Cond, CondUse);
1720 // If this exiting block dominates the latch block, it may also use
1721 // the post-inc value if it won't be shared with other uses.
1722 // Check for dominance.
1723 if (!DT.dominates(ExitingBlock, LatchBlock))
1726 // Conservatively avoid trying to use the post-inc value in non-latch
1727 // exits if there may be pre-inc users in intervening blocks.
1728 if (LatchBlock != ExitingBlock)
1729 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1730 // Test if the use is reachable from the exiting block. This dominator
1731 // query is a conservative approximation of reachability.
1732 if (&*UI != CondUse &&
1733 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1734 // Conservatively assume there may be reuse if the quotient of their
1735 // strides could be a legal scale.
1736 const SCEV *A = IU.getStride(*CondUse, L);
1737 const SCEV *B = IU.getStride(*UI, L);
1738 if (!A || !B) continue;
1739 if (SE.getTypeSizeInBits(A->getType()) !=
1740 SE.getTypeSizeInBits(B->getType())) {
1741 if (SE.getTypeSizeInBits(A->getType()) >
1742 SE.getTypeSizeInBits(B->getType()))
1743 B = SE.getSignExtendExpr(B, A->getType());
1745 A = SE.getSignExtendExpr(A, B->getType());
1747 if (const SCEVConstant *D =
1748 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
1749 const ConstantInt *C = D->getValue();
1750 // Stride of one or negative one can have reuse with non-addresses.
1751 if (C->isOne() || C->isAllOnesValue())
1752 goto decline_post_inc;
1753 // Avoid weird situations.
1754 if (C->getValue().getMinSignedBits() >= 64 ||
1755 C->getValue().isMinSignedValue())
1756 goto decline_post_inc;
1757 // Without TLI, assume that any stride might be valid, and so any
1758 // use might be shared.
1760 goto decline_post_inc;
1761 // Check for possible scaled-address reuse.
1762 const Type *AccessTy = getAccessType(UI->getUser());
1763 TargetLowering::AddrMode AM;
1764 AM.Scale = C->getSExtValue();
1765 if (TLI->isLegalAddressingMode(AM, AccessTy))
1766 goto decline_post_inc;
1767 AM.Scale = -AM.Scale;
1768 if (TLI->isLegalAddressingMode(AM, AccessTy))
1769 goto decline_post_inc;
1773 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
1776 // It's possible for the setcc instruction to be anywhere in the loop, and
1777 // possible for it to have multiple users. If it is not immediately before
1778 // the exiting block branch, move it.
1779 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1780 if (Cond->hasOneUse()) {
1781 Cond->moveBefore(TermBr);
1783 // Clone the terminating condition and insert into the loopend.
1784 ICmpInst *OldCond = Cond;
1785 Cond = cast<ICmpInst>(Cond->clone());
1786 Cond->setName(L->getHeader()->getName() + ".termcond");
1787 ExitingBlock->getInstList().insert(TermBr, Cond);
1789 // Clone the IVUse, as the old use still exists!
1790 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
1791 TermBr->replaceUsesOfWith(OldCond, Cond);
1795 // If we get to here, we know that we can transform the setcc instruction to
1796 // use the post-incremented version of the IV, allowing us to coalesce the
1797 // live ranges for the IV correctly.
1798 CondUse->transformToPostInc(L);
1801 PostIncs.insert(Cond);
1805 // Determine an insertion point for the loop induction variable increment. It
1806 // must dominate all the post-inc comparisons we just set up, and it must
1807 // dominate the loop latch edge.
1808 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1809 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1810 E = PostIncs.end(); I != E; ++I) {
1812 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1814 if (BB == (*I)->getParent())
1815 IVIncInsertPos = *I;
1816 else if (BB != IVIncInsertPos->getParent())
1817 IVIncInsertPos = BB->getTerminator();
1821 /// reconcileNewOffset - Determine if the given use can accomodate a fixup
1822 /// at the given offset and other details. If so, update the use and
1825 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1826 LSRUse::KindType Kind, const Type *AccessTy) {
1827 int64_t NewMinOffset = LU.MinOffset;
1828 int64_t NewMaxOffset = LU.MaxOffset;
1829 const Type *NewAccessTy = AccessTy;
1831 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1832 // something conservative, however this can pessimize in the case that one of
1833 // the uses will have all its uses outside the loop, for example.
1834 if (LU.Kind != Kind)
1836 // Conservatively assume HasBaseReg is true for now.
1837 if (NewOffset < LU.MinOffset) {
1838 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, HasBaseReg,
1839 Kind, AccessTy, TLI))
1841 NewMinOffset = NewOffset;
1842 } else if (NewOffset > LU.MaxOffset) {
1843 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, HasBaseReg,
1844 Kind, AccessTy, TLI))
1846 NewMaxOffset = NewOffset;
1848 // Check for a mismatched access type, and fall back conservatively as needed.
1849 // TODO: Be less conservative when the type is similar and can use the same
1850 // addressing modes.
1851 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1852 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
1855 LU.MinOffset = NewMinOffset;
1856 LU.MaxOffset = NewMaxOffset;
1857 LU.AccessTy = NewAccessTy;
1858 if (NewOffset != LU.Offsets.back())
1859 LU.Offsets.push_back(NewOffset);
1863 /// getUse - Return an LSRUse index and an offset value for a fixup which
1864 /// needs the given expression, with the given kind and optional access type.
1865 /// Either reuse an existing use or create a new one, as needed.
1866 std::pair<size_t, int64_t>
1867 LSRInstance::getUse(const SCEV *&Expr,
1868 LSRUse::KindType Kind, const Type *AccessTy) {
1869 const SCEV *Copy = Expr;
1870 int64_t Offset = ExtractImmediate(Expr, SE);
1872 // Basic uses can't accept any offset, for example.
1873 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
1878 std::pair<UseMapTy::iterator, bool> P =
1879 UseMap.insert(std::make_pair(std::make_pair(Expr, Kind), 0));
1881 // A use already existed with this base.
1882 size_t LUIdx = P.first->second;
1883 LSRUse &LU = Uses[LUIdx];
1884 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
1886 return std::make_pair(LUIdx, Offset);
1889 // Create a new use.
1890 size_t LUIdx = Uses.size();
1891 P.first->second = LUIdx;
1892 Uses.push_back(LSRUse(Kind, AccessTy));
1893 LSRUse &LU = Uses[LUIdx];
1895 // We don't need to track redundant offsets, but we don't need to go out
1896 // of our way here to avoid them.
1897 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1898 LU.Offsets.push_back(Offset);
1900 LU.MinOffset = Offset;
1901 LU.MaxOffset = Offset;
1902 return std::make_pair(LUIdx, Offset);
1905 /// DeleteUse - Delete the given use from the Uses list.
1906 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
1907 if (&LU != &Uses.back())
1908 std::swap(LU, Uses.back());
1912 RegUses.SwapAndDropUse(LUIdx, Uses.size());
1915 /// FindUseWithFormula - Look for a use distinct from OrigLU which is has
1916 /// a formula that has the same registers as the given formula.
1918 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
1919 const LSRUse &OrigLU) {
1920 // Search all uses for the formula. This could be more clever.
1921 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
1922 LSRUse &LU = Uses[LUIdx];
1923 // Check whether this use is close enough to OrigLU, to see whether it's
1924 // worthwhile looking through its formulae.
1925 // Ignore ICmpZero uses because they may contain formulae generated by
1926 // GenerateICmpZeroScales, in which case adding fixup offsets may
1928 if (&LU != &OrigLU &&
1929 LU.Kind != LSRUse::ICmpZero &&
1930 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
1931 LU.WidestFixupType == OrigLU.WidestFixupType &&
1932 LU.HasFormulaWithSameRegs(OrigF)) {
1933 // Scan through this use's formulae.
1934 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
1935 E = LU.Formulae.end(); I != E; ++I) {
1936 const Formula &F = *I;
1937 // Check to see if this formula has the same registers and symbols
1939 if (F.BaseRegs == OrigF.BaseRegs &&
1940 F.ScaledReg == OrigF.ScaledReg &&
1941 F.AM.BaseGV == OrigF.AM.BaseGV &&
1942 F.AM.Scale == OrigF.AM.Scale) {
1943 if (F.AM.BaseOffs == 0)
1945 // This is the formula where all the registers and symbols matched;
1946 // there aren't going to be any others. Since we declined it, we
1947 // can skip the rest of the formulae and procede to the next LSRUse.
1954 // Nothing looked good.
1958 void LSRInstance::CollectInterestingTypesAndFactors() {
1959 SmallSetVector<const SCEV *, 4> Strides;
1961 // Collect interesting types and strides.
1962 SmallVector<const SCEV *, 4> Worklist;
1963 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1964 const SCEV *Expr = IU.getExpr(*UI);
1966 // Collect interesting types.
1967 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
1969 // Add strides for mentioned loops.
1970 Worklist.push_back(Expr);
1972 const SCEV *S = Worklist.pop_back_val();
1973 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1974 Strides.insert(AR->getStepRecurrence(SE));
1975 Worklist.push_back(AR->getStart());
1976 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1977 Worklist.append(Add->op_begin(), Add->op_end());
1979 } while (!Worklist.empty());
1982 // Compute interesting factors from the set of interesting strides.
1983 for (SmallSetVector<const SCEV *, 4>::const_iterator
1984 I = Strides.begin(), E = Strides.end(); I != E; ++I)
1985 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
1986 llvm::next(I); NewStrideIter != E; ++NewStrideIter) {
1987 const SCEV *OldStride = *I;
1988 const SCEV *NewStride = *NewStrideIter;
1990 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1991 SE.getTypeSizeInBits(NewStride->getType())) {
1992 if (SE.getTypeSizeInBits(OldStride->getType()) >
1993 SE.getTypeSizeInBits(NewStride->getType()))
1994 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1996 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1998 if (const SCEVConstant *Factor =
1999 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2001 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2002 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2003 } else if (const SCEVConstant *Factor =
2004 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2007 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2008 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2012 // If all uses use the same type, don't bother looking for truncation-based
2014 if (Types.size() == 1)
2017 DEBUG(print_factors_and_types(dbgs()));
2020 void LSRInstance::CollectFixupsAndInitialFormulae() {
2021 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2023 LSRFixup &LF = getNewFixup();
2024 LF.UserInst = UI->getUser();
2025 LF.OperandValToReplace = UI->getOperandValToReplace();
2026 LF.PostIncLoops = UI->getPostIncLoops();
2028 LSRUse::KindType Kind = LSRUse::Basic;
2029 const Type *AccessTy = 0;
2030 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2031 Kind = LSRUse::Address;
2032 AccessTy = getAccessType(LF.UserInst);
2035 const SCEV *S = IU.getExpr(*UI);
2037 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2038 // (N - i == 0), and this allows (N - i) to be the expression that we work
2039 // with rather than just N or i, so we can consider the register
2040 // requirements for both N and i at the same time. Limiting this code to
2041 // equality icmps is not a problem because all interesting loops use
2042 // equality icmps, thanks to IndVarSimplify.
2043 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2044 if (CI->isEquality()) {
2045 // Swap the operands if needed to put the OperandValToReplace on the
2046 // left, for consistency.
2047 Value *NV = CI->getOperand(1);
2048 if (NV == LF.OperandValToReplace) {
2049 CI->setOperand(1, CI->getOperand(0));
2050 CI->setOperand(0, NV);
2051 NV = CI->getOperand(1);
2055 // x == y --> x - y == 0
2056 const SCEV *N = SE.getSCEV(NV);
2057 if (SE.isLoopInvariant(N, L)) {
2058 Kind = LSRUse::ICmpZero;
2059 S = SE.getMinusSCEV(N, S);
2062 // -1 and the negations of all interesting strides (except the negation
2063 // of -1) are now also interesting.
2064 for (size_t i = 0, e = Factors.size(); i != e; ++i)
2065 if (Factors[i] != -1)
2066 Factors.insert(-(uint64_t)Factors[i]);
2070 // Set up the initial formula for this use.
2071 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
2073 LF.Offset = P.second;
2074 LSRUse &LU = Uses[LF.LUIdx];
2075 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
2076 if (!LU.WidestFixupType ||
2077 SE.getTypeSizeInBits(LU.WidestFixupType) <
2078 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2079 LU.WidestFixupType = LF.OperandValToReplace->getType();
2081 // If this is the first use of this LSRUse, give it a formula.
2082 if (LU.Formulae.empty()) {
2083 InsertInitialFormula(S, LU, LF.LUIdx);
2084 CountRegisters(LU.Formulae.back(), LF.LUIdx);
2088 DEBUG(print_fixups(dbgs()));
2091 /// InsertInitialFormula - Insert a formula for the given expression into
2092 /// the given use, separating out loop-variant portions from loop-invariant
2093 /// and loop-computable portions.
2095 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
2097 F.InitialMatch(S, L, SE);
2098 bool Inserted = InsertFormula(LU, LUIdx, F);
2099 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
2102 /// InsertSupplementalFormula - Insert a simple single-register formula for
2103 /// the given expression into the given use.
2105 LSRInstance::InsertSupplementalFormula(const SCEV *S,
2106 LSRUse &LU, size_t LUIdx) {
2108 F.BaseRegs.push_back(S);
2109 F.AM.HasBaseReg = true;
2110 bool Inserted = InsertFormula(LU, LUIdx, F);
2111 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
2114 /// CountRegisters - Note which registers are used by the given formula,
2115 /// updating RegUses.
2116 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
2118 RegUses.CountRegister(F.ScaledReg, LUIdx);
2119 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2120 E = F.BaseRegs.end(); I != E; ++I)
2121 RegUses.CountRegister(*I, LUIdx);
2124 /// InsertFormula - If the given formula has not yet been inserted, add it to
2125 /// the list, and return true. Return false otherwise.
2126 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
2127 if (!LU.InsertFormula(F))
2130 CountRegisters(F, LUIdx);
2134 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
2135 /// loop-invariant values which we're tracking. These other uses will pin these
2136 /// values in registers, making them less profitable for elimination.
2137 /// TODO: This currently misses non-constant addrec step registers.
2138 /// TODO: Should this give more weight to users inside the loop?
2140 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
2141 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
2142 SmallPtrSet<const SCEV *, 8> Inserted;
2144 while (!Worklist.empty()) {
2145 const SCEV *S = Worklist.pop_back_val();
2147 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
2148 Worklist.append(N->op_begin(), N->op_end());
2149 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2150 Worklist.push_back(C->getOperand());
2151 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2152 Worklist.push_back(D->getLHS());
2153 Worklist.push_back(D->getRHS());
2154 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2155 if (!Inserted.insert(U)) continue;
2156 const Value *V = U->getValue();
2157 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2158 // Look for instructions defined outside the loop.
2159 if (L->contains(Inst)) continue;
2160 } else if (isa<UndefValue>(V))
2161 // Undef doesn't have a live range, so it doesn't matter.
2163 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
2165 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2166 // Ignore non-instructions.
2169 // Ignore instructions in other functions (as can happen with
2171 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
2173 // Ignore instructions not dominated by the loop.
2174 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2175 UserInst->getParent() :
2176 cast<PHINode>(UserInst)->getIncomingBlock(
2177 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2178 if (!DT.dominates(L->getHeader(), UseBB))
2180 // Ignore uses which are part of other SCEV expressions, to avoid
2181 // analyzing them multiple times.
2182 if (SE.isSCEVable(UserInst->getType())) {
2183 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2184 // If the user is a no-op, look through to its uses.
2185 if (!isa<SCEVUnknown>(UserS))
2189 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2193 // Ignore icmp instructions which are already being analyzed.
2194 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2195 unsigned OtherIdx = !UI.getOperandNo();
2196 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
2197 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
2201 LSRFixup &LF = getNewFixup();
2202 LF.UserInst = const_cast<Instruction *>(UserInst);
2203 LF.OperandValToReplace = UI.getUse();
2204 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2206 LF.Offset = P.second;
2207 LSRUse &LU = Uses[LF.LUIdx];
2208 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
2209 if (!LU.WidestFixupType ||
2210 SE.getTypeSizeInBits(LU.WidestFixupType) <
2211 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2212 LU.WidestFixupType = LF.OperandValToReplace->getType();
2213 InsertSupplementalFormula(U, LU, LF.LUIdx);
2214 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2221 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
2222 /// separate registers. If C is non-null, multiply each subexpression by C.
2223 static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2224 SmallVectorImpl<const SCEV *> &Ops,
2226 ScalarEvolution &SE) {
2227 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2228 // Break out add operands.
2229 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2231 CollectSubexprs(*I, C, Ops, L, SE);
2233 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2234 // Split a non-zero base out of an addrec.
2235 if (!AR->getStart()->isZero()) {
2236 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
2237 AR->getStepRecurrence(SE),
2240 CollectSubexprs(AR->getStart(), C, Ops, L, SE);
2243 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2244 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2245 if (Mul->getNumOperands() == 2)
2246 if (const SCEVConstant *Op0 =
2247 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2248 CollectSubexprs(Mul->getOperand(1),
2249 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2255 // Otherwise use the value itself, optionally with a scale applied.
2256 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2259 /// GenerateReassociations - Split out subexpressions from adds and the bases of
2261 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2264 // Arbitrarily cap recursion to protect compile time.
2265 if (Depth >= 3) return;
2267 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2268 const SCEV *BaseReg = Base.BaseRegs[i];
2270 SmallVector<const SCEV *, 8> AddOps;
2271 CollectSubexprs(BaseReg, 0, AddOps, L, SE);
2273 if (AddOps.size() == 1) continue;
2275 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2276 JE = AddOps.end(); J != JE; ++J) {
2278 // Loop-variant "unknown" values are uninteresting; we won't be able to
2279 // do anything meaningful with them.
2280 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
2283 // Don't pull a constant into a register if the constant could be folded
2284 // into an immediate field.
2285 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2286 Base.getNumRegs() > 1,
2287 LU.Kind, LU.AccessTy, TLI, SE))
2290 // Collect all operands except *J.
2291 SmallVector<const SCEV *, 8> InnerAddOps
2292 (((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
2294 (llvm::next(J), ((const SmallVector<const SCEV *, 8> &)AddOps).end());
2296 // Don't leave just a constant behind in a register if the constant could
2297 // be folded into an immediate field.
2298 if (InnerAddOps.size() == 1 &&
2299 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2300 Base.getNumRegs() > 1,
2301 LU.Kind, LU.AccessTy, TLI, SE))
2304 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2305 if (InnerSum->isZero())
2308 F.BaseRegs[i] = InnerSum;
2309 F.BaseRegs.push_back(*J);
2310 if (InsertFormula(LU, LUIdx, F))
2311 // If that formula hadn't been seen before, recurse to find more like
2313 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2318 /// GenerateCombinations - Generate a formula consisting of all of the
2319 /// loop-dominating registers added into a single register.
2320 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
2322 // This method is only interesting on a plurality of registers.
2323 if (Base.BaseRegs.size() <= 1) return;
2327 SmallVector<const SCEV *, 4> Ops;
2328 for (SmallVectorImpl<const SCEV *>::const_iterator
2329 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2330 const SCEV *BaseReg = *I;
2331 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
2332 !SE.hasComputableLoopEvolution(BaseReg, L))
2333 Ops.push_back(BaseReg);
2335 F.BaseRegs.push_back(BaseReg);
2337 if (Ops.size() > 1) {
2338 const SCEV *Sum = SE.getAddExpr(Ops);
2339 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2340 // opportunity to fold something. For now, just ignore such cases
2341 // rather than proceed with zero in a register.
2342 if (!Sum->isZero()) {
2343 F.BaseRegs.push_back(Sum);
2344 (void)InsertFormula(LU, LUIdx, F);
2349 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2350 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2352 // We can't add a symbolic offset if the address already contains one.
2353 if (Base.AM.BaseGV) return;
2355 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2356 const SCEV *G = Base.BaseRegs[i];
2357 GlobalValue *GV = ExtractSymbol(G, SE);
2358 if (G->isZero() || !GV)
2362 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2363 LU.Kind, LU.AccessTy, TLI))
2366 (void)InsertFormula(LU, LUIdx, F);
2370 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2371 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2373 // TODO: For now, just add the min and max offset, because it usually isn't
2374 // worthwhile looking at everything inbetween.
2375 SmallVector<int64_t, 2> Worklist;
2376 Worklist.push_back(LU.MinOffset);
2377 if (LU.MaxOffset != LU.MinOffset)
2378 Worklist.push_back(LU.MaxOffset);
2380 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2381 const SCEV *G = Base.BaseRegs[i];
2383 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2384 E = Worklist.end(); I != E; ++I) {
2386 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2387 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2388 LU.Kind, LU.AccessTy, TLI)) {
2389 // Add the offset to the base register.
2390 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
2391 // If it cancelled out, drop the base register, otherwise update it.
2392 if (NewG->isZero()) {
2393 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2394 F.BaseRegs.pop_back();
2396 F.BaseRegs[i] = NewG;
2398 (void)InsertFormula(LU, LUIdx, F);
2402 int64_t Imm = ExtractImmediate(G, SE);
2403 if (G->isZero() || Imm == 0)
2406 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2407 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2408 LU.Kind, LU.AccessTy, TLI))
2411 (void)InsertFormula(LU, LUIdx, F);
2415 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2416 /// the comparison. For example, x == y -> x*c == y*c.
2417 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2419 if (LU.Kind != LSRUse::ICmpZero) return;
2421 // Determine the integer type for the base formula.
2422 const Type *IntTy = Base.getType();
2424 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2426 // Don't do this if there is more than one offset.
2427 if (LU.MinOffset != LU.MaxOffset) return;
2429 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2431 // Check each interesting stride.
2432 for (SmallSetVector<int64_t, 8>::const_iterator
2433 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2434 int64_t Factor = *I;
2436 // Check that the multiplication doesn't overflow.
2437 if (Base.AM.BaseOffs == INT64_MIN && Factor == -1)
2439 int64_t NewBaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2440 if (NewBaseOffs / Factor != Base.AM.BaseOffs)
2443 // Check that multiplying with the use offset doesn't overflow.
2444 int64_t Offset = LU.MinOffset;
2445 if (Offset == INT64_MIN && Factor == -1)
2447 Offset = (uint64_t)Offset * Factor;
2448 if (Offset / Factor != LU.MinOffset)
2452 F.AM.BaseOffs = NewBaseOffs;
2454 // Check that this scale is legal.
2455 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2458 // Compensate for the use having MinOffset built into it.
2459 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2461 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2463 // Check that multiplying with each base register doesn't overflow.
2464 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2465 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
2466 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
2470 // Check that multiplying with the scaled register doesn't overflow.
2472 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
2473 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
2477 // If we make it here and it's legal, add it.
2478 (void)InsertFormula(LU, LUIdx, F);
2483 /// GenerateScales - Generate stride factor reuse formulae by making use of
2484 /// scaled-offset address modes, for example.
2485 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
2486 // Determine the integer type for the base formula.
2487 const Type *IntTy = Base.getType();
2490 // If this Formula already has a scaled register, we can't add another one.
2491 if (Base.AM.Scale != 0) return;
2493 // Check each interesting stride.
2494 for (SmallSetVector<int64_t, 8>::const_iterator
2495 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2496 int64_t Factor = *I;
2498 Base.AM.Scale = Factor;
2499 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2500 // Check whether this scale is going to be legal.
2501 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2502 LU.Kind, LU.AccessTy, TLI)) {
2503 // As a special-case, handle special out-of-loop Basic users specially.
2504 // TODO: Reconsider this special case.
2505 if (LU.Kind == LSRUse::Basic &&
2506 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2507 LSRUse::Special, LU.AccessTy, TLI) &&
2508 LU.AllFixupsOutsideLoop)
2509 LU.Kind = LSRUse::Special;
2513 // For an ICmpZero, negating a solitary base register won't lead to
2515 if (LU.Kind == LSRUse::ICmpZero &&
2516 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2518 // For each addrec base reg, apply the scale, if possible.
2519 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2520 if (const SCEVAddRecExpr *AR =
2521 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2522 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2523 if (FactorS->isZero())
2525 // Divide out the factor, ignoring high bits, since we'll be
2526 // scaling the value back up in the end.
2527 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
2528 // TODO: This could be optimized to avoid all the copying.
2530 F.ScaledReg = Quotient;
2531 F.DeleteBaseReg(F.BaseRegs[i]);
2532 (void)InsertFormula(LU, LUIdx, F);
2538 /// GenerateTruncates - Generate reuse formulae from different IV types.
2539 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
2540 // This requires TargetLowering to tell us which truncates are free.
2543 // Don't bother truncating symbolic values.
2544 if (Base.AM.BaseGV) return;
2546 // Determine the integer type for the base formula.
2547 const Type *DstTy = Base.getType();
2549 DstTy = SE.getEffectiveSCEVType(DstTy);
2551 for (SmallSetVector<const Type *, 4>::const_iterator
2552 I = Types.begin(), E = Types.end(); I != E; ++I) {
2553 const Type *SrcTy = *I;
2554 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2557 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2558 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2559 JE = F.BaseRegs.end(); J != JE; ++J)
2560 *J = SE.getAnyExtendExpr(*J, SrcTy);
2562 // TODO: This assumes we've done basic processing on all uses and
2563 // have an idea what the register usage is.
2564 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2567 (void)InsertFormula(LU, LUIdx, F);
2574 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
2575 /// defer modifications so that the search phase doesn't have to worry about
2576 /// the data structures moving underneath it.
2580 const SCEV *OrigReg;
2582 WorkItem(size_t LI, int64_t I, const SCEV *R)
2583 : LUIdx(LI), Imm(I), OrigReg(R) {}
2585 void print(raw_ostream &OS) const;
2591 void WorkItem::print(raw_ostream &OS) const {
2592 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2593 << " , add offset " << Imm;
2596 void WorkItem::dump() const {
2597 print(errs()); errs() << '\n';
2600 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2601 /// distance apart and try to form reuse opportunities between them.
2602 void LSRInstance::GenerateCrossUseConstantOffsets() {
2603 // Group the registers by their value without any added constant offset.
2604 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2605 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2607 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2608 SmallVector<const SCEV *, 8> Sequence;
2609 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2611 const SCEV *Reg = *I;
2612 int64_t Imm = ExtractImmediate(Reg, SE);
2613 std::pair<RegMapTy::iterator, bool> Pair =
2614 Map.insert(std::make_pair(Reg, ImmMapTy()));
2616 Sequence.push_back(Reg);
2617 Pair.first->second.insert(std::make_pair(Imm, *I));
2618 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2621 // Now examine each set of registers with the same base value. Build up
2622 // a list of work to do and do the work in a separate step so that we're
2623 // not adding formulae and register counts while we're searching.
2624 SmallVector<WorkItem, 32> WorkItems;
2625 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2626 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2627 E = Sequence.end(); I != E; ++I) {
2628 const SCEV *Reg = *I;
2629 const ImmMapTy &Imms = Map.find(Reg)->second;
2631 // It's not worthwhile looking for reuse if there's only one offset.
2632 if (Imms.size() == 1)
2635 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2636 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2638 dbgs() << ' ' << J->first;
2641 // Examine each offset.
2642 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2644 const SCEV *OrigReg = J->second;
2646 int64_t JImm = J->first;
2647 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2649 if (!isa<SCEVConstant>(OrigReg) &&
2650 UsedByIndicesMap[Reg].count() == 1) {
2651 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2655 // Conservatively examine offsets between this orig reg a few selected
2657 ImmMapTy::const_iterator OtherImms[] = {
2658 Imms.begin(), prior(Imms.end()),
2659 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2661 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2662 ImmMapTy::const_iterator M = OtherImms[i];
2663 if (M == J || M == JE) continue;
2665 // Compute the difference between the two.
2666 int64_t Imm = (uint64_t)JImm - M->first;
2667 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2668 LUIdx = UsedByIndices.find_next(LUIdx))
2669 // Make a memo of this use, offset, and register tuple.
2670 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2671 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
2678 UsedByIndicesMap.clear();
2679 UniqueItems.clear();
2681 // Now iterate through the worklist and add new formulae.
2682 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2683 E = WorkItems.end(); I != E; ++I) {
2684 const WorkItem &WI = *I;
2685 size_t LUIdx = WI.LUIdx;
2686 LSRUse &LU = Uses[LUIdx];
2687 int64_t Imm = WI.Imm;
2688 const SCEV *OrigReg = WI.OrigReg;
2690 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2691 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2692 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2694 // TODO: Use a more targeted data structure.
2695 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2696 const Formula &F = LU.Formulae[L];
2697 // Use the immediate in the scaled register.
2698 if (F.ScaledReg == OrigReg) {
2699 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2700 Imm * (uint64_t)F.AM.Scale;
2701 // Don't create 50 + reg(-50).
2702 if (F.referencesReg(SE.getSCEV(
2703 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2706 NewF.AM.BaseOffs = Offs;
2707 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2708 LU.Kind, LU.AccessTy, TLI))
2710 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2712 // If the new scale is a constant in a register, and adding the constant
2713 // value to the immediate would produce a value closer to zero than the
2714 // immediate itself, then the formula isn't worthwhile.
2715 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2716 if (C->getValue()->getValue().isNegative() !=
2717 (NewF.AM.BaseOffs < 0) &&
2718 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2719 .ule(abs64(NewF.AM.BaseOffs)))
2723 (void)InsertFormula(LU, LUIdx, NewF);
2725 // Use the immediate in a base register.
2726 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2727 const SCEV *BaseReg = F.BaseRegs[N];
2728 if (BaseReg != OrigReg)
2731 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2732 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2733 LU.Kind, LU.AccessTy, TLI))
2735 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2737 // If the new formula has a constant in a register, and adding the
2738 // constant value to the immediate would produce a value closer to
2739 // zero than the immediate itself, then the formula isn't worthwhile.
2740 for (SmallVectorImpl<const SCEV *>::const_iterator
2741 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2743 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2744 if ((C->getValue()->getValue() + NewF.AM.BaseOffs).abs().slt(
2745 abs64(NewF.AM.BaseOffs)) &&
2746 (C->getValue()->getValue() +
2747 NewF.AM.BaseOffs).countTrailingZeros() >=
2748 CountTrailingZeros_64(NewF.AM.BaseOffs))
2752 (void)InsertFormula(LU, LUIdx, NewF);
2761 /// GenerateAllReuseFormulae - Generate formulae for each use.
2763 LSRInstance::GenerateAllReuseFormulae() {
2764 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
2765 // queries are more precise.
2766 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2767 LSRUse &LU = Uses[LUIdx];
2768 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2769 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2770 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2771 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2773 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2774 LSRUse &LU = Uses[LUIdx];
2775 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2776 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2777 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2778 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2779 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2780 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2781 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2782 GenerateScales(LU, LUIdx, LU.Formulae[i]);
2784 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2785 LSRUse &LU = Uses[LUIdx];
2786 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2787 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2790 GenerateCrossUseConstantOffsets();
2792 DEBUG(dbgs() << "\n"
2793 "After generating reuse formulae:\n";
2794 print_uses(dbgs()));
2797 /// If there are multiple formulae with the same set of registers used
2798 /// by other uses, pick the best one and delete the others.
2799 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2800 DenseSet<const SCEV *> VisitedRegs;
2801 SmallPtrSet<const SCEV *, 16> Regs;
2803 bool ChangedFormulae = false;
2806 // Collect the best formula for each unique set of shared registers. This
2807 // is reset for each use.
2808 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2810 BestFormulaeTy BestFormulae;
2812 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2813 LSRUse &LU = Uses[LUIdx];
2814 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
2817 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2818 FIdx != NumForms; ++FIdx) {
2819 Formula &F = LU.Formulae[FIdx];
2821 SmallVector<const SCEV *, 2> Key;
2822 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2823 JE = F.BaseRegs.end(); J != JE; ++J) {
2824 const SCEV *Reg = *J;
2825 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2829 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2830 Key.push_back(F.ScaledReg);
2831 // Unstable sort by host order ok, because this is only used for
2833 std::sort(Key.begin(), Key.end());
2835 std::pair<BestFormulaeTy::const_iterator, bool> P =
2836 BestFormulae.insert(std::make_pair(Key, FIdx));
2838 Formula &Best = LU.Formulae[P.first->second];
2841 CostF.RateFormula(F, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2844 CostBest.RateFormula(Best, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2846 if (CostF < CostBest)
2848 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
2850 " in favor of formula "; Best.print(dbgs());
2853 ChangedFormulae = true;
2855 LU.DeleteFormula(F);
2863 // Now that we've filtered out some formulae, recompute the Regs set.
2865 LU.RecomputeRegs(LUIdx, RegUses);
2867 // Reset this to prepare for the next use.
2868 BestFormulae.clear();
2871 DEBUG(if (ChangedFormulae) {
2873 "After filtering out undesirable candidates:\n";
2878 // This is a rough guess that seems to work fairly well.
2879 static const size_t ComplexityLimit = UINT16_MAX;
2881 /// EstimateSearchSpaceComplexity - Estimate the worst-case number of
2882 /// solutions the solver might have to consider. It almost never considers
2883 /// this many solutions because it prune the search space, but the pruning
2884 /// isn't always sufficient.
2885 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
2887 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2888 E = Uses.end(); I != E; ++I) {
2889 size_t FSize = I->Formulae.size();
2890 if (FSize >= ComplexityLimit) {
2891 Power = ComplexityLimit;
2895 if (Power >= ComplexityLimit)
2901 /// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
2902 /// of the registers of another formula, it won't help reduce register
2903 /// pressure (though it may not necessarily hurt register pressure); remove
2904 /// it to simplify the system.
2905 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
2906 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2907 DEBUG(dbgs() << "The search space is too complex.\n");
2909 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
2910 "which use a superset of registers used by other "
2913 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2914 LSRUse &LU = Uses[LUIdx];
2916 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2917 Formula &F = LU.Formulae[i];
2918 // Look for a formula with a constant or GV in a register. If the use
2919 // also has a formula with that same value in an immediate field,
2920 // delete the one that uses a register.
2921 for (SmallVectorImpl<const SCEV *>::const_iterator
2922 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
2923 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
2925 NewF.AM.BaseOffs += C->getValue()->getSExtValue();
2926 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2927 (I - F.BaseRegs.begin()));
2928 if (LU.HasFormulaWithSameRegs(NewF)) {
2929 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2930 LU.DeleteFormula(F);
2936 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
2937 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
2940 NewF.AM.BaseGV = GV;
2941 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2942 (I - F.BaseRegs.begin()));
2943 if (LU.HasFormulaWithSameRegs(NewF)) {
2944 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
2946 LU.DeleteFormula(F);
2957 LU.RecomputeRegs(LUIdx, RegUses);
2960 DEBUG(dbgs() << "After pre-selection:\n";
2961 print_uses(dbgs()));
2965 /// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
2966 /// for expressions like A, A+1, A+2, etc., allocate a single register for
2968 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
2969 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2970 DEBUG(dbgs() << "The search space is too complex.\n");
2972 DEBUG(dbgs() << "Narrowing the search space by assuming that uses "
2973 "separated by a constant offset will use the same "
2976 // This is especially useful for unrolled loops.
2978 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2979 LSRUse &LU = Uses[LUIdx];
2980 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2981 E = LU.Formulae.end(); I != E; ++I) {
2982 const Formula &F = *I;
2983 if (F.AM.BaseOffs != 0 && F.AM.Scale == 0) {
2984 if (LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU)) {
2985 if (reconcileNewOffset(*LUThatHas, F.AM.BaseOffs,
2986 /*HasBaseReg=*/false,
2987 LU.Kind, LU.AccessTy)) {
2988 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs());
2991 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
2993 // Update the relocs to reference the new use.
2994 for (SmallVectorImpl<LSRFixup>::iterator I = Fixups.begin(),
2995 E = Fixups.end(); I != E; ++I) {
2996 LSRFixup &Fixup = *I;
2997 if (Fixup.LUIdx == LUIdx) {
2998 Fixup.LUIdx = LUThatHas - &Uses.front();
2999 Fixup.Offset += F.AM.BaseOffs;
3000 // Add the new offset to LUThatHas' offset list.
3001 if (LUThatHas->Offsets.back() != Fixup.Offset) {
3002 LUThatHas->Offsets.push_back(Fixup.Offset);
3003 if (Fixup.Offset > LUThatHas->MaxOffset)
3004 LUThatHas->MaxOffset = Fixup.Offset;
3005 if (Fixup.Offset < LUThatHas->MinOffset)
3006 LUThatHas->MinOffset = Fixup.Offset;
3008 DEBUG(dbgs() << "New fixup has offset "
3009 << Fixup.Offset << '\n');
3011 if (Fixup.LUIdx == NumUses-1)
3012 Fixup.LUIdx = LUIdx;
3015 // Delete formulae from the new use which are no longer legal.
3017 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
3018 Formula &F = LUThatHas->Formulae[i];
3019 if (!isLegalUse(F.AM,
3020 LUThatHas->MinOffset, LUThatHas->MaxOffset,
3021 LUThatHas->Kind, LUThatHas->AccessTy, TLI)) {
3022 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
3024 LUThatHas->DeleteFormula(F);
3031 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
3033 // Delete the old use.
3034 DeleteUse(LU, LUIdx);
3044 DEBUG(dbgs() << "After pre-selection:\n";
3045 print_uses(dbgs()));
3049 /// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
3050 /// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
3051 /// we've done more filtering, as it may be able to find more formulae to
3053 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
3054 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3055 DEBUG(dbgs() << "The search space is too complex.\n");
3057 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
3058 "undesirable dedicated registers.\n");
3060 FilterOutUndesirableDedicatedRegisters();
3062 DEBUG(dbgs() << "After pre-selection:\n";
3063 print_uses(dbgs()));
3067 /// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
3068 /// to be profitable, and then in any use which has any reference to that
3069 /// register, delete all formulae which do not reference that register.
3070 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
3071 // With all other options exhausted, loop until the system is simple
3072 // enough to handle.
3073 SmallPtrSet<const SCEV *, 4> Taken;
3074 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3075 // Ok, we have too many of formulae on our hands to conveniently handle.
3076 // Use a rough heuristic to thin out the list.
3077 DEBUG(dbgs() << "The search space is too complex.\n");
3079 // Pick the register which is used by the most LSRUses, which is likely
3080 // to be a good reuse register candidate.
3081 const SCEV *Best = 0;
3082 unsigned BestNum = 0;
3083 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
3085 const SCEV *Reg = *I;
3086 if (Taken.count(Reg))
3091 unsigned Count = RegUses.getUsedByIndices(Reg).count();
3092 if (Count > BestNum) {
3099 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
3100 << " will yield profitable reuse.\n");
3103 // In any use with formulae which references this register, delete formulae
3104 // which don't reference it.
3105 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3106 LSRUse &LU = Uses[LUIdx];
3107 if (!LU.Regs.count(Best)) continue;
3110 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3111 Formula &F = LU.Formulae[i];
3112 if (!F.referencesReg(Best)) {
3113 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
3114 LU.DeleteFormula(F);
3118 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
3124 LU.RecomputeRegs(LUIdx, RegUses);
3127 DEBUG(dbgs() << "After pre-selection:\n";
3128 print_uses(dbgs()));
3132 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
3133 /// formulae to choose from, use some rough heuristics to prune down the number
3134 /// of formulae. This keeps the main solver from taking an extraordinary amount
3135 /// of time in some worst-case scenarios.
3136 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
3137 NarrowSearchSpaceByDetectingSupersets();
3138 NarrowSearchSpaceByCollapsingUnrolledCode();
3139 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
3140 NarrowSearchSpaceByPickingWinnerRegs();
3143 /// SolveRecurse - This is the recursive solver.
3144 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
3146 SmallVectorImpl<const Formula *> &Workspace,
3147 const Cost &CurCost,
3148 const SmallPtrSet<const SCEV *, 16> &CurRegs,
3149 DenseSet<const SCEV *> &VisitedRegs) const {
3152 // - use more aggressive filtering
3153 // - sort the formula so that the most profitable solutions are found first
3154 // - sort the uses too
3156 // - don't compute a cost, and then compare. compare while computing a cost
3158 // - track register sets with SmallBitVector
3160 const LSRUse &LU = Uses[Workspace.size()];
3162 // If this use references any register that's already a part of the
3163 // in-progress solution, consider it a requirement that a formula must
3164 // reference that register in order to be considered. This prunes out
3165 // unprofitable searching.
3166 SmallSetVector<const SCEV *, 4> ReqRegs;
3167 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
3168 E = CurRegs.end(); I != E; ++I)
3169 if (LU.Regs.count(*I))
3172 bool AnySatisfiedReqRegs = false;
3173 SmallPtrSet<const SCEV *, 16> NewRegs;
3176 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3177 E = LU.Formulae.end(); I != E; ++I) {
3178 const Formula &F = *I;
3180 // Ignore formulae which do not use any of the required registers.
3181 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
3182 JE = ReqRegs.end(); J != JE; ++J) {
3183 const SCEV *Reg = *J;
3184 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
3185 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
3189 AnySatisfiedReqRegs = true;
3191 // Evaluate the cost of the current formula. If it's already worse than
3192 // the current best, prune the search at that point.
3195 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
3196 if (NewCost < SolutionCost) {
3197 Workspace.push_back(&F);
3198 if (Workspace.size() != Uses.size()) {
3199 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
3200 NewRegs, VisitedRegs);
3201 if (F.getNumRegs() == 1 && Workspace.size() == 1)
3202 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
3204 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
3205 dbgs() << ". Regs:";
3206 for (SmallPtrSet<const SCEV *, 16>::const_iterator
3207 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
3208 dbgs() << ' ' << **I;
3211 SolutionCost = NewCost;
3212 Solution = Workspace;
3214 Workspace.pop_back();
3219 // If none of the formulae had all of the required registers, relax the
3220 // constraint so that we don't exclude all formulae.
3221 if (!AnySatisfiedReqRegs) {
3222 assert(!ReqRegs.empty() && "Solver failed even without required registers");
3228 /// Solve - Choose one formula from each use. Return the results in the given
3229 /// Solution vector.
3230 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
3231 SmallVector<const Formula *, 8> Workspace;
3233 SolutionCost.Loose();
3235 SmallPtrSet<const SCEV *, 16> CurRegs;
3236 DenseSet<const SCEV *> VisitedRegs;
3237 Workspace.reserve(Uses.size());
3239 // SolveRecurse does all the work.
3240 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
3241 CurRegs, VisitedRegs);
3243 // Ok, we've now made all our decisions.
3244 DEBUG(dbgs() << "\n"
3245 "The chosen solution requires "; SolutionCost.print(dbgs());
3247 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
3249 Uses[i].print(dbgs());
3252 Solution[i]->print(dbgs());
3256 assert(Solution.size() == Uses.size() && "Malformed solution!");
3259 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
3260 /// the dominator tree far as we can go while still being dominated by the
3261 /// input positions. This helps canonicalize the insert position, which
3262 /// encourages sharing.
3263 BasicBlock::iterator
3264 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
3265 const SmallVectorImpl<Instruction *> &Inputs)
3268 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
3269 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
3272 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
3273 if (!Rung) return IP;
3274 Rung = Rung->getIDom();
3275 if (!Rung) return IP;
3276 IDom = Rung->getBlock();
3278 // Don't climb into a loop though.
3279 const Loop *IDomLoop = LI.getLoopFor(IDom);
3280 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
3281 if (IDomDepth <= IPLoopDepth &&
3282 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
3286 bool AllDominate = true;
3287 Instruction *BetterPos = 0;
3288 Instruction *Tentative = IDom->getTerminator();
3289 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
3290 E = Inputs.end(); I != E; ++I) {
3291 Instruction *Inst = *I;
3292 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
3293 AllDominate = false;
3296 // Attempt to find an insert position in the middle of the block,
3297 // instead of at the end, so that it can be used for other expansions.
3298 if (IDom == Inst->getParent() &&
3299 (!BetterPos || DT.dominates(BetterPos, Inst)))
3300 BetterPos = llvm::next(BasicBlock::iterator(Inst));
3313 /// AdjustInsertPositionForExpand - Determine an input position which will be
3314 /// dominated by the operands and which will dominate the result.
3315 BasicBlock::iterator
3316 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
3318 const LSRUse &LU) const {
3319 // Collect some instructions which must be dominated by the
3320 // expanding replacement. These must be dominated by any operands that
3321 // will be required in the expansion.
3322 SmallVector<Instruction *, 4> Inputs;
3323 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
3324 Inputs.push_back(I);
3325 if (LU.Kind == LSRUse::ICmpZero)
3326 if (Instruction *I =
3327 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
3328 Inputs.push_back(I);
3329 if (LF.PostIncLoops.count(L)) {
3330 if (LF.isUseFullyOutsideLoop(L))
3331 Inputs.push_back(L->getLoopLatch()->getTerminator());
3333 Inputs.push_back(IVIncInsertPos);
3335 // The expansion must also be dominated by the increment positions of any
3336 // loops it for which it is using post-inc mode.
3337 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
3338 E = LF.PostIncLoops.end(); I != E; ++I) {
3339 const Loop *PIL = *I;
3340 if (PIL == L) continue;
3342 // Be dominated by the loop exit.
3343 SmallVector<BasicBlock *, 4> ExitingBlocks;
3344 PIL->getExitingBlocks(ExitingBlocks);
3345 if (!ExitingBlocks.empty()) {
3346 BasicBlock *BB = ExitingBlocks[0];
3347 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
3348 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
3349 Inputs.push_back(BB->getTerminator());
3353 // Then, climb up the immediate dominator tree as far as we can go while
3354 // still being dominated by the input positions.
3355 IP = HoistInsertPosition(IP, Inputs);
3357 // Don't insert instructions before PHI nodes.
3358 while (isa<PHINode>(IP)) ++IP;
3360 // Ignore debug intrinsics.
3361 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
3366 /// Expand - Emit instructions for the leading candidate expression for this
3367 /// LSRUse (this is called "expanding").
3368 Value *LSRInstance::Expand(const LSRFixup &LF,
3370 BasicBlock::iterator IP,
3371 SCEVExpander &Rewriter,
3372 SmallVectorImpl<WeakVH> &DeadInsts) const {
3373 const LSRUse &LU = Uses[LF.LUIdx];
3375 // Determine an input position which will be dominated by the operands and
3376 // which will dominate the result.
3377 IP = AdjustInsertPositionForExpand(IP, LF, LU);
3379 // Inform the Rewriter if we have a post-increment use, so that it can
3380 // perform an advantageous expansion.
3381 Rewriter.setPostInc(LF.PostIncLoops);
3383 // This is the type that the user actually needs.
3384 const Type *OpTy = LF.OperandValToReplace->getType();
3385 // This will be the type that we'll initially expand to.
3386 const Type *Ty = F.getType();
3388 // No type known; just expand directly to the ultimate type.
3390 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3391 // Expand directly to the ultimate type if it's the right size.
3393 // This is the type to do integer arithmetic in.
3394 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3396 // Build up a list of operands to add together to form the full base.
3397 SmallVector<const SCEV *, 8> Ops;
3399 // Expand the BaseRegs portion.
3400 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3401 E = F.BaseRegs.end(); I != E; ++I) {
3402 const SCEV *Reg = *I;
3403 assert(!Reg->isZero() && "Zero allocated in a base register!");
3405 // If we're expanding for a post-inc user, make the post-inc adjustment.
3406 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3407 Reg = TransformForPostIncUse(Denormalize, Reg,
3408 LF.UserInst, LF.OperandValToReplace,
3411 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3414 // Flush the operand list to suppress SCEVExpander hoisting.
3416 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3418 Ops.push_back(SE.getUnknown(FullV));
3421 // Expand the ScaledReg portion.
3422 Value *ICmpScaledV = 0;
3423 if (F.AM.Scale != 0) {
3424 const SCEV *ScaledS = F.ScaledReg;
3426 // If we're expanding for a post-inc user, make the post-inc adjustment.
3427 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3428 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3429 LF.UserInst, LF.OperandValToReplace,
3432 if (LU.Kind == LSRUse::ICmpZero) {
3433 // An interesting way of "folding" with an icmp is to use a negated
3434 // scale, which we'll implement by inserting it into the other operand
3436 assert(F.AM.Scale == -1 &&
3437 "The only scale supported by ICmpZero uses is -1!");
3438 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3440 // Otherwise just expand the scaled register and an explicit scale,
3441 // which is expected to be matched as part of the address.
3442 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3443 ScaledS = SE.getMulExpr(ScaledS,
3444 SE.getConstant(ScaledS->getType(), F.AM.Scale));
3445 Ops.push_back(ScaledS);
3447 // Flush the operand list to suppress SCEVExpander hoisting.
3448 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3450 Ops.push_back(SE.getUnknown(FullV));
3454 // Expand the GV portion.
3456 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3458 // Flush the operand list to suppress SCEVExpander hoisting.
3459 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3461 Ops.push_back(SE.getUnknown(FullV));
3464 // Expand the immediate portion.
3465 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3467 if (LU.Kind == LSRUse::ICmpZero) {
3468 // The other interesting way of "folding" with an ICmpZero is to use a
3469 // negated immediate.
3471 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3473 Ops.push_back(SE.getUnknown(ICmpScaledV));
3474 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3477 // Just add the immediate values. These again are expected to be matched
3478 // as part of the address.
3479 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
3483 // Emit instructions summing all the operands.
3484 const SCEV *FullS = Ops.empty() ?
3485 SE.getConstant(IntTy, 0) :
3487 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3489 // We're done expanding now, so reset the rewriter.
3490 Rewriter.clearPostInc();
3492 // An ICmpZero Formula represents an ICmp which we're handling as a
3493 // comparison against zero. Now that we've expanded an expression for that
3494 // form, update the ICmp's other operand.
3495 if (LU.Kind == LSRUse::ICmpZero) {
3496 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3497 DeadInsts.push_back(CI->getOperand(1));
3498 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3499 "a scale at the same time!");
3500 if (F.AM.Scale == -1) {
3501 if (ICmpScaledV->getType() != OpTy) {
3503 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3505 ICmpScaledV, OpTy, "tmp", CI);
3508 CI->setOperand(1, ICmpScaledV);
3510 assert(F.AM.Scale == 0 &&
3511 "ICmp does not support folding a global value and "
3512 "a scale at the same time!");
3513 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3515 if (C->getType() != OpTy)
3516 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3520 CI->setOperand(1, C);
3527 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3528 /// of their operands effectively happens in their predecessor blocks, so the
3529 /// expression may need to be expanded in multiple places.
3530 void LSRInstance::RewriteForPHI(PHINode *PN,
3533 SCEVExpander &Rewriter,
3534 SmallVectorImpl<WeakVH> &DeadInsts,
3536 DenseMap<BasicBlock *, Value *> Inserted;
3537 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3538 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3539 BasicBlock *BB = PN->getIncomingBlock(i);
3541 // If this is a critical edge, split the edge so that we do not insert
3542 // the code on all predecessor/successor paths. We do this unless this
3543 // is the canonical backedge for this loop, which complicates post-inc
3545 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3546 !isa<IndirectBrInst>(BB->getTerminator()) &&
3547 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3548 // Split the critical edge.
3549 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3551 // If PN is outside of the loop and BB is in the loop, we want to
3552 // move the block to be immediately before the PHI block, not
3553 // immediately after BB.
3554 if (L->contains(BB) && !L->contains(PN))
3555 NewBB->moveBefore(PN->getParent());
3557 // Splitting the edge can reduce the number of PHI entries we have.
3558 e = PN->getNumIncomingValues();
3560 i = PN->getBasicBlockIndex(BB);
3563 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3564 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3566 PN->setIncomingValue(i, Pair.first->second);
3568 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
3570 // If this is reuse-by-noop-cast, insert the noop cast.
3571 const Type *OpTy = LF.OperandValToReplace->getType();
3572 if (FullV->getType() != OpTy)
3574 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3576 FullV, LF.OperandValToReplace->getType(),
3577 "tmp", BB->getTerminator());
3579 PN->setIncomingValue(i, FullV);
3580 Pair.first->second = FullV;
3585 /// Rewrite - Emit instructions for the leading candidate expression for this
3586 /// LSRUse (this is called "expanding"), and update the UserInst to reference
3587 /// the newly expanded value.
3588 void LSRInstance::Rewrite(const LSRFixup &LF,
3590 SCEVExpander &Rewriter,
3591 SmallVectorImpl<WeakVH> &DeadInsts,
3593 // First, find an insertion point that dominates UserInst. For PHI nodes,
3594 // find the nearest block which dominates all the relevant uses.
3595 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
3596 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
3598 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
3600 // If this is reuse-by-noop-cast, insert the noop cast.
3601 const Type *OpTy = LF.OperandValToReplace->getType();
3602 if (FullV->getType() != OpTy) {
3604 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3605 FullV, OpTy, "tmp", LF.UserInst);
3609 // Update the user. ICmpZero is handled specially here (for now) because
3610 // Expand may have updated one of the operands of the icmp already, and
3611 // its new value may happen to be equal to LF.OperandValToReplace, in
3612 // which case doing replaceUsesOfWith leads to replacing both operands
3613 // with the same value. TODO: Reorganize this.
3614 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3615 LF.UserInst->setOperand(0, FullV);
3617 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3620 DeadInsts.push_back(LF.OperandValToReplace);
3623 /// ImplementSolution - Rewrite all the fixup locations with new values,
3624 /// following the chosen solution.
3626 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3628 // Keep track of instructions we may have made dead, so that
3629 // we can remove them after we are done working.
3630 SmallVector<WeakVH, 16> DeadInsts;
3632 SCEVExpander Rewriter(SE);
3633 Rewriter.disableCanonicalMode();
3634 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3636 // Expand the new value definitions and update the users.
3637 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3638 E = Fixups.end(); I != E; ++I) {
3639 const LSRFixup &Fixup = *I;
3641 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
3646 // Clean up after ourselves. This must be done before deleting any
3650 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3653 LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3654 : IU(P->getAnalysis<IVUsers>()),
3655 SE(P->getAnalysis<ScalarEvolution>()),
3656 DT(P->getAnalysis<DominatorTree>()),
3657 LI(P->getAnalysis<LoopInfo>()),
3658 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
3660 // If LoopSimplify form is not available, stay out of trouble.
3661 if (!L->isLoopSimplifyForm()) return;
3663 // If there's no interesting work to be done, bail early.
3664 if (IU.empty()) return;
3666 DEBUG(dbgs() << "\nLSR on loop ";
3667 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3670 // First, perform some low-level loop optimizations.
3672 OptimizeLoopTermCond();
3674 // Start collecting data and preparing for the solver.
3675 CollectInterestingTypesAndFactors();
3676 CollectFixupsAndInitialFormulae();
3677 CollectLoopInvariantFixupsAndFormulae();
3679 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3680 print_uses(dbgs()));
3682 // Now use the reuse data to generate a bunch of interesting ways
3683 // to formulate the values needed for the uses.
3684 GenerateAllReuseFormulae();
3686 FilterOutUndesirableDedicatedRegisters();
3687 NarrowSearchSpaceUsingHeuristics();
3689 SmallVector<const Formula *, 8> Solution;
3692 // Release memory that is no longer needed.
3698 // Formulae should be legal.
3699 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3700 E = Uses.end(); I != E; ++I) {
3701 const LSRUse &LU = *I;
3702 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3703 JE = LU.Formulae.end(); J != JE; ++J)
3704 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3705 LU.Kind, LU.AccessTy, TLI) &&
3706 "Illegal formula generated!");
3710 // Now that we've decided what we want, make it so.
3711 ImplementSolution(Solution, P);
3714 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3715 if (Factors.empty() && Types.empty()) return;
3717 OS << "LSR has identified the following interesting factors and types: ";
3720 for (SmallSetVector<int64_t, 8>::const_iterator
3721 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3722 if (!First) OS << ", ";
3727 for (SmallSetVector<const Type *, 4>::const_iterator
3728 I = Types.begin(), E = Types.end(); I != E; ++I) {
3729 if (!First) OS << ", ";
3731 OS << '(' << **I << ')';
3736 void LSRInstance::print_fixups(raw_ostream &OS) const {
3737 OS << "LSR is examining the following fixup sites:\n";
3738 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3739 E = Fixups.end(); I != E; ++I) {
3746 void LSRInstance::print_uses(raw_ostream &OS) const {
3747 OS << "LSR is examining the following uses:\n";
3748 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3749 E = Uses.end(); I != E; ++I) {
3750 const LSRUse &LU = *I;
3754 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3755 JE = LU.Formulae.end(); J != JE; ++J) {
3763 void LSRInstance::print(raw_ostream &OS) const {
3764 print_factors_and_types(OS);
3769 void LSRInstance::dump() const {
3770 print(errs()); errs() << '\n';
3775 class LoopStrengthReduce : public LoopPass {
3776 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3777 /// transformation profitability.
3778 const TargetLowering *const TLI;
3781 static char ID; // Pass ID, replacement for typeid
3782 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3785 bool runOnLoop(Loop *L, LPPassManager &LPM);
3786 void getAnalysisUsage(AnalysisUsage &AU) const;
3791 char LoopStrengthReduce::ID = 0;
3792 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
3793 "Loop Strength Reduction", false, false)
3794 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3795 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3796 INITIALIZE_PASS_DEPENDENCY(IVUsers)
3797 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
3798 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3799 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
3800 "Loop Strength Reduction", false, false)
3803 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3804 return new LoopStrengthReduce(TLI);
3807 LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3808 : LoopPass(ID), TLI(tli) {
3809 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
3812 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3813 // We split critical edges, so we change the CFG. However, we do update
3814 // many analyses if they are around.
3815 AU.addPreservedID(LoopSimplifyID);
3816 AU.addPreserved("domfrontier");
3818 AU.addRequired<LoopInfo>();
3819 AU.addPreserved<LoopInfo>();
3820 AU.addRequiredID(LoopSimplifyID);
3821 AU.addRequired<DominatorTree>();
3822 AU.addPreserved<DominatorTree>();
3823 AU.addRequired<ScalarEvolution>();
3824 AU.addPreserved<ScalarEvolution>();
3825 AU.addRequired<IVUsers>();
3826 AU.addPreserved<IVUsers>();
3829 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3830 bool Changed = false;
3832 // Run the main LSR transformation.
3833 Changed |= LSRInstance(TLI, L, this).getChanged();
3835 // At this point, it is worth checking to see if any recurrence PHIs are also
3836 // dead, so that we can remove them as well.
3837 Changed |= DeleteDeadPHIs(L->getHeader());