1 //== AnalysisContext.cpp - Analysis context for Path Sens analysis -*- 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 file defines AnalysisContext, a class that manages the analysis context
11 // data for path sensitive analysis.
13 //===----------------------------------------------------------------------===//
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "clang/Analysis/Analyses/LiveVariables.h"
21 #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
22 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
23 #include "clang/Analysis/AnalysisContext.h"
24 #include "clang/Analysis/CFG.h"
25 #include "clang/Analysis/CFGStmtMap.h"
26 #include "clang/Analysis/Support/BumpVector.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/Support/ErrorHandling.h"
30 using namespace clang;
32 AnalysisContext::AnalysisContext(const Decl *d,
33 idx::TranslationUnit *tu,
34 bool useUnoptimizedCFG,
36 bool addImplicitDtors,
40 builtCFG(false), builtCompleteCFG(false),
41 useUnoptimizedCFG(useUnoptimizedCFG),
42 ReferencedBlockVars(0)
44 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
45 cfgBuildOptions.AddEHEdges = addehedges;
46 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
47 cfgBuildOptions.AddInitializers = addInitializers;
50 void AnalysisContextManager::clear() {
51 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
56 Stmt *AnalysisContext::getBody() {
57 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
59 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
61 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
63 else if (const FunctionTemplateDecl *FunTmpl
64 = dyn_cast_or_null<FunctionTemplateDecl>(D))
65 return FunTmpl->getTemplatedDecl()->getBody();
67 llvm_unreachable("unknown code decl");
70 const ImplicitParamDecl *AnalysisContext::getSelfDecl() const {
71 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
72 return MD->getSelfDecl();
77 void AnalysisContext::registerForcedBlockExpression(const Stmt *stmt) {
79 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
80 // Default construct an entry for 'stmt'.
81 if (const Expr *e = dyn_cast<Expr>(stmt))
82 stmt = e->IgnoreParens();
83 (void) (*forcedBlkExprs)[stmt];
87 AnalysisContext::getBlockForRegisteredExpression(const Stmt *stmt) {
88 assert(forcedBlkExprs);
89 if (const Expr *e = dyn_cast<Expr>(stmt))
90 stmt = e->IgnoreParens();
91 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
92 forcedBlkExprs->find(stmt);
93 assert(itr != forcedBlkExprs->end());
97 CFG *AnalysisContext::getCFG() {
98 if (useUnoptimizedCFG)
99 return getUnoptimizedCFG();
102 cfg.reset(CFG::buildCFG(D, getBody(),
103 &D->getASTContext(), cfgBuildOptions));
104 // Even when the cfg is not successfully built, we don't
105 // want to try building it again.
111 CFG *AnalysisContext::getUnoptimizedCFG() {
112 if (!builtCompleteCFG) {
113 CFG::BuildOptions B = cfgBuildOptions;
114 B.PruneTriviallyFalseEdges = false;
115 completeCFG.reset(CFG::buildCFG(D, getBody(), &D->getASTContext(), B));
116 // Even when the cfg is not successfully built, we don't
117 // want to try building it again.
118 builtCompleteCFG = true;
120 return completeCFG.get();
123 CFGStmtMap *AnalysisContext::getCFGStmtMap() {
125 return cfgStmtMap.get();
127 if (CFG *c = getCFG()) {
128 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
129 return cfgStmtMap.get();
135 CFGReverseBlockReachabilityAnalysis *AnalysisContext::getCFGReachablityAnalysis() {
139 if (CFG *c = getCFG()) {
140 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
147 void AnalysisContext::dumpCFG() {
148 getCFG()->dump(getASTContext().getLangOptions());
151 ParentMap &AnalysisContext::getParentMap() {
153 PM.reset(new ParentMap(getBody()));
157 PseudoConstantAnalysis *AnalysisContext::getPseudoConstantAnalysis() {
159 PCA.reset(new PseudoConstantAnalysis(getBody()));
163 LiveVariables *AnalysisContext::getLiveVariables() {
165 if (CFG *c = getCFG()) {
166 liveness.reset(new LiveVariables(*this));
167 liveness->runOnCFG(*c);
168 liveness->runOnAllBlocks(*c, 0, true);
172 return liveness.get();
175 LiveVariables *AnalysisContext::getRelaxedLiveVariables() {
176 if (!relaxedLiveness)
177 if (CFG *c = getCFG()) {
178 relaxedLiveness.reset(new LiveVariables(*this, false));
179 relaxedLiveness->runOnCFG(*c);
180 relaxedLiveness->runOnAllBlocks(*c, 0, true);
183 return relaxedLiveness.get();
186 AnalysisContext *AnalysisContextManager::getContext(const Decl *D,
187 idx::TranslationUnit *TU) {
188 AnalysisContext *&AC = Contexts[D];
190 AC = new AnalysisContext(D, TU, UseUnoptimizedCFG, false,
191 AddImplicitDtors, AddInitializers);
196 //===----------------------------------------------------------------------===//
197 // FoldingSet profiling.
198 //===----------------------------------------------------------------------===//
200 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
202 AnalysisContext *ctx,
203 const LocationContext *parent,
207 ID.AddPointer(parent);
211 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
212 Profile(ID, getAnalysisContext(), getParent(), CallSite, Block, Index);
215 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
216 Profile(ID, getAnalysisContext(), getParent(), Enter);
219 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
220 Profile(ID, getAnalysisContext(), getParent(), BD);
223 //===----------------------------------------------------------------------===//
224 // LocationContext creation.
225 //===----------------------------------------------------------------------===//
227 template <typename LOC, typename DATA>
229 LocationContextManager::getLocationContext(AnalysisContext *ctx,
230 const LocationContext *parent,
232 llvm::FoldingSetNodeID ID;
233 LOC::Profile(ID, ctx, parent, d);
236 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
239 L = new LOC(ctx, parent, d);
240 Contexts.InsertNode(L, InsertPos);
245 const StackFrameContext*
246 LocationContextManager::getStackFrame(AnalysisContext *ctx,
247 const LocationContext *parent,
249 const CFGBlock *blk, unsigned idx) {
250 llvm::FoldingSetNodeID ID;
251 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
253 StackFrameContext *L =
254 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
256 L = new StackFrameContext(ctx, parent, s, blk, idx);
257 Contexts.InsertNode(L, InsertPos);
263 LocationContextManager::getScope(AnalysisContext *ctx,
264 const LocationContext *parent,
266 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
269 //===----------------------------------------------------------------------===//
270 // LocationContext methods.
271 //===----------------------------------------------------------------------===//
273 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
274 const LocationContext *LC = this;
276 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
278 LC = LC->getParent();
283 const StackFrameContext *
284 LocationContext::getStackFrameForDeclContext(const DeclContext *DC) const {
285 const LocationContext *LC = this;
287 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) {
288 if (cast<DeclContext>(SFC->getDecl()) == DC)
291 LC = LC->getParent();
296 bool LocationContext::isParentOf(const LocationContext *LC) const {
298 const LocationContext *Parent = LC->getParent();
308 //===----------------------------------------------------------------------===//
309 // Lazily generated map to query the external variables referenced by a Block.
310 //===----------------------------------------------------------------------===//
313 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
314 BumpVector<const VarDecl*> &BEVals;
315 BumpVectorContext &BC;
316 llvm::DenseMap<const VarDecl*, unsigned> Visited;
317 llvm::SmallSet<const DeclContext*, 4> IgnoredContexts;
319 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
320 BumpVectorContext &bc)
321 : BEVals(bevals), BC(bc) {}
323 bool IsTrackedDecl(const VarDecl *VD) {
324 const DeclContext *DC = VD->getDeclContext();
325 return IgnoredContexts.count(DC) == 0;
328 void VisitStmt(Stmt *S) {
329 for (Stmt::child_range I = S->children(); I; ++I)
330 if (Stmt *child = *I)
334 void VisitDeclRefExpr(const DeclRefExpr *DR) {
335 // Non-local variables are also directly modified.
336 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
337 if (!VD->hasLocalStorage()) {
338 unsigned &flag = Visited[VD];
341 BEVals.push_back(VD, BC);
346 void VisitBlockDeclRefExpr(BlockDeclRefExpr *DR) {
347 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
348 unsigned &flag = Visited[VD];
351 if (IsTrackedDecl(VD))
352 BEVals.push_back(VD, BC);
357 void VisitBlockExpr(BlockExpr *BR) {
358 // Blocks containing blocks can transitively capture more variables.
359 IgnoredContexts.insert(BR->getBlockDecl());
360 Visit(BR->getBlockDecl()->getBody());
363 } // end anonymous namespace
365 typedef BumpVector<const VarDecl*> DeclVec;
367 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
369 llvm::BumpPtrAllocator &A) {
371 return (DeclVec*) Vec;
373 BumpVectorContext BC(A);
374 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
375 new (BV) DeclVec(BC, 10);
377 // Find the referenced variables.
378 FindBlockDeclRefExprsVals F(*BV, BC);
379 F.Visit(BD->getBody());
385 std::pair<AnalysisContext::referenced_decls_iterator,
386 AnalysisContext::referenced_decls_iterator>
387 AnalysisContext::getReferencedBlockVars(const BlockDecl *BD) {
388 if (!ReferencedBlockVars)
389 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
391 DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
392 return std::make_pair(V->begin(), V->end());
395 //===----------------------------------------------------------------------===//
397 //===----------------------------------------------------------------------===//
399 AnalysisContext::~AnalysisContext() {
400 delete forcedBlkExprs;
401 delete ReferencedBlockVars;
404 AnalysisContextManager::~AnalysisContextManager() {
405 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
409 LocationContext::~LocationContext() {}
411 LocationContextManager::~LocationContextManager() {
415 void LocationContextManager::clear() {
416 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
417 E = Contexts.end(); I != E; ) {
418 LocationContext *LC = &*I;