AnalysisConsumer.cpp revision a5937bbfd19e61d651a58b0f0ffeef68457902a5
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  BugReporter BR(*Mgr);
240  TranslationUnitDecl *TU = C.getTranslationUnitDecl();
241  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
242  HandleDeclContext(C, TU);
243
244  // After all decls handled, run checkers on the entire TranslationUnit.
245  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
246
247  // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
248  // FIXME: This should be replaced with something that doesn't rely on
249  // side-effects in PathDiagnosticConsumer's destructor. This is required when
250  // used with option -disable-free.
251  Mgr.reset(NULL);
252}
253
254static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
255  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
256    WL.push_back(BD);
257
258  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
259       I!=E; ++I)
260    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
261      FindBlocks(DC, WL);
262}
263
264static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
265                                   Decl *D);
266
267void AnalysisConsumer::HandleCode(Decl *D) {
268
269  // Don't run the actions if an error has occurred with parsing the file.
270  DiagnosticsEngine &Diags = PP.getDiagnostics();
271  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
272    return;
273
274  // Don't run the actions on declarations in header files unless
275  // otherwise specified.
276  SourceManager &SM = Ctx->getSourceManager();
277  SourceLocation SL = SM.getExpansionLoc(D->getLocation());
278  if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
279    return;
280
281  // Clear the AnalysisManager of old AnalysisContexts.
282  Mgr->ClearContexts();
283
284  // Dispatch on the actions.
285  SmallVector<Decl*, 10> WL;
286  WL.push_back(D);
287
288  if (D->hasBody() && Opts.AnalyzeNestedBlocks)
289    FindBlocks(cast<DeclContext>(D), WL);
290
291  BugReporter BR(*Mgr);
292  for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
293       WI != WE; ++WI)
294    if ((*WI)->hasBody()) {
295      checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
296      if (checkerMgr->hasPathSensitiveCheckers())
297        RunPathSensitiveChecks(*this, *Mgr, *WI);
298    }
299}
300
301//===----------------------------------------------------------------------===//
302// Path-sensitive checking.
303//===----------------------------------------------------------------------===//
304
305static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager &mgr,
306                             Decl *D, bool ObjCGCEnabled) {
307  // Construct the analysis engine.  First check if the CFG is valid.
308  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
309  if (!mgr.getCFG(D))
310    return;
311  ExprEngine Eng(mgr, ObjCGCEnabled);
312
313  // Set the graph auditor.
314  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
315  if (mgr.shouldVisualizeUbigraph()) {
316    Auditor.reset(CreateUbiViz());
317    ExplodedNode::SetAuditor(Auditor.get());
318  }
319
320  // Execute the worklist algorithm.
321  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
322
323  // Release the auditor (if any) so that it doesn't monitor the graph
324  // created BugReporter.
325  ExplodedNode::SetAuditor(0);
326
327  // Visualize the exploded graph.
328  if (mgr.shouldVisualizeGraphviz())
329    Eng.ViewGraph(mgr.shouldTrimGraph());
330
331  // Display warnings.
332  Eng.getBugReporter().FlushReports();
333}
334
335static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
336                                   Decl *D) {
337
338  switch (mgr.getLangOptions().getGC()) {
339  default:
340    llvm_unreachable("Invalid GC mode.");
341  case LangOptions::NonGC:
342    ActionExprEngine(C, mgr, D, false);
343    break;
344
345  case LangOptions::GCOnly:
346    ActionExprEngine(C, mgr, D, true);
347    break;
348
349  case LangOptions::HybridGC:
350    ActionExprEngine(C, mgr, D, false);
351    ActionExprEngine(C, mgr, D, true);
352    break;
353  }
354}
355
356//===----------------------------------------------------------------------===//
357// AnalysisConsumer creation.
358//===----------------------------------------------------------------------===//
359
360ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
361                                          const std::string& outDir,
362                                          const AnalyzerOptions& opts,
363                                          ArrayRef<std::string> plugins) {
364  // Disable the effects of '-Werror' when using the AnalysisConsumer.
365  pp.getDiagnostics().setWarningsAsErrors(false);
366
367  return new AnalysisConsumer(pp, outDir, opts, plugins);
368}
369
370//===----------------------------------------------------------------------===//
371// Ubigraph Visualization.  FIXME: Move to separate file.
372//===----------------------------------------------------------------------===//
373
374namespace {
375
376class UbigraphViz : public ExplodedNode::Auditor {
377  llvm::OwningPtr<raw_ostream> Out;
378  llvm::sys::Path Dir, Filename;
379  unsigned Cntr;
380
381  typedef llvm::DenseMap<void*,unsigned> VMap;
382  VMap M;
383
384public:
385  UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
386              llvm::sys::Path& filename);
387
388  ~UbigraphViz();
389
390  virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
391};
392
393} // end anonymous namespace
394
395static ExplodedNode::Auditor* CreateUbiViz() {
396  std::string ErrMsg;
397
398  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
399  if (!ErrMsg.empty())
400    return 0;
401
402  llvm::sys::Path Filename = Dir;
403  Filename.appendComponent("llvm_ubi");
404  Filename.makeUnique(true,&ErrMsg);
405
406  if (!ErrMsg.empty())
407    return 0;
408
409  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
410
411  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
412  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
413
414  if (!ErrMsg.empty())
415    return 0;
416
417  return new UbigraphViz(Stream.take(), Dir, Filename);
418}
419
420void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
421
422  assert (Src != Dst && "Self-edges are not allowed.");
423
424  // Lookup the Src.  If it is a new node, it's a root.
425  VMap::iterator SrcI= M.find(Src);
426  unsigned SrcID;
427
428  if (SrcI == M.end()) {
429    M[Src] = SrcID = Cntr++;
430    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
431  }
432  else
433    SrcID = SrcI->second;
434
435  // Lookup the Dst.
436  VMap::iterator DstI= M.find(Dst);
437  unsigned DstID;
438
439  if (DstI == M.end()) {
440    M[Dst] = DstID = Cntr++;
441    *Out << "('vertex', " << DstID << ")\n";
442  }
443  else {
444    // We have hit DstID before.  Change its style to reflect a cache hit.
445    DstID = DstI->second;
446    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
447  }
448
449  // Add the edge.
450  *Out << "('edge', " << SrcID << ", " << DstID
451       << ", ('arrow','true'), ('oriented', 'true'))\n";
452}
453
454UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
455                         llvm::sys::Path& filename)
456  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
457
458  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
459  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
460          " ('size', '1.5'))\n";
461}
462
463UbigraphViz::~UbigraphViz() {
464  Out.reset(0);
465  llvm::errs() << "Running 'ubiviz' program... ";
466  std::string ErrMsg;
467  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
468  std::vector<const char*> args;
469  args.push_back(Ubiviz.c_str());
470  args.push_back(Filename.c_str());
471  args.push_back(0);
472
473  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
474    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
475  }
476
477  // Delete the directory.
478  Dir.eraseFromDisk(true);
479}
480