56 changes: 56 additions & 0 deletions libc/utils/FPUtil/FloatOperations.h
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,62 @@ static inline T floor(T x) {
}
}

template <typename T,
cpp::EnableIfType<cpp::IsFloatingPointType<T>::Value, int> = 0>
static inline T round(T x) {
using Properties = FloatProperties<T>;
using BitsType = typename FloatProperties<T>::BitsType;

BitsType bits = valueAsBits(x);

// If x is infinity, NaN or zero, return it.
if (bitsAreInfOrNaN(bits) || bitsAreZero(bits))
return x;

bool isNeg = bits & Properties::signMask;
int exponent = getExponentFromBits(bits);

// If the exponent is greater than the most negative mantissa
// exponent, then x is already an integer.
if (exponent >= static_cast<int>(Properties::mantissaWidth))
return x;

if (exponent == -1) {
// Absolute value of x is greater than equal to 0.5 but less than 1.
if (isNeg)
return T(-1.0);
else
return T(1.0);
}

if (exponent <= -2) {
// Absolute value of x is less than 0.5.
if (isNeg)
return T(-0.0);
else
return T(0.0);
}

uint32_t trimSize = Properties::mantissaWidth - exponent;
// If x is already an integer, return it.
if ((bits << (Properties::bitWidth - trimSize)) == 0)
return x;

BitsType truncBits = (bits >> trimSize) << trimSize;
T truncValue = valueFromBits(truncBits);

if ((bits & (BitsType(1) << (trimSize - 1))) == 0) {
// Franctional part is less than 0.5 so round value is the
// same as the trunc value.
return truncValue;
}

if (isNeg)
return truncValue - T(1.0);
else
return truncValue + T(1.0);
}

} // namespace fputil
} // namespace __llvm_libc

Expand Down