blob: 381b9d0ba2b80485f50a7dd2cc3f9a7d774ff9d2 [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 Kremenekc0959972008-07-02 21:24:01 +000028#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenekf4381fd2008-07-02 00:03:09 +000029#include "clang/Analysis/Analyses/LiveVariables.h"
30#include "clang/Analysis/LocalCheckers.h"
31#include "clang/Analysis/PathSensitive/GRTransferFuncs.h"
32#include "clang/Analysis/PathSensitive/GRExprEngine.h"
Zhongxing Xuff944a82008-12-22 01:52:37 +000033#include "llvm/Support/CommandLine.h"
Ted Kremenek34d77342008-07-02 16:49:11 +000034#include "llvm/Support/Streams.h"
Ted Kremenekf8ce6992008-08-27 22:31:43 +000035#include "llvm/Support/raw_ostream.h"
36#include "llvm/System/Path.h"
Ted Kremenek710ad932008-08-28 03:54:51 +000037#include "llvm/System/Program.h"
Ted Kremenekdb09a4d2008-07-03 04:29:21 +000038
Ted Kremenekf4381fd2008-07-02 00:03:09 +000039using namespace clang;
40
Ted Kremenekf8ce6992008-08-27 22:31:43 +000041static ExplodedNodeImpl::Auditor* CreateUbiViz();
Zhongxing Xuff944a82008-12-22 01:52:37 +000042
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +000043//===----------------------------------------------------------------------===//
44// Analyzer Options: available analyses.
45//===----------------------------------------------------------------------===//
46
47/// Analysis - Set of available source code analyses.
48enum Analyses {
49#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE) NAME,
50#include "Analyses.def"
51NumAnalyses
52};
53
54static llvm::cl::list<Analyses>
55AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
56llvm::cl::values(
57#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
58clEnumValN(NAME, CMDFLAG, DESC),
59#include "Analyses.def"
60clEnumValEnd));
61
62//===----------------------------------------------------------------------===//
63// Analyzer Options: store model.
64//===----------------------------------------------------------------------===//
65
66/// AnalysisStores - Set of available analysis store models.
67enum AnalysisStores {
68#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
69#include "Analyses.def"
70NumStores
71};
72
73static llvm::cl::opt<AnalysisStores>
74AnalysisStoreOpt("analyzer-store",
75 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
76 llvm::cl::init(BasicStoreModel),
77 llvm::cl::values(
78#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
79clEnumValN(NAME##Model, CMDFLAG, DESC),
80#include "Analyses.def"
81clEnumValEnd));
82
83//===----------------------------------------------------------------------===//
84// Analyzer Options: constraint engines.
85//===----------------------------------------------------------------------===//
86
87/// AnalysisConstraints - Set of available constraint models.
88enum AnalysisConstraints {
89#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
90#include "Analyses.def"
91NumConstraints
92};
93
94static llvm::cl::opt<AnalysisConstraints>
95AnalysisConstraintsOpt("analyzer-constraints",
96 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
Ted Kremenek9f4ecb32009-02-20 21:49:22 +000097 llvm::cl::init(RangeConstraintsModel),
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +000098 llvm::cl::values(
99#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
100clEnumValN(NAME##Model, CMDFLAG, DESC),
101#include "Analyses.def"
102clEnumValEnd));
103
104//===----------------------------------------------------------------------===//
105// Analyzer Options: diagnostic clients.
106//===----------------------------------------------------------------------===//
107
108/// AnalysisDiagClients - Set of available diagnostic clients for rendering
109/// analysis results.
110enum AnalysisDiagClients {
111#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREAT) PD_##NAME,
112#include "Analyses.def"
113NUM_ANALYSIS_DIAG_CLIENTS
114};
115
116static llvm::cl::opt<AnalysisDiagClients>
117AnalysisDiagOpt("analyzer-output",
118 llvm::cl::desc("Source Code Analysis - Output Options"),
119 llvm::cl::init(PD_HTML),
120 llvm::cl::values(
121#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
122clEnumValN(PD_##NAME, CMDFLAG, DESC),
123#include "Analyses.def"
124clEnumValEnd));
125
126//===----------------------------------------------------------------------===//
127// Misc. fun options.
128//===----------------------------------------------------------------------===//
129
130static llvm::cl::opt<bool>
131VisualizeEGDot("analyzer-viz-egraph-graphviz",
132 llvm::cl::desc("Display exploded graph using GraphViz"));
133
134static llvm::cl::opt<bool>
135VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
136 llvm::cl::desc("Display exploded graph using Ubigraph"));
137
138static llvm::cl::opt<bool>
139AnalyzeAll("analyzer-opt-analyze-headers",
140 llvm::cl::desc("Force the static analyzer to analyze "
141 "functions defined in header files"));
142
143static llvm::cl::opt<bool>
144AnalyzerDisplayProgress("analyzer-display-progress",
145 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
146
Zhongxing Xuff944a82008-12-22 01:52:37 +0000147static llvm::cl::opt<bool>
148PurgeDead("analyzer-purge-dead",
149 llvm::cl::init(true),
150 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
151 " processing a statement."));
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000152
Ted Kremenek48af2a92009-02-25 22:32:02 +0000153static llvm::cl::opt<bool>
154EagerlyAssume("analyzer-eagerly-assume",
155 llvm::cl::init(false),
156 llvm::cl::desc("Eagerly assume the truth/falseness of some "
157 "symbolic constraints."));
158
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000159static llvm::cl::opt<std::string>
160AnalyzeSpecificFunction("analyze-function",
161 llvm::cl::desc("Run analysis on specific function"));
162
Ted Kremenek45021952009-02-14 17:08:39 +0000163static llvm::cl::opt<bool>
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000164TrimGraph("trim-egraph",
165 llvm::cl::desc("Only show error-related paths in the analysis graph"));
166
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000167//===----------------------------------------------------------------------===//
168// Basic type definitions.
169//===----------------------------------------------------------------------===//
170
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000171namespace {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000172 class AnalysisManager;
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000173 typedef void (*CodeAction)(AnalysisManager& Mgr);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000174} // end anonymous namespace
175
176//===----------------------------------------------------------------------===//
177// AnalysisConsumer declaration.
178//===----------------------------------------------------------------------===//
179
180namespace {
181
182 class VISIBILITY_HIDDEN AnalysisConsumer : public ASTConsumer {
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000183 typedef std::vector<CodeAction> Actions;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000184 Actions FunctionActions;
185 Actions ObjCMethodActions;
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000186 Actions ObjCImplementationActions;
Ted Kremenekdaac6342008-11-07 02:09:25 +0000187 Actions TranslationUnitActions;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000188
189 public:
Ted Kremenek95c7b002008-10-24 01:04:59 +0000190 const LangOptions& LOpts;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000191 Diagnostic &Diags;
192 ASTContext* Ctx;
193 Preprocessor* PP;
194 PreprocessorFactory* PPF;
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000195 const std::string OutDir;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000196 llvm::OwningPtr<PathDiagnosticClient> PD;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000197
198 AnalysisConsumer(Diagnostic &diags, Preprocessor* pp,
199 PreprocessorFactory* ppf,
200 const LangOptions& lopts,
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000201 const std::string& outdir)
202 : LOpts(lopts), Diags(diags),
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000203 Ctx(0), PP(pp), PPF(ppf),
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000204 OutDir(outdir) {}
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000205
206 void addCodeAction(CodeAction action) {
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000207 FunctionActions.push_back(action);
208 ObjCMethodActions.push_back(action);
209 }
210
211 void addObjCImplementationAction(CodeAction action) {
212 ObjCImplementationActions.push_back(action);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000213 }
214
Ted Kremenekdaac6342008-11-07 02:09:25 +0000215 void addTranslationUnitAction(CodeAction action) {
216 TranslationUnitActions.push_back(action);
217 }
218
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000219 virtual void Initialize(ASTContext &Context) {
220 Ctx = &Context;
221 }
222
Chris Lattner682bf922009-03-29 16:50:03 +0000223 virtual void HandleTopLevelDecl(DeclGroupRef D) {
224 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
225 HandleTopLevelSingleDecl(*I);
226 }
227
228 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000229 virtual void HandleTranslationUnit(ASTContext &C);
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000230
Ted Kremenek81922f02009-02-02 20:52:40 +0000231 void HandleCode(Decl* D, Stmt* Body, Actions& actions);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000232 };
233
234
Ted Kremenekc0959972008-07-02 21:24:01 +0000235 class VISIBILITY_HIDDEN AnalysisManager : public BugReporterData {
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000236 Decl* D; Stmt* Body;
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000237
238 enum AnalysisScope { ScopeTU, ScopeDecl } AScope;
239
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000240 AnalysisConsumer& C;
Ted Kremenek34d77342008-07-02 16:49:11 +0000241 bool DisplayedFunction;
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000242
243 llvm::OwningPtr<CFG> cfg;
244 llvm::OwningPtr<LiveVariables> liveness;
245 llvm::OwningPtr<ParentMap> PM;
246
Zhongxing Xu22438a82008-11-27 01:55:08 +0000247 // Configurable components creators.
248 StoreManagerCreator CreateStoreMgr;
249 ConstraintManagerCreator CreateConstraintMgr;
250
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000251 public:
Ted Kremenek491918e2009-01-23 20:52:26 +0000252 AnalysisManager(AnalysisConsumer& c, Decl* d, Stmt* b, bool displayProgress)
Chris Lattner678dc3b2009-03-28 04:05:05 +0000253 : D(d), Body(b), AScope(ScopeDecl), C(c),
Ted Kremenek491918e2009-01-23 20:52:26 +0000254 DisplayedFunction(!displayProgress) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000255 setManagerCreators();
256 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000257
Chris Lattner678dc3b2009-03-28 04:05:05 +0000258 AnalysisManager(AnalysisConsumer& c, bool displayProgress)
259 : D(0), Body(0), AScope(ScopeTU), C(c),
Ted Kremenek491918e2009-01-23 20:52:26 +0000260 DisplayedFunction(!displayProgress) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000261 setManagerCreators();
262 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000263
Ted Kremenekf304ddc2008-11-05 19:05:06 +0000264 Decl* getCodeDecl() const {
265 assert (AScope == ScopeDecl);
266 return D;
267 }
268
269 Stmt* getBody() const {
270 assert (AScope == ScopeDecl);
271 return Body;
272 }
273
Zhongxing Xu22438a82008-11-27 01:55:08 +0000274 StoreManagerCreator getStoreManagerCreator() {
275 return CreateStoreMgr;
Ted Kremenek95c7b002008-10-24 01:04:59 +0000276 };
Zhongxing Xu22438a82008-11-27 01:55:08 +0000277
278 ConstraintManagerCreator getConstraintManagerCreator() {
279 return CreateConstraintMgr;
280 }
Ted Kremenek95c7b002008-10-24 01:04:59 +0000281
Ted Kremenek7032f462008-07-03 05:26:14 +0000282 virtual CFG* getCFG() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000283 if (!cfg) cfg.reset(CFG::buildCFG(getBody()));
Ted Kremenek7032f462008-07-03 05:26:14 +0000284 return cfg.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000285 }
286
Ted Kremenekc0959972008-07-02 21:24:01 +0000287 virtual ParentMap& getParentMap() {
Ted Kremeneke2075582008-07-02 23:16:33 +0000288 if (!PM)
289 PM.reset(new ParentMap(getBody()));
Ted Kremenekc0959972008-07-02 21:24:01 +0000290 return *PM.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000291 }
292
Ted Kremenekc0959972008-07-02 21:24:01 +0000293 virtual ASTContext& getContext() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000294 return *C.Ctx;
295 }
296
Ted Kremenekc0959972008-07-02 21:24:01 +0000297 virtual SourceManager& getSourceManager() {
Ted Kremenek235e0312008-07-02 18:11:29 +0000298 return getContext().getSourceManager();
299 }
300
Ted Kremenekc0959972008-07-02 21:24:01 +0000301 virtual Diagnostic& getDiagnostic() {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000302 return C.Diags;
303 }
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000304
305 const LangOptions& getLangOptions() const {
306 return C.LOpts;
307 }
308
Ted Kremenekc0959972008-07-02 21:24:01 +0000309 virtual PathDiagnosticClient* getPathDiagnosticClient() {
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000310 if (C.PD.get() == 0 && !C.OutDir.empty()) {
311 switch (AnalysisDiagOpt) {
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000312 default:
Ted Kremenekc472d792009-01-23 20:06:20 +0000313#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000314case PD_##NAME: C.PD.reset(CREATEFN(C.OutDir, C.PP, C.PPF)); break;
Ted Kremenek4fc82c82008-11-03 23:18:07 +0000315#include "Analyses.def"
316 }
317 }
Ted Kremeneke2075582008-07-02 23:16:33 +0000318 return C.PD.get();
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000319 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000320
Ted Kremenek7032f462008-07-03 05:26:14 +0000321 virtual LiveVariables* getLiveVariables() {
Ted Kremenek235e0312008-07-02 18:11:29 +0000322 if (!liveness) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000323 CFG* c = getCFG();
324 if (!c) return 0;
325
Ted Kremenekca9bab02008-12-09 00:17:51 +0000326 liveness.reset(new LiveVariables(getContext(), *c));
Ted Kremenek7032f462008-07-03 05:26:14 +0000327 liveness->runOnCFG(*c);
328 liveness->runOnAllBlocks(*c, 0, true);
Ted Kremenek235e0312008-07-02 18:11:29 +0000329 }
Ted Kremenekc0959972008-07-02 21:24:01 +0000330
Ted Kremenek7032f462008-07-03 05:26:14 +0000331 return liveness.get();
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000332 }
Ted Kremenek34d77342008-07-02 16:49:11 +0000333
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000334 bool shouldVisualizeGraphviz() const { return VisualizeEGDot; }
335
336 bool shouldVisualizeUbigraph() const { return VisualizeEGUbi; }
337
338 bool shouldVisualize() const {
339 return VisualizeEGDot || VisualizeEGUbi;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000340 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000341
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000342 bool shouldTrimGraph() const { return TrimGraph; }
343
Ted Kremenek34d77342008-07-02 16:49:11 +0000344 void DisplayFunction() {
345
346 if (DisplayedFunction)
347 return;
348
349 DisplayedFunction = true;
350
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000351 // FIXME: Is getCodeDecl() always a named decl?
352 if (isa<FunctionDecl>(getCodeDecl()) ||
353 isa<ObjCMethodDecl>(getCodeDecl())) {
354 NamedDecl *ND = cast<NamedDecl>(getCodeDecl());
355 SourceManager &SM = getContext().getSourceManager();
Ted Kremeneka88fcef2008-11-20 16:14:48 +0000356 llvm::cerr << "ANALYZE: "
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000357 << SM.getPresumedLoc(ND->getLocation()).getFilename()
358 << ' ' << ND->getNameAsString() << '\n';
Ted Kremenek34d77342008-07-02 16:49:11 +0000359 }
360 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000361
362 private:
363 /// Set configurable analyzer components creators. First check if there are
364 /// components registered at runtime. Otherwise fall back to builtin
365 /// components.
366 void setManagerCreators() {
367 if (ManagerRegistry::StoreMgrCreator != 0) {
368 CreateStoreMgr = ManagerRegistry::StoreMgrCreator;
369 }
370 else {
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000371 switch (AnalysisStoreOpt) {
Zhongxing Xu22438a82008-11-27 01:55:08 +0000372 default:
373 assert(0 && "Unknown store manager.");
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000374#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
375 case NAME##Model: CreateStoreMgr = CREATEFN; break;
Zhongxing Xu22438a82008-11-27 01:55:08 +0000376#include "Analyses.def"
377 }
378 }
379
380 if (ManagerRegistry::ConstraintMgrCreator != 0)
381 CreateConstraintMgr = ManagerRegistry::ConstraintMgrCreator;
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000382 else {
383 switch (AnalysisConstraintsOpt) {
384 default:
385 assert(0 && "Unknown store manager.");
386#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
387 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
388#include "Analyses.def"
389 }
390 }
391
Ted Kremenekc472d792009-01-23 20:06:20 +0000392
393 // Some DiagnosticClients should be created all the time instead of
394 // lazily. Create those now.
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000395 switch (AnalysisDiagOpt) {
Ted Kremenekc472d792009-01-23 20:06:20 +0000396 default: break;
397#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN, AUTOCREATE)\
398case PD_##NAME: if (AUTOCREATE) getPathDiagnosticClient(); break;
399#include "Analyses.def"
400 }
Zhongxing Xu22438a82008-11-27 01:55:08 +0000401 }
402
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000403 };
Zhongxing Xu22438a82008-11-27 01:55:08 +0000404
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000405} // end anonymous namespace
406
407namespace llvm {
408 template <> struct FoldingSetTrait<CodeAction> {
409 static inline void Profile(CodeAction X, FoldingSetNodeID& ID) {
410 ID.AddPointer(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(X)));
411 }
412 };
413}
414
415//===----------------------------------------------------------------------===//
416// AnalysisConsumer implementation.
417//===----------------------------------------------------------------------===//
418
Chris Lattner682bf922009-03-29 16:50:03 +0000419void AnalysisConsumer::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000420 switch (D->getKind()) {
421 case Decl::Function: {
422 FunctionDecl* FD = cast<FunctionDecl>(D);
Ted Kremenek235e0312008-07-02 18:11:29 +0000423
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000424 if (AnalyzeSpecificFunction.size() > 0 &&
425 AnalyzeSpecificFunction != FD->getIdentifier()->getName())
Ted Kremenek235e0312008-07-02 18:11:29 +0000426 break;
427
Douglas Gregor72971342009-04-18 00:02:19 +0000428 Stmt* Body = FD->getBody(*Ctx);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000429 if (Body) HandleCode(FD, Body, FunctionActions);
430 break;
431 }
432
433 case Decl::ObjCMethod: {
434 ObjCMethodDecl* MD = cast<ObjCMethodDecl>(D);
Ted Kremenek235e0312008-07-02 18:11:29 +0000435
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000436 if (AnalyzeSpecificFunction.size() > 0 &&
437 AnalyzeSpecificFunction != MD->getSelector().getAsString())
Ted Kremenek235e0312008-07-02 18:11:29 +0000438 return;
439
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000440 Stmt* Body = MD->getBody();
441 if (Body) HandleCode(MD, Body, ObjCMethodActions);
442 break;
443 }
444
445 default:
446 break;
447 }
448}
449
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000450void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000451
Ted Kremenekdaac6342008-11-07 02:09:25 +0000452 if(!TranslationUnitActions.empty()) {
Chris Lattner678dc3b2009-03-28 04:05:05 +0000453 AnalysisManager mgr(*this, AnalyzerDisplayProgress);
Ted Kremenekdaac6342008-11-07 02:09:25 +0000454 for (Actions::iterator I = TranslationUnitActions.begin(),
455 E = TranslationUnitActions.end(); I != E; ++I)
456 (*I)(mgr);
457 }
458
Chris Lattnere9077872009-03-28 03:29:40 +0000459 if (!ObjCImplementationActions.empty()) {
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000460 TranslationUnitDecl *TUD = C.getTranslationUnitDecl();
Chris Lattnere9077872009-03-28 03:29:40 +0000461
Douglas Gregor6ab35242009-04-09 21:40:53 +0000462 for (DeclContext::decl_iterator I = TUD->decls_begin(C),
463 E = TUD->decls_end(C);
Chris Lattnere9077872009-03-28 03:29:40 +0000464 I != E; ++I)
Ted Kremenek4d53a532009-02-13 00:51:30 +0000465 if (ObjCImplementationDecl* ID = dyn_cast<ObjCImplementationDecl>(*I))
466 HandleCode(ID, 0, ObjCImplementationActions);
Chris Lattnere9077872009-03-28 03:29:40 +0000467 }
Ted Kremenek4d53a532009-02-13 00:51:30 +0000468
469 // Delete the PathDiagnosticClient here just in case the AnalysisConsumer
470 // object doesn't get released. This will cause any side-effects in the
471 // destructor of the PathDiagnosticClient to get executed.
472 PD.reset();
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000473}
474
Ted Kremenek81922f02009-02-02 20:52:40 +0000475void AnalysisConsumer::HandleCode(Decl* D, Stmt* Body, Actions& actions) {
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000476
477 // Don't run the actions if an error has occured with parsing the file.
478 if (Diags.hasErrorOccurred())
479 return;
Ted Kremenek81922f02009-02-02 20:52:40 +0000480
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000481 // Don't run the actions on declarations in header files unless
482 // otherwise specified.
Ted Kremenek81922f02009-02-02 20:52:40 +0000483 if (!AnalyzeAll && !Ctx->getSourceManager().isFromMainFile(D->getLocation()))
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000484 return;
485
486 // Create an AnalysisManager that will manage the state for analyzing
487 // this method/function.
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000488 AnalysisManager mgr(*this, D, Body, AnalyzerDisplayProgress);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000489
490 // Dispatch on the actions.
Zhongxing Xu3702af52008-10-30 05:03:28 +0000491 for (Actions::iterator I = actions.begin(), E = actions.end(); I != E; ++I)
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000492 (*I)(mgr);
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000493}
494
495//===----------------------------------------------------------------------===//
496// Analyses
497//===----------------------------------------------------------------------===//
498
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000499static void ActionWarnDeadStores(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000500 if (LiveVariables* L = mgr.getLiveVariables()) {
501 BugReporter BR(mgr);
502 CheckDeadStores(*L, BR);
503 }
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000504}
505
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000506static void ActionWarnUninitVals(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000507 if (CFG* c = mgr.getCFG())
508 CheckUninitializedValues(*c, mgr.getContext(), mgr.getDiagnostic());
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000509}
510
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000511
Ted Kremenek78d46242008-07-22 16:21:24 +0000512static void ActionGRExprEngine(AnalysisManager& mgr, GRTransferFuncs* tf,
513 bool StandardWarnings = true) {
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000514
Ted Kremenek7032f462008-07-03 05:26:14 +0000515
Ted Kremenekbc46f342008-07-02 16:35:50 +0000516 llvm::OwningPtr<GRTransferFuncs> TF(tf);
Ted Kremenek7032f462008-07-03 05:26:14 +0000517
Ted Kremenek8ffc8a52008-11-24 20:53:32 +0000518 // Display progress.
519 mgr.DisplayFunction();
520
Ted Kremenek7032f462008-07-03 05:26:14 +0000521 // Construct the analysis engine.
522 LiveVariables* L = mgr.getLiveVariables();
523 if (!L) return;
Ted Kremenek8ffc8a52008-11-24 20:53:32 +0000524
Ted Kremenekcf118d42009-02-04 23:49:09 +0000525 GRExprEngine Eng(*mgr.getCFG(), *mgr.getCodeDecl(), mgr.getContext(), *L, mgr,
Ted Kremenek48af2a92009-02-25 22:32:02 +0000526 PurgeDead, EagerlyAssume,
Zhongxing Xu22438a82008-11-27 01:55:08 +0000527 mgr.getStoreManagerCreator(),
528 mgr.getConstraintManagerCreator());
Ted Kremenek95c7b002008-10-24 01:04:59 +0000529
Ted Kremenekbc46f342008-07-02 16:35:50 +0000530 Eng.setTransferFunctions(tf);
531
Ted Kremenek78d46242008-07-22 16:21:24 +0000532 if (StandardWarnings) {
533 Eng.RegisterInternalChecks();
534 RegisterAppleChecks(Eng);
535 }
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000536
537 // Set the graph auditor.
538 llvm::OwningPtr<ExplodedNodeImpl::Auditor> Auditor;
539 if (mgr.shouldVisualizeUbigraph()) {
540 Auditor.reset(CreateUbiViz());
541 ExplodedNodeImpl::SetAuditor(Auditor.get());
542 }
Ted Kremenek78d46242008-07-22 16:21:24 +0000543
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000544 // Execute the worklist algorithm.
545 Eng.ExecuteWorkList();
Ted Kremenekbc46f342008-07-02 16:35:50 +0000546
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000547 // Release the auditor (if any) so that it doesn't monitor the graph
548 // created BugReporter.
549 ExplodedNodeImpl::SetAuditor(0);
Ted Kremenek3df64212009-03-11 01:42:29 +0000550
Ted Kremenek34d77342008-07-02 16:49:11 +0000551 // Visualize the exploded graph.
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000552 if (mgr.shouldVisualizeGraphviz())
Ted Kremenek34d77342008-07-02 16:49:11 +0000553 Eng.ViewGraph(mgr.shouldTrimGraph());
Ted Kremenek3df64212009-03-11 01:42:29 +0000554
555 // Display warnings.
556 Eng.getBugReporter().FlushReports();
Ted Kremenekbc46f342008-07-02 16:35:50 +0000557}
558
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000559static void ActionCheckerCFRefAux(AnalysisManager& mgr, bool GCEnabled,
Ted Kremenek78d46242008-07-22 16:21:24 +0000560 bool StandardWarnings) {
561
Ted Kremenekbc46f342008-07-02 16:35:50 +0000562 GRTransferFuncs* TF = MakeCFRefCountTF(mgr.getContext(),
563 GCEnabled,
Ted Kremenekbc46f342008-07-02 16:35:50 +0000564 mgr.getLangOptions());
565
Ted Kremenek78d46242008-07-22 16:21:24 +0000566 ActionGRExprEngine(mgr, TF, StandardWarnings);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000567}
568
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000569static void ActionCheckerCFRef(AnalysisManager& mgr) {
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000570
571 switch (mgr.getLangOptions().getGCMode()) {
572 default:
573 assert (false && "Invalid GC mode.");
574 case LangOptions::NonGC:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000575 ActionCheckerCFRefAux(mgr, false, true);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000576 break;
577
578 case LangOptions::GCOnly:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000579 ActionCheckerCFRefAux(mgr, true, true);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000580 break;
581
582 case LangOptions::HybridGC:
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000583 ActionCheckerCFRefAux(mgr, false, true);
584 ActionCheckerCFRefAux(mgr, true, false);
Ted Kremenekb35a74a2008-07-02 00:44:58 +0000585 break;
586 }
587}
588
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000589static void ActionCheckerSimple(AnalysisManager& mgr) {
Ted Kremenekbc46f342008-07-02 16:35:50 +0000590 ActionGRExprEngine(mgr, MakeGRSimpleValsTF());
591}
592
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000593static void ActionDisplayLiveVariables(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000594 if (LiveVariables* L = mgr.getLiveVariables()) {
595 mgr.DisplayFunction();
596 L->dumpBlockLiveness(mgr.getSourceManager());
597 }
Ted Kremenek235e0312008-07-02 18:11:29 +0000598}
599
Ted Kremenek902141f2008-07-02 18:23:21 +0000600static void ActionCFGDump(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000601 if (CFG* c = mgr.getCFG()) {
602 mgr.DisplayFunction();
603 c->dump();
604 }
Ted Kremenek902141f2008-07-02 18:23:21 +0000605}
606
607static void ActionCFGView(AnalysisManager& mgr) {
Ted Kremenek7032f462008-07-03 05:26:14 +0000608 if (CFG* c = mgr.getCFG()) {
609 mgr.DisplayFunction();
610 c->viewCFG();
611 }
Ted Kremenek902141f2008-07-02 18:23:21 +0000612}
613
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000614static void ActionWarnObjCDealloc(AnalysisManager& mgr) {
Ted Kremenek4f4e7e42008-08-04 17:14:10 +0000615 if (mgr.getLangOptions().getGCMode() == LangOptions::GCOnly)
616 return;
617
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000618 BugReporter BR(mgr);
Ted Kremenek3cd483c2008-07-03 14:35:01 +0000619
620 CheckObjCDealloc(cast<ObjCImplementationDecl>(mgr.getCodeDecl()),
621 mgr.getLangOptions(), BR);
Ted Kremenekdb09a4d2008-07-03 04:29:21 +0000622}
623
Ted Kremenek395aaf22008-07-23 00:45:26 +0000624static void ActionWarnObjCUnusedIvars(AnalysisManager& mgr) {
625 BugReporter BR(mgr);
626 CheckObjCUnusedIvar(cast<ObjCImplementationDecl>(mgr.getCodeDecl()), BR);
627}
628
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000629static void ActionWarnObjCMethSigs(AnalysisManager& mgr) {
Ted Kremenek0d8019e2008-07-11 22:40:47 +0000630 BugReporter BR(mgr);
631
632 CheckObjCInstMethSignature(cast<ObjCImplementationDecl>(mgr.getCodeDecl()),
633 BR);
634}
635
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000636//===----------------------------------------------------------------------===//
637// AnalysisConsumer creation.
638//===----------------------------------------------------------------------===//
639
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000640ASTConsumer* clang::CreateAnalysisConsumer(Diagnostic &diags, Preprocessor* pp,
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000641 PreprocessorFactory* ppf,
642 const LangOptions& lopts,
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000643 const std::string& OutDir) {
644
645 llvm::OwningPtr<AnalysisConsumer> C(new AnalysisConsumer(diags, pp, ppf,
646 lopts, OutDir));
647
648 for (unsigned i = 0; i < AnalysisList.size(); ++i)
649 switch (AnalysisList[i]) {
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000650#define ANALYSIS(NAME, CMD, DESC, SCOPE)\
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000651 case NAME:\
Ted Kremenekf7f3c202008-07-15 00:46:02 +0000652 C->add ## SCOPE ## Action(&Action ## NAME);\
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000653 break;
Ted Kremenekfb9a48c2008-07-14 23:41:13 +0000654#include "Analyses.def"
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000655 default: break;
656 }
Ted Kremenek2c4036e2009-05-07 19:02:53 +0000657
658 // Last, disable the effects of '-Werror' when using the AnalysisConsumer.
659 diags.setWarningsAsErrors(false);
Ted Kremenekbe1fe1e2009-02-17 04:27:41 +0000660
Ted Kremenekf4381fd2008-07-02 00:03:09 +0000661 return C.take();
662}
663
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000664//===----------------------------------------------------------------------===//
665// Ubigraph Visualization. FIXME: Move to separate file.
666//===----------------------------------------------------------------------===//
667
668namespace {
669
670class UbigraphViz : public ExplodedNodeImpl::Auditor {
671 llvm::OwningPtr<llvm::raw_ostream> Out;
Ted Kremenek710ad932008-08-28 03:54:51 +0000672 llvm::sys::Path Dir, Filename;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000673 unsigned Cntr;
674
675 typedef llvm::DenseMap<void*,unsigned> VMap;
676 VMap M;
677
678public:
Ted Kremenek710ad932008-08-28 03:54:51 +0000679 UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
Ted Kremenek56b98712008-08-28 05:02:09 +0000680 llvm::sys::Path& filename);
Ted Kremenek710ad932008-08-28 03:54:51 +0000681
682 ~UbigraphViz();
683
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000684 virtual void AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst);
685};
686
687} // end anonymous namespace
688
689static ExplodedNodeImpl::Auditor* CreateUbiViz() {
690 std::string ErrMsg;
691
Ted Kremenek710ad932008-08-28 03:54:51 +0000692 llvm::sys::Path Dir = llvm::sys::Path::GetTemporaryDirectory(&ErrMsg);
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000693 if (!ErrMsg.empty())
694 return 0;
695
Ted Kremenek710ad932008-08-28 03:54:51 +0000696 llvm::sys::Path Filename = Dir;
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000697 Filename.appendComponent("llvm_ubi");
698 Filename.makeUnique(true,&ErrMsg);
699
700 if (!ErrMsg.empty())
701 return 0;
702
703 llvm::cerr << "Writing '" << Filename << "'.\n";
704
705 llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
706 std::string filename = Filename.toString();
Daniel Dunbar26fb2722008-11-13 05:09:21 +0000707 Stream.reset(new llvm::raw_fd_ostream(filename.c_str(), false, ErrMsg));
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000708
709 if (!ErrMsg.empty())
710 return 0;
711
Ted Kremenek710ad932008-08-28 03:54:51 +0000712 return new UbigraphViz(Stream.take(), Dir, Filename);
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000713}
714
715void UbigraphViz::AddEdge(ExplodedNodeImpl* Src, ExplodedNodeImpl* Dst) {
Ted Kremenek45479c82008-08-28 18:34:41 +0000716
717 assert (Src != Dst && "Self-edges are not allowed.");
718
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000719 // Lookup the Src. If it is a new node, it's a root.
720 VMap::iterator SrcI= M.find(Src);
721 unsigned SrcID;
722
723 if (SrcI == M.end()) {
724 M[Src] = SrcID = Cntr++;
725 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n";
726 }
727 else
728 SrcID = SrcI->second;
729
730 // Lookup the Dst.
731 VMap::iterator DstI= M.find(Dst);
732 unsigned DstID;
733
734 if (DstI == M.end()) {
735 M[Dst] = DstID = Cntr++;
736 *Out << "('vertex', " << DstID << ")\n";
737 }
Ted Kremenek56b98712008-08-28 05:02:09 +0000738 else {
739 // We have hit DstID before. Change its style to reflect a cache hit.
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000740 DstID = DstI->second;
Ted Kremenek56b98712008-08-28 05:02:09 +0000741 *Out << "('change_vertex_style', " << DstID << ", 1)\n";
742 }
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000743
744 // Add the edge.
Ted Kremenekd1289322008-08-27 22:46:55 +0000745 *Out << "('edge', " << SrcID << ", " << DstID
746 << ", ('arrow','true'), ('oriented', 'true'))\n";
Ted Kremenekf8ce6992008-08-27 22:31:43 +0000747}
748
Ted Kremenek56b98712008-08-28 05:02:09 +0000749UbigraphViz::UbigraphViz(llvm::raw_ostream* out, llvm::sys::Path& dir,
750 llvm::sys::Path& filename)
751 : Out(out), Dir(dir), Filename(filename), Cntr(0) {
752
753 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n";
754 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66'),"
755 " ('size', '1.5'))\n";
756}
757
Ted Kremenek710ad932008-08-28 03:54:51 +0000758UbigraphViz::~UbigraphViz() {
759 Out.reset(0);
760 llvm::cerr << "Running 'ubiviz' program... ";
761 std::string ErrMsg;
762 llvm::sys::Path Ubiviz = llvm::sys::Program::FindProgramByName("ubiviz");
763 std::vector<const char*> args;
764 args.push_back(Ubiviz.c_str());
765 args.push_back(Filename.c_str());
766 args.push_back(0);
767
768 if (llvm::sys::Program::ExecuteAndWait(Ubiviz, &args[0],0,0,0,0,&ErrMsg)) {
769 llvm::cerr << "Error viewing graph: " << ErrMsg << "\n";
770 }
771
772 // Delete the directory.
773 Dir.eraseFromDisk(true);
Daniel Dunbar932680e2008-08-29 03:45:59 +0000774}