[PATCH] Fix UB in expmed.c (PR middle-end/61903)

Marek Polacek polacek@redhat.com
Mon Aug 25 19:21:00 GMT 2014


The following ought to fix two spots where an undefined behavior
can occur when compiling pr28045.c with instrumented compiler.
It does so by changing the type of V to an unsigned HOST_WIDE_INT
and performing the shift on unsigned HOST_WIDE_INT.
Hopefully it doesn't break anything...

Bootstrapped/regtested on x86_64-linux, ok for trunk?

2014-08-25  Marek Polacek  <polacek@redhat.com>

	PR middle-end/61903
	* expmed.c (store_fixed_bit_field_1): Shift UHWI 1 instead of HWI 1.
	Change the type of V to unsigned HOST_WIDE_INT.

diff --git gcc/expmed.c gcc/expmed.c
index 7b71616a2..e8d5c23 100644
--- gcc/expmed.c
+++ gcc/expmed.c
@@ -1051,16 +1051,17 @@ store_fixed_bit_field_1 (rtx op0, unsigned HOST_WIDE_INT bitsize,
 
   if (CONST_INT_P (value))
     {
-      HOST_WIDE_INT v = INTVAL (value);
+      unsigned HOST_WIDE_INT v = UINTVAL (value);
 
       if (bitsize < HOST_BITS_PER_WIDE_INT)
-	v &= ((HOST_WIDE_INT) 1 << bitsize) - 1;
+	v &= ((unsigned HOST_WIDE_INT) 1 << bitsize) - 1;
 
       if (v == 0)
 	all_zero = 1;
       else if ((bitsize < HOST_BITS_PER_WIDE_INT
-		&& v == ((HOST_WIDE_INT) 1 << bitsize) - 1)
-	       || (bitsize == HOST_BITS_PER_WIDE_INT && v == -1))
+		&& v == ((unsigned HOST_WIDE_INT) 1 << bitsize) - 1)
+	       || (bitsize == HOST_BITS_PER_WIDE_INT
+		   && v == (unsigned HOST_WIDE_INT) -1))
 	all_one = 1;
 
       value = lshift_value (mode, v, bitnum);

	Marek



More information about the Gcc-patches mailing list