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