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