29043a152cfe96902c80f426bb1a6f87d513748e
[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 <algorithm>
35 #include <set>
36 using namespace llvm;
37
38 namespace {
39   Statistic<> NumReduced ("loop-reduce", "Number of GEPs strength reduced");
40   Statistic<> NumInserted("loop-reduce", "Number of PHIs inserted");
41   Statistic<> NumVariable("loop-reduce","Number of PHIs with variable strides");
42
43   /// IVStrideUse - Keep track of one use of a strided induction variable, where
44   /// the stride is stored externally.  The Offset member keeps track of the 
45   /// offset from the IV, User is the actual user of the operand, and 'Operand'
46   /// is the operand # of the User that is the use.
47   struct IVStrideUse {
48     SCEVHandle Offset;
49     Instruction *User;
50     Value *OperandValToReplace;
51
52     // isUseOfPostIncrementedValue - True if this should use the
53     // post-incremented version of this IV, not the preincremented version.
54     // This can only be set in special cases, such as the terminating setcc
55     // instruction for a loop or uses dominated by the loop.
56     bool isUseOfPostIncrementedValue;
57     
58     IVStrideUse(const SCEVHandle &Offs, Instruction *U, Value *O)
59       : Offset(Offs), User(U), OperandValToReplace(O),
60         isUseOfPostIncrementedValue(false) {}
61   };
62   
63   /// IVUsersOfOneStride - This structure keeps track of all instructions that
64   /// have an operand that is based on the trip count multiplied by some stride.
65   /// The stride for all of these users is common and kept external to this
66   /// structure.
67   struct IVUsersOfOneStride {
68     /// Users - Keep track of all of the users of this stride as well as the
69     /// initial value and the operand that uses the IV.
70     std::vector<IVStrideUse> Users;
71     
72     void addUser(const SCEVHandle &Offset,Instruction *User, Value *Operand) {
73       Users.push_back(IVStrideUse(Offset, User, Operand));
74     }
75   };
76
77
78   class LoopStrengthReduce : public FunctionPass {
79     LoopInfo *LI;
80     DominatorSet *DS;
81     ScalarEvolution *SE;
82     const TargetData *TD;
83     const Type *UIntPtrTy;
84     bool Changed;
85
86     /// MaxTargetAMSize - This is the maximum power-of-two scale value that the
87     /// target can handle for free with its addressing modes.
88     unsigned MaxTargetAMSize;
89
90     /// IVUsesByStride - Keep track of all uses of induction variables that we
91     /// are interested in.  The key of the map is the stride of the access.
92     std::map<SCEVHandle, IVUsersOfOneStride> IVUsesByStride;
93
94     /// CastedValues - As we need to cast values to uintptr_t, this keeps track
95     /// of the casted version of each value.  This is accessed by
96     /// getCastedVersionOf.
97     std::map<Value*, Value*> CastedPointers;
98
99     /// DeadInsts - Keep track of instructions we may have made dead, so that
100     /// we can remove them after we are done working.
101     std::set<Instruction*> DeadInsts;
102   public:
103     LoopStrengthReduce(unsigned MTAMS = 1)
104       : MaxTargetAMSize(MTAMS) {
105     }
106
107     virtual bool runOnFunction(Function &) {
108       LI = &getAnalysis<LoopInfo>();
109       DS = &getAnalysis<DominatorSet>();
110       SE = &getAnalysis<ScalarEvolution>();
111       TD = &getAnalysis<TargetData>();
112       UIntPtrTy = TD->getIntPtrType();
113       Changed = false;
114
115       for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
116         runOnLoop(*I);
117       
118       return Changed;
119     }
120
121     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122       // We split critical edges, so we change the CFG.  However, we do update
123       // many analyses if they are around.
124       AU.addPreservedID(LoopSimplifyID);
125       AU.addPreserved<LoopInfo>();
126       AU.addPreserved<DominatorSet>();
127       AU.addPreserved<ImmediateDominators>();
128       AU.addPreserved<DominanceFrontier>();
129       AU.addPreserved<DominatorTree>();
130
131       AU.addRequiredID(LoopSimplifyID);
132       AU.addRequired<LoopInfo>();
133       AU.addRequired<DominatorSet>();
134       AU.addRequired<TargetData>();
135       AU.addRequired<ScalarEvolution>();
136     }
137     
138     /// getCastedVersionOf - Return the specified value casted to uintptr_t.
139     ///
140     Value *getCastedVersionOf(Value *V);
141 private:
142     void runOnLoop(Loop *L);
143     bool AddUsersIfInteresting(Instruction *I, Loop *L,
144                                std::set<Instruction*> &Processed);
145     SCEVHandle GetExpressionSCEV(Instruction *E, Loop *L);
146
147     void OptimizeIndvars(Loop *L);
148
149     void StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
150                                       IVUsersOfOneStride &Uses,
151                                       Loop *L, bool isOnlyStride);
152     void DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts);
153   };
154   RegisterOpt<LoopStrengthReduce> X("loop-reduce",
155                                     "Strength Reduce GEP Uses of Ind. Vars");
156 }
157
158 FunctionPass *llvm::createLoopStrengthReducePass(unsigned MaxTargetAMSize) {
159   return new LoopStrengthReduce(MaxTargetAMSize);
160 }
161
162 /// getCastedVersionOf - Return the specified value casted to uintptr_t.
163 ///
164 Value *LoopStrengthReduce::getCastedVersionOf(Value *V) {
165   if (V->getType() == UIntPtrTy) return V;
166   if (Constant *CB = dyn_cast<Constant>(V))
167     return ConstantExpr::getCast(CB, UIntPtrTy);
168
169   Value *&New = CastedPointers[V];
170   if (New) return New;
171   
172   BasicBlock::iterator InsertPt;
173   if (Argument *Arg = dyn_cast<Argument>(V)) {
174     // Insert into the entry of the function, after any allocas.
175     InsertPt = Arg->getParent()->begin()->begin();
176     while (isa<AllocaInst>(InsertPt)) ++InsertPt;
177   } else {
178     if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
179       InsertPt = II->getNormalDest()->begin();
180     } else {
181       InsertPt = cast<Instruction>(V);
182       ++InsertPt;
183     }
184
185     // Do not insert casts into the middle of PHI node blocks.
186     while (isa<PHINode>(InsertPt)) ++InsertPt;
187   }
188   
189   New = new CastInst(V, UIntPtrTy, V->getName(), InsertPt);
190   DeadInsts.insert(cast<Instruction>(New));
191   return New;
192 }
193
194
195 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
196 /// specified set are trivially dead, delete them and see if this makes any of
197 /// their operands subsequently dead.
198 void LoopStrengthReduce::
199 DeleteTriviallyDeadInstructions(std::set<Instruction*> &Insts) {
200   while (!Insts.empty()) {
201     Instruction *I = *Insts.begin();
202     Insts.erase(Insts.begin());
203     if (isInstructionTriviallyDead(I)) {
204       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
205         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
206           Insts.insert(U);
207       SE->deleteInstructionFromRecords(I);
208       I->eraseFromParent();
209       Changed = true;
210     }
211   }
212 }
213
214
215 /// GetExpressionSCEV - Compute and return the SCEV for the specified
216 /// instruction.
217 SCEVHandle LoopStrengthReduce::GetExpressionSCEV(Instruction *Exp, Loop *L) {
218   // Scalar Evolutions doesn't know how to compute SCEV's for GEP instructions.
219   // If this is a GEP that SE doesn't know about, compute it now and insert it.
220   // If this is not a GEP, or if we have already done this computation, just let
221   // SE figure it out.
222   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Exp);
223   if (!GEP || SE->hasSCEV(GEP))
224     return SE->getSCEV(Exp);
225     
226   // Analyze all of the subscripts of this getelementptr instruction, looking
227   // for uses that are determined by the trip count of L.  First, skip all
228   // operands the are not dependent on the IV.
229
230   // Build up the base expression.  Insert an LLVM cast of the pointer to
231   // uintptr_t first.
232   SCEVHandle GEPVal = SCEVUnknown::get(getCastedVersionOf(GEP->getOperand(0)));
233
234   gep_type_iterator GTI = gep_type_begin(GEP);
235   
236   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
237     // If this is a use of a recurrence that we can analyze, and it comes before
238     // Op does in the GEP operand list, we will handle this when we process this
239     // operand.
240     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
241       const StructLayout *SL = TD->getStructLayout(STy);
242       unsigned Idx = cast<ConstantUInt>(GEP->getOperand(i))->getValue();
243       uint64_t Offset = SL->MemberOffsets[Idx];
244       GEPVal = SCEVAddExpr::get(GEPVal,
245                                 SCEVUnknown::getIntegerSCEV(Offset, UIntPtrTy));
246     } else {
247       Value *OpVal = getCastedVersionOf(GEP->getOperand(i));
248       SCEVHandle Idx = SE->getSCEV(OpVal);
249
250       uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
251       if (TypeSize != 1)
252         Idx = SCEVMulExpr::get(Idx,
253                                SCEVConstant::get(ConstantUInt::get(UIntPtrTy,
254                                                                    TypeSize)));
255       GEPVal = SCEVAddExpr::get(GEPVal, Idx);
256     }
257   }
258
259   SE->setSCEV(GEP, GEPVal);
260   return GEPVal;
261 }
262
263 /// getSCEVStartAndStride - Compute the start and stride of this expression,
264 /// returning false if the expression is not a start/stride pair, or true if it
265 /// is.  The stride must be a loop invariant expression, but the start may be
266 /// a mix of loop invariant and loop variant expressions.
267 static bool getSCEVStartAndStride(const SCEVHandle &SH, Loop *L,
268                                   SCEVHandle &Start, SCEVHandle &Stride) {
269   SCEVHandle TheAddRec = Start;   // Initialize to zero.
270
271   // If the outer level is an AddExpr, the operands are all start values except
272   // for a nested AddRecExpr.
273   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
274     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
275       if (SCEVAddRecExpr *AddRec =
276              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
277         if (AddRec->getLoop() == L)
278           TheAddRec = SCEVAddExpr::get(AddRec, TheAddRec);
279         else
280           return false;  // Nested IV of some sort?
281       } else {
282         Start = SCEVAddExpr::get(Start, AE->getOperand(i));
283       }
284         
285   } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SH)) {
286     TheAddRec = SH;
287   } else {
288     return false;  // not analyzable.
289   }
290   
291   SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
292   if (!AddRec || AddRec->getLoop() != L) return false;
293   
294   // FIXME: Generalize to non-affine IV's.
295   if (!AddRec->isAffine()) return false;
296
297   Start = SCEVAddExpr::get(Start, AddRec->getOperand(0));
298   
299   if (!isa<SCEVConstant>(AddRec->getOperand(1)))
300     DEBUG(std::cerr << "[" << L->getHeader()->getName()
301                     << "] Variable stride: " << *AddRec << "\n");
302
303   Stride = AddRec->getOperand(1);
304   // Check that all constant strides are the unsigned type, we don't want to
305   // have two IV's one of signed stride 4 and one of unsigned stride 4 to not be
306   // merged.
307   assert((!isa<SCEVConstant>(Stride) || Stride->getType()->isUnsigned()) &&
308          "Constants should be canonicalized to unsigned!");
309
310   return true;
311 }
312
313 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
314 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
315 /// return true.  Otherwise, return false.
316 bool LoopStrengthReduce::AddUsersIfInteresting(Instruction *I, Loop *L,
317                                             std::set<Instruction*> &Processed) {
318   if (I->getType() == Type::VoidTy) return false;
319   if (!Processed.insert(I).second)
320     return true;    // Instruction already handled.
321   
322   // Get the symbolic expression for this instruction.
323   SCEVHandle ISE = GetExpressionSCEV(I, L);
324   if (isa<SCEVCouldNotCompute>(ISE)) return false;
325   
326   // Get the start and stride for this expression.
327   SCEVHandle Start = SCEVUnknown::getIntegerSCEV(0, ISE->getType());
328   SCEVHandle Stride = Start;
329   if (!getSCEVStartAndStride(ISE, L, Start, Stride))
330     return false;  // Non-reducible symbolic expression, bail out.
331   
332   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;++UI){
333     Instruction *User = cast<Instruction>(*UI);
334
335     // Do not infinitely recurse on PHI nodes.
336     if (isa<PHINode>(User) && User->getParent() == L->getHeader())
337       continue;
338
339     // If this is an instruction defined in a nested loop, or outside this loop,
340     // don't recurse into it.
341     bool AddUserToIVUsers = false;
342     if (LI->getLoopFor(User->getParent()) != L) {
343       DEBUG(std::cerr << "FOUND USER in nested loop: " << *User
344             << "   OF SCEV: " << *ISE << "\n");
345       AddUserToIVUsers = true;
346     } else if (!AddUsersIfInteresting(User, L, Processed)) {
347       DEBUG(std::cerr << "FOUND USER: " << *User
348             << "   OF SCEV: " << *ISE << "\n");
349       AddUserToIVUsers = true;
350     }
351
352     if (AddUserToIVUsers) {
353       // Okay, we found a user that we cannot reduce.  Analyze the instruction
354       // and decide what to do with it.  If we are a use inside of the loop, use
355       // the value before incrementation, otherwise use it after incrementation.
356       if (L->contains(User->getParent())) {
357         IVUsesByStride[Stride].addUser(Start, User, I);
358       } else {
359         // The value used will be incremented by the stride more than we are
360         // expecting, so subtract this off.
361         SCEVHandle NewStart = SCEV::getMinusSCEV(Start, Stride);
362         IVUsesByStride[Stride].addUser(NewStart, User, I);
363         IVUsesByStride[Stride].Users.back().isUseOfPostIncrementedValue = true;
364       }
365     }
366   }
367   return true;
368 }
369
370 namespace {
371   /// BasedUser - For a particular base value, keep information about how we've
372   /// partitioned the expression so far.
373   struct BasedUser {
374     /// Base - The Base value for the PHI node that needs to be inserted for
375     /// this use.  As the use is processed, information gets moved from this
376     /// field to the Imm field (below).  BasedUser values are sorted by this
377     /// field.
378     SCEVHandle Base;
379     
380     /// Inst - The instruction using the induction variable.
381     Instruction *Inst;
382
383     /// OperandValToReplace - The operand value of Inst to replace with the
384     /// EmittedBase.
385     Value *OperandValToReplace;
386
387     /// Imm - The immediate value that should be added to the base immediately
388     /// before Inst, because it will be folded into the imm field of the
389     /// instruction.
390     SCEVHandle Imm;
391
392     /// EmittedBase - The actual value* to use for the base value of this
393     /// operation.  This is null if we should just use zero so far.
394     Value *EmittedBase;
395
396     // isUseOfPostIncrementedValue - True if this should use the
397     // post-incremented version of this IV, not the preincremented version.
398     // This can only be set in special cases, such as the terminating setcc
399     // instruction for a loop and uses outside the loop that are dominated by
400     // the loop.
401     bool isUseOfPostIncrementedValue;
402     
403     BasedUser(IVStrideUse &IVSU)
404       : Base(IVSU.Offset), Inst(IVSU.User), 
405         OperandValToReplace(IVSU.OperandValToReplace), 
406         Imm(SCEVUnknown::getIntegerSCEV(0, Base->getType())), EmittedBase(0),
407         isUseOfPostIncrementedValue(IVSU.isUseOfPostIncrementedValue) {}
408
409     // Once we rewrite the code to insert the new IVs we want, update the
410     // operands of Inst to use the new expression 'NewBase', with 'Imm' added
411     // to it.
412     void RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
413                                         SCEVExpander &Rewriter, Loop *L,
414                                         Pass *P);
415
416     // Sort by the Base field.
417     bool operator<(const BasedUser &BU) const { return Base < BU.Base; }
418
419     void dump() const;
420   };
421 }
422
423 void BasedUser::dump() const {
424   std::cerr << " Base=" << *Base;
425   std::cerr << " Imm=" << *Imm;
426   if (EmittedBase)
427     std::cerr << "  EB=" << *EmittedBase;
428
429   std::cerr << "   Inst: " << *Inst;
430 }
431
432 // Once we rewrite the code to insert the new IVs we want, update the
433 // operands of Inst to use the new expression 'NewBase', with 'Imm' added
434 // to it.
435 void BasedUser::RewriteInstructionToUseNewBase(const SCEVHandle &NewBase,
436                                                SCEVExpander &Rewriter,
437                                                Loop *L, Pass *P) {
438   if (!isa<PHINode>(Inst)) {
439     SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
440     Value *NewVal = Rewriter.expandCodeFor(NewValSCEV, Inst,
441                                            OperandValToReplace->getType());
442     // Replace the use of the operand Value with the new Phi we just created.
443     Inst->replaceUsesOfWith(OperandValToReplace, NewVal);
444     DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
445     return;
446   }
447   
448   // PHI nodes are more complex.  We have to insert one copy of the NewBase+Imm
449   // expression into each operand block that uses it.  Note that PHI nodes can
450   // have multiple entries for the same predecessor.  We use a map to make sure
451   // that a PHI node only has a single Value* for each predecessor (which also
452   // prevents us from inserting duplicate code in some blocks).
453   std::map<BasicBlock*, Value*> InsertedCode;
454   PHINode *PN = cast<PHINode>(Inst);
455   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
456     if (PN->getIncomingValue(i) == OperandValToReplace) {
457       // If this is a critical edge, split the edge so that we do not insert the
458       // code on all predecessor/successor paths.
459       if (e != 1 &&
460           PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() > 1) {
461
462         // First step, split the critical edge.
463         SplitCriticalEdge(PN->getIncomingBlock(i), PN->getParent(), P);
464             
465         // Next step: move the basic block.  In particular, if the PHI node
466         // is outside of the loop, and PredTI is in the loop, we want to
467         // move the block to be immediately before the PHI block, not
468         // immediately after PredTI.
469         if (L->contains(PN->getIncomingBlock(i)) &&
470             !L->contains(PN->getParent())) {
471           BasicBlock *NewBB = PN->getIncomingBlock(i);
472           NewBB->moveBefore(PN->getParent());
473         }
474         break;
475       }
476
477       Value *&Code = InsertedCode[PN->getIncomingBlock(i)];
478       if (!Code) {
479         // Insert the code into the end of the predecessor block.
480         BasicBlock::iterator InsertPt =PN->getIncomingBlock(i)->getTerminator();
481       
482         SCEVHandle NewValSCEV = SCEVAddExpr::get(NewBase, Imm);
483         Code = Rewriter.expandCodeFor(NewValSCEV, InsertPt,
484                                       OperandValToReplace->getType());
485       }
486       
487       // Replace the use of the operand Value with the new Phi we just created.
488       PN->setIncomingValue(i, Code);
489       Rewriter.clear();
490     }
491   }
492   DEBUG(std::cerr << "    CHANGED: IMM =" << *Imm << "  Inst = " << *Inst);
493 }
494
495
496 /// isTargetConstant - Return true if the following can be referenced by the
497 /// immediate field of a target instruction.
498 static bool isTargetConstant(const SCEVHandle &V) {
499
500   // FIXME: Look at the target to decide if &GV is a legal constant immediate.
501   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
502     // PPC allows a sign-extended 16-bit immediate field.
503     if ((int64_t)SC->getValue()->getRawValue() > -(1 << 16) &&
504         (int64_t)SC->getValue()->getRawValue() < (1 << 16)-1)
505       return true;
506     return false;
507   }
508
509   return false;     // ENABLE this for x86
510
511   if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V))
512     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(SU->getValue()))
513       if (CE->getOpcode() == Instruction::Cast)
514         if (isa<GlobalValue>(CE->getOperand(0)))
515           // FIXME: should check to see that the dest is uintptr_t!
516           return true;
517   return false;
518 }
519
520 /// MoveLoopVariantsToImediateField - Move any subexpressions from Val that are
521 /// loop varying to the Imm operand.
522 static void MoveLoopVariantsToImediateField(SCEVHandle &Val, SCEVHandle &Imm,
523                                             Loop *L) {
524   if (Val->isLoopInvariant(L)) return;  // Nothing to do.
525   
526   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
527     std::vector<SCEVHandle> NewOps;
528     NewOps.reserve(SAE->getNumOperands());
529     
530     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
531       if (!SAE->getOperand(i)->isLoopInvariant(L)) {
532         // If this is a loop-variant expression, it must stay in the immediate
533         // field of the expression.
534         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
535       } else {
536         NewOps.push_back(SAE->getOperand(i));
537       }
538
539     if (NewOps.empty())
540       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
541     else
542       Val = SCEVAddExpr::get(NewOps);
543   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
544     // Try to pull immediates out of the start value of nested addrec's.
545     SCEVHandle Start = SARE->getStart();
546     MoveLoopVariantsToImediateField(Start, Imm, L);
547     
548     std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
549     Ops[0] = Start;
550     Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
551   } else {
552     // Otherwise, all of Val is variant, move the whole thing over.
553     Imm = SCEVAddExpr::get(Imm, Val);
554     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
555   }
556 }
557
558
559 /// MoveImmediateValues - Look at Val, and pull out any additions of constants
560 /// that can fit into the immediate field of instructions in the target.
561 /// Accumulate these immediate values into the Imm value.
562 static void MoveImmediateValues(SCEVHandle &Val, SCEVHandle &Imm,
563                                 bool isAddress, Loop *L) {
564   if (SCEVAddExpr *SAE = dyn_cast<SCEVAddExpr>(Val)) {
565     std::vector<SCEVHandle> NewOps;
566     NewOps.reserve(SAE->getNumOperands());
567     
568     for (unsigned i = 0; i != SAE->getNumOperands(); ++i)
569       if (isAddress && isTargetConstant(SAE->getOperand(i))) {
570         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
571       } else if (!SAE->getOperand(i)->isLoopInvariant(L)) {
572         // If this is a loop-variant expression, it must stay in the immediate
573         // field of the expression.
574         Imm = SCEVAddExpr::get(Imm, SAE->getOperand(i));
575       } else {
576         NewOps.push_back(SAE->getOperand(i));
577       }
578
579     if (NewOps.empty())
580       Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
581     else
582       Val = SCEVAddExpr::get(NewOps);
583     return;
584   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Val)) {
585     // Try to pull immediates out of the start value of nested addrec's.
586     SCEVHandle Start = SARE->getStart();
587     MoveImmediateValues(Start, Imm, isAddress, L);
588     
589     if (Start != SARE->getStart()) {
590       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
591       Ops[0] = Start;
592       Val = SCEVAddRecExpr::get(Ops, SARE->getLoop());
593     }
594     return;
595   }
596
597   // Loop-variant expressions must stay in the immediate field of the
598   // expression.
599   if ((isAddress && isTargetConstant(Val)) ||
600       !Val->isLoopInvariant(L)) {
601     Imm = SCEVAddExpr::get(Imm, Val);
602     Val = SCEVUnknown::getIntegerSCEV(0, Val->getType());
603     return;
604   }
605
606   // Otherwise, no immediates to move.
607 }
608
609
610 /// IncrementAddExprUses - Decompose the specified expression into its added
611 /// subexpressions, and increment SubExpressionUseCounts for each of these
612 /// decomposed parts.
613 static void SeparateSubExprs(std::vector<SCEVHandle> &SubExprs,
614                              SCEVHandle Expr) {
615   if (SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(Expr)) {
616     for (unsigned j = 0, e = AE->getNumOperands(); j != e; ++j)
617       SeparateSubExprs(SubExprs, AE->getOperand(j));
618   } else if (SCEVAddRecExpr *SARE = dyn_cast<SCEVAddRecExpr>(Expr)) {
619     SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Expr->getType());
620     if (SARE->getOperand(0) == Zero) {
621       SubExprs.push_back(Expr);
622     } else {
623       // Compute the addrec with zero as its base.
624       std::vector<SCEVHandle> Ops(SARE->op_begin(), SARE->op_end());
625       Ops[0] = Zero;   // Start with zero base.
626       SubExprs.push_back(SCEVAddRecExpr::get(Ops, SARE->getLoop()));
627       
628
629       SeparateSubExprs(SubExprs, SARE->getOperand(0));
630     }
631   } else if (!isa<SCEVConstant>(Expr) ||
632              !cast<SCEVConstant>(Expr)->getValue()->isNullValue()) {
633     // Do not add zero.
634     SubExprs.push_back(Expr);
635   }
636 }
637
638
639 /// RemoveCommonExpressionsFromUseBases - Look through all of the uses in Bases,
640 /// removing any common subexpressions from it.  Anything truly common is
641 /// removed, accumulated, and returned.  This looks for things like (a+b+c) and
642 /// (a+c+d) -> (a+c).  The common expression is *removed* from the Bases.
643 static SCEVHandle 
644 RemoveCommonExpressionsFromUseBases(std::vector<BasedUser> &Uses) {
645   unsigned NumUses = Uses.size();
646
647   // Only one use?  Use its base, regardless of what it is!
648   SCEVHandle Zero = SCEVUnknown::getIntegerSCEV(0, Uses[0].Base->getType());
649   SCEVHandle Result = Zero;
650   if (NumUses == 1) {
651     std::swap(Result, Uses[0].Base);
652     return Result;
653   }
654
655   // To find common subexpressions, count how many of Uses use each expression.
656   // If any subexpressions are used Uses.size() times, they are common.
657   std::map<SCEVHandle, unsigned> SubExpressionUseCounts;
658   
659   std::vector<SCEVHandle> SubExprs;
660   for (unsigned i = 0; i != NumUses; ++i) {
661     // If the base is zero (which is common), return zero now, there are no
662     // CSEs we can find.
663     if (Uses[i].Base == Zero) return Zero;
664
665     // Split the expression into subexprs.
666     SeparateSubExprs(SubExprs, Uses[i].Base);
667     // Add one to SubExpressionUseCounts for each subexpr present.
668     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
669       SubExpressionUseCounts[SubExprs[j]]++;
670     SubExprs.clear();
671   }
672
673
674   // Now that we know how many times each is used, build Result.
675   for (std::map<SCEVHandle, unsigned>::iterator I =
676        SubExpressionUseCounts.begin(), E = SubExpressionUseCounts.end();
677        I != E; )
678     if (I->second == NumUses) {  // Found CSE!
679       Result = SCEVAddExpr::get(Result, I->first);
680       ++I;
681     } else {
682       // Remove non-cse's from SubExpressionUseCounts.
683       SubExpressionUseCounts.erase(I++);
684     }
685   
686   // If we found no CSE's, return now.
687   if (Result == Zero) return Result;
688   
689   // Otherwise, remove all of the CSE's we found from each of the base values.
690   for (unsigned i = 0; i != NumUses; ++i) {
691     // Split the expression into subexprs.
692     SeparateSubExprs(SubExprs, Uses[i].Base);
693
694     // Remove any common subexpressions.
695     for (unsigned j = 0, e = SubExprs.size(); j != e; ++j)
696       if (SubExpressionUseCounts.count(SubExprs[j])) {
697         SubExprs.erase(SubExprs.begin()+j);
698         --j; --e;
699       }
700     
701     // Finally, the non-shared expressions together.
702     if (SubExprs.empty())
703       Uses[i].Base = Zero;
704     else
705       Uses[i].Base = SCEVAddExpr::get(SubExprs);
706     SubExprs.clear();
707   }
708  
709   return Result;
710 }
711
712
713 /// StrengthReduceStridedIVUsers - Strength reduce all of the users of a single
714 /// stride of IV.  All of the users may have different starting values, and this
715 /// may not be the only stride (we know it is if isOnlyStride is true).
716 void LoopStrengthReduce::StrengthReduceStridedIVUsers(const SCEVHandle &Stride,
717                                                       IVUsersOfOneStride &Uses,
718                                                       Loop *L,
719                                                       bool isOnlyStride) {
720   // Transform our list of users and offsets to a bit more complex table.  In
721   // this new vector, each 'BasedUser' contains 'Base' the base of the
722   // strided accessas well as the old information from Uses.  We progressively
723   // move information from the Base field to the Imm field, until we eventually
724   // have the full access expression to rewrite the use.
725   std::vector<BasedUser> UsersToProcess;
726   UsersToProcess.reserve(Uses.Users.size());
727   for (unsigned i = 0, e = Uses.Users.size(); i != e; ++i) {
728     UsersToProcess.push_back(Uses.Users[i]);
729     
730     // Move any loop invariant operands from the offset field to the immediate
731     // field of the use, so that we don't try to use something before it is
732     // computed.
733     MoveLoopVariantsToImediateField(UsersToProcess.back().Base,
734                                     UsersToProcess.back().Imm, L);
735     assert(UsersToProcess.back().Base->isLoopInvariant(L) &&
736            "Base value is not loop invariant!");
737   }
738   
739   // We now have a whole bunch of uses of like-strided induction variables, but
740   // they might all have different bases.  We want to emit one PHI node for this
741   // stride which we fold as many common expressions (between the IVs) into as
742   // possible.  Start by identifying the common expressions in the base values 
743   // for the strides (e.g. if we have "A+C+B" and "A+B+D" as our bases, find
744   // "A+B"), emit it to the preheader, then remove the expression from the
745   // UsersToProcess base values.
746   SCEVHandle CommonExprs = RemoveCommonExpressionsFromUseBases(UsersToProcess);
747   
748   // Next, figure out what we can represent in the immediate fields of
749   // instructions.  If we can represent anything there, move it to the imm
750   // fields of the BasedUsers.  We do this so that it increases the commonality
751   // of the remaining uses.
752   for (unsigned i = 0, e = UsersToProcess.size(); i != e; ++i) {
753     // If the user is not in the current loop, this means it is using the exit
754     // value of the IV.  Do not put anything in the base, make sure it's all in
755     // the immediate field to allow as much factoring as possible.
756     if (!L->contains(UsersToProcess[i].Inst->getParent())) {
757       UsersToProcess[i].Imm = SCEVAddExpr::get(UsersToProcess[i].Imm,
758                                                UsersToProcess[i].Base);
759       UsersToProcess[i].Base = 
760         SCEVUnknown::getIntegerSCEV(0, UsersToProcess[i].Base->getType());
761     } else {
762       
763       // Addressing modes can be folded into loads and stores.  Be careful that
764       // the store is through the expression, not of the expression though.
765       bool isAddress = isa<LoadInst>(UsersToProcess[i].Inst);
766       if (StoreInst *SI = dyn_cast<StoreInst>(UsersToProcess[i].Inst))
767         if (SI->getOperand(1) == UsersToProcess[i].OperandValToReplace)
768           isAddress = true;
769       
770       MoveImmediateValues(UsersToProcess[i].Base, UsersToProcess[i].Imm,
771                           isAddress, L);
772     }
773   }
774  
775   // Now that we know what we need to do, insert the PHI node itself.
776   //
777   DEBUG(std::cerr << "INSERTING IV of STRIDE " << *Stride << " and BASE "
778         << *CommonExprs << " :\n");
779     
780   SCEVExpander Rewriter(*SE, *LI);
781   SCEVExpander PreheaderRewriter(*SE, *LI);
782   
783   BasicBlock  *Preheader = L->getLoopPreheader();
784   Instruction *PreInsertPt = Preheader->getTerminator();
785   Instruction *PhiInsertBefore = L->getHeader()->begin();
786   
787   assert(isa<PHINode>(PhiInsertBefore) &&
788          "How could this loop have IV's without any phis?");
789   PHINode *SomeLoopPHI = cast<PHINode>(PhiInsertBefore);
790   assert(SomeLoopPHI->getNumIncomingValues() == 2 &&
791          "This loop isn't canonicalized right");
792   BasicBlock *LatchBlock =
793    SomeLoopPHI->getIncomingBlock(SomeLoopPHI->getIncomingBlock(0) == Preheader);
794   
795   // Create a new Phi for this base, and stick it in the loop header.
796   const Type *ReplacedTy = CommonExprs->getType();
797   PHINode *NewPHI = new PHINode(ReplacedTy, "iv.", PhiInsertBefore);
798   ++NumInserted;
799   
800   // Insert the stride into the preheader.
801   Value *StrideV = PreheaderRewriter.expandCodeFor(Stride, PreInsertPt,
802                                                    ReplacedTy);
803   if (!isa<ConstantInt>(StrideV)) ++NumVariable;
804
805
806   // Emit the initial base value into the loop preheader, and add it to the
807   // Phi node.
808   Value *PHIBaseV = PreheaderRewriter.expandCodeFor(CommonExprs, PreInsertPt,
809                                                     ReplacedTy);
810   NewPHI->addIncoming(PHIBaseV, Preheader);
811   
812   // Emit the increment of the base value before the terminator of the loop
813   // latch block, and add it to the Phi node.
814   SCEVHandle IncExp = SCEVAddExpr::get(SCEVUnknown::get(NewPHI),
815                                        SCEVUnknown::get(StrideV));
816   
817   Value *IncV = Rewriter.expandCodeFor(IncExp, LatchBlock->getTerminator(),
818                                        ReplacedTy);
819   IncV->setName(NewPHI->getName()+".inc");
820   NewPHI->addIncoming(IncV, LatchBlock);
821
822   // Sort by the base value, so that all IVs with identical bases are next to
823   // each other.
824   std::sort(UsersToProcess.begin(), UsersToProcess.end());
825   while (!UsersToProcess.empty()) {
826     SCEVHandle Base = UsersToProcess.front().Base;
827
828     DEBUG(std::cerr << "  INSERTING code for BASE = " << *Base << ":\n");
829    
830     // Emit the code for Base into the preheader.
831     Value *BaseV = PreheaderRewriter.expandCodeFor(Base, PreInsertPt,
832                                                    ReplacedTy);
833     
834     // If BaseV is a constant other than 0, make sure that it gets inserted into
835     // the preheader, instead of being forward substituted into the uses.  We do
836     // this by forcing a noop cast to be inserted into the preheader in this
837     // case.
838     if (Constant *C = dyn_cast<Constant>(BaseV))
839       if (!C->isNullValue() && !isTargetConstant(Base)) {
840         // We want this constant emitted into the preheader!
841         BaseV = new CastInst(BaseV, BaseV->getType(), "preheaderinsert",
842                              PreInsertPt);       
843       }
844     
845     // Emit the code to add the immediate offset to the Phi value, just before
846     // the instructions that we identified as using this stride and base.
847     while (!UsersToProcess.empty() && UsersToProcess.front().Base == Base) {
848       BasedUser &User = UsersToProcess.front();
849
850       // If this instruction wants to use the post-incremented value, move it
851       // after the post-inc and use its value instead of the PHI.
852       Value *RewriteOp = NewPHI;
853       if (User.isUseOfPostIncrementedValue) {
854         RewriteOp = IncV;
855
856         // If this user is in the loop, make sure it is the last thing in the
857         // loop to ensure it is dominated by the increment.
858         if (L->contains(User.Inst->getParent()))
859           User.Inst->moveBefore(LatchBlock->getTerminator());
860       }
861       SCEVHandle RewriteExpr = SCEVUnknown::get(RewriteOp);
862
863       // Clear the SCEVExpander's expression map so that we are guaranteed
864       // to have the code emitted where we expect it.
865       Rewriter.clear();
866      
867       // Now that we know what we need to do, insert code before User for the
868       // immediate and any loop-variant expressions.
869       if (!isa<ConstantInt>(BaseV) || !cast<ConstantInt>(BaseV)->isNullValue())
870         // Add BaseV to the PHI value if needed.
871         RewriteExpr = SCEVAddExpr::get(RewriteExpr, SCEVUnknown::get(BaseV));
872       
873       User.RewriteInstructionToUseNewBase(RewriteExpr, Rewriter, L, this);
874
875       // Mark old value we replaced as possibly dead, so that it is elminated
876       // if we just replaced the last use of that value.
877       DeadInsts.insert(cast<Instruction>(User.OperandValToReplace));
878
879       UsersToProcess.erase(UsersToProcess.begin());
880       ++NumReduced;
881     }
882     // TODO: Next, find out which base index is the most common, pull it out.
883   }
884
885   // IMPORTANT TODO: Figure out how to partition the IV's with this stride, but
886   // different starting values, into different PHIs.
887 }
888
889 // OptimizeIndvars - Now that IVUsesByStride is set up with all of the indvar
890 // uses in the loop, look to see if we can eliminate some, in favor of using
891 // common indvars for the different uses.
892 void LoopStrengthReduce::OptimizeIndvars(Loop *L) {
893   // TODO: implement optzns here.
894
895
896
897
898   // Finally, get the terminating condition for the loop if possible.  If we
899   // can, we want to change it to use a post-incremented version of its
900   // induction variable, to allow coallescing the live ranges for the IV into
901   // one register value.
902   PHINode *SomePHI = cast<PHINode>(L->getHeader()->begin());
903   BasicBlock  *Preheader = L->getLoopPreheader();
904   BasicBlock *LatchBlock =
905    SomePHI->getIncomingBlock(SomePHI->getIncomingBlock(0) == Preheader);
906   BranchInst *TermBr = dyn_cast<BranchInst>(LatchBlock->getTerminator());
907   if (!TermBr || TermBr->isUnconditional() ||
908       !isa<SetCondInst>(TermBr->getCondition()))
909     return;
910   SetCondInst *Cond = cast<SetCondInst>(TermBr->getCondition());
911
912   // Search IVUsesByStride to find Cond's IVUse if there is one.
913   IVStrideUse *CondUse = 0;
914   const SCEVHandle *CondStride = 0;
915
916   for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator 
917          I = IVUsesByStride.begin(), E = IVUsesByStride.end();
918        I != E && !CondUse; ++I)
919     for (std::vector<IVStrideUse>::iterator UI = I->second.Users.begin(),
920            E = I->second.Users.end(); UI != E; ++UI)
921       if (UI->User == Cond) {
922         CondUse = &*UI;
923         CondStride = &I->first;
924         // NOTE: we could handle setcc instructions with multiple uses here, but
925         // InstCombine does it as well for simple uses, it's not clear that it
926         // occurs enough in real life to handle.
927         break;
928       }
929   if (!CondUse) return;  // setcc doesn't use the IV.
930
931   // setcc stride is complex, don't mess with users.
932   // FIXME: Evaluate whether this is a good idea or not.
933   if (!isa<SCEVConstant>(*CondStride)) return;
934
935   // It's possible for the setcc instruction to be anywhere in the loop, and
936   // possible for it to have multiple users.  If it is not immediately before
937   // the latch block branch, move it.
938   if (&*++BasicBlock::iterator(Cond) != (Instruction*)TermBr) {
939     if (Cond->hasOneUse()) {   // Condition has a single use, just move it.
940       Cond->moveBefore(TermBr);
941     } else {
942       // Otherwise, clone the terminating condition and insert into the loopend.
943       Cond = cast<SetCondInst>(Cond->clone());
944       Cond->setName(L->getHeader()->getName() + ".termcond");
945       LatchBlock->getInstList().insert(TermBr, Cond);
946       
947       // Clone the IVUse, as the old use still exists!
948       IVUsesByStride[*CondStride].addUser(CondUse->Offset, Cond,
949                                          CondUse->OperandValToReplace);
950       CondUse = &IVUsesByStride[*CondStride].Users.back();
951     }
952   }
953
954   // If we get to here, we know that we can transform the setcc instruction to
955   // use the post-incremented version of the IV, allowing us to coallesce the
956   // live ranges for the IV correctly.
957   CondUse->Offset = SCEV::getMinusSCEV(CondUse->Offset, *CondStride);
958   CondUse->isUseOfPostIncrementedValue = true;
959 }
960
961 void LoopStrengthReduce::runOnLoop(Loop *L) {
962   // First step, transform all loops nesting inside of this loop.
963   for (LoopInfo::iterator I = L->begin(), E = L->end(); I != E; ++I)
964     runOnLoop(*I);
965
966   // Next, find all uses of induction variables in this loop, and catagorize
967   // them by stride.  Start by finding all of the PHI nodes in the header for
968   // this loop.  If they are induction variables, inspect their uses.
969   std::set<Instruction*> Processed;   // Don't reprocess instructions.
970   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
971     AddUsersIfInteresting(I, L, Processed);
972
973   // If we have nothing to do, return.
974   if (IVUsesByStride.empty()) return;
975
976   // Optimize induction variables.  Some indvar uses can be transformed to use
977   // strides that will be needed for other purposes.  A common example of this
978   // is the exit test for the loop, which can often be rewritten to use the
979   // computation of some other indvar to decide when to terminate the loop.
980   OptimizeIndvars(L);
981
982
983   // FIXME: We can widen subreg IV's here for RISC targets.  e.g. instead of
984   // doing computation in byte values, promote to 32-bit values if safe.
985
986   // FIXME: Attempt to reuse values across multiple IV's.  In particular, we
987   // could have something like "for(i) { foo(i*8); bar(i*16) }", which should be
988   // codegened as "for (j = 0;; j+=8) { foo(j); bar(j+j); }" on X86/PPC.  Need
989   // to be careful that IV's are all the same type.  Only works for intptr_t
990   // indvars.
991
992   // If we only have one stride, we can more aggressively eliminate some things.
993   bool HasOneStride = IVUsesByStride.size() == 1;
994
995   // Note: this processes each stride/type pair individually.  All users passed
996   // into StrengthReduceStridedIVUsers have the same type AND stride.
997   for (std::map<SCEVHandle, IVUsersOfOneStride>::iterator SI
998         = IVUsesByStride.begin(), E = IVUsesByStride.end(); SI != E; ++SI)
999     StrengthReduceStridedIVUsers(SI->first, SI->second, L, HasOneStride);
1000
1001   // Clean up after ourselves
1002   if (!DeadInsts.empty()) {
1003     DeleteTriviallyDeadInstructions(DeadInsts);
1004
1005     BasicBlock::iterator I = L->getHeader()->begin();
1006     PHINode *PN;
1007     while ((PN = dyn_cast<PHINode>(I))) {
1008       ++I;  // Preincrement iterator to avoid invalidating it when deleting PN.
1009       
1010       // At this point, we know that we have killed one or more GEP
1011       // instructions.  It is worth checking to see if the cann indvar is also
1012       // dead, so that we can remove it as well.  The requirements for the cann
1013       // indvar to be considered dead are:
1014       // 1. the cann indvar has one use
1015       // 2. the use is an add instruction
1016       // 3. the add has one use
1017       // 4. the add is used by the cann indvar
1018       // If all four cases above are true, then we can remove both the add and
1019       // the cann indvar.
1020       // FIXME: this needs to eliminate an induction variable even if it's being
1021       // compared against some value to decide loop termination.
1022       if (PN->hasOneUse()) {
1023         BinaryOperator *BO = dyn_cast<BinaryOperator>(*(PN->use_begin()));
1024         if (BO && BO->hasOneUse()) {
1025           if (PN == *(BO->use_begin())) {
1026             DeadInsts.insert(BO);
1027             // Break the cycle, then delete the PHI.
1028             PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1029             SE->deleteInstructionFromRecords(PN);
1030             PN->eraseFromParent();
1031           }
1032         }
1033       }
1034     }
1035     DeleteTriviallyDeadInstructions(DeadInsts);
1036   }
1037
1038   CastedPointers.clear();
1039   IVUsesByStride.clear();
1040   return;
1041 }