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