xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp (revision ea70eb30a030b5ac3afb32c5d91ec2a4f580511d)
1 //==- ObjCUnusedIVarsChecker.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 "ClangSACheckers.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/SourceManager.h"
26 
27 using namespace clang;
28 using namespace ento;
29 
30 enum IVarState { Unused, Used };
31 typedef llvm::DenseMap<const ObjCIvarDecl*,IVarState> IvarUsageMap;
32 
33 static void Scan(IvarUsageMap& M, const Stmt *S) {
34   if (!S)
35     return;
36 
37   if (const ObjCIvarRefExpr *Ex = dyn_cast<ObjCIvarRefExpr>(S)) {
38     const ObjCIvarDecl *D = Ex->getDecl();
39     IvarUsageMap::iterator I = M.find(D);
40     if (I != M.end())
41       I->second = Used;
42     return;
43   }
44 
45   // Blocks can reference an instance variable of a class.
46   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
47     Scan(M, BE->getBody());
48     return;
49   }
50 
51   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(S))
52     for (PseudoObjectExpr::const_semantics_iterator
53         i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
54       const Expr *sub = *i;
55       if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(sub))
56         sub = OVE->getSourceExpr();
57       Scan(M, sub);
58     }
59 
60   for (Stmt::const_child_iterator I=S->child_begin(),E=S->child_end(); I!=E;++I)
61     Scan(M, *I);
62 }
63 
64 static void Scan(IvarUsageMap& M, const ObjCPropertyImplDecl *D) {
65   if (!D)
66     return;
67 
68   const ObjCIvarDecl *ID = D->getPropertyIvarDecl();
69 
70   if (!ID)
71     return;
72 
73   IvarUsageMap::iterator I = M.find(ID);
74   if (I != M.end())
75     I->second = Used;
76 }
77 
78 static void Scan(IvarUsageMap& M, const ObjCContainerDecl *D) {
79   // Scan the methods for accesses.
80   for (ObjCContainerDecl::instmeth_iterator I = D->instmeth_begin(),
81        E = D->instmeth_end(); I!=E; ++I)
82     Scan(M, (*I)->getBody());
83 
84   if (const ObjCImplementationDecl *ID = dyn_cast<ObjCImplementationDecl>(D)) {
85     // Scan for @synthesized property methods that act as setters/getters
86     // to an ivar.
87     for (ObjCImplementationDecl::propimpl_iterator I = ID->propimpl_begin(),
88          E = ID->propimpl_end(); I!=E; ++I)
89       Scan(M, *I);
90 
91     // Scan the associated categories as well.
92     for (const ObjCCategoryDecl *CD =
93           ID->getClassInterface()->getCategoryList(); CD ;
94           CD = CD->getNextClassCategory()) {
95       if (const ObjCCategoryImplDecl *CID = CD->getImplementation())
96         Scan(M, CID);
97     }
98   }
99 }
100 
101 static void Scan(IvarUsageMap &M, const DeclContext *C, const FileID FID,
102                  SourceManager &SM) {
103   for (DeclContext::decl_iterator I=C->decls_begin(), E=C->decls_end();
104        I!=E; ++I)
105     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
106       SourceLocation L = FD->getLocStart();
107       if (SM.getFileID(L) == FID)
108         Scan(M, FD->getBody());
109     }
110 }
111 
112 static void checkObjCUnusedIvar(const ObjCImplementationDecl *D,
113                                 BugReporter &BR) {
114 
115   const ObjCInterfaceDecl *ID = D->getClassInterface();
116   IvarUsageMap M;
117 
118   // Iterate over the ivars.
119   for (ObjCInterfaceDecl::ivar_iterator I=ID->ivar_begin(),
120         E=ID->ivar_end(); I!=E; ++I) {
121 
122     const ObjCIvarDecl *ID = *I;
123 
124     // Ignore ivars that...
125     // (a) aren't private
126     // (b) explicitly marked unused
127     // (c) are iboutlets
128     // (d) are unnamed bitfields
129     if (ID->getAccessControl() != ObjCIvarDecl::Private ||
130         ID->getAttr<UnusedAttr>() || ID->getAttr<IBOutletAttr>() ||
131         ID->getAttr<IBOutletCollectionAttr>() ||
132         ID->isUnnamedBitfield())
133       continue;
134 
135     M[ID] = Unused;
136   }
137 
138   if (M.empty())
139     return;
140 
141   // Now scan the implementation declaration.
142   Scan(M, D);
143 
144   // Any potentially unused ivars?
145   bool hasUnused = false;
146   for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I)
147     if (I->second == Unused) {
148       hasUnused = true;
149       break;
150     }
151 
152   if (!hasUnused)
153     return;
154 
155   // We found some potentially unused ivars.  Scan the entire translation unit
156   // for functions inside the @implementation that reference these ivars.
157   // FIXME: In the future hopefully we can just use the lexical DeclContext
158   // to go from the ObjCImplementationDecl to the lexically "nested"
159   // C functions.
160   SourceManager &SM = BR.getSourceManager();
161   Scan(M, D->getDeclContext(), SM.getFileID(D->getLocation()), SM);
162 
163   // Find ivars that are unused.
164   for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I)
165     if (I->second == Unused) {
166       std::string sbuf;
167       llvm::raw_string_ostream os(sbuf);
168       os << "Instance variable '" << *I->first << "' in class '" << *ID
169          << "' is never used by the methods in its @implementation "
170             "(although it may be used by category methods).";
171 
172       PathDiagnosticLocation L =
173         PathDiagnosticLocation::create(I->first, BR.getSourceManager());
174       BR.EmitBasicReport(D, "Unused instance variable", "Optimization",
175                          os.str(), L);
176     }
177 }
178 
179 //===----------------------------------------------------------------------===//
180 // ObjCUnusedIvarsChecker
181 //===----------------------------------------------------------------------===//
182 
183 namespace {
184 class ObjCUnusedIvarsChecker : public Checker<
185                                       check::ASTDecl<ObjCImplementationDecl> > {
186 public:
187   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& mgr,
188                     BugReporter &BR) const {
189     checkObjCUnusedIvar(D, BR);
190   }
191 };
192 }
193 
194 void ento::registerObjCUnusedIvarsChecker(CheckerManager &mgr) {
195   mgr.registerChecker<ObjCUnusedIvarsChecker>();
196 }
197