How to enable __fp16 type on gcc for x86_64

16.5k Views Asked by At

The __fp16 floating point data-type is a well known extension to the C standard used notably on ARM processors. I would like to run the IEEE version of them on my x86_64 processor. While I know they typically do not have that, I would be fine with emulating them with "unsigned short" storage (they have the same alignment requirement and storage space), and (hardware) float arithmetic.

Is there a way to request that in gcc?

I assume the rounding might be slightly "incorrect", but that is ok to me.

If this were to work in C++ too that would be ideal.

4

There are 4 best solutions below

1
On

The issue with @Nonyme's solution is that using clang -cc1 deprives you from all the implicit parameters that the clang driver provides (in particular, the implicit include paths to system headers). A better solution is to pass the __fp16-related flags to cc1 through clang driver's -Xclang parameter, as in:

clang input.c -Xclang -fnative-half-type -fallow-half-arguments-and-returns
1
On

C++23 introduces std::float16_t

#include <stdfloat> // C++23
 
int main()
{
    std::float16_t f = 0.1F16;
}
0
On

_Float16 is the type you should be looking for now in recent versions of clang and gcc.

At least in the compilers I've worked with __fp16 was a limited type that you could only convert to/from binary32 (using hardware where supported) while _Float16 is more like a "real" arithmetic type, not that you should attempt too much in such limited precision.

2
On

I did not find a way to do so in gcc (as of gcc 8.2.0).

As for clang, in 6.0.0 the following options showed some success:

clang -cc1 -fnative-half-type -fallow-half-arguments-and-returns

The option -fnative-half-type enable the use of __fp16 type (instead of promoting them to float). While the option -fallow-half-arguments-and-returns allows to pass __fp16 by value, the API being non-standard be careful not to mix different compilers.

That being said, it does not provide math functions using __fp16 types (it will promote them to/from float or double).

It was sufficient for my use case.