Skip to content

[mypyc] Multiply short ints with negative operands inline - #22454

Open
rheard wants to merge 1 commit into
python:masterfrom
rheard:fix-mypyc-1254
Open

rheard wants to merge 1 commit into
python:masterfrom
rheard:fix-mypyc-1254

Conversation

@rheard

@rheard rheard commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Fixes mypyc/mypyc#1254.

CPyTagged_IsMultiplyOverflow() compared the tagged operands with unsigned comparisons, so every negative short int looked too big. x * y with a negative operand always boxed both operands and called PyNumber_Multiply(), which is more than 10 times slower than the inline multiplication.

Now each tagged operand has to fit in a signed integer of half the width of CPyTagged (int32_t on 64-bit platforms, int16_t on 32-bit ones), checked with a round trip through that type. Non-negative operands have the same limit as before, and negative operands get the same magnitudes. For two such operands the tagged product 2a * b has |2ab| <= 2**(N-3), where N is the number of bits in CPyTagged, so it can't overflow and it's a valid short int.

Negative operands never reached the inline multiplication before, so the new run test multiplies every combination of signs and magnitudes around the limits on 32-bit and 64-bit platforms (214 and 230 for the inline multiplication, 230 and 262 for short ints). It does that with two variable operands, and with constant operands, where the C compiler folds the check of the constant.

Performance

Compiled loops with 10**6 iterations:

loop master this PR
total += i * k, k = -3 41.8 ns 2.3 ns 17.9x
total += i * -3 39.8 ns 3.3 ns 12.2x
total += i * k, k = 3 3.3 ns 2.3 ns 1.40x
total += i * 3 2.8 ns 3.1 ns 0.90x

@JukkaL

JukkaL commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

In my experiments this helped with many use cases but regressed a few. I'll investigate this in more detail later this week hopefully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

x * y on ints is more than 10x slower when either operand is negative

2 participants