Skip to content

Commit e620035

Browse files
authored
[clang] Use current rounding mode for float inc/dec (#73770)
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: #73770
1 parent 0817efc commit e620035

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

clang/lib/AST/ExprConstant.cpp

+5-3
Original file line numberDiff line numberDiff line change
@@ -4623,11 +4623,13 @@ struct IncDecSubobjectHandler {
46234623
if (Old) *Old = APValue(Value);
46244624

46254625
APFloat One(Value.getSemantics(), 1);
4626+
llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4627+
APFloat::opStatus St;
46264628
if (AccessKind == AK_Increment)
4627-
Value.add(One, APFloat::rmNearestTiesToEven);
4629+
St = Value.add(One, RM);
46284630
else
4629-
Value.subtract(One, APFloat::rmNearestTiesToEven);
4630-
return true;
4631+
St = Value.subtract(One, RM);
4632+
return checkFloatingPointResult(Info, E, St);
46314633
}
46324634
bool foundPointer(APValue &Subobj, QualType SubobjType) {
46334635
if (!checkConst(SubobjType))

clang/test/SemaCXX/rounding-math.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,24 @@ struct S1d {
7777
int f;
7878
};
7979
static_assert(sizeof(S1d) == sizeof(int), "");
80+
81+
constexpr float incr_down(float k) {
82+
float x = k;
83+
++x;
84+
return x;
85+
}
86+
87+
// 0x1.0p23 = 8388608.0, inc(8388608.0) = 8388609.0
88+
static_assert(incr_down(0x1.0p23F) == 0x1.000002p23F, "");
89+
// 0x1.0p24 = 16777216.0, inc(16777216.0) = 16777217.0 -> round down -> 16777216.0
90+
static_assert(incr_down(0x1.0p24F) == 0x1.0p24F, "");
91+
92+
#pragma STDC FENV_ROUND FE_UPWARD
93+
constexpr float incr_up(float k) {
94+
float x = k;
95+
++x;
96+
return x;
97+
}
98+
static_assert(incr_up(0x1.0p23F) == 0x1.000002p23F, "");
99+
// 0x1.0p24 = 16777216.0, inc(16777216.0) = 16777217.0 -> round up -> 16777218.0
100+
static_assert(incr_up(0x1.0p24F) == 0x1.000002p24F, "");

0 commit comments

Comments
 (0)