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