1218887Sdim//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2218887Sdim//
3218887Sdim//                     The LLVM Compiler Infrastructure
4218887Sdim//
5218887Sdim// This file is distributed under the University of Illinois Open Source
6218887Sdim// License. See LICENSE.TXT for details.
7218887Sdim//
8218887Sdim//===----------------------------------------------------------------------===//
9218887Sdim//
10218887Sdim// "Meta" ASTConsumer for running different source analyses.
11218887Sdim//
12218887Sdim//===----------------------------------------------------------------------===//
13218887Sdim
14234353Sdim#define DEBUG_TYPE "AnalysisConsumer"
15234353Sdim
16218887Sdim#include "AnalysisConsumer.h"
17218887Sdim#include "clang/AST/ASTConsumer.h"
18218887Sdim#include "clang/AST/Decl.h"
19218887Sdim#include "clang/AST/DeclCXX.h"
20218887Sdim#include "clang/AST/DeclObjC.h"
21218887Sdim#include "clang/AST/ParentMap.h"
22234353Sdim#include "clang/AST/RecursiveASTVisitor.h"
23249423Sdim#include "clang/Analysis/Analyses/LiveVariables.h"
24218887Sdim#include "clang/Analysis/CFG.h"
25234353Sdim#include "clang/Analysis/CallGraph.h"
26249423Sdim#include "clang/Basic/FileManager.h"
27249423Sdim#include "clang/Basic/SourceManager.h"
28249423Sdim#include "clang/Lex/Preprocessor.h"
29218887Sdim#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
30249423Sdim#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
31249423Sdim#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
32218887Sdim#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
33249423Sdim#include "clang/StaticAnalyzer/Core/CheckerManager.h"
34249423Sdim#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
35218887Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
36218887Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
37249423Sdim#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
38234353Sdim#include "llvm/ADT/DepthFirstIterator.h"
39218887Sdim#include "llvm/ADT/OwningPtr.h"
40249423Sdim#include "llvm/ADT/PostOrderIterator.h"
41234353Sdim#include "llvm/ADT/SmallPtrSet.h"
42234353Sdim#include "llvm/ADT/Statistic.h"
43263508Sdim#include "llvm/Support/FileSystem.h"
44249423Sdim#include "llvm/Support/Path.h"
45249423Sdim#include "llvm/Support/Program.h"
46249423Sdim#include "llvm/Support/Timer.h"
47249423Sdim#include "llvm/Support/raw_ostream.h"
48234353Sdim#include <queue>
49234353Sdim
50218887Sdimusing namespace clang;
51218887Sdimusing namespace ento;
52234353Sdimusing llvm::SmallPtrSet;
53218887Sdim
54218887Sdimstatic ExplodedNode::Auditor* CreateUbiViz();
55218887Sdim
56234353SdimSTATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
57249423SdimSTATISTIC(NumFunctionsAnalyzed,
58249423Sdim                      "The # of functions and blocks analyzed (as top level "
59249423Sdim                      "with inlining turned on).");
60234353SdimSTATISTIC(NumBlocksInAnalyzedFunctions,
61249423Sdim                      "The # of basic blocks in the analyzed functions.");
62234353SdimSTATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
63239462SdimSTATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
64234353Sdim
65218887Sdim//===----------------------------------------------------------------------===//
66226633Sdim// Special PathDiagnosticConsumers.
67218887Sdim//===----------------------------------------------------------------------===//
68218887Sdim
69263508Sdimvoid ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
70263508Sdim                                             PathDiagnosticConsumers &C,
71263508Sdim                                             const std::string &prefix,
72263508Sdim                                             const Preprocessor &PP) {
73249423Sdim  createHTMLDiagnosticConsumer(AnalyzerOpts, C,
74249423Sdim                               llvm::sys::path::parent_path(prefix), PP);
75249423Sdim  createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
76218887Sdim}
77218887Sdim
78263508Sdimvoid ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
79263508Sdim                                            PathDiagnosticConsumers &C,
80263508Sdim                                            const std::string &Prefix,
81263508Sdim                                            const clang::Preprocessor &PP) {
82263508Sdim  llvm_unreachable("'text' consumer should be enabled on ClangDiags");
83263508Sdim}
84263508Sdim
85239462Sdimnamespace {
86239462Sdimclass ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
87239462Sdim  DiagnosticsEngine &Diag;
88263508Sdim  bool IncludePath;
89239462Sdimpublic:
90263508Sdim  ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
91263508Sdim    : Diag(Diag), IncludePath(false) {}
92239462Sdim  virtual ~ClangDiagPathDiagConsumer() {}
93239462Sdim  virtual StringRef getName() const { return "ClangDiags"; }
94239462Sdim
95263508Sdim  virtual bool supportsLogicalOpControlFlow() const { return true; }
96263508Sdim  virtual bool supportsCrossFileDiagnostics() const { return true; }
97263508Sdim
98263508Sdim  virtual PathGenerationScheme getGenerationScheme() const {
99263508Sdim    return IncludePath ? Minimal : None;
100263508Sdim  }
101263508Sdim
102263508Sdim  void enablePaths() {
103263508Sdim    IncludePath = true;
104263508Sdim  }
105263508Sdim
106263508Sdim  void emitDiag(SourceLocation L, unsigned DiagID,
107263508Sdim                ArrayRef<SourceRange> Ranges) {
108263508Sdim    DiagnosticBuilder DiagBuilder = Diag.Report(L, DiagID);
109263508Sdim
110263508Sdim    for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
111263508Sdim         I != E; ++I) {
112263508Sdim      DiagBuilder << *I;
113263508Sdim    }
114263508Sdim  }
115263508Sdim
116239462Sdim  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
117239462Sdim                            FilesMade *filesMade) {
118239462Sdim    for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
119239462Sdim         E = Diags.end(); I != E; ++I) {
120239462Sdim      const PathDiagnostic *PD = *I;
121243830Sdim      StringRef desc = PD->getShortDescription();
122239462Sdim      SmallString<512> TmpStr;
123239462Sdim      llvm::raw_svector_ostream Out(TmpStr);
124239462Sdim      for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) {
125239462Sdim        if (*I == '%')
126239462Sdim          Out << "%%";
127239462Sdim        else
128239462Sdim          Out << *I;
129239462Sdim      }
130239462Sdim      Out.flush();
131239462Sdim      unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning,
132239462Sdim                                                TmpStr);
133239462Sdim      SourceLocation L = PD->getLocation().asLocation();
134263508Sdim      emitDiag(L, ErrorDiag, PD->path.back()->getRanges());
135239462Sdim
136263508Sdim      if (!IncludePath)
137263508Sdim        continue;
138239462Sdim
139263508Sdim      PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
140263508Sdim      for (PathPieces::const_iterator PI = FlatPath.begin(),
141263508Sdim                                      PE = FlatPath.end();
142263508Sdim           PI != PE; ++PI) {
143263508Sdim        unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note,
144263508Sdim                                               (*PI)->getString());
145263508Sdim
146263508Sdim        SourceLocation NoteLoc = (*PI)->getLocation().asLocation();
147263508Sdim        emitDiag(NoteLoc, NoteID, (*PI)->getRanges());
148239462Sdim      }
149239462Sdim    }
150239462Sdim  }
151239462Sdim};
152239462Sdim} // end anonymous namespace
153239462Sdim
154218887Sdim//===----------------------------------------------------------------------===//
155218887Sdim// AnalysisConsumer declaration.
156218887Sdim//===----------------------------------------------------------------------===//
157218887Sdim
158218887Sdimnamespace {
159218887Sdim
160234353Sdimclass AnalysisConsumer : public ASTConsumer,
161234353Sdim                         public RecursiveASTVisitor<AnalysisConsumer> {
162243830Sdim  enum {
163243830Sdim    AM_None = 0,
164243830Sdim    AM_Syntax = 0x1,
165243830Sdim    AM_Path = 0x2
166234353Sdim  };
167243830Sdim  typedef unsigned AnalysisMode;
168234353Sdim
169234353Sdim  /// Mode of the analyzes while recursively visiting Decls.
170234353Sdim  AnalysisMode RecVisitorMode;
171234353Sdim  /// Bug Reporter to use while recursively visiting Decls.
172234353Sdim  BugReporter *RecVisitorBR;
173234353Sdim
174218887Sdimpublic:
175226633Sdim  ASTContext *Ctx;
176218887Sdim  const Preprocessor &PP;
177218887Sdim  const std::string OutDir;
178243830Sdim  AnalyzerOptionsRef Opts;
179226633Sdim  ArrayRef<std::string> Plugins;
180218887Sdim
181234353Sdim  /// \brief Stores the declarations from the local translation unit.
182234353Sdim  /// Note, we pre-compute the local declarations at parse time as an
183234353Sdim  /// optimization to make sure we do not deserialize everything from disk.
184234353Sdim  /// The local declaration to all declarations ratio might be very small when
185234353Sdim  /// working with a PCH file.
186234353Sdim  SetOfDecls LocalTUDecls;
187239462Sdim
188239462Sdim  // Set of PathDiagnosticConsumers.  Owned by AnalysisManager.
189239462Sdim  PathDiagnosticConsumers PathConsumers;
190234353Sdim
191218887Sdim  StoreManagerCreator CreateStoreMgr;
192218887Sdim  ConstraintManagerCreator CreateConstraintMgr;
193218887Sdim
194234353Sdim  OwningPtr<CheckerManager> checkerMgr;
195234353Sdim  OwningPtr<AnalysisManager> Mgr;
196218887Sdim
197234353Sdim  /// Time the analyzes time of each translation unit.
198234353Sdim  static llvm::Timer* TUTotalTimer;
199234353Sdim
200234353Sdim  /// The information about analyzed functions shared throughout the
201234353Sdim  /// translation unit.
202234353Sdim  FunctionSummariesTy FunctionSummaries;
203234353Sdim
204218887Sdim  AnalysisConsumer(const Preprocessor& pp,
205218887Sdim                   const std::string& outdir,
206243830Sdim                   AnalyzerOptionsRef opts,
207226633Sdim                   ArrayRef<std::string> plugins)
208243830Sdim    : RecVisitorMode(0), RecVisitorBR(0),
209239462Sdim      Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins) {
210218887Sdim    DigestAnalyzerOptions();
211243830Sdim    if (Opts->PrintStats) {
212234353Sdim      llvm::EnableStatistics();
213234353Sdim      TUTotalTimer = new llvm::Timer("Analyzer Total Time");
214234353Sdim    }
215218887Sdim  }
216218887Sdim
217234353Sdim  ~AnalysisConsumer() {
218243830Sdim    if (Opts->PrintStats)
219234353Sdim      delete TUTotalTimer;
220234353Sdim  }
221234353Sdim
222218887Sdim  void DigestAnalyzerOptions() {
223226633Sdim    // Create the PathDiagnosticConsumer.
224263508Sdim    ClangDiagPathDiagConsumer *clangDiags =
225263508Sdim      new ClangDiagPathDiagConsumer(PP.getDiagnostics());
226263508Sdim    PathConsumers.push_back(clangDiags);
227239462Sdim
228263508Sdim    if (Opts->AnalysisDiagOpt == PD_TEXT) {
229263508Sdim      clangDiags->enablePaths();
230263508Sdim
231263508Sdim    } else if (!OutDir.empty()) {
232243830Sdim      switch (Opts->AnalysisDiagOpt) {
233218887Sdim      default:
234263508Sdim#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
235249423Sdim        case PD_##NAME: CREATEFN(*Opts.getPtr(), PathConsumers, OutDir, PP);\
236249423Sdim        break;
237243830Sdim#include "clang/StaticAnalyzer/Core/Analyses.def"
238218887Sdim      }
239218887Sdim    }
240218887Sdim
241218887Sdim    // Create the analyzer component creators.
242243830Sdim    switch (Opts->AnalysisStoreOpt) {
243218887Sdim    default:
244226633Sdim      llvm_unreachable("Unknown store manager.");
245218887Sdim#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
246218887Sdim      case NAME##Model: CreateStoreMgr = CREATEFN; break;
247243830Sdim#include "clang/StaticAnalyzer/Core/Analyses.def"
248218887Sdim    }
249218887Sdim
250243830Sdim    switch (Opts->AnalysisConstraintsOpt) {
251218887Sdim    default:
252249423Sdim      llvm_unreachable("Unknown constraint manager.");
253218887Sdim#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
254218887Sdim      case NAME##Model: CreateConstraintMgr = CREATEFN; break;
255243830Sdim#include "clang/StaticAnalyzer/Core/Analyses.def"
256218887Sdim    }
257218887Sdim  }
258218887Sdim
259249423Sdim  void DisplayFunction(const Decl *D, AnalysisMode Mode,
260249423Sdim                       ExprEngine::InliningModes IMode) {
261243830Sdim    if (!Opts->AnalyzerDisplayProgress)
262218887Sdim      return;
263218887Sdim
264218887Sdim    SourceManager &SM = Mgr->getASTContext().getSourceManager();
265218887Sdim    PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
266218887Sdim    if (Loc.isValid()) {
267234353Sdim      llvm::errs() << "ANALYZE";
268243830Sdim
269243830Sdim      if (Mode == AM_Syntax)
270243830Sdim        llvm::errs() << " (Syntax)";
271249423Sdim      else if (Mode == AM_Path) {
272249423Sdim        llvm::errs() << " (Path, ";
273249423Sdim        switch (IMode) {
274249423Sdim          case ExprEngine::Inline_Minimal:
275249423Sdim            llvm::errs() << " Inline_Minimal";
276249423Sdim            break;
277249423Sdim          case ExprEngine::Inline_Regular:
278249423Sdim            llvm::errs() << " Inline_Regular";
279249423Sdim            break;
280249423Sdim        }
281249423Sdim        llvm::errs() << ")";
282249423Sdim      }
283243830Sdim      else
284243830Sdim        assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
285243830Sdim
286234353Sdim      llvm::errs() << ": " << Loc.getFilename();
287218887Sdim      if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
288218887Sdim        const NamedDecl *ND = cast<NamedDecl>(D);
289226633Sdim        llvm::errs() << ' ' << *ND << '\n';
290218887Sdim      }
291218887Sdim      else if (isa<BlockDecl>(D)) {
292218887Sdim        llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
293218887Sdim                     << Loc.getColumn() << '\n';
294218887Sdim      }
295218887Sdim      else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
296218887Sdim        Selector S = MD->getSelector();
297218887Sdim        llvm::errs() << ' ' << S.getAsString();
298218887Sdim      }
299218887Sdim    }
300218887Sdim  }
301218887Sdim
302218887Sdim  virtual void Initialize(ASTContext &Context) {
303218887Sdim    Ctx = &Context;
304243830Sdim    checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins,
305226633Sdim                                          PP.getDiagnostics()));
306239462Sdim    Mgr.reset(new AnalysisManager(*Ctx,
307239462Sdim                                  PP.getDiagnostics(),
308239462Sdim                                  PP.getLangOpts(),
309239462Sdim                                  PathConsumers,
310239462Sdim                                  CreateStoreMgr,
311239462Sdim                                  CreateConstraintMgr,
312218887Sdim                                  checkerMgr.get(),
313243830Sdim                                  *Opts));
314218887Sdim  }
315218887Sdim
316234353Sdim  /// \brief Store the top level decls in the set to be processed later on.
317234353Sdim  /// (Doing this pre-processing avoids deserialization of data from PCH.)
318234353Sdim  virtual bool HandleTopLevelDecl(DeclGroupRef D);
319234353Sdim  virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D);
320234353Sdim
321218887Sdim  virtual void HandleTranslationUnit(ASTContext &C);
322218887Sdim
323249423Sdim  /// \brief Determine which inlining mode should be used when this function is
324249423Sdim  /// analyzed. This allows to redefine the default inlining policies when
325249423Sdim  /// analyzing a given function.
326249423Sdim  ExprEngine::InliningModes
327249423Sdim  getInliningModeForFunction(const Decl *D, SetOfConstDecls Visited);
328249423Sdim
329234353Sdim  /// \brief Build the call graph for all the top level decls of this TU and
330234353Sdim  /// use it to define the order in which the functions should be visited.
331243830Sdim  void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
332234353Sdim
333234353Sdim  /// \brief Run analyzes(syntax or path sensitive) on the given function.
334234353Sdim  /// \param Mode - determines if we are requesting syntax only or path
335234353Sdim  /// sensitive only analysis.
336234353Sdim  /// \param VisitedCallees - The output parameter, which is populated with the
337234353Sdim  /// set of functions which should be considered analyzed after analyzing the
338234353Sdim  /// given root function.
339234353Sdim  void HandleCode(Decl *D, AnalysisMode Mode,
340249423Sdim                  ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
341234353Sdim                  SetOfConstDecls *VisitedCallees = 0);
342234353Sdim
343249423Sdim  void RunPathSensitiveChecks(Decl *D,
344249423Sdim                              ExprEngine::InliningModes IMode,
345249423Sdim                              SetOfConstDecls *VisitedCallees);
346234353Sdim  void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
347249423Sdim                        ExprEngine::InliningModes IMode,
348234353Sdim                        SetOfConstDecls *VisitedCallees);
349234353Sdim
350234353Sdim  /// Visitors for the RecursiveASTVisitor.
351239462Sdim  bool shouldWalkTypesOfTypeLocs() const { return false; }
352234353Sdim
353234353Sdim  /// Handle callbacks for arbitrary Decls.
354234353Sdim  bool VisitDecl(Decl *D) {
355243830Sdim    AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
356243830Sdim    if (Mode & AM_Syntax)
357243830Sdim      checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
358234353Sdim    return true;
359234353Sdim  }
360234353Sdim
361234353Sdim  bool VisitFunctionDecl(FunctionDecl *FD) {
362234353Sdim    IdentifierInfo *II = FD->getIdentifier();
363234353Sdim    if (II && II->getName().startswith("__inline"))
364234353Sdim      return true;
365234353Sdim
366234353Sdim    // We skip function template definitions, as their semantics is
367234353Sdim    // only determined when they are instantiated.
368234353Sdim    if (FD->isThisDeclarationADefinition() &&
369234353Sdim        !FD->isDependentContext()) {
370249423Sdim      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
371234353Sdim      HandleCode(FD, RecVisitorMode);
372234353Sdim    }
373234353Sdim    return true;
374234353Sdim  }
375234353Sdim
376234353Sdim  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
377249423Sdim    if (MD->isThisDeclarationADefinition()) {
378249423Sdim      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
379234353Sdim      HandleCode(MD, RecVisitorMode);
380249423Sdim    }
381234353Sdim    return true;
382234353Sdim  }
383249423Sdim
384249423Sdim  bool VisitBlockDecl(BlockDecl *BD) {
385249423Sdim    if (BD->hasBody()) {
386249423Sdim      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
387249423Sdim      HandleCode(BD, RecVisitorMode);
388249423Sdim    }
389249423Sdim    return true;
390249423Sdim  }
391234353Sdim
392234353Sdimprivate:
393234353Sdim  void storeTopLevelDecls(DeclGroupRef DG);
394234353Sdim
395234353Sdim  /// \brief Check if we should skip (not analyze) the given function.
396243830Sdim  AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
397234353Sdim
398218887Sdim};
399218887Sdim} // end anonymous namespace
400218887Sdim
401234353Sdim
402218887Sdim//===----------------------------------------------------------------------===//
403218887Sdim// AnalysisConsumer implementation.
404218887Sdim//===----------------------------------------------------------------------===//
405234353Sdimllvm::Timer* AnalysisConsumer::TUTotalTimer = 0;
406218887Sdim
407234353Sdimbool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
408234353Sdim  storeTopLevelDecls(DG);
409234353Sdim  return true;
410234353Sdim}
411234353Sdim
412234353Sdimvoid AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
413234353Sdim  storeTopLevelDecls(DG);
414234353Sdim}
415234353Sdim
416234353Sdimvoid AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
417234353Sdim  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
418234353Sdim
419234353Sdim    // Skip ObjCMethodDecl, wait for the objc container to avoid
420234353Sdim    // analyzing twice.
421234353Sdim    if (isa<ObjCMethodDecl>(*I))
422234353Sdim      continue;
423234353Sdim
424239462Sdim    LocalTUDecls.push_back(*I);
425226633Sdim  }
426226633Sdim}
427226633Sdim
428249423Sdimstatic bool shouldSkipFunction(const Decl *D,
429249423Sdim                               SetOfConstDecls Visited,
430249423Sdim                               SetOfConstDecls VisitedAsTopLevel) {
431249423Sdim  if (VisitedAsTopLevel.count(D))
432249423Sdim    return true;
433249423Sdim
434249423Sdim  // We want to re-analyse the functions as top level in the following cases:
435243830Sdim  // - The 'init' methods should be reanalyzed because
436243830Sdim  //   ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
437249423Sdim  //   'nil' and unless we analyze the 'init' functions as top level, we will
438249423Sdim  //   not catch errors within defensive code.
439243830Sdim  // - We want to reanalyze all ObjC methods as top level to report Retain
440243830Sdim  //   Count naming convention errors more aggressively.
441249423Sdim  if (isa<ObjCMethodDecl>(D))
442243830Sdim    return false;
443243830Sdim
444243830Sdim  // Otherwise, if we visited the function before, do not reanalyze it.
445249423Sdim  return Visited.count(D);
446243830Sdim}
447243830Sdim
448249423SdimExprEngine::InliningModes
449249423SdimAnalysisConsumer::getInliningModeForFunction(const Decl *D,
450249423Sdim                                             SetOfConstDecls Visited) {
451249423Sdim  // We want to reanalyze all ObjC methods as top level to report Retain
452249423Sdim  // Count naming convention errors more aggressively. But we should tune down
453249423Sdim  // inlining when reanalyzing an already inlined function.
454249423Sdim  if (Visited.count(D)) {
455249423Sdim    assert(isa<ObjCMethodDecl>(D) &&
456249423Sdim           "We are only reanalyzing ObjCMethods.");
457249423Sdim    const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
458249423Sdim    if (ObjCM->getMethodFamily() != OMF_init)
459249423Sdim      return ExprEngine::Inline_Minimal;
460249423Sdim  }
461249423Sdim
462249423Sdim  return ExprEngine::Inline_Regular;
463249423Sdim}
464249423Sdim
465243830Sdimvoid AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
466249423Sdim  // Build the Call Graph by adding all the top level declarations to the graph.
467239462Sdim  // Note: CallGraph can trigger deserialization of more items from a pch
468239462Sdim  // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
469239462Sdim  // We rely on random access to add the initially processed Decls to CG.
470249423Sdim  CallGraph CG;
471239462Sdim  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
472239462Sdim    CG.addToCallGraph(LocalTUDecls[i]);
473239462Sdim  }
474234353Sdim
475249423Sdim  // Walk over all of the call graph nodes in topological order, so that we
476249423Sdim  // analyze parents before the children. Skip the functions inlined into
477249423Sdim  // the previously processed functions. Use external Visited set to identify
478249423Sdim  // inlined functions. The topological order allows the "do not reanalyze
479249423Sdim  // previously inlined function" performance heuristic to be triggered more
480249423Sdim  // often.
481249423Sdim  SetOfConstDecls Visited;
482249423Sdim  SetOfConstDecls VisitedAsTopLevel;
483249423Sdim  llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
484249423Sdim  for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
485249423Sdim         I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
486234353Sdim    NumFunctionTopLevel++;
487218887Sdim
488249423Sdim    CallGraphNode *N = *I;
489249423Sdim    Decl *D = N->getDecl();
490249423Sdim
491249423Sdim    // Skip the abstract root node.
492249423Sdim    if (!D)
493249423Sdim      continue;
494234353Sdim
495234353Sdim    // Skip the functions which have been processed already or previously
496234353Sdim    // inlined.
497249423Sdim    if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
498234353Sdim      continue;
499234353Sdim
500234353Sdim    // Analyze the function.
501234353Sdim    SetOfConstDecls VisitedCallees;
502249423Sdim
503249423Sdim    HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
504243830Sdim               (Mgr->options.InliningMode == All ? 0 : &VisitedCallees));
505234353Sdim
506234353Sdim    // Add the visited callees to the global visited set.
507239462Sdim    for (SetOfConstDecls::iterator I = VisitedCallees.begin(),
508239462Sdim                                   E = VisitedCallees.end(); I != E; ++I) {
509249423Sdim        Visited.insert(*I);
510226633Sdim    }
511249423Sdim    VisitedAsTopLevel.insert(D);
512226633Sdim  }
513218887Sdim}
514218887Sdim
515218887Sdimvoid AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
516234353Sdim  // Don't run the actions if an error has occurred with parsing the file.
517234353Sdim  DiagnosticsEngine &Diags = PP.getDiagnostics();
518234353Sdim  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
519234353Sdim    return;
520218887Sdim
521234353Sdim  {
522234353Sdim    if (TUTotalTimer) TUTotalTimer->startTimer();
523223017Sdim
524234353Sdim    // Introduce a scope to destroy BR before Mgr.
525234353Sdim    BugReporter BR(*Mgr);
526234353Sdim    TranslationUnitDecl *TU = C.getTranslationUnitDecl();
527234353Sdim    checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
528234353Sdim
529234353Sdim    // Run the AST-only checks using the order in which functions are defined.
530234353Sdim    // If inlining is not turned on, use the simplest function order for path
531234353Sdim    // sensitive analyzes as well.
532243830Sdim    RecVisitorMode = AM_Syntax;
533243830Sdim    if (!Mgr->shouldInlineCall())
534243830Sdim      RecVisitorMode |= AM_Path;
535234353Sdim    RecVisitorBR = &BR;
536234353Sdim
537234353Sdim    // Process all the top level declarations.
538239462Sdim    //
539239462Sdim    // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
540239462Sdim    // entries.  Thus we don't use an iterator, but rely on LocalTUDecls
541239462Sdim    // random access.  By doing so, we automatically compensate for iterators
542239462Sdim    // possibly being invalidated, although this is a bit slower.
543239462Sdim    const unsigned LocalTUDeclsSize = LocalTUDecls.size();
544239462Sdim    for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
545239462Sdim      TraverseDecl(LocalTUDecls[i]);
546239462Sdim    }
547234353Sdim
548234353Sdim    if (Mgr->shouldInlineCall())
549243830Sdim      HandleDeclsCallGraph(LocalTUDeclsSize);
550234353Sdim
551234353Sdim    // After all decls handled, run checkers on the entire TranslationUnit.
552234353Sdim    checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
553234353Sdim
554234353Sdim    RecVisitorBR = 0;
555234353Sdim  }
556234353Sdim
557226633Sdim  // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
558218887Sdim  // FIXME: This should be replaced with something that doesn't rely on
559226633Sdim  // side-effects in PathDiagnosticConsumer's destructor. This is required when
560218887Sdim  // used with option -disable-free.
561218887Sdim  Mgr.reset(NULL);
562234353Sdim
563234353Sdim  if (TUTotalTimer) TUTotalTimer->stopTimer();
564234353Sdim
565234353Sdim  // Count how many basic blocks we have not covered.
566234353Sdim  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
567234353Sdim  if (NumBlocksInAnalyzedFunctions > 0)
568234353Sdim    PercentReachableBlocks =
569234353Sdim      (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
570234353Sdim        NumBlocksInAnalyzedFunctions;
571234353Sdim
572218887Sdim}
573218887Sdim
574234353Sdimstatic std::string getFunctionName(const Decl *D) {
575234353Sdim  if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) {
576234353Sdim    return ID->getSelector().getAsString();
577234353Sdim  }
578234353Sdim  if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) {
579234353Sdim    IdentifierInfo *II = ND->getIdentifier();
580234353Sdim    if (II)
581234353Sdim      return II->getName();
582234353Sdim  }
583234353Sdim  return "";
584234353Sdim}
585218887Sdim
586243830SdimAnalysisConsumer::AnalysisMode
587243830SdimAnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
588243830Sdim  if (!Opts->AnalyzeSpecificFunction.empty() &&
589243830Sdim      getFunctionName(D) != Opts->AnalyzeSpecificFunction)
590243830Sdim    return AM_None;
591221345Sdim
592243830Sdim  // Unless -analyze-all is specified, treat decls differently depending on
593243830Sdim  // where they came from:
594243830Sdim  // - Main source file: run both path-sensitive and non-path-sensitive checks.
595243830Sdim  // - Header files: run non-path-sensitive checks only.
596243830Sdim  // - System headers: don't run any checks.
597218887Sdim  SourceManager &SM = Ctx->getSourceManager();
598226633Sdim  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
599263508Sdim  if (!Opts->AnalyzeAll && !SM.isInMainFile(SL)) {
600243830Sdim    if (SL.isInvalid() || SM.isInSystemHeader(SL))
601243830Sdim      return AM_None;
602243830Sdim    return Mode & ~AM_Path;
603243830Sdim  }
604234353Sdim
605243830Sdim  return Mode;
606234353Sdim}
607234353Sdim
608234353Sdimvoid AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
609249423Sdim                                  ExprEngine::InliningModes IMode,
610234353Sdim                                  SetOfConstDecls *VisitedCallees) {
611249423Sdim  if (!D->hasBody())
612249423Sdim    return;
613243830Sdim  Mode = getModeForDecl(D, Mode);
614243830Sdim  if (Mode == AM_None)
615218887Sdim    return;
616218887Sdim
617249423Sdim  DisplayFunction(D, Mode, IMode);
618239462Sdim  CFG *DeclCFG = Mgr->getCFG(D);
619239462Sdim  if (DeclCFG) {
620239462Sdim    unsigned CFGSize = DeclCFG->size();
621239462Sdim    MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize;
622239462Sdim  }
623234353Sdim
624234353Sdim  // Clear the AnalysisManager of old AnalysisDeclContexts.
625218887Sdim  Mgr->ClearContexts();
626249423Sdim  BugReporter BR(*Mgr);
627218887Sdim
628249423Sdim  if (Mode & AM_Syntax)
629249423Sdim    checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
630249423Sdim  if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
631249423Sdim    RunPathSensitiveChecks(D, IMode, VisitedCallees);
632249423Sdim    if (IMode != ExprEngine::Inline_Minimal)
633249423Sdim      NumFunctionsAnalyzed++;
634249423Sdim  }
635218887Sdim}
636218887Sdim
637218887Sdim//===----------------------------------------------------------------------===//
638221345Sdim// Path-sensitive checking.
639218887Sdim//===----------------------------------------------------------------------===//
640218887Sdim
641234353Sdimvoid AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
642249423Sdim                                        ExprEngine::InliningModes IMode,
643234353Sdim                                        SetOfConstDecls *VisitedCallees) {
644226633Sdim  // Construct the analysis engine.  First check if the CFG is valid.
645218887Sdim  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
646234353Sdim  if (!Mgr->getCFG(D))
647218887Sdim    return;
648218887Sdim
649239462Sdim  // See if the LiveVariables analysis scales.
650239462Sdim  if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
651239462Sdim    return;
652239462Sdim
653249423Sdim  ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode);
654234353Sdim
655218887Sdim  // Set the graph auditor.
656234353Sdim  OwningPtr<ExplodedNode::Auditor> Auditor;
657243830Sdim  if (Mgr->options.visualizeExplodedGraphWithUbiGraph) {
658218887Sdim    Auditor.reset(CreateUbiViz());
659218887Sdim    ExplodedNode::SetAuditor(Auditor.get());
660218887Sdim  }
661218887Sdim
662218887Sdim  // Execute the worklist algorithm.
663239462Sdim  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
664249423Sdim                      Mgr->options.getMaxNodesPerTopLevelFunction());
665218887Sdim
666218887Sdim  // Release the auditor (if any) so that it doesn't monitor the graph
667218887Sdim  // created BugReporter.
668218887Sdim  ExplodedNode::SetAuditor(0);
669218887Sdim
670218887Sdim  // Visualize the exploded graph.
671243830Sdim  if (Mgr->options.visualizeExplodedGraphWithGraphViz)
672243830Sdim    Eng.ViewGraph(Mgr->options.TrimGraph);
673218887Sdim
674218887Sdim  // Display warnings.
675218887Sdim  Eng.getBugReporter().FlushReports();
676218887Sdim}
677218887Sdim
678234353Sdimvoid AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
679249423Sdim                                              ExprEngine::InliningModes IMode,
680234353Sdim                                              SetOfConstDecls *Visited) {
681218887Sdim
682234353Sdim  switch (Mgr->getLangOpts().getGC()) {
683226633Sdim  case LangOptions::NonGC:
684249423Sdim    ActionExprEngine(D, false, IMode, Visited);
685226633Sdim    break;
686226633Sdim
687226633Sdim  case LangOptions::GCOnly:
688249423Sdim    ActionExprEngine(D, true, IMode, Visited);
689226633Sdim    break;
690226633Sdim
691226633Sdim  case LangOptions::HybridGC:
692249423Sdim    ActionExprEngine(D, false, IMode, Visited);
693249423Sdim    ActionExprEngine(D, true, IMode, Visited);
694226633Sdim    break;
695226633Sdim  }
696218887Sdim}
697218887Sdim
698218887Sdim//===----------------------------------------------------------------------===//
699218887Sdim// AnalysisConsumer creation.
700218887Sdim//===----------------------------------------------------------------------===//
701218887Sdim
702218887SdimASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
703226633Sdim                                          const std::string& outDir,
704243830Sdim                                          AnalyzerOptionsRef opts,
705226633Sdim                                          ArrayRef<std::string> plugins) {
706226633Sdim  // Disable the effects of '-Werror' when using the AnalysisConsumer.
707218887Sdim  pp.getDiagnostics().setWarningsAsErrors(false);
708218887Sdim
709226633Sdim  return new AnalysisConsumer(pp, outDir, opts, plugins);
710218887Sdim}
711218887Sdim
712218887Sdim//===----------------------------------------------------------------------===//
713218887Sdim// Ubigraph Visualization.  FIXME: Move to separate file.
714218887Sdim//===----------------------------------------------------------------------===//
715218887Sdim
716218887Sdimnamespace {
717218887Sdim
718218887Sdimclass UbigraphViz : public ExplodedNode::Auditor {
719234353Sdim  OwningPtr<raw_ostream> Out;
720263508Sdim  std::string Filename;
721218887Sdim  unsigned Cntr;
722218887Sdim
723218887Sdim  typedef llvm::DenseMap<void*,unsigned> VMap;
724218887Sdim  VMap M;
725218887Sdim
726218887Sdimpublic:
727263508Sdim  UbigraphViz(raw_ostream *Out, StringRef Filename);
728218887Sdim
729218887Sdim  ~UbigraphViz();
730218887Sdim
731226633Sdim  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
732218887Sdim};
733218887Sdim
734218887Sdim} // end anonymous namespace
735218887Sdim
736218887Sdimstatic ExplodedNode::Auditor* CreateUbiViz() {
737263508Sdim  SmallString<128> P;
738263508Sdim  int FD;
739263508Sdim  llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P);
740263508Sdim  llvm::errs() << "Writing '" << P.str() << "'.\n";
741218887Sdim
742234353Sdim  OwningPtr<llvm::raw_fd_ostream> Stream;
743263508Sdim  Stream.reset(new llvm::raw_fd_ostream(FD, true));
744218887Sdim
745263508Sdim  return new UbigraphViz(Stream.take(), P);
746218887Sdim}
747218887Sdim
748226633Sdimvoid UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
749218887Sdim
750218887Sdim  assert (Src != Dst && "Self-edges are not allowed.");
751218887Sdim
752218887Sdim  // Lookup the Src.  If it is a new node, it's a root.
753218887Sdim  VMap::iterator SrcI= M.find(Src);
754218887Sdim  unsigned SrcID;
755218887Sdim
756218887Sdim  if (SrcI == M.end()) {
757218887Sdim    M[Src] = SrcID = Cntr++;
758218887Sdim    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
759218887Sdim  }
760218887Sdim  else
761218887Sdim    SrcID = SrcI->second;
762218887Sdim
763218887Sdim  // Lookup the Dst.
764218887Sdim  VMap::iterator DstI= M.find(Dst);
765218887Sdim  unsigned DstID;
766218887Sdim
767218887Sdim  if (DstI == M.end()) {
768218887Sdim    M[Dst] = DstID = Cntr++;
769218887Sdim    *Out << "('vertex', " << DstID << ")\n";
770218887Sdim  }
771218887Sdim  else {
772218887Sdim    // We have hit DstID before.  Change its style to reflect a cache hit.
773218887Sdim    DstID = DstI->second;
774218887Sdim    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
775218887Sdim  }
776218887Sdim
777218887Sdim  // Add the edge.
778218887Sdim  *Out << "('edge', " << SrcID << ", " << DstID
779218887Sdim       << ", ('arrow','true'), ('oriented', 'true'))\n";
780218887Sdim}
781218887Sdim
782263508SdimUbigraphViz::UbigraphViz(raw_ostream *Out, StringRef Filename)
783263508Sdim  : Out(Out), Filename(Filename), Cntr(0) {
784218887Sdim
785218887Sdim  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
786218887Sdim  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
787218887Sdim          " ('size', '1.5'))\n";
788218887Sdim}
789218887Sdim
790218887SdimUbigraphViz::~UbigraphViz() {
791218887Sdim  Out.reset(0);
792218887Sdim  llvm::errs() << "Running 'ubiviz' program... ";
793218887Sdim  std::string ErrMsg;
794263508Sdim  std::string Ubiviz = llvm::sys::FindProgramByName("ubiviz");
795218887Sdim  std::vector<const char*> args;
796218887Sdim  args.push_back(Ubiviz.c_str());
797218887Sdim  args.push_back(Filename.c_str());
798218887Sdim  args.push_back(0);
799218887Sdim
800263508Sdim  if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], 0, 0, 0, 0, &ErrMsg)) {
801218887Sdim    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
802218887Sdim  }
803218887Sdim
804263508Sdim  // Delete the file.
805263508Sdim  llvm::sys::fs::remove(Filename);
806218887Sdim}
807