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/Analysis/AnalysisContext.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
24 #include "clang/Analysis/Analyses/LiveVariables.h"
25 #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
26 #include "clang/Analysis/CFG.h"
27 #include "clang/Analysis/CFGStmtMap.h"
28 #include "clang/Analysis/Support/BumpVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Support/SaveAndRestore.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 bool addStaticInitBranch)
72 : SynthesizeBodies(synthesizeBodies)
74 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
75 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
76 cfgBuildOptions.AddInitializers = addInitializers;
77 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
78 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
81 void AnalysisDeclContextManager::clear() {
82 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
87 static BodyFarm &getBodyFarm(ASTContext &C) {
88 static BodyFarm *BF = new BodyFarm(C);
92 Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
93 IsAutosynthesized = false;
94 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
95 Stmt *Body = FD->getBody();
96 if (!Body && Manager && Manager->synthesizeBodies()) {
97 IsAutosynthesized = true;
98 return getBodyFarm(getASTContext()).getBody(FD);
102 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
103 return MD->getBody();
104 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
105 return BD->getBody();
106 else if (const FunctionTemplateDecl *FunTmpl
107 = dyn_cast_or_null<FunctionTemplateDecl>(D))
108 return FunTmpl->getTemplatedDecl()->getBody();
110 llvm_unreachable("unknown code decl");
113 Stmt *AnalysisDeclContext::getBody() const {
118 bool AnalysisDeclContext::isBodyAutosynthesized() const {
124 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
125 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
126 return MD->getSelfDecl();
127 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
128 // See if 'self' was captured by the block.
129 for (BlockDecl::capture_const_iterator it = BD->capture_begin(),
130 et = BD->capture_end(); it != et; ++it) {
131 const VarDecl *VD = it->getVariable();
132 if (VD->getName() == "self")
133 return dyn_cast<ImplicitParamDecl>(VD);
140 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
142 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
143 // Default construct an entry for 'stmt'.
144 if (const Expr *e = dyn_cast<Expr>(stmt))
145 stmt = e->IgnoreParens();
146 (void) (*forcedBlkExprs)[stmt];
150 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
151 assert(forcedBlkExprs);
152 if (const Expr *e = dyn_cast<Expr>(stmt))
153 stmt = e->IgnoreParens();
154 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
155 forcedBlkExprs->find(stmt);
156 assert(itr != forcedBlkExprs->end());
160 CFG *AnalysisDeclContext::getCFG() {
161 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
162 return getUnoptimizedCFG();
165 cfg.reset(CFG::buildCFG(D, getBody(),
166 &D->getASTContext(), cfgBuildOptions));
167 // Even when the cfg is not successfully built, we don't
168 // want to try building it again.
174 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
175 if (!builtCompleteCFG) {
176 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
178 completeCFG.reset(CFG::buildCFG(D, getBody(), &D->getASTContext(),
180 // Even when the cfg is not successfully built, we don't
181 // want to try building it again.
182 builtCompleteCFG = true;
184 return completeCFG.get();
187 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
189 return cfgStmtMap.get();
191 if (CFG *c = getCFG()) {
192 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
193 return cfgStmtMap.get();
199 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
203 if (CFG *c = getCFG()) {
204 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
211 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
212 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
215 ParentMap &AnalysisDeclContext::getParentMap() {
217 PM.reset(new ParentMap(getBody()));
218 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
219 for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
222 PM->addStmt((*I)->getInit());
229 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
231 PCA.reset(new PseudoConstantAnalysis(getBody()));
235 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
236 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
237 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
238 // that has the body.
243 AnalysisDeclContext *&AC = Contexts[D];
245 AC = new AnalysisDeclContext(this, D, cfgBuildOptions);
249 const StackFrameContext *
250 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
251 const CFGBlock *Blk, unsigned Idx) {
252 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
255 const BlockInvocationContext *
256 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
257 const clang::BlockDecl *BD,
258 const void *ContextData) {
259 return getLocationContextManager().getBlockInvocationContext(this, parent,
263 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
265 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
266 return Manager->getLocationContextManager();
269 //===----------------------------------------------------------------------===//
270 // FoldingSet profiling.
271 //===----------------------------------------------------------------------===//
273 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
275 AnalysisDeclContext *ctx,
276 const LocationContext *parent,
280 ID.AddPointer(parent);
284 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
285 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
288 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
289 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
292 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
293 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
296 //===----------------------------------------------------------------------===//
297 // LocationContext creation.
298 //===----------------------------------------------------------------------===//
300 template <typename LOC, typename DATA>
302 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
303 const LocationContext *parent,
305 llvm::FoldingSetNodeID ID;
306 LOC::Profile(ID, ctx, parent, d);
309 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
312 L = new LOC(ctx, parent, d);
313 Contexts.InsertNode(L, InsertPos);
318 const StackFrameContext*
319 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
320 const LocationContext *parent,
322 const CFGBlock *blk, unsigned idx) {
323 llvm::FoldingSetNodeID ID;
324 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
326 StackFrameContext *L =
327 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
329 L = new StackFrameContext(ctx, parent, s, blk, idx);
330 Contexts.InsertNode(L, InsertPos);
336 LocationContextManager::getScope(AnalysisDeclContext *ctx,
337 const LocationContext *parent,
339 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
342 const BlockInvocationContext *
343 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
344 const LocationContext *parent,
346 const void *ContextData) {
347 llvm::FoldingSetNodeID ID;
348 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
350 BlockInvocationContext *L =
351 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
354 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
355 Contexts.InsertNode(L, InsertPos);
360 //===----------------------------------------------------------------------===//
361 // LocationContext methods.
362 //===----------------------------------------------------------------------===//
364 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
365 const LocationContext *LC = this;
367 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
369 LC = LC->getParent();
374 bool LocationContext::inTopFrame() const {
375 return getCurrentStackFrame()->inTopFrame();
378 bool LocationContext::isParentOf(const LocationContext *LC) const {
380 const LocationContext *Parent = LC->getParent();
390 void LocationContext::dumpStack() const {
391 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
392 PrintingPolicy PP(Ctx.getLangOpts());
396 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
397 switch (LCtx->getKind()) {
399 llvm::errs() << '#' << Frame++ << ' ';
400 cast<StackFrameContext>(LCtx)->getDecl()->print(llvm::errs(), PP);
401 llvm::errs() << '\n';
404 llvm::errs() << " (scope)\n";
407 llvm::errs() << " (block context: "
408 << cast<BlockInvocationContext>(LCtx)->getContextData()
415 //===----------------------------------------------------------------------===//
416 // Lazily generated map to query the external variables referenced by a Block.
417 //===----------------------------------------------------------------------===//
420 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
421 BumpVector<const VarDecl*> &BEVals;
422 BumpVectorContext &BC;
423 llvm::SmallPtrSet<const VarDecl*, 4> Visited;
424 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
426 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
427 BumpVectorContext &bc)
428 : BEVals(bevals), BC(bc) {}
430 bool IsTrackedDecl(const VarDecl *VD) {
431 const DeclContext *DC = VD->getDeclContext();
432 return IgnoredContexts.count(DC) == 0;
435 void VisitStmt(Stmt *S) {
436 for (Stmt::child_range I = S->children(); I; ++I)
437 if (Stmt *child = *I)
441 void VisitDeclRefExpr(DeclRefExpr *DR) {
442 // Non-local variables are also directly modified.
443 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
444 if (!VD->hasLocalStorage()) {
445 if (Visited.insert(VD))
446 BEVals.push_back(VD, BC);
451 void VisitBlockExpr(BlockExpr *BR) {
452 // Blocks containing blocks can transitively capture more variables.
453 IgnoredContexts.insert(BR->getBlockDecl());
454 Visit(BR->getBlockDecl()->getBody());
457 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
458 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
459 et = PE->semantics_end(); it != et; ++it) {
460 Expr *Semantic = *it;
461 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
462 Semantic = OVE->getSourceExpr();
467 } // end anonymous namespace
469 typedef BumpVector<const VarDecl*> DeclVec;
471 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
473 llvm::BumpPtrAllocator &A) {
475 return (DeclVec*) Vec;
477 BumpVectorContext BC(A);
478 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
479 new (BV) DeclVec(BC, 10);
481 // Go through the capture list.
482 for (BlockDecl::capture_const_iterator CI = BD->capture_begin(),
483 CE = BD->capture_end(); CI != CE; ++CI) {
484 BV->push_back(CI->getVariable(), BC);
487 // Find the referenced global/static variables.
488 FindBlockDeclRefExprsVals F(*BV, BC);
489 F.Visit(BD->getBody());
495 std::pair<AnalysisDeclContext::referenced_decls_iterator,
496 AnalysisDeclContext::referenced_decls_iterator>
497 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
498 if (!ReferencedBlockVars)
499 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
501 DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
502 return std::make_pair(V->begin(), V->end());
505 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
506 if (!ManagedAnalyses)
507 ManagedAnalyses = new ManagedAnalysisMap();
508 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
512 //===----------------------------------------------------------------------===//
514 //===----------------------------------------------------------------------===//
516 ManagedAnalysis::~ManagedAnalysis() {}
518 AnalysisDeclContext::~AnalysisDeclContext() {
519 delete forcedBlkExprs;
520 delete ReferencedBlockVars;
521 // Release the managed analyses.
522 if (ManagedAnalyses) {
523 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
524 for (ManagedAnalysisMap::iterator I = M->begin(), E = M->end(); I!=E; ++I)
530 AnalysisDeclContextManager::~AnalysisDeclContextManager() {
531 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
535 LocationContext::~LocationContext() {}
537 LocationContextManager::~LocationContextManager() {
541 void LocationContextManager::clear() {
542 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
543 E = Contexts.end(); I != E; ) {
544 LocationContext *LC = &*I;