1 | //===----------------------------------------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // UNSUPPORTED: c++03, c++11, c++14, c++17 |
9 | // XFAIL: !has-64-bit-atomics |
10 | |
11 | // T exchange(T, memory_order = memory_order::seq_cst) volatile noexcept; |
12 | // T exchange(T, memory_order = memory_order::seq_cst) noexcept; |
13 | |
14 | #include <atomic> |
15 | #include <cassert> |
16 | #include <concepts> |
17 | #include <type_traits> |
18 | |
19 | #include "test_helper.h" |
20 | #include "test_macros.h" |
21 | |
22 | template <class T> |
23 | concept HasVolatileExchange = requires(volatile std::atomic<T>& a, T t) { a.exchange(t); }; |
24 | |
25 | template <class T, template <class> class MaybeVolatile = std::type_identity_t> |
26 | void test_impl() { |
27 | // Uncomment the test after P1831R1 is implemented |
28 | // static_assert(HasVolatileExchange<T> == std::atomic<T>::is_always_lock_free); |
29 | static_assert(noexcept(std::declval<MaybeVolatile<std::atomic<T>>&>() = (T(0)))); |
30 | |
31 | // exchange |
32 | { |
33 | MaybeVolatile<std::atomic<T>> a(T(3.1)); |
34 | std::same_as<T> decltype(auto) r = a.exchange(T(1.2), std::memory_order::relaxed); |
35 | assert(a.load() == T(1.2)); |
36 | assert(r == T(3.1)); |
37 | } |
38 | |
39 | // memory_order::release |
40 | { |
41 | auto exchange = [](MaybeVolatile<std::atomic<T>>& x, T, T new_val) { |
42 | x.exchange(new_val, std::memory_order::release); |
43 | }; |
44 | auto load = [](MaybeVolatile<std::atomic<T>>& x) { return x.load(std::memory_order::acquire); }; |
45 | test_acquire_release<T, MaybeVolatile>(exchange, load); |
46 | } |
47 | |
48 | // memory_order::seq_cst |
49 | { |
50 | auto exchange_no_arg = [](MaybeVolatile<std::atomic<T>>& x, T, T new_val) { x.exchange(new_val); }; |
51 | auto exchange_with_order = [](MaybeVolatile<std::atomic<T>>& x, T, T new_val) { |
52 | x.exchange(new_val, std::memory_order::seq_cst); |
53 | }; |
54 | auto load = [](MaybeVolatile<std::atomic<T>>& x) { return x.load(); }; |
55 | test_seq_cst<T, MaybeVolatile>(exchange_no_arg, load); |
56 | test_seq_cst<T, MaybeVolatile>(exchange_with_order, load); |
57 | } |
58 | } |
59 | |
60 | template <class T> |
61 | void test() { |
62 | test_impl<T>(); |
63 | if constexpr (std::atomic<T>::is_always_lock_free) { |
64 | test_impl<T, std::add_volatile_t>(); |
65 | } |
66 | } |
67 | |
68 | int main(int, char**) { |
69 | test<float>(); |
70 | test<double>(); |
71 | // TODO https://github.com/llvm/llvm-project/issues/47978 |
72 | // test<long double>(); |
73 | |
74 | return 0; |
75 | } |
76 | |