AnalysisConsumer.cpp revision 9be6e7ce5788e50c62d40c59b0bbc2ea423683f7
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/PathSensitive/TransferFuncs.h"
29#include "clang/StaticAnalyzer/Core/PathDiagnosticClients.h"
30
31#include "clang/Basic/FileManager.h"
32#include "clang/Basic/SourceManager.h"
33#include "clang/Frontend/AnalyzerOptions.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/Support/raw_ostream.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Program.h"
38#include "llvm/ADT/OwningPtr.h"
39
40using namespace clang;
41using namespace ento;
42
43static ExplodedNode::Auditor* CreateUbiViz();
44
45//===----------------------------------------------------------------------===//
46// Special PathDiagnosticClients.
47//===----------------------------------------------------------------------===//
48
49static PathDiagnosticClient*
50createPlistHTMLDiagnosticClient(const std::string& prefix,
51                                const Preprocessor &PP) {
52  PathDiagnosticClient *PD =
53    createHTMLDiagnosticClient(llvm::sys::path::parent_path(prefix), PP);
54  return createPlistDiagnosticClient(prefix, PP, PD);
55}
56
57//===----------------------------------------------------------------------===//
58// AnalysisConsumer declaration.
59//===----------------------------------------------------------------------===//
60
61namespace {
62
63class AnalysisConsumer : public ASTConsumer {
64public:
65  ASTContext* Ctx;
66  const Preprocessor &PP;
67  const std::string OutDir;
68  AnalyzerOptions Opts;
69
70  // PD is owned by AnalysisManager.
71  PathDiagnosticClient *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    : Ctx(0), PP(pp), OutDir(outdir),
83      Opts(opts), PD(0) {
84    DigestAnalyzerOptions();
85  }
86
87  void DigestAnalyzerOptions() {
88    // Create the PathDiagnosticClient.
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 = createTextPathDiagnosticClient("", PP);
100    }
101
102    // Create the analyzer component creators.
103    switch (Opts.AnalysisStoreOpt) {
104    default:
105      assert(0 && "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      assert(0 && "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(registerCheckers(Opts, PP.getLangOptions(),
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.PurgeDead, 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
165  void HandleCode(Decl *D);
166};
167} // end anonymous namespace
168
169//===----------------------------------------------------------------------===//
170// AnalysisConsumer implementation.
171//===----------------------------------------------------------------------===//
172
173void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
174  BugReporter BR(*Mgr);
175  for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
176       I != E; ++I) {
177    Decl *D = *I;
178    checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
179
180    switch (D->getKind()) {
181      case Decl::Namespace: {
182        HandleDeclContext(C, cast<NamespaceDecl>(D));
183        break;
184      }
185      case Decl::CXXConstructor:
186      case Decl::CXXDestructor:
187      case Decl::CXXConversion:
188      case Decl::CXXMethod:
189      case Decl::Function: {
190        FunctionDecl* FD = cast<FunctionDecl>(D);
191        // We skip function template definitions, as their semantics is
192        // only determined when they are instantiated.
193        if (FD->isThisDeclarationADefinition() &&
194            !FD->isDependentContext()) {
195          if (!Opts.AnalyzeSpecificFunction.empty() &&
196              FD->getDeclName().getAsString() != Opts.AnalyzeSpecificFunction)
197            break;
198          DisplayFunction(FD);
199          HandleCode(FD);
200        }
201        break;
202      }
203
204      case Decl::ObjCImplementation: {
205        ObjCImplementationDecl* ID = cast<ObjCImplementationDecl>(*I);
206        HandleCode(ID);
207
208        for (ObjCImplementationDecl::method_iterator MI = ID->meth_begin(),
209             ME = ID->meth_end(); MI != ME; ++MI) {
210          checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
211
212          if ((*MI)->isThisDeclarationADefinition()) {
213            if (!Opts.AnalyzeSpecificFunction.empty() &&
214                Opts.AnalyzeSpecificFunction != (*MI)->getSelector().getAsString())
215              break;
216            DisplayFunction(*MI);
217            HandleCode(*MI);
218          }
219        }
220        break;
221      }
222
223      default:
224        break;
225    }
226  }
227}
228
229void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
230  BugReporter BR(*Mgr);
231  TranslationUnitDecl *TU = C.getTranslationUnitDecl();
232  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
233  HandleDeclContext(C, TU);
234
235  // After all decls handled, run checkers on the entire TranslationUnit.
236  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
237
238  // Explicitly destroy the PathDiagnosticClient.  This will flush its output.
239  // FIXME: This should be replaced with something that doesn't rely on
240  // side-effects in PathDiagnosticClient's destructor. This is required when
241  // used with option -disable-free.
242  Mgr.reset(NULL);
243}
244
245static void FindBlocks(DeclContext *D, llvm::SmallVectorImpl<Decl*> &WL) {
246  if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
247    WL.push_back(BD);
248
249  for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
250       I!=E; ++I)
251    if (DeclContext *DC = dyn_cast<DeclContext>(*I))
252      FindBlocks(DC, WL);
253}
254
255static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
256                                 Decl *D);
257
258void AnalysisConsumer::HandleCode(Decl *D) {
259
260  // Don't run the actions if an error has occurred with parsing the file.
261  Diagnostic &Diags = PP.getDiagnostics();
262  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
263    return;
264
265  // Don't run the actions on declarations in header files unless
266  // otherwise specified.
267  SourceManager &SM = Ctx->getSourceManager();
268  SourceLocation SL = SM.getInstantiationLoc(D->getLocation());
269  if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
270    return;
271
272  // Clear the AnalysisManager of old AnalysisContexts.
273  Mgr->ClearContexts();
274
275  // Dispatch on the actions.
276  llvm::SmallVector<Decl*, 10> WL;
277  WL.push_back(D);
278
279  if (D->hasBody() && Opts.AnalyzeNestedBlocks)
280    FindBlocks(cast<DeclContext>(D), WL);
281
282  BugReporter BR(*Mgr);
283  for (llvm::SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
284       WI != WE; ++WI)
285    if ((*WI)->hasBody()) {
286      checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
287      if (checkerMgr->hasPathSensitiveCheckers())
288        ActionObjCMemChecker(*this, *Mgr, *WI);
289    }
290}
291
292//===----------------------------------------------------------------------===//
293// Path-sensitive checking.
294//===----------------------------------------------------------------------===//
295
296static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager& mgr,
297                               Decl *D,
298                               TransferFuncs* tf) {
299
300  llvm::OwningPtr<TransferFuncs> TF(tf);
301
302  // Construct the analysis engine.  We first query for the LiveVariables
303  // information to see if the CFG is valid.
304  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
305  if (!mgr.getLiveVariables(D))
306    return;
307  ExprEngine Eng(mgr, TF.take());
308
309  // Set the graph auditor.
310  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
311  if (mgr.shouldVisualizeUbigraph()) {
312    Auditor.reset(CreateUbiViz());
313    ExplodedNode::SetAuditor(Auditor.get());
314  }
315
316  // Execute the worklist algorithm.
317  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
318
319  // Release the auditor (if any) so that it doesn't monitor the graph
320  // created BugReporter.
321  ExplodedNode::SetAuditor(0);
322
323  // Visualize the exploded graph.
324  if (mgr.shouldVisualizeGraphviz())
325    Eng.ViewGraph(mgr.shouldTrimGraph());
326
327  // Display warnings.
328  Eng.getBugReporter().FlushReports();
329}
330
331static void ActionObjCMemCheckerAux(AnalysisConsumer &C, AnalysisManager& mgr,
332                                  Decl *D, bool GCEnabled) {
333
334  TransferFuncs* TF = MakeCFRefCountTF(mgr.getASTContext(),
335                                         GCEnabled,
336                                         mgr.getLangOptions());
337
338  ActionExprEngine(C, mgr, D, TF);
339}
340
341static void ActionObjCMemChecker(AnalysisConsumer &C, AnalysisManager& mgr,
342                               Decl *D) {
343
344 switch (mgr.getLangOptions().getGCMode()) {
345 default:
346   assert (false && "Invalid GC mode.");
347 case LangOptions::NonGC:
348   ActionObjCMemCheckerAux(C, mgr, D, false);
349   break;
350
351 case LangOptions::GCOnly:
352   ActionObjCMemCheckerAux(C, mgr, D, true);
353   break;
354
355 case LangOptions::HybridGC:
356   ActionObjCMemCheckerAux(C, mgr, D, false);
357   ActionObjCMemCheckerAux(C, mgr, D, true);
358   break;
359 }
360}
361
362//===----------------------------------------------------------------------===//
363// AnalysisConsumer creation.
364//===----------------------------------------------------------------------===//
365
366ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp,
367                                           const std::string& OutDir,
368                                           const AnalyzerOptions& Opts) {
369  llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(pp, OutDir, Opts));
370
371  // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
372  pp.getDiagnostics().setWarningsAsErrors(false);
373
374  return C.take();
375}
376
377//===----------------------------------------------------------------------===//
378// Ubigraph Visualization.  FIXME: Move to separate file.
379//===----------------------------------------------------------------------===//
380
381namespace {
382
383class UbigraphViz : public ExplodedNode::Auditor {
384  llvm::OwningPtr<llvm::raw_ostream> Out;
385  llvm::sys::Path Dir, Filename;
386  unsigned Cntr;
387
388  typedef llvm::DenseMap<void*,unsigned> VMap;
389  VMap M;
390
391public:
392  UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
393              llvm::sys::Path& filename);
394
395  ~UbigraphViz();
396
397  virtual void AddEdge(ExplodedNode* Src, ExplodedNode* Dst);
398};
399
400} // end anonymous namespace
401
402static ExplodedNode::Auditor* CreateUbiViz() {
403  std::string ErrMsg;
404
405  llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
406  if (!ErrMsg.empty())
407    return 0;
408
409  llvm::sys::Path Filename = Dir;
410  Filename.appendComponent("llvm_ubi");
411  Filename.makeUnique(true,&ErrMsg);
412
413  if (!ErrMsg.empty())
414    return 0;
415
416  llvm::errs() << "Writing '" << Filename.str() << "'.\n";
417
418  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
419  Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
420
421  if (!ErrMsg.empty())
422    return 0;
423
424  return new UbigraphViz(Stream.take(), Dir, Filename);
425}
426
427void UbigraphViz::AddEdge(ExplodedNode* Src, ExplodedNode* Dst) {
428
429  assert (Src != Dst && "Self-edges are not allowed.");
430
431  // Lookup the Src.  If it is a new node, it's a root.
432  VMap::iterator SrcI= M.find(Src);
433  unsigned SrcID;
434
435  if (SrcI == M.end()) {
436    M[Src] = SrcID = Cntr++;
437    *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
438  }
439  else
440    SrcID = SrcI->second;
441
442  // Lookup the Dst.
443  VMap::iterator DstI= M.find(Dst);
444  unsigned DstID;
445
446  if (DstI == M.end()) {
447    M[Dst] = DstID = Cntr++;
448    *Out << "('vertex', " << DstID << ")\n";
449  }
450  else {
451    // We have hit DstID before.  Change its style to reflect a cache hit.
452    DstID = DstI->second;
453    *Out << "('change_vertex_style', " << DstID << ", 1)\n";
454  }
455
456  // Add the edge.
457  *Out << "('edge', " << SrcID << ", " << DstID
458       << ", ('arrow','true'), ('oriented', 'true'))\n";
459}
460
461UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
462                         llvm::sys::Path& filename)
463  : Out(out), Dir(dir), Filename(filename), Cntr(0) {
464
465  *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
466  *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
467          " ('size', '1.5'))\n";
468}
469
470UbigraphViz::~UbigraphViz() {
471  Out.reset(0);
472  llvm::errs() << "Running 'ubiviz' program... ";
473  std::string ErrMsg;
474  llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
475  std::vector<const char*> args;
476  args.push_back(Ubiviz.c_str());
477  args.push_back(Filename.c_str());
478  args.push_back(0);
479
480  if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
481    llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
482  }
483
484  // Delete the directory.
485  Dir.eraseFromDisk(true);
486}
487