libstdc++: Tell GCC what basic_string::_M_is_local() means [PR109299]
authorJonathan Wakely <jwakely@redhat.com>
Tue, 28 Mar 2023 09:50:40 +0000 (10:50 +0100)
committerJonathan Wakely <jwakely@redhat.com>
Tue, 28 Mar 2023 20:12:18 +0000 (21:12 +0100)
This avoids a bogus warning about overflowing a buffer, because GCC
can't tell that we don't copy into the buffer unless it fits. By adding
a __builtin_unreachable() hint we inform the compiler about the
invariant that the buffer is only used when it's big enough.

This can also improve codegen, by eliminating dead code that GCC
couldn't tell was unreachable.

libstdc++-v3/ChangeLog:

PR libstdc++/109299
* include/bits/basic_string.h (basic_string::_M_is_local()): Add
hint for compiler that local strings fit in the local buffer.

libstdc++-v3/include/bits/basic_string.h

index 1b8ebca7dadcefb5e950b7ff21cbfa7c69e8d7e8..5d040e2897d49065c46546fe012d76fb429ef79e 100644 (file)
@@ -271,7 +271,15 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11
       _GLIBCXX20_CONSTEXPR
       bool
       _M_is_local() const
-      { return _M_data() == _M_local_data(); }
+      {
+       if (_M_data() == _M_local_data())
+         {
+           if (_M_string_length > _S_local_capacity)
+             __builtin_unreachable();
+           return true;
+         }
+       return false;
+      }
 
       // Create & Destroy
       _GLIBCXX20_CONSTEXPR