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