1 //== AnalysisDeclContext.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 AnalysisDeclContext, a class that manages the analysis context
11 // data for path sensitive analysis.
13 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/ParentMap.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/Analysis/Analyses/LiveVariables.h"
22 #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
23 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
24 #include "clang/Analysis/AnalysisContext.h"
25 #include "clang/Analysis/CFG.h"
26 #include "clang/Analysis/CFGStmtMap.h"
27 #include "clang/Analysis/Support/BumpVector.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/ErrorHandling.h"
34 using namespace clang;
36 typedef llvm::DenseMap<const void *, ManagedAnalysis *> ManagedAnalysisMap;
38 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
40 const CFG::BuildOptions &buildOptions)
43 cfgBuildOptions(buildOptions),
46 builtCompleteCFG(false),
47 ReferencedBlockVars(0),
50 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
53 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
59 builtCompleteCFG(false),
60 ReferencedBlockVars(0),
63 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
66 AnalysisDeclContextManager::AnalysisDeclContextManager(bool useUnoptimizedCFG,
67 bool addImplicitDtors,
69 bool addTemporaryDtors,
70 bool synthesizeBodies)
71 : SynthesizeBodies(synthesizeBodies)
73 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
74 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
75 cfgBuildOptions.AddInitializers = addInitializers;
76 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
79 void AnalysisDeclContextManager::clear() {
80 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
85 static BodyFarm &getBodyFarm(ASTContext &C) {
86 static BodyFarm *BF = new BodyFarm(C);
90 Stmt *AnalysisDeclContext::getBody() const {
91 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
92 Stmt *Body = FD->getBody();
93 if (!Body && Manager && Manager->synthesizeBodies())
94 return getBodyFarm(getASTContext()).getBody(FD);
97 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
99 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
100 return BD->getBody();
101 else if (const FunctionTemplateDecl *FunTmpl
102 = dyn_cast_or_null<FunctionTemplateDecl>(D))
103 return FunTmpl->getTemplatedDecl()->getBody();
105 llvm_unreachable("unknown code decl");
108 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
109 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
110 return MD->getSelfDecl();
111 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
112 // See if 'self' was captured by the block.
113 for (BlockDecl::capture_const_iterator it = BD->capture_begin(),
114 et = BD->capture_end(); it != et; ++it) {
115 const VarDecl *VD = it->getVariable();
116 if (VD->getName() == "self")
117 return dyn_cast<ImplicitParamDecl>(VD);
124 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
126 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
127 // Default construct an entry for 'stmt'.
128 if (const Expr *e = dyn_cast<Expr>(stmt))
129 stmt = e->IgnoreParens();
130 (void) (*forcedBlkExprs)[stmt];
134 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
135 assert(forcedBlkExprs);
136 if (const Expr *e = dyn_cast<Expr>(stmt))
137 stmt = e->IgnoreParens();
138 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
139 forcedBlkExprs->find(stmt);
140 assert(itr != forcedBlkExprs->end());
144 CFG *AnalysisDeclContext::getCFG() {
145 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
146 return getUnoptimizedCFG();
149 cfg.reset(CFG::buildCFG(D, getBody(),
150 &D->getASTContext(), cfgBuildOptions));
151 // Even when the cfg is not successfully built, we don't
152 // want to try building it again.
158 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
159 if (!builtCompleteCFG) {
160 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
162 completeCFG.reset(CFG::buildCFG(D, getBody(), &D->getASTContext(),
164 // Even when the cfg is not successfully built, we don't
165 // want to try building it again.
166 builtCompleteCFG = true;
168 return completeCFG.get();
171 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
173 return cfgStmtMap.get();
175 if (CFG *c = getCFG()) {
176 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
177 return cfgStmtMap.get();
183 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
187 if (CFG *c = getCFG()) {
188 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
195 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
196 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
199 ParentMap &AnalysisDeclContext::getParentMap() {
201 PM.reset(new ParentMap(getBody()));
202 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
203 for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
206 PM->addStmt((*I)->getInit());
213 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
215 PCA.reset(new PseudoConstantAnalysis(getBody()));
219 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
220 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
221 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
222 // that has the body.
227 AnalysisDeclContext *&AC = Contexts[D];
229 AC = new AnalysisDeclContext(this, D, cfgBuildOptions);
233 const StackFrameContext *
234 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
235 const CFGBlock *Blk, unsigned Idx) {
236 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
239 const BlockInvocationContext *
240 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
241 const clang::BlockDecl *BD,
242 const void *ContextData) {
243 return getLocationContextManager().getBlockInvocationContext(this, parent,
247 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
249 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
250 return Manager->getLocationContextManager();
253 //===----------------------------------------------------------------------===//
254 // FoldingSet profiling.
255 //===----------------------------------------------------------------------===//
257 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
259 AnalysisDeclContext *ctx,
260 const LocationContext *parent,
264 ID.AddPointer(parent);
268 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
269 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
272 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
273 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
276 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
277 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
280 //===----------------------------------------------------------------------===//
281 // LocationContext creation.
282 //===----------------------------------------------------------------------===//
284 template <typename LOC, typename DATA>
286 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
287 const LocationContext *parent,
289 llvm::FoldingSetNodeID ID;
290 LOC::Profile(ID, ctx, parent, d);
293 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
296 L = new LOC(ctx, parent, d);
297 Contexts.InsertNode(L, InsertPos);
302 const StackFrameContext*
303 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
304 const LocationContext *parent,
306 const CFGBlock *blk, unsigned idx) {
307 llvm::FoldingSetNodeID ID;
308 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
310 StackFrameContext *L =
311 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
313 L = new StackFrameContext(ctx, parent, s, blk, idx);
314 Contexts.InsertNode(L, InsertPos);
320 LocationContextManager::getScope(AnalysisDeclContext *ctx,
321 const LocationContext *parent,
323 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
326 const BlockInvocationContext *
327 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
328 const LocationContext *parent,
330 const void *ContextData) {
331 llvm::FoldingSetNodeID ID;
332 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
334 BlockInvocationContext *L =
335 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
338 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
339 Contexts.InsertNode(L, InsertPos);
344 //===----------------------------------------------------------------------===//
345 // LocationContext methods.
346 //===----------------------------------------------------------------------===//
348 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
349 const LocationContext *LC = this;
351 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
353 LC = LC->getParent();
358 bool LocationContext::inTopFrame() const {
359 return getCurrentStackFrame()->inTopFrame();
362 bool LocationContext::isParentOf(const LocationContext *LC) const {
364 const LocationContext *Parent = LC->getParent();
374 //===----------------------------------------------------------------------===//
375 // Lazily generated map to query the external variables referenced by a Block.
376 //===----------------------------------------------------------------------===//
379 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
380 BumpVector<const VarDecl*> &BEVals;
381 BumpVectorContext &BC;
382 llvm::SmallPtrSet<const VarDecl*, 4> Visited;
383 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
385 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
386 BumpVectorContext &bc)
387 : BEVals(bevals), BC(bc) {}
389 bool IsTrackedDecl(const VarDecl *VD) {
390 const DeclContext *DC = VD->getDeclContext();
391 return IgnoredContexts.count(DC) == 0;
394 void VisitStmt(Stmt *S) {
395 for (Stmt::child_range I = S->children(); I; ++I)
396 if (Stmt *child = *I)
400 void VisitDeclRefExpr(DeclRefExpr *DR) {
401 // Non-local variables are also directly modified.
402 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
403 if (!VD->hasLocalStorage()) {
404 if (Visited.insert(VD))
405 BEVals.push_back(VD, BC);
406 } else if (DR->refersToEnclosingLocal()) {
407 if (Visited.insert(VD) && IsTrackedDecl(VD))
408 BEVals.push_back(VD, BC);
413 void VisitBlockExpr(BlockExpr *BR) {
414 // Blocks containing blocks can transitively capture more variables.
415 IgnoredContexts.insert(BR->getBlockDecl());
416 Visit(BR->getBlockDecl()->getBody());
419 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
420 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
421 et = PE->semantics_end(); it != et; ++it) {
422 Expr *Semantic = *it;
423 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
424 Semantic = OVE->getSourceExpr();
429 } // end anonymous namespace
431 typedef BumpVector<const VarDecl*> DeclVec;
433 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
435 llvm::BumpPtrAllocator &A) {
437 return (DeclVec*) Vec;
439 BumpVectorContext BC(A);
440 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
441 new (BV) DeclVec(BC, 10);
443 // Find the referenced variables.
444 FindBlockDeclRefExprsVals F(*BV, BC);
445 F.Visit(BD->getBody());
451 std::pair<AnalysisDeclContext::referenced_decls_iterator,
452 AnalysisDeclContext::referenced_decls_iterator>
453 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
454 if (!ReferencedBlockVars)
455 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
457 DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
458 return std::make_pair(V->begin(), V->end());
461 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
462 if (!ManagedAnalyses)
463 ManagedAnalyses = new ManagedAnalysisMap();
464 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
468 //===----------------------------------------------------------------------===//
470 //===----------------------------------------------------------------------===//
472 ManagedAnalysis::~ManagedAnalysis() {}
474 AnalysisDeclContext::~AnalysisDeclContext() {
475 delete forcedBlkExprs;
476 delete ReferencedBlockVars;
477 // Release the managed analyses.
478 if (ManagedAnalyses) {
479 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
480 for (ManagedAnalysisMap::iterator I = M->begin(), E = M->end(); I!=E; ++I)
486 AnalysisDeclContextManager::~AnalysisDeclContextManager() {
487 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
491 LocationContext::~LocationContext() {}
493 LocationContextManager::~LocationContextManager() {
497 void LocationContextManager::clear() {
498 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
499 E = Contexts.end(); I != E; ) {
500 LocationContext *LC = &*I;