AnalysisConsumer.cpp revision 469ba550f54577f28e23ea42c293308fbcad6609
1//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// 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// "Meta" ASTConsumer for running different source analyses. 11// 12//===----------------------------------------------------------------------===// 13 14#define DEBUG_TYPE "AnalysisConsumer" 15 16#include "AnalysisConsumer.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/Decl.h" 19#include "clang/AST/DeclCXX.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/ParentMap.h" 22#include "clang/AST/RecursiveASTVisitor.h" 23#include "clang/Analysis/CFG.h" 24#include "clang/Analysis/CallGraph.h" 25#include "clang/Analysis/Analyses/LiveVariables.h" 26#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h" 27#include "clang/StaticAnalyzer/Core/CheckerManager.h" 28#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 29#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 30#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 31#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 32#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 33#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 34 35#include "clang/Basic/FileManager.h" 36#include "clang/Basic/SourceManager.h" 37#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 38#include "clang/Lex/Preprocessor.h" 39#include "llvm/Support/raw_ostream.h" 40#include "llvm/Support/Path.h" 41#include "llvm/Support/Program.h" 42#include "llvm/Support/Timer.h" 43#include "llvm/ADT/DepthFirstIterator.h" 44#include "llvm/ADT/OwningPtr.h" 45#include "llvm/ADT/SmallPtrSet.h" 46#include "llvm/ADT/Statistic.h" 47 48#include <queue> 49 50using namespace clang; 51using namespace ento; 52using llvm::SmallPtrSet; 53 54static ExplodedNode::Auditor* CreateUbiViz(); 55 56STATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 57STATISTIC(NumFunctionsAnalyzed, "The # of functions analysed (as top level)."); 58STATISTIC(NumBlocksInAnalyzedFunctions, 59 "The # of basic blocks in the analyzed functions."); 60STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 61STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 62 63//===----------------------------------------------------------------------===// 64// Special PathDiagnosticConsumers. 65//===----------------------------------------------------------------------===// 66 67static void createPlistHTMLDiagnosticConsumer(PathDiagnosticConsumers &C, 68 const std::string &prefix, 69 const Preprocessor &PP) { 70 createHTMLDiagnosticConsumer(C, llvm::sys::path::parent_path(prefix), PP); 71 createPlistDiagnosticConsumer(C, prefix, PP); 72} 73 74namespace { 75class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer { 76 DiagnosticsEngine &Diag; 77public: 78 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) : Diag(Diag) {} 79 virtual ~ClangDiagPathDiagConsumer() {} 80 virtual StringRef getName() const { return "ClangDiags"; } 81 virtual PathGenerationScheme getGenerationScheme() const { return None; } 82 83 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, 84 FilesMade *filesMade) { 85 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(), 86 E = Diags.end(); I != E; ++I) { 87 const PathDiagnostic *PD = *I; 88 StringRef desc = PD->getShortDescription(); 89 SmallString<512> TmpStr; 90 llvm::raw_svector_ostream Out(TmpStr); 91 for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) { 92 if (*I == '%') 93 Out << "%%"; 94 else 95 Out << *I; 96 } 97 Out.flush(); 98 unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning, 99 TmpStr); 100 SourceLocation L = PD->getLocation().asLocation(); 101 DiagnosticBuilder diagBuilder = Diag.Report(L, ErrorDiag); 102 103 // Get the ranges from the last point in the path. 104 ArrayRef<SourceRange> Ranges = PD->path.back()->getRanges(); 105 106 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), 107 E = Ranges.end(); I != E; ++I) { 108 diagBuilder << *I; 109 } 110 } 111 } 112}; 113} // end anonymous namespace 114 115//===----------------------------------------------------------------------===// 116// AnalysisConsumer declaration. 117//===----------------------------------------------------------------------===// 118 119namespace { 120 121class AnalysisConsumer : public ASTConsumer, 122 public RecursiveASTVisitor<AnalysisConsumer> { 123 enum AnalysisMode { 124 ANALYSIS_SYNTAX, 125 ANALYSIS_PATH, 126 ANALYSIS_ALL 127 }; 128 129 /// Mode of the analyzes while recursively visiting Decls. 130 AnalysisMode RecVisitorMode; 131 /// Bug Reporter to use while recursively visiting Decls. 132 BugReporter *RecVisitorBR; 133 134public: 135 ASTContext *Ctx; 136 const Preprocessor &PP; 137 const std::string OutDir; 138 AnalyzerOptionsRef Opts; 139 ArrayRef<std::string> Plugins; 140 141 /// \brief Stores the declarations from the local translation unit. 142 /// Note, we pre-compute the local declarations at parse time as an 143 /// optimization to make sure we do not deserialize everything from disk. 144 /// The local declaration to all declarations ratio might be very small when 145 /// working with a PCH file. 146 SetOfDecls LocalTUDecls; 147 148 // Set of PathDiagnosticConsumers. Owned by AnalysisManager. 149 PathDiagnosticConsumers PathConsumers; 150 151 StoreManagerCreator CreateStoreMgr; 152 ConstraintManagerCreator CreateConstraintMgr; 153 154 OwningPtr<CheckerManager> checkerMgr; 155 OwningPtr<AnalysisManager> Mgr; 156 157 /// Time the analyzes time of each translation unit. 158 static llvm::Timer* TUTotalTimer; 159 160 /// The information about analyzed functions shared throughout the 161 /// translation unit. 162 FunctionSummariesTy FunctionSummaries; 163 164 AnalysisConsumer(const Preprocessor& pp, 165 const std::string& outdir, 166 AnalyzerOptionsRef opts, 167 ArrayRef<std::string> plugins) 168 : RecVisitorMode(ANALYSIS_ALL), RecVisitorBR(0), 169 Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins) { 170 DigestAnalyzerOptions(); 171 if (Opts->PrintStats) { 172 llvm::EnableStatistics(); 173 TUTotalTimer = new llvm::Timer("Analyzer Total Time"); 174 } 175 } 176 177 ~AnalysisConsumer() { 178 if (Opts->PrintStats) 179 delete TUTotalTimer; 180 } 181 182 void DigestAnalyzerOptions() { 183 // Create the PathDiagnosticConsumer. 184 PathConsumers.push_back(new ClangDiagPathDiagConsumer(PP.getDiagnostics())); 185 186 if (!OutDir.empty()) { 187 switch (Opts->AnalysisDiagOpt) { 188 default: 189#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \ 190 case PD_##NAME: CREATEFN(PathConsumers, OutDir, PP); break; 191#include "clang/StaticAnalyzer/Core/Analyses.def" 192 } 193 } else if (Opts->AnalysisDiagOpt == PD_TEXT) { 194 // Create the text client even without a specified output file since 195 // it just uses diagnostic notes. 196 createTextPathDiagnosticConsumer(PathConsumers, "", PP); 197 } 198 199 // Create the analyzer component creators. 200 switch (Opts->AnalysisStoreOpt) { 201 default: 202 llvm_unreachable("Unknown store manager."); 203#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 204 case NAME##Model: CreateStoreMgr = CREATEFN; break; 205#include "clang/StaticAnalyzer/Core/Analyses.def" 206 } 207 208 switch (Opts->AnalysisConstraintsOpt) { 209 default: 210 llvm_unreachable("Unknown store manager."); 211#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 212 case NAME##Model: CreateConstraintMgr = CREATEFN; break; 213#include "clang/StaticAnalyzer/Core/Analyses.def" 214 } 215 } 216 217 void DisplayFunction(const Decl *D, AnalysisMode Mode) { 218 if (!Opts->AnalyzerDisplayProgress) 219 return; 220 221 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 222 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 223 if (Loc.isValid()) { 224 llvm::errs() << "ANALYZE"; 225 switch (Mode) { 226 case ANALYSIS_SYNTAX: llvm::errs() << "(Syntax)"; break; 227 case ANALYSIS_PATH: llvm::errs() << "(Path Sensitive)"; break; 228 case ANALYSIS_ALL: break; 229 }; 230 llvm::errs() << ": " << Loc.getFilename(); 231 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { 232 const NamedDecl *ND = cast<NamedDecl>(D); 233 llvm::errs() << ' ' << *ND << '\n'; 234 } 235 else if (isa<BlockDecl>(D)) { 236 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:" 237 << Loc.getColumn() << '\n'; 238 } 239 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 240 Selector S = MD->getSelector(); 241 llvm::errs() << ' ' << S.getAsString(); 242 } 243 } 244 } 245 246 virtual void Initialize(ASTContext &Context) { 247 Ctx = &Context; 248 checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins, 249 PP.getDiagnostics())); 250 Mgr.reset(new AnalysisManager(*Ctx, 251 PP.getDiagnostics(), 252 PP.getLangOpts(), 253 PathConsumers, 254 CreateStoreMgr, 255 CreateConstraintMgr, 256 checkerMgr.get(), 257 *Opts)); 258 } 259 260 /// \brief Store the top level decls in the set to be processed later on. 261 /// (Doing this pre-processing avoids deserialization of data from PCH.) 262 virtual bool HandleTopLevelDecl(DeclGroupRef D); 263 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D); 264 265 virtual void HandleTranslationUnit(ASTContext &C); 266 267 /// \brief Build the call graph for all the top level decls of this TU and 268 /// use it to define the order in which the functions should be visited. 269 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 270 271 /// \brief Run analyzes(syntax or path sensitive) on the given function. 272 /// \param Mode - determines if we are requesting syntax only or path 273 /// sensitive only analysis. 274 /// \param VisitedCallees - The output parameter, which is populated with the 275 /// set of functions which should be considered analyzed after analyzing the 276 /// given root function. 277 void HandleCode(Decl *D, AnalysisMode Mode, 278 SetOfConstDecls *VisitedCallees = 0); 279 280 void RunPathSensitiveChecks(Decl *D, SetOfConstDecls *VisitedCallees); 281 void ActionExprEngine(Decl *D, bool ObjCGCEnabled, 282 SetOfConstDecls *VisitedCallees); 283 284 /// Visitors for the RecursiveASTVisitor. 285 bool shouldWalkTypesOfTypeLocs() const { return false; } 286 287 /// Handle callbacks for arbitrary Decls. 288 bool VisitDecl(Decl *D) { 289 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 290 return true; 291 } 292 293 bool VisitFunctionDecl(FunctionDecl *FD) { 294 IdentifierInfo *II = FD->getIdentifier(); 295 if (II && II->getName().startswith("__inline")) 296 return true; 297 298 // We skip function template definitions, as their semantics is 299 // only determined when they are instantiated. 300 if (FD->isThisDeclarationADefinition() && 301 !FD->isDependentContext()) { 302 HandleCode(FD, RecVisitorMode); 303 } 304 return true; 305 } 306 307 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 308 if (MD->isThisDeclarationADefinition()) 309 HandleCode(MD, RecVisitorMode); 310 return true; 311 } 312 313private: 314 void storeTopLevelDecls(DeclGroupRef DG); 315 316 /// \brief Check if we should skip (not analyze) the given function. 317 bool skipFunction(Decl *D); 318 319}; 320} // end anonymous namespace 321 322 323//===----------------------------------------------------------------------===// 324// AnalysisConsumer implementation. 325//===----------------------------------------------------------------------===// 326llvm::Timer* AnalysisConsumer::TUTotalTimer = 0; 327 328bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 329 storeTopLevelDecls(DG); 330 return true; 331} 332 333void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 334 storeTopLevelDecls(DG); 335} 336 337void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 338 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 339 340 // Skip ObjCMethodDecl, wait for the objc container to avoid 341 // analyzing twice. 342 if (isa<ObjCMethodDecl>(*I)) 343 continue; 344 345 LocalTUDecls.push_back(*I); 346 } 347} 348 349static bool shouldSkipFunction(CallGraphNode *N, 350 SmallPtrSet<CallGraphNode*,24> Visited) { 351 // We want to re-analyse the functions as top level in several cases: 352 // - The 'init' methods should be reanalyzed because 353 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 354 // 'nil' and unless we analyze the 'init' functions as top level, we will not 355 // catch errors within defensive code. 356 // - We want to reanalyze all ObjC methods as top level to report Retain 357 // Count naming convention errors more aggressively. 358 if (isa<ObjCMethodDecl>(N->getDecl())) 359 return false; 360 361 // Otherwise, if we visited the function before, do not reanalyze it. 362 return Visited.count(N); 363} 364 365void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 366 // Otherwise, use the Callgraph to derive the order. 367 // Build the Call Graph. 368 CallGraph CG; 369 370 // Add all the top level declarations to the graph. 371 // Note: CallGraph can trigger deserialization of more items from a pch 372 // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 373 // We rely on random access to add the initially processed Decls to CG. 374 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 375 CG.addToCallGraph(LocalTUDecls[i]); 376 } 377 378 // Find the top level nodes - children of root + the unreachable (parentless) 379 // nodes. 380 llvm::SmallVector<CallGraphNode*, 24> TopLevelFunctions; 381 for (CallGraph::nodes_iterator TI = CG.parentless_begin(), 382 TE = CG.parentless_end(); TI != TE; ++TI) { 383 TopLevelFunctions.push_back(*TI); 384 NumFunctionTopLevel++; 385 } 386 CallGraphNode *Entry = CG.getRoot(); 387 for (CallGraphNode::iterator I = Entry->begin(), 388 E = Entry->end(); I != E; ++I) { 389 TopLevelFunctions.push_back(*I); 390 NumFunctionTopLevel++; 391 } 392 393 // Make sure the nodes are sorted in order reverse of their definition in the 394 // translation unit. This step is very important for performance. It ensures 395 // that we analyze the root functions before the externally available 396 // subroutines. 397 std::deque<CallGraphNode*> BFSQueue; 398 for (llvm::SmallVector<CallGraphNode*, 24>::reverse_iterator 399 TI = TopLevelFunctions.rbegin(), TE = TopLevelFunctions.rend(); 400 TI != TE; ++TI) 401 BFSQueue.push_back(*TI); 402 403 // BFS over all of the functions, while skipping the ones inlined into 404 // the previously processed functions. Use external Visited set, which is 405 // also modified when we inline a function. 406 SmallPtrSet<CallGraphNode*,24> Visited; 407 while(!BFSQueue.empty()) { 408 CallGraphNode *N = BFSQueue.front(); 409 BFSQueue.pop_front(); 410 411 // Push the children into the queue. 412 for (CallGraphNode::const_iterator CI = N->begin(), 413 CE = N->end(); CI != CE; ++CI) { 414 if (!shouldSkipFunction(*CI, Visited)) 415 BFSQueue.push_back(*CI); 416 } 417 418 // Skip the functions which have been processed already or previously 419 // inlined. 420 if (shouldSkipFunction(N, Visited)) 421 continue; 422 423 // Analyze the function. 424 SetOfConstDecls VisitedCallees; 425 Decl *D = N->getDecl(); 426 assert(D); 427 HandleCode(D, ANALYSIS_PATH, 428 (Mgr->options.InliningMode == All ? 0 : &VisitedCallees)); 429 430 // Add the visited callees to the global visited set. 431 for (SetOfConstDecls::iterator I = VisitedCallees.begin(), 432 E = VisitedCallees.end(); I != E; ++I) { 433 CallGraphNode *VN = CG.getNode(*I); 434 if (VN) 435 Visited.insert(VN); 436 } 437 Visited.insert(N); 438 } 439} 440 441void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 442 // Don't run the actions if an error has occurred with parsing the file. 443 DiagnosticsEngine &Diags = PP.getDiagnostics(); 444 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 445 return; 446 447 { 448 if (TUTotalTimer) TUTotalTimer->startTimer(); 449 450 // Introduce a scope to destroy BR before Mgr. 451 BugReporter BR(*Mgr); 452 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 453 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 454 455 // Run the AST-only checks using the order in which functions are defined. 456 // If inlining is not turned on, use the simplest function order for path 457 // sensitive analyzes as well. 458 RecVisitorMode = (Mgr->shouldInlineCall() ? ANALYSIS_SYNTAX : ANALYSIS_ALL); 459 RecVisitorBR = &BR; 460 461 // Process all the top level declarations. 462 // 463 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 464 // entries. Thus we don't use an iterator, but rely on LocalTUDecls 465 // random access. By doing so, we automatically compensate for iterators 466 // possibly being invalidated, although this is a bit slower. 467 const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 468 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 469 TraverseDecl(LocalTUDecls[i]); 470 } 471 472 if (Mgr->shouldInlineCall()) 473 HandleDeclsCallGraph(LocalTUDeclsSize); 474 475 // After all decls handled, run checkers on the entire TranslationUnit. 476 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 477 478 RecVisitorBR = 0; 479 } 480 481 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 482 // FIXME: This should be replaced with something that doesn't rely on 483 // side-effects in PathDiagnosticConsumer's destructor. This is required when 484 // used with option -disable-free. 485 Mgr.reset(NULL); 486 487 if (TUTotalTimer) TUTotalTimer->stopTimer(); 488 489 // Count how many basic blocks we have not covered. 490 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 491 if (NumBlocksInAnalyzedFunctions > 0) 492 PercentReachableBlocks = 493 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 494 NumBlocksInAnalyzedFunctions; 495 496} 497 498static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) { 499 if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) 500 WL.push_back(BD); 501 502 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end(); 503 I!=E; ++I) 504 if (DeclContext *DC = dyn_cast<DeclContext>(*I)) 505 FindBlocks(DC, WL); 506} 507 508static std::string getFunctionName(const Decl *D) { 509 if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { 510 return ID->getSelector().getAsString(); 511 } 512 if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) { 513 IdentifierInfo *II = ND->getIdentifier(); 514 if (II) 515 return II->getName(); 516 } 517 return ""; 518} 519 520bool AnalysisConsumer::skipFunction(Decl *D) { 521 if (!Opts->AnalyzeSpecificFunction.empty() && 522 getFunctionName(D) != Opts->AnalyzeSpecificFunction) 523 return true; 524 525 // Don't run the actions on declarations in header files unless 526 // otherwise specified. 527 SourceManager &SM = Ctx->getSourceManager(); 528 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 529 if (!Opts->AnalyzeAll && !SM.isFromMainFile(SL)) 530 return true; 531 532 return false; 533} 534 535void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 536 SetOfConstDecls *VisitedCallees) { 537 if (skipFunction(D)) 538 return; 539 540 DisplayFunction(D, Mode); 541 CFG *DeclCFG = Mgr->getCFG(D); 542 if (DeclCFG) { 543 unsigned CFGSize = DeclCFG->size(); 544 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize; 545 } 546 547 548 // Clear the AnalysisManager of old AnalysisDeclContexts. 549 Mgr->ClearContexts(); 550 551 // Dispatch on the actions. 552 SmallVector<Decl*, 10> WL; 553 WL.push_back(D); 554 555 if (D->hasBody() && Opts->AnalyzeNestedBlocks) 556 FindBlocks(cast<DeclContext>(D), WL); 557 558 BugReporter BR(*Mgr); 559 for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end(); 560 WI != WE; ++WI) 561 if ((*WI)->hasBody()) { 562 if (Mode != ANALYSIS_PATH) 563 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR); 564 if (Mode != ANALYSIS_SYNTAX && checkerMgr->hasPathSensitiveCheckers()) { 565 RunPathSensitiveChecks(*WI, VisitedCallees); 566 NumFunctionsAnalyzed++; 567 } 568 } 569} 570 571//===----------------------------------------------------------------------===// 572// Path-sensitive checking. 573//===----------------------------------------------------------------------===// 574 575void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled, 576 SetOfConstDecls *VisitedCallees) { 577 // Construct the analysis engine. First check if the CFG is valid. 578 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 579 if (!Mgr->getCFG(D)) 580 return; 581 582 // See if the LiveVariables analysis scales. 583 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 584 return; 585 586 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries); 587 588 // Set the graph auditor. 589 OwningPtr<ExplodedNode::Auditor> Auditor; 590 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) { 591 Auditor.reset(CreateUbiViz()); 592 ExplodedNode::SetAuditor(Auditor.get()); 593 } 594 595 // Execute the worklist algorithm. 596 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 597 Mgr->options.MaxNodes); 598 599 // Release the auditor (if any) so that it doesn't monitor the graph 600 // created BugReporter. 601 ExplodedNode::SetAuditor(0); 602 603 // Visualize the exploded graph. 604 if (Mgr->options.visualizeExplodedGraphWithGraphViz) 605 Eng.ViewGraph(Mgr->options.TrimGraph); 606 607 // Display warnings. 608 Eng.getBugReporter().FlushReports(); 609} 610 611void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 612 SetOfConstDecls *Visited) { 613 614 switch (Mgr->getLangOpts().getGC()) { 615 case LangOptions::NonGC: 616 ActionExprEngine(D, false, Visited); 617 break; 618 619 case LangOptions::GCOnly: 620 ActionExprEngine(D, true, Visited); 621 break; 622 623 case LangOptions::HybridGC: 624 ActionExprEngine(D, false, Visited); 625 ActionExprEngine(D, true, Visited); 626 break; 627 } 628} 629 630//===----------------------------------------------------------------------===// 631// AnalysisConsumer creation. 632//===----------------------------------------------------------------------===// 633 634ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 635 const std::string& outDir, 636 AnalyzerOptionsRef opts, 637 ArrayRef<std::string> plugins) { 638 // Disable the effects of '-Werror' when using the AnalysisConsumer. 639 pp.getDiagnostics().setWarningsAsErrors(false); 640 641 return new AnalysisConsumer(pp, outDir, opts, plugins); 642} 643 644//===----------------------------------------------------------------------===// 645// Ubigraph Visualization. FIXME: Move to separate file. 646//===----------------------------------------------------------------------===// 647 648namespace { 649 650class UbigraphViz : public ExplodedNode::Auditor { 651 OwningPtr<raw_ostream> Out; 652 llvm::sys::Path Dir, Filename; 653 unsigned Cntr; 654 655 typedef llvm::DenseMap<void*,unsigned> VMap; 656 VMap M; 657 658public: 659 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 660 llvm::sys::Path& filename); 661 662 ~UbigraphViz(); 663 664 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 665}; 666 667} // end anonymous namespace 668 669static ExplodedNode::Auditor* CreateUbiViz() { 670 std::string ErrMsg; 671 672 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 673 if (!ErrMsg.empty()) 674 return 0; 675 676 llvm::sys::Path Filename = Dir; 677 Filename.appendComponent("llvm_ubi"); 678 Filename.makeUnique(true,&ErrMsg); 679 680 if (!ErrMsg.empty()) 681 return 0; 682 683 llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 684 685 OwningPtr<llvm::raw_fd_ostream> Stream; 686 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 687 688 if (!ErrMsg.empty()) 689 return 0; 690 691 return new UbigraphViz(Stream.take(), Dir, Filename); 692} 693 694void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 695 696 assert (Src != Dst && "Self-edges are not allowed."); 697 698 // Lookup the Src. If it is a new node, it's a root. 699 VMap::iterator SrcI= M.find(Src); 700 unsigned SrcID; 701 702 if (SrcI == M.end()) { 703 M[Src] = SrcID = Cntr++; 704 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 705 } 706 else 707 SrcID = SrcI->second; 708 709 // Lookup the Dst. 710 VMap::iterator DstI= M.find(Dst); 711 unsigned DstID; 712 713 if (DstI == M.end()) { 714 M[Dst] = DstID = Cntr++; 715 *Out << "('vertex', " << DstID << ")\n"; 716 } 717 else { 718 // We have hit DstID before. Change its style to reflect a cache hit. 719 DstID = DstI->second; 720 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 721 } 722 723 // Add the edge. 724 *Out << "('edge', " << SrcID << ", " << DstID 725 << ", ('arrow','true'), ('oriented', 'true'))\n"; 726} 727 728UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 729 llvm::sys::Path& filename) 730 : Out(out), Dir(dir), Filename(filename), Cntr(0) { 731 732 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 733 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 734 " ('size', '1.5'))\n"; 735} 736 737UbigraphViz::~UbigraphViz() { 738 Out.reset(0); 739 llvm::errs() << "Running 'ubiviz' program... "; 740 std::string ErrMsg; 741 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 742 std::vector<const char*> args; 743 args.push_back(Ubiviz.c_str()); 744 args.push_back(Filename.c_str()); 745 args.push_back(0); 746 747 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 748 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 749 } 750 751 // Delete the directory. 752 Dir.eraseFromDisk(true); 753} 754