Skip to content

isunordered() can miss merging with FP comparisons with same operands if operands are swapped. #157812

@Explorer09

Description

@Explorer09

Clang can tell that the isunordered() operation in C is commutative if evaluated with simple equality like this:

isunordered(y, x) == isunordered(x, y)

But the commutative property is not fully utilized when it comes to merging floating point comparisons with same operands. The generated code can be less optimal once the operands in isunordered are swapped:

#include <math.h>
#include <stdlib.h>
int my_isless1(double x, double y) {
    if (isunordered(x, y))
        abort();
    if (x < y)
        return 1;
    return 0;
}
int my_isless2(double x, double y) {
    if (isunordered(y, x))
        abort();
    if (x < y)
        return 1;
    return 0;
}
int my_isless3(double x, double y) {
    // (x != x) may produce a -Wfloat-equal warning
    if (x != x || y != y)
        abort();
    if (x < y)
        return 1;
    return 0;
}

https://godbolt.org/z/fWc5P41eW
I tested the code with x86-64 Clang 21.1.0, with -O2 option. my_isless1 and my_isless3 should optimize to my_isless2.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions