1 //== AnalysisDeclContext.cpp - Analysis context for Path Sens analysis -*- C++ -*-// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines AnalysisDeclContext, a class that manages the analysis context 11 // data for path sensitive analysis. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Analysis/AnalysisContext.h" 16 #include "BodyFarm.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" 33 34 using namespace clang; 35 36 typedef llvm::DenseMap<const void *, ManagedAnalysis *> ManagedAnalysisMap; 37 38 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, 39 const Decl *d, 40 const CFG::BuildOptions &buildOptions) 41 : Manager(Mgr), 42 D(d), 43 cfgBuildOptions(buildOptions), 44 forcedBlkExprs(nullptr), 45 builtCFG(false), 46 builtCompleteCFG(false), 47 ReferencedBlockVars(nullptr), 48 ManagedAnalyses(nullptr) 49 { 50 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; 51 } 52 53 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, 54 const Decl *d) 55 : Manager(Mgr), 56 D(d), 57 forcedBlkExprs(nullptr), 58 builtCFG(false), 59 builtCompleteCFG(false), 60 ReferencedBlockVars(nullptr), 61 ManagedAnalyses(nullptr) 62 { 63 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; 64 } 65 66 AnalysisDeclContextManager::AnalysisDeclContextManager(bool useUnoptimizedCFG, 67 bool addImplicitDtors, 68 bool addInitializers, 69 bool addTemporaryDtors, 70 bool synthesizeBodies, 71 bool addStaticInitBranch, 72 bool addCXXNewAllocator, 73 CodeInjector *injector) 74 : Injector(injector), SynthesizeBodies(synthesizeBodies) 75 { 76 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG; 77 cfgBuildOptions.AddImplicitDtors = addImplicitDtors; 78 cfgBuildOptions.AddInitializers = addInitializers; 79 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors; 80 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch; 81 cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator; 82 } 83 84 void AnalysisDeclContextManager::clear() { Contexts.clear(); } 85 86 static BodyFarm &getBodyFarm(ASTContext &C, CodeInjector *injector = nullptr) { 87 static BodyFarm *BF = new BodyFarm(C, injector); 88 return *BF; 89 } 90 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; 101 } 102 } 103 return Body; 104 } 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; 113 } 114 } 115 return Body; 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(); 121 122 llvm_unreachable("unknown code decl"); 123 } 124 125 Stmt *AnalysisDeclContext::getBody() const { 126 bool Tmp; 127 return getBody(Tmp); 128 } 129 130 bool AnalysisDeclContext::isBodyAutosynthesized() const { 131 bool Tmp; 132 getBody(Tmp); 133 return Tmp; 134 } 135 136 bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const { 137 bool Tmp; 138 Stmt *Body = getBody(Tmp); 139 return Tmp && Body->getLocStart().isValid(); 140 } 141 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"; 145 } 146 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(); 154 if (isSelfDecl(VD)) 155 return dyn_cast<ImplicitParamDecl>(VD); 156 } 157 } 158 159 auto *CXXMethod = dyn_cast<CXXMethodDecl>(D); 160 if (!CXXMethod) 161 return nullptr; 162 163 const CXXRecordDecl *parent = CXXMethod->getParent(); 164 if (!parent->isLambda()) 165 return nullptr; 166 167 for (const LambdaCapture &LC : parent->captures()) { 168 if (!LC.capturesVariable()) 169 continue; 170 171 VarDecl *VD = LC.getCapturedVar(); 172 if (isSelfDecl(VD)) 173 return dyn_cast<ImplicitParamDecl>(VD); 174 } 175 176 return nullptr; 177 } 178 179 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) { 180 if (!forcedBlkExprs) 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]; 186 } 187 188 const CFGBlock * 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()); 196 return itr->second; 197 } 198 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) { 202 if (!TheCFG) 203 return; 204 205 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(), 206 E = TheCFG->synthetic_stmt_end(); 207 I != E; ++I) { 208 PM.setParent(I->first, PM.getParent(I->second)); 209 } 210 } 211 212 CFG *AnalysisDeclContext::getCFG() { 213 if (!cfgBuildOptions.PruneTriviallyFalseEdges) 214 return getUnoptimizedCFG(); 215 216 if (!builtCFG) { 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. 220 builtCFG = true; 221 222 if (PM) 223 addParentsForSyntheticStmts(cfg.get(), *PM); 224 225 // The Observer should only observe one build of the CFG. 226 getCFGBuildOptions().Observer = nullptr; 227 } 228 return cfg.get(); 229 } 230 231 CFG *AnalysisDeclContext::getUnoptimizedCFG() { 232 if (!builtCompleteCFG) { 233 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges, 234 false); 235 completeCFG = 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; 240 241 if (PM) 242 addParentsForSyntheticStmts(completeCFG.get(), *PM); 243 244 // The Observer should only observe one build of the CFG. 245 getCFGBuildOptions().Observer = nullptr; 246 } 247 return completeCFG.get(); 248 } 249 250 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() { 251 if (cfgStmtMap) 252 return cfgStmtMap.get(); 253 254 if (CFG *c = getCFG()) { 255 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap())); 256 return cfgStmtMap.get(); 257 } 258 259 return nullptr; 260 } 261 262 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() { 263 if (CFA) 264 return CFA.get(); 265 266 if (CFG *c = getCFG()) { 267 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c)); 268 return CFA.get(); 269 } 270 271 return nullptr; 272 } 273 274 void AnalysisDeclContext::dumpCFG(bool ShowColors) { 275 getCFG()->dump(getASTContext().getLangOpts(), ShowColors); 276 } 277 278 ParentMap &AnalysisDeclContext::getParentMap() { 279 if (!PM) { 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()); 284 } 285 } 286 if (builtCFG) 287 addParentsForSyntheticStmts(getCFG(), *PM); 288 if (builtCompleteCFG) 289 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM); 290 } 291 return *PM; 292 } 293 294 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() { 295 if (!PCA) 296 PCA.reset(new PseudoConstantAnalysis(getBody())); 297 return PCA.get(); 298 } 299 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. 304 FD->hasBody(FD); 305 D = FD; 306 } 307 308 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D]; 309 if (!AC) 310 AC = llvm::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions); 311 return AC.get(); 312 } 313 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); 318 } 319 320 const BlockInvocationContext * 321 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent, 322 const clang::BlockDecl *BD, 323 const void *ContextData) { 324 return getLocationContextManager().getBlockInvocationContext(this, parent, 325 BD, ContextData); 326 } 327 328 bool AnalysisDeclContext::isInStdNamespace(const Decl *D) { 329 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext(); 330 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC); 331 if (!ND) 332 return false; 333 334 while (const DeclContext *Parent = ND->getParent()) { 335 if (!isa<NamespaceDecl>(Parent)) 336 break; 337 ND = cast<NamespaceDecl>(Parent); 338 } 339 340 return ND->isStdNamespace(); 341 } 342 343 LocationContextManager & AnalysisDeclContext::getLocationContextManager() { 344 assert(Manager && 345 "Cannot create LocationContexts without an AnalysisDeclContextManager!"); 346 return Manager->getLocationContextManager(); 347 } 348 349 //===----------------------------------------------------------------------===// 350 // FoldingSet profiling. 351 //===----------------------------------------------------------------------===// 352 353 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID, 354 ContextKind ck, 355 AnalysisDeclContext *ctx, 356 const LocationContext *parent, 357 const void *data) { 358 ID.AddInteger(ck); 359 ID.AddPointer(ctx); 360 ID.AddPointer(parent); 361 ID.AddPointer(data); 362 } 363 364 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) { 365 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index); 366 } 367 368 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) { 369 Profile(ID, getAnalysisDeclContext(), getParent(), Enter); 370 } 371 372 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) { 373 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData); 374 } 375 376 //===----------------------------------------------------------------------===// 377 // LocationContext creation. 378 //===----------------------------------------------------------------------===// 379 380 template <typename LOC, typename DATA> 381 const LOC* 382 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx, 383 const LocationContext *parent, 384 const DATA *d) { 385 llvm::FoldingSetNodeID ID; 386 LOC::Profile(ID, ctx, parent, d); 387 void *InsertPos; 388 389 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); 390 391 if (!L) { 392 L = new LOC(ctx, parent, d); 393 Contexts.InsertNode(L, InsertPos); 394 } 395 return L; 396 } 397 398 const StackFrameContext* 399 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx, 400 const LocationContext *parent, 401 const Stmt *s, 402 const CFGBlock *blk, unsigned idx) { 403 llvm::FoldingSetNodeID ID; 404 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx); 405 void *InsertPos; 406 StackFrameContext *L = 407 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); 408 if (!L) { 409 L = new StackFrameContext(ctx, parent, s, blk, idx); 410 Contexts.InsertNode(L, InsertPos); 411 } 412 return L; 413 } 414 415 const ScopeContext * 416 LocationContextManager::getScope(AnalysisDeclContext *ctx, 417 const LocationContext *parent, 418 const Stmt *s) { 419 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s); 420 } 421 422 const BlockInvocationContext * 423 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx, 424 const LocationContext *parent, 425 const BlockDecl *BD, 426 const void *ContextData) { 427 llvm::FoldingSetNodeID ID; 428 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData); 429 void *InsertPos; 430 BlockInvocationContext *L = 431 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID, 432 InsertPos)); 433 if (!L) { 434 L = new BlockInvocationContext(ctx, parent, BD, ContextData); 435 Contexts.InsertNode(L, InsertPos); 436 } 437 return L; 438 } 439 440 //===----------------------------------------------------------------------===// 441 // LocationContext methods. 442 //===----------------------------------------------------------------------===// 443 444 const StackFrameContext *LocationContext::getCurrentStackFrame() const { 445 const LocationContext *LC = this; 446 while (LC) { 447 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) 448 return SFC; 449 LC = LC->getParent(); 450 } 451 return nullptr; 452 } 453 454 bool LocationContext::inTopFrame() const { 455 return getCurrentStackFrame()->inTopFrame(); 456 } 457 458 bool LocationContext::isParentOf(const LocationContext *LC) const { 459 do { 460 const LocationContext *Parent = LC->getParent(); 461 if (Parent == this) 462 return true; 463 else 464 LC = Parent; 465 } while (LC); 466 467 return false; 468 } 469 470 void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const { 471 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext(); 472 PrintingPolicy PP(Ctx.getLangOpts()); 473 PP.TerseOutput = 1; 474 475 unsigned Frame = 0; 476 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) { 477 switch (LCtx->getKind()) { 478 case StackFrame: 479 OS << Indent << '#' << Frame++ << ' '; 480 cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP); 481 OS << '\n'; 482 break; 483 case Scope: 484 OS << Indent << " (scope)\n"; 485 break; 486 case Block: 487 OS << Indent << " (block context: " 488 << cast<BlockInvocationContext>(LCtx)->getContextData() 489 << ")\n"; 490 break; 491 } 492 } 493 } 494 495 LLVM_DUMP_METHOD void LocationContext::dumpStack() const { 496 dumpStack(llvm::errs()); 497 } 498 499 //===----------------------------------------------------------------------===// 500 // Lazily generated map to query the external variables referenced by a Block. 501 //===----------------------------------------------------------------------===// 502 503 namespace { 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; 509 public: 510 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals, 511 BumpVectorContext &bc) 512 : BEVals(bevals), BC(bc) {} 513 514 void VisitStmt(Stmt *S) { 515 for (Stmt *Child : S->children()) 516 if (Child) 517 Visit(Child); 518 } 519 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); 526 } 527 } 528 } 529 530 void VisitBlockExpr(BlockExpr *BR) { 531 // Blocks containing blocks can transitively capture more variables. 532 IgnoredContexts.insert(BR->getBlockDecl()); 533 Visit(BR->getBlockDecl()->getBody()); 534 } 535 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(); 542 Visit(Semantic); 543 } 544 } 545 }; 546 } // end anonymous namespace 547 548 typedef BumpVector<const VarDecl*> DeclVec; 549 550 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD, 551 void *&Vec, 552 llvm::BumpPtrAllocator &A) { 553 if (Vec) 554 return (DeclVec*) Vec; 555 556 BumpVectorContext BC(A); 557 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>(); 558 new (BV) DeclVec(BC, 10); 559 560 // Go through the capture list. 561 for (const auto &CI : BD->captures()) { 562 BV->push_back(CI.getVariable(), BC); 563 } 564 565 // Find the referenced global/static variables. 566 FindBlockDeclRefExprsVals F(*BV, BC); 567 F.Visit(BD->getBody()); 568 569 Vec = BV; 570 return BV; 571 } 572 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*>(); 577 578 const DeclVec *V = 579 LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A); 580 return llvm::make_range(V->begin(), V->end()); 581 } 582 583 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) { 584 if (!ManagedAnalyses) 585 ManagedAnalyses = new ManagedAnalysisMap(); 586 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses; 587 return (*M)[tag]; 588 } 589 590 //===----------------------------------------------------------------------===// 591 // Cleanup. 592 //===----------------------------------------------------------------------===// 593 594 ManagedAnalysis::~ManagedAnalysis() {} 595 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); 603 delete M; 604 } 605 } 606 607 AnalysisDeclContextManager::~AnalysisDeclContextManager() {} 608 609 LocationContext::~LocationContext() {} 610 611 LocationContextManager::~LocationContextManager() { 612 clear(); 613 } 614 615 void LocationContextManager::clear() { 616 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(), 617 E = Contexts.end(); I != E; ) { 618 LocationContext *LC = &*I; 619 ++I; 620 delete LC; 621 } 622 623 Contexts.clear(); 624 } 625 626