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