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 const char LoopNameArray[] = "forLoopArray";
59static const char LoopNameIterator[] = "forLoopIterator";
60static const char LoopNameReverseIterator[] = "forLoopReverseIterator";
61static const char LoopNamePseudoArray[] = "forLoopPseudoArray";
62static const char ConditionBoundName[] = "conditionBound";
63static const char InitVarName[] = "initVar";
64static const char BeginCallName[] = "beginCall";
65static const char EndCallName[] = "endCall";
66static const char EndVarName[] = "endVar";
67static const char DerefByValueResultName[] = "derefByValueResult";
68static const 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
338
340 const Expr *Container;
341 StringRef Name;
344};
345
346// Find the Expr likely initializing an iterator.
347//
348// Call is either a CXXMemberCallExpr ('c.begin()') or CallExpr of a free
349// function with the first argument as a container ('begin(c)'), or nullptr.
350// Returns at a 3-tuple with the container expr, function name (begin/end/etc),
351// and whether the call is made through an arrow (->) for CXXMemberCallExprs.
352// The returned Expr* is nullptr if any of the assumptions are not met.
353// static std::tuple<const Expr *, StringRef, bool, IteratorCallKind>
354static std::optional<ContainerCall> getContainerExpr(const Expr *Call) {
355 const Expr *Dug = digThroughConstructorsConversions(Call);
356
358
359 if (const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
361 if (const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
362 if (Member->getMemberDecl() == nullptr ||
363 !MemberNames.contains(Member->getMemberDecl()->getName()))
364 return std::nullopt;
365 return ContainerCall{TheCall->getImplicitObjectArgument(),
366 Member->getMemberDecl()->getName(),
367 Member->isArrow(), CallKind};
368 }
369 if (TheCall->getDirectCallee() == nullptr ||
370 !MemberNames.contains(TheCall->getDirectCallee()->getName()))
371 return std::nullopt;
372 return ContainerCall{TheCall->getArg(0),
373 TheCall->getDirectCallee()->getName(), false,
374 CallKind};
375 }
376 if (const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
377 if (TheCall->getNumArgs() != 1)
378 return std::nullopt;
379
380 if (TheCall->usesADL()) {
381 if (TheCall->getDirectCallee() == nullptr ||
382 !ADLNames.contains(TheCall->getDirectCallee()->getName()))
383 return std::nullopt;
384 CallKind = IteratorCallKind::ICK_ADL;
385 } else {
386 if (!StdNames.contains(
387 TheCall->getDirectCallee()->getQualifiedNameAsString()))
388 return std::nullopt;
389 CallKind = IteratorCallKind::ICK_Std;
390 }
391
392 if (TheCall->getDirectCallee() == nullptr)
393 return std::nullopt;
394
395 return ContainerCall{TheCall->getArg(0),
396 TheCall->getDirectCallee()->getName(), false,
397 CallKind};
398 }
399 return std::nullopt;
400}
401
402/// Determine whether Init appears to be an initializing an iterator.
403///
404/// If it is, returns the object whose begin() or end() method is called, and
405/// the output parameter isArrow is set to indicate whether the initialization
406/// is called via . or ->.
407static std::pair<const Expr *, IteratorCallKind>
408getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow,
409 bool IsReverse) {
410 // FIXME: Maybe allow declaration/initialization outside of the for loop.
411
412 std::optional<ContainerCall> Call = getContainerExpr(Init);
413 if (!Call)
414 return {};
415
416 *IsArrow = Call->IsArrow;
417 if (!Call->Name.consume_back(IsBegin ? "begin" : "end"))
418 return {};
419 if (IsReverse && !Call->Name.consume_back("r"))
420 return {};
421 if (!Call->Name.empty() && Call->Name != "c")
422 return {};
423 return std::make_pair(Call->Container, Call->CallKind);
424}
425
426/// Determines the container whose begin() and end() functions are called
427/// for an iterator-based loop.
428///
429/// BeginExpr must be a member call to a function named "begin()", and EndExpr
430/// must be a member.
431static const Expr *findContainer(ASTContext *Context, const Expr *BeginExpr,
432 const Expr *EndExpr,
433 bool *ContainerNeedsDereference,
434 bool IsReverse) {
435 // Now that we know the loop variable and test expression, make sure they are
436 // valid.
437 bool BeginIsArrow = false;
438 bool EndIsArrow = false;
439 auto [BeginContainerExpr, BeginCallKind] = getContainerFromBeginEndCall(
440 BeginExpr, /*IsBegin=*/true, &BeginIsArrow, IsReverse);
441 if (!BeginContainerExpr)
442 return nullptr;
443
444 auto [EndContainerExpr, EndCallKind] = getContainerFromBeginEndCall(
445 EndExpr, /*IsBegin=*/false, &EndIsArrow, IsReverse);
446 if (BeginCallKind != EndCallKind)
447 return nullptr;
448
449 // Disallow loops that try evil things like this (note the dot and arrow):
450 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { }
451 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
452 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
453 return nullptr;
454
455 *ContainerNeedsDereference = BeginIsArrow;
456 return BeginContainerExpr;
457}
458
459/// Obtain the original source code text from a SourceRange.
460static StringRef getStringFromRange(SourceManager &SourceMgr,
461 const LangOptions &LangOpts,
462 SourceRange Range) {
463 if (SourceMgr.getFileID(Range.getBegin()) !=
464 SourceMgr.getFileID(Range.getEnd())) {
465 return {}; // Empty string.
466 }
467
468 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr,
469 LangOpts);
470}
471
472/// If the given expression is actually a DeclRefExpr or a MemberExpr,
473/// find and return the underlying ValueDecl; otherwise, return NULL.
474static const ValueDecl *getReferencedVariable(const Expr *E) {
475 if (const DeclRefExpr *DRE = getDeclRef(E))
476 return dyn_cast<VarDecl>(DRE->getDecl());
477 if (const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
478 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
479 return nullptr;
480}
481
482/// Returns true when the given expression is a member expression
483/// whose base is `this` (implicitly or not).
484static bool isDirectMemberExpr(const Expr *E) {
485 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
486 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
487 return false;
488}
489
490/// Given an expression that represents an usage of an element from the
491/// container that we are iterating over, returns false when it can be
492/// guaranteed this element cannot be modified as a result of this usage.
493static bool canBeModified(ASTContext *Context, const Expr *E) {
494 if (E->getType().isConstQualified())
495 return false;
496 auto Parents = Context->getParents(*E);
497 if (Parents.size() != 1)
498 return true;
499 if (const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
500 if ((Cast->getCastKind() == CK_NoOp &&
501 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
502 (Cast->getCastKind() == CK_LValueToRValue &&
503 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
504 return false;
505 }
506 // FIXME: Make this function more generic.
507 return true;
508}
509
510/// Returns true when it can be guaranteed that the elements of the
511/// container are not being modified.
512static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages) {
513 return llvm::none_of(Usages, [&Context](const Usage &U) {
514 // Lambda captures are just redeclarations (VarDecl) of the same variable,
515 // not expressions. If we want to know if a variable that is captured by
516 // reference can be modified in an usage inside the lambda's body, we need
517 // to find the expression corresponding to that particular usage, later in
518 // this loop.
519 return U.Kind != Usage::UK_CaptureByCopy &&
521 canBeModified(Context, U.Expression);
522 });
523}
524
525/// Returns true if the elements of the container are never accessed
526/// by reference.
527static bool usagesReturnRValues(const UsageResult &Usages) {
528 return llvm::all_of(Usages, [](const Usage &U) {
529 return !U.Expression || U.Expression->isPRValue();
530 });
531}
532
533/// Returns true if the container is const-qualified.
534static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) {
535 if (const auto *VDec = getReferencedVariable(ContainerExpr)) {
536 QualType CType = VDec->getType();
537 if (Dereference) {
538 if (!CType->isPointerType())
539 return false;
540 CType = CType->getPointeeType();
541 }
542 // If VDec is a reference to a container, Dereference is false,
543 // but we still need to check the const-ness of the underlying container
544 // type.
545 CType = CType.getNonReferenceType();
546 return CType.isConstQualified();
547 }
548 return false;
549}
550
552 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo),
553 MaxCopySize(Options.get("MaxCopySize", 16ULL)),
554 MinConfidence(Options.get("MinConfidence", Confidence::CL_Reasonable)),
555 NamingStyle(Options.get("NamingStyle", VariableNamer::NS_CamelCase)),
556 Inserter(Options.getLocalOrGlobal("IncludeStyle",
557 utils::IncludeSorter::IS_LLVM),
558 areDiagsSelfContained()),
559 UseCxx20IfAvailable(Options.get("UseCxx20ReverseRanges", true)),
560 ReverseFunction(Options.get("MakeReverseRangeFunction", "")),
561 ReverseHeader(Options.get("MakeReverseRangeHeader", "")) {
562 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
563 configurationDiag(
564 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
565 "'MakeReverseRangeFunction' is not, disabling reverse loop "
566 "transformation");
567 UseReverseRanges = false;
568 } else if (ReverseFunction.empty()) {
569 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
570 } else {
571 UseReverseRanges = true;
572 }
573}
574
576 Options.store(Opts, "MaxCopySize", MaxCopySize);
577 Options.store(Opts, "MinConfidence", MinConfidence);
578 Options.store(Opts, "NamingStyle", NamingStyle);
579 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
580 Options.store(Opts, "UseCxx20ReverseRanges", UseCxx20IfAvailable);
581 Options.store(Opts, "MakeReverseRangeFunction", ReverseFunction);
582 Options.store(Opts, "MakeReverseRangeHeader", ReverseHeader);
583}
584
585void LoopConvertCheck::registerPPCallbacks(const SourceManager &SM,
586 Preprocessor *PP,
587 Preprocessor *ModuleExpanderPP) {
588 Inserter.registerPreprocessor(PP);
589}
590
591void LoopConvertCheck::registerMatchers(MatchFinder *Finder) {
592 Finder->addMatcher(traverse(TK_AsIs, makeArrayLoopMatcher()), this);
593 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(false)), this);
594 Finder->addMatcher(traverse(TK_AsIs, makePseudoArrayLoopMatcher()), this);
595 if (UseReverseRanges)
596 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(true)), this);
597}
598
599/// Given the range of a single declaration, such as:
600/// \code
601/// unsigned &ThisIsADeclarationThatCanSpanSeveralLinesOfCode =
602/// InitializationValues[I];
603/// next_instruction;
604/// \endcode
605/// Finds the range that has to be erased to remove this declaration without
606/// leaving empty lines, by extending the range until the beginning of the
607/// next instruction.
608///
609/// We need to delete a potential newline after the deleted alias, as
610/// clang-format will leave empty lines untouched. For all other formatting we
611/// rely on clang-format to fix it.
612void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
613 bool Invalid = false;
614 const char *TextAfter =
615 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
616 if (Invalid)
617 return;
618 const unsigned Offset = std::strspn(TextAfter, " \t\r\n");
619 Range =
620 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
621}
622
623/// Computes the changes needed to convert a given for loop, and
624/// applies them.
625void LoopConvertCheck::doConversion(
626 ASTContext *Context, const VarDecl *IndexVar,
627 const ValueDecl *MaybeContainer, const UsageResult &Usages,
628 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit,
629 const ForStmt *Loop, RangeDescriptor Descriptor) {
630 std::string VarNameOrStructuredBinding;
631 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
632 bool AliasVarIsRef = false;
633 bool CanCopy = true;
634 std::vector<FixItHint> FixIts;
635 if (VarNameFromAlias) {
636 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
637
638 // Handle structured bindings
639 if (const auto *AliasDecompositionDecl =
640 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
641 VarNameOrStructuredBinding = "[";
642
643 assert(!AliasDecompositionDecl->bindings().empty() && "No bindings");
644 for (const BindingDecl *Binding : AliasDecompositionDecl->bindings()) {
645 VarNameOrStructuredBinding += Binding->getName().str() + ", ";
646 }
647
648 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
649 2);
650 VarNameOrStructuredBinding += "]";
651 } else {
652 VarNameOrStructuredBinding = AliasVar->getName().str();
653
654 // Use the type of the alias if it's not the same
655 QualType AliasVarType = AliasVar->getType();
656 assert(!AliasVarType.isNull() && "Type in VarDecl is null");
657 if (AliasVarType->isReferenceType()) {
658 AliasVarType = AliasVarType.getNonReferenceType();
659 AliasVarIsRef = true;
660 }
661 if (Descriptor.ElemType.isNull() ||
662 !ASTContext::hasSameUnqualifiedType(AliasVarType,
663 Descriptor.ElemType))
664 Descriptor.ElemType = AliasVarType;
665 }
666
667 // We keep along the entire DeclStmt to keep the correct range here.
668 SourceRange ReplaceRange = AliasDecl->getSourceRange();
669
670 std::string ReplacementText;
671 if (AliasUseRequired) {
672 ReplacementText = VarNameOrStructuredBinding;
673 } else if (AliasFromForInit) {
674 // FIXME: Clang includes the location of the ';' but only for DeclStmt's
675 // in a for loop's init clause. Need to put this ';' back while removing
676 // the declaration of the alias variable. This is probably a bug.
677 ReplacementText = ";";
678 } else {
679 // Avoid leaving empty lines or trailing whitespaces.
680 getAliasRange(Context->getSourceManager(), ReplaceRange);
681 }
682
683 FixIts.push_back(FixItHint::CreateReplacement(
684 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
685 // No further replacements are made to the loop, since the iterator or index
686 // was used exactly once - in the initialization of AliasVar.
687 } else {
688 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
689 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
690 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
691 VarNameOrStructuredBinding = Namer.createIndexName();
692 // First, replace all usages of the array subscript expression with our new
693 // variable.
694 for (const auto &Usage : Usages) {
695 std::string ReplaceText;
696 SourceRange Range = Usage.Range;
697 if (Usage.Expression) {
698 // If this is an access to a member through the arrow operator, after
699 // the replacement it must be accessed through the '.' operator.
700 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow
701 ? VarNameOrStructuredBinding + "."
702 : VarNameOrStructuredBinding;
703 const DynTypedNodeList Parents = Context->getParents(*Usage.Expression);
704 if (Parents.size() == 1) {
705 if (const auto *Paren = Parents[0].get<ParenExpr>()) {
706 // Usage.Expression will be replaced with the new index variable,
707 // and parenthesis around a simple DeclRefExpr can always be
708 // removed except in case of a `sizeof` operator call.
709 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
710 if (GrandParents.size() != 1 ||
711 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() == nullptr) {
712 Range = Paren->getSourceRange();
713 }
714 } else if (const auto *UOP = Parents[0].get<UnaryOperator>()) {
715 // If we are taking the address of the loop variable, then we must
716 // not use a copy, as it would mean taking the address of the loop's
717 // local index instead.
718 // FIXME: This won't catch cases where the address is taken outside
719 // of the loop's body (for instance, in a function that got the
720 // loop's index as a const reference parameter), or where we take
721 // the address of a member (like "&Arr[i].A.B.C").
722 if (UOP->getOpcode() == UO_AddrOf)
723 CanCopy = false;
724 }
725 }
726 } else {
727 // The Usage expression is only null in case of lambda captures (which
728 // are VarDecl). If the index is captured by value, add '&' to capture
729 // by reference instead.
730 ReplaceText = Usage.Kind == Usage::UK_CaptureByCopy
731 ? "&" + VarNameOrStructuredBinding
732 : VarNameOrStructuredBinding;
733 }
734 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
735 FixIts.push_back(FixItHint::CreateReplacement(
736 CharSourceRange::getTokenRange(Range), ReplaceText));
737 }
738 }
739
740 // Now, we need to construct the new range expression.
741 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
742
743 QualType Type = Context->getAutoDeductType();
744 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
745 Type = Descriptor.ElemType.getUnqualifiedType();
746 Type = Type.getDesugaredType(*Context);
747
748 // If the new variable name is from the aliased variable, then the reference
749 // type for the new variable should only be used if the aliased variable was
750 // declared as a reference.
751 const bool IsCheapToCopy =
752 !Descriptor.ElemType.isNull() &&
753 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
754 !Descriptor.ElemType->isDependentSizedArrayType() &&
755 // TypeInfo::Width is in bits.
756 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
757 const bool UseCopy =
758 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
759 (Descriptor.DerefByConstRef && IsCheapToCopy));
760
761 if (!UseCopy) {
762 if (Descriptor.DerefByConstRef) {
763 Type = Context->getLValueReferenceType(Context->getConstType(Type));
764 } else if (Descriptor.DerefByValue) {
765 if (!IsCheapToCopy)
766 Type = Context->getRValueReferenceType(Type);
767 } else {
768 Type = Context->getLValueReferenceType(Type);
769 }
770 }
771
772 SmallString<128> Range;
773 llvm::raw_svector_ostream Output(Range);
774 Output << '(';
775 Type.print(Output, getLangOpts());
776 Output << ' ' << VarNameOrStructuredBinding << " : ";
777 if (Descriptor.NeedsReverseCall)
778 Output << getReverseFunction() << '(';
779 if (Descriptor.ContainerNeedsDereference)
780 Output << '*';
781 Output << Descriptor.ContainerString;
782 if (Descriptor.NeedsReverseCall)
783 Output << "))";
784 else
785 Output << ')';
786 FixIts.push_back(FixItHint::CreateReplacement(
787 CharSourceRange::getTokenRange(ParenRange), Range));
788
789 if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) {
790 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
791 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
792 getReverseHeader()))
793 FixIts.push_back(*Insertion);
794 }
795 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts;
796 TUInfo->getGeneratedDecls().insert(
797 make_pair(Loop, VarNameOrStructuredBinding));
798}
799
800/// Returns a string which refers to the container iterated over.
801StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
802 const ForStmt *Loop,
803 const Expr *ContainerExpr) {
804 StringRef ContainerString;
805 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
806 if (isa<CXXThisExpr>(ContainerExpr)) {
807 ContainerString = "this";
808 } else {
809 // For CXXOperatorCallExpr such as vector_ptr->size() we want the class
810 // object vector_ptr, but for vector[2] we need the whole expression.
811 if (const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
812 if (E->getOperator() != OO_Subscript)
813 ContainerExpr = E->getArg(0);
814 ContainerString =
815 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(),
816 ContainerExpr->getSourceRange());
817 }
818
819 return ContainerString;
820}
821
822/// Determines what kind of 'auto' must be used after converting a for
823/// loop that iterates over an array or pseudoarray.
824void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
825 const BoundNodes &Nodes,
826 const Expr *ContainerExpr,
827 const UsageResult &Usages,
828 RangeDescriptor &Descriptor) {
829 // On arrays and pseudoarrays, we must figure out the qualifiers from the
830 // usages.
831 if (usagesAreConst(Context, Usages) ||
832 containerIsConst(ContainerExpr, Descriptor.ContainerNeedsDereference)) {
833 Descriptor.DerefByConstRef = true;
834 }
835 if (usagesReturnRValues(Usages)) {
836 // If the index usages (dereference, subscript, at, ...) return rvalues,
837 // then we should not use a reference, because we need to keep the code
838 // correct if it mutates the returned objects.
839 Descriptor.DerefByValue = true;
840 }
841 // Try to find the type of the elements on the container, to check if
842 // they are trivially copyable.
843 for (const Usage &U : Usages) {
844 if (!U.Expression || U.Expression->getType().isNull())
845 continue;
846 QualType Type = U.Expression->getType().getCanonicalType();
847 if (U.Kind == Usage::UK_MemberThroughArrow) {
848 if (!Type->isPointerType()) {
849 continue;
850 }
851 Type = Type->getPointeeType();
852 }
853 Descriptor.ElemType = Type;
854 }
855}
856
857/// Determines what kind of 'auto' must be used after converting an
858/// iterator based for loop.
859void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
860 const BoundNodes &Nodes,
861 RangeDescriptor &Descriptor) {
862 // The matchers for iterator loops provide bound nodes to obtain this
863 // information.
864 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
865 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
866 const auto *DerefByValueType =
867 Nodes.getNodeAs<QualType>(DerefByValueResultName);
868 Descriptor.DerefByValue = DerefByValueType;
869
870 if (Descriptor.DerefByValue) {
871 // If the dereference operator returns by value then test for the
872 // canonical const qualification of the init variable type.
873 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
874 Descriptor.ElemType = *DerefByValueType;
875 } else {
876 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
899/// Determines the parameters needed to build the range replacement.
900void LoopConvertCheck::determineRangeDescriptor(
901 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop,
902 LoopFixerKind FixerKind, const Expr *ContainerExpr,
903 const UsageResult &Usages, RangeDescriptor &Descriptor) {
904 Descriptor.ContainerString =
905 std::string(getContainerString(Context, Loop, ContainerExpr));
906 Descriptor.NeedsReverseCall = (FixerKind == LFK_ReverseIterator);
907
908 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator)
909 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
910 else
911 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
912}
913
914/// Check some of the conditions that must be met for the loop to be
915/// convertible.
916bool LoopConvertCheck::isConvertible(ASTContext *Context,
917 const ast_matchers::BoundNodes &Nodes,
918 const ForStmt *Loop,
919 LoopFixerKind FixerKind) {
920 // In self contained diagnostic mode we don't want dependencies on other
921 // loops, otherwise, If we already modified the range of this for loop, don't
922 // do any further updates on this iteration.
923 if (areDiagsSelfContained())
924 TUInfo = std::make_unique<TUTrackingInfo>();
925 else if (TUInfo->getReplacedVars().contains(Loop))
926 return false;
927
928 // Check that we have exactly one index variable and at most one end variable.
929 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
930
931 // FIXME: Try to put most of this logic inside a matcher.
932 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
933 const QualType InitVarType = InitVar->getType();
934 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
935
936 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(BeginCallName);
937 assert(BeginCall && "Bad Callback. No begin call expression");
938 const QualType CanonicalBeginType =
939 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
940 if (CanonicalBeginType->isPointerType() &&
941 CanonicalInitVarType->isPointerType()) {
942 // If the initializer and the variable are both pointers check if the
943 // un-qualified pointee types match, otherwise we don't use auto.
944 return ASTContext::hasSameUnqualifiedType(
945 CanonicalBeginType->getPointeeType(),
946 CanonicalInitVarType->getPointeeType());
947 }
948
949 if (CanonicalBeginType->isBuiltinType() ||
950 CanonicalInitVarType->isBuiltinType())
951 return false;
952
953 } else if (FixerKind == LFK_PseudoArray) {
954 if (const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName)) {
955 // This call is required to obtain the container.
956 if (!isa<MemberExpr>(EndCall->getCallee()))
957 return false;
958 }
959 return Nodes.getNodeAs<CallExpr>(EndCallName) != nullptr;
960 }
961 return true;
962}
963
964void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) {
965 const BoundNodes &Nodes = Result.Nodes;
966 Confidence ConfidenceLevel(Confidence::CL_Safe);
967 ASTContext *Context = Result.Context;
968
969 const ForStmt *Loop = nullptr;
970 LoopFixerKind FixerKind{};
971 RangeDescriptor Descriptor;
972
973 if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameArray))) {
974 FixerKind = LFK_Array;
975 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameIterator))) {
976 FixerKind = LFK_Iterator;
977 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameReverseIterator))) {
978 FixerKind = LFK_ReverseIterator;
979 } else {
980 Loop = Nodes.getNodeAs<ForStmt>(LoopNamePseudoArray);
981 assert(Loop && "Bad Callback. No for statement");
982 FixerKind = LFK_PseudoArray;
983 }
984
985 if (!isConvertible(Context, Nodes, Loop, FixerKind))
986 return;
987
988 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(InitVarName);
989 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName);
990
991 // If the loop calls end()/size() after each iteration, lower our confidence
992 // level.
993 if (FixerKind != LFK_Array && !EndVar)
994 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable);
995
996 // If the end comparison isn't a variable, we can try to work with the
997 // expression the loop variable is being tested against instead.
998 const auto *EndCall = Nodes.getNodeAs<Expr>(EndCallName);
999 const auto *BoundExpr = Nodes.getNodeAs<Expr>(ConditionBoundName);
1000
1001 // Find container expression of iterators and pseudoarrays, and determine if
1002 // this expression needs to be dereferenced to obtain the container.
1003 // With array loops, the container is often discovered during the
1004 // ForLoopIndexUseVisitor traversal.
1005 const Expr *ContainerExpr = nullptr;
1006 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
1007 ContainerExpr = findContainer(
1008 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1009 &Descriptor.ContainerNeedsDereference,
1010 /*IsReverse=*/FixerKind == LFK_ReverseIterator);
1011 } else if (FixerKind == LFK_PseudoArray) {
1012 std::optional<ContainerCall> Call = getContainerExpr(EndCall);
1013 if (Call) {
1014 ContainerExpr = Call->Container;
1015 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1016 }
1017 }
1018
1019 // We must know the container or an array length bound.
1020 if (!ContainerExpr && !BoundExpr)
1021 return;
1022
1023 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr,
1024 BoundExpr,
1025 Descriptor.ContainerNeedsDereference);
1026
1027 // Find expressions and variables on which the container depends.
1028 if (ContainerExpr) {
1029 ComponentFinderASTVisitor ComponentFinder;
1030 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts());
1031 Finder.addComponents(ComponentFinder.getComponents());
1032 }
1033
1034 // Find usages of the loop index. If they are not used in a convertible way,
1035 // stop here.
1036 if (!Finder.findAndVerifyUsages(Loop->getBody()))
1037 return;
1038 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel());
1039
1040 // Obtain the container expression, if we don't have it yet.
1041 if (FixerKind == LFK_Array) {
1042 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts();
1043
1044 // Very few loops are over expressions that generate arrays rather than
1045 // array variables. Consider loops over arrays that aren't just represented
1046 // by a variable to be risky conversions.
1047 if (!getReferencedVariable(ContainerExpr) &&
1048 !isDirectMemberExpr(ContainerExpr))
1049 ConfidenceLevel.lowerTo(Confidence::CL_Risky);
1050 }
1051
1052 // Find out which qualifiers we have to use in the loop range.
1053 const TraversalKindScope RAII(*Context, TK_AsIs);
1054 const UsageResult &Usages = Finder.getUsages();
1055 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1056 Usages, Descriptor);
1057
1058 // Ensure that we do not try to move an expression dependent on a local
1059 // variable declared inside the loop outside of it.
1060 // FIXME: Determine when the external dependency isn't an expression converted
1061 // by another loop.
1062 TUInfo->getParentFinder().gatherAncestors(*Context);
1063 DependencyFinderASTVisitor DependencyFinder(
1064 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1065 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1066 &TUInfo->getReplacedVars(), Loop);
1067
1068 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) ||
1069 Descriptor.ContainerString.empty() || Usages.empty() ||
1070 ConfidenceLevel.getLevel() < MinConfidence)
1071 return;
1072
1073 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages,
1074 Finder.getAliasDecl(), Finder.aliasUseRequired(),
1075 Finder.aliasFromForInit(), Loop, Descriptor);
1076}
1077
1078llvm::StringRef LoopConvertCheck::getReverseFunction() const {
1079 if (!ReverseFunction.empty())
1080 return ReverseFunction;
1081 if (UseReverseRanges)
1082 return "std::ranges::reverse_view";
1083 return "";
1084}
1085
1086llvm::StringRef LoopConvertCheck::getReverseHeader() const {
1087 if (!ReverseHeader.empty())
1088 return ReverseHeader;
1089 if (UseReverseRanges && ReverseFunction.empty()) {
1090 return "<ranges>";
1091 }
1092 return "";
1093}
1094
1095} // namespace modernize
1096} // 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
llvm::SmallVector< Usage, 8 > UsageResult
static const char EndCallName[]
static StringRef getStringFromRange(SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
static bool empty(SourceRange Range)
static const llvm::StringSet StdNames
static DeclarationMatcher initToZeroMatcher()
static StatementMatcher incrementVarMatcher()
static StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
static StatementMatcher arrayConditionMatcher(const internal::Matcher< Expr > &LimitExpr)
static const char DerefByValueResultName[]
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 const char LoopNamePseudoArray[]
static const char BeginCallName[]
static std::optional< ContainerCall > getContainerExpr(const Expr *Call)
static const char ConditionBoundName[]
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 StatementMatcher integerComparisonMatcher()
const Expr * digThroughConstructorsConversions(const Expr *E)
Look through conversion/copy constructors and member functions to find the explicit initialization ex...
static const char DerefByRefResultName[]
static bool containerIsConst(const Expr *ContainerExpr, bool Dereference)
Returns true if the container is const-qualified.
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 const char LoopNameIterator[]
static const char InitVarName[]
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
static const char EndVarName[]
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 const char LoopNameReverseIterator[]
static const 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:146
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.