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/AnalysisDeclContext.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/ParentMap.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
23 #include "clang/Analysis/Analyses/LiveVariables.h"
24 #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
25 #include "clang/Analysis/BodyFarm.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(
67 ASTContext &ASTCtx, bool useUnoptimizedCFG, bool addImplicitDtors,
68 bool addInitializers, bool addTemporaryDtors, bool addLifetime,
69 bool addLoopExit, bool synthesizeBodies, bool addStaticInitBranch,
70 bool addCXXNewAllocator, CodeInjector *injector)
71 : Injector(injector), FunctionBodyFarm(ASTCtx, injector),
72 SynthesizeBodies(synthesizeBodies) {
73 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
74 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
75 cfgBuildOptions.AddInitializers = addInitializers;
76 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
77 cfgBuildOptions.AddLifetime = addLifetime;
78 cfgBuildOptions.AddLoopExit = addLoopExit;
79 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
80 cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator;
83 void AnalysisDeclContextManager::clear() { Contexts.clear(); }
85 Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
86 IsAutosynthesized = false;
87 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
88 Stmt *Body = FD->getBody();
89 if (auto *CoroBody = dyn_cast_or_null<CoroutineBodyStmt>(Body))
90 Body = CoroBody->getBody();
91 if (Manager && Manager->synthesizeBodies()) {
92 Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(FD);
93 if (SynthesizedBody) {
94 Body = SynthesizedBody;
95 IsAutosynthesized = true;
100 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
101 Stmt *Body = MD->getBody();
102 if (Manager && Manager->synthesizeBodies()) {
103 Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(MD);
104 if (SynthesizedBody) {
105 Body = SynthesizedBody;
106 IsAutosynthesized = true;
110 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
111 return BD->getBody();
112 else if (const FunctionTemplateDecl *FunTmpl
113 = dyn_cast_or_null<FunctionTemplateDecl>(D))
114 return FunTmpl->getTemplatedDecl()->getBody();
116 llvm_unreachable("unknown code decl");
119 Stmt *AnalysisDeclContext::getBody() const {
124 bool AnalysisDeclContext::isBodyAutosynthesized() const {
130 bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const {
132 Stmt *Body = getBody(Tmp);
133 return Tmp && Body->getLocStart().isValid();
136 /// Returns true if \param VD is an Objective-C implicit 'self' parameter.
137 static bool isSelfDecl(const VarDecl *VD) {
138 return isa<ImplicitParamDecl>(VD) && VD->getName() == "self";
141 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
142 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
143 return MD->getSelfDecl();
144 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
145 // See if 'self' was captured by the block.
146 for (const auto &I : BD->captures()) {
147 const VarDecl *VD = I.getVariable();
149 return dyn_cast<ImplicitParamDecl>(VD);
153 auto *CXXMethod = dyn_cast<CXXMethodDecl>(D);
157 const CXXRecordDecl *parent = CXXMethod->getParent();
158 if (!parent->isLambda())
161 for (const LambdaCapture &LC : parent->captures()) {
162 if (!LC.capturesVariable())
165 VarDecl *VD = LC.getCapturedVar();
167 return dyn_cast<ImplicitParamDecl>(VD);
173 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
175 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
176 // Default construct an entry for 'stmt'.
177 if (const Expr *e = dyn_cast<Expr>(stmt))
178 stmt = e->IgnoreParens();
179 (void) (*forcedBlkExprs)[stmt];
183 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
184 assert(forcedBlkExprs);
185 if (const Expr *e = dyn_cast<Expr>(stmt))
186 stmt = e->IgnoreParens();
187 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
188 forcedBlkExprs->find(stmt);
189 assert(itr != forcedBlkExprs->end());
193 /// Add each synthetic statement in the CFG to the parent map, using the
194 /// source statement's parent.
195 static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
199 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
200 E = TheCFG->synthetic_stmt_end();
202 PM.setParent(I->first, PM.getParent(I->second));
206 CFG *AnalysisDeclContext::getCFG() {
207 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
208 return getUnoptimizedCFG();
211 cfg = CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
212 // Even when the cfg is not successfully built, we don't
213 // want to try building it again.
217 addParentsForSyntheticStmts(cfg.get(), *PM);
219 // The Observer should only observe one build of the CFG.
220 getCFGBuildOptions().Observer = nullptr;
225 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
226 if (!builtCompleteCFG) {
227 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
230 CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
231 // Even when the cfg is not successfully built, we don't
232 // want to try building it again.
233 builtCompleteCFG = true;
236 addParentsForSyntheticStmts(completeCFG.get(), *PM);
238 // The Observer should only observe one build of the CFG.
239 getCFGBuildOptions().Observer = nullptr;
241 return completeCFG.get();
244 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
246 return cfgStmtMap.get();
248 if (CFG *c = getCFG()) {
249 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
250 return cfgStmtMap.get();
256 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
260 if (CFG *c = getCFG()) {
261 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
268 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
269 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
272 ParentMap &AnalysisDeclContext::getParentMap() {
274 PM.reset(new ParentMap(getBody()));
275 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
276 for (const auto *I : C->inits()) {
277 PM->addStmt(I->getInit());
281 addParentsForSyntheticStmts(getCFG(), *PM);
282 if (builtCompleteCFG)
283 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
288 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
290 PCA.reset(new PseudoConstantAnalysis(getBody()));
294 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
295 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
296 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
297 // that has the body.
302 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D];
304 AC = llvm::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions);
308 BodyFarm &AnalysisDeclContextManager::getBodyFarm() { return FunctionBodyFarm; }
310 const StackFrameContext *
311 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
312 const CFGBlock *Blk, unsigned Idx) {
313 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
316 const BlockInvocationContext *
317 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
318 const clang::BlockDecl *BD,
319 const void *ContextData) {
320 return getLocationContextManager().getBlockInvocationContext(this, parent,
324 bool AnalysisDeclContext::isInStdNamespace(const Decl *D) {
325 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
326 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
330 while (const DeclContext *Parent = ND->getParent()) {
331 if (!isa<NamespaceDecl>(Parent))
333 ND = cast<NamespaceDecl>(Parent);
336 return ND->isStdNamespace();
339 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
341 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
342 return Manager->getLocationContextManager();
345 //===----------------------------------------------------------------------===//
346 // FoldingSet profiling.
347 //===----------------------------------------------------------------------===//
349 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
351 AnalysisDeclContext *ctx,
352 const LocationContext *parent,
356 ID.AddPointer(parent);
360 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
361 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
364 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
365 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
368 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
369 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
372 //===----------------------------------------------------------------------===//
373 // LocationContext creation.
374 //===----------------------------------------------------------------------===//
376 template <typename LOC, typename DATA>
378 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
379 const LocationContext *parent,
381 llvm::FoldingSetNodeID ID;
382 LOC::Profile(ID, ctx, parent, d);
385 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
388 L = new LOC(ctx, parent, d);
389 Contexts.InsertNode(L, InsertPos);
394 const StackFrameContext*
395 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
396 const LocationContext *parent,
398 const CFGBlock *blk, unsigned idx) {
399 llvm::FoldingSetNodeID ID;
400 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
402 StackFrameContext *L =
403 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
405 L = new StackFrameContext(ctx, parent, s, blk, idx);
406 Contexts.InsertNode(L, InsertPos);
412 LocationContextManager::getScope(AnalysisDeclContext *ctx,
413 const LocationContext *parent,
415 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
418 const BlockInvocationContext *
419 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
420 const LocationContext *parent,
422 const void *ContextData) {
423 llvm::FoldingSetNodeID ID;
424 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
426 BlockInvocationContext *L =
427 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
430 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
431 Contexts.InsertNode(L, InsertPos);
436 //===----------------------------------------------------------------------===//
437 // LocationContext methods.
438 //===----------------------------------------------------------------------===//
440 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
441 const LocationContext *LC = this;
443 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
445 LC = LC->getParent();
450 bool LocationContext::inTopFrame() const {
451 return getCurrentStackFrame()->inTopFrame();
454 bool LocationContext::isParentOf(const LocationContext *LC) const {
456 const LocationContext *Parent = LC->getParent();
466 void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const {
467 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
468 PrintingPolicy PP(Ctx.getLangOpts());
472 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
473 switch (LCtx->getKind()) {
475 OS << Indent << '#' << Frame++ << ' ';
476 cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP);
480 OS << Indent << " (scope)\n";
483 OS << Indent << " (block context: "
484 << cast<BlockInvocationContext>(LCtx)->getContextData()
491 LLVM_DUMP_METHOD void LocationContext::dumpStack() const {
492 dumpStack(llvm::errs());
495 //===----------------------------------------------------------------------===//
496 // Lazily generated map to query the external variables referenced by a Block.
497 //===----------------------------------------------------------------------===//
500 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
501 BumpVector<const VarDecl*> &BEVals;
502 BumpVectorContext &BC;
503 llvm::SmallPtrSet<const VarDecl*, 4> Visited;
504 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
506 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
507 BumpVectorContext &bc)
508 : BEVals(bevals), BC(bc) {}
510 void VisitStmt(Stmt *S) {
511 for (Stmt *Child : S->children())
516 void VisitDeclRefExpr(DeclRefExpr *DR) {
517 // Non-local variables are also directly modified.
518 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
519 if (!VD->hasLocalStorage()) {
520 if (Visited.insert(VD).second)
521 BEVals.push_back(VD, BC);
526 void VisitBlockExpr(BlockExpr *BR) {
527 // Blocks containing blocks can transitively capture more variables.
528 IgnoredContexts.insert(BR->getBlockDecl());
529 Visit(BR->getBlockDecl()->getBody());
532 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
533 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
534 et = PE->semantics_end(); it != et; ++it) {
535 Expr *Semantic = *it;
536 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
537 Semantic = OVE->getSourceExpr();
542 } // end anonymous namespace
544 typedef BumpVector<const VarDecl*> DeclVec;
546 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
548 llvm::BumpPtrAllocator &A) {
550 return (DeclVec*) Vec;
552 BumpVectorContext BC(A);
553 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
554 new (BV) DeclVec(BC, 10);
556 // Go through the capture list.
557 for (const auto &CI : BD->captures()) {
558 BV->push_back(CI.getVariable(), BC);
561 // Find the referenced global/static variables.
562 FindBlockDeclRefExprsVals F(*BV, BC);
563 F.Visit(BD->getBody());
569 llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
570 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
571 if (!ReferencedBlockVars)
572 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
575 LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
576 return llvm::make_range(V->begin(), V->end());
579 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
580 if (!ManagedAnalyses)
581 ManagedAnalyses = new ManagedAnalysisMap();
582 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
586 //===----------------------------------------------------------------------===//
588 //===----------------------------------------------------------------------===//
590 ManagedAnalysis::~ManagedAnalysis() {}
592 AnalysisDeclContext::~AnalysisDeclContext() {
593 delete forcedBlkExprs;
594 delete ReferencedBlockVars;
595 // Release the managed analyses.
596 if (ManagedAnalyses) {
597 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
598 llvm::DeleteContainerSeconds(*M);
603 LocationContext::~LocationContext() {}
605 LocationContextManager::~LocationContextManager() {
609 void LocationContextManager::clear() {
610 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
611 E = Contexts.end(); I != E; ) {
612 LocationContext *LC = &*I;