Skip to content

Commit

Permalink
Fix issues of fract(x)
Browse files Browse the repository at this point in the history
The problem is similar to modf(x) when x=-0.0 or +INF/-INF. Although
SPIR-V spec says nothing about such cases, the OpenCL spec does define
the results of those operations as follow:

  fract(-0.0) = -0.0
  fract(+INF) = 0.0
  fract(-INF) = -0.0

Hence, we follow what have been done for modf.
  • Loading branch information
amdrexu committed Nov 9, 2023
1 parent 8e7a79b commit 2dc262f
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lgc/builder/ArithBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,32 @@ Value *BuilderImpl::CreateSSign(Value *x, const Twine &instName) {
Value *BuilderImpl::CreateFract(Value *x, const Twine &instName) {
// We need to scalarize this ourselves.
Value *result = scalarize(x, [this](Value *x) { return CreateIntrinsic(Intrinsic::amdgcn_fract, x->getType(), x); });

// NOTE: Although SPIR-V spec says nothing about such cases: fract(-0.0), fract(+INF), fract(-INF), OpenCL spec does
// have following defintions:

Check warning on line 705 in lgc/builder/ArithBuilder.cpp

View workflow job for this annotation

GitHub Actions / typos

"defintions" should be "definitions".
//
// fract(-0.0) = -0.0
// fract(+INF) = +0.0
// fract(-INF) = -0.0
//
// When we follow it, we have two issues that are similar to modf(x):
//
// 1. When we input x=+INF/-INF to above formula, we finally get the computation of (-INF) + INF or INF - INF.
// The result is NaN returned by HW.
// 2. When we input x=-0.0 to above formula, we finally get the addition of (-0.0) + 0.0. The result is +0.0
// returned by HW.
//
// Hence, we have to manually check those special cases:
//
// y = fract(x)
// y = x == -0.0 || x == INF ? copysign(0.0, x) : y, when either NSZ or NoInfs is not present
if (!getFastMathFlags().noSignedZeros() || !getFastMathFlags().noInfs()) {
Value *isNegZeroOrInf =
createIsFPClass(x, CmpClass::NegativeZero | CmpClass::NegativeInfinity | CmpClass::PositiveInfinity);
Value *signedZero = CreateCopySign(ConstantFP::getNullValue(x->getType()), x);
result = CreateSelect(isNegZeroOrInf, signedZero, result);
}

result->setName(instName);
return result;
}
Expand Down

0 comments on commit 2dc262f

Please sign in to comment.