minmax: simplify and clarify min_t()/max_t() implementation

This simplifies the min_t() and max_t() macros by no longer making them
work in the context of a C constant expression.

That means that you can no longer use them for static initializers or
for array sizes in type definitions, but there were only a couple of
such uses, and all of them were converted (famous last words) to use
MIN_T/MAX_T instead.

Cc: David Laight <David.Laight@aculab.com>
Cc: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
This commit is contained in:
Linus Torvalds 2024-07-28 13:50:01 -07:00
parent 4477b39c32
commit 017fa3e891

View File

@ -45,17 +45,20 @@
#define __cmp(op, x, y) ((x) __cmp_op_##op (y) ? (x) : (y)) #define __cmp(op, x, y) ((x) __cmp_op_##op (y) ? (x) : (y))
#define __cmp_once(op, x, y, unique_x, unique_y) ({ \ #define __cmp_once_unique(op, type, x, y, ux, uy) \
typeof(x) unique_x = (x); \ ({ type ux = (x); type uy = (y); __cmp(op, ux, uy); })
typeof(y) unique_y = (y); \
#define __cmp_once(op, type, x, y) \
__cmp_once_unique(op, type, x, y, __UNIQUE_ID(x_), __UNIQUE_ID(y_))
#define __careful_cmp_once(op, x, y) ({ \
static_assert(__types_ok(x, y), \ static_assert(__types_ok(x, y), \
#op "(" #x ", " #y ") signedness error, fix types or consider u" #op "() before " #op "_t()"); \ #op "(" #x ", " #y ") signedness error, fix types or consider u" #op "() before " #op "_t()"); \
__cmp(op, unique_x, unique_y); }) __cmp_once(op, __auto_type, x, y); })
#define __careful_cmp(op, x, y) \ #define __careful_cmp(op, x, y) \
__builtin_choose_expr(__is_constexpr((x) - (y)), \ __builtin_choose_expr(__is_constexpr((x) - (y)), \
__cmp(op, x, y), \ __cmp(op, x, y), __careful_cmp_once(op, x, y))
__cmp_once(op, x, y, __UNIQUE_ID(__x), __UNIQUE_ID(__y)))
#define __clamp(val, lo, hi) \ #define __clamp(val, lo, hi) \
((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val))) ((val) >= (hi) ? (hi) : ((val) <= (lo) ? (lo) : (val)))
@ -158,7 +161,7 @@
* @x: first value * @x: first value
* @y: second value * @y: second value
*/ */
#define min_t(type, x, y) __careful_cmp(min, (type)(x), (type)(y)) #define min_t(type, x, y) __cmp_once(min, type, x, y)
/** /**
* max_t - return maximum of two values, using the specified type * max_t - return maximum of two values, using the specified type
@ -166,7 +169,7 @@
* @x: first value * @x: first value
* @y: second value * @y: second value
*/ */
#define max_t(type, x, y) __careful_cmp(max, (type)(x), (type)(y)) #define max_t(type, x, y) __cmp_once(max, type, x, y)
/* /*
* Do not check the array parameter using __must_be_array(). * Do not check the array parameter using __must_be_array().