iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😎

Can Multiplying a Floating-Point Number by 1 Be Optimized? / On the Canonicity of Floating-Point Bit Representations

に公開

Consider a function that multiplies a floating-point number by 1:

void multiply_one(double *x)
{
    static const volatile double one = 1.0;
    *x *= one;
}

Mathematically, this function is the identity function—it returns the input unchanged. But what about for floating-point numbers? Specifically, does this function change the bit-level representation of the given floating-point number?

Many people might think "it won't change" or "even if it does, the difference isn't important," but this becomes a significant issue when considering compiler optimizations. Of course, in a "don't care about floating-point intricacies" mode, it would be fine to optimize it away, but here we consider a compiler that cares about every last detail of floating-point numbers.

Let's create a simple program and test it with several values:

#include <inttypes.h>
#include <stdio.h>
#include <string.h>

void multiply_one(double *x)
{
    static const volatile double one = 1.0;
    *x *= one;
}

void make_f64(double *x, uint64_t data)
{
    memcpy(x, &data, 8);
}

void print_f64(const char *s, double *x)
{
    uint64_t data;
    memcpy(&data, x, 8);
    printf("%s: %g, 0x%016" PRIx64 "\n", s, *x, data);
}

int main(void)
{
    double x = 3.14;
    print_f64("3.14 (before)", &x);
    multiply_one(&x);
    print_f64("3.14 (after)", &x);
    x = -0.0;
    print_f64("-0.0 (before)", &x);
    multiply_one(&x);
    print_f64("-0.0 (after)", &x);
    make_f64(&x, 0x7ff8000000c0ffee);
    print_f64("NaN (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f64("NaN (c0ffee) (after)", &x);
}
$ uname -m
x86_64
$ cc test.c
$ ./a.out
3.14 (before): 3.14, 0x40091eb851eb851f
3.14 (after): 3.14, 0x40091eb851eb851f
-0.0 (before): -0, 0x8000000000000000
-0.0 (after): -0, 0x8000000000000000
NaN (c0ffee) (before): nan, 0x7ff8000000c0ffee
NaN (c0ffee) (after): nan, 0x7ff8000000c0ffee

Running this on an x86_64 machine shows that for these three examples, the bit representation appears unchanged.

This article explores the "multiply by 1" function, investigating:

  • What about other data types?
  • What about more special floating-point data?
  • What happens when we change floating-point operation settings?
  • What about other architectures?

We'll also touch on the related concept of "canonicity of floating-point bit representations."

Decimal Floating-Point Numbers

IEEE 754 defines bit representations for decimal floating-point numbers. Please refer to the article "Basics of IEEE 754 Decimal Floating-Point Numbers" for an overview of decimal floating-point numbers.

Let's try the same experiment with decimal floating-point numbers using GCC:

#include <inttypes.h>
#include <stdio.h>
#include <string.h>

void multiply_one(_Decimal32 *x)
{
    static const volatile _Decimal32 one = 1.0df;
    *x *= one;
}

void make_d32(_Decimal32 *x, uint32_t data)
{
    memcpy(x, &data, 4);
}

void print_d32(const char *s, _Decimal32 *x)
{
    uint32_t data;
    memcpy(&data, x, 4);
    printf("%s: %g, 0x%08" PRIx32 "\n", s, (double)*x, data);
}

int main(void)
{
    _Decimal32 x = 7.df;
    print_d32("7 (before)", &x);
    multiply_one(&x);
    print_d32("7 (after)", &x);
    x = -0.0df;
    print_d32("-0.0 (before)", &x);
    multiply_one(&x);
    print_d32("-0.0 (after)", &x);
    make_d32(&x, 0x62ffffff); // 0b0'110 0010 1'111 ...
    print_d32("0x62ffffff (before)", &x);
    multiply_one(&x);
    print_d32("0x62ffffff (after)", &x);
    make_d32(&x, 0x7c0ffee0);
    print_d32("NaN (0x7c0ffee0) (before)", &x);
    multiply_one(&x);
    print_d32("NaN (0x7c0ffee0) (after)", &x);
}

Results on x86_64 Linux GCC 13.3:

$ gcc decimal32.c
$ ./a.out
7 (before): 7, 0x32800007
7 (after): 7, 0x32000046
-0.0 (before): -0, 0xb2000000
-0.0 (after): -0, 0xb1800000
0x62ffffff (before): 0, 0x62ffffff
0x62ffffff (after): 0, 0x0b000000
NaN (0x7c0ffee0) (before): nan, 0x7c0ffee0
NaN (0x7c0ffee0) (after): nan, 0x7c000000

Surprisingly, the bit representation changed even though we only multiplied by 1.0!

The bit representation of 7 and -0.0 changed because we multiplied by 1.0, a number with trailing zeros in its significand, causing the number of trailing zeros in the significand to increase while the exponent was adjusted accordingly. The representation changed to a different one belonging to the same cohort.

Thus, for IEEE 754 decimal floating-point numbers, it is necessary to distinguish between "multiply by 1.0" and "multiply by 1".

If we use 1.df instead of 1.0df, the bit representations of 7 and -0.0 remain unchanged:

// ...

void multiply_one(_Decimal32 *x)
{
    static const volatile _Decimal32 one = 1.df;
    *x *= one;
}

// ...
$ gcc decimal32-2.c
$ ./a.out
7 (before): 7, 0x32800007
7 (after): 7, 0x32800007
-0.0 (before): -0, 0xb2000000
-0.0 (after): -0, 0xb2000000
0x62ffffff (before): 0, 0x62ffffff
0x62ffffff (after): 0, 0x0b800000
NaN (0x7c0ffee0) (before): nan, 0x7c0ffee0
NaN (0x7c0ffee0) (after): nan, 0x7c000000

The floating-point number 1.df should behave as a number that "does nothing when multiplied" to the representation of floating-point data, and indeed the bit representation remains unchanged for 7 and -0.0, but it still changes the bit representation for the values represented by bit patterns 0x62ffffff and 0x7c0ffee0.

The bit pattern 0x62ffffff, when cast to double, appears to represent the value 0. Similarly, the bit pattern 0x7c0ffee0 appears to represent NaN. These bit patterns are non-canonical representations of 0 and NaN, and applying a floating-point operation (even one that doesn't change the floating-point data) converts them to canonical bit representations (normalization).

This is the "canonicity of floating-point bit representations" as defined by IEEE 754. While there are 2^{32} possible bit patterns for the decimal32 format, the number of data representations (for normal numbers: the combination of sign, exponent, and significand; for NaN: sign and payload) is smaller, leading to overlap in encoding/decoding. IEEE 754 designates one of the multiple possible bit patterns as the canonical encoding and states that floating-point operations should generally return canonical bit representations (except for operations that only manipulate the sign bit).

Therefore, even a numerically no-op floating-point operation like "multiply by 1" can exhibit the behavior of converting a non-canonical bit representation to a canonical one.

From a compiler's perspective, this means that even if a floating-point operation "does nothing" numerically, optimizing it away could change the behavior when the bit representation is observable.

Signaling NaN

For signaling NaN, please refer to "Binary Hacks Rebooted", specifically "Hack #74 Deep Dive into NaN".

In principle, when a signaling NaN is given as input to a floating-point operation, it raises a floating-point exception and (by default) returns a quiet NaN (except for operations that only manipulate the sign bit). Therefore, multiplying a signaling NaN by 1 changes its bit representation.

#include <inttypes.h>
#include <stdio.h>
#include <string.h>

void multiply_one(double *x)
{
    static const volatile double one = 1.0;
    *x *= one;
}

void make_f64(double *x, uint64_t data)
{
    memcpy(x, &data, 8);
}

void print_f64(const char *s, double *x)
{
    uint64_t data;
    memcpy(&data, x, 8);
    printf("%s: %g, 0x%016" PRIx64 "\n", s, *x, data);
}

int main(void)
{
    double x = 3.14;
    print_f64("3.14 (before)", &x);
    multiply_one(&x);
    print_f64("3.14 (after)", &x);
    x = -0.0;
    print_f64("-0.0 (before)", &x);
    multiply_one(&x);
    print_f64("-0.0 (after)", &x);
    make_f64(&x, 0x7ff0000000c0ffee);
    print_f64("sNaN (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f64("sNaN (c0ffee) (after)", &x);
}
$ gcc snan.c
$ ./a.out
3.14 (before): 3.14, 0x40091eb851eb851f
3.14 (after): 3.14, 0x40091eb851eb851f
-0.0 (before): -0, 0x8000000000000000
-0.0 (after): -0, 0x8000000000000000
sNaN (c0ffee) (before): nan, 0x7ff0000000c0ffee
sNaN (c0ffee) (after): nan, 0x7ff8000000c0ffee

We can see that the bit representation of the signaling NaN (0x7ff0...) changed to a quiet NaN (0x7ff8...).

x87 FPU 80-bit Extended Precision

The internal floating-point format of the x87 FPU is 80 bits, and some implementations make it available as the long double type. For more about the x87 FPU, see "The Curse of the x87 FPU" and "About long double".

The bit representation of this format is not defined by IEEE 754. Unlike IEEE 754 interchange formats that use the so-called "implicit leading bit," this format stores the leading 1 of the significand in the bit representation.

So, how does the x87 FPU handle a value where the leading bit of the significand is not 1? Let's test it.

#include <inttypes.h>
#include <stdio.h>
#include <string.h>

void multiply_one(long double *x)
{
    static const volatile long double one = 1.0L;
    *x *= one;
}

void make_f80(long double *x, uint16_t e, uint64_t m)
{
    char buf[10];
    memcpy(buf, &m, 8);
    memcpy(buf + 8, &e, 2);
    memcpy(x, buf, 10);
}

void print_f80(const char *s, long double *x)
{
    uint16_t e;
    uint64_t m;
    char buf[10];
    memcpy(buf, x, 10);
    memcpy(&m, buf, 8);
    memcpy(&e, buf + 8, 2);
    printf("%s: %Lg, 0x%04" PRIx16 "%016" PRIx64 "\n", s, *x, e, m);
}

int main(void)
{
    long double x = 3.14L;
    print_f80("3.14 (before)", &x);
    multiply_one(&x);
    print_f80("3.14 (after)", &x);
    x = -0.0L;
    print_f80("-0.0 (before)", &x);
    multiply_one(&x);
    print_f80("-0.0 (after)", &x);
    x = 0x1p-16400L;
    print_f80("0x1p-16400 (before)", &x);
    multiply_one(&x);
    print_f80("0x1p-16400 (after)", &x);
    x = 1.0L / 0.0L;
    print_f80("infinity (before)", &x);
    multiply_one(&x);
    print_f80("infinity (after)", &x);
    make_f80(&x, 0x7fff, 0xc000000000c0ffee);
    print_f80("qNaN (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f80("qNaN (c0ffee) (after)", &x);
    make_f80(&x, 0x7fff, 0x8000000000c0ffee);
    print_f80("sNaN (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f80("sNaN (c0ffee) (after)", &x);
    //
    // Now for the real main event
    //
    make_f80(&x, 0x7fff, 0x0000000000c0ffee);
    print_f80("pseudo sNaN (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f80("pseudo sNaN (c0ffee) (after)", &x);
    make_f80(&x, 0x7fff, 0x4000000000c0ffee);
    print_f80("pseudo qNaN (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f80("pseudo qNaN (c0ffee) (after)", &x);
    make_f80(&x, 0x7fff, 0x0000000000000000);
    print_f80("pseudo infinity (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f80("pseudo infinity (c0ffee) (after)", &x);
    make_f80(&x, 0x3fff, 0x0000000000000003);
    print_f80("unnormal (before)", &x);
    multiply_one(&x);
    print_f80("unnormal (after)", &x);
    make_f80(&x, 0x0000, 0x9000000000000003);
    print_f80("pseudo denormal (before)", &x);
    multiply_one(&x);
    print_f80("pseudo denormal (after)", &x);
}
$ gcc x87.c 
$ ./a.out
3.14 (before): 3.14, 0x4000c8f5c28f5c28f5c3
3.14 (after): 3.14, 0x4000c8f5c28f5c28f5c3
-0.0 (before): -0, 0x80000000000000000000
-0.0 (after): -0, 0x80000000000000000000
0x1p-16400 (before): 1.28254e-4937, 0x00000000200000000000
0x1p-16400 (after): 1.28254e-4937, 0x00000000200000000000
infinity (before): inf, 0x7fff8000000000000000
infinity (after): inf, 0x7fff8000000000000000
qNaN (c0ffee) (before): nan, 0x7fffc000000000c0ffee
qNaN (c0ffee) (after): nan, 0x7fffc000000000c0ffee
sNaN (c0ffee) (before): nan, 0x7fff8000000000c0ffee
sNaN (c0ffee) (after): nan, 0x7fffc000000000c0ffee
pseudo sNaN (c0ffee) (before): nan, 0x7fff0000000000c0ffee
pseudo sNaN (c0ffee) (after): -nan, 0xffffc000000000000000
pseudo qNaN (c0ffee) (before): nan, 0x7fff4000000000c0ffee
pseudo qNaN (c0ffee) (after): -nan, 0xffffc000000000000000
pseudo infinity (c0ffee) (before): nan, 0x7fff0000000000000000
pseudo infinity (c0ffee) (after): -nan, 0xffffc000000000000000
unnormal (before): nan, 0x3fff0000000000000003
unnormal (after): -nan, 0xffffc000000000000000
pseudo denormal (before): 4.20263e-4933, 0x00009000000000000003
pseudo denormal (after): 3.78237e-4932, 0x00019000000000000003

In the Intel SDM, a NaN with a leading 0 in its significand is called a pseudo-NaN, infinity with a leading 0 is called pseudo-infinity, a number with a leading 0 in the significand and an exponent in the normal range is called unnormal, and a number with a leading 1 in the significand and an exponent corresponding to a denormal number is called a pseudo-denormal.

When the x87 FPU encounters a pseudo-NaN, pseudo-infinity, or unnormal, it raises an invalid exception. On x86, the default handling of an invalid exception returns a quiet NaN with the sign bit set, which explains these results. Pseudo-denormals are converted to normalized numbers.

In any case, we can see that the x87 80-bit extended precision format also has many "bit representations that change when multiplied by 1."

Flush to Zero and Denormalized Numbers

Some environments, such as x86, Arm, and GPUs, have a mode that treats denormalized numbers as zero. Here we call it flush to zero. This is explained in "[Binary Hacks Rebooted]" (Hack #71 Floating-Point Exceptions).

With flush to zero enabled, let's multiply a denormalized number by 1.

#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#if defined(__SSE2__)
#include <immintrin.h>
#elif defined(__aarch64__)
#include <arm_acle.h>
#endif

void multiply_one(double *x)
{
    static const volatile double one = 1.0;
    *x *= one;
}

void print_f64(const char *s, double *x)
{
    uint64_t data;
    memcpy(&data, x, 8);
    printf("%s: %g, 0x%016" PRIx64 "\n", s, *x, data);
}

int main(void)
{
    double x = 0x1.cafep-1050;
    print_f64("0x1.cafep-1050 (before)", &x);
#if defined(__SSE2__)
    unsigned int csr = _mm_getcsr();
    _mm_setcsr(csr | (1u << 15)); // Set FTZ (Flush to Zero)
#elif defined(__aarch64__)
    // Set FZ (Flushing denormalized numbers to zero)
    uint64_t fpcr = __arm_rsr64("fpcr");
    __arm_wsr64("fpcr", fpcr | (1u << 24));
#endif
    multiply_one(&x);
    print_f64("0x1.cafep-1050 (after)", &x);
}
$ cc fz.c
$ ./a.out
0x1.cafep-1050 (before): 1.48617e-316, 0x0000000001cafe00
0x1.cafep-1050 (after): 0, 0x0000000000000000

It became 0.

Strictly speaking, on x86, the setting that returns 0 instead of a denormalized number when underflow occurs is called Flush-To-Zero (FTZ), and the setting that treats denormalized numbers in input as 0 is called Denormals-Are-Zero (DAZ). In either case, 0 is returned here.

Thus, on x86 and Arm with flush to zero enabled, denormalized numbers also fall into the category of "values whose bit representation (and even the value) changes when multiplied by 1."

RISC-V Canonical NaN and Arm Default NaN

In the initial x86 execution example, the NaN payload remained unchanged after multiplying by 1.

NaN (c0ffee) (before): nan, 0x7ff8000000c0ffee
NaN (c0ffee) (after): nan, 0x7ff8000000c0ffee

On RISC-V, this changes. Let's try it on QEMU for Linux:

$ riscv64-linux-gnu-gcc test.c
$ qemu-riscv64 -L /usr/riscv64-linux-gnu/ ./a.out
3.14 (before): 3.14, 0x40091eb851eb851f
3.14 (after): 3.14, 0x40091eb851eb851f
-0.0 (before): -0, 0x8000000000000000
-0.0 (after): -0, 0x8000000000000000
NaN (c0ffee) (before): nan, 0x7ff8000000c0ffee
NaN (c0ffee) (after): nan, 0x7ff8000000000000

In RISC-V extensions for floating-point, a NaN with a sign bit of 0 and a payload of 0 is called a "canonical NaN," and NaNs generated by floating-point operations are specified to be that form.

Arm also has a similar mode called Default NaN.

#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#if defined(__aarch64__)
#include <arm_acle.h>
#endif

void multiply_one(double *x)
{
    static const volatile double one = 1.0;
    *x *= one;
}

void make_f64(double *x, uint64_t data)
{
    memcpy(x, &data, 8);
}

void print_f64(const char *s, double *x)
{
    uint64_t data;
    memcpy(&data, x, 8);
    printf("%s: %g, 0x%016" PRIx64 "\n", s, *x, data);
}

int main(void)
{
#if defined(__aarch64__)
    // Set DN (Default NaN)
    uint64_t fpcr = __arm_rsr64("fpcr");
    __arm_wsr64("fpcr", fpcr | (1u << 25));
#endif
    double x;
    make_f64(&x, 0x7ff8000000c0ffee);
    print_f64("NaN (c0ffee) (before)", &x);
    multiply_one(&x);
    print_f64("NaN (c0ffee) (after)", &x);
    make_f64(&x, 0xfff8000000c0ffee);
    print_f64("NaN (negative, c0ffee) (before)", &x);
    multiply_one(&x);
    print_f64("NaN (negative, c0ffee) (after)", &x);
}
$ clang default-nan.c 
$ ./a.out
NaN (c0ffee) (before): nan, 0x7ff8000000c0ffee
NaN (c0ffee) (after): nan, 0x7ff8000000000000
NaN (negative, c0ffee) (before): nan, 0xfff8000000c0ffee
NaN (negative, c0ffee) (after): nan, 0x7ff8000000000000

Canonicity

In this article, we have seen cases where the operation "multiply by 1" can change the bit representation:

  • For decimal formats
  • When the input is a signaling NaN
  • When the input is a special bit pattern in the x87 FPU's 80-bit format
  • When flush to zero is enabled and the input is a denormalized number
  • When a NaN with a payload is given on RISC-V or with Arm Default NaN enabled

While the IEEE 754 standard's mention of "non-canonical encodings" is limited to decimal interchange formats (binary interchange formats are said to have all numbers and NaNs encoded canonically), these other examples could be said to be similar in the sense that "the bit pattern changes when passed through an arithmetic unit." RISC-V even uses the word "canonical."

The IEEE 754 isCanonical operation and the C23 macro iscanonical can determine whether a given value is canonical. For decimal, that's straightforward. A signaling NaN would likely be determined as "canonical." IEEE 754-2019 states:

Implementations should extend isCanonical(x) to formats that are not interchange formats in ways appropriate to those formats, which might, or might not, have finite numbers, infinities, or NaNs that are non-canonical.

So, for pseudo- types in the x87 FPU, they would likely be judged as "non-canonical." What about denormalized numbers under flush to zero, or NaNs on RISC-V? I think that's a gray area.

#include <math.c>
int iscanonical(real-floating x); // macro

Compiler Optimization and Canonicalization

Considering the observability of the bit representation of floating-point types and the existence of signaling NaN, compilers cannot simply optimize 1 * x or x - 0 (when the rounding direction attribute is not roundTowardNegative) to x. However, even in the presence of non-canonical bit representations or signaling NaN, optimization seems possible under certain conditions.

Let's refer to "numerically invariant floating-point operations" like 1 * x or x - 0 as canonicalization and represent them with a function canonicalize.

// Optimization rule
1 * x → canonicalize(x)
x - 0 → canonicalize(x)

Then, if the result of canonicalize is used as input to another floating-point operation, the canonicalize can be eliminated.

// Optimization rule
canonicalize(x) ★ y → x ★ y
x ★ canonicalize(y) → x ★ y

Also, if canonicalize is applied to the result of another floating-point operation, it can be eliminated.

// Optimization rule
canonicalize(x ★ y) → x ★ y

Thus, it seems beneficial for the intermediate representation of a compiler that wants to handle floating-point numbers rigorously to have a canonicalize operation.

C23 defines a function named canonicalize.

#include <math.h>
int canonicalize(double *cx, const double *x);
int canonicalizef(float *cx, const float *x);
int canonicalizel(long double *cx, const long double *x);
#ifdef __STDC_IEC_60559_DFP__
int canonicalized32(_Decimal32 *cx, const _Decimal32 *x);
int canonicalized64(_Decimal64 *cx, const _Decimal64 *x);
int canonicalized128(_Decimal128 *cx, const _Decimal128 *x);
#endif

The input to this function is given via *x, and the canonicalized result is stored in *cx. It returns 0 on success and non-zero on failure. This function explicitly states that it transforms non-canonical bit representations into canonical ones, and also converts signaling NaN to quiet NaN. In other words, it seems intended to be implemented by an operation like "multiply by 1."

In IEEE 754 terms, C23's canonicalize corresponds to applying convertFormat to the same format. The reason for using pointers is that, depending on the environment, simply passing an argument or returning a value might involve floating-point arithmetic that could convert the representation to canonical.


That wraps up the discussion on canonicity, a very niche concept related to floating-point numbers. Perhaps it's more of a compiler topic than a floating-point one.

Discussion