clang-tools 22.0.0git
PreferMemberInitializerCheck.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 "../utils/LexerUtils.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Decl.h"
13#include "clang/ASTMatchers/ASTMatchFinder.h"
14#include "llvm/ADT/DenseMap.h"
15
16using namespace clang::ast_matchers;
17
19
20static bool isControlStatement(const Stmt *S) {
21 return isa<IfStmt, SwitchStmt, ForStmt, WhileStmt, DoStmt, ReturnStmt,
22 GotoStmt, CXXTryStmt, CXXThrowExpr>(S);
23}
24
25static bool isNoReturnCallStatement(const Stmt *S) {
26 const auto *Call = dyn_cast<CallExpr>(S);
27 if (!Call)
28 return false;
29
30 const FunctionDecl *Func = Call->getDirectCallee();
31 if (!Func)
32 return false;
33
34 return Func->isNoReturn();
35}
36
37namespace {
38
39AST_MATCHER_P(FieldDecl, indexNotLessThan, unsigned, Index) {
40 return Node.getFieldIndex() >= Index;
41}
42
43enum class AssignedLevel {
44 // Field is not assigned.
45 None,
46 // Field is assigned.
47 Default,
48 // Assignment of field has side effect:
49 // - assign to reference.
50 // FIXME: support other side effect.
51 HasSideEffect,
52 // Assignment of field has data dependence.
53 HasDependence,
54};
55
56} // namespace
57
58static bool canAdvanceAssignment(AssignedLevel Level) {
59 return Level == AssignedLevel::None || Level == AssignedLevel::Default;
60}
61
62// Checks if Field is initialised using a field that will be initialised after
63// it.
64// TODO: Probably should guard against function calls that could have side
65// effects or if they do reference another field that's initialized before
66// this field, but is modified before the assignment.
68 const FieldDecl *Field, const Expr *Init, const CXXConstructorDecl *Ctor,
69 llvm::DenseMap<const FieldDecl *, AssignedLevel> &AssignedFields) {
70 auto It = AssignedFields.try_emplace(Field, AssignedLevel::None).first;
71
72 if (!canAdvanceAssignment(It->second))
73 // fast path for already decided field.
74 return;
75
76 if (Field->getType().getCanonicalType()->isReferenceType()) {
77 // assign to reference type twice cannot be simplified to once.
78 It->second = AssignedLevel::HasSideEffect;
79 return;
80 }
81
82 auto MemberMatcher =
83 memberExpr(hasObjectExpression(cxxThisExpr()),
84 member(fieldDecl(indexNotLessThan(Field->getFieldIndex()))));
85 auto DeclMatcher = declRefExpr(
86 to(valueDecl(unless(parmVarDecl()), hasDeclContext(equalsNode(Ctor)))));
87 const bool HasDependence = !match(expr(anyOf(MemberMatcher, DeclMatcher,
88 hasDescendant(MemberMatcher),
89 hasDescendant(DeclMatcher))),
90 *Init, Field->getASTContext())
91 .empty();
92 if (HasDependence) {
93 It->second = AssignedLevel::HasDependence;
94 return;
95 }
96}
97
98namespace {
99
100struct AssignmentPair {
101 const FieldDecl *Field;
102 const Expr *Init;
103};
104
105} // namespace
106
107static std::optional<AssignmentPair>
108isAssignmentToMemberOf(const CXXRecordDecl *Rec, const Stmt *S,
109 const CXXConstructorDecl *Ctor) {
110 if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
111 if (BO->getOpcode() != BO_Assign)
112 return {};
113
114 const auto *ME = dyn_cast<MemberExpr>(BO->getLHS()->IgnoreParenImpCasts());
115 if (!ME)
116 return {};
117
118 const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
119 if (!Field)
120 return {};
121
122 if (!isa<CXXThisExpr>(ME->getBase()))
123 return {};
124 const Expr *Init = BO->getRHS()->IgnoreParenImpCasts();
125 return AssignmentPair{Field, Init};
126 }
127 if (const auto *COCE = dyn_cast<CXXOperatorCallExpr>(S)) {
128 if (COCE->getOperator() != OO_Equal)
129 return {};
130
131 const auto *ME =
132 dyn_cast<MemberExpr>(COCE->getArg(0)->IgnoreParenImpCasts());
133 if (!ME)
134 return {};
135
136 const auto *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
137 if (!Field)
138 return {};
139
140 if (!isa<CXXThisExpr>(ME->getBase()))
141 return {};
142 const Expr *Init = COCE->getArg(1)->IgnoreParenImpCasts();
143 return AssignmentPair{Field, Init};
144 }
145 return {};
146}
147
151
153 Finder->addMatcher(cxxConstructorDecl(hasBody(compoundStmt()),
154 unless(isInstantiated()),
155 unless(isDelegatingConstructor()))
156 .bind("ctor"),
157 this);
158}
159
161 const MatchFinder::MatchResult &Result) {
162 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
163 const auto *Body = cast<CompoundStmt>(Ctor->getBody());
164
165 const CXXRecordDecl *Class = Ctor->getParent();
166 bool FirstToCtorInits = true;
167
168 llvm::DenseMap<const FieldDecl *, AssignedLevel> AssignedFields{};
169
170 for (const CXXCtorInitializer *Init : Ctor->inits())
171 if (const FieldDecl *Field = Init->getMember())
172 updateAssignmentLevel(Field, Init->getInit(), Ctor, AssignedFields);
173
174 for (const Stmt *S : Body->body()) {
175 if (S->getBeginLoc().isMacroID()) {
176 const StringRef MacroName = Lexer::getImmediateMacroName(
177 S->getBeginLoc(), *Result.SourceManager, getLangOpts());
178 if (MacroName.contains_insensitive("assert"))
179 return;
180 }
181 if (isControlStatement(S))
182 return;
183
185 return;
186
187 if (const auto *CondOp = dyn_cast<ConditionalOperator>(S)) {
188 if (isNoReturnCallStatement(CondOp->getLHS()) ||
189 isNoReturnCallStatement(CondOp->getRHS()))
190 return;
191 }
192
193 std::optional<AssignmentPair> AssignmentToMember =
194 isAssignmentToMemberOf(Class, S, Ctor);
195 if (!AssignmentToMember)
196 continue;
197 const FieldDecl *Field = AssignmentToMember->Field;
198 // Skip if the field is inherited from a base class.
199 if (Field->getParent() != Class)
200 continue;
201 const Expr *InitValue = AssignmentToMember->Init;
202 updateAssignmentLevel(Field, InitValue, Ctor, AssignedFields);
203 if (!canAdvanceAssignment(AssignedFields[Field]))
204 continue;
205
206 StringRef InsertPrefix = "";
207 bool HasInitAlready = false;
208 SourceLocation InsertPos;
209 SourceRange ReplaceRange;
210 bool AddComma = false;
211 bool AddBrace = false;
212 bool InvalidFix = false;
213 const unsigned Index = Field->getFieldIndex();
214 const CXXCtorInitializer *LastInListInit = nullptr;
215 for (const CXXCtorInitializer *Init : Ctor->inits()) {
216 if (!Init->isWritten() || Init->isInClassMemberInitializer())
217 continue;
218 if (Init->getMember() == Field) {
219 HasInitAlready = true;
220 if (isa<ImplicitValueInitExpr>(Init->getInit()))
221 InsertPos = Init->getRParenLoc();
222 else {
223 ReplaceRange = Init->getInit()->getSourceRange();
224 AddBrace = isa<InitListExpr>(Init->getInit());
225 }
226 break;
227 }
228 if (Init->isMemberInitializer() &&
229 Index < Init->getMember()->getFieldIndex()) {
230 InsertPos = Init->getSourceLocation();
231 // There are initializers after the one we are inserting, so add a
232 // comma after this insertion in order to not break anything.
233 AddComma = true;
234 break;
235 }
236 LastInListInit = Init;
237 }
238 if (HasInitAlready) {
239 if (InsertPos.isValid())
240 InvalidFix |= InsertPos.isMacroID();
241 else
242 InvalidFix |= ReplaceRange.getBegin().isMacroID() ||
243 ReplaceRange.getEnd().isMacroID();
244 } else {
245 if (InsertPos.isInvalid()) {
246 if (LastInListInit) {
247 InsertPos =
248 Lexer::getLocForEndOfToken(LastInListInit->getRParenLoc(), 0,
249 *Result.SourceManager, getLangOpts());
250 // Inserting after the last constructor initializer, so we need a
251 // comma.
252 InsertPrefix = ", ";
253 } else {
254 InsertPos = Lexer::getLocForEndOfToken(
255 Ctor->getTypeSourceInfo()
256 ->getTypeLoc()
257 .getAs<clang::FunctionTypeLoc>()
258 .getLocalRangeEnd(),
259 0, *Result.SourceManager, getLangOpts());
260
261 // If this is first time in the loop, there are no initializers so
262 // `:` declares member initialization list. If this is a
263 // subsequent pass then we have already inserted a `:` so continue
264 // with a comma.
265 InsertPrefix = FirstToCtorInits ? " : " : ", ";
266 }
267 }
268 InvalidFix |= InsertPos.isMacroID();
269 }
270
271 SourceLocation SemiColonEnd;
273 S->getEndLoc(), *Result.SourceManager, getLangOpts()))
274 SemiColonEnd = NextToken->getEndLoc();
275 else
276 InvalidFix = true;
277
278 auto Diag = diag(S->getBeginLoc(), "%0 should be initialized in a member"
279 " initializer of the constructor")
280 << Field;
281 if (InvalidFix)
282 continue;
283 const StringRef NewInit = Lexer::getSourceText(
284 Result.SourceManager->getExpansionRange(InitValue->getSourceRange()),
285 *Result.SourceManager, getLangOpts());
286 if (HasInitAlready) {
287 if (InsertPos.isValid())
288 Diag << FixItHint::CreateInsertion(InsertPos, NewInit);
289 else if (AddBrace)
290 Diag << FixItHint::CreateReplacement(ReplaceRange,
291 ("{" + NewInit + "}").str());
292 else
293 Diag << FixItHint::CreateReplacement(ReplaceRange, NewInit);
294 } else {
295 const SmallString<128> Insertion({InsertPrefix, Field->getName(), "(",
296 NewInit, AddComma ? "), " : ")"});
297 Diag << FixItHint::CreateInsertion(InsertPos, Insertion,
298 FirstToCtorInits);
299 FirstToCtorInits = areDiagsSelfContained();
300 }
301 Diag << FixItHint::CreateRemoval(
302 CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd));
303 }
304}
305
306} // namespace clang::tidy::cppcoreguidelines
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static void updateAssignmentLevel(const FieldDecl *Field, const Expr *Init, const CXXConstructorDecl *Ctor, llvm::DenseMap< const FieldDecl *, AssignedLevel > &AssignedFields)
static bool canAdvanceAssignment(AssignedLevel Level)
static bool isNoReturnCallStatement(const Stmt *S)
static std::optional< AssignmentPair > isAssignmentToMemberOf(const CXXRecordDecl *Rec, const Stmt *S, const CXXConstructorDecl *Ctor)
std::optional< Token > findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, const LangOptions &LangOpts)
Definition LexerUtils.h:101