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