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/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Operator.h"
31 #include "llvm/Support/Allocator.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetData.h"
38 STATISTIC(NumAnswered
, "Number of dependence queries answered");
39 STATISTIC(NumAnalysed
, "Number of distinct dependence pairs analysed");
40 STATISTIC(NumDependent
, "Number of pairs with dependent accesses");
41 STATISTIC(NumIndependent
, "Number of pairs with independent accesses");
42 STATISTIC(NumUnknown
, "Number of pairs with unknown accesses");
44 LoopPass
*llvm::createLoopDependenceAnalysisPass() {
45 return new LoopDependenceAnalysis();
48 static RegisterPass
<LoopDependenceAnalysis
>
49 R("lda", "Loop Dependence Analysis", false, true);
50 char LoopDependenceAnalysis::ID
= 0;
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
56 static inline bool IsMemRefInstr(const Value
*V
) {
57 const Instruction
*I
= dyn_cast
<const Instruction
>(V
);
58 return I
&& (I
->mayReadFromMemory() || I
->mayWriteToMemory());
61 static void GetMemRefInstrs(const Loop
*L
,
62 SmallVectorImpl
<Instruction
*> &Memrefs
) {
63 for (Loop::block_iterator b
= L
->block_begin(), be
= L
->block_end();
65 for (BasicBlock::iterator i
= (*b
)->begin(), ie
= (*b
)->end();
71 static bool IsLoadOrStoreInst(Value
*I
) {
72 return isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
);
75 static Value
*GetPointerOperand(Value
*I
) {
76 if (LoadInst
*i
= dyn_cast
<LoadInst
>(I
))
77 return i
->getPointerOperand();
78 if (StoreInst
*i
= dyn_cast
<StoreInst
>(I
))
79 return i
->getPointerOperand();
80 llvm_unreachable("Value is no load or store instruction!");
85 static AliasAnalysis::AliasResult
UnderlyingObjectsAlias(AliasAnalysis
*AA
,
88 const Value
*aObj
= A
->getUnderlyingObject();
89 const Value
*bObj
= B
->getUnderlyingObject();
90 return AA
->alias(aObj
, AA
->getTypeStoreSize(aObj
->getType()),
91 bObj
, AA
->getTypeStoreSize(bObj
->getType()));
94 static inline const SCEV
*GetZeroSCEV(ScalarEvolution
*SE
) {
95 return SE
->getConstant(Type::Int32Ty
, 0L);
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
102 bool LoopDependenceAnalysis::isDependencePair(const Value
*A
,
103 const Value
*B
) const {
104 return IsMemRefInstr(A
) &&
106 (cast
<const Instruction
>(A
)->mayWriteToMemory() ||
107 cast
<const Instruction
>(B
)->mayWriteToMemory());
110 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value
*A
,
112 DependencePair
*&P
) {
118 P
= Pairs
.FindNodeOrInsertPos(id
, insertPos
);
121 P
= PairAllocator
.Allocate
<DependencePair
>();
122 new (P
) DependencePair(id
, A
, B
);
123 Pairs
.InsertNode(P
, insertPos
);
127 bool LoopDependenceAnalysis::isLoopInvariant(const SCEV
*S
) const {
128 for (const Loop
*L
= this->L
; L
!= 0; L
= L
->getParentLoop())
129 if (!S
->isLoopInvariant(L
))
134 bool LoopDependenceAnalysis::isAffine(const SCEV
*S
) const {
135 const SCEVAddRecExpr
*rec
= dyn_cast
<SCEVAddRecExpr
>(S
);
136 return isLoopInvariant(S
) || (rec
&& rec
->isAffine());
139 bool LoopDependenceAnalysis::isZIVPair(const SCEV
*A
, const SCEV
*B
) const {
140 return isLoopInvariant(A
) && isLoopInvariant(B
);
143 LoopDependenceAnalysis::DependenceResult
144 LoopDependenceAnalysis::analyseZIV(const SCEV
*A
,
146 Subscript
*S
) const {
147 assert(isZIVPair(A
, B
) && "Attempted to ZIV-test non-ZIV SCEVs!");
148 return A
== B
? Dependent
: Independent
;
151 LoopDependenceAnalysis::DependenceResult
152 LoopDependenceAnalysis::analyseSubscript(const SCEV
*A
,
154 Subscript
*S
) const {
155 DEBUG(errs() << " Testing subscript: " << *A
<< ", " << *B
<< "\n");
158 DEBUG(errs() << " -> [D] same SCEV\n");
162 if (!isAffine(A
) || !isAffine(B
)) {
163 DEBUG(errs() << " -> [?] not affine\n");
168 return analyseZIV(A
, B
, S
);
170 // TODO: Implement SIV/MIV testers.
172 DEBUG(errs() << " -> [?] cannot analyse subscript\n");
176 LoopDependenceAnalysis::DependenceResult
177 LoopDependenceAnalysis::analysePair(DependencePair
*P
) const {
178 DEBUG(errs() << "Analysing:\n" << *P
->A
<< "\n" << *P
->B
<< "\n");
180 // We only analyse loads and stores but no possible memory accesses by e.g.
181 // free, call, or invoke instructions.
182 if (!IsLoadOrStoreInst(P
->A
) || !IsLoadOrStoreInst(P
->B
)) {
183 DEBUG(errs() << "--> [?] no load/store\n");
187 Value
*aPtr
= GetPointerOperand(P
->A
);
188 Value
*bPtr
= GetPointerOperand(P
->B
);
190 switch (UnderlyingObjectsAlias(AA
, aPtr
, bPtr
)) {
191 case AliasAnalysis::MayAlias
:
192 // We can not analyse objects if we do not know about their aliasing.
193 DEBUG(errs() << "---> [?] may alias\n");
196 case AliasAnalysis::NoAlias
:
197 // If the objects noalias, they are distinct, accesses are independent.
198 DEBUG(errs() << "---> [I] no alias\n");
201 case AliasAnalysis::MustAlias
:
202 break; // The underlying objects alias, test accesses for dependence.
205 const GEPOperator
*aGEP
= dyn_cast
<GEPOperator
>(aPtr
);
206 const GEPOperator
*bGEP
= dyn_cast
<GEPOperator
>(bPtr
);
211 // FIXME: Is filtering coupled subscripts necessary?
213 // Collect GEP operand pairs (FIXME: use GetGEPOperands from BasicAA), adding
214 // trailing zeroes to the smaller GEP, if needed.
215 typedef SmallVector
<std::pair
<const SCEV
*, const SCEV
*>, 4> GEPOpdPairsTy
;
217 for(GEPOperator::const_op_iterator aIdx
= aGEP
->idx_begin(),
218 aEnd
= aGEP
->idx_end(),
219 bIdx
= bGEP
->idx_begin(),
220 bEnd
= bGEP
->idx_end();
221 aIdx
!= aEnd
&& bIdx
!= bEnd
;
222 aIdx
+= (aIdx
!= aEnd
), bIdx
+= (bIdx
!= bEnd
)) {
223 const SCEV
* aSCEV
= (aIdx
!= aEnd
) ? SE
->getSCEV(*aIdx
) : GetZeroSCEV(SE
);
224 const SCEV
* bSCEV
= (bIdx
!= bEnd
) ? SE
->getSCEV(*bIdx
) : GetZeroSCEV(SE
);
225 opds
.push_back(std::make_pair(aSCEV
, bSCEV
));
228 if (!opds
.empty() && opds
[0].first
!= opds
[0].second
) {
229 // We cannot (yet) handle arbitrary GEP pointer offsets. By limiting
231 // TODO: this could be relaxed by adding the size of the underlying object
232 // to the first subscript. If we have e.g. (GEP x,0,i; GEP x,2,-i) and we
233 // know that x is a [100 x i8]*, we could modify the first subscript to be
234 // (i, 200-i) instead of (i, -i).
238 // Now analyse the collected operand pairs (skipping the GEP ptr offsets).
239 for (GEPOpdPairsTy::const_iterator i
= opds
.begin() + 1, end
= opds
.end();
242 DependenceResult result
= analyseSubscript(i
->first
, i
->second
, &subscript
);
243 if (result
!= Dependent
) {
244 // We either proved independence or failed to analyse this subscript.
245 // Further subscripts will not improve the situation, so abort early.
248 P
->Subscripts
.push_back(subscript
);
250 // We successfully analysed all subscripts but failed to prove independence.
254 bool LoopDependenceAnalysis::depends(Value
*A
, Value
*B
) {
255 assert(isDependencePair(A
, B
) && "Values form no dependence pair!");
259 if (!findOrInsertDependencePair(A
, B
, p
)) {
260 // The pair is not cached, so analyse it.
262 switch (p
->Result
= analysePair(p
)) {
263 case Dependent
: ++NumDependent
; break;
264 case Independent
: ++NumIndependent
; break;
265 case Unknown
: ++NumUnknown
; break;
268 return p
->Result
!= Independent
;
271 //===----------------------------------------------------------------------===//
272 // LoopDependenceAnalysis Implementation
273 //===----------------------------------------------------------------------===//
275 bool LoopDependenceAnalysis::runOnLoop(Loop
*L
, LPPassManager
&) {
277 AA
= &getAnalysis
<AliasAnalysis
>();
278 SE
= &getAnalysis
<ScalarEvolution
>();
282 void LoopDependenceAnalysis::releaseMemory() {
284 PairAllocator
.Reset();
287 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage
&AU
) const {
288 AU
.setPreservesAll();
289 AU
.addRequiredTransitive
<AliasAnalysis
>();
290 AU
.addRequiredTransitive
<ScalarEvolution
>();
293 static void PrintLoopInfo(raw_ostream
&OS
,
294 LoopDependenceAnalysis
*LDA
, const Loop
*L
) {
295 if (!L
->empty()) return; // ignore non-innermost loops
297 SmallVector
<Instruction
*, 8> memrefs
;
298 GetMemRefInstrs(L
, memrefs
);
300 OS
<< "Loop at depth " << L
->getLoopDepth() << ", header block: ";
301 WriteAsOperand(OS
, L
->getHeader(), false);
304 OS
<< " Load/store instructions: " << memrefs
.size() << "\n";
305 for (SmallVector
<Instruction
*, 8>::const_iterator x
= memrefs
.begin(),
306 end
= memrefs
.end(); x
!= end
; ++x
)
307 OS
<< "\t" << (x
- memrefs
.begin()) << ": " << **x
<< "\n";
309 OS
<< " Pairwise dependence results:\n";
310 for (SmallVector
<Instruction
*, 8>::const_iterator x
= memrefs
.begin(),
311 end
= memrefs
.end(); x
!= end
; ++x
)
312 for (SmallVector
<Instruction
*, 8>::const_iterator y
= x
+ 1;
314 if (LDA
->isDependencePair(*x
, *y
))
315 OS
<< "\t" << (x
- memrefs
.begin()) << "," << (y
- memrefs
.begin())
316 << ": " << (LDA
->depends(*x
, *y
) ? "dependent" : "independent")
320 void LoopDependenceAnalysis::print(raw_ostream
&OS
, const Module
*) const {
321 // TODO: doc why const_cast is safe
322 PrintLoopInfo(OS
, const_cast<LoopDependenceAnalysis
*>(this), this->L
);
325 void LoopDependenceAnalysis::print(std::ostream
&OS
, const Module
*M
) const {
326 raw_os_ostream
os(OS
);