[PATCH] D121715: [Clang] Fix an unused-but-set-variable warning with compond assignment

Yonghong Song via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Tue Mar 15 09:46:00 PDT 2022


yonghong-song created this revision.
yonghong-song added a reviewer: eli.friedman.
Herald added a project: All.
yonghong-song requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

For the following code,

  void test() {
      int j = 0;
      for (int i = 0; i < 1000; i++)
              j += 1;
      return;
  } 

If compiled with

  clang -g -Wall -Werror -S -emit-llvm test.c

we will see the following error:

  test.c:2:6: error: variable 'j' set but not used [-Werror,-Wunused-but-set-variable]
          int j = 0;
              ^   

This is not quite right since 'j' is indeed used due to '+=' operator.
gcc doesn't emit error either in this case.
Also if we change 'j += 1' to 'j++', the warning will disappear too 
with latest clang.

Our original use case is to use 'volatile int j = 0' with a loop like
in the above to burn cpu cycles so we could test certain kernel features.
The compilatin error will show up regardless of whether 'volatile' key 
word is used or not.

To fix the issue, in function MaybeDecrementCount(), if the 
operator is a compund assignment (i.e., +=, -=, etc.), we should
not decrement count for RefsMinusAssignments since here we have
both a reference and an assignment.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121715

Files:
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/Sema/warn-unused-but-set-variables.c


Index: clang/test/Sema/warn-unused-but-set-variables.c
===================================================================
--- clang/test/Sema/warn-unused-but-set-variables.c
+++ clang/test/Sema/warn-unused-but-set-variables.c
@@ -59,3 +59,10 @@
   __attribute__((__cleanup__(for_cleanup))) int x;
   x = 5;
 }
+
+void f4() {
+  int j = 0;
+  for (int i = 0; i < 1000; i++)
+    j += 1;
+  return;
+}
Index: clang/lib/Sema/SemaExprCXX.cpp
===================================================================
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -7927,7 +7927,7 @@
         BO->getRHS()->getType()->isDependentType()) {
       if (BO->getOpcode() != BO_Assign)
         return;
-    } else if (!BO->isAssignmentOp())
+    } else if (!BO->isAssignmentOp() || BO->isCompoundAssignmentOp())
       return;
     LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
   } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D121715.415479.patch
Type: text/x-patch
Size: 963 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20220315/7e0a4199/attachment.bin>


More information about the cfe-commits mailing list