implement enough of the memset inference algorithm to recognize and insert
[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/Support/Debug.h"
24 #include "llvm/Support/IRBuilder.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
27
28 // TODO: Recognize "N" size array multiplies: replace with call to blas or
29 // something.
30
31 namespace {
32   class LoopIdiomRecognize : public LoopPass {
33     Loop *CurLoop;
34     const TargetData *TD;
35     ScalarEvolution *SE;
36   public:
37     static char ID;
38     explicit LoopIdiomRecognize() : LoopPass(ID) {
39       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
40     }
41
42     bool runOnLoop(Loop *L, LPPassManager &LPM);
43
44     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
45     
46     bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
47                                       Value *SplatValue,
48                                       const SCEVAddRecExpr *Ev,
49                                       const SCEV *BECount);
50     
51     /// This transformation requires natural loop information & requires that
52     /// loop preheaders be inserted into the CFG.
53     ///
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.addRequired<LoopInfo>();
56       AU.addPreserved<LoopInfo>();
57       AU.addRequiredID(LoopSimplifyID);
58       AU.addPreservedID(LoopSimplifyID);
59       AU.addRequiredID(LCSSAID);
60       AU.addPreservedID(LCSSAID);
61       AU.addRequired<ScalarEvolution>();
62       AU.addPreserved<ScalarEvolution>();
63       AU.addPreserved<DominatorTree>();
64     }
65   };
66 }
67
68 char LoopIdiomRecognize::ID = 0;
69 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
70                       false, false)
71 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
72 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
73 INITIALIZE_PASS_DEPENDENCY(LCSSA)
74 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
75 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
76                     false, false)
77
78 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
79
80 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
81   CurLoop = L;
82   
83   // We only look at trivial single basic block loops.
84   // TODO: eventually support more complex loops, scanning the header.
85   if (L->getBlocks().size() != 1)
86     return false;
87   
88   // The trip count of the loop must be analyzable.
89   SE = &getAnalysis<ScalarEvolution>();
90   if (!SE->hasLoopInvariantBackedgeTakenCount(L))
91     return false;
92   const SCEV *BECount = SE->getBackedgeTakenCount(L);
93   if (isa<SCEVCouldNotCompute>(BECount)) return false;
94   
95   // We require target data for now.
96   TD = getAnalysisIfAvailable<TargetData>();
97   if (TD == 0) return false;
98   
99   BasicBlock *BB = L->getHeader();
100   DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
101                << "] Loop %" << BB->getName() << "\n");
102
103   bool MadeChange = false;
104   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
105     // Look for store instructions, which may be memsets.
106     StoreInst *SI = dyn_cast<StoreInst>(I++);
107     if (SI == 0 || SI->isVolatile()) continue;
108     
109     
110     MadeChange |= processLoopStore(SI, BECount);
111   }
112   
113   return MadeChange;
114 }
115
116 /// scanBlock - Look over a block to see if we can promote anything out of it.
117 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
118   Value *StoredVal = SI->getValueOperand();
119   Value *StorePtr = SI->getPointerOperand();
120   
121   // Check to see if the store updates all bits in memory.  We don't want to
122   // process things like a store of i3.  We also require that the store be a
123   // multiple of a byte.
124   uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
125   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0 ||
126       SizeInBits != TD->getTypeStoreSizeInBits(StoredVal->getType()))
127     return false;
128   
129   // See if the pointer expression is an AddRec like {base,+,1} on the current
130   // loop, which indicates a strided store.  If we have something else, it's a
131   // random store we can't handle.
132   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
133   if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
134     return false;
135
136   // Check to see if the stride matches the size of the store.  If so, then we
137   // know that every byte is touched in the loop.
138   unsigned StoreSize = (unsigned)SizeInBits >> 3; 
139   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
140   if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
141     return false;
142   
143   // If the stored value is a byte-wise value (like i32 -1), then it may be
144   // turned into a memset of i8 -1, assuming that all the consequtive bytes
145   // are stored.  A store of i32 0x01020304 can never be turned into a memset.
146   if (Value *SplatValue = isBytewiseValue(StoredVal))
147     return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
148
149   // Handle the memcpy case here.
150   errs() << "Found strided store: " << *Ev << "\n";
151   
152
153   return false;
154 }
155
156 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
157 /// If we can transform this into a memset in the loop preheader, do so.
158 bool LoopIdiomRecognize::
159 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
160                              Value *SplatValue,
161                              const SCEVAddRecExpr *Ev, const SCEV *BECount) {
162   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
163   // this into a memset in the loop preheader now if we want.  However, this
164   // would be unsafe to do if there is anything else in the loop that may read
165   // or write to the aliased location.  Check for an alias.
166   
167   // FIXME: TODO safety check.
168   
169   // Okay, everything looks good, insert the memset.
170   BasicBlock *Preheader = CurLoop->getLoopPreheader();
171   
172   IRBuilder<> Builder(Preheader->getTerminator());
173   
174   // The trip count of the loop and the base pointer of the addrec SCEV is
175   // guaranteed to be loop invariant, which means that it should dominate the
176   // header.  Just insert code for it in the preheader.
177   SCEVExpander Expander(*SE);
178   
179   unsigned AddrSpace = SI->getPointerAddressSpace();
180   Value *BasePtr = 
181     Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
182                            Preheader->getTerminator());
183   
184   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
185   // pointer size if it isn't already.
186   const Type *IntPtr = TD->getIntPtrType(SI->getContext());
187   unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
188   if (BESize < TD->getPointerSizeInBits())
189     BECount = SE->getZeroExtendExpr(BECount, IntPtr);
190   else if (BESize > TD->getPointerSizeInBits())
191     BECount = SE->getTruncateExpr(BECount, IntPtr);
192   
193   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
194                                          true, true /*nooverflow*/);
195   if (StoreSize != 1)
196     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
197                                true, true /*nooverflow*/);
198   
199   Value *NumBytes = 
200     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
201   
202   Value *NewCall =
203     Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
204   
205   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
206                << "    from store to: " << *Ev << " at: " << *SI << "\n");
207   
208   // Okay, the memset has been formed.  Zap the original store.
209   // FIXME: We want to recursively delete dead instructions, but we have to
210   // update SCEV.
211   SI->eraseFromParent();  
212   return true;
213 }
214