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