Skip to content

Commit

Permalink
Fix issues of tanh(x) when x=INF or -INF
Browse files Browse the repository at this point in the history
We didn't check this special case. We just computed tanh(x) by
sinh(x)/cosh(x). But when x=INF or -INF, the limit of tanh(x) is defined
as follow:

  lim(tanh(x)) = 1.0, x -> INF; lim(tanh(x)) = -1.0, x -> -INF
  • Loading branch information
amdrexu committed Oct 26, 2023
1 parent a2ed744 commit db6e682
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lgc/builder/ArithBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,18 @@ Value *BuilderImpl::CreateTanh(Value *x, const Twine &instName) {
Value *doubleSinh = CreateFSub(exp, expNeg);
Value *doubleCosh = CreateFAdd(exp, expNeg);
Value *result = fDivFast(doubleSinh, doubleCosh);

if (!getFastMathFlags().noInfs()) {
// NOTE: If the fast math flags might have INFs, we should check the special case when the input is +INF or -INF.
// According to the limit of tanh(x), we have following definitions:
// / 1.0, when x -> +INF
// lim(tanh(x)) =
// \ -1.0, when x -> -INF
Value *one = ConstantFP::get(x->getType(), 1.0);
Value *isInf = CreateIsInf(x);
result = CreateSelect(isInf, CreateCopySign(one, x), result);
}

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

0 comments on commit db6e682

Please sign in to comment.