1 //===- LoopDependenceAnalysis.cpp - LDA Implementation ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
16 // TODO: adapt as implementation progresses.
18 // TODO: document lingo (pair, subscript, index)
20 //===----------------------------------------------------------------------===//
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/Instructions.h"
29 #include "llvm/Operator.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetData.h"
37 STATISTIC(NumAnswered, "Number of dependence queries answered");
38 STATISTIC(NumAnalysed, "Number of distinct dependence pairs analysed");
39 STATISTIC(NumDependent, "Number of pairs with dependent accesses");
40 STATISTIC(NumIndependent, "Number of pairs with independent accesses");
41 STATISTIC(NumUnknown, "Number of pairs with unknown accesses");
43 LoopPass *llvm::createLoopDependenceAnalysisPass() {
44 return new LoopDependenceAnalysis();
47 static RegisterPass<LoopDependenceAnalysis>
48 R("lda", "Loop Dependence Analysis", false, true);
49 char LoopDependenceAnalysis::ID = 0;
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 static inline bool IsMemRefInstr(const Value *V) {
56 const Instruction *I = dyn_cast<const Instruction>(V);
57 return I && (I->mayReadFromMemory() || I->mayWriteToMemory());
60 static void GetMemRefInstrs(const Loop *L,
61 SmallVectorImpl<Instruction*> &Memrefs) {
62 for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
64 for (BasicBlock::iterator i = (*b)->begin(), ie = (*b)->end();
70 static bool IsLoadOrStoreInst(Value *I) {
71 return isa<LoadInst>(I) || isa<StoreInst>(I);
74 static Value *GetPointerOperand(Value *I) {
75 if (LoadInst *i = dyn_cast<LoadInst>(I))
76 return i->getPointerOperand();
77 if (StoreInst *i = dyn_cast<StoreInst>(I))
78 return i->getPointerOperand();
79 llvm_unreachable("Value is no load or store instruction!");
84 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
87 const Value *aObj = A->getUnderlyingObject();
88 const Value *bObj = B->getUnderlyingObject();
89 return AA->alias(aObj, AA->getTypeStoreSize(aObj->getType()),
90 bObj, AA->getTypeStoreSize(bObj->getType()));
93 static inline const SCEV *GetZeroSCEV(ScalarEvolution *SE) {
94 return SE->getConstant(Type::Int32Ty, 0L);
97 //===----------------------------------------------------------------------===//
99 //===----------------------------------------------------------------------===//
101 bool LoopDependenceAnalysis::isDependencePair(const Value *A,
102 const Value *B) const {
103 return IsMemRefInstr(A) &&
105 (cast<const Instruction>(A)->mayWriteToMemory() ||
106 cast<const Instruction>(B)->mayWriteToMemory());
109 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value *A,
111 DependencePair *&P) {
117 P = Pairs.FindNodeOrInsertPos(id, insertPos);
120 P = PairAllocator.Allocate<DependencePair>();
121 new (P) DependencePair(id, A, B);
122 Pairs.InsertNode(P, insertPos);
126 LoopDependenceAnalysis::DependenceResult
127 LoopDependenceAnalysis::analyseSubscript(const SCEV *A,
129 Subscript *S) const {
130 return Unknown; // TODO: Implement.
133 LoopDependenceAnalysis::DependenceResult
134 LoopDependenceAnalysis::analysePair(DependencePair *P) const {
135 DEBUG(errs() << "Analysing:\n" << *P->A << "\n" << *P->B << "\n");
137 // We only analyse loads and stores but no possible memory accesses by e.g.
138 // free, call, or invoke instructions.
139 if (!IsLoadOrStoreInst(P->A) || !IsLoadOrStoreInst(P->B)) {
140 DEBUG(errs() << "--> [?] no load/store\n");
144 Value *aPtr = GetPointerOperand(P->A);
145 Value *bPtr = GetPointerOperand(P->B);
147 switch (UnderlyingObjectsAlias(AA, aPtr, bPtr)) {
148 case AliasAnalysis::MayAlias:
149 // We can not analyse objects if we do not know about their aliasing.
150 DEBUG(errs() << "---> [?] may alias\n");
153 case AliasAnalysis::NoAlias:
154 // If the objects noalias, they are distinct, accesses are independent.
155 DEBUG(errs() << "---> [I] no alias\n");
158 case AliasAnalysis::MustAlias:
159 break; // The underlying objects alias, test accesses for dependence.
162 const GEPOperator *aGEP = dyn_cast<GEPOperator>(aPtr);
163 const GEPOperator *bGEP = dyn_cast<GEPOperator>(bPtr);
168 // FIXME: Is filtering coupled subscripts necessary?
170 // Analyse indices pairwise (FIXME: use GetGEPOperands from BasicAA), adding
171 // trailing zeroes to the smaller GEP, if needed.
172 GEPOperator::const_op_iterator aIdx = aGEP->idx_begin(),
173 aEnd = aGEP->idx_end(),
174 bIdx = bGEP->idx_begin(),
175 bEnd = bGEP->idx_end();
176 while (aIdx != aEnd && bIdx != bEnd) {
177 const SCEV* aSCEV = (aIdx != aEnd) ? SE->getSCEV(*aIdx) : GetZeroSCEV(SE);
178 const SCEV* bSCEV = (bIdx != bEnd) ? SE->getSCEV(*bIdx) : GetZeroSCEV(SE);
180 DependenceResult result = analyseSubscript(aSCEV, bSCEV, &subscript);
181 if (result != Dependent) {
182 // We either proved independence or failed to analyse this subscript.
183 // Further subscripts will not improve the situation, so abort early.
186 P->Subscripts.push_back(subscript);
187 if (aIdx != aEnd) ++aIdx;
188 if (bIdx != bEnd) ++bIdx;
190 // Either there were no subscripts or all subscripts were analysed to be
191 // dependent; in both cases we know the accesses are dependent.
195 bool LoopDependenceAnalysis::depends(Value *A, Value *B) {
196 assert(isDependencePair(A, B) && "Values form no dependence pair!");
200 if (!findOrInsertDependencePair(A, B, p)) {
201 // The pair is not cached, so analyse it.
203 switch (p->Result = analysePair(p)) {
204 case Dependent: ++NumDependent; break;
205 case Independent: ++NumIndependent; break;
206 case Unknown: ++NumUnknown; break;
209 return p->Result != Independent;
212 //===----------------------------------------------------------------------===//
213 // LoopDependenceAnalysis Implementation
214 //===----------------------------------------------------------------------===//
216 bool LoopDependenceAnalysis::runOnLoop(Loop *L, LPPassManager &) {
218 AA = &getAnalysis<AliasAnalysis>();
219 SE = &getAnalysis<ScalarEvolution>();
223 void LoopDependenceAnalysis::releaseMemory() {
225 PairAllocator.Reset();
228 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
229 AU.setPreservesAll();
230 AU.addRequiredTransitive<AliasAnalysis>();
231 AU.addRequiredTransitive<ScalarEvolution>();
234 static void PrintLoopInfo(raw_ostream &OS,
235 LoopDependenceAnalysis *LDA, const Loop *L) {
236 if (!L->empty()) return; // ignore non-innermost loops
238 SmallVector<Instruction*, 8> memrefs;
239 GetMemRefInstrs(L, memrefs);
241 OS << "Loop at depth " << L->getLoopDepth() << ", header block: ";
242 WriteAsOperand(OS, L->getHeader(), false);
245 OS << " Load/store instructions: " << memrefs.size() << "\n";
246 for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
247 end = memrefs.end(); x != end; ++x)
248 OS << "\t" << (x - memrefs.begin()) << ": " << **x << "\n";
250 OS << " Pairwise dependence results:\n";
251 for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
252 end = memrefs.end(); x != end; ++x)
253 for (SmallVector<Instruction*, 8>::const_iterator y = x + 1;
255 if (LDA->isDependencePair(*x, *y))
256 OS << "\t" << (x - memrefs.begin()) << "," << (y - memrefs.begin())
257 << ": " << (LDA->depends(*x, *y) ? "dependent" : "independent")
261 void LoopDependenceAnalysis::print(raw_ostream &OS, const Module*) const {
262 // TODO: doc why const_cast is safe
263 PrintLoopInfo(OS, const_cast<LoopDependenceAnalysis*>(this), this->L);
266 void LoopDependenceAnalysis::print(std::ostream &OS, const Module *M) const {
267 raw_os_ostream os(OS);