https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128901

            Bug ID: 128901
           Summary: string built-ins are not folded on constexpr-heap or
                    automatic storage, so char_traits loops in constant
                    evaluation: 22% of front-end work in reflection-heavy
                    code
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: compile-time-hog
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: filip.sajdak at gmail dot com
  Target Milestone: ---
              Host: aarch64-unknown-linux-gnu
            Target: aarch64-unknown-linux-gnu
             Build: aarch64-unknown-linux-gnu

Created attachment 66238
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=66238&action=edit
experiment (LLM-generated, reference only, NOT a patch submission), against
releases/gcc-16.2.0

__builtin_memcmp, __builtin_strlen and friends are not folded in constant
evaluation when the pointer refers to constexpr-heap or automatic storage, so
libstdc++'s char_traits has to loop character by character there. PR 106889
reports the functional side (the built-in is not a constant expression there);
this report is about what it costs. Related: PR 70816 and PR 80265 (local
arrays), PR 127218 (folding at an offset), PR 127894 (evaluator overhead of
array scans).

Seen on 16.2.0 and on trunk 9eb44775b9 (2026-11-19), aarch64-unknown-linux-gnu,
configured with --enable-languages=c,c++ --disable-bootstrap --disable-multilib
--enable-checking=release.

Reproducer:

#include <string>
consteval int a() { std::string s = "hello world, on the constexpr heap";
return __builtin_memcmp(s.data(), "hello", 5); }
constexpr int x = a();
int main() { return x; }

g++ -std=c++26 -fsyntax-only b_builtin_heap.cpp

16.2.0 and trunk 9eb44775 both print:

b_builtin_heap.cpp:2:98: error: '__builtin_memcmp(((char*)(& heap )), "hello",
5)' is not a constant expression

cxx_eval_builtin_function_call replaces a string argument by a STRING_CST only
when the argument is written as &something.
Its comment says so: "expand_builtin doesn't know how to look in the values
table".
A pointer that only evaluates to the heap or to a local array reaches the
folder as an address whose contents the folder cannot see.

Why it matters:

Because the built-ins cannot be relied on, libstdc++'s
char_traits<char>::compare and length take a loop in constant evaluation.
In reflection-heavy code most strings are names, and string_view::starts_with,
== and string_view(const char*) all reach these loops.

Per-call cost, user-space instructions of cc1plus, least of three runs, front
end only:

Compiler and library          starts_with("lv_0") on a literal view  The same
on a std::string  The reproducer
16.2.0                        307 k                                  308 k     
                error
trunk 9eb44775                312 k                                  294 k     
                error
16.2.0, front-end half below  311 k                                  325 k     
                compiles
16.2.0, library half below    53 k                                   242 k     
                error
16.2.0, both halves           53 k                                   60 k      
                compiles

The probes run 4000 calls on distinct names of 34 characters; a twin without
the call is subtracted. The heap probes carry a noise of about 15 k a call.

For a real program, a file of a C++26 UI library goes from 54.09 G to 41.82 G
instructions in the front end with both halves (-22.7 %), and to 42.52 G with
the library half alone.

The experiment:

Front-end half, gcc/cp/constexpr.cc: after the arguments are evaluated, a
string argument that was not &something is looked at again.
If its value points into an array of single-byte integers, the array's value is
read from the evaluation (cxx_eval_constant_expression on the array).
The characters that are known from the pointed-to one on are copied into a new
STRING_CST: n of them for memcmp, memchr and strnlen, otherwise up to the first
NUL.
An uninitialized element, an unknown bound or a non-constant element stops it,
and the call stays non-constant as before.
A RAW_DATA_CST element (from #embed or a long initializer) is read byte by
byte.

Library half, bits/char_traits.h: in constant evaluation, compare and length of
char_traits<char> try the built-in under __builtin_constant_p first, and keep
the loop otherwise.

(The experiment is attached as a diff against releases/gcc-16.2.0. It was
written with the help of an LLM, so with regard to the GCC AI policy it is NOT
offered as a patch submission: it is an analysis, and a measure of what a fix
can gain.)

Tests:

Run                                                                            
               Before                                             After
make check-c++ RUNTESTFLAGS="dg.exp=reflect/* *constexpr*"                     
               8777 passes, 34 expected failures, 13 unsupported  the same
libstdc++ conformance.exp on 21_strings, 23_containers/vector,
20_util/specialized_algorithms  1478 passes, 14 expected failures, 39
unsupported  the same

A first version of the front-end half zero-filled the span of a RAW_DATA_CST
and returned wrong results for #embed data, and the testsuite still passed.
So a real patch needs its own tests. These passed with the version above. With
16.2.0 the heap and local-array lines fail to compile; the #embed lines pass
there, through the library loop, and guard against a wrong fold:

#include <string>
#include <string_view>
consteval int a() { std::string s = "hello world, on the constexpr heap";
return __builtin_memcmp(s.data(), "hello", 5); }
consteval int b() { std::string s = "hello world, on the constexpr heap";
return __builtin_memcmp(s.data() + 6, "world", 5); }
consteval unsigned long d() { std::string s = "hello world, on the constexpr
heap"; return __builtin_strlen(s.c_str() + 3); }
consteval long e() { std::string s = "hello world, on the constexpr heap";
return static_cast<const char*>(__builtin_memchr(s.data() + 2, 'o', 30)) -
s.data(); }
consteval int f() { char buf[8] = {'a', 'b', 'c'}; return
__builtin_strlen(buf); }
consteval int h() { std::string s = "abc"; s[1] = 'x'; return
__builtin_memcmp(s.data(), "axc", 3); }
consteval long i() { char buf[6] = "abcab"; return static_cast<const
char*>(__builtin_memchr(buf + 1, 'a', 4)) - buf; }
static_assert(a() == 0 && b() == 0 && d() == 31 && e() == 4 && f() == 3 && h()
== 0 && i() == 3);

constexpr char text[] = {
#embed "text.txt"   // 5033 bytes, "0.1 degree" at offset 4017
};
constexpr std::string_view view(text, sizeof text);
static_assert(view.find("0.1 degree") == 4017);

Reading uninitialized bytes stays an error:

#include <memory>
consteval int a() {
  std::allocator<char> al;
  char* p = al.allocate(8);
  std::construct_at(p, 'a');
  std::construct_at(p + 1, 'b');
  int r = __builtin_memcmp(p, "abc", 3);  // p[2] is not initialized: still not
a constant expression
  al.deallocate(p, 8);
  return r;
}
constexpr int x = a();

Questions for the maintainers:

- Is folding the string built-ins on any storage the evaluation knows wanted,
or should libstdc++ get a dedicated front-end built-in instead?
- The library half evaluates the built-in twice, once inside
__builtin_constant_p. A built-in that returns "not constant" without an error
would avoid that.

Not checked:

- A build with --enable-checking=yes.
- wchar_t, char8_t, char16_t and char32_t traits; only char was changed.
- memchr and find in the library half; only compare and length were changed.
- Trunk: the experiment was built on 16.2.0 only.

This report was prepared with AI assistance (analysis and the experiment). The
builds, the measurements and the test runs were done on a machine of mine.

Reply via email to