Improve float conversion folding safety
Float conversion folding now requires intermediate types to exactly represent the input type, preventing precision loss.
This patch enhances the floating-point conversion folding in match.pd by introducing real_exact_conversion_p. This new check ensures that the intermediate floating-point type in a conversion chain can precisely represent all values of the preceding type. Previously, folding could occur based solely on bit-width, leading to precision loss and incorrect results, particularly with formats like _Decimal32, _Float16, and __bf16.
In Details
The two conversions in a row pattern in match.pd previously used element_precision to determine if an intermediate float-to-float conversion could be eliminated. This commit replaces that with real_exact_conversion_p, which performs a more robust check comparing radix, precision, exponent range, and special value support. This prevents folding chains like (float) (_Decimal32) f16 or (double) (_Float16) (__bf16) x where the intermediate type (_Decimal32, _Float16) cannot exactly represent the input type (f16, __bf16), thus avoiding precision loss and incorrect results due t…
- match.pd
- A file containing pattern matching rules for the GCC middle-end, used to identify and optimize sequences of operations.
- folding
- An optimization technique where constant expressions or predictable operations are evaluated at compile time rather than runtime.
- _Decimal32
- A IEEE 754-2008 decimal floating-point format with 32 bits of precision.
- _Float16
- A 16-bit floating-point format, often used for machine learning and graphics, with limited precision and range.
- __bf16
- Bfloat16, a 16-bit floating-point format primarily used in deep learning, prioritizing dynamic range over precision.
- element_precision
- A property of floating-point types indicating the number of representable digits.
- radix
- The base of a number system; for floating-point types, this is typically 2 (binary) or 10 (decimal).