GCC Newspaper
NOVEMBER 30, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
tree-optimization

gimple-ssa-sprintf: Fix %lc argument range check for ASCII

Ensures %lc format specifier correctly handles ASCII character ranges in snprintf optimizations.

This commit corrects an optimization in gimple-ssa-sprintf that incorrectly assumed %lc format specifiers always succeed for ASCII characters, even when the input range included values beyond the ASCII set. The optimization, which folds comparisons of snprintf results, failed for ranges like [0, 200] where characters above 127 can cause snprintf to return an error. The fix tightens the range check to [0, 127], ensuring the optimization correctly accounts for potential failures and prevents incorrect code transformations.

In Details

The gimple-ssa-sprintf.cc pass performs optimizations based on snprintf behavior. The format_character function's logic for handling %lc arguments, particularly when determining if a range is purely ASCII, was flawed. It checked the minimum value but not the maximum, leading to incorrect assumptions about mayfail when the upper bound exceeded 127. This patch modifies get_int_range usage to enforce the [0, 127] range for ASCII, ensuring that the printf return value optimization correctly folds comparisons only when truly safe.

For Context
gimple-ssa-sprintf
A GCC optimization pass that analyzes and optimizes code involving the sprintf family of functions using the SSA (Static Single Assignment) form of GIMPLE (GCC's internal representation).
%lc
A format specifier for printf-like functions that expects a wide character (typically wint_t) as an argument.
snprintf
A C standard library function that formats data into a string, similar to sprintf, but with a buffer size limit to prevent buffer overflows. It returns the number of characters that *would have been* written, including the null terminator.
SSA
Static Single Assignment. An intermediate representation property where each variable is assigned a value exactly once. This simplifies many optimization analyses.
GIMPLE
GCC's internal three-address code representation used for optimization passes.
Filed Under: optimizationcompiler buginteger overflowprintf