match.pd: Fold (t * u) % u to zero when multiplication cannot overflow
Optimization rule added to simplify expressions like (t * u) % u to zero if the multiplication is guaranteed not to overflow.
A new simplification rule has been added to match.pd to handle expressions of the form (t * u) % u. When the multiplication t * u is guaranteed to not overflow, the result of the modulo operation will always be zero. This rule applies to various modulo codes (TRUNC_MOD_EXPR, MODULO, mod) and extends the existing fold for (t * u) / u to its remainder counterpart, improving code efficiency by eliminating redundant operations.
In Details
The match.pd optimization pass now includes a new pattern to fold (t * u) % u to zero. This simplification is valid when the multiplication t * u does not overflow. For signed types, overflow is undefined behavior, so this always holds. For unsigned types, value ranges are used to prove overflow-freeness, similar to the existing (t * u) / u -> t fold. This applies to C-family TRUNC_MOD_EXPR, Fortran's MODULO, and Ada's mod operations, covering floor and ceiling forms.
- match.pd
- A pattern-matching file within GCC used for optimizing GIMPLE (GCC's intermediate representation) code. It defines rules to recognize and transform specific code patterns into more efficient forms.
- fold
- In compiler optimization, 'folding' refers to evaluating an expression at compile time rather than runtime, if possible.
- GIMPLE
- GCC's Internal Gimple Representation. It's a three-address, low-level intermediate representation used by the compiler's optimization passes.
- TRUNC_MOD_EXPR
- A GIMPLE expression representing the remainder of a division, typically corresponding to the '%' operator in C-like languages. The result has the same sign as the dividend.
- overflow
- A condition that occurs when the result of an arithmetic operation is too large to be represented in the destination data type, leading to unexpected or incorrect values.