[clang-tools-extra] [clang-tidy] Handle inclusive array bounds in modernize-loop-convert (PR #242929)
via cfe-commits
cfe-commits at lists.llvm.org
Sun Nov 15 17:44:52 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tools-extra
Author: Richard Thomson (LegalizeAdulthood)
<details>
<summary>Changes</summary>
Recognize i <= N - 1 and N - 1 >= i when iterating over arrays. Reject bounds that overflow the index. Add tests and documentation.
Fixes #<!-- -->22568
---
Full diff: https://github.com/llvm/llvm-project/pull/242929.diff
6 Files Affected:
- (modified) clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp (+15-4)
- (modified) clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp (+22-10)
- (modified) clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h (+3-1)
- (modified) clang-tools-extra/docs/ReleaseNotes.md (+6)
- (modified) clang-tools-extra/docs/clang-tidy/checks/modernize/loop-convert.rst (+3)
- (added) clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-inclusive.cpp (+138)
``````````diff
diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index 75bf2a73259000..62af693a151bc1 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -60,6 +60,7 @@ static constexpr char LoopNameIterator[] = "forLoopIterator";
static constexpr char LoopNameReverseIterator[] = "forLoopReverseIterator";
static constexpr char LoopNamePseudoArray[] = "forLoopPseudoArray";
static constexpr char ConditionBoundName[] = "conditionBound";
+static constexpr char InclusiveConditionName[] = "inclusiveCondition";
static constexpr char InitVarName[] = "initVar";
static constexpr char BeginCallName[] = "beginCall";
static constexpr char EndCallName[] = "endCall";
@@ -120,7 +121,16 @@ static StatementMatcher makeArrayLoopMatcher() {
return forStmt(unless(isInTemplateInstantiation()),
hasLoopInit(declStmt(hasSingleDecl(initToZeroMatcher()))),
- hasCondition(arrayConditionMatcher(ArrayBoundMatcher)),
+ hasCondition(
+ anyOf(arrayConditionMatcher(ArrayBoundMatcher),
+ binaryOperator(
+ anyOf(allOf(hasOperatorName("<="),
+ hasLHS(integerComparisonMatcher()),
+ hasRHS(ArrayBoundMatcher)),
+ allOf(hasOperatorName(">="),
+ hasLHS(ArrayBoundMatcher),
+ hasRHS(integerComparisonMatcher()))))
+ .bind(InclusiveConditionName))),
hasIncrement(
unaryOperator(hasOperatorName("++"),
hasUnaryOperand(incrementVarMatcher()))))
@@ -1061,9 +1071,10 @@ void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) {
if (!ContainerExpr && !BoundExpr)
return;
- ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr,
- BoundExpr,
- Descriptor.ContainerNeedsDereference);
+ ForLoopIndexUseVisitor Finder(
+ Context, LoopVar, EndVar, ContainerExpr, BoundExpr,
+ Descriptor.ContainerNeedsDereference,
+ Nodes.getNodeAs<BinaryOperator>(InclusiveConditionName) != nullptr);
// Find expressions and variables on which the container depends.
if (ContainerExpr) {
diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
index f173de2c52bc0f..85c7ee106cfdfc 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp
@@ -413,7 +413,8 @@ static bool isAliasDecl(const ASTContext *Context, const Decl *TheDecl,
}
/// Determines whether the bound of a for loop condition expression is
-/// the same as the statically computable size of ArrayType.
+/// the same as the statically computable size of ArrayType, or one less for
+/// an inclusive bound.
///
/// Given
/// \code
@@ -424,10 +425,12 @@ static bool isAliasDecl(const ASTContext *Context, const Decl *TheDecl,
/// \code
/// for (int i = 0; i < N; ++i) { /* use arr[i] */ }
/// for (int i = 0; i < arraysize(arr); ++i) { /* use arr[i] */ }
+/// for (int i = 0; i <= N - 1; ++i) { /* use arr[i] */ }
/// \endcode
static bool arrayMatchesBoundExpr(const ASTContext *Context,
const QualType &ArrayType,
- const Expr *ConditionExpr) {
+ const Expr *ConditionExpr, QualType IndexType,
+ bool IsInclusive) {
if (!ConditionExpr || ConditionExpr->isValueDependent())
return false;
const ConstantArrayType *ConstType =
@@ -438,19 +441,27 @@ static bool arrayMatchesBoundExpr(const ASTContext *Context,
ConditionExpr->getIntegerConstantExpr(*Context);
if (!ConditionSize)
return false;
- const llvm::APSInt ArraySize(ConstType->getSize());
+ llvm::APSInt ArraySize(ConstType->getSize());
+ if (IsInclusive) {
+ // The increment after the last element must not overflow the index.
+ const llvm::APSInt MaxIndex = llvm::APSInt::getMaxValue(
+ Context->getIntWidth(IndexType), IndexType->isUnsignedIntegerType());
+ if (ArraySize.isZero() ||
+ llvm::APSInt::compareValues(ArraySize, MaxIndex) > 0)
+ return false;
+ --ArraySize;
+ }
return llvm::APSInt::isSameValue(*ConditionSize, ArraySize);
}
-ForLoopIndexUseVisitor::ForLoopIndexUseVisitor(ASTContext *Context,
- const VarDecl *IndexVar,
- const VarDecl *EndVar,
- const Expr *ContainerExpr,
- const Expr *ArrayBoundExpr,
- bool ContainerNeedsDereference)
+ForLoopIndexUseVisitor::ForLoopIndexUseVisitor(
+ ASTContext *Context, const VarDecl *IndexVar, const VarDecl *EndVar,
+ const Expr *ContainerExpr, const Expr *ArrayBoundExpr,
+ bool ContainerNeedsDereference, bool ArrayBoundIsInclusive)
: Context(Context), IndexVar(IndexVar), EndVar(EndVar),
ContainerExpr(ContainerExpr), ArrayBoundExpr(ArrayBoundExpr),
ContainerNeedsDereference(ContainerNeedsDereference),
+ ArrayBoundIsInclusive(ArrayBoundIsInclusive),
ConfidenceLevel(Confidence::CL_Safe) {
if (ContainerExpr)
@@ -688,7 +699,8 @@ bool ForLoopIndexUseVisitor::TraverseArraySubscriptExpr(ArraySubscriptExpr *E) {
if ((ContainerExpr && !areSameExpr(Context, Arr->IgnoreParenImpCasts(),
ContainerExpr->IgnoreParenImpCasts())) ||
!arrayMatchesBoundExpr(Context, Arr->IgnoreImpCasts()->getType(),
- ArrayBoundExpr)) {
+ ArrayBoundExpr, IndexVar->getType(),
+ ArrayBoundIsInclusive)) {
// If we have already discovered the array being indexed and this isn't it
// or this array doesn't match, mark this loop as unconvertible.
OnlyUsedAsIndex = false;
diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
index 1415af6061783f..0974ab6caa415d 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.h
@@ -284,7 +284,8 @@ class ForLoopIndexUseVisitor
ForLoopIndexUseVisitor(ASTContext *Context, const VarDecl *IndexVar,
const VarDecl *EndVar, const Expr *ContainerExpr,
const Expr *ArrayBoundExpr,
- bool ContainerNeedsDereference);
+ bool ContainerNeedsDereference,
+ bool ArrayBoundIsInclusive);
/// Finds all uses of IndexVar in Body, placing all usages in Usages,
/// and returns true if IndexVar was only used in a way consistent with a
@@ -366,6 +367,7 @@ class ForLoopIndexUseVisitor
/// The Expr which refers to the terminating condition for array-based loops.
const Expr *ArrayBoundExpr;
bool ContainerNeedsDereference;
+ bool ArrayBoundIsInclusive;
// Output member variables:
/// A container which holds all usages of IndexVar as the index of
diff --git a/clang-tools-extra/docs/ReleaseNotes.md b/clang-tools-extra/docs/ReleaseNotes.md
index b6774370511feb..8f91cebd1c75b0 100644
--- a/clang-tools-extra/docs/ReleaseNotes.md
+++ b/clang-tools-extra/docs/ReleaseNotes.md
@@ -305,6 +305,12 @@ infrastructure are described first, followed by tool-specific sections.
nested expressions involving different macros or a mix of macro and
non-macro operands.
+- Improved {doc}`modernize-loop-convert
+ <clang-tidy/checks/modernize/loop-convert>` to recognize inclusive bounds
+ such as `i <= N - 1` and `N - 1 >= i` when iterating over an array of
+ `N` elements.
+ Fixes [#22568](https://github.com/llvm/llvm-project/issues/22568).
+
- Fixed false positive in {doc}`modernize-make-unique
<clang-tidy/checks/modernize/make-unique>` in presence of private, protected
or deleted destructor.
diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/loop-convert.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/loop-convert.rst
index 87790db99f4c7d..3042e3f251a9c2 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/modernize/loop-convert.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/loop-convert.rst
@@ -12,6 +12,9 @@ Three kinds of loops can be converted:
- Loops over containers, using iterators.
- Loops over array-like containers, using ``operator[]`` and ``at()``.
+For statically allocated arrays, the check also recognizes inclusive bounds
+such as ``i <= N - 1`` and ``N - 1 >= i``, where ``N`` is the array size.
+
MinConfidence option
--------------------
diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-inclusive.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-inclusive.cpp
new file mode 100644
index 00000000000000..852231b1877fad
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-inclusive.cpp
@@ -0,0 +1,138 @@
+// RUN: %check_clang_tidy %s modernize-loop-convert %t -- -- -I %S/Inputs/loop-convert
+
+#include "structures.h"
+
+void inclusiveArrays() {
+ static int ImplicitSize[] = {1, 0};
+ for (int I = 0; I <= 1; ++I) {
+ --ImplicitSize[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead [modernize-loop-convert]
+ // CHECK-FIXES: for (int & I : ImplicitSize) {
+ // CHECK-FIXES-NEXT: --I;
+
+ const int N = 6;
+ int Arr[N];
+ for (int I = 0; I <= N - 1; ++I) {
+ ++Arr[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead
+ // CHECK-FIXES: for (int & I : Arr) {
+ // CHECK-FIXES-NEXT: ++I;
+
+ const int Last = N - 1;
+ for (int I = 0; Last >= I; ++I) {
+ ++Arr[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead
+ // CHECK-FIXES: for (int & I : Arr) {
+ // CHECK-FIXES-NEXT: ++I;
+
+ for (unsigned I = 0; I <= sizeof(Arr) / sizeof(Arr[0]) - 1; ++I) {
+ ++Arr[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead
+ // CHECK-FIXES: for (int & I : Arr) {
+ // CHECK-FIXES-NEXT: ++I;
+
+ for (unsigned I = 0; 5ULL >= I; ++I) {
+ ++Arr[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead
+ // CHECK-FIXES: for (int & I : Arr) {
+ // CHECK-FIXES-NEXT: ++I;
+
+ int Single[1];
+ for (int I = 0; I <= 0; ++I) {
+ ++Single[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead
+ // CHECK-FIXES: for (int & I : Single) {
+ // CHECK-FIXES-NEXT: ++I;
+
+ // The increment after the final iteration still fits in the index type.
+ int Small[__SCHAR_MAX__];
+ for (signed char I = 0; I <= __SCHAR_MAX__ - 1; ++I) {
+ ++Small[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead
+ // CHECK-FIXES: for (int & I : Small) {
+ // CHECK-FIXES-NEXT: ++I;
+
+ for (unsigned char I = 0; I <= __SCHAR_MAX__ - 1; ++I) {
+ ++Small[I];
+ }
+ // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: use range-based for loop instead
+ // CHECK-FIXES: for (int & I : Small) {
+ // CHECK-FIXES-NEXT: ++I;
+}
+
+void invalidBounds(int Last) {
+ int Arr[6];
+ for (int I = 0; I <= 6; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 0; I <= 6; ++I)
+
+ for (int I = 0; 6 >= I; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 0; 6 >= I; ++I)
+
+ for (int I = 0; I <= 4; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 0; I <= 4; ++I)
+
+ for (int I = 0; 4 >= I; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 0; 4 >= I; ++I)
+
+ for (int I = 0; I <= -1; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 0; I <= -1; ++I)
+
+ for (unsigned I = 0; I <= ~0U; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (unsigned I = 0; I <= ~0U; ++I)
+
+ for (int I = 0; I <= Last; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 0; I <= Last; ++I)
+
+ for (int I = 1; I <= 5; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 1; I <= 5; ++I)
+
+ for (int I = 0; I <= 5; ++I)
+ Arr[I] += I;
+ // CHECK-FIXES: for (int I = 0; I <= 5; ++I)
+
+ // Incrementing the final index would overflow or wrap.
+ int Signed[__SCHAR_MAX__ + 1];
+ for (signed char I = 0; I <= __SCHAR_MAX__; ++I)
+ ++Signed[I];
+ // CHECK-FIXES: for (signed char I = 0; I <= __SCHAR_MAX__; ++I)
+
+ int Unsigned[__SCHAR_MAX__ * 2 + 2];
+ for (unsigned char I = 0; I <= __SCHAR_MAX__ * 2 + 1; ++I)
+ ++Unsigned[I];
+ // CHECK-FIXES: for (unsigned char I = 0; I <= __SCHAR_MAX__ * 2 + 1; ++I)
+
+ int Empty[0];
+ for (unsigned long long I = 0; I <= ~0ULL; ++I)
+ ++Empty[I];
+ // CHECK-FIXES: for (unsigned long long I = 0; I <= ~0ULL; ++I)
+}
+
+void inclusiveContainer() {
+ dependent<int> Ss;
+ for (int I = 0; I <= Ss.size(); ++I)
+ ++Ss[I];
+ // CHECK-FIXES: for (int I = 0; I <= Ss.size(); ++I)
+}
+
+template <int N>
+void dependentBound() {
+ int Arr[N];
+ for (int I = 0; I <= N - 1; ++I)
+ ++Arr[I];
+ // CHECK-FIXES: for (int I = 0; I <= N - 1; ++I)
+}
``````````
</details>
https://github.com/llvm/llvm-project/pull/242929
More information about the cfe-commits
mailing list