Skip to content

Commit 98571be

Browse files
committed
[JSC] Compute double modulo by a power-of-two constant inline in DFG / Baseline
https://bugs.webkit.org/show_bug.cgi?id=328041 rdar://190398258 Reviewed by Sosuke Suzuki. We apply the optimization `x % power-of-two` in FTL to DFG and Baseline JIT. Tests: JSTests/stress/double-mod-by-power-of-two-constant.js Source/JavaScriptCore/b3/testb3_2.cpp * JSTests/stress/double-mod-by-power-of-two-constant.js: Added. (modBy1): (modBy2): (modBy8): (modByMinus4): (modByHalf): (modBy2p52): (modBy2p53): (modBy2p1023): (modByMinus2p31): (modBy2p31): (modBy2p32): (modBy3): (reference): (random): (modBy4Generic): (valueOf): * Source/JavaScriptCore/b3/B3LowerMacros.cpp: * Source/JavaScriptCore/b3/testb3_2.cpp: (testModArgImmDouble): (testModImmsDouble): * Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp: (JSC::DFG::SpeculativeJIT::compileArithModDoubleByPowerOfTwo): (JSC::DFG::SpeculativeJIT::compileArithMod): * Source/JavaScriptCore/dfg/DFGSpeculativeJIT.h: * Source/JavaScriptCore/jit/AssemblyHelpers.cpp: (JSC::AssemblyHelpers::emitDoubleModByPowerOfTwoIgnoringSignOfZero): (JSC::AssemblyHelpers::emitDoubleModByPowerOfTwo): * Source/JavaScriptCore/jit/AssemblyHelpers.h: * Source/JavaScriptCore/jit/JIT.h: * Source/JavaScriptCore/jit/JITArithmetic.cpp: (JSC::JIT::emitModByPowerOfTwoConstant): (JSC::JIT::emit_op_mod): * Source/JavaScriptCore/runtime/MathCommon.h: (JSC::powerOfTwoDivisorForDoubleMod): Canonical link: https://commits.webkit.org/324244@main
1 parent 8ec0143 commit 98571be

10 files changed

Lines changed: 275 additions & 2 deletions

File tree

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
function modBy1(x) { return x % 1; }
2+
function modBy2(x) { return x % 2; }
3+
function modBy8(x) { return x % 8; }
4+
function modByMinus4(x) { return x % -4; }
5+
function modByHalf(x) { return x % 0.5; }
6+
function modBy2p52(x) { return x % 4503599627370496; }
7+
function modBy2p53(x) { return x % 9007199254740992; }
8+
function modBy2p1023(x) { return x % 8.98846567431158e+307; }
9+
function modByMinus2p31(x) { return x % -2147483648; }
10+
function modBy2p31(x) { return x % 2147483648; }
11+
function modBy2p32(x) { return x % 4294967296; }
12+
function modBy3(x) { return x % 3; }
13+
noInline(modBy1);
14+
noInline(modBy2);
15+
noInline(modBy8);
16+
noInline(modByMinus4);
17+
noInline(modByHalf);
18+
noInline(modBy2p52);
19+
noInline(modBy2p53);
20+
noInline(modBy2p1023);
21+
noInline(modByMinus2p31);
22+
noInline(modBy2p31);
23+
noInline(modBy2p32);
24+
noInline(modBy3);
25+
26+
function reference(x, y) { return x % y; }
27+
noInline(reference);
28+
29+
const tests = [
30+
[modBy1, 1],
31+
[modBy2, 2],
32+
[modBy8, 8],
33+
[modByMinus4, -4],
34+
[modByHalf, 0.5],
35+
[modBy2p52, 4503599627370496],
36+
[modBy2p53, 9007199254740992],
37+
[modBy2p1023, 8.98846567431158e+307],
38+
[modByMinus2p31, -2147483648],
39+
[modBy2p31, 2147483648],
40+
[modBy2p32, 4294967296],
41+
[modBy3, 3],
42+
];
43+
44+
const inputs = [
45+
0, -0, 0.5, -0.5, 1, -1, 1.5, -1.5, 2, -2, 3.75, -3.75, 4, -4, 7.999999999999999, -8, 8.000000000000002,
46+
0.1, -0.1, 1e-310, -1e-310, 5e-324, -5e-324, 2.2250738585072014e-308, -2.2250738585072014e-308,
47+
123456789.123, -123456789.123, 4503599627370495.5, -4503599627370495.5, 4503599627370497, -4503599627370497,
48+
9007199254740991, -9007199254740991, 9007199254740994, -9007199254740994, 1e300, -1e300, 1.7976931348623157e308,
49+
-1.7976931348623157e308, Infinity, -Infinity, NaN,
50+
-3, 5, -7, 9, -16, 1073741824, -1073741824, 2147483647, -2147483647, -2147483648, 2147483648, -2147483649,
51+
];
52+
53+
let seed = 1;
54+
function random() {
55+
seed = (seed * 1103515245 + 12345) % 2147483648;
56+
return seed / 2147483648;
57+
}
58+
for (let i = 0; i < 100; ++i)
59+
inputs.push((random() - 0.5) * Math.pow(2, Math.floor(random() * 120) - 40));
60+
61+
for (let i = 0; i < testLoopCount; ++i) {
62+
const input = inputs[i % inputs.length];
63+
for (const [func, divisor] of tests) {
64+
const actual = func(input);
65+
const expected = reference(input, divisor);
66+
if (!Object.is(actual, expected))
67+
throw new Error(`${func.name}(${input}): expected ${expected} but got ${actual}`);
68+
}
69+
}
70+
71+
function modBy4Generic(x) { return x % 4; }
72+
noInline(modBy4Generic);
73+
74+
const genericInputs = ["-6", "7.5", true, null, undefined, { valueOf() { return -12.5; } }, -8, 2.5];
75+
for (let i = 0; i < testLoopCount; ++i) {
76+
const input = genericInputs[i % genericInputs.length];
77+
const actual = modBy4Generic(input);
78+
const expected = reference(input, 4);
79+
if (!Object.is(actual, expected))
80+
throw new Error(`modBy4Generic(${String(input)}): expected ${expected} but got ${actual}`);
81+
}

‎Source/JavaScriptCore/b3/B3LowerMacros.cpp‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,9 @@ class LowerMacros {
155155
}
156156

157157
if (m_value->type() == Double) {
158+
if (lowerDoubleModByPowerOfTwo())
159+
break;
160+
158161
if constexpr (!isARM64()) {
159162
// Non-ARM64: just call fmod directly.
160163
Value* functionAddress = m_insertionSet.insert<ConstPtrValue>(m_index, m_origin, tagCFunction<OperationPtrTag>(Math::fmodDouble));
@@ -1058,6 +1061,39 @@ class LowerMacros {
10581061
m_changed = true;
10591062
}
10601063

1064+
bool lowerDoubleModByPowerOfTwo()
1065+
{
1066+
if (!MacroAssembler::supportsFloatingPointRounding())
1067+
return false;
1068+
1069+
Value* right = m_value->child(1);
1070+
if (!right->hasDouble())
1071+
return false;
1072+
1073+
std::optional<double> divisor = powerOfTwoDivisorForDoubleMod(right->asDouble());
1074+
if (!divisor)
1075+
return false;
1076+
1077+
Value* left = m_value->child(0);
1078+
Value* product;
1079+
if (*divisor == 1)
1080+
product = m_insertionSet.insert<Value>(m_index, FTrunc, m_origin, left);
1081+
else {
1082+
Value* scaled = m_insertionSet.insert<Value>(m_index, Mul, m_origin, left, m_insertionSet.insert<ConstDoubleValue>(m_index, m_origin, 1 / *divisor));
1083+
Value* quotient = m_insertionSet.insert<Value>(m_index, FTrunc, m_origin, scaled);
1084+
product = m_insertionSet.insert<Value>(m_index, Mul, m_origin, quotient, m_insertionSet.insert<ConstDoubleValue>(m_index, m_origin, *divisor));
1085+
}
1086+
Value* remainder = m_insertionSet.insert<Value>(m_index, Sub, m_origin, left, product);
1087+
// Masking in the integer domain keeps the sign mask an immediate instead of a constant-pool load.
1088+
Value* signBit = m_insertionSet.insert<Value>(m_index, BitwiseCast, m_origin,
1089+
m_insertionSet.insert<Value>(m_index, BitAnd, m_origin,
1090+
m_insertionSet.insert<Value>(m_index, BitwiseCast, m_origin, left),
1091+
m_insertionSet.insert<Const64Value>(m_index, m_origin, std::numeric_limits<int64_t>::min())));
1092+
m_value->replaceWithIdentity(m_insertionSet.insert<Value>(m_index, BitOr, m_origin, remainder, signBit));
1093+
m_changed = true;
1094+
return true;
1095+
}
1096+
10611097
void makeDivisionChill(Opcode nonChillOpcode)
10621098
{
10631099
ASSERT(nonChillOpcode == Div || nonChillOpcode == Mod);

‎Source/JavaScriptCore/b3/testb3_2.cpp‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2534,7 +2534,12 @@ void testModArgImmDouble(double a, double b)
25342534
root->clearSuccessors();
25352535
root->appendNew<Value>(proc, Return, Origin(), root->appendNew<Value>(proc, Mod, Origin(), valueA, valueB));
25362536

2537-
CHECK(isIdentical(compileAndRun<double>(proc, a), fmod(a, b)));
2537+
double expected = fmod(a, b);
2538+
double actual = compileAndRun<double>(proc, a);
2539+
if (std::isnan(expected))
2540+
CHECK(std::isnan(actual));
2541+
else
2542+
CHECK(isIdentical(actual, expected));
25382543
}
25392544

25402545
void testModImmArgDouble(double a, double b)
@@ -2560,7 +2565,12 @@ void testModImmsDouble(double a, double b)
25602565
root->clearSuccessors();
25612566
root->appendNew<Value>(proc, Return, Origin(), root->appendNew<Value>(proc, Mod, Origin(), valueA, valueB));
25622567

2563-
CHECK(isIdentical(compileAndRun<double>(proc), fmod(a, b)));
2568+
double expected = fmod(a, b);
2569+
double actual = compileAndRun<double>(proc);
2570+
if (std::isnan(expected))
2571+
CHECK(std::isnan(actual));
2572+
else
2573+
CHECK(isIdentical(actual, expected));
25642574
}
25652575

25662576
void testModArgFloat(float a)

‎Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5888,6 +5888,32 @@ void SpeculativeJIT::compileValueMod(Node* node)
58885888
jsValueResult(resultGPR, node);
58895889
}
58905890

5891+
bool SpeculativeJIT::compileArithModDoubleByPowerOfTwo(Node* node)
5892+
{
5893+
if (!supportsFloatingPointRounding())
5894+
return false;
5895+
5896+
JSValue divisorValue = m_state.forNode(node->child2()).value();
5897+
if (!divisorValue || !divisorValue.isNumber())
5898+
return false;
5899+
std::optional<double> divisor = powerOfTwoDivisorForDoubleMod(divisorValue.asNumber());
5900+
if (!divisor)
5901+
return false;
5902+
5903+
SpeculateDoubleOperand op1(this, node->child1());
5904+
FPRTemporary result(this);
5905+
FPRTemporary scratch(this);
5906+
5907+
FPRReg op1FPR = op1.fpr();
5908+
FPRReg resultFPR = result.fpr();
5909+
FPRReg scratchFPR = scratch.fpr();
5910+
5911+
emitDoubleModByPowerOfTwo(op1FPR, *divisor, resultFPR, scratchFPR);
5912+
5913+
doubleResult(resultFPR, node);
5914+
return true;
5915+
}
5916+
58915917
void SpeculativeJIT::compileArithMod(Node* node)
58925918
{
58935919
switch (node->binaryUseKind()) {
@@ -6233,6 +6259,8 @@ void SpeculativeJIT::compileArithMod(Node* node)
62336259
}
62346260

62356261
case DoubleRepUse: {
6262+
if (compileArithModDoubleByPowerOfTwo(node))
6263+
return;
62366264
#if CPU(ARM64)
62376265
SpeculateDoubleOperand op1(this, node->child1());
62386266
SpeculateDoubleOperand op2(this, node->child2());

‎Source/JavaScriptCore/dfg/DFGSpeculativeJIT.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1489,6 +1489,7 @@ class SpeculativeJIT : public JITCompiler {
14891489
void compileArithF16Round(Node*);
14901490
void compileValueMod(Node*);
14911491
void compileArithMod(Node*);
1492+
bool compileArithModDoubleByPowerOfTwo(Node*);
14921493
void compileArithPow(Node*);
14931494
void compileValuePow(Node*);
14941495
void compileArithRounding(Node*);

‎Source/JavaScriptCore/jit/AssemblyHelpers.cpp‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
3838
#include "JSCJSValueInlines.h"
3939
#include "JSDataView.h"
4040
#include "LinkBuffer.h"
41+
#include "MathCommon.h"
4142
#include "MaxFrameExtentForSlowPathCall.h"
4243
#include "MegamorphicCache.h"
4344
#include "SuperSampler.h"
@@ -89,6 +90,34 @@ void AssemblyHelpers::purifyNaN(FPRReg inputFPR, FPRReg resultFPR)
8990
moveDoubleConditionallyDouble(DoubleEqualAndOrdered, inputFPR, inputFPR, inputFPR, fpTempRegister, resultFPR);
9091
}
9192

93+
void AssemblyHelpers::emitDoubleModByPowerOfTwoIgnoringSignOfZero(FPRReg dividendFPR, double divisor, FPRReg resultFPR, FPRReg scratchFPR)
94+
{
95+
ASSERT(supportsFloatingPointRounding());
96+
ASSERT(powerOfTwoDivisorForDoubleMod(divisor) == divisor);
97+
ASSERT(noOverlap(dividendFPR, resultFPR, scratchFPR));
98+
99+
if (divisor == 1) {
100+
roundTowardZeroDouble(dividendFPR, resultFPR);
101+
subDouble(dividendFPR, resultFPR, resultFPR);
102+
return;
103+
}
104+
105+
move64ToDouble(TrustedImm64(std::bit_cast<int64_t>(1 / divisor)), scratchFPR);
106+
mulDouble(dividendFPR, scratchFPR, resultFPR);
107+
roundTowardZeroDouble(resultFPR, resultFPR);
108+
move64ToDouble(TrustedImm64(std::bit_cast<int64_t>(divisor)), scratchFPR);
109+
mulDouble(resultFPR, scratchFPR, resultFPR);
110+
subDouble(dividendFPR, resultFPR, resultFPR);
111+
}
112+
113+
void AssemblyHelpers::emitDoubleModByPowerOfTwo(FPRReg dividendFPR, double divisor, FPRReg resultFPR, FPRReg scratchFPR)
114+
{
115+
emitDoubleModByPowerOfTwoIgnoringSignOfZero(dividendFPR, divisor, resultFPR, scratchFPR);
116+
move64ToDouble(TrustedImm64(std::numeric_limits<int64_t>::min()), scratchFPR);
117+
andDouble(dividendFPR, scratchFPR, scratchFPR);
118+
orDouble(resultFPR, scratchFPR, resultFPR);
119+
}
120+
92121
#if ENABLE(SAMPLING_FLAGS)
93122
void AssemblyHelpers::setSamplingFlag(int32_t flag)
94123
{

‎Source/JavaScriptCore/jit/AssemblyHelpers.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1045,6 +1045,11 @@ class AssemblyHelpers : public MacroAssembler {
10451045

10461046
void purifyNaN(FPRReg, FPRReg);
10471047

1048+
// The divisor must come from powerOfTwoDivisorForDoubleMod(). The IgnoringSignOfZero variant produces +0 where
1049+
// fmod produces -0, leaving it to the caller to copy the dividend's sign bit into the result.
1050+
void emitDoubleModByPowerOfTwo(FPRReg dividendFPR, double divisor, FPRReg resultFPR, FPRReg scratchFPR);
1051+
void emitDoubleModByPowerOfTwoIgnoringSignOfZero(FPRReg dividendFPR, double divisor, FPRReg resultFPR, FPRReg scratchFPR);
1052+
10481053
// These methods convert between doubles, and doubles boxed and JSValues.
10491054
GPRReg boxDouble(FPRReg fpr, GPRReg gpr, TagRegistersMode mode = HaveTagRegisters)
10501055
{

‎Source/JavaScriptCore/jit/JIT.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -786,6 +786,8 @@ namespace JSC {
786786
template<typename Op>
787787
void emitRightShiftFastPath(const JSInstruction* currentInstruction, JITRightShiftGenerator::ShiftType);
788788

789+
bool emitModByPowerOfTwoConstant(VirtualRegister result, VirtualRegister op1, VirtualRegister op2);
790+
789791
void updateTopCallFrame();
790792

791793
// Loads the character value of a single character string into dst.

‎Source/JavaScriptCore/jit/JITArithmetic.cpp‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,66 @@ void JIT::emit_op_dec(const JSInstruction* currentInstruction)
475475

476476
/* ------------------------------ BEGIN: OP_MOD ------------------------------ */
477477

478+
bool JIT::emitModByPowerOfTwoConstant(VirtualRegister result, VirtualRegister op1, VirtualRegister op2)
479+
{
480+
if (!supportsFloatingPointRounding())
481+
return false;
482+
if (!isOperandConstantInt(op2) && !isOperandConstantDouble(op2))
483+
return false;
484+
std::optional<double> divisor = powerOfTwoDivisorForDoubleMod(getConstantOperand(op2).asNumber());
485+
if (!divisor)
486+
return false;
487+
488+
JumpList done;
489+
emitGetVirtualRegister(op1, regT0);
490+
491+
if (*divisor > static_cast<double>(1ULL << 31))
492+
done.append(branchIfInt32(regT0));
493+
else {
494+
Jump notInt32 = branchIfNotInt32(regT0);
495+
int32_t mask = static_cast<int32_t>(*divisor - 1);
496+
if (mask) {
497+
// Biasing a negative dividend by mask makes the masked bits round toward zero, as % does.
498+
if (mask == 1)
499+
urshift32(regT0, TrustedImm32(31), regT1);
500+
else {
501+
rshift32(regT0, TrustedImm32(31), regT1);
502+
and32(TrustedImm32(mask), regT1);
503+
}
504+
add32(regT0, regT1, regT2);
505+
and32(TrustedImm32(mask), regT2);
506+
sub32(regT2, regT1, regT2);
507+
boxInt32(regT2, regT2);
508+
} else
509+
move(GPRInfo::numberTagRegister, regT2);
510+
// The result is -0 exactly when the dividend is negative and a multiple of the divisor.
511+
xor32(TrustedImm32(std::numeric_limits<int32_t>::min()), regT0, regT1);
512+
moveValue(jsDoubleNumber(-0.0), regT0);
513+
moveConditionallyTest32(NonZero, regT1, TrustedImm32(std::numeric_limits<int32_t>::min() | mask), regT2, regT0);
514+
done.append(jump());
515+
notInt32.link(this);
516+
}
517+
518+
addSlowCase(branchIfNotNumber(regT0));
519+
unboxDouble(regT0, regT1, fpRegT0);
520+
emitDoubleModByPowerOfTwoIgnoringSignOfZero(fpRegT0, *divisor, fpRegT1, fpRegT2);
521+
moveDoubleTo64(fpRegT1, regT3);
522+
and64(TrustedImm64(std::numeric_limits<int64_t>::min()), regT1);
523+
or64(regT1, regT3);
524+
// Box integral results as int32 like slow_path_mod does, so that use sites keep int32 predictions. Comparing
525+
// bits after a round trip through int32 rejects -0, NaN, and out-of-range values.
526+
truncateDoubleToInt32(fpRegT1, regT2);
527+
convertInt32ToDouble(regT2, fpRegT2);
528+
moveDoubleTo64(fpRegT2, regT1);
529+
boxInt32(regT2, regT2);
530+
sub64(regT3, GPRInfo::numberTagRegister, regT0);
531+
moveConditionally64(Equal, regT3, regT1, regT2, regT0);
532+
533+
done.link(this);
534+
emitPutVirtualRegister(result, regT0);
535+
return true;
536+
}
537+
478538
#if CPU(X86_64)
479539

480540
void JIT::emit_op_mod(const JSInstruction* currentInstruction)
@@ -484,6 +544,9 @@ void JIT::emit_op_mod(const JSInstruction* currentInstruction)
484544
VirtualRegister op1 = bytecode.m_lhs;
485545
VirtualRegister op2 = bytecode.m_rhs;
486546

547+
if (emitModByPowerOfTwoConstant(result, op1, op2))
548+
return;
549+
487550
// Make sure registers are correct for x86 IDIV instructions.
488551
ASSERT(regT0 == X86Registers::eax);
489552
auto edx = X86Registers::edx;
@@ -527,6 +590,9 @@ void JIT::emit_op_mod(const JSInstruction* currentInstruction)
527590
VirtualRegister op1 = bytecode.m_lhs;
528591
VirtualRegister op2 = bytecode.m_rhs;
529592

593+
if (emitModByPowerOfTwoConstant(result, op1, op2))
594+
return;
595+
530596
emitGetVirtualRegister(op1, regT0);
531597
emitGetVirtualRegister(op2, regT2);
532598

‎Source/JavaScriptCore/runtime/MathCommon.h‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,21 @@ inline std::optional<double> safeReciprocalForDivByConst(double constant)
236236
return reciprocal;
237237
}
238238

239+
// Returns |constant| when fmod(x, constant) == copysign(x - trunc(x * (1 / |constant|)) * |constant|, x) for
240+
// every x, which holds when |constant| is a power of two no smaller than 1: scaling by a power of two is exact
241+
// whenever trunc() can see a nonzero integer part, the product does not exceed |x|, and the difference is a
242+
// multiple of x's lowest significant bit that is smaller than |x|.
243+
inline std::optional<double> powerOfTwoDivisorForDoubleMod(double constant)
244+
{
245+
double divisor = std::abs(constant);
246+
if (!std::isfinite(divisor) || divisor < 1)
247+
return std::nullopt;
248+
int exponent;
249+
if (std::frexp(divisor, &exponent) != 0.5)
250+
return std::nullopt;
251+
return divisor;
252+
}
253+
239254
extern "C" {
240255
JSC_DECLARE_NOEXCEPT_JIT_OPERATION(jsRound, double, (double));
241256
}

0 commit comments

Comments
 (0)