Debian Codegraph @

js/src/jsmath.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * JS math package.
9 */
10
11 #include "jsmath.h"
12
13 #include "mozilla/CheckedInt.h"
14 #include "mozilla/FloatingPoint.h"
15 #include "mozilla/MathAlgorithms.h"
16 #include "mozilla/RandomNum.h"
17 #include "mozilla/WrappingOperations.h"
18
19 #include <cmath>
20
21 #include "fdlibm.h"
22 #include "jsapi.h"
23 #include "jstypes.h"
24
25 #include "jit/InlinableNatives.h"
26 #include "js/Class.h"
27 #include "js/ForOfIterator.h"
28 #include "js/Prefs.h"
29 #include "js/PropertySpec.h"
30 #include "util/DifferentialTesting.h"
31 #include "vm/Float16.h"
32 #include "vm/Interpreter.h"
33 #include "vm/JSContext.h"
34 #include "vm/Realm.h"
35 #include "vm/Time.h"
36 #include "xsum/xsum.h"
37
38 #include "vm/JSObject-inl.h"
39
40 using namespace js;
41
42 using JS::GenericNaN;
43 using JS::ToNumber;
44 using mozilla::ExponentComponent;
45 using mozilla::FloatingPoint;
46 using mozilla::IsNegative;
47 using mozilla::IsNegativeZero;
48 using mozilla::Maybe;
49 using mozilla::NegativeInfinity;
50 using mozilla::NumberEqualsInt32;
51 using mozilla::NumberEqualsInt64;
52 using mozilla::PositiveInfinity;
53 using mozilla::WrappingMultiply;
54
55 bool js::math_use_fdlibm_for_sin_cos_tan() {
56 return JS::Prefs::use_fdlibm_for_sin_cos_tan();
57 }
58
59 static inline bool UseFdlibmForSinCosTan(const CallArgs& args) {
60 return math_use_fdlibm_for_sin_cos_tan() ||
61 args.callee().nonCCWRealm()->creationOptions().alwaysUseFdlibm();
62 }
63
64 template <UnaryMathFunctionType F>
65 static bool math_function(JSContext* cx, CallArgs& args) {
66 if (args.length() == 0) {
67 args.rval().setNaN();
68 return true;
69 }
70
71 double x;
72 if (!ToNumber(cx, args[0], &x)) {
73 return false;
74 }
75
76 // TODO(post-Warp): Re-evaluate if it's still necessary resp. useful to always
77 // type the value as a double.
78
79 // NB: Always stored as a double so the math function can be inlined
80 // through MMathFunction.
81 double z = F(x);
82 args.rval().setDouble(z);
83 return true;
84 }
85
86 double js::math_abs_impl(double x) { return mozilla::Abs(x); }
87
88 bool js::math_abs(JSContext* cx, unsigned argc, Value* vp) {
89 CallArgs args = CallArgsFromVp(argc, vp);
90
91 if (args.length() == 0) {
92 args.rval().setNaN();
93 return true;
94 }
95
96 double x;
97 if (!ToNumber(cx, args[0], &x)) {
98 return false;
99 }
100
101 args.rval().setNumber(math_abs_impl(x));
102 return true;
103 }
104
105 double js::math_acos_impl(double x) {
106 AutoUnsafeCallWithABI unsafe;
107 return fdlibm_acos(x);
108 }
109
110 static bool math_acos(JSContext* cx, unsigned argc, Value* vp) {
111 CallArgs args = CallArgsFromVp(argc, vp);
112 return math_function<math_acos_impl>(cx, args);
113 }
114
115 double js::math_asin_impl(double x) {
116 AutoUnsafeCallWithABI unsafe;
117 return fdlibm_asin(x);
118 }
119
120 static bool math_asin(JSContext* cx, unsigned argc, Value* vp) {
121 CallArgs args = CallArgsFromVp(argc, vp);
122 return math_function<math_asin_impl>(cx, args);
123 }
124
125 double js::math_atan_impl(double x) {
126 AutoUnsafeCallWithABI unsafe;
127 return fdlibm_atan(x);
128 }
129
130 static bool math_atan(JSContext* cx, unsigned argc, Value* vp) {
131 CallArgs args = CallArgsFromVp(argc, vp);
132 return math_function<math_atan_impl>(cx, args);
133 }
134
135 double js::ecmaAtan2(double y, double x) {
136 AutoUnsafeCallWithABI unsafe;
137 return fdlibm_atan2(y, x);
138 }
139
140 static bool math_atan2(JSContext* cx, unsigned argc, Value* vp) {
141 CallArgs args = CallArgsFromVp(argc, vp);
142
143 double y;
144 if (!ToNumber(cx, args.get(0), &y)) {
145 return false;
146 }
147
148 double x;
149 if (!ToNumber(cx, args.get(1), &x)) {
150 return false;
151 }
152
153 double z = ecmaAtan2(y, x);
154 args.rval().setDouble(z);
155 return true;
156 }
157
158 double js::math_ceil_impl(double x) {
159 AutoUnsafeCallWithABI unsafe;
160 return fdlibm_ceil(x);
161 }
162
163 static bool math_ceil(JSContext* cx, unsigned argc, Value* vp) {
164 CallArgs args = CallArgsFromVp(argc, vp);
165
166 if (args.length() == 0) {
167 args.rval().setNaN();
168 return true;
169 }
170
171 double x;
172 if (!ToNumber(cx, args[0], &x)) {
173 return false;
174 }
175
176 args.rval().setNumber(math_ceil_impl(x));
177 return true;
178 }
179
180 static bool math_clz32(JSContext* cx, unsigned argc, Value* vp) {
181 CallArgs args = CallArgsFromVp(argc, vp);
182
183 if (args.length() == 0) {
184 args.rval().setInt32(32);
185 return true;
186 }
187
188 uint32_t n;
189 if (!ToUint32(cx, args[0], &n)) {
190 return false;
191 }
192
193 if (n == 0) {
194 args.rval().setInt32(32);
195 return true;
196 }
197
198 args.rval().setInt32(mozilla::CountLeadingZeroes32(n));
199 return true;
200 }
201
202 double js::math_cos_fdlibm_impl(double x) {
203 AutoUnsafeCallWithABI unsafe;
204 return fdlibm_cos(x);
205 }
206
207 double js::math_cos_native_impl(double x) {
208 MOZ_ASSERT(!math_use_fdlibm_for_sin_cos_tan());
209 AutoUnsafeCallWithABI unsafe;
210 return std::cos(x);
211 }
212
213 static bool math_cos(JSContext* cx, unsigned argc, Value* vp) {
214 CallArgs args = CallArgsFromVp(argc, vp);
215 if (UseFdlibmForSinCosTan(args)) {
216 return math_function<math_cos_fdlibm_impl>(cx, args);
217 }
218 return math_function<math_cos_native_impl>(cx, args);
219 }
220
221 double js::math_exp_impl(double x) {
222 AutoUnsafeCallWithABI unsafe;
223 return fdlibm_exp(x);
224 }
225
226 static bool math_exp(JSContext* cx, unsigned argc, Value* vp) {
227 CallArgs args = CallArgsFromVp(argc, vp);
228 return math_function<math_exp_impl>(cx, args);
229 }
230
231 double js::math_floor_impl(double x) {
232 AutoUnsafeCallWithABI unsafe;
233 return fdlibm_floor(x);
234 }
235
236 bool js::math_floor(JSContext* cx, unsigned argc, Value* vp) {
237 CallArgs args = CallArgsFromVp(argc, vp);
238
239 if (args.length() == 0) {
240 args.rval().setNaN();
241 return true;
242 }
243
244 double x;
245 if (!ToNumber(cx, args[0], &x)) {
246 return false;
247 }
248
249 args.rval().setNumber(math_floor_impl(x));
250 return true;
251 }
252
253 bool js::math_imul_handle(JSContext* cx, HandleValue lhs, HandleValue rhs,
254 MutableHandleValue res) {
255 int32_t a = 0, b = 0;
256 if (!lhs.isUndefined() && !ToInt32(cx, lhs, &a)) {
257 return false;
258 }
259 if (!rhs.isUndefined() && !ToInt32(cx, rhs, &b)) {
260 return false;
261 }
262
263 res.setInt32(WrappingMultiply(a, b));
264 return true;
265 }
266
267 static bool math_imul(JSContext* cx, unsigned argc, Value* vp) {
268 CallArgs args = CallArgsFromVp(argc, vp);
269
270 return math_imul_handle(cx, args.get(0), args.get(1), args.rval());
271 }
272
273 // Implements Math.fround (20.2.2.16) up to step 3
274 bool js::RoundFloat32(JSContext* cx, HandleValue v, float* out) {
275 double d;
276 bool success = ToNumber(cx, v, &d);
277 *out = static_cast<float>(d);
278 return success;
279 }
280
281 bool js::RoundFloat32(JSContext* cx, HandleValue arg, MutableHandleValue res) {
282 float f;
283 if (!RoundFloat32(cx, arg, &f)) {
284 return false;
285 }
286
287 res.setDouble(static_cast<double>(f));
288 return true;
289 }
290
291 double js::RoundFloat32(double d) {
292 return static_cast<double>(static_cast<float>(d));
293 }
294
295 static bool math_fround(JSContext* cx, unsigned argc, Value* vp) {
296 CallArgs args = CallArgsFromVp(argc, vp);
297
298 if (args.length() == 0) {
299 args.rval().setNaN();
300 return true;
301 }
302
303 return RoundFloat32(cx, args[0], args.rval());
304 }
305
306 double js::RoundFloat16(double d) {
307 AutoUnsafeCallWithABI unsafe;
308
309 // http://tc39.es/proposal-float16array/#sec-function-properties-of-the-math-object
310
311 // 1. Let n be ? ToNumber(x).
312 // [Not applicable here]
313
314 // 2. If n is NaN, return NaN.
315 // 3. If n is one of +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return n.
316 // 4. Let n16 be the result of converting n to IEEE 754-2019 binary16 format
317 // using roundTiesToEven mode.
318 js::float16 f16 = js::float16(d);
319
320 // 5. Let n64 be the result of converting n16 to IEEE 754-2019 binary64
321 // format.
322 // 6. Return the ECMAScript Number value corresponding to n64.
323 return static_cast<double>(f16);
324 }
325
326 static bool math_f16round(JSContext* cx, unsigned argc, Value* vp) {
327 // http://tc39.es/proposal-float16array/#sec-function-properties-of-the-math-object
328 CallArgs args = CallArgsFromVp(argc, vp);
329
330 if (args.length() == 0) {
331 args.rval().setNaN();
332 return true;
333 }
334
335 // 1. Let n be ? ToNumber(x).
336 double d;
337 if (!ToNumber(cx, args[0], &d)) {
338 return false;
339 }
340
341 // Steps 2-6.
342 args.rval().setDouble(RoundFloat16(d));
343 return true;
344 }
345
346 double js::math_log_impl(double x) {
347 AutoUnsafeCallWithABI unsafe;
348 return fdlibm_log(x);
349 }
350
351 static bool math_log(JSContext* cx, unsigned argc, Value* vp) {
352 CallArgs args = CallArgsFromVp(argc, vp);
353 return math_function<math_log_impl>(cx, args);
354 }
355
356 double js::math_max_impl(double x, double y) {
357 AutoUnsafeCallWithABI unsafe;
358
359 // Math.max(num, NaN) => NaN, Math.max(-0, +0) => +0
360 if (x > y || std::isnan(x) || (x == y && IsNegative(y))) {
361 return x;
362 }
363 return y;
364 }
365
366 bool js::math_max(JSContext* cx, unsigned argc, Value* vp) {
367 CallArgs args = CallArgsFromVp(argc, vp);
368
369 double maxval = NegativeInfinity<double>();
370 for (unsigned i = 0; i < args.length(); i++) {
371 double x;
372 if (!ToNumber(cx, args[i], &x)) {
373 return false;
374 }
375 maxval = math_max_impl(x, maxval);
376 }
377 args.rval().setNumber(maxval);
378 return true;
379 }
380
381 double js::math_min_impl(double x, double y) {
382 AutoUnsafeCallWithABI unsafe;
383
384 // Math.min(num, NaN) => NaN, Math.min(-0, +0) => -0
385 if (x < y || std::isnan(x) || (x == y && IsNegativeZero(x))) {
386 return x;
387 }
388 return y;
389 }
390
391 bool js::math_min(JSContext* cx, unsigned argc, Value* vp) {
392 CallArgs args = CallArgsFromVp(argc, vp);
393
394 double minval = PositiveInfinity<double>();
395 for (unsigned i = 0; i < args.length(); i++) {
396 double x;
397 if (!ToNumber(cx, args[i], &x)) {
398 return false;
399 }
400 minval = math_min_impl(x, minval);
401 }
402 args.rval().setNumber(minval);
403 return true;
404 }
405
406 double js::powi(double x, int32_t y) {
407 AutoUnsafeCallWithABI unsafe;
408
409 // It's only safe to optimize this when we can compute with integer values or
410 // the exponent is a small, positive constant.
411 if (y >= 0) {
412 uint32_t n = uint32_t(y);
413
414 // NB: Have to take fast-path for n <= 4 to match |MPow::foldsTo|. Otherwise
415 // we risk causing differential testing issues.
416 if (n == 0) {
417 return 1;
418 }
419 if (n == 1) {
420 return x;
421 }
422 if (n == 2) {
423 return x * x;
424 }
425 if (n == 3) {
426 return x * x * x;
427 }
428 if (n == 4) {
429 double z = x * x;
430 return z * z;
431 }
432
433 int64_t i;
434 if (NumberEqualsInt64(x, &i)) {
435 // Special-case: |-0 ** odd| is -0.
436 if (i == 0) {
437 return (n & 1) ? x : 0;
438 }
439
440 // Use int64 to cover cases like |Math.pow(2, 53)|.
441 mozilla::CheckedInt64 runningSquare = i;
442 mozilla::CheckedInt64 result = 1;
443 while (true) {
444 if ((n & 1) != 0) {
445 result *= runningSquare;
446 if (!result.isValid()) {
447 break;
448 }
449 }
450
451 n >>= 1;
452 if (n == 0) {
453 return static_cast<double>(result.value());
454 }
455
456 runningSquare *= runningSquare;
457 if (!runningSquare.isValid()) {
458 break;
459 }
460 }
461 }
462
463 // Fall-back to use std::pow to reduce floating point precision errors.
464 }
465
466 return std::pow(x, static_cast<double>(y)); // Avoid pow(double, int).
467 }
468
469 double js::ecmaPow(double x, double y) {
470 AutoUnsafeCallWithABI unsafe;
471
472 /*
473 * Use powi if the exponent is an integer-valued double. We don't have to
474 * check for NaN since a comparison with NaN is always false.
475 */
476 int32_t yi;
477 if (NumberEqualsInt32(y, &yi)) {
478 return powi(x, yi);
479 }
480
481 /*
482 * Because C99 and ECMA specify different behavior for pow(),
483 * we need to wrap the libm call to make it ECMA compliant.
484 */
485 if (!std::isfinite(y) && (x == 1.0 || x == -1.0)) {
486 return GenericNaN();
487 }
488
489 /* pow(x, +-0) is always 1, even for x = NaN (MSVC gets this wrong). */
490 if (y == 0) {
491 return 1;
492 }
493
494 /*
495 * Special case for square roots. Note that pow(x, 0.5) != sqrt(x)
496 * when x = -0.0, so we have to guard for this.
497 */
498 if (std::isfinite(x) && x != 0.0) {
499 if (y == 0.5) {
500 return std::sqrt(x);
501 }
502 if (y == -0.5) {
503 return 1.0 / std::sqrt(x);
504 }
505 }
506 return std::pow(x, y);
507 }
508
509 static bool math_pow(JSContext* cx, unsigned argc, Value* vp) {
510 CallArgs args = CallArgsFromVp(argc, vp);
511
512 double x;
513 if (!ToNumber(cx, args.get(0), &x)) {
514 return false;
515 }
516
517 double y;
518 if (!ToNumber(cx, args.get(1), &y)) {
519 return false;
520 }
521
522 double z = ecmaPow(x, y);
523 args.rval().setNumber(z);
524 return true;
525 }
526
527 uint64_t js::GenerateRandomSeed() {
528 Maybe<uint64_t> maybeSeed = mozilla::RandomUint64();
529
530 return maybeSeed.valueOrFrom([] {
531 // Use PRMJ_Now() in case we couldn't read random bits from the OS.
532 uint64_t timestamp = PRMJ_Now();
533 return timestamp ^ (timestamp << 32);
534 });
535 }
536
537 void js::GenerateXorShift128PlusSeed(mozilla::Array<uint64_t, 2>& seed) {
538 // XorShift128PlusRNG must be initialized with a non-zero seed.
539 do {
540 seed[0] = GenerateRandomSeed();
541 seed[1] = GenerateRandomSeed();
542 } while (seed[0] == 0 && seed[1] == 0);
543 }
544
545 mozilla::non_crypto::XorShift128PlusRNG&
546 Realm::getOrCreateRandomNumberGenerator() {
547 if (randomNumberGenerator_.isNothing()) {
548 mozilla::Array<uint64_t, 2> seed;
549 GenerateXorShift128PlusSeed(seed);
550 randomNumberGenerator_.emplace(seed[0], seed[1]);
551 }
552
553 return randomNumberGenerator_.ref();
554 }
555
556 double js::math_random_impl(JSContext* cx) {
557 return cx->realm()->getOrCreateRandomNumberGenerator().nextDouble();
558 }
559
560 static bool math_random(JSContext* cx, unsigned argc, Value* vp) {
561 CallArgs args = CallArgsFromVp(argc, vp);
562 if (js::SupportDifferentialTesting()) {
563 args.rval().setDouble(0);
564 } else {
565 args.rval().setDouble(math_random_impl(cx));
566 }
567 return true;
568 }
569
570 template <typename T>
571 T js::GetBiggestNumberLessThan(T x) {
572 MOZ_ASSERT(!IsNegative(x));
573 MOZ_ASSERT(std::isfinite(x));
574 using Bits = typename mozilla::FloatingPoint<T>::Bits;
575 Bits bits = mozilla::BitwiseCast<Bits>(x);
576 MOZ_ASSERT(bits > 0, "will underflow");
577 return mozilla::BitwiseCast<T>(bits - 1);
578 }
579
580 template double js::GetBiggestNumberLessThan<>(double x);
581 template float js::GetBiggestNumberLessThan<>(float x);
582
583 double js::math_round_impl(double x) {
584 AutoUnsafeCallWithABI unsafe;
585
586 int32_t ignored;
587 if (NumberEqualsInt32(x, &ignored)) {
588 return x;
589 }
590
591 /* Some numbers are so big that adding 0.5 would give the wrong number. */
592 if (ExponentComponent(x) >=
593 int_fast16_t(FloatingPoint<double>::kExponentShift)) {
594 return x;
595 }
596
597 double add = (x >= 0) ? GetBiggestNumberLessThan(0.5) : 0.5;
598 return std::copysign(fdlibm_floor(x + add), x);
599 }
600
601 float js::math_roundf_impl(float x) {
602 AutoUnsafeCallWithABI unsafe;
603
604 int32_t ignored;
605 if (NumberEqualsInt32(x, &ignored)) {
606 return x;
607 }
608
609 /* Some numbers are so big that adding 0.5 would give the wrong number. */
610 if (ExponentComponent(x) >=
611 int_fast16_t(FloatingPoint<float>::kExponentShift)) {
612 return x;
613 }
614
615 float add = (x >= 0) ? GetBiggestNumberLessThan(0.5f) : 0.5f;
616 return std::copysign(fdlibm_floorf(x + add), x);
617 }
618
619 /* ES5 15.8.2.15. */
620 static bool math_round(JSContext* cx, unsigned argc, Value* vp) {
621 CallArgs args = CallArgsFromVp(argc, vp);
622
623 if (args.length() == 0) {
624 args.rval().setNaN();
625 return true;
626 }
627
628 double x;
629 if (!ToNumber(cx, args[0], &x)) {
630 return false;
631 }
632
633 args.rval().setNumber(math_round_impl(x));
634 return true;
635 }
636
637 double js::math_sin_fdlibm_impl(double x) {
638 AutoUnsafeCallWithABI unsafe;
639 return fdlibm_sin(x);
640 }
641
642 double js::math_sin_native_impl(double x) {
643 MOZ_ASSERT(!math_use_fdlibm_for_sin_cos_tan());
644 AutoUnsafeCallWithABI unsafe;
645 return std::sin(x);
646 }
647
648 static bool math_sin(JSContext* cx, unsigned argc, Value* vp) {
649 CallArgs args = CallArgsFromVp(argc, vp);
650 if (UseFdlibmForSinCosTan(args)) {
651 return math_function<math_sin_fdlibm_impl>(cx, args);
652 }
653 return math_function<math_sin_native_impl>(cx, args);
654 }
655
656 double js::math_sqrt_impl(double x) {
657 AutoUnsafeCallWithABI unsafe;
658 return std::sqrt(x);
659 }
660
661 static bool math_sqrt(JSContext* cx, unsigned argc, Value* vp) {
662 CallArgs args = CallArgsFromVp(argc, vp);
663 return math_function<math_sqrt_impl>(cx, args);
664 }
665
666 double js::math_tan_fdlibm_impl(double x) {
667 AutoUnsafeCallWithABI unsafe;
668 return fdlibm_tan(x);
669 }
670
671 double js::math_tan_native_impl(double x) {
672 MOZ_ASSERT(!math_use_fdlibm_for_sin_cos_tan());
673 AutoUnsafeCallWithABI unsafe;
674 return std::tan(x);
675 }
676
677 static bool math_tan(JSContext* cx, unsigned argc, Value* vp) {
678 CallArgs args = CallArgsFromVp(argc, vp);
679 if (UseFdlibmForSinCosTan(args)) {
680 return math_function<math_tan_fdlibm_impl>(cx, args);
681 }
682 return math_function<math_tan_native_impl>(cx, args);
683 }
684
685 double js::math_log10_impl(double x) {
686 AutoUnsafeCallWithABI unsafe;
687 return fdlibm_log10(x);
688 }
689
690 static bool math_log10(JSContext* cx, unsigned argc, Value* vp) {
691 CallArgs args = CallArgsFromVp(argc, vp);
692 return math_function<math_log10_impl>(cx, args);
693 }
694
695 double js::math_log2_impl(double x) {
696 AutoUnsafeCallWithABI unsafe;
697 return fdlibm_log2(x);
698 }
699
700 static bool math_log2(JSContext* cx, unsigned argc, Value* vp) {
701 CallArgs args = CallArgsFromVp(argc, vp);
702 return math_function<math_log2_impl>(cx, args);
703 }
704
705 double js::math_log1p_impl(double x) {
706 AutoUnsafeCallWithABI unsafe;
707 return fdlibm_log1p(x);
708 }
709
710 static bool math_log1p(JSContext* cx, unsigned argc, Value* vp) {
711 CallArgs args = CallArgsFromVp(argc, vp);
712 return math_function<math_log1p_impl>(cx, args);
713 }
714
715 double js::math_expm1_impl(double x) {
716 AutoUnsafeCallWithABI unsafe;
717 return fdlibm_expm1(x);
718 }
719
720 static bool math_expm1(JSContext* cx, unsigned argc, Value* vp) {
721 CallArgs args = CallArgsFromVp(argc, vp);
722 return math_function<math_expm1_impl>(cx, args);
723 }
724
725 double js::math_cosh_impl(double x) {
726 AutoUnsafeCallWithABI unsafe;
727 return fdlibm_cosh(x);
728 }
729
730 static bool math_cosh(JSContext* cx, unsigned argc, Value* vp) {
731 CallArgs args = CallArgsFromVp(argc, vp);
732 return math_function<math_cosh_impl>(cx, args);
733 }
734
735 double js::math_sinh_impl(double x) {
736 AutoUnsafeCallWithABI unsafe;
737 return fdlibm_sinh(x);
738 }
739
740 static bool math_sinh(JSContext* cx, unsigned argc, Value* vp) {
741 CallArgs args = CallArgsFromVp(argc, vp);
742 return math_function<math_sinh_impl>(cx, args);
743 }
744
745 double js::math_tanh_impl(double x) {
746 AutoUnsafeCallWithABI unsafe;
747 return fdlibm_tanh(x);
748 }
749
750 static bool math_tanh(JSContext* cx, unsigned argc, Value* vp) {
751 CallArgs args = CallArgsFromVp(argc, vp);
752 return math_function<math_tanh_impl>(cx, args);
753 }
754
755 double js::math_acosh_impl(double x) {
756 AutoUnsafeCallWithABI unsafe;
757 return fdlibm_acosh(x);
758 }
759
760 static bool math_acosh(JSContext* cx, unsigned argc, Value* vp) {
761 CallArgs args = CallArgsFromVp(argc, vp);
762 return math_function<math_acosh_impl>(cx, args);
763 }
764
765 double js::math_asinh_impl(double x) {
766 AutoUnsafeCallWithABI unsafe;
767 return fdlibm_asinh(x);
768 }
769
770 static bool math_asinh(JSContext* cx, unsigned argc, Value* vp) {
771 CallArgs args = CallArgsFromVp(argc, vp);
772 return math_function<math_asinh_impl>(cx, args);
773 }
774
775 double js::math_atanh_impl(double x) {
776 AutoUnsafeCallWithABI unsafe;
777 return fdlibm_atanh(x);
778 }
779
780 static bool math_atanh(JSContext* cx, unsigned argc, Value* vp) {
781 CallArgs args = CallArgsFromVp(argc, vp);
782 return math_function<math_atanh_impl>(cx, args);
783 }
784
785 double js::ecmaHypot(double x, double y) {
786 AutoUnsafeCallWithABI unsafe;
787 return fdlibm_hypot(x, y);
788 }
789
790 static inline void hypot_step(double& scale, double& sumsq, double x) {
791 double xabs = mozilla::Abs(x);
792 if (scale < xabs) {
793 sumsq = 1 + sumsq * (scale / xabs) * (scale / xabs);
794 scale = xabs;
795 } else if (scale != 0) {
796 sumsq += (xabs / scale) * (xabs / scale);
797 }
798 }
799
800 double js::hypot4(double x, double y, double z, double w) {
801 AutoUnsafeCallWithABI unsafe;
802
803 // Check for infinities or NaNs so that we can return immediately.
804 if (std::isinf(x) || std::isinf(y) || std::isinf(z) || std::isinf(w)) {
805 return mozilla::PositiveInfinity<double>();
806 }
807
808 if (std::isnan(x) || std::isnan(y) || std::isnan(z) || std::isnan(w)) {
809 return GenericNaN();
810 }
811
812 double scale = 0;
813 double sumsq = 1;
814
815 hypot_step(scale, sumsq, x);
816 hypot_step(scale, sumsq, y);
817 hypot_step(scale, sumsq, z);
818 hypot_step(scale, sumsq, w);
819
820 return scale * std::sqrt(sumsq);
821 }
822
823 double js::hypot3(double x, double y, double z) {
824 AutoUnsafeCallWithABI unsafe;
825 return hypot4(x, y, z, 0.0);
826 }
827
828 static bool math_hypot(JSContext* cx, unsigned argc, Value* vp) {
829 CallArgs args = CallArgsFromVp(argc, vp);
830 return math_hypot_handle(cx, args, args.rval());
831 }
832
833 bool js::math_hypot_handle(JSContext* cx, HandleValueArray args,
834 MutableHandleValue res) {
835 // IonMonkey calls the ecmaHypot function directly if two arguments are
836 // given. Do that here as well to get the same results.
837 if (args.length() == 2) {
838 double x, y;
839 if (!ToNumber(cx, args[0], &x)) {
840 return false;
841 }
842 if (!ToNumber(cx, args[1], &y)) {
843 return false;
844 }
845
846 double result = ecmaHypot(x, y);
847 res.setDouble(result);
848 return true;
849 }
850
851 bool isInfinite = false;
852 bool isNaN = false;
853
854 double scale = 0;
855 double sumsq = 1;
856
857 for (unsigned i = 0; i < args.length(); i++) {
858 double x;
859 if (!ToNumber(cx, args[i], &x)) {
860 return false;
861 }
862
863 isInfinite |= std::isinf(x);
864 isNaN |= std::isnan(x);
865 if (isInfinite || isNaN) {
866 continue;
867 }
868
869 hypot_step(scale, sumsq, x);
870 }
871
872 double result = isInfinite ? PositiveInfinity<double>()
873 : isNaN ? GenericNaN()
874 : scale * std::sqrt(sumsq);
875 res.setDouble(result);
876 return true;
877 }
878
879 double js::math_trunc_impl(double x) {
880 AutoUnsafeCallWithABI unsafe;
881 return fdlibm_trunc(x);
882 }
883
884 float js::math_truncf_impl(float x) {
885 AutoUnsafeCallWithABI unsafe;
886 return fdlibm_truncf(x);
887 }
888
889 bool js::math_trunc(JSContext* cx, unsigned argc, Value* vp) {
890 CallArgs args = CallArgsFromVp(argc, vp);
891 if (args.length() == 0) {
892 args.rval().setNaN();
893 return true;
894 }
895
896 double x;
897 if (!ToNumber(cx, args[0], &x)) {
898 return false;
899 }
900
901 args.rval().setNumber(math_trunc_impl(x));
902 return true;
903 }
904
905 double js::math_sign_impl(double x) {
906 AutoUnsafeCallWithABI unsafe;
907
908 if (std::isnan(x)) {
909 return GenericNaN();
910 }
911
912 return x == 0 ? x : x < 0 ? -1 : 1;
913 }
914
915 bool js::math_sign(JSContext* cx, unsigned argc, Value* vp) {
916 CallArgs args = CallArgsFromVp(argc, vp);
917 if (args.length() == 0) {
918 args.rval().setNaN();
919 return true;
920 }
921
922 double x;
923 if (!ToNumber(cx, args[0], &x)) {
924 return false;
925 }
926
927 args.rval().setNumber(math_sign_impl(x));
928 return true;
929 }
930
931 double js::math_cbrt_impl(double x) {
932 AutoUnsafeCallWithABI unsafe;
933 return fdlibm_cbrt(x);
934 }
935
936 static bool math_cbrt(JSContext* cx, unsigned argc, Value* vp) {
937 CallArgs args = CallArgsFromVp(argc, vp);
938 return math_function<math_cbrt_impl>(cx, args);
939 }
940
941 static bool math_toSource(JSContext* cx, unsigned argc, Value* vp) {
942 CallArgs args = CallArgsFromVp(argc, vp);
943 args.rval().setString(cx->names().Math);
944 return true;
945 }
946
947 enum class SumPreciseState : uint8_t {
948 MinusZero,
949 Finite,
950 PlusInfinity,
951 MinusInfinity,
952 NotANumber,
953 };
954
955 /**
956 * Math.sumPrecise ( items )
957 *
958 * https://tc39.es/proposal-math-sum/#sec-math.sumprecise
959 */
960 static bool math_sumPrecise(JSContext* cx, unsigned argc, Value* vp) {
961 constexpr int64_t MaxCount = int64_t(1) << 53;
962
963 // Step 1. Perform ? RequireObjectCoercible(items).
964 CallArgs args = CallArgsFromVp(argc, vp);
965 if (!args.requireAtLeast(cx, "Math.sumPrecise", 1)) {
966 return false;
967 }
968
969 // Step 2. Let iteratorRecord be ? GetIterator(items, sync).
970 JS::ForOfIterator iterator(cx);
971 if (!iterator.init(args[0], JS::ForOfIterator::ThrowOnNonIterable)) {
972 return false;
973 }
974
975 // Step 3. Let state be minus-zero.
976 SumPreciseState state = SumPreciseState::MinusZero;
977
978 // Step 4. Let sum be 0.
979 xsum_small_accumulator sum;
980 xsum_small_init(&sum);
981
982 // Step 5. Let count be 0.
983 int64_t count = 0;
984
985 // Step 6. Let next be not-started.
986 // (implicit)
987
988 JS::Rooted<JS::Value> value(cx);
989
990 // Step 7. Repeat, while next is not done,
991 while (true) {
992 // Step 7.a. Set next to ? IteratorStepValue(iteratorRecord).
993 bool done;
994 if (!iterator.next(&value, &done)) {
995 return false;
996 }
997
998 // Step 7.b. If next is not done, then
999 if (done) {
1000 break;
1001 }
1002
1003 // Step 7.b.i. Set count to count + 1.
1004 count += 1;
1005
1006 // Step 7.b.ii. If count ≥ 2**53, then
1007 if (count >= MaxCount) {
1008 // Step 7.b.ii.1. Let error be ThrowCompletion(a newly created RangeError
1009 // object).
1010 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1011 JSMSG_SUMPRECISE_TOO_MANY_VALUES);
1012
1013 // Step 7.b.ii.2. Return ? IteratorClose(iteratorRecord, error).
1014 iterator.closeThrow();
1015 return false;
1016 }
1017
1018 // Step 7.b.iv. If next is not a Number, then
1019 if (!value.isNumber()) {
1020 // Step 7.b.iv.1. Let error be ThrowCompletion(a newly created TypeError
1021 // object).
1022 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1023 JSMSG_SUMPRECISE_EXPECTED_NUMBER);
1024
1025 // Step 7.b.iv.2. Return ? IteratorClose(iteratorRecord, error).
1026 iterator.closeThrow();
1027 return false;
1028 }
1029
1030 // Step 7.b.v. Let n be next.
1031 double n = value.toNumber();
1032
1033 // Step 7.b.vi. If state is not not-a-number, then
1034 if (state == SumPreciseState::NotANumber) {
1035 continue;
1036 }
1037
1038 // Step 7.b.vi.1. If n is NaN, then
1039 if (std::isnan(n)) {
1040 // Step 7.b.vi.1.a. Set state to not-a-number.
1041 state = SumPreciseState::NotANumber;
1042 } else if (n == PositiveInfinity<double>()) {
1043 // Step 7.b.vi.2. Else if n is +∞𝔽, then
1044 if (state == SumPreciseState::MinusInfinity) {
1045 // Step 7.b.vi.2.a. If state is minus-infinity, set state to
1046 // not-a-number.
1047 state = SumPreciseState::NotANumber;
1048 } else {
1049 // Step 7.b.vi.2.b. Else, set state to plus-infinity.
1050 state = SumPreciseState::PlusInfinity;
1051 }
1052 } else if (n == NegativeInfinity<double>()) {
1053 // Step 7.b.vi.3. Else if n is -∞𝔽, then
1054 if (state == SumPreciseState::PlusInfinity) {
1055 // Step 7.b.vi.3.a. If state is plus-infinity, set state to
1056 // not-a-number.
1057 state = SumPreciseState::NotANumber;
1058 } else {
1059 // Step 7.b.vi.3.b. Else, set state to minus-infinity.
1060 state = SumPreciseState::MinusInfinity;
1061 }
1062 } else if (!IsNegativeZero(n) && (state == SumPreciseState::MinusZero ||
1063 state == SumPreciseState::Finite)) {
1064 // Step 7.b.vi.4. Else if n is not -0𝔽 and state is either minus-zero or
1065 // finite, then
1066 // Step 7.b.vi.4.a. Set state to finite.
1067 state = SumPreciseState::Finite;
1068
1069 // Step 7.b.vi.4.b. Set sum to sum + ℝ(n).
1070 xsum_small_add1(&sum, n);
1071 }
1072 }
1073
1074 double rval;
1075 switch (state) {
1076 case SumPreciseState::NotANumber:
1077 // Step 8. If state is not-a-number, return NaN.
1078 rval = GenericNaN();
1079 break;
1080 case SumPreciseState::PlusInfinity:
1081 // Step 9. If state is plus-infinity, return +∞𝔽.
1082 rval = PositiveInfinity<double>();
1083 break;
1084 case SumPreciseState::MinusInfinity:
1085 // Step 10. If state is minus-infinity, return -∞𝔽.
1086 rval = NegativeInfinity<double>();
1087 break;
1088 case SumPreciseState::MinusZero:
1089 // Step 11. If state is minus-zero, return -0𝔽.
1090 rval = -0.0;
1091 break;
1092 case SumPreciseState::Finite:
1093 // Step 12. Return 𝔽(sum).
1094 rval = xsum_small_round(&sum);
1095 break;
1096 }
1097
1098 args.rval().setNumber(rval);
1099 return true;
1100 }
1101
1102 UnaryMathFunctionType js::GetUnaryMathFunctionPtr(UnaryMathFunction fun) {
1103 switch (fun) {
1104 case UnaryMathFunction::SinNative:
1105 return math_sin_native_impl;
1106 case UnaryMathFunction::SinFdlibm:
1107 return math_sin_fdlibm_impl;
1108 case UnaryMathFunction::CosNative:
1109 return math_cos_native_impl;
1110 case UnaryMathFunction::CosFdlibm:
1111 return math_cos_fdlibm_impl;
1112 case UnaryMathFunction::TanNative:
1113 return math_tan_native_impl;
1114 case UnaryMathFunction::TanFdlibm:
1115 return math_tan_fdlibm_impl;
1116 case UnaryMathFunction::Log:
1117 return math_log_impl;
1118 case UnaryMathFunction::Exp:
1119 return math_exp_impl;
1120 case UnaryMathFunction::ATan:
1121 return math_atan_impl;
1122 case UnaryMathFunction::ASin:
1123 return math_asin_impl;
1124 case UnaryMathFunction::ACos:
1125 return math_acos_impl;
1126 case UnaryMathFunction::Log10:
1127 return math_log10_impl;
1128 case UnaryMathFunction::Log2:
1129 return math_log2_impl;
1130 case UnaryMathFunction::Log1P:
1131 return math_log1p_impl;
1132 case UnaryMathFunction::ExpM1:
1133 return math_expm1_impl;
1134 case UnaryMathFunction::CosH:
1135 return math_cosh_impl;
1136 case UnaryMathFunction::SinH:
1137 return math_sinh_impl;
1138 case UnaryMathFunction::TanH:
1139 return math_tanh_impl;
1140 case UnaryMathFunction::ACosH:
1141 return math_acosh_impl;
1142 case UnaryMathFunction::ASinH:
1143 return math_asinh_impl;
1144 case UnaryMathFunction::ATanH:
1145 return math_atanh_impl;
1146 case UnaryMathFunction::Trunc:
1147 return math_trunc_impl;
1148 case UnaryMathFunction::Cbrt:
1149 return math_cbrt_impl;
1150 case UnaryMathFunction::Floor:
1151 return math_floor_impl;
1152 case UnaryMathFunction::Ceil:
1153 return math_ceil_impl;
1154 case UnaryMathFunction::Round:
1155 return math_round_impl;
1156 }
1157 MOZ_CRASH("Unknown function");
1158 }
1159
1160 const char* js::GetUnaryMathFunctionName(UnaryMathFunction fun, bool enumName) {
1161 switch (fun) {
1162 case UnaryMathFunction::SinNative:
1163 return enumName ? "SinNative" : "Sin (native)";
1164 case UnaryMathFunction::SinFdlibm:
1165 return enumName ? "SinFdlibm" : "Sin (fdlibm)";
1166 case UnaryMathFunction::CosNative:
1167 return enumName ? "CosNative" : "Cos (native)";
1168 case UnaryMathFunction::CosFdlibm:
1169 return enumName ? "CosFdlibm" : "Cos (fdlibm)";
1170 case UnaryMathFunction::TanNative:
1171 return enumName ? "TanNative" : "Tan (native)";
1172 case UnaryMathFunction::TanFdlibm:
1173 return enumName ? "TanFdlibm" : "Tan (fdlibm)";
1174 case UnaryMathFunction::Log:
1175 return "Log";
1176 case UnaryMathFunction::Exp:
1177 return "Exp";
1178 case UnaryMathFunction::ACos:
1179 return "ACos";
1180 case UnaryMathFunction::ASin:
1181 return "ASin";
1182 case UnaryMathFunction::ATan:
1183 return "ATan";
1184 case UnaryMathFunction::Log10:
1185 return "Log10";
1186 case UnaryMathFunction::Log2:
1187 return "Log2";
1188 case UnaryMathFunction::Log1P:
1189 return "Log1P";
1190 case UnaryMathFunction::ExpM1:
1191 return "ExpM1";
1192 case UnaryMathFunction::CosH:
1193 return "CosH";
1194 case UnaryMathFunction::SinH:
1195 return "SinH";
1196 case UnaryMathFunction::TanH:
1197 return "TanH";
1198 case UnaryMathFunction::ACosH:
1199 return "ACosH";
1200 case UnaryMathFunction::ASinH:
1201 return "ASinH";
1202 case UnaryMathFunction::ATanH:
1203 return "ATanH";
1204 case UnaryMathFunction::Trunc:
1205 return "Trunc";
1206 case UnaryMathFunction::Cbrt:
1207 return "Cbrt";
1208 case UnaryMathFunction::Floor:
1209 return "Floor";
1210 case UnaryMathFunction::Ceil:
1211 return "Ceil";
1212 case UnaryMathFunction::Round:
1213 return "Round";
1214 }
1215 MOZ_CRASH("Unknown function");
1216 }
1217
1218 static const JSFunctionSpec math_static_methods[] = {
1219 JS_FN("toSource", math_toSource, 0, 0),
1220 JS_INLINABLE_FN("abs", math_abs, 1, 0, MathAbs),
1221 JS_INLINABLE_FN("acos", math_acos, 1, 0, MathACos),
1222 JS_INLINABLE_FN("asin", math_asin, 1, 0, MathASin),
1223 JS_INLINABLE_FN("atan", math_atan, 1, 0, MathATan),
1224 JS_INLINABLE_FN("atan2", math_atan2, 2, 0, MathATan2),
1225 JS_INLINABLE_FN("ceil", math_ceil, 1, 0, MathCeil),
1226 JS_INLINABLE_FN("clz32", math_clz32, 1, 0, MathClz32),
1227 JS_INLINABLE_FN("cos", math_cos, 1, 0, MathCos),
1228 JS_INLINABLE_FN("exp", math_exp, 1, 0, MathExp),
1229 JS_INLINABLE_FN("floor", math_floor, 1, 0, MathFloor),
1230 JS_INLINABLE_FN("imul", math_imul, 2, 0, MathImul),
1231 JS_INLINABLE_FN("fround", math_fround, 1, 0, MathFRound),
1232 JS_INLINABLE_FN("f16round", math_f16round, 1, 0, MathF16Round),
1233 JS_INLINABLE_FN("log", math_log, 1, 0, MathLog),
1234 JS_INLINABLE_FN("max", math_max, 2, 0, MathMax),
1235 JS_INLINABLE_FN("min", math_min, 2, 0, MathMin),
1236 JS_INLINABLE_FN("pow", math_pow, 2, 0, MathPow),
1237 JS_INLINABLE_FN("random", math_random, 0, 0, MathRandom),
1238 JS_INLINABLE_FN("round", math_round, 1, 0, MathRound),
1239 JS_INLINABLE_FN("sin", math_sin, 1, 0, MathSin),
1240 JS_INLINABLE_FN("sqrt", math_sqrt, 1, 0, MathSqrt),
1241 JS_INLINABLE_FN("tan", math_tan, 1, 0, MathTan),
1242 JS_INLINABLE_FN("log10", math_log10, 1, 0, MathLog10),
1243 JS_INLINABLE_FN("log2", math_log2, 1, 0, MathLog2),
1244 JS_INLINABLE_FN("log1p", math_log1p, 1, 0, MathLog1P),
1245 JS_INLINABLE_FN("expm1", math_expm1, 1, 0, MathExpM1),
1246 JS_INLINABLE_FN("cosh", math_cosh, 1, 0, MathCosH),
1247 JS_INLINABLE_FN("sinh", math_sinh, 1, 0, MathSinH),
1248 JS_INLINABLE_FN("tanh", math_tanh, 1, 0, MathTanH),
1249 JS_INLINABLE_FN("acosh", math_acosh, 1, 0, MathACosH),
1250 JS_INLINABLE_FN("asinh", math_asinh, 1, 0, MathASinH),
1251 JS_INLINABLE_FN("atanh", math_atanh, 1, 0, MathATanH),
1252 JS_INLINABLE_FN("hypot", math_hypot, 2, 0, MathHypot),
1253 JS_INLINABLE_FN("trunc", math_trunc, 1, 0, MathTrunc),
1254 JS_INLINABLE_FN("sign", math_sign, 1, 0, MathSign),
1255 JS_INLINABLE_FN("cbrt", math_cbrt, 1, 0, MathCbrt),
1256 JS_FN("sumPrecise", math_sumPrecise, 1, 0),
1257 JS_FS_END,
1258 };
1259
1260 static const JSPropertySpec math_static_properties[] = {
1261 JS_DOUBLE_PS("E", M_E, JSPROP_READONLY | JSPROP_PERMANENT),
1262 JS_DOUBLE_PS("LOG2E", M_LOG2E, JSPROP_READONLY | JSPROP_PERMANENT),
1263 JS_DOUBLE_PS("LOG10E", M_LOG10E, JSPROP_READONLY | JSPROP_PERMANENT),
1264 JS_DOUBLE_PS("LN2", M_LN2, JSPROP_READONLY | JSPROP_PERMANENT),
1265 JS_DOUBLE_PS("LN10", M_LN10, JSPROP_READONLY | JSPROP_PERMANENT),
1266 JS_DOUBLE_PS("PI", M_PI, JSPROP_READONLY | JSPROP_PERMANENT),
1267 JS_DOUBLE_PS("SQRT2", M_SQRT2, JSPROP_READONLY | JSPROP_PERMANENT),
1268 JS_DOUBLE_PS("SQRT1_2", M_SQRT1_2, JSPROP_READONLY | JSPROP_PERMANENT),
1269
1270 JS_STRING_SYM_PS(toStringTag, "Math", JSPROP_READONLY),
1271 JS_PS_END,
1272 };
1273
1274 static JSObject* CreateMathObject(JSContext* cx, JSProtoKey key) {
1275 RootedObject proto(cx, &cx->global()->getObjectPrototype());
1276 return NewTenuredObjectWithGivenProto(cx, &MathClass, proto);
1277 }
1278
1279 static const ClassSpec MathClassSpec = {
1280 CreateMathObject,
1281 nullptr,
1282 math_static_methods,
1283 math_static_properties,
1284 nullptr,
1285 nullptr,
1286 nullptr,
1287 };
1288
1289 const JSClass js::MathClass = {
1290 "Math",
1291 JSCLASS_HAS_CACHED_PROTO(JSProto_Math),
1292 JS_NULL_CLASS_OPS,
1293 &MathClassSpec,
1294 };