Fixed some bugs.
[llvm/zpu.git] / lib / Analysis / LoopDependenceAnalysis.cpp
blob068b434a07f01997c4ef50dc4d1e253c99a55776
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.
13 // Please note that this is work in progress and the interface is subject to
14 // change.
16 // TODO: adapt as implementation progresses.
18 // TODO: document lingo (pair, subscript, index)
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "lda"
23 #include "llvm/ADT/DenseSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/LoopDependenceAnalysis.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Operator.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetData.h"
37 using namespace llvm;
39 STATISTIC(NumAnswered, "Number of dependence queries answered");
40 STATISTIC(NumAnalysed, "Number of distinct dependence pairs analysed");
41 STATISTIC(NumDependent, "Number of pairs with dependent accesses");
42 STATISTIC(NumIndependent, "Number of pairs with independent accesses");
43 STATISTIC(NumUnknown, "Number of pairs with unknown accesses");
45 LoopPass *llvm::createLoopDependenceAnalysisPass() {
46 return new LoopDependenceAnalysis();
49 INITIALIZE_PASS_BEGIN(LoopDependenceAnalysis, "lda",
50 "Loop Dependence Analysis", false, true)
51 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
52 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
53 INITIALIZE_PASS_END(LoopDependenceAnalysis, "lda",
54 "Loop Dependence Analysis", false, true)
55 char LoopDependenceAnalysis::ID = 0;
57 //===----------------------------------------------------------------------===//
58 // Utility Functions
59 //===----------------------------------------------------------------------===//
61 static inline bool IsMemRefInstr(const Value *V) {
62 const Instruction *I = dyn_cast<const Instruction>(V);
63 return I && (I->mayReadFromMemory() || I->mayWriteToMemory());
66 static void GetMemRefInstrs(const Loop *L,
67 SmallVectorImpl<Instruction*> &Memrefs) {
68 for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
69 b != be; ++b)
70 for (BasicBlock::iterator i = (*b)->begin(), ie = (*b)->end();
71 i != ie; ++i)
72 if (IsMemRefInstr(i))
73 Memrefs.push_back(i);
76 static bool IsLoadOrStoreInst(Value *I) {
77 return isa<LoadInst>(I) || isa<StoreInst>(I);
80 static Value *GetPointerOperand(Value *I) {
81 if (LoadInst *i = dyn_cast<LoadInst>(I))
82 return i->getPointerOperand();
83 if (StoreInst *i = dyn_cast<StoreInst>(I))
84 return i->getPointerOperand();
85 llvm_unreachable("Value is no load or store instruction!");
86 // Never reached.
87 return 0;
90 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
91 const Value *A,
92 const Value *B) {
93 const Value *aObj = A->getUnderlyingObject();
94 const Value *bObj = B->getUnderlyingObject();
95 return AA->alias(aObj, AA->getTypeStoreSize(aObj->getType()),
96 bObj, AA->getTypeStoreSize(bObj->getType()));
99 static inline const SCEV *GetZeroSCEV(ScalarEvolution *SE) {
100 return SE->getConstant(Type::getInt32Ty(SE->getContext()), 0L);
103 //===----------------------------------------------------------------------===//
104 // Dependence Testing
105 //===----------------------------------------------------------------------===//
107 bool LoopDependenceAnalysis::isDependencePair(const Value *A,
108 const Value *B) const {
109 return IsMemRefInstr(A) &&
110 IsMemRefInstr(B) &&
111 (cast<const Instruction>(A)->mayWriteToMemory() ||
112 cast<const Instruction>(B)->mayWriteToMemory());
115 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value *A,
116 Value *B,
117 DependencePair *&P) {
118 void *insertPos = 0;
119 FoldingSetNodeID id;
120 id.AddPointer(A);
121 id.AddPointer(B);
123 P = Pairs.FindNodeOrInsertPos(id, insertPos);
124 if (P) return true;
126 P = new (PairAllocator) DependencePair(id, A, B);
127 Pairs.InsertNode(P, insertPos);
128 return false;
131 void LoopDependenceAnalysis::getLoops(const SCEV *S,
132 DenseSet<const Loop*>* Loops) const {
133 // Refactor this into an SCEVVisitor, if efficiency becomes a concern.
134 for (const Loop *L = this->L; L != 0; L = L->getParentLoop())
135 if (!S->isLoopInvariant(L))
136 Loops->insert(L);
139 bool LoopDependenceAnalysis::isLoopInvariant(const SCEV *S) const {
140 DenseSet<const Loop*> loops;
141 getLoops(S, &loops);
142 return loops.empty();
145 bool LoopDependenceAnalysis::isAffine(const SCEV *S) const {
146 const SCEVAddRecExpr *rec = dyn_cast<SCEVAddRecExpr>(S);
147 return isLoopInvariant(S) || (rec && rec->isAffine());
150 bool LoopDependenceAnalysis::isZIVPair(const SCEV *A, const SCEV *B) const {
151 return isLoopInvariant(A) && isLoopInvariant(B);
154 bool LoopDependenceAnalysis::isSIVPair(const SCEV *A, const SCEV *B) const {
155 DenseSet<const Loop*> loops;
156 getLoops(A, &loops);
157 getLoops(B, &loops);
158 return loops.size() == 1;
161 LoopDependenceAnalysis::DependenceResult
162 LoopDependenceAnalysis::analyseZIV(const SCEV *A,
163 const SCEV *B,
164 Subscript *S) const {
165 assert(isZIVPair(A, B) && "Attempted to ZIV-test non-ZIV SCEVs!");
166 return A == B ? Dependent : Independent;
169 LoopDependenceAnalysis::DependenceResult
170 LoopDependenceAnalysis::analyseSIV(const SCEV *A,
171 const SCEV *B,
172 Subscript *S) const {
173 return Unknown; // TODO: Implement.
176 LoopDependenceAnalysis::DependenceResult
177 LoopDependenceAnalysis::analyseMIV(const SCEV *A,
178 const SCEV *B,
179 Subscript *S) const {
180 return Unknown; // TODO: Implement.
183 LoopDependenceAnalysis::DependenceResult
184 LoopDependenceAnalysis::analyseSubscript(const SCEV *A,
185 const SCEV *B,
186 Subscript *S) const {
187 DEBUG(dbgs() << " Testing subscript: " << *A << ", " << *B << "\n");
189 if (A == B) {
190 DEBUG(dbgs() << " -> [D] same SCEV\n");
191 return Dependent;
194 if (!isAffine(A) || !isAffine(B)) {
195 DEBUG(dbgs() << " -> [?] not affine\n");
196 return Unknown;
199 if (isZIVPair(A, B))
200 return analyseZIV(A, B, S);
202 if (isSIVPair(A, B))
203 return analyseSIV(A, B, S);
205 return analyseMIV(A, B, S);
208 LoopDependenceAnalysis::DependenceResult
209 LoopDependenceAnalysis::analysePair(DependencePair *P) const {
210 DEBUG(dbgs() << "Analysing:\n" << *P->A << "\n" << *P->B << "\n");
212 // We only analyse loads and stores but no possible memory accesses by e.g.
213 // free, call, or invoke instructions.
214 if (!IsLoadOrStoreInst(P->A) || !IsLoadOrStoreInst(P->B)) {
215 DEBUG(dbgs() << "--> [?] no load/store\n");
216 return Unknown;
219 Value *aPtr = GetPointerOperand(P->A);
220 Value *bPtr = GetPointerOperand(P->B);
222 switch (UnderlyingObjectsAlias(AA, aPtr, bPtr)) {
223 case AliasAnalysis::MayAlias:
224 // We can not analyse objects if we do not know about their aliasing.
225 DEBUG(dbgs() << "---> [?] may alias\n");
226 return Unknown;
228 case AliasAnalysis::NoAlias:
229 // If the objects noalias, they are distinct, accesses are independent.
230 DEBUG(dbgs() << "---> [I] no alias\n");
231 return Independent;
233 case AliasAnalysis::MustAlias:
234 break; // The underlying objects alias, test accesses for dependence.
237 const GEPOperator *aGEP = dyn_cast<GEPOperator>(aPtr);
238 const GEPOperator *bGEP = dyn_cast<GEPOperator>(bPtr);
240 if (!aGEP || !bGEP)
241 return Unknown;
243 // FIXME: Is filtering coupled subscripts necessary?
245 // Collect GEP operand pairs (FIXME: use GetGEPOperands from BasicAA), adding
246 // trailing zeroes to the smaller GEP, if needed.
247 typedef SmallVector<std::pair<const SCEV*, const SCEV*>, 4> GEPOpdPairsTy;
248 GEPOpdPairsTy opds;
249 for(GEPOperator::const_op_iterator aIdx = aGEP->idx_begin(),
250 aEnd = aGEP->idx_end(),
251 bIdx = bGEP->idx_begin(),
252 bEnd = bGEP->idx_end();
253 aIdx != aEnd && bIdx != bEnd;
254 aIdx += (aIdx != aEnd), bIdx += (bIdx != bEnd)) {
255 const SCEV* aSCEV = (aIdx != aEnd) ? SE->getSCEV(*aIdx) : GetZeroSCEV(SE);
256 const SCEV* bSCEV = (bIdx != bEnd) ? SE->getSCEV(*bIdx) : GetZeroSCEV(SE);
257 opds.push_back(std::make_pair(aSCEV, bSCEV));
260 if (!opds.empty() && opds[0].first != opds[0].second) {
261 // We cannot (yet) handle arbitrary GEP pointer offsets. By limiting
263 // TODO: this could be relaxed by adding the size of the underlying object
264 // to the first subscript. If we have e.g. (GEP x,0,i; GEP x,2,-i) and we
265 // know that x is a [100 x i8]*, we could modify the first subscript to be
266 // (i, 200-i) instead of (i, -i).
267 return Unknown;
270 // Now analyse the collected operand pairs (skipping the GEP ptr offsets).
271 for (GEPOpdPairsTy::const_iterator i = opds.begin() + 1, end = opds.end();
272 i != end; ++i) {
273 Subscript subscript;
274 DependenceResult result = analyseSubscript(i->first, i->second, &subscript);
275 if (result != Dependent) {
276 // We either proved independence or failed to analyse this subscript.
277 // Further subscripts will not improve the situation, so abort early.
278 return result;
280 P->Subscripts.push_back(subscript);
282 // We successfully analysed all subscripts but failed to prove independence.
283 return Dependent;
286 bool LoopDependenceAnalysis::depends(Value *A, Value *B) {
287 assert(isDependencePair(A, B) && "Values form no dependence pair!");
288 ++NumAnswered;
290 DependencePair *p;
291 if (!findOrInsertDependencePair(A, B, p)) {
292 // The pair is not cached, so analyse it.
293 ++NumAnalysed;
294 switch (p->Result = analysePair(p)) {
295 case Dependent: ++NumDependent; break;
296 case Independent: ++NumIndependent; break;
297 case Unknown: ++NumUnknown; break;
300 return p->Result != Independent;
303 //===----------------------------------------------------------------------===//
304 // LoopDependenceAnalysis Implementation
305 //===----------------------------------------------------------------------===//
307 bool LoopDependenceAnalysis::runOnLoop(Loop *L, LPPassManager &) {
308 this->L = L;
309 AA = &getAnalysis<AliasAnalysis>();
310 SE = &getAnalysis<ScalarEvolution>();
311 return false;
314 void LoopDependenceAnalysis::releaseMemory() {
315 Pairs.clear();
316 PairAllocator.Reset();
319 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
320 AU.setPreservesAll();
321 AU.addRequiredTransitive<AliasAnalysis>();
322 AU.addRequiredTransitive<ScalarEvolution>();
325 static void PrintLoopInfo(raw_ostream &OS,
326 LoopDependenceAnalysis *LDA, const Loop *L) {
327 if (!L->empty()) return; // ignore non-innermost loops
329 SmallVector<Instruction*, 8> memrefs;
330 GetMemRefInstrs(L, memrefs);
332 OS << "Loop at depth " << L->getLoopDepth() << ", header block: ";
333 WriteAsOperand(OS, L->getHeader(), false);
334 OS << "\n";
336 OS << " Load/store instructions: " << memrefs.size() << "\n";
337 for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
338 end = memrefs.end(); x != end; ++x)
339 OS << "\t" << (x - memrefs.begin()) << ": " << **x << "\n";
341 OS << " Pairwise dependence results:\n";
342 for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
343 end = memrefs.end(); x != end; ++x)
344 for (SmallVector<Instruction*, 8>::const_iterator y = x + 1;
345 y != end; ++y)
346 if (LDA->isDependencePair(*x, *y))
347 OS << "\t" << (x - memrefs.begin()) << "," << (y - memrefs.begin())
348 << ": " << (LDA->depends(*x, *y) ? "dependent" : "independent")
349 << "\n";
352 void LoopDependenceAnalysis::print(raw_ostream &OS, const Module*) const {
353 // TODO: doc why const_cast is safe
354 PrintLoopInfo(OS, const_cast<LoopDependenceAnalysis*>(this), this->L);