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"
48#define DEBUG_TYPE "AnalysisConsumer"
50STAT_COUNTER(NumFunctionTopLevel,
"The # of functions at top level.");
52 "The # of functions and blocks analyzed (as top level "
53 "with inlining turned on).");
55 NumFunctionsAnalyzedSyntaxOnly,
56 "The # of functions analyzed by syntax checkers only.");
58 "The # of basic blocks in the analyzed functions.");
60 NumVisitedBlocksInAnalyzedFunctions,
61 "The # of visited basic blocks in the analyzed functions.");
63 "The % of reachable basic blocks.");
64STAT_MAX(MaxCFGSize,
"The maximum number of basic blocks in a function.");
75 : Input.
getBuffer().getBufferIdentifier();
87 typedef unsigned AnalysisMode;
90 AnalysisMode RecVisitorMode;
92 BugReporter *RecVisitorBR;
94 std::vector<
std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
99 const std::string OutDir;
100 AnalyzerOptions &Opts;
101 ArrayRef<std::string> Plugins;
102 std::unique_ptr<CodeInjector> Injector;
103 cross_tu::CrossTranslationUnitContext CTU;
112 MacroExpansionContext MacroExpansions;
120 std::unique_ptr<CheckerManager> checkerMgr;
121 std::unique_ptr<AnalysisManager> Mgr;
124 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
125 std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
126 std::unique_ptr<llvm::Timer> ExprEngineTimer;
127 std::unique_ptr<llvm::Timer> BugReporterTimer;
131 FunctionSummariesTy FunctionSummaries;
133 AnalysisConsumer(CompilerInstance &CI,
const std::string &outdir,
134 AnalyzerOptions &opts, ArrayRef<std::string> plugins,
135 std::unique_ptr<CodeInjector> injector)
137 PP(CI.getPreprocessor()), OutDir(outdir), Opts(opts), Plugins(plugins),
138 Injector(std::move(injector)), CTU(CI),
139 MacroExpansions(CI.getLangOpts()) {
142 DigestAnalyzerOptions();
144 if (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||
145 Opts.ShouldSerializeStats) {
146 AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
147 "analyzer",
"Analyzer timers");
148 SyntaxCheckTimer = std::make_unique<llvm::Timer>(
149 "syntaxchecks",
"Syntax-based analysis time", *AnalyzerTimers);
150 ExprEngineTimer = std::make_unique<llvm::Timer>(
151 "exprengine",
"Path exploration time", *AnalyzerTimers);
152 BugReporterTimer = std::make_unique<llvm::Timer>(
153 "bugreporter",
"Path-sensitive report post-processing time",
157 if (Opts.PrintStats || Opts.ShouldSerializeStats) {
158 llvm::EnableStatistics(
false);
161 if (Opts.ShouldDisplayMacroExpansions)
162 MacroExpansions.registerForPreprocessor(PP);
165 ShouldWalkTypesOfTypeLocs =
false;
168 ~AnalysisConsumer()
override {
169 if (Opts.PrintStats) {
170 llvm::PrintStatistics();
174 void DigestAnalyzerOptions() {
175 switch (Opts.AnalysisDiagOpt) {
178#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
180 CREATEFN(Opts.getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
183#include "clang/StaticAnalyzer/Core/Analyses.def"
185 llvm_unreachable(
"Unknown analyzer output type!");
191 switch (Opts.AnalysisConstraintsOpt) {
193 llvm_unreachable(
"Unknown constraint manager.");
194#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
195 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
196#include "clang/StaticAnalyzer/Core/Analyses.def"
200 void DisplayTime(llvm::TimeRecord &Time) {
201 if (!Opts.AnalyzerDisplayProgress) {
204 llvm::errs() <<
" : " << llvm::format(
"%1.1f", Time.getWallTime() * 1000)
208 void DisplayFunction(
const Decl *D, AnalysisMode Mode,
210 if (!Opts.AnalyzerDisplayProgress)
213 SourceManager &
SM = Mgr->getASTContext().getSourceManager();
216 llvm::errs() <<
"ANALYZE";
218 if (Mode == AM_Syntax)
219 llvm::errs() <<
" (Syntax)";
220 else if (Mode == AM_Path) {
221 llvm::errs() <<
" (Path, ";
224 llvm::errs() <<
" Inline_Minimal";
227 llvm::errs() <<
" Inline_Regular";
232 assert(Mode == (AM_Syntax | AM_Path) &&
"Unexpected mode!");
241 bool HandleTopLevelDecl(DeclGroupRef D)
override;
242 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D)
override;
244 void HandleTranslationUnit(ASTContext &
C)
override;
250 getInliningModeForFunction(
const Decl *D,
const SetOfConstDecls &Visited);
254 void HandleDeclsCallGraph(
const unsigned LocalTUDeclsSize);
262 void HandleCode(Decl *D, AnalysisMode Mode,
266 void RunPathSensitiveChecks(Decl *D,
271 bool VisitDecl(Decl *D)
override {
272 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
273 if (Mode & AM_Syntax) {
274 if (SyntaxCheckTimer)
275 SyntaxCheckTimer->startTimer();
276 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
277 if (SyntaxCheckTimer)
278 SyntaxCheckTimer->stopTimer();
283 bool VisitVarDecl(VarDecl *VD)
override {
284 if (!Opts.IsNaiveCTUEnabled)
298 llvm::Expected<const VarDecl *> CTUDeclOrError =
299 CTU.getCrossTUDefinition(VD, Opts.CTUDir, Opts.CTUIndexName,
300 Opts.DisplayCTUProgress);
302 if (!CTUDeclOrError) {
303 handleAllErrors(CTUDeclOrError.takeError(),
304 [&](
const cross_tu::IndexError &IE) {
305 CTU.emitCrossTUDiagnostics(IE);
312 bool VisitFunctionDecl(FunctionDecl *FD)
override {
314 if (II && II->
getName().starts_with(
"__inline"))
321 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
322 HandleCode(FD, RecVisitorMode);
327 bool VisitObjCMethodDecl(ObjCMethodDecl *MD)
override {
329 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
330 HandleCode(MD, RecVisitorMode);
335 bool VisitBlockDecl(BlockDecl *BD)
override {
337 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
341 HandleCode(BD, RecVisitorMode);
347 void AddDiagnosticConsumer(
348 std::unique_ptr<PathDiagnosticConsumer> Consumer)
override {
349 PathConsumers.push_back(std::move(Consumer));
352 void AddCheckerRegistrationFn(
std::function<
void(CheckerRegistry&)> Fn)
override {
353 CheckerRegistrationFns.push_back(std::move(Fn));
357 void storeTopLevelDecls(DeclGroupRef DG);
360 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
361 void runAnalysisOnTranslationUnit(ASTContext &
C);
364 void reportAnalyzerProgress(StringRef S);
367std::string timeTraceScopeDeclName(StringRef FunName,
const Decl *D) {
368 if (llvm::timeTraceProfilerEnabled()) {
369 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(D))
370 return (FunName +
" " + ND->getQualifiedNameAsString()).str();
371 return (FunName +
" <anonymous> ").str();
376llvm::TimeTraceMetadata timeTraceScopeDeclMetadata(
const Decl *D) {
378 assert(llvm::timeTraceProfilerEnabled());
382 return llvm::TimeTraceMetadata{
383 std::move(DeclName),
SM.getFilename(
Loc).str(),
384 static_cast<int>(
SM.getExpansionLineNumber(
Loc))};
386 return llvm::TimeTraceMetadata{
"",
""};
389void flushReports(llvm::Timer *BugReporterTimer,
BugReporter &BR) {
390 llvm::TimeTraceScope TCS{
"Flushing reports"};
392 if (BugReporterTimer)
393 BugReporterTimer->startTimer();
395 if (BugReporterTimer)
396 BugReporterTimer->stopTimer();
403bool AnalysisConsumer::HandleTopLevelDecl(
DeclGroupRef DG) {
404 storeTopLevelDecls(DG);
408void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
409 storeTopLevelDecls(DG);
412void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
420 LocalTUDecls.push_back(I);
427 if (VisitedAsTopLevel.count(D))
433 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
434 if (CD->isInheritingConstructor())
449 if (
const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
450 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
455 return Visited.count(D);
459AnalysisConsumer::getInliningModeForFunction(
const Decl *D,
473void AnalysisConsumer::HandleDeclsCallGraph(
const unsigned LocalTUDeclsSize) {
479 for (
unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
491 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
492 for (
auto &N : RPOT) {
493 NumFunctionTopLevel++;
495 Decl *D = N->getDecl();
510 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
521 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
522 (Mgr->options.InliningMode ==
All ?
nullptr : &VisitedCallees));
525 for (
const Decl *Callee : VisitedCallees)
529 :
Callee->getCanonicalDecl());
530 VisitedAsTopLevel.insert(D);
537 StringRef Buffer =
SM.getBufferOrFake(FID).getBuffer();
538 return Buffer.contains(Substring);
543 llvm::errs() <<
"Every top-level function was skipped.\n";
546 llvm::errs() <<
"Pass the -analyzer-display-progress for tracking which "
547 "functions are analyzed.\n";
554 <<
"For analyzing C++ code you need to pass the function parameter "
555 "list: -analyze-function=\"foobar(int, _Bool)\"\n";
556 }
else if (!Ctx.
getLangOpts().CPlusPlus && HasBrackets) {
557 llvm::errs() <<
"For analyzing C code you shouldn't pass the function "
558 "parameter list, only the name of the function: "
559 "-analyze-function=foobar\n";
563void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &
C) {
564 BugReporter BR(*Mgr);
565 const TranslationUnitDecl *TU =
C.getTranslationUnitDecl();
567 if (SyntaxCheckTimer)
568 SyntaxCheckTimer->startTimer();
569 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
570 if (SyntaxCheckTimer)
571 SyntaxCheckTimer->stopTimer();
576 RecVisitorMode = AM_Syntax;
577 if (!Mgr->shouldInlineCall())
578 RecVisitorMode |= AM_Path;
587 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
588 for (
unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
589 TraverseDecl(LocalTUDecls[i]);
592 if (Mgr->shouldInlineCall())
593 HandleDeclsCallGraph(LocalTUDeclsSize);
596 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
599 RecVisitorBR =
nullptr;
605 NumFunctionsAnalyzedSyntaxOnly == 0) {
610void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
615void AnalysisConsumer::HandleTranslationUnit(ASTContext &
C) {
622 checkerMgr = std::make_unique<CheckerManager>(*Ctx, Opts, PP, Plugins,
623 CheckerRegistrationFns);
625 Mgr = std::make_unique<AnalysisManager>(
626 *Ctx, PP, std::move(PathConsumers), CreateStoreMgr, CreateConstraintMgr,
627 checkerMgr.get(), Opts, std::move(Injector));
633 const auto DiagFlusherScopeExit =
634 llvm::make_scope_exit([
this] { Mgr.reset(); });
636 if (Opts.ShouldIgnoreBisonGeneratedFiles &&
638 reportAnalyzerProgress(
"Skipping bison-generated file\n");
642 if (Opts.ShouldIgnoreFlexGeneratedFiles &&
644 reportAnalyzerProgress(
"Skipping flex-generated file\n");
651 reportAnalyzerProgress(
"All checks are disabled using a supplied option\n");
656 runAnalysisOnTranslationUnit(
C);
660 NumVisitedBlocksInAnalyzedFunctions =
662 if (NumBlocksInAnalyzedFunctions > 0)
663 PercentReachableBlocks =
665 NumBlocksInAnalyzedFunctions;
667 if (!Opts.DumpEntryPointStatsToCSV.empty()) {
672AnalysisConsumer::AnalysisMode
673AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
691 const SourceLocation Loc = [&
SM](
Decl *D) -> SourceLocation {
692 const Stmt *Body = D->
getBody();
694 return SM.getExpansionLoc(SL);
702 if (!Mgr->isInCodeFile(Loc))
703 return Mode & ~AM_Path;
710void AnalysisConsumer::HandleCode(
Decl *D, AnalysisMode Mode,
713 llvm::TimeTraceScope TCS(timeTraceScopeDeclName(
"HandleCode", D),
714 [D]() {
return timeTraceScopeDeclMetadata(D); });
717 Mode = getModeForDecl(D, Mode);
722 Mgr->ClearContexts();
724 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
727 CFG *DeclCFG = Mgr->getCFG(D);
729 MaxCFGSize.updateMax(DeclCFG->
size());
731 DisplayFunction(D, Mode, IMode);
732 BugReporter BR(*Mgr);
735 if (Mode & AM_Syntax) {
736 llvm::TimeRecord CheckerStartTime;
737 if (SyntaxCheckTimer) {
738 CheckerStartTime = SyntaxCheckTimer->getTotalTime();
739 SyntaxCheckTimer->startTimer();
741 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
742 ++NumFunctionsAnalyzedSyntaxOnly;
743 if (SyntaxCheckTimer) {
744 SyntaxCheckTimer->stopTimer();
745 llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
746 CheckerEndTime -= CheckerStartTime;
747 DisplayTime(CheckerEndTime);
753 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
754 RunPathSensitiveChecks(D, IMode, VisitedCallees);
757 NumFunctionsAnalyzed++;
765void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
774 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
777 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
780 llvm::TimeRecord ExprEngineStartTime;
781 if (ExprEngineTimer) {
782 ExprEngineStartTime = ExprEngineTimer->getTotalTime();
783 ExprEngineTimer->startTimer();
785 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
786 Mgr->options.MaxNodesPerTopLevelFunction);
787 if (ExprEngineTimer) {
788 ExprEngineTimer->stopTimer();
789 llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
790 ExprEngineEndTime -= ExprEngineStartTime;
791 DisplayTime(ExprEngineEndTime);
794 if (!Mgr->options.DumpExplodedGraphTo.empty())
795 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
798 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
799 Eng.ViewGraph(Mgr->options.TrimGraph);
801 flushReports(BugReporterTimer.get(), Eng.getBugReporter());
808std::unique_ptr<AnalysisASTConsumer>
814 bool hasModelPath = analyzerOpts.
Config.count(
"model-path") > 0;
816 return std::make_unique<AnalysisConsumer>(
819 hasModelPath ? std::make_unique<ModelInjector>(CI) :
nullptr);
static UnsignedEPStat PathRunningTime("PathRunningTime")
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)
#define STAT_MAX(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.
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 lockRegistry(llvm::StringRef CPPFileName)
static void dumpStatsAsCSV(llvm::raw_ostream &OS)
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()
unsigned getTotalNumVisitedBasicBlocks()
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