clang-tools 23.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 if (ArrayT->getElementType()->isPointerType())
264 VC = VariableCategory::Pointer;
265 }
266
267 auto CheckValue = [&]() {
268 // Offload const-analysis to utility function.
269 if (isMutated(Variable, LocalScope, Function, Result.Context))
270 return;
271
272 auto Diag = diag(Variable->getBeginLoc(),
273 "variable %0 of type %1 can be declared 'const'")
274 << Variable << VT;
275 if (IsNormalVariableInTemplate)
276 TemplateDiagnosticsCache.insert(Variable->getBeginLoc());
277 if (!CanBeFixIt)
278 return;
279 using namespace utils::fixit;
280
281 if (VC == VariableCategory::Value && TransformValues) {
282 addConstFixits(Diag, Variable, Function, *Result.Context,
283 Qualifiers::Const, QualifierTarget::Value,
284 QualifierPolicy::Right);
285 // FIXME: Add '{}' for default initialization if no user-defined default
286 // constructor exists and there is no initializer.
287 return;
288 }
289
290 if (VC == VariableCategory::Reference && TransformReferences) {
291 addConstFixits(Diag, Variable, Function, *Result.Context,
292 Qualifiers::Const, QualifierTarget::Value,
293 QualifierPolicy::Right);
294 return;
295 }
296
297 if (VC == VariableCategory::Pointer && TransformPointersAsValues) {
298 addConstFixits(Diag, Variable, Function, *Result.Context,
299 Qualifiers::Const, QualifierTarget::Value,
300 QualifierPolicy::Right);
301 return;
302 }
303 };
304
305 auto CheckPointee = [&]() {
306 assert(VC == VariableCategory::Pointer);
307 registerScope(LocalScope, Result.Context);
308 if (ScopesCache[LocalScope]->isPointeeMutated(Variable))
309 return;
310 auto Diag =
311 diag(Variable->getBeginLoc(),
312 "pointee of variable %0 of type %1 can be declared 'const'")
313 << Variable << VT;
314 if (IsNormalVariableInTemplate)
315 TemplateDiagnosticsCache.insert(Variable->getBeginLoc());
316 if (!CanBeFixIt)
317 return;
318 using namespace utils::fixit;
319 if (TransformPointersAsPointers) {
320 addConstFixits(Diag, Variable, Function, *Result.Context,
321 Qualifiers::Const, QualifierTarget::Pointee,
322 QualifierPolicy::Right);
323 }
324 };
325
326 // Each variable can only be in one category: Value, Pointer, Reference.
327 // Analysis can be controlled for every category.
328 if (VC == VariableCategory::Value && AnalyzeValues) {
329 CheckValue();
330 return;
331 }
332 if (VC == VariableCategory::Reference && AnalyzeReferences) {
333 if (VT->getPointeeType()->isPointerType() && !WarnPointersAsValues)
334 return;
335 CheckValue();
336 return;
337 }
338 if (VC == VariableCategory::Pointer && AnalyzePointers) {
339 if (WarnPointersAsValues && !VT.isConstQualified())
340 CheckValue();
341 if (WarnPointersAsPointers) {
342 if (const auto *PT = dyn_cast<PointerType>(VT)) {
343 if (!PT->getPointeeType().isConstQualified() &&
344 !PT->getPointeeType()->isFunctionType())
345 CheckPointee();
346 }
347 if (const auto *AT = dyn_cast<ArrayType>(VT)) {
348 assert(AT->getElementType()->isPointerType());
349 if (!AT->getElementType()->getPointeeType().isConstQualified())
350 CheckPointee();
351 }
352 }
353 return;
354 }
355}
356
357void ConstCorrectnessCheck::registerScope(const Stmt *LocalScope,
358 ASTContext *Context) {
359 auto &Analyzer = ScopesCache[LocalScope];
360 if (!Analyzer)
361 Analyzer = std::make_unique<ExprMutationAnalyzer>(*LocalScope, *Context);
362}
363
364bool ConstCorrectnessCheck::isMutated(const VarDecl *Variable,
365 const Stmt *Scope,
366 const FunctionDecl *Func,
367 ASTContext *Context) {
368 if (const auto *Param = dyn_cast<ParmVarDecl>(Variable)) {
369 return FunctionParmMutationAnalyzer::getFunctionParmMutationAnalyzer(
370 *Func, *Context, ParamMutationAnalyzerMemoized)
371 ->isMutated(Param);
372 }
373
374 registerScope(Scope, Context);
375 return ScopesCache[Scope]->isMutated(Variable);
376}
377
378} // 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