AnalysisConsumer.cpp revision c5bdc556f6a65c677e0ed73f918c3000ecad33af
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#include "AnalysisConsumer.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/Analysis/CFG.h"
21#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
22#include "clang/StaticAnalyzer/Core/CheckerManager.h"
23#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
26#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
28#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
29
30#include "clang/Basic/FileManager.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Frontend/AnalyzerOptions.h"
33#include "clang/Lex/Preprocessor.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Support/Path.h"
36#include "llvm/Support/Program.h"
37#include "llvm/ADT/OwningPtr.h"
38
39using namespace clang;
40using namespace ento;
41
42static ExplodedNode::Auditor* CreateUbiViz();
43
44//===----------------------------------------------------------------------===//
45// Special PathDiagnosticConsumers.
46//===----------------------------------------------------------------------===//
47
48static PathDiagnosticConsumer*
49createPlistHTMLDiagnosticConsumer(const std::string& prefix,
50                                const Preprocessor &PP) {
51  PathDiagnosticConsumer *PD =
52    createHTMLDiagnosticConsumer(llvm::sys::path::parent_path(prefix), PP);
53  return createPlistDiagnosticConsumer(prefix, PP, PD);
54}
55
56//===----------------------------------------------------------------------===//
57// AnalysisConsumer declaration.
58//===----------------------------------------------------------------------===//
59
60namespace {
61
62class AnalysisConsumer : public ASTConsumer {
63public:
64  ASTContext *Ctx;
65  const Preprocessor &PP;
66  const std::string OutDir;
67  AnalyzerOptions Opts;
68  ArrayRef<std::string> Plugins;
69
70  // PD is owned by AnalysisManager.
71  PathDiagnosticConsumer *PD;
72
73  StoreManagerCreator CreateStoreMgr;
74  ConstraintManagerCreator CreateConstraintMgr;
75
76  llvm::OwningPtr<CheckerManager> checkerMgr;
77  llvm::OwningPtr<AnalysisManager> Mgr;
78
79  AnalysisConsumer(const Preprocessor& pp,
80                   const std::string& outdir,
81                   const AnalyzerOptions& opts,
82                   ArrayRef<std::string> plugins)
83    : Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins), PD(0) {
84    DigestAnalyzerOptions();
85  }
86
87  void DigestAnalyzerOptions() {
88    // Create the PathDiagnosticConsumer.
89    if (!OutDir.empty()) {
90      switch (Opts.AnalysisDiagOpt) {
91      default:
92#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
93        case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
94#include "clang/Frontend/Analyses.def"
95      }
96    } else if (Opts.AnalysisDiagOpt == PD_TEXT) {
97      // Create the text client even without a specified output file since
98      // it just uses diagnostic notes.
99      PD = createTextPathDiagnosticConsumer("", PP);
100    }
101
102    // Create the analyzer component creators.
103    switch (Opts.AnalysisStoreOpt) {
104    default:
105      llvm_unreachable("Unknown store manager.");
106#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
107      case NAME##Model: CreateStoreMgr = CREATEFN; break;
108#include "clang/Frontend/Analyses.def"
109    }
110
111    switch (Opts.AnalysisConstraintsOpt) {
112    default:
113      llvm_unreachable("Unknown store manager.");
114#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
115      case NAME##Model: CreateConstraintMgr = CREATEFN; break;
116#include "clang/Frontend/Analyses.def"
117    }
118  }
119
120  void DisplayFunction(const Decl *D) {
121    if (!Opts.AnalyzerDisplayProgress)
122      return;
123
124    SourceManager &SM = Mgr->getASTContext().getSourceManager();
125    PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
126    if (Loc.isValid()) {
127      llvm::errs() << "ANALYZE: " << Loc.getFilename();
128
129      if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
130        const NamedDecl *ND = cast<NamedDecl>(D);
131        llvm::errs() << ' ' << *ND << '\n';
132      }
133      else if (isa<BlockDecl>(D)) {
134        llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
135                     << Loc.getColumn() << '\n';
136      }
137      else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
138        Selector S = MD->getSelector();
139        llvm::errs() << ' ' << S.getAsString();
140      }
141    }
142  }
143
144  virtual void Initialize(ASTContext &Context) {
145    Ctx = &Context;
146    checkerMgr.reset(createCheckerManager(Opts, PP.getLangOptions(), Plugins,
147                                          PP.getDiagnostics()));
148    Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
149                                  PP.getLangOptions(), PD,
150                                  CreateStoreMgr, CreateConstraintMgr,
151                                  checkerMgr.get(),
152                                  /* Indexer */ 0,
153                                  Opts.MaxNodes, Opts.MaxLoop,
154                                  Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
155                                  Opts.AnalysisPurgeOpt, Opts.EagerlyAssume,
156                                  Opts.TrimGraph, Opts.InlineCall,
157                                  Opts.UnoptimizedCFG, Opts.CFGAddImplicitDtors,
158                                  Opts.CFGAddInitializers,
159                                  Opts.EagerlyTrimEGraph));
160  }
161
162  virtual void HandleTranslationUnit(ASTContext &C);
163  void HandleDeclContext(ASTContext &C, DeclContext *dc);
164  void HandleDeclContextDecl(ASTContext &C, Decl *D);
165
166  void HandleCode(Decl *D);
167};
168} // end anonymous namespace
169
170//===----------------------------------------------------------------------===//
171// AnalysisConsumer implementation.
172//===----------------------------------------------------------------------===//
173
174void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
175  for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
176       I != E; ++I) {
177    HandleDeclContextDecl(C, *I);
178  }
179}
180
181void AnalysisConsumer::HandleDeclContextDecl(ASTContext &C, Decl *D) {
182  { // Handle callbacks for arbitrary decls.
183    BugReporter BR(*Mgr);
184    checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
185  }
186
187  switch (D->getKind()) {
188    case Decl::Namespace: {
189      HandleDeclContext(C, cast<NamespaceDecl>(D));
190      break;
191    }
192    case Decl::CXXConstructor:
193    case Decl::CXXDestructor:
194    case Decl::CXXConversion:
195    case Decl::CXXMethod:
196    case Decl::Function: {
197      FunctionDecl *FD = cast<FunctionDecl>(D);
198      // We skip function template definitions, as their semantics is
199      // only determined when they are instantiated.
200      if (FD->isThisDeclarationADefinition() &&
201          !FD->isDependentContext()) {
202        if (!Opts.AnalyzeSpecificFunction.empty() &&
203            FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
204          break;
205        DisplayFunction(FD);
206        HandleCode(FD);
207      }
208      break;
209    }
210
211    case Decl::ObjCCategoryImpl:
212    case Decl::ObjCImplementation: {
213      ObjCImplDecl *ID = cast<ObjCImplDecl>(D);
214      HandleCode(ID);
215
216      for (ObjCContainerDecl::method_iterator MI = ID->meth_begin(),
217           ME = ID->meth_end(); MI != ME; ++MI) {
218        BugReporter BR(*Mgr);
219        checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
220
221        if ((*MI)->isThisDeclarationADefinition()) {
222          if (!Opts.AnalyzeSpecificFunction.empty() &&
223              Opts.AnalyzeSpecificFunction !=
224                (*MI)->getSelector().getAsString())
225            continue;
226          DisplayFunction(*MI);
227          HandleCode(*MI);
228        }
229      }
230      break;
231    }
232
233    default:
234      break;
235  }
236}
237
238void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
239  {
240    // Introduce a scope to destroy BR before Mgr.
241    BugReporter BR(*Mgr);
242    TranslationUnitDecl *TU = C.getTranslationUnitDecl();
243    checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
244    HandleDeclContext(C, TU);
245
246    // After all decls handled, run checkers on the entire TranslationUnit.
247    checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
248  }
249
250  // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
251  // FIXME: This should be replaced with something that doesn't rely on
252  // side-effects in PathDiagnosticConsumer's destructor. This is required when
253  // used with option -disable-free.
254  Mgr.reset(NULL);
255}
256
257static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
258  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
259    WL.push_back(BD);
260
261  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
262       I!=E; ++I)
263    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
264      FindBlocks(DC, WL);
265}
266
267static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
268                                   Decl *D);
269
270void AnalysisConsumer::HandleCode(Decl *D) {
271
272  // Don't run the actions if an error has occurred with parsing the file.
273  DiagnosticsEngine &Diags = PP.getDiagnostics();
274  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
275    return;
276
277  // Don't run the actions on declarations in header files unless
278  // otherwise specified.
279  SourceManager &SM = Ctx->getSourceManager();
280  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
281  if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
282    return;
283
284  // Clear the AnalysisManager of old AnalysisDeclContexts.
285  Mgr->ClearContexts();
286
287  // Dispatch on the actions.
288  SmallVector<Decl*, 10> WL;
289  WL.push_back(D);
290
291  if (D->hasBody() && Opts.AnalyzeNestedBlocks)
292    FindBlocks(cast<DeclContext>(D), WL);
293
294  BugReporter BR(*Mgr);
295  for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
296       WI != WE; ++WI)
297    if ((*WI)->hasBody()) {
298      checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
299      if (checkerMgr->hasPathSensitiveCheckers())
300        RunPathSensitiveChecks(*this, *Mgr, *WI);
301    }
302}
303
304//===----------------------------------------------------------------------===//
305// Path-sensitive checking.
306//===----------------------------------------------------------------------===//
307
308static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager &mgr,
309                             Decl *D, bool ObjCGCEnabled) {
310  // Construct the analysis engine.  First check if the CFG is valid.
311  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
312  if (!mgr.getCFG(D))
313    return;
314  ExprEngine Eng(mgr, ObjCGCEnabled);
315
316  // Set the graph auditor.
317  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
318  if (mgr.shouldVisualizeUbigraph()) {
319    Auditor.reset(CreateUbiViz());
320    ExplodedNode::SetAuditor(Auditor.get());
321  }
322
323  // Execute the worklist algorithm.
324  Eng.ExecuteWorkList(mgr.getAnalysisDeclContextManager().getStackFrame(D, 0),
325                      mgr.getMaxNodes());
326
327  // Release the auditor (if any) so that it doesn't monitor the graph
328  // created BugReporter.
329  ExplodedNode::SetAuditor(0);
330
331  // Visualize the exploded graph.
332  if (mgr.shouldVisualizeGraphviz())
333    Eng.ViewGraph(mgr.shouldTrimGraph());
334
335  // Display warnings.
336  Eng.getBugReporter().FlushReports();
337}
338
339static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
340                                   Decl *D) {
341
342  switch (mgr.getLangOptions().getGC()) {
343  default:
344    llvm_unreachable("Invalid GC mode.");
345  case LangOptions::NonGC:
346    ActionExprEngine(C, mgr, D, false);
347    break;
348
349  case LangOptions::GCOnly:
350    ActionExprEngine(C, mgr, D, true);
351    break;
352
353  case LangOptions::HybridGC:
354    ActionExprEngine(C, mgr, D, false);
355    ActionExprEngine(C, mgr, D, true);
356    break;
357  }
358}
359
360//===----------------------------------------------------------------------===//
361// AnalysisConsumer creation.
362//===----------------------------------------------------------------------===//
363
364ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
365                                          const std::string& outDir,
366                                          const AnalyzerOptions& opts,
367                                          ArrayRef<std::string> plugins) {
368  // Disable the effects of '-Werror' when using the AnalysisConsumer.
369  pp.getDiagnostics().setWarningsAsErrors(false);
370
371  return new AnalysisConsumer(pp, outDir, opts, plugins);
372}
373
374//===----------------------------------------------------------------------===//
375// Ubigraph Visualization.  FIXME: Move to separate file.
376//===----------------------------------------------------------------------===//
377
378namespace {
379
380class UbigraphViz : public ExplodedNode::Auditor {
381  llvm::OwningPtr<raw_ostream> Out;
382  llvm::sys::Path Dir, Filename;
383  unsigned Cntr;
384
385  typedef llvm::DenseMap<void*,unsigned> VMap;
386  VMap M;
387
388public:
389  UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
390              llvm::sys::Path& filename);
391
392  ~UbigraphViz();
393
394  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
395};
396
397} // end anonymous namespace
398
399static ExplodedNode::Auditor* CreateUbiViz() {
400  std::string ErrMsg;
401
402  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
403  if (!ErrMsg.empty())
404    return 0;
405
406  llvm::sys::Path Filename = Dir;
407  Filename.appendComponent("llvm_ubi");
408  Filename.makeUnique(true,&ErrMsg);
409
410  if (!ErrMsg.empty())
411    return 0;
412
413  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
414
415  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
416  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
417
418  if (!ErrMsg.empty())
419    return 0;
420
421  return new UbigraphViz(Stream.take(), Dir, Filename);
422}
423
424void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
425
426  assert (Src != Dst && "Self-edges are not allowed.");
427
428  // Lookup the Src.  If it is a new node, it's a root.
429  VMap::iterator SrcI= M.find(Src);
430  unsigned SrcID;
431
432  if (SrcI == M.end()) {
433    M[Src] = SrcID = Cntr++;
434    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
435  }
436  else
437    SrcID = SrcI->second;
438
439  // Lookup the Dst.
440  VMap::iterator DstI= M.find(Dst);
441  unsigned DstID;
442
443  if (DstI == M.end()) {
444    M[Dst] = DstID = Cntr++;
445    *Out << "('vertex', " << DstID << ")\n";
446  }
447  else {
448    // We have hit DstID before.  Change its style to reflect a cache hit.
449    DstID = DstI->second;
450    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
451  }
452
453  // Add the edge.
454  *Out << "('edge', " << SrcID << ", " << DstID
455       << ", ('arrow','true'), ('oriented', 'true'))\n";
456}
457
458UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
459                         llvm::sys::Path& filename)
460  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
461
462  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
463  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
464          " ('size', '1.5'))\n";
465}
466
467UbigraphViz::~UbigraphViz() {
468  Out.reset(0);
469  llvm::errs() << "Running 'ubiviz' program... ";
470  std::string ErrMsg;
471  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
472  std::vector<const char*> args;
473  args.push_back(Ubiviz.c_str());
474  args.push_back(Filename.c_str());
475  args.push_back(0);
476
477  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
478    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
479  }
480
481  // Delete the directory.
482  Dir.eraseFromDisk(true);
483}
484