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++1z -fcoroutines-ts -triple=x86_64-unknown-linux-gnu -emit-llvm -o - %s -disable-llvm-passes | FileCheck %s
4 
5 namespace std::experimental {
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::experimental
19 
20 struct suspend_always {
21   bool await_ready() noexcept;
22   void await_suspend(std::experimental::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::experimental::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 {
44   ~Cleanup();
45 };
46 void doSomething() noexcept;
47 
48 // CHECK: define{{.*}} i32 @_Z1fv(
49 int f() {
50   // CHECK: %[[RetVal:.+]] = alloca i32
51 
52   // CHECK: %[[Size:.+]] = call i64 @llvm.coro.size.i64()
53   // CHECK: call noalias noundef nonnull i8* @_Znwm(i64 noundef %[[Size]])
54   // CHECK: call void @_ZNSt12experimental16coroutine_traitsIJiEE12promise_typeC1Ev(
55   // CHECK: call void @_ZNSt12experimental16coroutine_traitsIJiEE12promise_type17get_return_objectEv(%struct.GroType* sret(%struct.GroType) align {{[0-9]+}} %[[GRO:.+]],
56   // CHECK: %[[Conv:.+]] = call noundef i32 @_ZN7GroTypecviEv({{.*}}[[GRO]]
57   // CHECK: store i32 %[[Conv]], i32* %[[RetVal]]
58 
59   Cleanup cleanup;
60   doSomething();
61   co_return;
62 
63   // CHECK: call void @_Z11doSomethingv(
64   // CHECK: call void @_ZNSt12experimental16coroutine_traitsIJiEE12promise_type11return_voidEv(
65   // CHECK: call void @_ZN7CleanupD1Ev(
66 
67   // Destroy promise and free the memory.
68 
69   // CHECK: call void @_ZNSt12experimental16coroutine_traitsIJiEE12promise_typeD1Ev(
70   // CHECK: %[[Mem:.+]] = call i8* @llvm.coro.free(
71   // CHECK: call void @_ZdlPv(i8* noundef %[[Mem]])
72 
73   // CHECK: coro.ret:
74   // CHECK:   %[[LoadRet:.+]] = load i32, i32* %[[RetVal]]
75   // CHECK:   ret i32 %[[LoadRet]]
76 }
77