97ac3886e2ced9fc133c82872eb43632f7d60a88
[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 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "lda"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/LoopDependenceAnalysis.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetData.h"
32 using namespace llvm;
33
34 STATISTIC(NumAnswered,    "Number of dependence queries answered");
35 STATISTIC(NumAnalysed,    "Number of distinct dependence pairs analysed");
36 STATISTIC(NumDependent,   "Number of pairs with dependent accesses");
37 STATISTIC(NumIndependent, "Number of pairs with independent accesses");
38 STATISTIC(NumUnknown,     "Number of pairs with unknown accesses");
39
40 LoopPass *llvm::createLoopDependenceAnalysisPass() {
41   return new LoopDependenceAnalysis();
42 }
43
44 static RegisterPass<LoopDependenceAnalysis>
45 R("lda", "Loop Dependence Analysis", false, true);
46 char LoopDependenceAnalysis::ID = 0;
47
48 //===----------------------------------------------------------------------===//
49 //                             Utility Functions
50 //===----------------------------------------------------------------------===//
51
52 static inline bool IsMemRefInstr(const Value *V) {
53   const Instruction *I = dyn_cast<const Instruction>(V);
54   return I && (I->mayReadFromMemory() || I->mayWriteToMemory());
55 }
56
57 static void GetMemRefInstrs(const Loop *L,
58                             SmallVectorImpl<Instruction*> &Memrefs) {
59   for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
60        b != be; ++b)
61     for (BasicBlock::iterator i = (*b)->begin(), ie = (*b)->end();
62          i != ie; ++i)
63       if (IsMemRefInstr(i))
64         Memrefs.push_back(i);
65 }
66
67 static bool IsLoadOrStoreInst(Value *I) {
68   return isa<LoadInst>(I) || isa<StoreInst>(I);
69 }
70
71 static Value *GetPointerOperand(Value *I) {
72   if (LoadInst *i = dyn_cast<LoadInst>(I))
73     return i->getPointerOperand();
74   if (StoreInst *i = dyn_cast<StoreInst>(I))
75     return i->getPointerOperand();
76   llvm_unreachable("Value is no load or store instruction!");
77   // Never reached.
78   return 0;
79 }
80
81 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
82                                                          const Value *A,
83                                                          const Value *B) {
84   const Value *aObj = A->getUnderlyingObject();
85   const Value *bObj = B->getUnderlyingObject();
86   return AA->alias(aObj, AA->getTypeStoreSize(aObj->getType()),
87                    bObj, AA->getTypeStoreSize(bObj->getType()));
88 }
89
90 //===----------------------------------------------------------------------===//
91 //                             Dependence Testing
92 //===----------------------------------------------------------------------===//
93
94 bool LoopDependenceAnalysis::isDependencePair(const Value *A,
95                                               const Value *B) const {
96   return IsMemRefInstr(A) &&
97          IsMemRefInstr(B) &&
98          (cast<const Instruction>(A)->mayWriteToMemory() ||
99           cast<const Instruction>(B)->mayWriteToMemory());
100 }
101
102 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value *A,
103                                                         Value *B,
104                                                         DependencePair *&P) {
105   void *insertPos = 0;
106   FoldingSetNodeID id;
107   id.AddPointer(A);
108   id.AddPointer(B);
109
110   P = Pairs.FindNodeOrInsertPos(id, insertPos);
111   if (P) return true;
112
113   P = PairAllocator.Allocate<DependencePair>();
114   new (P) DependencePair(id, A, B);
115   Pairs.InsertNode(P, insertPos);
116   return false;
117 }
118
119 void LoopDependenceAnalysis::analysePair(DependencePair *P) const {
120   DEBUG(errs() << "Analysing:\n" << *P->A << "\n" << *P->B << "\n");
121
122   // Our default answer: we don't know anything, i.e. we failed to analyse this
123   // pair to get a more specific answer (dependent, independent).
124   P->Result = Unknown;
125
126   // We only analyse loads and stores but no possible memory accesses by e.g.
127   // free, call, or invoke instructions.
128   if (!IsLoadOrStoreInst(P->A) || !IsLoadOrStoreInst(P->B)) {
129     DEBUG(errs() << "--> [?] no load/store\n");
130     return;
131   }
132
133   Value *aPtr = GetPointerOperand(P->A);
134   Value *bPtr = GetPointerOperand(P->B);
135
136   switch (UnderlyingObjectsAlias(AA, aPtr, bPtr)) {
137   case AliasAnalysis::MayAlias:
138     // We can not analyse objects if we do not know about their aliasing.
139     DEBUG(errs() << "---> [?] may alias\n");
140     return;
141
142   case AliasAnalysis::NoAlias:
143     // If the objects noalias, they are distinct, accesses are independent.
144     DEBUG(errs() << "---> [I] no alias\n");
145     P->Result = Independent;
146     return;
147
148   case AliasAnalysis::MustAlias:
149     break; // The underlying objects alias, test accesses for dependence.
150   }
151
152   DEBUG(errs() << "---> [?] cannot analyse\n");
153   return;
154 }
155
156 bool LoopDependenceAnalysis::depends(Value *A, Value *B) {
157   assert(isDependencePair(A, B) && "Values form no dependence pair!");
158   ++NumAnswered;
159
160   DependencePair *p;
161   if (!findOrInsertDependencePair(A, B, p)) {
162     // The pair is not cached, so analyse it.
163     ++NumAnalysed;
164     analysePair(p);
165     switch (p->Result) {
166     case Dependent:   ++NumDependent;   break;
167     case Independent: ++NumIndependent; break;
168     case Unknown:     ++NumUnknown;     break;
169     }
170   }
171   return p->Result != Independent;
172 }
173
174 //===----------------------------------------------------------------------===//
175 //                   LoopDependenceAnalysis Implementation
176 //===----------------------------------------------------------------------===//
177
178 bool LoopDependenceAnalysis::runOnLoop(Loop *L, LPPassManager &) {
179   this->L = L;
180   AA = &getAnalysis<AliasAnalysis>();
181   SE = &getAnalysis<ScalarEvolution>();
182   return false;
183 }
184
185 void LoopDependenceAnalysis::releaseMemory() {
186   Pairs.clear();
187   PairAllocator.Reset();
188 }
189
190 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
191   AU.setPreservesAll();
192   AU.addRequiredTransitive<AliasAnalysis>();
193   AU.addRequiredTransitive<ScalarEvolution>();
194 }
195
196 static void PrintLoopInfo(raw_ostream &OS,
197                           LoopDependenceAnalysis *LDA, const Loop *L) {
198   if (!L->empty()) return; // ignore non-innermost loops
199
200   SmallVector<Instruction*, 8> memrefs;
201   GetMemRefInstrs(L, memrefs);
202
203   OS << "Loop at depth " << L->getLoopDepth() << ", header block: ";
204   WriteAsOperand(OS, L->getHeader(), false);
205   OS << "\n";
206
207   OS << "  Load/store instructions: " << memrefs.size() << "\n";
208   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
209        end = memrefs.end(); x != end; ++x)
210     OS << "\t" << (x - memrefs.begin()) << ": " << **x << "\n";
211
212   OS << "  Pairwise dependence results:\n";
213   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
214        end = memrefs.end(); x != end; ++x)
215     for (SmallVector<Instruction*, 8>::const_iterator y = x + 1;
216          y != end; ++y)
217       if (LDA->isDependencePair(*x, *y))
218         OS << "\t" << (x - memrefs.begin()) << "," << (y - memrefs.begin())
219            << ": " << (LDA->depends(*x, *y) ? "dependent" : "independent")
220            << "\n";
221 }
222
223 void LoopDependenceAnalysis::print(raw_ostream &OS, const Module*) const {
224   // TODO: doc why const_cast is safe
225   PrintLoopInfo(OS, const_cast<LoopDependenceAnalysis*>(this), this->L);
226 }
227
228 void LoopDependenceAnalysis::print(std::ostream &OS, const Module *M) const {
229   raw_os_ostream os(OS);
230   print(os, M);
231 }