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