Make sure struct members are initialized
[openal-soft.git] / common / opthelpers.h
blobae2611dad3a45baa779b558c6fe87864e5a038ed
1 #ifndef OPTHELPERS_H
2 #define OPTHELPERS_H
4 #include <cstdint>
5 #include <utility>
6 #include <memory>
8 #ifdef __has_builtin
9 #define HAS_BUILTIN __has_builtin
10 #else
11 #define HAS_BUILTIN(x) (0)
12 #endif
14 #ifdef __has_cpp_attribute
15 #define HAS_ATTRIBUTE __has_cpp_attribute
16 #else
17 #define HAS_ATTRIBUTE(x) (0)
18 #endif
20 #ifdef __GNUC__
21 #define force_inline [[gnu::always_inline]] inline
22 #define NOINLINE [[gnu::noinline]]
23 #elif defined(_MSC_VER)
24 #define force_inline __forceinline
25 #define NOINLINE __declspec(noinline)
26 #else
27 #define force_inline inline
28 #define NOINLINE
29 #endif
31 /* Unlike the likely attribute, ASSUME requires the condition to be true or
32 * else it invokes undefined behavior. It's essentially an assert without
33 * actually checking the condition at run-time, allowing for stronger
34 * optimizations than the likely attribute.
36 #if HAS_BUILTIN(__builtin_assume)
37 #define ASSUME __builtin_assume
38 #elif defined(_MSC_VER)
39 #define ASSUME __assume
40 #elif __has_attribute(assume)
41 #define ASSUME(x) [[assume(x)]]
42 #elif HAS_BUILTIN(__builtin_unreachable)
43 #define ASSUME(x) do { if(x) break; __builtin_unreachable(); } while(0)
44 #else
45 #define ASSUME(x) (static_cast<void>(0))
46 #endif
48 /* This shouldn't be needed since unknown attributes are ignored, but older
49 * versions of GCC choke on the attribute syntax in certain situations.
51 #if HAS_ATTRIBUTE(likely)
52 #define LIKELY [[likely]]
53 #define UNLIKELY [[unlikely]]
54 #else
55 #define LIKELY
56 #define UNLIKELY
57 #endif
59 namespace al {
61 template<typename T>
62 constexpr std::underlying_type_t<T> to_underlying(T e) noexcept
63 { return static_cast<std::underlying_type_t<T>>(e); }
65 [[noreturn]] inline void unreachable()
67 #if HAS_BUILTIN(__builtin_unreachable)
68 __builtin_unreachable();
69 #else
70 ASSUME(false);
71 #endif
74 template<std::size_t alignment, typename T>
75 force_inline constexpr auto assume_aligned(T *ptr) noexcept
77 #ifdef __cpp_lib_assume_aligned
78 return std::assume_aligned<alignment,T>(ptr);
79 #elif HAS_BUILTIN(__builtin_assume_aligned)
80 return static_cast<T*>(__builtin_assume_aligned(ptr, alignment));
81 #elif defined(_MSC_VER)
82 constexpr std::size_t alignment_mask{(1<<alignment) - 1};
83 if((reinterpret_cast<std::uintptr_t>(ptr)&alignment_mask) == 0)
84 return ptr;
85 __assume(0);
86 #elif defined(__ICC)
87 __assume_aligned(ptr, alignment);
88 return ptr;
89 #else
90 return ptr;
91 #endif
94 } // namespace al
96 #endif /* OPTHELPERS_H */