]> git.sesse.net Git - movit/blob - fp16.h
Make all fp16 routines work with fp32 as input instead of fp64, since that is what...
[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 float fp16_to_fp32(fp16_int_t x)
30 {
31         return _cvtsh_ss(x.val);
32 }
33
34 static inline fp16_int_t fp32_to_fp16(float x)
35 {
36         fp16_int_t ret;
37         ret.val = _cvtss_sh(x, 0);
38         return ret;
39 }
40
41 #else
42
43 float fp16_to_fp32(fp16_int_t x);
44 fp16_int_t fp32_to_fp16(float x);
45
46 #endif
47
48 // Overloads for use in templates.
49 static inline float to_fp32(double x) { return x; }
50 static inline float to_fp32(float x) { return x; }
51 static inline float to_fp32(fp16_int_t x) { return fp16_to_fp32(x); }
52
53 template<class T> inline T from_fp32(float x);
54 template<> inline double from_fp32<double>(float x) { return x; }
55 template<> inline float from_fp32<float>(float x) { return x; }
56 template<> inline fp16_int_t from_fp32<fp16_int_t>(float x) { return fp32_to_fp16(x); }
57
58 template<class From, class To>
59 inline To convert_float(From x) { return from_fp32<To>(to_fp32(x)); }
60
61 template<class Same>
62 inline Same convert_float(Same x) { return x; }
63
64 }  // namespace movit
65
66 #endif  // _MOVIT_FP16_H