1 // Verifies lifetime of __gro local variable
2 // Verify that coroutine promise and allocated memory are freed up on exception.
3 // RUN: %clang_cc1 -no-opaque-pointers -std=c++20 -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s -disable-llvm-passes | FileCheck %s
4 
5 namespace std {
6 template <typename... T> struct coroutine_traits;
7 
8 template <class Promise = void> struct coroutine_handle {
9   coroutine_handle() = default;
10   static coroutine_handle from_address(void *) noexcept;
11 };
12 template <> struct coroutine_handle<void> {
13   static coroutine_handle from_address(void *) noexcept;
14   coroutine_handle() = default;
15   template <class PromiseType>
16   coroutine_handle(coroutine_handle<PromiseType>) noexcept;
17 };
18 } // namespace std
19 
20 struct suspend_always {
21   bool await_ready() noexcept;
22   void await_suspend(std::coroutine_handle<>) noexcept;
23   void await_resume() noexcept;
24 };
25 
26 struct GroType {
27   ~GroType();
28   operator int() noexcept;
29 };
30 
31 template <> struct std::coroutine_traits<int> {
32   struct promise_type {
33     GroType get_return_object() noexcept;
34     suspend_always initial_suspend() noexcept;
35     suspend_always final_suspend() noexcept;
36     void return_void() noexcept;
37     promise_type();
38     ~promise_type();
39     void unhandled_exception() noexcept;
40   };
41 };
42 
43 struct Cleanup { ~Cleanup(); };
44 void doSomething() noexcept;
45 
46 // CHECK: define{{.*}} i32 @_Z1fv(
f()47 int f() {
48   // CHECK: %[[RetVal:.+]] = alloca i32
49 
50   // CHECK: %[[Size:.+]] = call i64 @llvm.coro.size.i64()
51   // CHECK: call noalias noundef nonnull i8* @_Znwm(i64 noundef %[[Size]])
52   // CHECK: call void @_ZNSt16coroutine_traitsIJiEE12promise_typeC1Ev(
53   // CHECK: call void @_ZNSt16coroutine_traitsIJiEE12promise_type17get_return_objectEv(%struct.GroType* sret(%struct.GroType) align {{[0-9]+}} %[[GRO:.+]],
54   // CHECK: %[[Conv:.+]] = call noundef i32 @_ZN7GroTypecviEv({{.*}}[[GRO]]
55   // CHECK: store i32 %[[Conv]], i32* %[[RetVal]]
56 
57   Cleanup cleanup;
58   doSomething();
59   co_return;
60 
61   // CHECK: call void @_Z11doSomethingv(
62   // CHECK: call void @_ZNSt16coroutine_traitsIJiEE12promise_type11return_voidEv(
63   // CHECK: call void @_ZN7CleanupD1Ev(
64 
65   // Destroy promise and free the memory.
66 
67   // CHECK: call void @_ZNSt16coroutine_traitsIJiEE12promise_typeD1Ev(
68   // CHECK: %[[Mem:.+]] = call i8* @llvm.coro.free(
69   // CHECK: call void @_ZdlPv(i8* noundef %[[Mem]])
70 
71   // CHECK: coro.ret:
72   // CHECK:   %[[LoadRet:.+]] = load i32, i32* %[[RetVal]]
73   // CHECK:   ret i32 %[[LoadRet]]
74 }
75