1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // "Meta" ASTConsumer for running different source analyses.
11 //===----------------------------------------------------------------------===//
13 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
14 #include "ModelInjector.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/Analysis/Analyses/LiveVariables.h"
20 #include "clang/Analysis/CFG.h"
21 #include "clang/Analysis/CallGraph.h"
22 #include "clang/Analysis/CodeInjector.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/CrossTU/CrossTranslationUnit.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"
47 using namespace clang;
50 #define DEBUG_TYPE "AnalysisConsumer"
52 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
53 STATISTIC(NumFunctionsAnalyzed,
54 "The # of functions and blocks analyzed (as top level "
55 "with inlining turned on).");
56 STATISTIC(NumBlocksInAnalyzedFunctions,
57 "The # of basic blocks in the analyzed functions.");
58 STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
59 "The # of visited 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.");
63 //===----------------------------------------------------------------------===//
64 // Special PathDiagnosticConsumers.
65 //===----------------------------------------------------------------------===//
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 createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
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");
84 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
85 DiagnosticsEngine &Diag;
86 bool IncludePath, ShouldEmitAsError;
89 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
90 : Diag(Diag), IncludePath(false), ShouldEmitAsError(false) {}
91 ~ClangDiagPathDiagConsumer() override {}
92 StringRef getName() const override { return "ClangDiags"; }
94 bool supportsLogicalOpControlFlow() const override { return true; }
95 bool supportsCrossFileDiagnostics() const override { return true; }
97 PathGenerationScheme getGenerationScheme() const override {
98 return IncludePath ? Minimal : None;
105 void enableWerror() { ShouldEmitAsError = true; }
107 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
108 FilesMade *filesMade) override {
111 ? Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0")
112 : Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
113 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
115 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
116 E = Diags.end(); I != E; ++I) {
117 const PathDiagnostic *PD = *I;
118 SourceLocation WarnLoc = PD->getLocation().asLocation();
119 Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
120 << PD->path.back()->getRanges();
122 // First, add extra notes, even if paths should not be included.
123 for (const auto &Piece : PD->path) {
124 if (!isa<PathDiagnosticNotePiece>(Piece.get()))
127 SourceLocation NoteLoc = Piece->getLocation().asLocation();
128 Diag.Report(NoteLoc, NoteID) << Piece->getString()
129 << Piece->getRanges();
135 // Then, add the path notes if necessary.
136 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
137 for (const auto &Piece : FlatPath) {
138 if (isa<PathDiagnosticNotePiece>(Piece.get()))
141 SourceLocation NoteLoc = Piece->getLocation().asLocation();
142 Diag.Report(NoteLoc, NoteID) << Piece->getString()
143 << Piece->getRanges();
148 } // end anonymous namespace
150 //===----------------------------------------------------------------------===//
151 // AnalysisConsumer declaration.
152 //===----------------------------------------------------------------------===//
156 class AnalysisConsumer : public AnalysisASTConsumer,
157 public RecursiveASTVisitor<AnalysisConsumer> {
163 typedef unsigned AnalysisMode;
165 /// Mode of the analyzes while recursively visiting Decls.
166 AnalysisMode RecVisitorMode;
167 /// Bug Reporter to use while recursively visiting Decls.
168 BugReporter *RecVisitorBR;
170 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
174 const Preprocessor &PP;
175 const std::string OutDir;
176 AnalyzerOptionsRef Opts;
177 ArrayRef<std::string> Plugins;
178 CodeInjector *Injector;
179 cross_tu::CrossTranslationUnitContext CTU;
181 /// Stores the declarations from the local translation unit.
182 /// Note, we pre-compute the local declarations at parse time as an
183 /// optimization to make sure we do not deserialize everything from disk.
184 /// The local declaration to all declarations ratio might be very small when
185 /// working with a PCH file.
186 SetOfDecls LocalTUDecls;
188 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
189 PathDiagnosticConsumers PathConsumers;
191 StoreManagerCreator CreateStoreMgr;
192 ConstraintManagerCreator CreateConstraintMgr;
194 std::unique_ptr<CheckerManager> checkerMgr;
195 std::unique_ptr<AnalysisManager> Mgr;
197 /// Time the analyzes time of each translation unit.
198 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
199 std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
200 std::unique_ptr<llvm::Timer> ExprEngineTimer;
201 std::unique_ptr<llvm::Timer> BugReporterTimer;
203 /// The information about analyzed functions shared throughout the
204 /// translation unit.
205 FunctionSummariesTy FunctionSummaries;
207 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
208 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
209 CodeInjector *injector)
210 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
211 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
212 Plugins(plugins), Injector(injector), CTU(CI) {
213 DigestAnalyzerOptions();
214 if (Opts->PrintStats || Opts->ShouldSerializeStats) {
215 AnalyzerTimers = llvm::make_unique<llvm::TimerGroup>(
216 "analyzer", "Analyzer timers");
217 SyntaxCheckTimer = llvm::make_unique<llvm::Timer>(
218 "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);
219 ExprEngineTimer = llvm::make_unique<llvm::Timer>(
220 "exprengine", "Path exploration time", *AnalyzerTimers);
221 BugReporterTimer = llvm::make_unique<llvm::Timer>(
222 "bugreporter", "Path-sensitive report post-processing time",
224 llvm::EnableStatistics(/* PrintOnExit= */ false);
228 ~AnalysisConsumer() override {
229 if (Opts->PrintStats) {
230 llvm::PrintStatistics();
234 void DigestAnalyzerOptions() {
235 if (Opts->AnalysisDiagOpt != PD_NONE) {
236 // Create the PathDiagnosticConsumer.
237 ClangDiagPathDiagConsumer *clangDiags =
238 new ClangDiagPathDiagConsumer(PP.getDiagnostics());
239 PathConsumers.push_back(clangDiags);
241 if (Opts->AnalyzerWerror)
242 clangDiags->enableWerror();
244 if (Opts->AnalysisDiagOpt == PD_TEXT) {
245 clangDiags->enablePaths();
247 } else if (!OutDir.empty()) {
248 switch (Opts->AnalysisDiagOpt) {
250 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
252 CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \
254 #include "clang/StaticAnalyzer/Core/Analyses.def"
259 // Create the analyzer component creators.
260 switch (Opts->AnalysisStoreOpt) {
262 llvm_unreachable("Unknown store manager.");
263 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
264 case NAME##Model: CreateStoreMgr = CREATEFN; break;
265 #include "clang/StaticAnalyzer/Core/Analyses.def"
268 switch (Opts->AnalysisConstraintsOpt) {
270 llvm_unreachable("Unknown constraint manager.");
271 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
272 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
273 #include "clang/StaticAnalyzer/Core/Analyses.def"
277 void DisplayFunction(const Decl *D, AnalysisMode Mode,
278 ExprEngine::InliningModes IMode) {
279 if (!Opts->AnalyzerDisplayProgress)
282 SourceManager &SM = Mgr->getASTContext().getSourceManager();
283 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
285 llvm::errs() << "ANALYZE";
287 if (Mode == AM_Syntax)
288 llvm::errs() << " (Syntax)";
289 else if (Mode == AM_Path) {
290 llvm::errs() << " (Path, ";
292 case ExprEngine::Inline_Minimal:
293 llvm::errs() << " Inline_Minimal";
295 case ExprEngine::Inline_Regular:
296 llvm::errs() << " Inline_Regular";
302 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
304 llvm::errs() << ": " << Loc.getFilename() << ' '
305 << getFunctionName(D) << '\n';
309 void Initialize(ASTContext &Context) override {
311 checkerMgr = createCheckerManager(
312 *Ctx, *Opts, Plugins, CheckerRegistrationFns, PP.getDiagnostics());
314 Mgr = llvm::make_unique<AnalysisManager>(
315 *Ctx, PP.getDiagnostics(), PathConsumers, CreateStoreMgr,
316 CreateConstraintMgr, checkerMgr.get(), *Opts, Injector);
319 /// Store the top level decls in the set to be processed later on.
320 /// (Doing this pre-processing avoids deserialization of data from PCH.)
321 bool HandleTopLevelDecl(DeclGroupRef D) override;
322 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
324 void HandleTranslationUnit(ASTContext &C) override;
326 /// Determine which inlining mode should be used when this function is
327 /// analyzed. This allows to redefine the default inlining policies when
328 /// analyzing a given function.
329 ExprEngine::InliningModes
330 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
332 /// Build the call graph for all the top level decls of this TU and
333 /// use it to define the order in which the functions should be visited.
334 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
336 /// Run analyzes(syntax or path sensitive) on the given function.
337 /// \param Mode - determines if we are requesting syntax only or path
338 /// sensitive only analysis.
339 /// \param VisitedCallees - The output parameter, which is populated with the
340 /// set of functions which should be considered analyzed after analyzing the
341 /// given root function.
342 void HandleCode(Decl *D, AnalysisMode Mode,
343 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
344 SetOfConstDecls *VisitedCallees = nullptr);
346 void RunPathSensitiveChecks(Decl *D,
347 ExprEngine::InliningModes IMode,
348 SetOfConstDecls *VisitedCallees);
350 /// Visitors for the RecursiveASTVisitor.
351 bool shouldWalkTypesOfTypeLocs() const { return false; }
353 /// Handle callbacks for arbitrary Decls.
354 bool VisitDecl(Decl *D) {
355 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
356 if (Mode & AM_Syntax) {
357 if (SyntaxCheckTimer)
358 SyntaxCheckTimer->startTimer();
359 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
360 if (SyntaxCheckTimer)
361 SyntaxCheckTimer->stopTimer();
366 bool VisitVarDecl(VarDecl *VD) {
367 if (!Opts->IsNaiveCTUEnabled)
370 if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
371 if (!cross_tu::containsConst(VD, *Ctx))
374 // Cannot be initialized in another TU.
378 if (VD->getAnyInitializer())
381 llvm::Expected<const VarDecl *> CTUDeclOrError =
382 CTU.getCrossTUDefinition(VD, Opts->CTUDir, Opts->CTUIndexName,
383 Opts->DisplayCTUProgress);
385 if (!CTUDeclOrError) {
386 handleAllErrors(CTUDeclOrError.takeError(),
387 [&](const cross_tu::IndexError &IE) {
388 CTU.emitCrossTUDiagnostics(IE);
395 bool VisitFunctionDecl(FunctionDecl *FD) {
396 IdentifierInfo *II = FD->getIdentifier();
397 if (II && II->getName().startswith("__inline"))
400 // We skip function template definitions, as their semantics is
401 // only determined when they are instantiated.
402 if (FD->isThisDeclarationADefinition() &&
403 !FD->isDependentContext()) {
404 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
405 HandleCode(FD, RecVisitorMode);
410 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
411 if (MD->isThisDeclarationADefinition()) {
412 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
413 HandleCode(MD, RecVisitorMode);
418 bool VisitBlockDecl(BlockDecl *BD) {
420 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
421 // Since we skip function template definitions, we should skip blocks
422 // declared in those functions as well.
423 if (!BD->isDependentContext()) {
424 HandleCode(BD, RecVisitorMode);
430 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
431 PathConsumers.push_back(Consumer);
434 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
435 CheckerRegistrationFns.push_back(std::move(Fn));
439 void storeTopLevelDecls(DeclGroupRef DG);
440 std::string getFunctionName(const Decl *D);
442 /// Check if we should skip (not analyze) the given function.
443 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
444 void runAnalysisOnTranslationUnit(ASTContext &C);
446 /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
447 void reportAnalyzerProgress(StringRef S);
449 } // end anonymous namespace
452 //===----------------------------------------------------------------------===//
453 // AnalysisConsumer implementation.
454 //===----------------------------------------------------------------------===//
455 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
456 storeTopLevelDecls(DG);
460 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
461 storeTopLevelDecls(DG);
464 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
465 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
467 // Skip ObjCMethodDecl, wait for the objc container to avoid
469 if (isa<ObjCMethodDecl>(*I))
472 LocalTUDecls.push_back(*I);
476 static bool shouldSkipFunction(const Decl *D,
477 const SetOfConstDecls &Visited,
478 const SetOfConstDecls &VisitedAsTopLevel) {
479 if (VisitedAsTopLevel.count(D))
482 // We want to re-analyse the functions as top level in the following cases:
483 // - The 'init' methods should be reanalyzed because
484 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
485 // 'nil' and unless we analyze the 'init' functions as top level, we will
486 // not catch errors within defensive code.
487 // - We want to reanalyze all ObjC methods as top level to report Retain
488 // Count naming convention errors more aggressively.
489 if (isa<ObjCMethodDecl>(D))
491 // We also want to reanalyze all C++ copy and move assignment operators to
492 // separately check the two cases where 'this' aliases with the parameter and
493 // where it may not. (cplusplus.SelfAssignmentChecker)
494 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
495 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
499 // Otherwise, if we visited the function before, do not reanalyze it.
500 return Visited.count(D);
503 ExprEngine::InliningModes
504 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
505 const SetOfConstDecls &Visited) {
506 // We want to reanalyze all ObjC methods as top level to report Retain
507 // Count naming convention errors more aggressively. But we should tune down
508 // inlining when reanalyzing an already inlined function.
509 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
510 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
511 if (ObjCM->getMethodFamily() != OMF_init)
512 return ExprEngine::Inline_Minimal;
515 return ExprEngine::Inline_Regular;
518 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
519 // Build the Call Graph by adding all the top level declarations to the graph.
520 // Note: CallGraph can trigger deserialization of more items from a pch
521 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
522 // We rely on random access to add the initially processed Decls to CG.
524 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
525 CG.addToCallGraph(LocalTUDecls[i]);
528 // Walk over all of the call graph nodes in topological order, so that we
529 // analyze parents before the children. Skip the functions inlined into
530 // the previously processed functions. Use external Visited set to identify
531 // inlined functions. The topological order allows the "do not reanalyze
532 // previously inlined function" performance heuristic to be triggered more
534 SetOfConstDecls Visited;
535 SetOfConstDecls VisitedAsTopLevel;
536 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
537 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
538 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
539 NumFunctionTopLevel++;
541 CallGraphNode *N = *I;
542 Decl *D = N->getDecl();
544 // Skip the abstract root node.
548 // Skip the functions which have been processed already or previously
550 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
553 // Analyze the function.
554 SetOfConstDecls VisitedCallees;
556 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
557 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
559 // Add the visited callees to the global visited set.
560 for (const Decl *Callee : VisitedCallees)
561 // Decls from CallGraph are already canonical. But Decls coming from
562 // CallExprs may be not. We should canonicalize them manually.
563 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
564 : Callee->getCanonicalDecl());
565 VisitedAsTopLevel.insert(D);
569 static bool isBisonFile(ASTContext &C) {
570 const SourceManager &SM = C.getSourceManager();
571 FileID FID = SM.getMainFileID();
572 StringRef Buffer = SM.getBuffer(FID)->getBuffer();
573 if (Buffer.startswith("/* A Bison parser, made by"))
578 void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
579 BugReporter BR(*Mgr);
580 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
581 if (SyntaxCheckTimer)
582 SyntaxCheckTimer->startTimer();
583 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
584 if (SyntaxCheckTimer)
585 SyntaxCheckTimer->stopTimer();
587 // Run the AST-only checks using the order in which functions are defined.
588 // If inlining is not turned on, use the simplest function order for path
589 // sensitive analyzes as well.
590 RecVisitorMode = AM_Syntax;
591 if (!Mgr->shouldInlineCall())
592 RecVisitorMode |= AM_Path;
595 // Process all the top level declarations.
597 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
598 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
599 // random access. By doing so, we automatically compensate for iterators
600 // possibly being invalidated, although this is a bit slower.
601 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
602 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
603 TraverseDecl(LocalTUDecls[i]);
606 if (Mgr->shouldInlineCall())
607 HandleDeclsCallGraph(LocalTUDeclsSize);
609 // After all decls handled, run checkers on the entire TranslationUnit.
610 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
612 RecVisitorBR = nullptr;
615 void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
616 if (Opts->AnalyzerDisplayProgress)
620 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
622 // Don't run the actions if an error has occurred with parsing the file.
623 DiagnosticsEngine &Diags = PP.getDiagnostics();
624 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
627 if (isBisonFile(C)) {
628 reportAnalyzerProgress("Skipping bison-generated file\n");
629 } else if (Opts->DisableAllChecks) {
631 // Don't analyze if the user explicitly asked for no checks to be performed
633 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
635 // Otherwise, just run the analysis.
636 runAnalysisOnTranslationUnit(C);
639 // Count how many basic blocks we have not covered.
640 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
641 NumVisitedBlocksInAnalyzedFunctions =
642 FunctionSummaries.getTotalNumVisitedBasicBlocks();
643 if (NumBlocksInAnalyzedFunctions > 0)
644 PercentReachableBlocks =
645 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
646 NumBlocksInAnalyzedFunctions;
648 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
649 // FIXME: This should be replaced with something that doesn't rely on
650 // side-effects in PathDiagnosticConsumer's destructor. This is required when
651 // used with option -disable-free.
655 std::string AnalysisConsumer::getFunctionName(const Decl *D) {
657 llvm::raw_string_ostream OS(Str);
659 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
660 OS << FD->getQualifiedNameAsString();
662 // In C++, there are overloads.
663 if (Ctx->getLangOpts().CPlusPlus) {
665 for (const auto &P : FD->parameters()) {
666 if (P != *FD->param_begin())
668 OS << P->getType().getAsString();
673 } else if (isa<BlockDecl>(D)) {
674 PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
677 OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
681 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
683 // FIXME: copy-pasted from CGDebugInfo.cpp.
684 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
685 const DeclContext *DC = OMD->getDeclContext();
686 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
687 OS << OID->getName();
688 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
689 OS << OID->getName();
690 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
691 if (OC->IsClassExtension()) {
692 OS << OC->getClassInterface()->getName();
694 OS << OC->getIdentifier()->getNameStart() << '('
695 << OC->getIdentifier()->getNameStart() << ')';
697 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
698 OS << OCD->getClassInterface()->getName() << '('
699 << OCD->getName() << ')';
700 } else if (isa<ObjCProtocolDecl>(DC)) {
701 // We can extract the type of the class from the self pointer.
702 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
704 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
705 ClassTy.print(OS, PrintingPolicy(LangOptions()));
708 OS << ' ' << OMD->getSelector().getAsString() << ']';
715 AnalysisConsumer::AnalysisMode
716 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
717 if (!Opts->AnalyzeSpecificFunction.empty() &&
718 getFunctionName(D) != Opts->AnalyzeSpecificFunction)
721 // Unless -analyze-all is specified, treat decls differently depending on
722 // where they came from:
723 // - Main source file: run both path-sensitive and non-path-sensitive checks.
724 // - Header files: run non-path-sensitive checks only.
725 // - System headers: don't run any checks.
726 SourceManager &SM = Ctx->getSourceManager();
727 const Stmt *Body = D->getBody();
728 SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
729 SL = SM.getExpansionLoc(SL);
731 if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
732 if (SL.isInvalid() || SM.isInSystemHeader(SL))
734 return Mode & ~AM_Path;
740 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
741 ExprEngine::InliningModes IMode,
742 SetOfConstDecls *VisitedCallees) {
745 Mode = getModeForDecl(D, Mode);
749 // Clear the AnalysisManager of old AnalysisDeclContexts.
750 Mgr->ClearContexts();
751 // Ignore autosynthesized code.
752 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
755 DisplayFunction(D, Mode, IMode);
756 CFG *DeclCFG = Mgr->getCFG(D);
758 MaxCFGSize.updateMax(DeclCFG->size());
760 BugReporter BR(*Mgr);
762 if (Mode & AM_Syntax) {
763 if (SyntaxCheckTimer)
764 SyntaxCheckTimer->startTimer();
765 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
766 if (SyntaxCheckTimer)
767 SyntaxCheckTimer->stopTimer();
769 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
770 RunPathSensitiveChecks(D, IMode, VisitedCallees);
771 if (IMode != ExprEngine::Inline_Minimal)
772 NumFunctionsAnalyzed++;
776 //===----------------------------------------------------------------------===//
777 // Path-sensitive checking.
778 //===----------------------------------------------------------------------===//
780 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
781 ExprEngine::InliningModes IMode,
782 SetOfConstDecls *VisitedCallees) {
783 // Construct the analysis engine. First check if the CFG is valid.
784 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
788 // See if the LiveVariables analysis scales.
789 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
792 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
794 // Execute the worklist algorithm.
796 ExprEngineTimer->startTimer();
797 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
798 Mgr->options.MaxNodesPerTopLevelFunction);
800 ExprEngineTimer->stopTimer();
802 if (!Mgr->options.DumpExplodedGraphTo.empty())
803 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
805 // Visualize the exploded graph.
806 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
807 Eng.ViewGraph(Mgr->options.TrimGraph);
810 if (BugReporterTimer)
811 BugReporterTimer->startTimer();
812 Eng.getBugReporter().FlushReports();
813 if (BugReporterTimer)
814 BugReporterTimer->stopTimer();
817 //===----------------------------------------------------------------------===//
818 // AnalysisConsumer creation.
819 //===----------------------------------------------------------------------===//
821 std::unique_ptr<AnalysisASTConsumer>
822 ento::CreateAnalysisConsumer(CompilerInstance &CI) {
823 // Disable the effects of '-Werror' when using the AnalysisConsumer.
824 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
826 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
827 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
829 return llvm::make_unique<AnalysisConsumer>(
830 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
831 CI.getFrontendOpts().Plugins,
832 hasModelPath ? new ModelInjector(CI) : nullptr);