1 | /* |
2 | * Copyright 2017-present Facebook, Inc. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | #pragma once |
18 | |
19 | #include <new> |
20 | |
21 | #include <folly/CPortability.h> |
22 | #include <folly/Portability.h> |
23 | |
24 | /*** |
25 | * include or backport: |
26 | * * std::launder |
27 | */ |
28 | |
29 | // Note: libc++ 6+ adds std::launder but does not define __cpp_lib_launder |
30 | #if __cpp_lib_launder >= 201606 || (_MSC_VER && _HAS_LAUNDER) || \ |
31 | (_LIBCPP_VERSION >= 6000 && __cplusplus >= 201703L) |
32 | |
33 | namespace folly { |
34 | |
35 | /* using override */ using std::launder; |
36 | |
37 | } // namespace folly |
38 | |
39 | #else |
40 | |
41 | namespace folly { |
42 | |
43 | /** |
44 | * Approximate backport from C++17 of std::launder. It should be `constexpr` |
45 | * but that can't be done without specific support from the compiler. |
46 | */ |
47 | template <typename T> |
48 | FOLLY_NODISCARD inline T* launder(T* in) noexcept { |
49 | #if FOLLY_HAS_BUILTIN(__builtin_launder) || __GNUC__ >= 7 |
50 | // The builtin has no unwanted side-effects. |
51 | return __builtin_launder(in); |
52 | #elif __GNUC__ |
53 | // This inline assembler block declares that `in` is an input and an output, |
54 | // so the compiler has to assume that it has been changed inside the block. |
55 | __asm__("" : "+r" (in)); |
56 | return in; |
57 | #elif defined(_WIN32) |
58 | // MSVC does not currently have optimizations around const members of structs. |
59 | // _ReadWriteBarrier() will prevent compiler reordering memory accesses. |
60 | _ReadWriteBarrier(); |
61 | return in; |
62 | #else |
63 | static_assert( |
64 | false, "folly::launder is not implemented for this environment" ); |
65 | #endif |
66 | } |
67 | |
68 | /* The standard explicitly forbids laundering these */ |
69 | void launder(void*) = delete; |
70 | void launder(void const*) = delete; |
71 | void launder(void volatile*) = delete; |
72 | void launder(void const volatile*) = delete; |
73 | template <typename T, typename... Args> |
74 | void launder(T (*)(Args...)) = delete; |
75 | } // namespace folly |
76 | |
77 | #endif |
78 | |