1 //===- AnalysisDeclContext.cpp - Analysis context for Path Sens analysis --===//
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
11 // context 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/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/LambdaCapture.h"
24 #include "clang/AST/ParentMap.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtVisitor.h"
29 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
30 #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
31 #include "clang/Analysis/BodyFarm.h"
32 #include "clang/Analysis/CFG.h"
33 #include "clang/Analysis/CFGStmtMap.h"
34 #include "clang/Analysis/Support/BumpVector.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/SourceLocation.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/FoldingSet.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/iterator_range.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
52 using namespace clang;
54 using ManagedAnalysisMap = llvm::DenseMap<const void *, ManagedAnalysis *>;
56 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
58 const CFG::BuildOptions &buildOptions)
59 : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) {
60 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
63 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
65 : Manager(Mgr), D(d) {
66 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
69 AnalysisDeclContextManager::AnalysisDeclContextManager(
70 ASTContext &ASTCtx, bool useUnoptimizedCFG, bool addImplicitDtors,
71 bool addInitializers, bool addTemporaryDtors, bool addLifetime,
72 bool addLoopExit, bool addScopes, bool synthesizeBodies,
73 bool addStaticInitBranch, bool addCXXNewAllocator,
74 bool addRichCXXConstructors, bool markElidedCXXConstructors,
75 CodeInjector *injector)
76 : Injector(injector), FunctionBodyFarm(ASTCtx, injector),
77 SynthesizeBodies(synthesizeBodies) {
78 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
79 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
80 cfgBuildOptions.AddInitializers = addInitializers;
81 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
82 cfgBuildOptions.AddLifetime = addLifetime;
83 cfgBuildOptions.AddLoopExit = addLoopExit;
84 cfgBuildOptions.AddScopes = addScopes;
85 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
86 cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator;
87 cfgBuildOptions.AddRichCXXConstructors = addRichCXXConstructors;
88 cfgBuildOptions.MarkElidedCXXConstructors = markElidedCXXConstructors;
91 void AnalysisDeclContextManager::clear() { Contexts.clear(); }
93 Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
94 IsAutosynthesized = false;
95 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
96 Stmt *Body = FD->getBody();
97 if (auto *CoroBody = dyn_cast_or_null<CoroutineBodyStmt>(Body))
98 Body = CoroBody->getBody();
99 if (Manager && Manager->synthesizeBodies()) {
100 Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(FD);
101 if (SynthesizedBody) {
102 Body = SynthesizedBody;
103 IsAutosynthesized = true;
108 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
109 Stmt *Body = MD->getBody();
110 if (Manager && Manager->synthesizeBodies()) {
111 Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(MD);
112 if (SynthesizedBody) {
113 Body = SynthesizedBody;
114 IsAutosynthesized = true;
118 } else if (const auto *BD = dyn_cast<BlockDecl>(D))
119 return BD->getBody();
120 else if (const auto *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
121 return FunTmpl->getTemplatedDecl()->getBody();
123 llvm_unreachable("unknown code decl");
126 Stmt *AnalysisDeclContext::getBody() const {
131 bool AnalysisDeclContext::isBodyAutosynthesized() const {
137 bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const {
139 Stmt *Body = getBody(Tmp);
140 return Tmp && Body->getLocStart().isValid();
143 /// Returns true if \param VD is an Objective-C implicit 'self' parameter.
144 static bool isSelfDecl(const VarDecl *VD) {
145 return isa<ImplicitParamDecl>(VD) && VD->getName() == "self";
148 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
149 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
150 return MD->getSelfDecl();
151 if (const auto *BD = dyn_cast<BlockDecl>(D)) {
152 // See if 'self' was captured by the block.
153 for (const auto &I : BD->captures()) {
154 const VarDecl *VD = I.getVariable();
156 return dyn_cast<ImplicitParamDecl>(VD);
160 auto *CXXMethod = dyn_cast<CXXMethodDecl>(D);
164 const CXXRecordDecl *parent = CXXMethod->getParent();
165 if (!parent->isLambda())
168 for (const auto &LC : parent->captures()) {
169 if (!LC.capturesVariable())
172 VarDecl *VD = LC.getCapturedVar();
174 return dyn_cast<ImplicitParamDecl>(VD);
180 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
182 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
183 // Default construct an entry for 'stmt'.
184 if (const auto *e = dyn_cast<Expr>(stmt))
185 stmt = e->IgnoreParens();
186 (void) (*forcedBlkExprs)[stmt];
190 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
191 assert(forcedBlkExprs);
192 if (const auto *e = dyn_cast<Expr>(stmt))
193 stmt = e->IgnoreParens();
194 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
195 forcedBlkExprs->find(stmt);
196 assert(itr != forcedBlkExprs->end());
200 /// Add each synthetic statement in the CFG to the parent map, using the
201 /// source statement's parent.
202 static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
206 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
207 E = TheCFG->synthetic_stmt_end();
209 PM.setParent(I->first, PM.getParent(I->second));
213 CFG *AnalysisDeclContext::getCFG() {
214 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
215 return getUnoptimizedCFG();
218 cfg = CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
219 // Even when the cfg is not successfully built, we don't
220 // want to try building it again.
224 addParentsForSyntheticStmts(cfg.get(), *PM);
226 // The Observer should only observe one build of the CFG.
227 getCFGBuildOptions().Observer = nullptr;
232 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
233 if (!builtCompleteCFG) {
234 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
237 CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
238 // Even when the cfg is not successfully built, we don't
239 // want to try building it again.
240 builtCompleteCFG = true;
243 addParentsForSyntheticStmts(completeCFG.get(), *PM);
245 // The Observer should only observe one build of the CFG.
246 getCFGBuildOptions().Observer = nullptr;
248 return completeCFG.get();
251 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
253 return cfgStmtMap.get();
255 if (CFG *c = getCFG()) {
256 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
257 return cfgStmtMap.get();
263 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
267 if (CFG *c = getCFG()) {
268 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
275 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
276 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
279 ParentMap &AnalysisDeclContext::getParentMap() {
281 PM.reset(new ParentMap(getBody()));
282 if (const auto *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
283 for (const auto *I : C->inits()) {
284 PM->addStmt(I->getInit());
288 addParentsForSyntheticStmts(getCFG(), *PM);
289 if (builtCompleteCFG)
290 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
295 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
297 PCA.reset(new PseudoConstantAnalysis(getBody()));
301 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
302 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
303 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
304 // that has the body.
309 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D];
311 AC = llvm::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions);
315 BodyFarm &AnalysisDeclContextManager::getBodyFarm() { return FunctionBodyFarm; }
317 const StackFrameContext *
318 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
319 const CFGBlock *Blk, unsigned Idx) {
320 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
323 const BlockInvocationContext *
324 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
326 const void *ContextData) {
327 return getLocationContextManager().getBlockInvocationContext(this, parent,
331 bool AnalysisDeclContext::isInStdNamespace(const Decl *D) {
332 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
333 const auto *ND = dyn_cast<NamespaceDecl>(DC);
337 while (const DeclContext *Parent = ND->getParent()) {
338 if (!isa<NamespaceDecl>(Parent))
340 ND = cast<NamespaceDecl>(Parent);
343 return ND->isStdNamespace();
346 LocationContextManager &AnalysisDeclContext::getLocationContextManager() {
348 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
349 return Manager->getLocationContextManager();
352 //===----------------------------------------------------------------------===//
353 // FoldingSet profiling.
354 //===----------------------------------------------------------------------===//
356 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
358 AnalysisDeclContext *ctx,
359 const LocationContext *parent,
363 ID.AddPointer(parent);
367 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
368 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
371 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
372 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
375 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
376 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
379 //===----------------------------------------------------------------------===//
380 // LocationContext creation.
381 //===----------------------------------------------------------------------===//
383 template <typename LOC, typename DATA>
385 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
386 const LocationContext *parent,
388 llvm::FoldingSetNodeID ID;
389 LOC::Profile(ID, ctx, parent, d);
392 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
395 L = new LOC(ctx, parent, d);
396 Contexts.InsertNode(L, InsertPos);
401 const StackFrameContext*
402 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
403 const LocationContext *parent,
405 const CFGBlock *blk, unsigned idx) {
406 llvm::FoldingSetNodeID ID;
407 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
410 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
412 L = new StackFrameContext(ctx, parent, s, blk, idx);
413 Contexts.InsertNode(L, InsertPos);
419 LocationContextManager::getScope(AnalysisDeclContext *ctx,
420 const LocationContext *parent,
422 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
425 const BlockInvocationContext *
426 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
427 const LocationContext *parent,
429 const void *ContextData) {
430 llvm::FoldingSetNodeID ID;
431 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
434 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
437 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
438 Contexts.InsertNode(L, InsertPos);
443 //===----------------------------------------------------------------------===//
444 // LocationContext methods.
445 //===----------------------------------------------------------------------===//
447 const StackFrameContext *LocationContext::getStackFrame() const {
448 const LocationContext *LC = this;
450 if (const auto *SFC = dyn_cast<StackFrameContext>(LC))
452 LC = LC->getParent();
457 bool LocationContext::inTopFrame() const {
458 return getStackFrame()->inTopFrame();
461 bool LocationContext::isParentOf(const LocationContext *LC) const {
463 const LocationContext *Parent = LC->getParent();
473 static void printLocation(raw_ostream &OS, const SourceManager &SM,
474 SourceLocation SLoc) {
475 if (SLoc.isFileID() && SM.isInMainFile(SLoc))
476 OS << "line " << SM.getExpansionLineNumber(SLoc);
481 void LocationContext::dumpStack(
482 raw_ostream &OS, StringRef Indent, const char *NL, const char *Sep,
483 std::function<void(const LocationContext *)> printMoreInfoPerContext) const {
484 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
485 PrintingPolicy PP(Ctx.getLangOpts());
488 const SourceManager &SM =
489 getAnalysisDeclContext()->getASTContext().getSourceManager();
492 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
493 switch (LCtx->getKind()) {
495 OS << Indent << '#' << Frame << ' ';
497 if (const auto *D = dyn_cast<NamedDecl>(LCtx->getDecl()))
498 OS << "Calling " << D->getQualifiedNameAsString();
500 OS << "Calling anonymous code";
501 if (const Stmt *S = cast<StackFrameContext>(LCtx)->getCallSite()) {
503 printLocation(OS, SM, S->getLocStart());
507 OS << "Entering scope";
510 OS << "Invoking block";
511 if (const Decl *D = cast<BlockInvocationContext>(LCtx)->getDecl()) {
512 OS << " defined at ";
513 printLocation(OS, SM, D->getLocStart());
519 printMoreInfoPerContext(LCtx);
523 LLVM_DUMP_METHOD void LocationContext::dumpStack() const {
524 dumpStack(llvm::errs());
527 //===----------------------------------------------------------------------===//
528 // Lazily generated map to query the external variables referenced by a Block.
529 //===----------------------------------------------------------------------===//
533 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
534 BumpVector<const VarDecl *> &BEVals;
535 BumpVectorContext &BC;
536 llvm::SmallPtrSet<const VarDecl *, 4> Visited;
537 llvm::SmallPtrSet<const DeclContext *, 4> IgnoredContexts;
540 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
541 BumpVectorContext &bc)
542 : BEVals(bevals), BC(bc) {}
544 void VisitStmt(Stmt *S) {
545 for (auto *Child : S->children())
550 void VisitDeclRefExpr(DeclRefExpr *DR) {
551 // Non-local variables are also directly modified.
552 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
553 if (!VD->hasLocalStorage()) {
554 if (Visited.insert(VD).second)
555 BEVals.push_back(VD, BC);
560 void VisitBlockExpr(BlockExpr *BR) {
561 // Blocks containing blocks can transitively capture more variables.
562 IgnoredContexts.insert(BR->getBlockDecl());
563 Visit(BR->getBlockDecl()->getBody());
566 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
567 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
568 et = PE->semantics_end(); it != et; ++it) {
569 Expr *Semantic = *it;
570 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
571 Semantic = OVE->getSourceExpr();
579 using DeclVec = BumpVector<const VarDecl *>;
581 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
583 llvm::BumpPtrAllocator &A) {
585 return (DeclVec*) Vec;
587 BumpVectorContext BC(A);
588 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
589 new (BV) DeclVec(BC, 10);
591 // Go through the capture list.
592 for (const auto &CI : BD->captures()) {
593 BV->push_back(CI.getVariable(), BC);
596 // Find the referenced global/static variables.
597 FindBlockDeclRefExprsVals F(*BV, BC);
598 F.Visit(BD->getBody());
604 llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
605 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
606 if (!ReferencedBlockVars)
607 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
610 LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
611 return llvm::make_range(V->begin(), V->end());
614 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
615 if (!ManagedAnalyses)
616 ManagedAnalyses = new ManagedAnalysisMap();
617 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
621 //===----------------------------------------------------------------------===//
623 //===----------------------------------------------------------------------===//
625 ManagedAnalysis::~ManagedAnalysis() = default;
627 AnalysisDeclContext::~AnalysisDeclContext() {
628 delete forcedBlkExprs;
629 delete ReferencedBlockVars;
630 // Release the managed analyses.
631 if (ManagedAnalyses) {
632 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
633 llvm::DeleteContainerSeconds(*M);
638 LocationContext::~LocationContext() = default;
640 LocationContextManager::~LocationContextManager() {
644 void LocationContextManager::clear() {
645 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
646 E = Contexts.end(); I != E; ) {
647 LocationContext *LC = &*I;