have loop-idiom nuke instructions that feed stores that get removed.
[oota-llvm.git] / lib / Transforms / Scalar / LoopIdiomRecognize.cpp
1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form.  In cases that this kicks in, it can be a significant
12 // performance win.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "loop-idiom"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ScalarEvolutionExpander.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 // TODO: Recognize "N" size array multiplies: replace with call to blas or
30 // something.
31
32 namespace {
33   class LoopIdiomRecognize : public LoopPass {
34     Loop *CurLoop;
35     const TargetData *TD;
36     ScalarEvolution *SE;
37   public:
38     static char ID;
39     explicit LoopIdiomRecognize() : LoopPass(ID) {
40       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
41     }
42
43     bool runOnLoop(Loop *L, LPPassManager &LPM);
44
45     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
46     
47     bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
48                                       Value *SplatValue,
49                                       const SCEVAddRecExpr *Ev,
50                                       const SCEV *BECount);
51     
52     /// This transformation requires natural loop information & requires that
53     /// loop preheaders be inserted into the CFG.
54     ///
55     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56       AU.addRequired<LoopInfo>();
57       AU.addPreserved<LoopInfo>();
58       AU.addRequiredID(LoopSimplifyID);
59       AU.addPreservedID(LoopSimplifyID);
60       AU.addRequiredID(LCSSAID);
61       AU.addPreservedID(LCSSAID);
62       AU.addRequired<ScalarEvolution>();
63       AU.addPreserved<ScalarEvolution>();
64       AU.addPreserved<DominatorTree>();
65     }
66   };
67 }
68
69 char LoopIdiomRecognize::ID = 0;
70 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
71                       false, false)
72 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
73 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
74 INITIALIZE_PASS_DEPENDENCY(LCSSA)
75 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
76 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
77                     false, false)
78
79 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
80
81 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
82 /// and zero out all the operands of this instruction.  If any of them become
83 /// dead, delete them and the computation tree that feeds them.
84 ///
85 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
86   SmallVector<Instruction*, 32> NowDeadInsts;
87   
88   NowDeadInsts.push_back(I);
89   
90   // Before we touch this instruction, remove it from SE!
91   do {
92     Instruction *DeadInst = NowDeadInsts.pop_back_val();
93     
94     // This instruction is dead, zap it, in stages.  Start by removing it from
95     // SCEV.
96     SE.forgetValue(DeadInst);
97     
98     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
99       Value *Op = DeadInst->getOperand(op);
100       DeadInst->setOperand(op, 0);
101       
102       // If this operand just became dead, add it to the NowDeadInsts list.
103       if (!Op->use_empty()) continue;
104       
105       if (Instruction *OpI = dyn_cast<Instruction>(Op))
106         if (isInstructionTriviallyDead(OpI))
107           NowDeadInsts.push_back(OpI);
108     }
109     
110     DeadInst->eraseFromParent();
111     
112   } while (!NowDeadInsts.empty());
113 }
114
115 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
116   CurLoop = L;
117   
118   // We only look at trivial single basic block loops.
119   // TODO: eventually support more complex loops, scanning the header.
120   if (L->getBlocks().size() != 1)
121     return false;
122   
123   // The trip count of the loop must be analyzable.
124   SE = &getAnalysis<ScalarEvolution>();
125   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
126     return false;
127   const SCEV *BECount = SE->getBackedgeTakenCount(L);
128   if (isa<SCEVCouldNotCompute>(BECount)) return false;
129   
130   // We require target data for now.
131   TD = getAnalysisIfAvailable<TargetData>();
132   if (TD == 0) return false;
133   
134   BasicBlock *BB = L->getHeader();
135   DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
136                << "] Loop %" << BB->getName() << "\n");
137
138   bool MadeChange = false;
139   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
140     // Look for store instructions, which may be memsets.
141     StoreInst *SI = dyn_cast<StoreInst>(I++);
142     if (SI == 0 || SI->isVolatile()) continue;
143     
144     WeakVH InstPtr;
145     if (processLoopStore(SI, BECount)) {
146       // If processing the store invalidated our iterator, start over from the
147       // head of the loop.
148       if (InstPtr == 0)
149         I = BB->begin();
150     }
151   }
152   
153   return MadeChange;
154 }
155
156 /// scanBlock - Look over a block to see if we can promote anything out of it.
157 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
158   Value *StoredVal = SI->getValueOperand();
159   Value *StorePtr = SI->getPointerOperand();
160   
161   // Check to see if the store updates all bits in memory.  We don't want to
162   // process things like a store of i3.  We also require that the store be a
163   // multiple of a byte.
164   uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
165   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0 ||
166       SizeInBits != TD->getTypeStoreSizeInBits(StoredVal->getType()))
167     return false;
168   
169   // See if the pointer expression is an AddRec like {base,+,1} on the current
170   // loop, which indicates a strided store.  If we have something else, it's a
171   // random store we can't handle.
172   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
173   if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
174     return false;
175
176   // Check to see if the stride matches the size of the store.  If so, then we
177   // know that every byte is touched in the loop.
178   unsigned StoreSize = (unsigned)SizeInBits >> 3; 
179   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
180   if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
181     return false;
182   
183   // If the stored value is a byte-wise value (like i32 -1), then it may be
184   // turned into a memset of i8 -1, assuming that all the consequtive bytes
185   // are stored.  A store of i32 0x01020304 can never be turned into a memset.
186   if (Value *SplatValue = isBytewiseValue(StoredVal))
187     return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
188
189   // Handle the memcpy case here.
190   errs() << "Found strided store: " << *Ev << "\n";
191   
192
193   return false;
194 }
195
196 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
197 /// If we can transform this into a memset in the loop preheader, do so.
198 bool LoopIdiomRecognize::
199 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
200                              Value *SplatValue,
201                              const SCEVAddRecExpr *Ev, const SCEV *BECount) {
202   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
203   // this into a memset in the loop preheader now if we want.  However, this
204   // would be unsafe to do if there is anything else in the loop that may read
205   // or write to the aliased location.  Check for an alias.
206   
207   // FIXME: TODO safety check.
208   
209   // Okay, everything looks good, insert the memset.
210   BasicBlock *Preheader = CurLoop->getLoopPreheader();
211   
212   IRBuilder<> Builder(Preheader->getTerminator());
213   
214   // The trip count of the loop and the base pointer of the addrec SCEV is
215   // guaranteed to be loop invariant, which means that it should dominate the
216   // header.  Just insert code for it in the preheader.
217   SCEVExpander Expander(*SE);
218   
219   unsigned AddrSpace = SI->getPointerAddressSpace();
220   Value *BasePtr = 
221     Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
222                            Preheader->getTerminator());
223   
224   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
225   // pointer size if it isn't already.
226   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
227   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
228   if (BESize < TD->getPointerSizeInBits())
229     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
230   else if (BESize > TD->getPointerSizeInBits())
231     BECount = SE->getTruncateExpr(BECount, IntPtr);
232   
233   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
234                                          true, true /*nooverflow*/);
235   if (StoreSize != 1)
236     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
237                                true, true /*nooverflow*/);
238   
239   Value *NumBytes = 
240     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
241   
242   Value *NewCall =
243     Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
244   
245   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
246                << "    from store to: " << *Ev << " at: " << *SI << "\n");
247   
248   // Okay, the memset has been formed.  Zap the original store and anything that
249   // feeds into it.
250   DeleteDeadInstruction(SI, *SE);
251   return true;
252 }
253