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