Make TargetData optional in MemoryDependenceAnalysis.
[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/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/LoopDependenceAnalysis.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Operator.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetData.h"
35 using namespace llvm;
36
37 STATISTIC(NumAnswered,    "Number of dependence queries answered");
38 STATISTIC(NumAnalysed,    "Number of distinct dependence pairs analysed");
39 STATISTIC(NumDependent,   "Number of pairs with dependent accesses");
40 STATISTIC(NumIndependent, "Number of pairs with independent accesses");
41 STATISTIC(NumUnknown,     "Number of pairs with unknown accesses");
42
43 LoopPass *llvm::createLoopDependenceAnalysisPass() {
44   return new LoopDependenceAnalysis();
45 }
46
47 static RegisterPass<LoopDependenceAnalysis>
48 R("lda", "Loop Dependence Analysis", false, true);
49 char LoopDependenceAnalysis::ID = 0;
50
51 //===----------------------------------------------------------------------===//
52 //                             Utility Functions
53 //===----------------------------------------------------------------------===//
54
55 static inline bool IsMemRefInstr(const Value *V) {
56   const Instruction *I = dyn_cast<const Instruction>(V);
57   return I && (I->mayReadFromMemory() || I->mayWriteToMemory());
58 }
59
60 static void GetMemRefInstrs(const Loop *L,
61                             SmallVectorImpl<Instruction*> &Memrefs) {
62   for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
63        b != be; ++b)
64     for (BasicBlock::iterator i = (*b)->begin(), ie = (*b)->end();
65          i != ie; ++i)
66       if (IsMemRefInstr(i))
67         Memrefs.push_back(i);
68 }
69
70 static bool IsLoadOrStoreInst(Value *I) {
71   return isa<LoadInst>(I) || isa<StoreInst>(I);
72 }
73
74 static Value *GetPointerOperand(Value *I) {
75   if (LoadInst *i = dyn_cast<LoadInst>(I))
76     return i->getPointerOperand();
77   if (StoreInst *i = dyn_cast<StoreInst>(I))
78     return i->getPointerOperand();
79   llvm_unreachable("Value is no load or store instruction!");
80   // Never reached.
81   return 0;
82 }
83
84 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
85                                                          const Value *A,
86                                                          const Value *B) {
87   const Value *aObj = A->getUnderlyingObject();
88   const Value *bObj = B->getUnderlyingObject();
89   return AA->alias(aObj, AA->getTypeStoreSize(aObj->getType()),
90                    bObj, AA->getTypeStoreSize(bObj->getType()));
91 }
92
93 static inline const SCEV *GetZeroSCEV(ScalarEvolution *SE) {
94   return SE->getConstant(Type::Int32Ty, 0L);
95 }
96
97 //===----------------------------------------------------------------------===//
98 //                             Dependence Testing
99 //===----------------------------------------------------------------------===//
100
101 bool LoopDependenceAnalysis::isDependencePair(const Value *A,
102                                               const Value *B) const {
103   return IsMemRefInstr(A) &&
104          IsMemRefInstr(B) &&
105          (cast<const Instruction>(A)->mayWriteToMemory() ||
106           cast<const Instruction>(B)->mayWriteToMemory());
107 }
108
109 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value *A,
110                                                         Value *B,
111                                                         DependencePair *&P) {
112   void *insertPos = 0;
113   FoldingSetNodeID id;
114   id.AddPointer(A);
115   id.AddPointer(B);
116
117   P = Pairs.FindNodeOrInsertPos(id, insertPos);
118   if (P) return true;
119
120   P = PairAllocator.Allocate<DependencePair>();
121   new (P) DependencePair(id, A, B);
122   Pairs.InsertNode(P, insertPos);
123   return false;
124 }
125
126 LoopDependenceAnalysis::DependenceResult
127 LoopDependenceAnalysis::analyseSubscript(const SCEV *A,
128                                          const SCEV *B,
129                                          Subscript *S) const {
130   DEBUG(errs() << "  Testing subscript: " << *A << ", " << *B << "\n");
131
132   if (A == B) {
133     DEBUG(errs() << "  -> [D] same SCEV\n");
134     return Dependent;
135   }
136
137   // TODO: Implement ZIV/SIV/MIV testers.
138
139   DEBUG(errs() << "  -> [?] cannot analyse subscript\n");
140   return Unknown;
141 }
142
143 LoopDependenceAnalysis::DependenceResult
144 LoopDependenceAnalysis::analysePair(DependencePair *P) const {
145   DEBUG(errs() << "Analysing:\n" << *P->A << "\n" << *P->B << "\n");
146
147   // We only analyse loads and stores but no possible memory accesses by e.g.
148   // free, call, or invoke instructions.
149   if (!IsLoadOrStoreInst(P->A) || !IsLoadOrStoreInst(P->B)) {
150     DEBUG(errs() << "--> [?] no load/store\n");
151     return Unknown;
152   }
153
154   Value *aPtr = GetPointerOperand(P->A);
155   Value *bPtr = GetPointerOperand(P->B);
156
157   switch (UnderlyingObjectsAlias(AA, aPtr, bPtr)) {
158   case AliasAnalysis::MayAlias:
159     // We can not analyse objects if we do not know about their aliasing.
160     DEBUG(errs() << "---> [?] may alias\n");
161     return Unknown;
162
163   case AliasAnalysis::NoAlias:
164     // If the objects noalias, they are distinct, accesses are independent.
165     DEBUG(errs() << "---> [I] no alias\n");
166     return Independent;
167
168   case AliasAnalysis::MustAlias:
169     break; // The underlying objects alias, test accesses for dependence.
170   }
171
172   const GEPOperator *aGEP = dyn_cast<GEPOperator>(aPtr);
173   const GEPOperator *bGEP = dyn_cast<GEPOperator>(bPtr);
174
175   if (!aGEP || !bGEP)
176     return Unknown;
177
178   // FIXME: Is filtering coupled subscripts necessary?
179
180   // Analyse indices pairwise (FIXME: use GetGEPOperands from BasicAA), adding
181   // trailing zeroes to the smaller GEP, if needed.
182   GEPOperator::const_op_iterator aIdx = aGEP->idx_begin(),
183                                  aEnd = aGEP->idx_end(),
184                                  bIdx = bGEP->idx_begin(),
185                                  bEnd = bGEP->idx_end();
186   while (aIdx != aEnd && bIdx != bEnd) {
187     const SCEV* aSCEV = (aIdx != aEnd) ? SE->getSCEV(*aIdx) : GetZeroSCEV(SE);
188     const SCEV* bSCEV = (bIdx != bEnd) ? SE->getSCEV(*bIdx) : GetZeroSCEV(SE);
189     Subscript subscript;
190     DependenceResult result = analyseSubscript(aSCEV, bSCEV, &subscript);
191     if (result != Dependent) {
192       // We either proved independence or failed to analyse this subscript.
193       // Further subscripts will not improve the situation, so abort early.
194       return result;
195     }
196     P->Subscripts.push_back(subscript);
197     if (aIdx != aEnd) ++aIdx;
198     if (bIdx != bEnd) ++bIdx;
199   }
200   // Either there were no subscripts or all subscripts were analysed to be
201   // dependent; in both cases we know the accesses are dependent.
202   return Dependent;
203 }
204
205 bool LoopDependenceAnalysis::depends(Value *A, Value *B) {
206   assert(isDependencePair(A, B) && "Values form no dependence pair!");
207   ++NumAnswered;
208
209   DependencePair *p;
210   if (!findOrInsertDependencePair(A, B, p)) {
211     // The pair is not cached, so analyse it.
212     ++NumAnalysed;
213     switch (p->Result = analysePair(p)) {
214     case Dependent:   ++NumDependent;   break;
215     case Independent: ++NumIndependent; break;
216     case Unknown:     ++NumUnknown;     break;
217     }
218   }
219   return p->Result != Independent;
220 }
221
222 //===----------------------------------------------------------------------===//
223 //                   LoopDependenceAnalysis Implementation
224 //===----------------------------------------------------------------------===//
225
226 bool LoopDependenceAnalysis::runOnLoop(Loop *L, LPPassManager &) {
227   this->L = L;
228   AA = &getAnalysis<AliasAnalysis>();
229   SE = &getAnalysis<ScalarEvolution>();
230   return false;
231 }
232
233 void LoopDependenceAnalysis::releaseMemory() {
234   Pairs.clear();
235   PairAllocator.Reset();
236 }
237
238 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
239   AU.setPreservesAll();
240   AU.addRequiredTransitive<AliasAnalysis>();
241   AU.addRequiredTransitive<ScalarEvolution>();
242 }
243
244 static void PrintLoopInfo(raw_ostream &OS,
245                           LoopDependenceAnalysis *LDA, const Loop *L) {
246   if (!L->empty()) return; // ignore non-innermost loops
247
248   SmallVector<Instruction*, 8> memrefs;
249   GetMemRefInstrs(L, memrefs);
250
251   OS << "Loop at depth " << L->getLoopDepth() << ", header block: ";
252   WriteAsOperand(OS, L->getHeader(), false);
253   OS << "\n";
254
255   OS << "  Load/store instructions: " << memrefs.size() << "\n";
256   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
257        end = memrefs.end(); x != end; ++x)
258     OS << "\t" << (x - memrefs.begin()) << ": " << **x << "\n";
259
260   OS << "  Pairwise dependence results:\n";
261   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
262        end = memrefs.end(); x != end; ++x)
263     for (SmallVector<Instruction*, 8>::const_iterator y = x + 1;
264          y != end; ++y)
265       if (LDA->isDependencePair(*x, *y))
266         OS << "\t" << (x - memrefs.begin()) << "," << (y - memrefs.begin())
267            << ": " << (LDA->depends(*x, *y) ? "dependent" : "independent")
268            << "\n";
269 }
270
271 void LoopDependenceAnalysis::print(raw_ostream &OS, const Module*) const {
272   // TODO: doc why const_cast is safe
273   PrintLoopInfo(OS, const_cast<LoopDependenceAnalysis*>(this), this->L);
274 }
275
276 void LoopDependenceAnalysis::print(std::ostream &OS, const Module *M) const {
277   raw_os_ostream os(OS);
278   print(os, M);
279 }