Fix batch of converting RegisterPass<> to INTIALIZE_PASS().
[oota-llvm.git] / lib / Analysis / LoopDependenceAnalysis.cpp
1 //===- LoopDependenceAnalysis.cpp - LDA Implementation ----------*- C++ -*-===//
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 is the (beginning) of an implementation of a loop dependence analysis
11 // framework, which is used to detect dependences in memory accesses in loops.
12 //
13 // Please note that this is work in progress and the interface is subject to
14 // change.
15 //
16 // TODO: adapt as implementation progresses.
17 //
18 // TODO: document lingo (pair, subscript, index)
19 //
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "lda"
23 #include "llvm/ADT/DenseSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/LoopDependenceAnalysis.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Operator.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetData.h"
37 using namespace llvm;
38
39 STATISTIC(NumAnswered,    "Number of dependence queries answered");
40 STATISTIC(NumAnalysed,    "Number of distinct dependence pairs analysed");
41 STATISTIC(NumDependent,   "Number of pairs with dependent accesses");
42 STATISTIC(NumIndependent, "Number of pairs with independent accesses");
43 STATISTIC(NumUnknown,     "Number of pairs with unknown accesses");
44
45 LoopPass *llvm::createLoopDependenceAnalysisPass() {
46   return new LoopDependenceAnalysis();
47 }
48
49 INITIALIZE_PASS(LoopDependenceAnalysis, "lda",
50                 "Loop Dependence Analysis", false, true);
51 char LoopDependenceAnalysis::ID = 0;
52
53 //===----------------------------------------------------------------------===//
54 //                             Utility Functions
55 //===----------------------------------------------------------------------===//
56
57 static inline bool IsMemRefInstr(const Value *V) {
58   const Instruction *I = dyn_cast<const Instruction>(V);
59   return I && (I->mayReadFromMemory() || I->mayWriteToMemory());
60 }
61
62 static void GetMemRefInstrs(const Loop *L,
63                             SmallVectorImpl<Instruction*> &Memrefs) {
64   for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
65        b != be; ++b)
66     for (BasicBlock::iterator i = (*b)->begin(), ie = (*b)->end();
67          i != ie; ++i)
68       if (IsMemRefInstr(i))
69         Memrefs.push_back(i);
70 }
71
72 static bool IsLoadOrStoreInst(Value *I) {
73   return isa<LoadInst>(I) || isa<StoreInst>(I);
74 }
75
76 static Value *GetPointerOperand(Value *I) {
77   if (LoadInst *i = dyn_cast<LoadInst>(I))
78     return i->getPointerOperand();
79   if (StoreInst *i = dyn_cast<StoreInst>(I))
80     return i->getPointerOperand();
81   llvm_unreachable("Value is no load or store instruction!");
82   // Never reached.
83   return 0;
84 }
85
86 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
87                                                          const Value *A,
88                                                          const Value *B) {
89   const Value *aObj = A->getUnderlyingObject();
90   const Value *bObj = B->getUnderlyingObject();
91   return AA->alias(aObj, AA->getTypeStoreSize(aObj->getType()),
92                    bObj, AA->getTypeStoreSize(bObj->getType()));
93 }
94
95 static inline const SCEV *GetZeroSCEV(ScalarEvolution *SE) {
96   return SE->getConstant(Type::getInt32Ty(SE->getContext()), 0L);
97 }
98
99 //===----------------------------------------------------------------------===//
100 //                             Dependence Testing
101 //===----------------------------------------------------------------------===//
102
103 bool LoopDependenceAnalysis::isDependencePair(const Value *A,
104                                               const Value *B) const {
105   return IsMemRefInstr(A) &&
106          IsMemRefInstr(B) &&
107          (cast<const Instruction>(A)->mayWriteToMemory() ||
108           cast<const Instruction>(B)->mayWriteToMemory());
109 }
110
111 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value *A,
112                                                         Value *B,
113                                                         DependencePair *&P) {
114   void *insertPos = 0;
115   FoldingSetNodeID id;
116   id.AddPointer(A);
117   id.AddPointer(B);
118
119   P = Pairs.FindNodeOrInsertPos(id, insertPos);
120   if (P) return true;
121
122   P = new (PairAllocator) DependencePair(id, A, B);
123   Pairs.InsertNode(P, insertPos);
124   return false;
125 }
126
127 void LoopDependenceAnalysis::getLoops(const SCEV *S,
128                                       DenseSet<const Loop*>* Loops) const {
129   // Refactor this into an SCEVVisitor, if efficiency becomes a concern.
130   for (const Loop *L = this->L; L != 0; L = L->getParentLoop())
131     if (!S->isLoopInvariant(L))
132       Loops->insert(L);
133 }
134
135 bool LoopDependenceAnalysis::isLoopInvariant(const SCEV *S) const {
136   DenseSet<const Loop*> loops;
137   getLoops(S, &loops);
138   return loops.empty();
139 }
140
141 bool LoopDependenceAnalysis::isAffine(const SCEV *S) const {
142   const SCEVAddRecExpr *rec = dyn_cast<SCEVAddRecExpr>(S);
143   return isLoopInvariant(S) || (rec && rec->isAffine());
144 }
145
146 bool LoopDependenceAnalysis::isZIVPair(const SCEV *A, const SCEV *B) const {
147   return isLoopInvariant(A) && isLoopInvariant(B);
148 }
149
150 bool LoopDependenceAnalysis::isSIVPair(const SCEV *A, const SCEV *B) const {
151   DenseSet<const Loop*> loops;
152   getLoops(A, &loops);
153   getLoops(B, &loops);
154   return loops.size() == 1;
155 }
156
157 LoopDependenceAnalysis::DependenceResult
158 LoopDependenceAnalysis::analyseZIV(const SCEV *A,
159                                    const SCEV *B,
160                                    Subscript *S) const {
161   assert(isZIVPair(A, B) && "Attempted to ZIV-test non-ZIV SCEVs!");
162   return A == B ? Dependent : Independent;
163 }
164
165 LoopDependenceAnalysis::DependenceResult
166 LoopDependenceAnalysis::analyseSIV(const SCEV *A,
167                                    const SCEV *B,
168                                    Subscript *S) const {
169   return Unknown; // TODO: Implement.
170 }
171
172 LoopDependenceAnalysis::DependenceResult
173 LoopDependenceAnalysis::analyseMIV(const SCEV *A,
174                                    const SCEV *B,
175                                    Subscript *S) const {
176   return Unknown; // TODO: Implement.
177 }
178
179 LoopDependenceAnalysis::DependenceResult
180 LoopDependenceAnalysis::analyseSubscript(const SCEV *A,
181                                          const SCEV *B,
182                                          Subscript *S) const {
183   DEBUG(dbgs() << "  Testing subscript: " << *A << ", " << *B << "\n");
184
185   if (A == B) {
186     DEBUG(dbgs() << "  -> [D] same SCEV\n");
187     return Dependent;
188   }
189
190   if (!isAffine(A) || !isAffine(B)) {
191     DEBUG(dbgs() << "  -> [?] not affine\n");
192     return Unknown;
193   }
194
195   if (isZIVPair(A, B))
196     return analyseZIV(A, B, S);
197
198   if (isSIVPair(A, B))
199     return analyseSIV(A, B, S);
200
201   return analyseMIV(A, B, S);
202 }
203
204 LoopDependenceAnalysis::DependenceResult
205 LoopDependenceAnalysis::analysePair(DependencePair *P) const {
206   DEBUG(dbgs() << "Analysing:\n" << *P->A << "\n" << *P->B << "\n");
207
208   // We only analyse loads and stores but no possible memory accesses by e.g.
209   // free, call, or invoke instructions.
210   if (!IsLoadOrStoreInst(P->A) || !IsLoadOrStoreInst(P->B)) {
211     DEBUG(dbgs() << "--> [?] no load/store\n");
212     return Unknown;
213   }
214
215   Value *aPtr = GetPointerOperand(P->A);
216   Value *bPtr = GetPointerOperand(P->B);
217
218   switch (UnderlyingObjectsAlias(AA, aPtr, bPtr)) {
219   case AliasAnalysis::MayAlias:
220     // We can not analyse objects if we do not know about their aliasing.
221     DEBUG(dbgs() << "---> [?] may alias\n");
222     return Unknown;
223
224   case AliasAnalysis::NoAlias:
225     // If the objects noalias, they are distinct, accesses are independent.
226     DEBUG(dbgs() << "---> [I] no alias\n");
227     return Independent;
228
229   case AliasAnalysis::MustAlias:
230     break; // The underlying objects alias, test accesses for dependence.
231   }
232
233   const GEPOperator *aGEP = dyn_cast<GEPOperator>(aPtr);
234   const GEPOperator *bGEP = dyn_cast<GEPOperator>(bPtr);
235
236   if (!aGEP || !bGEP)
237     return Unknown;
238
239   // FIXME: Is filtering coupled subscripts necessary?
240
241   // Collect GEP operand pairs (FIXME: use GetGEPOperands from BasicAA), adding
242   // trailing zeroes to the smaller GEP, if needed.
243   typedef SmallVector<std::pair<const SCEV*, const SCEV*>, 4> GEPOpdPairsTy;
244   GEPOpdPairsTy opds;
245   for(GEPOperator::const_op_iterator aIdx = aGEP->idx_begin(),
246                                      aEnd = aGEP->idx_end(),
247                                      bIdx = bGEP->idx_begin(),
248                                      bEnd = bGEP->idx_end();
249       aIdx != aEnd && bIdx != bEnd;
250       aIdx += (aIdx != aEnd), bIdx += (bIdx != bEnd)) {
251     const SCEV* aSCEV = (aIdx != aEnd) ? SE->getSCEV(*aIdx) : GetZeroSCEV(SE);
252     const SCEV* bSCEV = (bIdx != bEnd) ? SE->getSCEV(*bIdx) : GetZeroSCEV(SE);
253     opds.push_back(std::make_pair(aSCEV, bSCEV));
254   }
255
256   if (!opds.empty() && opds[0].first != opds[0].second) {
257     // We cannot (yet) handle arbitrary GEP pointer offsets. By limiting
258     //
259     // TODO: this could be relaxed by adding the size of the underlying object
260     // to the first subscript. If we have e.g. (GEP x,0,i; GEP x,2,-i) and we
261     // know that x is a [100 x i8]*, we could modify the first subscript to be
262     // (i, 200-i) instead of (i, -i).
263     return Unknown;
264   }
265
266   // Now analyse the collected operand pairs (skipping the GEP ptr offsets).
267   for (GEPOpdPairsTy::const_iterator i = opds.begin() + 1, end = opds.end();
268        i != end; ++i) {
269     Subscript subscript;
270     DependenceResult result = analyseSubscript(i->first, i->second, &subscript);
271     if (result != Dependent) {
272       // We either proved independence or failed to analyse this subscript.
273       // Further subscripts will not improve the situation, so abort early.
274       return result;
275     }
276     P->Subscripts.push_back(subscript);
277   }
278   // We successfully analysed all subscripts but failed to prove independence.
279   return Dependent;
280 }
281
282 bool LoopDependenceAnalysis::depends(Value *A, Value *B) {
283   assert(isDependencePair(A, B) && "Values form no dependence pair!");
284   ++NumAnswered;
285
286   DependencePair *p;
287   if (!findOrInsertDependencePair(A, B, p)) {
288     // The pair is not cached, so analyse it.
289     ++NumAnalysed;
290     switch (p->Result = analysePair(p)) {
291     case Dependent:   ++NumDependent;   break;
292     case Independent: ++NumIndependent; break;
293     case Unknown:     ++NumUnknown;     break;
294     }
295   }
296   return p->Result != Independent;
297 }
298
299 //===----------------------------------------------------------------------===//
300 //                   LoopDependenceAnalysis Implementation
301 //===----------------------------------------------------------------------===//
302
303 bool LoopDependenceAnalysis::runOnLoop(Loop *L, LPPassManager &) {
304   this->L = L;
305   AA = &getAnalysis<AliasAnalysis>();
306   SE = &getAnalysis<ScalarEvolution>();
307   return false;
308 }
309
310 void LoopDependenceAnalysis::releaseMemory() {
311   Pairs.clear();
312   PairAllocator.Reset();
313 }
314
315 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
316   AU.setPreservesAll();
317   AU.addRequiredTransitive<AliasAnalysis>();
318   AU.addRequiredTransitive<ScalarEvolution>();
319 }
320
321 static void PrintLoopInfo(raw_ostream &OS,
322                           LoopDependenceAnalysis *LDA, const Loop *L) {
323   if (!L->empty()) return; // ignore non-innermost loops
324
325   SmallVector<Instruction*, 8> memrefs;
326   GetMemRefInstrs(L, memrefs);
327
328   OS << "Loop at depth " << L->getLoopDepth() << ", header block: ";
329   WriteAsOperand(OS, L->getHeader(), false);
330   OS << "\n";
331
332   OS << "  Load/store instructions: " << memrefs.size() << "\n";
333   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
334        end = memrefs.end(); x != end; ++x)
335     OS << "\t" << (x - memrefs.begin()) << ": " << **x << "\n";
336
337   OS << "  Pairwise dependence results:\n";
338   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
339        end = memrefs.end(); x != end; ++x)
340     for (SmallVector<Instruction*, 8>::const_iterator y = x + 1;
341          y != end; ++y)
342       if (LDA->isDependencePair(*x, *y))
343         OS << "\t" << (x - memrefs.begin()) << "," << (y - memrefs.begin())
344            << ": " << (LDA->depends(*x, *y) ? "dependent" : "independent")
345            << "\n";
346 }
347
348 void LoopDependenceAnalysis::print(raw_ostream &OS, const Module*) const {
349   // TODO: doc why const_cast is safe
350   PrintLoopInfo(OS, const_cast<LoopDependenceAnalysis*>(this), this->L);
351 }