clang 22.0.0git
AnalysisConsumer.cpp
Go to the documentation of this file.
1//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// "Meta" ASTConsumer for running different source analyses.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ModelInjector.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
20#include "clang/Analysis/CFG.h"
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"
42#include <memory>
43#include <utility>
44
45using namespace clang;
46using namespace ento;
47
48#define DEBUG_TYPE "AnalysisConsumer"
49
50STAT_COUNTER(NumFunctionTopLevel, "The # of functions at top level.");
51ALWAYS_ENABLED_STATISTIC(NumFunctionsAnalyzed,
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.");
57ALWAYS_ENABLED_STATISTIC(NumBlocksInAnalyzedFunctions,
58 "The # of basic blocks in the analyzed functions.");
60 NumVisitedBlocksInAnalyzedFunctions,
61 "The # of visited basic blocks in the analyzed functions.");
62ALWAYS_ENABLED_STATISTIC(PercentReachableBlocks,
63 "The % of reachable basic blocks.");
64STAT_MAX(MaxCFGSize, "The maximum number of basic blocks in a function.");
65//===----------------------------------------------------------------------===//
66// AnalysisConsumer declaration.
67//===----------------------------------------------------------------------===//
68
69namespace {
70
71StringRef getMainFileName(const CompilerInvocation &Invocation) {
72 if (!Invocation.getFrontendOpts().Inputs.empty()) {
73 const FrontendInputFile &Input = Invocation.getFrontendOpts().Inputs[0];
74 return Input.isFile() ? Input.getFile()
75 : Input.getBuffer().getBufferIdentifier();
76 }
77 return "<no input>";
78}
79
80class AnalysisConsumer : public AnalysisASTConsumer,
82 enum {
83 AM_None = 0,
84 AM_Syntax = 0x1,
85 AM_Path = 0x2
86 };
87 typedef unsigned AnalysisMode;
88
89 /// Mode of the analyzes while recursively visiting Decls.
90 AnalysisMode RecVisitorMode;
91 /// Bug Reporter to use while recursively visiting Decls.
92 BugReporter *RecVisitorBR;
93
94 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
95
96public:
97 ASTContext *Ctx;
98 Preprocessor &PP;
99 const std::string OutDir;
100 AnalyzerOptions &Opts;
101 ArrayRef<std::string> Plugins;
102 std::unique_ptr<CodeInjector> Injector;
103 cross_tu::CrossTranslationUnitContext CTU;
104
105 /// Stores the declarations from the local translation unit.
106 /// Note, we pre-compute the local declarations at parse time as an
107 /// optimization to make sure we do not deserialize everything from disk.
108 /// The local declaration to all declarations ratio might be very small when
109 /// working with a PCH file.
110 SetOfDecls LocalTUDecls;
111
112 MacroExpansionContext MacroExpansions;
113
114 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
115 PathDiagnosticConsumers PathConsumers;
116
117 StoreManagerCreator CreateStoreMgr;
118 ConstraintManagerCreator CreateConstraintMgr;
119
120 std::unique_ptr<CheckerManager> checkerMgr;
121 std::unique_ptr<AnalysisManager> Mgr;
122
123 /// Time the analyzes time of each translation unit.
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;
128
129 /// The information about analyzed functions shared throughout the
130 /// translation unit.
131 FunctionSummariesTy FunctionSummaries;
132
133 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
134 AnalyzerOptions &opts, ArrayRef<std::string> plugins,
135 std::unique_ptr<CodeInjector> injector)
136 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
137 PP(CI.getPreprocessor()), OutDir(outdir), Opts(opts), Plugins(plugins),
138 Injector(std::move(injector)), CTU(CI),
139 MacroExpansions(CI.getLangOpts()) {
140
141 EntryPointStat::lockRegistry(getMainFileName(CI.getInvocation()));
142 DigestAnalyzerOptions();
143
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",
154 *AnalyzerTimers);
155 }
156
157 if (Opts.PrintStats || Opts.ShouldSerializeStats) {
158 llvm::EnableStatistics(/* DoPrintOnExit= */ false);
159 }
160
161 if (Opts.ShouldDisplayMacroExpansions)
162 MacroExpansions.registerForPreprocessor(PP);
163
164 // Visitor options.
165 ShouldWalkTypesOfTypeLocs = false;
166 }
167
168 ~AnalysisConsumer() override {
169 if (Opts.PrintStats) {
170 llvm::PrintStatistics();
171 }
172 }
173
174 void DigestAnalyzerOptions() {
175 switch (Opts.AnalysisDiagOpt) {
176 case PD_NONE:
177 break;
178#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
179 case PD_##NAME: \
180 CREATEFN(Opts.getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
181 MacroExpansions); \
182 break;
183#include "clang/StaticAnalyzer/Core/Analyses.def"
184 default:
185 llvm_unreachable("Unknown analyzer output type!");
186 }
187
188 // Create the analyzer component creators.
189 CreateStoreMgr = &CreateRegionStoreManager;
190
191 switch (Opts.AnalysisConstraintsOpt) {
192 default:
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"
197 }
198 }
199
200 void DisplayTime(llvm::TimeRecord &Time) {
201 if (!Opts.AnalyzerDisplayProgress) {
202 return;
203 }
204 llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000)
205 << " ms\n";
206 }
207
208 void DisplayFunction(const Decl *D, AnalysisMode Mode,
210 if (!Opts.AnalyzerDisplayProgress)
211 return;
212
213 SourceManager &SM = Mgr->getASTContext().getSourceManager();
214 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
215 if (Loc.isValid()) {
216 llvm::errs() << "ANALYZE";
217
218 if (Mode == AM_Syntax)
219 llvm::errs() << " (Syntax)";
220 else if (Mode == AM_Path) {
221 llvm::errs() << " (Path, ";
222 switch (IMode) {
224 llvm::errs() << " Inline_Minimal";
225 break;
227 llvm::errs() << " Inline_Regular";
228 break;
229 }
230 llvm::errs() << ")";
231 } else
232 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
233
234 llvm::errs() << ": " << Loc.getFilename() << ' '
236 }
237 }
238
239 /// Store the top level decls in the set to be processed later on.
240 /// (Doing this pre-processing avoids deserialization of data from PCH.)
241 bool HandleTopLevelDecl(DeclGroupRef D) override;
242 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
243
244 void HandleTranslationUnit(ASTContext &C) override;
245
246 /// Determine which inlining mode should be used when this function is
247 /// analyzed. This allows to redefine the default inlining policies when
248 /// analyzing a given function.
250 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
251
252 /// Build the call graph for all the top level decls of this TU and
253 /// use it to define the order in which the functions should be visited.
254 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
255
256 /// Run analyzes(syntax or path sensitive) on the given function.
257 /// \param Mode - determines if we are requesting syntax only or path
258 /// sensitive only analysis.
259 /// \param VisitedCallees - The output parameter, which is populated with the
260 /// set of functions which should be considered analyzed after analyzing the
261 /// given root function.
262 void HandleCode(Decl *D, AnalysisMode Mode,
264 SetOfConstDecls *VisitedCallees = nullptr);
265
266 void RunPathSensitiveChecks(Decl *D,
268 SetOfConstDecls *VisitedCallees);
269
270 /// Handle callbacks for arbitrary Decls.
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();
279 }
280 return true;
281 }
282
283 bool VisitVarDecl(VarDecl *VD) override {
284 if (!Opts.IsNaiveCTUEnabled)
285 return true;
286
287 if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
288 if (!cross_tu::shouldImport(VD, *Ctx))
289 return true;
290 } else {
291 // Cannot be initialized in another TU.
292 return true;
293 }
294
295 if (VD->getAnyInitializer())
296 return true;
297
298 llvm::Expected<const VarDecl *> CTUDeclOrError =
299 CTU.getCrossTUDefinition(VD, Opts.CTUDir, Opts.CTUIndexName,
300 Opts.DisplayCTUProgress);
301
302 if (!CTUDeclOrError) {
303 handleAllErrors(CTUDeclOrError.takeError(),
304 [&](const cross_tu::IndexError &IE) {
305 CTU.emitCrossTUDiagnostics(IE);
306 });
307 }
308
309 return true;
310 }
311
312 bool VisitFunctionDecl(FunctionDecl *FD) override {
313 IdentifierInfo *II = FD->getIdentifier();
314 if (II && II->getName().starts_with("__inline"))
315 return true;
316
317 // We skip function template definitions, as their semantics is
318 // only determined when they are instantiated.
320 !FD->isDependentContext()) {
321 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
322 HandleCode(FD, RecVisitorMode);
323 }
324 return true;
325 }
326
327 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) override {
329 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
330 HandleCode(MD, RecVisitorMode);
331 }
332 return true;
333 }
334
335 bool VisitBlockDecl(BlockDecl *BD) override {
336 if (BD->hasBody()) {
337 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
338 // Since we skip function template definitions, we should skip blocks
339 // declared in those functions as well.
340 if (!BD->isDependentContext()) {
341 HandleCode(BD, RecVisitorMode);
342 }
343 }
344 return true;
345 }
346
347 void AddDiagnosticConsumer(
348 std::unique_ptr<PathDiagnosticConsumer> Consumer) override {
349 PathConsumers.push_back(std::move(Consumer));
350 }
351
352 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
353 CheckerRegistrationFns.push_back(std::move(Fn));
354 }
355
356private:
357 void storeTopLevelDecls(DeclGroupRef DG);
358
359 /// Check if we should skip (not analyze) the given function.
360 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
361 void runAnalysisOnTranslationUnit(ASTContext &C);
362
363 /// Print \p S to stderr if \c Opts.AnalyzerDisplayProgress is set.
364 void reportAnalyzerProgress(StringRef S);
365};
366
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();
372 }
373 return "";
374}
375
376llvm::TimeTraceMetadata timeTraceScopeDeclMetadata(const Decl *D) {
377 // If time-trace profiler is not enabled, this function is never called.
378 assert(llvm::timeTraceProfilerEnabled());
379 if (const auto &Loc = D->getBeginLoc(); Loc.isValid()) {
380 const auto &SM = D->getASTContext().getSourceManager();
381 std::string DeclName = AnalysisDeclContext::getFunctionName(D);
382 return llvm::TimeTraceMetadata{
383 std::move(DeclName), SM.getFilename(Loc).str(),
384 static_cast<int>(SM.getExpansionLineNumber(Loc))};
385 }
386 return llvm::TimeTraceMetadata{"", ""};
387}
388
389void flushReports(llvm::Timer *BugReporterTimer, BugReporter &BR) {
390 llvm::TimeTraceScope TCS{"Flushing reports"};
391 // Display warnings.
392 if (BugReporterTimer)
393 BugReporterTimer->startTimer();
394 BR.FlushReports();
395 if (BugReporterTimer)
396 BugReporterTimer->stopTimer();
397}
398} // namespace
399
400//===----------------------------------------------------------------------===//
401// AnalysisConsumer implementation.
402//===----------------------------------------------------------------------===//
403bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
404 storeTopLevelDecls(DG);
405 return true;
406}
407
408void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
409 storeTopLevelDecls(DG);
410}
411
412void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
413 for (auto &I : DG) {
414
415 // Skip ObjCMethodDecl, wait for the objc container to avoid
416 // analyzing twice.
417 if (isa<ObjCMethodDecl>(I))
418 continue;
419
420 LocalTUDecls.push_back(I);
421 }
422}
423
424static bool shouldSkipFunction(const Decl *D,
425 const SetOfConstDecls &Visited,
426 const SetOfConstDecls &VisitedAsTopLevel) {
427 if (VisitedAsTopLevel.count(D))
428 return true;
429
430 // Skip analysis of inheriting constructors as top-level functions. These
431 // constructors don't even have a body written down in the code, so even if
432 // we find a bug, we won't be able to display it.
433 if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
434 if (CD->isInheritingConstructor())
435 return true;
436
437 // We want to re-analyse the functions as top level in the following cases:
438 // - The 'init' methods should be reanalyzed because
439 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
440 // 'nil' and unless we analyze the 'init' functions as top level, we will
441 // not catch errors within defensive code.
442 // - We want to reanalyze all ObjC methods as top level to report Retain
443 // Count naming convention errors more aggressively.
444 if (isa<ObjCMethodDecl>(D))
445 return false;
446 // We also want to reanalyze all C++ copy and move assignment operators to
447 // separately check the two cases where 'this' aliases with the parameter and
448 // where it may not. (cplusplus.SelfAssignmentChecker)
449 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
450 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
451 return false;
452 }
453
454 // Otherwise, if we visited the function before, do not reanalyze it.
455 return Visited.count(D);
456}
457
459AnalysisConsumer::getInliningModeForFunction(const Decl *D,
460 const SetOfConstDecls &Visited) {
461 // We want to reanalyze all ObjC methods as top level to report Retain
462 // Count naming convention errors more aggressively. But we should tune down
463 // inlining when reanalyzing an already inlined function.
464 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
465 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
466 if (ObjCM->getMethodFamily() != OMF_init)
468 }
469
471}
472
473void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
474 // Build the Call Graph by adding all the top level declarations to the graph.
475 // Note: CallGraph can trigger deserialization of more items from a pch
476 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
477 // We rely on random access to add the initially processed Decls to CG.
478 CallGraph CG;
479 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
480 CG.addToCallGraph(LocalTUDecls[i]);
481 }
482
483 // Walk over all of the call graph nodes in topological order, so that we
484 // analyze parents before the children. Skip the functions inlined into
485 // the previously processed functions. Use external Visited set to identify
486 // inlined functions. The topological order allows the "do not reanalyze
487 // previously inlined function" performance heuristic to be triggered more
488 // often.
489 SetOfConstDecls Visited;
490 SetOfConstDecls VisitedAsTopLevel;
491 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
492 for (auto &N : RPOT) {
493 NumFunctionTopLevel++;
494
495 Decl *D = N->getDecl();
496
497 // Skip the abstract root node.
498 if (!D)
499 continue;
500
501 // Skip the functions which have been processed already or previously
502 // inlined.
503 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
504 continue;
505
506 // The CallGraph might have declarations as callees. However, during CTU
507 // the declaration might form a declaration chain with the newly imported
508 // definition from another TU. In this case we don't want to analyze the
509 // function definition as toplevel.
510 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
511 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
512 // that has the body.
513 FD->hasBody(FD);
514 if (CTU.isImportedAsNew(FD))
515 continue;
516 }
517
518 // Analyze the function.
519 SetOfConstDecls VisitedCallees;
520
521 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
522 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
523
524 // Add the visited callees to the global visited set.
525 for (const Decl *Callee : VisitedCallees)
526 // Decls from CallGraph are already canonical. But Decls coming from
527 // CallExprs may be not. We should canonicalize them manually.
528 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
529 : Callee->getCanonicalDecl());
530 VisitedAsTopLevel.insert(D);
531 }
532}
533
534static bool fileContainsString(StringRef Substring, ASTContext &C) {
535 const SourceManager &SM = C.getSourceManager();
536 FileID FID = SM.getMainFileID();
537 StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
538 return Buffer.contains(Substring);
539}
540
542 const ASTContext &Ctx) {
543 llvm::errs() << "Every top-level function was skipped.\n";
544
545 if (!Opts.AnalyzerDisplayProgress)
546 llvm::errs() << "Pass the -analyzer-display-progress for tracking which "
547 "functions are analyzed.\n";
548
549 bool HasBrackets =
550 Opts.AnalyzeSpecificFunction.find("(") != std::string::npos;
551
552 if (Ctx.getLangOpts().CPlusPlus && !HasBrackets) {
553 llvm::errs()
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";
560 }
561}
562
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();
572
573 // Run the AST-only checks using the order in which functions are defined.
574 // If inlining is not turned on, use the simplest function order for path
575 // sensitive analyzes as well.
576 RecVisitorMode = AM_Syntax;
577 if (!Mgr->shouldInlineCall())
578 RecVisitorMode |= AM_Path;
579 RecVisitorBR = &BR;
580
581 // Process all the top level declarations.
582 //
583 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
584 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
585 // random access. By doing so, we automatically compensate for iterators
586 // possibly being invalidated, although this is a bit slower.
587 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
588 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
589 TraverseDecl(LocalTUDecls[i]);
590 }
591
592 if (Mgr->shouldInlineCall())
593 HandleDeclsCallGraph(LocalTUDeclsSize);
594
595 // After all decls handled, run checkers on the entire TranslationUnit.
596 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
597
598 BR.FlushReports();
599 RecVisitorBR = nullptr;
600
601 // If the user wanted to analyze a specific function and the number of basic
602 // blocks analyzed is zero, than the user might not specified the function
603 // name correctly.
604 if (!Opts.AnalyzeSpecificFunction.empty() && NumFunctionsAnalyzed == 0 &&
605 NumFunctionsAnalyzedSyntaxOnly == 0) {
607 }
608}
609
610void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
612 llvm::errs() << S;
613}
614
615void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
616 // Don't run the actions if an error has occurred with parsing the file.
617 DiagnosticsEngine &Diags = PP.getDiagnostics();
618 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
619 return;
620
621 Ctx = &C;
622 checkerMgr = std::make_unique<CheckerManager>(*Ctx, Opts, PP, Plugins,
623 CheckerRegistrationFns);
624
625 Mgr = std::make_unique<AnalysisManager>(
626 *Ctx, PP, std::move(PathConsumers), CreateStoreMgr, CreateConstraintMgr,
627 checkerMgr.get(), Opts, std::move(Injector));
628
629 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
630 // FIXME: This should be replaced with something that doesn't rely on
631 // side-effects in PathDiagnosticConsumer's destructor. This is required when
632 // used with option -disable-free.
633 const auto DiagFlusherScopeExit =
634 llvm::make_scope_exit([this] { Mgr.reset(); });
635
636 if (Opts.ShouldIgnoreBisonGeneratedFiles &&
637 fileContainsString("/* A Bison parser, made by", C)) {
638 reportAnalyzerProgress("Skipping bison-generated file\n");
639 return;
640 }
641
642 if (Opts.ShouldIgnoreFlexGeneratedFiles &&
643 fileContainsString("/* A lexical scanner generated by flex", C)) {
644 reportAnalyzerProgress("Skipping flex-generated file\n");
645 return;
646 }
647
648 // Don't analyze if the user explicitly asked for no checks to be performed
649 // on this file.
650 if (Opts.DisableAllCheckers) {
651 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
652 return;
653 }
654
655 // Otherwise, just run the analysis.
656 runAnalysisOnTranslationUnit(C);
657
658 // Count how many basic blocks we have not covered.
659 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
660 NumVisitedBlocksInAnalyzedFunctions =
661 FunctionSummaries.getTotalNumVisitedBasicBlocks();
662 if (NumBlocksInAnalyzedFunctions > 0)
663 PercentReachableBlocks =
664 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
665 NumBlocksInAnalyzedFunctions;
666
667 if (!Opts.DumpEntryPointStatsToCSV.empty()) {
668 EntryPointStat::dumpStatsAsCSV(Opts.DumpEntryPointStatsToCSV);
669 }
670}
671
672AnalysisConsumer::AnalysisMode
673AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
674 if (!Opts.AnalyzeSpecificFunction.empty() &&
678 return AM_None;
679 }
680
681 // Unless -analyze-all is specified, treat decls differently depending on
682 // where they came from:
683 // - Main source file: run both path-sensitive and non-path-sensitive checks.
684 // - Header files: run non-path-sensitive checks only.
685 // - System headers: don't run any checks.
686 if (Opts.AnalyzeAll)
687 return Mode;
688
689 const SourceManager &SM = Ctx->getSourceManager();
690
691 const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation {
692 const Stmt *Body = D->getBody();
693 SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
694 return SM.getExpansionLoc(SL);
695 }(D);
696
697 // Ignore system headers.
698 if (Loc.isInvalid() || SM.isInSystemHeader(Loc))
699 return AM_None;
700
701 // Disable path sensitive analysis in user-headers.
702 if (!Mgr->isInCodeFile(Loc))
703 return Mode & ~AM_Path;
704
705 return Mode;
706}
707
708static UnsignedEPStat PathRunningTime("PathRunningTime");
709
710void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
712 SetOfConstDecls *VisitedCallees) {
713 llvm::TimeTraceScope TCS(timeTraceScopeDeclName("HandleCode", D),
714 [D]() { return timeTraceScopeDeclMetadata(D); });
715 if (!D->hasBody())
716 return;
717 Mode = getModeForDecl(D, Mode);
718 if (Mode == AM_None)
719 return;
720
721 // Clear the AnalysisManager of old AnalysisDeclContexts.
722 Mgr->ClearContexts();
723 // Ignore autosynthesized code.
724 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
725 return;
726
727 CFG *DeclCFG = Mgr->getCFG(D);
728 if (DeclCFG)
729 MaxCFGSize.updateMax(DeclCFG->size());
730
731 DisplayFunction(D, Mode, IMode);
732 BugReporter BR(*Mgr);
734
735 if (Mode & AM_Syntax) {
736 llvm::TimeRecord CheckerStartTime;
737 if (SyntaxCheckTimer) {
738 CheckerStartTime = SyntaxCheckTimer->getTotalTime();
739 SyntaxCheckTimer->startTimer();
740 }
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);
748 }
749 }
750
751 BR.FlushReports();
752
753 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
754 RunPathSensitiveChecks(D, IMode, VisitedCallees);
756 if (IMode != ExprEngine::Inline_Minimal)
757 NumFunctionsAnalyzed++;
758 }
759}
760
761//===----------------------------------------------------------------------===//
762// Path-sensitive checking.
763//===----------------------------------------------------------------------===//
764
765void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
767 SetOfConstDecls *VisitedCallees) {
768 // Construct the analysis engine. First check if the CFG is valid.
769 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
770 if (!Mgr->getCFG(D))
771 return;
772
773 // See if the LiveVariables analysis scales.
774 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
775 return;
776
777 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
778
779 // Execute the worklist algorithm.
780 llvm::TimeRecord ExprEngineStartTime;
781 if (ExprEngineTimer) {
782 ExprEngineStartTime = ExprEngineTimer->getTotalTime();
783 ExprEngineTimer->startTimer();
784 }
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);
792 }
793
794 if (!Mgr->options.DumpExplodedGraphTo.empty())
795 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
796
797 // Visualize the exploded graph.
798 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
799 Eng.ViewGraph(Mgr->options.TrimGraph);
800
801 flushReports(BugReporterTimer.get(), Eng.getBugReporter());
802}
803
804//===----------------------------------------------------------------------===//
805// AnalysisConsumer creation.
806//===----------------------------------------------------------------------===//
807
808std::unique_ptr<AnalysisASTConsumer>
810 // Disable the effects of '-Werror' when using the AnalysisConsumer.
812
813 AnalyzerOptions &analyzerOpts = CI.getAnalyzerOpts();
814 bool hasModelPath = analyzerOpts.Config.count("model-path") > 0;
815
816 return std::make_unique<AnalysisConsumer>(
817 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
819 hasModelPath ? std::make_unique<ModelInjector>(CI) : nullptr);
820}
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...
#define SM(sm)
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 ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:833
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
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 size() const
Return the total number of CFGBlocks within the CFG This is simply a renaming of the getNumBlockIDs()...
Definition CFG.h:1415
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
Definition CallGraph.h:63
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.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1087
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1093
SourceLocation getLocation() const
Definition DeclBase.h:439
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasErrorOccurred() const
Definition Diagnostic.h:872
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
Definition Diagnostic.h:702
bool hasFatalErrorOccurred() const
Definition Diagnostic.h:879
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
An input file for the front end.
llvm::MemoryBufferRef getBuffer() const
StringRef getFile() const
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 ...
Definition Decl.h:2314
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
Definition DeclObjC.h:534
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
Definition Stmt.cpp:346
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
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.
Definition ExprEngine.h:129
@ Inline_Minimal
Do minimal inlining of callees.
Definition ExprEngine.h:134
@ Inline_Regular
Follow the default settings for inlining callees.
Definition ExprEngine.h:131
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)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31