]> git.sesse.net Git - movit/blob - fp16.h
Make shader generation more deterministic by removing a sort of pointers.
[movit] / fp16.h
1 #ifndef _MOVIT_FP16_H
2 #define _MOVIT_FP16_H 1
3
4 #ifdef __F16C__
5 #include <immintrin.h>
6 #endif
7
8 // Code for converting to and from fp16 (from fp64), without any particular
9 // machine support, with proper IEEE round-to-even behavior (and correct
10 // handling of NaNs and infinities). This is needed because some OpenGL
11 // drivers don't properly round off when asked to convert data themselves.
12 //
13 // These routines are not particularly fast.
14
15 namespace movit {
16
17 // structs instead of ints, so that they are not implicitly convertible.
18 struct fp32_int_t {
19         unsigned int val;
20 };
21 struct fp16_int_t {
22         unsigned short val;
23 };
24
25 #ifdef __F16C__
26
27 // Use the f16c instructions from Haswell if available (and we know that they
28 // are at compile time).
29 static inline double fp16_to_fp64(fp16_int_t x)
30 {
31         return _cvtsh_ss(x.val);
32 }
33
34 static inline fp16_int_t fp64_to_fp16(double x)
35 {
36         // NOTE: Strictly speaking, there are some select values where this isn't correct,
37         // since we first round to fp32 and then to fp16.
38         fp16_int_t ret;
39         ret.val = _cvtss_sh(x, 0);
40         return ret;
41 }
42
43 #else
44
45 double fp16_to_fp64(fp16_int_t x);
46 fp16_int_t fp64_to_fp16(double x);
47
48 #endif
49
50 // These are not very useful by themselves, but are implemented using the same
51 // code as the fp16 ones (just with different constants), so they are useful
52 // for verifying against the FPU in unit tests.
53 double fp32_to_fp64(fp32_int_t x);
54 fp32_int_t fp64_to_fp32(double x);
55
56 // Overloads for use in templates.
57 static inline double to_fp64(double x) { return x; }
58 static inline double to_fp64(float x) { return x; }
59 static inline double to_fp64(fp16_int_t x) { return fp16_to_fp64(x); }
60
61 template<class T> inline T from_fp64(double x);
62 template<> inline double from_fp64<double>(double x) { return x; }
63 template<> inline float from_fp64<float>(double x) { return x; }
64 template<> inline fp16_int_t from_fp64<fp16_int_t>(double x) { return fp64_to_fp16(x); }
65
66 template<class From, class To>
67 inline To convert_float(From x) { return from_fp64<To>(to_fp64(x)); }
68
69 template<class Same>
70 inline Same convert_float(Same x) { return x; }
71
72 }  // namespace movit
73
74 #endif  // _MOVIT_FP16_H