Search code examples
c++comparisonllvmoperator-keywordrelational

Can someone explain to me why there is an inequality test with the same operands in the following code from LLVM?


My colleague showed me the following macro from the LLVM source code:

#define IMPLEMENT_UNORDERED(TY, X,Y)                                         \
    if (TY->isFloatTy()) {                                                   \
        if (X.FloatVal != X.FloatVal || Y.FloatVal != Y.FloatVal) {          \
            return Dest;                                                     \
        }                                                                    \
    } else if (X.DoubleVal != X.DoubleVal || Y.DoubleVal != Y.DoubleVal) {   \
            Dest.IntVal = APInt(1,true);                                     \
            return Dest;                                                     \
}

Here's how they use this macro:

static GenericValue executeFCMP_UEQ(GenericValue Src1, GenericValue Src2,
                                    Type *Ty) {
    GenericValue Dest;
    IMPLEMENT_UNORDERED(Ty, Src1, Src2)
    return executeFCMP_OEQ(Src1, Src2, Ty);
}

Below you can see the definition of GenericValue:

struct GenericValue {
    union {
        double          DoubleVal;
        float           FloatVal;
        PointerTy       PointerVal;
        struct { unsigned int first; unsigned int second; } UIntPairVal;
        unsigned char   Untyped[8];
    };
    APInt IntVal;   // also used for long doubles

    GenericValue() : DoubleVal(0.0), IntVal(1,0) {}
    explicit GenericValue(void *V) : PointerVal(V), IntVal(1,0) { }
};

My question is why there's the following inequality test inside the macro:

X.FloatVal != X.FloatVal

Solution

  • I'd guess they test for NaN (not a number): if x has a NaN value, x != x yields true.