blob: d536ea4bdbfad824ed0602bd749b470990098780 [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;
Ted Kremenekcc87ba22008-07-23 18:21:36 +000060
61 // Skip IB Outlets.
62 if (ID->getAttr<IBOutletAttr>())
Ted Kremenek395aaf22008-07-23 00:45:26 +000063 continue;
64
65 M[ID] = Unused;
66 }
67
68 if (M.empty())
69 return;
70
71 // Now scan the methods for accesses.
72 for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
73 E = D->instmeth_end(); I!=E; ++I)
74 Scan(M, (*I)->getBody());
75
76 // Find ivars that are unused.
77 for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I)
78 if (I->second == Unused) {
79
80 std::ostringstream os;
Ted Kremenekcc87ba22008-07-23 18:21:36 +000081 os << "Instance variable '" << I->first->getName()
82 << "' in class '" << ID->getName() << "' is never used.";
83
Ted Kremenek395aaf22008-07-23 00:45:26 +000084 BR.EmitBasicReport("unused ivar",
85 os.str().c_str(), I->first->getLocation());
86 }
87}
88