[libcxx-commits] [libcxx] [libc++] Ensure that `std::expected` has no tail padding (PR #69673)
Jan Kokemüller via libcxx-commits
libcxx-commits at lists.llvm.org
Thu Nov 2 13:34:10 PDT 2023
================
@@ -88,8 +88,263 @@ _LIBCPP_HIDE_FROM_ABI void __throw_bad_expected_access(_Arg&& __arg) {
# endif
}
+struct __expected_invoke_tag {};
+
+template <bool _NoUnique, class _Tp>
+class __expected_conditional_no_unique_address {
+ struct __unique {
+ template <class... _Args>
+ _LIBCPP_HIDE_FROM_ABI constexpr explicit __unique(_Args&&... __args)
+ : __v(std::forward<_Args>(__args)...) {}
+
+ template <class _Func, class... _Args>
+ _LIBCPP_HIDE_FROM_ABI constexpr explicit __unique(
+ __expected_invoke_tag, _Func&& __f, _Args&&... __args)
+ : __v(std::invoke(std::forward<_Func>(__f), std::forward<_Args>(__args)...)) {}
+
+ _Tp __v;
+ };
+
+ struct __no_unique {
+ template <class... _Args>
+ _LIBCPP_HIDE_FROM_ABI constexpr explicit __no_unique(_Args&&... __args)
+ : __v(std::forward<_Args>(__args)...) {}
+
+ template <class _Func, class... _Args>
+ _LIBCPP_HIDE_FROM_ABI constexpr explicit __no_unique(
+ __expected_invoke_tag, _Func&& __f, _Args&&... __args)
+ : __v(std::invoke(std::forward<_Func>(__f), std::forward<_Args>(__args)...)) {}
+
+ _LIBCPP_NO_UNIQUE_ADDRESS _Tp __v;
+ };
+
+public:
+ using __type = std::conditional<_NoUnique, __no_unique, __unique>::type;
+};
+
+template <class _Union>
+_LIBCPP_HIDE_FROM_ABI constexpr bool __expected_can_stuff_tail()
+{
+ struct __x {
+ private:
+ _LIBCPP_NO_UNIQUE_ADDRESS _Union __union_;
+ _LIBCPP_NO_UNIQUE_ADDRESS bool __has_val_;
+ };
+ return sizeof(__x) == sizeof(_Union);
+}
+
+template <class _Tp, class _Err>
+class __expected_base {
+ // use named union because [[no_unique_address]] cannot be applied to an unnamed union,
+ // also guaranteed elision into a potentially-overlapping subobject is unsettled (and
+ // it's not clear that it's implementable, given that the function is allowed to clobber
+ // the tail padding) - see https://github.com/itanium-cxx-abi/cxx-abi/issues/107.
+ union __union_t {
----------------
jiixyj wrote:
Should I extract the `__repr` out of the `__expected_base` as well?
What I like about the current approach is that both `__union` and `__repr` are tucked away inside the `__expected_base` class and cannot be used anywhere else by accident. Outside, they would have to be templates again and have names with a prefix (like `__expected_union_t`). What do you think?
https://github.com/llvm/llvm-project/pull/69673
More information about the libcxx-commits
mailing list