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

            Bug ID: 82000
           Summary: Missed optimization of char_traits::length() on
                    constant string
           Product: gcc
           Version: 8.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: ldionne.2 at gmail dot com
  Target Milestone: ---

In the following code, the calculation of the string length is not folded,
despite the input string being visible to the compiler:

  template <char ...c>
  struct string_constant {
    static constexpr char internal_buffer[sizeof...(c)+1] = {c..., '\0'};
    constexpr char const* c_str() const { return internal_buffer; }
    constexpr std::size_t size() const { return sizeof...(c); }
  };

  auto const text = string_constant<'s', 'o', 'm', 'e', 'c', 'o', 'm', 'p',
'i', 'l', 'e', 't', 'i', 'm', 'e', 't', 'e', 'x', 't'>{};

  int main() {
    std::string_view sv1{text.c_str()}; // calculation of length not folded

    std::string_view sv2{text.c_str(), text.size()}; // no work required
  }

I tracked it down to `char_traits<char>::length()` not being folded. Note that
Clang folds that without problem. Here's a link on Godbolt so you can reproduce
the issue easily and look at the assembly: https://godbolt.org/g/sF3enh

Reply via email to