Skip to content

Commit

Permalink
[AST] Fix handling of some edge cases in fixed-point division.
Browse files Browse the repository at this point in the history
Division by zero was not being handled, and division of
-EPSILON / MAX did not perform rounding correctly.
  • Loading branch information
bevin-hansson committed Jun 30, 2020
1 parent 80eb422 commit 33bae9c
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 1 deletion.
4 changes: 4 additions & 0 deletions clang/lib/AST/ExprConstant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12954,6 +12954,10 @@ bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
break;
}
case BO_Div: {
if (RHSFX.getValue() == 0) {
Info.FFDiag(E, diag::note_expr_divide_by_zero);
return false;
}
Result = LHSFX.div(RHSFX, &OpOverflow)
.convert(ResultFXSema, &ConversionOverflow);
break;
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/Basic/FixedPoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ APFixedPoint APFixedPoint::div(const APFixedPoint &Other,
llvm::APInt::sdivrem(ThisVal, OtherVal, Result, Rem);
// If the quotient is negative and the remainder is nonzero, round
// towards negative infinity by subtracting epsilon from the result.
if (Result.isNegative() && !Rem.isNullValue())
if (ThisVal.isNegative() != OtherVal.isNegative() && !Rem.isNullValue())
Result = Result - 1;
} else
Result = ThisVal.udiv(OtherVal);
Expand Down
2 changes: 2 additions & 0 deletions clang/test/Frontend/fixed_point_div.c
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ short _Accum sa_const13 = 0.0234375hk / 2.0hk;
// CHECK-DAG: @sa_const13 = {{.*}}global i16 1, align 2
short _Accum sa_const14 = -0.0234375hk / 2.0hk;
// CHECK-DAG: @sa_const14 = {{.*}}global i16 -2, align 2
short _Accum sa_const15 = -0.0078125hk / 255.28125hk;
// CHECK-DAG: @sa_const15 = {{.*}}global i16 -1, align 2

void SignedDivision() {
// CHECK-LABEL: SignedDivision
Expand Down
3 changes: 3 additions & 0 deletions clang/test/Frontend/fixed_point_errors.c
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,6 @@ short _Fract add_sat = (_Sat short _Fract)0.5hr + 0.5hr;
short _Accum sub_sat = (_Sat short _Accum)-200.0hk - 80.0hk;
short _Accum mul_sat = (_Sat short _Accum)80.0hk * 10.0hk;
short _Fract div_sat = (_Sat short _Fract)0.9hr / 0.1hr;

// Division by zero
short _Accum div_zero = 4.5k / 0.0lr; // expected-error {{initializer element is not a compile-time constant}}

0 comments on commit 33bae9c

Please sign in to comment.