clang-tools 24.0.0git
ConstCorrectnessCheck.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
11#include "../utils/Matchers.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/ASTMatchers/ASTMatchFinder.h"
15#include "clang/ASTMatchers/ASTMatchers.h"
16#include <cassert>
17
18using namespace clang::ast_matchers;
19using namespace clang::ast_matchers::internal;
20
21namespace clang::tidy::misc {
22
23namespace {
24// FIXME: This matcher exists in some other code-review as well.
25// It should probably move to ASTMatchers.
26AST_MATCHER(VarDecl, isLocal) { return Node.isLocalVarDecl(); }
27// FIXME: The matcher 'hasName(Name)' asserts that its argument 'Name' is
28// nonempty. Perhaps remove that assertion and replace 'isUnnamed()' with
29// 'hasName("")'.
30AST_MATCHER(VarDecl, isUnnamed) {
31 return Node.getDeclName().isIdentifier() && Node.getName().empty();
32}
33AST_MATCHER_P(DeclStmt, containsAnyDeclaration,
34 ast_matchers::internal::Matcher<Decl>, InnerMatcher) {
35 return ast_matchers::internal::matchesFirstInPointerRange(
36 InnerMatcher, Node.decl_begin(), Node.decl_end(), Finder,
37 Builder) != Node.decl_end();
38}
39AST_MATCHER(ReferenceType, isSpelledAsLValue) {
40 return Node.isSpelledAsLValue();
41}
42AST_MATCHER(Type, isDependentType) { return Node.isDependentType(); }
43
44AST_MATCHER(TypeLoc, hasContainedAutoType) {
45 return !Node.getContainedAutoTypeLoc().isNull();
46}
47
48AST_MATCHER(FunctionDecl, isTemplate) {
49 return Node.getDescribedFunctionTemplate() != nullptr;
50}
51
52AST_MATCHER(FunctionDecl, isFunctionTemplateSpecialization) {
53 return Node.isFunctionTemplateSpecialization();
54}
55} // namespace
56
58 ClangTidyContext *Context)
59 : ClangTidyCheck(Name, Context),
60 AnalyzePointers(Options.get("AnalyzePointers", true)),
61 AnalyzeReferences(Options.get("AnalyzeReferences", true)),
62 AnalyzeValues(Options.get("AnalyzeValues", true)),
63 AnalyzeAutoVariables(Options.get("AnalyzeAutoVariables", true)),
64 AnalyzeLambdas(Options.get("AnalyzeLambdas", true)),
65 AnalyzeParameters(Options.get("AnalyzeParameters", true)),
66
67 WarnPointersAsPointers(Options.get("WarnPointersAsPointers", true)),
68 WarnPointersAsValues(Options.get("WarnPointersAsValues", false)),
69
70 TransformPointersAsPointers(
71 Options.get("TransformPointersAsPointers", true)),
72 TransformPointersAsValues(
73 Options.get("TransformPointersAsValues", false)),
74 TransformReferences(Options.get("TransformReferences", true)),
75 TransformValues(Options.get("TransformValues", true)),
76
77 AllowedTypes(
78 utils::options::parseStringList(Options.get("AllowedTypes", ""))) {
79 if (AnalyzeValues == false && AnalyzeReferences == false &&
80 AnalyzePointers == false)
81 this->configurationDiag(
82 "The check 'misc-const-correctness' will not "
83 "perform any analysis because 'AnalyzeValues', "
84 "'AnalyzeReferences' and 'AnalyzePointers' are false.");
85
86 if (AnalyzeLambdas && !AnalyzeAutoVariables)
87 this->configurationDiag("The check 'misc-const-correctness' will not "
88 "analyze lambdas because 'AnalyzeLambdas' has no "
89 "effect while 'AnalyzeAutoVariables' is false.");
90}
91
93 Options.store(Opts, "AnalyzePointers", AnalyzePointers);
94 Options.store(Opts, "AnalyzeReferences", AnalyzeReferences);
95 Options.store(Opts, "AnalyzeValues", AnalyzeValues);
96 Options.store(Opts, "AnalyzeAutoVariables", AnalyzeAutoVariables);
97 Options.store(Opts, "AnalyzeLambdas", AnalyzeLambdas);
98 Options.store(Opts, "AnalyzeParameters", AnalyzeParameters);
99
100 Options.store(Opts, "WarnPointersAsPointers", WarnPointersAsPointers);
101 Options.store(Opts, "WarnPointersAsValues", WarnPointersAsValues);
102
103 Options.store(Opts, "TransformPointersAsPointers",
104 TransformPointersAsPointers);
105 Options.store(Opts, "TransformPointersAsValues", TransformPointersAsValues);
106 Options.store(Opts, "TransformReferences", TransformReferences);
107 Options.store(Opts, "TransformValues", TransformValues);
108
109 Options.store(Opts, "AllowedTypes",
111}
112
114 const auto ConstType =
115 hasType(qualType(isConstQualified(),
116 // pointee check will check the constness of pointer
117 unless(pointerType())));
118
119 const auto ConstReference = hasType(references(isConstQualified()));
120 const auto RValueReference = hasType(
121 referenceType(anyOf(rValueReferenceType(), unless(isSpelledAsLValue()))));
122
123 const auto TemplateType = anyOf(
124 hasType(hasCanonicalType(templateTypeParmType())),
125 hasType(substTemplateTypeParmType()), hasType(isDependentType()),
126 // References to template types, their substitutions or typedefs to
127 // template types need to be considered as well.
128 hasType(referenceType(pointee(hasCanonicalType(templateTypeParmType())))),
129 hasType(referenceType(pointee(substTemplateTypeParmType()))));
130
131 const auto AllowedTypeDecl = namedDecl(anyOf(
132 matchers::matchesAnyListedRegexName(AllowedTypes), usingShadowDecl()));
133
134 const auto AllowedType = hasType(qualType(
135 anyOf(hasDeclaration(AllowedTypeDecl), references(AllowedTypeDecl),
136 pointerType(pointee(hasDeclaration(AllowedTypeDecl))))));
137
138 const auto AutoTemplateType = varDecl(
139 anyOf(hasType(autoType()), hasType(referenceType(pointee(autoType()))),
140 hasType(pointerType(pointee(autoType())))));
141
142 const auto FunctionPointerRef =
143 hasType(hasCanonicalType(referenceType(pointee(functionType()))));
144
145 const auto CommonExcludeTypes =
146 anyOf(ConstType, ConstReference, RValueReference, TemplateType,
147 FunctionPointerRef, hasType(cxxRecordDecl(isLambda())),
148 AutoTemplateType, isImplicit(), AllowedType);
149
150 // Match local variables which could be 'const' if not modified later.
151 // Example: `int i = 10` would match `int i`.
152 const auto LocalValDecl = varDecl(
153 isLocal(), hasInitializer(anything()),
154 unless(anyOf(ConstType, ConstReference, TemplateType,
155 hasInitializer(isInstantiationDependent()), RValueReference,
156 FunctionPointerRef, isImplicit(), AllowedType)),
157 AnalyzeLambdas
158 ? Matcher<VarDecl>(anything())
159 : Matcher<VarDecl>(unless(hasType(cxxRecordDecl(isLambda())))),
160 AnalyzeAutoVariables
161 ? Matcher<VarDecl>(anything())
162 : Matcher<VarDecl>(unless(hasTypeLoc(hasContainedAutoType()))));
163
164 // Match the function scope for which the analysis of all local variables
165 // shall be run.
166 const auto FunctionScope =
167 functionDecl(hasBody(stmt(forEachDescendant(
168 declStmt(containsAnyDeclaration(
169 LocalValDecl.bind("value")),
170 unless(has(decompositionDecl())))
171 .bind("decl-stmt")))
172 .bind("scope")))
173 .bind("function-decl");
174
175 Finder->addMatcher(FunctionScope, this);
176
177 if (AnalyzeParameters) {
178 const auto ParamMatcher =
179 parmVarDecl(unless(CommonExcludeTypes), unless(isUnnamed()),
180 anyOf(hasType(referenceType()), hasType(pointerType())))
181 .bind("value");
182
183 // Match function parameters which could be 'const' if not modified later.
184 // Example: `void foo(int* ptr)` would match `int* ptr`.
185 const auto FunctionWithParams =
186 functionDecl(
187 hasBody(stmt().bind("scope")), has(typeLoc(forEach(ParamMatcher))),
188 unless(cxxMethodDecl()), unless(isFunctionTemplateSpecialization()),
189 unless(isTemplate()))
190 .bind("function-decl");
191
192 Finder->addMatcher(FunctionWithParams, this);
193 }
194}
195
196static void addConstFixits(const DiagnosticBuilder &Diag,
197 const VarDecl *Variable,
198 const FunctionDecl *Function,
199 const ASTContext &Context, Qualifiers::TQ Qualifier,
202 // If this is a parameter, also add fixits for corresponding parameters in
203 // function declarations
204 if (const auto *ParamDecl = dyn_cast<ParmVarDecl>(Variable)) {
205 const unsigned ParamIdx = ParamDecl->getFunctionScopeIndex();
206 // Skip if all fix-its can not be applied properly due to 'using'/'typedef'
207 if (llvm::any_of(
208 Function->redecls(), [ParamIdx](const FunctionDecl *Redecl) {
209 const QualType Type = Redecl->getParamDecl(ParamIdx)->getType();
210 return Type->isTypedefNameType() || Type->getAs<UsingType>();
211 }))
212 return;
213
214 for (const FunctionDecl *Redecl : Function->redecls()) {
215 Diag << addQualifierToVarDecl(*Redecl->getParamDecl(ParamIdx), Context,
216 Qualifier, Target, Policy);
217 }
218 } else {
219 Diag << addQualifierToVarDecl(*Variable, Context, Qualifier, Target,
220 Policy);
221 }
222}
223
224namespace {
225
226/// Classify for a variable in what the Const-Check is interested.
227enum class VariableCategory { Value, Reference, Pointer };
228
229} // namespace
230
231void ConstCorrectnessCheck::check(const MatchFinder::MatchResult &Result) {
232 const auto *LocalScope = Result.Nodes.getNodeAs<Stmt>("scope");
233 const auto *Variable = Result.Nodes.getNodeAs<VarDecl>("value");
234 const auto *Function = Result.Nodes.getNodeAs<FunctionDecl>("function-decl");
235 const auto *VarDeclStmt = Result.Nodes.getNodeAs<DeclStmt>("decl-stmt");
236
237 assert(Variable && LocalScope && Function);
238
239 // It can not be guaranteed that the variable is declared isolated,
240 // therefore a transformation might effect the other variables as well and
241 // be incorrect. Parameters don't need this check - they receive values from
242 // callers.
243 const bool CanBeFixIt = isa<ParmVarDecl>(Variable) ||
244 (VarDeclStmt && VarDeclStmt->isSingleDecl());
245
246 /// If the variable was declared in a template it might be analyzed multiple
247 /// times. Only one of those instantiations shall emit a warning. NOTE: This
248 /// shall only deduplicate warnings for variables that are not instantiation
249 /// dependent. Variables like 'int x = 42;' in a template that can become
250 /// const emit multiple warnings otherwise.
251 bool IsNormalVariableInTemplate = Function->isTemplateInstantiation();
252 if (IsNormalVariableInTemplate &&
253 TemplateDiagnosticsCache.contains(Variable->getBeginLoc()))
254 return;
255
256 VariableCategory VC = VariableCategory::Value;
257 const QualType VT = Variable->getType();
258 if (VT->isReferenceType())
259 VC = VariableCategory::Reference;
260 else if (VT->isPointerType())
261 VC = VariableCategory::Pointer;
262 else if (const auto *ArrayT = dyn_cast<ArrayType>(VT);
263 ArrayT && ArrayT->getElementType()->isPointerType())
264 VC = VariableCategory::Pointer;
265
266 const auto CheckValue = [&]() {
267 // Offload const-analysis to utility function.
268 if (isMutated(Variable, LocalScope, Function, Result.Context))
269 return;
270
271 const auto Diag = diag(Variable->getBeginLoc(),
272 "variable %0 of type %1 can be declared 'const'")
273 << Variable << VT;
274 if (IsNormalVariableInTemplate)
275 TemplateDiagnosticsCache.insert(Variable->getBeginLoc());
276 if (!CanBeFixIt)
277 return;
278 using namespace utils::fixit;
279
280 if (VC == VariableCategory::Value && TransformValues) {
281 addConstFixits(Diag, Variable, Function, *Result.Context,
282 Qualifiers::Const, QualifierTarget::Value,
283 QualifierPolicy::Right);
284 // FIXME: Add '{}' for default initialization if no user-defined default
285 // constructor exists and there is no initializer.
286 return;
287 }
288
289 if (VC == VariableCategory::Reference && TransformReferences) {
290 addConstFixits(Diag, Variable, Function, *Result.Context,
291 Qualifiers::Const, QualifierTarget::Value,
292 QualifierPolicy::Right);
293 return;
294 }
295
296 if (VC == VariableCategory::Pointer && TransformPointersAsValues) {
297 addConstFixits(Diag, Variable, Function, *Result.Context,
298 Qualifiers::Const, QualifierTarget::Value,
299 QualifierPolicy::Right);
300 return;
301 }
302 };
303
304 const auto CheckPointee = [&]() {
305 assert(VC == VariableCategory::Pointer);
306 registerScope(LocalScope, Result.Context);
307 if (ScopesCache[LocalScope]->isPointeeMutated(Variable))
308 return;
309 const auto Diag =
310 diag(Variable->getBeginLoc(),
311 "pointee of variable %0 of type %1 can be declared 'const'")
312 << Variable << VT;
313 if (IsNormalVariableInTemplate)
314 TemplateDiagnosticsCache.insert(Variable->getBeginLoc());
315 if (!CanBeFixIt)
316 return;
317 using namespace utils::fixit;
318 if (TransformPointersAsPointers) {
319 addConstFixits(Diag, Variable, Function, *Result.Context,
320 Qualifiers::Const, QualifierTarget::Pointee,
321 QualifierPolicy::Right);
322 }
323 };
324
325 // Each variable can only be in one category: Value, Pointer, Reference.
326 // Analysis can be controlled for every category.
327 if (VC == VariableCategory::Value && AnalyzeValues) {
328 CheckValue();
329 return;
330 }
331 if (VC == VariableCategory::Reference && AnalyzeReferences) {
332 if (VT->getPointeeType()->isPointerType() && !WarnPointersAsValues)
333 return;
334 CheckValue();
335 return;
336 }
337 if (VC == VariableCategory::Pointer && AnalyzePointers) {
338 if (WarnPointersAsValues && !VT.isConstQualified())
339 CheckValue();
340 if (WarnPointersAsPointers) {
341 if (const auto *PT = dyn_cast<PointerType>(VT);
342 PT && !PT->getPointeeType().isConstQualified() &&
343 !PT->getPointeeType()->isFunctionType())
344 CheckPointee();
345
346 if (const auto *AT = dyn_cast<ArrayType>(VT)) {
347 assert(AT->getElementType()->isPointerType());
348 if (!AT->getElementType()->getPointeeType().isConstQualified())
349 CheckPointee();
350 }
351 }
352 return;
353 }
354}
355
356void ConstCorrectnessCheck::registerScope(const Stmt *LocalScope,
357 ASTContext *Context) {
358 auto &Analyzer = ScopesCache[LocalScope];
359 if (!Analyzer)
360 Analyzer = std::make_unique<ExprMutationAnalyzer>(*LocalScope, *Context);
361}
362
363bool ConstCorrectnessCheck::isMutated(const VarDecl *Variable,
364 const Stmt *Scope,
365 const FunctionDecl *Func,
366 ASTContext *Context) {
367 if (const auto *Param = dyn_cast<ParmVarDecl>(Variable)) {
368 return FunctionParmMutationAnalyzer::getFunctionParmMutationAnalyzer(
369 *Func, *Context, ParamMutationAnalyzerMemoized)
370 ->isMutated(Param);
371 }
372
373 registerScope(Scope, Context);
374 return ScopesCache[Scope]->isMutated(Variable);
375}
376
377} // namespace clang::tidy::misc
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ConstCorrectnessCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedRegexName(llvm::ArrayRef< StringRef > NameList)
static void addConstFixits(const DiagnosticBuilder &Diag, const VarDecl *Variable, const FunctionDecl *Function, const ASTContext &Context, Qualifiers::TQ Qualifier, utils::fixit::QualifierTarget Target, utils::fixit::QualifierPolicy Policy)
QualifierTarget
This enum defines which entity is the target for adding the qualifier. This makes only a difference f...
QualifierPolicy
This enum defines where the qualifier shall be preferably added.
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap