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