https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115858
Bug ID: 115858
Summary: Incompatibility of coroutines and alloca()
Product: gcc
Version: 14.1.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: fchelnokov at gmail dot com
Target Milestone: ---
This program
```
#include <coroutine>
#include <iostream>
struct ReturnObject {
struct promise_type {
unsigned * value_ = nullptr;
void return_void() {}
ReturnObject get_return_object() {
return {
.h_ = std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void unhandled_exception() {}
};
std::coroutine_handle<promise_type> h_;
operator auto() const { return h_; }
};
template<typename PromiseType>
struct GetPromise {
PromiseType *p_;
bool await_ready() { return false; }
bool await_suspend(std::coroutine_handle<PromiseType> h) {
p_ = &h.promise();
return false;
}
PromiseType *await_resume() { return p_; }
};
ReturnObject counter()
{
auto pp = co_await GetPromise<ReturnObject::promise_type>{};
//unsigned a[1]; auto & i = a[0]; //this version works fine
auto & i = *new (alloca(sizeof(unsigned))) unsigned(0); //and this not
for (;; ++i) {
pp->value_ = &i;
co_await std::suspend_always{};
}
}
int main()
{
std::coroutine_handle<ReturnObject::promise_type> h = counter();
auto &promise = h.promise();
for (int i = 0; i < 5; ++i) {
std::cout << *promise.value_ << ' ';
h();
}
h.destroy();
}
```
prints `0 1 2 3 4` in Clang, but in GCC with -O2 flag it prints random numbers,
e.g. `1479544584 2 2 2 2`
Online demo: https://gcc.godbolt.org/z/E8GEKn3M9
Could you please clarify, whether alloca() is compatible with coroutines? And
if not, could you please add a diagnostic?
Original discussion: https://stackoverflow.com/q/67576168/7325599