AnalysisConsumer.cpp revision 39cf781d62daaec09e443c6e66a01cd7543ffb41
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/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/SmallPtrSet.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/Program.h"
44#include "llvm/Support/Timer.h"
45#include "llvm/Support/raw_ostream.h"
46#include <queue>
47
48using namespace clang;
49using namespace ento;
50using llvm::SmallPtrSet;
51
52static ExplodedNode::Auditor* CreateUbiViz();
53
54STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
55STATISTIC(NumFunctionsAnalyzed,
56                      "The # of functions and blocks analyzed (as top level "
57                      "with inlining turned on).");
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 PathGenerationScheme getGenerationScheme() const { return None; }
82
83  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
84                            FilesMade *filesMade) {
85    for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
86         E = Diags.end(); I != E; ++I) {
87      const PathDiagnostic *PD = *I;
88      StringRef desc = PD->getShortDescription();
89      SmallString<512> TmpStr;
90      llvm::raw_svector_ostream Out(TmpStr);
91      for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) {
92        if (*I == '%')
93          Out << "%%";
94        else
95          Out << *I;
96      }
97      Out.flush();
98      unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning,
99                                                TmpStr);
100      SourceLocation L = PD->getLocation().asLocation();
101      DiagnosticBuilder diagBuilder = Diag.Report(L, ErrorDiag);
102
103      // Get the ranges from the last point in the path.
104      ArrayRef<SourceRange> Ranges = PD->path.back()->getRanges();
105
106      for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
107                                           E = Ranges.end(); I != E; ++I) {
108        diagBuilder << *I;
109      }
110    }
111  }
112};
113} // end anonymous namespace
114
115//===----------------------------------------------------------------------===//
116// AnalysisConsumer declaration.
117//===----------------------------------------------------------------------===//
118
119namespace {
120
121class AnalysisConsumer : public ASTConsumer,
122                         public RecursiveASTVisitor<AnalysisConsumer> {
123  enum {
124    AM_None = 0,
125    AM_Syntax = 0x1,
126    AM_Path = 0x2
127  };
128  typedef unsigned AnalysisMode;
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  AnalyzerOptionsRef 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                   AnalyzerOptionsRef opts,
168                   ArrayRef<std::string> plugins)
169    : RecVisitorMode(0), 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/Core/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/Core/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/Core/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
227      if (Mode == AM_Syntax)
228        llvm::errs() << " (Syntax)";
229      else if (Mode == AM_Path)
230        llvm::errs() << " (Path)";
231      else
232        assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
233
234      llvm::errs() << ": " << Loc.getFilename();
235      if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
236        const NamedDecl *ND = cast<NamedDecl>(D);
237        llvm::errs() << ' ' << *ND << '\n';
238      }
239      else if (isa<BlockDecl>(D)) {
240        llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
241                     << Loc.getColumn() << '\n';
242      }
243      else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
244        Selector S = MD->getSelector();
245        llvm::errs() << ' ' << S.getAsString();
246      }
247    }
248  }
249
250  virtual void Initialize(ASTContext &Context) {
251    Ctx = &Context;
252    checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
253                                          PP.getDiagnostics()));
254    Mgr.reset(new AnalysisManager(*Ctx,
255                                  PP.getDiagnostics(),
256                                  PP.getLangOpts(),
257                                  PathConsumers,
258                                  CreateStoreMgr,
259                                  CreateConstraintMgr,
260                                  checkerMgr.get(),
261                                  *Opts));
262  }
263
264  /// \brief Store the top level decls in the set to be processed later on.
265  /// (Doing this pre-processing avoids deserialization of data from PCH.)
266  virtual bool HandleTopLevelDecl(DeclGroupRef D);
267  virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D);
268
269  virtual void HandleTranslationUnit(ASTContext &C);
270
271  /// \brief Determine which inlining mode should be used when this function is
272  /// analyzed. For example, determines if the callees should be inlined.
273  ExprEngine::InliningModes
274  getInliningModeForFunction(const Decl *D, SetOfConstDecls Visited);
275
276  /// \brief Build the call graph for all the top level decls of this TU and
277  /// use it to define the order in which the functions should be visited.
278  void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
279
280  /// \brief Run analyzes(syntax or path sensitive) on the given function.
281  /// \param Mode - determines if we are requesting syntax only or path
282  /// sensitive only analysis.
283  /// \param VisitedCallees - The output parameter, which is populated with the
284  /// set of functions which should be considered analyzed after analyzing the
285  /// given root function.
286  void HandleCode(Decl *D, AnalysisMode Mode,
287                  ExprEngine::InliningModes IMode = ExprEngine::Inline_None,
288                  SetOfConstDecls *VisitedCallees = 0);
289
290  void RunPathSensitiveChecks(Decl *D,
291                              ExprEngine::InliningModes IMode,
292                              SetOfConstDecls *VisitedCallees);
293  void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
294                        ExprEngine::InliningModes IMode,
295                        SetOfConstDecls *VisitedCallees);
296
297  /// Visitors for the RecursiveASTVisitor.
298  bool shouldWalkTypesOfTypeLocs() const { return false; }
299
300  /// Handle callbacks for arbitrary Decls.
301  bool VisitDecl(Decl *D) {
302    AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
303    if (Mode & AM_Syntax)
304      checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
305    return true;
306  }
307
308  bool VisitFunctionDecl(FunctionDecl *FD) {
309    IdentifierInfo *II = FD->getIdentifier();
310    if (II && II->getName().startswith("__inline"))
311      return true;
312
313    // We skip function template definitions, as their semantics is
314    // only determined when they are instantiated.
315    if (FD->isThisDeclarationADefinition() &&
316        !FD->isDependentContext()) {
317      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
318      HandleCode(FD, RecVisitorMode);
319    }
320    return true;
321  }
322
323  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
324    if (MD->isThisDeclarationADefinition()) {
325      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
326      HandleCode(MD, RecVisitorMode);
327    }
328    return true;
329  }
330
331private:
332  void storeTopLevelDecls(DeclGroupRef DG);
333
334  /// \brief Check if we should skip (not analyze) the given function.
335  AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
336
337};
338} // end anonymous namespace
339
340
341//===----------------------------------------------------------------------===//
342// AnalysisConsumer implementation.
343//===----------------------------------------------------------------------===//
344llvm::Timer* AnalysisConsumer::TUTotalTimer = 0;
345
346bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
347  storeTopLevelDecls(DG);
348  return true;
349}
350
351void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
352  storeTopLevelDecls(DG);
353}
354
355void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
356  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
357
358    // Skip ObjCMethodDecl, wait for the objc container to avoid
359    // analyzing twice.
360    if (isa<ObjCMethodDecl>(*I))
361      continue;
362
363    LocalTUDecls.push_back(*I);
364  }
365}
366
367static bool shouldSkipFunction(const Decl *D,
368                               SetOfConstDecls Visited,
369                               SetOfConstDecls VisitedAsTopLevel) {
370  if (VisitedAsTopLevel.count(D))
371    return true;
372
373  // We want to re-analyse the functions as top level in the following cases:
374  // - The 'init' methods should be reanalyzed because
375  //   ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
376  //   'nil' and unless we analyze the 'init' functions as top level, we will
377  //   not catch errors within defensive code.
378  // - We want to reanalyze all ObjC methods as top level to report Retain
379  //   Count naming convention errors more aggressively.
380  if (isa<ObjCMethodDecl>(D))
381    return false;
382
383  // Otherwise, if we visited the function before, do not reanalyze it.
384  return Visited.count(D);
385}
386
387ExprEngine::InliningModes
388AnalysisConsumer::getInliningModeForFunction(const Decl *D,
389                                             SetOfConstDecls Visited) {
390  ExprEngine::InliningModes HowToInline =
391      (Mgr->shouldInlineCall()) ? ExprEngine::Inline_All :
392                                  ExprEngine::Inline_None;
393
394  // We want to reanalyze all ObjC methods as top level to report Retain
395  // Count naming convention errors more aggressively. But we can turn off
396  // inlining when reanalyzing an already inlined function.
397  if (Visited.count(D)) {
398    assert(isa<ObjCMethodDecl>(D) &&
399           "We are only reanalyzing ObjCMethods.");
400    const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
401    if (ObjCM->getMethodFamily() != OMF_init)
402      HowToInline = ExprEngine::Inline_None;
403  }
404
405  return HowToInline;
406}
407
408void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
409  // Otherwise, use the Callgraph to derive the order.
410  // Build the Call Graph.
411  CallGraph CG;
412
413  // Add all the top level declarations to the graph.
414  // Note: CallGraph can trigger deserialization of more items from a pch
415  // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
416  // We rely on random access to add the initially processed Decls to CG.
417  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
418    CG.addToCallGraph(LocalTUDecls[i]);
419  }
420
421  // Find the top level nodes - children of root + the unreachable (parentless)
422  // nodes.
423  llvm::SmallVector<CallGraphNode*, 24> TopLevelFunctions;
424  for (CallGraph::nodes_iterator TI = CG.parentless_begin(),
425                                 TE = CG.parentless_end(); TI != TE; ++TI) {
426    TopLevelFunctions.push_back(*TI);
427    NumFunctionTopLevel++;
428  }
429  CallGraphNode *Entry = CG.getRoot();
430  for (CallGraphNode::iterator I = Entry->begin(),
431                               E = Entry->end(); I != E; ++I) {
432    TopLevelFunctions.push_back(*I);
433    NumFunctionTopLevel++;
434  }
435
436  // Make sure the nodes are sorted in order reverse of their definition in the
437  // translation unit. This step is very important for performance. It ensures
438  // that we analyze the root functions before the externally available
439  // subroutines.
440  std::deque<CallGraphNode*> BFSQueue;
441  for (llvm::SmallVector<CallGraphNode*, 24>::reverse_iterator
442         TI = TopLevelFunctions.rbegin(), TE = TopLevelFunctions.rend();
443         TI != TE; ++TI)
444    BFSQueue.push_back(*TI);
445
446  // BFS over all of the functions, while skipping the ones inlined into
447  // the previously processed functions. Use external Visited set, which is
448  // also modified when we inline a function.
449  SetOfConstDecls Visited;
450  SetOfConstDecls VisitedAsTopLevel;
451  while(!BFSQueue.empty()) {
452    CallGraphNode *N = BFSQueue.front();
453    BFSQueue.pop_front();
454
455    // Push the children into the queue.
456    for (CallGraphNode::const_iterator CI = N->begin(),
457         CE = N->end(); CI != CE; ++CI) {
458      if (!shouldSkipFunction((*CI)->getDecl(), Visited, VisitedAsTopLevel))
459        BFSQueue.push_back(*CI);
460    }
461
462    Decl *D = N->getDecl();
463    assert(D);
464
465    // Skip the functions which have been processed already or previously
466    // inlined.
467    if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
468      continue;
469
470    // Analyze the function.
471    SetOfConstDecls VisitedCallees;
472
473    HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
474               (Mgr->options.InliningMode == All ? 0 : &VisitedCallees));
475
476    // Add the visited callees to the global visited set.
477    for (SetOfConstDecls::iterator I = VisitedCallees.begin(),
478                                   E = VisitedCallees.end(); I != E; ++I) {
479        Visited.insert(*I);
480    }
481    VisitedAsTopLevel.insert(D);
482  }
483}
484
485void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
486  // Don't run the actions if an error has occurred with parsing the file.
487  DiagnosticsEngine &Diags = PP.getDiagnostics();
488  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
489    return;
490
491  {
492    if (TUTotalTimer) TUTotalTimer->startTimer();
493
494    // Introduce a scope to destroy BR before Mgr.
495    BugReporter BR(*Mgr);
496    TranslationUnitDecl *TU = C.getTranslationUnitDecl();
497    checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
498
499    // Run the AST-only checks using the order in which functions are defined.
500    // If inlining is not turned on, use the simplest function order for path
501    // sensitive analyzes as well.
502    RecVisitorMode = AM_Syntax;
503    if (!Mgr->shouldInlineCall())
504      RecVisitorMode |= AM_Path;
505    RecVisitorBR = &BR;
506
507    // Process all the top level declarations.
508    //
509    // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
510    // entries.  Thus we don't use an iterator, but rely on LocalTUDecls
511    // random access.  By doing so, we automatically compensate for iterators
512    // possibly being invalidated, although this is a bit slower.
513    const unsigned LocalTUDeclsSize = LocalTUDecls.size();
514    for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
515      TraverseDecl(LocalTUDecls[i]);
516    }
517
518    if (Mgr->shouldInlineCall())
519      HandleDeclsCallGraph(LocalTUDeclsSize);
520
521    // After all decls handled, run checkers on the entire TranslationUnit.
522    checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
523
524    RecVisitorBR = 0;
525  }
526
527  // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
528  // FIXME: This should be replaced with something that doesn't rely on
529  // side-effects in PathDiagnosticConsumer's destructor. This is required when
530  // used with option -disable-free.
531  Mgr.reset(NULL);
532
533  if (TUTotalTimer) TUTotalTimer->stopTimer();
534
535  // Count how many basic blocks we have not covered.
536  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
537  if (NumBlocksInAnalyzedFunctions > 0)
538    PercentReachableBlocks =
539      (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
540        NumBlocksInAnalyzedFunctions;
541
542}
543
544static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
545  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
546    WL.push_back(BD);
547
548  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
549       I!=E; ++I)
550    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
551      FindBlocks(DC, WL);
552}
553
554static std::string getFunctionName(const Decl *D) {
555  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
556    return ID->getSelector().getAsString();
557  }
558  if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
559    IdentifierInfo *II = ND->getIdentifier();
560    if (II)
561      return II->getName();
562  }
563  return "";
564}
565
566AnalysisConsumer::AnalysisMode
567AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
568  if (!Opts->AnalyzeSpecificFunction.empty() &&
569      getFunctionName(D) != Opts->AnalyzeSpecificFunction)
570    return AM_None;
571
572  // Unless -analyze-all is specified, treat decls differently depending on
573  // where they came from:
574  // - Main source file: run both path-sensitive and non-path-sensitive checks.
575  // - Header files: run non-path-sensitive checks only.
576  // - System headers: don't run any checks.
577  SourceManager &SM = Ctx->getSourceManager();
578  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
579  if (!Opts->AnalyzeAll && !SM.isFromMainFile(SL)) {
580    if (SL.isInvalid() || SM.isInSystemHeader(SL))
581      return AM_None;
582    return Mode & ~AM_Path;
583  }
584
585  return Mode;
586}
587
588void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
589                                  ExprEngine::InliningModes IMode,
590                                  SetOfConstDecls *VisitedCallees) {
591  Mode = getModeForDecl(D, Mode);
592  if (Mode == AM_None)
593    return;
594
595  DisplayFunction(D, Mode);
596  CFG *DeclCFG = Mgr->getCFG(D);
597  if (DeclCFG) {
598    unsigned CFGSize = DeclCFG->size();
599    MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
600  }
601
602
603  // Clear the AnalysisManager of old AnalysisDeclContexts.
604  Mgr->ClearContexts();
605
606  // Dispatch on the actions.
607  SmallVector<Decl*, 10> WL;
608  WL.push_back(D);
609
610  if (D->hasBody() && Opts->AnalyzeNestedBlocks)
611    FindBlocks(cast<DeclContext>(D), WL);
612
613  BugReporter BR(*Mgr);
614  for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
615       WI != WE; ++WI)
616    if ((*WI)->hasBody()) {
617      if (Mode & AM_Syntax)
618        checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
619      if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
620        RunPathSensitiveChecks(*WI, IMode, VisitedCallees);
621        if (IMode != ExprEngine::Inline_None)
622          NumFunctionsAnalyzed++;
623      }
624    }
625}
626
627//===----------------------------------------------------------------------===//
628// Path-sensitive checking.
629//===----------------------------------------------------------------------===//
630
631void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
632                                        ExprEngine::InliningModes IMode,
633                                        SetOfConstDecls *VisitedCallees) {
634  // Construct the analysis engine.  First check if the CFG is valid.
635  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
636  if (!Mgr->getCFG(D))
637    return;
638
639  // See if the LiveVariables analysis scales.
640  if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
641    return;
642
643  ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
644
645  // Set the graph auditor.
646  OwningPtr<ExplodedNode::Auditor> Auditor;
647  if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
648    Auditor.reset(CreateUbiViz());
649    ExplodedNode::SetAuditor(Auditor.get());
650  }
651
652  // Execute the worklist algorithm.
653  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
654                      Mgr->options.MaxNodes);
655
656  // Release the auditor (if any) so that it doesn't monitor the graph
657  // created BugReporter.
658  ExplodedNode::SetAuditor(0);
659
660  // Visualize the exploded graph.
661  if (Mgr->options.visualizeExplodedGraphWithGraphViz)
662    Eng.ViewGraph(Mgr->options.TrimGraph);
663
664  // Display warnings.
665  Eng.getBugReporter().FlushReports();
666}
667
668void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
669                                              ExprEngine::InliningModes IMode,
670                                              SetOfConstDecls *Visited) {
671
672  switch (Mgr->getLangOpts().getGC()) {
673  case LangOptions::NonGC:
674    ActionExprEngine(D, false, IMode, Visited);
675    break;
676
677  case LangOptions::GCOnly:
678    ActionExprEngine(D, true, IMode, Visited);
679    break;
680
681  case LangOptions::HybridGC:
682    ActionExprEngine(D, false, IMode, Visited);
683    ActionExprEngine(D, true, IMode, Visited);
684    break;
685  }
686}
687
688//===----------------------------------------------------------------------===//
689// AnalysisConsumer creation.
690//===----------------------------------------------------------------------===//
691
692ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
693                                          const std::string& outDir,
694                                          AnalyzerOptionsRef opts,
695                                          ArrayRef<std::string> plugins) {
696  // Disable the effects of '-Werror' when using the AnalysisConsumer.
697  pp.getDiagnostics().setWarningsAsErrors(false);
698
699  return new AnalysisConsumer(pp, outDir, opts, plugins);
700}
701
702//===----------------------------------------------------------------------===//
703// Ubigraph Visualization.  FIXME: Move to separate file.
704//===----------------------------------------------------------------------===//
705
706namespace {
707
708class UbigraphViz : public ExplodedNode::Auditor {
709  OwningPtr<raw_ostream> Out;
710  llvm::sys::Path Dir, Filename;
711  unsigned Cntr;
712
713  typedef llvm::DenseMap<void*,unsigned> VMap;
714  VMap M;
715
716public:
717  UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
718              llvm::sys::Path& filename);
719
720  ~UbigraphViz();
721
722  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
723};
724
725} // end anonymous namespace
726
727static ExplodedNode::Auditor* CreateUbiViz() {
728  std::string ErrMsg;
729
730  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
731  if (!ErrMsg.empty())
732    return 0;
733
734  llvm::sys::Path Filename = Dir;
735  Filename.appendComponent("llvm_ubi");
736  Filename.makeUnique(true,&ErrMsg);
737
738  if (!ErrMsg.empty())
739    return 0;
740
741  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
742
743  OwningPtr<llvm::raw_fd_ostream> Stream;
744  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
745
746  if (!ErrMsg.empty())
747    return 0;
748
749  return new UbigraphViz(Stream.take(), Dir, Filename);
750}
751
752void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
753
754  assert (Src != Dst && "Self-edges are not allowed.");
755
756  // Lookup the Src.  If it is a new node, it's a root.
757  VMap::iterator SrcI= M.find(Src);
758  unsigned SrcID;
759
760  if (SrcI == M.end()) {
761    M[Src] = SrcID = Cntr++;
762    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
763  }
764  else
765    SrcID = SrcI->second;
766
767  // Lookup the Dst.
768  VMap::iterator DstI= M.find(Dst);
769  unsigned DstID;
770
771  if (DstI == M.end()) {
772    M[Dst] = DstID = Cntr++;
773    *Out << "('vertex', " << DstID << ")\n";
774  }
775  else {
776    // We have hit DstID before.  Change its style to reflect a cache hit.
777    DstID = DstI->second;
778    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
779  }
780
781  // Add the edge.
782  *Out << "('edge', " << SrcID << ", " << DstID
783       << ", ('arrow','true'), ('oriented', 'true'))\n";
784}
785
786UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
787                         llvm::sys::Path& filename)
788  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
789
790  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
791  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
792          " ('size', '1.5'))\n";
793}
794
795UbigraphViz::~UbigraphViz() {
796  Out.reset(0);
797  llvm::errs() << "Running 'ubiviz' program... ";
798  std::string ErrMsg;
799  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
800  std::vector<const char*> args;
801  args.push_back(Ubiviz.c_str());
802  args.push_back(Filename.c_str());
803  args.push_back(0);
804
805  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
806    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
807  }
808
809  // Delete the directory.
810  Dir.eraseFromDisk(true);
811}
812