Hi,

Apple has added a -Wshorten-64-to-32 option to GCC. It generates a
warning if a value is implicitly converted from a 64-bit to a 32-bit
type. I found it useful, looked at the code and ported it to OpenBSD.

I don't think this is worth integrating. Use at your own discretion. :)

-p.

Index: gcc/gcc/c-common.c
===================================================================
RCS file: /cvs/src/gnu/gcc/gcc/c-common.c,v
retrieving revision 1.4
diff -u -p -r1.4 c-common.c
--- gcc/gcc/c-common.c  15 Sep 2011 12:19:12 -0000      1.4
+++ gcc/gcc/c-common.c  3 Apr 2013 12:38:19 -0000
@@ -552,6 +552,8 @@ static bool nonnull_check_p (tree, unsig
 static bool get_nonnull_operand (tree, unsigned HOST_WIDE_INT *);
 static int resort_field_decl_cmp (const void *, const void *);
+static void warnings_for_convert_and_check (tree, tree, tree);
+
 /* Table of machine-independent attributes common to all C-like languages.  */
 const struct attribute_spec c_common_attribute_table[] =
 {
@@ -1073,6 +1075,26 @@ vector_types_convertible_p (tree t1, tre
                == INTEGRAL_TYPE_P (TREE_TYPE (t2)));
 }
+void
+warnings_for_convert_and_check (tree type, tree expr, tree result 
ATTRIBUTE_UNUSED)
+{
+  if (warn_shorten_64_to_32
+      && TYPE_PRECISION (TREE_TYPE (expr)) == 64
+      && TYPE_PRECISION (type) == 32)
+     {
+       /* As a special case, don't warn when we are working with small
+         constants as the enum forming code shortens them into smaller
+         types.  */
+       if (TREE_CODE (expr) == INTEGER_CST)
+        {
+          bool unsignedp = tree_int_cst_sgn (expr) >= 0;
+          if (min_precision (expr, unsignedp) <= TYPE_PRECISION (type))
+            return;
+        }
+       warning (0, "implicit conversion shortens 64-bit value into a 32-bit 
value");
+     }
+}
+
 /* Convert EXPR to TYPE, warning about conversion problems with constants.
    Invoke this function on every expression that is converted implicitly,
    i.e. because of language rules and not because of an explicit cast.  */
@@ -1109,6 +1131,8 @@ convert_and_check (tree type, tree expr)
       else
        unsigned_conversion_warning (t, expr);
     }
+  if (!skip_evaluation && !TREE_OVERFLOW (expr) && t != error_mark_node)
+    warnings_for_convert_and_check (type, expr, t);
   return t;
 }
 
Index: gcc/gcc/c.opt
===================================================================
RCS file: /cvs/src/gnu/gcc/gcc/c.opt,v
retrieving revision 1.4
diff -u -p -r1.4 c.opt
--- gcc/gcc/c.opt       15 Sep 2011 12:19:12 -0000      1.4
+++ gcc/gcc/c.opt       3 Apr 2013 12:38:19 -0000
@@ -161,6 +161,10 @@ Wconversion
 C ObjC C++ ObjC++ Var(warn_conversion)
 Warn about possibly confusing type conversions
+Wshorten-64-to-32
+C Var(warn_shorten_64_to_32)
+Warn if a value is implicitly converted from a 64-bit to a 32-bit type
+
 Wctor-dtor-privacy
 C++ ObjC++ Var(warn_ctor_dtor_privacy)
 Warn when all constructors and destructors are private

Reply via email to