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/PostOrderIterator.h" 41 #include "llvm/ADT/SmallPtrSet.h" 42 #include "llvm/ADT/Statistic.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 49 using namespace clang; 50 using namespace ento; 51 using llvm::SmallPtrSet; 52 53 static ExplodedNode::Auditor* CreateUbiViz(); 54 55 STATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 56 STATISTIC(NumFunctionsAnalyzed, 57 "The # of functions and blocks analyzed (as top level " 58 "with inlining turned on)."); 59 STATISTIC(NumBlocksInAnalyzedFunctions, 60 "The # of basic blocks in the analyzed functions."); 61 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 62 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 63 64 //===----------------------------------------------------------------------===// 65 // Special PathDiagnosticConsumers. 66 //===----------------------------------------------------------------------===// 67 68 static 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 77 namespace { 78 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer { 79 DiagnosticsEngine &Diag; 80 public: 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 122 namespace { 123 124 class 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 138 public: 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 constraint 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 ExprEngine::InliningModes IMode) { 224 if (!Opts->AnalyzerDisplayProgress) 225 return; 226 227 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 228 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 229 if (Loc.isValid()) { 230 llvm::errs() << "ANALYZE"; 231 232 if (Mode == AM_Syntax) 233 llvm::errs() << " (Syntax)"; 234 else if (Mode == AM_Path) { 235 llvm::errs() << " (Path, "; 236 switch (IMode) { 237 case ExprEngine::Inline_None: 238 llvm::errs() << " Inline_None"; 239 break; 240 case ExprEngine::Inline_All: 241 llvm::errs() << " Inline_All"; 242 break; 243 } 244 llvm::errs() << ")"; 245 } 246 else 247 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!"); 248 249 llvm::errs() << ": " << Loc.getFilename(); 250 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { 251 const NamedDecl *ND = cast<NamedDecl>(D); 252 llvm::errs() << ' ' << *ND << '\n'; 253 } 254 else if (isa<BlockDecl>(D)) { 255 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:" 256 << Loc.getColumn() << '\n'; 257 } 258 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 259 Selector S = MD->getSelector(); 260 llvm::errs() << ' ' << S.getAsString(); 261 } 262 } 263 } 264 265 virtual void Initialize(ASTContext &Context) { 266 Ctx = &Context; 267 checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins, 268 PP.getDiagnostics())); 269 Mgr.reset(new AnalysisManager(*Ctx, 270 PP.getDiagnostics(), 271 PP.getLangOpts(), 272 PathConsumers, 273 CreateStoreMgr, 274 CreateConstraintMgr, 275 checkerMgr.get(), 276 *Opts)); 277 } 278 279 /// \brief Store the top level decls in the set to be processed later on. 280 /// (Doing this pre-processing avoids deserialization of data from PCH.) 281 virtual bool HandleTopLevelDecl(DeclGroupRef D); 282 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D); 283 284 virtual void HandleTranslationUnit(ASTContext &C); 285 286 /// \brief Determine which inlining mode should be used when this function is 287 /// analyzed. For example, determines if the callees should be inlined. 288 ExprEngine::InliningModes 289 getInliningModeForFunction(const Decl *D, SetOfConstDecls Visited); 290 291 /// \brief Build the call graph for all the top level decls of this TU and 292 /// use it to define the order in which the functions should be visited. 293 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 294 295 /// \brief Run analyzes(syntax or path sensitive) on the given function. 296 /// \param Mode - determines if we are requesting syntax only or path 297 /// sensitive only analysis. 298 /// \param VisitedCallees - The output parameter, which is populated with the 299 /// set of functions which should be considered analyzed after analyzing the 300 /// given root function. 301 void HandleCode(Decl *D, AnalysisMode Mode, 302 ExprEngine::InliningModes IMode = ExprEngine::Inline_None, 303 SetOfConstDecls *VisitedCallees = 0); 304 305 void RunPathSensitiveChecks(Decl *D, 306 ExprEngine::InliningModes IMode, 307 SetOfConstDecls *VisitedCallees); 308 void ActionExprEngine(Decl *D, bool ObjCGCEnabled, 309 ExprEngine::InliningModes IMode, 310 SetOfConstDecls *VisitedCallees); 311 312 /// Visitors for the RecursiveASTVisitor. 313 bool shouldWalkTypesOfTypeLocs() const { return false; } 314 315 /// Handle callbacks for arbitrary Decls. 316 bool VisitDecl(Decl *D) { 317 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode); 318 if (Mode & AM_Syntax) 319 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 320 return true; 321 } 322 323 bool VisitFunctionDecl(FunctionDecl *FD) { 324 IdentifierInfo *II = FD->getIdentifier(); 325 if (II && II->getName().startswith("__inline")) 326 return true; 327 328 // We skip function template definitions, as their semantics is 329 // only determined when they are instantiated. 330 if (FD->isThisDeclarationADefinition() && 331 !FD->isDependentContext()) { 332 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 333 HandleCode(FD, RecVisitorMode); 334 } 335 return true; 336 } 337 338 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 339 if (MD->isThisDeclarationADefinition()) { 340 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 341 HandleCode(MD, RecVisitorMode); 342 } 343 return true; 344 } 345 346 bool VisitBlockDecl(BlockDecl *BD) { 347 if (BD->hasBody()) { 348 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 349 HandleCode(BD, RecVisitorMode); 350 } 351 return true; 352 } 353 354 private: 355 void storeTopLevelDecls(DeclGroupRef DG); 356 357 /// \brief Check if we should skip (not analyze) the given function. 358 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode); 359 360 }; 361 } // end anonymous namespace 362 363 364 //===----------------------------------------------------------------------===// 365 // AnalysisConsumer implementation. 366 //===----------------------------------------------------------------------===// 367 llvm::Timer* AnalysisConsumer::TUTotalTimer = 0; 368 369 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 370 storeTopLevelDecls(DG); 371 return true; 372 } 373 374 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 375 storeTopLevelDecls(DG); 376 } 377 378 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 379 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 380 381 // Skip ObjCMethodDecl, wait for the objc container to avoid 382 // analyzing twice. 383 if (isa<ObjCMethodDecl>(*I)) 384 continue; 385 386 LocalTUDecls.push_back(*I); 387 } 388 } 389 390 static bool shouldSkipFunction(const Decl *D, 391 SetOfConstDecls Visited, 392 SetOfConstDecls VisitedAsTopLevel) { 393 if (VisitedAsTopLevel.count(D)) 394 return true; 395 396 // We want to re-analyse the functions as top level in the following cases: 397 // - The 'init' methods should be reanalyzed because 398 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 399 // 'nil' and unless we analyze the 'init' functions as top level, we will 400 // not catch errors within defensive code. 401 // - We want to reanalyze all ObjC methods as top level to report Retain 402 // Count naming convention errors more aggressively. 403 if (isa<ObjCMethodDecl>(D)) 404 return false; 405 406 // Otherwise, if we visited the function before, do not reanalyze it. 407 return Visited.count(D); 408 } 409 410 ExprEngine::InliningModes 411 AnalysisConsumer::getInliningModeForFunction(const Decl *D, 412 SetOfConstDecls Visited) { 413 ExprEngine::InliningModes HowToInline = 414 (Mgr->shouldInlineCall()) ? ExprEngine::Inline_All : 415 ExprEngine::Inline_None; 416 417 // We want to reanalyze all ObjC methods as top level to report Retain 418 // Count naming convention errors more aggressively. But we can turn off 419 // inlining when reanalyzing an already inlined function. 420 if (Visited.count(D)) { 421 assert(isa<ObjCMethodDecl>(D) && 422 "We are only reanalyzing ObjCMethods."); 423 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D); 424 if (ObjCM->getMethodFamily() != OMF_init) 425 HowToInline = ExprEngine::Inline_None; 426 } 427 428 return HowToInline; 429 } 430 431 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 432 // Build the Call Graph by adding all the top level declarations to the graph. 433 // Note: CallGraph can trigger deserialization of more items from a pch 434 // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 435 // We rely on random access to add the initially processed Decls to CG. 436 CallGraph CG; 437 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 438 CG.addToCallGraph(LocalTUDecls[i]); 439 } 440 441 // Walk over all of the call graph nodes in topological order, so that we 442 // analyze parents before the children. Skip the functions inlined into 443 // the previously processed functions. Use external Visited set to identify 444 // inlined functions. The topological order allows the "do not reanalyze 445 // previously inlined function" performance heuristic to be triggered more 446 // often. 447 SetOfConstDecls Visited; 448 SetOfConstDecls VisitedAsTopLevel; 449 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG); 450 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator 451 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) { 452 NumFunctionTopLevel++; 453 454 CallGraphNode *N = *I; 455 Decl *D = N->getDecl(); 456 457 // Skip the abstract root node. 458 if (!D) 459 continue; 460 461 // Skip the functions which have been processed already or previously 462 // inlined. 463 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel)) 464 continue; 465 466 // Analyze the function. 467 SetOfConstDecls VisitedCallees; 468 469 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited), 470 (Mgr->options.InliningMode == All ? 0 : &VisitedCallees)); 471 472 // Add the visited callees to the global visited set. 473 for (SetOfConstDecls::iterator I = VisitedCallees.begin(), 474 E = VisitedCallees.end(); I != E; ++I) { 475 Visited.insert(*I); 476 } 477 VisitedAsTopLevel.insert(D); 478 } 479 } 480 481 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 482 // Don't run the actions if an error has occurred with parsing the file. 483 DiagnosticsEngine &Diags = PP.getDiagnostics(); 484 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 485 return; 486 487 { 488 if (TUTotalTimer) TUTotalTimer->startTimer(); 489 490 // Introduce a scope to destroy BR before Mgr. 491 BugReporter BR(*Mgr); 492 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 493 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 494 495 // Run the AST-only checks using the order in which functions are defined. 496 // If inlining is not turned on, use the simplest function order for path 497 // sensitive analyzes as well. 498 RecVisitorMode = AM_Syntax; 499 if (!Mgr->shouldInlineCall()) 500 RecVisitorMode |= AM_Path; 501 RecVisitorBR = &BR; 502 503 // Process all the top level declarations. 504 // 505 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 506 // entries. Thus we don't use an iterator, but rely on LocalTUDecls 507 // random access. By doing so, we automatically compensate for iterators 508 // possibly being invalidated, although this is a bit slower. 509 const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 510 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 511 TraverseDecl(LocalTUDecls[i]); 512 } 513 514 if (Mgr->shouldInlineCall()) 515 HandleDeclsCallGraph(LocalTUDeclsSize); 516 517 // After all decls handled, run checkers on the entire TranslationUnit. 518 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 519 520 RecVisitorBR = 0; 521 } 522 523 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 524 // FIXME: This should be replaced with something that doesn't rely on 525 // side-effects in PathDiagnosticConsumer's destructor. This is required when 526 // used with option -disable-free. 527 Mgr.reset(NULL); 528 529 if (TUTotalTimer) TUTotalTimer->stopTimer(); 530 531 // Count how many basic blocks we have not covered. 532 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 533 if (NumBlocksInAnalyzedFunctions > 0) 534 PercentReachableBlocks = 535 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 536 NumBlocksInAnalyzedFunctions; 537 538 } 539 540 static std::string getFunctionName(const Decl *D) { 541 if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { 542 return ID->getSelector().getAsString(); 543 } 544 if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) { 545 IdentifierInfo *II = ND->getIdentifier(); 546 if (II) 547 return II->getName(); 548 } 549 return ""; 550 } 551 552 AnalysisConsumer::AnalysisMode 553 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) { 554 if (!Opts->AnalyzeSpecificFunction.empty() && 555 getFunctionName(D) != Opts->AnalyzeSpecificFunction) 556 return AM_None; 557 558 // Unless -analyze-all is specified, treat decls differently depending on 559 // where they came from: 560 // - Main source file: run both path-sensitive and non-path-sensitive checks. 561 // - Header files: run non-path-sensitive checks only. 562 // - System headers: don't run any checks. 563 SourceManager &SM = Ctx->getSourceManager(); 564 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 565 if (!Opts->AnalyzeAll && !SM.isFromMainFile(SL)) { 566 if (SL.isInvalid() || SM.isInSystemHeader(SL)) 567 return AM_None; 568 return Mode & ~AM_Path; 569 } 570 571 return Mode; 572 } 573 574 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 575 ExprEngine::InliningModes IMode, 576 SetOfConstDecls *VisitedCallees) { 577 if (!D->hasBody()) 578 return; 579 Mode = getModeForDecl(D, Mode); 580 if (Mode == AM_None) 581 return; 582 583 DisplayFunction(D, Mode, IMode); 584 CFG *DeclCFG = Mgr->getCFG(D); 585 if (DeclCFG) { 586 unsigned CFGSize = DeclCFG->size(); 587 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize; 588 } 589 590 // Clear the AnalysisManager of old AnalysisDeclContexts. 591 Mgr->ClearContexts(); 592 BugReporter BR(*Mgr); 593 594 if (Mode & AM_Syntax) 595 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR); 596 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) { 597 RunPathSensitiveChecks(D, IMode, VisitedCallees); 598 if (IMode != ExprEngine::Inline_None) 599 NumFunctionsAnalyzed++; 600 } 601 } 602 603 //===----------------------------------------------------------------------===// 604 // Path-sensitive checking. 605 //===----------------------------------------------------------------------===// 606 607 void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled, 608 ExprEngine::InliningModes IMode, 609 SetOfConstDecls *VisitedCallees) { 610 // Construct the analysis engine. First check if the CFG is valid. 611 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 612 if (!Mgr->getCFG(D)) 613 return; 614 615 // See if the LiveVariables analysis scales. 616 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 617 return; 618 619 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode); 620 621 // Set the graph auditor. 622 OwningPtr<ExplodedNode::Auditor> Auditor; 623 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) { 624 Auditor.reset(CreateUbiViz()); 625 ExplodedNode::SetAuditor(Auditor.get()); 626 } 627 628 // Execute the worklist algorithm. 629 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 630 Mgr->options.getMaxNodesPerTopLevelFunction()); 631 632 // Release the auditor (if any) so that it doesn't monitor the graph 633 // created BugReporter. 634 ExplodedNode::SetAuditor(0); 635 636 // Visualize the exploded graph. 637 if (Mgr->options.visualizeExplodedGraphWithGraphViz) 638 Eng.ViewGraph(Mgr->options.TrimGraph); 639 640 // Display warnings. 641 Eng.getBugReporter().FlushReports(); 642 } 643 644 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 645 ExprEngine::InliningModes IMode, 646 SetOfConstDecls *Visited) { 647 648 switch (Mgr->getLangOpts().getGC()) { 649 case LangOptions::NonGC: 650 ActionExprEngine(D, false, IMode, Visited); 651 break; 652 653 case LangOptions::GCOnly: 654 ActionExprEngine(D, true, IMode, Visited); 655 break; 656 657 case LangOptions::HybridGC: 658 ActionExprEngine(D, false, IMode, Visited); 659 ActionExprEngine(D, true, IMode, Visited); 660 break; 661 } 662 } 663 664 //===----------------------------------------------------------------------===// 665 // AnalysisConsumer creation. 666 //===----------------------------------------------------------------------===// 667 668 ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 669 const std::string& outDir, 670 AnalyzerOptionsRef opts, 671 ArrayRef<std::string> plugins) { 672 // Disable the effects of '-Werror' when using the AnalysisConsumer. 673 pp.getDiagnostics().setWarningsAsErrors(false); 674 675 return new AnalysisConsumer(pp, outDir, opts, plugins); 676 } 677 678 //===----------------------------------------------------------------------===// 679 // Ubigraph Visualization. FIXME: Move to separate file. 680 //===----------------------------------------------------------------------===// 681 682 namespace { 683 684 class UbigraphViz : public ExplodedNode::Auditor { 685 OwningPtr<raw_ostream> Out; 686 llvm::sys::Path Dir, Filename; 687 unsigned Cntr; 688 689 typedef llvm::DenseMap<void*,unsigned> VMap; 690 VMap M; 691 692 public: 693 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 694 llvm::sys::Path& filename); 695 696 ~UbigraphViz(); 697 698 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 699 }; 700 701 } // end anonymous namespace 702 703 static ExplodedNode::Auditor* CreateUbiViz() { 704 std::string ErrMsg; 705 706 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg); 707 if (!ErrMsg.empty()) 708 return 0; 709 710 llvm::sys::Path Filename = Dir; 711 Filename.appendComponent("llvm_ubi"); 712 Filename.makeUnique(true,&ErrMsg); 713 714 if (!ErrMsg.empty()) 715 return 0; 716 717 llvm::errs() << "Writing '" << Filename.str() << "'.\n"; 718 719 OwningPtr<llvm::raw_fd_ostream> Stream; 720 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg)); 721 722 if (!ErrMsg.empty()) 723 return 0; 724 725 return new UbigraphViz(Stream.take(), Dir, Filename); 726 } 727 728 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 729 730 assert (Src != Dst && "Self-edges are not allowed."); 731 732 // Lookup the Src. If it is a new node, it's a root. 733 VMap::iterator SrcI= M.find(Src); 734 unsigned SrcID; 735 736 if (SrcI == M.end()) { 737 M[Src] = SrcID = Cntr++; 738 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 739 } 740 else 741 SrcID = SrcI->second; 742 743 // Lookup the Dst. 744 VMap::iterator DstI= M.find(Dst); 745 unsigned DstID; 746 747 if (DstI == M.end()) { 748 M[Dst] = DstID = Cntr++; 749 *Out << "('vertex', " << DstID << ")\n"; 750 } 751 else { 752 // We have hit DstID before. Change its style to reflect a cache hit. 753 DstID = DstI->second; 754 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 755 } 756 757 // Add the edge. 758 *Out << "('edge', " << SrcID << ", " << DstID 759 << ", ('arrow','true'), ('oriented', 'true'))\n"; 760 } 761 762 UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir, 763 llvm::sys::Path& filename) 764 : Out(out), Dir(dir), Filename(filename), Cntr(0) { 765 766 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 767 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 768 " ('size', '1.5'))\n"; 769 } 770 771 UbigraphViz::~UbigraphViz() { 772 Out.reset(0); 773 llvm::errs() << "Running 'ubiviz' program... "; 774 std::string ErrMsg; 775 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz"); 776 std::vector<const char*> args; 777 args.push_back(Ubiviz.c_str()); 778 args.push_back(Filename.c_str()); 779 args.push_back(0); 780 781 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) { 782 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 783 } 784 785 // Delete the directory. 786 Dir.eraseFromDisk(true); 787 } 788