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

            Bug ID: 125262
           Summary: constexpr asm doesn't work with std::string
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: ivan.lazaric.gcc at gmail dot com
  Target Milestone: ---

In an asm statement AssemblerInstructions/AssemblerTemplate does not
have to be a string literal, it can also be a (parenthesized) constant
expression.
https://gcc.gnu.org/onlinedocs/gcc-16.1.0/gcc/Asm-constexprs.html
```
The constant expression can return a container with data () and size () 
member functions, following similar rules as the C++26 static_assert message.
```

Consider the following code snippet:
```cpp
#include <string>
#include <string_view>

#ifndef __GXX_CONSTEXPR_ASM__
# error "missing support for constexpr asm"
#endif

asm((std::string_view("")));
asm((std::string("")));
```

Compiler flags: "-std=c++26"

First asm statement with `std::string_view` works,
while the second one with `std::string` errors, with diagnostic:
```
<source>:9:21: error:
'std::string{std::__cxx11::basic_string<char>::_Alloc_hider{((char*)(&<anonymous>.std::__cxx11::basic_string<char>::<anonymous>.std::__cxx11::basic_string<char>::<unnamed
union>::_M_local_buf))}, 0, std::__cxx11::basic_string<char>::<unnamed
union>{char [16]{0, '\000', '\000', '\000', '\000', '\000', '\000', '\000',
'\000', '\000', '\000', '\000', '\000', '\000', '\000', '\000'}}}' is not a
constant expression
    9 | asm((std::string("")));
      |                     ^
<source>:9:21: error: 'std::__cxx11::basic_string<char>(((const char*)""),
std::allocator<char>())' is not a constant expression because it refers to an
incompletely initialized variable
```

Godbolt: https://godbolt.org/z/MaPv8bz4h


Noting that this is easy to avoid via `std::define_static_string()`
```cpp
consteval std::string_view simplify(const std::string& str) {
    return std::string_view(std::define_static_string(str), str.size());
}

asm((simplify(std::string(""))));
```

Reply via email to