https://gcc.gnu.org/bugzilla/show_bug.cgi?id=126294

--- Comment #4 from GCC Commits <cvs-commit at gcc dot gnu.org> ---
The master branch has been updated by Jeff Law <[email protected]>:

https://gcc.gnu.org/g:0333a956e3f953cfc8796d41948fecced4264eed

commit r17-6644-g0333a956e3f953cfc8796d41948fecced4264eed
Author: Shivam Gupta <[email protected]>
Date:   Tue Nov 24 10:53:24 2026 -0700

    [PATCH v4] match.pd: Simplify (t * (C + 1)) / C to t + t / C [PR126294]

    Simplify (t * (C + 1)) / C to t + t / C for signed and unsigned types
    when the multiplication does not overflow, either because signed
    overflow is undefined or because value ranges prove it.  Unsigned
    division by a power of two has already become a right shift when
    ranges are available, so also simplify (t * (2^k + 1)) >> k to
    t + (t >> k) for unsigned types under the same range condition.

    Both transformations require the multiplication to have a single use,
    since otherwise it is kept and the result needs an extra operation.

    For exact_div only, also simplify (t * (C - 1)) / C to t - t / C.  For
    trunc_div the result is t - ceil (t / C), which differs unless C
    divides t.  exact_div cannot be produced from C source and the GIMPLE
    front end cannot express it, so this case has no testcase.

    Changes since v3:
     * Compare the shift count using wi::to_widest so a narrow or negative
       count cannot pass the bounds check. Addressed sashiko review comment.

    Changes since v2:
     * Compare the constants using the sign of the type, so unsigned
       divisors with the most significant bit set are not rejected.
     * Allow the division transformation without range information when
       signed overflow is undefined and not sanitized, matching the
       (t * u) / v pattern above, instead of requiring a known range.
     * Require a single use of the multiplication: single_use for the
       division arm, which shares its match expression with the
       (t * u) / v pattern, and :s for the shift pattern.
     * Add tests for the above, including -fwrapv.

    Changes since v1:
     * Add a comment explaining the !vr0.varying_p () check.
     * Restrict the (t * (2^k + 1)) >> k pattern to unsigned types.

    Bootstrapped and regtested on x86_64-linux-gnu.

            PR tree-optimization/126294

    gcc/ChangeLog:

            * match.pd: Simplify (t * (C + 1)) / C to t + t / C and, for
            exact_div, (t * (C - 1)) / C to t - t / C, and
            (t * (2^k + 1)) >> k to t + (t >> k), when the multiplication
            has a single use and does not overflow.

    gcc/testsuite/ChangeLog:

            * gcc.dg/tree-ssa/pr126294.c: New test.
            * gcc.dg/tree-ssa/pr126294-2.c: New test.

    Signed-off-by: Shivam Gupta <[email protected]>

Reply via email to