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