blob: d074dde8a3c9bb6c5ed33769ccf1a815ba0a5af6 [file] [log] [blame]
Ted Kremenek395aaf22008-07-23 00:45:26 +00001//==- CheckObjCUnusedIVars.cpp - Check for unused ivars ----------*- C++ -*-==//
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// This file defines a CheckObjCUnusedIvars, a checker that
11// analyzes an Objective-C class's interface/implementation to determine if it
12// has any ivars that are never accessed.
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/Analysis/LocalCheckers.h"
17#include "clang/Analysis/PathDiagnostic.h"
18#include "clang/Analysis/PathSensitive/BugReporter.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/Basic/LangOptions.h"
23#include <sstream>
24
25using namespace clang;
26
27enum IVarState { Unused, Used };
28typedef llvm::DenseMap<ObjCIvarDecl*,IVarState> IvarUsageMap;
29
30static void Scan(IvarUsageMap& M, Stmt* S) {
31 if (!S)
32 return;
33
34 if (ObjCIvarRefExpr* Ex = dyn_cast<ObjCIvarRefExpr>(S)) {
35 ObjCIvarDecl* D = Ex->getDecl();
36 IvarUsageMap::iterator I = M.find(D);
37 if (I != M.end()) I->second = Used;
38 }
39 else
40 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E;++I)
41 Scan(M, *I);
42}
43
44void clang::CheckObjCUnusedIvar(ObjCImplementationDecl* D, BugReporter& BR) {
45
46 ObjCInterfaceDecl* ID = D->getClassInterface();
47 IvarUsageMap M;
48
49
50
51 // Iterate over the ivars.
52 for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(), E=ID->ivar_end();
53 I!=E; ++I) {
54
55 ObjCIvarDecl* ID = *I;
56
57 // Ignore ivars that aren't private.
Ted Kremenek6678f7f2008-07-23 17:14:39 +000058 if (ID->getAccessControl() != ObjCIvarDecl::Private)
Ted Kremenek395aaf22008-07-23 00:45:26 +000059 continue;
60
61 if (ID->getAttr<IBOutletAttr>() == 0)
62 continue;
63
64 M[ID] = Unused;
65 }
66
67 if (M.empty())
68 return;
69
70 // Now scan the methods for accesses.
71 for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
72 E = D->instmeth_end(); I!=E; ++I)
73 Scan(M, (*I)->getBody());
74
75 // Find ivars that are unused.
76 for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I)
77 if (I->second == Unused) {
78
79 std::ostringstream os;
80 os << "Private ivar '" << I->first->getName() << "' is never used.";
81
82 BR.EmitBasicReport("unused ivar",
83 os.str().c_str(), I->first->getLocation());
84 }
85}
86