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