Debian Codegraph @

gcc/testsuite/gcc.target/i386/truncsfbf-2.c

raw
1 /* { dg-do run } */
2 /* { dg-options "-msse2 -O2 -ffast-math" } */
3
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <string.h>
7 #include <math.h>
8
9 __bf16
10 foo (float a)
11 {
12 return a;
13 }
14
15 static __bf16
16 CALC (float *a)
17 {
18 uint32_t bits;
19 memcpy (&bits, a, sizeof (bits));
20 bits >>= 16;
21 uint16_t bfloat16_bits = (uint16_t) bits;
22 __bf16 bf16;
23 memcpy (&bf16, &bfloat16_bits, sizeof (bf16));
24 return bf16;
25 }
26
27 int
28 main (void)
29 {
30 float test_values[] = { 0.0f, -0.0f, 1.0f, -1.0f, 0.5f, -0.5f, 1000.0f, -1000.0f,
31 3.1415926f, -3.1415926f, 1e-8f, -1e-8f,
32 1.0e+38f, -1.0e+38f, 1.0e-38f, -1.0e-38f };
33 size_t num_values = sizeof (test_values) / sizeof (test_values[0]);
34
35 for (size_t i = 0; i < num_values; ++i)
36 {
37 float original = test_values[i];
38 __bf16 hw_bf16 = foo (original);
39 __bf16 sw_bf16 = CALC (&original);
40
41 /* Verify psrld $16, %0 == %0 >> 16 */
42 if (memcmp (&hw_bf16, &sw_bf16, sizeof (__bf16)) != 0)
43 abort ();
44
45 /* Reconstruct the float value from the __bf16 bits */
46 uint16_t bf16_bits;
47 memcpy (&bf16_bits, &hw_bf16, sizeof (bf16_bits));
48 uint32_t reconstructed_bits = ((uint32_t) bf16_bits) << 16;
49 float converted;
50 memcpy (&converted, &reconstructed_bits, sizeof (converted));
51
52 float diff = fabsf (original - converted);
53
54 /* Expected Maximum Precision Loss */
55 uint32_t orig_bits;
56 memcpy (&orig_bits, &original, sizeof (orig_bits));
57 int exponent = ((orig_bits >> 23) & 0xFF) - 127;
58 float expected_loss = (exponent == -127)
59 ? ldexpf (1.0f, -126 - 7)
60 : ldexpf (1.0f, exponent - 7);
61 if (diff > expected_loss)
62 abort ();
63 }
64 return 0;
65 }