From da57fbfb0742fcb0a9911d248fb9091ffd87d8bc Mon Sep 17 00:00:00 2001 From: Caio Oliveira Date: Thu, 5 Mar 2026 11:07:56 -0800 Subject: [PATCH] nir: Fix constant folding for iadd_sat Use INT_MIN instead of INT_MAX for underflow. Fixes: cc4b50b023c ("nir/opcodes: use u_overflow to fix incorrect checks") Reviewed-by: Ian Romanick Reviewed-by: Pierre-Eric Pelloux-Prayer Part-of: --- src/compiler/nir/nir_opcodes.py | 2 +- src/compiler/nir/nir_opt_algebraic.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/compiler/nir/nir_opcodes.py b/src/compiler/nir/nir_opcodes.py index b1d71828f3c..32572541de6 100644 --- a/src/compiler/nir/nir_opcodes.py +++ b/src/compiler/nir/nir_opcodes.py @@ -729,7 +729,7 @@ if (nir_is_rounding_mode_rtz(execution_mode, bit_size)) { binop("iadd", tint, _2src_commutative + associative, "(uint64_t)src0 + (uint64_t)src1") binop("iadd_sat", tint, _2src_commutative, """ util_add_check_overflow({dest_type}, src0, src1) ? - (src1 < 0 ? u_intN_max(bit_size) : u_uintN_max(bit_size)) : (src0 + src1) + (src1 < 0 ? u_intN_min(bit_size) : u_intN_max(bit_size)) : (src0 + src1) """, "", True) binop("uadd_sat", tuint, _2src_commutative, "util_add_check_overflow({dest_type}, src0, src1) ? u_uintN_max(sizeof(src0) * 8) : (src0 + src1)", diff --git a/src/compiler/nir/nir_opt_algebraic.py b/src/compiler/nir/nir_opt_algebraic.py index 0d71c3229b3..983467f66f4 100644 --- a/src/compiler/nir/nir_opt_algebraic.py +++ b/src/compiler/nir/nir_opt_algebraic.py @@ -2460,7 +2460,7 @@ optimizations.extend([ ('ior', ('ior', ('ilt', a, 0), ('ilt', b, 0)), ('ige', ('iadd', a, b), 0)), ('iadd', a, b), 0x7fffffffffffffff)), - '(options->lower_int64_options & nir_lower_iadd_sat64) != 0', TestStatus.XFAIL), + '(options->lower_int64_options & nir_lower_iadd_sat64) != 0'), # int64_t sum = a - b; # @@ -2867,7 +2867,7 @@ for bit_size in [8, 16, 32, 64]: optimizations += [ (('iadd_sat@' + str(bit_size), a, b), ('bcsel', ('ige', b, 1), ('bcsel', ('ilt', ('iadd', a, b), a), intmax, ('iadd', a, b)), - ('bcsel', ('ilt', a, ('iadd', a, b)), intmin, ('iadd', a, b))), 'options->lower_iadd_sat', TestStatus.XFAIL if bit_size in [8, 64] else TestStatus.PASS), + ('bcsel', ('ilt', a, ('iadd', a, b)), intmin, ('iadd', a, b))), 'options->lower_iadd_sat'), (('isub_sat@' + str(bit_size), a, b), ('bcsel', ('ilt', b, 0), ('bcsel', ('ilt', ('isub', a, b), a), intmax, ('isub', a, b)), ('bcsel', ('ilt', a, ('isub', a, b)), intmin, ('isub', a, b))), 'options->lower_iadd_sat'),