a2f7b58be1fafdead099e8e828ebfdcaea68b813
[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/AliasAnalysis.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/ScalarEvolutionExpander.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/IRBuilder.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/Statistic.h"
29 using namespace llvm;
30
31 // TODO: Recognize "N" size array multiplies: replace with call to blas or
32 // something.
33 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
34 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
35
36 namespace {
37   class LoopIdiomRecognize : public LoopPass {
38     Loop *CurLoop;
39     const TargetData *TD;
40     ScalarEvolution *SE;
41   public:
42     static char ID;
43     explicit LoopIdiomRecognize() : LoopPass(ID) {
44       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
45     }
46
47     bool runOnLoop(Loop *L, LPPassManager &LPM);
48
49     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
50     
51     bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
52                                       Value *SplatValue,
53                                       const SCEVAddRecExpr *Ev,
54                                       const SCEV *BECount);
55     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
56                                     const SCEVAddRecExpr *StoreEv,
57                                     const SCEVAddRecExpr *LoadEv,
58                                     const SCEV *BECount);
59       
60     /// This transformation requires natural loop information & requires that
61     /// loop preheaders be inserted into the CFG.
62     ///
63     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64       AU.addRequired<LoopInfo>();
65       AU.addPreserved<LoopInfo>();
66       AU.addRequiredID(LoopSimplifyID);
67       AU.addPreservedID(LoopSimplifyID);
68       AU.addRequiredID(LCSSAID);
69       AU.addPreservedID(LCSSAID);
70       AU.addRequired<AliasAnalysis>();
71       AU.addPreserved<AliasAnalysis>();
72       AU.addRequired<ScalarEvolution>();
73       AU.addPreserved<ScalarEvolution>();
74       AU.addPreserved<DominatorTree>();
75     }
76   };
77 }
78
79 char LoopIdiomRecognize::ID = 0;
80 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
81                       false, false)
82 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
83 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
84 INITIALIZE_PASS_DEPENDENCY(LCSSA)
85 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
86 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
87 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
88                     false, false)
89
90 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
91
92 /// DeleteDeadInstruction - Delete this instruction.  Before we do, go through
93 /// and zero out all the operands of this instruction.  If any of them become
94 /// dead, delete them and the computation tree that feeds them.
95 ///
96 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
97   SmallVector<Instruction*, 32> NowDeadInsts;
98   
99   NowDeadInsts.push_back(I);
100   
101   // Before we touch this instruction, remove it from SE!
102   do {
103     Instruction *DeadInst = NowDeadInsts.pop_back_val();
104     
105     // This instruction is dead, zap it, in stages.  Start by removing it from
106     // SCEV.
107     SE.forgetValue(DeadInst);
108     
109     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
110       Value *Op = DeadInst->getOperand(op);
111       DeadInst->setOperand(op, 0);
112       
113       // If this operand just became dead, add it to the NowDeadInsts list.
114       if (!Op->use_empty()) continue;
115       
116       if (Instruction *OpI = dyn_cast<Instruction>(Op))
117         if (isInstructionTriviallyDead(OpI))
118           NowDeadInsts.push_back(OpI);
119     }
120     
121     DeadInst->eraseFromParent();
122     
123   } while (!NowDeadInsts.empty());
124 }
125
126 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
127   CurLoop = L;
128   
129   if (L->getHeader()->getName().startswith("bb29")) {
130     errs() << *L->getHeader();
131   }
132   
133   // We only look at trivial single basic block loops.
134   // TODO: eventually support more complex loops, scanning the header.
135   if (L->getBlocks().size() != 1)
136     return false;
137   
138   // The trip count of the loop must be analyzable.
139   SE = &getAnalysis<ScalarEvolution>();
140   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
141     return false;
142   const SCEV *BECount = SE->getBackedgeTakenCount(L);
143   if (isa<SCEVCouldNotCompute>(BECount)) return false;
144   
145   // We require target data for now.
146   TD = getAnalysisIfAvailable<TargetData>();
147   if (TD == 0) return false;
148   
149   BasicBlock *BB = L->getHeader();
150   DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
151                << "] Loop %" << BB->getName() << "\n");
152
153   bool MadeChange = false;
154   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
155     // Look for store instructions, which may be memsets.
156     StoreInst *SI = dyn_cast<StoreInst>(I++);
157     if (SI == 0 || SI->isVolatile()) continue;
158     
159     WeakVH InstPtr(SI);
160     if (!processLoopStore(SI, BECount)) continue;
161     
162     MadeChange = true;
163     
164     // If processing the store invalidated our iterator, start over from the
165     // head of the loop.
166     if (InstPtr == 0)
167       I = BB->begin();
168   }
169   
170   return MadeChange;
171 }
172
173 /// scanBlock - Look over a block to see if we can promote anything out of it.
174 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
175   Value *StoredVal = SI->getValueOperand();
176   Value *StorePtr = SI->getPointerOperand();
177   
178   // Reject stores that are so large that they overflow an unsigned.
179   uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
180   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
181     return false;
182   
183   // See if the pointer expression is an AddRec like {base,+,1} on the current
184   // loop, which indicates a strided store.  If we have something else, it's a
185   // random store we can't handle.
186   const SCEVAddRecExpr *StoreEv =
187     dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
188   if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
189     return false;
190
191   // Check to see if the stride matches the size of the store.  If so, then we
192   // know that every byte is touched in the loop.
193   unsigned StoreSize = (unsigned)SizeInBits >> 3; 
194   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
195   
196   // TODO: Could also handle negative stride here someday, that will require the
197   // validity check in mayLoopModRefLocation to be updated though.
198   if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
199     return false;
200   
201   // If the stored value is a byte-wise value (like i32 -1), then it may be
202   // turned into a memset of i8 -1, assuming that all the consequtive bytes
203   // are stored.  A store of i32 0x01020304 can never be turned into a memset.
204   if (Value *SplatValue = isBytewiseValue(StoredVal))
205     if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
206                                      BECount))
207       return true;
208
209   // If the stored value is a strided load in the same loop with the same stride
210   // this this may be transformable into a memcpy.  This kicks in for stuff like
211   //   for (i) A[i] = B[i];
212   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
213     const SCEVAddRecExpr *LoadEv =
214       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
215     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
216         StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
217       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
218         return true;
219   }
220   //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
221
222   return false;
223 }
224
225 /// mayLoopModRefLocation - Return true if the specified loop might do a load or
226 /// store to the same location that the specified store could store to, which is
227 /// a loop-strided access. 
228 static bool mayLoopModRefLocation(Value *Ptr, Loop *L, const SCEV *BECount,
229                                   unsigned StoreSize, AliasAnalysis &AA,
230                                   StoreInst *IgnoredStore) {
231   // Get the location that may be stored across the loop.  Since the access is
232   // strided positively through memory, we say that the modified location starts
233   // at the pointer and has infinite size.
234   uint64_t AccessSize = AliasAnalysis::UnknownSize;
235
236   // If the loop iterates a fixed number of times, we can refine the access size
237   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
238   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
239     AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
240   
241   // TODO: For this to be really effective, we have to dive into the pointer
242   // operand in the store.  Store to &A[i] of 100 will always return may alias
243   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
244   // which will then no-alias a store to &A[100].
245   AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
246
247   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
248        ++BI)
249     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
250       if (&*I != IgnoredStore &&
251           AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
252         return true;
253
254   return false;
255 }
256
257 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
258 /// If we can transform this into a memset in the loop preheader, do so.
259 bool LoopIdiomRecognize::
260 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
261                              Value *SplatValue,
262                              const SCEVAddRecExpr *Ev, const SCEV *BECount) {
263   // Verify that the stored value is loop invariant.  If not, we can't promote
264   // the memset.
265   if (!CurLoop->isLoopInvariant(SplatValue))
266     return false;
267   
268   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
269   // this into a memset in the loop preheader now if we want.  However, this
270   // would be unsafe to do if there is anything else in the loop that may read
271   // or write to the aliased location.  Check for an alias.
272   if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
273                             StoreSize, getAnalysis<AliasAnalysis>(), SI))
274     return false;
275   
276   // Okay, everything looks good, insert the memset.
277   BasicBlock *Preheader = CurLoop->getLoopPreheader();
278   
279   IRBuilder<> Builder(Preheader->getTerminator());
280   
281   // The trip count of the loop and the base pointer of the addrec SCEV is
282   // guaranteed to be loop invariant, which means that it should dominate the
283   // header.  Just insert code for it in the preheader.
284   SCEVExpander Expander(*SE);
285   
286   unsigned AddrSpace = SI->getPointerAddressSpace();
287   Value *BasePtr = 
288     Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
289                            Preheader->getTerminator());
290   
291   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
292   // pointer size if it isn't already.
293   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
294   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
295   if (BESize < TD->getPointerSizeInBits())
296     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
297   else if (BESize > TD->getPointerSizeInBits())
298     BECount = SE->getTruncateExpr(BECount, IntPtr);
299   
300   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
301                                          true, true /*nooverflow*/);
302   if (StoreSize != 1)
303     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
304                                true, true /*nooverflow*/);
305   
306   Value *NumBytes = 
307     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
308   
309   Value *NewCall =
310     Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
311   
312   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
313                << "    from store to: " << *Ev << " at: " << *SI << "\n");
314   (void)NewCall;
315   
316   // Okay, the memset has been formed.  Zap the original store and anything that
317   // feeds into it.
318   DeleteDeadInstruction(SI, *SE);
319   ++NumMemSet;
320   return true;
321 }
322
323 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
324 /// same-strided load.
325 bool LoopIdiomRecognize::
326 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
327                            const SCEVAddRecExpr *StoreEv,
328                            const SCEVAddRecExpr *LoadEv,
329                            const SCEV *BECount) {
330   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
331   
332   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
333   // this into a memcmp in the loop preheader now if we want.  However, this
334   // would be unsafe to do if there is anything else in the loop that may read
335   // or write to the aliased location (including the load feeding the stores).
336   // Check for an alias.
337   if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
338                             StoreSize, getAnalysis<AliasAnalysis>(), SI))
339     return false;
340   
341   // Okay, everything looks good, insert the memcpy.
342   BasicBlock *Preheader = CurLoop->getLoopPreheader();
343   
344   IRBuilder<> Builder(Preheader->getTerminator());
345   
346   // The trip count of the loop and the base pointer of the addrec SCEV is
347   // guaranteed to be loop invariant, which means that it should dominate the
348   // header.  Just insert code for it in the preheader.
349   SCEVExpander Expander(*SE);
350
351   Value *LoadBasePtr = 
352     Expander.expandCodeFor(LoadEv->getStart(),
353                            Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
354                            Preheader->getTerminator());
355   Value *StoreBasePtr = 
356     Expander.expandCodeFor(StoreEv->getStart(),
357                            Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
358                            Preheader->getTerminator());
359   
360   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
361   // pointer size if it isn't already.
362   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
363   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
364   if (BESize < TD->getPointerSizeInBits())
365     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
366   else if (BESize > TD->getPointerSizeInBits())
367     BECount = SE->getTruncateExpr(BECount, IntPtr);
368   
369   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
370                                          true, true /*nooverflow*/);
371   if (StoreSize != 1)
372     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
373                                true, true /*nooverflow*/);
374   
375   Value *NumBytes =
376     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
377   
378   Value *NewCall =
379     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
380                          std::min(SI->getAlignment(), LI->getAlignment()));
381   
382   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
383                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
384                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
385   (void)NewCall;
386   
387   // Okay, the memset has been formed.  Zap the original store and anything that
388   // feeds into it.
389   DeleteDeadInstruction(SI, *SE);
390   ++NumMemCpy;
391   return true;
392 }