s|llvm/Support/Visibility.h|llvm/Support/Compiler.h|
[oota-llvm.git] / lib / Transforms / Scalar / LoopStrengthReduce.cpp
1 //===- LoopStrengthReduce.cpp - Strength Reduce GEPs in Loops -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source 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.  This is
12 // accomplished by creating a new Value to hold the initial value of the array
13 // access for the first iteration, and then creating a new GEP instruction in
14 // the loop to increment the value by the appropriate amount.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "loop-reduce"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Type.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/ScalarEvolutionExpander.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include <algorithm>
37 #include <iostream>
38 #include <set>
39 using namespace llvm;
40
41 namespace {
42   Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
43   Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
44   Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
45
46   /// IVStrideUse - Keep track of one use of a strided induction variable, where
47   /// the stride is stored externally.  The Offset member keeps track of the 
48   /// offset from the IV, User is the actual user of the operand, and 'Operand'
49   /// is the operand # of the User that is the use.
50   struct IVStrideUse {
51     SCEVHandle Offset;
52     Instruction *User;
53     Value *OperandValToReplace;
54
55     // isUseOfPostIncrementedValue - True if this should use the
56     // post-incremented version of this IV, not the preincremented version.
57     // This can only be set in special cases, such as the terminating setcc
58     // instruction for a loop or uses dominated by the loop.
59     bool isUseOfPostIncrementedValue;
60     
61     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
62       : Offset(Offs), User(U), OperandValToReplace(O),
63         isUseOfPostIncrementedValue(false) {}
64   };
65   
66   /// IVUsersOfOneStride - This structure keeps track of all instructions that
67   /// have an operand that is based on the trip count multiplied by some stride.
68   /// The stride for all of these users is common and kept external to this
69   /// structure.
70   struct IVUsersOfOneStride {
71     /// Users - Keep track of all of the users of this stride as well as the
72     /// initial value and the operand that uses the IV.
73     std::vector<IVStrideUse> Users;
74     
75     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
76       Users.push_back(IVStrideUse(Offset, User, Operand));
77     }
78   };
79
80   /// IVInfo - This structure keeps track of one IV expression inserted during
81   /// StrengthReduceStridedIVUsers. It contains the stride, the common base, as
82   /// well as the PHI node and increment value created for rewrite.
83   struct IVExpr {
84     SCEVHandle  Stride;
85     SCEVHandle  Base;
86     PHINode    *PHI;
87     Value      *IncV;
88
89     IVExpr()
90       : Stride(SCEVUnknown::getIntegerSCEV(0, Type::UIntTy)),
91         Base  (SCEVUnknown::getIntegerSCEV(0, Type::UIntTy)) {}
92     IVExpr(const SCEVHandle &stride, const SCEVHandle &base, PHINode *phi,
93            Value *incv)
94       : Stride(stride), Base(base), PHI(phi), IncV(incv) {}
95   };
96
97   /// IVsOfOneStride - This structure keeps track of all IV expression inserted
98   /// during StrengthReduceStridedIVUsers for a particular stride of the IV.
99   struct IVsOfOneStride {
100     std::vector<IVExpr> IVs;
101
102     void addIV(const SCEVHandle &Stride, const SCEVHandle &Base, PHINode *PHI,
103                Value *IncV) {
104       IVs.push_back(IVExpr(Stride, Base, PHI, IncV));
105     }
106   };
107
108   class VISIBILITY_HIDDEN LoopStrengthReduce : public FunctionPass {
109     LoopInfo *LI;
110     ETForest *EF;
111     ScalarEvolution *SE;
112     const TargetData *TD;
113     const Type *UIntPtrTy;
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     std::vector<SCEVHandle> StrideOrder;
128
129     /// CastedValues - As we need to cast values to uintptr_t, this keeps track
130     /// of the casted version of each value.  This is accessed by
131     /// getCastedVersionOf.
132     std::map<Value*, Value*> CastedPointers;
133
134     /// DeadInsts - Keep track of instructions we may have made dead, so that
135     /// we can remove them after we are done working.
136     std::set<Instruction*> DeadInsts;
137
138     /// TLI - Keep a pointer of a TargetLowering to consult for determining
139     /// transformation profitability.
140     const TargetLowering *TLI;
141
142   public:
143     LoopStrengthReduce(const TargetLowering *tli = NULL)
144       : TLI(tli) {
145     }
146
147     virtual bool runOnFunction(Function &) {
148       LI = &getAnalysis<LoopInfo>();
149       EF = &getAnalysis<ETForest>();
150       SE = &getAnalysis<ScalarEvolution>();
151       TD = &getAnalysis<TargetData>();
152       UIntPtrTy = TD->getIntPtrType();
153       Changed = false;
154
155       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
156         runOnLoop(*I);
157       
158       return Changed;
159     }
160
161     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162       // We split critical edges, so we change the CFG.  However, we do update
163       // many analyses if they are around.
164       AU.addPreservedID(LoopSimplifyID);
165       AU.addPreserved<LoopInfo>();
166       AU.addPreserved<DominatorSet>();
167       AU.addPreserved<ETForest>();
168       AU.addPreserved<ImmediateDominators>();
169       AU.addPreserved<DominanceFrontier>();
170       AU.addPreserved<DominatorTree>();
171
172       AU.addRequiredID(LoopSimplifyID);
173       AU.addRequired<LoopInfo>();
174       AU.addRequired<ETForest>();
175       AU.addRequired<TargetData>();
176       AU.addRequired<ScalarEvolution>();
177     }
178     
179     /// getCastedVersionOf - Return the specified value casted to uintptr_t.
180     ///
181     Value *getCastedVersionOf(Value *V);
182 private:
183     void runOnLoop(Loop *L);
184     bool AddUsersIfInteresting(Instruction *I, Loop *L,
185                                std::set<Instruction*> &Processed);
186     SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
187
188     void OptimizeIndvars(Loop *L);
189
190     unsigned CheckForIVReuse(const SCEVHandle&, IVExpr&, const Type*);
191
192     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
193                                       IVUsersOfOneStride &Uses,
194                                       Loop *L, bool isOnlyStride);
195     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
196   };
197   RegisterOpt<LoopStrengthReduce> X("loop-reduce",
198                                     "Loop Strength Reduction");
199 }
200
201 FunctionPass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
202   return new LoopStrengthReduce(TLI);
203 }
204
205 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
206 ///
207 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
208   if (V->getType() == UIntPtrTy) return V;
209   if (Constant *CB = dyn_cast<Constant>(V))
210     return ConstantExpr::getCast(CB, UIntPtrTy);
211
212   Value *&New = CastedPointers[V];
213   if (New) return New;
214   
215   New = SCEVExpander::InsertCastOfTo(V, UIntPtrTy);
216   DeadInsts.insert(cast<Instruction>(New));
217   return New;
218 }
219
220
221 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
222 /// specified set are trivially dead, delete them and see if this makes any of
223 /// their operands subsequently dead.
224 void LoopStrengthReduce::
225 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
226   while (!Insts.empty()) {
227     Instruction *I = *Insts.begin();
228     Insts.erase(Insts.begin());
229     if (isInstructionTriviallyDead(I)) {
230       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
231         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
232           Insts.insert(U);
233       SE->deleteInstructionFromRecords(I);
234       I->eraseFromParent();
235       Changed = true;
236     }
237   }
238 }
239
240
241 /// GetExpressionSCEV - Compute and return the SCEV for the specified
242 /// instruction.
243 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
244   // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
245   // If this is a GEP that SE doesn't know about, compute it now and insert it.
246   // If this is not a GEP, or if we have already done this computation, just let
247   // SE figure it out.
248   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
249   if (!GEP || SE->hasSCEV(GEP))
250     return SE->getSCEV(Exp);
251     
252   // Analyze all of the subscripts of this getelementptr instruction, looking
253   // for uses that are determined by the trip count of L.  First, skip all
254   // operands the are not dependent on the IV.
255
256   // Build up the base expression.  Insert an LLVM cast of the pointer to
257   // uintptr_t first.
258   SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
259
260   gep_type_iterator GTI = gep_type_begin(GEP);
261   
262   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
263     // If this is a use of a recurrence that we can analyze, and it comes before
264     // Op does in the GEP operand list, we will handle this when we process this
265     // operand.
266     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
267       const StructLayout *SL = TD->getStructLayout(STy);
268       unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
269       uint64_t Offset = SL->MemberOffsets[Idx];
270       GEPVal = SCEVAddExpr::get(GEPVal,
271                                 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
272     } else {
273       Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
274       SCEVHandle Idx = SE->getSCEV(OpVal);
275
276       uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
277       if (TypeSize != 1)
278         Idx = SCEVMulExpr::get(Idx,
279                                SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
280                                                                    TypeSize)));
281       GEPVal = SCEVAddExpr::get(GEPVal, Idx);
282     }
283   }
284
285   SE->setSCEV(GEP, GEPVal);
286   return GEPVal;
287 }
288
289 /// getSCEVStartAndStride - Compute the start and stride of this expression,
290 /// returning false if the expression is not a start/stride pair, or true if it
291 /// is.  The stride must be a loop invariant expression, but the start may be
292 /// a mix of loop invariant and loop variant expressions.
293 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
294                                   SCEVHandle &Start, SCEVHandle &Stride) {
295   SCEVHandle TheAddRec = Start;   // Initialize to zero.
296
297   // If the outer level is an AddExpr, the operands are all start values except
298   // for a nested AddRecExpr.
299   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
300     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
301       if (SCEVAddRecExpr *AddRec =
302              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
303         if (AddRec->getLoop() == L)
304           TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
305         else
306           return false;  // Nested IV of some sort?
307       } else {
308         Start = SCEVAddExpr::get(Start, AE->getOperand(i));
309       }
310         
311   } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
312     TheAddRec = SH;
313   } else {
314     return false;  // not analyzable.
315   }
316   
317   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
318   if (!AddRec || AddRec->getLoop() != L) return false;
319   
320   // FIXME: Generalize to non-affine IV's.
321   if (!AddRec->isAffine()) return false;
322
323   Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
324   
325   if (!isa<SCEVConstant>(AddRec->getOperand(1)))
326     DEBUG(std::cerr << "[" << L->getHeader()->getName()
327                     << "] Variable stride: " << *AddRec << "\n");
328
329   Stride = AddRec->getOperand(1);
330   // Check that all constant strides are the unsigned type, we don't want to
331   // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
332   // merged.
333   assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
334          "Constants should be canonicalized to unsigned!");
335
336   return true;
337 }
338
339 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
340 /// and now we need to decide whether the user should use the preinc or post-inc
341 /// value.  If this user should use the post-inc version of the IV, return true.
342 ///
343 /// Choosing wrong here can break dominance properties (if we choose to use the
344 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
345 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
346 /// should use the post-inc value).
347 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
348                                        Loop *L, ETForest *EF, Pass *P) {
349   // If the user is in the loop, use the preinc value.
350   if (L->contains(User->getParent())) return false;
351   
352   BasicBlock *LatchBlock = L->getLoopLatch();
353   
354   // Ok, the user is outside of the loop.  If it is dominated by the latch
355   // block, use the post-inc value.
356   if (EF->dominates(LatchBlock, User->getParent()))
357     return true;
358
359   // There is one case we have to be careful of: PHI nodes.  These little guys
360   // can live in blocks that do not dominate the latch block, but (since their
361   // uses occur in the predecessor block, not the block the PHI lives in) should
362   // still use the post-inc value.  Check for this case now.
363   PHINode *PN = dyn_cast<PHINode>(User);
364   if (!PN) return false;  // not a phi, not dominated by latch block.
365   
366   // Look at all of the uses of IV by the PHI node.  If any use corresponds to
367   // a block that is not dominated by the latch block, give up and use the
368   // preincremented value.
369   unsigned NumUses = 0;
370   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
371     if (PN->getIncomingValue(i) == IV) {
372       ++NumUses;
373       if (!EF->dominates(LatchBlock, PN->getIncomingBlock(i)))
374         return false;
375     }
376
377   // Okay, all uses of IV by PN are in predecessor blocks that really are
378   // dominated by the latch block.  Split the critical edges and use the
379   // post-incremented value.
380   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
381     if (PN->getIncomingValue(i) == IV) {
382       SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
383       if (--NumUses == 0) break;
384     }
385   
386   return true;
387 }
388
389   
390
391 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
392 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
393 /// return true.  Otherwise, return false.
394 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
395                                             std::set<Instruction*> &Processed) {
396   if (!I->getType()->isInteger() && !isa<PointerType>(I->getType()))
397       return false;   // Void and FP expressions cannot be reduced.
398   if (!Processed.insert(I).second)
399     return true;    // Instruction already handled.
400   
401   // Get the symbolic expression for this instruction.
402   SCEVHandle ISE = GetExpressionSCEV(I, L);
403   if (isa<SCEVCouldNotCompute>(ISE)) return false;
404   
405   // Get the start and stride for this expression.
406   SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
407   SCEVHandle Stride = Start;
408   if (!getSCEVStartAndStride(ISE, L, Start, Stride))
409     return false;  // Non-reducible symbolic expression, bail out.
410   
411   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
412     Instruction *User = cast<Instruction>(*UI);
413
414     // Do not infinitely recurse on PHI nodes.
415     if (isa<PHINode>(User) && Processed.count(User))
416       continue;
417
418     // If this is an instruction defined in a nested loop, or outside this loop,
419     // don't recurse into it.
420     bool AddUserToIVUsers = false;
421     if (LI->getLoopFor(User->getParent()) != L) {
422       DEBUG(std::cerr << "FOUND USER in other loop: " << *User
423             << "   OF SCEV: " << *ISE << "\n");
424       AddUserToIVUsers = true;
425     } else if (!AddUsersIfInteresting(User, L, Processed)) {
426       DEBUG(std::cerr << "FOUND USER: " << *User
427             << "   OF SCEV: " << *ISE << "\n");
428       AddUserToIVUsers = true;
429     }
430
431     if (AddUserToIVUsers) {
432       IVUsersOfOneStride &StrideUses = IVUsesByStride[Stride];
433       if (StrideUses.Users.empty())     // First occurance of this stride?
434         StrideOrder.push_back(Stride);
435       
436       // Okay, we found a user that we cannot reduce.  Analyze the instruction
437       // and decide what to do with it.  If we are a use inside of the loop, use
438       // the value before incrementation, otherwise use it after incrementation.
439       if (IVUseShouldUsePostIncValue(User, I, L, EF, this)) {
440         // The value used will be incremented by the stride more than we are
441         // expecting, so subtract this off.
442         SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
443         StrideUses.addUser(NewStart, User, I);
444         StrideUses.Users.back().isUseOfPostIncrementedValue = true;
445         DEBUG(std::cerr << "   USING POSTINC SCEV, START=" << *NewStart<< "\n");
446       } else {        
447         StrideUses.addUser(Start, User, I);
448       }
449     }
450   }
451   return true;
452 }
453
454 namespace {
455   /// BasedUser - For a particular base value, keep information about how we've
456   /// partitioned the expression so far.
457   struct BasedUser {
458     /// Base - The Base value for the PHI node that needs to be inserted for
459     /// this use.  As the use is processed, information gets moved from this
460     /// field to the Imm field (below).  BasedUser values are sorted by this
461     /// field.
462     SCEVHandle Base;
463     
464     /// Inst - The instruction using the induction variable.
465     Instruction *Inst;
466
467     /// OperandValToReplace - The operand value of Inst to replace with the
468     /// EmittedBase.
469     Value *OperandValToReplace;
470
471     /// Imm - The immediate value that should be added to the base immediately
472     /// before Inst, because it will be folded into the imm field of the
473     /// instruction.
474     SCEVHandle Imm;
475
476     /// EmittedBase - The actual value* to use for the base value of this
477     /// operation.  This is null if we should just use zero so far.
478     Value *EmittedBase;
479
480     // isUseOfPostIncrementedValue - True if this should use the
481     // post-incremented version of this IV, not the preincremented version.
482     // This can only be set in special cases, such as the terminating setcc
483     // instruction for a loop and uses outside the loop that are dominated by
484     // the loop.
485     bool isUseOfPostIncrementedValue;
486     
487     BasedUser(IVStrideUse &IVSU)
488       : Base(IVSU.Offset), Inst(IVSU.User), 
489         OperandValToReplace(IVSU.OperandValToReplace), 
490         Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
491         isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
492
493     // Once we rewrite the code to insert the new IVs we want, update the
494     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
495     // to it.
496     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
497                                         SCEVExpander &Rewriter, Loop *L,
498                                         Pass *P);
499     
500     Value *InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
501                                        SCEVExpander &Rewriter,
502                                        Instruction *IP, Loop *L);
503     void dump() const;
504   };
505 }
506
507 void BasedUser::dump() const {
508   std::cerr << " Base=" << *Base;
509   std::cerr << " Imm=" << *Imm;
510   if (EmittedBase)
511     std::cerr << "  EB=" << *EmittedBase;
512
513   std::cerr << "   Inst: " << *Inst;
514 }
515
516 Value *BasedUser::InsertCodeForBaseAtPosition(const SCEVHandle &NewBase, 
517                                               SCEVExpander &Rewriter,
518                                               Instruction *IP, Loop *L) {
519   // Figure out where we *really* want to insert this code.  In particular, if
520   // the user is inside of a loop that is nested inside of L, we really don't
521   // want to insert this expression before the user, we'd rather pull it out as
522   // many loops as possible.
523   LoopInfo &LI = Rewriter.getLoopInfo();
524   Instruction *BaseInsertPt = IP;
525   
526   // Figure out the most-nested loop that IP is in.
527   Loop *InsertLoop = LI.getLoopFor(IP->getParent());
528   
529   // If InsertLoop is not L, and InsertLoop is nested inside of L, figure out
530   // the preheader of the outer-most loop where NewBase is not loop invariant.
531   while (InsertLoop && NewBase->isLoopInvariant(InsertLoop)) {
532     BaseInsertPt = InsertLoop->getLoopPreheader()->getTerminator();
533     InsertLoop = InsertLoop->getParentLoop();
534   }
535   
536   // If there is no immediate value, skip the next part.
537   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Imm))
538     if (SC->getValue()->isNullValue())
539       return Rewriter.expandCodeFor(NewBase, BaseInsertPt,
540                                     OperandValToReplace->getType());
541
542   Value *Base = Rewriter.expandCodeFor(NewBase, BaseInsertPt);
543   
544   // Always emit the immediate (if non-zero) into the same block as the user.
545   SCEVHandle NewValSCEV = SCEVAddExpr::get(SCEVUnknown::get(Base), Imm);
546   return Rewriter.expandCodeFor(NewValSCEV, IP,
547                                 OperandValToReplace->getType());
548 }
549
550
551 // Once we rewrite the code to insert the new IVs we want, update the
552 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
553 // to it.
554 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
555                                                SCEVExpander &Rewriter,
556                                                Loop *L, Pass *P) {
557   if (!isa<PHINode>(Inst)) {
558     Value *NewVal = InsertCodeForBaseAtPosition(NewBase, Rewriter, Inst, L);
559     // Replace the use of the operand Value with the new Phi we just created.
560     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
561     DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
562     return;
563   }
564   
565   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
566   // expression into each operand block that uses it.  Note that PHI nodes can
567   // have multiple entries for the same predecessor.  We use a map to make sure
568   // that a PHI node only has a single Value* for each predecessor (which also
569   // prevents us from inserting duplicate code in some blocks).
570   std::map<BasicBlock*, Value*> InsertedCode;
571   PHINode *PN = cast<PHINode>(Inst);
572   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
573     if (PN->getIncomingValue(i) == OperandValToReplace) {
574       // If this is a critical edge, split the edge so that we do not insert the
575       // code on all predecessor/successor paths.  We do this unless this is the
576       // canonical backedge for this loop, as this can make some inserted code
577       // be in an illegal position.
578       BasicBlock *PHIPred = PN->getIncomingBlock(i);
579       if (e != 1 && PHIPred->getTerminator()->getNumSuccessors() > 1 &&
580           (PN->getParent() != L->getHeader() || !L->contains(PHIPred))) {
581         
582         // First step, split the critical edge.
583         SplitCriticalEdge(PHIPred, PN->getParent(), P);
584             
585         // Next step: move the basic block.  In particular, if the PHI node
586         // is outside of the loop, and PredTI is in the loop, we want to
587         // move the block to be immediately before the PHI block, not
588         // immediately after PredTI.
589         if (L->contains(PHIPred) && !L->contains(PN->getParent())) {
590           BasicBlock *NewBB = PN->getIncomingBlock(i);
591           NewBB->moveBefore(PN->getParent());
592         }
593       }
594
595       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
596       if (!Code) {
597         // Insert the code into the end of the predecessor block.
598         Instruction *InsertPt = PN->getIncomingBlock(i)->getTerminator();
599         Code = InsertCodeForBaseAtPosition(NewBase, Rewriter, InsertPt, L);
600       }
601       
602       // Replace the use of the operand Value with the new Phi we just created.
603       PN->setIncomingValue(i, Code);
604       Rewriter.clear();
605     }
606   }
607   DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
608 }
609
610
611 /// isTargetConstant - Return true if the following can be referenced by the
612 /// immediate field of a target instruction.
613 static bool isTargetConstant(const SCEVHandle &V, const TargetLowering *TLI) {
614   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
615     int64_t V = SC->getValue()->getSExtValue();
616     if (TLI)
617       return TLI->isLegalAddressImmediate(V);
618     else
619       // Defaults to PPC. PPC allows a sign-extended 16-bit immediate field.
620       return (V > -(1 << 16) && V < (1 << 16)-1);
621   }
622
623   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
624     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
625       if (CE->getOpcode() == Instruction::Cast) {
626         Constant *Op0 = CE->getOperand(0);
627         if (isa<GlobalValue>(Op0) &&
628             TLI &&
629             TLI->isLegalAddressImmediate(cast<GlobalValue>(Op0)))
630           return true;
631       }
632   return false;
633 }
634
635 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
636 /// loop varying to the Imm operand.
637 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
638                                             Loop *L) {
639   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
640   
641   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
642     std::vector<SCEVHandle> NewOps;
643     NewOps.reserve(SAE->getNumOperands());
644     
645     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
646       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
647         // If this is a loop-variant expression, it must stay in the immediate
648         // field of the expression.
649         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
650       } else {
651         NewOps.push_back(SAE->getOperand(i));
652       }
653
654     if (NewOps.empty())
655       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
656     else
657       Val = SCEVAddExpr::get(NewOps);
658   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
659     // Try to pull immediates out of the start value of nested addrec's.
660     SCEVHandle Start = SARE->getStart();
661     MoveLoopVariantsToImediateField(Start, Imm, L);
662     
663     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
664     Ops[0] = Start;
665     Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
666   } else {
667     // Otherwise, all of Val is variant, move the whole thing over.
668     Imm = SCEVAddExpr::get(Imm, Val);
669     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
670   }
671 }
672
673
674 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
675 /// that can fit into the immediate field of instructions in the target.
676 /// Accumulate these immediate values into the Imm value.
677 static void MoveImmediateValues(const TargetLowering *TLI,
678                                 SCEVHandle &Val, SCEVHandle &Imm,
679                                 bool isAddress, Loop *L) {
680   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
681     std::vector<SCEVHandle> NewOps;
682     NewOps.reserve(SAE->getNumOperands());
683     
684     for (unsigned i = 0; i != SAE->getNumOperands(); ++i) {
685       SCEVHandle NewOp = SAE->getOperand(i);
686       MoveImmediateValues(TLI, NewOp, Imm, isAddress, L);
687       
688       if (!NewOp->isLoopInvariant(L)) {
689         // If this is a loop-variant expression, it must stay in the immediate
690         // field of the expression.
691         Imm = SCEVAddExpr::get(Imm, NewOp);
692       } else {
693         NewOps.push_back(NewOp);
694       }
695     }
696
697     if (NewOps.empty())
698       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
699     else
700       Val = SCEVAddExpr::get(NewOps);
701     return;
702   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
703     // Try to pull immediates out of the start value of nested addrec's.
704     SCEVHandle Start = SARE->getStart();
705     MoveImmediateValues(TLI, Start, Imm, isAddress, L);
706     
707     if (Start != SARE->getStart()) {
708       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
709       Ops[0] = Start;
710       Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
711     }
712     return;
713   } else if (SCEVMulExpr *SME = dyn_cast<SCEVMulExpr>(Val)) {
714     // Transform "8 * (4 + v)" -> "32 + 8*V" if "32" fits in the immed field.
715     if (isAddress && isTargetConstant(SME->getOperand(0), TLI) &&
716         SME->getNumOperands() == 2 && SME->isLoopInvariant(L)) {
717
718       SCEVHandle SubImm = SCEVUnknown::getIntegerSCEV(0, Val->getType());
719       SCEVHandle NewOp = SME->getOperand(1);
720       MoveImmediateValues(TLI, NewOp, SubImm, isAddress, L);
721       
722       // If we extracted something out of the subexpressions, see if we can 
723       // simplify this!
724       if (NewOp != SME->getOperand(1)) {
725         // Scale SubImm up by "8".  If the result is a target constant, we are
726         // good.
727         SubImm = SCEVMulExpr::get(SubImm, SME->getOperand(0));
728         if (isTargetConstant(SubImm, TLI)) {
729           // Accumulate the immediate.
730           Imm = SCEVAddExpr::get(Imm, SubImm);
731           
732           // Update what is left of 'Val'.
733           Val = SCEVMulExpr::get(SME->getOperand(0), NewOp);
734           return;
735         }
736       }
737     }
738   }
739
740   // Loop-variant expressions must stay in the immediate field of the
741   // expression.
742   if ((isAddress && isTargetConstant(Val, TLI)) ||
743       !Val->isLoopInvariant(L)) {
744     Imm = SCEVAddExpr::get(Imm, Val);
745     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
746     return;
747   }
748
749   // Otherwise, no immediates to move.
750 }
751
752
753 /// SeparateSubExprs - Decompose Expr into all of the subexpressions that are
754 /// added together.  This is used to reassociate common addition subexprs
755 /// together for maximal sharing when rewriting bases.
756 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
757                              SCEVHandle Expr) {
758   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
759     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
760       SeparateSubExprs(SubExprs, AE->getOperand(j));
761   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
762     SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
763     if (SARE->getOperand(0) == Zero) {
764       SubExprs.push_back(Expr);
765     } else {
766       // Compute the addrec with zero as its base.
767       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
768       Ops[0] = Zero;   // Start with zero base.
769       SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
770       
771
772       SeparateSubExprs(SubExprs, SARE->getOperand(0));
773     }
774   } else if (!isa<SCEVConstant>(Expr) ||
775              !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
776     // Do not add zero.
777     SubExprs.push_back(Expr);
778   }
779 }
780
781
782 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
783 /// removing any common subexpressions from it.  Anything truly common is
784 /// removed, accumulated, and returned.  This looks for things like (a+b+c) and
785 /// (a+c+d) -> (a+c).  The common expression is *removed* from the Bases.
786 static SCEVHandle 
787 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
788   unsigned NumUses = Uses.size();
789
790   // Only one use?  Use its base, regardless of what it is!
791   SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
792   SCEVHandle Result = Zero;
793   if (NumUses == 1) {
794     std::swap(Result, Uses[0].Base);
795     return Result;
796   }
797
798   // To find common subexpressions, count how many of Uses use each expression.
799   // If any subexpressions are used Uses.size() times, they are common.
800   std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
801   
802   // UniqueSubExprs - Keep track of all of the subexpressions we see in the
803   // order we see them.
804   std::vector<SCEVHandle> UniqueSubExprs;
805
806   std::vector<SCEVHandle> SubExprs;
807   for (unsigned i = 0; i != NumUses; ++i) {
808     // If the base is zero (which is common), return zero now, there are no
809     // CSEs we can find.
810     if (Uses[i].Base == Zero) return Zero;
811
812     // Split the expression into subexprs.
813     SeparateSubExprs(SubExprs, Uses[i].Base);
814     // Add one to SubExpressionUseCounts for each subexpr present.
815     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
816       if (++SubExpressionUseCounts[SubExprs[j]] == 1)
817         UniqueSubExprs.push_back(SubExprs[j]);
818     SubExprs.clear();
819   }
820
821   // Now that we know how many times each is used, build Result.  Iterate over
822   // UniqueSubexprs so that we have a stable ordering.
823   for (unsigned i = 0, e = UniqueSubExprs.size(); i != e; ++i) {
824     std::map<SCEVHandle, unsigned>::iterator I = 
825        SubExpressionUseCounts.find(UniqueSubExprs[i]);
826     assert(I != SubExpressionUseCounts.end() && "Entry not found?");
827     if (I->second == NumUses) {  // Found CSE!
828       Result = SCEVAddExpr::get(Result, I->first);
829     } else {
830       // Remove non-cse's from SubExpressionUseCounts.
831       SubExpressionUseCounts.erase(I);
832     }
833   }
834   
835   // If we found no CSE's, return now.
836   if (Result == Zero) return Result;
837   
838   // Otherwise, remove all of the CSE's we found from each of the base values.
839   for (unsigned i = 0; i != NumUses; ++i) {
840     // Split the expression into subexprs.
841     SeparateSubExprs(SubExprs, Uses[i].Base);
842
843     // Remove any common subexpressions.
844     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
845       if (SubExpressionUseCounts.count(SubExprs[j])) {
846         SubExprs.erase(SubExprs.begin()+j);
847         --j; --e;
848       }
849     
850     // Finally, the non-shared expressions together.
851     if (SubExprs.empty())
852       Uses[i].Base = Zero;
853     else
854       Uses[i].Base = SCEVAddExpr::get(SubExprs);
855     SubExprs.clear();
856   }
857  
858   return Result;
859 }
860
861 /// isZero - returns true if the scalar evolution expression is zero.
862 ///
863 static bool isZero(SCEVHandle &V) {
864   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V))
865     return SC->getValue()->getRawValue() == 0;
866   return false;
867 }
868
869
870 /// CheckForIVReuse - Returns the multiple if the stride is the multiple
871 /// of a previous stride and it is a legal value for the target addressing
872 /// mode scale component. This allows the users of this stride to be rewritten
873 /// as prev iv * factor. It returns 0 if no reuse is possible.
874 unsigned LoopStrengthReduce::CheckForIVReuse(const SCEVHandle &Stride,
875                                              IVExpr &IV, const Type *Ty) {
876   if (!TLI) return 0;
877
878   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride)) {
879     int64_t SInt = SC->getValue()->getSExtValue();
880     if (SInt == 1) return 0;
881
882     for (TargetLowering::legal_am_scale_iterator
883            I = TLI->legal_am_scale_begin(), E = TLI->legal_am_scale_end();
884          I != E; ++I) {
885       unsigned Scale = *I;
886       if (unsigned(abs(SInt)) < Scale || (SInt % Scale) != 0)
887         continue;
888       std::map<SCEVHandle, IVsOfOneStride>::iterator SI =
889         IVsByStride.find(SCEVUnknown::getIntegerSCEV(SInt/Scale, Type::UIntTy));
890       if (SI == IVsByStride.end())
891         continue;
892       for (std::vector<IVExpr>::iterator II = SI->second.IVs.begin(),
893              IE = SI->second.IVs.end(); II != IE; ++II)
894         // FIXME: Only handle base == 0 for now.
895         // Only reuse previous IV if it would not require a type conversion.
896         if (isZero(II->Base) &&
897             II->Base->getType()->isLosslesslyConvertibleTo(Ty)) {
898           IV = *II;
899           return Scale;
900         }
901     }
902   }
903
904   return 0;
905 }
906
907 /// PartitionByIsUseOfPostIncrementedValue - Simple boolean predicate that
908 /// returns true if Val's isUseOfPostIncrementedValue is true.
909 static bool PartitionByIsUseOfPostIncrementedValue(const BasedUser &Val) {
910   return Val.isUseOfPostIncrementedValue;
911 }
912
913 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
914 /// stride of IV.  All of the users may have different starting values, and this
915 /// may not be the only stride (we know it is if isOnlyStride is true).
916 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
917                                                       IVUsersOfOneStride &Uses,
918                                                       Loop *L,
919                                                       bool isOnlyStride) {
920   // Transform our list of users and offsets to a bit more complex table.  In
921   // this new vector, each 'BasedUser' contains 'Base' the base of the
922   // strided accessas well as the old information from Uses.  We progressively
923   // move information from the Base field to the Imm field, until we eventually
924   // have the full access expression to rewrite the use.
925   std::vector<BasedUser> UsersToProcess;
926   UsersToProcess.reserve(Uses.Users.size());
927   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
928     UsersToProcess.push_back(Uses.Users[i]);
929     
930     // Move any loop invariant operands from the offset field to the immediate
931     // field of the use, so that we don't try to use something before it is
932     // computed.
933     MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
934                                     UsersToProcess.back().Imm, L);
935     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
936            "Base value is not loop invariant!");
937   }
938
939   // We now have a whole bunch of uses of like-strided induction variables, but
940   // they might all have different bases.  We want to emit one PHI node for this
941   // stride which we fold as many common expressions (between the IVs) into as
942   // possible.  Start by identifying the common expressions in the base values 
943   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
944   // "A+B"), emit it to the preheader, then remove the expression from the
945   // UsersToProcess base values.
946   SCEVHandle CommonExprs =
947     RemoveCommonExpressionsFromUseBases(UsersToProcess);
948   
949   // Check if it is possible to reuse a IV with stride that is factor of this
950   // stride. And the multiple is a number that can be encoded in the scale
951   // field of the target addressing mode.
952   PHINode *NewPHI = NULL;
953   Value   *IncV   = NULL;
954   IVExpr   ReuseIV;
955   unsigned RewriteFactor = CheckForIVReuse(Stride, ReuseIV,
956                                            CommonExprs->getType());
957   if (RewriteFactor != 0) {
958     DEBUG(std::cerr << "BASED ON IV of STRIDE " << *ReuseIV.Stride
959           << " and BASE " << *ReuseIV.Base << " :\n");
960     NewPHI = ReuseIV.PHI;
961     IncV   = ReuseIV.IncV;
962   }
963
964   // Next, figure out what we can represent in the immediate fields of
965   // instructions.  If we can represent anything there, move it to the imm
966   // fields of the BasedUsers.  We do this so that it increases the commonality
967   // of the remaining uses.
968   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
969     // If the user is not in the current loop, this means it is using the exit
970     // value of the IV.  Do not put anything in the base, make sure it's all in
971     // the immediate field to allow as much factoring as possible.
972     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
973       UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
974                                                UsersToProcess[i].Base);
975       UsersToProcess[i].Base = 
976         SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
977     } else {
978       
979       // Addressing modes can be folded into loads and stores.  Be careful that
980       // the store is through the expression, not of the expression though.
981       bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
982       if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
983         if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
984           isAddress = true;
985       
986       MoveImmediateValues(TLI, UsersToProcess[i].Base, UsersToProcess[i].Imm,
987                           isAddress, L);
988     }
989   }
990
991   // Now that we know what we need to do, insert the PHI node itself.
992   //
993   DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
994         << *CommonExprs << " :\n");
995
996   SCEVExpander Rewriter(*SE, *LI);
997   SCEVExpander PreheaderRewriter(*SE, *LI);
998   
999   BasicBlock  *Preheader = L->getLoopPreheader();
1000   Instruction *PreInsertPt = Preheader->getTerminator();
1001   Instruction *PhiInsertBefore = L->getHeader()->begin();
1002   
1003   BasicBlock *LatchBlock = L->getLoopLatch();
1004
1005   const Type *ReplacedTy = CommonExprs->getType();
1006
1007   // Emit the initial base value into the loop preheader.
1008   Value *CommonBaseV
1009     = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
1010                                       ReplacedTy);
1011
1012   if (RewriteFactor == 0) {
1013     // Create a new Phi for this base, and stick it in the loop header.
1014     NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
1015     ++NumInserted;
1016   
1017     // Add common base to the new Phi node.
1018     NewPHI->addIncoming(CommonBaseV, Preheader);
1019
1020     // Insert the stride into the preheader.
1021     Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
1022                                                      ReplacedTy);
1023     if (!isa<ConstantInt>(StrideV)) ++NumVariable;
1024
1025     // Emit the increment of the base value before the terminator of the loop
1026     // latch block, and add it to the Phi node.
1027     SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
1028                                          SCEVUnknown::get(StrideV));
1029   
1030     IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
1031                                   ReplacedTy);
1032     IncV->setName(NewPHI->getName()+".inc");
1033     NewPHI->addIncoming(IncV, LatchBlock);
1034
1035     // Remember this in case a later stride is multiple of this.
1036     IVsByStride[Stride].addIV(Stride, CommonExprs, NewPHI, IncV);
1037   } else {
1038     Constant *C = dyn_cast<Constant>(CommonBaseV);
1039     if (!C ||
1040         (!C->isNullValue() &&
1041          !isTargetConstant(SCEVUnknown::get(CommonBaseV), TLI)))
1042       // We want the common base emitted into the preheader!
1043       CommonBaseV = new CastInst(CommonBaseV, CommonBaseV->getType(),
1044                                  "commonbase", PreInsertPt);
1045   }
1046
1047   // We want to emit code for users inside the loop first.  To do this, we
1048   // rearrange BasedUser so that the entries at the end have
1049   // isUseOfPostIncrementedValue = false, because we pop off the end of the
1050   // vector (so we handle them first).
1051   std::partition(UsersToProcess.begin(), UsersToProcess.end(),
1052                  PartitionByIsUseOfPostIncrementedValue);
1053   
1054   // Sort this by base, so that things with the same base are handled
1055   // together.  By partitioning first and stable-sorting later, we are
1056   // guaranteed that within each base we will pop off users from within the
1057   // loop before users outside of the loop with a particular base.
1058   //
1059   // We would like to use stable_sort here, but we can't.  The problem is that
1060   // SCEVHandle's don't have a deterministic ordering w.r.t to each other, so
1061   // we don't have anything to do a '<' comparison on.  Because we think the
1062   // number of uses is small, do a horrible bubble sort which just relies on
1063   // ==.
1064   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
1065     // Get a base value.
1066     SCEVHandle Base = UsersToProcess[i].Base;
1067     
1068     // Compact everything with this base to be consequetive with this one.
1069     for (unsigned j = i+1; j != e; ++j) {
1070       if (UsersToProcess[j].Base == Base) {
1071         std::swap(UsersToProcess[i+1], UsersToProcess[j]);
1072         ++i;
1073       }
1074     }
1075   }
1076
1077   // Process all the users now.  This outer loop handles all bases, the inner
1078   // loop handles all users of a particular base.
1079   while (!UsersToProcess.empty()) {
1080     SCEVHandle Base = UsersToProcess.back().Base;
1081
1082     DEBUG(std::cerr << "  INSERTING code for BASE = " << *Base << ":\n");
1083    
1084     // Emit the code for Base into the preheader.
1085     Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
1086                                                    ReplacedTy);
1087     
1088     // If BaseV is a constant other than 0, make sure that it gets inserted into
1089     // the preheader, instead of being forward substituted into the uses.  We do
1090     // this by forcing a noop cast to be inserted into the preheader in this
1091     // case.
1092     if (Constant *C = dyn_cast<Constant>(BaseV)) {
1093       if (!C->isNullValue() && !isTargetConstant(Base, TLI)) {
1094         // We want this constant emitted into the preheader!
1095         BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
1096                              PreInsertPt);       
1097       }
1098     }
1099
1100     // Emit the code to add the immediate offset to the Phi value, just before
1101     // the instructions that we identified as using this stride and base.
1102     do {
1103       // FIXME: Use emitted users to emit other users.
1104       BasedUser &User = UsersToProcess.back();
1105
1106       // If this instruction wants to use the post-incremented value, move it
1107       // after the post-inc and use its value instead of the PHI.
1108       Value *RewriteOp = NewPHI;
1109       if (User.isUseOfPostIncrementedValue) {
1110         RewriteOp = IncV;
1111
1112         // If this user is in the loop, make sure it is the last thing in the
1113         // loop to ensure it is dominated by the increment.
1114         if (L->contains(User.Inst->getParent()))
1115           User.Inst->moveBefore(LatchBlock->getTerminator());
1116       }
1117       if (RewriteOp->getType() != ReplacedTy)
1118         RewriteOp = SCEVExpander::InsertCastOfTo(RewriteOp, ReplacedTy);
1119
1120       SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
1121
1122       // Clear the SCEVExpander's expression map so that we are guaranteed
1123       // to have the code emitted where we expect it.
1124       Rewriter.clear();
1125
1126       // If we are reusing the iv, then it must be multiplied by a constant
1127       // factor take advantage of addressing mode scale component.
1128       if (RewriteFactor != 0) {
1129         RewriteExpr =
1130           SCEVMulExpr::get(SCEVUnknown::getIntegerSCEV(RewriteFactor,
1131                                                        RewriteExpr->getType()),
1132                            RewriteExpr);
1133
1134         // The common base is emitted in the loop preheader. But since we
1135         // are reusing an IV, it has not been used to initialize the PHI node.
1136         // Add it to the expression used to rewrite the uses.
1137         if (!isa<ConstantInt>(CommonBaseV) ||
1138             !cast<ConstantInt>(CommonBaseV)->isNullValue())
1139           RewriteExpr = SCEVAddExpr::get(RewriteExpr,
1140                                          SCEVUnknown::get(CommonBaseV));
1141       }
1142
1143       // Now that we know what we need to do, insert code before User for the
1144       // immediate and any loop-variant expressions.
1145       if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
1146         // Add BaseV to the PHI value if needed.
1147         RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
1148
1149       User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
1150
1151       // Mark old value we replaced as possibly dead, so that it is elminated
1152       // if we just replaced the last use of that value.
1153       DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
1154
1155       UsersToProcess.pop_back();
1156       ++NumReduced;
1157
1158       // If there are any more users to process with the same base, process them
1159       // now.  We sorted by base above, so we just have to check the last elt.
1160     } while (!UsersToProcess.empty() && UsersToProcess.back().Base == Base);
1161     // TODO: Next, find out which base index is the most common, pull it out.
1162   }
1163
1164   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
1165   // different starting values, into different PHIs.
1166 }
1167
1168 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
1169 // uses in the loop, look to see if we can eliminate some, in favor of using
1170 // common indvars for the different uses.
1171 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
1172   // TODO: implement optzns here.
1173
1174
1175
1176
1177   // Finally, get the terminating condition for the loop if possible.  If we
1178   // can, we want to change it to use a post-incremented version of its
1179   // induction variable, to allow coalescing the live ranges for the IV into
1180   // one register value.
1181   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
1182   BasicBlock  *Preheader = L->getLoopPreheader();
1183   BasicBlock *LatchBlock =
1184    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
1185   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
1186   if (!TermBr || TermBr->isUnconditional() ||
1187       !isa<SetCondInst>(TermBr->getCondition()))
1188     return;
1189   SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
1190
1191   // Search IVUsesByStride to find Cond's IVUse if there is one.
1192   IVStrideUse *CondUse = 0;
1193   const SCEVHandle *CondStride = 0;
1194
1195   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e && !CondUse;
1196        ++Stride) {
1197     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
1198       IVUsesByStride.find(StrideOrder[Stride]);
1199     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1200     
1201     for (std::vector<IVStrideUse>::iterator UI = SI->second.Users.begin(),
1202            E = SI->second.Users.end(); UI != E; ++UI)
1203       if (UI->User == Cond) {
1204         CondUse = &*UI;
1205         CondStride = &SI->first;
1206         // NOTE: we could handle setcc instructions with multiple uses here, but
1207         // InstCombine does it as well for simple uses, it's not clear that it
1208         // occurs enough in real life to handle.
1209         break;
1210       }
1211   }
1212   if (!CondUse) return;  // setcc doesn't use the IV.
1213
1214   // setcc stride is complex, don't mess with users.
1215   // FIXME: Evaluate whether this is a good idea or not.
1216   if (!isa<SCEVConstant>(*CondStride)) return;
1217
1218   // It's possible for the setcc instruction to be anywhere in the loop, and
1219   // possible for it to have multiple users.  If it is not immediately before
1220   // the latch block branch, move it.
1221   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
1222     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
1223       Cond->moveBefore(TermBr);
1224     } else {
1225       // Otherwise, clone the terminating condition and insert into the loopend.
1226       Cond = cast<SetCondInst>(Cond->clone());
1227       Cond->setName(L->getHeader()->getName() + ".termcond");
1228       LatchBlock->getInstList().insert(TermBr, Cond);
1229       
1230       // Clone the IVUse, as the old use still exists!
1231       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
1232                                          CondUse->OperandValToReplace);
1233       CondUse = &IVUsesByStride[*CondStride].Users.back();
1234     }
1235   }
1236
1237   // If we get to here, we know that we can transform the setcc instruction to
1238   // use the post-incremented version of the IV, allowing us to coalesce the
1239   // live ranges for the IV correctly.
1240   CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
1241   CondUse->isUseOfPostIncrementedValue = true;
1242 }
1243
1244 namespace {
1245   // Constant strides come first which in turns are sorted by their absolute
1246   // values. If absolute values are the same, then positive strides comes first.
1247   // e.g.
1248   // 4, -1, X, 1, 2 ==> 1, -1, 2, 4, X
1249   struct StrideCompare {
1250     bool operator()(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1251       SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS);
1252       SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
1253       if (LHSC && RHSC) {
1254         int64_t  LV = LHSC->getValue()->getSExtValue();
1255         int64_t  RV = RHSC->getValue()->getSExtValue();
1256         uint64_t ALV = (LV < 0) ? -LV : LV;
1257         uint64_t ARV = (RV < 0) ? -RV : RV;
1258         if (ALV == ARV)
1259           return LV > RV;
1260         else
1261           return ALV < ARV;
1262       }
1263       return (LHSC && !RHSC);
1264     }
1265   };
1266 }
1267
1268 void LoopStrengthReduce::runOnLoop(Loop *L) {
1269   // First step, transform all loops nesting inside of this loop.
1270   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
1271     runOnLoop(*I);
1272
1273   // Next, find all uses of induction variables in this loop, and catagorize
1274   // them by stride.  Start by finding all of the PHI nodes in the header for
1275   // this loop.  If they are induction variables, inspect their uses.
1276   std::set<Instruction*> Processed;   // Don't reprocess instructions.
1277   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
1278     AddUsersIfInteresting(I, L, Processed);
1279
1280   // If we have nothing to do, return.
1281   if (IVUsesByStride.empty()) return;
1282
1283   // Optimize induction variables.  Some indvar uses can be transformed to use
1284   // strides that will be needed for other purposes.  A common example of this
1285   // is the exit test for the loop, which can often be rewritten to use the
1286   // computation of some other indvar to decide when to terminate the loop.
1287   OptimizeIndvars(L);
1288
1289
1290   // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
1291   // doing computation in byte values, promote to 32-bit values if safe.
1292
1293   // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
1294   // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
1295   // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.  Need
1296   // to be careful that IV's are all the same type.  Only works for intptr_t
1297   // indvars.
1298
1299   // If we only have one stride, we can more aggressively eliminate some things.
1300   bool HasOneStride = IVUsesByStride.size() == 1;
1301
1302 #ifndef NDEBUG
1303   DEBUG(std::cerr << "\nLSR on ");
1304   DEBUG(L->dump());
1305 #endif
1306
1307   // IVsByStride keeps IVs for one particular loop.
1308   IVsByStride.clear();
1309
1310   // Sort the StrideOrder so we process larger strides first.
1311   std::stable_sort(StrideOrder.begin(), StrideOrder.end(), StrideCompare());
1312
1313   // Note: this processes each stride/type pair individually.  All users passed
1314   // into StrengthReduceStridedIVUsers have the same type AND stride.  Also,
1315   // node that we iterate over IVUsesByStride indirectly by using StrideOrder.
1316   // This extra layer of indirection makes the ordering of strides deterministic
1317   // - not dependent on map order.
1318   for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
1319     std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI = 
1320       IVUsesByStride.find(StrideOrder[Stride]);
1321     assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
1322     StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1323   }
1324
1325   // Clean up after ourselves
1326   if (!DeadInsts.empty()) {
1327     DeleteTriviallyDeadInstructions(DeadInsts);
1328
1329     BasicBlock::iterator I = L->getHeader()->begin();
1330     PHINode *PN;
1331     while ((PN = dyn_cast<PHINode>(I))) {
1332       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
1333       
1334       // At this point, we know that we have killed one or more GEP
1335       // instructions.  It is worth checking to see if the cann indvar is also
1336       // dead, so that we can remove it as well.  The requirements for the cann
1337       // indvar to be considered dead are:
1338       // 1. the cann indvar has one use
1339       // 2. the use is an add instruction
1340       // 3. the add has one use
1341       // 4. the add is used by the cann indvar
1342       // If all four cases above are true, then we can remove both the add and
1343       // the cann indvar.
1344       // FIXME: this needs to eliminate an induction variable even if it's being
1345       // compared against some value to decide loop termination.
1346       if (PN->hasOneUse()) {
1347         BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
1348         if (BO && BO->hasOneUse()) {
1349           if (PN == *(BO->use_begin())) {
1350             DeadInsts.insert(BO);
1351             // Break the cycle, then delete the PHI.
1352             PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1353             SE->deleteInstructionFromRecords(PN);
1354             PN->eraseFromParent();
1355           }
1356         }
1357       }
1358     }
1359     DeleteTriviallyDeadInstructions(DeadInsts);
1360   }
1361
1362   CastedPointers.clear();
1363   IVUsesByStride.clear();
1364   StrideOrder.clear();
1365   return;
1366 }