Skip to content

Add Decimal from the TC39 proposal, off by default - #1004

Open
cirospaciari wants to merge 28 commits into
mainfrom
claude/gallant-feynman-0m5ti5
Open

cirospaciari wants to merge 28 commits into
mainfrom
claude/gallant-feynman-0m5ti5

Conversation

@cirospaciari

@cirospaciari cirospaciari commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Adds Decimal from the TC39 proposal (stage 1): exact base-10 arithmetic on IEEE 754 Decimal128 values. It is off by default; --useDecimal=1 turns it on.

This is what the draft has and nothing else. Literals, operators, structured clone and a toJSON() that answers are stacked on it in #1077, each behind an option of its own.

new Decimal("0.1").add(new Decimal("0.2")).toString()        // "0.3"
new Decimal("19.99").multiply(new Decimal(3)).toString()     // "59.97"
new Decimal(1) + new Decimal(2)                              // TypeError, as in the draft

What is in it

  • The constructor and every method of the prototype.
  • Number(decimal) and BigInt(decimal). Number() has separate code in the host functions, the DFG/FTL operation and compiled programs. Each gets a Decimal branch.
  • Intl.NumberFormat, Intl.PluralRules and toLocaleString.
  • Operators throw, == compares identity and JSON.stringify() throws, as in the draft. structuredClone() throws, since HTML has no steps for a Decimal.
  • Nothing in the parser, the bytecode generator, cached bytecode or WebCore changes.

How it is fast

  • A value is 16 bytes, its object 32. The arithmetic is in 64 or 128 bits where the operands fit, and in limbs of 64 bits otherwise.

  • DecimalStringCache: 512 sets of two strings per VM, 32 KB, made on first use and cleared by a full collection, as the one of numbers.

  • DFG and FTL compute with the two words of a value in registers, and make an object only where one can be seen. x.multiply(y).add(z) makes one object, x.add(y).lessThan(z) none, and new Decimal("0.95") that is an operand is a constant.

    Node
    DecimalWordConstant, GetDecimalWord a word: of a constant, or of an object behind a CheckJSCast
    ToDecimal, DecimalArith, DecimalScale both words, as a tuple: new Decimal(x), arithmetic, round() and scale10()
    DecimalTest, DecimalToNumber, DecimalToString, DecimalToFixed a boolean, a number, a string
    NewDecimal, PhantomNewDecimal the object, which allocation sinking moves or removes, and an OSR exit makes
  • Add, subtract, multiply, the comparisons, round(), scale10(), exponent() and new Decimal(int32) are inline for coefficients of 64 bits, and C++ is called for the rest. jit/DecimalFastPaths.h has them once, for the FTL and for compiled programs.

  • An object never shows trailing zeros. A result that only goes into another operation keeps them, and what needs the one way to write a value strips them.

  • A quotient that is only rounded is computed to the digits that stay. A division by a constant with an exact reciprocal is a multiplication.

  • A value that goes around a loop, in the FTL: DecimalPhiUnboxingPhase turns a Phi of Decimals into Phis of the words and a NewDecimal behind them, which allocation sinking removes. An object that exists already goes along in a third Phi, so that its identity is kept.

  • Compiled programs generate a row of calls by the names of the methods twice, for Decimals and as it is written (DecimalRuns). Values of which no two are alive at once take turns in one object, until something else than a Decimal operation reads it (ReusedDecimals). Both need the option when the program is built; without it the generated code is as before.

  • Optimized code throws no error of a Decimal function. It exits (BadType, or the new BadDecimalArgument), the function throws, and the call is an ordinary one from then on. An error is thus the same in every tier, with its native frame.

  • One intrinsic, since the enum is nearly full: the native function says which operation it is. Calls are ordinary where only the executable is known, as with Decimals of two realms, for toPrecision() and toLocaleString(), for a rounding mode of round() that is no constant, and for options of toFixed() that are not an object literal.

  • Outside of Decimal code: LICM can hoist an ExtractFromTuple of these words and leaves an empty Check for it, and an assertion in VirtualRegisterAllocationPhase allows for a tuple that must be generated.

  • Loops with these nodes are not unrolled. A total in a property, in a variable of a closure (forEach), or one that begins as undefined is still an object in each turn, 8 to 9 ns.

Nanoseconds for everyday amounts like 19.99, from JavaScript, with the new object. A local Release build without LTO, AMD EPYC. "Compiled" is bun build --compile --aot. decimal.js 10.6.0 runs in the same engine, with the JIT; C# decimal and rust_decimal 1.43.0 (with LTO) are compiled calls on values. The table is of the code before the split, where the loops have literals. With new Decimal() in their place this branch takes 4.0, 13 and 12 ns with the JIT, 4.3, 15 and 12 compiled, and 45, 211 and 151 without a JIT, on a machine of the same kind. The single operations have the same code; eleven of them, timed again in turns, are within 0.2 ns with the JIT and compiled, and 0 to 3 ns slower here without a JIT, for which I found no cause. Five loops without Decimal take as long as on main, with a JIT and without.

JIT Compiled No JIT decimal.js C# Rust
add 8.8 7.5 74 57 8.6 8.1
subtract 8.7 7.5 74 56 8.8 8.2
multiply 7.0 6.0 74 74 7.6 4.8
divide 14 13 79 944 34 21
remainder 9.6 9.2 75 528 13 10
compare 6.4 5.4 52 27 6.3 6.4
round(2) 4.8 4.6 58 56 2.5 6.5
toString, converted lately 4.1 5.5 34 36 37 44
parse 15 19 66 207 32 12
loop: add up prices 4.0 4.3 44 80 4.1 3.3
loop: price × quantity, discount, add up 13 14 198 332 28 28
loop: price ÷ quantity, round(2), add up 13 12 152 638 52 52

Without a JIT decimal.js takes 9.5 to 63 times as long as Decimal for the nine operations, and compiled 12 to 73 times.

Over 259 combinations of a method and a set of values (21 had a literal) decimal.js is faster in 7, with a JIT and without: where exponent(), 3 to 4 ns, is compared with the field that it stores, 2 ns. So it is in 2 of 56 in compiled programs. isNaN() and isFinite() are level with a JIT, within 0.1 ns. 100,000 distinct values, which no cache serves: toString() 41 ns, decimal.js 101.

Where the draft is not followed

Its steps are followed except where they cannot be carried out, contradict its own definitions, or write another value than the Decimal has. Comments mark the places.

Place Steps of the draft Here
decimal notation of an integer drops the sign keeps it
decimal notation of a fraction cuts it to as many digits as the integer part has writes all of it
exponential notation the exponent has the wrong sign, so the mantissa is scaled the wrong way (12300e-2 for 123) and can leave the domain significand and exponent
toFixed point behind the scaled digits, appends what rounding dropped, strips zeros; a negative value rounds in the mirrored mode the rounded value with that many digits, rounded as the mode is defined
toPrecision never uses the precision it reads uses it
toPrecision, as many digits or fewer a wrong value for many (125 for 1.25) digits and notation of Number
toPrecision, more digits wrong scale and exponent, an assertion that always fails exponential notation of the rounded value
toPrecision, negative counts the sign as a digit, can write it twice, mirrored mode counts digits, one sign, the mode as defined
Intl [[Decimal128Data]] throughout; a zero is returned unconverted; toLocaleString does not convert [[DecimalData]]; 0 and negative zero; through ToIntlMathematicalValue
PluralRules the callers of ResolvePlural are not amended select and selectRange pass a Decimal on, by its Number value

Slips of type are read in the obvious way: mantissa has Numbers for Decimal values and an unbound e, remainder the mathematical value 0, and some operations get the object for its value.

Followed although surprising: new Decimal(-0) is +0; notEquals is false of a NaN; toFixed takes { digits }; 1e34 has no plus sign; round takes a negative count; toPrecision() is a RangeError; toPrecision({}) never uses an exponent; toPrecision does not check roundingMode, and rounds half to even by what is not one; valueOf.length is 1; == compares identity, since the draft has no steps for it, while the README of the proposal says that it throws.

selectRange with two ends that are written the same gives their category, as ECMA-402 says, if one is a Decimal. For other values this engine answers as before.

To check

  • runtime/Decimal*.cpp are @no-unify. In the bundles they move JSONObject.cpp, which then lacks an include.
  • The link of compiled programs takes Decimal for a name that an option defines, like gc, whether the option is on or not. A program that stores a class of its own as globalThis.Decimal is optimized less for it, 14% in one loop.
  • An executable that is trimmed keeps the run time of Decimal. In Bun's CI on Linux x64, with Bun's side of it and the extensions on top, hello world maps 82 KB more with --trim (25,696,465 bytes for 25,614,563) and 111 KB more without. A removable feature for it has to be added here and in Bun's engine.def at once, so it is left for the upgrade. toLocaleString() leaves with IntlNumberFormat.
  • The compiler grows by 62 KB in Bun's CI, most of it its code for Decimals, which is compiled for minimum size. That is more than the room that Bun's compile-aot-size.test.ts has, so the upgrade restates its bound. Compiling a program without Decimals retires no more instructions than on main in a local link, and Bun's budgets.test.ts passes in CI.
  • Bun builds with this as it is, and runs and compiles programs with BUN_JSC_useDecimal=1. It then takes a Decimal for an object without properties: Bun.deepEquals finds two different ones equal, and console.log prints the methods. Support Decimal objects with BUN_JSC_useDecimal=1 bun#49321 mends this, and needs nothing but this pull request.

Merging

The extensions were on this branch, and 784e5d7 takes them out, so the diff is the thing to read, not the commits. A merge commit lets #1077 be retargeted to main as it is. After a squash it conflicts, and needs main merged into it first.

Testing

Linux x64, clang 21, Release unless noted. All of it is of 784e5d7, unless noted. The three commits behind it change how the compiler is built and where it tests for Decimals: it writes the same machine code for 700 generated programs and an application of 100,000 lines, and the Decimal tests, testaot run (2890 pass) and testaot native were run again.

  • All of JSTests/stress in all modes: 93483 runs pass, 19 fail: bigint-inc-dec-in-place (17), big-int-out-of-memory-tests and bigint-terminate-multiply, which fail as often on a build of main. Modules: 1639 pass. es6: 605 pass. Two Decimal tests were widened after that run.
  • The Decimal tests as they are checked in, in every mode of the runner: 444 runs pass in Release, 392 in Debug.
  • testaot run: 2889 pass, 0 fail. testaot native: 1 fails, the same as on main.
  • 26.5 million cases against Python's decimal in each of FTL, DFG, no JIT and without concurrent compilation. The only differences are those of a notation of toPrecision that the older of two generators has, as before.
  • 3,467 generated programs against the interpreter, no difference: straight code, and loops that print which values are one object. 1,204 of them are compiled ahead of time; others run with assertions and validation at each phase, with OSR exit and LICM fuzzing, and with frequent collection.
  • 162 deliberate mistakes in the generators of code: the checked-in tests find 140, one more than before the split. Of the others 9 change only what is optimized or where it is emitted. 13 take away a guard for which I found no program that depends on it, among them the explicit watch of the structure in the new phase (the abstract interpreter watches it too) and the CheckNotEmpty in front of a hoisted check.
  • check-includes.py for what changed outside aot/, with and without --headers and --gate-off, and check-syntax.py for the changed sources of aot/: no error.
  • A local build of Bun at bc9a4c84f8, without changes: a program prints the same under bun run, without a JIT, and compiled in four ways. Compiled ahead of time with the option and run without it, it ends with a ReferenceError.
  • The generated code has not run on arm64 locally. All 86 jobs of CI pass at ca19e3f, the tests on arm64 among them.
  • Before the split, for code that it leaves as it is: the draft audited clause by clause (27 findings, all addressed); the arithmetic against the code it replaces, 20 million cases in each of three variants of the build and 3 million with sanitizers, no difference; 12 deliberate mistakes in the string cache and 25 in the arithmetic all found, 60 of 66 in the DFG and FTL nodes; 1253 files of Bun's AOT tests with the option on, where none of the 8 that failed is due to it; nothing from UBSan and ASan.

Generated by Claude Code

@github-actions

github-actions Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Preview build of ca19e3f: autobuild-preview-pr-1004-ca19e3ff

Copy link
Copy Markdown
Member Author

Test bun-webkit-linux-amd64-lto-hardened-aot is red on 948c64d with one failure: stress/new-largeish-contiguous-array-with-size.js.ram-size-10000000, "heap too big before forced GC: 15349288" (limit 10000000).

It is not from this change. The test checks the heap size before a forced GC, so it depends on when the collector got to run. main at 32dc1b0 fails it as often here (Release, Linux x64, 32 cores, 1200 runs each, two rounds):

main this PR
8 at a time 7, 7 10, 5
128 at a time 297, 294 289, 270

The values are the same apart from 16 bytes of initial heap (median 1766502 and 1766518, maximum 15350083 and 15350099, 8 at a time). The other finished amd64 test lanes passed.

I know of no fix. Judging the heap size before the GC by one sample is what makes it fail; taking the smallest of a few samples during the loop might hold. I left the test alone, as this PR is for Decimal only. The job could not be re-run while the workflow is still running (403), so it needs a re-run afterwards.


Generated by Claude Code

Decimal is exact base-10 arithmetic on IEEE 754 Decimal128 values. The
option --useDecimal=1 turns it on. The spec is the draft at
https://tc39.es/proposal-decimal/.

- new Decimal(string, number or BigInt), and all methods of the prototype.
- Number(decimal) and BigInt(decimal). Number() has its own code in the
  interpreter, the DFG and FTL, and compiled programs; each handles it.
- Intl.NumberFormat, Intl.PluralRules and toLocaleString.
- Literals: 1.5m, .5m, 1_000.25m, 1e-3m. The draft leaves these for later.
  A literal makes a new object of %Decimal% each time.

As in the draft, operators throw on a Decimal, so -1.5m throws; write
1.5m.negate().

The steps of the draft are followed except where they cannot be carried
out or contradict its own definitions. Comments mark each place:

- toString keeps the sign of an integer.
- The exponent of the exponential notation is that of the value.
- toFixed writes the rounded value with the digits asked for.
- toPrecision uses the precision it reads.
@cirospaciari
cirospaciari force-pushed the claude/gallant-feynman-0m5ti5 branch from 948c64d to 79e8fb1 Compare November 9, 2026 17:51

Copy link
Copy Markdown
Member Author

bun-webkit-linux-arm64-assertions-aot is red on 79e8fb1, and not from this change. The lane's guard cancelled it in the ICU stage, before any file of WebKit was compiled: "icu/compress-data.ts has taken 240 seconds. This runner is too slow. Use "Re-run failed jobs"". The lane passed on main at 0f29ce7, this PR's base. There is nothing to fix here; it needs a re-run, which is possible once the workflow has finished.


Generated by Claude Code

…raft

--useDecimalOperators=1 with --useDecimal=1 makes + - * / %, unary -, ++,
--, the assignments, < <= > >=, == and != work on Decimals. The draft has
them throw, and that is still what --useDecimal=1 alone does. A Decimal and
something else is a TypeError as before, === is identity, and ** and the
bitwise operators throw. Programs compiled ahead of time do not have it.

The operation is a call that BytecodeGenerator emits in front of the
ordinary opcode, for two objects only. The call answers undefined if they
are not Decimals. So no tier has to learn that the result of op_add can be
an object, and without the option the bytecode is what it was. Cached
bytecode made with the option is only used with it.

Changes to follow the steps of the draft:

- toPrecision() without options is a RangeError.
- toPrecision does not check roundingMode; what is not one is halfEven.
- toPrecision reads roundingMode before it throws for -Infinity.
- toPrecision of a value with more digits than asked for has an exponent.
- Intl.PluralRules.prototype.selectRange of Decimals that are written the
  same has their category.

Comments now mark every place where the steps are not followed. Tests for
attributes, realms, white space, the order of checks, identity of results,
modules and 16-bit sources.

cirospaciari commented Nov 9, 2026 •

Copy link
Copy Markdown
Member Author

Test bun-webkit-linux-arm64-lto failed on 73cf989 in one run of about 125,000: stress/ftl-uint32-array-out-of-bounds.js.ftl-eager-no-cjit, with GC Verifier: ERROR cell ... was not marked.

It is not this change's: main fails as often. The arm64 shells that CI built, under qemu-user on x64, with the exact command of the log:

fails
main (0f29ce7, run 42570886217) 39 of 4000
this pull request (73cf989) 41 of 4000

With --verboseVerifyGC=true all five of main's failures I read are the same. The cell is an ArrayBuffer, reached by the opaque root that a marked Float32Array adds in the verifier's marking, and did not add in the real one.

From reading the code, not verified: JSArrayBufferView::slowDownAndWasteMemory() has its write barrier in setButterfly(), and only after that sets m_mode = WastefulTypedArray. A concurrent collector that visits the view between the two sees FastTypedArray, adds no opaque root, and nothing makes it visit the view again. If so, this would fix it, in a change of its own:

         WTF::storeStoreFence();
         m_mode = WastefulTypedArray;
     }
+    // The collector may have visited this since setButterfly(), as a view without an ArrayBuffer.
+    vm.writeBarrier(this);
     heap->addReference(this, buffer.get(), bytesAlreadyReported);

The three other arm64 test lanes and all amd64 lanes passed. The job is to be re-run; GitHub refused that while the run was in progress.


Generated by Claude Code

claude and others added 8 commits November 9, 2026 23:07
…tion

Structured clone of a Decimal, alone or in other values, used to fail. It
now gives an exact copy, with the identity within the graph kept, as for a
BigInt object. The README of the proposal asks for that. Bytes with a
Decimal are rejected where useDecimal is off.

JSON.stringify() of a Decimal is a TypeError, as in the draft. With
--useDecimalToJSON=1 it writes what toString() answers, as a string: a
number would lose digits in JSON.parse().
Adding two amounts like 19.99 from JavaScript takes 14 ns, from 97, and
decimal.js takes 56 in the same engine. Over 217 combinations of a method
and a set of values decimal.js is faster at isNaN() and isFinite(), by 0.1
ns, and where exponent() is compared with the field it stores.

- The arithmetic has limbs of 64 bits instead of 32, computes in 128 bits
  where both operands fit and in 64 bits where the result fits too. A
  quotient is a long division of up to 19 digits at a time. The parser
  reads eight digits at once.
- A Decimal takes 16 bytes, its object 32.
- toString() and the like have a cache of 512 strings, as numbers have.
- new Decimal(number) does not go through text.
- Optimized code has isNaN(), isFinite() and exponent() inline and calls
  the other methods without arguments directly.
- Options are read without the general lookup where the object is
  ordinary. The names are no longer made for each call.

CallDOMGetterData is used for a method here, which has no getter function.
Pure ones are told apart by their DOMJIT::GetterSetter where there is one,
so that two methods on one value are not taken for the same.
The previous commit hashed a Decimal in a way that left the exponent out,
so 1, 0.01 and 1000 had one entry, and compared it through an array, which
the compiler stores and reloads. A cached toString() took 10 to 33 ns, not
5 as before it. The results were right, since a hit is compared in full.

- The hash is the multiply and fold of WTF::intHash(). It takes the format
  too, so the formats of one value are spread as well.
- 512 sets of two entries, so that two values that share a set and take
  turns are both found. toString() of 100 values in a loop takes 4 ns, from
  12 before both commits, and of 256 values 9 ns, from 25.
- A string is made out of line, and the format is the only key beside the
  value.
- The name of a rounding mode is compared as before that commit, which was
  1 ns faster.

The test has values that share sets on purpose. Each of 12 mistakes, as an
ignored sign or mode, makes it fail.

The message of that commit is wrong where it says that decimal.js is only
faster at isNaN(), isFinite() and exponent().
add(), subtract(), multiply(), divide(), remainder(), compare() and the
six other comparisons take both operands checked, and say that they change
nothing but the heap, so that what is known around them stays known. So
does round() with an integer in the source and no mode.

x * y + x - y with methods takes 33 ns, from 46; add() 14 from 16;
compare() 8 from 10; round(2) 12 from 15. round(n, "ceil") takes 22, from
20: the same function, compiled otherwise.

- Only where the function is known. Where only its executable is, code
  that sees Decimals of two realms was thrown away once for each call.
  That was so since the first direct calls, as with isNaN() and abs().
- A CallDOM can have a cell of the class of its receiver as an argument,
  behind a CheckJSCast. It is hoisted only where the class is proven.
- SpeculateInt32Operand and SpeculateBooleanOperand had no move
  constructor, so compileCallDOM() unlocked a register three times for an
  argument of one. Nothing in the tree had such an argument.
- An intrinsic without a thunk does not keep a call from going straight to
  the native function.
- cachedTypesFormatRevision: main's op_call_varargs_with_spread is 15, so
  Decimal's is 16.
- The intrinsic of Decimal no longer looks for Uncountable exits. Upstream
  made the exits of operands BadType, which it looks for anyway.
- The list of the fork's own tests names those of Decimal.
…answers a Decimal

Compiled code converts these in one operation. useDecimalOperators now says that code from strings beside
compiled code has the operators.

Copy link
Copy Markdown
Member Author

Test bun-webkit-linux-arm64-lto-hardened failed on 9c934de with one test, stress/sampling-profiler-line-column.js.ftl-eager-no-cjit (Bad stack trace {"interval":0.001,"traces":[],"sources":[]}). It is not from this pull request.

The test waits for a sample of test() that has a line, and a frame of FTL code is sampled without one. If no sample falls in the time before test() is compiled by the FTL, the test waits its 50 s in vain. BUN-TEST-DIFFERENCES.md describes this for ftl-eager. ftl-eager-no-cjit does it too, less often.

Measured on Linux x64 with 400 processes at a time on 32 cores, with the mode's options except the executable allocation fuzz:

failed
main (6fc709c) 3 of 3000, 6 of 5000
this branch 4 of 3000
main, with the change below 0 of 10000

With the allocation fuzz on, as the mode has it, neither build failed in 1500 runs at normal load or in 600 at this load. I have not reproduced it on arm64.

No fix exists yet that I know of. This one belongs in a change of its own, so I have left it out here. It may also make the $skipModes line unnecessary, which I have not measured.

--- a/JSTests/stress/sampling-profiler-line-column.js
+++ b/JSTests/stress/sampling-profiler-line-column.js
@@
-    noInline(test);
+    noInline(test); noFTL(test); // Bun: upstream lets the FTL compile it. A frame of FTL code is sampled without a line.

Generated by Claude Code

A Decimal128 is two nodes, its words, and an object is made only where one
can be seen: NewDecimal is sunk, and made at an OSR exit. This replaces the
use of CallDOM and CallDOMGetter, and the changes that were made to them.

- The FTL has add, subtract, multiply, the comparisons, round(), scale10(),
  exponent() and new Decimal(int32) inline for coefficients of 64 bits.
- Literals, and operations on constants, are constants.
- round() and scale10() take any count, and toFixed() reads an object
  literal without making it.
- Optimized code exits where a function has an error to throw, so errors
  are the same in every tier.
- Conversions from and to doubles no longer go through text.

A literal is a call of the link-time function decimalLiteral, which compiled
programs can call too. A minus in front of a literal belongs to it, also
without the operators. A literal can no longer be the name of a property.

toLocaleString() leaves with Intl.NumberFormat when an executable is trimmed.
It is not constexpr on Windows. The table is the same.
A long result is searched for zeros at its end only if it is a multiple of
10, a digit too many is dropped without a division, and values of one sign
and one exponent are compared by their words, inline in the FTL.
The link took a name that is in no table for undefined, so a program with
`const D = Decimal` compiled and then failed a type check. The name is now
one of those that options define.

decimalLiteral() answers NaN for text that is no number, since its row in
the table of built-ins takes any String.
A result goes to its object in registers, short literals are not parsed
each time, and round() of an Int32 does not go through a double.
…piled programs

- Division, remainder and parsing have new paths without branches on the data.
  A division whose quotient is only rounded computes the digits that stay, and
  one by a constant with an exact reciprocal is a multiplication.
- The fast paths are written once, for the FTL and for compiled programs.
- A result that only goes into another operation keeps its trailing zeros.
- Compiled programs generate a row of calls of Decimal methods twice: for
  Decimals, with the words in registers, and as it is written.
- FTL: a Phi of Decimals becomes Phis of their words and a NewDecimal behind
  them, which allocation sinking removes. An object that exists already goes
  along in a third Phi, so that identity is kept.
- Compiled programs: values of which no two are alive at once take turns in
  one object, until something other than a Decimal operation reads it.
- A total keeps its trailing zeros around the loop, and an addition to it has
  a path on which the next one waits for one instruction.
Literals, operators, structured clone and the option for toJSON() move to a
branch on top of this one.

- The parser, the bytecode generator, cached bytecode and WebCore are as on
  main.
- The tests construct their values where they had literals.
- The test of operators covers all of them, in every tier.

Copy link
Copy Markdown
Member Author

A correction to my comment on stress/sampling-profiler-line-column.js: the cause I gave was wrong. FTL frames are not always sampled without a line. The test runs without the map from pc to origin, so the line of optimized code is what an earlier call left in the frame. noFTL(test) only hides that. The fix is in #1078.


Generated by Claude Code

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the two inline nits, a few larger candidates were examined and ruled out: LICM hoisting of ToDecimal (its typed forms are Int32/DoubleRep and cannot fail; the Untyped form only resolves ropes, so a hoisted copy can at most deopt or OOM, as other hoisted string nodes already can), the concurrent-GC visit of the lazily created DecimalStringCache (it is visited via vm().visitAggregate under the same strong-handles constraint as NumericStrings, with null-checked entries), and the unbounded toFixed/toPrecision digit count (matches the draft, which sets no limit, and is exercised by decimal-longest-texts.js). Nothing was built or run in this review; the DFG/FTL/AOT paths were checked by reading only, so a human pass over the JIT tiers is still worthwhile given the size.

Extended reasoning...

The change adds a complete Decimal128 implementation (runtime objects, prototype, Intl hooks, a per-VM string cache, new DFG/FTL node types with allocation sinking and a phi-unboxing phase, and AOT code generation) across 168 files and about 14k lines, gated behind --useDecimal. It touches no auth, injection or data-exposure surface, but it adds new JIT node semantics (mayExit, clobberize, safeToExecute, LICM) where a mistake is a miscompile rather than a visible error. The two confirmed findings are nits; the sheer size and the JIT-tier scope are what make a human review still worthwhile rather than approval.

Comment thread JSTests/stress/decimal-longest-texts.js Resolved
The tests for Decimals at each read, operation and block added 0.24% to the
instructions of emit with the option off. They now share flags that were
tested already. The generated code is the same.
It takes 56 KB instead of 100. AOTFacts.cpp comes to the head of a bundle of 8,
where it lacked an include.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

The emitter kept the address of the run, which lives on the stack of its
caller. Nothing read it afterwards, and the generated code is the same.

void VM::initializeDecimalStringCache()
{
m_decimalStringCache = makeUnique<DecimalStringCache>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 On weakly ordered CPUs (ARM64), a concurrent GC can read the Decimal string cache before its zeroed contents are visible and mark garbage pointers, which can crash the process. VM.cpp:895 publishes the lazily made cache with a plain store, while the collector reads it concurrently at VM.cpp:2469-2470 from the "Sh" constraint, which is ConstraintConcurrency::Concurrent (Heap.cpp:3371-3374). Fix: publish the cache the way other GC-visited lazy state is published, with WTF::storeStoreFence() between constructing the DecimalStringCache and storing m_decimalStringCache (as VM.cpp:675 does for m_isInService), or create the cache eagerly in the VM constructor like m_jsonCache.

Why this was flagged

A program with --useDecimal=1 calls toString(), toFixed() or toPrecision() on a Decimal for the first time while a concurrent marking cycle is in progress. decimalStringCache() at VM.h:699-704 finds m_decimalStringCache null and calls initializeDecimalStringCache(), which at VM.cpp:895 does m_decimalStringCache = makeUnique<DecimalStringCache>(): the constructor zero-fills std::array<Set, 512> m_sets { } (DecimalStringCache.h:71), then the pointer is stored with no fence. The collector thread runs vm().visitAggregate(visitor) from the "Sh" marking constraint, registered Concurrent at Heap.cpp:3371-3374, and at VM.cpp:2469-2470 tests m_decimalStringCache and iterates every entry calling visitor.appendUnbarriered(entry.string). On ARM64 the store of the pointer may become visible before the zeroing stores, so the collector can read stale bytes from the freshly allocated block as JSString pointers and mark them. The base branch has no such lazily published, GC-visited cache. Existing JSC lazy publication to the collector uses WTF::storeStoreFence() first (VM.cpp:674-676); nothing here does.

Verification: VM.cpp:893-896 publishes it with a plain store. No WTF::storeStoreFence() sits between the fill and the pointer store. The collector reads it concurrently at VM.cpp:2469-2470 from the "Sh" constraint (Heap.cpp:3374). On ARM64 the pointer store may become visible before the zeroing stores, so the collector can see non-null, uninitialized entry.string values.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I traced this and left the code as it is: the collector does not read the cache while the mutator runs.

  • ConstraintConcurrency::Concurrent is about other constraints. ConstraintConcurrency.h:32: "This is concurrency with other constraints not the mutator. All constraints run with the world stopped."
  • VM::visitAggregate() has one caller, the "Sh" constraint. Constraints run from Collector::runFixpointPhase() (Collector.cpp:650, behind assertIsConductorWithWorldStopped()) and from the verifier at the end of a collection (:1268). runTaskInParallel() waits for every thread before it returns (:1214).
  • The stores are ordered by the stop itself. Either the mutator conducts and hands the task to the helpers under m_markingMutex, or it has released access with a compare-and-swap of m_worldState, which stopTheMutator() reads.
  • The same function walks the vectors of m_synchronousModuleQueue without a lock, and DecimalStringCache::add() writes entries with plain stores, as NumericStrings does. A fence at the first store would not make either safe beside a running mutator.

With --collectContinuously=1 --useConcurrentGC=1 and breakpoints that log stopThePeriphery, resumeThePeriphery and VM::visitAggregate (x64, three runs): 4,448 concurrent phases and 19,171 visits, all of them between a stop and a resume.

I am leaving the thread open for a maintainer to confirm.


Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants