[clang] Implement lifetime analysis for lifetime_capture_by(X) (#115921)
[llvm-project.git] / clang / test / CodeGenCoroutines / pr59221.cpp
blobc27afa260316a039f65fc5e350e4fc5f0c3b320e
1 // Test for PR59221. Tests the compiler wouldn't misoptimize the final result.
2 //
3 // REQUIRES: x86-registered-target
4 //
5 // RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++20 %s -O1 -emit-llvm -o - | FileCheck %s
7 #include "Inputs/coroutine.h"
9 template <typename T> struct task {
10 struct promise_type {
11 T value{123};
12 std::coroutine_handle<> caller{std::noop_coroutine()};
14 struct final_awaiter: std::suspend_always {
15 auto await_suspend(std::coroutine_handle<promise_type> me) const noexcept {
16 return me.promise().caller;
20 constexpr auto initial_suspend() const noexcept {
21 return std::suspend_always();
23 constexpr auto final_suspend() const noexcept {
24 return final_awaiter{};
26 auto unhandled_exception() noexcept {
27 // ignore
29 constexpr void return_value(T v) noexcept {
30 value = v;
32 constexpr auto & get_return_object() noexcept {
33 return *this;
37 using coroutine_handle = std::coroutine_handle<promise_type>;
39 promise_type & promise{nullptr};
41 task(promise_type & p) noexcept: promise{p} { }
43 ~task() noexcept {
44 coroutine_handle::from_promise(promise).destroy();
47 auto await_ready() noexcept {
48 return false;
51 auto await_suspend(std::coroutine_handle<> caller) noexcept {
52 promise.caller = caller;
53 return coroutine_handle::from_promise(promise);
56 constexpr auto await_resume() const noexcept {
57 return promise.value;
60 // non-coroutine access to result
61 auto get() noexcept {
62 const auto handle = coroutine_handle::from_promise(promise);
64 if (!handle.done()) {
65 handle.resume();
68 return promise.value;
73 static inline auto a() noexcept -> task<int> {
74 co_return 42;
77 static inline auto test() noexcept -> task<int> {
78 co_return co_await a();
81 int foo() {
82 return test().get();
85 // Checks that the store for the result value 42 is not misoptimized out.
86 // CHECK: define{{.*}}_Z3foov(
87 // CHECK: store i32 42, ptr %{{.*}}
88 // CHECK: }