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