Repository navigation
[JSC] AOT: counted loops that can be interrupted, vector loops over typed arrays, number fields past 32 bits, records that passes keep true - #927
Conversation
…leanup - Plain code that imports from the compiled program reads through to the compiled variable (JSScope, JSModuleEnvironment, JSModuleNamespaceObject, SyntheticModuleRecord); plain module reads are unchanged. - A literal of constants with 4,096 leaves or more at the top of an untyped module is JSON text and one parse; a frame too large for the image is a sentence instead of a trap; long chains of concatenations are not fused into one. - The lock on built-ins in sloppy code: what the lock alone refuses is loud, every Reflect.* answers false, a delete asks for itself. - Spreads in cold text have a stub; eight *KnownArray built-ins and the rest of the first design's tables are gone. - Names for debuggers and profilers in a Mach-O executable. - The position of `throw new Error()` without taking the stack eagerly. - --aot-audit: what carries the audit's tag passes in line. - Build time: an index of who uses a value; allocation sinking without five walks over all candidates; on ARM64 a constant serves one stretch of a very large procedure.
…testb3 - JSON.parse makes objects with every member in line (up to 62); a literal is finished with every property at its end; conversion plans ask the record's own size. - A record of another layout and a plain object are read by name through a type that accepts outside objects. - Whoever calls by value checks the stack, so functions with a general entry and the entries themselves no longer check in their prologue. - Slow paths: shared argument thunks for more operations, hole and string tests, regular expressions' prologues. - The image step frees the program as read, function by function, and gives pages back between stages. - Error.captureStackTrace keeps `stack` not enumerable on typed records. - testb3 and the other engine test programs run on this branch again; testb3_bun.cpp holds the cases for the opcodes this branch adds.
…aller code - Reads, stores and method calls by name go through one table per Structure and a stub per name; more than half of the read sites are 12 bytes or less. - Guards on arrays are checked once where the array is made or enters, not at each use. - `switch` over a union is a jump table again. - Spreads, rest parameters and destructuring without intermediate arrays. - One copy of the shared stubs in the middle of a large ARM64 image instead of two. - Compiled regular expressions share their class tables. - B3: integer paths are separated early, register copies are forwarded in Air, values live in an arena, and functions are compiled in cohorts. - Typed objects answer getOwnPropertyDescriptor, `in`, Object.entries and deep equality without being turned into plain objects. - A prototype changed on a typed object is honoured per object. - Fewer stack checks, smaller frames and smaller slow paths. - Validation of type facts can be built into a whole program.
Brings the branch up to main at b1e30d0, which includes the upgrade to upstream WebKit. Also in this commit, the ahead-of-time compilation work since the last commit: - Each Worker gets its own 32 GB heap range. Under a limited address space the large reservations share one budget, and later heaps share the first range. - JSON.stringify and Response.json are compiled per record type, including Date members, lists, and records that hold untyped values. - Code made at run time with `new Function` runs faster in the interpreter: warm functions are decoded once, and typed objects, accessors and array literals take cached paths. - Closures keep only the captured variables they can reach. - A method that instances assign to gets a field in the layout. - An object of an open class gives up its layout per object, as a record does. - A store by name that reaches a setter of a typed class is cached. - Property tables: shared stubs per name, entries that no longer evict live ones, cheaper `in`, hasOwnProperty, for-in after a delete, computed keys and Object.fromEntries. - Frozen arrays stay in place; symbols as property names are constants. - Regular expressions: no give-ups to the byte-code interpreter at run time, and a wrong capture for an optional empty group is fixed. - B3: resetReachability() refreshes value owners, barriers made Nops are not decorated, and the optimizer's queue hands out small functions in batches. - The engine builds and runs the test programs with assertions, with exception-check validation, as a Debug build and with AddressSanitizer. Fixes found that way: a Structure kept alive across an allocation, a strict store to an accessor without a setter, operations that forward to another operation from C++.
…keep their fast version Work on ahead-of-time compilation since the merge of main. Property access by name: - A name's column in the lookup table is the name itself, so two names of one object can no longer collide and leave one of them on the slow path. Identifiers are numbered by the sites that use the table. - Own and inherited properties stored far out of line have entries. - A new row is placed where rows of similar objects have room, which makes the first access of a property cheaper. - A store that replaces a property is cached on objects that others inherit from, including static fields of an extended class. - Reading a property that an Error lacks, and `in` on an Error, are cached. - A function is not marked as a possible prototype until something inherits from it. Adding a property to a function used to discard what the table knew under that name. - Symbols made at the top of a CommonJS module are constant names unless the module has failed to load once. Typed code: - Bun.parse<T>() runs a parser emitted for T that fills the laid-out objects directly and falls back to JSON.parse plus validation when in doubt. Bun.validate, Bun.safeValidate and Bun.schema are compiled from the type. - A spread of a record with one layout is copied inside the allocation stub. A spread into a wider type no longer evicts its one cache slot when records with and without an optional field reach the same site. - An array literal of numbers is made by one stub call. - Whether a field may be absent is decided by the type the access goes through, not by every type that shares the slot. - A const filled by `new` keeps the type of what was made. - A length read from an object that is only expected to be a typed array is compared on each path out of its check. - filter(Boolean), map(Number) and similar calls with built-in callbacks are lowered in place. - A BigInt literal is made once and kept. - WebAssembly modules known at build time have their code in the image. Loops and B3: - `i < a.length` in untyped code is compared as integers. - An int32 addition in a loop is an add and an overflow branch. - A rare path out of a versioned loop runs the rest of that iteration in a copy and returns to the fast version instead of leaving it for good. - Several compile-time blowups on very large functions are gone. Fixes: - DFG: with built-ins locked, an array that becomes a derived array and an instance of a class that extends Array no longer contradict the abstract interpreter. - Memory faults found by stressing young collections, and a typed array that lost its buffer after a fifth property under a computed key. - Values that satisfy their declared type are no longer refused in several cases involving Promise, ArrayBuffer, Error and casts. - `"use strict"` is recognized only in its exact spellings.
…ting, JIT fixes Names: - About 7,000 identifiers in aot/ and in this branch's additions to runtime/, heap/, bytecode/, b3/ and assembler/ are renamed to ordinary engine vocabulary, and about 3,000 comment lines are deleted. The IR dump and 34 messages are reworded. AOTLockWords.h is now AOTLockedOperation.h. Typed code: - Unused parameters have no check at the generic entrypoint and are not passed. String and object checks there are half the size. - JSON.stringify of a typed literal is written from the values it was made with, and the literal is allocated only on the fallback. Members that are the constant undefined are dropped at compile time. - `typeof x === "number"` on an optional number no longer boxes it. Reads of optional fields skip a normalization that the next test does not look at. - A spread's fast path no longer loads strings that only its slow path reads. - An empty array literal of numbers is one stub call. - Stores to compact number slots are shorter. JSON, dates and numbers: - The parser emitted for Bun.parse<T>() parses integers inline, reads 16-bit text without converting it to UTF-8, and frees a large scan buffer at the next collection. A catch scope is declared before the generic parse. - A Date no longer sends JSON.stringify to the generic writer, in the per-type writer and in FastStringifier when Date.prototype is locked. toISOString is one operation. A 16-bit string no longer fails the part of a typed JSON.stringify that is handed to the runtime. - Intl.DateTimeFormat and Intl.NumberFormat with a constant locale and constant options format from a pattern in the image: Gregorian calendar, Latin digits, UTC or a fixed offset. Everything else goes to ICU. Property access by name: - A lookup table row is 16 bytes. Sibling rows are placed side by side and never copied. A read miss tries the ordinary-object lookup first. - A keyed read that the by-name cache could answer reaches the keyed table again, so the same key on the same shape stays on the short path. - The first named property stored to an array is cached. Calls and loops: - The generic entrypoint of a function that returns nothing jumps to it. - A loop returns to its fast version at the header after a cloned slow path. A loop whose test never changes gets no fast version. Typed loops with a guard on their element poll once in 65,536 iterations. - Declared int32 arithmetic stays integer. JIT: - The DFG's abstract interpreter no longer claims an Array for Construct of a class that extends Array when built-ins are locked. Freezing an array in place fires the old structure's transition watchpoint. - HasOwnProperty in a for-in over a string constant no longer reaches Unreachable in the FTL. A string switch does not trust a substring's 8-bit flag after its base became 16-bit. An out-of-bounds store of a Number into a BigInt64Array throws. Each has a test in JSTests/stress.
…er generators
Build and tests:
- AOTTypedVerifier.cpp includes <wtf/text/MakeString.h>. All six Windows lanes
stopped there.
- Four stress tests (immutable-intrinsics, immutable-properties-*) expected a
write or delete refused by makePropertiesImmutable() to be ignored in sloppy
code. It throws in both modes, so they now expect the TypeError.
Fixes:
- The cached in-place conversion of a plain object remembered the cell size of
the first object it converted, keyed by StructureID. Objects of one Structure
can lie in cells of two sizes, so a smaller cell could be written past its
end. It now uses the object's own cell size. The cached path also takes
properties that hold objects, arrays and functions, which halves the cost of
a conversion.
- Object.setPrototypeOf() on a typed record cleared every prototype-dependent
entry of the by-name table. It now invalidates only if the object may itself
be a prototype, as JSObject::setPrototypeDirect() does.
- Locking the properties of a lazily created built-in class no longer clears
the by-name table.
- `{ ...o, 1: v }`, `{ ...record, ...dictionary }` and a crash in
placeVariables(), all found by the fuzzers.
- A function that ends in g.apply(thisArg, list) with a list that is not an
array no longer crashes when g throws into a caller that is not compiled.
Typed code:
- Generators: next(), yield* and for-of over a generator that arrives as a
value take a third to a quarter of the instructions.
- Members keyed by a module-level `const k = Symbol()` are fields of the layout.
- An object literal with a computed key the type lacks is born typed.
- A literal that leaves most members unset fills them in chunks.
- super() and `new` of a global constructor drop inline paths that cannot be
taken.
- Text columns whose declared type is a union of string literals are decoded by
comparing bytes.
Compile time:
- Flatter data in B3 and Air (Phi children, sparse collections, stackmap
parameters) and fewer passes over a procedure.
…smaller code outside hot functions - WeakSetInlines.h includes HeapCellInlines.h. The Windows ASAN lane stopped on -Wundefined-inline there. - Revert the marking solver change that passed over a GreyedByExecution constraint while the mutator's execution version stood still. The fast path of Heap::acquireAccess() does not move that version, so a root could stay unmarked. The wasm tests under the GC verifier caught it. - Take the DFG fix from the fork's main, with its test. - One question about hot code replaces four, and a loop no longer changes the code outside it. - Fixes to by-name reads of fields that were never stored, to typed object conversion, and to generators.
…side hot functions - Rename a local named small: the Windows SDK defines it as a macro. - instanceof with many classes no longer goes to C++ for each test. - Code no loop calls shares one fast body per signature. - Reads of a declared field nothing stored to stay out of the runtime. - Fixes to generic types that grow several ways, casts to non-primitive types, and per-file tsconfig handling.
…uarded calls - Windows x64 keeps no chain of frame pointers, so the walk from a native frame to its compiled caller goes through RtlVirtualUnwind. - The image's build stamp has a Windows case. - Calls through a function field share one guarded body per target. - instanceof keeps its one-class fast path. - Small integers are written to JSON from a table of digit pairs. - A literal field whose name starts with a digit is born undefined, not empty.
- AOTTypedObject.cpp named a variable that a rename had removed. - AOTTypedBuiltins.h includes AOTTypedBuiltinLists.h, which was not in the list of private framework headers, so a prebuilt WebKit could not be compiled against. - The error for a store to a locked host prototype names the class and says to use a subclass or a wrapper.
…hey are safe, fixes - mimalloc no longer deletes its pthread key at exit. A thread that started late stored into the deleted key, which another library could have been given by then; jsc died in glibc's mutex code in very short processes. - RegExps whose text is only known at run time run on a flat program instead of the Yarr interpreter: lookahead, repeated and counted groups, simple back-references. - A string buffer region is never nested in another. A stale mark left a later string starting with an earlier call's leftovers, and two interleaved regions could stop a build. - Growing the side storage of a typed object copies from its first slot. - ARM64 stubs check for FJCVTZS before using it. - The first pages are reserved where mmap_min_addr is low. - `instanceof` on an untyped object against a known class stays out of C++.
… x86-64 An operation's front end is entered under the C calling convention. This one used two stub temporaries that are rdi and r12 there, so r12, which is callee-saved, was overwritten.
…matcher - A comparison of a widened string-literal-union field looked through the upcast to a placeholder and folded to false. - A typed object used as a prototype no longer sends every inherited read, call and first store on its heirs to C++. - The flat RegExp program is built only when the RegExp JIT is off: a failed JIT compile leaves the pattern reordered. - A back-reference at the head of a group no longer hides a match; compiling a very long pattern is linear again. - The placement check counts the bit sets of instanceof tests. - Spreading an instance of a class, `delete` of an optional field and `%` with large or negative operands stay out of C++. - A mismatch between front end and engine prints both sides' numbers.
- A pointer to a string's characters was kept from a split to a later Number() or parseInt(); it could dangle once the string was flattened. - An unmade split, field or match group is made where the lowering asks for it. - exec and match results are taken apart only where their type is an array or null. - The RegExp matcher handles every pattern of the fuzzer's grammar. - `new` through a constructor held in a variable is compiled. - A call on an abstract class that is never used as a value is direct. - Sorting by a key compares without calling back. - ARM64: stubs that convert a double without FJCVTZS name the register they use.
…ixes
- Functions that stand for an import() no longer load every built-in module inline.
- Object.setPrototypeOf on a plain object, String(n), `${n}` and ~n stay out of C++.
- A class with a fixed layout constructed through a value is made in the stub.
- for..of over a user's iterable calls [Symbol.iterator] methods directly.
- A cast leaves a plain object as it is.
- The RegExp matcher: a counted group that is always empty is no loop.
- One symbol-keyed field no longer sends every Reflect.ownKeys to C++.
- At its step limit the flat RegExp matcher hands the pattern and the subject to Yarr's interpreter; optional pieces are bounded by what must follow them. - import() functions load what the entry points have not, through one shared call. - A copy made with Object.assign(Object.create(Object.getPrototypeOf(x)), x) keeps its layout. - A cast converts a plain object again. - Templates stored into an array inside a loop are built flat. - A global read in rare code uses the value in its cache. - abort() on Windows prints a crash report that names compiled functions. - stress/sampling-profiler-line-column.js is skipped in one mode (see BUN-TEST-DIFFERENCES.md).
…s keys - The collector's fast visitor of typed objects wrote the whole byte that holds a structure's marking stamp and its flags; it keeps the flags now. - instanceof asks the structure whether a typed record's prototype was replaced. - A generator of one module graph that is stepped from another runs with its own instance. - JSON.parse without a reviver learns the shapes it meets at a place and expects their keys. - A store of a lazily made closure fills its site's own cache slot. - A class's own prototype may gain members where the program names it.
…s into C++ - a === b on two strings, substrings in loops and s === "text" take fewer bytes and fewer instructions. - instanceof, private fields and module-level symbols no longer leak from one module graph into another. - Two recurring keyed stores that shared a slot of the transition table turned their objects into dictionaries at every request; they keep their structures. - Map.prototype.forEach on an unknown receiver and globalThis.Number.isNaN are compiled instead of calling the host. - A sort at a hot site calls its comparator in line again; s += c appends one short string without a call. - An arrow function in a class field is called with its receiver and no longer allocates its closure per instance. - slice, substring and substr accept an undefined start in line. - Response and BunRequest have host class numbers of their own. - Compiled executables on Android do not ask for executable memory.
…branch hints - A call that returns an object in registers is not joined by a block parameter when the code behind a shape test is split; the compiler aborted on it. - new Response(x.body, init) with a call, an await or a yield as its init no longer aborts the compiler. - The structure remembered for `new F()` is no longer shared by call sites whose cache slots have one address; an object could be born with another site's layout. - A block that only asks whether a module has been evaluated is not treated as rare, and the question is asked in line. - An explicit throw in a small function calls its stub again instead of trapping. - The shared JSON parser shares repeated string values as the former one does. - Set.prototype.forEach on an unknown receiver walks the table. - startsWith and endsWith with a literal, substrings and string comparisons take fewer bytes and instructions. - Built-in modules can mark a condition as likely or unlikely. - Fixes for a use after poison in the JSON scan buffer and for a crash in release builds.
…instanceof stays in line - Air lays the unlikely side of a branch out of line; the frequency estimate carries weights backward and treats edges to cold blocks outside loops as rare. - An exception that unwinds through a tail call from one module graph into another is caught with the catching graph's instance; it could crash. - A recursion in which every call crosses module graphs throws a RangeError instead of running off the stack. - A Map or Set that grows in the code of a module graph gets its table's structure; the collector crashed on the table. - A program that may run in several module graphs makes no lazy closures: one read from another graph aborted or ran with the reader's module variables. - A host class's getter read by name in the host and then in a module graph no longer crashes. - The globals of a Bun.ModuleGraph may replace the globals that Bun provides. - instanceof of a built-in class stays in line in programs that hold eval, new Function or a subclass of a built-in class. - new F(), super() and the guards of direct calls hit their fast paths for functions that were constructed before and for class objects. - ARM64: methods of primitives on unknown receivers take the stub's fast part. - A cast of an object that cannot be converted is decided once per structure and type; a cast converts a plain object in place during marking without waiting for the collector. - A closure returned by a direct call with constant arguments is known when the program is built, so calls through it are direct. - Arithmetic and comparisons of two heap BigInts, === of two unknown strings in a loop, super(...args) and reads at known places in loops take fewer steps. - Generator closures no longer collide in the cache of resume functions. - Header names that are constants are looked up when the program is built. - A slice of a rope and Object.setPrototypeOf on a fresh object take as many instructions as before. - BUN_AOT_LAYOUT_SEED pads the compiled code when a program is built, so that a measurement can be averaged over layouts; unset, the output is unchanged.
- The table of copied properties holds its entries behind a pointer; an entry was over the size WTF::HashTable allows where Vector carries ASAN's fields. - Calls of built-ins beside exception handlers, global functions, the size of a Map or Set and private names may share one body; equal bodies are folded. - new Set(array) is made by the runtime again: filled by compiled code it allocated more. - The stub that converts by a plan takes fewer instructions on its way to the runtime. - A closure returned by a helper that needs no constant argument is known when the program is built.
…ed stores and Map lookups - Heap::waitForCollector(): a mutator that is handed the conn uses it instead of handing it straight back; one wait cost thousands of wake-ups on one core. - Converting a plain object to its record type waits for marking to end again: doing it in place raised peak memory. - o[key] = value looks in one table; the megamorphic cache's epoch is mirrored in the instance. - Map.get, Map.has and Set.has on an ordinary table look a hashed string key up without a frame; `key in o` takes fewer instructions. - new Set(array) is filled by compiled code where no compact table is due. - Freezing a typed record that is a prototype tells the caches: a store on an object that inherits from it throws as it must. - A string that was left out of the image is no longer compared when a module graph's globals are looked up: it was given a hash that was not its own. - Number.isNaN and its kin and stores to private names stay in line. - The side of `number | undefined` that is not a number is laid out as unlikely. - A read of a permanent dictionary takes fewer instructions. - The JSON parser's kinds: late turns of a long session no longer pay for the wait.
…objects - Revert "o[key] = value looks in one table" and the two changes on top of it. A keyed store that adds a property within the object's capacity skipped the write barrier when the value was not a cell. The store still gives the object a new Structure, so an old object could end up holding a Structure that nothing else kept alive: heap corruption in long-running processes. - validateAOTTypedFacts: the check of the keyed tables no longer ends in a collection. It cleared a descriptor row that a stub had just found filled. - Object.assign onto an instance of a typed class follows a remembered plan, and between objects of known types the fields are copied in line. - A typed read of a property that the class does not declare is answered ahead of the operation. - `k in o ? o[k] : d` looks the key up once. - The cache of native getters uses open addressing and grows: which entries collided depended on the addresses of strings, so counts varied by run. - An entry point that casts its arguments calls its body through the leaf stubs again.
…s get layouts - A Set or Map literal with constant string keys is a table in the image's read-only data. The cell is made at run time and points at it; the first write copies it. Making a Set of eight strings: 2,413 -> 176 instructions. - `const self = Object.create(Proto); self.a = a; return self` is born as the record its declared type names. - `key in record` finds an inherited name without leaving compiled code. - A typed read of a property beyond the layout no longer forgets its answer when objects of one structure differ in their further keys. - `new URL(request.url, base)` that is only read is not allocated. - process.nextTick(f, a, b) makes no array. - Short slow paths of functions that run at most once are laid behind their guards. - ASAN builds: after a collection only blocks where something can have died are searched. - Tests for the write barrier of keyed stores and for validateAOTTypedFacts.
…hat are never made - Reads, stores and method calls by name test a cache of their own site in line, in the built-in modules that run at every request. node:http /text: -7.0% cycles, Fastify /text: -4.3%. - A constant Set or Map that the program only asks has, get or size is never made: the lookup names the table in the image. - o[key] = value looks in one table again, with the write barrier on the store that adds a property. - What a program makes read-only on a class prototype, or freezes, stops stores on objects that inherit from it, as without --aot. - Fix a crash: a plain object that refers to itself entering typed code a second time. - A number stored under a name the class does not declare is cached: 2,150 -> 40 instructions. - A base URL written as a literal is parsed when the program is built. - `x instanceof C` goes by shape also where C is passed as a value. - node:http and streams queue their ticks by a direct call. - Tests run a part of the suite under the GC verifier.
…nt Sets - Fix a crash on arm64: the stub that converts array elements restored the first argument register over the conversion's answer, so an element that was not converted could reach typed code as if it had been. - has() and get() on a constant Set or Map resolve a rope once instead of copying it at every lookup. - A name that the program defines as an accessor anywhere gets no site cache. - A missing name read through an index signature: 437 -> 52 instructions. - A literal that only a cast holds is made as the record its type names. - Native setters stored in turn: 2,149 -> 132 instructions at every size.
- A call through a function-valued field of an object that never escapes could run the wrong function: two passes dropped the store that the call's test reads. - Proper tail calls were lost for a large typed method taken as a value. - A generic function that spreads its argument threw a TypeError in code that is cold by the call graph: whether the copy keeps its source's layout hung on a prediction that compact code does not ask for. - A copy of an object that inherits a field (spread, Object.assign) no longer counts as the whole type, so reading the missing field gives undefined. - Freezing an object made by Object.create no longer marks every layout as possibly frozen. - Objects made deep in a chain of small makers are made as the type they are cast to. - `x.length` beside `x[i]` in a loop is read in line. - Constant Sets and Maps are made at first use again: skipping that made has() slower.
…rged reads - Array.prototype.sort in compiled code is the engine's algorithm, call for call. The order and the number of comparator calls differed for a comparator that is not transitive. - A young plain object that typed code only reads is checked in line and stays plain: three fields 234 -> 91 instructions, six fields 339 -> 135. - Reads of several properties of one object at one place are merged into one call: smaller code and 1 to 3% fewer cycles on an Effect server. - A testing option compiles every function as cold, beside the one that compiles every function as hot. - Site caches: stores that add a property no longer miss at every run. - Object.keys of an instance with an undeclared property is read in line.
…il-call results checked by the receiver - Chains of filter, map, slice ending in an array, reduce, length, some, every, find or findIndex run as one loop where every callback is proved unobservable. - A plain object that typed code only reads is checked in line instead of converted, including nested data and fields that are unions of string literals. - The result of a call in tail position is checked by whoever receives it, the same whatever was inlined. Proper tail calls hold. - A function that calls itself last is a loop. Atomics on integer typed arrays are in line. - A typed object that untyped code freezes keeps its layout. - A property descriptor that is only taken apart is never made. - Inline caches at call sites on ARM64. - Fixes: a copy of an object with inherited members no longer throws, new of a function cast to a constructor type no longer throws, a cast kept its "if convertible" when an inlining showed the layout.
…n on vectors, number fields hold more than an int32, and passes keep flow's records true - Loops: a counted loop polls for a requested termination once per stretch of turns; unrollLoops also runs in functions without warm code and ignores blocks behind decided comparisons; a loop that its data ends after a few turns keeps its poll in the turn, and so does a loop that goes on where the counter of a loop around it stands and that a path which is not rare leaves for that loop. A loop and its polling copy may both hold blocks behind a rare edge that come back into the loop. The poll does not count as a write of the run time's state; a stub or operation that may collect counts as changing the slots of by-name sites. - B3: VectorizeLoops turns counted loops over typed arrays into vector loops: copy, scale, mean of neighbors, reverse in place, clamp, and elements narrower than the lanes they are computed in. Two counters that meet are tested against one limit. Without AVX the x86-64 assembler emits least, greatest and narrowing from a table of opcode bytes. A vector may be alive at a patchpoint that gives no result, writes nothing and takes no register for numbers. - Module variables: DeferDefinitions records the variable that it reads as read, as DeferInitializers does. The verifier refuses a read of a variable that is recorded as never read, a store to a variable or an environment field that is recorded as never stored to, a NewObject of a layout that is recorded as never allocated, and a namespace that is recorded as never created. Variables of a module whose import is recorded as failed are left out. - Fields: a number field whose writers store more than an int32 is widened where flow narrows it; a field that is added to, indexes or takes part in a bit operation stays an integer until a fraction is stored. A plain Double goes into a slot that keeps markers without a test for NaN. - Classes: an unused class leaves the look at its heritage behind unless the heritage is proven; EliminateDeadCode removes that look where the type rules a throw out. Once the class of a constructor function is defined, a store that leaves another object in its prototype property ends the class's guards. A lookup through super right below a constructor function also depends on that function's prototype property. An allocation that is handed its prototype says that it writes the member guards. SinkAllocations follows objects of constructor functions; a copy of own properties runs its rule before it looks at its source. - Objects: getOwnPropertyNames() asks whether the list is empty after the index keys are in. A fast copy of extra properties follows checkStructureForClone, refuses a Structure with private names and takes the Structure in front of PreventExtensions, Seal or Freeze. The JSON serializer asks what a slot holds, markers included. Object.defineProperty() with a data descriptor becomes a definition where the receiver's set of layouts is complete, each has a plain field of that name and the value's type lies within the slot's type. - Calls: a forwarded apply() tells its list from its receiver by the operand's position. Only callable built-ins join a function type; the type of a well-known symbol is symbol. The stub in front of Construct enters a native constructor of up to 16 arguments without a test of the stack, as the thunk of a host function does. - Proxies: ResolveAccesses expands an access through a proxy whose handler gets its trap by a later store. - Flow: built-ins that let in unseen code stand behind the unknown object in the heap once they have escaped, and share a few records per cause. One readLength() serves keys, values and entries; escaped iterators are chosen by what they were allocated as; opening an iterator reads next. A read under an unknown key of an unknown value counts as read the accessors whose getter is a function of the library. The arguments of a call are carried out where the program calls a method that nobody knows. Tables made once replace walks over all objects. - Modules: require() of a module whose load an import() has begun loads its root once more where that load is still pending. An import() that began outside a require() is not handed to the loader while that require()'s synchronous queue is active. A root that is evaluated with its own stack has its top-level capability set first. The faces of CommonJS files that capture their names get their record before imported files run ahead of the link. - Workers: a new thread's reservation leaves room while other threads are ending. - Errors: making an Error takes fewer steps. A string past the longest length throws. The frame's size is tested before the frame is written. - The compiler: its own sort, shared walks and tables in place of repeated template instances. A third list, SourcesCompiledForMinimumSize.txt, names sources that take no sample in a profiled build. Dominators numbers a backwards graph without making a list of successors at each step. - Checking builds: --aot-check=DecidedComparisons compares again what versionLoops, unrollLoops and foldComparisonsWithBounds decided, and every test that unrollLoops drops from a written-out turn. The log of moved loads follows joined blocks. The scratch word for misfits is a heap of its own, and a call with a landing for misfits says that it writes it. Where facts of guards meet, one number written twice is one position. The validator of inner pointers finds the load that an instruction has taken in by nearness. The validating mode keeps its state behind one thread-local pointer. - Windows: tail calls are marked musttail; three IR tests have lines for Windows x64. - Tests: IR, native, testb3 and testair cases for each of the above.
|
Preview build of 408aaa9: |
…tion says which modules may begin while another runs, and a store that a slot refuses repeats what the last one made - Closures: the cells of the closure table have a heap of their own. Every real call, every stub or operation that may collect, run code or write what a program sees, and the stub that makes a closure write it; it is stated in procedures that read a cell in line. - Loops: what lies behind the rare edges of written-out turns has a copy of its own, which asks again whether there is room and polls before it enters the turns again, so the loop itself has no poll. Where such a loop does not fit one stretch, its written-out turns poll once together and run in no stretches. What is asked in front of a loop makes a constant end anew in the pre-header, and an end that a copied block computes has its user there before values that leave copied blocks are demoted. ThreadJumps raises the frequency of a block that a threaded edge always reaches where one innermost loop holds both, the block has no other way in and the edge's own block is not unlikely. - Module variables: a variable that DeferDefinitions reads where it is defined is recorded as ReadState::OnlyWhereDefined; the call graph and the entry points take that as never read, the verifier does not. RemoveUnreadExports leaves a constant whose making may throw or run code. computeCirclesOfModuleLoads() says for DeferInitializers and CopyClosureFactories which modules may each begin while the other runs: a module loads what its record requests and what a call of require or import in one of its functions names, and a name that the build does not know finds an entry point. - Modules: the queue of a synchronous load stays where the collector finds it while counted imports are handed to the loader. VM::synchronousModuleQueue() answers which queue reactions are diverted to. - Fields: a store of a value that the slot of a field does not take repeats what the last such store made of an object in the same state; 64 such records are kept and cleared at each collection. A read of a silent slot asks first whether some field of the object lies outside its slot. - Flow: the index of the heap reads the written nodes that are asked for in the end. A store that reaches a setter of the host through a chain in which the unknown object stands for the escaped holder files its write. - SinkAllocations: guards of no object are no longer carried along with the guard of an object that is not built, and a copy of own properties looks at its source as it did; the two IR tests of that go with it. - Built-ins: the list of Reflect.construct is an object, as that of Reflect.apply. - Types: what a type test proves keeps an expected type only where that lies inside the type. Where a check of a stored value is answered by the types of all arrivals, the stores of that function take the type of their position again. - Checking builds: with --aot-validate a throw that leaves a call without a site is reported before it is unwound; a validated image marks the return address of each such call, on ARM64 with moves into the zero register. A sabotage lets bounds that are read twice outlast writes. - Sources: no two sources of the compiler declare one name for themselves at namespace scope; check-unified-sources.py takes constinit for no internal linkage. - Tests: IR, native and testb3 cases for each of the above.
…t a compiled object keeps outside its Structure - B3: VectorizeLoops adds up `sum += view[k]` and `sum -= view[k]` in lanes, for up to two sums in a loop that stores nothing. A stretch has no more turns than the lanes of a sum hold without wrapping around. A sum that is a number is added in integer lanes only while it is whole and under 2^51 at the head of a stretch; anything else, and minus zero, goes to the loop as written. Lanes of sixteen bits are added up in pairs; without AVX the x86-64 assembler emits pmaddwd for that, and reduceStrength leaves the multiplication that needs AVX alone there. - Objects: JSObject::ordinaryGetOwnPropertySlot() and JSObject::hasDirectProperty() ask the class of an object only where its Structure says that absence cannot be cached; otherwise they are JSObject::getOwnPropertySlot() and a look into the Structure. The tests in front of the fast paths of RegExp.prototype.exec, Symbol.species and Symbol.isConcatSpreadable, calculatedClassName(), sanitizedNameString() and the labels of both heap snapshots use them; the two places that asked for compiled objects by themselves do so no longer. The Structure of a compiled object and that of the ordinary prototype of a class say that they have transitioned. - Flow: the index of the heap reads written nodes at rest again, and a store through a setter of the host files what it filed before. testing=DelayFlowRules:<n> picks one of 256 schedules of the rules. - Loops: a sum that starts at a constant is not tested in front of the first stretch. In a truthiness test of a value that may be no cell, neither way is called rare. - JSON: an inner object that is refused leaves no refusal for other texts that begin with the same name. - Checking builds: the check that holds a typing from what changed against a typing from nothing asks whether the log ran full meanwhile. A sabotage takes sums of numbers to be whole. - Tests: IR, native and testb3 cases for each of the above.
There was a problem hiding this comment.
I re-reviewed this PR after the three newest commits and found no new bugs; given its size (352 files, roughly 8.5k lines across the AOT compiler, B3 loop phases, and the module loader), a human look is still worthwhile.
What was reviewed:
- The three earlier inline points now read as addressed at HEAD: AOTModules.cpp:1074 sets the synchronous module queue aside through m_synchronousModuleQueueSetAside rather than nulling the pointer VM::visitAggregateImpl walks; appendChoiceOfLoop (B3UnrollLoops.cpp:881) re-materializes a constant counter or bound in the asking block; the duplicate helper is renamed hasClassProofsToCheck.
- tryReservePagesForNewThread (AOTModuleHost.h:158) now takes a bool: an exported-API change that an embedder calling the old signature must follow, not a defect in this tree.
- leavePollToCopy deleting the pre-header's Jump before appendChoiceOfLoop reads preHeader->last(): the pre-header always holds the counter's initial Upsilon (counterFor requires one there), so last() is not read from an empty block.
Extended reasoning...
The diff spans 352 files and about 8.5k inserted lines: the AOT compiler (analysis, codegen, passes, value flow, runtime), B3 loop unrolling/vectorization/versioning, Air shrink wrapping, bmalloc, the heap, and JSC's module loader and promise microtask queue. It touches no injection, auth, or data-exposure surface, but it changes GC-visited runtime state and compiler phases where a wrong transform is a memory-safety bug. The bug hunt ran dry this run and the three findings from the prior review appear fixed in the newest commits, which is what makes this a defer rather than silence; the sheer size and compiler-core nature of the change, plus an incomplete conversation timeline, rule out approval.
There was a problem hiding this comment.
I re-reviewed this PR after the latest commits and found no new bugs; because it is a 480-file change across the AOT compiler, B3 loop unrolling/vectorization, VM module loading and bmalloc, a human look is still worthwhile.
What was reviewed:
- The three earlier inline findings are addressed in HEAD: the set-aside synchronous module queue now stays in the collector-visited chain (VM.h synchronousModuleQueue(), AOTModules.cpp:1083), appendChoiceOfLoop re-materializes constant counter/bound in the asking block (B3UnrollLoops.cpp:874-878), and the duplicate helper is renamed (AOTRuntimeValidationEmitter.cpp:41).
- The ~180 files changed since the last review (valueflow results/rules, B3VectorizeLoops, JSModuleLoader/CyclicModuleRecord, FTL/DFG touches) were hunted for new issues and none surfaced.
Extended reasoning...
The diff spans 480 files with about 11.9K insertions, touching the AOT compiler pipeline (analysis, codegen, runtime, stubs, valueflow), B3 unroll/vectorize phases, VM synchronous module queue handling, JSModuleLoader, DFG/FTL, WTF assertions and bmalloc. It touches no auth, injection or data-exposure surface, but it changes memory-management-adjacent code (GC visiting of module queue tasks, heap-allocated closure tables, B3 codegen). Since the previous review, 182 files changed and all three prior inline findings were verified fixed in the code. The size, complexity and critical compiler/VM paths rule out approval even with a dry-streak hunt; the PR conversation history is also incomplete this run.
main got #927 (d6e9f85) after the merge of 3ba7716. Two files conflict, and both conflicts are one repair that both sides made. A switch over a string that reads the characters of a substring in place took the width from the bit that the rope caches. Atomizing the base can put a 16-bit StringImpl in its place, so the width has to come from the base as it is now. - dfg/DFGSpeculativeJIT.cpp (emitSwitchStringOnString): the same line on both sides under two comments. Upstream's comment. - ftl/FTLLowerDFGToB3.cpp (the switch on a string): upstream b92d6a6 moved the read of a substring's base into substringRopeBaseImplAndOffset() and tests the base with isNot8BitStringImpl(). #927 tests the same flag in the code that upstream moved. Upstream's code. Both files are now the files of this branch before the merge: #927 changed nothing else in them. #927 adds JSTests/stress/switch-string-substring-of-base-widened-by-atomization.js for its repair. With the jsc of this branch before the merge (x64 lto-aot, bcd362b), which has upstream's code, the test passes in its 17 modes. With the jsc of main before #927 (fcc1ea0) it fails with "bad value: 0, expected 3" once the function is compiled. Five more files changed on both sides, and git merged them: JSTests/BUN-TEST-DIFFERENCES.md, interpreter/Interpreter.cpp, runtime/ArrayPrototypeInlines.h, runtime/VM.h and wtf/Assertions.h. No added line of #927 uses a name that upstream removed in this range. Its new tests name a runtime function by its name ($toLocaleString), not by a number, and the numbers of the engine's functions are the same with and without #927 (aot/builtins/generator/engine.ts on both trees). Not compiled before the push: the sources of #927 under aot/ against this branch. The lanes of CI do that.
…se; the main module (#930) Follow-up to #927, from the same branch. - Typed `JSON.parse` takes the learned path for a record inside another as it did before, and keeps what it learned where a member holds a record or `null`. - Flow analysis follows `Proxy`, the library's helpers and the members of host classes, so a small program compiles fewer library functions. - The host reads the main module's exports where its body ends, also behind a top-level `await`. The names of a CommonJS entry point are taken when the file has run. - A field that an allocation lists gets no accessor's slot. - An arm of a type test whose class no code can test comes last and serves only where the class is proven. - The range of a tally in a counted loop is computed in checked 64-bit arithmetic. - Slots are planned by the loops and branches of a site's own function, without an estimate of the whole program. - Passes that walked every callee of every call for every member of a union visit each once, and sorted sets search the larger list. `statistics.def` has four counts of work that the scaling tests read. - `Object.freeze()` of a module namespace throws. Rows of a typed `sql` query are made as typed objects. - A loop is asked whether it is expected to run. Sums in the fast versions of loops are added up in integers, and the counter of a loop stays zero-extended. - `DeferInitializers` asks the rule of effects whether a call or a construction may throw before it enters, and a static member whose written key spells `prototype` stays where it is. - A star or dynamic import of a library module brings what its getters load. The options of `Bun.spawn`, `Bun.listen`, `Bun.connect` and `fetch` are described by their paths. - B3's loop vectorizer and unroller, with their `testb3` cases. - The greedy register allocator: the pairs of a `Shuffle` name registers to each other, and a register that a frame saves is no wish for the half of a cut live range that does more than cross the border. - `testaot` writes its output in binary mode on Windows, and `run-in-shell` hands its leading `--` words to the shell. Outside `aot/` and `b3/`: - Four hooks in `runtime/` (`CyclicModuleRecord.cpp`, `JSMicrotask.cpp`, `JSModuleLoader.cpp`, `JSONObject.cpp`), each under `#if ENABLE(AOT)` and taken only for compiled modules. - `heap/ReservedRangeHeap.cpp`: a build without mimalloc hands out granules of the reserved range itself. - `heap/MarkedBlockCage.cpp`, `runtime/VM.cpp`: the dead stack that is cleared lies below the frame that asks, and goes down to the stack limit of the running thread. - `heap/MarkedBlockCage.*`, `heap/ReservedRangeHeap.*`: no cell lies where an address of the image could name it: the range starts at a distance from the base of the cage. - `bmalloc/bmalloc.cpp`, with mimalloc on Linux, where address space is kept aside: a request that finds no piece to let go of looks once more if a piece was let go of since its last look. - `assembler/` (`LinkBuffer.cpp`, `X86JumpShortening.h`): the recorded link sites and jumps arrive as a few ascending runs and are merged rather than sorted. - `wasm/` (`WasmBinding`, `WasmCodeInImage.cpp`, `WasmOMGIRGenerator.cpp`, `js/JSToWasm.cpp`): code for an image cages a memory's base through two slots of its pointer table. Only builds with a Gigacage have the slots and the instructions; other code is generated as before. - `yarr/` (`YarrInterpreter.cpp`, `YarrJIT.cpp`): under `verboseRegExpCompilation`, a line says which matcher a pattern runs on. - `.gitignore`: `rustc-ice-*.txt`.
main has #47129, the Bun side of oven-sh/WebKit#927 and #930. The one conflict is WEBKIT_VERSION. It is now the preview build of oven-sh/WebKit#923 at 35b64c4a: the upstream merge, the fork's main up to f495db1d24 (what main pins) and the commit that keeps the generic copy for a spread of a function.
Follow-up to #914, from the same branch. Almost all of it is under
Source/JavaScriptCore/aot, which only a build withENABLE_AOTcompiles. The last section lists every file outside that folder.Changes that reach builds without
ENABLE_AOTswitchover a string takes the width of a substring's characters from its base's storage as it is now.JSTests/stress/switch-string-substring-of-base-widened-by-atomization.jscovers it.require()of an ES module re-enters it.ModuleRegistryEntry::replaceRecord()swaps the record of an entry. The queue of a synchronous load stays where the collector finds it, andVM::synchronousModuleQueue()says which queue reactions go to.JSON.stringify: takes the width of a string's characters from its storage as it is now.JSObject:ordinaryGetOwnPropertySlot()andhasDirectProperty()ask an object's class only where its Structure says that absence can't be cached. The fast-path tests ofRegExp.prototype.exec,Symbol.speciesandSymbol.isConcatSpreadable,calculatedClassName()and the labels of both heap snapshots use them.CRASH()callsWTFAbort(), which first calls the reporter that the embedder sets withWTFSetAbortReporter().Dominatorsnumbers a backwards graph without building a list of successors at each step.B3 and Air
These phases run under the policy that the ahead-of-time compiler sets.
VectorizeLoopsturns counted loops over typed arrays into vector loops: copy, scale, mean of neighbors, reverse in place, clamp, least, greatest, and sums in integer lanes. Anything a lane can't hold goes to the loop as written. Without AVX, the x86-64 assembler emits the SSE forms.UnrollLoopsalso runs in functions without warm code. A counted loop polls for a requested termination once per stretch of turns, soworker.terminate()ends it.RegionCloner,VersionLoops,RotateLoops: an end that a copied block computes has its user in the pre-header before values that leave copied blocks are demoted.MovedLoadCheckfollows joined blocks.The ahead-of-time compiler
DefineOwnPropertywhere the object can't grow or the property is read-only.prototypeends the class's guards. An unused class keeps the look at its heritage unless the heritage is proven.[...arguments]appends what the arguments object was made of. A forwardedapply()tells its list from its receiver by position.require()of a module whoseimport()is still pending loads its root once more. Where a statement imports a file as text, animport()of it without a type gets the text.--aot-check=DecidedComparisonscompares again what the loop phases decided. With--aot-validate, a throw that leaves a call without a site is reported before it is unwound.musttail, a counted loop polls with one load on x64, and the native tests map an image's code from its file.SourcesCompiledForMinimumSize.txtnames sources that take no sample in a profiled build.Every file outside
aot/JSTests/:BUN-TEST-DIFFERENCES.mdJSTests/stress/:switch-string-substring-of-base-widened-by-atomization.jsSource/JavaScriptCore/assembler/:MacroAssemblerX86_64.cpp,MacroAssemblerX86_64.h,X86Assembler.hSource/JavaScriptCore/b3/:B3AbstractHeapRepository.cpp,B3AbstractHeapRepository.h,B3EliminateDeadCode.cpp,B3FoldComparisonsWithBounds.cpp,B3Generate.cpp,B3Limits.h,B3LoopInvariance.cpp,B3LoopRangeChecks.cpp,B3LoopRangeChecks.h,B3LoopUtilities.cpp,B3LoopUtilities.h,B3LowerToAir.cpp,B3MoveConstants.cpp,B3MovedLoadCheck.cpp,B3MovedLoadCheck.h,B3PatchpointValue.cpp,B3PatchpointValue.h,B3Policy.cpp,B3Policy.h,B3ReduceStrength.cpp,B3RegionCloner.cpp,B3RotateLoops.cpp,B3StackmapSpecial.cpp,B3UnrollLoops.cpp,B3UnrollLoops.h,B3VectorizeLoops.cpp,B3VectorizeLoops.h,B3VersionLoops.cpp,testb3_bun_hoisting.cpp,testb3_bun_loop_plans.cpp,testb3_bun_strided_range_checks.cpp,testb3_bun_unroll_loops.cpp,testb3_bun_vectorize_loops.cpp,testb3_bun_version_loops.cppSource/JavaScriptCore/b3/air/:AirFrameStates.cpp,AirFrameStates.h,AirOptimizePairedLoadStore.cpp,AirPolicy.cpp,AirPolicy.h,AirShrinkWrapFrame.cpp,testair_bun.h,testair_bun_shrink_wrap.hSource/JavaScriptCore/dfg/:DFGSpeculativeJIT.cppSource/JavaScriptCore/ftl/:FTLLowerDFGToB3.cppSource/JavaScriptCore/heap/:AddressSpaceBudget.h,BunV8HeapSnapshotBuilder.cpp,HeapSnapshotBuilder.cpp,ReservedRangeHeap.cpp,ReservedRangeHeap.hSource/JavaScriptCore/interpreter/:Interpreter.cppSource/JavaScriptCore/llint/:LowLevelInterpreterAOT.asmSource/JavaScriptCore/runtime/:ArrayPrototypeInlines.h,CyclicModuleRecord.cpp,ErrorInstance.cpp,JSFunction.cpp,JSModuleLoader.cpp,JSModuleLoader.h,JSONObject.cpp,JSObject.cpp,JSObject.h,JSObjectInlines.h,JSPromise.cpp,ModuleRegistryEntry.cpp,ModuleRegistryEntry.h,RegExpPrototypeInlines.h,Structure.h,VM.hSource/WTF/wtf/:Assertions.cpp,Assertions.h,BackwardsGraph.h,Dominators.hSource/bmalloc/bmalloc/:bmalloc.cppTools/Scripts/aot/:check-includes.py,check-unified-sources.py