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

source code of clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp