KaMPIng 0.1.0
(Near) zero-overhead C++ MPI bindings.
Loading...
Searching...
No Matches
mpi_datatype.hpp
Go to the documentation of this file.
1// This file is part of KaMPIng.
2//
3// Copyright 2021-2024 The KaMPIng Authors
4//
5// KaMPIng is free software : you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
6// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
7// version. KaMPIng is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
8// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
9// for more details.
10//
11// You should have received a copy of the GNU Lesser General Public License along with KaMPIng. If not, see
12// <https://www.gnu.org/licenses/>.
13
14/// @file
15/// @brief Utility that maps C++ types to types that can be understood by MPI.
16
17#pragma once
18
19#include <type_traits>
20
21#include <kassert/kassert.hpp>
22#include <mpi.h>
23#include <pfr.hpp>
24
27#include "kamping/noexcept.hpp"
28
29namespace kamping {
30/// @brief Tag used for indicating that a struct is reflectable.
31/// @see struct_type
32struct kamping_tag {};
33} // namespace kamping
34
35namespace kamping {
36/// @addtogroup kamping_mpi_utility
37/// @{
38///
39///
40
41namespace internal {
42/// @brief Helper to check if a type is a `std::pair`.
43template <typename T>
44struct is_std_pair : std::false_type {};
45/// @brief Helper to check if a type is a `std::pair`.
46template <typename T1, typename T2>
47struct is_std_pair<std::pair<T1, T2>> : std::true_type {};
48
49/// @brief Helper to check if a type is a `std::tuple`.
50template <typename T>
51struct is_std_tuple : std::false_type {};
52/// @brief Helper to check if a type is a `std::tuple`.
53template <typename... Ts>
54struct is_std_tuple<std::tuple<Ts...>> : std::true_type {};
55
56/// @brief Helper to check if a type is a `std::array`.
57template <typename A>
58struct is_std_array : std::false_type {};
59
60/// @brief Helper to check if a type is a `std::array`.
61template <typename T, size_t N>
62struct is_std_array<std::array<T, N>> : std::true_type {
63 using value_type = T; ///< The type of the elements in the array.
64 static constexpr size_t size = N; ///< The number of elements in the array.
65};
66} // namespace internal
67
68/// @brief Constructs an contiguous type of size \p N from type \p T using `MPI_Type_contiguous`.
69template <typename T, size_t N>
71 static constexpr TypeCategory category = TypeCategory::contiguous; ///< The category of the type.
72 /// @brief Whether the type has to be committed before it can be used in MPI calls.
74 /// @brief The MPI_Datatype corresponding to the type.
76};
77
78/// @brief Constructs a type that is serialized as a sequence of `sizeof(T)` bytes using `MPI_BYTE`. Note that you must
79/// ensure that this conversion is valid.
80template <typename T>
81struct byte_serialized : contiguous_type<std::byte, sizeof(T)> {};
82
83/// @brief Constructs a MPI_Datatype for a struct-like type.
84/// @tparam T The type to construct the MPI_Datatype for.
85///
86/// This requires that \p T is a `std::pair`, `std::tuple` or a type that is reflectable with
87/// [pfr](https://github.com/apolukhin/pfr_non_boost). If you do not agree with PFR's decision if a type is implicitly
88/// reflectable, you can override it by providing a specialization of \c pfr::is_reflectable with the tag \ref
89/// kamping_tag.
90/// @see https://apolukhin.github.io/pfr_non_boost/pfr/is_reflectable.html for details
91template <typename T>
93 static_assert(
95 || pfr::is_implicitly_reflectable<T, kamping_tag>::value,
96 "Type must be a std::pair, std::tuple or reflectable"
97 );
98 /// @brief The category of the type.
99 static constexpr TypeCategory category = TypeCategory::struct_like;
100 /// @brief Whether the type has to be committed before it can be used in MPI calls.
102 /// @brief The MPI_Datatype corresponding to the type.
104};
105
106/// @brief Type tag for indicating that no static type definition exists for a type.
108
109/// @brief The type dispatcher that maps a C++ type \p T to a type trait that can be used to construct an MPI_Datatype.
110///
111/// The mapping is as follows:
112/// - C++ types directly supported by MPI are mapped to the corresponding `MPI_Datatype`.
113/// - Enums are mapped to the underlying type.
114/// - C-style arrays and `std::array` are mapped to contiguous types of the underlying type.
115/// - All other trivially copyable types are mapped to a contiguous type consisting of `sizeof(T)` bytes.
116/// - All other types are not supported directly and require a specialization of `mpi_type_traits`. In this case, the
117/// trait `no_matching_type` is returned.
118///
119/// @returns The corresponding type trait for the type \p T.
120template <typename T>
122 using T_no_const = std::remove_const_t<T>; // remove const from T
123 // we previously also removed volatile here, but interpreting a pointer
124 // to a volatile type as a pointer to a non-volatile type is UB
125
126 static_assert(
127 !std::is_pointer_v<T_no_const>,
128 "MPI does not support pointer types. Why do you want to transfer a pointer over MPI?"
129 );
130
131 static_assert(!std::is_function_v<T_no_const>, "MPI does not support function types.");
132
133 // TODO: this might be a bit too strict. We might want to allow unions in the future.
134 static_assert(!std::is_union_v<T_no_const>, "MPI does not support union types.");
135
136 static_assert(!std::is_void_v<T_no_const>, "There is no MPI datatype corresponding to void.");
137
138 if constexpr (is_builtin_type_v<T_no_const>) {
139 // builtin types are handled by the builtin_type trait
141 } else if constexpr (std::is_enum_v<T_no_const>) {
142 // enums are mapped to the underlying type
144 } else if constexpr (std::is_array_v<T_no_const>) {
145 // arrays are mapped to contiguous types
146 constexpr size_t array_size = std::extent_v<T_no_const>;
147 using underlying_type = std::remove_extent_t<T_no_const>;
149 } else if constexpr (internal::is_std_array<T_no_const>::value) {
150 // std::array is mapped to contiguous types
154 } else if constexpr (std::is_trivially_copyable_v<T_no_const>) {
155 // all other trivially copyable types are mapped to a sequence of bytes
157 } else {
158 return no_matching_type{};
159 }
160}
161
162/// @brief The type trait that maps a C++ type \p T to a type trait that can be used to construct an MPI_Datatype.
163///
164/// The default behavior is controlled by \ref type_dispatcher. If you want to support a type that is not supported by
165/// the default behavior, you can specialize this trait. For example:
166///
167/// ```cpp
168/// struct MyType {
169/// int a;
170/// double b;
171/// char c;
172/// std::array<int, 3> d;
173/// };
174/// namespace kamping {
175/// // using KaMPIng's built-in struct serializer
176/// template <>
177/// struct mpi_type_traits<MyType> : struct_type<MyType> {};
178///
179/// // or using an explicitly constructed type
180/// template <>
181/// struct mpi_type_traits<MyType> {
182/// static constexpr bool has_to_be_committed = true;
183/// static MPI_Datatype data_type() {
184/// MPI_Datatype type;
185/// MPI_Type_create_*(..., &type);
186/// return type;
187/// }
188/// };
189/// } // namespace kamping
190/// ```
191///
192template <typename T, typename Enable = void>
194
195/// @brief The type trait that maps a C++ type \p T to a type trait that can be used to construct an MPI_Datatype.
196///
197/// The default behavior is controlled by \ref type_dispatcher. If you want to support a type that is not supported by
198/// the default behavior, you can specialize this trait. For example:
199///
200/// ```cpp
201/// struct MyType {
202/// int a;
203/// double b;
204/// char c;
205/// std::array<int, 3> d;
206/// };
207/// namespace kamping {
208/// // using KaMPIng's built-in struct serializer
209/// template <>
210/// struct mpi_type_traits<MyType> : struct_type<MyType> {};
211///
212/// // or using an explicitly constructed type
213/// template <>
214/// struct mpi_type_traits<MyType> {
215/// static constexpr bool has_to_be_committed = true;
216/// static MPI_Datatype data_type() {
217/// MPI_Datatype type;
218/// MPI_Type_create_*(..., &type);
219/// return type;
220/// }
221/// };
222/// } // namespace kamping
223/// ```
224///
225template <typename T>
226struct mpi_type_traits<T, std::enable_if_t<!std::is_same_v<decltype(type_dispatcher<T>()), no_matching_type>>> {
227 /// @brief The base type of this trait obtained via \ref type_dispatcher.
228 /// This defines how the data type is constructed in \c mpi_type_traits::data_type().
229 using base = decltype(type_dispatcher<T>());
230 /// @brief The category of the type.
231 static constexpr TypeCategory category = base::category;
232 /// @brief Whether the type has to be committed before it can be used in MPI calls.
233 static constexpr bool has_to_be_committed = category_has_to_be_committed(category);
234 /// @brief The MPI_Datatype corresponding to the type T.
236 return decltype(type_dispatcher<T>())::data_type();
237 }
238};
239
240///@brief Check if the type has a static type definition, i.e. \ref mpi_type_traits is defined.
241template <typename, typename Enable = void>
242struct has_static_type : std::false_type {};
243
244///@brief Check if the type has a static type definition, i.e. \ref mpi_type_traits is defined.
245template <typename T>
246struct has_static_type<T, std::void_t<decltype(mpi_type_traits<T>::data_type())>> : std::true_type {};
247
248///@brief Check if the type has a static type definition, i.e. has a corresponding \c MPI_Datatype defined following the
249/// rules from \ref type_dispatcher.
250template <typename T>
252
253/// @brief Register a new \c MPI_Datatype for \p T with the MPI environment. It will be freed when the environment is
254/// finalized.
255///
256/// The \c MPI_Datatype is created using \c mpi_type_traits<T>::data_type() and committed using \c MPI_Type_commit.
257///
258/// @tparam T The type to register.
259template <typename T>
262 MPI_Type_commit(&type);
263 KASSERT(type != MPI_DATATYPE_NULL);
264 mpi_env.register_mpi_type(type);
265 return type;
266}
267
268/// @brief Translate template parameter T to an MPI_Datatype. If no corresponding MPI_Datatype exists, we will create
269/// new continuous type.
270/// Based on https://gist.github.com/2b-t/50d85115db8b12ed263f8231abf07fa2
271/// To check if type \c T maps to a builtin \c MPI_Datatype at compile-time, use \c mpi_type_traits.
272/// @tparam T The type to translate into an MPI_Datatype.
273/// @return The tag identifying the corresponding MPI_Datatype or the newly created type.
274/// @see mpi_custom_continuous_type()
275///
276
277/// @brief Translate type \p T to an MPI_Datatype using the type defined via \ref mpi_type_traits.
278///
279/// If the type has not been registered with MPI yet, it will be created and committed and automatically registered with
280/// the MPI environment, such that it will be freed when the environment is finalized.
281///
282/// @tparam T The type to translate into an MPI_Datatype.
283template <typename T>
285 static_assert(
287 "\n --> Type not supported directly by KaMPIng. Please provide a specialization for mpi_type_traits."
288 );
290 // using static initialization to ensure that the type is only committed once
292 return type;
293 } else {
295 }
296}
297
298template <typename T, size_t N>
300 MPI_Datatype type;
302 if constexpr (std::is_same_v<T, std::byte>) {
304 } else {
305 static_assert(
307 "\n --> Type not supported directly by KaMPIng. Please provide a specialization for mpi_type_traits."
308 );
310 }
311 int count = static_cast<int>(N);
312 int err = MPI_Type_contiguous(count, base_type, &type);
314 return type;
315}
316
317namespace internal {
318/// @brief Applies functor \p f to each field of the tuple with an index in index sequence \p Is.
319///
320/// \p f should be a callable that takes a reference to the field and its index.
321template <typename T, typename F, size_t... Is>
322void for_each_tuple_field(T&& t, F&& f, std::index_sequence<Is...>) {
323 (f(std::get<Is>(std::forward<T>(t)), Is), ...);
324}
325
326/// @brief Applies functor \p f to each field of the tuple \p t.
327///
328/// \p f should be a callable that takes a reference to the field and its index.
329template <typename T, typename F>
330void for_each_tuple_field(T& t, F&& f) {
331 for_each_tuple_field(t, std::forward<F>(f), std::make_index_sequence<std::tuple_size_v<T>>{});
332}
333
334/// @brief Applies functor \p f to each field of the tuple-like type \p t.
335/// This works for `std::pair` and `std::tuple` as well as types that are reflectable with
336/// [pfr](https://github.com/apolukhin/pfr_non_boost).
337///
338/// \p f should be a callable that takes a reference to the field and
339/// its index.
340template <typename T, typename F>
341void for_each_field(T& t, F&& f) {
343 for_each_tuple_field(t, std::forward<F>(f));
344 } else {
345 pfr::for_each_field(t, std::forward<F>(f));
346 }
347}
348
349/// @brief The number of elements in a tuple-like type.
350/// This works for `std::pair` and `std::tuple` as well as types that are reflectable with
351/// [pfr](https://github.com/apolukhin/pfr_non_boost).
352template <typename T>
353constexpr size_t tuple_size = [] {
354 if constexpr (internal::is_std_pair<T>::value) {
355 return 2;
356 } else if constexpr (internal::is_std_tuple<T>::value) {
357 return std::tuple_size_v<T>;
358 } else {
359 return pfr::tuple_size_v<T>;
360 }
361}();
362} // namespace internal
363
364template <typename T>
366 T t{};
367 MPI_Aint base;
368 MPI_Get_address(&t, &base);
369 int blocklens[internal::tuple_size<T>];
370 MPI_Datatype types[internal::tuple_size<T>];
371 MPI_Aint disp[internal::tuple_size<T>];
372 internal::for_each_field(t, [&](auto& elem, size_t i) {
374 using elem_type = std::remove_reference_t<decltype(elem)>;
375 static_assert(
377 "\n --> Type not supported directly by KaMPIng. Please provide a specialization for mpi_type_traits."
378 );
380 disp[i] = MPI_Aint_diff(disp[i], base);
381 blocklens[i] = 1;
382 });
383 MPI_Datatype type;
384 int err = MPI_Type_create_struct(static_cast<int>(internal::tuple_size<T>), blocklens, disp, types, &type);
387 err = MPI_Type_create_resized(type, 0, sizeof(T), &resized_type);
389 return resized_type;
390}
391
392/// @brief A scoped MPI_Datatype that commits the type on construction and frees it on destruction.
393/// This is useful for RAII-style management of MPI_Datatype objects.
395 MPI_Datatype _type; ///< The MPI_Datatype.
396public:
397 /// @brief Construct a new scoped MPI_Datatype and commits it. If no type is provided, default to
398 /// `MPI_DATATYPE_NULL` and does not commit or free anything.
400 if (type != MPI_DATATYPE_NULL) {
401 mpi_env.commit(type);
402 }
403 }
404 /// @brief Deleted copy constructor.
406 /// @brief Deleted copy assignment.
408
409 /// @brief Move constructor.
413 /// @brief Move assignment.
415 std::swap(_type, other._type);
416 return *this;
417 }
418 /// @brief Get the MPI_Datatype.
419 MPI_Datatype const& data_type() const {
420 return _type;
421 }
422 /// @brief Free the MPI_Datatype.
424 if (_type != MPI_DATATYPE_NULL) {
425 mpi_env.free(_type);
426 }
427 }
428};
429
430/// @}
431
432} // namespace kamping
Mapping of C++ datatypes to builtin MPI types.
STL-compatible allocator for requesting memory using the builtin MPI allocator.
Definition allocator.hpp:32
A scoped MPI_Datatype that commits the type on construction and frees it on destruction....
Definition mpi_datatype.hpp:394
ScopedDatatype(ScopedDatatype const &)=delete
Deleted copy constructor.
ScopedDatatype & operator=(ScopedDatatype &&other) noexcept
Move assignment.
Definition mpi_datatype.hpp:414
ScopedDatatype(ScopedDatatype &&other) noexcept
Move constructor.
Definition mpi_datatype.hpp:410
ScopedDatatype & operator=(ScopedDatatype const &)=delete
Deleted copy assignment.
ScopedDatatype(MPI_Datatype type=MPI_DATATYPE_NULL)
Construct a new scoped MPI_Datatype and commits it. If no type is provided, default to MPI_DATATYPE_N...
Definition mpi_datatype.hpp:399
~ScopedDatatype()
Free the MPI_Datatype.
Definition mpi_datatype.hpp:423
MPI_Datatype const & data_type() const
Get the MPI_Datatype.
Definition mpi_datatype.hpp:419
Wrapper for MPI functions that don't require a communicator.
Environment< InitMPIMode::NoInitFinalize > const mpi_env
A global environment object to use when you don't want to create a new Environment object.
Definition environment.hpp:323
#define THROW_IF_MPI_ERROR(error_code, function)
Wrapper around THROWING_KASSERT for MPI errors.
Definition error_handling.hpp:33
auto type_dispatcher()
The type dispatcher that maps a C++ type T to a type trait that can be used to construct an MPI_Datat...
Definition mpi_datatype.hpp:121
static constexpr bool has_static_type_v
Check if the type has a static type definition, i.e. has a corresponding MPI_Datatype defined followi...
Definition mpi_datatype.hpp:251
static MPI_Datatype data_type()
The MPI_Datatype corresponding to the type.
Definition mpi_datatype.hpp:365
MPI_Datatype mpi_datatype() KAMPING_NOEXCEPT
Translate template parameter T to an MPI_Datatype. If no corresponding MPI_Datatype exists,...
Definition mpi_datatype.hpp:284
static MPI_Datatype data_type()
The MPI_Datatype corresponding to the type.
Definition mpi_datatype.hpp:299
constexpr bool category_has_to_be_committed(TypeCategory category)
Checks if a type of the given category has to commited before usage in MPI calls.
Definition builtin_types.hpp:35
TypeCategory
the members specify which group the datatype belongs to according to the type groups specified in Sec...
Definition builtin_types.hpp:32
MPI_Datatype construct_and_commit_type()
Register a new MPI_Datatype for T with the MPI environment. It will be freed when the environment is ...
Definition mpi_datatype.hpp:260
void for_each_tuple_field(T &&t, F &&f, std::index_sequence< Is... >)
Applies functor f to each field of the tuple with an index in index sequence Is.
Definition mpi_datatype.hpp:322
void for_each_field(T &t, F &&f)
Applies functor f to each field of the tuple-like type t. This works for std::pair and std::tuple as ...
Definition mpi_datatype.hpp:341
constexpr size_t tuple_size
The number of elements in a tuple-like type. This works for std::pair and std::tuple as well as types...
Definition mpi_datatype.hpp:353
STL namespace.
Defines the macro KAMPING_NOEXCEPT to be used instad of noexcept.
#define KAMPING_NOEXCEPT
noexcept macro.
Definition noexcept.hpp:19
Constructs a type that is serialized as a sequence of sizeof(T) bytes using MPI_BYTE....
Definition mpi_datatype.hpp:81
Constructs an contiguous type of size N from type T using MPI_Type_contiguous.
Definition mpi_datatype.hpp:70
static constexpr bool has_to_be_committed
Whether the type has to be committed before it can be used in MPI calls.
Definition mpi_datatype.hpp:73
static constexpr TypeCategory category
Definition mpi_datatype.hpp:71
Check if the type has a static type definition, i.e. mpi_type_traits is defined.
Definition mpi_datatype.hpp:242
T value_type
The type of the elements in the array.
Definition mpi_datatype.hpp:63
Helper to check if a type is a std::array.
Definition mpi_datatype.hpp:58
Helper to check if a type is a std::pair.
Definition mpi_datatype.hpp:44
Helper to check if a type is a std::tuple.
Definition mpi_datatype.hpp:51
Tag used for indicating that a struct is reflectable.
Definition mpi_datatype.hpp:32
static MPI_Datatype data_type()
The MPI_Datatype corresponding to the type T.
Definition mpi_datatype.hpp:235
The type trait that maps a C++ type T to a type trait that can be used to construct an MPI_Datatype.
Definition mpi_datatype.hpp:193
Type tag for indicating that no static type definition exists for a type.
Definition mpi_datatype.hpp:107
Constructs a MPI_Datatype for a struct-like type.
Definition mpi_datatype.hpp:92
static constexpr TypeCategory category
The category of the type.
Definition mpi_datatype.hpp:99
static constexpr bool has_to_be_committed
Whether the type has to be committed before it can be used in MPI calls.
Definition mpi_datatype.hpp:101