[clang-tidy] Fix minor bug in bugprone-too-small-loop-variable
authorPiotr Zegar <me@piotrzegar.pl>
Sat, 18 Mar 2023 10:44:11 +0000 (10:44 +0000)
committerPiotr Zegar <me@piotrzegar.pl>
Sat, 18 Mar 2023 10:44:13 +0000 (10:44 +0000)
Correct issue when incorrectly matched bitfield loop
variable would still be considered valid and equal to
base type, because check didnt compare size of bitfield.

Fixes issue introduced in: D142587

Reviewed By: carlosgalvezp

Differential Revision: https://reviews.llvm.org/D145958

clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/bugprone/too-small-loop-variable.cpp

index 133fcab..8ba8b89 100644 (file)
@@ -34,6 +34,11 @@ struct MagnitudeBits {
   bool operator<(const MagnitudeBits &Other) const noexcept {
     return WidthWithoutSignBit < Other.WidthWithoutSignBit;
   }
+
+  bool operator!=(const MagnitudeBits &Other) const noexcept {
+    return WidthWithoutSignBit != Other.WidthWithoutSignBit ||
+           BitFieldWidth != Other.BitFieldWidth;
+  }
 };
 
 } // namespace
@@ -184,13 +189,19 @@ void TooSmallLoopVariableCheck::check(const MatchFinder::MatchResult &Result) {
   if (LoopVar->getType() != LoopIncrement->getType())
     return;
 
-  const QualType LoopVarType = LoopVar->getType();
-  const QualType UpperBoundType = UpperBound->getType();
-
   ASTContext &Context = *Result.Context;
 
+  const QualType LoopVarType = LoopVar->getType();
   const MagnitudeBits LoopVarMagnitudeBits =
       calcMagnitudeBits(Context, LoopVarType, LoopVar);
+
+  const MagnitudeBits LoopIncrementMagnitudeBits =
+      calcMagnitudeBits(Context, LoopIncrement->getType(), LoopIncrement);
+  // We matched the loop variable incorrectly.
+  if (LoopIncrementMagnitudeBits != LoopVarMagnitudeBits)
+    return;
+
+  const QualType UpperBoundType = UpperBound->getType();
   const MagnitudeBits UpperBoundMagnitudeBits =
       calcUpperBoundMagnitudeBits(Context, UpperBound, UpperBoundType);
 
index 1505dbf..7821c41 100644 (file)
@@ -373,3 +373,20 @@ void badForLoopWithBitfieldOnLoopVarAndUpperBoundOnPtr() {
   }
 }
 
+void goodForLoopWithBitfieldOnUpperBoundOnly() {
+  struct S {
+    int x : 4;
+  } s;
+
+  for (int i = 10; i > s.x; --i) {
+  }
+}
+
+void goodForLoopWithIntegersOnUpperBoundOnly() {
+  struct S {
+    short x;
+  } s;
+
+  for (int i = 10; i > s.x; --i) {
+  }
+}