37#include "llvm/ADT/PostOrderIterator.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/Support/TimeProfiler.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/Support/raw_ostream.h"
49#define DEBUG_TYPE "AnalysisConsumer"
51STAT_COUNTER(NumFunctionTopLevel,
"The # of functions at top level.");
53 "The # of functions and blocks analyzed (as top level "
54 "with inlining turned on).");
56 NumFunctionsAnalyzedSyntaxOnly,
57 "The # of functions analyzed by syntax checkers only.");
59 "The # of basic blocks in the analyzed functions.");
61 NumVisitedBlocksInAnalyzedFunctions,
62 "The # of visited basic blocks in the analyzed functions.");
64 "The % of reachable basic blocks.");
66 "The maximum number of basic blocks in a function.");
78 : Input.
getBuffer().getBufferIdentifier();
90 typedef unsigned AnalysisMode;
93 AnalysisMode RecVisitorMode;
95 BugReporter *RecVisitorBR;
97 std::vector<
std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
102 const std::string OutDir;
103 AnalyzerOptions &Opts;
104 ArrayRef<std::string> Plugins;
105 std::unique_ptr<CodeInjector> Injector;
106 cross_tu::CrossTranslationUnitContext CTU;
115 MacroExpansionContext MacroExpansions;
123 std::unique_ptr<CheckerManager> checkerMgr;
124 std::unique_ptr<AnalysisManager> Mgr;
127 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
128 std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
129 std::unique_ptr<llvm::Timer> ExprEngineTimer;
130 std::unique_ptr<llvm::Timer> BugReporterTimer;
134 FunctionSummariesTy FunctionSummaries;
136 AnalysisConsumer(CompilerInstance &CI,
const std::string &outdir,
137 AnalyzerOptions &opts, ArrayRef<std::string> plugins,
138 std::unique_ptr<CodeInjector> injector)
140 PP(CI.getPreprocessor()), OutDir(outdir), Opts(opts), Plugins(plugins),
141 Injector(std::move(injector)), CTU(CI),
142 MacroExpansions(CI.getLangOpts()) {
146 DigestAnalyzerOptions();
148 if (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||
149 Opts.ShouldSerializeStats || !Opts.DumpEntryPointStatsToCSV.empty()) {
150 AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
151 "analyzer",
"Analyzer timers",
153 (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||
154 Opts.ShouldSerializeStats));
155 SyntaxCheckTimer = std::make_unique<llvm::Timer>(
156 "syntaxchecks",
"Syntax-based analysis time", *AnalyzerTimers);
157 ExprEngineTimer = std::make_unique<llvm::Timer>(
158 "exprengine",
"Path exploration time", *AnalyzerTimers);
159 BugReporterTimer = std::make_unique<llvm::Timer>(
160 "bugreporter",
"Path-sensitive report post-processing time",
164 if (Opts.PrintStats || Opts.ShouldSerializeStats) {
165 llvm::EnableStatistics(
false);
168 if (Opts.ShouldDisplayMacroExpansions)
169 MacroExpansions.registerForPreprocessor(PP);
172 ShouldWalkTypesOfTypeLocs =
false;
175 ~AnalysisConsumer()
override {
176 if (Opts.PrintStats) {
177 llvm::PrintStatistics();
181 void DigestAnalyzerOptions() {
182 switch (Opts.AnalysisDiagOpt) {
185#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
187 CREATEFN(Opts.getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
190#include "clang/StaticAnalyzer/Core/Analyses.def"
192 llvm_unreachable(
"Unknown analyzer output type!");
198 switch (Opts.AnalysisConstraintsOpt) {
200 llvm_unreachable(
"Unknown constraint manager.");
201#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
202 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
203#include "clang/StaticAnalyzer/Core/Analyses.def"
207 void DisplayTime(llvm::TimeRecord &Time) {
208 if (!Opts.AnalyzerDisplayProgress) {
211 llvm::errs() <<
" : " << llvm::format(
"%1.1f", Time.getWallTime() * 1000)
215 void DisplayFunction(
const Decl *D, AnalysisMode Mode,
217 if (!Opts.AnalyzerDisplayProgress)
220 SourceManager &
SM = Mgr->getASTContext().getSourceManager();
223 llvm::errs() <<
"ANALYZE";
225 if (Mode == AM_Syntax)
226 llvm::errs() <<
" (Syntax)";
227 else if (Mode == AM_Path) {
228 llvm::errs() <<
" (Path, ";
231 llvm::errs() <<
" Inline_Minimal";
234 llvm::errs() <<
" Inline_Regular";
239 assert(Mode == (AM_Syntax | AM_Path) &&
"Unexpected mode!");
248 bool HandleTopLevelDecl(DeclGroupRef D)
override;
249 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D)
override;
251 void HandleTranslationUnit(ASTContext &
C)
override;
257 getInliningModeForFunction(
const Decl *D,
const SetOfConstDecls &Visited);
261 void HandleDeclsCallGraph(
const unsigned LocalTUDeclsSize);
269 void HandleCode(Decl *D, AnalysisMode Mode,
273 void RunPathSensitiveChecks(Decl *D,
278 bool VisitDecl(Decl *D)
override {
279 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
280 if (Mode & AM_Syntax) {
281 if (SyntaxCheckTimer)
282 SyntaxCheckTimer->startTimer();
283 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
284 if (SyntaxCheckTimer)
285 SyntaxCheckTimer->stopTimer();
290 bool VisitVarDecl(VarDecl *VD)
override {
291 if (!Opts.IsNaiveCTUEnabled)
305 llvm::Expected<const VarDecl *> CTUDeclOrError =
306 CTU.getCrossTUDefinition(VD, Opts.CTUDir, Opts.CTUIndexName,
307 Opts.DisplayCTUProgress);
309 if (!CTUDeclOrError) {
310 handleAllErrors(CTUDeclOrError.takeError(),
311 [&](
const cross_tu::IndexError &IE) {
312 CTU.emitCrossTUDiagnostics(IE);
319 bool VisitFunctionDecl(FunctionDecl *FD)
override {
321 if (II && II->
getName().starts_with(
"__inline"))
328 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
329 HandleCode(FD, RecVisitorMode);
334 bool VisitObjCMethodDecl(ObjCMethodDecl *MD)
override {
336 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
337 HandleCode(MD, RecVisitorMode);
342 bool VisitBlockDecl(BlockDecl *BD)
override {
344 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
348 HandleCode(BD, RecVisitorMode);
354 void AddDiagnosticConsumer(
355 std::unique_ptr<PathDiagnosticConsumer> Consumer)
override {
356 PathConsumers.push_back(std::move(Consumer));
359 void AddCheckerRegistrationFn(
std::function<
void(CheckerRegistry&)> Fn)
override {
360 CheckerRegistrationFns.push_back(std::move(Fn));
364 void storeTopLevelDecls(DeclGroupRef DG);
367 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
368 void runAnalysisOnTranslationUnit(ASTContext &
C);
371 void reportAnalyzerProgress(StringRef S);
374std::string timeTraceScopeDeclName(StringRef FunName,
const Decl *D) {
375 if (llvm::timeTraceProfilerEnabled()) {
376 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(D))
377 return (FunName +
" " + ND->getQualifiedNameAsString()).str();
378 return (FunName +
" <anonymous> ").str();
383llvm::TimeTraceMetadata timeTraceScopeDeclMetadata(
const Decl *D) {
385 assert(llvm::timeTraceProfilerEnabled());
389 return llvm::TimeTraceMetadata{
390 std::move(DeclName),
SM.getFilename(
Loc).str(),
391 static_cast<int>(
SM.getExpansionLineNumber(
Loc))};
393 return llvm::TimeTraceMetadata{
"",
""};
396void flushReports(llvm::Timer *BugReporterTimer,
BugReporter &BR) {
397 llvm::TimeTraceScope TCS{
"Flushing reports"};
399 if (BugReporterTimer)
400 BugReporterTimer->startTimer();
402 if (BugReporterTimer)
403 BugReporterTimer->stopTimer();
410bool AnalysisConsumer::HandleTopLevelDecl(
DeclGroupRef DG) {
411 storeTopLevelDecls(DG);
415void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
416 storeTopLevelDecls(DG);
419void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
427 LocalTUDecls.push_back(I);
434 if (VisitedAsTopLevel.count(D))
440 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
441 if (CD->isInheritingConstructor())
456 if (
const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
457 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
462 return Visited.count(D);
466AnalysisConsumer::getInliningModeForFunction(
const Decl *D,
480void AnalysisConsumer::HandleDeclsCallGraph(
const unsigned LocalTUDeclsSize) {
486 for (
unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
498 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
499 for (
auto &N : RPOT) {
500 NumFunctionTopLevel++;
502 Decl *D = N->getDecl();
517 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
528 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
529 (Mgr->options.InliningMode ==
All ?
nullptr : &VisitedCallees));
532 for (
const Decl *Callee : VisitedCallees)
536 :
Callee->getCanonicalDecl());
537 VisitedAsTopLevel.insert(D);
544 StringRef Buffer =
SM.getBufferOrFake(FID).getBuffer();
545 return Buffer.contains(Substring);
550 llvm::errs() <<
"Every top-level function was skipped.\n";
553 llvm::errs() <<
"Pass the -analyzer-display-progress for tracking which "
554 "functions are analyzed.\n";
561 <<
"For analyzing C++ code you need to pass the function parameter "
562 "list: -analyze-function=\"foobar(int, _Bool)\"\n";
563 }
else if (!Ctx.
getLangOpts().CPlusPlus && HasBrackets) {
564 llvm::errs() <<
"For analyzing C code you shouldn't pass the function "
565 "parameter list, only the name of the function: "
566 "-analyze-function=foobar\n";
570void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &
C) {
571 BugReporter BR(*Mgr);
572 const TranslationUnitDecl *TU =
C.getTranslationUnitDecl();
574 if (SyntaxCheckTimer)
575 SyntaxCheckTimer->startTimer();
576 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
577 if (SyntaxCheckTimer)
578 SyntaxCheckTimer->stopTimer();
583 RecVisitorMode = AM_Syntax;
584 if (!Mgr->shouldInlineCall())
585 RecVisitorMode |= AM_Path;
594 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
595 for (
unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
596 TraverseDecl(LocalTUDecls[i]);
599 if (Mgr->shouldInlineCall())
600 HandleDeclsCallGraph(LocalTUDeclsSize);
603 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
606 RecVisitorBR =
nullptr;
612 NumFunctionsAnalyzedSyntaxOnly == 0) {
617void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
622void AnalysisConsumer::HandleTranslationUnit(ASTContext &
C) {
629 checkerMgr = std::make_unique<CheckerManager>(*Ctx, Opts, PP, Plugins,
630 CheckerRegistrationFns);
632 Mgr = std::make_unique<AnalysisManager>(
633 *Ctx, PP, std::move(PathConsumers), CreateStoreMgr, CreateConstraintMgr,
634 checkerMgr.get(), Opts, std::move(Injector));
640 const auto DiagFlusherScopeExit =
641 llvm::make_scope_exit([
this] { Mgr.reset(); });
643 if (Opts.ShouldIgnoreBisonGeneratedFiles &&
645 reportAnalyzerProgress(
"Skipping bison-generated file\n");
649 if (Opts.ShouldIgnoreFlexGeneratedFiles &&
651 reportAnalyzerProgress(
"Skipping flex-generated file\n");
658 reportAnalyzerProgress(
"All checks are disabled using a supplied option\n");
663 runAnalysisOnTranslationUnit(
C);
667 NumVisitedBlocksInAnalyzedFunctions =
669 if (NumBlocksInAnalyzedFunctions > 0)
670 PercentReachableBlocks =
672 NumBlocksInAnalyzedFunctions;
674 if (!Opts.DumpEntryPointStatsToCSV.empty()) {
679AnalysisConsumer::AnalysisMode
680AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
698 const SourceLocation Loc = [&
SM](
Decl *D) -> SourceLocation {
699 const Stmt *Body = D->
getBody();
701 return SM.getExpansionLoc(SL);
709 if (!Mgr->isInCodeFile(Loc))
710 return Mode & ~AM_Path;
718void AnalysisConsumer::HandleCode(
Decl *D, AnalysisMode Mode,
721 llvm::TimeTraceScope TCS(timeTraceScopeDeclName(
"HandleCode", D),
722 [D]() {
return timeTraceScopeDeclMetadata(D); });
725 Mode = getModeForDecl(D, Mode);
730 Mgr->ClearContexts();
732 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
735 CFG *DeclCFG = Mgr->getCFG(D);
737 MaxCFGSize.updateMax(DeclCFG->
size());
739 DisplayFunction(D, Mode, IMode);
740 BugReporter BR(*Mgr);
743 if (Mode & AM_Syntax) {
744 llvm::TimeRecord CheckerStartTime;
745 if (SyntaxCheckTimer) {
746 CheckerStartTime = SyntaxCheckTimer->getTotalTime();
747 SyntaxCheckTimer->startTimer();
749 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
750 ++NumFunctionsAnalyzedSyntaxOnly;
751 if (SyntaxCheckTimer) {
752 SyntaxCheckTimer->stopTimer();
753 llvm::TimeRecord CheckerDuration =
754 SyntaxCheckTimer->getTotalTime() - CheckerStartTime;
757 DisplayTime(CheckerDuration);
763 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
764 RunPathSensitiveChecks(D, IMode, VisitedCallees);
767 NumFunctionsAnalyzed++;
775void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
778 auto *CFG = Mgr->getCFG(D);
787 auto *DeclContext = Mgr->getAnalysisDeclContext(D);
789 if (!DeclContext->getAnalysis<RelaxedLiveVariables>())
793 const Decl *DefDecl = DeclContext->getDecl();
798 if (
const auto *Summary = FunctionSummaries.
findSummary(DefDecl);
799 Summary && Summary->SyntaxRunningTime.has_value()) {
803 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
806 llvm::TimeRecord ExprEngineStartTime;
807 if (ExprEngineTimer) {
808 ExprEngineStartTime = ExprEngineTimer->getTotalTime();
809 ExprEngineTimer->startTimer();
811 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
812 Mgr->options.MaxNodesPerTopLevelFunction);
813 if (ExprEngineTimer) {
814 ExprEngineTimer->stopTimer();
815 llvm::TimeRecord ExprEngineDuration =
816 ExprEngineTimer->getTotalTime() - ExprEngineStartTime;
818 std::lround(ExprEngineDuration.getWallTime() * 1000)));
819 DisplayTime(ExprEngineDuration);
822 if (!Mgr->options.DumpExplodedGraphTo.empty())
823 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
826 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
827 Eng.ViewGraph(Mgr->options.TrimGraph);
829 flushReports(BugReporterTimer.get(), Eng.getBugReporter());
836std::unique_ptr<AnalysisASTConsumer>
842 bool hasModelPath = analyzerOpts.
Config.count(
"model-path") > 0;
844 return std::make_unique<AnalysisConsumer>(
847 hasModelPath ? std::make_unique<ModelInjector>(CI) :
nullptr);
static UnsignedEPStat PathRunningTime("PathRunningTime")
static UnsignedEPStat SyntaxRunningTime("SyntaxRunningTime")
static UnsignedEPStat CFGSize("CFGSize")
ALWAYS_ENABLED_STATISTIC(NumFunctionsAnalyzed, "The # of functions and blocks analyzed (as top level " "with inlining turned on).")
static bool shouldSkipFunction(const Decl *D, const SetOfConstDecls &Visited, const SetOfConstDecls &VisitedAsTopLevel)
static bool fileContainsString(StringRef Substring, ASTContext &C)
static void reportAnalyzerFunctionMisuse(const AnalyzerOptions &Opts, const ASTContext &Ctx)
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
#define STAT_COUNTER(VARNAME, DESC)
This file defines the clang::ento::ModelInjector class which implements the clang::CodeInjector inter...
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
const LangOptions & getLangOpts() const
static std::string getFunctionName(const Decl *D)
Stores options for the analyzer from the command line.
unsigned DisableAllCheckers
Disable all analyzer checkers.
ConfigTable Config
A key-value table of use-specified configuration values.
std::string AnalyzeSpecificFunction
unsigned AnalyzerDisplayProgress
unsigned size() const
Return the total number of CFGBlocks within the CFG This is simply a renaming of the getNumBlockIDs()...
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
AnalyzerOptions & getAnalyzerOpts()
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
FrontendOptions & getFrontendOpts()
CompilerInvocation & getInvocation()
Helper class for holding the data necessary to invoke the compiler.
FrontendOptions & getFrontendOpts()
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
bool hasErrorOccurred() const
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
bool hasFatalErrorOccurred() const
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
std::string OutputFile
The output file, if any.
std::vector< std::string > Plugins
The list of plugins to load.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
DiagnosticsEngine & getDiagnostics() const
const char * getFilename() const
Return the presumed filename of this location.
This class handles loading and caching of source files into memory.
SourceLocation getBeginLoc() const LLVM_READONLY
bool isStaticDataMember() const
Determines whether this is a static data member.
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
static std::optional< std::string > getLookupName(const Decl *D)
Get a name to identify a decl.
bool isImportedAsNew(const Decl *ToDecl) const
Returns true if the given Decl is newly created during the import.
BugReporter is a utility class for generating PathDiagnostics for analysis.
void FlushReports()
Generate and flush diagnostics for all bug reports.
void setAnalysisEntryPoint(const Decl *EntryPoint)
bool isValid() const =delete
static void dumpStatsAsCSV(llvm::raw_ostream &OS)
static void lockRegistry(llvm::StringRef CPPFileName, ASTContext &Ctx)
static void takeSnapshot(const Decl *EntryPoint)
InliningModes
The modes of inlining, which override the default analysis-wide settings.
@ Inline_Minimal
Do minimal inlining of callees.
@ Inline_Regular
Follow the default settings for inlining callees.
unsigned getTotalNumBasicBlocks()
FunctionSummary const * findSummary(const Decl *D) const
unsigned getTotalNumVisitedBasicBlocks()
MapTy::iterator findOrInsertSummary(const Decl *D)
bool shouldImport(const VarDecl *VD, const ASTContext &ACtx)
Returns true if it makes sense to import a foreign variable definition.
std::deque< Decl * > SetOfDecls
std::unique_ptr< AnalysisASTConsumer > CreateAnalysisConsumer(CompilerInstance &CI)
CreateAnalysisConsumer - Creates an ASTConsumer to run various code analysis passes.
llvm::DenseSet< const Decl * > SetOfConstDecls
std::unique_ptr< ConstraintManager >(* ConstraintManagerCreator)(ProgramStateManager &, ExprEngine *)
std::unique_ptr< StoreManager >(* StoreManagerCreator)(ProgramStateManager &)
std::vector< std::unique_ptr< PathDiagnosticConsumer > > PathDiagnosticConsumers
std::unique_ptr< StoreManager > CreateRegionStoreManager(ProgramStateManager &StMgr)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
int const char * function