Skip to content

Commit

Permalink
[clang] Use current rounding mode for float inc/dec (llvm#73770)
Browse files Browse the repository at this point in the history
Increment and decrement are equivalent to adding or subtracting 1. For
the floating-point values these operations depend on the current
rounding mode. Teach constant evaluator to perform ++ and -- according
to the current floating-point environment.

Pull request: llvm#73770
  • Loading branch information
spavloff authored Nov 30, 2023
1 parent 0817efc commit e620035
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
8 changes: 5 additions & 3 deletions clang/lib/AST/ExprConstant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4623,11 +4623,13 @@ struct IncDecSubobjectHandler {
if (Old) *Old = APValue(Value);

APFloat One(Value.getSemantics(), 1);
llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
APFloat::opStatus St;
if (AccessKind == AK_Increment)
Value.add(One, APFloat::rmNearestTiesToEven);
St = Value.add(One, RM);
else
Value.subtract(One, APFloat::rmNearestTiesToEven);
return true;
St = Value.subtract(One, RM);
return checkFloatingPointResult(Info, E, St);
}
bool foundPointer(APValue &Subobj, QualType SubobjType) {
if (!checkConst(SubobjType))
Expand Down
21 changes: 21 additions & 0 deletions clang/test/SemaCXX/rounding-math.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,24 @@ struct S1d {
int f;
};
static_assert(sizeof(S1d) == sizeof(int), "");

constexpr float incr_down(float k) {
float x = k;
++x;
return x;
}

// 0x1.0p23 = 8388608.0, inc(8388608.0) = 8388609.0
static_assert(incr_down(0x1.0p23F) == 0x1.000002p23F, "");
// 0x1.0p24 = 16777216.0, inc(16777216.0) = 16777217.0 -> round down -> 16777216.0
static_assert(incr_down(0x1.0p24F) == 0x1.0p24F, "");

#pragma STDC FENV_ROUND FE_UPWARD
constexpr float incr_up(float k) {
float x = k;
++x;
return x;
}
static_assert(incr_up(0x1.0p23F) == 0x1.000002p23F, "");
// 0x1.0p24 = 16777216.0, inc(16777216.0) = 16777217.0 -> round up -> 16777218.0
static_assert(incr_up(0x1.0p24F) == 0x1.000002p24F, "");

0 comments on commit e620035

Please sign in to comment.