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