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);
116 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
118 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
122 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
123 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
124 iterator begin() { return RegSequence.begin(); }
125 iterator end() { return RegSequence.end(); }
126 const_iterator begin() const { return RegSequence.begin(); }
127 const_iterator end() const { return RegSequence.end(); }
133 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
134 std::pair<RegUsesTy::iterator, bool> Pair =
135 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
136 RegSortData &RSD = Pair.first->second;
138 RegSequence.push_back(Reg);
139 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
140 RSD.UsedByIndices.set(LUIdx);
144 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
145 if (!RegUsesMap.count(Reg)) return false;
146 const SmallBitVector &UsedByIndices =
147 RegUsesMap.find(Reg)->second.UsedByIndices;
148 int i = UsedByIndices.find_first();
149 if (i == -1) return false;
150 if ((size_t)i != LUIdx) return true;
151 return UsedByIndices.find_next(i) != -1;
154 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
155 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
156 assert(I != RegUsesMap.end() && "Unknown register!");
157 return I->second.UsedByIndices;
160 void RegUseTracker::clear() {
167 /// Formula - This class holds information that describes a formula for
168 /// computing satisfying a use. It may include broken-out immediates and scaled
171 /// AM - This is used to represent complex addressing, as well as other kinds
172 /// of interesting uses.
173 TargetLowering::AddrMode AM;
175 /// BaseRegs - The list of "base" registers for this use. When this is
176 /// non-empty, AM.HasBaseReg should be set to true.
177 SmallVector<const SCEV *, 2> BaseRegs;
179 /// ScaledReg - The 'scaled' register for this use. This should be non-null
180 /// when AM.Scale is not zero.
181 const SCEV *ScaledReg;
183 Formula() : ScaledReg(0) {}
185 void InitialMatch(const SCEV *S, Loop *L,
186 ScalarEvolution &SE, DominatorTree &DT);
188 unsigned getNumRegs() const;
189 const Type *getType() const;
191 bool referencesReg(const SCEV *S) const;
192 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
193 const RegUseTracker &RegUses) const;
195 void print(raw_ostream &OS) const;
201 /// DoInitialMatch - Recursion helper for InitialMatch.
202 static void DoInitialMatch(const SCEV *S, Loop *L,
203 SmallVectorImpl<const SCEV *> &Good,
204 SmallVectorImpl<const SCEV *> &Bad,
205 ScalarEvolution &SE, DominatorTree &DT) {
206 // Collect expressions which properly dominate the loop header.
207 if (S->properlyDominates(L->getHeader(), &DT)) {
212 // Look at add operands.
213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
214 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
216 DoInitialMatch(*I, L, Good, Bad, SE, DT);
220 // Look at addrec operands.
221 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
222 if (!AR->getStart()->isZero()) {
223 DoInitialMatch(AR->getStart(), L, Good, Bad, SE, DT);
224 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
225 AR->getStepRecurrence(SE),
227 L, Good, Bad, SE, DT);
231 // Handle a multiplication by -1 (negation) if it didn't fold.
232 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
233 if (Mul->getOperand(0)->isAllOnesValue()) {
234 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
235 const SCEV *NewMul = SE.getMulExpr(Ops);
237 SmallVector<const SCEV *, 4> MyGood;
238 SmallVector<const SCEV *, 4> MyBad;
239 DoInitialMatch(NewMul, L, MyGood, MyBad, SE, DT);
240 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
241 SE.getEffectiveSCEVType(NewMul->getType())));
242 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
243 E = MyGood.end(); I != E; ++I)
244 Good.push_back(SE.getMulExpr(NegOne, *I));
245 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
246 E = MyBad.end(); I != E; ++I)
247 Bad.push_back(SE.getMulExpr(NegOne, *I));
251 // Ok, we can't do anything interesting. Just stuff the whole thing into a
252 // register and hope for the best.
256 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
257 /// attempting to keep all loop-invariant and loop-computable values in a
258 /// single base register.
259 void Formula::InitialMatch(const SCEV *S, Loop *L,
260 ScalarEvolution &SE, DominatorTree &DT) {
261 SmallVector<const SCEV *, 4> Good;
262 SmallVector<const SCEV *, 4> Bad;
263 DoInitialMatch(S, L, Good, Bad, SE, DT);
265 const SCEV *Sum = SE.getAddExpr(Good);
267 BaseRegs.push_back(Sum);
268 AM.HasBaseReg = true;
271 const SCEV *Sum = SE.getAddExpr(Bad);
273 BaseRegs.push_back(Sum);
274 AM.HasBaseReg = true;
278 /// getNumRegs - Return the total number of register operands used by this
279 /// formula. This does not include register uses implied by non-constant
281 unsigned Formula::getNumRegs() const {
282 return !!ScaledReg + BaseRegs.size();
285 /// getType - Return the type of this formula, if it has one, or null
286 /// otherwise. This type is meaningless except for the bit size.
287 const Type *Formula::getType() const {
288 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
289 ScaledReg ? ScaledReg->getType() :
290 AM.BaseGV ? AM.BaseGV->getType() :
294 /// referencesReg - Test if this formula references the given register.
295 bool Formula::referencesReg(const SCEV *S) const {
296 return S == ScaledReg ||
297 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
300 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
301 /// which are used by uses other than the use with the given index.
302 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
303 const RegUseTracker &RegUses) const {
305 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
307 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
308 E = BaseRegs.end(); I != E; ++I)
309 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
314 void Formula::print(raw_ostream &OS) const {
317 if (!First) OS << " + "; else First = false;
318 WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
320 if (AM.BaseOffs != 0) {
321 if (!First) OS << " + "; else First = false;
324 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
325 E = BaseRegs.end(); I != E; ++I) {
326 if (!First) OS << " + "; else First = false;
327 OS << "reg(" << **I << ')';
329 if (AM.HasBaseReg && BaseRegs.empty()) {
330 if (!First) OS << " + "; else First = false;
331 OS << "**error: HasBaseReg**";
332 } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
333 if (!First) OS << " + "; else First = false;
334 OS << "**error: !HasBaseReg**";
337 if (!First) OS << " + "; else First = false;
338 OS << AM.Scale << "*reg(";
347 void Formula::dump() const {
348 print(errs()); errs() << '\n';
351 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
352 /// without changing its value.
353 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
355 IntegerType::get(SE.getContext(),
356 SE.getTypeSizeInBits(AR->getType()) + 1);
357 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
360 /// isAddSExtable - Return true if the given add can be sign-extended
361 /// without changing its value.
362 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
364 IntegerType::get(SE.getContext(),
365 SE.getTypeSizeInBits(A->getType()) + 1);
366 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
369 /// isMulSExtable - Return true if the given add can be sign-extended
370 /// without changing its value.
371 static bool isMulSExtable(const SCEVMulExpr *A, ScalarEvolution &SE) {
373 IntegerType::get(SE.getContext(),
374 SE.getTypeSizeInBits(A->getType()) + 1);
375 return isa<SCEVMulExpr>(SE.getSignExtendExpr(A, WideTy));
378 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
379 /// and if the remainder is known to be zero, or null otherwise. If
380 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
381 /// to Y, ignoring that the multiplication may overflow, which is useful when
382 /// the result will be used in a context where the most significant bits are
384 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
386 bool IgnoreSignificantBits = false) {
387 // Handle the trivial case, which works for any SCEV type.
389 return SE.getConstant(LHS->getType(), 1);
391 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
393 if (RHS->isAllOnesValue())
394 return SE.getMulExpr(LHS, RHS);
396 // Check for a division of a constant by a constant.
397 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
398 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
401 if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
403 return SE.getConstant(C->getValue()->getValue()
404 .sdiv(RC->getValue()->getValue()));
407 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
408 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
409 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
410 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
411 IgnoreSignificantBits);
412 if (!Start) return 0;
413 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
414 IgnoreSignificantBits);
416 return SE.getAddRecExpr(Start, Step, AR->getLoop());
420 // Distribute the sdiv over add operands, if the add doesn't overflow.
421 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
422 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
423 SmallVector<const SCEV *, 8> Ops;
424 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
426 const SCEV *Op = getExactSDiv(*I, RHS, SE,
427 IgnoreSignificantBits);
431 return SE.getAddExpr(Ops);
435 // Check for a multiply operand that we can pull RHS out of.
436 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
437 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
438 SmallVector<const SCEV *, 4> Ops;
440 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
443 if (const SCEV *Q = getExactSDiv(*I, RHS, SE,
444 IgnoreSignificantBits)) {
451 return Found ? SE.getMulExpr(Ops) : 0;
454 // Otherwise we don't know.
458 /// ExtractImmediate - If S involves the addition of a constant integer value,
459 /// return that integer value, and mutate S to point to a new SCEV with that
461 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
462 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
463 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
464 S = SE.getConstant(C->getType(), 0);
465 return C->getValue()->getSExtValue();
467 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
468 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
469 int64_t Result = ExtractImmediate(NewOps.front(), SE);
470 S = SE.getAddExpr(NewOps);
472 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
473 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
474 int64_t Result = ExtractImmediate(NewOps.front(), SE);
475 S = SE.getAddRecExpr(NewOps, AR->getLoop());
481 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
482 /// return that symbol, and mutate S to point to a new SCEV with that
484 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
485 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
486 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
487 S = SE.getConstant(GV->getType(), 0);
490 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
491 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
492 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
493 S = SE.getAddExpr(NewOps);
495 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
496 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
497 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
498 S = SE.getAddRecExpr(NewOps, AR->getLoop());
504 /// isAddressUse - Returns true if the specified instruction is using the
505 /// specified value as an address.
506 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
507 bool isAddress = isa<LoadInst>(Inst);
508 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
509 if (SI->getOperand(1) == OperandVal)
511 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
512 // Addressing modes can also be folded into prefetches and a variety
514 switch (II->getIntrinsicID()) {
516 case Intrinsic::prefetch:
517 case Intrinsic::x86_sse2_loadu_dq:
518 case Intrinsic::x86_sse2_loadu_pd:
519 case Intrinsic::x86_sse_loadu_ps:
520 case Intrinsic::x86_sse_storeu_ps:
521 case Intrinsic::x86_sse2_storeu_pd:
522 case Intrinsic::x86_sse2_storeu_dq:
523 case Intrinsic::x86_sse2_storel_dq:
524 if (II->getOperand(1) == OperandVal)
532 /// getAccessType - Return the type of the memory being accessed.
533 static const Type *getAccessType(const Instruction *Inst) {
534 const Type *AccessTy = Inst->getType();
535 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
536 AccessTy = SI->getOperand(0)->getType();
537 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
538 // Addressing modes can also be folded into prefetches and a variety
540 switch (II->getIntrinsicID()) {
542 case Intrinsic::x86_sse_storeu_ps:
543 case Intrinsic::x86_sse2_storeu_pd:
544 case Intrinsic::x86_sse2_storeu_dq:
545 case Intrinsic::x86_sse2_storel_dq:
546 AccessTy = II->getOperand(1)->getType();
551 // All pointers have the same requirements, so canonicalize them to an
552 // arbitrary pointer type to minimize variation.
553 if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
554 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
555 PTy->getAddressSpace());
560 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
561 /// specified set are trivially dead, delete them and see if this makes any of
562 /// their operands subsequently dead.
564 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
565 bool Changed = false;
567 while (!DeadInsts.empty()) {
568 Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
570 if (I == 0 || !isInstructionTriviallyDead(I))
573 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
574 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
577 DeadInsts.push_back(U);
580 I->eraseFromParent();
589 /// Cost - This class is used to measure and compare candidate formulae.
591 /// TODO: Some of these could be merged. Also, a lexical ordering
592 /// isn't always optimal.
596 unsigned NumBaseAdds;
602 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
605 unsigned getNumRegs() const { return NumRegs; }
607 bool operator<(const Cost &Other) const;
611 void RateFormula(const Formula &F,
612 SmallPtrSet<const SCEV *, 16> &Regs,
613 const DenseSet<const SCEV *> &VisitedRegs,
615 const SmallVectorImpl<int64_t> &Offsets,
616 ScalarEvolution &SE, DominatorTree &DT);
618 void print(raw_ostream &OS) const;
622 void RateRegister(const SCEV *Reg,
623 SmallPtrSet<const SCEV *, 16> &Regs,
625 ScalarEvolution &SE, DominatorTree &DT);
626 void RatePrimaryRegister(const SCEV *Reg,
627 SmallPtrSet<const SCEV *, 16> &Regs,
629 ScalarEvolution &SE, DominatorTree &DT);
634 /// RateRegister - Tally up interesting quantities from the given register.
635 void Cost::RateRegister(const SCEV *Reg,
636 SmallPtrSet<const SCEV *, 16> &Regs,
638 ScalarEvolution &SE, DominatorTree &DT) {
639 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
640 if (AR->getLoop() == L)
641 AddRecCost += 1; /// TODO: This should be a function of the stride.
643 // If this is an addrec for a loop that's already been visited by LSR,
644 // don't second-guess its addrec phi nodes. LSR isn't currently smart
645 // enough to reason about more than one loop at a time. Consider these
646 // registers free and leave them alone.
647 else if (L->contains(AR->getLoop()) ||
648 (!AR->getLoop()->contains(L) &&
649 DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
650 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
651 PHINode *PN = dyn_cast<PHINode>(I); ++I)
652 if (SE.isSCEVable(PN->getType()) &&
653 (SE.getEffectiveSCEVType(PN->getType()) ==
654 SE.getEffectiveSCEVType(AR->getType())) &&
655 SE.getSCEV(PN) == AR)
658 // If this isn't one of the addrecs that the loop already has, it
659 // would require a costly new phi and add. TODO: This isn't
660 // precisely modeled right now.
662 if (!Regs.count(AR->getStart()))
663 RateRegister(AR->getStart(), Regs, L, SE, DT);
666 // Add the step value register, if it needs one.
667 // TODO: The non-affine case isn't precisely modeled here.
668 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
669 if (!Regs.count(AR->getStart()))
670 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
674 // Rough heuristic; favor registers which don't require extra setup
675 // instructions in the preheader.
676 if (!isa<SCEVUnknown>(Reg) &&
677 !isa<SCEVConstant>(Reg) &&
678 !(isa<SCEVAddRecExpr>(Reg) &&
679 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
680 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
684 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
686 void Cost::RatePrimaryRegister(const SCEV *Reg,
687 SmallPtrSet<const SCEV *, 16> &Regs,
689 ScalarEvolution &SE, DominatorTree &DT) {
690 if (Regs.insert(Reg))
691 RateRegister(Reg, Regs, L, SE, DT);
694 void Cost::RateFormula(const Formula &F,
695 SmallPtrSet<const SCEV *, 16> &Regs,
696 const DenseSet<const SCEV *> &VisitedRegs,
698 const SmallVectorImpl<int64_t> &Offsets,
699 ScalarEvolution &SE, DominatorTree &DT) {
700 // Tally up the registers.
701 if (const SCEV *ScaledReg = F.ScaledReg) {
702 if (VisitedRegs.count(ScaledReg)) {
706 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
708 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
709 E = F.BaseRegs.end(); I != E; ++I) {
710 const SCEV *BaseReg = *I;
711 if (VisitedRegs.count(BaseReg)) {
715 RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
717 NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
718 BaseReg->hasComputableLoopEvolution(L);
721 if (F.BaseRegs.size() > 1)
722 NumBaseAdds += F.BaseRegs.size() - 1;
724 // Tally up the non-zero immediates.
725 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
726 E = Offsets.end(); I != E; ++I) {
727 int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
729 ImmCost += 64; // Handle symbolic values conservatively.
730 // TODO: This should probably be the pointer size.
731 else if (Offset != 0)
732 ImmCost += APInt(64, Offset, true).getMinSignedBits();
736 /// Loose - Set this cost to a loosing value.
746 /// operator< - Choose the lower cost.
747 bool Cost::operator<(const Cost &Other) const {
748 if (NumRegs != Other.NumRegs)
749 return NumRegs < Other.NumRegs;
750 if (AddRecCost != Other.AddRecCost)
751 return AddRecCost < Other.AddRecCost;
752 if (NumIVMuls != Other.NumIVMuls)
753 return NumIVMuls < Other.NumIVMuls;
754 if (NumBaseAdds != Other.NumBaseAdds)
755 return NumBaseAdds < Other.NumBaseAdds;
756 if (ImmCost != Other.ImmCost)
757 return ImmCost < Other.ImmCost;
758 if (SetupCost != Other.SetupCost)
759 return SetupCost < Other.SetupCost;
763 void Cost::print(raw_ostream &OS) const {
764 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
766 OS << ", with addrec cost " << AddRecCost;
768 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
769 if (NumBaseAdds != 0)
770 OS << ", plus " << NumBaseAdds << " base add"
771 << (NumBaseAdds == 1 ? "" : "s");
773 OS << ", plus " << ImmCost << " imm cost";
775 OS << ", plus " << SetupCost << " setup cost";
778 void Cost::dump() const {
779 print(errs()); errs() << '\n';
784 /// LSRFixup - An operand value in an instruction which is to be replaced
785 /// with some equivalent, possibly strength-reduced, replacement.
787 /// UserInst - The instruction which will be updated.
788 Instruction *UserInst;
790 /// OperandValToReplace - The operand of the instruction which will
791 /// be replaced. The operand may be used more than once; every instance
792 /// will be replaced.
793 Value *OperandValToReplace;
795 /// PostIncLoops - If this user is to use the post-incremented value of an
796 /// induction variable, this variable is non-null and holds the loop
797 /// associated with the induction variable.
798 PostIncLoopSet PostIncLoops;
800 /// LUIdx - The index of the LSRUse describing the expression which
801 /// this fixup needs, minus an offset (below).
804 /// Offset - A constant offset to be added to the LSRUse expression.
805 /// This allows multiple fixups to share the same LSRUse with different
806 /// offsets, for example in an unrolled loop.
809 bool isUseFullyOutsideLoop(const Loop *L) const;
813 void print(raw_ostream &OS) const;
820 : UserInst(0), OperandValToReplace(0),
821 LUIdx(~size_t(0)), Offset(0) {}
823 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
824 /// value outside of the given loop.
825 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
826 // PHI nodes use their value in their incoming blocks.
827 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
828 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
829 if (PN->getIncomingValue(i) == OperandValToReplace &&
830 L->contains(PN->getIncomingBlock(i)))
835 return !L->contains(UserInst);
838 void LSRFixup::print(raw_ostream &OS) const {
840 // Store is common and interesting enough to be worth special-casing.
841 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
843 WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
844 } else if (UserInst->getType()->isVoidTy())
845 OS << UserInst->getOpcodeName();
847 WriteAsOperand(OS, UserInst, /*PrintType=*/false);
849 OS << ", OperandValToReplace=";
850 WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
852 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
853 E = PostIncLoops.end(); I != E; ++I) {
854 OS << ", PostIncLoop=";
855 WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
858 if (LUIdx != ~size_t(0))
859 OS << ", LUIdx=" << LUIdx;
862 OS << ", Offset=" << Offset;
865 void LSRFixup::dump() const {
866 print(errs()); errs() << '\n';
871 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
872 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
873 struct UniquifierDenseMapInfo {
874 static SmallVector<const SCEV *, 2> getEmptyKey() {
875 SmallVector<const SCEV *, 2> V;
876 V.push_back(reinterpret_cast<const SCEV *>(-1));
880 static SmallVector<const SCEV *, 2> getTombstoneKey() {
881 SmallVector<const SCEV *, 2> V;
882 V.push_back(reinterpret_cast<const SCEV *>(-2));
886 static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
888 for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
889 E = V.end(); I != E; ++I)
890 Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
894 static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
895 const SmallVector<const SCEV *, 2> &RHS) {
900 /// LSRUse - This class holds the state that LSR keeps for each use in
901 /// IVUsers, as well as uses invented by LSR itself. It includes information
902 /// about what kinds of things can be folded into the user, information about
903 /// the user itself, and information about how the use may be satisfied.
904 /// TODO: Represent multiple users of the same expression in common?
906 DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
909 /// KindType - An enum for a kind of use, indicating what types of
910 /// scaled and immediate operands it might support.
912 Basic, ///< A normal use, with no folding.
913 Special, ///< A special case of basic, allowing -1 scales.
914 Address, ///< An address use; folding according to TargetLowering
915 ICmpZero ///< An equality icmp with both operands folded into one.
916 // TODO: Add a generic icmp too?
920 const Type *AccessTy;
922 SmallVector<int64_t, 8> Offsets;
926 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
927 /// LSRUse are outside of the loop, in which case some special-case heuristics
929 bool AllFixupsOutsideLoop;
931 /// Formulae - A list of ways to build a value that can satisfy this user.
932 /// After the list is populated, one of these is selected heuristically and
933 /// used to formulate a replacement for OperandValToReplace in UserInst.
934 SmallVector<Formula, 12> Formulae;
936 /// Regs - The set of register candidates used by all formulae in this LSRUse.
937 SmallPtrSet<const SCEV *, 4> Regs;
939 LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
940 MinOffset(INT64_MAX),
941 MaxOffset(INT64_MIN),
942 AllFixupsOutsideLoop(true) {}
944 bool InsertFormula(const Formula &F);
945 void DeleteFormula(Formula &F);
949 void print(raw_ostream &OS) const;
953 /// InsertFormula - If the given formula has not yet been inserted, add it to
954 /// the list, and return true. Return false otherwise.
955 bool LSRUse::InsertFormula(const Formula &F) {
956 SmallVector<const SCEV *, 2> Key = F.BaseRegs;
957 if (F.ScaledReg) Key.push_back(F.ScaledReg);
958 // Unstable sort by host order ok, because this is only used for uniquifying.
959 std::sort(Key.begin(), Key.end());
961 if (!Uniquifier.insert(Key).second)
964 // Using a register to hold the value of 0 is not profitable.
965 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
966 "Zero allocated in a scaled register!");
968 for (SmallVectorImpl<const SCEV *>::const_iterator I =
969 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
970 assert(!(*I)->isZero() && "Zero allocated in a base register!");
973 // Add the formula to the list.
974 Formulae.push_back(F);
976 // Record registers now being used by this use.
977 if (F.ScaledReg) Regs.insert(F.ScaledReg);
978 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
983 /// DeleteFormula - Remove the given formula from this use's list.
984 void LSRUse::DeleteFormula(Formula &F) {
985 std::swap(F, Formulae.back());
989 void LSRUse::print(raw_ostream &OS) const {
990 OS << "LSR Use: Kind=";
992 case Basic: OS << "Basic"; break;
993 case Special: OS << "Special"; break;
994 case ICmpZero: OS << "ICmpZero"; break;
997 if (AccessTy->isPointerTy())
998 OS << "pointer"; // the full pointer type could be really verbose
1003 OS << ", Offsets={";
1004 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1005 E = Offsets.end(); I != E; ++I) {
1012 if (AllFixupsOutsideLoop)
1013 OS << ", all-fixups-outside-loop";
1016 void LSRUse::dump() const {
1017 print(errs()); errs() << '\n';
1020 /// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1021 /// be completely folded into the user instruction at isel time. This includes
1022 /// address-mode folding and special icmp tricks.
1023 static bool isLegalUse(const TargetLowering::AddrMode &AM,
1024 LSRUse::KindType Kind, const Type *AccessTy,
1025 const TargetLowering *TLI) {
1027 case LSRUse::Address:
1028 // If we have low-level target information, ask the target if it can
1029 // completely fold this address.
1030 if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1032 // Otherwise, just guess that reg+reg addressing is legal.
1033 return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1035 case LSRUse::ICmpZero:
1036 // There's not even a target hook for querying whether it would be legal to
1037 // fold a GV into an ICmp.
1041 // ICmp only has two operands; don't allow more than two non-trivial parts.
1042 if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1045 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1046 // putting the scaled register in the other operand of the icmp.
1047 if (AM.Scale != 0 && AM.Scale != -1)
1050 // If we have low-level target information, ask the target if it can fold an
1051 // integer immediate on an icmp.
1052 if (AM.BaseOffs != 0) {
1053 if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1060 // Only handle single-register values.
1061 return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1063 case LSRUse::Special:
1064 // Only handle -1 scales, or no scale.
1065 return AM.Scale == 0 || AM.Scale == -1;
1071 static bool isLegalUse(TargetLowering::AddrMode AM,
1072 int64_t MinOffset, int64_t MaxOffset,
1073 LSRUse::KindType Kind, const Type *AccessTy,
1074 const TargetLowering *TLI) {
1075 // Check for overflow.
1076 if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1079 AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1080 if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1081 AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1082 // Check for overflow.
1083 if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1086 AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1087 return isLegalUse(AM, Kind, AccessTy, TLI);
1092 static bool isAlwaysFoldable(int64_t BaseOffs,
1093 GlobalValue *BaseGV,
1095 LSRUse::KindType Kind, const Type *AccessTy,
1096 const TargetLowering *TLI) {
1097 // Fast-path: zero is always foldable.
1098 if (BaseOffs == 0 && !BaseGV) return true;
1100 // Conservatively, create an address with an immediate and a
1101 // base and a scale.
1102 TargetLowering::AddrMode AM;
1103 AM.BaseOffs = BaseOffs;
1105 AM.HasBaseReg = HasBaseReg;
1106 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1108 return isLegalUse(AM, Kind, AccessTy, TLI);
1111 static bool isAlwaysFoldable(const SCEV *S,
1112 int64_t MinOffset, int64_t MaxOffset,
1114 LSRUse::KindType Kind, const Type *AccessTy,
1115 const TargetLowering *TLI,
1116 ScalarEvolution &SE) {
1117 // Fast-path: zero is always foldable.
1118 if (S->isZero()) return true;
1120 // Conservatively, create an address with an immediate and a
1121 // base and a scale.
1122 int64_t BaseOffs = ExtractImmediate(S, SE);
1123 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1125 // If there's anything else involved, it's not foldable.
1126 if (!S->isZero()) return false;
1128 // Fast-path: zero is always foldable.
1129 if (BaseOffs == 0 && !BaseGV) return true;
1131 // Conservatively, create an address with an immediate and a
1132 // base and a scale.
1133 TargetLowering::AddrMode AM;
1134 AM.BaseOffs = BaseOffs;
1136 AM.HasBaseReg = HasBaseReg;
1137 AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1139 return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
1142 /// FormulaSorter - This class implements an ordering for formulae which sorts
1143 /// the by their standalone cost.
1144 class FormulaSorter {
1145 /// These two sets are kept empty, so that we compute standalone costs.
1146 DenseSet<const SCEV *> VisitedRegs;
1147 SmallPtrSet<const SCEV *, 16> Regs;
1150 ScalarEvolution &SE;
1154 FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1155 : L(l), LU(&lu), SE(se), DT(dt) {}
1157 bool operator()(const Formula &A, const Formula &B) {
1159 CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1162 CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1164 return CostA < CostB;
1168 /// LSRInstance - This class holds state for the main loop strength reduction
1172 ScalarEvolution &SE;
1175 const TargetLowering *const TLI;
1179 /// IVIncInsertPos - This is the insert position that the current loop's
1180 /// induction variable increment should be placed. In simple loops, this is
1181 /// the latch block's terminator. But in more complicated cases, this is a
1182 /// position which will dominate all the in-loop post-increment users.
1183 Instruction *IVIncInsertPos;
1185 /// Factors - Interesting factors between use strides.
1186 SmallSetVector<int64_t, 8> Factors;
1188 /// Types - Interesting use types, to facilitate truncation reuse.
1189 SmallSetVector<const Type *, 4> Types;
1191 /// Fixups - The list of operands which are to be replaced.
1192 SmallVector<LSRFixup, 16> Fixups;
1194 /// Uses - The list of interesting uses.
1195 SmallVector<LSRUse, 16> Uses;
1197 /// RegUses - Track which uses use which register candidates.
1198 RegUseTracker RegUses;
1200 void OptimizeShadowIV();
1201 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1202 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1203 bool OptimizeLoopTermCond();
1205 void CollectInterestingTypesAndFactors();
1206 void CollectFixupsAndInitialFormulae();
1208 LSRFixup &getNewFixup() {
1209 Fixups.push_back(LSRFixup());
1210 return Fixups.back();
1213 // Support for sharing of LSRUses between LSRFixups.
1214 typedef DenseMap<const SCEV *, size_t> UseMapTy;
1217 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1218 LSRUse::KindType Kind, const Type *AccessTy);
1220 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1221 LSRUse::KindType Kind,
1222 const Type *AccessTy);
1225 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1226 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1227 void CountRegisters(const Formula &F, size_t LUIdx);
1228 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1230 void CollectLoopInvariantFixupsAndFormulae();
1232 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1233 unsigned Depth = 0);
1234 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1235 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1236 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1237 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1238 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1239 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1240 void GenerateCrossUseConstantOffsets();
1241 void GenerateAllReuseFormulae();
1243 void FilterOutUndesirableDedicatedRegisters();
1244 void NarrowSearchSpaceUsingHeuristics();
1246 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1248 SmallVectorImpl<const Formula *> &Workspace,
1249 const Cost &CurCost,
1250 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1251 DenseSet<const SCEV *> &VisitedRegs) const;
1252 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1254 BasicBlock::iterator
1255 HoistInsertPosition(BasicBlock::iterator IP,
1256 const SmallVectorImpl<Instruction *> &Inputs) const;
1257 BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1259 const LSRUse &LU) const;
1261 Value *Expand(const LSRFixup &LF,
1263 BasicBlock::iterator IP,
1264 SCEVExpander &Rewriter,
1265 SmallVectorImpl<WeakVH> &DeadInsts) const;
1266 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1268 SCEVExpander &Rewriter,
1269 SmallVectorImpl<WeakVH> &DeadInsts,
1271 void Rewrite(const LSRFixup &LF,
1273 SCEVExpander &Rewriter,
1274 SmallVectorImpl<WeakVH> &DeadInsts,
1276 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1279 LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1281 bool getChanged() const { return Changed; }
1283 void print_factors_and_types(raw_ostream &OS) const;
1284 void print_fixups(raw_ostream &OS) const;
1285 void print_uses(raw_ostream &OS) const;
1286 void print(raw_ostream &OS) const;
1292 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1293 /// inside the loop then try to eliminate the cast operation.
1294 void LSRInstance::OptimizeShadowIV() {
1295 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1296 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1299 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1300 UI != E; /* empty */) {
1301 IVUsers::const_iterator CandidateUI = UI;
1303 Instruction *ShadowUse = CandidateUI->getUser();
1304 const Type *DestTy = NULL;
1306 /* If shadow use is a int->float cast then insert a second IV
1307 to eliminate this cast.
1309 for (unsigned i = 0; i < n; ++i)
1315 for (unsigned i = 0; i < n; ++i, ++d)
1318 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1319 DestTy = UCast->getDestTy();
1320 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1321 DestTy = SCast->getDestTy();
1322 if (!DestTy) continue;
1325 // If target does not support DestTy natively then do not apply
1326 // this transformation.
1327 EVT DVT = TLI->getValueType(DestTy);
1328 if (!TLI->isTypeLegal(DVT)) continue;
1331 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1333 if (PH->getNumIncomingValues() != 2) continue;
1335 const Type *SrcTy = PH->getType();
1336 int Mantissa = DestTy->getFPMantissaWidth();
1337 if (Mantissa == -1) continue;
1338 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1341 unsigned Entry, Latch;
1342 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1350 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1351 if (!Init) continue;
1352 Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
1354 BinaryOperator *Incr =
1355 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1356 if (!Incr) continue;
1357 if (Incr->getOpcode() != Instruction::Add
1358 && Incr->getOpcode() != Instruction::Sub)
1361 /* Initialize new IV, double d = 0.0 in above example. */
1362 ConstantInt *C = NULL;
1363 if (Incr->getOperand(0) == PH)
1364 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1365 else if (Incr->getOperand(1) == PH)
1366 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
1372 // Ignore negative constants, as the code below doesn't handle them
1373 // correctly. TODO: Remove this restriction.
1374 if (!C->getValue().isStrictlyPositive()) continue;
1376 /* Add new PHINode. */
1377 PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
1379 /* create new increment. '++d' in above example. */
1380 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1381 BinaryOperator *NewIncr =
1382 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1383 Instruction::FAdd : Instruction::FSub,
1384 NewPH, CFP, "IV.S.next.", Incr);
1386 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1387 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1389 /* Remove cast operation */
1390 ShadowUse->replaceAllUsesWith(NewPH);
1391 ShadowUse->eraseFromParent();
1396 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1397 /// set the IV user and stride information and return true, otherwise return
1399 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1400 IVStrideUse *&CondUse) {
1401 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1402 if (UI->getUser() == Cond) {
1403 // NOTE: we could handle setcc instructions with multiple uses here, but
1404 // InstCombine does it as well for simple uses, it's not clear that it
1405 // occurs enough in real life to handle.
1412 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
1413 /// a max computation.
1415 /// This is a narrow solution to a specific, but acute, problem. For loops
1421 /// } while (++i < n);
1423 /// the trip count isn't just 'n', because 'n' might not be positive. And
1424 /// unfortunately this can come up even for loops where the user didn't use
1425 /// a C do-while loop. For example, seemingly well-behaved top-test loops
1426 /// will commonly be lowered like this:
1432 /// } while (++i < n);
1435 /// and then it's possible for subsequent optimization to obscure the if
1436 /// test in such a way that indvars can't find it.
1438 /// When indvars can't find the if test in loops like this, it creates a
1439 /// max expression, which allows it to give the loop a canonical
1440 /// induction variable:
1443 /// max = n < 1 ? 1 : n;
1446 /// } while (++i != max);
1448 /// Canonical induction variables are necessary because the loop passes
1449 /// are designed around them. The most obvious example of this is the
1450 /// LoopInfo analysis, which doesn't remember trip count values. It
1451 /// expects to be able to rediscover the trip count each time it is
1452 /// needed, and it does this using a simple analysis that only succeeds if
1453 /// the loop has a canonical induction variable.
1455 /// However, when it comes time to generate code, the maximum operation
1456 /// can be quite costly, especially if it's inside of an outer loop.
1458 /// This function solves this problem by detecting this type of loop and
1459 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1460 /// the instructions for the maximum computation.
1462 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
1463 // Check that the loop matches the pattern we're looking for.
1464 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1465 Cond->getPredicate() != CmpInst::ICMP_NE)
1468 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1469 if (!Sel || !Sel->hasOneUse()) return Cond;
1471 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1472 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1474 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
1476 // Add one to the backedge-taken count to get the trip count.
1477 const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
1478 if (IterationCount != SE.getSCEV(Sel)) return Cond;
1480 // Check for a max calculation that matches the pattern. There's no check
1481 // for ICMP_ULE here because the comparison would be with zero, which
1482 // isn't interesting.
1483 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1484 const SCEVNAryExpr *Max = 0;
1485 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1486 Pred = ICmpInst::ICMP_SLE;
1488 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1489 Pred = ICmpInst::ICMP_SLT;
1491 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1492 Pred = ICmpInst::ICMP_ULT;
1499 // To handle a max with more than two operands, this optimization would
1500 // require additional checking and setup.
1501 if (Max->getNumOperands() != 2)
1504 const SCEV *MaxLHS = Max->getOperand(0);
1505 const SCEV *MaxRHS = Max->getOperand(1);
1507 // ScalarEvolution canonicalizes constants to the left. For < and >, look
1508 // for a comparison with 1. For <= and >=, a comparison with zero.
1510 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1513 // Check the relevant induction variable for conformance to
1515 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
1516 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1517 if (!AR || !AR->isAffine() ||
1518 AR->getStart() != One ||
1519 AR->getStepRecurrence(SE) != One)
1522 assert(AR->getLoop() == L &&
1523 "Loop condition operand is an addrec in a different loop!");
1525 // Check the right operand of the select, and remember it, as it will
1526 // be used in the new comparison instruction.
1528 if (ICmpInst::isTrueWhenEqual(Pred)) {
1529 // Look for n+1, and grab n.
1530 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1531 if (isa<ConstantInt>(BO->getOperand(1)) &&
1532 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1533 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1534 NewRHS = BO->getOperand(0);
1535 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1536 if (isa<ConstantInt>(BO->getOperand(1)) &&
1537 cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1538 SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1539 NewRHS = BO->getOperand(0);
1542 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
1543 NewRHS = Sel->getOperand(1);
1544 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
1545 NewRHS = Sel->getOperand(2);
1547 llvm_unreachable("Max doesn't match expected pattern!");
1549 // Determine the new comparison opcode. It may be signed or unsigned,
1550 // and the original comparison may be either equality or inequality.
1551 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1552 Pred = CmpInst::getInversePredicate(Pred);
1554 // Ok, everything looks ok to change the condition into an SLT or SGE and
1555 // delete the max calculation.
1557 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1559 // Delete the max calculation instructions.
1560 Cond->replaceAllUsesWith(NewCond);
1561 CondUse->setUser(NewCond);
1562 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1563 Cond->eraseFromParent();
1564 Sel->eraseFromParent();
1565 if (Cmp->use_empty())
1566 Cmp->eraseFromParent();
1570 /// OptimizeLoopTermCond - Change loop terminating condition to use the
1571 /// postinc iv when possible.
1573 LSRInstance::OptimizeLoopTermCond() {
1574 SmallPtrSet<Instruction *, 4> PostIncs;
1576 BasicBlock *LatchBlock = L->getLoopLatch();
1577 SmallVector<BasicBlock*, 8> ExitingBlocks;
1578 L->getExitingBlocks(ExitingBlocks);
1580 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1581 BasicBlock *ExitingBlock = ExitingBlocks[i];
1583 // Get the terminating condition for the loop if possible. If we
1584 // can, we want to change it to use a post-incremented version of its
1585 // induction variable, to allow coalescing the live ranges for the IV into
1586 // one register value.
1588 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1591 // FIXME: Overly conservative, termination condition could be an 'or' etc..
1592 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1595 // Search IVUsesByStride to find Cond's IVUse if there is one.
1596 IVStrideUse *CondUse = 0;
1597 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1598 if (!FindIVUserForCond(Cond, CondUse))
1601 // If the trip count is computed in terms of a max (due to ScalarEvolution
1602 // being unable to find a sufficient guard, for example), change the loop
1603 // comparison to use SLT or ULT instead of NE.
1604 // One consequence of doing this now is that it disrupts the count-down
1605 // optimization. That's not always a bad thing though, because in such
1606 // cases it may still be worthwhile to avoid a max.
1607 Cond = OptimizeMax(Cond, CondUse);
1609 // If this exiting block dominates the latch block, it may also use
1610 // the post-inc value if it won't be shared with other uses.
1611 // Check for dominance.
1612 if (!DT.dominates(ExitingBlock, LatchBlock))
1615 // Conservatively avoid trying to use the post-inc value in non-latch
1616 // exits if there may be pre-inc users in intervening blocks.
1617 if (LatchBlock != ExitingBlock)
1618 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1619 // Test if the use is reachable from the exiting block. This dominator
1620 // query is a conservative approximation of reachability.
1621 if (&*UI != CondUse &&
1622 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1623 // Conservatively assume there may be reuse if the quotient of their
1624 // strides could be a legal scale.
1625 const SCEV *A = IU.getStride(*CondUse, L);
1626 const SCEV *B = IU.getStride(*UI, L);
1627 if (!A || !B) continue;
1628 if (SE.getTypeSizeInBits(A->getType()) !=
1629 SE.getTypeSizeInBits(B->getType())) {
1630 if (SE.getTypeSizeInBits(A->getType()) >
1631 SE.getTypeSizeInBits(B->getType()))
1632 B = SE.getSignExtendExpr(B, A->getType());
1634 A = SE.getSignExtendExpr(A, B->getType());
1636 if (const SCEVConstant *D =
1637 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
1638 // Stride of one or negative one can have reuse with non-addresses.
1639 if (D->getValue()->isOne() ||
1640 D->getValue()->isAllOnesValue())
1641 goto decline_post_inc;
1642 // Avoid weird situations.
1643 if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1644 D->getValue()->getValue().isMinSignedValue())
1645 goto decline_post_inc;
1646 // Without TLI, assume that any stride might be valid, and so any
1647 // use might be shared.
1649 goto decline_post_inc;
1650 // Check for possible scaled-address reuse.
1651 const Type *AccessTy = getAccessType(UI->getUser());
1652 TargetLowering::AddrMode AM;
1653 AM.Scale = D->getValue()->getSExtValue();
1654 if (TLI->isLegalAddressingMode(AM, AccessTy))
1655 goto decline_post_inc;
1656 AM.Scale = -AM.Scale;
1657 if (TLI->isLegalAddressingMode(AM, AccessTy))
1658 goto decline_post_inc;
1662 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
1665 // It's possible for the setcc instruction to be anywhere in the loop, and
1666 // possible for it to have multiple users. If it is not immediately before
1667 // the exiting block branch, move it.
1668 if (&*++BasicBlock::iterator(Cond) != TermBr) {
1669 if (Cond->hasOneUse()) {
1670 Cond->moveBefore(TermBr);
1672 // Clone the terminating condition and insert into the loopend.
1673 ICmpInst *OldCond = Cond;
1674 Cond = cast<ICmpInst>(Cond->clone());
1675 Cond->setName(L->getHeader()->getName() + ".termcond");
1676 ExitingBlock->getInstList().insert(TermBr, Cond);
1678 // Clone the IVUse, as the old use still exists!
1679 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
1680 TermBr->replaceUsesOfWith(OldCond, Cond);
1684 // If we get to here, we know that we can transform the setcc instruction to
1685 // use the post-incremented version of the IV, allowing us to coalesce the
1686 // live ranges for the IV correctly.
1687 CondUse->transformToPostInc(L);
1690 PostIncs.insert(Cond);
1694 // Determine an insertion point for the loop induction variable increment. It
1695 // must dominate all the post-inc comparisons we just set up, and it must
1696 // dominate the loop latch edge.
1697 IVIncInsertPos = L->getLoopLatch()->getTerminator();
1698 for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1699 E = PostIncs.end(); I != E; ++I) {
1701 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1703 if (BB == (*I)->getParent())
1704 IVIncInsertPos = *I;
1705 else if (BB != IVIncInsertPos->getParent())
1706 IVIncInsertPos = BB->getTerminator();
1713 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1714 LSRUse::KindType Kind, const Type *AccessTy) {
1715 int64_t NewMinOffset = LU.MinOffset;
1716 int64_t NewMaxOffset = LU.MaxOffset;
1717 const Type *NewAccessTy = AccessTy;
1719 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1720 // something conservative, however this can pessimize in the case that one of
1721 // the uses will have all its uses outside the loop, for example.
1722 if (LU.Kind != Kind)
1724 // Conservatively assume HasBaseReg is true for now.
1725 if (NewOffset < LU.MinOffset) {
1726 if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
1727 Kind, AccessTy, TLI))
1729 NewMinOffset = NewOffset;
1730 } else if (NewOffset > LU.MaxOffset) {
1731 if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
1732 Kind, AccessTy, TLI))
1734 NewMaxOffset = NewOffset;
1736 // Check for a mismatched access type, and fall back conservatively as needed.
1737 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1738 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
1741 LU.MinOffset = NewMinOffset;
1742 LU.MaxOffset = NewMaxOffset;
1743 LU.AccessTy = NewAccessTy;
1744 if (NewOffset != LU.Offsets.back())
1745 LU.Offsets.push_back(NewOffset);
1749 /// getUse - Return an LSRUse index and an offset value for a fixup which
1750 /// needs the given expression, with the given kind and optional access type.
1751 /// Either reuse an existing use or create a new one, as needed.
1752 std::pair<size_t, int64_t>
1753 LSRInstance::getUse(const SCEV *&Expr,
1754 LSRUse::KindType Kind, const Type *AccessTy) {
1755 const SCEV *Copy = Expr;
1756 int64_t Offset = ExtractImmediate(Expr, SE);
1758 // Basic uses can't accept any offset, for example.
1759 if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
1764 std::pair<UseMapTy::iterator, bool> P =
1765 UseMap.insert(std::make_pair(Expr, 0));
1767 // A use already existed with this base.
1768 size_t LUIdx = P.first->second;
1769 LSRUse &LU = Uses[LUIdx];
1770 if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1772 return std::make_pair(LUIdx, Offset);
1775 // Create a new use.
1776 size_t LUIdx = Uses.size();
1777 P.first->second = LUIdx;
1778 Uses.push_back(LSRUse(Kind, AccessTy));
1779 LSRUse &LU = Uses[LUIdx];
1781 // We don't need to track redundant offsets, but we don't need to go out
1782 // of our way here to avoid them.
1783 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1784 LU.Offsets.push_back(Offset);
1786 LU.MinOffset = Offset;
1787 LU.MaxOffset = Offset;
1788 return std::make_pair(LUIdx, Offset);
1791 void LSRInstance::CollectInterestingTypesAndFactors() {
1792 SmallSetVector<const SCEV *, 4> Strides;
1794 // Collect interesting types and strides.
1795 SmallVector<const SCEV *, 4> Worklist;
1796 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1797 const SCEV *Expr = IU.getExpr(*UI);
1799 // Collect interesting types.
1800 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
1802 // Add strides for mentioned loops.
1803 Worklist.push_back(Expr);
1805 const SCEV *S = Worklist.pop_back_val();
1806 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1807 Strides.insert(AR->getStepRecurrence(SE));
1808 Worklist.push_back(AR->getStart());
1809 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1810 Worklist.insert(Worklist.end(), Add->op_begin(), Add->op_end());
1812 } while (!Worklist.empty());
1815 // Compute interesting factors from the set of interesting strides.
1816 for (SmallSetVector<const SCEV *, 4>::const_iterator
1817 I = Strides.begin(), E = Strides.end(); I != E; ++I)
1818 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
1819 next(I); NewStrideIter != E; ++NewStrideIter) {
1820 const SCEV *OldStride = *I;
1821 const SCEV *NewStride = *NewStrideIter;
1823 if (SE.getTypeSizeInBits(OldStride->getType()) !=
1824 SE.getTypeSizeInBits(NewStride->getType())) {
1825 if (SE.getTypeSizeInBits(OldStride->getType()) >
1826 SE.getTypeSizeInBits(NewStride->getType()))
1827 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1829 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1831 if (const SCEVConstant *Factor =
1832 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1834 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1835 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1836 } else if (const SCEVConstant *Factor =
1837 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
1840 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1841 Factors.insert(Factor->getValue()->getValue().getSExtValue());
1845 // If all uses use the same type, don't bother looking for truncation-based
1847 if (Types.size() == 1)
1850 DEBUG(print_factors_and_types(dbgs()));
1853 void LSRInstance::CollectFixupsAndInitialFormulae() {
1854 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1856 LSRFixup &LF = getNewFixup();
1857 LF.UserInst = UI->getUser();
1858 LF.OperandValToReplace = UI->getOperandValToReplace();
1859 LF.PostIncLoops = UI->getPostIncLoops();
1861 LSRUse::KindType Kind = LSRUse::Basic;
1862 const Type *AccessTy = 0;
1863 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1864 Kind = LSRUse::Address;
1865 AccessTy = getAccessType(LF.UserInst);
1868 const SCEV *S = IU.getExpr(*UI);
1870 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1871 // (N - i == 0), and this allows (N - i) to be the expression that we work
1872 // with rather than just N or i, so we can consider the register
1873 // requirements for both N and i at the same time. Limiting this code to
1874 // equality icmps is not a problem because all interesting loops use
1875 // equality icmps, thanks to IndVarSimplify.
1876 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1877 if (CI->isEquality()) {
1878 // Swap the operands if needed to put the OperandValToReplace on the
1879 // left, for consistency.
1880 Value *NV = CI->getOperand(1);
1881 if (NV == LF.OperandValToReplace) {
1882 CI->setOperand(1, CI->getOperand(0));
1883 CI->setOperand(0, NV);
1886 // x == y --> x - y == 0
1887 const SCEV *N = SE.getSCEV(NV);
1888 if (N->isLoopInvariant(L)) {
1889 Kind = LSRUse::ICmpZero;
1890 S = SE.getMinusSCEV(N, S);
1893 // -1 and the negations of all interesting strides (except the negation
1894 // of -1) are now also interesting.
1895 for (size_t i = 0, e = Factors.size(); i != e; ++i)
1896 if (Factors[i] != -1)
1897 Factors.insert(-(uint64_t)Factors[i]);
1901 // Set up the initial formula for this use.
1902 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1904 LF.Offset = P.second;
1905 LSRUse &LU = Uses[LF.LUIdx];
1906 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
1908 // If this is the first use of this LSRUse, give it a formula.
1909 if (LU.Formulae.empty()) {
1910 InsertInitialFormula(S, LU, LF.LUIdx);
1911 CountRegisters(LU.Formulae.back(), LF.LUIdx);
1915 DEBUG(print_fixups(dbgs()));
1919 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
1921 F.InitialMatch(S, L, SE, DT);
1922 bool Inserted = InsertFormula(LU, LUIdx, F);
1923 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1927 LSRInstance::InsertSupplementalFormula(const SCEV *S,
1928 LSRUse &LU, size_t LUIdx) {
1930 F.BaseRegs.push_back(S);
1931 F.AM.HasBaseReg = true;
1932 bool Inserted = InsertFormula(LU, LUIdx, F);
1933 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1936 /// CountRegisters - Note which registers are used by the given formula,
1937 /// updating RegUses.
1938 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1940 RegUses.CountRegister(F.ScaledReg, LUIdx);
1941 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1942 E = F.BaseRegs.end(); I != E; ++I)
1943 RegUses.CountRegister(*I, LUIdx);
1946 /// InsertFormula - If the given formula has not yet been inserted, add it to
1947 /// the list, and return true. Return false otherwise.
1948 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
1949 if (!LU.InsertFormula(F))
1952 CountRegisters(F, LUIdx);
1956 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1957 /// loop-invariant values which we're tracking. These other uses will pin these
1958 /// values in registers, making them less profitable for elimination.
1959 /// TODO: This currently misses non-constant addrec step registers.
1960 /// TODO: Should this give more weight to users inside the loop?
1962 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1963 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1964 SmallPtrSet<const SCEV *, 8> Inserted;
1966 while (!Worklist.empty()) {
1967 const SCEV *S = Worklist.pop_back_val();
1969 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
1970 Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
1971 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1972 Worklist.push_back(C->getOperand());
1973 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1974 Worklist.push_back(D->getLHS());
1975 Worklist.push_back(D->getRHS());
1976 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
1977 if (!Inserted.insert(U)) continue;
1978 const Value *V = U->getValue();
1979 if (const Instruction *Inst = dyn_cast<Instruction>(V))
1980 if (L->contains(Inst)) continue;
1981 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1983 const Instruction *UserInst = dyn_cast<Instruction>(*UI);
1984 // Ignore non-instructions.
1987 // Ignore instructions in other functions (as can happen with
1989 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
1991 // Ignore instructions not dominated by the loop.
1992 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
1993 UserInst->getParent() :
1994 cast<PHINode>(UserInst)->getIncomingBlock(
1995 PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
1996 if (!DT.dominates(L->getHeader(), UseBB))
1998 // Ignore uses which are part of other SCEV expressions, to avoid
1999 // analyzing them multiple times.
2000 if (SE.isSCEVable(UserInst->getType())) {
2001 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2002 // If the user is a no-op, look through to its uses.
2003 if (!isa<SCEVUnknown>(UserS))
2007 SE.getUnknown(const_cast<Instruction *>(UserInst)));
2011 // Ignore icmp instructions which are already being analyzed.
2012 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2013 unsigned OtherIdx = !UI.getOperandNo();
2014 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
2015 if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
2019 LSRFixup &LF = getNewFixup();
2020 LF.UserInst = const_cast<Instruction *>(UserInst);
2021 LF.OperandValToReplace = UI.getUse();
2022 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2024 LF.Offset = P.second;
2025 LSRUse &LU = Uses[LF.LUIdx];
2026 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
2027 InsertSupplementalFormula(U, LU, LF.LUIdx);
2028 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2035 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
2036 /// separate registers. If C is non-null, multiply each subexpression by C.
2037 static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2038 SmallVectorImpl<const SCEV *> &Ops,
2039 ScalarEvolution &SE) {
2040 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2041 // Break out add operands.
2042 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2044 CollectSubexprs(*I, C, Ops, SE);
2046 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2047 // Split a non-zero base out of an addrec.
2048 if (!AR->getStart()->isZero()) {
2049 CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
2050 AR->getStepRecurrence(SE),
2051 AR->getLoop()), C, Ops, SE);
2052 CollectSubexprs(AR->getStart(), C, Ops, SE);
2055 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2056 // Break (C * (a + b + c)) into C*a + C*b + C*c.
2057 if (Mul->getNumOperands() == 2)
2058 if (const SCEVConstant *Op0 =
2059 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2060 CollectSubexprs(Mul->getOperand(1),
2061 C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2067 // Otherwise use the value itself.
2068 Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2071 /// GenerateReassociations - Split out subexpressions from adds and the bases of
2073 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2076 // Arbitrarily cap recursion to protect compile time.
2077 if (Depth >= 3) return;
2079 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2080 const SCEV *BaseReg = Base.BaseRegs[i];
2082 SmallVector<const SCEV *, 8> AddOps;
2083 CollectSubexprs(BaseReg, 0, AddOps, SE);
2084 if (AddOps.size() == 1) continue;
2086 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2087 JE = AddOps.end(); J != JE; ++J) {
2088 // Don't pull a constant into a register if the constant could be folded
2089 // into an immediate field.
2090 if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2091 Base.getNumRegs() > 1,
2092 LU.Kind, LU.AccessTy, TLI, SE))
2095 // Collect all operands except *J.
2096 SmallVector<const SCEV *, 8> InnerAddOps;
2097 for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2098 KE = AddOps.end(); K != KE; ++K)
2100 InnerAddOps.push_back(*K);
2102 // Don't leave just a constant behind in a register if the constant could
2103 // be folded into an immediate field.
2104 if (InnerAddOps.size() == 1 &&
2105 isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2106 Base.getNumRegs() > 1,
2107 LU.Kind, LU.AccessTy, TLI, SE))
2110 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2111 if (InnerSum->isZero())
2114 F.BaseRegs[i] = InnerSum;
2115 F.BaseRegs.push_back(*J);
2116 if (InsertFormula(LU, LUIdx, F))
2117 // If that formula hadn't been seen before, recurse to find more like
2119 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2124 /// GenerateCombinations - Generate a formula consisting of all of the
2125 /// loop-dominating registers added into a single register.
2126 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
2128 // This method is only interesting on a plurality of registers.
2129 if (Base.BaseRegs.size() <= 1) return;
2133 SmallVector<const SCEV *, 4> Ops;
2134 for (SmallVectorImpl<const SCEV *>::const_iterator
2135 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2136 const SCEV *BaseReg = *I;
2137 if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2138 !BaseReg->hasComputableLoopEvolution(L))
2139 Ops.push_back(BaseReg);
2141 F.BaseRegs.push_back(BaseReg);
2143 if (Ops.size() > 1) {
2144 const SCEV *Sum = SE.getAddExpr(Ops);
2145 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2146 // opportunity to fold something. For now, just ignore such cases
2147 // rather than proceed with zero in a register.
2148 if (!Sum->isZero()) {
2149 F.BaseRegs.push_back(Sum);
2150 (void)InsertFormula(LU, LUIdx, F);
2155 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2156 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2158 // We can't add a symbolic offset if the address already contains one.
2159 if (Base.AM.BaseGV) return;
2161 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2162 const SCEV *G = Base.BaseRegs[i];
2163 GlobalValue *GV = ExtractSymbol(G, SE);
2164 if (G->isZero() || !GV)
2168 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2169 LU.Kind, LU.AccessTy, TLI))
2172 (void)InsertFormula(LU, LUIdx, F);
2176 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2177 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2179 // TODO: For now, just add the min and max offset, because it usually isn't
2180 // worthwhile looking at everything inbetween.
2181 SmallVector<int64_t, 4> Worklist;
2182 Worklist.push_back(LU.MinOffset);
2183 if (LU.MaxOffset != LU.MinOffset)
2184 Worklist.push_back(LU.MaxOffset);
2186 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2187 const SCEV *G = Base.BaseRegs[i];
2189 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2190 E = Worklist.end(); I != E; ++I) {
2192 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2193 if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2194 LU.Kind, LU.AccessTy, TLI)) {
2195 F.BaseRegs[i] = SE.getAddExpr(G, SE.getConstant(G->getType(), *I));
2197 (void)InsertFormula(LU, LUIdx, F);
2201 int64_t Imm = ExtractImmediate(G, SE);
2202 if (G->isZero() || Imm == 0)
2205 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2206 if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2207 LU.Kind, LU.AccessTy, TLI))
2210 (void)InsertFormula(LU, LUIdx, F);
2214 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2215 /// the comparison. For example, x == y -> x*c == y*c.
2216 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2218 if (LU.Kind != LSRUse::ICmpZero) return;
2220 // Determine the integer type for the base formula.
2221 const Type *IntTy = Base.getType();
2223 if (SE.getTypeSizeInBits(IntTy) > 64) return;
2225 // Don't do this if there is more than one offset.
2226 if (LU.MinOffset != LU.MaxOffset) return;
2228 assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2230 // Check each interesting stride.
2231 for (SmallSetVector<int64_t, 8>::const_iterator
2232 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2233 int64_t Factor = *I;
2236 // Check that the multiplication doesn't overflow.
2237 if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2239 F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2240 if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
2243 // Check that multiplying with the use offset doesn't overflow.
2244 int64_t Offset = LU.MinOffset;
2245 if (Offset == INT64_MIN && Factor == -1)
2247 Offset = (uint64_t)Offset * Factor;
2248 if (Offset / Factor != LU.MinOffset)
2251 // Check that this scale is legal.
2252 if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2255 // Compensate for the use having MinOffset built into it.
2256 F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2258 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2260 // Check that multiplying with each base register doesn't overflow.
2261 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2262 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
2263 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
2267 // Check that multiplying with the scaled register doesn't overflow.
2269 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
2270 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
2274 // If we make it here and it's legal, add it.
2275 (void)InsertFormula(LU, LUIdx, F);
2280 /// GenerateScales - Generate stride factor reuse formulae by making use of
2281 /// scaled-offset address modes, for example.
2282 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2284 // Determine the integer type for the base formula.
2285 const Type *IntTy = Base.getType();
2288 // If this Formula already has a scaled register, we can't add another one.
2289 if (Base.AM.Scale != 0) return;
2291 // Check each interesting stride.
2292 for (SmallSetVector<int64_t, 8>::const_iterator
2293 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2294 int64_t Factor = *I;
2296 Base.AM.Scale = Factor;
2297 Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2298 // Check whether this scale is going to be legal.
2299 if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2300 LU.Kind, LU.AccessTy, TLI)) {
2301 // As a special-case, handle special out-of-loop Basic users specially.
2302 // TODO: Reconsider this special case.
2303 if (LU.Kind == LSRUse::Basic &&
2304 isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2305 LSRUse::Special, LU.AccessTy, TLI) &&
2306 LU.AllFixupsOutsideLoop)
2307 LU.Kind = LSRUse::Special;
2311 // For an ICmpZero, negating a solitary base register won't lead to
2313 if (LU.Kind == LSRUse::ICmpZero &&
2314 !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2316 // For each addrec base reg, apply the scale, if possible.
2317 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2318 if (const SCEVAddRecExpr *AR =
2319 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2320 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2321 if (FactorS->isZero())
2323 // Divide out the factor, ignoring high bits, since we'll be
2324 // scaling the value back up in the end.
2325 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
2326 // TODO: This could be optimized to avoid all the copying.
2328 F.ScaledReg = Quotient;
2329 std::swap(F.BaseRegs[i], F.BaseRegs.back());
2330 F.BaseRegs.pop_back();
2331 (void)InsertFormula(LU, LUIdx, F);
2337 /// GenerateTruncates - Generate reuse formulae from different IV types.
2338 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2340 // This requires TargetLowering to tell us which truncates are free.
2343 // Don't bother truncating symbolic values.
2344 if (Base.AM.BaseGV) return;
2346 // Determine the integer type for the base formula.
2347 const Type *DstTy = Base.getType();
2349 DstTy = SE.getEffectiveSCEVType(DstTy);
2351 for (SmallSetVector<const Type *, 4>::const_iterator
2352 I = Types.begin(), E = Types.end(); I != E; ++I) {
2353 const Type *SrcTy = *I;
2354 if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2357 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2358 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2359 JE = F.BaseRegs.end(); J != JE; ++J)
2360 *J = SE.getAnyExtendExpr(*J, SrcTy);
2362 // TODO: This assumes we've done basic processing on all uses and
2363 // have an idea what the register usage is.
2364 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2367 (void)InsertFormula(LU, LUIdx, F);
2374 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
2375 /// defer modifications so that the search phase doesn't have to worry about
2376 /// the data structures moving underneath it.
2380 const SCEV *OrigReg;
2382 WorkItem(size_t LI, int64_t I, const SCEV *R)
2383 : LUIdx(LI), Imm(I), OrigReg(R) {}
2385 void print(raw_ostream &OS) const;
2391 void WorkItem::print(raw_ostream &OS) const {
2392 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2393 << " , add offset " << Imm;
2396 void WorkItem::dump() const {
2397 print(errs()); errs() << '\n';
2400 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2401 /// distance apart and try to form reuse opportunities between them.
2402 void LSRInstance::GenerateCrossUseConstantOffsets() {
2403 // Group the registers by their value without any added constant offset.
2404 typedef std::map<int64_t, const SCEV *> ImmMapTy;
2405 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2407 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2408 SmallVector<const SCEV *, 8> Sequence;
2409 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2411 const SCEV *Reg = *I;
2412 int64_t Imm = ExtractImmediate(Reg, SE);
2413 std::pair<RegMapTy::iterator, bool> Pair =
2414 Map.insert(std::make_pair(Reg, ImmMapTy()));
2416 Sequence.push_back(Reg);
2417 Pair.first->second.insert(std::make_pair(Imm, *I));
2418 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2421 // Now examine each set of registers with the same base value. Build up
2422 // a list of work to do and do the work in a separate step so that we're
2423 // not adding formulae and register counts while we're searching.
2424 SmallVector<WorkItem, 32> WorkItems;
2425 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2426 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2427 E = Sequence.end(); I != E; ++I) {
2428 const SCEV *Reg = *I;
2429 const ImmMapTy &Imms = Map.find(Reg)->second;
2431 // It's not worthwhile looking for reuse if there's only one offset.
2432 if (Imms.size() == 1)
2435 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2436 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2438 dbgs() << ' ' << J->first;
2441 // Examine each offset.
2442 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2444 const SCEV *OrigReg = J->second;
2446 int64_t JImm = J->first;
2447 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2449 if (!isa<SCEVConstant>(OrigReg) &&
2450 UsedByIndicesMap[Reg].count() == 1) {
2451 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2455 // Conservatively examine offsets between this orig reg a few selected
2457 ImmMapTy::const_iterator OtherImms[] = {
2458 Imms.begin(), prior(Imms.end()),
2459 Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2461 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2462 ImmMapTy::const_iterator M = OtherImms[i];
2463 if (M == J || M == JE) continue;
2465 // Compute the difference between the two.
2466 int64_t Imm = (uint64_t)JImm - M->first;
2467 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2468 LUIdx = UsedByIndices.find_next(LUIdx))
2469 // Make a memo of this use, offset, and register tuple.
2470 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2471 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
2478 UsedByIndicesMap.clear();
2479 UniqueItems.clear();
2481 // Now iterate through the worklist and add new formulae.
2482 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2483 E = WorkItems.end(); I != E; ++I) {
2484 const WorkItem &WI = *I;
2485 size_t LUIdx = WI.LUIdx;
2486 LSRUse &LU = Uses[LUIdx];
2487 int64_t Imm = WI.Imm;
2488 const SCEV *OrigReg = WI.OrigReg;
2490 const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2491 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2492 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2494 // TODO: Use a more targeted data structure.
2495 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2496 Formula F = LU.Formulae[L];
2497 // Use the immediate in the scaled register.
2498 if (F.ScaledReg == OrigReg) {
2499 int64_t Offs = (uint64_t)F.AM.BaseOffs +
2500 Imm * (uint64_t)F.AM.Scale;
2501 // Don't create 50 + reg(-50).
2502 if (F.referencesReg(SE.getSCEV(
2503 ConstantInt::get(IntTy, -(uint64_t)Offs))))
2506 NewF.AM.BaseOffs = Offs;
2507 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2508 LU.Kind, LU.AccessTy, TLI))
2510 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2512 // If the new scale is a constant in a register, and adding the constant
2513 // value to the immediate would produce a value closer to zero than the
2514 // immediate itself, then the formula isn't worthwhile.
2515 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2516 if (C->getValue()->getValue().isNegative() !=
2517 (NewF.AM.BaseOffs < 0) &&
2518 (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2519 .ule(abs64(NewF.AM.BaseOffs)))
2523 (void)InsertFormula(LU, LUIdx, NewF);
2525 // Use the immediate in a base register.
2526 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2527 const SCEV *BaseReg = F.BaseRegs[N];
2528 if (BaseReg != OrigReg)
2531 NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2532 if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2533 LU.Kind, LU.AccessTy, TLI))
2535 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2537 // If the new formula has a constant in a register, and adding the
2538 // constant value to the immediate would produce a value closer to
2539 // zero than the immediate itself, then the formula isn't worthwhile.
2540 for (SmallVectorImpl<const SCEV *>::const_iterator
2541 J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2543 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2544 if (C->getValue()->getValue().isNegative() !=
2545 (NewF.AM.BaseOffs < 0) &&
2546 C->getValue()->getValue().abs()
2547 .ule(abs64(NewF.AM.BaseOffs)))
2551 (void)InsertFormula(LU, LUIdx, NewF);
2560 /// GenerateAllReuseFormulae - Generate formulae for each use.
2562 LSRInstance::GenerateAllReuseFormulae() {
2563 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
2564 // queries are more precise.
2565 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2566 LSRUse &LU = Uses[LUIdx];
2567 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2568 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2569 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2570 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2572 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2573 LSRUse &LU = Uses[LUIdx];
2574 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2575 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2576 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2577 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2578 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2579 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2580 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2581 GenerateScales(LU, LUIdx, LU.Formulae[i]);
2583 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2584 LSRUse &LU = Uses[LUIdx];
2585 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2586 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2589 GenerateCrossUseConstantOffsets();
2592 /// If their are multiple formulae with the same set of registers used
2593 /// by other uses, pick the best one and delete the others.
2594 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2596 bool Changed = false;
2599 // Collect the best formula for each unique set of shared registers. This
2600 // is reset for each use.
2601 typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2603 BestFormulaeTy BestFormulae;
2605 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2606 LSRUse &LU = Uses[LUIdx];
2607 FormulaSorter Sorter(L, LU, SE, DT);
2608 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << "\n");
2610 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2611 FIdx != NumForms; ++FIdx) {
2612 Formula &F = LU.Formulae[FIdx];
2614 SmallVector<const SCEV *, 2> Key;
2615 for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2616 JE = F.BaseRegs.end(); J != JE; ++J) {
2617 const SCEV *Reg = *J;
2618 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2622 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2623 Key.push_back(F.ScaledReg);
2624 // Unstable sort by host order ok, because this is only used for
2626 std::sort(Key.begin(), Key.end());
2628 std::pair<BestFormulaeTy::const_iterator, bool> P =
2629 BestFormulae.insert(std::make_pair(Key, FIdx));
2631 Formula &Best = LU.Formulae[P.first->second];
2632 if (Sorter.operator()(F, Best))
2634 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
2636 " in favor of formula "; Best.print(dbgs());
2641 LU.DeleteFormula(F);
2648 // Now that we've filtered out some formulae, recompute the Regs set.
2650 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2651 FIdx != NumForms; ++FIdx) {
2652 Formula &F = LU.Formulae[FIdx];
2653 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2654 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2657 // Reset this to prepare for the next use.
2658 BestFormulae.clear();
2661 DEBUG(if (Changed) {
2663 "After filtering out undesirable candidates:\n";
2668 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
2669 /// formulae to choose from, use some rough heuristics to prune down the number
2670 /// of formulae. This keeps the main solver from taking an extraordinary amount
2671 /// of time in some worst-case scenarios.
2672 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2673 // This is a rough guess that seems to work fairly well.
2674 const size_t Limit = UINT16_MAX;
2676 SmallPtrSet<const SCEV *, 4> Taken;
2678 // Estimate the worst-case number of solutions we might consider. We almost
2679 // never consider this many solutions because we prune the search space,
2680 // but the pruning isn't always sufficient.
2682 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2683 E = Uses.end(); I != E; ++I) {
2684 size_t FSize = I->Formulae.size();
2685 if (FSize >= Limit) {
2696 // Ok, we have too many of formulae on our hands to conveniently handle.
2697 // Use a rough heuristic to thin out the list.
2699 // Pick the register which is used by the most LSRUses, which is likely
2700 // to be a good reuse register candidate.
2701 const SCEV *Best = 0;
2702 unsigned BestNum = 0;
2703 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2705 const SCEV *Reg = *I;
2706 if (Taken.count(Reg))
2711 unsigned Count = RegUses.getUsedByIndices(Reg).count();
2712 if (Count > BestNum) {
2719 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
2720 << " will yield profitable reuse.\n");
2723 // In any use with formulae which references this register, delete formulae
2724 // which don't reference it.
2725 for (SmallVectorImpl<LSRUse>::iterator I = Uses.begin(),
2726 E = Uses.end(); I != E; ++I) {
2728 if (!LU.Regs.count(Best)) continue;
2730 // Clear out the set of used regs; it will be recomputed.
2733 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2734 Formula &F = LU.Formulae[i];
2735 if (!F.referencesReg(Best)) {
2736 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
2737 LU.DeleteFormula(F);
2740 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
2744 if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2745 LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2749 DEBUG(dbgs() << "After pre-selection:\n";
2750 print_uses(dbgs()));
2754 /// SolveRecurse - This is the recursive solver.
2755 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2757 SmallVectorImpl<const Formula *> &Workspace,
2758 const Cost &CurCost,
2759 const SmallPtrSet<const SCEV *, 16> &CurRegs,
2760 DenseSet<const SCEV *> &VisitedRegs) const {
2763 // - use more aggressive filtering
2764 // - sort the formula so that the most profitable solutions are found first
2765 // - sort the uses too
2767 // - don't compute a cost, and then compare. compare while computing a cost
2769 // - track register sets with SmallBitVector
2771 const LSRUse &LU = Uses[Workspace.size()];
2773 // If this use references any register that's already a part of the
2774 // in-progress solution, consider it a requirement that a formula must
2775 // reference that register in order to be considered. This prunes out
2776 // unprofitable searching.
2777 SmallSetVector<const SCEV *, 4> ReqRegs;
2778 for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2779 E = CurRegs.end(); I != E; ++I)
2780 if (LU.Regs.count(*I))
2783 bool AnySatisfiedReqRegs = false;
2784 SmallPtrSet<const SCEV *, 16> NewRegs;
2787 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2788 E = LU.Formulae.end(); I != E; ++I) {
2789 const Formula &F = *I;
2791 // Ignore formulae which do not use any of the required registers.
2792 for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2793 JE = ReqRegs.end(); J != JE; ++J) {
2794 const SCEV *Reg = *J;
2795 if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2796 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2800 AnySatisfiedReqRegs = true;
2802 // Evaluate the cost of the current formula. If it's already worse than
2803 // the current best, prune the search at that point.
2806 NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2807 if (NewCost < SolutionCost) {
2808 Workspace.push_back(&F);
2809 if (Workspace.size() != Uses.size()) {
2810 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2811 NewRegs, VisitedRegs);
2812 if (F.getNumRegs() == 1 && Workspace.size() == 1)
2813 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2815 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2816 dbgs() << ". Regs:";
2817 for (SmallPtrSet<const SCEV *, 16>::const_iterator
2818 I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2819 dbgs() << ' ' << **I;
2822 SolutionCost = NewCost;
2823 Solution = Workspace;
2825 Workspace.pop_back();
2830 // If none of the formulae had all of the required registers, relax the
2831 // constraint so that we don't exclude all formulae.
2832 if (!AnySatisfiedReqRegs) {
2833 assert(!ReqRegs.empty() && "Solver failed even without required registers");
2839 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2840 SmallVector<const Formula *, 8> Workspace;
2842 SolutionCost.Loose();
2844 SmallPtrSet<const SCEV *, 16> CurRegs;
2845 DenseSet<const SCEV *> VisitedRegs;
2846 Workspace.reserve(Uses.size());
2848 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2849 CurRegs, VisitedRegs);
2851 // Ok, we've now made all our decisions.
2852 DEBUG(dbgs() << "\n"
2853 "The chosen solution requires "; SolutionCost.print(dbgs());
2855 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2857 Uses[i].print(dbgs());
2860 Solution[i]->print(dbgs());
2865 /// getImmediateDominator - A handy utility for the specific DominatorTree
2866 /// query that we need here.
2868 static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2869 DomTreeNode *Node = DT.getNode(BB);
2870 if (!Node) return 0;
2871 Node = Node->getIDom();
2872 if (!Node) return 0;
2873 return Node->getBlock();
2876 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
2877 /// the dominator tree far as we can go while still being dominated by the
2878 /// input positions. This helps canonicalize the insert position, which
2879 /// encourages sharing.
2880 BasicBlock::iterator
2881 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
2882 const SmallVectorImpl<Instruction *> &Inputs)
2885 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
2886 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
2889 for (BasicBlock *Rung = IP->getParent(); ; Rung = IDom) {
2890 IDom = getImmediateDominator(Rung, DT);
2891 if (!IDom) return IP;
2893 // Don't climb into a loop though.
2894 const Loop *IDomLoop = LI.getLoopFor(IDom);
2895 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
2896 if (IDomDepth <= IPLoopDepth &&
2897 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
2901 bool AllDominate = true;
2902 Instruction *BetterPos = 0;
2903 Instruction *Tentative = IDom->getTerminator();
2904 for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2905 E = Inputs.end(); I != E; ++I) {
2906 Instruction *Inst = *I;
2907 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2908 AllDominate = false;
2911 // Attempt to find an insert position in the middle of the block,
2912 // instead of at the end, so that it can be used for other expansions.
2913 if (IDom == Inst->getParent() &&
2914 (!BetterPos || DT.dominates(BetterPos, Inst)))
2915 BetterPos = llvm::next(BasicBlock::iterator(Inst));
2928 /// AdjustInsertPositionForExpand - Determine an input position which will be
2929 /// dominated by the operands and which will dominate the result.
2930 BasicBlock::iterator
2931 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2933 const LSRUse &LU) const {
2934 // Collect some instructions which must be dominated by the
2935 // expanding replacement. These must be dominated by any operands that
2936 // will be required in the expansion.
2937 SmallVector<Instruction *, 4> Inputs;
2938 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2939 Inputs.push_back(I);
2940 if (LU.Kind == LSRUse::ICmpZero)
2941 if (Instruction *I =
2942 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2943 Inputs.push_back(I);
2944 if (LF.PostIncLoops.count(L)) {
2945 if (LF.isUseFullyOutsideLoop(L))
2946 Inputs.push_back(L->getLoopLatch()->getTerminator());
2948 Inputs.push_back(IVIncInsertPos);
2950 // The expansion must also be dominated by the increment positions of any
2951 // loops it for which it is using post-inc mode.
2952 for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
2953 E = LF.PostIncLoops.end(); I != E; ++I) {
2954 const Loop *PIL = *I;
2955 if (PIL == L) continue;
2957 // Be dominated by the loop exit.
2958 SmallVector<BasicBlock *, 4> ExitingBlocks;
2959 PIL->getExitingBlocks(ExitingBlocks);
2960 if (!ExitingBlocks.empty()) {
2961 BasicBlock *BB = ExitingBlocks[0];
2962 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
2963 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
2964 Inputs.push_back(BB->getTerminator());
2968 // Then, climb up the immediate dominator tree as far as we can go while
2969 // still being dominated by the input positions.
2970 IP = HoistInsertPosition(IP, Inputs);
2972 // Don't insert instructions before PHI nodes.
2973 while (isa<PHINode>(IP)) ++IP;
2975 // Ignore debug intrinsics.
2976 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
2981 Value *LSRInstance::Expand(const LSRFixup &LF,
2983 BasicBlock::iterator IP,
2984 SCEVExpander &Rewriter,
2985 SmallVectorImpl<WeakVH> &DeadInsts) const {
2986 const LSRUse &LU = Uses[LF.LUIdx];
2988 // Determine an input position which will be dominated by the operands and
2989 // which will dominate the result.
2990 IP = AdjustInsertPositionForExpand(IP, LF, LU);
2992 // Inform the Rewriter if we have a post-increment use, so that it can
2993 // perform an advantageous expansion.
2994 Rewriter.setPostInc(LF.PostIncLoops);
2996 // This is the type that the user actually needs.
2997 const Type *OpTy = LF.OperandValToReplace->getType();
2998 // This will be the type that we'll initially expand to.
2999 const Type *Ty = F.getType();
3001 // No type known; just expand directly to the ultimate type.
3003 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3004 // Expand directly to the ultimate type if it's the right size.
3006 // This is the type to do integer arithmetic in.
3007 const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3009 // Build up a list of operands to add together to form the full base.
3010 SmallVector<const SCEV *, 8> Ops;
3012 // Expand the BaseRegs portion.
3013 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3014 E = F.BaseRegs.end(); I != E; ++I) {
3015 const SCEV *Reg = *I;
3016 assert(!Reg->isZero() && "Zero allocated in a base register!");
3018 // If we're expanding for a post-inc user, make the post-inc adjustment.
3019 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3020 Reg = TransformForPostIncUse(Denormalize, Reg,
3021 LF.UserInst, LF.OperandValToReplace,
3024 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3027 // Flush the operand list to suppress SCEVExpander hoisting.
3029 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3031 Ops.push_back(SE.getUnknown(FullV));
3034 // Expand the ScaledReg portion.
3035 Value *ICmpScaledV = 0;
3036 if (F.AM.Scale != 0) {
3037 const SCEV *ScaledS = F.ScaledReg;
3039 // If we're expanding for a post-inc user, make the post-inc adjustment.
3040 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3041 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3042 LF.UserInst, LF.OperandValToReplace,
3045 if (LU.Kind == LSRUse::ICmpZero) {
3046 // An interesting way of "folding" with an icmp is to use a negated
3047 // scale, which we'll implement by inserting it into the other operand
3049 assert(F.AM.Scale == -1 &&
3050 "The only scale supported by ICmpZero uses is -1!");
3051 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3053 // Otherwise just expand the scaled register and an explicit scale,
3054 // which is expected to be matched as part of the address.
3055 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3056 ScaledS = SE.getMulExpr(ScaledS,
3057 SE.getConstant(ScaledS->getType(), F.AM.Scale));
3058 Ops.push_back(ScaledS);
3060 // Flush the operand list to suppress SCEVExpander hoisting.
3061 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3063 Ops.push_back(SE.getUnknown(FullV));
3067 // Expand the GV portion.
3069 Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3071 // Flush the operand list to suppress SCEVExpander hoisting.
3072 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3074 Ops.push_back(SE.getUnknown(FullV));
3077 // Expand the immediate portion.
3078 int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3080 if (LU.Kind == LSRUse::ICmpZero) {
3081 // The other interesting way of "folding" with an ICmpZero is to use a
3082 // negated immediate.
3084 ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3086 Ops.push_back(SE.getUnknown(ICmpScaledV));
3087 ICmpScaledV = ConstantInt::get(IntTy, Offset);
3090 // Just add the immediate values. These again are expected to be matched
3091 // as part of the address.
3092 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
3096 // Emit instructions summing all the operands.
3097 const SCEV *FullS = Ops.empty() ?
3098 SE.getConstant(IntTy, 0) :
3100 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3102 // We're done expanding now, so reset the rewriter.
3103 Rewriter.clearPostInc();
3105 // An ICmpZero Formula represents an ICmp which we're handling as a
3106 // comparison against zero. Now that we've expanded an expression for that
3107 // form, update the ICmp's other operand.
3108 if (LU.Kind == LSRUse::ICmpZero) {
3109 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3110 DeadInsts.push_back(CI->getOperand(1));
3111 assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3112 "a scale at the same time!");
3113 if (F.AM.Scale == -1) {
3114 if (ICmpScaledV->getType() != OpTy) {
3116 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3118 ICmpScaledV, OpTy, "tmp", CI);
3121 CI->setOperand(1, ICmpScaledV);
3123 assert(F.AM.Scale == 0 &&
3124 "ICmp does not support folding a global value and "
3125 "a scale at the same time!");
3126 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3128 if (C->getType() != OpTy)
3129 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3133 CI->setOperand(1, C);
3140 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3141 /// of their operands effectively happens in their predecessor blocks, so the
3142 /// expression may need to be expanded in multiple places.
3143 void LSRInstance::RewriteForPHI(PHINode *PN,
3146 SCEVExpander &Rewriter,
3147 SmallVectorImpl<WeakVH> &DeadInsts,
3149 DenseMap<BasicBlock *, Value *> Inserted;
3150 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3151 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3152 BasicBlock *BB = PN->getIncomingBlock(i);
3154 // If this is a critical edge, split the edge so that we do not insert
3155 // the code on all predecessor/successor paths. We do this unless this
3156 // is the canonical backedge for this loop, which complicates post-inc
3158 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3159 !isa<IndirectBrInst>(BB->getTerminator()) &&
3160 (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3161 // Split the critical edge.
3162 BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3164 // If PN is outside of the loop and BB is in the loop, we want to
3165 // move the block to be immediately before the PHI block, not
3166 // immediately after BB.
3167 if (L->contains(BB) && !L->contains(PN))
3168 NewBB->moveBefore(PN->getParent());
3170 // Splitting the edge can reduce the number of PHI entries we have.
3171 e = PN->getNumIncomingValues();
3173 i = PN->getBasicBlockIndex(BB);
3176 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3177 Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3179 PN->setIncomingValue(i, Pair.first->second);
3181 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
3183 // If this is reuse-by-noop-cast, insert the noop cast.
3184 const Type *OpTy = LF.OperandValToReplace->getType();
3185 if (FullV->getType() != OpTy)
3187 CastInst::Create(CastInst::getCastOpcode(FullV, false,
3189 FullV, LF.OperandValToReplace->getType(),
3190 "tmp", BB->getTerminator());
3192 PN->setIncomingValue(i, FullV);
3193 Pair.first->second = FullV;
3198 /// Rewrite - Emit instructions for the leading candidate expression for this
3199 /// LSRUse (this is called "expanding"), and update the UserInst to reference
3200 /// the newly expanded value.
3201 void LSRInstance::Rewrite(const LSRFixup &LF,
3203 SCEVExpander &Rewriter,
3204 SmallVectorImpl<WeakVH> &DeadInsts,
3206 // First, find an insertion point that dominates UserInst. For PHI nodes,
3207 // find the nearest block which dominates all the relevant uses.
3208 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
3209 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
3211 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
3213 // If this is reuse-by-noop-cast, insert the noop cast.
3214 const Type *OpTy = LF.OperandValToReplace->getType();
3215 if (FullV->getType() != OpTy) {
3217 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3218 FullV, OpTy, "tmp", LF.UserInst);
3222 // Update the user. ICmpZero is handled specially here (for now) because
3223 // Expand may have updated one of the operands of the icmp already, and
3224 // its new value may happen to be equal to LF.OperandValToReplace, in
3225 // which case doing replaceUsesOfWith leads to replacing both operands
3226 // with the same value. TODO: Reorganize this.
3227 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3228 LF.UserInst->setOperand(0, FullV);
3230 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3233 DeadInsts.push_back(LF.OperandValToReplace);
3237 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3239 // Keep track of instructions we may have made dead, so that
3240 // we can remove them after we are done working.
3241 SmallVector<WeakVH, 16> DeadInsts;
3243 SCEVExpander Rewriter(SE);
3244 Rewriter.disableCanonicalMode();
3245 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3247 // Expand the new value definitions and update the users.
3248 for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3249 size_t LUIdx = Fixups[i].LUIdx;
3251 Rewrite(Fixups[i], *Solution[LUIdx], Rewriter, DeadInsts, P);
3256 // Clean up after ourselves. This must be done before deleting any
3260 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3263 LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3264 : IU(P->getAnalysis<IVUsers>()),
3265 SE(P->getAnalysis<ScalarEvolution>()),
3266 DT(P->getAnalysis<DominatorTree>()),
3267 LI(P->getAnalysis<LoopInfo>()),
3268 TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
3270 // If LoopSimplify form is not available, stay out of trouble.
3271 if (!L->isLoopSimplifyForm()) return;
3273 // If there's no interesting work to be done, bail early.
3274 if (IU.empty()) return;
3276 DEBUG(dbgs() << "\nLSR on loop ";
3277 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3280 /// OptimizeShadowIV - If IV is used in a int-to-float cast
3281 /// inside the loop then try to eliminate the cast operation.
3284 // Change loop terminating condition to use the postinc iv when possible.
3285 Changed |= OptimizeLoopTermCond();
3287 CollectInterestingTypesAndFactors();
3288 CollectFixupsAndInitialFormulae();
3289 CollectLoopInvariantFixupsAndFormulae();
3291 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3292 print_uses(dbgs()));
3294 // Now use the reuse data to generate a bunch of interesting ways
3295 // to formulate the values needed for the uses.
3296 GenerateAllReuseFormulae();
3298 DEBUG(dbgs() << "\n"
3299 "After generating reuse formulae:\n";
3300 print_uses(dbgs()));
3302 FilterOutUndesirableDedicatedRegisters();
3303 NarrowSearchSpaceUsingHeuristics();
3305 SmallVector<const Formula *, 8> Solution;
3307 assert(Solution.size() == Uses.size() && "Malformed solution!");
3309 // Release memory that is no longer needed.
3315 // Formulae should be legal.
3316 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3317 E = Uses.end(); I != E; ++I) {
3318 const LSRUse &LU = *I;
3319 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3320 JE = LU.Formulae.end(); J != JE; ++J)
3321 assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3322 LU.Kind, LU.AccessTy, TLI) &&
3323 "Illegal formula generated!");
3327 // Now that we've decided what we want, make it so.
3328 ImplementSolution(Solution, P);
3331 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3332 if (Factors.empty() && Types.empty()) return;
3334 OS << "LSR has identified the following interesting factors and types: ";
3337 for (SmallSetVector<int64_t, 8>::const_iterator
3338 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3339 if (!First) OS << ", ";
3344 for (SmallSetVector<const Type *, 4>::const_iterator
3345 I = Types.begin(), E = Types.end(); I != E; ++I) {
3346 if (!First) OS << ", ";
3348 OS << '(' << **I << ')';
3353 void LSRInstance::print_fixups(raw_ostream &OS) const {
3354 OS << "LSR is examining the following fixup sites:\n";
3355 for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3356 E = Fixups.end(); I != E; ++I) {
3357 const LSRFixup &LF = *I;
3364 void LSRInstance::print_uses(raw_ostream &OS) const {
3365 OS << "LSR is examining the following uses:\n";
3366 for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3367 E = Uses.end(); I != E; ++I) {
3368 const LSRUse &LU = *I;
3372 for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3373 JE = LU.Formulae.end(); J != JE; ++J) {
3381 void LSRInstance::print(raw_ostream &OS) const {
3382 print_factors_and_types(OS);
3387 void LSRInstance::dump() const {
3388 print(errs()); errs() << '\n';
3393 class LoopStrengthReduce : public LoopPass {
3394 /// TLI - Keep a pointer of a TargetLowering to consult for determining
3395 /// transformation profitability.
3396 const TargetLowering *const TLI;
3399 static char ID; // Pass ID, replacement for typeid
3400 explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3403 bool runOnLoop(Loop *L, LPPassManager &LPM);
3404 void getAnalysisUsage(AnalysisUsage &AU) const;
3409 char LoopStrengthReduce::ID = 0;
3410 static RegisterPass<LoopStrengthReduce>
3411 X("loop-reduce", "Loop Strength Reduction");
3413 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3414 return new LoopStrengthReduce(TLI);
3417 LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3418 : LoopPass(&ID), TLI(tli) {}
3420 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3421 // We split critical edges, so we change the CFG. However, we do update
3422 // many analyses if they are around.
3423 AU.addPreservedID(LoopSimplifyID);
3424 AU.addPreserved("domfrontier");
3426 AU.addRequired<LoopInfo>();
3427 AU.addPreserved<LoopInfo>();
3428 AU.addRequiredID(LoopSimplifyID);
3429 AU.addRequired<DominatorTree>();
3430 AU.addPreserved<DominatorTree>();
3431 AU.addRequired<ScalarEvolution>();
3432 AU.addPreserved<ScalarEvolution>();
3433 AU.addRequired<IVUsers>();
3434 AU.addPreserved<IVUsers>();
3437 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3438 bool Changed = false;
3440 // Run the main LSR transformation.
3441 Changed |= LSRInstance(TLI, L, this).getChanged();
3443 // At this point, it is worth checking to see if any recurrence PHIs are also
3444 // dead, so that we can remove them as well.
3445 Changed |= DeleteDeadPHIs(L->getHeader());