clang-tools 23.0.0git
NonConstParameterCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
16
18 // Add parameters to Parameters.
19 Finder->addMatcher(parmVarDecl().bind("Parm"), this);
20
21 // C++ constructor.
22 Finder->addMatcher(cxxConstructorDecl().bind("Ctor"), this);
23
24 // Track unused parameters, there is Wunused-parameter about unused
25 // parameters.
26 Finder->addMatcher(declRefExpr().bind("Ref"), this);
27
28 // Analyse parameter usage in function.
29 Finder->addMatcher(
30 stmt(anyOf(unaryOperator(hasAnyOperatorName("++", "--")),
31 binaryOperator(), callExpr(), returnStmt(), cxxConstructExpr(),
32 cxxUnresolvedConstructExpr()))
33 .bind("Mark"),
34 this);
35 Finder->addMatcher(varDecl(hasInitializer(anything())).bind("Mark"), this);
36}
37
38void NonConstParameterCheck::check(const MatchFinder::MatchResult &Result) {
39 if (const auto *Parm = Result.Nodes.getNodeAs<ParmVarDecl>("Parm")) {
40 if (const DeclContext *D = Parm->getParentFunctionOrMethod()) {
41 if (const auto *M = dyn_cast<CXXMethodDecl>(D)) {
42 if (M->isVirtual() || M->size_overridden_methods() != 0)
43 return;
44 }
45 }
46 addParm(Parm);
47 } else if (const auto *Ctor =
48 Result.Nodes.getNodeAs<CXXConstructorDecl>("Ctor")) {
49 for (const auto *Parm : Ctor->parameters())
50 addParm(Parm);
51 for (const auto *Init : Ctor->inits())
52 markCanNotBeConst(Init->getInit(), true);
53 } else if (const auto *Ref = Result.Nodes.getNodeAs<DeclRefExpr>("Ref")) {
54 setReferenced(Ref);
55 } else if (const auto *S = Result.Nodes.getNodeAs<Stmt>("Mark")) {
56 if (const auto *B = dyn_cast<BinaryOperator>(S)) {
57 if (B->isAssignmentOp())
58 markCanNotBeConst(B, false);
59 } else if (const auto *CE = dyn_cast<CallExpr>(S)) {
60 // Typically, if a parameter is const then it is fine to make the data
61 // const. But sometimes the data is written even though the parameter
62 // is const. Mark all data passed by address to the function.
63 for (const auto *Arg : CE->arguments())
64 markCanNotBeConst(Arg->IgnoreParenCasts(), true);
65
66 // Data passed by nonconst reference should not be made const.
67 if (const FunctionDecl *FD = CE->getDirectCallee()) {
68 unsigned ArgNr = 0U;
69 for (const auto *Par : FD->parameters()) {
70 if (ArgNr >= CE->getNumArgs())
71 break;
72 const Expr *Arg = CE->getArg(ArgNr++);
73 // Is this a non constant reference parameter?
74 const Type *ParType = Par->getType().getTypePtr();
75 if (!ParType->isReferenceType() || Par->getType().isConstQualified())
76 continue;
77 markCanNotBeConst(Arg->IgnoreParenCasts(), false);
78 }
79 }
80 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(S)) {
81 for (const auto *Arg : CE->arguments())
82 markCanNotBeConst(Arg->IgnoreParenCasts(), true);
83 // Data passed by nonconst reference should not be made const.
84 unsigned ArgNr = 0U;
85 if (const auto *CD = CE->getConstructor()) {
86 for (const auto *Par : CD->parameters()) {
87 if (ArgNr >= CE->getNumArgs())
88 break;
89 const Expr *Arg = CE->getArg(ArgNr++);
90 // Is this a non constant reference parameter?
91 const Type *ParType = Par->getType().getTypePtr();
92 if (!ParType->isReferenceType() || Par->getType().isConstQualified())
93 continue;
94 markCanNotBeConst(Arg->IgnoreParenCasts(), false);
95 }
96 }
97 } else if (const auto *CE = dyn_cast<CXXUnresolvedConstructExpr>(S)) {
98 for (const auto *Arg : CE->arguments())
99 markCanNotBeConst(Arg->IgnoreParenCasts(), true);
100 } else if (const auto *R = dyn_cast<ReturnStmt>(S)) {
101 markCanNotBeConst(R->getRetValue(), true);
102 } else if (const auto *U = dyn_cast<UnaryOperator>(S)) {
103 markCanNotBeConst(U, true);
104 }
105 } else if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("Mark")) {
106 const QualType T = VD->getType();
107 if ((T->isPointerType() && !T->getPointeeType().isConstQualified()) ||
108 T->isArrayType() || T->isRecordType())
109 markCanNotBeConst(VD->getInit(), true);
110 else if (T->isLValueReferenceType() &&
111 !T->getPointeeType().isConstQualified())
112 markCanNotBeConst(VD->getInit(), false);
113 }
114}
115
116void NonConstParameterCheck::addParm(const ParmVarDecl *Parm) {
117 // Only add nonconst integer/float pointer parameters.
118 const QualType T = Parm->getType();
119 if (!T->isPointerType() || T->getPointeeType().isConstQualified() ||
120 !(T->getPointeeType()->isIntegerType() ||
121 T->getPointeeType()->isFloatingType()))
122 return;
123
124 auto [It, Inserted] = Parameters.try_emplace(Parm);
125 if (!Inserted)
126 return;
127
128 It->second.IsReferenced = false;
129 It->second.CanBeConst = true;
130}
131
132void NonConstParameterCheck::setReferenced(const DeclRefExpr *Ref) {
133 auto It = Parameters.find(dyn_cast<ParmVarDecl>(Ref->getDecl()));
134 if (It != Parameters.end())
135 It->second.IsReferenced = true;
136}
137
139 diagnoseNonConstParameters();
140}
141
142void NonConstParameterCheck::diagnoseNonConstParameters() {
143 for (const auto &It : Parameters) {
144 const ParmVarDecl *Par = It.first;
145 const ParmInfo &ParamInfo = It.second;
146
147 // Unused parameter => there are other warnings about this.
148 if (!ParamInfo.IsReferenced)
149 continue;
150
151 // Parameter can't be const.
152 if (!ParamInfo.CanBeConst)
153 continue;
154
155 SmallVector<FixItHint, 8> Fixes;
156 auto *Function =
157 dyn_cast_or_null<const FunctionDecl>(Par->getParentFunctionOrMethod());
158 if (!Function)
159 continue;
160 const unsigned Index = Par->getFunctionScopeIndex();
161 for (FunctionDecl *FnDecl : Function->redecls()) {
162 if (FnDecl->getNumParams() <= Index)
163 continue;
164 Fixes.push_back(FixItHint::CreateInsertion(
165 FnDecl->getParamDecl(Index)->getBeginLoc(), "const "));
166 }
167
168 diag(Par->getLocation(), "pointer parameter '%0' can be pointer to const")
169 << Par->getName() << Fixes;
170 }
171}
172
173void NonConstParameterCheck::markCanNotBeConst(const Expr *E,
174 bool CanNotBeConst) {
175 if (!E)
176 return;
177
178 if (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) {
179 // If expression is const then ignore usage.
180 const QualType T = Cast->getType();
181 if (T->isPointerType() && T->getPointeeType().isConstQualified())
182 return;
183 }
184
185 E = E->IgnoreParenCasts();
186
187 if (const auto *B = dyn_cast<BinaryOperator>(E)) {
188 if (B->isAdditiveOp()) {
189 // p + 2
190 markCanNotBeConst(B->getLHS(), CanNotBeConst);
191 markCanNotBeConst(B->getRHS(), CanNotBeConst);
192 } else if (B->isAssignmentOp()) {
193 markCanNotBeConst(B->getLHS(), false);
194
195 // If LHS is not const then RHS can't be const.
196 const QualType T = B->getLHS()->getType();
197 if (T->isPointerType() && !T->getPointeeType().isConstQualified())
198 markCanNotBeConst(B->getRHS(), true);
199 }
200 } else if (const auto *C = dyn_cast<ConditionalOperator>(E)) {
201 markCanNotBeConst(C->getTrueExpr(), CanNotBeConst);
202 markCanNotBeConst(C->getFalseExpr(), CanNotBeConst);
203 } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
204 if (U->getOpcode() == UO_PreInc || U->getOpcode() == UO_PreDec ||
205 U->getOpcode() == UO_PostInc || U->getOpcode() == UO_PostDec) {
206 if (const auto *SubU =
207 dyn_cast<UnaryOperator>(U->getSubExpr()->IgnoreParenCasts()))
208 markCanNotBeConst(SubU->getSubExpr(), true);
209 markCanNotBeConst(U->getSubExpr(), CanNotBeConst);
210 } else if (U->getOpcode() == UO_Deref) {
211 if (!CanNotBeConst)
212 markCanNotBeConst(U->getSubExpr(), true);
213 } else {
214 markCanNotBeConst(U->getSubExpr(), CanNotBeConst);
215 }
216 } else if (const auto *A = dyn_cast<ArraySubscriptExpr>(E)) {
217 markCanNotBeConst(A->getBase(), true);
218 } else if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(E)) {
219 markCanNotBeConst(CLE->getInitializer(), true);
220 } else if (const auto *Constr = dyn_cast<CXXConstructExpr>(E)) {
221 for (const auto *Arg : Constr->arguments())
222 if (const auto *M = dyn_cast<MaterializeTemporaryExpr>(Arg))
223 markCanNotBeConst(cast<Expr>(M->getSubExpr()), CanNotBeConst);
224 } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
225 for (unsigned I = 0U; I < ILE->getNumInits(); ++I)
226 markCanNotBeConst(ILE->getInit(I), true);
227 } else if (CanNotBeConst) {
228 // Referencing parameter.
229 if (const auto *D = dyn_cast<DeclRefExpr>(E)) {
230 auto It = Parameters.find(dyn_cast<ParmVarDecl>(D->getDecl()));
231 if (It != Parameters.end())
232 It->second.CanBeConst = false;
233 }
234 }
235}
236
237} // namespace clang::tidy::readability
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override