Optimize signed < 0 ? positive : min<signed, positive> to (signed)min<(unsigned), (unsigned)positive>
GCC now optimizes ternary expressions where a signed value is compared to zero against the minimum of the signed value and a positive one, reducing code size a…
The compiler can now recognize and optimize a specific pattern in ternary expressions. When code contains the structure signed < 0 ? positive : min<signed, positive>, the compiler transforms it into a sequence using unsigned comparisons and a final cast back to signed. This optimization avoids branches and directly computes the minimum, potentially improving performance, especially in tight loops or frequently executed code paths. The change addresses a missed optimization opportunity initially identified while investigating PR 110252.
In Details
The change introduces a new pattern in match.pd to optimize ternary expressions involving signed and positive values. Specifically, it transforms signed < 0 ? positive : min<signed, positive> into an equivalent sequence using unsigned comparisons and a cast. This optimization leverages existing compiler infrastructure for pattern matching and code replacement, and adds new test cases ensure the transformation is correct and efficient.
For Context
Compilers often perform optimizations by recognizing common code patterns and replacing them with more efficient equivalents. This commit adds a new optimization rule to GCC's pattern matching engine. The compiler identifies ternary expressions—statements that pick one of two values based on a condition—that compare a signed value to zero. If the condition is true, a positive value is selected; otherwise, the minimum of the signed value and the positive value is chosen. The optimized code avoids a direct comparison and branch, which can be slower than performing arithmetic operations.