1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // "Meta" ASTConsumer for running different source analyses.
12 //===----------------------------------------------------------------------===//
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"
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"
39 using namespace clang;
42 static ExplodedNode::Auditor* CreateUbiViz();
44 //===----------------------------------------------------------------------===//
45 // Special PathDiagnosticConsumers.
46 //===----------------------------------------------------------------------===//
48 static PathDiagnosticConsumer*
49 createPlistHTMLDiagnosticConsumer(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);
56 //===----------------------------------------------------------------------===//
57 // AnalysisConsumer declaration.
58 //===----------------------------------------------------------------------===//
62 class AnalysisConsumer : public ASTConsumer {
65 const Preprocessor &PP;
66 const std::string OutDir;
68 ArrayRef<std::string> Plugins;
70 // PD is owned by AnalysisManager.
71 PathDiagnosticConsumer *PD;
73 StoreManagerCreator CreateStoreMgr;
74 ConstraintManagerCreator CreateConstraintMgr;
76 llvm::OwningPtr<CheckerManager> checkerMgr;
77 llvm::OwningPtr<AnalysisManager> Mgr;
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();
87 void DigestAnalyzerOptions() {
88 // Create the PathDiagnosticConsumer.
89 if (!OutDir.empty()) {
90 switch (Opts.AnalysisDiagOpt) {
92 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE) \
93 case PD_##NAME: PD = CREATEFN(OutDir, PP); break;
94 #include "clang/Frontend/Analyses.def"
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);
102 // Create the analyzer component creators.
103 switch (Opts.AnalysisStoreOpt) {
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"
111 switch (Opts.AnalysisConstraintsOpt) {
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"
120 void DisplayFunction(const Decl *D) {
121 if (!Opts.AnalyzerDisplayProgress)
124 SourceManager &SM = Mgr->getASTContext().getSourceManager();
125 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
127 llvm::errs() << "ANALYZE: " << Loc.getFilename();
129 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
130 const NamedDecl *ND = cast<NamedDecl>(D);
131 llvm::errs() << ' ' << *ND << '\n';
133 else if (isa<BlockDecl>(D)) {
134 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:"
135 << Loc.getColumn() << '\n';
137 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
138 Selector S = MD->getSelector();
139 llvm::errs() << ' ' << S.getAsString();
144 virtual void Initialize(ASTContext &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,
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));
162 virtual void HandleTranslationUnit(ASTContext &C);
163 void HandleDeclContext(ASTContext &C, DeclContext *dc);
164 void HandleDeclContextDecl(ASTContext &C, Decl *D);
166 void HandleCode(Decl *D);
168 } // end anonymous namespace
170 //===----------------------------------------------------------------------===//
171 // AnalysisConsumer implementation.
172 //===----------------------------------------------------------------------===//
174 void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
175 for (DeclContext::decl_iterator I = dc->decls_begin(), E = dc->decls_end();
177 HandleDeclContextDecl(C, *I);
181 void AnalysisConsumer::HandleDeclContextDecl(ASTContext &C, Decl *D) {
182 { // Handle callbacks for arbitrary decls.
183 BugReporter BR(*Mgr);
184 checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
187 switch (D->getKind()) {
188 case Decl::Namespace: {
189 HandleDeclContext(C, cast<NamespaceDecl>(D));
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)
211 case Decl::ObjCCategoryImpl:
212 case Decl::ObjCImplementation: {
213 ObjCImplDecl *ID = cast<ObjCImplDecl>(D);
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);
221 if ((*MI)->isThisDeclarationADefinition()) {
222 if (!Opts.AnalyzeSpecificFunction.empty() &&
223 Opts.AnalyzeSpecificFunction !=
224 (*MI)->getSelector().getAsString())
226 DisplayFunction(*MI);
238 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
239 BugReporter BR(*Mgr);
240 TranslationUnitDecl *TU = C.getTranslationUnitDecl();
241 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
242 HandleDeclContext(C, TU);
244 // After all decls handled, run checkers on the entire TranslationUnit.
245 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
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.
254 static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
255 if (BlockDecl *BD = dyn_cast<BlockDecl>(D))
258 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
260 if (DeclContext *DC = dyn_cast<DeclContext>(*I))
264 static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
267 void AnalysisConsumer::HandleCode(Decl *D) {
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())
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))
281 // Clear the AnalysisManager of old AnalysisContexts.
282 Mgr->ClearContexts();
284 // Dispatch on the actions.
285 SmallVector<Decl*, 10> WL;
288 if (D->hasBody() && Opts.AnalyzeNestedBlocks)
289 FindBlocks(cast<DeclContext>(D), WL);
291 BugReporter BR(*Mgr);
292 for (SmallVectorImpl<Decl*>::iterator WI=WL.begin(), WE=WL.end();
294 if ((*WI)->hasBody()) {
295 checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
296 if (checkerMgr->hasPathSensitiveCheckers())
297 RunPathSensitiveChecks(*this, *Mgr, *WI);
301 //===----------------------------------------------------------------------===//
302 // Path-sensitive checking.
303 //===----------------------------------------------------------------------===//
305 static 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.
311 ExprEngine Eng(mgr, ObjCGCEnabled);
313 // Set the graph auditor.
314 llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
315 if (mgr.shouldVisualizeUbigraph()) {
316 Auditor.reset(CreateUbiViz());
317 ExplodedNode::SetAuditor(Auditor.get());
320 // Execute the worklist algorithm.
321 Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
323 // Release the auditor (if any) so that it doesn't monitor the graph
324 // created BugReporter.
325 ExplodedNode::SetAuditor(0);
327 // Visualize the exploded graph.
328 if (mgr.shouldVisualizeGraphviz())
329 Eng.ViewGraph(mgr.shouldTrimGraph());
332 Eng.getBugReporter().FlushReports();
335 static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &mgr,
338 switch (mgr.getLangOptions().getGC()) {
340 llvm_unreachable("Invalid GC mode.");
341 case LangOptions::NonGC:
342 ActionExprEngine(C, mgr, D, false);
345 case LangOptions::GCOnly:
346 ActionExprEngine(C, mgr, D, true);
349 case LangOptions::HybridGC:
350 ActionExprEngine(C, mgr, D, false);
351 ActionExprEngine(C, mgr, D, true);
356 //===----------------------------------------------------------------------===//
357 // AnalysisConsumer creation.
358 //===----------------------------------------------------------------------===//
360 ASTConsumer* 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);
367 return new AnalysisConsumer(pp, outDir, opts, plugins);
370 //===----------------------------------------------------------------------===//
371 // Ubigraph Visualization. FIXME: Move to separate file.
372 //===----------------------------------------------------------------------===//
376 class UbigraphViz : public ExplodedNode::Auditor {
377 llvm::OwningPtr<raw_ostream> Out;
378 llvm::sys::Path Dir, Filename;
381 typedef llvm::DenseMap<void*,unsigned> VMap;
385 UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
386 llvm::sys::Path& filename);
390 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst);
393 } // end anonymous namespace
395 static ExplodedNode::Auditor* CreateUbiViz() {
398 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
402 llvm::sys::Path Filename = Dir;
403 Filename.appendComponent("llvm_ubi");
404 Filename.makeUnique(true,&ErrMsg);
409 llvm::errs() << "Writing '" << Filename.str() << "'.\n";
411 llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
412 Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
417 return new UbigraphViz(Stream.take(), Dir, Filename);
420 void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) {
422 assert (Src != Dst && "Self-edges are not allowed.");
424 // Lookup the Src. If it is a new node, it's a root.
425 VMap::iterator SrcI= M.find(Src);
428 if (SrcI == M.end()) {
429 M[Src] = SrcID = Cntr++;
430 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
433 SrcID = SrcI->second;
436 VMap::iterator DstI= M.find(Dst);
439 if (DstI == M.end()) {
440 M[Dst] = DstID = Cntr++;
441 *Out << "('vertex', " << DstID << ")\n";
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";
450 *Out << "('edge', " << SrcID << ", " << DstID
451 << ", ('arrow','true'), ('oriented', 'true'))\n";
454 UbigraphViz::UbigraphViz(raw_ostream *out, llvm::sys::Path& dir,
455 llvm::sys::Path& filename)
456 : Out(out), Dir(dir), Filename(filename), Cntr(0) {
458 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
459 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
460 " ('size', '1.5'))\n";
463 UbigraphViz::~UbigraphViz() {
465 llvm::errs() << "Running 'ubiviz' program... ";
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());
473 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
474 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
477 // Delete the directory.
478 Dir.eraseFromDisk(true);