clang 19.0.0git
ObjCUnusedIVarsChecker.cpp
Go to the documentation of this file.
1//==- ObjCUnusedIVarsChecker.cpp - Check for unused ivars --------*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a CheckObjCUnusedIvars, a checker that
10// analyzes an Objective-C class's interface/implementation to determine if it
11// has any ivars that are never accessed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/Attr.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprObjC.h"
25#include "llvm/ADT/STLExtras.h"
26
27using namespace clang;
28using namespace ento;
29
31typedef llvm::DenseMap<const ObjCIvarDecl*,IVarState> IvarUsageMap;
32
33static 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 (const Expr *sub : POE->semantics()) {
53 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(sub))
54 sub = OVE->getSourceExpr();
55 Scan(M, sub);
56 }
57
58 for (const Stmt *SubStmt : S->children())
59 Scan(M, SubStmt);
60}
61
62static void Scan(IvarUsageMap& M, const ObjCPropertyImplDecl *D) {
63 if (!D)
64 return;
65
66 const ObjCIvarDecl *ID = D->getPropertyIvarDecl();
67
68 if (!ID)
69 return;
70
71 IvarUsageMap::iterator I = M.find(ID);
72 if (I != M.end())
73 I->second = Used;
74}
75
76static void Scan(IvarUsageMap& M, const ObjCContainerDecl *D) {
77 // Scan the methods for accesses.
78 for (const auto *I : D->instance_methods())
79 Scan(M, I->getBody());
80
81 if (const ObjCImplementationDecl *ID = dyn_cast<ObjCImplementationDecl>(D)) {
82 // Scan for @synthesized property methods that act as setters/getters
83 // to an ivar.
84 for (const auto *I : ID->property_impls())
85 Scan(M, I);
86
87 // Scan the associated categories as well.
88 for (const auto *Cat : ID->getClassInterface()->visible_categories()) {
89 if (const ObjCCategoryImplDecl *CID = Cat->getImplementation())
90 Scan(M, CID);
91 }
92 }
93}
94
95static void Scan(IvarUsageMap &M, const DeclContext *C, const FileID FID,
96 const SourceManager &SM) {
97 for (const auto *I : C->decls())
98 if (const auto *FD = dyn_cast<FunctionDecl>(I)) {
99 SourceLocation L = FD->getBeginLoc();
100 if (SM.getFileID(L) == FID)
101 Scan(M, FD->getBody());
102 }
103}
104
106 BugReporter &BR,
107 const CheckerBase *Checker) {
108
109 const ObjCInterfaceDecl *ID = D->getClassInterface();
110 IvarUsageMap M;
111
112 // Iterate over the ivars.
113 for (const auto *Ivar : ID->ivars()) {
114 // Ignore ivars that...
115 // (a) aren't private
116 // (b) explicitly marked unused
117 // (c) are iboutlets
118 // (d) are unnamed bitfields
119 if (Ivar->getAccessControl() != ObjCIvarDecl::Private ||
120 Ivar->hasAttr<UnusedAttr>() || Ivar->hasAttr<IBOutletAttr>() ||
121 Ivar->hasAttr<IBOutletCollectionAttr>() ||
122 Ivar->isUnnamedBitfield())
123 continue;
124
125 M[Ivar] = Unused;
126 }
127
128 if (M.empty())
129 return;
130
131 // Now scan the implementation declaration.
132 Scan(M, D);
133
134 // Any potentially unused ivars?
135 bool hasUnused = false;
136 for (IVarState State : llvm::make_second_range(M))
137 if (State == Unused) {
138 hasUnused = true;
139 break;
140 }
141
142 if (!hasUnused)
143 return;
144
145 // We found some potentially unused ivars. Scan the entire translation unit
146 // for functions inside the @implementation that reference these ivars.
147 // FIXME: In the future hopefully we can just use the lexical DeclContext
148 // to go from the ObjCImplementationDecl to the lexically "nested"
149 // C functions.
150 const SourceManager &SM = BR.getSourceManager();
151 Scan(M, D->getDeclContext(), SM.getFileID(D->getLocation()), SM);
152
153 // Find ivars that are unused.
154 for (auto [Ivar, State] : M)
155 if (State == Unused) {
156 std::string sbuf;
157 llvm::raw_string_ostream os(sbuf);
158 os << "Instance variable '" << *Ivar << "' in class '" << *ID
159 << "' is never used by the methods in its @implementation "
160 "(although it may be used by category methods).";
161
164 BR.EmitBasicReport(ID, Checker, "Unused instance variable",
165 "Optimization", os.str(), L);
166 }
167}
168
169//===----------------------------------------------------------------------===//
170// ObjCUnusedIvarsChecker
171//===----------------------------------------------------------------------===//
172
173namespace {
174class ObjCUnusedIvarsChecker : public Checker<
175 check::ASTDecl<ObjCImplementationDecl> > {
176public:
177 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& mgr,
178 BugReporter &BR) const {
179 checkObjCUnusedIvar(D, BR, this);
180 }
181};
182}
183
184void ento::registerObjCUnusedIvarsChecker(CheckerManager &mgr) {
185 mgr.registerChecker<ObjCUnusedIvarsChecker>();
186}
187
188bool ento::shouldRegisterObjCUnusedIvarsChecker(const CheckerManager &mgr) {
189 return true;
190}
#define SM(sm)
Definition: Cuda.cpp:82
Defines the clang::LangOptions interface.
static void checkObjCUnusedIvar(const ObjCImplementationDecl *D, BugReporter &BR, const CheckerBase *Checker)
llvm::DenseMap< const ObjCIvarDecl *, IVarState > IvarUsageMap
static void Scan(IvarUsageMap &M, const Stmt *S)
Defines the SourceManager interface.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6167
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
SourceLocation getLocation() const
Definition: DeclBase.h:444
DeclContext * getDeclContext()
Definition: DeclBase.h:453
This represents one expression.
Definition: Expr.h:110
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:944
instmeth_range instance_methods() const
Definition: DeclObjC.h:1029
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2595
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1947
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2802
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2875
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6299
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Stmt - This represents one statement.
Definition: Stmt.h:84
BugReporter is a utility class for generating PathDiagnostics for analysis.
Definition: BugReporter.h:585
const SourceManager & getSourceManager()
Definition: BugReporter.h:620
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges=std::nullopt, ArrayRef< FixItHint > Fixits=std::nullopt)
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
The JSON file list parser is used to communicate input to InstallAPI.