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