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