GCC Newspaper
OCTOBER 6, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
gcc/tree-optimization Performance Win

Enable constant folding for `strnlen` calls with constant length.

Compiler now folds `__builtin_strnlen` into constants when the length argument is known, improving optimization.

This commit enhances the fold_const_call.cc pass to recognize and constant-fold calls to __builtin_strnlen when the maximum length argument is a compile-time constant. Previously, only __builtin_strlen was optimized this way. This change allows for better constant propagation and dead code elimination in cases involving bounded string length checks, as demonstrated by an example where a strnlen call with a PHI node input is successfully reduced.

In Details

Enhances fold_const_call.cc to handle CFN_BUILTIN_STRNLEN. Previously, only CFN_BUILTIN_STRLEN was folded. This allows optimization of calls like __builtin_strnlen(s, N) where N is a constant. The PR example shows how this enables folding a strnlen with a PHI node argument into a constant range, avoiding runtime calls. Test cases were updated to reflect changes in warnings/behavior.

For Context
Constant folding
An optimization technique where expressions with constant operands are evaluated at compile time rather than at runtime. This reduces the amount of computation needed when the program executes.
strnlen
A C standard library function that calculates the length of a string, but stops after a specified maximum number of characters. It is safer than strlen as it prevents buffer overflows.
PHI node
In Static Single Assignment (SSA) form, a PHI node is an instruction that merges values from different control flow paths. It represents a variable that has different values depending on which path of execution was taken to reach that point.
tree-optimization
A phase in the GCC compiler that operates on the compiler's intermediate representation (IR) called GENERIC and GIMPLE, performing various high-level optimizations before code generation.
Filed Under: optimizationconstant foldingbuiltin