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 /// Add each synthetic statement in the CFG to the parent map, using the
161 /// source statement's parent.
162 static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
166 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
167 E = TheCFG->synthetic_stmt_end();
169 PM.setParent(I->first, PM.getParent(I->second));
173 CFG *AnalysisDeclContext::getCFG() {
174 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
175 return getUnoptimizedCFG();
178 cfg.reset(CFG::buildCFG(D, getBody(),
179 &D->getASTContext(), cfgBuildOptions));
180 // Even when the cfg is not successfully built, we don't
181 // want to try building it again.
185 addParentsForSyntheticStmts(cfg.get(), *PM);
190 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
191 if (!builtCompleteCFG) {
192 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
194 completeCFG.reset(CFG::buildCFG(D, getBody(), &D->getASTContext(),
196 // Even when the cfg is not successfully built, we don't
197 // want to try building it again.
198 builtCompleteCFG = true;
201 addParentsForSyntheticStmts(completeCFG.get(), *PM);
203 return completeCFG.get();
206 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
208 return cfgStmtMap.get();
210 if (CFG *c = getCFG()) {
211 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
212 return cfgStmtMap.get();
218 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
222 if (CFG *c = getCFG()) {
223 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
230 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
231 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
234 ParentMap &AnalysisDeclContext::getParentMap() {
236 PM.reset(new ParentMap(getBody()));
237 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
238 for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
241 PM->addStmt((*I)->getInit());
245 addParentsForSyntheticStmts(getCFG(), *PM);
246 if (builtCompleteCFG)
247 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
252 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
254 PCA.reset(new PseudoConstantAnalysis(getBody()));
258 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
259 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
260 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
261 // that has the body.
266 AnalysisDeclContext *&AC = Contexts[D];
268 AC = new AnalysisDeclContext(this, D, cfgBuildOptions);
272 const StackFrameContext *
273 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
274 const CFGBlock *Blk, unsigned Idx) {
275 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
278 const BlockInvocationContext *
279 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
280 const clang::BlockDecl *BD,
281 const void *ContextData) {
282 return getLocationContextManager().getBlockInvocationContext(this, parent,
286 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
288 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
289 return Manager->getLocationContextManager();
292 //===----------------------------------------------------------------------===//
293 // FoldingSet profiling.
294 //===----------------------------------------------------------------------===//
296 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
298 AnalysisDeclContext *ctx,
299 const LocationContext *parent,
303 ID.AddPointer(parent);
307 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
308 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
311 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
312 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
315 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
316 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
319 //===----------------------------------------------------------------------===//
320 // LocationContext creation.
321 //===----------------------------------------------------------------------===//
323 template <typename LOC, typename DATA>
325 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
326 const LocationContext *parent,
328 llvm::FoldingSetNodeID ID;
329 LOC::Profile(ID, ctx, parent, d);
332 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
335 L = new LOC(ctx, parent, d);
336 Contexts.InsertNode(L, InsertPos);
341 const StackFrameContext*
342 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
343 const LocationContext *parent,
345 const CFGBlock *blk, unsigned idx) {
346 llvm::FoldingSetNodeID ID;
347 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
349 StackFrameContext *L =
350 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
352 L = new StackFrameContext(ctx, parent, s, blk, idx);
353 Contexts.InsertNode(L, InsertPos);
359 LocationContextManager::getScope(AnalysisDeclContext *ctx,
360 const LocationContext *parent,
362 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
365 const BlockInvocationContext *
366 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
367 const LocationContext *parent,
369 const void *ContextData) {
370 llvm::FoldingSetNodeID ID;
371 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
373 BlockInvocationContext *L =
374 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
377 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
378 Contexts.InsertNode(L, InsertPos);
383 //===----------------------------------------------------------------------===//
384 // LocationContext methods.
385 //===----------------------------------------------------------------------===//
387 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
388 const LocationContext *LC = this;
390 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
392 LC = LC->getParent();
397 bool LocationContext::inTopFrame() const {
398 return getCurrentStackFrame()->inTopFrame();
401 bool LocationContext::isParentOf(const LocationContext *LC) const {
403 const LocationContext *Parent = LC->getParent();
413 void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const {
414 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
415 PrintingPolicy PP(Ctx.getLangOpts());
419 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
420 switch (LCtx->getKind()) {
422 OS << Indent << '#' << Frame++ << ' ';
423 cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP);
427 OS << Indent << " (scope)\n";
430 OS << Indent << " (block context: "
431 << cast<BlockInvocationContext>(LCtx)->getContextData()
438 void LocationContext::dumpStack() const {
439 dumpStack(llvm::errs());
442 //===----------------------------------------------------------------------===//
443 // Lazily generated map to query the external variables referenced by a Block.
444 //===----------------------------------------------------------------------===//
447 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
448 BumpVector<const VarDecl*> &BEVals;
449 BumpVectorContext &BC;
450 llvm::SmallPtrSet<const VarDecl*, 4> Visited;
451 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
453 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
454 BumpVectorContext &bc)
455 : BEVals(bevals), BC(bc) {}
457 bool IsTrackedDecl(const VarDecl *VD) {
458 const DeclContext *DC = VD->getDeclContext();
459 return IgnoredContexts.count(DC) == 0;
462 void VisitStmt(Stmt *S) {
463 for (Stmt::child_range I = S->children(); I; ++I)
464 if (Stmt *child = *I)
468 void VisitDeclRefExpr(DeclRefExpr *DR) {
469 // Non-local variables are also directly modified.
470 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
471 if (!VD->hasLocalStorage()) {
472 if (Visited.insert(VD))
473 BEVals.push_back(VD, BC);
478 void VisitBlockExpr(BlockExpr *BR) {
479 // Blocks containing blocks can transitively capture more variables.
480 IgnoredContexts.insert(BR->getBlockDecl());
481 Visit(BR->getBlockDecl()->getBody());
484 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
485 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
486 et = PE->semantics_end(); it != et; ++it) {
487 Expr *Semantic = *it;
488 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
489 Semantic = OVE->getSourceExpr();
494 } // end anonymous namespace
496 typedef BumpVector<const VarDecl*> DeclVec;
498 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
500 llvm::BumpPtrAllocator &A) {
502 return (DeclVec*) Vec;
504 BumpVectorContext BC(A);
505 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
506 new (BV) DeclVec(BC, 10);
508 // Go through the capture list.
509 for (BlockDecl::capture_const_iterator CI = BD->capture_begin(),
510 CE = BD->capture_end(); CI != CE; ++CI) {
511 BV->push_back(CI->getVariable(), BC);
514 // Find the referenced global/static variables.
515 FindBlockDeclRefExprsVals F(*BV, BC);
516 F.Visit(BD->getBody());
522 std::pair<AnalysisDeclContext::referenced_decls_iterator,
523 AnalysisDeclContext::referenced_decls_iterator>
524 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
525 if (!ReferencedBlockVars)
526 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
528 DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
529 return std::make_pair(V->begin(), V->end());
532 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
533 if (!ManagedAnalyses)
534 ManagedAnalyses = new ManagedAnalysisMap();
535 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
539 //===----------------------------------------------------------------------===//
541 //===----------------------------------------------------------------------===//
543 ManagedAnalysis::~ManagedAnalysis() {}
545 AnalysisDeclContext::~AnalysisDeclContext() {
546 delete forcedBlkExprs;
547 delete ReferencedBlockVars;
548 // Release the managed analyses.
549 if (ManagedAnalyses) {
550 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
551 for (ManagedAnalysisMap::iterator I = M->begin(), E = M->end(); I!=E; ++I)
557 AnalysisDeclContextManager::~AnalysisDeclContextManager() {
558 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
562 LocationContext::~LocationContext() {}
564 LocationContextManager::~LocationContextManager() {
568 void LocationContextManager::clear() {
569 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
570 E = Contexts.end(); I != E; ) {
571 LocationContext *LC = &*I;