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