r/programming • u/DataBaeBee • Sep 14 '26
How GCC Eliminates Unnecessary Integer Division
https://leetarxiv.substack.com/p/how-gcc-eliminates-unnecessary-integer
250
Upvotes
r/programming • u/DataBaeBee • Sep 14 '26
165
u/DataBaeBee Sep 14 '26
GCC, when provided a constant divisor, finds two magic numbers and replaces division with multiplication and a comparison. The succint term for this op is called Reciprocal multiplication.
It's pretty cool and this obscure paper from 2011 shows one how to derive these magic numbers for division.
41
u/Elektro-Hijena Sep 14 '26 edited Sep 14 '26
Java JIT C2 does the same, transforms division to Granlund-Montgomery multiplication (mul | imul) and bitwise shifting (sar | shr).
There's also cases of so called uncooperative divisors (like number 7) when addition is needed to correct the result before shifting.
21
u/LonelyAndroid11942 Sep 14 '26 edited Sep 14 '26
So is the purpose of this to reduce the difficulties that come with float precision?
EDIT: The comments are informative, if they’re not made by jerks. I clearly have much to learn. I appreciate the patience of those who have it, and wish a very strong “go step on some legos” to those who do not.
1
u/BobFloss Sep 15 '26
Classic
1
u/Blue_Moon_Lake Sep 16 '26
So dividing by 7 is also annoying for computers.
6
u/[deleted] Sep 15 '26
[removed] — view removed comment