blob: bda3df09759ea3af7a61aae0c70b589f11f80281 [file] [log] [blame]
Ted Kremenekf4381fd2008-07-02 00:03:09 +00001//===--- 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 "ASTConsumers.h"
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000015#include "clang/Frontend/PathDiagnosticClients.h"
16#include "clang/Frontend/ManagerRegistry.h"
Ted Kremenekf4381fd2008-07-02 00:03:09 +000017#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "llvm/Support/Compiler.h"
Ted Kremenekf4381fd2008-07-02 00:03:09 +000021#include "llvm/ADT/OwningPtr.h"
22#include "clang/AST/CFG.h"
23#include "clang/Analysis/Analyses/LiveVariables.h"
24#include "clang/Analysis/PathDiagnostic.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/AST/ParentMap.h"
Ted Kremenekdb09a4d2008-07-03 04:29:21 +000028#include "clang/AST/TranslationUnit.h"
Ted Kremenekc0959972008-07-02 21:24:01 +000029#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenekf4381fd2008-07-02 00:03:09 +000030#include "clang/Analysis/Analyses/LiveVariables.h"
31#include "clang/Analysis/LocalCheckers.h"
32#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
33#include "clang/Analysis/PathSensitive/GRExprEngine.h"
Zhongxing Xuff944a82008-12-22 01:52:37 +000034#include "llvm/Support/CommandLine.h"
Ted Kremenek34d77342008-07-02 16:49:11 +000035#include "llvm/Support/Streams.h"
Ted Kremenekf8ce6992008-08-27 22:31:43 +000036#include "llvm/Support/raw_ostream.h"
37#include "llvm/System/Path.h"
Ted Kremenek710ad932008-08-28 03:54:51 +000038#include "llvm/System/Program.h"
Ted Kremenekdb09a4d2008-07-03 04:29:21 +000039#include <vector>
40
Ted Kremenekf4381fd2008-07-02 00:03:09 +000041using namespace clang;
42
Ted Kremenekf8ce6992008-08-27 22:31:43 +000043static ExplodedNodeImpl::Auditor* CreateUbiViz();
Zhongxing Xuff944a82008-12-22 01:52:37 +000044
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +000045//===----------------------------------------------------------------------===//
46// Analyzer Options: available analyses.
47//===----------------------------------------------------------------------===//
48
49/// Analysis - Set of available source code analyses.
50enum Analyses {
51#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE) NAME,
52#include "Analyses.def"
53NumAnalyses
54};
55
56static llvm::cl::list<Analyses>
57AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
58llvm::cl::values(
59#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
60clEnumValN(NAME, CMDFLAG, DESC),
61#include "Analyses.def"
62clEnumValEnd));
63
64//===----------------------------------------------------------------------===//
65// Analyzer Options: store model.
66//===----------------------------------------------------------------------===//
67
68/// AnalysisStores - Set of available analysis store models.
69enum AnalysisStores {
70#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
71#include "Analyses.def"
72NumStores
73};
74
75static llvm::cl::opt<AnalysisStores>
76AnalysisStoreOpt("analyzer-store",
77 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
78 llvm::cl::init(BasicStoreModel),
79 llvm::cl::values(
80#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
81clEnumValN(NAME##Model, CMDFLAG, DESC),
82#include "Analyses.def"
83clEnumValEnd));
84
85//===----------------------------------------------------------------------===//
86// Analyzer Options: constraint engines.
87//===----------------------------------------------------------------------===//
88
89/// AnalysisConstraints - Set of available constraint models.
90enum AnalysisConstraints {
91#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
92#include "Analyses.def"
93NumConstraints
94};
95
96static llvm::cl::opt<AnalysisConstraints>
97AnalysisConstraintsOpt("analyzer-constraints",
98 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
Ted Kremenek9f4ecb32009-02-20 21:49:22 +000099 llvm::cl::init(RangeConstraintsModel),
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000100 llvm::cl::values(
101#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
102clEnumValN(NAME##Model, CMDFLAG, DESC),
103#include "Analyses.def"
104clEnumValEnd));
105
106//===----------------------------------------------------------------------===//
107// Analyzer Options: diagnostic clients.
108//===----------------------------------------------------------------------===//
109
110/// AnalysisDiagClients - Set of available diagnostic clients for rendering
111/// analysis results.
112enum AnalysisDiagClients {
113#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREAT) PD_##NAME,
114#include "Analyses.def"
115NUM_ANALYSIS_DIAG_CLIENTS
116};
117
118static llvm::cl::opt<AnalysisDiagClients>
119AnalysisDiagOpt("analyzer-output",
120 llvm::cl::desc("Source Code Analysis - Output Options"),
121 llvm::cl::init(PD_HTML),
122 llvm::cl::values(
123#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
124clEnumValN(PD_##NAME, CMDFLAG, DESC),
125#include "Analyses.def"
126clEnumValEnd));
127
128//===----------------------------------------------------------------------===//
129// Misc. fun options.
130//===----------------------------------------------------------------------===//
131
132static llvm::cl::opt<bool>
133VisualizeEGDot("analyzer-viz-egraph-graphviz",
134 llvm::cl::desc("Display exploded graph using GraphViz"));
135
136static llvm::cl::opt<bool>
137VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
138 llvm::cl::desc("Display exploded graph using Ubigraph"));
139
140static llvm::cl::opt<bool>
141AnalyzeAll("analyzer-opt-analyze-headers",
142 llvm::cl::desc("Force the static analyzer to analyze "
143 "functions defined in header files"));
144
145static llvm::cl::opt<bool>
146AnalyzerDisplayProgress("analyzer-display-progress",
147 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
148
Zhongxing Xuff944a82008-12-22 01:52:37 +0000149static llvm::cl::opt<bool>
150PurgeDead("analyzer-purge-dead",
151 llvm::cl::init(true),
152 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
153 " processing a statement."));
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000154
Ted Kremenek48af2a92009-02-25 22:32:02 +0000155static llvm::cl::opt<bool>
156EagerlyAssume("analyzer-eagerly-assume",
157 llvm::cl::init(false),
158 llvm::cl::desc("Eagerly assume the truth/falseness of some "
159 "symbolic constraints."));
160
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000161static llvm::cl::opt<std::string>
162AnalyzeSpecificFunction("analyze-function",
163 llvm::cl::desc("Run analysis on specific function"));
164
Ted Kremenek45021952009-02-14 17:08:39 +0000165static llvm::cl::opt<bool>
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000166TrimGraph("trim-egraph",
167 llvm::cl::desc("Only show error-related paths in the analysis graph"));
168
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000169//===----------------------------------------------------------------------===//
170// Basic type definitions.
171//===----------------------------------------------------------------------===//
172
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000173namespace {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000174 class AnalysisManager;
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000175 typedef void (*CodeAction)(AnalysisManager& Mgr);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000176} // end anonymous namespace
177
178//===----------------------------------------------------------------------===//
179// AnalysisConsumer declaration.
180//===----------------------------------------------------------------------===//
181
182namespace {
183
184 class VISIBILITY_HIDDEN AnalysisConsumer : public ASTConsumer {
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000185 typedef std::vector<CodeAction> Actions;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000186 Actions FunctionActions;
187 Actions ObjCMethodActions;
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000188 Actions ObjCImplementationActions;
Ted Kremenekdaac6342008-11-07 02:09:25 +0000189 Actions TranslationUnitActions;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000190
191 public:
Ted Kremenek95c7b002008-10-24 01:04:59 +0000192 const LangOptions& LOpts;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000193 Diagnostic &Diags;
194 ASTContext* Ctx;
195 Preprocessor* PP;
196 PreprocessorFactory* PPF;
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000197 const std::string OutDir;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000198 llvm::OwningPtr<PathDiagnosticClient> PD;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000199
200 AnalysisConsumer(Diagnostic &diags, Preprocessor* pp,
201 PreprocessorFactory* ppf,
202 const LangOptions& lopts,
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000203 const std::string& outdir)
204 : LOpts(lopts), Diags(diags),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000205 Ctx(0), PP(pp), PPF(ppf),
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000206 OutDir(outdir) {}
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000207
208 void addCodeAction(CodeAction action) {
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000209 FunctionActions.push_back(action);
210 ObjCMethodActions.push_back(action);
211 }
212
213 void addObjCImplementationAction(CodeAction action) {
214 ObjCImplementationActions.push_back(action);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000215 }
216
Ted Kremenekdaac6342008-11-07 02:09:25 +0000217 void addTranslationUnitAction(CodeAction action) {
218 TranslationUnitActions.push_back(action);
219 }
220
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000221 virtual void Initialize(ASTContext &Context) {
222 Ctx = &Context;
223 }
224
225 virtual void HandleTopLevelDecl(Decl *D);
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000226 virtual void HandleTranslationUnit(TranslationUnit &TU);
227
Ted Kremenek81922f02009-02-02 20:52:40 +0000228 void HandleCode(Decl* D, Stmt* Body, Actions& actions);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000229 };
230
231
Ted Kremenekc0959972008-07-02 21:24:01 +0000232 class VISIBILITY_HIDDEN AnalysisManager : public BugReporterData {
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000233 Decl* D; Stmt* Body;
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000234
235 enum AnalysisScope { ScopeTU, ScopeDecl } AScope;
236
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000237 AnalysisConsumer& C;
Ted Kremenek34d77342008-07-02 16:49:11 +0000238 bool DisplayedFunction;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000239
240 llvm::OwningPtr<CFG> cfg;
241 llvm::OwningPtr<LiveVariables> liveness;
242 llvm::OwningPtr<ParentMap> PM;
243
Zhongxing Xu22438a82008-11-27 01:55:08 +0000244 // Configurable components creators.
245 StoreManagerCreator CreateStoreMgr;
246 ConstraintManagerCreator CreateConstraintMgr;
247
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000248 public:
Ted Kremenek491918e2009-01-23 20:52:26 +0000249 AnalysisManager(AnalysisConsumer& c, Decl* d, Stmt* b, bool displayProgress)
Chris Lattner678dc3b2009-03-28 04:05:05 +0000250 : D(d), Body(b), AScope(ScopeDecl), C(c),
Ted Kremenek491918e2009-01-23 20:52:26 +0000251 DisplayedFunction(!displayProgress) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000252 setManagerCreators();
253 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000254
Chris Lattner678dc3b2009-03-28 04:05:05 +0000255 AnalysisManager(AnalysisConsumer& c, bool displayProgress)
256 : D(0), Body(0), AScope(ScopeTU), C(c),
Ted Kremenek491918e2009-01-23 20:52:26 +0000257 DisplayedFunction(!displayProgress) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000258 setManagerCreators();
259 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000260
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000261 Decl* getCodeDecl() const {
262 assert (AScope == ScopeDecl);
263 return D;
264 }
265
266 Stmt* getBody() const {
267 assert (AScope == ScopeDecl);
268 return Body;
269 }
270
Zhongxing Xu22438a82008-11-27 01:55:08 +0000271 StoreManagerCreator getStoreManagerCreator() {
272 return CreateStoreMgr;
Ted Kremenek95c7b002008-10-24 01:04:59 +0000273 };
Zhongxing Xu22438a82008-11-27 01:55:08 +0000274
275 ConstraintManagerCreator getConstraintManagerCreator() {
276 return CreateConstraintMgr;
277 }
Ted Kremenek95c7b002008-10-24 01:04:59 +0000278
Ted Kremenek7032f462008-07-03 05:26:14 +0000279 virtual CFG* getCFG() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000280 if (!cfg) cfg.reset(CFG::buildCFG(getBody()));
Ted Kremenek7032f462008-07-03 05:26:14 +0000281 return cfg.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000282 }
283
Ted Kremenekc0959972008-07-02 21:24:01 +0000284 virtual ParentMap& getParentMap() {
Ted Kremeneke2075582008-07-02 23:16:33 +0000285 if (!PM)
286 PM.reset(new ParentMap(getBody()));
Ted Kremenekc0959972008-07-02 21:24:01 +0000287 return *PM.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000288 }
289
Ted Kremenekc0959972008-07-02 21:24:01 +0000290 virtual ASTContext& getContext() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000291 return *C.Ctx;
292 }
293
Ted Kremenekc0959972008-07-02 21:24:01 +0000294 virtual SourceManager& getSourceManager() {
Ted Kremenek235e0312008-07-02 18:11:29 +0000295 return getContext().getSourceManager();
296 }
297
Ted Kremenekc0959972008-07-02 21:24:01 +0000298 virtual Diagnostic& getDiagnostic() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000299 return C.Diags;
300 }
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000301
302 const LangOptions& getLangOptions() const {
303 return C.LOpts;
304 }
305
Ted Kremenekc0959972008-07-02 21:24:01 +0000306 virtual PathDiagnosticClient* getPathDiagnosticClient() {
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000307 if (C.PD.get() == 0 && !C.OutDir.empty()) {
308 switch (AnalysisDiagOpt) {
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000309 default:
Ted Kremenekc472d792009-01-23 20:06:20 +0000310#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000311case PD_##NAME: C.PD.reset(CREATEFN(C.OutDir, C.PP, C.PPF)); break;
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000312#include "Analyses.def"
313 }
314 }
Ted Kremeneke2075582008-07-02 23:16:33 +0000315 return C.PD.get();
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000316 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000317
Ted Kremenek7032f462008-07-03 05:26:14 +0000318 virtual LiveVariables* getLiveVariables() {
Ted Kremenek235e0312008-07-02 18:11:29 +0000319 if (!liveness) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000320 CFG* c = getCFG();
321 if (!c) return 0;
322
Ted Kremenekca9bab02008-12-09 00:17:51 +0000323 liveness.reset(new LiveVariables(getContext(), *c));
Ted Kremenek7032f462008-07-03 05:26:14 +0000324 liveness->runOnCFG(*c);
325 liveness->runOnAllBlocks(*c, 0, true);
Ted Kremenek235e0312008-07-02 18:11:29 +0000326 }
Ted Kremenekc0959972008-07-02 21:24:01 +0000327
Ted Kremenek7032f462008-07-03 05:26:14 +0000328 return liveness.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000329 }
Ted Kremenek34d77342008-07-02 16:49:11 +0000330
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000331 bool shouldVisualizeGraphviz() const { return VisualizeEGDot; }
332
333 bool shouldVisualizeUbigraph() const { return VisualizeEGUbi; }
334
335 bool shouldVisualize() const {
336 return VisualizeEGDot || VisualizeEGUbi;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000337 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000338
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000339 bool shouldTrimGraph() const { return TrimGraph; }
340
Ted Kremenek34d77342008-07-02 16:49:11 +0000341 void DisplayFunction() {
342
343 if (DisplayedFunction)
344 return;
345
346 DisplayedFunction = true;
347
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000348 // FIXME: Is getCodeDecl() always a named decl?
349 if (isa<FunctionDecl>(getCodeDecl()) ||
350 isa<ObjCMethodDecl>(getCodeDecl())) {
351 NamedDecl *ND = cast<NamedDecl>(getCodeDecl());
352 SourceManager &SM = getContext().getSourceManager();
Ted Kremeneka88fcef2008-11-20 16:14:48 +0000353 llvm::cerr << "ANALYZE: "
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000354 << SM.getPresumedLoc(ND->getLocation()).getFilename()
355 << ' ' << ND->getNameAsString() << '\n';
Ted Kremenek34d77342008-07-02 16:49:11 +0000356 }
357 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000358
359 private:
360 /// Set configurable analyzer components creators. First check if there are
361 /// components registered at runtime. Otherwise fall back to builtin
362 /// components.
363 void setManagerCreators() {
364 if (ManagerRegistry::StoreMgrCreator != 0) {
365 CreateStoreMgr = ManagerRegistry::StoreMgrCreator;
366 }
367 else {
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000368 switch (AnalysisStoreOpt) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000369 default:
370 assert(0 && "Unknown store manager.");
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000371#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
372 case NAME##Model: CreateStoreMgr = CREATEFN; break;
Zhongxing Xu22438a82008-11-27 01:55:08 +0000373#include "Analyses.def"
374 }
375 }
376
377 if (ManagerRegistry::ConstraintMgrCreator != 0)
378 CreateConstraintMgr = ManagerRegistry::ConstraintMgrCreator;
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000379 else {
380 switch (AnalysisConstraintsOpt) {
381 default:
382 assert(0 && "Unknown store manager.");
383#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
384 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
385#include "Analyses.def"
386 }
387 }
388
Ted Kremenekc472d792009-01-23 20:06:20 +0000389
390 // Some DiagnosticClients should be created all the time instead of
391 // lazily. Create those now.
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000392 switch (AnalysisDiagOpt) {
Ted Kremenekc472d792009-01-23 20:06:20 +0000393 default: break;
394#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\
395case PD_##NAME: if (AUTOCREATE) getPathDiagnosticClient(); break;
396#include "Analyses.def"
397 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000398 }
399
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000400 };
Zhongxing Xu22438a82008-11-27 01:55:08 +0000401
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000402} // end anonymous namespace
403
404namespace llvm {
405 template <> struct FoldingSetTrait<CodeAction> {
406 static inline void Profile(CodeAction X, FoldingSetNodeID& ID) {
407 ID.AddPointer(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(X)));
408 }
409 };
410}
411
412//===----------------------------------------------------------------------===//
413// AnalysisConsumer implementation.
414//===----------------------------------------------------------------------===//
415
416void AnalysisConsumer::HandleTopLevelDecl(Decl *D) {
417 switch (D->getKind()) {
418 case Decl::Function: {
419 FunctionDecl* FD = cast<FunctionDecl>(D);
Ted Kremenek235e0312008-07-02 18:11:29 +0000420
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000421 if (AnalyzeSpecificFunction.size() > 0 &&
422 AnalyzeSpecificFunction != FD->getIdentifier()->getName())
Ted Kremenek235e0312008-07-02 18:11:29 +0000423 break;
424
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000425 Stmt* Body = FD->getBody();
426 if (Body) HandleCode(FD, Body, FunctionActions);
427 break;
428 }
429
430 case Decl::ObjCMethod: {
431 ObjCMethodDecl* MD = cast<ObjCMethodDecl>(D);
Ted Kremenek235e0312008-07-02 18:11:29 +0000432
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000433 if (AnalyzeSpecificFunction.size() > 0 &&
434 AnalyzeSpecificFunction != MD->getSelector().getAsString())
Ted Kremenek235e0312008-07-02 18:11:29 +0000435 return;
436
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000437 Stmt* Body = MD->getBody();
438 if (Body) HandleCode(MD, Body, ObjCMethodActions);
439 break;
440 }
441
442 default:
443 break;
444 }
445}
446
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000447void AnalysisConsumer::HandleTranslationUnit(TranslationUnit& TU) {
448
Ted Kremenekdaac6342008-11-07 02:09:25 +0000449 if(!TranslationUnitActions.empty()) {
Chris Lattner678dc3b2009-03-28 04:05:05 +0000450 AnalysisManager mgr(*this, AnalyzerDisplayProgress);
Ted Kremenekdaac6342008-11-07 02:09:25 +0000451 for (Actions::iterator I = TranslationUnitActions.begin(),
452 E = TranslationUnitActions.end(); I != E; ++I)
453 (*I)(mgr);
454 }
455
Chris Lattnere9077872009-03-28 03:29:40 +0000456 if (!ObjCImplementationActions.empty()) {
457 TranslationUnitDecl *TUD = TU.getContext().getTranslationUnitDecl();
458
459 for (DeclContext::decl_iterator I = TUD->decls_begin(),E = TUD->decls_end();
460 I != E; ++I)
Ted Kremenek4d53a532009-02-13 00:51:30 +0000461 if (ObjCImplementationDecl* ID = dyn_cast<ObjCImplementationDecl>(*I))
462 HandleCode(ID, 0, ObjCImplementationActions);
Chris Lattnere9077872009-03-28 03:29:40 +0000463 }
Ted Kremenek4d53a532009-02-13 00:51:30 +0000464
465 // Delete the PathDiagnosticClient here just in case the AnalysisConsumer
466 // object doesn't get released. This will cause any side-effects in the
467 // destructor of the PathDiagnosticClient to get executed.
468 PD.reset();
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000469}
470
Ted Kremenek81922f02009-02-02 20:52:40 +0000471void AnalysisConsumer::HandleCode(Decl* D, Stmt* Body, Actions& actions) {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000472
473 // Don't run the actions if an error has occured with parsing the file.
474 if (Diags.hasErrorOccurred())
475 return;
Ted Kremenek81922f02009-02-02 20:52:40 +0000476
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000477 // Don't run the actions on declarations in header files unless
478 // otherwise specified.
Ted Kremenek81922f02009-02-02 20:52:40 +0000479 if (!AnalyzeAll && !Ctx->getSourceManager().isFromMainFile(D->getLocation()))
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000480 return;
481
482 // Create an AnalysisManager that will manage the state for analyzing
483 // this method/function.
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000484 AnalysisManager mgr(*this, D, Body, AnalyzerDisplayProgress);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000485
486 // Dispatch on the actions.
Zhongxing Xu3702af52008-10-30 05:03:28 +0000487 for (Actions::iterator I = actions.begin(), E = actions.end(); I != E; ++I)
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000488 (*I)(mgr);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000489}
490
491//===----------------------------------------------------------------------===//
492// Analyses
493//===----------------------------------------------------------------------===//
494
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000495static void ActionWarnDeadStores(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000496 if (LiveVariables* L = mgr.getLiveVariables()) {
497 BugReporter BR(mgr);
498 CheckDeadStores(*L, BR);
499 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000500}
501
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000502static void ActionWarnUninitVals(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000503 if (CFG* c = mgr.getCFG())
504 CheckUninitializedValues(*c, mgr.getContext(), mgr.getDiagnostic());
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000505}
506
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000507
Ted Kremenek78d46242008-07-22 16:21:24 +0000508static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf,
509 bool StandardWarnings = true) {
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000510
Ted Kremenek7032f462008-07-03 05:26:14 +0000511
Ted Kremenekbc46f342008-07-02 16:35:50 +0000512 llvm::OwningPtr<GRTransferFuncs> TF(tf);
Ted Kremenek7032f462008-07-03 05:26:14 +0000513
Ted Kremenek8ffc8a52008-11-24 20:53:32 +0000514 // Display progress.
515 mgr.DisplayFunction();
516
Ted Kremenek7032f462008-07-03 05:26:14 +0000517 // Construct the analysis engine.
518 LiveVariables* L = mgr.getLiveVariables();
519 if (!L) return;
Ted Kremenek8ffc8a52008-11-24 20:53:32 +0000520
Ted Kremenekcf118d42009-02-04 23:49:09 +0000521 GRExprEngine Eng(*mgr.getCFG(), *mgr.getCodeDecl(), mgr.getContext(), *L, mgr,
Ted Kremenek48af2a92009-02-25 22:32:02 +0000522 PurgeDead, EagerlyAssume,
Zhongxing Xu22438a82008-11-27 01:55:08 +0000523 mgr.getStoreManagerCreator(),
524 mgr.getConstraintManagerCreator());
Ted Kremenek95c7b002008-10-24 01:04:59 +0000525
Ted Kremenekbc46f342008-07-02 16:35:50 +0000526 Eng.setTransferFunctions(tf);
527
Ted Kremenek78d46242008-07-22 16:21:24 +0000528 if (StandardWarnings) {
529 Eng.RegisterInternalChecks();
530 RegisterAppleChecks(Eng);
531 }
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000532
533 // Set the graph auditor.
534 llvm::OwningPtr<ExplodedNodeImpl::Auditor> Auditor;
535 if (mgr.shouldVisualizeUbigraph()) {
536 Auditor.reset(CreateUbiViz());
537 ExplodedNodeImpl::SetAuditor(Auditor.get());
538 }
Ted Kremenek78d46242008-07-22 16:21:24 +0000539
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000540 // Execute the worklist algorithm.
541 Eng.ExecuteWorkList();
Ted Kremenekbc46f342008-07-02 16:35:50 +0000542
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000543 // Release the auditor (if any) so that it doesn't monitor the graph
544 // created BugReporter.
545 ExplodedNodeImpl::SetAuditor(0);
Ted Kremenek3df64212009-03-11 01:42:29 +0000546
Ted Kremenek34d77342008-07-02 16:49:11 +0000547 // Visualize the exploded graph.
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000548 if (mgr.shouldVisualizeGraphviz())
Ted Kremenek34d77342008-07-02 16:49:11 +0000549 Eng.ViewGraph(mgr.shouldTrimGraph());
Ted Kremenek3df64212009-03-11 01:42:29 +0000550
551 // Display warnings.
552 Eng.getBugReporter().FlushReports();
Ted Kremenekbc46f342008-07-02 16:35:50 +0000553}
554
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000555static void ActionCheckerCFRefAux(AnalysisManager& mgr, bool GCEnabled,
Ted Kremenek78d46242008-07-22 16:21:24 +0000556 bool StandardWarnings) {
557
Ted Kremenekbc46f342008-07-02 16:35:50 +0000558 GRTransferFuncs* TF = MakeCFRefCountTF(mgr.getContext(),
559 GCEnabled,
Ted Kremenekbc46f342008-07-02 16:35:50 +0000560 mgr.getLangOptions());
561
Ted Kremenek78d46242008-07-22 16:21:24 +0000562 ActionGRExprEngine(mgr, TF, StandardWarnings);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000563}
564
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000565static void ActionCheckerCFRef(AnalysisManager& mgr) {
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000566
567 switch (mgr.getLangOptions().getGCMode()) {
568 default:
569 assert (false && "Invalid GC mode.");
570 case LangOptions::NonGC:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000571 ActionCheckerCFRefAux(mgr, false, true);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000572 break;
573
574 case LangOptions::GCOnly:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000575 ActionCheckerCFRefAux(mgr, true, true);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000576 break;
577
578 case LangOptions::HybridGC:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000579 ActionCheckerCFRefAux(mgr, false, true);
580 ActionCheckerCFRefAux(mgr, true, false);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000581 break;
582 }
583}
584
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000585static void ActionCheckerSimple(AnalysisManager& mgr) {
Ted Kremenekbc46f342008-07-02 16:35:50 +0000586 ActionGRExprEngine(mgr, MakeGRSimpleValsTF());
587}
588
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000589static void ActionDisplayLiveVariables(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000590 if (LiveVariables* L = mgr.getLiveVariables()) {
591 mgr.DisplayFunction();
592 L->dumpBlockLiveness(mgr.getSourceManager());
593 }
Ted Kremenek235e0312008-07-02 18:11:29 +0000594}
595
Ted Kremenek902141f2008-07-02 18:23:21 +0000596static void ActionCFGDump(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000597 if (CFG* c = mgr.getCFG()) {
598 mgr.DisplayFunction();
599 c->dump();
600 }
Ted Kremenek902141f2008-07-02 18:23:21 +0000601}
602
603static void ActionCFGView(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000604 if (CFG* c = mgr.getCFG()) {
605 mgr.DisplayFunction();
606 c->viewCFG();
607 }
Ted Kremenek902141f2008-07-02 18:23:21 +0000608}
609
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000610static void ActionWarnObjCDealloc(AnalysisManager& mgr) {
Ted Kremenek4f4e7e42008-08-04 17:14:10 +0000611 if (mgr.getLangOptions().getGCMode() == LangOptions::GCOnly)
612 return;
613
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000614 BugReporter BR(mgr);
Ted Kremenek3cd483c2008-07-03 14:35:01 +0000615
616 CheckObjCDealloc(cast<ObjCImplementationDecl>(mgr.getCodeDecl()),
617 mgr.getLangOptions(), BR);
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000618}
619
Ted Kremenek395aaf22008-07-23 00:45:26 +0000620static void ActionWarnObjCUnusedIvars(AnalysisManager& mgr) {
621 BugReporter BR(mgr);
622 CheckObjCUnusedIvar(cast<ObjCImplementationDecl>(mgr.getCodeDecl()), BR);
623}
624
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000625static void ActionWarnObjCMethSigs(AnalysisManager& mgr) {
Ted Kremenek0d8019e2008-07-11 22:40:47 +0000626 BugReporter BR(mgr);
627
628 CheckObjCInstMethSignature(cast<ObjCImplementationDecl>(mgr.getCodeDecl()),
629 BR);
630}
631
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000632//===----------------------------------------------------------------------===//
633// AnalysisConsumer creation.
634//===----------------------------------------------------------------------===//
635
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000636ASTConsumer* clang::CreateAnalysisConsumer(Diagnostic &diags, Preprocessor* pp,
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000637 PreprocessorFactory* ppf,
638 const LangOptions& lopts,
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000639 const std::string& OutDir) {
640
641 llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(diags, pp, ppf,
642 lopts, OutDir));
643
644 for (unsigned i = 0; i < AnalysisList.size(); ++i)
645 switch (AnalysisList[i]) {
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000646#define ANALYSIS(NAME, CMD, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000647 case NAME:\
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000648 C->add ## SCOPE ## Action(&Action ## NAME);\
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000649 break;
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000650#include "Analyses.def"
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000651 default: break;
652 }
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000653
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000654 return C.take();
655}
656
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000657//===----------------------------------------------------------------------===//
658// Ubigraph Visualization. FIXME: Move to separate file.
659//===----------------------------------------------------------------------===//
660
661namespace {
662
663class UbigraphViz : public ExplodedNodeImpl::Auditor {
664 llvm::OwningPtr<llvm::raw_ostream> Out;
Ted Kremenek710ad932008-08-28 03:54:51 +0000665 llvm::sys::Path Dir, Filename;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000666 unsigned Cntr;
667
668 typedef llvm::DenseMap<void*,unsigned> VMap;
669 VMap M;
670
671public:
Ted Kremenek710ad932008-08-28 03:54:51 +0000672 UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
Ted Kremenek56b98712008-08-28 05:02:09 +0000673 llvm::sys::Path& filename);
Ted Kremenek710ad932008-08-28 03:54:51 +0000674
675 ~UbigraphViz();
676
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000677 virtual void AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst);
678};
679
680} // end anonymous namespace
681
682static ExplodedNodeImpl::Auditor* CreateUbiViz() {
683 std::string ErrMsg;
684
Ted Kremenek710ad932008-08-28 03:54:51 +0000685 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000686 if (!ErrMsg.empty())
687 return 0;
688
Ted Kremenek710ad932008-08-28 03:54:51 +0000689 llvm::sys::Path Filename = Dir;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000690 Filename.appendComponent("llvm_ubi");
691 Filename.makeUnique(true,&ErrMsg);
692
693 if (!ErrMsg.empty())
694 return 0;
695
696 llvm::cerr << "Writing '" << Filename << "'.\n";
697
698 llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
699 std::string filename = Filename.toString();
Daniel Dunbar26fb2722008-11-13 05:09:21 +0000700 Stream.reset(new llvm::raw_fd_ostream(filename.c_str(), false, ErrMsg));
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000701
702 if (!ErrMsg.empty())
703 return 0;
704
Ted Kremenek710ad932008-08-28 03:54:51 +0000705 return new UbigraphViz(Stream.take(), Dir, Filename);
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000706}
707
708void UbigraphViz::AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst) {
Ted Kremenek45479c82008-08-28 18:34:41 +0000709
710 assert (Src != Dst && "Self-edges are not allowed.");
711
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000712 // Lookup the Src. If it is a new node, it's a root.
713 VMap::iterator SrcI= M.find(Src);
714 unsigned SrcID;
715
716 if (SrcI == M.end()) {
717 M[Src] = SrcID = Cntr++;
718 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
719 }
720 else
721 SrcID = SrcI->second;
722
723 // Lookup the Dst.
724 VMap::iterator DstI= M.find(Dst);
725 unsigned DstID;
726
727 if (DstI == M.end()) {
728 M[Dst] = DstID = Cntr++;
729 *Out << "('vertex', " << DstID << ")\n";
730 }
Ted Kremenek56b98712008-08-28 05:02:09 +0000731 else {
732 // We have hit DstID before. Change its style to reflect a cache hit.
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000733 DstID = DstI->second;
Ted Kremenek56b98712008-08-28 05:02:09 +0000734 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
735 }
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000736
737 // Add the edge.
Ted Kremenekd1289322008-08-27 22:46:55 +0000738 *Out << "('edge', " << SrcID << ", " << DstID
739 << ", ('arrow','true'), ('oriented', 'true'))\n";
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000740}
741
Ted Kremenek56b98712008-08-28 05:02:09 +0000742UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
743 llvm::sys::Path& filename)
744 : Out(out), Dir(dir), Filename(filename), Cntr(0) {
745
746 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
747 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
748 " ('size', '1.5'))\n";
749}
750
Ted Kremenek710ad932008-08-28 03:54:51 +0000751UbigraphViz::~UbigraphViz() {
752 Out.reset(0);
753 llvm::cerr << "Running 'ubiviz' program... ";
754 std::string ErrMsg;
755 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
756 std::vector<const char*> args;
757 args.push_back(Ubiviz.c_str());
758 args.push_back(Filename.c_str());
759 args.push_back(0);
760
761 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
762 llvm::cerr << "Error viewing graph: " << ErrMsg << "\n";
763 }
764
765 // Delete the directory.
766 Dir.eraseFromDisk(true);
Daniel Dunbar932680e2008-08-29 03:45:59 +0000767}