clang-tools 22.0.0git
LoopConvertCheck.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
9#include "LoopConvertCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Basic/LLVM.h"
13#include "clang/Basic/LangOptions.h"
14#include "clang/Basic/SourceLocation.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/Support/raw_ostream.h"
22#include <cassert>
23#include <cstring>
24#include <optional>
25#include <utility>
26
27using namespace clang::ast_matchers;
28using namespace llvm;
29
30namespace clang::tidy {
31
32template <> struct OptionEnumMapping<modernize::Confidence::Level> {
33 static llvm::ArrayRef<std::pair<modernize::Confidence::Level, StringRef>>
35 static constexpr std::pair<modernize::Confidence::Level, StringRef>
36 Mapping[] = {{modernize::Confidence::CL_Reasonable, "reasonable"},
39 return {Mapping};
40 }
41};
42
43template <> struct OptionEnumMapping<modernize::VariableNamer::NamingStyle> {
44 static llvm::ArrayRef<
45 std::pair<modernize::VariableNamer::NamingStyle, StringRef>>
47 static constexpr std::pair<modernize::VariableNamer::NamingStyle, StringRef>
48 Mapping[] = {{modernize::VariableNamer::NS_CamelCase, "CamelCase"},
52 return {Mapping};
53 }
54};
55
56namespace modernize {
57
58static constexpr char LoopNameArray[] = "forLoopArray";
59static constexpr char LoopNameIterator[] = "forLoopIterator";
60static constexpr char LoopNameReverseIterator[] = "forLoopReverseIterator";
61static constexpr char LoopNamePseudoArray[] = "forLoopPseudoArray";
62static constexpr char ConditionBoundName[] = "conditionBound";
63static constexpr char InitVarName[] = "initVar";
64static constexpr char BeginCallName[] = "beginCall";
65static constexpr char EndCallName[] = "endCall";
66static constexpr char EndVarName[] = "endVar";
67static constexpr char DerefByValueResultName[] = "derefByValueResult";
68static constexpr char DerefByRefResultName[] = "derefByRefResult";
69static const llvm::StringSet<> MemberNames{"begin", "cbegin", "rbegin",
70 "crbegin", "end", "cend",
71 "rend", "crend", "size"};
72static const llvm::StringSet<> ADLNames{"begin", "cbegin", "rbegin",
73 "crbegin", "end", "cend",
74 "rend", "crend", "size"};
75static const llvm::StringSet<> StdNames{
76 "std::begin", "std::cbegin", "std::rbegin", "std::crbegin", "std::end",
77 "std::cend", "std::rend", "std::crend", "std::size"};
78
79static StatementMatcher integerComparisonMatcher() {
80 return expr(ignoringParenImpCasts(
81 declRefExpr(to(varDecl(equalsBoundNode(InitVarName))))));
82}
83
84static DeclarationMatcher initToZeroMatcher() {
85 return varDecl(
86 hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0)))))
87 .bind(InitVarName);
88}
89
90static StatementMatcher incrementVarMatcher() {
91 return declRefExpr(to(varDecl(equalsBoundNode(InitVarName))));
92}
93
94static StatementMatcher
95arrayConditionMatcher(const internal::Matcher<Expr> &LimitExpr) {
96 return binaryOperator(
97 anyOf(allOf(hasOperatorName("<"), hasLHS(integerComparisonMatcher()),
98 hasRHS(LimitExpr)),
99 allOf(hasOperatorName(">"), hasLHS(LimitExpr),
100 hasRHS(integerComparisonMatcher())),
101 allOf(hasOperatorName("!="),
102 hasOperands(integerComparisonMatcher(), LimitExpr))));
103}
104
105/// The matcher for loops over arrays.
106/// \code
107/// for (int i = 0; i < 3 + 2; ++i) { ... }
108/// \endcode
109/// The following string identifiers are bound to these parts of the AST:
110/// ConditionBoundName: '3 + 2' (as an Expr)
111/// InitVarName: 'i' (as a VarDecl)
112/// LoopName: The entire for loop (as a ForStmt)
113///
114/// Client code will need to make sure that:
115/// - The index variable is only used as an array index.
116/// - All arrays indexed by the loop are the same.
117static StatementMatcher makeArrayLoopMatcher() {
118 const StatementMatcher ArrayBoundMatcher =
119 expr(hasType(isInteger())).bind(ConditionBoundName);
120
121 return forStmt(unless(isInTemplateInstantiation()),
122 hasLoopInit(declStmt(hasSingleDecl(initToZeroMatcher()))),
123 hasCondition(arrayConditionMatcher(ArrayBoundMatcher)),
124 hasIncrement(
125 unaryOperator(hasOperatorName("++"),
126 hasUnaryOperand(incrementVarMatcher()))))
127 .bind(LoopNameArray);
128}
129
130/// The matcher used for iterator-based for loops.
131///
132/// This matcher is more flexible than array-based loops. It will match
133/// catch loops of the following textual forms (regardless of whether the
134/// iterator type is actually a pointer type or a class type):
135///
136/// \code
137/// for (containerType::iterator it = container.begin(),
138/// e = createIterator(); it != e; ++it) { ... }
139/// for (containerType::iterator it = container.begin();
140/// it != anotherContainer.end(); ++it) { ... }
141/// for (containerType::iterator it = begin(container),
142/// e = end(container); it != e; ++it) { ... }
143/// for (containerType::iterator it = std::begin(container),
144/// e = std::end(container); it != e; ++it) { ... }
145/// \endcode
146/// The following string identifiers are bound to the parts of the AST:
147/// InitVarName: 'it' (as a VarDecl)
148/// LoopName: The entire for loop (as a ForStmt)
149/// In the first example only:
150/// EndVarName: 'e' (as a VarDecl)
151/// In the second example only:
152/// EndCallName: 'container.end()' (as a CXXMemberCallExpr)
153/// In the third/fourth examples:
154/// 'end(container)' or 'std::end(container)' (as a CallExpr)
155///
156/// Client code will need to make sure that:
157/// - The two containers on which 'begin' and 'end' are called are the same.
158static StatementMatcher makeIteratorLoopMatcher(bool IsReverse) {
159 auto BeginNameMatcher = IsReverse ? hasAnyName("rbegin", "crbegin")
160 : hasAnyName("begin", "cbegin");
161 auto BeginNameMatcherStd = IsReverse
162 ? hasAnyName("::std::rbegin", "::std::crbegin")
163 : hasAnyName("::std::begin", "::std::cbegin");
164
165 auto EndNameMatcher =
166 IsReverse ? hasAnyName("rend", "crend") : hasAnyName("end", "cend");
167 auto EndNameMatcherStd = IsReverse ? hasAnyName("::std::rend", "::std::crend")
168 : hasAnyName("::std::end", "::std::cend");
169
170 const StatementMatcher BeginCallMatcher =
171 expr(anyOf(cxxMemberCallExpr(argumentCountIs(0),
172 callee(cxxMethodDecl(BeginNameMatcher))),
173 callExpr(argumentCountIs(1),
174 callee(functionDecl(BeginNameMatcher)), usesADL()),
175 callExpr(argumentCountIs(1),
176 callee(functionDecl(BeginNameMatcherStd)))))
177 .bind(BeginCallName);
178
179 const DeclarationMatcher InitDeclMatcher =
180 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
181 materializeTemporaryExpr(
182 ignoringParenImpCasts(BeginCallMatcher)),
183 hasDescendant(BeginCallMatcher))))
184 .bind(InitVarName);
185
186 const DeclarationMatcher EndDeclMatcher =
187 varDecl(hasInitializer(anything())).bind(EndVarName);
188
189 const StatementMatcher EndCallMatcher = expr(anyOf(
190 cxxMemberCallExpr(argumentCountIs(0),
191 callee(cxxMethodDecl(EndNameMatcher))),
192 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcher)),
193 usesADL()),
194 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcherStd)))));
195
196 const StatementMatcher IteratorBoundMatcher =
197 expr(anyOf(ignoringParenImpCasts(
198 declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))),
199 ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)),
200 materializeTemporaryExpr(ignoringParenImpCasts(
201 expr(EndCallMatcher).bind(EndCallName)))));
202
203 const StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
204 declRefExpr(to(varDecl(equalsBoundNode(InitVarName))))));
205
206 // This matcher tests that a declaration is a CXXRecordDecl that has an
207 // overloaded operator*(). If the operator*() returns by value instead of by
208 // reference then the return type is tagged with DerefByValueResultName.
209 const internal::Matcher<VarDecl> TestDerefReturnsByValue =
210 hasType(hasUnqualifiedDesugaredType(
211 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl(
212 hasOverloadedOperatorName("*"),
213 anyOf(
214 // Tag the return type if it's by value.
215 returns(qualType(unless(hasCanonicalType(referenceType())))
217 returns(
218 // Skip loops where the iterator's operator* returns an
219 // rvalue reference. This is just weird.
220 qualType(unless(hasCanonicalType(rValueReferenceType())))
221 .bind(DerefByRefResultName))))))))));
222
223 return forStmt(
224 unless(isInTemplateInstantiation()),
225 hasLoopInit(anyOf(declStmt(declCountIs(2),
226 containsDeclaration(0, InitDeclMatcher),
227 containsDeclaration(1, EndDeclMatcher)),
228 declStmt(hasSingleDecl(InitDeclMatcher)))),
229 hasCondition(ignoringImplicit(binaryOperation(
230 hasOperatorName("!="), hasOperands(IteratorComparisonMatcher,
231 IteratorBoundMatcher)))),
232 hasIncrement(anyOf(
233 unaryOperator(hasOperatorName("++"),
234 hasUnaryOperand(declRefExpr(
235 to(varDecl(equalsBoundNode(InitVarName)))))),
236 cxxOperatorCallExpr(
237 hasOverloadedOperatorName("++"),
238 hasArgument(0, declRefExpr(to(
239 varDecl(equalsBoundNode(InitVarName),
240 TestDerefReturnsByValue))))))))
241 .bind(IsReverse ? LoopNameReverseIterator : LoopNameIterator);
242}
243
244/// The matcher used for array-like containers (pseudoarrays).
245///
246/// This matcher is more flexible than array-based loops. It will match
247/// loops of the following textual forms (regardless of whether the
248/// iterator type is actually a pointer type or a class type):
249///
250/// \code
251/// for (int i = 0, j = container.size(); i < j; ++i) { ... }
252/// for (int i = 0; i < container.size(); ++i) { ... }
253/// for (int i = 0; i < size(container); ++i) { ... }
254/// \endcode
255/// The following string identifiers are bound to the parts of the AST:
256/// InitVarName: 'i' (as a VarDecl)
257/// LoopName: The entire for loop (as a ForStmt)
258/// In the first example only:
259/// EndVarName: 'j' (as a VarDecl)
260/// In the second example only:
261/// EndCallName: 'container.size()' (as a CXXMemberCallExpr) or
262/// 'size(container)' (as a CallExpr)
263///
264/// Client code will need to make sure that:
265/// - The containers on which 'size()' is called is the container indexed.
266/// - The index variable is only used in overloaded operator[] or
267/// container.at().
268/// - The container's iterators would not be invalidated during the loop.
269static StatementMatcher makePseudoArrayLoopMatcher() {
270 // Test that the incoming type has a record declaration that has methods
271 // called 'begin' and 'end'. If the incoming type is const, then make sure
272 // these methods are also marked const.
273 //
274 // FIXME: To be completely thorough this matcher should also ensure the
275 // return type of begin/end is an iterator that dereferences to the same as
276 // what operator[] or at() returns. Such a test isn't likely to fail except
277 // for pathological cases.
278 //
279 // FIXME: Also, a record doesn't necessarily need begin() and end(). Free
280 // functions called begin() and end() taking the container as an argument
281 // are also allowed.
282 const TypeMatcher RecordWithBeginEnd = qualType(anyOf(
283 qualType(isConstQualified(),
284 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
285 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
286 hasMethod(cxxMethodDecl(hasName("begin"), isConst())),
287 hasMethod(cxxMethodDecl(hasName("end"),
288 isConst())))))) // hasDeclaration
289 ))), // qualType
290 qualType(unless(isConstQualified()),
291 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
292 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
293 hasMethod(hasName("begin")),
294 hasMethod(hasName("end"))))))))) // qualType
295 ));
296
297 const StatementMatcher SizeCallMatcher = expr(anyOf(
298 cxxMemberCallExpr(argumentCountIs(0),
299 callee(cxxMethodDecl(hasAnyName("size", "length"))),
300 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
301 hasType(RecordWithBeginEnd)))),
302 callExpr(argumentCountIs(1), callee(functionDecl(hasName("size"))),
303 usesADL()),
304 callExpr(argumentCountIs(1),
305 callee(functionDecl(hasName("::std::size"))))));
306
307 StatementMatcher EndInitMatcher =
308 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(EndCallName)),
309 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
310 expr(SizeCallMatcher).bind(EndCallName))))));
311
312 const DeclarationMatcher EndDeclMatcher =
313 varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName);
314
315 const StatementMatcher IndexBoundMatcher =
316 expr(anyOf(ignoringParenImpCasts(
317 declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))),
318 EndInitMatcher));
319
320 return forStmt(unless(isInTemplateInstantiation()),
321 hasLoopInit(
322 anyOf(declStmt(declCountIs(2),
323 containsDeclaration(0, initToZeroMatcher()),
324 containsDeclaration(1, EndDeclMatcher)),
325 declStmt(hasSingleDecl(initToZeroMatcher())))),
326 hasCondition(arrayConditionMatcher(IndexBoundMatcher)),
327 hasIncrement(
328 unaryOperator(hasOperatorName("++"),
329 hasUnaryOperand(incrementVarMatcher()))))
330 .bind(LoopNamePseudoArray);
331}
332
333namespace {
334
335enum class IteratorCallKind {
336 ICK_Member,
337 ICK_ADL,
338 ICK_Std,
339};
340
341struct ContainerCall {
342 const Expr *Container;
343 StringRef Name;
344 bool IsArrow;
345 IteratorCallKind CallKind;
346};
347
348} // namespace
349
350// Find the Expr likely initializing an iterator.
351//
352// Call is either a CXXMemberCallExpr ('c.begin()') or CallExpr of a free
353// function with the first argument as a container ('begin(c)'), or nullptr.
354// Returns at a 3-tuple with the container expr, function name (begin/end/etc),
355// and whether the call is made through an arrow (->) for CXXMemberCallExprs.
356// The returned Expr* is nullptr if any of the assumptions are not met.
357// static std::tuple<const Expr *, StringRef, bool, IteratorCallKind>
358static std::optional<ContainerCall> getContainerExpr(const Expr *Call) {
359 const Expr *Dug = digThroughConstructorsConversions(Call);
360
361 IteratorCallKind CallKind = IteratorCallKind::ICK_Member;
362
363 if (const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
364 CallKind = IteratorCallKind::ICK_Member;
365 if (const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
366 if (Member->getMemberDecl() == nullptr ||
367 !MemberNames.contains(Member->getMemberDecl()->getName()))
368 return std::nullopt;
369 return ContainerCall{TheCall->getImplicitObjectArgument(),
370 Member->getMemberDecl()->getName(),
371 Member->isArrow(), CallKind};
372 }
373 if (TheCall->getDirectCallee() == nullptr ||
374 !MemberNames.contains(TheCall->getDirectCallee()->getName()))
375 return std::nullopt;
376 return ContainerCall{TheCall->getArg(0),
377 TheCall->getDirectCallee()->getName(), false,
378 CallKind};
379 }
380 if (const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
381 if (TheCall->getNumArgs() != 1)
382 return std::nullopt;
383
384 if (TheCall->usesADL()) {
385 if (TheCall->getDirectCallee() == nullptr ||
386 !ADLNames.contains(TheCall->getDirectCallee()->getName()))
387 return std::nullopt;
388 CallKind = IteratorCallKind::ICK_ADL;
389 } else {
390 if (!StdNames.contains(
391 TheCall->getDirectCallee()->getQualifiedNameAsString()))
392 return std::nullopt;
393 CallKind = IteratorCallKind::ICK_Std;
394 }
395
396 if (TheCall->getDirectCallee() == nullptr)
397 return std::nullopt;
398
399 return ContainerCall{TheCall->getArg(0),
400 TheCall->getDirectCallee()->getName(), false,
401 CallKind};
402 }
403 return std::nullopt;
404}
405
406/// Determine whether Init appears to be an initializing an iterator.
407///
408/// If it is, returns the object whose begin() or end() method is called, and
409/// the output parameter isArrow is set to indicate whether the initialization
410/// is called via . or ->.
411static std::pair<const Expr *, IteratorCallKind>
412getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow,
413 bool IsReverse) {
414 // FIXME: Maybe allow declaration/initialization outside of the for loop.
415
416 std::optional<ContainerCall> Call = getContainerExpr(Init);
417 if (!Call)
418 return {};
419
420 *IsArrow = Call->IsArrow;
421 if (!Call->Name.consume_back(IsBegin ? "begin" : "end"))
422 return {};
423 if (IsReverse && !Call->Name.consume_back("r"))
424 return {};
425 if (!Call->Name.empty() && Call->Name != "c")
426 return {};
427 return {Call->Container, Call->CallKind};
428}
429
430/// Determines the container whose begin() and end() functions are called
431/// for an iterator-based loop.
432///
433/// BeginExpr must be a member call to a function named "begin()", and EndExpr
434/// must be a member.
435static const Expr *findContainer(ASTContext *Context, const Expr *BeginExpr,
436 const Expr *EndExpr,
437 bool *ContainerNeedsDereference,
438 bool IsReverse) {
439 // Now that we know the loop variable and test expression, make sure they are
440 // valid.
441 bool BeginIsArrow = false;
442 bool EndIsArrow = false;
443 auto [BeginContainerExpr, BeginCallKind] = getContainerFromBeginEndCall(
444 BeginExpr, /*IsBegin=*/true, &BeginIsArrow, IsReverse);
445 if (!BeginContainerExpr)
446 return nullptr;
447
448 auto [EndContainerExpr, EndCallKind] = getContainerFromBeginEndCall(
449 EndExpr, /*IsBegin=*/false, &EndIsArrow, IsReverse);
450 if (BeginCallKind != EndCallKind)
451 return nullptr;
452
453 // Disallow loops that try evil things like this (note the dot and arrow):
454 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { }
455 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
456 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
457 return nullptr;
458
459 *ContainerNeedsDereference = BeginIsArrow;
460 return BeginContainerExpr;
461}
462
463/// Obtain the original source code text from a SourceRange.
464static StringRef getStringFromRange(SourceManager &SourceMgr,
465 const LangOptions &LangOpts,
466 SourceRange Range) {
467 if (SourceMgr.getFileID(Range.getBegin()) !=
468 SourceMgr.getFileID(Range.getEnd())) {
469 return {}; // Empty string.
470 }
471
472 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr,
473 LangOpts);
474}
475
476/// If the given expression is actually a DeclRefExpr or a MemberExpr,
477/// find and return the underlying ValueDecl; otherwise, return NULL.
478static const ValueDecl *getReferencedVariable(const Expr *E) {
479 if (const DeclRefExpr *DRE = getDeclRef(E))
480 return dyn_cast<VarDecl>(DRE->getDecl());
481 if (const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
482 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
483 return nullptr;
484}
485
486/// Returns true when the given expression is a member expression
487/// whose base is `this` (implicitly or not).
488static bool isDirectMemberExpr(const Expr *E) {
489 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
490 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
491 return false;
492}
493
494/// Given an expression that represents an usage of an element from the
495/// container that we are iterating over, returns false when it can be
496/// guaranteed this element cannot be modified as a result of this usage.
497static bool canBeModified(ASTContext *Context, const Expr *E) {
498 if (E->getType().isConstQualified())
499 return false;
500 auto Parents = Context->getParents(*E);
501 if (Parents.size() != 1)
502 return true;
503 if (const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
504 if ((Cast->getCastKind() == CK_NoOp &&
505 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
506 (Cast->getCastKind() == CK_LValueToRValue &&
507 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
508 return false;
509 }
510 // FIXME: Make this function more generic.
511 return true;
512}
513
514/// Returns true when it can be guaranteed that the elements of the
515/// container are not being modified.
516static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages) {
517 return llvm::none_of(Usages, [&Context](const Usage &U) {
518 // Lambda captures are just redeclarations (VarDecl) of the same variable,
519 // not expressions. If we want to know if a variable that is captured by
520 // reference can be modified in an usage inside the lambda's body, we need
521 // to find the expression corresponding to that particular usage, later in
522 // this loop.
523 return U.Kind != Usage::UK_CaptureByCopy &&
525 canBeModified(Context, U.Expression);
526 });
527}
528
529/// Returns true if the elements of the container are never accessed
530/// by reference.
531static bool usagesReturnRValues(const UsageResult &Usages) {
532 return llvm::all_of(Usages, [](const Usage &U) {
533 return !U.Expression || U.Expression->isPRValue();
534 });
535}
536
537/// Returns true if the container is const-qualified.
538static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) {
539 if (const auto *VDec = getReferencedVariable(ContainerExpr)) {
540 QualType CType = VDec->getType();
541 if (Dereference) {
542 if (!CType->isPointerType())
543 return false;
544 CType = CType->getPointeeType();
545 }
546 // If VDec is a reference to a container, Dereference is false,
547 // but we still need to check the const-ness of the underlying container
548 // type.
549 CType = CType.getNonReferenceType();
550 return CType.isConstQualified();
551 }
552 return false;
553}
554
556 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo),
557 MaxCopySize(Options.get("MaxCopySize", 16ULL)),
558 MinConfidence(Options.get("MinConfidence", Confidence::CL_Reasonable)),
559 NamingStyle(Options.get("NamingStyle", VariableNamer::NS_CamelCase)),
560 Inserter(Options.getLocalOrGlobal("IncludeStyle",
561 utils::IncludeSorter::IS_LLVM),
562 areDiagsSelfContained()),
563 UseCxx20IfAvailable(Options.get("UseCxx20ReverseRanges", true)),
564 ReverseFunction(Options.get("MakeReverseRangeFunction", "")),
565 ReverseHeader(Options.get("MakeReverseRangeHeader", "")) {
566 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
567 configurationDiag(
568 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
569 "'MakeReverseRangeFunction' is not, disabling reverse loop "
570 "transformation");
571 UseReverseRanges = false;
572 } else if (ReverseFunction.empty()) {
573 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
574 } else {
575 UseReverseRanges = true;
576 }
577}
578
580 Options.store(Opts, "MaxCopySize", MaxCopySize);
581 Options.store(Opts, "MinConfidence", MinConfidence);
582 Options.store(Opts, "NamingStyle", NamingStyle);
583 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
584 Options.store(Opts, "UseCxx20ReverseRanges", UseCxx20IfAvailable);
585 Options.store(Opts, "MakeReverseRangeFunction", ReverseFunction);
586 Options.store(Opts, "MakeReverseRangeHeader", ReverseHeader);
587}
588
589void LoopConvertCheck::registerPPCallbacks(const SourceManager &SM,
590 Preprocessor *PP,
591 Preprocessor *ModuleExpanderPP) {
592 Inserter.registerPreprocessor(PP);
593}
594
595void LoopConvertCheck::registerMatchers(MatchFinder *Finder) {
596 Finder->addMatcher(traverse(TK_AsIs, makeArrayLoopMatcher()), this);
597 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(false)), this);
598 Finder->addMatcher(traverse(TK_AsIs, makePseudoArrayLoopMatcher()), this);
599 if (UseReverseRanges)
600 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(true)), this);
601}
602
603/// Given the range of a single declaration, such as:
604/// \code
605/// unsigned &ThisIsADeclarationThatCanSpanSeveralLinesOfCode =
606/// InitializationValues[I];
607/// next_instruction;
608/// \endcode
609/// Finds the range that has to be erased to remove this declaration without
610/// leaving empty lines, by extending the range until the beginning of the
611/// next instruction.
612///
613/// We need to delete a potential newline after the deleted alias, as
614/// clang-format will leave empty lines untouched. For all other formatting we
615/// rely on clang-format to fix it.
616void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
617 bool Invalid = false;
618 const char *TextAfter =
619 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
620 if (Invalid)
621 return;
622 const unsigned Offset = std::strspn(TextAfter, " \t\r\n");
623 Range =
624 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
625}
626
627/// Computes the changes needed to convert a given for loop, and
628/// applies them.
629void LoopConvertCheck::doConversion(
630 ASTContext *Context, const VarDecl *IndexVar,
631 const ValueDecl *MaybeContainer, const UsageResult &Usages,
632 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit,
633 const ForStmt *Loop, RangeDescriptor Descriptor) {
634 std::string VarNameOrStructuredBinding;
635 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
636 bool AliasVarIsRef = false;
637 bool CanCopy = true;
638 std::vector<FixItHint> FixIts;
639 if (VarNameFromAlias) {
640 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
641
642 // Handle structured bindings
643 if (const auto *AliasDecompositionDecl =
644 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
645 VarNameOrStructuredBinding = "[";
646
647 assert(!AliasDecompositionDecl->bindings().empty() && "No bindings");
648 for (const BindingDecl *Binding : AliasDecompositionDecl->bindings())
649 VarNameOrStructuredBinding += Binding->getName().str() + ", ";
650
651 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
652 2);
653 VarNameOrStructuredBinding += "]";
654 } else {
655 VarNameOrStructuredBinding = AliasVar->getName().str();
656
657 // Use the type of the alias if it's not the same
658 QualType AliasVarType = AliasVar->getType();
659 assert(!AliasVarType.isNull() && "Type in VarDecl is null");
660 if (AliasVarType->isReferenceType()) {
661 AliasVarType = AliasVarType.getNonReferenceType();
662 AliasVarIsRef = true;
663 }
664 if (Descriptor.ElemType.isNull() ||
665 !ASTContext::hasSameUnqualifiedType(AliasVarType,
666 Descriptor.ElemType))
667 Descriptor.ElemType = AliasVarType;
668 }
669
670 // We keep along the entire DeclStmt to keep the correct range here.
671 SourceRange ReplaceRange = AliasDecl->getSourceRange();
672
673 std::string ReplacementText;
674 if (AliasUseRequired) {
675 ReplacementText = VarNameOrStructuredBinding;
676 } else if (AliasFromForInit) {
677 // FIXME: Clang includes the location of the ';' but only for DeclStmt's
678 // in a for loop's init clause. Need to put this ';' back while removing
679 // the declaration of the alias variable. This is probably a bug.
680 ReplacementText = ";";
681 } else {
682 // Avoid leaving empty lines or trailing whitespaces.
683 getAliasRange(Context->getSourceManager(), ReplaceRange);
684 }
685
686 FixIts.push_back(FixItHint::CreateReplacement(
687 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
688 // No further replacements are made to the loop, since the iterator or index
689 // was used exactly once - in the initialization of AliasVar.
690 } else {
691 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
692 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
693 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
694 VarNameOrStructuredBinding = Namer.createIndexName();
695 // First, replace all usages of the array subscript expression with our new
696 // variable.
697 for (const auto &Usage : Usages) {
698 std::string ReplaceText;
699 SourceRange Range = Usage.Range;
700 if (Usage.Expression) {
701 // If this is an access to a member through the arrow operator, after
702 // the replacement it must be accessed through the '.' operator.
703 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow
704 ? VarNameOrStructuredBinding + "."
705 : VarNameOrStructuredBinding;
706 const DynTypedNodeList Parents = Context->getParents(*Usage.Expression);
707 if (Parents.size() == 1) {
708 if (const auto *Paren = Parents[0].get<ParenExpr>()) {
709 // Usage.Expression will be replaced with the new index variable,
710 // and parenthesis around a simple DeclRefExpr can always be
711 // removed except in case of a `sizeof` operator call.
712 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
713 if (GrandParents.size() != 1 ||
714 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() == nullptr) {
715 Range = Paren->getSourceRange();
716 }
717 } else if (const auto *UOP = Parents[0].get<UnaryOperator>()) {
718 // If we are taking the address of the loop variable, then we must
719 // not use a copy, as it would mean taking the address of the loop's
720 // local index instead.
721 // FIXME: This won't catch cases where the address is taken outside
722 // of the loop's body (for instance, in a function that got the
723 // loop's index as a const reference parameter), or where we take
724 // the address of a member (like "&Arr[i].A.B.C").
725 if (UOP->getOpcode() == UO_AddrOf)
726 CanCopy = false;
727 }
728 }
729 } else {
730 // The Usage expression is only null in case of lambda captures (which
731 // are VarDecl). If the index is captured by value, add '&' to capture
732 // by reference instead.
733 ReplaceText = Usage.Kind == Usage::UK_CaptureByCopy
734 ? "&" + VarNameOrStructuredBinding
735 : VarNameOrStructuredBinding;
736 }
737 TUInfo->getReplacedVars().try_emplace(Loop, IndexVar);
738 FixIts.push_back(FixItHint::CreateReplacement(
739 CharSourceRange::getTokenRange(Range), ReplaceText));
740 }
741 }
742
743 // Now, we need to construct the new range expression.
744 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
745
746 QualType Type = Context->getAutoDeductType();
747 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
748 Type = Descriptor.ElemType.getUnqualifiedType();
749 Type = Type.getDesugaredType(*Context);
750
751 // If the new variable name is from the aliased variable, then the reference
752 // type for the new variable should only be used if the aliased variable was
753 // declared as a reference.
754 const bool IsCheapToCopy =
755 !Descriptor.ElemType.isNull() &&
756 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
757 !Descriptor.ElemType->isDependentSizedArrayType() &&
758 // TypeInfo::Width is in bits.
759 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
760 const bool UseCopy =
761 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
762 (Descriptor.DerefByConstRef && IsCheapToCopy));
763
764 if (!UseCopy) {
765 if (Descriptor.DerefByConstRef) {
766 Type = Context->getLValueReferenceType(Context->getConstType(Type));
767 } else if (Descriptor.DerefByValue) {
768 if (!IsCheapToCopy)
769 Type = Context->getRValueReferenceType(Type);
770 } else {
771 Type = Context->getLValueReferenceType(Type);
772 }
773 }
774
775 SmallString<128> Range;
776 llvm::raw_svector_ostream Output(Range);
777 Output << '(';
778 Type.print(Output, getLangOpts());
779 Output << ' ' << VarNameOrStructuredBinding << " : ";
780 if (Descriptor.NeedsReverseCall)
781 Output << getReverseFunction() << '(';
782 if (Descriptor.ContainerNeedsDereference)
783 Output << '*';
784 Output << Descriptor.ContainerString;
785 if (Descriptor.NeedsReverseCall)
786 Output << "))";
787 else
788 Output << ')';
789 FixIts.push_back(FixItHint::CreateReplacement(
790 CharSourceRange::getTokenRange(ParenRange), Range));
791
792 if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) {
793 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
794 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
795 getReverseHeader()))
796 FixIts.push_back(*Insertion);
797 }
798 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts;
799 TUInfo->getGeneratedDecls().try_emplace(Loop, VarNameOrStructuredBinding);
800}
801
802/// Returns a string which refers to the container iterated over.
803StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
804 const ForStmt *Loop,
805 const Expr *ContainerExpr) {
806 StringRef ContainerString;
807 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
808 if (isa<CXXThisExpr>(ContainerExpr)) {
809 ContainerString = "this";
810 } else {
811 // For CXXOperatorCallExpr such as vector_ptr->size() we want the class
812 // object vector_ptr, but for vector[2] we need the whole expression.
813 if (const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
814 if (E->getOperator() != OO_Subscript)
815 ContainerExpr = E->getArg(0);
816 ContainerString =
817 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(),
818 ContainerExpr->getSourceRange());
819 }
820
821 return ContainerString;
822}
823
824/// Determines what kind of 'auto' must be used after converting a for
825/// loop that iterates over an array or pseudoarray.
826void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
827 const BoundNodes &Nodes,
828 const Expr *ContainerExpr,
829 const UsageResult &Usages,
830 RangeDescriptor &Descriptor) {
831 // On arrays and pseudoarrays, we must figure out the qualifiers from the
832 // usages.
833 if (usagesAreConst(Context, Usages) ||
834 containerIsConst(ContainerExpr, Descriptor.ContainerNeedsDereference)) {
835 Descriptor.DerefByConstRef = true;
836 }
837 if (usagesReturnRValues(Usages)) {
838 // If the index usages (dereference, subscript, at, ...) return rvalues,
839 // then we should not use a reference, because we need to keep the code
840 // correct if it mutates the returned objects.
841 Descriptor.DerefByValue = true;
842 }
843 // Try to find the type of the elements on the container, to check if
844 // they are trivially copyable.
845 for (const Usage &U : Usages) {
846 if (!U.Expression || U.Expression->getType().isNull())
847 continue;
848 QualType Type = U.Expression->getType().getCanonicalType();
849 if (U.Kind == Usage::UK_MemberThroughArrow) {
850 if (!Type->isPointerType())
851 continue;
852 Type = Type->getPointeeType();
853 }
854 Descriptor.ElemType = Type;
855 }
856}
857
858/// Determines what kind of 'auto' must be used after converting an
859/// iterator based for loop.
860void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
861 const BoundNodes &Nodes,
862 RangeDescriptor &Descriptor) {
863 // The matchers for iterator loops provide bound nodes to obtain this
864 // information.
865 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
866 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
867 const auto *DerefByValueType =
868 Nodes.getNodeAs<QualType>(DerefByValueResultName);
869 Descriptor.DerefByValue = DerefByValueType;
870
871 if (Descriptor.DerefByValue) {
872 // If the dereference operator returns by value then test for the
873 // canonical const qualification of the init variable type.
874 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
875 Descriptor.ElemType = *DerefByValueType;
876 } else if (const auto *DerefType =
877 Nodes.getNodeAs<QualType>(DerefByRefResultName)) {
878 // A node will only be bound with DerefByRefResultName if we're dealing
879 // with a user-defined iterator type. Test the const qualification of
880 // the reference type.
881 auto ValueType = DerefType->getNonReferenceType();
882
883 Descriptor.DerefByConstRef = ValueType.isConstQualified();
884 Descriptor.ElemType = ValueType;
885 } else {
886 // By nature of the matcher this case is triggered only for built-in
887 // iterator types (i.e. pointers).
888 assert(isa<PointerType>(CanonicalInitVarType) &&
889 "Non-class iterator type is not a pointer type");
890
891 // We test for const qualification of the pointed-at type.
892 Descriptor.DerefByConstRef =
893 CanonicalInitVarType->getPointeeType().isConstQualified();
894 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
895 }
896}
897
898/// Determines the parameters needed to build the range replacement.
899void LoopConvertCheck::determineRangeDescriptor(
900 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop,
901 LoopFixerKind FixerKind, const Expr *ContainerExpr,
902 const UsageResult &Usages, RangeDescriptor &Descriptor) {
903 Descriptor.ContainerString =
904 std::string(getContainerString(Context, Loop, ContainerExpr));
905 Descriptor.NeedsReverseCall = (FixerKind == LFK_ReverseIterator);
906
907 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator)
908 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
909 else
910 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
911}
912
913/// Check some of the conditions that must be met for the loop to be
914/// convertible.
915bool LoopConvertCheck::isConvertible(ASTContext *Context,
916 const ast_matchers::BoundNodes &Nodes,
917 const ForStmt *Loop,
918 LoopFixerKind FixerKind) {
919 // In self contained diagnostic mode we don't want dependencies on other
920 // loops, otherwise, If we already modified the range of this for loop, don't
921 // do any further updates on this iteration.
922 if (areDiagsSelfContained())
923 TUInfo = std::make_unique<TUTrackingInfo>();
924 else if (TUInfo->getReplacedVars().contains(Loop))
925 return false;
926
927 // Check that we have exactly one index variable and at most one end variable.
928 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
929
930 // FIXME: Try to put most of this logic inside a matcher.
931 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
932 const QualType InitVarType = InitVar->getType();
933 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
934
935 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(BeginCallName);
936 assert(BeginCall && "Bad Callback. No begin call expression");
937 const QualType CanonicalBeginType =
938 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
939 if (CanonicalBeginType->isPointerType() &&
940 CanonicalInitVarType->isPointerType()) {
941 // If the initializer and the variable are both pointers check if the
942 // un-qualified pointee types match, otherwise we don't use auto.
943 return ASTContext::hasSameUnqualifiedType(
944 CanonicalBeginType->getPointeeType(),
945 CanonicalInitVarType->getPointeeType());
946 }
947
948 if (CanonicalBeginType->isBuiltinType() ||
949 CanonicalInitVarType->isBuiltinType())
950 return false;
951
952 } else if (FixerKind == LFK_PseudoArray) {
953 if (const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName)) {
954 // This call is required to obtain the container.
955 if (!isa<MemberExpr>(EndCall->getCallee()))
956 return false;
957 }
958 return Nodes.getNodeAs<CallExpr>(EndCallName) != nullptr;
959 }
960 return true;
961}
962
963void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) {
964 const BoundNodes &Nodes = Result.Nodes;
965 Confidence ConfidenceLevel(Confidence::CL_Safe);
966 ASTContext *Context = Result.Context;
967
968 const ForStmt *Loop = nullptr;
969 LoopFixerKind FixerKind{};
970 RangeDescriptor Descriptor;
971
972 if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameArray))) {
973 FixerKind = LFK_Array;
974 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameIterator))) {
975 FixerKind = LFK_Iterator;
976 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameReverseIterator))) {
977 FixerKind = LFK_ReverseIterator;
978 } else {
979 Loop = Nodes.getNodeAs<ForStmt>(LoopNamePseudoArray);
980 assert(Loop && "Bad Callback. No for statement");
981 FixerKind = LFK_PseudoArray;
982 }
983
984 if (!isConvertible(Context, Nodes, Loop, FixerKind))
985 return;
986
987 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(InitVarName);
988 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName);
989
990 // If the loop calls end()/size() after each iteration, lower our confidence
991 // level.
992 if (FixerKind != LFK_Array && !EndVar)
993 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable);
994
995 // If the end comparison isn't a variable, we can try to work with the
996 // expression the loop variable is being tested against instead.
997 const auto *EndCall = Nodes.getNodeAs<Expr>(EndCallName);
998 const auto *BoundExpr = Nodes.getNodeAs<Expr>(ConditionBoundName);
999
1000 // Find container expression of iterators and pseudoarrays, and determine if
1001 // this expression needs to be dereferenced to obtain the container.
1002 // With array loops, the container is often discovered during the
1003 // ForLoopIndexUseVisitor traversal.
1004 const Expr *ContainerExpr = nullptr;
1005 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
1006 ContainerExpr = findContainer(
1007 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1008 &Descriptor.ContainerNeedsDereference,
1009 /*IsReverse=*/FixerKind == LFK_ReverseIterator);
1010 } else if (FixerKind == LFK_PseudoArray) {
1011 std::optional<ContainerCall> Call = getContainerExpr(EndCall);
1012 if (Call) {
1013 ContainerExpr = Call->Container;
1014 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1015 }
1016 }
1017
1018 // We must know the container or an array length bound.
1019 if (!ContainerExpr && !BoundExpr)
1020 return;
1021
1022 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr,
1023 BoundExpr,
1024 Descriptor.ContainerNeedsDereference);
1025
1026 // Find expressions and variables on which the container depends.
1027 if (ContainerExpr) {
1028 ComponentFinderASTVisitor ComponentFinder;
1029 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts());
1030 Finder.addComponents(ComponentFinder.getComponents());
1031 }
1032
1033 // Find usages of the loop index. If they are not used in a convertible way,
1034 // stop here.
1035 if (!Finder.findAndVerifyUsages(Loop->getBody()))
1036 return;
1037 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel());
1038
1039 // Obtain the container expression, if we don't have it yet.
1040 if (FixerKind == LFK_Array) {
1041 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts();
1042
1043 // Very few loops are over expressions that generate arrays rather than
1044 // array variables. Consider loops over arrays that aren't just represented
1045 // by a variable to be risky conversions.
1046 if (!getReferencedVariable(ContainerExpr) &&
1047 !isDirectMemberExpr(ContainerExpr))
1048 ConfidenceLevel.lowerTo(Confidence::CL_Risky);
1049 }
1050
1051 // Find out which qualifiers we have to use in the loop range.
1052 const TraversalKindScope RAII(*Context, TK_AsIs);
1053 const UsageResult &Usages = Finder.getUsages();
1054 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1055 Usages, Descriptor);
1056
1057 // Ensure that we do not try to move an expression dependent on a local
1058 // variable declared inside the loop outside of it.
1059 // FIXME: Determine when the external dependency isn't an expression converted
1060 // by another loop.
1061 TUInfo->getParentFinder().gatherAncestors(*Context);
1062 DependencyFinderASTVisitor DependencyFinder(
1063 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1064 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1065 &TUInfo->getReplacedVars(), Loop);
1066
1067 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) ||
1068 Descriptor.ContainerString.empty() || Usages.empty() ||
1069 ConfidenceLevel.getLevel() < MinConfidence)
1070 return;
1071
1072 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages,
1073 Finder.getAliasDecl(), Finder.aliasUseRequired(),
1074 Finder.aliasFromForInit(), Loop, Descriptor);
1075}
1076
1077llvm::StringRef LoopConvertCheck::getReverseFunction() const {
1078 if (!ReverseFunction.empty())
1079 return ReverseFunction;
1080 if (UseReverseRanges)
1081 return "std::views::reverse";
1082 return "";
1083}
1084
1085llvm::StringRef LoopConvertCheck::getReverseHeader() const {
1086 if (!ReverseHeader.empty())
1087 return ReverseHeader;
1088 if (UseReverseRanges && ReverseFunction.empty())
1089 return "<ranges>";
1090 return "";
1091}
1092
1093} // namespace modernize
1094} // namespace clang::tidy
const char Usage[]
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Class used to find the variables and member expressions on which an arbitrary expression depends.
void findExprComponents(const clang::Expr *SourceExpr)
Find the components of an expression and place them in a ComponentVector.
const ComponentVector & getComponents()
Accessor for Components.
A class to encapsulate lowering of the tool's confidence level.
Level getLevel() const
Return the internal confidence level.
void lowerTo(Confidence::Level Level)
Lower the internal confidence level to Level, but do not raise it.
Class used to determine if an expression is dependent on a variable declared inside of the loop where...
bool dependsOnInsideVariable(const clang::Stmt *Body)
Run the analysis on Body, and return true iff the expression depends on some variable declared within...
Discover usages of expressions consisting of index or iterator access.
const UsageResult & getUsages() const
Accessor for Usages.
bool aliasFromForInit() const
Indicates if the alias declaration came from the init clause of a nested for loop.
const DeclStmt * getAliasDecl() const
Returns the statement declaring the variable created as an alias for the loop element,...
bool aliasUseRequired() const
Indicates if the alias declaration was in a place where it cannot simply be removed but rather replac...
bool findAndVerifyUsages(const Stmt *Body)
Finds all uses of IndexVar in Body, placing all usages in Usages, and returns true if IndexVar was on...
Confidence::Level getConfidenceLevel() const
Accessor for ConfidenceLevel.
void addComponents(const ComponentVector &Components)
Add a set of components that we should consider relevant to the container.
const Expr * getContainerIndexed() const
Get the container indexed by IndexVar, if any.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
LoopConvertCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Create names for generated variables within a particular statement.
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1678
static constexpr char BeginCallName[]
llvm::SmallVector< Usage, 8 > UsageResult
static StringRef getStringFromRange(SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
static constexpr char DerefByRefResultName[]
static bool empty(SourceRange Range)
static constexpr char LoopNameReverseIterator[]
static const llvm::StringSet StdNames
static DeclarationMatcher initToZeroMatcher()
static StatementMatcher incrementVarMatcher()
static constexpr char EndCallName[]
static StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
static StatementMatcher arrayConditionMatcher(const internal::Matcher< Expr > &LimitExpr)
static constexpr char ConditionBoundName[]
static bool canBeModified(ASTContext *Context, const Expr *E)
Given an expression that represents an usage of an element from the container that we are iterating o...
static std::optional< ContainerCall > getContainerExpr(const Expr *Call)
const DeclRefExpr * getDeclRef(const Expr *E)
Returns the DeclRefExpr represented by E, or NULL if there isn't one.
static const llvm::StringSet MemberNames
static const llvm::StringSet ADLNames
static StatementMatcher makeArrayLoopMatcher()
The matcher for loops over arrays.
static bool usagesReturnRValues(const UsageResult &Usages)
Returns true if the elements of the container are never accessed by reference.
static const ValueDecl * getReferencedVariable(const Expr *E)
If the given expression is actually a DeclRefExpr or a MemberExpr, find and return the underlying Val...
static constexpr char EndVarName[]
static StatementMatcher integerComparisonMatcher()
const Expr * digThroughConstructorsConversions(const Expr *E)
Look through conversion/copy constructors and member functions to find the explicit initialization ex...
static bool containerIsConst(const Expr *ContainerExpr, bool Dereference)
Returns true if the container is const-qualified.
static constexpr char LoopNamePseudoArray[]
static const Expr * findContainer(ASTContext *Context, const Expr *BeginExpr, const Expr *EndExpr, bool *ContainerNeedsDereference, bool IsReverse)
Determines the container whose begin() and end() functions are called for an iterator-based loop.
static std::pair< const Expr *, IteratorCallKind > getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow, bool IsReverse)
Determine whether Init appears to be an initializing an iterator.
static constexpr char InitVarName[]
static constexpr char LoopNameIterator[]
static constexpr char DerefByValueResultName[]
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
static bool isDirectMemberExpr(const Expr *E)
Returns true when the given expression is a member expression whose base is this (implicitly or not).
static StatementMatcher makeIteratorLoopMatcher(bool IsReverse)
The matcher used for iterator-based for loops.
static constexpr char LoopNameArray[]
static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages)
Returns true when it can be guaranteed that the elements of the container are not being modified.
Some operations such as code completion produce a set of candidates.
Definition Generators.h:145
llvm::StringMap< ClangTidyValue > OptionMap
static llvm::ArrayRef< std::pair< modernize::Confidence::Level, StringRef > > getEnumMapping()
static llvm::ArrayRef< std::pair< modernize::VariableNamer::NamingStyle, StringRef > > getEnumMapping()
This class should be specialized by any enum type that needs to be converted to and from an llvm::Str...
The information needed to describe a valid convertible usage of an array index or iterator.