From c03c83152d6ce6fa5ae49a8698da5fc25a53127f Mon Sep 17 00:00:00 2001 From: Erik Faye-Lund Date: Tue, 5 Oct 2010 09:24:10 +0200 Subject: do not depend on signed integer overflow Signed integer overflow is not defined in C, so do not depend on it. This fixes a problem with GCC 4.4.0 and -O3 where the optimizer would consider "consumed_bytes > consumed_bytes + bytes" as a constant expression, and never execute the die()-call. Signed-off-by: Erik Faye-Lund Acked-by: Nicolas Pitre Signed-off-by: Junio C Hamano --- git-compat-util.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'git-compat-util.h') diff --git a/git-compat-util.h b/git-compat-util.h index 81883e7270..2af8d3edbe 100644 --- a/git-compat-util.h +++ b/git-compat-util.h @@ -28,6 +28,18 @@ #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) #define bitsizeof(x) (CHAR_BIT * sizeof(x)) +#define maximum_signed_value_of_type(a) \ + (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a))) + +/* + * Signed integer overflow is undefined in C, so here's a helper macro + * to detect if the sum of two integers will overflow. + * + * Requires: a >= 0, typeof(a) equals typeof(b) + */ +#define signed_add_overflows(a, b) \ + ((b) > maximum_signed_value_of_type(a) - (a)) + #ifdef __GNUC__ #define TYPEOF(x) (__typeof__(x)) #else -- cgit v1.2.3