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