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