GCC Newspaper
NOVEMBER 30, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
match Performance Win

match: Fold bitwise NOT X op -Y as (Y-1) op X

Optimizes bitwise NOT and negation patterns involving signed integers.

This commit enhances the GCC matching patterns to optimize expressions involving bitwise NOT and negation. It folds ~X op -Y into (Y-1) op X by leveraging the identity ~(-Y) == Y - 1. This transformation allows GCC to simplify various comparisons, such as turning unsigned ~a < -a into a != 0, signed ~a < -a into true, and ~a == -a into false. The optimization is safely gated to avoid undefined behavior with signed integer overflow.

In Details

A new pattern ~X op -Y has been added to gcc/match.pd. This pattern leverages the identity ~(-Y) == Y - 1 to rewrite expressions involving bitwise NOT and negation. The fold is gated by !TYPE_OVERFLOW_SANITIZED and !TYPE_OVERFLOW_TRAPS to ensure correctness, particularly for signed types where Y == INT_MIN could cause overflow during the -Y operation. The resulting expression (Y-1) op X can then be further simplified by existing patterns, leading to more efficient code for comparisons and logical operations.

For Context
match.pd
A file in GCC containing patterns used by the 'match' optimization pass, which identifies and rewrites common intermediate representation subtrees.
BIT_NOT_EXPR
A GCC intermediate representation (tree) node representing the bitwise NOT operation.
NEGATE_EXPR
A GCC intermediate representation (tree) node representing the arithmetic negation operation.
TYPE_OVERFLOW_SANITIZED
A flag indicating that the type system in GCC has been configured to handle signed integer overflow by sanitizing or trapping.
TYPE_OVERFLOW_TRAPS
A flag indicating that signed integer overflow will cause a trap (runtime error).
undefined behavior (UB)
Program behavior that results from an implementation-defined or unspecified condition, or a violation of an instruction, in which case the C and C++ standards impose no requirements on the behavior.
Filed Under: matchoptimizationbitwise operationssigned integer overflow