Remove the Expr member from IVUsers. Instead of remembering the expression,
[oota-llvm.git] / lib / Transforms / Scalar / LoopStrengthReduce.cpp
1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into forms suitable for efficient execution
12 // on the target.
13 //
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.
19 //
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:
23 //
24 //   %i = phi [ 0, %entry ], [ %i.next, %latch ]
25 //   ...
26 //   %i.next = add %i, 1
27 //   %c = icmp eq %i.next, %n
28 //
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.
35 //
36 // TODO: More sophistication in the way Formulae are generated and filtered.
37 //
38 // TODO: Handle multiple loops at a time.
39 //
40 // TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
41 //       instead of a GlobalValue?
42 //
43 // TODO: When truncation is free, truncate ICmp users' operands to make it a
44 //       smaller encoding (on x86 at least).
45 //
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"
52 //       use kind.
53 //
54 //===----------------------------------------------------------------------===//
55
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"
75 #include <algorithm>
76 using namespace llvm;
77
78 namespace {
79
80 /// RegSortData - This class holds data which is used to order reuse candidates.
81 class RegSortData {
82 public:
83   /// UsedByIndices - This represents the set of LSRUse indices which reference
84   /// a particular register.
85   SmallBitVector UsedByIndices;
86
87   RegSortData() {}
88
89   void print(raw_ostream &OS) const;
90   void dump() const;
91 };
92
93 }
94
95 void RegSortData::print(raw_ostream &OS) const {
96   OS << "[NumUses=" << UsedByIndices.count() << ']';
97 }
98
99 void RegSortData::dump() const {
100   print(errs()); errs() << '\n';
101 }
102
103 namespace {
104
105 /// RegUseTracker - Map register candidates to information about how they are
106 /// used.
107 class RegUseTracker {
108   typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
109
110   RegUsesTy RegUses;
111   SmallVector<const SCEV *, 16> RegSequence;
112
113 public:
114   void CountRegister(const SCEV *Reg, size_t LUIdx);
115
116   bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
117
118   const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
119
120   void clear();
121
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(); }
128 };
129
130 }
131
132 void
133 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
134   std::pair<RegUsesTy::iterator, bool> Pair =
135     RegUses.insert(std::make_pair(Reg, RegSortData()));
136   RegSortData &RSD = Pair.first->second;
137   if (Pair.second)
138     RegSequence.push_back(Reg);
139   RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
140   RSD.UsedByIndices.set(LUIdx);
141 }
142
143 bool
144 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
145   if (!RegUses.count(Reg)) return false;
146   const SmallBitVector &UsedByIndices =
147     RegUses.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;
152 }
153
154 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
155   RegUsesTy::const_iterator I = RegUses.find(Reg);
156   assert(I != RegUses.end() && "Unknown register!");
157   return I->second.UsedByIndices;
158 }
159
160 void RegUseTracker::clear() {
161   RegUses.clear();
162   RegSequence.clear();
163 }
164
165 namespace {
166
167 /// Formula - This class holds information that describes a formula for
168 /// computing satisfying a use. It may include broken-out immediates and scaled
169 /// registers.
170 struct Formula {
171   /// AM - This is used to represent complex addressing, as well as other kinds
172   /// of interesting uses.
173   TargetLowering::AddrMode AM;
174
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;
178
179   /// ScaledReg - The 'scaled' register for this use. This should be non-null
180   /// when AM.Scale is not zero.
181   const SCEV *ScaledReg;
182
183   Formula() : ScaledReg(0) {}
184
185   void InitialMatch(const SCEV *S, Loop *L,
186                     ScalarEvolution &SE, DominatorTree &DT);
187
188   unsigned getNumRegs() const;
189   const Type *getType() const;
190
191   bool referencesReg(const SCEV *S) const;
192   bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
193                                   const RegUseTracker &RegUses) const;
194
195   void print(raw_ostream &OS) const;
196   void dump() const;
197 };
198
199 }
200
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)) {
208     Good.push_back(S);
209     return;
210   }
211
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();
215          I != E; ++I)
216       DoInitialMatch(*I, L, Good, Bad, SE, DT);
217     return;
218   }
219
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.getIntegerSCEV(0, AR->getType()),
225                                       AR->getStepRecurrence(SE),
226                                       AR->getLoop()),
227                      L, Good, Bad, SE, DT);
228       return;
229     }
230
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);
236
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));
248       return;
249     }
250
251   // Ok, we can't do anything interesting. Just stuff the whole thing into a
252   // register and hope for the best.
253   Bad.push_back(S);
254 }
255
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);
264   if (!Good.empty()) {
265     const SCEV *Sum = SE.getAddExpr(Good);
266     if (!Sum->isZero())
267       BaseRegs.push_back(Sum);
268     AM.HasBaseReg = true;
269   }
270   if (!Bad.empty()) {
271     const SCEV *Sum = SE.getAddExpr(Bad);
272     if (!Sum->isZero())
273       BaseRegs.push_back(Sum);
274     AM.HasBaseReg = true;
275   }
276 }
277
278 /// getNumRegs - Return the total number of register operands used by this
279 /// formula. This does not include register uses implied by non-constant
280 /// addrec strides.
281 unsigned Formula::getNumRegs() const {
282   return !!ScaledReg + BaseRegs.size();
283 }
284
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() :
291          0;
292 }
293
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();
298 }
299
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 {
304   if (ScaledReg)
305     if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
306       return true;
307   for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
308        E = BaseRegs.end(); I != E; ++I)
309     if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
310       return true;
311   return false;
312 }
313
314 void Formula::print(raw_ostream &OS) const {
315   bool First = true;
316   if (AM.BaseGV) {
317     if (!First) OS << " + "; else First = false;
318     WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
319   }
320   if (AM.BaseOffs != 0) {
321     if (!First) OS << " + "; else First = false;
322     OS << AM.BaseOffs;
323   }
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 << ')';
328   }
329   if (AM.Scale != 0) {
330     if (!First) OS << " + "; else First = false;
331     OS << AM.Scale << "*reg(";
332     if (ScaledReg)
333       OS << *ScaledReg;
334     else
335       OS << "<unknown>";
336     OS << ')';
337   }
338 }
339
340 void Formula::dump() const {
341   print(errs()); errs() << '\n';
342 }
343
344 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
345 /// without changing its value.
346 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
347   const Type *WideTy =
348     IntegerType::get(SE.getContext(),
349                      SE.getTypeSizeInBits(AR->getType()) + 1);
350   return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
351 }
352
353 /// isAddSExtable - Return true if the given add can be sign-extended
354 /// without changing its value.
355 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
356   const Type *WideTy =
357     IntegerType::get(SE.getContext(),
358                      SE.getTypeSizeInBits(A->getType()) + 1);
359   return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
360 }
361
362 /// isMulSExtable - Return true if the given add can be sign-extended
363 /// without changing its value.
364 static bool isMulSExtable(const SCEVMulExpr *A, ScalarEvolution &SE) {
365   const Type *WideTy =
366     IntegerType::get(SE.getContext(),
367                      SE.getTypeSizeInBits(A->getType()) + 1);
368   return isa<SCEVMulExpr>(SE.getSignExtendExpr(A, WideTy));
369 }
370
371 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
372 /// and if the remainder is known to be zero,  or null otherwise. If
373 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
374 /// to Y, ignoring that the multiplication may overflow, which is useful when
375 /// the result will be used in a context where the most significant bits are
376 /// ignored.
377 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
378                                 ScalarEvolution &SE,
379                                 bool IgnoreSignificantBits = false) {
380   // Handle the trivial case, which works for any SCEV type.
381   if (LHS == RHS)
382     return SE.getIntegerSCEV(1, LHS->getType());
383
384   // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do some
385   // folding.
386   if (RHS->isAllOnesValue())
387     return SE.getMulExpr(LHS, RHS);
388
389   // Check for a division of a constant by a constant.
390   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
391     const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
392     if (!RC)
393       return 0;
394     if (C->getValue()->getValue().srem(RC->getValue()->getValue()) != 0)
395       return 0;
396     return SE.getConstant(C->getValue()->getValue()
397                .sdiv(RC->getValue()->getValue()));
398   }
399
400   // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
401   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
402     if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
403       const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
404                                        IgnoreSignificantBits);
405       if (!Start) return 0;
406       const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
407                                       IgnoreSignificantBits);
408       if (!Step) return 0;
409       return SE.getAddRecExpr(Start, Step, AR->getLoop());
410     }
411   }
412
413   // Distribute the sdiv over add operands, if the add doesn't overflow.
414   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
415     if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
416       SmallVector<const SCEV *, 8> Ops;
417       for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
418            I != E; ++I) {
419         const SCEV *Op = getExactSDiv(*I, RHS, SE,
420                                       IgnoreSignificantBits);
421         if (!Op) return 0;
422         Ops.push_back(Op);
423       }
424       return SE.getAddExpr(Ops);
425     }
426   }
427
428   // Check for a multiply operand that we can pull RHS out of.
429   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS))
430     if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
431       SmallVector<const SCEV *, 4> Ops;
432       bool Found = false;
433       for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
434            I != E; ++I) {
435         if (!Found)
436           if (const SCEV *Q = getExactSDiv(*I, RHS, SE,
437                                            IgnoreSignificantBits)) {
438             Ops.push_back(Q);
439             Found = true;
440             continue;
441           }
442         Ops.push_back(*I);
443       }
444       return Found ? SE.getMulExpr(Ops) : 0;
445     }
446
447   // Otherwise we don't know.
448   return 0;
449 }
450
451 /// ExtractImmediate - If S involves the addition of a constant integer value,
452 /// return that integer value, and mutate S to point to a new SCEV with that
453 /// value excluded.
454 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
455   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
456     if (C->getValue()->getValue().getMinSignedBits() <= 64) {
457       S = SE.getIntegerSCEV(0, C->getType());
458       return C->getValue()->getSExtValue();
459     }
460   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
461     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
462     int64_t Result = ExtractImmediate(NewOps.front(), SE);
463     S = SE.getAddExpr(NewOps);
464     return Result;
465   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
466     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
467     int64_t Result = ExtractImmediate(NewOps.front(), SE);
468     S = SE.getAddRecExpr(NewOps, AR->getLoop());
469     return Result;
470   }
471   return 0;
472 }
473
474 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
475 /// return that symbol, and mutate S to point to a new SCEV with that
476 /// value excluded.
477 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
478   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
479     if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
480       S = SE.getIntegerSCEV(0, GV->getType());
481       return GV;
482     }
483   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
484     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
485     GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
486     S = SE.getAddExpr(NewOps);
487     return Result;
488   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
489     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
490     GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
491     S = SE.getAddRecExpr(NewOps, AR->getLoop());
492     return Result;
493   }
494   return 0;
495 }
496
497 /// isAddressUse - Returns true if the specified instruction is using the
498 /// specified value as an address.
499 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
500   bool isAddress = isa<LoadInst>(Inst);
501   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
502     if (SI->getOperand(1) == OperandVal)
503       isAddress = true;
504   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
505     // Addressing modes can also be folded into prefetches and a variety
506     // of intrinsics.
507     switch (II->getIntrinsicID()) {
508       default: break;
509       case Intrinsic::prefetch:
510       case Intrinsic::x86_sse2_loadu_dq:
511       case Intrinsic::x86_sse2_loadu_pd:
512       case Intrinsic::x86_sse_loadu_ps:
513       case Intrinsic::x86_sse_storeu_ps:
514       case Intrinsic::x86_sse2_storeu_pd:
515       case Intrinsic::x86_sse2_storeu_dq:
516       case Intrinsic::x86_sse2_storel_dq:
517         if (II->getOperand(1) == OperandVal)
518           isAddress = true;
519         break;
520     }
521   }
522   return isAddress;
523 }
524
525 /// getAccessType - Return the type of the memory being accessed.
526 static const Type *getAccessType(const Instruction *Inst) {
527   const Type *AccessTy = Inst->getType();
528   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
529     AccessTy = SI->getOperand(0)->getType();
530   else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
531     // Addressing modes can also be folded into prefetches and a variety
532     // of intrinsics.
533     switch (II->getIntrinsicID()) {
534     default: break;
535     case Intrinsic::x86_sse_storeu_ps:
536     case Intrinsic::x86_sse2_storeu_pd:
537     case Intrinsic::x86_sse2_storeu_dq:
538     case Intrinsic::x86_sse2_storel_dq:
539       AccessTy = II->getOperand(1)->getType();
540       break;
541     }
542   }
543
544   // All pointers have the same requirements, so canonicalize them to an
545   // arbitrary pointer type to minimize variation.
546   if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
547     AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
548                                 PTy->getAddressSpace());
549
550   return AccessTy;
551 }
552
553 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
554 /// specified set are trivially dead, delete them and see if this makes any of
555 /// their operands subsequently dead.
556 static bool
557 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
558   bool Changed = false;
559
560   while (!DeadInsts.empty()) {
561     Instruction *I = dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val());
562
563     if (I == 0 || !isInstructionTriviallyDead(I))
564       continue;
565
566     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
567       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
568         *OI = 0;
569         if (U->use_empty())
570           DeadInsts.push_back(U);
571       }
572
573     I->eraseFromParent();
574     Changed = true;
575   }
576
577   return Changed;
578 }
579
580 namespace {
581
582 /// Cost - This class is used to measure and compare candidate formulae.
583 class Cost {
584   /// TODO: Some of these could be merged. Also, a lexical ordering
585   /// isn't always optimal.
586   unsigned NumRegs;
587   unsigned AddRecCost;
588   unsigned NumIVMuls;
589   unsigned NumBaseAdds;
590   unsigned ImmCost;
591   unsigned SetupCost;
592
593 public:
594   Cost()
595     : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
596       SetupCost(0) {}
597
598   unsigned getNumRegs() const { return NumRegs; }
599
600   bool operator<(const Cost &Other) const;
601
602   void Loose();
603
604   void RateFormula(const Formula &F,
605                    SmallPtrSet<const SCEV *, 16> &Regs,
606                    const DenseSet<const SCEV *> &VisitedRegs,
607                    const Loop *L,
608                    const SmallVectorImpl<int64_t> &Offsets,
609                    ScalarEvolution &SE, DominatorTree &DT);
610
611   void print(raw_ostream &OS) const;
612   void dump() const;
613
614 private:
615   void RateRegister(const SCEV *Reg,
616                     SmallPtrSet<const SCEV *, 16> &Regs,
617                     const Loop *L,
618                     ScalarEvolution &SE, DominatorTree &DT);
619   void RatePrimaryRegister(const SCEV *Reg,
620                            SmallPtrSet<const SCEV *, 16> &Regs,
621                            const Loop *L,
622                            ScalarEvolution &SE, DominatorTree &DT);
623 };
624
625 }
626
627 /// RateRegister - Tally up interesting quantities from the given register.
628 void Cost::RateRegister(const SCEV *Reg,
629                         SmallPtrSet<const SCEV *, 16> &Regs,
630                         const Loop *L,
631                         ScalarEvolution &SE, DominatorTree &DT) {
632   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
633     if (AR->getLoop() == L)
634       AddRecCost += 1; /// TODO: This should be a function of the stride.
635
636     // If this is an addrec for a loop that's already been visited by LSR,
637     // don't second-guess its addrec phi nodes. LSR isn't currently smart
638     // enough to reason about more than one loop at a time. Consider these
639     // registers free and leave them alone.
640     else if (L->contains(AR->getLoop()) ||
641              (!AR->getLoop()->contains(L) &&
642               DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
643       for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
644            PHINode *PN = dyn_cast<PHINode>(I); ++I)
645         if (SE.isSCEVable(PN->getType()) &&
646             (SE.getEffectiveSCEVType(PN->getType()) ==
647              SE.getEffectiveSCEVType(AR->getType())) &&
648             SE.getSCEV(PN) == AR)
649           return;
650
651       // If this isn't one of the addrecs that the loop already has, it
652       // would require a costly new phi and add. TODO: This isn't
653       // precisely modeled right now.
654       ++NumBaseAdds;
655       if (!Regs.count(AR->getStart()))
656         RateRegister(AR->getStart(), Regs, L, SE, DT);
657     }
658
659     // Add the step value register, if it needs one.
660     // TODO: The non-affine case isn't precisely modeled here.
661     if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
662       if (!Regs.count(AR->getStart()))
663         RateRegister(AR->getOperand(1), Regs, L, SE, DT);
664   }
665   ++NumRegs;
666
667   // Rough heuristic; favor registers which don't require extra setup
668   // instructions in the preheader.
669   if (!isa<SCEVUnknown>(Reg) &&
670       !isa<SCEVConstant>(Reg) &&
671       !(isa<SCEVAddRecExpr>(Reg) &&
672         (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
673          isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
674     ++SetupCost;
675 }
676
677 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
678 /// before, rate it.
679 void Cost::RatePrimaryRegister(const SCEV *Reg,
680                                SmallPtrSet<const SCEV *, 16> &Regs,
681                                const Loop *L,
682                                ScalarEvolution &SE, DominatorTree &DT) {
683   if (Regs.insert(Reg))
684     RateRegister(Reg, Regs, L, SE, DT);
685 }
686
687 void Cost::RateFormula(const Formula &F,
688                        SmallPtrSet<const SCEV *, 16> &Regs,
689                        const DenseSet<const SCEV *> &VisitedRegs,
690                        const Loop *L,
691                        const SmallVectorImpl<int64_t> &Offsets,
692                        ScalarEvolution &SE, DominatorTree &DT) {
693   // Tally up the registers.
694   if (const SCEV *ScaledReg = F.ScaledReg) {
695     if (VisitedRegs.count(ScaledReg)) {
696       Loose();
697       return;
698     }
699     RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
700   }
701   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
702        E = F.BaseRegs.end(); I != E; ++I) {
703     const SCEV *BaseReg = *I;
704     if (VisitedRegs.count(BaseReg)) {
705       Loose();
706       return;
707     }
708     RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
709
710     NumIVMuls += isa<SCEVMulExpr>(BaseReg) &&
711                  BaseReg->hasComputableLoopEvolution(L);
712   }
713
714   if (F.BaseRegs.size() > 1)
715     NumBaseAdds += F.BaseRegs.size() - 1;
716
717   // Tally up the non-zero immediates.
718   for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
719        E = Offsets.end(); I != E; ++I) {
720     int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
721     if (F.AM.BaseGV)
722       ImmCost += 64; // Handle symbolic values conservatively.
723                      // TODO: This should probably be the pointer size.
724     else if (Offset != 0)
725       ImmCost += APInt(64, Offset, true).getMinSignedBits();
726   }
727 }
728
729 /// Loose - Set this cost to a loosing value.
730 void Cost::Loose() {
731   NumRegs = ~0u;
732   AddRecCost = ~0u;
733   NumIVMuls = ~0u;
734   NumBaseAdds = ~0u;
735   ImmCost = ~0u;
736   SetupCost = ~0u;
737 }
738
739 /// operator< - Choose the lower cost.
740 bool Cost::operator<(const Cost &Other) const {
741   if (NumRegs != Other.NumRegs)
742     return NumRegs < Other.NumRegs;
743   if (AddRecCost != Other.AddRecCost)
744     return AddRecCost < Other.AddRecCost;
745   if (NumIVMuls != Other.NumIVMuls)
746     return NumIVMuls < Other.NumIVMuls;
747   if (NumBaseAdds != Other.NumBaseAdds)
748     return NumBaseAdds < Other.NumBaseAdds;
749   if (ImmCost != Other.ImmCost)
750     return ImmCost < Other.ImmCost;
751   if (SetupCost != Other.SetupCost)
752     return SetupCost < Other.SetupCost;
753   return false;
754 }
755
756 void Cost::print(raw_ostream &OS) const {
757   OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
758   if (AddRecCost != 0)
759     OS << ", with addrec cost " << AddRecCost;
760   if (NumIVMuls != 0)
761     OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
762   if (NumBaseAdds != 0)
763     OS << ", plus " << NumBaseAdds << " base add"
764        << (NumBaseAdds == 1 ? "" : "s");
765   if (ImmCost != 0)
766     OS << ", plus " << ImmCost << " imm cost";
767   if (SetupCost != 0)
768     OS << ", plus " << SetupCost << " setup cost";
769 }
770
771 void Cost::dump() const {
772   print(errs()); errs() << '\n';
773 }
774
775 namespace {
776
777 /// LSRFixup - An operand value in an instruction which is to be replaced
778 /// with some equivalent, possibly strength-reduced, replacement.
779 struct LSRFixup {
780   /// UserInst - The instruction which will be updated.
781   Instruction *UserInst;
782
783   /// OperandValToReplace - The operand of the instruction which will
784   /// be replaced. The operand may be used more than once; every instance
785   /// will be replaced.
786   Value *OperandValToReplace;
787
788   /// PostIncLoops - If this user is to use the post-incremented value of an
789   /// induction variable, this variable is non-null and holds the loop
790   /// associated with the induction variable.
791   PostIncLoopSet PostIncLoops;
792
793   /// LUIdx - The index of the LSRUse describing the expression which
794   /// this fixup needs, minus an offset (below).
795   size_t LUIdx;
796
797   /// Offset - A constant offset to be added to the LSRUse expression.
798   /// This allows multiple fixups to share the same LSRUse with different
799   /// offsets, for example in an unrolled loop.
800   int64_t Offset;
801
802   bool isUseFullyOutsideLoop(const Loop *L) const;
803
804   LSRFixup();
805
806   void print(raw_ostream &OS) const;
807   void dump() const;
808 };
809
810 }
811
812 LSRFixup::LSRFixup()
813   : UserInst(0), OperandValToReplace(0),
814     LUIdx(~size_t(0)), Offset(0) {}
815
816 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
817 /// value outside of the given loop.
818 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
819   // PHI nodes use their value in their incoming blocks.
820   if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
821     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
822       if (PN->getIncomingValue(i) == OperandValToReplace &&
823           L->contains(PN->getIncomingBlock(i)))
824         return false;
825     return true;
826   }
827
828   return !L->contains(UserInst);
829 }
830
831 void LSRFixup::print(raw_ostream &OS) const {
832   OS << "UserInst=";
833   // Store is common and interesting enough to be worth special-casing.
834   if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
835     OS << "store ";
836     WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
837   } else if (UserInst->getType()->isVoidTy())
838     OS << UserInst->getOpcodeName();
839   else
840     WriteAsOperand(OS, UserInst, /*PrintType=*/false);
841
842   OS << ", OperandValToReplace=";
843   WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
844
845   for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
846        E = PostIncLoops.end(); I != E; ++I) {
847     OS << ", PostIncLoop=";
848     WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
849   }
850
851   if (LUIdx != ~size_t(0))
852     OS << ", LUIdx=" << LUIdx;
853
854   if (Offset != 0)
855     OS << ", Offset=" << Offset;
856 }
857
858 void LSRFixup::dump() const {
859   print(errs()); errs() << '\n';
860 }
861
862 namespace {
863
864 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
865 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
866 struct UniquifierDenseMapInfo {
867   static SmallVector<const SCEV *, 2> getEmptyKey() {
868     SmallVector<const SCEV *, 2> V;
869     V.push_back(reinterpret_cast<const SCEV *>(-1));
870     return V;
871   }
872
873   static SmallVector<const SCEV *, 2> getTombstoneKey() {
874     SmallVector<const SCEV *, 2> V;
875     V.push_back(reinterpret_cast<const SCEV *>(-2));
876     return V;
877   }
878
879   static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
880     unsigned Result = 0;
881     for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
882          E = V.end(); I != E; ++I)
883       Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
884     return Result;
885   }
886
887   static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
888                       const SmallVector<const SCEV *, 2> &RHS) {
889     return LHS == RHS;
890   }
891 };
892
893 /// LSRUse - This class holds the state that LSR keeps for each use in
894 /// IVUsers, as well as uses invented by LSR itself. It includes information
895 /// about what kinds of things can be folded into the user, information about
896 /// the user itself, and information about how the use may be satisfied.
897 /// TODO: Represent multiple users of the same expression in common?
898 class LSRUse {
899   DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
900
901 public:
902   /// KindType - An enum for a kind of use, indicating what types of
903   /// scaled and immediate operands it might support.
904   enum KindType {
905     Basic,   ///< A normal use, with no folding.
906     Special, ///< A special case of basic, allowing -1 scales.
907     Address, ///< An address use; folding according to TargetLowering
908     ICmpZero ///< An equality icmp with both operands folded into one.
909     // TODO: Add a generic icmp too?
910   };
911
912   KindType Kind;
913   const Type *AccessTy;
914
915   SmallVector<int64_t, 8> Offsets;
916   int64_t MinOffset;
917   int64_t MaxOffset;
918
919   /// AllFixupsOutsideLoop - This records whether all of the fixups using this
920   /// LSRUse are outside of the loop, in which case some special-case heuristics
921   /// may be used.
922   bool AllFixupsOutsideLoop;
923
924   /// Formulae - A list of ways to build a value that can satisfy this user.
925   /// After the list is populated, one of these is selected heuristically and
926   /// used to formulate a replacement for OperandValToReplace in UserInst.
927   SmallVector<Formula, 12> Formulae;
928
929   /// Regs - The set of register candidates used by all formulae in this LSRUse.
930   SmallPtrSet<const SCEV *, 4> Regs;
931
932   LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
933                                       MinOffset(INT64_MAX),
934                                       MaxOffset(INT64_MIN),
935                                       AllFixupsOutsideLoop(true) {}
936
937   bool InsertFormula(const Formula &F);
938
939   void check() const;
940
941   void print(raw_ostream &OS) const;
942   void dump() const;
943 };
944
945 /// InsertFormula - If the given formula has not yet been inserted, add it to
946 /// the list, and return true. Return false otherwise.
947 bool LSRUse::InsertFormula(const Formula &F) {
948   SmallVector<const SCEV *, 2> Key = F.BaseRegs;
949   if (F.ScaledReg) Key.push_back(F.ScaledReg);
950   // Unstable sort by host order ok, because this is only used for uniquifying.
951   std::sort(Key.begin(), Key.end());
952
953   if (!Uniquifier.insert(Key).second)
954     return false;
955
956   // Using a register to hold the value of 0 is not profitable.
957   assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
958          "Zero allocated in a scaled register!");
959 #ifndef NDEBUG
960   for (SmallVectorImpl<const SCEV *>::const_iterator I =
961        F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
962     assert(!(*I)->isZero() && "Zero allocated in a base register!");
963 #endif
964
965   // Add the formula to the list.
966   Formulae.push_back(F);
967
968   // Record registers now being used by this use.
969   if (F.ScaledReg) Regs.insert(F.ScaledReg);
970   Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
971
972   return true;
973 }
974
975 void LSRUse::print(raw_ostream &OS) const {
976   OS << "LSR Use: Kind=";
977   switch (Kind) {
978   case Basic:    OS << "Basic"; break;
979   case Special:  OS << "Special"; break;
980   case ICmpZero: OS << "ICmpZero"; break;
981   case Address:
982     OS << "Address of ";
983     if (AccessTy->isPointerTy())
984       OS << "pointer"; // the full pointer type could be really verbose
985     else
986       OS << *AccessTy;
987   }
988
989   OS << ", Offsets={";
990   for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
991        E = Offsets.end(); I != E; ++I) {
992     OS << *I;
993     if (next(I) != E)
994       OS << ',';
995   }
996   OS << '}';
997
998   if (AllFixupsOutsideLoop)
999     OS << ", all-fixups-outside-loop";
1000 }
1001
1002 void LSRUse::dump() const {
1003   print(errs()); errs() << '\n';
1004 }
1005
1006 /// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1007 /// be completely folded into the user instruction at isel time. This includes
1008 /// address-mode folding and special icmp tricks.
1009 static bool isLegalUse(const TargetLowering::AddrMode &AM,
1010                        LSRUse::KindType Kind, const Type *AccessTy,
1011                        const TargetLowering *TLI) {
1012   switch (Kind) {
1013   case LSRUse::Address:
1014     // If we have low-level target information, ask the target if it can
1015     // completely fold this address.
1016     if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1017
1018     // Otherwise, just guess that reg+reg addressing is legal.
1019     return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1020
1021   case LSRUse::ICmpZero:
1022     // There's not even a target hook for querying whether it would be legal to
1023     // fold a GV into an ICmp.
1024     if (AM.BaseGV)
1025       return false;
1026
1027     // ICmp only has two operands; don't allow more than two non-trivial parts.
1028     if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1029       return false;
1030
1031     // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1032     // putting the scaled register in the other operand of the icmp.
1033     if (AM.Scale != 0 && AM.Scale != -1)
1034       return false;
1035
1036     // If we have low-level target information, ask the target if it can fold an
1037     // integer immediate on an icmp.
1038     if (AM.BaseOffs != 0) {
1039       if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1040       return false;
1041     }
1042
1043     return true;
1044
1045   case LSRUse::Basic:
1046     // Only handle single-register values.
1047     return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1048
1049   case LSRUse::Special:
1050     // Only handle -1 scales, or no scale.
1051     return AM.Scale == 0 || AM.Scale == -1;
1052   }
1053
1054   return false;
1055 }
1056
1057 static bool isLegalUse(TargetLowering::AddrMode AM,
1058                        int64_t MinOffset, int64_t MaxOffset,
1059                        LSRUse::KindType Kind, const Type *AccessTy,
1060                        const TargetLowering *TLI) {
1061   // Check for overflow.
1062   if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1063       (MinOffset > 0))
1064     return false;
1065   AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1066   if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1067     AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1068     // Check for overflow.
1069     if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1070         (MaxOffset > 0))
1071       return false;
1072     AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1073     return isLegalUse(AM, Kind, AccessTy, TLI);
1074   }
1075   return false;
1076 }
1077
1078 static bool isAlwaysFoldable(int64_t BaseOffs,
1079                              GlobalValue *BaseGV,
1080                              bool HasBaseReg,
1081                              LSRUse::KindType Kind, const Type *AccessTy,
1082                              const TargetLowering *TLI) {
1083   // Fast-path: zero is always foldable.
1084   if (BaseOffs == 0 && !BaseGV) return true;
1085
1086   // Conservatively, create an address with an immediate and a
1087   // base and a scale.
1088   TargetLowering::AddrMode AM;
1089   AM.BaseOffs = BaseOffs;
1090   AM.BaseGV = BaseGV;
1091   AM.HasBaseReg = HasBaseReg;
1092   AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1093
1094   return isLegalUse(AM, Kind, AccessTy, TLI);
1095 }
1096
1097 static bool isAlwaysFoldable(const SCEV *S,
1098                              int64_t MinOffset, int64_t MaxOffset,
1099                              bool HasBaseReg,
1100                              LSRUse::KindType Kind, const Type *AccessTy,
1101                              const TargetLowering *TLI,
1102                              ScalarEvolution &SE) {
1103   // Fast-path: zero is always foldable.
1104   if (S->isZero()) return true;
1105
1106   // Conservatively, create an address with an immediate and a
1107   // base and a scale.
1108   int64_t BaseOffs = ExtractImmediate(S, SE);
1109   GlobalValue *BaseGV = ExtractSymbol(S, SE);
1110
1111   // If there's anything else involved, it's not foldable.
1112   if (!S->isZero()) return false;
1113
1114   // Fast-path: zero is always foldable.
1115   if (BaseOffs == 0 && !BaseGV) return true;
1116
1117   // Conservatively, create an address with an immediate and a
1118   // base and a scale.
1119   TargetLowering::AddrMode AM;
1120   AM.BaseOffs = BaseOffs;
1121   AM.BaseGV = BaseGV;
1122   AM.HasBaseReg = HasBaseReg;
1123   AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1124
1125   return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
1126 }
1127
1128 /// FormulaSorter - This class implements an ordering for formulae which sorts
1129 /// the by their standalone cost.
1130 class FormulaSorter {
1131   /// These two sets are kept empty, so that we compute standalone costs.
1132   DenseSet<const SCEV *> VisitedRegs;
1133   SmallPtrSet<const SCEV *, 16> Regs;
1134   Loop *L;
1135   LSRUse *LU;
1136   ScalarEvolution &SE;
1137   DominatorTree &DT;
1138
1139 public:
1140   FormulaSorter(Loop *l, LSRUse &lu, ScalarEvolution &se, DominatorTree &dt)
1141     : L(l), LU(&lu), SE(se), DT(dt) {}
1142
1143   bool operator()(const Formula &A, const Formula &B) {
1144     Cost CostA;
1145     CostA.RateFormula(A, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1146     Regs.clear();
1147     Cost CostB;
1148     CostB.RateFormula(B, Regs, VisitedRegs, L, LU->Offsets, SE, DT);
1149     Regs.clear();
1150     return CostA < CostB;
1151   }
1152 };
1153
1154 /// LSRInstance - This class holds state for the main loop strength reduction
1155 /// logic.
1156 class LSRInstance {
1157   IVUsers &IU;
1158   ScalarEvolution &SE;
1159   DominatorTree &DT;
1160   LoopInfo &LI;
1161   const TargetLowering *const TLI;
1162   Loop *const L;
1163   bool Changed;
1164
1165   /// IVIncInsertPos - This is the insert position that the current loop's
1166   /// induction variable increment should be placed. In simple loops, this is
1167   /// the latch block's terminator. But in more complicated cases, this is a
1168   /// position which will dominate all the in-loop post-increment users.
1169   Instruction *IVIncInsertPos;
1170
1171   /// Factors - Interesting factors between use strides.
1172   SmallSetVector<int64_t, 8> Factors;
1173
1174   /// Types - Interesting use types, to facilitate truncation reuse.
1175   SmallSetVector<const Type *, 4> Types;
1176
1177   /// Fixups - The list of operands which are to be replaced.
1178   SmallVector<LSRFixup, 16> Fixups;
1179
1180   /// Uses - The list of interesting uses.
1181   SmallVector<LSRUse, 16> Uses;
1182
1183   /// RegUses - Track which uses use which register candidates.
1184   RegUseTracker RegUses;
1185
1186   void OptimizeShadowIV();
1187   bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1188   ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1189   bool OptimizeLoopTermCond();
1190
1191   void CollectInterestingTypesAndFactors();
1192   void CollectFixupsAndInitialFormulae();
1193
1194   LSRFixup &getNewFixup() {
1195     Fixups.push_back(LSRFixup());
1196     return Fixups.back();
1197   }
1198
1199   // Support for sharing of LSRUses between LSRFixups.
1200   typedef DenseMap<const SCEV *, size_t> UseMapTy;
1201   UseMapTy UseMap;
1202
1203   bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1204                           LSRUse::KindType Kind, const Type *AccessTy);
1205
1206   std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1207                                     LSRUse::KindType Kind,
1208                                     const Type *AccessTy);
1209
1210 public:
1211   void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1212   void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1213   void CountRegisters(const Formula &F, size_t LUIdx);
1214   bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1215
1216   void CollectLoopInvariantFixupsAndFormulae();
1217
1218   void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1219                               unsigned Depth = 0);
1220   void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1221   void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1222   void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1223   void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1224   void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1225   void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1226   void GenerateCrossUseConstantOffsets();
1227   void GenerateAllReuseFormulae();
1228
1229   void FilterOutUndesirableDedicatedRegisters();
1230   void NarrowSearchSpaceUsingHeuristics();
1231
1232   void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1233                     Cost &SolutionCost,
1234                     SmallVectorImpl<const Formula *> &Workspace,
1235                     const Cost &CurCost,
1236                     const SmallPtrSet<const SCEV *, 16> &CurRegs,
1237                     DenseSet<const SCEV *> &VisitedRegs) const;
1238   void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1239
1240   BasicBlock::iterator
1241     HoistInsertPosition(BasicBlock::iterator IP,
1242                         const SmallVectorImpl<Instruction *> &Inputs) const;
1243   BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1244                                                      const LSRFixup &LF,
1245                                                      const LSRUse &LU) const;
1246
1247   Value *Expand(const LSRFixup &LF,
1248                 const Formula &F,
1249                 BasicBlock::iterator IP,
1250                 SCEVExpander &Rewriter,
1251                 SmallVectorImpl<WeakVH> &DeadInsts) const;
1252   void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1253                      const Formula &F,
1254                      SCEVExpander &Rewriter,
1255                      SmallVectorImpl<WeakVH> &DeadInsts,
1256                      Pass *P) const;
1257   void Rewrite(const LSRFixup &LF,
1258                const Formula &F,
1259                SCEVExpander &Rewriter,
1260                SmallVectorImpl<WeakVH> &DeadInsts,
1261                Pass *P) const;
1262   void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1263                          Pass *P);
1264
1265   LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1266
1267   bool getChanged() const { return Changed; }
1268
1269   void print_factors_and_types(raw_ostream &OS) const;
1270   void print_fixups(raw_ostream &OS) const;
1271   void print_uses(raw_ostream &OS) const;
1272   void print(raw_ostream &OS) const;
1273   void dump() const;
1274 };
1275
1276 }
1277
1278 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1279 /// inside the loop then try to eliminate the cast operation.
1280 void LSRInstance::OptimizeShadowIV() {
1281   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1282   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1283     return;
1284
1285   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1286        UI != E; /* empty */) {
1287     IVUsers::const_iterator CandidateUI = UI;
1288     ++UI;
1289     Instruction *ShadowUse = CandidateUI->getUser();
1290     const Type *DestTy = NULL;
1291
1292     /* If shadow use is a int->float cast then insert a second IV
1293        to eliminate this cast.
1294
1295          for (unsigned i = 0; i < n; ++i)
1296            foo((double)i);
1297
1298        is transformed into
1299
1300          double d = 0.0;
1301          for (unsigned i = 0; i < n; ++i, ++d)
1302            foo(d);
1303     */
1304     if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1305       DestTy = UCast->getDestTy();
1306     else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1307       DestTy = SCast->getDestTy();
1308     if (!DestTy) continue;
1309
1310     if (TLI) {
1311       // If target does not support DestTy natively then do not apply
1312       // this transformation.
1313       EVT DVT = TLI->getValueType(DestTy);
1314       if (!TLI->isTypeLegal(DVT)) continue;
1315     }
1316
1317     PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1318     if (!PH) continue;
1319     if (PH->getNumIncomingValues() != 2) continue;
1320
1321     const Type *SrcTy = PH->getType();
1322     int Mantissa = DestTy->getFPMantissaWidth();
1323     if (Mantissa == -1) continue;
1324     if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1325       continue;
1326
1327     unsigned Entry, Latch;
1328     if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1329       Entry = 0;
1330       Latch = 1;
1331     } else {
1332       Entry = 1;
1333       Latch = 0;
1334     }
1335
1336     ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1337     if (!Init) continue;
1338     Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
1339
1340     BinaryOperator *Incr =
1341       dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1342     if (!Incr) continue;
1343     if (Incr->getOpcode() != Instruction::Add
1344         && Incr->getOpcode() != Instruction::Sub)
1345       continue;
1346
1347     /* Initialize new IV, double d = 0.0 in above example. */
1348     ConstantInt *C = NULL;
1349     if (Incr->getOperand(0) == PH)
1350       C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1351     else if (Incr->getOperand(1) == PH)
1352       C = dyn_cast<ConstantInt>(Incr->getOperand(0));
1353     else
1354       continue;
1355
1356     if (!C) continue;
1357
1358     // Ignore negative constants, as the code below doesn't handle them
1359     // correctly. TODO: Remove this restriction.
1360     if (!C->getValue().isStrictlyPositive()) continue;
1361
1362     /* Add new PHINode. */
1363     PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
1364
1365     /* create new increment. '++d' in above example. */
1366     Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1367     BinaryOperator *NewIncr =
1368       BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1369                                Instruction::FAdd : Instruction::FSub,
1370                              NewPH, CFP, "IV.S.next.", Incr);
1371
1372     NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1373     NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1374
1375     /* Remove cast operation */
1376     ShadowUse->replaceAllUsesWith(NewPH);
1377     ShadowUse->eraseFromParent();
1378     break;
1379   }
1380 }
1381
1382 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1383 /// set the IV user and stride information and return true, otherwise return
1384 /// false.
1385 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond,
1386                                     IVStrideUse *&CondUse) {
1387   for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1388     if (UI->getUser() == Cond) {
1389       // NOTE: we could handle setcc instructions with multiple uses here, but
1390       // InstCombine does it as well for simple uses, it's not clear that it
1391       // occurs enough in real life to handle.
1392       CondUse = UI;
1393       return true;
1394     }
1395   return false;
1396 }
1397
1398 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
1399 /// a max computation.
1400 ///
1401 /// This is a narrow solution to a specific, but acute, problem. For loops
1402 /// like this:
1403 ///
1404 ///   i = 0;
1405 ///   do {
1406 ///     p[i] = 0.0;
1407 ///   } while (++i < n);
1408 ///
1409 /// the trip count isn't just 'n', because 'n' might not be positive. And
1410 /// unfortunately this can come up even for loops where the user didn't use
1411 /// a C do-while loop. For example, seemingly well-behaved top-test loops
1412 /// will commonly be lowered like this:
1413 //
1414 ///   if (n > 0) {
1415 ///     i = 0;
1416 ///     do {
1417 ///       p[i] = 0.0;
1418 ///     } while (++i < n);
1419 ///   }
1420 ///
1421 /// and then it's possible for subsequent optimization to obscure the if
1422 /// test in such a way that indvars can't find it.
1423 ///
1424 /// When indvars can't find the if test in loops like this, it creates a
1425 /// max expression, which allows it to give the loop a canonical
1426 /// induction variable:
1427 ///
1428 ///   i = 0;
1429 ///   max = n < 1 ? 1 : n;
1430 ///   do {
1431 ///     p[i] = 0.0;
1432 ///   } while (++i != max);
1433 ///
1434 /// Canonical induction variables are necessary because the loop passes
1435 /// are designed around them. The most obvious example of this is the
1436 /// LoopInfo analysis, which doesn't remember trip count values. It
1437 /// expects to be able to rediscover the trip count each time it is
1438 /// needed, and it does this using a simple analysis that only succeeds if
1439 /// the loop has a canonical induction variable.
1440 ///
1441 /// However, when it comes time to generate code, the maximum operation
1442 /// can be quite costly, especially if it's inside of an outer loop.
1443 ///
1444 /// This function solves this problem by detecting this type of loop and
1445 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1446 /// the instructions for the maximum computation.
1447 ///
1448 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
1449   // Check that the loop matches the pattern we're looking for.
1450   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1451       Cond->getPredicate() != CmpInst::ICMP_NE)
1452     return Cond;
1453
1454   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1455   if (!Sel || !Sel->hasOneUse()) return Cond;
1456
1457   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1458   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1459     return Cond;
1460   const SCEV *One = SE.getIntegerSCEV(1, BackedgeTakenCount->getType());
1461
1462   // Add one to the backedge-taken count to get the trip count.
1463   const SCEV *IterationCount = SE.getAddExpr(BackedgeTakenCount, One);
1464
1465   // Check for a max calculation that matches the pattern.
1466   if (!isa<SCEVSMaxExpr>(IterationCount) && !isa<SCEVUMaxExpr>(IterationCount))
1467     return Cond;
1468   const SCEVNAryExpr *Max = cast<SCEVNAryExpr>(IterationCount);
1469   if (Max != SE.getSCEV(Sel)) return Cond;
1470
1471   // To handle a max with more than two operands, this optimization would
1472   // require additional checking and setup.
1473   if (Max->getNumOperands() != 2)
1474     return Cond;
1475
1476   const SCEV *MaxLHS = Max->getOperand(0);
1477   const SCEV *MaxRHS = Max->getOperand(1);
1478   if (!MaxLHS || MaxLHS != One) return Cond;
1479   // Check the relevant induction variable for conformance to
1480   // the pattern.
1481   const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
1482   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1483   if (!AR || !AR->isAffine() ||
1484       AR->getStart() != One ||
1485       AR->getStepRecurrence(SE) != One)
1486     return Cond;
1487
1488   assert(AR->getLoop() == L &&
1489          "Loop condition operand is an addrec in a different loop!");
1490
1491   // Check the right operand of the select, and remember it, as it will
1492   // be used in the new comparison instruction.
1493   Value *NewRHS = 0;
1494   if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
1495     NewRHS = Sel->getOperand(1);
1496   else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
1497     NewRHS = Sel->getOperand(2);
1498   if (!NewRHS) return Cond;
1499
1500   // Determine the new comparison opcode. It may be signed or unsigned,
1501   // and the original comparison may be either equality or inequality.
1502   CmpInst::Predicate Pred =
1503     isa<SCEVSMaxExpr>(Max) ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
1504   if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1505     Pred = CmpInst::getInversePredicate(Pred);
1506
1507   // Ok, everything looks ok to change the condition into an SLT or SGE and
1508   // delete the max calculation.
1509   ICmpInst *NewCond =
1510     new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1511
1512   // Delete the max calculation instructions.
1513   Cond->replaceAllUsesWith(NewCond);
1514   CondUse->setUser(NewCond);
1515   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1516   Cond->eraseFromParent();
1517   Sel->eraseFromParent();
1518   if (Cmp->use_empty())
1519     Cmp->eraseFromParent();
1520   return NewCond;
1521 }
1522
1523 /// OptimizeLoopTermCond - Change loop terminating condition to use the
1524 /// postinc iv when possible.
1525 bool
1526 LSRInstance::OptimizeLoopTermCond() {
1527   SmallPtrSet<Instruction *, 4> PostIncs;
1528
1529   BasicBlock *LatchBlock = L->getLoopLatch();
1530   SmallVector<BasicBlock*, 8> ExitingBlocks;
1531   L->getExitingBlocks(ExitingBlocks);
1532
1533   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1534     BasicBlock *ExitingBlock = ExitingBlocks[i];
1535
1536     // Get the terminating condition for the loop if possible.  If we
1537     // can, we want to change it to use a post-incremented version of its
1538     // induction variable, to allow coalescing the live ranges for the IV into
1539     // one register value.
1540
1541     BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1542     if (!TermBr)
1543       continue;
1544     // FIXME: Overly conservative, termination condition could be an 'or' etc..
1545     if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1546       continue;
1547
1548     // Search IVUsesByStride to find Cond's IVUse if there is one.
1549     IVStrideUse *CondUse = 0;
1550     ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1551     if (!FindIVUserForCond(Cond, CondUse))
1552       continue;
1553
1554     // If the trip count is computed in terms of a max (due to ScalarEvolution
1555     // being unable to find a sufficient guard, for example), change the loop
1556     // comparison to use SLT or ULT instead of NE.
1557     // One consequence of doing this now is that it disrupts the count-down
1558     // optimization. That's not always a bad thing though, because in such
1559     // cases it may still be worthwhile to avoid a max.
1560     Cond = OptimizeMax(Cond, CondUse);
1561
1562     // If this exiting block dominates the latch block, it may also use
1563     // the post-inc value if it won't be shared with other uses.
1564     // Check for dominance.
1565     if (!DT.dominates(ExitingBlock, LatchBlock))
1566       continue;
1567
1568     // Conservatively avoid trying to use the post-inc value in non-latch
1569     // exits if there may be pre-inc users in intervening blocks.
1570     if (LatchBlock != ExitingBlock)
1571       for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1572         // Test if the use is reachable from the exiting block. This dominator
1573         // query is a conservative approximation of reachability.
1574         if (&*UI != CondUse &&
1575             !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1576           // Conservatively assume there may be reuse if the quotient of their
1577           // strides could be a legal scale.
1578           const SCEV *A = IU.getStride(*CondUse, L);
1579           const SCEV *B = IU.getStride(*UI, L);
1580           if (!A || !B) continue;
1581           if (SE.getTypeSizeInBits(A->getType()) !=
1582               SE.getTypeSizeInBits(B->getType())) {
1583             if (SE.getTypeSizeInBits(A->getType()) >
1584                 SE.getTypeSizeInBits(B->getType()))
1585               B = SE.getSignExtendExpr(B, A->getType());
1586             else
1587               A = SE.getSignExtendExpr(A, B->getType());
1588           }
1589           if (const SCEVConstant *D =
1590                 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
1591             // Stride of one or negative one can have reuse with non-addresses.
1592             if (D->getValue()->isOne() ||
1593                 D->getValue()->isAllOnesValue())
1594               goto decline_post_inc;
1595             // Avoid weird situations.
1596             if (D->getValue()->getValue().getMinSignedBits() >= 64 ||
1597                 D->getValue()->getValue().isMinSignedValue())
1598               goto decline_post_inc;
1599             // Without TLI, assume that any stride might be valid, and so any
1600             // use might be shared.
1601             if (!TLI)
1602               goto decline_post_inc;
1603             // Check for possible scaled-address reuse.
1604             const Type *AccessTy = getAccessType(UI->getUser());
1605             TargetLowering::AddrMode AM;
1606             AM.Scale = D->getValue()->getSExtValue();
1607             if (TLI->isLegalAddressingMode(AM, AccessTy))
1608               goto decline_post_inc;
1609             AM.Scale = -AM.Scale;
1610             if (TLI->isLegalAddressingMode(AM, AccessTy))
1611               goto decline_post_inc;
1612           }
1613         }
1614
1615     DEBUG(dbgs() << "  Change loop exiting icmp to use postinc iv: "
1616                  << *Cond << '\n');
1617
1618     // It's possible for the setcc instruction to be anywhere in the loop, and
1619     // possible for it to have multiple users.  If it is not immediately before
1620     // the exiting block branch, move it.
1621     if (&*++BasicBlock::iterator(Cond) != TermBr) {
1622       if (Cond->hasOneUse()) {
1623         Cond->moveBefore(TermBr);
1624       } else {
1625         // Clone the terminating condition and insert into the loopend.
1626         ICmpInst *OldCond = Cond;
1627         Cond = cast<ICmpInst>(Cond->clone());
1628         Cond->setName(L->getHeader()->getName() + ".termcond");
1629         ExitingBlock->getInstList().insert(TermBr, Cond);
1630
1631         // Clone the IVUse, as the old use still exists!
1632         CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
1633         TermBr->replaceUsesOfWith(OldCond, Cond);
1634       }
1635     }
1636
1637     // If we get to here, we know that we can transform the setcc instruction to
1638     // use the post-incremented version of the IV, allowing us to coalesce the
1639     // live ranges for the IV correctly.
1640     CondUse->transformToPostInc(L);
1641     Changed = true;
1642
1643     PostIncs.insert(Cond);
1644   decline_post_inc:;
1645   }
1646
1647   // Determine an insertion point for the loop induction variable increment. It
1648   // must dominate all the post-inc comparisons we just set up, and it must
1649   // dominate the loop latch edge.
1650   IVIncInsertPos = L->getLoopLatch()->getTerminator();
1651   for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1652        E = PostIncs.end(); I != E; ++I) {
1653     BasicBlock *BB =
1654       DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1655                                     (*I)->getParent());
1656     if (BB == (*I)->getParent())
1657       IVIncInsertPos = *I;
1658     else if (BB != IVIncInsertPos->getParent())
1659       IVIncInsertPos = BB->getTerminator();
1660   }
1661
1662   return Changed;
1663 }
1664
1665 bool
1666 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
1667                                 LSRUse::KindType Kind, const Type *AccessTy) {
1668   int64_t NewMinOffset = LU.MinOffset;
1669   int64_t NewMaxOffset = LU.MaxOffset;
1670   const Type *NewAccessTy = AccessTy;
1671
1672   // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1673   // something conservative, however this can pessimize in the case that one of
1674   // the uses will have all its uses outside the loop, for example.
1675   if (LU.Kind != Kind)
1676     return false;
1677   // Conservatively assume HasBaseReg is true for now.
1678   if (NewOffset < LU.MinOffset) {
1679     if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, /*HasBaseReg=*/true,
1680                           Kind, AccessTy, TLI))
1681       return false;
1682     NewMinOffset = NewOffset;
1683   } else if (NewOffset > LU.MaxOffset) {
1684     if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, /*HasBaseReg=*/true,
1685                           Kind, AccessTy, TLI))
1686       return false;
1687     NewMaxOffset = NewOffset;
1688   }
1689   // Check for a mismatched access type, and fall back conservatively as needed.
1690   if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1691     NewAccessTy = Type::getVoidTy(AccessTy->getContext());
1692
1693   // Update the use.
1694   LU.MinOffset = NewMinOffset;
1695   LU.MaxOffset = NewMaxOffset;
1696   LU.AccessTy = NewAccessTy;
1697   if (NewOffset != LU.Offsets.back())
1698     LU.Offsets.push_back(NewOffset);
1699   return true;
1700 }
1701
1702 /// getUse - Return an LSRUse index and an offset value for a fixup which
1703 /// needs the given expression, with the given kind and optional access type.
1704 /// Either reuse an existing use or create a new one, as needed.
1705 std::pair<size_t, int64_t>
1706 LSRInstance::getUse(const SCEV *&Expr,
1707                     LSRUse::KindType Kind, const Type *AccessTy) {
1708   const SCEV *Copy = Expr;
1709   int64_t Offset = ExtractImmediate(Expr, SE);
1710
1711   // Basic uses can't accept any offset, for example.
1712   if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
1713     Expr = Copy;
1714     Offset = 0;
1715   }
1716
1717   std::pair<UseMapTy::iterator, bool> P =
1718     UseMap.insert(std::make_pair(Expr, 0));
1719   if (!P.second) {
1720     // A use already existed with this base.
1721     size_t LUIdx = P.first->second;
1722     LSRUse &LU = Uses[LUIdx];
1723     if (reconcileNewOffset(LU, Offset, Kind, AccessTy))
1724       // Reuse this use.
1725       return std::make_pair(LUIdx, Offset);
1726   }
1727
1728   // Create a new use.
1729   size_t LUIdx = Uses.size();
1730   P.first->second = LUIdx;
1731   Uses.push_back(LSRUse(Kind, AccessTy));
1732   LSRUse &LU = Uses[LUIdx];
1733
1734   // We don't need to track redundant offsets, but we don't need to go out
1735   // of our way here to avoid them.
1736   if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1737     LU.Offsets.push_back(Offset);
1738
1739   LU.MinOffset = Offset;
1740   LU.MaxOffset = Offset;
1741   return std::make_pair(LUIdx, Offset);
1742 }
1743
1744 void LSRInstance::CollectInterestingTypesAndFactors() {
1745   SmallSetVector<const SCEV *, 4> Strides;
1746
1747   // Collect interesting types and strides.
1748   SmallVector<const SCEV *, 4> Worklist;
1749   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1750     const SCEV *Expr = IU.getExpr(*UI);
1751
1752     // Collect interesting types.
1753     Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
1754
1755     // Add strides for mentioned loops.
1756     Worklist.push_back(Expr);
1757     do {
1758       const SCEV *S = Worklist.pop_back_val();
1759       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1760         Strides.insert(AR->getStepRecurrence(SE));
1761         Worklist.push_back(AR->getStart());
1762       } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1763         Worklist.insert(Worklist.end(), Add->op_begin(), Add->op_end());
1764       }
1765     } while (!Worklist.empty());
1766   }
1767
1768   // Compute interesting factors from the set of interesting strides.
1769   for (SmallSetVector<const SCEV *, 4>::const_iterator
1770        I = Strides.begin(), E = Strides.end(); I != E; ++I)
1771     for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
1772          next(I); NewStrideIter != E; ++NewStrideIter) {
1773       const SCEV *OldStride = *I;
1774       const SCEV *NewStride = *NewStrideIter;
1775
1776       if (SE.getTypeSizeInBits(OldStride->getType()) !=
1777           SE.getTypeSizeInBits(NewStride->getType())) {
1778         if (SE.getTypeSizeInBits(OldStride->getType()) >
1779             SE.getTypeSizeInBits(NewStride->getType()))
1780           NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1781         else
1782           OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1783       }
1784       if (const SCEVConstant *Factor =
1785             dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
1786                                                         SE, true))) {
1787         if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1788           Factors.insert(Factor->getValue()->getValue().getSExtValue());
1789       } else if (const SCEVConstant *Factor =
1790                    dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
1791                                                                NewStride,
1792                                                                SE, true))) {
1793         if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
1794           Factors.insert(Factor->getValue()->getValue().getSExtValue());
1795       }
1796     }
1797
1798   // If all uses use the same type, don't bother looking for truncation-based
1799   // reuse.
1800   if (Types.size() == 1)
1801     Types.clear();
1802
1803   DEBUG(print_factors_and_types(dbgs()));
1804 }
1805
1806 void LSRInstance::CollectFixupsAndInitialFormulae() {
1807   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1808     // Record the uses.
1809     LSRFixup &LF = getNewFixup();
1810     LF.UserInst = UI->getUser();
1811     LF.OperandValToReplace = UI->getOperandValToReplace();
1812     LF.PostIncLoops = UI->getPostIncLoops();
1813
1814     LSRUse::KindType Kind = LSRUse::Basic;
1815     const Type *AccessTy = 0;
1816     if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
1817       Kind = LSRUse::Address;
1818       AccessTy = getAccessType(LF.UserInst);
1819     }
1820
1821     const SCEV *S = IU.getExpr(*UI);
1822
1823     // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
1824     // (N - i == 0), and this allows (N - i) to be the expression that we work
1825     // with rather than just N or i, so we can consider the register
1826     // requirements for both N and i at the same time. Limiting this code to
1827     // equality icmps is not a problem because all interesting loops use
1828     // equality icmps, thanks to IndVarSimplify.
1829     if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
1830       if (CI->isEquality()) {
1831         // Swap the operands if needed to put the OperandValToReplace on the
1832         // left, for consistency.
1833         Value *NV = CI->getOperand(1);
1834         if (NV == LF.OperandValToReplace) {
1835           CI->setOperand(1, CI->getOperand(0));
1836           CI->setOperand(0, NV);
1837         }
1838
1839         // x == y  -->  x - y == 0
1840         const SCEV *N = SE.getSCEV(NV);
1841         if (N->isLoopInvariant(L)) {
1842           Kind = LSRUse::ICmpZero;
1843           S = SE.getMinusSCEV(N, S);
1844         }
1845
1846         // -1 and the negations of all interesting strides (except the negation
1847         // of -1) are now also interesting.
1848         for (size_t i = 0, e = Factors.size(); i != e; ++i)
1849           if (Factors[i] != -1)
1850             Factors.insert(-(uint64_t)Factors[i]);
1851         Factors.insert(-1);
1852       }
1853
1854     // Set up the initial formula for this use.
1855     std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
1856     LF.LUIdx = P.first;
1857     LF.Offset = P.second;
1858     LSRUse &LU = Uses[LF.LUIdx];
1859     LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
1860
1861     // If this is the first use of this LSRUse, give it a formula.
1862     if (LU.Formulae.empty()) {
1863       InsertInitialFormula(S, LU, LF.LUIdx);
1864       CountRegisters(LU.Formulae.back(), LF.LUIdx);
1865     }
1866   }
1867
1868   DEBUG(print_fixups(dbgs()));
1869 }
1870
1871 void
1872 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
1873   Formula F;
1874   F.InitialMatch(S, L, SE, DT);
1875   bool Inserted = InsertFormula(LU, LUIdx, F);
1876   assert(Inserted && "Initial formula already exists!"); (void)Inserted;
1877 }
1878
1879 void
1880 LSRInstance::InsertSupplementalFormula(const SCEV *S,
1881                                        LSRUse &LU, size_t LUIdx) {
1882   Formula F;
1883   F.BaseRegs.push_back(S);
1884   F.AM.HasBaseReg = true;
1885   bool Inserted = InsertFormula(LU, LUIdx, F);
1886   assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
1887 }
1888
1889 /// CountRegisters - Note which registers are used by the given formula,
1890 /// updating RegUses.
1891 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
1892   if (F.ScaledReg)
1893     RegUses.CountRegister(F.ScaledReg, LUIdx);
1894   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1895        E = F.BaseRegs.end(); I != E; ++I)
1896     RegUses.CountRegister(*I, LUIdx);
1897 }
1898
1899 /// InsertFormula - If the given formula has not yet been inserted, add it to
1900 /// the list, and return true. Return false otherwise.
1901 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
1902   if (!LU.InsertFormula(F))
1903     return false;
1904
1905   CountRegisters(F, LUIdx);
1906   return true;
1907 }
1908
1909 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
1910 /// loop-invariant values which we're tracking. These other uses will pin these
1911 /// values in registers, making them less profitable for elimination.
1912 /// TODO: This currently misses non-constant addrec step registers.
1913 /// TODO: Should this give more weight to users inside the loop?
1914 void
1915 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
1916   SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
1917   SmallPtrSet<const SCEV *, 8> Inserted;
1918
1919   while (!Worklist.empty()) {
1920     const SCEV *S = Worklist.pop_back_val();
1921
1922     if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
1923       Worklist.insert(Worklist.end(), N->op_begin(), N->op_end());
1924     else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
1925       Worklist.push_back(C->getOperand());
1926     else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1927       Worklist.push_back(D->getLHS());
1928       Worklist.push_back(D->getRHS());
1929     } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
1930       if (!Inserted.insert(U)) continue;
1931       const Value *V = U->getValue();
1932       if (const Instruction *Inst = dyn_cast<Instruction>(V))
1933         if (L->contains(Inst)) continue;
1934       for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1935            UI != UE; ++UI) {
1936         const Instruction *UserInst = dyn_cast<Instruction>(*UI);
1937         // Ignore non-instructions.
1938         if (!UserInst)
1939           continue;
1940         // Ignore instructions in other functions (as can happen with
1941         // Constants).
1942         if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
1943           continue;
1944         // Ignore instructions not dominated by the loop.
1945         const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
1946           UserInst->getParent() :
1947           cast<PHINode>(UserInst)->getIncomingBlock(
1948             PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
1949         if (!DT.dominates(L->getHeader(), UseBB))
1950           continue;
1951         // Ignore uses which are part of other SCEV expressions, to avoid
1952         // analyzing them multiple times.
1953         if (SE.isSCEVable(UserInst->getType())) {
1954           const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
1955           // If the user is a no-op, look through to its uses.
1956           if (!isa<SCEVUnknown>(UserS))
1957             continue;
1958           if (UserS == U) {
1959             Worklist.push_back(
1960               SE.getUnknown(const_cast<Instruction *>(UserInst)));
1961             continue;
1962           }
1963         }
1964         // Ignore icmp instructions which are already being analyzed.
1965         if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
1966           unsigned OtherIdx = !UI.getOperandNo();
1967           Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
1968           if (SE.getSCEV(OtherOp)->hasComputableLoopEvolution(L))
1969             continue;
1970         }
1971
1972         LSRFixup &LF = getNewFixup();
1973         LF.UserInst = const_cast<Instruction *>(UserInst);
1974         LF.OperandValToReplace = UI.getUse();
1975         std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
1976         LF.LUIdx = P.first;
1977         LF.Offset = P.second;
1978         LSRUse &LU = Uses[LF.LUIdx];
1979         LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
1980         InsertSupplementalFormula(U, LU, LF.LUIdx);
1981         CountRegisters(LU.Formulae.back(), Uses.size() - 1);
1982         break;
1983       }
1984     }
1985   }
1986 }
1987
1988 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
1989 /// separate registers. If C is non-null, multiply each subexpression by C.
1990 static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
1991                             SmallVectorImpl<const SCEV *> &Ops,
1992                             ScalarEvolution &SE) {
1993   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1994     // Break out add operands.
1995     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
1996          I != E; ++I)
1997       CollectSubexprs(*I, C, Ops, SE);
1998     return;
1999   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2000     // Split a non-zero base out of an addrec.
2001     if (!AR->getStart()->isZero()) {
2002       CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
2003                                        AR->getStepRecurrence(SE),
2004                                        AR->getLoop()), C, Ops, SE);
2005       CollectSubexprs(AR->getStart(), C, Ops, SE);
2006       return;
2007     }
2008   } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2009     // Break (C * (a + b + c)) into C*a + C*b + C*c.
2010     if (Mul->getNumOperands() == 2)
2011       if (const SCEVConstant *Op0 =
2012             dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2013         CollectSubexprs(Mul->getOperand(1),
2014                         C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2015                         Ops, SE);
2016         return;
2017       }
2018   }
2019
2020   // Otherwise use the value itself.
2021   Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2022 }
2023
2024 /// GenerateReassociations - Split out subexpressions from adds and the bases of
2025 /// addrecs.
2026 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2027                                          Formula Base,
2028                                          unsigned Depth) {
2029   // Arbitrarily cap recursion to protect compile time.
2030   if (Depth >= 3) return;
2031
2032   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2033     const SCEV *BaseReg = Base.BaseRegs[i];
2034
2035     SmallVector<const SCEV *, 8> AddOps;
2036     CollectSubexprs(BaseReg, 0, AddOps, SE);
2037     if (AddOps.size() == 1) continue;
2038
2039     for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2040          JE = AddOps.end(); J != JE; ++J) {
2041       // Don't pull a constant into a register if the constant could be folded
2042       // into an immediate field.
2043       if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2044                            Base.getNumRegs() > 1,
2045                            LU.Kind, LU.AccessTy, TLI, SE))
2046         continue;
2047
2048       // Collect all operands except *J.
2049       SmallVector<const SCEV *, 8> InnerAddOps;
2050       for (SmallVectorImpl<const SCEV *>::const_iterator K = AddOps.begin(),
2051            KE = AddOps.end(); K != KE; ++K)
2052         if (K != J)
2053           InnerAddOps.push_back(*K);
2054
2055       // Don't leave just a constant behind in a register if the constant could
2056       // be folded into an immediate field.
2057       if (InnerAddOps.size() == 1 &&
2058           isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2059                            Base.getNumRegs() > 1,
2060                            LU.Kind, LU.AccessTy, TLI, SE))
2061         continue;
2062
2063       Formula F = Base;
2064       F.BaseRegs[i] = SE.getAddExpr(InnerAddOps);
2065       F.BaseRegs.push_back(*J);
2066       if (InsertFormula(LU, LUIdx, F))
2067         // If that formula hadn't been seen before, recurse to find more like
2068         // it.
2069         GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2070     }
2071   }
2072 }
2073
2074 /// GenerateCombinations - Generate a formula consisting of all of the
2075 /// loop-dominating registers added into a single register.
2076 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
2077                                        Formula Base) {
2078   // This method is only interesting on a plurality of registers.
2079   if (Base.BaseRegs.size() <= 1) return;
2080
2081   Formula F = Base;
2082   F.BaseRegs.clear();
2083   SmallVector<const SCEV *, 4> Ops;
2084   for (SmallVectorImpl<const SCEV *>::const_iterator
2085        I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2086     const SCEV *BaseReg = *I;
2087     if (BaseReg->properlyDominates(L->getHeader(), &DT) &&
2088         !BaseReg->hasComputableLoopEvolution(L))
2089       Ops.push_back(BaseReg);
2090     else
2091       F.BaseRegs.push_back(BaseReg);
2092   }
2093   if (Ops.size() > 1) {
2094     const SCEV *Sum = SE.getAddExpr(Ops);
2095     // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2096     // opportunity to fold something. For now, just ignore such cases
2097     // rather than proceed with zero in a register.
2098     if (!Sum->isZero()) {
2099       F.BaseRegs.push_back(Sum);
2100       (void)InsertFormula(LU, LUIdx, F);
2101     }
2102   }
2103 }
2104
2105 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2106 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2107                                           Formula Base) {
2108   // We can't add a symbolic offset if the address already contains one.
2109   if (Base.AM.BaseGV) return;
2110
2111   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2112     const SCEV *G = Base.BaseRegs[i];
2113     GlobalValue *GV = ExtractSymbol(G, SE);
2114     if (G->isZero() || !GV)
2115       continue;
2116     Formula F = Base;
2117     F.AM.BaseGV = GV;
2118     if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2119                     LU.Kind, LU.AccessTy, TLI))
2120       continue;
2121     F.BaseRegs[i] = G;
2122     (void)InsertFormula(LU, LUIdx, F);
2123   }
2124 }
2125
2126 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2127 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2128                                           Formula Base) {
2129   // TODO: For now, just add the min and max offset, because it usually isn't
2130   // worthwhile looking at everything inbetween.
2131   SmallVector<int64_t, 4> Worklist;
2132   Worklist.push_back(LU.MinOffset);
2133   if (LU.MaxOffset != LU.MinOffset)
2134     Worklist.push_back(LU.MaxOffset);
2135
2136   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2137     const SCEV *G = Base.BaseRegs[i];
2138
2139     for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2140          E = Worklist.end(); I != E; ++I) {
2141       Formula F = Base;
2142       F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2143       if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2144                      LU.Kind, LU.AccessTy, TLI)) {
2145         F.BaseRegs[i] = SE.getAddExpr(G, SE.getIntegerSCEV(*I, G->getType()));
2146
2147         (void)InsertFormula(LU, LUIdx, F);
2148       }
2149     }
2150
2151     int64_t Imm = ExtractImmediate(G, SE);
2152     if (G->isZero() || Imm == 0)
2153       continue;
2154     Formula F = Base;
2155     F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2156     if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2157                     LU.Kind, LU.AccessTy, TLI))
2158       continue;
2159     F.BaseRegs[i] = G;
2160     (void)InsertFormula(LU, LUIdx, F);
2161   }
2162 }
2163
2164 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2165 /// the comparison. For example, x == y -> x*c == y*c.
2166 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2167                                          Formula Base) {
2168   if (LU.Kind != LSRUse::ICmpZero) return;
2169
2170   // Determine the integer type for the base formula.
2171   const Type *IntTy = Base.getType();
2172   if (!IntTy) return;
2173   if (SE.getTypeSizeInBits(IntTy) > 64) return;
2174
2175   // Don't do this if there is more than one offset.
2176   if (LU.MinOffset != LU.MaxOffset) return;
2177
2178   assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2179
2180   // Check each interesting stride.
2181   for (SmallSetVector<int64_t, 8>::const_iterator
2182        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2183     int64_t Factor = *I;
2184     Formula F = Base;
2185
2186     // Check that the multiplication doesn't overflow.
2187     if (F.AM.BaseOffs == INT64_MIN && Factor == -1)
2188       continue;
2189     F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2190     if (F.AM.BaseOffs / Factor != Base.AM.BaseOffs)
2191       continue;
2192
2193     // Check that multiplying with the use offset doesn't overflow.
2194     int64_t Offset = LU.MinOffset;
2195     if (Offset == INT64_MIN && Factor == -1)
2196       continue;
2197     Offset = (uint64_t)Offset * Factor;
2198     if (Offset / Factor != LU.MinOffset)
2199       continue;
2200
2201     // Check that this scale is legal.
2202     if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2203       continue;
2204
2205     // Compensate for the use having MinOffset built into it.
2206     F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2207
2208     const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2209
2210     // Check that multiplying with each base register doesn't overflow.
2211     for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2212       F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
2213       if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
2214         goto next;
2215     }
2216
2217     // Check that multiplying with the scaled register doesn't overflow.
2218     if (F.ScaledReg) {
2219       F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
2220       if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
2221         continue;
2222     }
2223
2224     // If we make it here and it's legal, add it.
2225     (void)InsertFormula(LU, LUIdx, F);
2226   next:;
2227   }
2228 }
2229
2230 /// GenerateScales - Generate stride factor reuse formulae by making use of
2231 /// scaled-offset address modes, for example.
2232 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx,
2233                                  Formula Base) {
2234   // Determine the integer type for the base formula.
2235   const Type *IntTy = Base.getType();
2236   if (!IntTy) return;
2237
2238   // If this Formula already has a scaled register, we can't add another one.
2239   if (Base.AM.Scale != 0) return;
2240
2241   // Check each interesting stride.
2242   for (SmallSetVector<int64_t, 8>::const_iterator
2243        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2244     int64_t Factor = *I;
2245
2246     Base.AM.Scale = Factor;
2247     Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2248     // Check whether this scale is going to be legal.
2249     if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2250                     LU.Kind, LU.AccessTy, TLI)) {
2251       // As a special-case, handle special out-of-loop Basic users specially.
2252       // TODO: Reconsider this special case.
2253       if (LU.Kind == LSRUse::Basic &&
2254           isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2255                      LSRUse::Special, LU.AccessTy, TLI) &&
2256           LU.AllFixupsOutsideLoop)
2257         LU.Kind = LSRUse::Special;
2258       else
2259         continue;
2260     }
2261     // For an ICmpZero, negating a solitary base register won't lead to
2262     // new solutions.
2263     if (LU.Kind == LSRUse::ICmpZero &&
2264         !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2265       continue;
2266     // For each addrec base reg, apply the scale, if possible.
2267     for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2268       if (const SCEVAddRecExpr *AR =
2269             dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2270         const SCEV *FactorS = SE.getIntegerSCEV(Factor, IntTy);
2271         if (FactorS->isZero())
2272           continue;
2273         // Divide out the factor, ignoring high bits, since we'll be
2274         // scaling the value back up in the end.
2275         if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
2276           // TODO: This could be optimized to avoid all the copying.
2277           Formula F = Base;
2278           F.ScaledReg = Quotient;
2279           std::swap(F.BaseRegs[i], F.BaseRegs.back());
2280           F.BaseRegs.pop_back();
2281           (void)InsertFormula(LU, LUIdx, F);
2282         }
2283       }
2284   }
2285 }
2286
2287 /// GenerateTruncates - Generate reuse formulae from different IV types.
2288 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx,
2289                                     Formula Base) {
2290   // This requires TargetLowering to tell us which truncates are free.
2291   if (!TLI) return;
2292
2293   // Don't bother truncating symbolic values.
2294   if (Base.AM.BaseGV) return;
2295
2296   // Determine the integer type for the base formula.
2297   const Type *DstTy = Base.getType();
2298   if (!DstTy) return;
2299   DstTy = SE.getEffectiveSCEVType(DstTy);
2300
2301   for (SmallSetVector<const Type *, 4>::const_iterator
2302        I = Types.begin(), E = Types.end(); I != E; ++I) {
2303     const Type *SrcTy = *I;
2304     if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2305       Formula F = Base;
2306
2307       if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2308       for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2309            JE = F.BaseRegs.end(); J != JE; ++J)
2310         *J = SE.getAnyExtendExpr(*J, SrcTy);
2311
2312       // TODO: This assumes we've done basic processing on all uses and
2313       // have an idea what the register usage is.
2314       if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2315         continue;
2316
2317       (void)InsertFormula(LU, LUIdx, F);
2318     }
2319   }
2320 }
2321
2322 namespace {
2323
2324 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
2325 /// defer modifications so that the search phase doesn't have to worry about
2326 /// the data structures moving underneath it.
2327 struct WorkItem {
2328   size_t LUIdx;
2329   int64_t Imm;
2330   const SCEV *OrigReg;
2331
2332   WorkItem(size_t LI, int64_t I, const SCEV *R)
2333     : LUIdx(LI), Imm(I), OrigReg(R) {}
2334
2335   void print(raw_ostream &OS) const;
2336   void dump() const;
2337 };
2338
2339 }
2340
2341 void WorkItem::print(raw_ostream &OS) const {
2342   OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2343      << " , add offset " << Imm;
2344 }
2345
2346 void WorkItem::dump() const {
2347   print(errs()); errs() << '\n';
2348 }
2349
2350 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2351 /// distance apart and try to form reuse opportunities between them.
2352 void LSRInstance::GenerateCrossUseConstantOffsets() {
2353   // Group the registers by their value without any added constant offset.
2354   typedef std::map<int64_t, const SCEV *> ImmMapTy;
2355   typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2356   RegMapTy Map;
2357   DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2358   SmallVector<const SCEV *, 8> Sequence;
2359   for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2360        I != E; ++I) {
2361     const SCEV *Reg = *I;
2362     int64_t Imm = ExtractImmediate(Reg, SE);
2363     std::pair<RegMapTy::iterator, bool> Pair =
2364       Map.insert(std::make_pair(Reg, ImmMapTy()));
2365     if (Pair.second)
2366       Sequence.push_back(Reg);
2367     Pair.first->second.insert(std::make_pair(Imm, *I));
2368     UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2369   }
2370
2371   // Now examine each set of registers with the same base value. Build up
2372   // a list of work to do and do the work in a separate step so that we're
2373   // not adding formulae and register counts while we're searching.
2374   SmallVector<WorkItem, 32> WorkItems;
2375   SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2376   for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2377        E = Sequence.end(); I != E; ++I) {
2378     const SCEV *Reg = *I;
2379     const ImmMapTy &Imms = Map.find(Reg)->second;
2380
2381     // It's not worthwhile looking for reuse if there's only one offset.
2382     if (Imms.size() == 1)
2383       continue;
2384
2385     DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2386           for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2387                J != JE; ++J)
2388             dbgs() << ' ' << J->first;
2389           dbgs() << '\n');
2390
2391     // Examine each offset.
2392     for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2393          J != JE; ++J) {
2394       const SCEV *OrigReg = J->second;
2395
2396       int64_t JImm = J->first;
2397       const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2398
2399       if (!isa<SCEVConstant>(OrigReg) &&
2400           UsedByIndicesMap[Reg].count() == 1) {
2401         DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2402         continue;
2403       }
2404
2405       // Conservatively examine offsets between this orig reg a few selected
2406       // other orig regs.
2407       ImmMapTy::const_iterator OtherImms[] = {
2408         Imms.begin(), prior(Imms.end()),
2409         Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2410       };
2411       for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2412         ImmMapTy::const_iterator M = OtherImms[i];
2413         if (M == J || M == JE) continue;
2414
2415         // Compute the difference between the two.
2416         int64_t Imm = (uint64_t)JImm - M->first;
2417         for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2418              LUIdx = UsedByIndices.find_next(LUIdx))
2419           // Make a memo of this use, offset, and register tuple.
2420           if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2421             WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
2422       }
2423     }
2424   }
2425
2426   Map.clear();
2427   Sequence.clear();
2428   UsedByIndicesMap.clear();
2429   UniqueItems.clear();
2430
2431   // Now iterate through the worklist and add new formulae.
2432   for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2433        E = WorkItems.end(); I != E; ++I) {
2434     const WorkItem &WI = *I;
2435     size_t LUIdx = WI.LUIdx;
2436     LSRUse &LU = Uses[LUIdx];
2437     int64_t Imm = WI.Imm;
2438     const SCEV *OrigReg = WI.OrigReg;
2439
2440     const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2441     const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2442     unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2443
2444     // TODO: Use a more targeted data structure.
2445     for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2446       Formula F = LU.Formulae[L];
2447       // Use the immediate in the scaled register.
2448       if (F.ScaledReg == OrigReg) {
2449         int64_t Offs = (uint64_t)F.AM.BaseOffs +
2450                        Imm * (uint64_t)F.AM.Scale;
2451         // Don't create 50 + reg(-50).
2452         if (F.referencesReg(SE.getSCEV(
2453                    ConstantInt::get(IntTy, -(uint64_t)Offs))))
2454           continue;
2455         Formula NewF = F;
2456         NewF.AM.BaseOffs = Offs;
2457         if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2458                         LU.Kind, LU.AccessTy, TLI))
2459           continue;
2460         NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2461
2462         // If the new scale is a constant in a register, and adding the constant
2463         // value to the immediate would produce a value closer to zero than the
2464         // immediate itself, then the formula isn't worthwhile.
2465         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2466           if (C->getValue()->getValue().isNegative() !=
2467                 (NewF.AM.BaseOffs < 0) &&
2468               (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2469                 .ule(abs64(NewF.AM.BaseOffs)))
2470             continue;
2471
2472         // OK, looks good.
2473         (void)InsertFormula(LU, LUIdx, NewF);
2474       } else {
2475         // Use the immediate in a base register.
2476         for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2477           const SCEV *BaseReg = F.BaseRegs[N];
2478           if (BaseReg != OrigReg)
2479             continue;
2480           Formula NewF = F;
2481           NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2482           if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2483                           LU.Kind, LU.AccessTy, TLI))
2484             continue;
2485           NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2486
2487           // If the new formula has a constant in a register, and adding the
2488           // constant value to the immediate would produce a value closer to
2489           // zero than the immediate itself, then the formula isn't worthwhile.
2490           for (SmallVectorImpl<const SCEV *>::const_iterator
2491                J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2492                J != JE; ++J)
2493             if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2494               if (C->getValue()->getValue().isNegative() !=
2495                     (NewF.AM.BaseOffs < 0) &&
2496                   C->getValue()->getValue().abs()
2497                     .ule(abs64(NewF.AM.BaseOffs)))
2498                 goto skip_formula;
2499
2500           // Ok, looks good.
2501           (void)InsertFormula(LU, LUIdx, NewF);
2502           break;
2503         skip_formula:;
2504         }
2505       }
2506     }
2507   }
2508 }
2509
2510 /// GenerateAllReuseFormulae - Generate formulae for each use.
2511 void
2512 LSRInstance::GenerateAllReuseFormulae() {
2513   // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
2514   // queries are more precise.
2515   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2516     LSRUse &LU = Uses[LUIdx];
2517     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2518       GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2519     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2520       GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2521   }
2522   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2523     LSRUse &LU = Uses[LUIdx];
2524     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2525       GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2526     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2527       GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2528     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2529       GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2530     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2531       GenerateScales(LU, LUIdx, LU.Formulae[i]);
2532   }
2533   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2534     LSRUse &LU = Uses[LUIdx];
2535     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2536       GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2537   }
2538
2539   GenerateCrossUseConstantOffsets();
2540 }
2541
2542 /// If their are multiple formulae with the same set of registers used
2543 /// by other uses, pick the best one and delete the others.
2544 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2545 #ifndef NDEBUG
2546   bool Changed = false;
2547 #endif
2548
2549   // Collect the best formula for each unique set of shared registers. This
2550   // is reset for each use.
2551   typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2552     BestFormulaeTy;
2553   BestFormulaeTy BestFormulae;
2554
2555   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2556     LSRUse &LU = Uses[LUIdx];
2557     FormulaSorter Sorter(L, LU, SE, DT);
2558
2559     // Clear out the set of used regs; it will be recomputed.
2560     LU.Regs.clear();
2561
2562     for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2563          FIdx != NumForms; ++FIdx) {
2564       Formula &F = LU.Formulae[FIdx];
2565
2566       SmallVector<const SCEV *, 2> Key;
2567       for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2568            JE = F.BaseRegs.end(); J != JE; ++J) {
2569         const SCEV *Reg = *J;
2570         if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2571           Key.push_back(Reg);
2572       }
2573       if (F.ScaledReg &&
2574           RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2575         Key.push_back(F.ScaledReg);
2576       // Unstable sort by host order ok, because this is only used for
2577       // uniquifying.
2578       std::sort(Key.begin(), Key.end());
2579
2580       std::pair<BestFormulaeTy::const_iterator, bool> P =
2581         BestFormulae.insert(std::make_pair(Key, FIdx));
2582       if (!P.second) {
2583         Formula &Best = LU.Formulae[P.first->second];
2584         if (Sorter.operator()(F, Best))
2585           std::swap(F, Best);
2586         DEBUG(dbgs() << "Filtering out "; F.print(dbgs());
2587               dbgs() << "\n"
2588                         "  in favor of "; Best.print(dbgs());
2589               dbgs() << '\n');
2590 #ifndef NDEBUG
2591         Changed = true;
2592 #endif
2593         std::swap(F, LU.Formulae.back());
2594         LU.Formulae.pop_back();
2595         --FIdx;
2596         --NumForms;
2597         continue;
2598       }
2599       if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2600       LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2601     }
2602     BestFormulae.clear();
2603   }
2604
2605   DEBUG(if (Changed) {
2606           dbgs() << "\n"
2607                     "After filtering out undesirable candidates:\n";
2608           print_uses(dbgs());
2609         });
2610 }
2611
2612 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
2613 /// formulae to choose from, use some rough heuristics to prune down the number
2614 /// of formulae. This keeps the main solver from taking an extraordinary amount
2615 /// of time in some worst-case scenarios.
2616 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
2617   // This is a rough guess that seems to work fairly well.
2618   const size_t Limit = UINT16_MAX;
2619
2620   SmallPtrSet<const SCEV *, 4> Taken;
2621   for (;;) {
2622     // Estimate the worst-case number of solutions we might consider. We almost
2623     // never consider this many solutions because we prune the search space,
2624     // but the pruning isn't always sufficient.
2625     uint32_t Power = 1;
2626     for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2627          E = Uses.end(); I != E; ++I) {
2628       size_t FSize = I->Formulae.size();
2629       if (FSize >= Limit) {
2630         Power = Limit;
2631         break;
2632       }
2633       Power *= FSize;
2634       if (Power >= Limit)
2635         break;
2636     }
2637     if (Power < Limit)
2638       break;
2639
2640     // Ok, we have too many of formulae on our hands to conveniently handle.
2641     // Use a rough heuristic to thin out the list.
2642
2643     // Pick the register which is used by the most LSRUses, which is likely
2644     // to be a good reuse register candidate.
2645     const SCEV *Best = 0;
2646     unsigned BestNum = 0;
2647     for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2648          I != E; ++I) {
2649       const SCEV *Reg = *I;
2650       if (Taken.count(Reg))
2651         continue;
2652       if (!Best)
2653         Best = Reg;
2654       else {
2655         unsigned Count = RegUses.getUsedByIndices(Reg).count();
2656         if (Count > BestNum) {
2657           Best = Reg;
2658           BestNum = Count;
2659         }
2660       }
2661     }
2662
2663     DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
2664                  << " will yield profitable reuse.\n");
2665     Taken.insert(Best);
2666
2667     // In any use with formulae which references this register, delete formulae
2668     // which don't reference it.
2669     for (SmallVectorImpl<LSRUse>::iterator I = Uses.begin(),
2670          E = Uses.end(); I != E; ++I) {
2671       LSRUse &LU = *I;
2672       if (!LU.Regs.count(Best)) continue;
2673
2674       // Clear out the set of used regs; it will be recomputed.
2675       LU.Regs.clear();
2676
2677       for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2678         Formula &F = LU.Formulae[i];
2679         if (!F.referencesReg(Best)) {
2680           DEBUG(dbgs() << "  Deleting "; F.print(dbgs()); dbgs() << '\n');
2681           std::swap(LU.Formulae.back(), F);
2682           LU.Formulae.pop_back();
2683           --e;
2684           --i;
2685           continue;
2686         }
2687
2688         if (F.ScaledReg) LU.Regs.insert(F.ScaledReg);
2689         LU.Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
2690       }
2691     }
2692
2693     DEBUG(dbgs() << "After pre-selection:\n";
2694           print_uses(dbgs()));
2695   }
2696 }
2697
2698 /// SolveRecurse - This is the recursive solver.
2699 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2700                                Cost &SolutionCost,
2701                                SmallVectorImpl<const Formula *> &Workspace,
2702                                const Cost &CurCost,
2703                                const SmallPtrSet<const SCEV *, 16> &CurRegs,
2704                                DenseSet<const SCEV *> &VisitedRegs) const {
2705   // Some ideas:
2706   //  - prune more:
2707   //    - use more aggressive filtering
2708   //    - sort the formula so that the most profitable solutions are found first
2709   //    - sort the uses too
2710   //  - search faster:
2711   //    - don't compute a cost, and then compare. compare while computing a cost
2712   //      and bail early.
2713   //    - track register sets with SmallBitVector
2714
2715   const LSRUse &LU = Uses[Workspace.size()];
2716
2717   // If this use references any register that's already a part of the
2718   // in-progress solution, consider it a requirement that a formula must
2719   // reference that register in order to be considered. This prunes out
2720   // unprofitable searching.
2721   SmallSetVector<const SCEV *, 4> ReqRegs;
2722   for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
2723        E = CurRegs.end(); I != E; ++I)
2724     if (LU.Regs.count(*I))
2725       ReqRegs.insert(*I);
2726
2727   bool AnySatisfiedReqRegs = false;
2728   SmallPtrSet<const SCEV *, 16> NewRegs;
2729   Cost NewCost;
2730 retry:
2731   for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2732        E = LU.Formulae.end(); I != E; ++I) {
2733     const Formula &F = *I;
2734
2735     // Ignore formulae which do not use any of the required registers.
2736     for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
2737          JE = ReqRegs.end(); J != JE; ++J) {
2738       const SCEV *Reg = *J;
2739       if ((!F.ScaledReg || F.ScaledReg != Reg) &&
2740           std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
2741           F.BaseRegs.end())
2742         goto skip;
2743     }
2744     AnySatisfiedReqRegs = true;
2745
2746     // Evaluate the cost of the current formula. If it's already worse than
2747     // the current best, prune the search at that point.
2748     NewCost = CurCost;
2749     NewRegs = CurRegs;
2750     NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
2751     if (NewCost < SolutionCost) {
2752       Workspace.push_back(&F);
2753       if (Workspace.size() != Uses.size()) {
2754         SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
2755                      NewRegs, VisitedRegs);
2756         if (F.getNumRegs() == 1 && Workspace.size() == 1)
2757           VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
2758       } else {
2759         DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
2760               dbgs() << ". Regs:";
2761               for (SmallPtrSet<const SCEV *, 16>::const_iterator
2762                    I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
2763                 dbgs() << ' ' << **I;
2764               dbgs() << '\n');
2765
2766         SolutionCost = NewCost;
2767         Solution = Workspace;
2768       }
2769       Workspace.pop_back();
2770     }
2771   skip:;
2772   }
2773
2774   // If none of the formulae had all of the required registers, relax the
2775   // constraint so that we don't exclude all formulae.
2776   if (!AnySatisfiedReqRegs) {
2777     ReqRegs.clear();
2778     goto retry;
2779   }
2780 }
2781
2782 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
2783   SmallVector<const Formula *, 8> Workspace;
2784   Cost SolutionCost;
2785   SolutionCost.Loose();
2786   Cost CurCost;
2787   SmallPtrSet<const SCEV *, 16> CurRegs;
2788   DenseSet<const SCEV *> VisitedRegs;
2789   Workspace.reserve(Uses.size());
2790
2791   SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
2792                CurRegs, VisitedRegs);
2793
2794   // Ok, we've now made all our decisions.
2795   DEBUG(dbgs() << "\n"
2796                   "The chosen solution requires "; SolutionCost.print(dbgs());
2797         dbgs() << ":\n";
2798         for (size_t i = 0, e = Uses.size(); i != e; ++i) {
2799           dbgs() << "  ";
2800           Uses[i].print(dbgs());
2801           dbgs() << "\n"
2802                     "    ";
2803           Solution[i]->print(dbgs());
2804           dbgs() << '\n';
2805         });
2806 }
2807
2808 /// getImmediateDominator - A handy utility for the specific DominatorTree
2809 /// query that we need here.
2810 ///
2811 static BasicBlock *getImmediateDominator(BasicBlock *BB, DominatorTree &DT) {
2812   DomTreeNode *Node = DT.getNode(BB);
2813   if (!Node) return 0;
2814   Node = Node->getIDom();
2815   if (!Node) return 0;
2816   return Node->getBlock();
2817 }
2818
2819 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
2820 /// the dominator tree far as we can go while still being dominated by the
2821 /// input positions. This helps canonicalize the insert position, which
2822 /// encourages sharing.
2823 BasicBlock::iterator
2824 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
2825                                  const SmallVectorImpl<Instruction *> &Inputs)
2826                                                                          const {
2827   for (;;) {
2828     const Loop *IPLoop = LI.getLoopFor(IP->getParent());
2829     unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
2830
2831     BasicBlock *IDom;
2832     for (BasicBlock *Rung = IP->getParent(); ; Rung = IDom) {
2833       IDom = getImmediateDominator(Rung, DT);
2834       if (!IDom) return IP;
2835
2836       // Don't climb into a loop though.
2837       const Loop *IDomLoop = LI.getLoopFor(IDom);
2838       unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
2839       if (IDomDepth <= IPLoopDepth &&
2840           (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
2841         break;
2842     }
2843
2844     bool AllDominate = true;
2845     Instruction *BetterPos = 0;
2846     Instruction *Tentative = IDom->getTerminator();
2847     for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
2848          E = Inputs.end(); I != E; ++I) {
2849       Instruction *Inst = *I;
2850       if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
2851         AllDominate = false;
2852         break;
2853       }
2854       // Attempt to find an insert position in the middle of the block,
2855       // instead of at the end, so that it can be used for other expansions.
2856       if (IDom == Inst->getParent() &&
2857           (!BetterPos || DT.dominates(BetterPos, Inst)))
2858         BetterPos = next(BasicBlock::iterator(Inst));
2859     }
2860     if (!AllDominate)
2861       break;
2862     if (BetterPos)
2863       IP = BetterPos;
2864     else
2865       IP = Tentative;
2866   }
2867
2868   return IP;
2869 }
2870
2871 /// AdjustInsertPositionForExpand - Determine an input position which will be
2872 /// dominated by the operands and which will dominate the result.
2873 BasicBlock::iterator
2874 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2875                                            const LSRFixup &LF,
2876                                            const LSRUse &LU) const {
2877   // Collect some instructions which must be dominated by the
2878   // expanding replacement. These must be dominated by any operands that
2879   // will be required in the expansion.
2880   SmallVector<Instruction *, 4> Inputs;
2881   if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
2882     Inputs.push_back(I);
2883   if (LU.Kind == LSRUse::ICmpZero)
2884     if (Instruction *I =
2885           dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
2886       Inputs.push_back(I);
2887   if (LF.PostIncLoops.count(L)) {
2888     if (LF.isUseFullyOutsideLoop(L))
2889       Inputs.push_back(L->getLoopLatch()->getTerminator());
2890     else
2891       Inputs.push_back(IVIncInsertPos);
2892   }
2893   // The expansion must also be dominated by the increment positions of any
2894   // loops it for which it is using post-inc mode.
2895   for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
2896        E = LF.PostIncLoops.end(); I != E; ++I) {
2897     const Loop *PIL = *I;
2898     if (PIL == L) continue;
2899
2900     // Be dominated by the loop exit.
2901     SmallVector<BasicBlock *, 4> ExitingBlocks;
2902     PIL->getExitingBlocks(ExitingBlocks);
2903     if (!ExitingBlocks.empty()) {
2904       BasicBlock *BB = ExitingBlocks[0];
2905       for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
2906         BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
2907       Inputs.push_back(BB->getTerminator());
2908     }
2909   }
2910
2911   // Then, climb up the immediate dominator tree as far as we can go while
2912   // still being dominated by the input positions.
2913   IP = HoistInsertPosition(IP, Inputs);
2914
2915   // Don't insert instructions before PHI nodes.
2916   while (isa<PHINode>(IP)) ++IP;
2917
2918   // Ignore debug intrinsics.
2919   while (isa<DbgInfoIntrinsic>(IP)) ++IP;
2920
2921   return IP;
2922 }
2923
2924 Value *LSRInstance::Expand(const LSRFixup &LF,
2925                            const Formula &F,
2926                            BasicBlock::iterator IP,
2927                            SCEVExpander &Rewriter,
2928                            SmallVectorImpl<WeakVH> &DeadInsts) const {
2929   const LSRUse &LU = Uses[LF.LUIdx];
2930
2931   // Determine an input position which will be dominated by the operands and
2932   // which will dominate the result.
2933   IP = AdjustInsertPositionForExpand(IP, LF, LU);
2934
2935   // Inform the Rewriter if we have a post-increment use, so that it can
2936   // perform an advantageous expansion.
2937   Rewriter.setPostInc(LF.PostIncLoops);
2938
2939   // This is the type that the user actually needs.
2940   const Type *OpTy = LF.OperandValToReplace->getType();
2941   // This will be the type that we'll initially expand to.
2942   const Type *Ty = F.getType();
2943   if (!Ty)
2944     // No type known; just expand directly to the ultimate type.
2945     Ty = OpTy;
2946   else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
2947     // Expand directly to the ultimate type if it's the right size.
2948     Ty = OpTy;
2949   // This is the type to do integer arithmetic in.
2950   const Type *IntTy = SE.getEffectiveSCEVType(Ty);
2951
2952   // Build up a list of operands to add together to form the full base.
2953   SmallVector<const SCEV *, 8> Ops;
2954
2955   // Expand the BaseRegs portion.
2956   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2957        E = F.BaseRegs.end(); I != E; ++I) {
2958     const SCEV *Reg = *I;
2959     assert(!Reg->isZero() && "Zero allocated in a base register!");
2960
2961     // If we're expanding for a post-inc user, make the post-inc adjustment.
2962     PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
2963     Reg = TransformForPostIncUse(Denormalize, Reg,
2964                                  LF.UserInst, LF.OperandValToReplace,
2965                                  Loops, SE, DT);
2966
2967     Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
2968   }
2969
2970   // Flush the operand list to suppress SCEVExpander hoisting.
2971   if (!Ops.empty()) {
2972     Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
2973     Ops.clear();
2974     Ops.push_back(SE.getUnknown(FullV));
2975   }
2976
2977   // Expand the ScaledReg portion.
2978   Value *ICmpScaledV = 0;
2979   if (F.AM.Scale != 0) {
2980     const SCEV *ScaledS = F.ScaledReg;
2981
2982     // If we're expanding for a post-inc user, make the post-inc adjustment.
2983     PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
2984     ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
2985                                      LF.UserInst, LF.OperandValToReplace,
2986                                      Loops, SE, DT);
2987
2988     if (LU.Kind == LSRUse::ICmpZero) {
2989       // An interesting way of "folding" with an icmp is to use a negated
2990       // scale, which we'll implement by inserting it into the other operand
2991       // of the icmp.
2992       assert(F.AM.Scale == -1 &&
2993              "The only scale supported by ICmpZero uses is -1!");
2994       ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
2995     } else {
2996       // Otherwise just expand the scaled register and an explicit scale,
2997       // which is expected to be matched as part of the address.
2998       ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
2999       ScaledS = SE.getMulExpr(ScaledS,
3000                               SE.getIntegerSCEV(F.AM.Scale,
3001                                                 ScaledS->getType()));
3002       Ops.push_back(ScaledS);
3003
3004       // Flush the operand list to suppress SCEVExpander hoisting.
3005       Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3006       Ops.clear();
3007       Ops.push_back(SE.getUnknown(FullV));
3008     }
3009   }
3010
3011   // Expand the GV portion.
3012   if (F.AM.BaseGV) {
3013     Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3014
3015     // Flush the operand list to suppress SCEVExpander hoisting.
3016     Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3017     Ops.clear();
3018     Ops.push_back(SE.getUnknown(FullV));
3019   }
3020
3021   // Expand the immediate portion.
3022   int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3023   if (Offset != 0) {
3024     if (LU.Kind == LSRUse::ICmpZero) {
3025       // The other interesting way of "folding" with an ICmpZero is to use a
3026       // negated immediate.
3027       if (!ICmpScaledV)
3028         ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3029       else {
3030         Ops.push_back(SE.getUnknown(ICmpScaledV));
3031         ICmpScaledV = ConstantInt::get(IntTy, Offset);
3032       }
3033     } else {
3034       // Just add the immediate values. These again are expected to be matched
3035       // as part of the address.
3036       Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
3037     }
3038   }
3039
3040   // Emit instructions summing all the operands.
3041   const SCEV *FullS = Ops.empty() ?
3042                       SE.getIntegerSCEV(0, IntTy) :
3043                       SE.getAddExpr(Ops);
3044   Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3045
3046   // We're done expanding now, so reset the rewriter.
3047   Rewriter.clearPostInc();
3048
3049   // An ICmpZero Formula represents an ICmp which we're handling as a
3050   // comparison against zero. Now that we've expanded an expression for that
3051   // form, update the ICmp's other operand.
3052   if (LU.Kind == LSRUse::ICmpZero) {
3053     ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3054     DeadInsts.push_back(CI->getOperand(1));
3055     assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3056                            "a scale at the same time!");
3057     if (F.AM.Scale == -1) {
3058       if (ICmpScaledV->getType() != OpTy) {
3059         Instruction *Cast =
3060           CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3061                                                    OpTy, false),
3062                            ICmpScaledV, OpTy, "tmp", CI);
3063         ICmpScaledV = Cast;
3064       }
3065       CI->setOperand(1, ICmpScaledV);
3066     } else {
3067       assert(F.AM.Scale == 0 &&
3068              "ICmp does not support folding a global value and "
3069              "a scale at the same time!");
3070       Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3071                                            -(uint64_t)Offset);
3072       if (C->getType() != OpTy)
3073         C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3074                                                           OpTy, false),
3075                                   C, OpTy);
3076
3077       CI->setOperand(1, C);
3078     }
3079   }
3080
3081   return FullV;
3082 }
3083
3084 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3085 /// of their operands effectively happens in their predecessor blocks, so the
3086 /// expression may need to be expanded in multiple places.
3087 void LSRInstance::RewriteForPHI(PHINode *PN,
3088                                 const LSRFixup &LF,
3089                                 const Formula &F,
3090                                 SCEVExpander &Rewriter,
3091                                 SmallVectorImpl<WeakVH> &DeadInsts,
3092                                 Pass *P) const {
3093   DenseMap<BasicBlock *, Value *> Inserted;
3094   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3095     if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3096       BasicBlock *BB = PN->getIncomingBlock(i);
3097
3098       // If this is a critical edge, split the edge so that we do not insert
3099       // the code on all predecessor/successor paths.  We do this unless this
3100       // is the canonical backedge for this loop, which complicates post-inc
3101       // users.
3102       if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3103           !isa<IndirectBrInst>(BB->getTerminator()) &&
3104           (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3105         // Split the critical edge.
3106         BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3107
3108         // If PN is outside of the loop and BB is in the loop, we want to
3109         // move the block to be immediately before the PHI block, not
3110         // immediately after BB.
3111         if (L->contains(BB) && !L->contains(PN))
3112           NewBB->moveBefore(PN->getParent());
3113
3114         // Splitting the edge can reduce the number of PHI entries we have.
3115         e = PN->getNumIncomingValues();
3116         BB = NewBB;
3117         i = PN->getBasicBlockIndex(BB);
3118       }
3119
3120       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3121         Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3122       if (!Pair.second)
3123         PN->setIncomingValue(i, Pair.first->second);
3124       else {
3125         Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
3126
3127         // If this is reuse-by-noop-cast, insert the noop cast.
3128         const Type *OpTy = LF.OperandValToReplace->getType();
3129         if (FullV->getType() != OpTy)
3130           FullV =
3131             CastInst::Create(CastInst::getCastOpcode(FullV, false,
3132                                                      OpTy, false),
3133                              FullV, LF.OperandValToReplace->getType(),
3134                              "tmp", BB->getTerminator());
3135
3136         PN->setIncomingValue(i, FullV);
3137         Pair.first->second = FullV;
3138       }
3139     }
3140 }
3141
3142 /// Rewrite - Emit instructions for the leading candidate expression for this
3143 /// LSRUse (this is called "expanding"), and update the UserInst to reference
3144 /// the newly expanded value.
3145 void LSRInstance::Rewrite(const LSRFixup &LF,
3146                           const Formula &F,
3147                           SCEVExpander &Rewriter,
3148                           SmallVectorImpl<WeakVH> &DeadInsts,
3149                           Pass *P) const {
3150   // First, find an insertion point that dominates UserInst. For PHI nodes,
3151   // find the nearest block which dominates all the relevant uses.
3152   if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
3153     RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
3154   } else {
3155     Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
3156
3157     // If this is reuse-by-noop-cast, insert the noop cast.
3158     const Type *OpTy = LF.OperandValToReplace->getType();
3159     if (FullV->getType() != OpTy) {
3160       Instruction *Cast =
3161         CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3162                          FullV, OpTy, "tmp", LF.UserInst);
3163       FullV = Cast;
3164     }
3165
3166     // Update the user. ICmpZero is handled specially here (for now) because
3167     // Expand may have updated one of the operands of the icmp already, and
3168     // its new value may happen to be equal to LF.OperandValToReplace, in
3169     // which case doing replaceUsesOfWith leads to replacing both operands
3170     // with the same value. TODO: Reorganize this.
3171     if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3172       LF.UserInst->setOperand(0, FullV);
3173     else
3174       LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3175   }
3176
3177   DeadInsts.push_back(LF.OperandValToReplace);
3178 }
3179
3180 void
3181 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3182                                Pass *P) {
3183   // Keep track of instructions we may have made dead, so that
3184   // we can remove them after we are done working.
3185   SmallVector<WeakVH, 16> DeadInsts;
3186
3187   SCEVExpander Rewriter(SE);
3188   Rewriter.disableCanonicalMode();
3189   Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3190
3191   // Expand the new value definitions and update the users.
3192   for (size_t i = 0, e = Fixups.size(); i != e; ++i) {
3193     size_t LUIdx = Fixups[i].LUIdx;
3194
3195     Rewrite(Fixups[i], *Solution[LUIdx], Rewriter, DeadInsts, P);
3196
3197     Changed = true;
3198   }
3199
3200   // Clean up after ourselves. This must be done before deleting any
3201   // instructions.
3202   Rewriter.clear();
3203
3204   Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3205 }
3206
3207 LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3208   : IU(P->getAnalysis<IVUsers>()),
3209     SE(P->getAnalysis<ScalarEvolution>()),
3210     DT(P->getAnalysis<DominatorTree>()),
3211     LI(P->getAnalysis<LoopInfo>()),
3212     TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
3213
3214   // If LoopSimplify form is not available, stay out of trouble.
3215   if (!L->isLoopSimplifyForm()) return;
3216
3217   // If there's no interesting work to be done, bail early.
3218   if (IU.empty()) return;
3219
3220   DEBUG(dbgs() << "\nLSR on loop ";
3221         WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3222         dbgs() << ":\n");
3223
3224   /// OptimizeShadowIV - If IV is used in a int-to-float cast
3225   /// inside the loop then try to eliminate the cast operation.
3226   OptimizeShadowIV();
3227
3228   // Change loop terminating condition to use the postinc iv when possible.
3229   Changed |= OptimizeLoopTermCond();
3230
3231   CollectInterestingTypesAndFactors();
3232   CollectFixupsAndInitialFormulae();
3233   CollectLoopInvariantFixupsAndFormulae();
3234
3235   DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3236         print_uses(dbgs()));
3237
3238   // Now use the reuse data to generate a bunch of interesting ways
3239   // to formulate the values needed for the uses.
3240   GenerateAllReuseFormulae();
3241
3242   DEBUG(dbgs() << "\n"
3243                   "After generating reuse formulae:\n";
3244         print_uses(dbgs()));
3245
3246   FilterOutUndesirableDedicatedRegisters();
3247   NarrowSearchSpaceUsingHeuristics();
3248
3249   SmallVector<const Formula *, 8> Solution;
3250   Solve(Solution);
3251   assert(Solution.size() == Uses.size() && "Malformed solution!");
3252
3253   // Release memory that is no longer needed.
3254   Factors.clear();
3255   Types.clear();
3256   RegUses.clear();
3257
3258 #ifndef NDEBUG
3259   // Formulae should be legal.
3260   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3261        E = Uses.end(); I != E; ++I) {
3262      const LSRUse &LU = *I;
3263      for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3264           JE = LU.Formulae.end(); J != JE; ++J)
3265         assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3266                           LU.Kind, LU.AccessTy, TLI) &&
3267                "Illegal formula generated!");
3268   };
3269 #endif
3270
3271   // Now that we've decided what we want, make it so.
3272   ImplementSolution(Solution, P);
3273 }
3274
3275 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3276   if (Factors.empty() && Types.empty()) return;
3277
3278   OS << "LSR has identified the following interesting factors and types: ";
3279   bool First = true;
3280
3281   for (SmallSetVector<int64_t, 8>::const_iterator
3282        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3283     if (!First) OS << ", ";
3284     First = false;
3285     OS << '*' << *I;
3286   }
3287
3288   for (SmallSetVector<const Type *, 4>::const_iterator
3289        I = Types.begin(), E = Types.end(); I != E; ++I) {
3290     if (!First) OS << ", ";
3291     First = false;
3292     OS << '(' << **I << ')';
3293   }
3294   OS << '\n';
3295 }
3296
3297 void LSRInstance::print_fixups(raw_ostream &OS) const {
3298   OS << "LSR is examining the following fixup sites:\n";
3299   for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3300        E = Fixups.end(); I != E; ++I) {
3301     const LSRFixup &LF = *I;
3302     dbgs() << "  ";
3303     LF.print(OS);
3304     OS << '\n';
3305   }
3306 }
3307
3308 void LSRInstance::print_uses(raw_ostream &OS) const {
3309   OS << "LSR is examining the following uses:\n";
3310   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3311        E = Uses.end(); I != E; ++I) {
3312     const LSRUse &LU = *I;
3313     dbgs() << "  ";
3314     LU.print(OS);
3315     OS << '\n';
3316     for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3317          JE = LU.Formulae.end(); J != JE; ++J) {
3318       OS << "    ";
3319       J->print(OS);
3320       OS << '\n';
3321     }
3322   }
3323 }
3324
3325 void LSRInstance::print(raw_ostream &OS) const {
3326   print_factors_and_types(OS);
3327   print_fixups(OS);
3328   print_uses(OS);
3329 }
3330
3331 void LSRInstance::dump() const {
3332   print(errs()); errs() << '\n';
3333 }
3334
3335 namespace {
3336
3337 class LoopStrengthReduce : public LoopPass {
3338   /// TLI - Keep a pointer of a TargetLowering to consult for determining
3339   /// transformation profitability.
3340   const TargetLowering *const TLI;
3341
3342 public:
3343   static char ID; // Pass ID, replacement for typeid
3344   explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3345
3346 private:
3347   bool runOnLoop(Loop *L, LPPassManager &LPM);
3348   void getAnalysisUsage(AnalysisUsage &AU) const;
3349 };
3350
3351 }
3352
3353 char LoopStrengthReduce::ID = 0;
3354 static RegisterPass<LoopStrengthReduce>
3355 X("loop-reduce", "Loop Strength Reduction");
3356
3357 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3358   return new LoopStrengthReduce(TLI);
3359 }
3360
3361 LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3362   : LoopPass(&ID), TLI(tli) {}
3363
3364 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3365   // We split critical edges, so we change the CFG.  However, we do update
3366   // many analyses if they are around.
3367   AU.addPreservedID(LoopSimplifyID);
3368   AU.addPreserved("domfrontier");
3369
3370   AU.addRequired<LoopInfo>();
3371   AU.addPreserved<LoopInfo>();
3372   AU.addRequiredID(LoopSimplifyID);
3373   AU.addRequired<DominatorTree>();
3374   AU.addPreserved<DominatorTree>();
3375   AU.addRequired<ScalarEvolution>();
3376   AU.addPreserved<ScalarEvolution>();
3377   AU.addRequired<IVUsers>();
3378   AU.addPreserved<IVUsers>();
3379 }
3380
3381 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3382   bool Changed = false;
3383
3384   // Run the main LSR transformation.
3385   Changed |= LSRInstance(TLI, L, this).getChanged();
3386
3387   // At this point, it is worth checking to see if any recurrence PHIs are also
3388   // dead, so that we can remove them as well.
3389   Changed |= DeleteDeadPHIs(L->getHeader());
3390
3391   return Changed;
3392 }