diff --git a/gcc/gimple-lower-bitint.cc b/gcc/gimple-lower-bitint.cc index 6de869fa81c..01346f17ca7 100644 --- a/gcc/gimple-lower-bitint.cc +++ b/gcc/gimple-lower-bitint.cc @@ -3911,15 +3911,18 @@ bitint_large_huge::lower_addsub_overflow (tree obj, gimple *stmt) tree type0 = TREE_TYPE (arg0); tree type1 = TREE_TYPE (arg1); - if (TYPE_PRECISION (type0) < prec3) + int prec5 = prec3; + if (bitint_precision_kind (prec5) < bitint_prec_large) + prec5 = MAX (TYPE_PRECISION (type0), TYPE_PRECISION (type1)); + if (TYPE_PRECISION (type0) < prec5) { - type0 = build_bitint_type (prec3, TYPE_UNSIGNED (type0)); + type0 = build_bitint_type (prec5, TYPE_UNSIGNED (type0)); if (TREE_CODE (arg0) == INTEGER_CST) arg0 = fold_convert (type0, arg0); } - if (TYPE_PRECISION (type1) < prec3) + if (TYPE_PRECISION (type1) < prec5) { - type1 = build_bitint_type (prec3, TYPE_UNSIGNED (type1)); + type1 = build_bitint_type (prec5, TYPE_UNSIGNED (type1)); if (TREE_CODE (arg1) == INTEGER_CST) arg1 = fold_convert (type1, arg1); } diff --git a/gcc/testsuite/gcc.dg/bitint-46.c b/gcc/testsuite/gcc.dg/bitint-46.c new file mode 100644 index 00000000000..4e503376d7f --- /dev/null +++ b/gcc/testsuite/gcc.dg/bitint-46.c @@ -0,0 +1,32 @@ +/* PR middle-end/112807 */ +/* { dg-do compile { target bitint } } */ +/* { dg-options "-std=gnu23 -O2" } */ + +#if __BITINT_MAXWIDTH__ >= 256 +__attribute__((noipa)) int +foo (_BitInt (256) a, _BitInt (2) b) +{ + if (a < 0 || a > ~0U) + return -1; + return __builtin_sub_overflow_p (a, b, 0); +} +#endif + +int +main () +{ +#if __BITINT_MAXWIDTH__ >= 256 + if (foo (-5wb, 1wb) != -1 + || foo (1 + (_BitInt (256)) ~0U, -2) != -1 + || foo (0, 0) != 0 + || foo (0, 1) != 0 + || foo (0, -1) != 0 + || foo (~0U, 0) != 1 + || foo (__INT_MAX__, 0) != 0 + || foo (__INT_MAX__, -1) != 1 + || foo (1 + (_BitInt (256)) __INT_MAX__, 0) != 1 + || foo (1 + (_BitInt (256)) __INT_MAX__, 1) != 0 + || foo (1 + (_BitInt (256)) __INT_MAX__, -2) != 1) + __builtin_abort (); +#endif +}