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