[Clang] Fix FE crash during CGCoroutine GRO Alloca Emission (#148962)

Fixes: https://github.com/llvm/llvm-project/issues/148953

Currently when coroutine return object type is const qualified, we don't
do direct emission. The regular emission logic assumed that the auto var
emission will always result in an `AllocaInst`. However, based on my
findings, NRVO var emissions don't result in `AllocaInst`s. Therefore,
this
[assertion](1a940bfff9/clang/lib/CodeGen/CGCoroutine.cpp (L712))
will fail.

Since the NRVOed returned object don't live on the coroutine frame, we
won't have the problem of it outliving the coroutine frame, therefore,
we can safely omit this metadata.

(cherry picked from commit c36156de45a0f5e24e7a4ee2259c3302ea814785)
This commit is contained in:
Yuxuan Chen 2025-07-15 15:02:32 -07:00 committed by Tobias Hieta
parent 2067574f54
commit ad9051049d
2 changed files with 37 additions and 6 deletions

View File

@ -707,11 +707,15 @@ struct GetReturnObjectManager {
Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
GroEmission.getOriginalAllocatedAddress().getPointer());
assert(GroAlloca && "expected alloca to be emitted");
GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
if (!GroVarDecl->isNRVOVariable()) {
// NRVO variables don't have allocas and won't have the same issue.
auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
GroEmission.getOriginalAllocatedAddress().getPointer());
assert(GroAlloca && "expected alloca to be emitted");
GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
}
// Remember the top of EHStack before emitting the cleanup.
auto old_top = CGF.EHStack.stable_begin();

View File

@ -106,4 +106,31 @@ invoker g() {
// CHECK: call void @_ZN7invoker15invoker_promise17get_return_objectEv({{.*}} %[[AggRes]]
co_return;
}
// CHECK: ![[OutFrameMetadata]] = !{}
namespace gh148953 {
struct Task {
struct promise_type {
Task get_return_object();
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
Task() {}
// Different from `invoker`, this Task is copy constructible.
Task(const Task&) {};
};
// NRVO on const qualified return type should work.
// CHECK: define{{.*}} void @_ZN8gh1489537exampleEv({{.*}} sret(%"struct.gh148953::Task") align 1 %[[NrvoRes:.+]])
const Task example() {
// CHECK: %[[ResultPtr:.+]] = alloca ptr
// CHECK: store ptr %[[NrvoRes]], ptr %[[ResultPtr]]
// CHECK: coro.init:
// CHECK: call void @_ZN8gh1489534Task12promise_type17get_return_objectEv({{.*}} %[[NrvoRes:.+]], {{.*}})
co_return;
}
} // namespace gh148953
// CHECK: ![[OutFrameMetadata]] = !{}