On Mon, Nov 09, 2026 at 05:36:01PM +0100, [email protected] wrote:
> From: Kyrylo Tkachov <[email protected]>
>
> expand_CLMUL_WIDEN takes a shortcut when the whole product fits in the
> mode of the operands and stores zero as the high half. The test
> compares against the precision of the mode. For an unsigned _BitInt
> narrower than its mode the bits of the product above the precision of
> the type are the high half, so the shortcut returns zero where it
> should not. Operands of known small range hit the same path.
>
> For example, with unsigned _BitInt(3) a = 7 and b = 7:
>
> unsigned _BitInt(3) hi;
> unsigned _BitInt(3) lo = __builtin_clmulg (a, b, &hi);
>
> the product is 0b10101, so lo is 0b101 and hi is 0b10. The expansion
> returned hi == 0.
>
> Compute the high half as the product shifted right by the precision of
> the type when the product needs more bits than the type has.
Thanks for figuring this out.
> --- a/gcc/internal-fn.cc
> +++ b/gcc/internal-fn.cc
> @@ -6361,13 +6361,19 @@ expand_CLMUL_WIDEN (internal_fn, gcall *stmt)
> bitint_mask
> = immed_wide_int_const (wi::mask (TYPE_PRECISION (TREE_TYPE (arg0)),
> false, prec), mode);
> + unsigned int type_prec = TYPE_PRECISION (TREE_TYPE (arg0));
When you add this, I'd prefer to move it above the if guarding
initialization of bitint_mask above and replace all uses of
TYPE_PRECISION (TREE_TYPE (arg0)) with type_prec. There are 6 other
uses in the function.
> if (prec0 + prec1 - 1 <= prec)
> {
> + /* The whole product fits in MODE. For a type narrower than MODE
> + the bits above its precision are the high half. */
> rtx res = expand_clmul (mode, mode, op0, op1, prec0, prec1);
And rename res to reslo in that case in this block and adjust all uses.
> + rtx reshi = const0_rtx;
> + if (prec0 + prec1 - 1 > type_prec)
> + reshi = expand_shift (RSHIFT_EXPR, mode, res, type_prec, NULL_RTX, 1);
> if (bitint_mask)
> res = expand_and (mode, res, bitint_mask, NULL_RTX);
> write_complex_part (target, res, false, true);
> - write_complex_part (target, const0_rtx, true, false);
> + write_complex_part (target, reshi, true, false);
> return;
> }
> if (optab_handler (clmul_widen_optab, mode) != CODE_FOR_nothing
LGTM with those nits tweaked.
Jakub