[PATCH] D38678: [Sema] Warn about unused variables if we can constant evaluate the initializer.

Benjamin Kramer via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Sun Oct 8 15:34:01 PDT 2017


bkramer created this revision.

If the variable construction can be constant evaluated it doesn't have
side effects, so removing it is always safe. We only try to evaluate
variables that are unused, there should be no impact on compile time.


https://reviews.llvm.org/D38678

Files:
  lib/Sema/SemaDecl.cpp
  test/SemaCXX/warn-unused-variables.cpp


Index: test/SemaCXX/warn-unused-variables.cpp
===================================================================
--- test/SemaCXX/warn-unused-variables.cpp
+++ test/SemaCXX/warn-unused-variables.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label -Wno-c++1y-extensions -verify %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label -Wno-c++1y-extensions -verify -std=c++11 %s
 template<typename T> void f() {
   T t;
   t = 17;
@@ -194,3 +195,35 @@
 }
 
 }
+
+#if __cplusplus >= 201103L
+namespace with_constexpr {
+template <typename T>
+struct Literal {
+  T i;
+  Literal() = default;
+  constexpr Literal(T i) : i(i) {}
+};
+
+struct NoLiteral {
+  int i;
+  NoLiteral() = default;
+  constexpr NoLiteral(int i) : i(i) {}
+  ~NoLiteral() {}
+};
+
+static Literal<int> gl1;          // expected-warning {{unused variable 'gl1'}}
+static Literal<int> gl2(1);       // expected-warning {{unused variable 'gl2'}}
+static const Literal<int> gl3(0); // expected-warning {{unused variable 'gl3'}}
+
+template <typename T>
+void test(int i) {
+  Literal<int> l1;     // expected-warning {{unused variable 'l1'}}
+  Literal<int> l2(42); // expected-warning {{unused variable 'l2'}}
+  Literal<int> l3(i);  // no-warning
+  Literal<T> l4(0);    // no-warning
+  NoLiteral nl1;       // no-warning
+  NoLiteral nl2(42);   // no-warning
+}
+}
+#endif
Index: lib/Sema/SemaDecl.cpp
===================================================================
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -1683,7 +1683,8 @@
             dyn_cast<CXXConstructExpr>(Init);
           if (Construct && !Construct->isElidable()) {
             CXXConstructorDecl *CD = Construct->getConstructor();
-            if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
+            if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
+                !VD->evaluateValue())
               return false;
           }
         }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D38678.118175.patch
Type: text/x-patch
Size: 1967 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20171008/e306352b/attachment.bin>


More information about the cfe-commits mailing list