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