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/SaveAndRestore.h"
32 #include "llvm/Support/raw_ostream.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),
44 forcedBlkExprs(nullptr),
46 builtCompleteCFG(false),
47 ReferencedBlockVars(nullptr),
48 ManagedAnalyses(nullptr)
50 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
53 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
57 forcedBlkExprs(nullptr),
59 builtCompleteCFG(false),
60 ReferencedBlockVars(nullptr),
61 ManagedAnalyses(nullptr)
63 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
66 AnalysisDeclContextManager::AnalysisDeclContextManager(bool useUnoptimizedCFG,
67 bool addImplicitDtors,
69 bool addTemporaryDtors,
70 bool synthesizeBodies,
71 bool addStaticInitBranch,
72 bool addCXXNewAllocator,
73 CodeInjector *injector)
74 : Injector(injector), SynthesizeBodies(synthesizeBodies)
76 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
77 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
78 cfgBuildOptions.AddInitializers = addInitializers;
79 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
80 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
81 cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator;
84 void AnalysisDeclContextManager::clear() { Contexts.clear(); }
86 static BodyFarm &getBodyFarm(ASTContext &C, CodeInjector *injector = nullptr) {
87 static BodyFarm *BF = new BodyFarm(C, injector);
91 Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
92 IsAutosynthesized = false;
93 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
94 Stmt *Body = FD->getBody();
95 if (Manager && Manager->synthesizeBodies()) {
96 Stmt *SynthesizedBody =
97 getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(FD);
98 if (SynthesizedBody) {
99 Body = SynthesizedBody;
100 IsAutosynthesized = true;
105 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
106 Stmt *Body = MD->getBody();
107 if (Manager && Manager->synthesizeBodies()) {
108 Stmt *SynthesizedBody =
109 getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(MD);
110 if (SynthesizedBody) {
111 Body = SynthesizedBody;
112 IsAutosynthesized = true;
116 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
117 return BD->getBody();
118 else if (const FunctionTemplateDecl *FunTmpl
119 = dyn_cast_or_null<FunctionTemplateDecl>(D))
120 return FunTmpl->getTemplatedDecl()->getBody();
122 llvm_unreachable("unknown code decl");
125 Stmt *AnalysisDeclContext::getBody() const {
130 bool AnalysisDeclContext::isBodyAutosynthesized() const {
136 bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const {
138 Stmt *Body = getBody(Tmp);
139 return Tmp && Body->getLocStart().isValid();
142 /// Returns true if \param VD is an Objective-C implicit 'self' parameter.
143 static bool isSelfDecl(const VarDecl *VD) {
144 return isa<ImplicitParamDecl>(VD) && VD->getName() == "self";
147 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
148 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
149 return MD->getSelfDecl();
150 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
151 // See if 'self' was captured by the block.
152 for (const auto &I : BD->captures()) {
153 const VarDecl *VD = I.getVariable();
155 return dyn_cast<ImplicitParamDecl>(VD);
159 auto *CXXMethod = dyn_cast<CXXMethodDecl>(D);
163 const CXXRecordDecl *parent = CXXMethod->getParent();
164 if (!parent->isLambda())
167 for (const LambdaCapture &LC : parent->captures()) {
168 if (!LC.capturesVariable())
171 VarDecl *VD = LC.getCapturedVar();
173 return dyn_cast<ImplicitParamDecl>(VD);
179 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
181 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
182 // Default construct an entry for 'stmt'.
183 if (const Expr *e = dyn_cast<Expr>(stmt))
184 stmt = e->IgnoreParens();
185 (void) (*forcedBlkExprs)[stmt];
189 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
190 assert(forcedBlkExprs);
191 if (const Expr *e = dyn_cast<Expr>(stmt))
192 stmt = e->IgnoreParens();
193 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
194 forcedBlkExprs->find(stmt);
195 assert(itr != forcedBlkExprs->end());
199 /// Add each synthetic statement in the CFG to the parent map, using the
200 /// source statement's parent.
201 static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
205 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
206 E = TheCFG->synthetic_stmt_end();
208 PM.setParent(I->first, PM.getParent(I->second));
212 CFG *AnalysisDeclContext::getCFG() {
213 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
214 return getUnoptimizedCFG();
217 cfg = CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
218 // Even when the cfg is not successfully built, we don't
219 // want to try building it again.
223 addParentsForSyntheticStmts(cfg.get(), *PM);
225 // The Observer should only observe one build of the CFG.
226 getCFGBuildOptions().Observer = nullptr;
231 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
232 if (!builtCompleteCFG) {
233 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
236 CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
237 // Even when the cfg is not successfully built, we don't
238 // want to try building it again.
239 builtCompleteCFG = true;
242 addParentsForSyntheticStmts(completeCFG.get(), *PM);
244 // The Observer should only observe one build of the CFG.
245 getCFGBuildOptions().Observer = nullptr;
247 return completeCFG.get();
250 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
252 return cfgStmtMap.get();
254 if (CFG *c = getCFG()) {
255 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
256 return cfgStmtMap.get();
262 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
266 if (CFG *c = getCFG()) {
267 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
274 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
275 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
278 ParentMap &AnalysisDeclContext::getParentMap() {
280 PM.reset(new ParentMap(getBody()));
281 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
282 for (const auto *I : C->inits()) {
283 PM->addStmt(I->getInit());
287 addParentsForSyntheticStmts(getCFG(), *PM);
288 if (builtCompleteCFG)
289 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
294 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
296 PCA.reset(new PseudoConstantAnalysis(getBody()));
300 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
301 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
302 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
303 // that has the body.
308 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D];
310 AC = llvm::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions);
314 const StackFrameContext *
315 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
316 const CFGBlock *Blk, unsigned Idx) {
317 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
320 const BlockInvocationContext *
321 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
322 const clang::BlockDecl *BD,
323 const void *ContextData) {
324 return getLocationContextManager().getBlockInvocationContext(this, parent,
328 bool AnalysisDeclContext::isInStdNamespace(const Decl *D) {
329 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
330 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
334 while (const DeclContext *Parent = ND->getParent()) {
335 if (!isa<NamespaceDecl>(Parent))
337 ND = cast<NamespaceDecl>(Parent);
340 return ND->isStdNamespace();
343 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
345 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
346 return Manager->getLocationContextManager();
349 //===----------------------------------------------------------------------===//
350 // FoldingSet profiling.
351 //===----------------------------------------------------------------------===//
353 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
355 AnalysisDeclContext *ctx,
356 const LocationContext *parent,
360 ID.AddPointer(parent);
364 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
365 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
368 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
369 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
372 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
373 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
376 //===----------------------------------------------------------------------===//
377 // LocationContext creation.
378 //===----------------------------------------------------------------------===//
380 template <typename LOC, typename DATA>
382 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
383 const LocationContext *parent,
385 llvm::FoldingSetNodeID ID;
386 LOC::Profile(ID, ctx, parent, d);
389 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
392 L = new LOC(ctx, parent, d);
393 Contexts.InsertNode(L, InsertPos);
398 const StackFrameContext*
399 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
400 const LocationContext *parent,
402 const CFGBlock *blk, unsigned idx) {
403 llvm::FoldingSetNodeID ID;
404 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
406 StackFrameContext *L =
407 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
409 L = new StackFrameContext(ctx, parent, s, blk, idx);
410 Contexts.InsertNode(L, InsertPos);
416 LocationContextManager::getScope(AnalysisDeclContext *ctx,
417 const LocationContext *parent,
419 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
422 const BlockInvocationContext *
423 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
424 const LocationContext *parent,
426 const void *ContextData) {
427 llvm::FoldingSetNodeID ID;
428 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
430 BlockInvocationContext *L =
431 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
434 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
435 Contexts.InsertNode(L, InsertPos);
440 //===----------------------------------------------------------------------===//
441 // LocationContext methods.
442 //===----------------------------------------------------------------------===//
444 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
445 const LocationContext *LC = this;
447 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
449 LC = LC->getParent();
454 bool LocationContext::inTopFrame() const {
455 return getCurrentStackFrame()->inTopFrame();
458 bool LocationContext::isParentOf(const LocationContext *LC) const {
460 const LocationContext *Parent = LC->getParent();
470 void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const {
471 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
472 PrintingPolicy PP(Ctx.getLangOpts());
476 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
477 switch (LCtx->getKind()) {
479 OS << Indent << '#' << Frame++ << ' ';
480 cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP);
484 OS << Indent << " (scope)\n";
487 OS << Indent << " (block context: "
488 << cast<BlockInvocationContext>(LCtx)->getContextData()
495 LLVM_DUMP_METHOD void LocationContext::dumpStack() const {
496 dumpStack(llvm::errs());
499 //===----------------------------------------------------------------------===//
500 // Lazily generated map to query the external variables referenced by a Block.
501 //===----------------------------------------------------------------------===//
504 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
505 BumpVector<const VarDecl*> &BEVals;
506 BumpVectorContext &BC;
507 llvm::SmallPtrSet<const VarDecl*, 4> Visited;
508 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
510 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
511 BumpVectorContext &bc)
512 : BEVals(bevals), BC(bc) {}
514 void VisitStmt(Stmt *S) {
515 for (Stmt *Child : S->children())
520 void VisitDeclRefExpr(DeclRefExpr *DR) {
521 // Non-local variables are also directly modified.
522 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
523 if (!VD->hasLocalStorage()) {
524 if (Visited.insert(VD).second)
525 BEVals.push_back(VD, BC);
530 void VisitBlockExpr(BlockExpr *BR) {
531 // Blocks containing blocks can transitively capture more variables.
532 IgnoredContexts.insert(BR->getBlockDecl());
533 Visit(BR->getBlockDecl()->getBody());
536 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
537 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
538 et = PE->semantics_end(); it != et; ++it) {
539 Expr *Semantic = *it;
540 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
541 Semantic = OVE->getSourceExpr();
546 } // end anonymous namespace
548 typedef BumpVector<const VarDecl*> DeclVec;
550 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
552 llvm::BumpPtrAllocator &A) {
554 return (DeclVec*) Vec;
556 BumpVectorContext BC(A);
557 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
558 new (BV) DeclVec(BC, 10);
560 // Go through the capture list.
561 for (const auto &CI : BD->captures()) {
562 BV->push_back(CI.getVariable(), BC);
565 // Find the referenced global/static variables.
566 FindBlockDeclRefExprsVals F(*BV, BC);
567 F.Visit(BD->getBody());
573 llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
574 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
575 if (!ReferencedBlockVars)
576 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
579 LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
580 return llvm::make_range(V->begin(), V->end());
583 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
584 if (!ManagedAnalyses)
585 ManagedAnalyses = new ManagedAnalysisMap();
586 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
590 //===----------------------------------------------------------------------===//
592 //===----------------------------------------------------------------------===//
594 ManagedAnalysis::~ManagedAnalysis() {}
596 AnalysisDeclContext::~AnalysisDeclContext() {
597 delete forcedBlkExprs;
598 delete ReferencedBlockVars;
599 // Release the managed analyses.
600 if (ManagedAnalyses) {
601 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
602 llvm::DeleteContainerSeconds(*M);
607 AnalysisDeclContextManager::~AnalysisDeclContextManager() {}
609 LocationContext::~LocationContext() {}
611 LocationContextManager::~LocationContextManager() {
615 void LocationContextManager::clear() {
616 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
617 E = Contexts.end(); I != E; ) {
618 LocationContext *LC = &*I;