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