ahatanak created this revision.
ahatanak added a subscriber: cfe-commits.

Issue a warning if an initializing integer expression overflows.

For example, clang should issue a warning when compiling the following code 
because 4 * 1024 * 1024 * 1024 doesn't fit into a 32-bit integer:

struct s {
unsigned x;
} s = {
 .x = 4 * 1024 * 1024 * 1024
};

http://reviews.llvm.org/D15097

Files:
  lib/Sema/SemaChecking.cpp
  test/Sema/integer-overflow.c

Index: test/Sema/integer-overflow.c
===================================================================
--- test/Sema/integer-overflow.c
+++ test/Sema/integer-overflow.c
@@ -145,3 +145,11 @@
 // expected-warning@+1 2{{overflow in expression; result is 536870912 with 
type 'int'}}
   return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
 }
+
+struct s {
+  unsigned x;
+  unsigned y;
+} s = {
+  .y = 5,
+  .x = 4 * 1024 * 1024 * 1024  // expected-warning {{overflow in expression; 
result is 0 with type 'int'}}
+};
Index: lib/Sema/SemaChecking.cpp
===================================================================
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -7817,6 +7817,10 @@
 void Sema::CheckForIntOverflow (Expr *E) {
   if (isa<BinaryOperator>(E->IgnoreParenCasts()))
     E->IgnoreParenCasts()->EvaluateForOverflow(Context);
+  else if (auto InitList = dyn_cast<InitListExpr>(E))
+    for (Expr *E : InitList->inits())
+      if (isa<BinaryOperator>(E->IgnoreParenCasts()))
+        E->IgnoreParenCasts()->EvaluateForOverflow(Context);
 }
 
 namespace {


Index: test/Sema/integer-overflow.c
===================================================================
--- test/Sema/integer-overflow.c
+++ test/Sema/integer-overflow.c
@@ -145,3 +145,11 @@
 // expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
   return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
 }
+
+struct s {
+  unsigned x;
+  unsigned y;
+} s = {
+  .y = 5,
+  .x = 4 * 1024 * 1024 * 1024  // expected-warning {{overflow in expression; result is 0 with type 'int'}}
+};
Index: lib/Sema/SemaChecking.cpp
===================================================================
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -7817,6 +7817,10 @@
 void Sema::CheckForIntOverflow (Expr *E) {
   if (isa<BinaryOperator>(E->IgnoreParenCasts()))
     E->IgnoreParenCasts()->EvaluateForOverflow(Context);
+  else if (auto InitList = dyn_cast<InitListExpr>(E))
+    for (Expr *E : InitList->inits())
+      if (isa<BinaryOperator>(E->IgnoreParenCasts()))
+        E->IgnoreParenCasts()->EvaluateForOverflow(Context);
 }
 
 namespace {
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to