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