Revert r70645 for now; it's causing a variety of regressions.
[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 pass performs a strength reduction on array references inside loops that
11 // have as one or more of their components the loop induction variable.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "loop-reduce"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Type.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolutionExpander.h"
26 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ValueHandle.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include <algorithm>
38 using namespace llvm;
39
40 STATISTIC(NumReduced ,    "Number of IV uses strength reduced");
41 STATISTIC(NumInserted,    "Number of PHIs inserted");
42 STATISTIC(NumVariable,    "Number of PHIs with variable strides");
43 STATISTIC(NumEliminated,  "Number of strides eliminated");
44 STATISTIC(NumShadow,      "Number of Shadow IVs optimized");
45 STATISTIC(NumImmSunk,     "Number of common expr immediates sunk into uses");
46
47 static cl::opt<bool> EnableFullLSRMode("enable-full-lsr",
48                                        cl::init(false),
49                                        cl::Hidden);
50
51 namespace {
52
53   struct BasedUser;
54
55   /// IVStrideUse - Keep track of one use of a strided induction variable, where
56   /// the stride is stored externally.  The Offset member keeps track of the 
57   /// offset from the IV, User is the actual user of the operand, and
58   /// 'OperandValToReplace' is the operand of the User that is the use.
59   struct VISIBILITY_HIDDEN IVStrideUse {
60     SCEVHandle Offset;
61     Instruction *User;
62     Value *OperandValToReplace;
63
64     // isUseOfPostIncrementedValue - True if this should use the
65     // post-incremented version of this IV, not the preincremented version.
66     // This can only be set in special cases, such as the terminating setcc
67     // instruction for a loop or uses dominated by the loop.
68     bool isUseOfPostIncrementedValue;
69     
70     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
71       : Offset(Offs), User(U), OperandValToReplace(O),
72         isUseOfPostIncrementedValue(false) {}
73   };
74   
75   /// IVUsersOfOneStride - This structure keeps track of all instructions that
76   /// have an operand that is based on the trip count multiplied by some stride.
77   /// The stride for all of these users is common and kept external to this
78   /// structure.
79   struct VISIBILITY_HIDDEN IVUsersOfOneStride {
80     /// Users - Keep track of all of the users of this stride as well as the
81     /// initial value and the operand that uses the IV.
82     std::vector<IVStrideUse> Users;
83     
84     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
85       Users.push_back(IVStrideUse(Offset, User, Operand));
86     }
87   };
88
89   /// IVInfo - This structure keeps track of one IV expression inserted during
90   /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
91   /// well as the PHI node and increment value created for rewrite.
92   struct VISIBILITY_HIDDEN IVExpr {
93     SCEVHandle  Stride;
94     SCEVHandle  Base;
95     PHINode    *PHI;
96
97     IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi)
98       : Stride(stride), Base(base), PHI(phi) {}
99   };
100
101   /// IVsOfOneStride - This structure keeps track of all IV expression inserted
102   /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
103   struct VISIBILITY_HIDDEN IVsOfOneStride {
104     std::vector<IVExpr> IVs;
105
106     void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI) {
107       IVs.push_back(IVExpr(Stride, Base, PHI));
108     }
109   };
110
111   class VISIBILITY_HIDDEN LoopStrengthReduce : public LoopPass {
112     LoopInfo *LI;
113     DominatorTree *DT;
114     ScalarEvolution *SE;
115     bool Changed;
116
117     /// IVUsesByStride - Keep track of all uses of induction variables that we
118     /// are interested in.  The key of the map is the stride of the access.
119     std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
120
121     /// IVsByStride - Keep track of all IVs that have been inserted for a
122     /// particular stride.
123     std::map<SCEVHandle, IVsOfOneStride> IVsByStride;
124
125     /// StrideOrder - An ordering of the keys in IVUsesByStride that is stable:
126     /// We use this to iterate over the IVUsesByStride collection without being
127     /// dependent on random ordering of pointers in the process.
128     SmallVector<SCEVHandle, 16> StrideOrder;
129
130     /// DeadInsts - Keep track of instructions we may have made dead, so that
131     /// we can remove them after we are done working.
132     SmallVector<Instruction*, 16> DeadInsts;
133
134     /// TLI - Keep a pointer of a TargetLowering to consult for determining
135     /// transformation profitability.
136     const TargetLowering *TLI;
137
138   public:
139     static char ID; // Pass ID, replacement for typeid
140     explicit LoopStrengthReduce(const TargetLowering *tli = NULL) : 
141       LoopPass(&ID), TLI(tli) {
142     }
143
144     bool runOnLoop(Loop *L, LPPassManager &LPM);
145
146     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
147       // We split critical edges, so we change the CFG.  However, we do update
148       // many analyses if they are around.
149       AU.addPreservedID(LoopSimplifyID);
150       AU.addPreserved<LoopInfo>();
151       AU.addPreserved<DominanceFrontier>();
152       AU.addPreserved<DominatorTree>();
153
154       AU.addRequiredID(LoopSimplifyID);
155       AU.addRequired<LoopInfo>();
156       AU.addRequired<DominatorTree>();
157       AU.addRequired<ScalarEvolution>();
158       AU.addPreserved<ScalarEvolution>();
159     }
160
161   private:
162     bool AddUsersIfInteresting(Instruction *I, Loop *L,
163                                SmallPtrSet<Instruction*,16> &Processed);
164     ICmpInst *ChangeCompareStride(Loop *L, ICmpInst *Cond,
165                                   IVStrideUse* &CondUse,
166                                   const SCEVHandle* &CondStride);
167     void OptimizeIndvars(Loop *L);
168
169     /// OptimizeShadowIV - If IV is used in a int-to-float cast
170     /// inside the loop then try to eliminate the cast opeation.
171     void OptimizeShadowIV(Loop *L);
172
173     /// OptimizeSMax - Rewrite the loop's terminating condition
174     /// if it uses an smax computation.
175     ICmpInst *OptimizeSMax(Loop *L, ICmpInst *Cond,
176                            IVStrideUse* &CondUse);
177
178     bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
179                            const SCEVHandle *&CondStride);
180     bool RequiresTypeConversion(const Type *Ty, const Type *NewTy);
181     SCEVHandle CheckForIVReuse(bool, bool, bool, const SCEVHandle&,
182                              IVExpr&, const Type*,
183                              const std::vector<BasedUser>& UsersToProcess);
184     bool ValidStride(bool, int64_t,
185                      const std::vector<BasedUser>& UsersToProcess);
186     SCEVHandle CollectIVUsers(const SCEVHandle &Stride,
187                               IVUsersOfOneStride &Uses,
188                               Loop *L,
189                               bool &AllUsesAreAddresses,
190                               bool &AllUsesAreOutsideLoop,
191                               std::vector<BasedUser> &UsersToProcess);
192     bool ShouldUseFullStrengthReductionMode(
193                                 const std::vector<BasedUser> &UsersToProcess,
194                                 const Loop *L,
195                                 bool AllUsesAreAddresses,
196                                 SCEVHandle Stride);
197     void PrepareToStrengthReduceFully(
198                              std::vector<BasedUser> &UsersToProcess,
199                              SCEVHandle Stride,
200                              SCEVHandle CommonExprs,
201                              const Loop *L,
202                              SCEVExpander &PreheaderRewriter);
203     void PrepareToStrengthReduceFromSmallerStride(
204                                          std::vector<BasedUser> &UsersToProcess,
205                                          Value *CommonBaseV,
206                                          const IVExpr &ReuseIV,
207                                          Instruction *PreInsertPt);
208     void PrepareToStrengthReduceWithNewPhi(
209                                   std::vector<BasedUser> &UsersToProcess,
210                                   SCEVHandle Stride,
211                                   SCEVHandle CommonExprs,
212                                   Value *CommonBaseV,
213                                   const Loop *L,
214                                   SCEVExpander &PreheaderRewriter);
215     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
216                                       IVUsersOfOneStride &Uses,
217                                       Loop *L);
218     void DeleteTriviallyDeadInstructions();
219   };
220 }
221
222 char LoopStrengthReduce::ID = 0;
223 static RegisterPass<LoopStrengthReduce>
224 X("loop-reduce", "Loop Strength Reduction");
225
226 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
227   return new LoopStrengthReduce(TLI);
228 }
229
230 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
231 /// specified set are trivially dead, delete them and see if this makes any of
232 /// their operands subsequently dead.
233 void LoopStrengthReduce::DeleteTriviallyDeadInstructions() {
234   if (DeadInsts.empty()) return;
235   
236   // Sort the deadinsts list so that we can trivially eliminate duplicates as we
237   // go.  The code below never adds a non-dead instruction to the worklist, but
238   // callers may not be so careful.
239   array_pod_sort(DeadInsts.begin(), DeadInsts.end());
240
241   // Drop duplicate instructions and those with uses.
242   for (unsigned i = 0, e = DeadInsts.size()-1; i < e; ++i) {
243     Instruction *I = DeadInsts[i];
244     if (!I->use_empty()) DeadInsts[i] = 0;
245     while (i != e && DeadInsts[i+1] == I)
246       DeadInsts[++i] = 0;
247   }
248   
249   while (!DeadInsts.empty()) {
250     Instruction *I = DeadInsts.back();
251     DeadInsts.pop_back();
252     
253     if (I == 0 || !isInstructionTriviallyDead(I))
254       continue;
255
256     SE->deleteValueFromRecords(I);
257
258     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
259       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
260         *OI = 0;
261         if (U->use_empty())
262           DeadInsts.push_back(U);
263       }
264     }
265     
266     I->eraseFromParent();
267     Changed = true;
268   }
269 }
270
271 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a 
272 /// subexpression that is an AddRec from a loop other than L.  An outer loop 
273 /// of L is OK, but not an inner loop nor a disjoint loop.
274 static bool containsAddRecFromDifferentLoop(SCEVHandle S, Loop *L) {
275   // This is very common, put it first.
276   if (isa<SCEVConstant>(S))
277     return false;
278   if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
279     for (unsigned int i=0; i< AE->getNumOperands(); i++)
280       if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
281         return true;
282     return false;
283   }
284   if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
285     if (const Loop *newLoop = AE->getLoop()) {
286       if (newLoop == L)
287         return false;
288       // if newLoop is an outer loop of L, this is OK.
289       if (!LoopInfoBase<BasicBlock>::isNotAlreadyContainedIn(L, newLoop))
290         return false;
291     }
292     return true;
293   }
294   if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
295     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
296            containsAddRecFromDifferentLoop(DE->getRHS(), L);
297 #if 0
298   // SCEVSDivExpr has been backed out temporarily, but will be back; we'll 
299   // need this when it is.
300   if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
301     return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
302            containsAddRecFromDifferentLoop(DE->getRHS(), L);
303 #endif
304   if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
305     return containsAddRecFromDifferentLoop(CE->getOperand(), L);
306   return false;
307 }
308
309 /// getSCEVStartAndStride - Compute the start and stride of this expression,
310 /// returning false if the expression is not a start/stride pair, or true if it
311 /// is.  The stride must be a loop invariant expression, but the start may be
312 /// a mix of loop invariant and loop variant expressions.  The start cannot,
313 /// however, contain an AddRec from a different loop, unless that loop is an
314 /// outer loop of the current loop.
315 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
316                                   SCEVHandle &Start, SCEVHandle &Stride,
317                                   ScalarEvolution *SE, DominatorTree *DT) {
318   SCEVHandle TheAddRec = Start;   // Initialize to zero.
319
320   // If the outer level is an AddExpr, the operands are all start values except
321   // for a nested AddRecExpr.
322   if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
323     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
324       if (SCEVAddRecExpr *AddRec =
325              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
326         if (AddRec->getLoop() == L)
327           TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
328         else
329           return false;  // Nested IV of some sort?
330       } else {
331         Start = SE->getAddExpr(Start, AE->getOperand(i));
332       }
333         
334   } else if (isa<SCEVAddRecExpr>(SH)) {
335     TheAddRec = SH;
336   } else {
337     return false;  // not analyzable.
338   }
339   
340   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
341   if (!AddRec || AddRec->getLoop() != L) return false;
342   
343   // FIXME: Generalize to non-affine IV's.
344   if (!AddRec->isAffine()) return false;
345
346   // If Start contains an SCEVAddRecExpr from a different loop, other than an
347   // outer loop of the current loop, reject it.  SCEV has no concept of 
348   // operating on more than one loop at a time so don't confuse it with such
349   // expressions.
350   if (containsAddRecFromDifferentLoop(AddRec->getOperand(0), L))
351     return false;
352
353   Start = SE->getAddExpr(Start, AddRec->getOperand(0));
354   
355   if (!isa<SCEVConstant>(AddRec->getOperand(1))) {
356     // If stride is an instruction, make sure it dominates the loop preheader.
357     // Otherwise we could end up with a use before def situation.
358     BasicBlock *Preheader = L->getLoopPreheader();
359     if (!AddRec->getOperand(1)->dominates(Preheader, DT))
360       return false;
361
362     DOUT << "[" << L->getHeader()->getName()
363          << "] Variable stride: " << *AddRec << "\n";
364   }
365
366   Stride = AddRec->getOperand(1);
367   return true;
368 }
369
370 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
371 /// and now we need to decide whether the user should use the preinc or post-inc
372 /// value.  If this user should use the post-inc version of the IV, return true.
373 ///
374 /// Choosing wrong here can break dominance properties (if we choose to use the
375 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
376 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
377 /// should use the post-inc value).
378 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
379                                        Loop *L, DominatorTree *DT, Pass *P,
380                                       SmallVectorImpl<Instruction*> &DeadInsts){
381   // If the user is in the loop, use the preinc value.
382   if (L->contains(User->getParent())) return false;
383   
384   BasicBlock *LatchBlock = L->getLoopLatch();
385   
386   // Ok, the user is outside of the loop.  If it is dominated by the latch
387   // block, use the post-inc value.
388   if (DT->dominates(LatchBlock, User->getParent()))
389     return true;
390
391   // There is one case we have to be careful of: PHI nodes.  These little guys
392   // can live in blocks that do not dominate the latch block, but (since their
393   // uses occur in the predecessor block, not the block the PHI lives in) should
394   // still use the post-inc value.  Check for this case now.
395   PHINode *PN = dyn_cast<PHINode>(User);
396   if (!PN) return false;  // not a phi, not dominated by latch block.
397   
398   // Look at all of the uses of IV by the PHI node.  If any use corresponds to
399   // a block that is not dominated by the latch block, give up and use the
400   // preincremented value.
401   unsigned NumUses = 0;
402   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
403     if (PN->getIncomingValue(i) == IV) {
404       ++NumUses;
405       if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
406         return false;
407     }
408
409   // Okay, all uses of IV by PN are in predecessor blocks that really are
410   // dominated by the latch block.  Use the post-incremented value.
411   return true;
412 }
413
414 /// isAddressUse - Returns true if the specified instruction is using the
415 /// specified value as an address.
416 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
417   bool isAddress = isa<LoadInst>(Inst);
418   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
419     if (SI->getOperand(1) == OperandVal)
420       isAddress = true;
421   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
422     // Addressing modes can also be folded into prefetches and a variety
423     // of intrinsics.
424     switch (II->getIntrinsicID()) {
425       default: break;
426       case Intrinsic::prefetch:
427       case Intrinsic::x86_sse2_loadu_dq:
428       case Intrinsic::x86_sse2_loadu_pd:
429       case Intrinsic::x86_sse_loadu_ps:
430       case Intrinsic::x86_sse_storeu_ps:
431       case Intrinsic::x86_sse2_storeu_pd:
432       case Intrinsic::x86_sse2_storeu_dq:
433       case Intrinsic::x86_sse2_storel_dq:
434         if (II->getOperand(1) == OperandVal)
435           isAddress = true;
436         break;
437     }
438   }
439   return isAddress;
440 }
441
442 /// getAccessType - Return the type of the memory being accessed.
443 static const Type *getAccessType(const Instruction *Inst) {
444   const Type *UseTy = Inst->getType();
445   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
446     UseTy = SI->getOperand(0)->getType();
447   else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
448     // Addressing modes can also be folded into prefetches and a variety
449     // of intrinsics.
450     switch (II->getIntrinsicID()) {
451     default: break;
452     case Intrinsic::x86_sse_storeu_ps:
453     case Intrinsic::x86_sse2_storeu_pd:
454     case Intrinsic::x86_sse2_storeu_dq:
455     case Intrinsic::x86_sse2_storel_dq:
456       UseTy = II->getOperand(1)->getType();
457       break;
458     }
459   }
460   return UseTy;
461 }
462
463 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
464 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
465 /// return true.  Otherwise, return false.
466 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
467                                       SmallPtrSet<Instruction*,16> &Processed) {
468   if (!SE->isSCEVable(I->getType()))
469     return false;   // Void and FP expressions cannot be reduced.
470
471   // LSR is not APInt clean, do not touch integers bigger than 64-bits.
472   if (SE->getTypeSizeInBits(I->getType()) > 64)
473     return false;
474   
475   if (!Processed.insert(I))
476     return true;    // Instruction already handled.
477   
478   // Get the symbolic expression for this instruction.
479   SCEVHandle ISE = SE->getSCEV(I);
480   if (isa<SCEVCouldNotCompute>(ISE)) return false;
481   
482   // Get the start and stride for this expression.
483   SCEVHandle Start = SE->getIntegerSCEV(0, ISE->getType());
484   SCEVHandle Stride = Start;
485   if (!getSCEVStartAndStride(ISE, L, Start, Stride, SE, DT))
486     return false;  // Non-reducible symbolic expression, bail out.
487
488   std::vector<Instruction *> IUsers;
489   // Collect all I uses now because IVUseShouldUsePostIncValue may 
490   // invalidate use_iterator.
491   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
492     IUsers.push_back(cast<Instruction>(*UI));
493
494   for (unsigned iused_index = 0, iused_size = IUsers.size(); 
495        iused_index != iused_size; ++iused_index) {
496
497     Instruction *User = IUsers[iused_index];
498
499     // Do not infinitely recurse on PHI nodes.
500     if (isa<PHINode>(User) && Processed.count(User))
501       continue;
502
503     // Descend recursively, but not into PHI nodes outside the current loop.
504     // It's important to see the entire expression outside the loop to get
505     // choices that depend on addressing mode use right, although we won't
506     // consider references ouside the loop in all cases.
507     // If User is already in Processed, we don't want to recurse into it again,
508     // but do want to record a second reference in the same instruction.
509     bool AddUserToIVUsers = false;
510     if (LI->getLoopFor(User->getParent()) != L) {
511       if (isa<PHINode>(User) || Processed.count(User) ||
512           !AddUsersIfInteresting(User, L, Processed)) {
513         DOUT << "FOUND USER in other loop: " << *User
514              << "   OF SCEV: " << *ISE << "\n";
515         AddUserToIVUsers = true;
516       }
517     } else if (Processed.count(User) || 
518                !AddUsersIfInteresting(User, L, Processed)) {
519       DOUT << "FOUND USER: " << *User
520            << "   OF SCEV: " << *ISE << "\n";
521       AddUserToIVUsers = true;
522     }
523
524     if (AddUserToIVUsers) {
525       IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
526       if (StrideUses.Users.empty())     // First occurrence of this stride?
527         StrideOrder.push_back(Stride);
528       
529       // Okay, we found a user that we cannot reduce.  Analyze the instruction
530       // and decide what to do with it.  If we are a use inside of the loop, use
531       // the value before incrementation, otherwise use it after incrementation.
532       if (IVUseShouldUsePostIncValue(User, I, L, DT, this, DeadInsts)) {
533         // The value used will be incremented by the stride more than we are
534         // expecting, so subtract this off.
535         SCEVHandle NewStart = SE->getMinusSCEV(Start, Stride);
536         StrideUses.addUser(NewStart, User, I);
537         StrideUses.Users.back().isUseOfPostIncrementedValue = true;
538         DOUT << "   USING POSTINC SCEV, START=" << *NewStart<< "\n";
539       } else {        
540         StrideUses.addUser(Start, User, I);
541       }
542     }
543   }
544   return true;
545 }
546
547 namespace {
548   /// BasedUser - For a particular base value, keep information about how we've
549   /// partitioned the expression so far.
550   struct BasedUser {
551     /// SE - The current ScalarEvolution object.
552     ScalarEvolution *SE;
553
554     /// Base - The Base value for the PHI node that needs to be inserted for
555     /// this use.  As the use is processed, information gets moved from this
556     /// field to the Imm field (below).  BasedUser values are sorted by this
557     /// field.
558     SCEVHandle Base;
559     
560     /// Inst - The instruction using the induction variable.
561     Instruction *Inst;
562
563     /// OperandValToReplace - The operand value of Inst to replace with the
564     /// EmittedBase.
565     Value *OperandValToReplace;
566
567     /// Imm - The immediate value that should be added to the base immediately
568     /// before Inst, because it will be folded into the imm field of the
569     /// instruction.  This is also sometimes used for loop-variant values that
570     /// must be added inside the loop.
571     SCEVHandle Imm;
572
573     /// Phi - The induction variable that performs the striding that
574     /// should be used for this user.
575     PHINode *Phi;
576
577     // isUseOfPostIncrementedValue - True if this should use the
578     // post-incremented version of this IV, not the preincremented version.
579     // This can only be set in special cases, such as the terminating setcc
580     // instruction for a loop and uses outside the loop that are dominated by
581     // the loop.
582     bool isUseOfPostIncrementedValue;
583     
584     BasedUser(IVStrideUse &IVSU, ScalarEvolution *se)
585       : SE(se), Base(IVSU.Offset), Inst(IVSU.User), 
586         OperandValToReplace(IVSU.OperandValToReplace), 
587         Imm(SE->getIntegerSCEV(0, Base->getType())), 
588         isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
589
590     // Once we rewrite the code to insert the new IVs we want, update the
591     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
592     // to it.
593     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
594                                         Instruction *InsertPt,
595                                        SCEVExpander &Rewriter, Loop *L, Pass *P,
596                                       SmallVectorImpl<Instruction*> &DeadInsts);
597     
598     Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
599                                        const Type *Ty,
600                                        SCEVExpander &Rewriter,
601                                        Instruction *IP, Loop *L);
602     void dump() const;
603   };
604 }
605
606 void BasedUser::dump() const {
607   cerr << " Base=" << *Base;
608   cerr << " Imm=" << *Imm;
609   cerr << "   Inst: " << *Inst;
610 }
611
612 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
613                                               const Type *Ty,
614                                               SCEVExpander &Rewriter,
615                                               Instruction *IP, Loop *L) {
616   // Figure out where we *really* want to insert this code.  In particular, if
617   // the user is inside of a loop that is nested inside of L, we really don't
618   // want to insert this expression before the user, we'd rather pull it out as
619   // many loops as possible.
620   LoopInfo &LI = Rewriter.getLoopInfo();
621   Instruction *BaseInsertPt = IP;
622   
623   // Figure out the most-nested loop that IP is in.
624   Loop *InsertLoop = LI.getLoopFor(IP->getParent());
625   
626   // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
627   // the preheader of the outer-most loop where NewBase is not loop invariant.
628   if (L->contains(IP->getParent()))
629     while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
630       BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
631       InsertLoop = InsertLoop->getParentLoop();
632     }
633   
634   Value *Base = Rewriter.expandCodeFor(NewBase, Ty, BaseInsertPt);
635
636   // If there is no immediate value, skip the next part.
637   if (Imm->isZero())
638     return Base;
639
640   // If we are inserting the base and imm values in the same block, make sure to
641   // adjust the IP position if insertion reused a result.
642   if (IP == BaseInsertPt)
643     IP = Rewriter.getInsertionPoint();
644   
645   // Always emit the immediate (if non-zero) into the same block as the user.
646   SCEVHandle NewValSCEV = SE->getAddExpr(SE->getUnknown(Base), Imm);
647   return Rewriter.expandCodeFor(NewValSCEV, Ty, IP);
648 }
649
650
651 // Once we rewrite the code to insert the new IVs we want, update the
652 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
653 // to it. NewBasePt is the last instruction which contributes to the
654 // value of NewBase in the case that it's a diffferent instruction from
655 // the PHI that NewBase is computed from, or null otherwise.
656 //
657 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
658                                                Instruction *NewBasePt,
659                                       SCEVExpander &Rewriter, Loop *L, Pass *P,
660                                       SmallVectorImpl<Instruction*> &DeadInsts){
661   if (!isa<PHINode>(Inst)) {
662     // By default, insert code at the user instruction.
663     BasicBlock::iterator InsertPt = Inst;
664     
665     // However, if the Operand is itself an instruction, the (potentially
666     // complex) inserted code may be shared by many users.  Because of this, we
667     // want to emit code for the computation of the operand right before its old
668     // computation.  This is usually safe, because we obviously used to use the
669     // computation when it was computed in its current block.  However, in some
670     // cases (e.g. use of a post-incremented induction variable) the NewBase
671     // value will be pinned to live somewhere after the original computation.
672     // In this case, we have to back off.
673     //
674     // If this is a use outside the loop (which means after, since it is based
675     // on a loop indvar) we use the post-incremented value, so that we don't
676     // artificially make the preinc value live out the bottom of the loop. 
677     if (!isUseOfPostIncrementedValue && L->contains(Inst->getParent())) {
678       if (NewBasePt && isa<PHINode>(OperandValToReplace)) {
679         InsertPt = NewBasePt;
680         ++InsertPt;
681       } else if (Instruction *OpInst
682                  = dyn_cast<Instruction>(OperandValToReplace)) {
683         InsertPt = OpInst;
684         while (isa<PHINode>(InsertPt)) ++InsertPt;
685       }
686     }
687     Value *NewVal = InsertCodeForBaseAtPosition(NewBase,
688                                                 OperandValToReplace->getType(),
689                                                 Rewriter, InsertPt, L);
690     // Replace the use of the operand Value with the new Phi we just created.
691     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
692
693     DOUT << "      Replacing with ";
694     DEBUG(WriteAsOperand(*DOUT, NewVal, /*PrintType=*/false));
695     DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
696     return;
697   }
698
699   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
700   // expression into each operand block that uses it.  Note that PHI nodes can
701   // have multiple entries for the same predecessor.  We use a map to make sure
702   // that a PHI node only has a single Value* for each predecessor (which also
703   // prevents us from inserting duplicate code in some blocks).
704   DenseMap<BasicBlock*, Value*> InsertedCode;
705   PHINode *PN = cast<PHINode>(Inst);
706   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
707     if (PN->getIncomingValue(i) == OperandValToReplace) {
708       // If the original expression is outside the loop, put the replacement
709       // code in the same place as the original expression,
710       // which need not be an immediate predecessor of this PHI.  This way we 
711       // need only one copy of it even if it is referenced multiple times in
712       // the PHI.  We don't do this when the original expression is inside the
713       // loop because multiple copies sometimes do useful sinking of code in
714       // that case(?).
715       Instruction *OldLoc = dyn_cast<Instruction>(OperandValToReplace);
716       if (L->contains(OldLoc->getParent())) {
717         // If this is a critical edge, split the edge so that we do not insert
718         // the code on all predecessor/successor paths.  We do this unless this
719         // is the canonical backedge for this loop, as this can make some
720         // inserted code be in an illegal position.
721         BasicBlock *PHIPred = PN->getIncomingBlock(i);
722         if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
723             (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
724
725           // First step, split the critical edge.
726           SplitCriticalEdge(PHIPred, PN->getParent(), P, false);
727
728           // Next step: move the basic block.  In particular, if the PHI node
729           // is outside of the loop, and PredTI is in the loop, we want to
730           // move the block to be immediately before the PHI block, not
731           // immediately after PredTI.
732           if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
733             BasicBlock *NewBB = PN->getIncomingBlock(i);
734             NewBB->moveBefore(PN->getParent());
735           }
736
737           // Splitting the edge can reduce the number of PHI entries we have.
738           e = PN->getNumIncomingValues();
739         }
740       }
741       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
742       if (!Code) {
743         // Insert the code into the end of the predecessor block.
744         Instruction *InsertPt = (L->contains(OldLoc->getParent())) ?
745                                 PN->getIncomingBlock(i)->getTerminator() :
746                                 OldLoc->getParent()->getTerminator();
747         Code = InsertCodeForBaseAtPosition(NewBase, PN->getType(),
748                                            Rewriter, InsertPt, L);
749
750         DOUT << "      Changing PHI use to ";
751         DEBUG(WriteAsOperand(*DOUT, Code, /*PrintType=*/false));
752         DOUT << ", which has value " << *NewBase << " plus IMM " << *Imm << "\n";
753       }
754
755       // Replace the use of the operand Value with the new Phi we just created.
756       PN->setIncomingValue(i, Code);
757       Rewriter.clear();
758     }
759   }
760
761   // PHI node might have become a constant value after SplitCriticalEdge.
762   DeadInsts.push_back(Inst);
763 }
764
765
766 /// fitsInAddressMode - Return true if V can be subsumed within an addressing
767 /// mode, and does not need to be put in a register first.
768 static bool fitsInAddressMode(const SCEVHandle &V, const Type *UseTy,
769                              const TargetLowering *TLI, bool HasBaseReg) {
770   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
771     int64_t VC = SC->getValue()->getSExtValue();
772     if (TLI) {
773       TargetLowering::AddrMode AM;
774       AM.BaseOffs = VC;
775       AM.HasBaseReg = HasBaseReg;
776       return TLI->isLegalAddressingMode(AM, UseTy);
777     } else {
778       // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
779       return (VC > -(1 << 16) && VC < (1 << 16)-1);
780     }
781   }
782
783   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
784     if (GlobalValue *GV = dyn_cast<GlobalValue>(SU->getValue())) {
785       if (TLI) {
786         TargetLowering::AddrMode AM;
787         AM.BaseGV = GV;
788         AM.HasBaseReg = HasBaseReg;
789         return TLI->isLegalAddressingMode(AM, UseTy);
790       } else {
791         // Default: assume global addresses are not legal.
792       }
793     }
794
795   return false;
796 }
797
798 /// MoveLoopVariantsToImmediateField - Move any subexpressions from Val that are
799 /// loop varying to the Imm operand.
800 static void MoveLoopVariantsToImmediateField(SCEVHandle &Val, SCEVHandle &Imm,
801                                             Loop *L, ScalarEvolution *SE) {
802   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
803   
804   if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
805     std::vector<SCEVHandle> NewOps;
806     NewOps.reserve(SAE->getNumOperands());
807     
808     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
809       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
810         // If this is a loop-variant expression, it must stay in the immediate
811         // field of the expression.
812         Imm = SE->getAddExpr(Imm, SAE->getOperand(i));
813       } else {
814         NewOps.push_back(SAE->getOperand(i));
815       }
816
817     if (NewOps.empty())
818       Val = SE->getIntegerSCEV(0, Val->getType());
819     else
820       Val = SE->getAddExpr(NewOps);
821   } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
822     // Try to pull immediates out of the start value of nested addrec's.
823     SCEVHandle Start = SARE->getStart();
824     MoveLoopVariantsToImmediateField(Start, Imm, L, SE);
825     
826     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
827     Ops[0] = Start;
828     Val = SE->getAddRecExpr(Ops, SARE->getLoop());
829   } else {
830     // Otherwise, all of Val is variant, move the whole thing over.
831     Imm = SE->getAddExpr(Imm, Val);
832     Val = SE->getIntegerSCEV(0, Val->getType());
833   }
834 }
835
836
837 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
838 /// that can fit into the immediate field of instructions in the target.
839 /// Accumulate these immediate values into the Imm value.
840 static void MoveImmediateValues(const TargetLowering *TLI,
841                                 const Type *UseTy,
842                                 SCEVHandle &Val, SCEVHandle &Imm,
843                                 bool isAddress, Loop *L,
844                                 ScalarEvolution *SE) {
845   if (const SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
846     std::vector<SCEVHandle> NewOps;
847     NewOps.reserve(SAE->getNumOperands());
848     
849     for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
850       SCEVHandle NewOp = SAE->getOperand(i);
851       MoveImmediateValues(TLI, UseTy, NewOp, Imm, isAddress, L, SE);
852       
853       if (!NewOp->isLoopInvariant(L)) {
854         // If this is a loop-variant expression, it must stay in the immediate
855         // field of the expression.
856         Imm = SE->getAddExpr(Imm, NewOp);
857       } else {
858         NewOps.push_back(NewOp);
859       }
860     }
861
862     if (NewOps.empty())
863       Val = SE->getIntegerSCEV(0, Val->getType());
864     else
865       Val = SE->getAddExpr(NewOps);
866     return;
867   } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
868     // Try to pull immediates out of the start value of nested addrec's.
869     SCEVHandle Start = SARE->getStart();
870     MoveImmediateValues(TLI, UseTy, Start, Imm, isAddress, L, SE);
871     
872     if (Start != SARE->getStart()) {
873       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
874       Ops[0] = Start;
875       Val = SE->getAddRecExpr(Ops, SARE->getLoop());
876     }
877     return;
878   } else if (const SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
879     // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
880     if (isAddress && fitsInAddressMode(SME->getOperand(0), UseTy, TLI, false) &&
881         SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
882
883       SCEVHandle SubImm = SE->getIntegerSCEV(0, Val->getType());
884       SCEVHandle NewOp = SME->getOperand(1);
885       MoveImmediateValues(TLI, UseTy, NewOp, SubImm, isAddress, L, SE);
886       
887       // If we extracted something out of the subexpressions, see if we can 
888       // simplify this!
889       if (NewOp != SME->getOperand(1)) {
890         // Scale SubImm up by "8".  If the result is a target constant, we are
891         // good.
892         SubImm = SE->getMulExpr(SubImm, SME->getOperand(0));
893         if (fitsInAddressMode(SubImm, UseTy, TLI, false)) {
894           // Accumulate the immediate.
895           Imm = SE->getAddExpr(Imm, SubImm);
896           
897           // Update what is left of 'Val'.
898           Val = SE->getMulExpr(SME->getOperand(0), NewOp);
899           return;
900         }
901       }
902     }
903   }
904
905   // Loop-variant expressions must stay in the immediate field of the
906   // expression.
907   if ((isAddress && fitsInAddressMode(Val, UseTy, TLI, false)) ||
908       !Val->isLoopInvariant(L)) {
909     Imm = SE->getAddExpr(Imm, Val);
910     Val = SE->getIntegerSCEV(0, Val->getType());
911     return;
912   }
913
914   // Otherwise, no immediates to move.
915 }
916
917 static void MoveImmediateValues(const TargetLowering *TLI,
918                                 Instruction *User,
919                                 SCEVHandle &Val, SCEVHandle &Imm,
920                                 bool isAddress, Loop *L,
921                                 ScalarEvolution *SE) {
922   const Type *UseTy = getAccessType(User);
923   MoveImmediateValues(TLI, UseTy, Val, Imm, isAddress, L, SE);
924 }
925
926 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
927 /// added together.  This is used to reassociate common addition subexprs
928 /// together for maximal sharing when rewriting bases.
929 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
930                              SCEVHandle Expr,
931                              ScalarEvolution *SE) {
932   if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
933     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
934       SeparateSubExprs(SubExprs, AE->getOperand(j), SE);
935   } else if (const SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
936     SCEVHandle Zero = SE->getIntegerSCEV(0, Expr->getType());
937     if (SARE->getOperand(0) == Zero) {
938       SubExprs.push_back(Expr);
939     } else {
940       // Compute the addrec with zero as its base.
941       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
942       Ops[0] = Zero;   // Start with zero base.
943       SubExprs.push_back(SE->getAddRecExpr(Ops, SARE->getLoop()));
944       
945
946       SeparateSubExprs(SubExprs, SARE->getOperand(0), SE);
947     }
948   } else if (!Expr->isZero()) {
949     // Do not add zero.
950     SubExprs.push_back(Expr);
951   }
952 }
953
954 // This is logically local to the following function, but C++ says we have 
955 // to make it file scope.
956 struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
957
958 /// RemoveCommonExpressionsFromUseBases - Look through all of the Bases of all
959 /// the Uses, removing any common subexpressions, except that if all such
960 /// subexpressions can be folded into an addressing mode for all uses inside
961 /// the loop (this case is referred to as "free" in comments herein) we do
962 /// not remove anything.  This looks for things like (a+b+c) and
963 /// (a+c+d) and computes the common (a+c) subexpression.  The common expression
964 /// is *removed* from the Bases and returned.
965 static SCEVHandle 
966 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses,
967                                     ScalarEvolution *SE, Loop *L,
968                                     const TargetLowering *TLI) {
969   unsigned NumUses = Uses.size();
970
971   // Only one use?  This is a very common case, so we handle it specially and
972   // cheaply.
973   SCEVHandle Zero = SE->getIntegerSCEV(0, Uses[0].Base->getType());
974   SCEVHandle Result = Zero;
975   SCEVHandle FreeResult = Zero;
976   if (NumUses == 1) {
977     // If the use is inside the loop, use its base, regardless of what it is:
978     // it is clearly shared across all the IV's.  If the use is outside the loop
979     // (which means after it) we don't want to factor anything *into* the loop,
980     // so just use 0 as the base.
981     if (L->contains(Uses[0].Inst->getParent()))
982       std::swap(Result, Uses[0].Base);
983     return Result;
984   }
985
986   // To find common subexpressions, count how many of Uses use each expression.
987   // If any subexpressions are used Uses.size() times, they are common.
988   // Also track whether all uses of each expression can be moved into an
989   // an addressing mode "for free"; such expressions are left within the loop.
990   // struct SubExprUseData { unsigned Count; bool notAllUsesAreFree; };
991   std::map<SCEVHandle, SubExprUseData> SubExpressionUseData;
992   
993   // UniqueSubExprs - Keep track of all of the subexpressions we see in the
994   // order we see them.
995   std::vector<SCEVHandle> UniqueSubExprs;
996
997   std::vector<SCEVHandle> SubExprs;
998   unsigned NumUsesInsideLoop = 0;
999   for (unsigned i = 0; i != NumUses; ++i) {
1000     // If the user is outside the loop, just ignore it for base computation.
1001     // Since the user is outside the loop, it must be *after* the loop (if it
1002     // were before, it could not be based on the loop IV).  We don't want users
1003     // after the loop to affect base computation of values *inside* the loop,
1004     // because we can always add their offsets to the result IV after the loop
1005     // is done, ensuring we get good code inside the loop.
1006     if (!L->contains(Uses[i].Inst->getParent()))
1007       continue;
1008     NumUsesInsideLoop++;
1009     
1010     // If the base is zero (which is common), return zero now, there are no
1011     // CSEs we can find.
1012     if (Uses[i].Base == Zero) return Zero;
1013
1014     // If this use is as an address we may be able to put CSEs in the addressing
1015     // mode rather than hoisting them.
1016     bool isAddrUse = isAddressUse(Uses[i].Inst, Uses[i].OperandValToReplace);
1017     // We may need the UseTy below, but only when isAddrUse, so compute it
1018     // only in that case.
1019     const Type *UseTy = 0;
1020     if (isAddrUse)
1021       UseTy = getAccessType(Uses[i].Inst);
1022
1023     // Split the expression into subexprs.
1024     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1025     // Add one to SubExpressionUseData.Count for each subexpr present, and
1026     // if the subexpr is not a valid immediate within an addressing mode use,
1027     // set SubExpressionUseData.notAllUsesAreFree.  We definitely want to
1028     // hoist these out of the loop (if they are common to all uses).
1029     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1030       if (++SubExpressionUseData[SubExprs[j]].Count == 1)
1031         UniqueSubExprs.push_back(SubExprs[j]);
1032       if (!isAddrUse || !fitsInAddressMode(SubExprs[j], UseTy, TLI, false))
1033         SubExpressionUseData[SubExprs[j]].notAllUsesAreFree = true;
1034     }
1035     SubExprs.clear();
1036   }
1037
1038   // Now that we know how many times each is used, build Result.  Iterate over
1039   // UniqueSubexprs so that we have a stable ordering.
1040   for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
1041     std::map<SCEVHandle, SubExprUseData>::iterator I = 
1042        SubExpressionUseData.find(UniqueSubExprs[i]);
1043     assert(I != SubExpressionUseData.end() && "Entry not found?");
1044     if (I->second.Count == NumUsesInsideLoop) { // Found CSE! 
1045       if (I->second.notAllUsesAreFree)
1046         Result = SE->getAddExpr(Result, I->first);
1047       else 
1048         FreeResult = SE->getAddExpr(FreeResult, I->first);
1049     } else
1050       // Remove non-cse's from SubExpressionUseData.
1051       SubExpressionUseData.erase(I);
1052   }
1053
1054   if (FreeResult != Zero) {
1055     // We have some subexpressions that can be subsumed into addressing
1056     // modes in every use inside the loop.  However, it's possible that
1057     // there are so many of them that the combined FreeResult cannot
1058     // be subsumed, or that the target cannot handle both a FreeResult
1059     // and a Result in the same instruction (for example because it would
1060     // require too many registers).  Check this.
1061     for (unsigned i=0; i<NumUses; ++i) {
1062       if (!L->contains(Uses[i].Inst->getParent()))
1063         continue;
1064       // We know this is an addressing mode use; if there are any uses that
1065       // are not, FreeResult would be Zero.
1066       const Type *UseTy = getAccessType(Uses[i].Inst);
1067       if (!fitsInAddressMode(FreeResult, UseTy, TLI, Result!=Zero)) {
1068         // FIXME:  could split up FreeResult into pieces here, some hoisted
1069         // and some not.  There is no obvious advantage to this.
1070         Result = SE->getAddExpr(Result, FreeResult);
1071         FreeResult = Zero;
1072         break;
1073       }
1074     }
1075   }
1076
1077   // If we found no CSE's, return now.
1078   if (Result == Zero) return Result;
1079   
1080   // If we still have a FreeResult, remove its subexpressions from
1081   // SubExpressionUseData.  This means they will remain in the use Bases.
1082   if (FreeResult != Zero) {
1083     SeparateSubExprs(SubExprs, FreeResult, SE);
1084     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j) {
1085       std::map<SCEVHandle, SubExprUseData>::iterator I = 
1086          SubExpressionUseData.find(SubExprs[j]);
1087       SubExpressionUseData.erase(I);
1088     }
1089     SubExprs.clear();
1090   }
1091
1092   // Otherwise, remove all of the CSE's we found from each of the base values.
1093   for (unsigned i = 0; i != NumUses; ++i) {
1094     // Uses outside the loop don't necessarily include the common base, but
1095     // the final IV value coming into those uses does.  Instead of trying to
1096     // remove the pieces of the common base, which might not be there,
1097     // subtract off the base to compensate for this.
1098     if (!L->contains(Uses[i].Inst->getParent())) {
1099       Uses[i].Base = SE->getMinusSCEV(Uses[i].Base, Result);
1100       continue;
1101     }
1102
1103     // Split the expression into subexprs.
1104     SeparateSubExprs(SubExprs, Uses[i].Base, SE);
1105
1106     // Remove any common subexpressions.
1107     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
1108       if (SubExpressionUseData.count(SubExprs[j])) {
1109         SubExprs.erase(SubExprs.begin()+j);
1110         --j; --e;
1111       }
1112     
1113     // Finally, add the non-shared expressions together.
1114     if (SubExprs.empty())
1115       Uses[i].Base = Zero;
1116     else
1117       Uses[i].Base = SE->getAddExpr(SubExprs);
1118     SubExprs.clear();
1119   }
1120  
1121   return Result;
1122 }
1123
1124 /// ValidStride - Check whether the given Scale is valid for all loads and 
1125 /// stores in UsersToProcess.
1126 ///
1127 bool LoopStrengthReduce::ValidStride(bool HasBaseReg,
1128                                int64_t Scale, 
1129                                const std::vector<BasedUser>& UsersToProcess) {
1130   if (!TLI)
1131     return true;
1132
1133   for (unsigned i=0, e = UsersToProcess.size(); i!=e; ++i) {
1134     // If this is a load or other access, pass the type of the access in.
1135     const Type *AccessTy = Type::VoidTy;
1136     if (isAddressUse(UsersToProcess[i].Inst,
1137                      UsersToProcess[i].OperandValToReplace))
1138       AccessTy = getAccessType(UsersToProcess[i].Inst);
1139     else if (isa<PHINode>(UsersToProcess[i].Inst))
1140       continue;
1141     
1142     TargetLowering::AddrMode AM;
1143     if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(UsersToProcess[i].Imm))
1144       AM.BaseOffs = SC->getValue()->getSExtValue();
1145     AM.HasBaseReg = HasBaseReg || !UsersToProcess[i].Base->isZero();
1146     AM.Scale = Scale;
1147
1148     // If load[imm+r*scale] is illegal, bail out.
1149     if (!TLI->isLegalAddressingMode(AM, AccessTy))
1150       return false;
1151   }
1152   return true;
1153 }
1154
1155 /// RequiresTypeConversion - Returns true if converting Ty1 to Ty2 is not
1156 /// a nop.
1157 bool LoopStrengthReduce::RequiresTypeConversion(const Type *Ty1,
1158                                                 const Type *Ty2) {
1159   if (Ty1 == Ty2)
1160     return false;
1161   Ty1 = SE->getEffectiveSCEVType(Ty1);
1162   Ty2 = SE->getEffectiveSCEVType(Ty2);
1163   if (Ty1 == Ty2)
1164     return false;
1165   if (Ty1->canLosslesslyBitCastTo(Ty2))
1166     return false;
1167   if (TLI && TLI->isTruncateFree(Ty1, Ty2))
1168     return false;
1169   return true;
1170 }
1171
1172 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
1173 /// of a previous stride and it is a legal value for the target addressing
1174 /// mode scale component and optional base reg. This allows the users of
1175 /// this stride to be rewritten as prev iv * factor. It returns 0 if no
1176 /// reuse is possible.  Factors can be negative on same targets, e.g. ARM.
1177 ///
1178 /// If all uses are outside the loop, we don't require that all multiplies
1179 /// be folded into the addressing mode, nor even that the factor be constant; 
1180 /// a multiply (executed once) outside the loop is better than another IV 
1181 /// within.  Well, usually.
1182 SCEVHandle LoopStrengthReduce::CheckForIVReuse(bool HasBaseReg,
1183                                 bool AllUsesAreAddresses,
1184                                 bool AllUsesAreOutsideLoop,
1185                                 const SCEVHandle &Stride, 
1186                                 IVExpr &IV, const Type *Ty,
1187                                 const std::vector<BasedUser>& UsersToProcess) {
1188   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
1189     int64_t SInt = SC->getValue()->getSExtValue();
1190     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1191          ++NewStride) {
1192       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1193                 IVsByStride.find(StrideOrder[NewStride]);
1194       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1195         continue;
1196       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1197       if (SI->first != Stride &&
1198           (unsigned(abs(SInt)) < SSInt || (SInt % SSInt) != 0))
1199         continue;
1200       int64_t Scale = SInt / SSInt;
1201       // Check that this stride is valid for all the types used for loads and
1202       // stores; if it can be used for some and not others, we might as well use
1203       // the original stride everywhere, since we have to create the IV for it
1204       // anyway. If the scale is 1, then we don't need to worry about folding
1205       // multiplications.
1206       if (Scale == 1 ||
1207           (AllUsesAreAddresses &&
1208            ValidStride(HasBaseReg, Scale, UsersToProcess)))
1209         for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1210                IE = SI->second.IVs.end(); II != IE; ++II)
1211           // FIXME: Only handle base == 0 for now.
1212           // Only reuse previous IV if it would not require a type conversion.
1213           if (II->Base->isZero() &&
1214               !RequiresTypeConversion(II->Base->getType(), Ty)) {
1215             IV = *II;
1216             return SE->getIntegerSCEV(Scale, Stride->getType());
1217           }
1218     }
1219   } else if (AllUsesAreOutsideLoop) {
1220     // Accept nonconstant strides here; it is really really right to substitute
1221     // an existing IV if we can.
1222     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1223          ++NewStride) {
1224       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1225                 IVsByStride.find(StrideOrder[NewStride]);
1226       if (SI == IVsByStride.end() || !isa<SCEVConstant>(SI->first))
1227         continue;
1228       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
1229       if (SI->first != Stride && SSInt != 1)
1230         continue;
1231       for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1232              IE = SI->second.IVs.end(); II != IE; ++II)
1233         // Accept nonzero base here.
1234         // Only reuse previous IV if it would not require a type conversion.
1235         if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1236           IV = *II;
1237           return Stride;
1238         }
1239     }
1240     // Special case, old IV is -1*x and this one is x.  Can treat this one as
1241     // -1*old.
1242     for (unsigned NewStride = 0, e = StrideOrder.size(); NewStride != e;
1243          ++NewStride) {
1244       std::map<SCEVHandle, IVsOfOneStride>::iterator SI = 
1245                 IVsByStride.find(StrideOrder[NewStride]);
1246       if (SI == IVsByStride.end()) 
1247         continue;
1248       if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(SI->first))
1249         if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(ME->getOperand(0)))
1250           if (Stride == ME->getOperand(1) &&
1251               SC->getValue()->getSExtValue() == -1LL)
1252             for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
1253                    IE = SI->second.IVs.end(); II != IE; ++II)
1254               // Accept nonzero base here.
1255               // Only reuse previous IV if it would not require type conversion.
1256               if (!RequiresTypeConversion(II->Base->getType(), Ty)) {
1257                 IV = *II;
1258                 return SE->getIntegerSCEV(-1LL, Stride->getType());
1259               }
1260     }
1261   }
1262   return SE->getIntegerSCEV(0, Stride->getType());
1263 }
1264
1265 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
1266 /// returns true if Val's isUseOfPostIncrementedValue is true.
1267 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
1268   return Val.isUseOfPostIncrementedValue;
1269 }
1270
1271 /// isNonConstantNegative - Return true if the specified scev is negated, but
1272 /// not a constant.
1273 static bool isNonConstantNegative(const SCEVHandle &Expr) {
1274   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Expr);
1275   if (!Mul) return false;
1276   
1277   // If there is a constant factor, it will be first.
1278   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
1279   if (!SC) return false;
1280   
1281   // Return true if the value is negative, this matches things like (-42 * V).
1282   return SC->getValue()->getValue().isNegative();
1283 }
1284
1285 // CollectIVUsers - Transform our list of users and offsets to a bit more
1286 // complex table. In this new vector, each 'BasedUser' contains 'Base', the base
1287 // of the strided accesses, as well as the old information from Uses. We
1288 // progressively move information from the Base field to the Imm field, until
1289 // we eventually have the full access expression to rewrite the use.
1290 SCEVHandle LoopStrengthReduce::CollectIVUsers(const SCEVHandle &Stride,
1291                                               IVUsersOfOneStride &Uses,
1292                                               Loop *L,
1293                                               bool &AllUsesAreAddresses,
1294                                               bool &AllUsesAreOutsideLoop,
1295                                        std::vector<BasedUser> &UsersToProcess) {
1296   UsersToProcess.reserve(Uses.Users.size());
1297   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
1298     UsersToProcess.push_back(BasedUser(Uses.Users[i], SE));
1299     
1300     // Move any loop variant operands from the offset field to the immediate
1301     // field of the use, so that we don't try to use something before it is
1302     // computed.
1303     MoveLoopVariantsToImmediateField(UsersToProcess.back().Base,
1304                                     UsersToProcess.back().Imm, L, SE);
1305     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
1306            "Base value is not loop invariant!");
1307   }
1308
1309   // We now have a whole bunch of uses of like-strided induction variables, but
1310   // they might all have different bases.  We want to emit one PHI node for this
1311   // stride which we fold as many common expressions (between the IVs) into as
1312   // possible.  Start by identifying the common expressions in the base values 
1313   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
1314   // "A+B"), emit it to the preheader, then remove the expression from the
1315   // UsersToProcess base values.
1316   SCEVHandle CommonExprs =
1317     RemoveCommonExpressionsFromUseBases(UsersToProcess, SE, L, TLI);
1318
1319   // Next, figure out what we can represent in the immediate fields of
1320   // instructions.  If we can represent anything there, move it to the imm
1321   // fields of the BasedUsers.  We do this so that it increases the commonality
1322   // of the remaining uses.
1323   unsigned NumPHI = 0;
1324   bool HasAddress = false;
1325   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1326     // If the user is not in the current loop, this means it is using the exit
1327     // value of the IV.  Do not put anything in the base, make sure it's all in
1328     // the immediate field to allow as much factoring as possible.
1329     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
1330       UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm,
1331                                              UsersToProcess[i].Base);
1332       UsersToProcess[i].Base = 
1333         SE->getIntegerSCEV(0, UsersToProcess[i].Base->getType());
1334     } else {
1335       // Not all uses are outside the loop.
1336       AllUsesAreOutsideLoop = false; 
1337
1338       // Addressing modes can be folded into loads and stores.  Be careful that
1339       // the store is through the expression, not of the expression though.
1340       bool isPHI = false;
1341       bool isAddress = isAddressUse(UsersToProcess[i].Inst,
1342                                     UsersToProcess[i].OperandValToReplace);
1343       if (isa<PHINode>(UsersToProcess[i].Inst)) {
1344         isPHI = true;
1345         ++NumPHI;
1346       }
1347
1348       if (isAddress)
1349         HasAddress = true;
1350      
1351       // If this use isn't an address, then not all uses are addresses.
1352       if (!isAddress && !isPHI)
1353         AllUsesAreAddresses = false;
1354       
1355       MoveImmediateValues(TLI, UsersToProcess[i].Inst, UsersToProcess[i].Base,
1356                           UsersToProcess[i].Imm, isAddress, L, SE);
1357     }
1358   }
1359
1360   // If one of the use is a PHI node and all other uses are addresses, still
1361   // allow iv reuse. Essentially we are trading one constant multiplication
1362   // for one fewer iv.
1363   if (NumPHI > 1)
1364     AllUsesAreAddresses = false;
1365     
1366   // There are no in-loop address uses.
1367   if (AllUsesAreAddresses && (!HasAddress && !AllUsesAreOutsideLoop))
1368     AllUsesAreAddresses = false;
1369
1370   return CommonExprs;
1371 }
1372
1373 /// ShouldUseFullStrengthReductionMode - Test whether full strength-reduction
1374 /// is valid and profitable for the given set of users of a stride. In
1375 /// full strength-reduction mode, all addresses at the current stride are
1376 /// strength-reduced all the way down to pointer arithmetic.
1377 ///
1378 bool LoopStrengthReduce::ShouldUseFullStrengthReductionMode(
1379                                    const std::vector<BasedUser> &UsersToProcess,
1380                                    const Loop *L,
1381                                    bool AllUsesAreAddresses,
1382                                    SCEVHandle Stride) {
1383   if (!EnableFullLSRMode)
1384     return false;
1385
1386   // The heuristics below aim to avoid increasing register pressure, but
1387   // fully strength-reducing all the addresses increases the number of
1388   // add instructions, so don't do this when optimizing for size.
1389   // TODO: If the loop is large, the savings due to simpler addresses
1390   // may oughtweight the costs of the extra increment instructions.
1391   if (L->getHeader()->getParent()->hasFnAttr(Attribute::OptimizeForSize))
1392     return false;
1393
1394   // TODO: For now, don't do full strength reduction if there could
1395   // potentially be greater-stride multiples of the current stride
1396   // which could reuse the current stride IV.
1397   if (StrideOrder.back() != Stride)
1398     return false;
1399
1400   // Iterate through the uses to find conditions that automatically rule out
1401   // full-lsr mode.
1402   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1403     SCEV *Base = UsersToProcess[i].Base;
1404     SCEV *Imm = UsersToProcess[i].Imm;
1405     // If any users have a loop-variant component, they can't be fully
1406     // strength-reduced.
1407     if (Imm && !Imm->isLoopInvariant(L))
1408       return false;
1409     // If there are to users with the same base and the difference between
1410     // the two Imm values can't be folded into the address, full
1411     // strength reduction would increase register pressure.
1412     do {
1413       SCEV *CurImm = UsersToProcess[i].Imm;
1414       if ((CurImm || Imm) && CurImm != Imm) {
1415         if (!CurImm) CurImm = SE->getIntegerSCEV(0, Stride->getType());
1416         if (!Imm)       Imm = SE->getIntegerSCEV(0, Stride->getType());
1417         const Instruction *Inst = UsersToProcess[i].Inst;
1418         const Type *UseTy = getAccessType(Inst);
1419         SCEVHandle Diff = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1420         if (!Diff->isZero() &&
1421             (!AllUsesAreAddresses ||
1422              !fitsInAddressMode(Diff, UseTy, TLI, /*HasBaseReg=*/true)))
1423           return false;
1424       }
1425     } while (++i != e && Base == UsersToProcess[i].Base);
1426   }
1427
1428   // If there's exactly one user in this stride, fully strength-reducing it
1429   // won't increase register pressure. If it's starting from a non-zero base,
1430   // it'll be simpler this way.
1431   if (UsersToProcess.size() == 1 && !UsersToProcess[0].Base->isZero())
1432     return true;
1433
1434   // Otherwise, if there are any users in this stride that don't require
1435   // a register for their base, full strength-reduction will increase
1436   // register pressure.
1437   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1438     if (UsersToProcess[i].Base->isZero())
1439       return false;
1440
1441   // Otherwise, go for it.
1442   return true;
1443 }
1444
1445 /// InsertAffinePhi Create and insert a PHI node for an induction variable
1446 /// with the specified start and step values in the specified loop.
1447 ///
1448 /// If NegateStride is true, the stride should be negated by using a
1449 /// subtract instead of an add.
1450 ///
1451 /// Return the created phi node.
1452 ///
1453 static PHINode *InsertAffinePhi(SCEVHandle Start, SCEVHandle Step,
1454                                 const Loop *L,
1455                                 SCEVExpander &Rewriter) {
1456   assert(Start->isLoopInvariant(L) && "New PHI start is not loop invariant!");
1457   assert(Step->isLoopInvariant(L) && "New PHI stride is not loop invariant!");
1458
1459   BasicBlock *Header = L->getHeader();
1460   BasicBlock *Preheader = L->getLoopPreheader();
1461   BasicBlock *LatchBlock = L->getLoopLatch();
1462   const Type *Ty = Start->getType();
1463   Ty = Rewriter.SE.getEffectiveSCEVType(Ty);
1464
1465   PHINode *PN = PHINode::Create(Ty, "lsr.iv", Header->begin());
1466   PN->addIncoming(Rewriter.expandCodeFor(Start, Ty, Preheader->getTerminator()),
1467                   Preheader);
1468
1469   // If the stride is negative, insert a sub instead of an add for the
1470   // increment.
1471   bool isNegative = isNonConstantNegative(Step);
1472   SCEVHandle IncAmount = Step;
1473   if (isNegative)
1474     IncAmount = Rewriter.SE.getNegativeSCEV(Step);
1475
1476   // Insert an add instruction right before the terminator corresponding
1477   // to the back-edge.
1478   Value *StepV = Rewriter.expandCodeFor(IncAmount, Ty,
1479                                         Preheader->getTerminator());
1480   Instruction *IncV;
1481   if (isNegative) {
1482     IncV = BinaryOperator::CreateSub(PN, StepV, "lsr.iv.next",
1483                                      LatchBlock->getTerminator());
1484   } else {
1485     IncV = BinaryOperator::CreateAdd(PN, StepV, "lsr.iv.next",
1486                                      LatchBlock->getTerminator());
1487   }
1488   if (!isa<ConstantInt>(StepV)) ++NumVariable;
1489
1490   PN->addIncoming(IncV, LatchBlock);
1491
1492   ++NumInserted;
1493   return PN;
1494 }
1495
1496 static void SortUsersToProcess(std::vector<BasedUser> &UsersToProcess) {
1497   // We want to emit code for users inside the loop first.  To do this, we
1498   // rearrange BasedUser so that the entries at the end have
1499   // isUseOfPostIncrementedValue = false, because we pop off the end of the
1500   // vector (so we handle them first).
1501   std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1502                  PartitionByIsUseOfPostIncrementedValue);
1503
1504   // Sort this by base, so that things with the same base are handled
1505   // together.  By partitioning first and stable-sorting later, we are
1506   // guaranteed that within each base we will pop off users from within the
1507   // loop before users outside of the loop with a particular base.
1508   //
1509   // We would like to use stable_sort here, but we can't.  The problem is that
1510   // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1511   // we don't have anything to do a '<' comparison on.  Because we think the
1512   // number of uses is small, do a horrible bubble sort which just relies on
1513   // ==.
1514   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1515     // Get a base value.
1516     SCEVHandle Base = UsersToProcess[i].Base;
1517
1518     // Compact everything with this base to be consecutive with this one.
1519     for (unsigned j = i+1; j != e; ++j) {
1520       if (UsersToProcess[j].Base == Base) {
1521         std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1522         ++i;
1523       }
1524     }
1525   }
1526 }
1527
1528 /// PrepareToStrengthReduceFully - Prepare to fully strength-reduce
1529 /// UsersToProcess, meaning lowering addresses all the way down to direct
1530 /// pointer arithmetic.
1531 ///
1532 void
1533 LoopStrengthReduce::PrepareToStrengthReduceFully(
1534                                         std::vector<BasedUser> &UsersToProcess,
1535                                         SCEVHandle Stride,
1536                                         SCEVHandle CommonExprs,
1537                                         const Loop *L,
1538                                         SCEVExpander &PreheaderRewriter) {
1539   DOUT << "  Fully reducing all users\n";
1540
1541   // Rewrite the UsersToProcess records, creating a separate PHI for each
1542   // unique Base value.
1543   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ) {
1544     // TODO: The uses are grouped by base, but not sorted. We arbitrarily
1545     // pick the first Imm value here to start with, and adjust it for the
1546     // other uses.
1547     SCEVHandle Imm = UsersToProcess[i].Imm;
1548     SCEVHandle Base = UsersToProcess[i].Base;
1549     SCEVHandle Start = SE->getAddExpr(CommonExprs, Base, Imm);
1550     PHINode *Phi = InsertAffinePhi(Start, Stride, L,
1551                                    PreheaderRewriter);
1552     // Loop over all the users with the same base.
1553     do {
1554       UsersToProcess[i].Base = SE->getIntegerSCEV(0, Stride->getType());
1555       UsersToProcess[i].Imm = SE->getMinusSCEV(UsersToProcess[i].Imm, Imm);
1556       UsersToProcess[i].Phi = Phi;
1557       assert(UsersToProcess[i].Imm->isLoopInvariant(L) &&
1558              "ShouldUseFullStrengthReductionMode should reject this!");
1559     } while (++i != e && Base == UsersToProcess[i].Base);
1560   }
1561 }
1562
1563 /// PrepareToStrengthReduceWithNewPhi - Insert a new induction variable for the
1564 /// given users to share.
1565 ///
1566 void
1567 LoopStrengthReduce::PrepareToStrengthReduceWithNewPhi(
1568                                          std::vector<BasedUser> &UsersToProcess,
1569                                          SCEVHandle Stride,
1570                                          SCEVHandle CommonExprs,
1571                                          Value *CommonBaseV,
1572                                          const Loop *L,
1573                                          SCEVExpander &PreheaderRewriter) {
1574   DOUT << "  Inserting new PHI:\n";
1575
1576   PHINode *Phi = InsertAffinePhi(SE->getUnknown(CommonBaseV),
1577                                  Stride, L,
1578                                  PreheaderRewriter);
1579
1580   // Remember this in case a later stride is multiple of this.
1581   IVsByStride[Stride].addIV(Stride, CommonExprs, Phi);
1582
1583   // All the users will share this new IV.
1584   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1585     UsersToProcess[i].Phi = Phi;
1586
1587   DOUT << "    IV=";
1588   DEBUG(WriteAsOperand(*DOUT, Phi, /*PrintType=*/false));
1589   DOUT << "\n";
1590 }
1591
1592 /// PrepareToStrengthReduceWithNewPhi - Prepare for the given users to reuse
1593 /// an induction variable with a stride that is a factor of the current
1594 /// induction variable.
1595 ///
1596 void
1597 LoopStrengthReduce::PrepareToStrengthReduceFromSmallerStride(
1598                                          std::vector<BasedUser> &UsersToProcess,
1599                                          Value *CommonBaseV,
1600                                          const IVExpr &ReuseIV,
1601                                          Instruction *PreInsertPt) {
1602   DOUT << "  Rewriting in terms of existing IV of STRIDE " << *ReuseIV.Stride
1603        << " and BASE " << *ReuseIV.Base << "\n";
1604
1605   // All the users will share the reused IV.
1606   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1607     UsersToProcess[i].Phi = ReuseIV.PHI;
1608
1609   Constant *C = dyn_cast<Constant>(CommonBaseV);
1610   if (C &&
1611       (!C->isNullValue() &&
1612        !fitsInAddressMode(SE->getUnknown(CommonBaseV), CommonBaseV->getType(),
1613                          TLI, false)))
1614     // We want the common base emitted into the preheader! This is just
1615     // using cast as a copy so BitCast (no-op cast) is appropriate
1616     CommonBaseV = new BitCastInst(CommonBaseV, CommonBaseV->getType(),
1617                                   "commonbase", PreInsertPt);
1618 }
1619
1620 static bool IsImmFoldedIntoAddrMode(GlobalValue *GV, int64_t Offset,
1621                                     const Type *AccessTy,
1622                                    std::vector<BasedUser> &UsersToProcess,
1623                                    const TargetLowering *TLI) {
1624   SmallVector<Instruction*, 16> AddrModeInsts;
1625   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1626     if (UsersToProcess[i].isUseOfPostIncrementedValue)
1627       continue;
1628     ExtAddrMode AddrMode =
1629       AddressingModeMatcher::Match(UsersToProcess[i].OperandValToReplace,
1630                                    AccessTy, UsersToProcess[i].Inst,
1631                                    AddrModeInsts, *TLI);
1632     if (GV && GV != AddrMode.BaseGV)
1633       return false;
1634     if (Offset && !AddrMode.BaseOffs)
1635       // FIXME: How to accurate check it's immediate offset is folded.
1636       return false;
1637     AddrModeInsts.clear();
1638   }
1639   return true;
1640 }
1641
1642 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
1643 /// stride of IV.  All of the users may have different starting values, and this
1644 /// may not be the only stride.
1645 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
1646                                                       IVUsersOfOneStride &Uses,
1647                                                       Loop *L) {
1648   // If all the users are moved to another stride, then there is nothing to do.
1649   if (Uses.Users.empty())
1650     return;
1651
1652   // Keep track if every use in UsersToProcess is an address. If they all are,
1653   // we may be able to rewrite the entire collection of them in terms of a
1654   // smaller-stride IV.
1655   bool AllUsesAreAddresses = true;
1656
1657   // Keep track if every use of a single stride is outside the loop.  If so,
1658   // we want to be more aggressive about reusing a smaller-stride IV; a
1659   // multiply outside the loop is better than another IV inside.  Well, usually.
1660   bool AllUsesAreOutsideLoop = true;
1661
1662   // Transform our list of users and offsets to a bit more complex table.  In
1663   // this new vector, each 'BasedUser' contains 'Base' the base of the
1664   // strided accessas well as the old information from Uses.  We progressively
1665   // move information from the Base field to the Imm field, until we eventually
1666   // have the full access expression to rewrite the use.
1667   std::vector<BasedUser> UsersToProcess;
1668   SCEVHandle CommonExprs = CollectIVUsers(Stride, Uses, L, AllUsesAreAddresses,
1669                                           AllUsesAreOutsideLoop,
1670                                           UsersToProcess);
1671
1672   // Sort the UsersToProcess array so that users with common bases are
1673   // next to each other.
1674   SortUsersToProcess(UsersToProcess);
1675
1676   // If we managed to find some expressions in common, we'll need to carry
1677   // their value in a register and add it in for each use. This will take up
1678   // a register operand, which potentially restricts what stride values are
1679   // valid.
1680   bool HaveCommonExprs = !CommonExprs->isZero();
1681   const Type *ReplacedTy = CommonExprs->getType();
1682
1683   // If all uses are addresses, consider sinking the immediate part of the
1684   // common expression back into uses if they can fit in the immediate fields.
1685   if (TLI && HaveCommonExprs && AllUsesAreAddresses) {
1686     SCEVHandle NewCommon = CommonExprs;
1687     SCEVHandle Imm = SE->getIntegerSCEV(0, ReplacedTy);
1688     MoveImmediateValues(TLI, Type::VoidTy, NewCommon, Imm, true, L, SE);
1689     if (!Imm->isZero()) {
1690       bool DoSink = true;
1691
1692       // If the immediate part of the common expression is a GV, check if it's
1693       // possible to fold it into the target addressing mode.
1694       GlobalValue *GV = 0;
1695       if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(Imm))
1696         GV = dyn_cast<GlobalValue>(SU->getValue());
1697       int64_t Offset = 0;
1698       if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
1699         Offset = SC->getValue()->getSExtValue();
1700       if (GV || Offset)
1701         // Pass VoidTy as the AccessTy to be conservative, because
1702         // there could be multiple access types among all the uses.
1703         DoSink = IsImmFoldedIntoAddrMode(GV, Offset, Type::VoidTy,
1704                                          UsersToProcess, TLI);
1705
1706       if (DoSink) {
1707         DOUT << "  Sinking " << *Imm << " back down into uses\n";
1708         for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i)
1709           UsersToProcess[i].Imm = SE->getAddExpr(UsersToProcess[i].Imm, Imm);
1710         CommonExprs = NewCommon;
1711         HaveCommonExprs = !CommonExprs->isZero();
1712         ++NumImmSunk;
1713       }
1714     }
1715   }
1716
1717   // Now that we know what we need to do, insert the PHI node itself.
1718   //
1719   DOUT << "LSR: Examining IVs of TYPE " << *ReplacedTy << " of STRIDE "
1720        << *Stride << ":\n"
1721        << "  Common base: " << *CommonExprs << "\n";
1722
1723   SCEVExpander Rewriter(*SE, *LI);
1724   SCEVExpander PreheaderRewriter(*SE, *LI);
1725
1726   BasicBlock  *Preheader = L->getLoopPreheader();
1727   Instruction *PreInsertPt = Preheader->getTerminator();
1728   BasicBlock *LatchBlock = L->getLoopLatch();
1729
1730   Value *CommonBaseV = Constant::getNullValue(ReplacedTy);
1731
1732   SCEVHandle RewriteFactor = SE->getIntegerSCEV(0, ReplacedTy);
1733   IVExpr   ReuseIV(SE->getIntegerSCEV(0, Type::Int32Ty),
1734                    SE->getIntegerSCEV(0, Type::Int32Ty),
1735                    0);
1736
1737   /// Choose a strength-reduction strategy and prepare for it by creating
1738   /// the necessary PHIs and adjusting the bookkeeping.
1739   if (ShouldUseFullStrengthReductionMode(UsersToProcess, L,
1740                                          AllUsesAreAddresses, Stride)) {
1741     PrepareToStrengthReduceFully(UsersToProcess, Stride, CommonExprs, L,
1742                                  PreheaderRewriter);
1743   } else {
1744     // Emit the initial base value into the loop preheader.
1745     CommonBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, ReplacedTy,
1746                                                   PreInsertPt);
1747
1748     // If all uses are addresses, check if it is possible to reuse an IV with a
1749     // stride that is a factor of this stride. And that the multiple is a number
1750     // that can be encoded in the scale field of the target addressing mode. And
1751     // that we will have a valid instruction after this substition, including
1752     // the immediate field, if any.
1753     RewriteFactor = CheckForIVReuse(HaveCommonExprs, AllUsesAreAddresses,
1754                                     AllUsesAreOutsideLoop,
1755                                     Stride, ReuseIV, ReplacedTy,
1756                                     UsersToProcess);
1757     if (isa<SCEVConstant>(RewriteFactor) &&
1758         cast<SCEVConstant>(RewriteFactor)->isZero())
1759       PrepareToStrengthReduceWithNewPhi(UsersToProcess, Stride, CommonExprs,
1760                                         CommonBaseV, L, PreheaderRewriter);
1761     else
1762       PrepareToStrengthReduceFromSmallerStride(UsersToProcess, CommonBaseV,
1763                                                ReuseIV, PreInsertPt);
1764   }
1765
1766   // Process all the users now, replacing their strided uses with
1767   // strength-reduced forms.  This outer loop handles all bases, the inner
1768   // loop handles all users of a particular base.
1769   while (!UsersToProcess.empty()) {
1770     SCEVHandle Base = UsersToProcess.back().Base;
1771     Instruction *Inst = UsersToProcess.back().Inst;
1772
1773     // Emit the code for Base into the preheader.
1774     Value *BaseV = 0;
1775     if (!Base->isZero()) {
1776       BaseV = PreheaderRewriter.expandCodeFor(Base, Base->getType(),
1777                                               PreInsertPt);
1778
1779       DOUT << "  INSERTING code for BASE = " << *Base << ":";
1780       if (BaseV->hasName())
1781         DOUT << " Result value name = %" << BaseV->getNameStr();
1782       DOUT << "\n";
1783
1784       // If BaseV is a non-zero constant, make sure that it gets inserted into
1785       // the preheader, instead of being forward substituted into the uses.  We
1786       // do this by forcing a BitCast (noop cast) to be inserted into the
1787       // preheader in this case.
1788       if (!fitsInAddressMode(Base, getAccessType(Inst), TLI, false)) {
1789         // We want this constant emitted into the preheader! This is just
1790         // using cast as a copy so BitCast (no-op cast) is appropriate
1791         BaseV = new BitCastInst(BaseV, BaseV->getType(), "preheaderinsert",
1792                                 PreInsertPt);       
1793       }
1794     }
1795
1796     // Emit the code to add the immediate offset to the Phi value, just before
1797     // the instructions that we identified as using this stride and base.
1798     do {
1799       // FIXME: Use emitted users to emit other users.
1800       BasedUser &User = UsersToProcess.back();
1801
1802       DOUT << "    Examining use ";
1803       DEBUG(WriteAsOperand(*DOUT, UsersToProcess.back().OperandValToReplace,
1804                            /*PrintType=*/false));
1805       DOUT << " in Inst: " << *(User.Inst);
1806
1807       // If this instruction wants to use the post-incremented value, move it
1808       // after the post-inc and use its value instead of the PHI.
1809       Value *RewriteOp = User.Phi;
1810       if (User.isUseOfPostIncrementedValue) {
1811         RewriteOp = User.Phi->getIncomingValueForBlock(LatchBlock);
1812
1813         // If this user is in the loop, make sure it is the last thing in the
1814         // loop to ensure it is dominated by the increment.
1815         if (L->contains(User.Inst->getParent()))
1816           User.Inst->moveBefore(LatchBlock->getTerminator());
1817       }
1818
1819       SCEVHandle RewriteExpr = SE->getUnknown(RewriteOp);
1820
1821       if (SE->getTypeSizeInBits(RewriteOp->getType()) !=
1822           SE->getTypeSizeInBits(ReplacedTy)) {
1823         assert(SE->getTypeSizeInBits(RewriteOp->getType()) >
1824                SE->getTypeSizeInBits(ReplacedTy) &&
1825                "Unexpected widening cast!");
1826         RewriteExpr = SE->getTruncateExpr(RewriteExpr, ReplacedTy);
1827       }
1828
1829       // If we had to insert new instructions for RewriteOp, we have to
1830       // consider that they may not have been able to end up immediately
1831       // next to RewriteOp, because non-PHI instructions may never precede
1832       // PHI instructions in a block. In this case, remember where the last
1833       // instruction was inserted so that if we're replacing a different
1834       // PHI node, we can use the later point to expand the final
1835       // RewriteExpr.
1836       Instruction *NewBasePt = dyn_cast<Instruction>(RewriteOp);
1837       if (RewriteOp == User.Phi) NewBasePt = 0;
1838
1839       // Clear the SCEVExpander's expression map so that we are guaranteed
1840       // to have the code emitted where we expect it.
1841       Rewriter.clear();
1842
1843       // If we are reusing the iv, then it must be multiplied by a constant
1844       // factor to take advantage of the addressing mode scale component.
1845       if (!RewriteFactor->isZero()) {
1846         // If we're reusing an IV with a nonzero base (currently this happens
1847         // only when all reuses are outside the loop) subtract that base here.
1848         // The base has been used to initialize the PHI node but we don't want
1849         // it here.
1850         if (!ReuseIV.Base->isZero()) {
1851           SCEVHandle typedBase = ReuseIV.Base;
1852           if (SE->getTypeSizeInBits(RewriteExpr->getType()) !=
1853               SE->getTypeSizeInBits(ReuseIV.Base->getType())) {
1854             // It's possible the original IV is a larger type than the new IV,
1855             // in which case we have to truncate the Base.  We checked in
1856             // RequiresTypeConversion that this is valid.
1857             assert(SE->getTypeSizeInBits(RewriteExpr->getType()) <
1858                    SE->getTypeSizeInBits(ReuseIV.Base->getType()) &&
1859                    "Unexpected lengthening conversion!");
1860             typedBase = SE->getTruncateExpr(ReuseIV.Base, 
1861                                             RewriteExpr->getType());
1862           }
1863           RewriteExpr = SE->getMinusSCEV(RewriteExpr, typedBase);
1864         }
1865
1866         // Multiply old variable, with base removed, by new scale factor.
1867         RewriteExpr = SE->getMulExpr(RewriteFactor,
1868                                      RewriteExpr);
1869
1870         // The common base is emitted in the loop preheader. But since we
1871         // are reusing an IV, it has not been used to initialize the PHI node.
1872         // Add it to the expression used to rewrite the uses.
1873         // When this use is outside the loop, we earlier subtracted the
1874         // common base, and are adding it back here.  Use the same expression
1875         // as before, rather than CommonBaseV, so DAGCombiner will zap it.
1876         if (!CommonExprs->isZero()) {
1877           if (L->contains(User.Inst->getParent()))
1878             RewriteExpr = SE->getAddExpr(RewriteExpr,
1879                                        SE->getUnknown(CommonBaseV));
1880           else
1881             RewriteExpr = SE->getAddExpr(RewriteExpr, CommonExprs);
1882         }
1883       }
1884
1885       // Now that we know what we need to do, insert code before User for the
1886       // immediate and any loop-variant expressions.
1887       if (BaseV)
1888         // Add BaseV to the PHI value if needed.
1889         RewriteExpr = SE->getAddExpr(RewriteExpr, SE->getUnknown(BaseV));
1890
1891       User.RewriteInstructionToUseNewBase(RewriteExpr, NewBasePt,
1892                                           Rewriter, L, this,
1893                                           DeadInsts);
1894
1895       // Mark old value we replaced as possibly dead, so that it is eliminated
1896       // if we just replaced the last use of that value.
1897       DeadInsts.push_back(cast<Instruction>(User.OperandValToReplace));
1898
1899       UsersToProcess.pop_back();
1900       ++NumReduced;
1901
1902       // If there are any more users to process with the same base, process them
1903       // now.  We sorted by base above, so we just have to check the last elt.
1904     } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1905     // TODO: Next, find out which base index is the most common, pull it out.
1906   }
1907
1908   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1909   // different starting values, into different PHIs.
1910 }
1911
1912 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1913 /// set the IV user and stride information and return true, otherwise return
1914 /// false.
1915 bool LoopStrengthReduce::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse,
1916                                        const SCEVHandle *&CondStride) {
1917   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1918        ++Stride) {
1919     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
1920     IVUsesByStride.find(StrideOrder[Stride]);
1921     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1922     
1923     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1924          E = SI->second.Users.end(); UI != E; ++UI)
1925       if (UI->User == Cond) {
1926         // NOTE: we could handle setcc instructions with multiple uses here, but
1927         // InstCombine does it as well for simple uses, it's not clear that it
1928         // occurs enough in real life to handle.
1929         CondUse = &*UI;
1930         CondStride = &SI->first;
1931         return true;
1932       }
1933   }
1934   return false;
1935 }    
1936
1937 namespace {
1938   // Constant strides come first which in turns are sorted by their absolute
1939   // values. If absolute values are the same, then positive strides comes first.
1940   // e.g.
1941   // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1942   struct StrideCompare {
1943     const ScalarEvolution *SE;
1944     explicit StrideCompare(const ScalarEvolution *se) : SE(se) {}
1945
1946     bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1947       const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1948       const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1949       if (LHSC && RHSC) {
1950         int64_t  LV = LHSC->getValue()->getSExtValue();
1951         int64_t  RV = RHSC->getValue()->getSExtValue();
1952         uint64_t ALV = (LV < 0) ? -LV : LV;
1953         uint64_t ARV = (RV < 0) ? -RV : RV;
1954         if (ALV == ARV) {
1955           if (LV != RV)
1956             return LV > RV;
1957         } else {
1958           return ALV < ARV;
1959         }
1960
1961         // If it's the same value but different type, sort by bit width so
1962         // that we emit larger induction variables before smaller
1963         // ones, letting the smaller be re-written in terms of larger ones.
1964         return SE->getTypeSizeInBits(RHS->getType()) <
1965                SE->getTypeSizeInBits(LHS->getType());
1966       }
1967       return LHSC && !RHSC;
1968     }
1969   };
1970 }
1971
1972 /// ChangeCompareStride - If a loop termination compare instruction is the
1973 /// only use of its stride, and the compaison is against a constant value,
1974 /// try eliminate the stride by moving the compare instruction to another
1975 /// stride and change its constant operand accordingly. e.g.
1976 ///
1977 /// loop:
1978 /// ...
1979 /// v1 = v1 + 3
1980 /// v2 = v2 + 1
1981 /// if (v2 < 10) goto loop
1982 /// =>
1983 /// loop:
1984 /// ...
1985 /// v1 = v1 + 3
1986 /// if (v1 < 30) goto loop
1987 ICmpInst *LoopStrengthReduce::ChangeCompareStride(Loop *L, ICmpInst *Cond,
1988                                                 IVStrideUse* &CondUse,
1989                                                 const SCEVHandle* &CondStride) {
1990   if (StrideOrder.size() < 2 ||
1991       IVUsesByStride[*CondStride].Users.size() != 1)
1992     return Cond;
1993   const SCEVConstant *SC = dyn_cast<SCEVConstant>(*CondStride);
1994   if (!SC) return Cond;
1995
1996   ICmpInst::Predicate Predicate = Cond->getPredicate();
1997   int64_t CmpSSInt = SC->getValue()->getSExtValue();
1998   unsigned BitWidth = SE->getTypeSizeInBits((*CondStride)->getType());
1999   uint64_t SignBit = 1ULL << (BitWidth-1);
2000   const Type *CmpTy = Cond->getOperand(0)->getType();
2001   const Type *NewCmpTy = NULL;
2002   unsigned TyBits = SE->getTypeSizeInBits(CmpTy);
2003   unsigned NewTyBits = 0;
2004   SCEVHandle *NewStride = NULL;
2005   Value *NewCmpLHS = NULL;
2006   Value *NewCmpRHS = NULL;
2007   int64_t Scale = 1;
2008   SCEVHandle NewOffset = SE->getIntegerSCEV(0, CmpTy);
2009
2010   if (ConstantInt *C = dyn_cast<ConstantInt>(Cond->getOperand(1))) {
2011     int64_t CmpVal = C->getValue().getSExtValue();
2012
2013     // Check stride constant and the comparision constant signs to detect
2014     // overflow.
2015     if ((CmpVal & SignBit) != (CmpSSInt & SignBit))
2016       return Cond;
2017
2018     // Look for a suitable stride / iv as replacement.
2019     for (unsigned i = 0, e = StrideOrder.size(); i != e; ++i) {
2020       std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
2021         IVUsesByStride.find(StrideOrder[i]);
2022       if (!isa<SCEVConstant>(SI->first))
2023         continue;
2024       int64_t SSInt = cast<SCEVConstant>(SI->first)->getValue()->getSExtValue();
2025       if (SSInt == CmpSSInt ||
2026           abs(SSInt) < abs(CmpSSInt) ||
2027           (SSInt % CmpSSInt) != 0)
2028         continue;
2029
2030       Scale = SSInt / CmpSSInt;
2031       int64_t NewCmpVal = CmpVal * Scale;
2032       APInt Mul = APInt(BitWidth, NewCmpVal);
2033       // Check for overflow.
2034       if (Mul.getSExtValue() != NewCmpVal)
2035         continue;
2036
2037       // Watch out for overflow.
2038       if (ICmpInst::isSignedPredicate(Predicate) &&
2039           (CmpVal & SignBit) != (NewCmpVal & SignBit))
2040         continue;
2041
2042       if (NewCmpVal == CmpVal)
2043         continue;
2044       // Pick the best iv to use trying to avoid a cast.
2045       NewCmpLHS = NULL;
2046       for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2047              E = SI->second.Users.end(); UI != E; ++UI) {
2048         NewCmpLHS = UI->OperandValToReplace;
2049         if (NewCmpLHS->getType() == CmpTy)
2050           break;
2051       }
2052       if (!NewCmpLHS)
2053         continue;
2054
2055       NewCmpTy = NewCmpLHS->getType();
2056       NewTyBits = SE->getTypeSizeInBits(NewCmpTy);
2057       const Type *NewCmpIntTy = IntegerType::get(NewTyBits);
2058       if (RequiresTypeConversion(NewCmpTy, CmpTy)) {
2059         // Check if it is possible to rewrite it using
2060         // an iv / stride of a smaller integer type.
2061         unsigned Bits = NewTyBits;
2062         if (ICmpInst::isSignedPredicate(Predicate))
2063           --Bits;
2064         uint64_t Mask = (1ULL << Bits) - 1;
2065         if (((uint64_t)NewCmpVal & Mask) != (uint64_t)NewCmpVal)
2066           continue;
2067       }
2068
2069       // Don't rewrite if use offset is non-constant and the new type is
2070       // of a different type.
2071       // FIXME: too conservative?
2072       if (NewTyBits != TyBits && !isa<SCEVConstant>(CondUse->Offset))
2073         continue;
2074
2075       bool AllUsesAreAddresses = true;
2076       bool AllUsesAreOutsideLoop = true;
2077       std::vector<BasedUser> UsersToProcess;
2078       SCEVHandle CommonExprs = CollectIVUsers(SI->first, SI->second, L,
2079                                               AllUsesAreAddresses,
2080                                               AllUsesAreOutsideLoop,
2081                                               UsersToProcess);
2082       // Avoid rewriting the compare instruction with an iv of new stride
2083       // if it's likely the new stride uses will be rewritten using the
2084       // stride of the compare instruction.
2085       if (AllUsesAreAddresses &&
2086           ValidStride(!CommonExprs->isZero(), Scale, UsersToProcess))
2087         continue;
2088
2089       // If scale is negative, use swapped predicate unless it's testing
2090       // for equality.
2091       if (Scale < 0 && !Cond->isEquality())
2092         Predicate = ICmpInst::getSwappedPredicate(Predicate);
2093
2094       NewStride = &StrideOrder[i];
2095       if (!isa<PointerType>(NewCmpTy))
2096         NewCmpRHS = ConstantInt::get(NewCmpTy, NewCmpVal);
2097       else {
2098         ConstantInt *CI = ConstantInt::get(NewCmpIntTy, NewCmpVal);
2099         NewCmpRHS = ConstantExpr::getIntToPtr(CI, NewCmpTy);
2100       }
2101       NewOffset = TyBits == NewTyBits
2102         ? SE->getMulExpr(CondUse->Offset,
2103                          SE->getConstant(ConstantInt::get(CmpTy, Scale)))
2104         : SE->getConstant(ConstantInt::get(NewCmpIntTy,
2105           cast<SCEVConstant>(CondUse->Offset)->getValue()->getSExtValue()*Scale));
2106       break;
2107     }
2108   }
2109
2110   // Forgo this transformation if it the increment happens to be
2111   // unfortunately positioned after the condition, and the condition
2112   // has multiple uses which prevent it from being moved immediately
2113   // before the branch. See
2114   // test/Transforms/LoopStrengthReduce/change-compare-stride-trickiness-*.ll
2115   // for an example of this situation.
2116   if (!Cond->hasOneUse()) {
2117     for (BasicBlock::iterator I = Cond, E = Cond->getParent()->end();
2118          I != E; ++I)
2119       if (I == NewCmpLHS)
2120         return Cond;
2121   }
2122
2123   if (NewCmpRHS) {
2124     // Create a new compare instruction using new stride / iv.
2125     ICmpInst *OldCond = Cond;
2126     // Insert new compare instruction.
2127     Cond = new ICmpInst(Predicate, NewCmpLHS, NewCmpRHS,
2128                         L->getHeader()->getName() + ".termcond",
2129                         OldCond);
2130
2131     // Remove the old compare instruction. The old indvar is probably dead too.
2132     DeadInsts.push_back(cast<Instruction>(CondUse->OperandValToReplace));
2133     SE->deleteValueFromRecords(OldCond);
2134     OldCond->replaceAllUsesWith(Cond);
2135     OldCond->eraseFromParent();
2136
2137     IVUsesByStride[*CondStride].Users.pop_back();
2138     IVUsesByStride[*NewStride].addUser(NewOffset, Cond, NewCmpLHS);
2139     CondUse = &IVUsesByStride[*NewStride].Users.back();
2140     CondStride = NewStride;
2141     ++NumEliminated;
2142     Changed = true;
2143   }
2144
2145   return Cond;
2146 }
2147
2148 /// OptimizeSMax - Rewrite the loop's terminating condition if it uses
2149 /// an smax computation.
2150 ///
2151 /// This is a narrow solution to a specific, but acute, problem. For loops
2152 /// like this:
2153 ///
2154 ///   i = 0;
2155 ///   do {
2156 ///     p[i] = 0.0;
2157 ///   } while (++i < n);
2158 ///
2159 /// where the comparison is signed, the trip count isn't just 'n', because
2160 /// 'n' could be negative. And unfortunately this can come up even for loops
2161 /// where the user didn't use a C do-while loop. For example, seemingly
2162 /// well-behaved top-test loops will commonly be lowered like this:
2163 //
2164 ///   if (n > 0) {
2165 ///     i = 0;
2166 ///     do {
2167 ///       p[i] = 0.0;
2168 ///     } while (++i < n);
2169 ///   }
2170 ///
2171 /// and then it's possible for subsequent optimization to obscure the if
2172 /// test in such a way that indvars can't find it.
2173 ///
2174 /// When indvars can't find the if test in loops like this, it creates a
2175 /// signed-max expression, which allows it to give the loop a canonical
2176 /// induction variable:
2177 ///
2178 ///   i = 0;
2179 ///   smax = n < 1 ? 1 : n;
2180 ///   do {
2181 ///     p[i] = 0.0;
2182 ///   } while (++i != smax);
2183 ///
2184 /// Canonical induction variables are necessary because the loop passes
2185 /// are designed around them. The most obvious example of this is the
2186 /// LoopInfo analysis, which doesn't remember trip count values. It
2187 /// expects to be able to rediscover the trip count each time it is
2188 /// needed, and it does this using a simple analyis that only succeeds if
2189 /// the loop has a canonical induction variable.
2190 ///
2191 /// However, when it comes time to generate code, the maximum operation
2192 /// can be quite costly, especially if it's inside of an outer loop.
2193 ///
2194 /// This function solves this problem by detecting this type of loop and
2195 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2196 /// the instructions for the maximum computation.
2197 ///
2198 ICmpInst *LoopStrengthReduce::OptimizeSMax(Loop *L, ICmpInst *Cond,
2199                                            IVStrideUse* &CondUse) {
2200   // Check that the loop matches the pattern we're looking for.
2201   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2202       Cond->getPredicate() != CmpInst::ICMP_NE)
2203     return Cond;
2204
2205   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2206   if (!Sel || !Sel->hasOneUse()) return Cond;
2207
2208   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2209   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2210     return Cond;
2211   SCEVHandle One = SE->getIntegerSCEV(1, BackedgeTakenCount->getType());
2212
2213   // Add one to the backedge-taken count to get the trip count.
2214   SCEVHandle IterationCount = SE->getAddExpr(BackedgeTakenCount, One);
2215
2216   // Check for a max calculation that matches the pattern.
2217   SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(IterationCount);
2218   if (!SMax || SMax != SE->getSCEV(Sel)) return Cond;
2219
2220   SCEVHandle SMaxLHS = SMax->getOperand(0);
2221   SCEVHandle SMaxRHS = SMax->getOperand(1);
2222   if (!SMaxLHS || SMaxLHS != One) return Cond;
2223
2224   // Check the relevant induction variable for conformance to
2225   // the pattern.
2226   SCEVHandle IV = SE->getSCEV(Cond->getOperand(0));
2227   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2228   if (!AR || !AR->isAffine() ||
2229       AR->getStart() != One ||
2230       AR->getStepRecurrence(*SE) != One)
2231     return Cond;
2232
2233   assert(AR->getLoop() == L &&
2234          "Loop condition operand is an addrec in a different loop!");
2235
2236   // Check the right operand of the select, and remember it, as it will
2237   // be used in the new comparison instruction.
2238   Value *NewRHS = 0;
2239   if (SE->getSCEV(Sel->getOperand(1)) == SMaxRHS)
2240     NewRHS = Sel->getOperand(1);
2241   else if (SE->getSCEV(Sel->getOperand(2)) == SMaxRHS)
2242     NewRHS = Sel->getOperand(2);
2243   if (!NewRHS) return Cond;
2244
2245   // Ok, everything looks ok to change the condition into an SLT or SGE and
2246   // delete the max calculation.
2247   ICmpInst *NewCond =
2248     new ICmpInst(Cond->getPredicate() == CmpInst::ICMP_NE ?
2249                    CmpInst::ICMP_SLT :
2250                    CmpInst::ICMP_SGE,
2251                  Cond->getOperand(0), NewRHS, "scmp", Cond);
2252
2253   // Delete the max calculation instructions.
2254   SE->deleteValueFromRecords(Cond);
2255   Cond->replaceAllUsesWith(NewCond);
2256   Cond->eraseFromParent();
2257   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2258   SE->deleteValueFromRecords(Sel);
2259   Sel->eraseFromParent();
2260   if (Cmp->use_empty()) {
2261     SE->deleteValueFromRecords(Cmp);
2262     Cmp->eraseFromParent();
2263   }
2264   CondUse->User = NewCond;
2265   return NewCond;
2266 }
2267
2268 /// OptimizeShadowIV - If IV is used in a int-to-float cast
2269 /// inside the loop then try to eliminate the cast opeation.
2270 void LoopStrengthReduce::OptimizeShadowIV(Loop *L) {
2271
2272   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2273   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2274     return;
2275
2276   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e;
2277        ++Stride) {
2278     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
2279       IVUsesByStride.find(StrideOrder[Stride]);
2280     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2281     if (!isa<SCEVConstant>(SI->first))
2282       continue;
2283
2284     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
2285            E = SI->second.Users.end(); UI != E; /* empty */) {
2286       std::vector<IVStrideUse>::iterator CandidateUI = UI;
2287       ++UI;
2288       Instruction *ShadowUse = CandidateUI->User;
2289       const Type *DestTy = NULL;
2290
2291       /* If shadow use is a int->float cast then insert a second IV
2292          to eliminate this cast.
2293
2294            for (unsigned i = 0; i < n; ++i) 
2295              foo((double)i);
2296
2297          is transformed into
2298
2299            double d = 0.0;
2300            for (unsigned i = 0; i < n; ++i, ++d) 
2301              foo(d);
2302       */
2303       if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->User))
2304         DestTy = UCast->getDestTy();
2305       else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->User))
2306         DestTy = SCast->getDestTy();
2307       if (!DestTy) continue;
2308
2309       if (TLI) {
2310         /* If target does not support DestTy natively then do not apply
2311            this transformation. */
2312         MVT DVT = TLI->getValueType(DestTy);
2313         if (!TLI->isTypeLegal(DVT)) continue;
2314       }
2315
2316       PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2317       if (!PH) continue;
2318       if (PH->getNumIncomingValues() != 2) continue;
2319
2320       const Type *SrcTy = PH->getType();
2321       int Mantissa = DestTy->getFPMantissaWidth();
2322       if (Mantissa == -1) continue; 
2323       if ((int)SE->getTypeSizeInBits(SrcTy) > Mantissa)
2324         continue;
2325
2326       unsigned Entry, Latch;
2327       if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2328         Entry = 0;
2329         Latch = 1;
2330       } else {
2331         Entry = 1;
2332         Latch = 0;
2333       }
2334         
2335       ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2336       if (!Init) continue;
2337       ConstantFP *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
2338
2339       BinaryOperator *Incr = 
2340         dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2341       if (!Incr) continue;
2342       if (Incr->getOpcode() != Instruction::Add
2343           && Incr->getOpcode() != Instruction::Sub)
2344         continue;
2345
2346       /* Initialize new IV, double d = 0.0 in above example. */
2347       ConstantInt *C = NULL;
2348       if (Incr->getOperand(0) == PH)
2349         C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2350       else if (Incr->getOperand(1) == PH)
2351         C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2352       else
2353         continue;
2354
2355       if (!C) continue;
2356
2357       /* Add new PHINode. */
2358       PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
2359
2360       /* create new increment. '++d' in above example. */
2361       ConstantFP *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2362       BinaryOperator *NewIncr = 
2363         BinaryOperator::Create(Incr->getOpcode(),
2364                                NewPH, CFP, "IV.S.next.", Incr);
2365
2366       NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2367       NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2368
2369       /* Remove cast operation */
2370       SE->deleteValueFromRecords(ShadowUse);
2371       ShadowUse->replaceAllUsesWith(NewPH);
2372       ShadowUse->eraseFromParent();
2373       SI->second.Users.erase(CandidateUI);
2374       NumShadow++;
2375       break;
2376     }
2377   }
2378 }
2379
2380 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
2381 // uses in the loop, look to see if we can eliminate some, in favor of using
2382 // common indvars for the different uses.
2383 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
2384   // TODO: implement optzns here.
2385
2386   OptimizeShadowIV(L);
2387
2388   // Finally, get the terminating condition for the loop if possible.  If we
2389   // can, we want to change it to use a post-incremented version of its
2390   // induction variable, to allow coalescing the live ranges for the IV into
2391   // one register value.
2392   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
2393   BasicBlock  *Preheader = L->getLoopPreheader();
2394   BasicBlock *LatchBlock =
2395    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
2396   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
2397   if (!TermBr || TermBr->isUnconditional() || 
2398       !isa<ICmpInst>(TermBr->getCondition()))
2399     return;
2400   ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2401
2402   // Search IVUsesByStride to find Cond's IVUse if there is one.
2403   IVStrideUse *CondUse = 0;
2404   const SCEVHandle *CondStride = 0;
2405
2406   if (!FindIVUserForCond(Cond, CondUse, CondStride))
2407     return; // setcc doesn't use the IV.
2408
2409   // If the trip count is computed in terms of an smax (due to ScalarEvolution
2410   // being unable to find a sufficient guard, for example), change the loop
2411   // comparison to use SLT instead of NE.
2412   Cond = OptimizeSMax(L, Cond, CondUse);
2413
2414   // If possible, change stride and operands of the compare instruction to
2415   // eliminate one stride.
2416   Cond = ChangeCompareStride(L, Cond, CondUse, CondStride);
2417
2418   // It's possible for the setcc instruction to be anywhere in the loop, and
2419   // possible for it to have multiple users.  If it is not immediately before
2420   // the latch block branch, move it.
2421   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
2422     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
2423       Cond->moveBefore(TermBr);
2424     } else {
2425       // Otherwise, clone the terminating condition and insert into the loopend.
2426       Cond = cast<ICmpInst>(Cond->clone());
2427       Cond->setName(L->getHeader()->getName() + ".termcond");
2428       LatchBlock->getInstList().insert(TermBr, Cond);
2429       
2430       // Clone the IVUse, as the old use still exists!
2431       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
2432                                          CondUse->OperandValToReplace);
2433       CondUse = &IVUsesByStride[*CondStride].Users.back();
2434     }
2435   }
2436
2437   // If we get to here, we know that we can transform the setcc instruction to
2438   // use the post-incremented version of the IV, allowing us to coalesce the
2439   // live ranges for the IV correctly.
2440   CondUse->Offset = SE->getMinusSCEV(CondUse->Offset, *CondStride);
2441   CondUse->isUseOfPostIncrementedValue = true;
2442   Changed = true;
2443 }
2444
2445 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager &LPM) {
2446
2447   LI = &getAnalysis<LoopInfo>();
2448   DT = &getAnalysis<DominatorTree>();
2449   SE = &getAnalysis<ScalarEvolution>();
2450   Changed = false;
2451
2452   // Find all uses of induction variables in this loop, and categorize
2453   // them by stride.  Start by finding all of the PHI nodes in the header for
2454   // this loop.  If they are induction variables, inspect their uses.
2455   SmallPtrSet<Instruction*,16> Processed;   // Don't reprocess instructions.
2456   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
2457     AddUsersIfInteresting(I, L, Processed);
2458
2459   if (!IVUsesByStride.empty()) {
2460 #ifndef NDEBUG
2461     DOUT << "\nLSR on \"" << L->getHeader()->getParent()->getNameStart()
2462          << "\" ";
2463     DEBUG(L->dump());
2464 #endif
2465
2466     // Sort the StrideOrder so we process larger strides first.
2467     std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare(SE));
2468
2469     // Optimize induction variables.  Some indvar uses can be transformed to use
2470     // strides that will be needed for other purposes.  A common example of this
2471     // is the exit test for the loop, which can often be rewritten to use the
2472     // computation of some other indvar to decide when to terminate the loop.
2473     OptimizeIndvars(L);
2474
2475     // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
2476     // doing computation in byte values, promote to 32-bit values if safe.
2477
2478     // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
2479     // could have something like "for(i) { foo(i*8); bar(i*16) }", which should
2480     // be codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.
2481     // Need to be careful that IV's are all the same type.  Only works for
2482     // intptr_t indvars.
2483
2484     // IVsByStride keeps IVs for one particular loop.
2485     assert(IVsByStride.empty() && "Stale entries in IVsByStride?");
2486
2487     // Note: this processes each stride/type pair individually.  All users
2488     // passed into StrengthReduceStridedIVUsers have the same type AND stride.
2489     // Also, note that we iterate over IVUsesByStride indirectly by using
2490     // StrideOrder. This extra layer of indirection makes the ordering of
2491     // strides deterministic - not dependent on map order.
2492     for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
2493       std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
2494         IVUsesByStride.find(StrideOrder[Stride]);
2495       assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
2496       StrengthReduceStridedIVUsers(SI->first, SI->second, L);
2497     }
2498   }
2499
2500   // We're done analyzing this loop; release all the state we built up for it.
2501   IVUsesByStride.clear();
2502   IVsByStride.clear();
2503   StrideOrder.clear();
2504
2505   // Clean up after ourselves
2506   if (!DeadInsts.empty())
2507     DeleteTriviallyDeadInstructions();
2508
2509   // At this point, it is worth checking to see if any recurrence PHIs are also
2510   // dead, so that we can remove them as well. To keep ScalarEvolution
2511   // current, use a ValueDeletionListener class.
2512   struct LSRListener : public ValueDeletionListener {
2513     ScalarEvolution &SE;
2514     explicit LSRListener(ScalarEvolution &se) : SE(se) {}
2515
2516     virtual void ValueWillBeDeleted(Value *V) {
2517       SE.deleteValueFromRecords(V);
2518     }
2519   } VDL(*SE);
2520   DeleteDeadPHIs(L->getHeader(), &VDL);
2521
2522   return Changed;
2523 }