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/raw_ostream.h" 32 #include "llvm/Support/SaveAndRestore.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(0), 45 builtCFG(false), 46 builtCompleteCFG(false), 47 ReferencedBlockVars(0), 48 ManagedAnalyses(0) 49 { 50 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs; 51 } 52 53 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr, 54 const Decl *d) 55 : Manager(Mgr), 56 D(d), 57 forcedBlkExprs(0), 58 builtCFG(false), 59 builtCompleteCFG(false), 60 ReferencedBlockVars(0), 61 ManagedAnalyses(0) 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 : SynthesizeBodies(synthesizeBodies) 73 { 74 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG; 75 cfgBuildOptions.AddImplicitDtors = addImplicitDtors; 76 cfgBuildOptions.AddInitializers = addInitializers; 77 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors; 78 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch; 79 } 80 81 void AnalysisDeclContextManager::clear() { 82 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I) 83 delete I->second; 84 Contexts.clear(); 85 } 86 87 static BodyFarm &getBodyFarm(ASTContext &C) { 88 static BodyFarm *BF = new BodyFarm(C); 89 return *BF; 90 } 91 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); 99 } 100 return Body; 101 } 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(); 109 110 llvm_unreachable("unknown code decl"); 111 } 112 113 Stmt *AnalysisDeclContext::getBody() const { 114 bool Tmp; 115 return getBody(Tmp); 116 } 117 118 bool AnalysisDeclContext::isBodyAutosynthesized() const { 119 bool Tmp; 120 getBody(Tmp); 121 return Tmp; 122 } 123 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); 134 } 135 } 136 137 return NULL; 138 } 139 140 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) { 141 if (!forcedBlkExprs) 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]; 147 } 148 149 const CFGBlock * 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()); 157 return itr->second; 158 } 159 160 CFG *AnalysisDeclContext::getCFG() { 161 if (!cfgBuildOptions.PruneTriviallyFalseEdges) 162 return getUnoptimizedCFG(); 163 164 if (!builtCFG) { 165 cfg.reset(CFG::buildCFG(D, getBody(), 166 &D->getASTContext(), cfgBuildOptions)); 167 // Even when the cfg is not successfully built, we don't 168 // want to try building it again. 169 builtCFG = true; 170 } 171 return cfg.get(); 172 } 173 174 CFG *AnalysisDeclContext::getUnoptimizedCFG() { 175 if (!builtCompleteCFG) { 176 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges, 177 false); 178 completeCFG.reset(CFG::buildCFG(D, getBody(), &D->getASTContext(), 179 cfgBuildOptions)); 180 // Even when the cfg is not successfully built, we don't 181 // want to try building it again. 182 builtCompleteCFG = true; 183 } 184 return completeCFG.get(); 185 } 186 187 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() { 188 if (cfgStmtMap) 189 return cfgStmtMap.get(); 190 191 if (CFG *c = getCFG()) { 192 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap())); 193 return cfgStmtMap.get(); 194 } 195 196 return 0; 197 } 198 199 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() { 200 if (CFA) 201 return CFA.get(); 202 203 if (CFG *c = getCFG()) { 204 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c)); 205 return CFA.get(); 206 } 207 208 return 0; 209 } 210 211 void AnalysisDeclContext::dumpCFG(bool ShowColors) { 212 getCFG()->dump(getASTContext().getLangOpts(), ShowColors); 213 } 214 215 ParentMap &AnalysisDeclContext::getParentMap() { 216 if (!PM) { 217 PM.reset(new ParentMap(getBody())); 218 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) { 219 for (CXXConstructorDecl::init_const_iterator I = C->init_begin(), 220 E = C->init_end(); 221 I != E; ++I) { 222 PM->addStmt((*I)->getInit()); 223 } 224 } 225 } 226 return *PM; 227 } 228 229 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() { 230 if (!PCA) 231 PCA.reset(new PseudoConstantAnalysis(getBody())); 232 return PCA.get(); 233 } 234 235 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) { 236 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 237 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl 238 // that has the body. 239 FD->hasBody(FD); 240 D = FD; 241 } 242 243 AnalysisDeclContext *&AC = Contexts[D]; 244 if (!AC) 245 AC = new AnalysisDeclContext(this, D, cfgBuildOptions); 246 return AC; 247 } 248 249 const StackFrameContext * 250 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S, 251 const CFGBlock *Blk, unsigned Idx) { 252 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx); 253 } 254 255 const BlockInvocationContext * 256 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent, 257 const clang::BlockDecl *BD, 258 const void *ContextData) { 259 return getLocationContextManager().getBlockInvocationContext(this, parent, 260 BD, ContextData); 261 } 262 263 LocationContextManager & AnalysisDeclContext::getLocationContextManager() { 264 assert(Manager && 265 "Cannot create LocationContexts without an AnalysisDeclContextManager!"); 266 return Manager->getLocationContextManager(); 267 } 268 269 //===----------------------------------------------------------------------===// 270 // FoldingSet profiling. 271 //===----------------------------------------------------------------------===// 272 273 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID, 274 ContextKind ck, 275 AnalysisDeclContext *ctx, 276 const LocationContext *parent, 277 const void *data) { 278 ID.AddInteger(ck); 279 ID.AddPointer(ctx); 280 ID.AddPointer(parent); 281 ID.AddPointer(data); 282 } 283 284 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) { 285 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index); 286 } 287 288 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) { 289 Profile(ID, getAnalysisDeclContext(), getParent(), Enter); 290 } 291 292 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) { 293 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData); 294 } 295 296 //===----------------------------------------------------------------------===// 297 // LocationContext creation. 298 //===----------------------------------------------------------------------===// 299 300 template <typename LOC, typename DATA> 301 const LOC* 302 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx, 303 const LocationContext *parent, 304 const DATA *d) { 305 llvm::FoldingSetNodeID ID; 306 LOC::Profile(ID, ctx, parent, d); 307 void *InsertPos; 308 309 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); 310 311 if (!L) { 312 L = new LOC(ctx, parent, d); 313 Contexts.InsertNode(L, InsertPos); 314 } 315 return L; 316 } 317 318 const StackFrameContext* 319 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx, 320 const LocationContext *parent, 321 const Stmt *s, 322 const CFGBlock *blk, unsigned idx) { 323 llvm::FoldingSetNodeID ID; 324 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx); 325 void *InsertPos; 326 StackFrameContext *L = 327 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); 328 if (!L) { 329 L = new StackFrameContext(ctx, parent, s, blk, idx); 330 Contexts.InsertNode(L, InsertPos); 331 } 332 return L; 333 } 334 335 const ScopeContext * 336 LocationContextManager::getScope(AnalysisDeclContext *ctx, 337 const LocationContext *parent, 338 const Stmt *s) { 339 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s); 340 } 341 342 const BlockInvocationContext * 343 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx, 344 const LocationContext *parent, 345 const BlockDecl *BD, 346 const void *ContextData) { 347 llvm::FoldingSetNodeID ID; 348 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData); 349 void *InsertPos; 350 BlockInvocationContext *L = 351 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID, 352 InsertPos)); 353 if (!L) { 354 L = new BlockInvocationContext(ctx, parent, BD, ContextData); 355 Contexts.InsertNode(L, InsertPos); 356 } 357 return L; 358 } 359 360 //===----------------------------------------------------------------------===// 361 // LocationContext methods. 362 //===----------------------------------------------------------------------===// 363 364 const StackFrameContext *LocationContext::getCurrentStackFrame() const { 365 const LocationContext *LC = this; 366 while (LC) { 367 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) 368 return SFC; 369 LC = LC->getParent(); 370 } 371 return NULL; 372 } 373 374 bool LocationContext::inTopFrame() const { 375 return getCurrentStackFrame()->inTopFrame(); 376 } 377 378 bool LocationContext::isParentOf(const LocationContext *LC) const { 379 do { 380 const LocationContext *Parent = LC->getParent(); 381 if (Parent == this) 382 return true; 383 else 384 LC = Parent; 385 } while (LC); 386 387 return false; 388 } 389 390 void LocationContext::dumpStack() const { 391 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext(); 392 PrintingPolicy PP(Ctx.getLangOpts()); 393 PP.TerseOutput = 1; 394 395 unsigned Frame = 0; 396 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) { 397 switch (LCtx->getKind()) { 398 case StackFrame: 399 llvm::errs() << '#' << Frame++ << ' '; 400 cast<StackFrameContext>(LCtx)->getDecl()->print(llvm::errs(), PP); 401 llvm::errs() << '\n'; 402 break; 403 case Scope: 404 llvm::errs() << " (scope)\n"; 405 break; 406 case Block: 407 llvm::errs() << " (block context: " 408 << cast<BlockInvocationContext>(LCtx)->getContextData() 409 << ")\n"; 410 break; 411 } 412 } 413 } 414 415 //===----------------------------------------------------------------------===// 416 // Lazily generated map to query the external variables referenced by a Block. 417 //===----------------------------------------------------------------------===// 418 419 namespace { 420 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{ 421 BumpVector<const VarDecl*> &BEVals; 422 BumpVectorContext &BC; 423 llvm::SmallPtrSet<const VarDecl*, 4> Visited; 424 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts; 425 public: 426 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals, 427 BumpVectorContext &bc) 428 : BEVals(bevals), BC(bc) {} 429 430 bool IsTrackedDecl(const VarDecl *VD) { 431 const DeclContext *DC = VD->getDeclContext(); 432 return IgnoredContexts.count(DC) == 0; 433 } 434 435 void VisitStmt(Stmt *S) { 436 for (Stmt::child_range I = S->children(); I; ++I) 437 if (Stmt *child = *I) 438 Visit(child); 439 } 440 441 void VisitDeclRefExpr(DeclRefExpr *DR) { 442 // Non-local variables are also directly modified. 443 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 444 if (!VD->hasLocalStorage()) { 445 if (Visited.insert(VD)) 446 BEVals.push_back(VD, BC); 447 } 448 } 449 } 450 451 void VisitBlockExpr(BlockExpr *BR) { 452 // Blocks containing blocks can transitively capture more variables. 453 IgnoredContexts.insert(BR->getBlockDecl()); 454 Visit(BR->getBlockDecl()->getBody()); 455 } 456 457 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) { 458 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(), 459 et = PE->semantics_end(); it != et; ++it) { 460 Expr *Semantic = *it; 461 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) 462 Semantic = OVE->getSourceExpr(); 463 Visit(Semantic); 464 } 465 } 466 }; 467 } // end anonymous namespace 468 469 typedef BumpVector<const VarDecl*> DeclVec; 470 471 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD, 472 void *&Vec, 473 llvm::BumpPtrAllocator &A) { 474 if (Vec) 475 return (DeclVec*) Vec; 476 477 BumpVectorContext BC(A); 478 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>(); 479 new (BV) DeclVec(BC, 10); 480 481 // Go through the capture list. 482 for (BlockDecl::capture_const_iterator CI = BD->capture_begin(), 483 CE = BD->capture_end(); CI != CE; ++CI) { 484 BV->push_back(CI->getVariable(), BC); 485 } 486 487 // Find the referenced global/static variables. 488 FindBlockDeclRefExprsVals F(*BV, BC); 489 F.Visit(BD->getBody()); 490 491 Vec = BV; 492 return BV; 493 } 494 495 std::pair<AnalysisDeclContext::referenced_decls_iterator, 496 AnalysisDeclContext::referenced_decls_iterator> 497 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) { 498 if (!ReferencedBlockVars) 499 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>(); 500 501 DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A); 502 return std::make_pair(V->begin(), V->end()); 503 } 504 505 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) { 506 if (!ManagedAnalyses) 507 ManagedAnalyses = new ManagedAnalysisMap(); 508 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses; 509 return (*M)[tag]; 510 } 511 512 //===----------------------------------------------------------------------===// 513 // Cleanup. 514 //===----------------------------------------------------------------------===// 515 516 ManagedAnalysis::~ManagedAnalysis() {} 517 518 AnalysisDeclContext::~AnalysisDeclContext() { 519 delete forcedBlkExprs; 520 delete ReferencedBlockVars; 521 // Release the managed analyses. 522 if (ManagedAnalyses) { 523 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses; 524 for (ManagedAnalysisMap::iterator I = M->begin(), E = M->end(); I!=E; ++I) 525 delete I->second; 526 delete M; 527 } 528 } 529 530 AnalysisDeclContextManager::~AnalysisDeclContextManager() { 531 for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I) 532 delete I->second; 533 } 534 535 LocationContext::~LocationContext() {} 536 537 LocationContextManager::~LocationContextManager() { 538 clear(); 539 } 540 541 void LocationContextManager::clear() { 542 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(), 543 E = Contexts.end(); I != E; ) { 544 LocationContext *LC = &*I; 545 ++I; 546 delete LC; 547 } 548 549 Contexts.clear(); 550 } 551 552