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