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