Use a macro for when __has_cpp_attribute is unsupported
[openal-soft.git] / common / opthelpers.h
blob596c24554d510c1f5951819bb2f2c0bbfa723067
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 #elif defined(_MSC_VER)
23 #define force_inline __forceinline
24 #else
25 #define force_inline inline
26 #endif
28 /* Unlike the likely attribute, ASSUME requires the condition to be true or
29 * else it invokes undefined behavior. It's essentially an assert without
30 * actually checking the condition at run-time, allowing for stronger
31 * optimizations than the likely attribute.
33 #if HAS_BUILTIN(__builtin_assume)
34 #define ASSUME __builtin_assume
35 #elif defined(_MSC_VER)
36 #define ASSUME __assume
37 #elif __has_attribute(assume)
38 #define ASSUME(x) [[assume(x)]]
39 #elif HAS_BUILTIN(__builtin_unreachable)
40 #define ASSUME(x) do { if(x) break; __builtin_unreachable(); } while(0)
41 #else
42 #define ASSUME(x) ((void)0)
43 #endif
45 /* This shouldn't be needed since unknown attributes are ignored, but older
46 * versions of GCC choke on the attribute syntax in certain situations.
48 #if HAS_ATTRIBUTE(likely)
49 #define LIKELY [[likely]]
50 #define UNLIKELY [[unlikely]]
51 #else
52 #define LIKELY
53 #define UNLIKELY
54 #endif
56 namespace al {
58 template<typename T>
59 constexpr std::underlying_type_t<T> to_underlying(T e) noexcept
60 { return static_cast<std::underlying_type_t<T>>(e); }
62 [[noreturn]] inline void unreachable()
64 #if HAS_BUILTIN(__builtin_unreachable)
65 __builtin_unreachable();
66 #else
67 ASSUME(false);
68 #endif
71 template<std::size_t alignment, typename T>
72 force_inline constexpr auto assume_aligned(T *ptr) noexcept
74 #ifdef __cpp_lib_assume_aligned
75 return std::assume_aligned<alignment,T>(ptr);
76 #elif HAS_BUILTIN(__builtin_assume_aligned)
77 return static_cast<T*>(__builtin_assume_aligned(ptr, alignment));
78 #elif defined(_MSC_VER)
79 constexpr std::size_t alignment_mask{(1<<alignment) - 1};
80 if((reinterpret_cast<std::uintptr_t>(ptr)&alignment_mask) == 0)
81 return ptr;
82 __assume(0);
83 #elif defined(__ICC)
84 __assume_aligned(ptr, alignment);
85 return ptr;
86 #else
87 return ptr;
88 #endif
91 } // namespace al
93 #endif /* OPTHELPERS_H */