Repository navigation
[JSC] AOT: proxy traps, member reads and calls from compiled code, position-independent decisions, a check of pointers across collections - #912
Conversation
…m, inline callees of up to 32 bytes Built-ins: - Under immutable intrinsics, what an existing built-in name resolves to cannot be changed. Beside writing, redefining or deleting an existing property, which was refused already, a built-in object can no longer be given an own property under a name that it inherits from a built-in prototype, and its prototype cannot be changed. New names may be added: the objects stay extensible. Objects and classes of the program shadow built-in names as before. - So the read of call, apply or bind on a function whose type is an intrinsic folds to the member of Function.prototype, the comparison behind it folds, and the generic call leaves the graph: Math.floor.call(null, x) is Math.floor(x). - The array and non-cell edges of Array.isArray end in a jump, so that B3 threads them for an alias as well. Calls: - The limit for inlining a callee outside loops is 32 bytes of bytecode instead of 18. A sweep over a large compiler written in TypeScript gave -1.5% instructions for +1.5% of code at 32; 24 gave -0.4% for +0.4%, 40 gave -1.9% for +4.1%, 60 gave -3.0% for +8.5%, and raising the limit inside loops alone gave nothing. - A block that is reachable only through a catch entry is rarely executed. - A parameter whose type excludes undefined is passed by every caller, so it is read from an argument list without the test of the count. - The VM and the global object are loaded where they are used, not at the entry of every function that may need them.
run-tests.py joined the options of all `//@ runDefault(...)` lines of a header into one list, so a test with several run lines ran once, with later options overriding earlier ones, which could switch off what the test is about. It also read only the first six lines of a header. Now each run line is a run of its own and the whole header is read. The runs of one test follow each other, since they may write the same files; different tests run beside each other (--jobs). aot-element-stores-by-array-shape.js failed in three runs with this, as it had before, unseen. Its expectation was wrong: a literal of four slots with a hole is born with a vector of three, so its last store grows it, once a literal. It now says so, and asks that literals of three slots make no call at all. check-stub-clobbers.py --print counted visits of a call instruction instead of call instructions. The check itself never used that count.
…push inline, stop batching stores that add nothing Soundness: - The generic call behind a lowered built-in was never a tail call. A method of a plain object that is named like a built-in and calls itself or another one in tail position overflowed the stack: 41 of 58 generated forms, all that are lowered. The fallback is a tail call again where the call was one. Nothing is lowered less. Code: - A constant cell of the program is read from a slot of the function's data: a load and a test where code may be bulky, a stub of three instructions on the usual path elsewhere. It was a hash lookup of 16 instructions at every use. The hash stays the owner and the root. In a large program with 383,045 uses in 64,703 functions, 300,377 distinct pairs of function and constant, this is 1.2% more code. - Array.prototype.push of one value is inline behind the check of the receiver that the site makes anyway, except in tail position. 39 instructions through the thunk before, about 13 to 25 now. 0.6% more code in the same program. - A run of stores to one object that once added nothing goes by single stores from then on. The run is meant for births; in that program 97.6% of its arrivals in the runtime stored the properties one by one, each with a lookup. Runs that add properties still make one structure. Arrivals: -87%. - String.prototype.indexOf and includes with a needle of one character scan up to 32 Latin-1 characters inline. - The read of a method on a value whose type is a primitive folds to the member of the built-in prototype. - The remainder of two numbers that are integers is computed inline. - Object.hasOwn probes the VM's cache of own properties, as the native function does: 148 instructions a call to 94. - Built-in functions are marked immutable without reifying their lazy name and length: 888 bytes of live heap at launch instead of 42,538, and 0.6 M instructions fewer. Diagnostics: - A heap snapshot has an edge for each scope slot without a name and each captured value. Before, whatever hung on them had no path from a root. In a snapshot for GC debugging a compiled function is labelled with its number in the image. - More named counts behind useAOTOperationCounters: fills of the megamorphic cache by kind, slots cleared by watchpoints, why an object cannot take a typed layout, how a typed read that reaches the runtime ends, how a copy of data properties ends, compilations of regular expressions.
…e of what reaches the runtime - An operation that could cache its outcome filled the megamorphic cache whether or not the pair was there. Filling moves the occupant of the primary entry to the secondary table first, so filling a pair that is the occupant put a second copy of it there and threw another pair out. The JIT tiers have the same code but fill only after a miss. Now the cache is asked first (MegamorphicCache::findStore beside findLoad). With 900 pairs in use, filling 300 present pairs again made the other stores miss 1.8 to 3.8 times as often; now 0.98 to 1.04 times. - Behind useAOTOperationCounters: whether a fill found its pair, real fills as new pairs or pairs seen before, with the pairs of dead structures forgotten at each collection, so that "seen before" means thrown out; distinct pairs by kind; whether a store that arrives with an abandoned slot has its pair in the cache; typed reads that reach the runtime by site, with the layout wanted and the one found; regular expressions that are compiled without code in the image, by who compiled them and by the start of their pattern.
…t was not monotone - The read of call, apply or bind was typed as exactly the member of Function.prototype whenever the base was a built-in function or anything that is no object. The helper it asked was made for the callee of a call, where a primitive throws; a read from a primitive does not. So with `g` a number or Math.floor, `g.call ? a : b` was folded to `a`. The rule now applies only if all that is left of the base's type, without null and undefined, is a function. - A built-in value was taken to be truthy. Built-in strings are such values too, and Function.prototype.name is the empty string: `Function.prototype.name ? a : b` was folded to `a`. The rule now asks for an object. Checking inferred types could not see this: the type was right, the branch was not. - The same read gave every type for a base that is only null or undefined and one function for a base that may also be a built-in function or a primitive, so the type of a larger base was smaller. Types are joined, so nothing was wrong at run time, but what a reader of a variable saw depended on whether another thread had inferred the writer yet: a fold was made or not by chance, in about 2% of the compilations of one test program. A base that is only null or undefined now gives no type: the read throws.
Copies of data properties into objects with a typed layout. The fast path of a
spread or a rest refused such a target, so a literal with a spread whose type
has a layout was filled by the generic function. The plan of a copy takes the
transitions that ordinary stores take, so it had the right structure and
offsets already. It now also records the field each value lands in. A value is
checked and represented as a store would. Every check comes before the first
write, and a rejected value leaves the copy to the generic function, which
throws as before. A clone born in another layout than its source's uses the
same plan before it goes property by property.
A spread of a boolean, a number, a symbol or a bigint copies nothing.
`{ a, ...(condition && object) }` spreads false when the condition fails, and
the fast path left that to the generic function. A string has indices and
stays as it was.
Direct stores are served from the megamorphic cache. The PutById stub left for
C++ on a direct store before it probed the cache, so the definitions in
`{ ...e, a: x, b: y }` and class fields arrived in C++ each time once their
site had seen too many structures: 23,700 of 24,000 in a test with 40
structures. An entry for a transition holds for a definition whatever the
prototypes have. An entry for a replacement holds if no property of the
structure is non-enumerable or non-configurable. A direct store that replaces
now fills the cache, and an entry whose transition grows the out-of-line
storage is applied at the start of the operation.
Validated mode checks the branches that types folded. A wrong fold with a
right type was invisible to it. The fold drops the arm as in production and,
validated only, keeps the condition, which is evaluated where the branch was
and reports a disagreement. --aotFunctionWithWrongBranchesForTesting plants a
wrong fold so that tests can show the check fires.
The shell reads remarks and type coverage without stat. On macOS
stat("/dev/fd/<n>") fails with EBADF in up to a quarter of calls while several
processes do it at once. aotRemarks() then returned null and tests skipped
their assertions. A failure now throws.
More named counts for copies, clones and conversions.
A Structure without a typed layout can record, for each of its first inline slots, a number that stands for the name of the plain data property there. The GetById stub already trusted that record on its polymorphic path, but a Structure got its numbers lazily, through C++, one Structure at a time. The numbers of the names a program gives its objects are now part of the image, and a new Structure records the number of the property it adds when it is made. A transition that adds a property copies the record. Every other transition starts from an empty one, which reads as "not known" and is a miss, never a wrong hit. The record covers 24 slots instead of 16. A pass over the program notes the shapes its constructors and literals give their objects. For a read `x.name` it takes the shapes that hold all the names read from or written to the same value. If they agree on the slot of the name, the read first compares the number recorded for that slot and loads on a match. A mismatch takes the GetById stub as before, so a wrong guess costs time only. Compact code calls a stub per slot. Other code has the comparison inline, and consecutive reads of one value share the address of its Structure, which is kept only when the read was lowered on the main path of its node. Validated builds compare each such read with the generic one. With operation counters on, hits and misses are counted by reason. useAOTGuessedPlaces and useAOTInlineGuessedPlacesEverywhere exist for measuring. Tests that asked whether data stubs are in use by looking for a call of GetById accept the new stubs too. Also: a literal whose type has a typed layout is born with a structure known at build time when some of its names are no fields of the layout. Such a literal was made by three calls that looked every property up by name. Names that are no fields go behind the reserved slots in the order of the literal. A structure with out-of-line storage is never put into the allocation cache of the site.
Fixes. A name that only code left out of the image gives to an object was in the image's list of property names with the number of an identifier that is not encoded. A string equal to it at run time, such as a key from JSON.parse, hit a release assertion. A name is now listed only if a function in the image has it among its identifiers. The numbers of the names do not move, and the numbers given at run time begin behind the last one given to any name, listed or not. The records of typed fields use the same filter. With a type table loaded, the Structure of a literal without a typed layout lost the numbers of its names: setting the layout number 0 cleared them. A typed object is born before it is validated. When the validation failed, the rejected value was still in a typed slot while the error was allocated, where the heap verifier could see it. The message is made first, the slots are cleared, then the error is thrown. A keyed store with a symbol as its key always fell through the front end into C++: 540 instructions against 80 for a string. Stores. A store `x.name = v` that replaces a property first compares the number recorded for a guessed slot, as reads do. A Structure that may be a prototype, or has a typed layout with typed fields, records no numbers, and the replacement watchpoint set of a slot with a number is born invalidated. Stores to an object born in the same function and definitions are not guessed. Validated builds assert all of that at each hit. Guesses. Every name the program reads or writes is listed, ordered by the number of sites. Computed keys and spreads in literals and derived classes are understood. The state of the pass hangs on the compilation, not on a static. Cheaper checks. The address a structure ID is added to is kept per slot, which takes one instruction off every check. Reads of several values share what is known about their Structures across nodes that cannot change one. The read by name at the place a site remembers is two instructions shorter. Guards over whole functions, off by default. A function with enough guessed places is compiled with a second, generic copy of its code, as loops are when they are split. A guessed access becomes a guard that leaves for the generic copy at the same bytecode offset when the name is not in its slot, and never comes back, so the access has no call and no effect on the fast path. useAOTGuardsOverWholeFunctions turns it on, useAOTGuardsOverWholeFunctionsInsteadOfLoopSplitting lets such a function keep its loops whole, and two more options set the least number of guards and the largest size. Constructors, generators, async functions, functions with a handler, functions that return their values in registers or whose allocations were elided are refused, and no guard stands where the creation of an environment can still be reached. A search of the recorded numbers by vector comparison, off by default, for measuring. Counts. With operation counters on when the image is built, every executed read and store by name is counted by its outcome and by how its site will serve it. Arrivals of keyed and named accesses in C++ are counted by receiver and key. Validated mode remarks which folded branches it verifies.
Fix. Since stubs check recorded names, a split loop never stayed in its fast copy. The guards of the fast copy compare the Structure of the base with the slot of the site's cache. Only a miss of GetById or PutById fills that slot, and in the generic copy the stub that checks a name hit without touching it. Every iteration left the fast copy at its first guessed access. A loop that walks pointers took 12 ns a node instead of 5.4. In the generic copy of a split loop no place is guessed now, so the plain stub fills the slot as it did before. Families, off by default (useAOTFamilies, with useAOTGuardsOverWholeFunctions). The objects born with all the names of a shape, by a literal or by a planned construction, carry the number of that family in their Structure. Transitions that add a property hand the number on. Those that delete, change attributes, make a dictionary, prevent extension, change the prototype, make the object a prototype, give it indexed storage or convert it to a typed layout drop the number and set a byte for the family. A pass over the fast copy decides what each guard has to check: the name, the family's number once per value, the byte behind an effect, or nothing. Validated builds check the cell, the number and the name in full behind every guard. Builds with assertions check at every change of Structure that a member only leaves behind a hook. The option is not to be turned on in typed code before a test sees what the pass makes of type tags, narrowed typed fields and typed literals. Guards over whole functions, still off by default. A guarded read uses the value remembered from an earlier guarded read. A function keeps a loop without calls whole only if a guard stands in it. The entry of such a function costs nothing more than before. New options allow functions with handlers, ask for a least density of guards, and compile the fast copy with inline fast paths. Guesses. Births in the same module count first. The names of Object.prototype are not listed, and `return` of the iterator protocol is not guessed. A value read from a variable takes the names accessed on every read of that variable. Inline checks of stores share the Structure with reads. The search of recorded numbers by vector comparison is removed again: it cost 17 instructions wherever it found nothing. An option that did nothing is replaced by useAOTStructureAddressesReloadedAfterCalls. Remarks have a key in a third column.
The names an image lists were found by a filter, a binary search and a map in the VM. The first sight of a name cost about 560 instructions, and a program sees some ten thousand before it is ready. The list is now an open-addressed table by the string's own hash, at most half full. A candidate is confirmed by comparing it with the program's identifier of that index. A listed name needs no entry in the VM's map, which keeps only the names numbered at run time. The first sight costs about 60 instructions. A module's code block that is linked from an image has no constants, and the offset of its environment's symbol table is never set. One use of that offset was guarded already. The other computed an index that is never used, which builds with assertions reject. When a conversion to a typed layout is refused, the Structure stops recording names. The object does not move, so what its family promises still holds. Validated builds expected the name in the slot and trapped. They now accept a Structure that records nothing where the guard's place has a family. Builds with assertions asked whether the byte of a family was set when a member left. The byte stays set, so only the first member to leave was checked. A hook now notes the family it is called for and the check takes that note, so every departure has to come straight behind its own hook.
Both need useAOTGuardsOverWholeFunctions, which is off by default, and both are as old as the option. Its generic copy is the only final graph with blocks that no graph of the whole-program analysis has. Behind a guard every live register is a phi of the two copies there. A plain call f() passes the resolved scope as `this`, and the parser replaced it by undefined while it parsed the block. In the generic copy the register was still a pending phi, so the scope stayed. The analysis had seen the graph without the second copy, recorded that `this` is undefined, and the callee had dropped its conversion. A strict callee returned a scope object to the program. The replacement now runs behind the simplification of phis, for all graphs alike, and sees through phis whose leaves all qualify. Plain calls behind joins and in loops pass undefined too now. A constant object that is only read by name is never allocated, and its reads are folded where the base is the read of the variable. A read behind a guard exists twice, and behind a later guard the two meet in a phi. The fold did not match and an ordinary read ran on the placeholder. A function that folds such a read gets no second copy. The check of a graph against the facts of the analysis ran in validated builds only and printed. It now runs on every graph with guards in every build. A function whose graph contradicts a fact is compiled again without guards, and that graph is checked too. A contradiction there stops the build. The generic copy does not narrow by its own tests, so its static types are wider in a few functions. failEveryNthAOTGuardForTesting makes every n-th check of a guard leave though it would pass, for the guards of split loops as well. An exit that is only valid after a real failure, where a call must throw, is left alone. useAOTPropertyNameIDs, for measuring: with it off a place without a family is no place, nothing is guessed outside guards and the image lists no names. Validated builds then ask the property table by name behind every check. No guess by the births of a module where a shape born only elsewhere holds the same names with the accessed one in another slot. Reads of one variable with nothing between them count as one value for the checks of guards. A family given by a birth has at least one name. Misses of guessed places are counted by site. Structure::createWithProperties seeds every slot and sets the largest offset before it adds a name, so that the table and the offset agree at every step. Builds with assertions could not run code with typed layouts before.
A read or store could compare the number recorded for a name in a guessed slot, through a stub, inline, or as a guard. By themselves the checks through stubs changed nothing: one check replaced another of the same length. With families only one guarded access in twenty still compared a name. On a large application the guards without them execute the same instructions within half a percent, the code grows by 1.0% instead of 2.0%, and a program reaches its first prompt with 0.7% fewer instructions. Gone: the list of names in the image and its table by hash, the recording of names when a Structure gets a property, the 48 stubs ReadNameInSlot and WriteNameInSlot with their 816 forms by register, the inline forms and their sharing of Structures, guessed places outside guards and with them the special case for split loops, the guard that checks a name, and seven options. The pass that guesses places stays, since the names decide in the compiler. It runs with useAOTFamilies, and a guessed place is a family and a slot. Families, their bytes and hooks, the pass over the checks of guards and the guards themselves are as they were. The read by name at the place a site remembers stays, and with it the numbers that are given to names when a cache is filled. Graph::remarkOnGuessedPlaces says what was guessed when remarks are collected, since the lowering no longer asks. Validated builds ask the property table by name behind every check of a guard.
…async functions A validated build checks every call, store and return of the final graph against the facts of the whole-program analysis. On a large application it printed 14 distinct contradictions with default options. In each that was understood the analysis is right and the final graph's static type is wider. The final compile changes the graph in front of its own inference in ways the analysis never does. As long as harmless lines are printed, a real one is not seen. 13 of the 14 are gone. readUnchangedRegistersFromFrame replaced a use of a phi behind a resumption by a fresh read of the frame's slot. Narrowing attaches to the node that is tested, so a branch tested one read and a call passed another, and what the test had proved was lost. The pass still decides at its old place, where a block's bytecode range tells its definitions. It rewrites behind the inference now, and the read takes the type of the value it replaces. A save that was moved to the definition of its register outlives the suspension it was made for, if inlining and folding remove that. The check skips such a store by a flag. The store stays, since the identity of a scope restored from the frame is read from the stores to its slot. A contradiction behind a value whose type is empty is in code that cannot be reached, for example behind a check of a type that always fails. It is ignored, said by a remark, and counted in the log of a verbose build, so that silence cannot be mistaken for a check that did not run.
…inlined body An inlined callee does `kept = e ?? fallback`, and the argument is a read of a `let` variable in the caller, so its type holds Empty. On the edge where it is neither undefined nor null the type was not narrowed, since with Empty in it the result is not all cells and narrowing was held not worth a node. The whole-program analysis types the parameter without Empty and does narrow. The store in the final graph was wider than the fact, and a validated build said so. Where a branch of an inlined body tests a value from outside that body, whether narrowing is worth it may also be decided on the type without Empty. The narrowed type is as before and keeps Empty, so nothing new is claimed. The condition is never true in a graph of the analysis, which does not inline, so no fact changes. This was the last contradiction that a validated build of a large application printed with default options.
…is without guards A function whose graph with guards contradicts a fact of the whole-program analysis is compiled again without guards. That second graph was checked too, and a contradiction there was a release assertion. But a graph can be wider than a fact for reasons that have nothing to do with guards, where the final compile narrows less than the analysis. Two such shapes are known, and one is what a transpiler makes of `??` for an older target. A valid program with that shape in a function with guards killed the compiler. With default options the same program compiles, and nothing looks. The second graph is now compiled as a build without guards compiles it. A validated build prints the contradiction as before. That the restart did not help is said by a remark and counted in the log of a verbose build.
…rowing in an inlined body Whether narrowing is worth it may be decided on the type without Empty where a branch of an inlined body tests a value from outside that body. The first test puts a narrowed value in front of the second, and that value belongs to the inlined body, so `e !== undefined && e !== null` narrowed once and then no more. The store behind it was wider than the fact of the whole-program analysis, and a validated build said so. It is the form a transpiler gives `??` and `?.` for an older target. The value is now followed to its origin behind the narrowed values in front of it. The test of a contradiction that stays without guards leaned on this shape. It moves to another: an argument that may be empty, merged with another value inside the inlined body and tested behind the merge.
…ting A function whose graph with guards contradicts the whole-program analysis is compiled again without guards. Both ways that can end were tested only through shapes where the final compile happens to narrow less than the analysis, and each cure of such a shape turned a test red. contradictAOTAnalysisForTesting takes the result recorded for a function to be unreachable where the graph is checked against it, so that the real report runs. With 1 only graphs with guards contradict, and compiling again cures it. With 2 every graph does, and it does not. It applies to all functions, since a test can read back an option that is a number but not one that is a name. The shape the test leaned on becomes an ordinary case with values.
With validateAOTInferredTypes compiled code checks every value against its inferred type. The check is emitted only where a bytecode node follows in the same block, since that node gives the place to report. Parameters stand in the first block, which holds no bytecode node, so they were never checked. A validated run showed that the values computed on the paths it took were in their types. It did not show that callers passed what the whole-program analysis assumes of a function that does not escape. For a parameter the search for a place goes on along single successors to the first bytecode node, and the check is emitted where the parameter is lowered, before anything else runs. `this` is checked only where the calling convention says the callee uses it, since a direct call does not load it otherwise. A parameter that is passed in a list and whose type has no undefined is read with a look at the count when validating, so that a caller that passes too few shows as undefined. A function that the analysis takes never to be called has parameters without a type, so any entry is reported. A validated build passes every parameter boxed, so the convention that passes numbers and booleans unboxed is still not checked by it.
With useAOTFamilies, which is off by default, two builds of one program differed. The number of families itself varied. What a constructor stores on `this` is noted under the constructor as the key, in a pass that runs on many threads. For a class that declares plain fields two graphs noted the same constructor with different content. The graph that defines the class noted it because a field initializer is stored on it, with no names given at once. The constructor's own graph noted it because plain field definitions are part of the constructor, with all names given at once. The last writer won. A class whose construction gives no names at once gets no family, and every later family had another number. The graph that defines the class now leaves a class that is not derived to the constructor's graph wherever that one notes it, so that each key has one writer. That is the state a build with one thread had: every such class gets its family. check-reproducible.py compiled with default options only, so it said nothing of what is off by default. It takes --option now.
VirtualRegister::isArgument() is true for the registers of the frame's header, so the check of parameters at entry also took the node that stands for the callee. Only a remark was new, since that node found its place as before. The condition asks for a register that is not in the header. The report of a violation computed the number of the argument in the compiler, which is negative for the callee and would have indexed a table out of bounds. It carries the register now and says "the callee" or "argument <n>". The test asked some premises under an option that reads false while the script runs, so they were never asked. It asks whether its own helper has remarks, as other tests do. A method and functions without parameters replace names that were compiled twice or shared with their bodies.
…gePath A guard counted its exits if useAOTTypeCoverageCounters was set, but the counters are set up only if aotTypeCoveragePath is given too. Without it the pointer was null, and the first exit that was taken crashed. The count now asks for both, as the setup does.
The lines of a map file that give the numbers of identifiers were written in the order of a table keyed by pointers, so two builds of one program gave equal images and different map files. They are sorted by number.
…f a block With validateAOTInferredTypes a value is checked against its inferred type only where a bytecode node follows in the same block, since that node gives the place to report. A value that is narrowed on an edge stands alone in the block of that edge, as in `x ?? 0` or `x || 0`, so what the inference claims there was never checked. A narrowed value that carries the index of the branch that has just run is its own place. That names the right function where the branch belongs to an inlined body, and it needs no single successor, so it also serves in front of a guard that ends the block. For other nodes the search for a place goes on along single successors, as it does for parameters. Remarks say which values are checked so and which cannot be. numberOfAOTValuesWithCorrectTypesForTesting lets the first values checked in a function with aotFunctionWithWrongTypesForTesting keep their types. Raising it one by one shows which checks fire at or after each place, since otherwise a parameter always fires first.
Two builds of one program could differ, with default options. On a large application one build in ten had one function of 166,952 with one check of a type more. Both are right. A value that a branch tests is narrowed on the edges of the branch only if that is held to be worth a node. The rule looked at the type the value had at that moment. From a string or an object to a string was not worth it, so the value went on as a string or an object. From anything that may also be a number it was worth it, and the value went on as a string. A smaller input gave a larger output. What a caller passes is joined into the parameter types of its callee and never taken back, and the rounds of the whole-program inference read summaries while other threads still join into them, so the result depended on timing. Narrowing is now also worth it if it would be with everything the test excludes present. Over all types and all tested edges that is the smallest rule that contains the old one and never gives a larger output for a smaller input. It narrows anew only from cells to a kind of cells. One case is left under the old rule and the new one alike: a run of the inference on one function that ends because it reached its limit of passes.
A function with enough reads and stores at guessed places is compiled with a second, generic copy of its code. The first copy checks once that an object belongs to the family of shapes that was guessed and then reads and stores at fixed offsets. A check that fails leaves for the generic copy at the same place and does not come back. useAOTGuardsOverWholeFunctions, useAOTGuardsOverWholeFunctionsWithHandlers and useAOTFamilies are now on, and a function needs ten such places per 1,000 bytes of bytecode. On a large application that is one function in a hundred, 0.4% more in the executable and 3.3% fewer instructions in a steady state. useAOTGuardsOverWholeFunctionsInsteadOfLoopSplitting stays off. The loop splitter guards every instruction of a loop that has a slow path, so what those instructions give has a type. The first copy of a function guards only its guessed places. A loop over numbers took three times the cycles with that option, and the application gained no time from it. Tests that took the old defaults for granted follow.
They are on by default, so they are how the compiler works. The three options that turned them on go, and the three thresholds become constants where a function's places are chosen: at least three guessed places, at least ten per 1,000 bytes of bytecode, at most 4,096 bytes. useAOTGuardsOverWholeFunctionsInsteadOfLoopSplitting goes with its code. It was never on by default. A function with a loop worth splitting keeps the split loop and gets no second copy. Two options for testing come. Small programs rarely pass the thresholds, so useAOTGuardsAtEveryGuessedPlaceForTesting lets one guessed place suffice, whatever the density. Only the first 2,048 families have a byte that says whether a member has left, and numberOfAOTFamiliesWithByteForTesting lowers that bound in the pass over the checks of guards, so that a test with two families sees a family without a byte. A new test holds what a program can observe of a function in its first copy against the same in its second: stacks, positions, names, arguments, handlers and the sampling profiler.
The image must not depend on the order in which whole-program type inference visits functions. With all threads the order varies by itself, but a rule that depends on it may show once in ten builds, and one thread shows only one order. seedOfAOTInferenceOrderForTesting shuffles the functions of each round with a seed. The list between rounds comes from a hash set and is sorted first, so one place covers the first round, the rounds in between and every full re-analysis. check-reproducible.py --orders N compiles each program with one thread in N shuffled orders and compares the images with the first.
Narrowing tested values and inferring types alternate, since a value that has been narrowed can make a later test worth narrowing. That stopped after four passes. An analysis of a function that ran early, when less was known of what it is passed, could need more passes than one that ran late, so it stopped with wider types. What it passed on was joined into summaries and never taken back. In a small program a callee had 52 or 56 bytes of code, depending on the order in which functions were visited. The limit goes. It ends: nothing between two passes removes a narrowed value, each pass that goes on makes a new one on the chain of a use that was there from the start, and a chain holds a test at most once. A narrowed value now has its type when it is made, so several tests of one value are all seen in one pass instead of one pass each. The type is forgotten with all others before types are inferred again. The test uses seedOfAOTInferenceOrderForTesting. Its seeds belong to the file as it is, since another number of functions gives other orders.
Since the passes of narrowing have no limit, a function in which each test is worth narrowing only once the one before has been narrowed takes as many passes as it has tests. Each pass went over the whole graph for every edge that was worth it, also where it had found no use before. A function of 800 such tests took 36 s in type inference and 18 s in code generation. It now takes 1.2 s and 0.8 s, and the time grows with the square of the number of tests. A pass remembers for each edge of a branch the type it last tried to narrow to, and for each check for the empty value that it was tried. It is the type and not a bit, since what a branch tests can change between passes: a call tests its argument only while its callee is known to be a function such as Array.isArray. That the graph is the same as without this rests on a property of the bytecode: every read of a variable that may be empty has a check of its own in front of it. In a graph without that property a value could be narrowed less, which is sound. 353 programs in two orders each and an application of 166,952 functions give the same bytes as before. The number of passes is asserted to be below twice the number of blocks plus the number of nodes.
Compiled code can read and store a field of an object with one load or store only while nothing can move, remove or redefine that field. Two bits of a Structure say so, and the object model enforces them. hasStableFields: the properties the object is born with keep their offsets and stay plain data properties. Deleting one, making it an accessor or read-only, freezing the object and turning it into a dictionary are refused. Adding properties, sealing, a new prototype and indexed storage pass. hasImmutableShape: the object keeps one Structure for life. Every transition is refused. A transition function cannot fail, so each refusal stands in the object-level caller, in front of the language's own tests, and throws a TypeError whatever the mode, also for Reflect. One assertion where a Structure is copied for a child covers every maker of a child, so a road that was missed crashes at the culprit instead of giving wrong code. No test stands on a path that succeeds without a transition. Since a direct put can now fail, putDirectWithReify accepts a pending exception, and five scopes check for one after a refusal. validateAndApplyPropertyDescriptor threw a second error over the pending one. Nothing sets the bits yet but two functions of the shell, for the tests. From C++ a refusal is weaker: putDirect leaves the exception pending for its caller. Object.freeze on an object with stable fields that has elements, or through a Proxy, throws but leaves the object not extensible.
…ction object that its caller made and handed to nobody is called directly, and nothing is decided by where text stands - A read of a name that nothing above the layout has: where flow has seen the read find more than undefined, the prototype is tested where the read stands, and the arm that finds nothing is the unlikely one. A PropGet whose receivers' layouts all lack the name gets a site cache and compares the slot at its site in line in fast code. Where flow has seen one getter called at the site, the new operation GetCachedGetter takes it out of the site's slot, a TypeTest holds it to that function, and the body is called directly. - A function object that the caller made itself and has handed to nobody on any way to the call has the names it was made with: its call is direct, without a test and without an arm by value, also where its function has tests at its head (CallDirect has `callsOwnFunctionObject`). Frames of such calls show the name as written, from an optional part of the function's side tables. - Nothing is decided by where text stands: whether a constructor function gets the second generic entry point goes by the values of its body as read (FunctionCapabilities::IsLongConstructor), the counter of a store that converts an array is numbered by the function's number, and of functions that begin at one place the one without text, then the outer one, comes first. - `Promise` that is constructed as a value: the first such construction leaves the function object and the closure in two words of the Instance, and the stub ConstructValue compares with the first and goes on with the second. - `new` of a class below Promise: the call of operationAOTCreatePromise has a prelude that takes the Structure which the rare data of new.target names and makes the promise on the spot, and an inlined `new Promise(..)` makes a plain promise and compares nothing. - The constructor of a base class that has classes below looks at the prototype first where its NewObject stores no field, and makes one cell of the class that new.target selects (two new stub families, AllocateInstance and AllocateInstanceOutOfLine). - EliminateRedundantReads drops a PrivateGet of a brand where the same test of the same object and token, or the PrivateDefine of the brand, comes first (dropRepeatedBrandTests()). - createMethodClosure(): a member without captures of a class that is proven to be evaluated once is the closure table's closure. - findFunctionsEnteredByUnknownCode() also counts a function that is derived from one that is called indirectly. - `===` and `==` on strings read a piece of a flat 8-bit string where it lies: two strings of up to 32 characters in the stub, a longer written text through the new leaf CharactersEqualImageString. - Reflect.ownKeys() and Object.getOwnPropertySymbols() of an object with fields under symbols: the lists with symbols lie in the table of key lists beside the names, and compiled code looks there. - Accesses through a proxy: compiled code reads the `get`, `has` and `set` traps off the handler and calls them itself (new stub family ThroughProxy; six new operations), and a read by name that is left to the run time goes straight to operationAOTGetById. - fileRead(): where the look itself has altered something once (a dictionary made flat, members made, an absent field marked as read) it looks a second time on the spot, by a look that runs no code of the program, and files that answer. - SeparateUnlikelyLoopPaths: the way back out of the copy tests a variable that holds literal strings on the likely path for `string`, not for the literals. - `JSON.parse(text) as T`: a key with an escape goes by a rare block to JSONParseExtraMembers, which decodes it, in place of a second read of the whole text. A new counter StringBuilderGrowths counts where a buffer takes the place of another. - A string builder remembers the capacity of the last buffer that was too large to keep, and the next text that outgrows a first buffer gets as much in one step. - new Worker() where the address space is limited: it reads how much is left in place of mapping as much, and the cell range is asked for by heaps of their own in each segment, one set for each thread that is starting. - The caches of the program and the open interning phase last as long as the CodeGenerationJob, not as long as run(). - The merge of the plans of frame allocation runs beside the edits, under the caches and phases that are open around both, and whoever installs the caches of the program or opens an interning phase checks that it is inside no loop and no task (ParallelLoops::isInsideLoop()). - A string builder that holds no text goes back into the empty pool in a stub (StringBuilderDiscard). - In the estimate of classes the host enters a function whose callers are not all known as often as a loop would only where code that runs may enter it (SeenCode::hasSiteThatMayEnter), else once. Two .ir files. - The heat graph: a read or a store under a name that may run code nobody knows calls the name `get` or `set`. One .ir file. - DeferClosuresInFields leaves no closure of a function that records its callee unmade: it is made where it is written. - A spread into an empty literal of the source's own layout that nobody keeps is filled field by field only where no operation stands behind its arms or the site stands in a hot loop; anywhere else the slots are copied at once. - PlanArrayCapacities: the road behind the test for Double storage is copied for storage for any value only where flow has proven the contents within undefined | number. In that copy the element is read and asked for a number behind every presence test that has lost its read. - GuardFacts: a store of what may be undefined or null counts against the declared type of a slot only where a way leads from it to the user without passing the allocation that the user names. Two .ir files. - Modules: a first import() of a synchronous ES module of the program is a promise and one job that queues itself again each turn, without a record, an entry or a promise of the loader; several import() whose graphs share nothing left to load are counted side by side, and where anybody asks for another module the loader is asked for all of them and takes the steps it would have taken. - Modules: a require() hands the counted import() over to the loader only where the required graph comes to a root or a found module of one of them; a graph that shares nothing left to load is evaluated beside them. - Flow: callFromNativeCode() says that the callee was found on its receiver. - Flow: a function that lets in unseen code and is stored under a name into an object that has escaped is written on that object alone, and a read that starts from the unknown object takes no such function from it. - Flow: the solver hands what its lookup of `get`, `set` and `value` finds on a descriptor (own, above, under a computed key, from a getter, through a copy or a proxy), and every member of a source that is defined as it stands, to one host node, and which closures a definition compares is read from that node. One .ir file. - Flow: beside a key nobody knows a written name hands out no member of Bun that lets in unseen code, and the walk of readEvaluators() looks no further up than an object whose prototype link is locked. - Flow: a name that a spread or a rest brings into objects of a layout is given a value there, so it is no accessor field of the layout, whatever getters or setters other objects of the layout define under it. - WTF: the table of enumName() ends at the last named enumerator (EnumTraits.h); a value behind it answers as the empty entries did. - Build time: use lists are brought up to date from the function's log of edits where the function has 64 values or more and the edit touched at most a quarter of them. What many receiver sets store under keys into the same many layouts is noted once, in a table that those layouts share. InlineCalls takes a body in at most 32 levels deep (new limit MaxInlineNesting), and a lookup of a name up a row of classes keeps its answer for every class that it passed. - Checking: under --aot-check=validate-references and in testaot the finished Air of every function is read: a pointer into what a cell owns is not held across a call that may collect unless the cell is. In a validating build the list of frames that is handed out is the one that is compared. The check takes a floating point or narrow load through a butterfly for no cell and a copy into a frame word that is no spill for a read. A new testing word, OverwriteDeadValuesAtCollections, writes the word 1 into each register and spilled word whose value is not read again in front of every call that may collect, and a stub that reaches a custom getter or setter by value checks, when it is generated, that it has not written the register of the key. The check of pointers runs only where the code is as a product gets it. - testaot: the printer of what a front end sends writes the word `callers` behind the second position, the parser reads it back, and `round-trip wire` is the round trip in the form that is sent. - Tests: .ir files for reads of members of the object that a receiver was put below (three), the function object that the caller made, a brand that is taken, the way back that tests for a string, a constructor function by the length of its body, use lists brought up to date, and written positions for callers. Native tests for pointers into what a cell owns (thirteen), names of enums, the next large text, and caches that last as long as the job. More .ir files: the limit of nesting, closures in fields of functions that record their callee, the element behind a presence test without a read, and the construct prototype of a class evaluated again. Three .ir files say the same under Bun's table of built-ins and the stand-in host's, and the README says who compiles the table. Also .ir files for a list that may hold anything and for an accessor of a layout that a copy also fills, and a native test for caches that last as long as what runs beside edits.
- codegen/element-access/reads-of-dense-arrays.ir: a read from a dense array and a read from an array that may have holes may not have the same size, the same frame and the same offset where the first frame is set up. On x86-64 a second run asks for different sizes, as before.
- Modules: a first import() of a synchronous ES module of the program asks the loader, as every other import() does: the promise with one job that queued itself again each turn, the import() that were counted side by side and their handing over at a require() go. AOTModules.{h,cpp}, AOTModuleEvaluation.cpp, AOTModuleMicrotasks.h and JSMicrotask.cpp are as on main.
- AOTSinkAllocationsExecution.cpp and AOTBuiltinCallEmitter.cpp name maxSafeInteger() and include the header that declares it.
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟡
Source/JavaScriptCore/aot/passes/AOTResolveCalls.cpp— A closure read through a member access before being called is treated as handed to nobody, so the call is emitted without a test and the frame is named from the side table. If Function.prototype carries a user accessor, that read runs the accessor with the closure as its receiver, so the closure has escaped before the untested call at AOTResolveCalls.cpp:2137. A stack trace or Error.stack then shows the compiled name while the object the accessor captured can have been renamed or inspected. Fix: isHandedToNobodyBefore must treat a PropGet or PropSet whose receiver is the closure as escaping unless the name resolves to an own or compiled-known field that runs no accessor.Why this was flagged
isHandedToNobodyBefore at Source/JavaScriptCore/aot/passes/AOTResolveCalls.cpp:2137 classifies PropGet and PropSet uses of the function object as inspections that hand it to nobody. A member read of the closure such as fn.displayName or fn.foo, where the name is absent from the function and an accessor sits on Function.prototype or Object.prototype, invokes that accessor with the closure as this, so the closure escapes before the call. The pass still resolves the call as CallDirect::callsOwnFunctionObject and codegen emits no identity test and records the frame as naming the function from the side table (AOTCodeDescription.cpp, callsOwnFunctionObject). The base resolved such calls with a test. The behavioural consequence is limited to what the escaped closure's holder can observe or change (name, properties shown in traces), which is why the finder let it go; the rate is every call site that reads a member off its own closure first, a common pattern for memoized or tagged function objects.
Verification: In the schema, PropGet's and PropSet's receiver is
object: Any/inspects(operations.def:65-66). So a member store or member read on the closure counts as "handed to nobody" (AOTResolveCalls.cpp:2137) and CallDirect is emitted with no AreFunctionNamesUnchanged test. On the base such a call stays by value and Error.stack shows 'custom'; after this change the frame shows the written name. -
🟡
Source/JavaScriptCore/aot/runtime/AOTPropertyCachesAnswers.cpp— Programs that read, test or store through a Proxy at a site lose the new proxy fast path at every collection and pay a miss, a classifyRead and a new slot each time. Slot::createForProxies at Source/JavaScriptCore/aot/runtime/AOTPropertyCachesAnswers.cpp:1000 keys the slot on a freshly made jsString that only the slot references. The record is WeakByKey (AOTRuntimeRecords.h:463 namesOnlyLiveCells), so the key dies at each collection and the slot is evicted. Fix: key the proxy slot on a cell that outlives collections, such as the interned name cell of the program's string table or the Structure, so the slot survives like other ById slots.Why this was flagged
The ThroughProxy fast path (AOTStubsPropertyReadHandlers.cpp:441-532) is reached only through a slot filed by classifyRead at AOTPropertyCachesAnswers.cpp:388 and :871. That slot's payload is built with identifierToSafePublicJSValue, a new JSString cell for the name, stored at AOTPropertyCachesAnswers.cpp:1000. The record's eviction rule keeps a slot only while its key cell is live (AOTRuntimeRecords.h:463), and no root, cache or field references that string. Every collection therefore drops every proxy slot of every site, and the next access at each such site goes back to the operation, re-classifies and re-allocates a string and a slot. For a server that proxies request or environment objects on a hot path this is a steady allocation and miss cost per collection per site that the other ById slots do not pay. Remedy: use a long-lived key cell.
Verification: Trigger: any garbage collection after a site has been filled for a read,
inor store through a Proxy. slotFor (Source/JavaScriptCore/aot/runtime/AOTPropertyCachesAnswers.cpp:1000) stores a fresh JSString cell asslot.holder. Nothing marks that string, so the proxy slot is dropped at every collection. The base branch has no proxy fast path, so this is better than base.
- SeparateUnlikelyLoopPaths: a module variable that goes around a loop is read ahead of it. Where a path that is seldom taken, a call or a store stands between the entry of the loop and the read in its body, the read ahead of the loop is marked mayPrecedeItsStore in every build, not only in a validating one. - Such a read counts as a value that may be unspecified (isUnspecifiedAtDefinition(), now shared by AOTFrameAllocationPointers.h), so CreateStringBuilders, PlaceTypeTests, Select and the code generator take no type from it. - Tests: two .ir files.
… alone in the pool is the first - A new column of the schema, isUniqueInFunction, stands on InitialYield. RegionCloner::checkCanDuplicate() answers CloneCheck::UniqueInFunction for a block that holds such an operation, so ThreadJumps copies no small join in which a generator begins. - StringBuilderStorage::returnToPool(): compiled code lays a builder into the empty pool by one store, which writes no depth. The builder that has none below it counts as the first. - Tests: two .ir files and two native tests.
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Still open from earlier reviews (1):
- Unresolved: 1 minor or pre-existing.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟣
Source/JavaScriptCore/aot/passes/AOTEliminateRedundantReads.cpp— pre-existing: a carried variable read that the pass itself marks as possibly empty can still be type-tested ahead of the loop, which dereferences an empty JSValue. findTestsOfVariables (AOTEliminateRedundantReads.cpp:2741-2749) accepts a TypeTest of a carried parameter without asking whether it may be unspecified, while findTestsOfEveryTurn skips such parameters at 2679. testOnEdges at 2921 then emits that TypeTest on the entering edge, on the read that insertRead marked mayPrecedeItsStore at 1838-1839. Fix: place no test ahead of the loop on a carried value that mayBeUnspecified (skip it in findTestsOfVariables as findTestsOfEveryTurn does, and in findLeadingTests/moveLeadingTestsAheadOf at 1940-2027), which covers the 2 sites.Why this was flagged
The trigger is a loop separated by LoopPathSeparator whose variable read dominates the loop's latches only once the rare path has been moved into the copy, with that read tested in every turn by a TypeTest that narrows its declared type. insertRead (AOTEliminateRedundantReads.cpp:1836-1842) puts the read in front of the loop and, since the read's clone does not dominate the way back (1631-1639), sets mayPrecedeItsStore. findTestsOfVariables at 2712-2757 then takes the loop's TypeTest of that parameter (2741-2749) and testOnEdges at 2921 and emitTests at 2785 append a TypeTest of the hoisted read on the entering edge. The hoisted read's type has no Absent primitive, so TypeTestEmitter::testBoxed (AOTTypeTestEmitter.cpp:343-367) emits no emptiness check and unboxes the cell: for the empty value (0) it loads the cell type from address 0 and the process faults. The base branch has the same findTestsOfVariables and no marking, so it fails the same way; the marking added by this PR is consulted by findTestsOfEveryTurn (2679-2680) but not here.
Verification: pre-existing (the base takes the same route). Trigger: a loop separated with plan.letsVariablesBeCarried whose rare path loops back without reading a StoredBeforeEveryRead variable. findTestsOfVariables (AOTEliminateRedundantReads.cpp:2741-2749) records the TypeTest with no check of whether the parameter may be unspecified; testBoxed (AOTTypeTestEmitter.cpp:367-372) loads from a null cell pointer.
|
Preview build of 0ecc6c5: |
…reads under a key with a receiver are answered in a stub, and long rows of classes take fewer steps to build
- Modules: the module table of an image says in two bits of a byte it had which module is the first entry point and which modules are loaded with it (firstEntryPoint, loadedWithFirstEntryPoint; markModulesLoadedWithFirstEntryPoint() at the build). wasLoadedWithGraph() reads them, so an import() of a module that has nothing to link or to run takes as many jobs as under `bun run`, with or without an evaluation on the stack.
- Modules: the number of jobs of a load that somebody watches is exact where a module imports a module of its own level or of a level above that still has imports to load (countStepsOfWholeGraph(), PlanOfLoad::asksAcrossLevels).
- Modules: nobody can tell how a graph is loaded only for the module that the host starts with (m_firstModuleRequestedByHost). A further entry point that import() loads beside other jobs is evaluated by its levels.
- Modules: on top of these three a first import() of a synchronous ES module of the program is again a promise and one job that queues itself each turn, with the exact number of jobs. Several import() whose graphs share nothing left to load are counted side by side, handCountedImportsToLoader() hands them over where somebody asks for another module, and every caller of it looks for an exception behind it.
- Modules: the loader takes no step in a later graph for the names of a CommonJS file that it evaluated itself (noteLoadOfFile()), and a graph that a running file requires comes to that file also where the loader already has it.
- Modules: the first who asks for the entry point while its graph is loading gets a promise of its own in the registry entry, settled one step ahead of the promise of the program (takeLoadPromiseBelowMainModule(); JSModuleLoader.cpp and JSMicrotask.cpp under ENABLE(AOT)).
- Modules: `export { c } from` a module of the program that has two or more `export *` over modules without a table is an indirect entry that is looked up at run time (findsNamesAtRunTime() in the program verifier, recordForResolution in ModuleRecord::resolveOwnExport(), and flow reads what stands behind the stars).
- Modules: a deferred namespace object of a module that exports `then` lists the name among all own keys and leaves it out where only properties count. A read of the deferred namespace object of a module that ran in a cycle whose root then threw behind an await throws what the root threw, each time.
- Modules: a realm that the program creates holds nothing compiled, so there the host runs the modules of its library from their text (leavesModuleToHost(), refusesLibraryText(realm)): `new ShadowRealm().importValue("node:path", "sep")` answers as under `bun run`.
- Proxies: a proxy without a `get` trap reads a data property of its target in the stub (ThroughProxy.Get goes on to TryGetSuperById), and `key in proxy` under a variable key calls the `has` trap from compiled code (InByValCached).
- Proxies: the string that a trap is handed for a name of the program is made once and kept (PropertyCaches::keyForTraps()), so what is filed for a proxy outlives a collection.
- Proxies: StubOptions::callsTrapsOfProxies says whether the four places that leave for ThroughProxy are emitted. It is set where unseen code may run, where flow has a use of Proxy or Proxy.revocable, and where machine code is loaded (loadsOfMachineCode()). Without it a proxy that arrives is left to the run time, and a program without proxies holds 3,150 bytes of stubs fewer.
- `Reflect.get(object, key, receiver)` and `super[key]`: the new stub GetSuperByVal answers a data property from the places and the hashed table of reads by key and calls a getter with the receiver. A proxy, an index and an empty slot go to the operation, which files once (getUnderKeyForReceiver()).
- A custom accessor or value that stays in the table of its class (Symbol.prototype.description, RegExp.input) is filed for a primitive receiver too, and the walk of the chain names it.
- `object[index] = value` that adds an element to a compiled object defines it directly in operationAOTPutByVal where nothing above the object may intercept an index.
- The definitions of the accessors of a literal fill their slots in one loop for the plan found and the plan just made (AOTObjectMethodTable.cpp).
- The two operations that cut a short piece out of a string leave cells for ropes when the free list is used up (leaveCellsForRopes()), so the stubs answer again.
- A kept spread into an empty literal outside hot code copies the slots at once in front of the operation where the source is expected to have the literal's layout and no other (expectsOneLayout()).
- FinishBirths emits no TryFinishBirth where some field of birth has been stored on no path from the allocation and nobody else has seen the object (storedOnSomePath, mayHoldMoreThanIsListed).
- A check for a type that holds any object makes no second version of a function: no tests at the entrance and no copy (changesCodeWhereProven()).
- RemoveRedundantBarriers finds the owner of a store through the names that a type test narrows (identityOf()). Where the arms of one store meet again, one new operation RememberOwner at the head of that block runs the barrier for all of them.
- Whether a name is read off a closure without code is asked name by name of the table (isLockedLocation(), hasLockedPrototypeLink()) and goes by nothing that flow marks on Function.prototype or Object.prototype in the whole program.
- ResolveCalls: a function object that its caller made counts as handed to nobody only where every use between its creation and the call merely looks at it by its effects (onlyLooksAt()), a store is no look, and a use behind the call that leads round to it counts (leadsOnward(), liesOnWayRoundWithoutCreation()).
- A value that may be unspecified is looked at only where the program looks at it: HoistLoopInvariantReads moves no operation that looks through one, and the tests that SeparateUnlikelyLoopPaths, ResolveAccesses, PlaceTypeTests and CreateStringBuilders place ahead of a loop ask mayBeVariableReadEarly().
- An element of a list literal that does not fit the proven storage by its own type gets the proven contents as its type, in functions with and without checks. The creator and flow's application ask one rule, fitsStorageOfLiteral().
- AddGenericVersion: what is made from a checked value counts as tainted too where it stays listed in an allocation untested, so the generic version takes no type of the field from it.
- SimplifyCasts: where a cast that goes to an edge gets a type outside the type of the cast at the head, the cast at the head stays as an AssumeType behind checks (Proven::byRulesBehindChecks).
- Effect summaries: the generic versions are summarized first, and what a version hands on to its generic version is read from that body where it says less than flow's table. The seed is lent to the heat estimate and taken back (LendableSummaries, lendSeed(), takeSeedBack()), so one compiler gives one output.
- Flow: every name that reads as a number (an index, NaN, Infinity, -1, 1.5, 1e21) is kept in the one place for elements. ValueFlowName::property(), getter() and setter() take the program and answer that place, and namesElementByText() is the one predicate.
- Flow: the namespace object of a CommonJS file, and a name that is imported from one, also hold what the exported object holds under its own names without a statement that wrote it (readOwnPropertiesNobodyWrote()).
- Flow: a read or a store lists, as Accessor records of its site, the closures that the program lays under keys nobody knows on the objects its receiver may be (AccessorsUnderUnknownKeys), so the heat graph has an edge from the readers to such a getter.
- Flow, one answer in every order of its rules: a node in the program's code lists an escaped object that the library constructs only where it comes there past no node that is retired in the end. A copy that may run a getter nobody knows hands over only the sources that hold one (tellObjectsApart()). holdersOfReplaceableMembers() leaves out only the prototype objects that no listing names. A getter of the table that does more to its receiver than look at it is found by each receiver that has not escaped on its own chain.
- Flow: a read under a private name of the library through an object nobody knows finds what is written under that name on the objects that have escaped. Such a name has a key cell for the run time, and NodesCodegen.cpp defines a class member under it under the name, not under its text.
- The key of a created symbol holds the number of its call among the calls of its file (Call has `callNumber`, PropertyKey has `callNumber` in place of `position`). The front end computes it and keyOfSymbolsCreatedBy() reads it off the Call.
- Stack frames: the sites that run the steps of getOwnPropertyDescriptor, hasOwn, hasOwnProperty, propertyIsEnumerable, Object.prototype.toString and Object.fromEntries name their built-in function (`calledBuiltin` on PropHasOwn and ElemDefine). A built-in that the engine writes in JavaScript is listed as such, and one that only built-in code can name is named by no site. A function with a tail call that only built-ins and `new` construct makes a call and a return (FlowIndirectCall::isAlwaysConstruction).
- Stack frames: a function whose closures have escaped, that no statement is seen to name and that is made more than once gets RecordsCalleeOnceRenamed, and from the first definition or removal of `name` on the calls by value record their callee. Every native frame under a function object of compiled code is private (StackVisitor.cpp). While import() runs a library module no frame of the importer is listed.
- Interpreter::getStackTrace() takes an optional StackFrameFilter, so the embedder's filter and the search for the caller run inside the one walk, which ends at the last frame shown.
- A string builder that is emptied with a buffer too large to keep makes no buffer on the spot: it remembers the capacity (m_capacityOfNextBuffer) and makes that buffer at the next write.
- arm64: generateAllocateInstanceOutOfLine() keeps its flag in T13, which is no argument register on either machine, and a static_assert says so. B3MaterializePinnedConstants reads a pinned constant that lives in a register of the other bank through BitwiseCast.
- B3: an access whose trap is attributed to it takes [base + index] only beside a pinned base (B3LowerToAir.cpp). An entry of the log of moved loads follows the head of a block that is split and goes with a block that is freed.
- Build time, long rows of classes: one bit a layout says that it names every field of the class above (indexNames). builtinBaseClassOf(), hasFieldsFilledAtBirth() and findField() keep answers while the caches of the program are open, from fewestClassesAbove steps on. TellingFields walks from one layout that has such a field to the next. KeysOfFieldsHeld and two sets stand for searches through lists. A link that is new in a chain of prototypes wakes its readers last (listAsDueLast(), isChainOfPrototypes()). A walk in front of flow ends as unknown at its first condition, and tellWhatIsTyped() remembers its answer by block.
- Build time, long functions: above 8,192 stack slots a function in which very many pairs of slots are live together gets its places from live ranges (AirAllocateStackByGraphColoring.cpp).
- Checking, in builds that verify the program: the records are verified at the head of the read stage (ProgramVerifier::runRecords(), PassRunner::stopAfterErrors()). A new diagnostic, OperationWithoutValue (reportOperationsWithoutValue()): every operand of a reached operation has a value and its result has none. What an inner pass answers for is told to the pass around it (addForOperationThatWent()).
- Checking: the check of pointers into what a cell owns sees a pointer whose own load took over a trap (B3 policy keepsOriginsOfAccessesThatTakeTraps). The check of native calls counts an entry into compiled code as code that ran (didEnterCompiledCode) and follows an operand that another operand holds under an index.
- Nine sources include or declare what they themselves use.
- Tests: new .ir files, among them the schedules of flow for three of its rules, six on private names of the library, three on barriers and two on stand-ins in copies. Native tests for what is filed for a proxy, a proxy handed to a program that makes none, a builder that leaves the next buffer to the next write, a pointer whose load took a trap, classes constructed by value in rotation (AOTThisAllocationProgramTests.cpp) and entry parameters counted ahead of the passes. Two tests in testb3.
…tack trace walks each run of compiled code once, and flow follows a loader through bind, call and apply
- Guesses and facts: new aot/ir/AOTExpected.h. Expected<T> holds what heat, an annotation or an open set says. It turns into neither its value nor a bool by itself, what is computed from one is one, and predicted() marks each place that acts on it. ProvenValue<T> holds what is true in every run of the compiled program, and only struct Proven makes one.
- Guesses and facts, heat: Block::frequency, the questions of BlockFrequencies and of class Heat, isHotLoop(), isInColderPartOfProgram() and FunctionPassContext::heatOf() answer Expected<..>. A pass that compares a frequency in an `if` writes `.predicted()`, and two predictions are compared for caches by isSamePredictionAs().
- `--aot-heat=shuffled` with `--aot-layout-seed=<n>` draws the class of every block, edge and function from a hash (HeatOverride::Shuffled, shuffleRecordedFrequencies()): a program means the same under any heat.
- Guesses and facts, what a collection holds: ClassPart has three questions. provenContentsAt() answers a ProvenValue only where flow has followed all that is stored (Proven::byFlowOfContents), expectedContentsAt() answers an ExpectedType, and writtenContentsAt() is for the algebra of types, printers and tables. arrayStorageDeclaredBy() answers Expected<ArrayStorage>.
- Guesses and facts, callees: CalleeSet is a struct written by hand with private fields (new aot/ir/AOTCalleeSet.h, `handwrittenStruct` in flow-records.def): all() where the set is complete, seen(), followed() and written(), made by CalleeSet::complete() and CalleeSet::open(). CalleeList (AOTEffectsOfProtocols.h) and CalleeCandidates (AOTResolveCallsCallees.h) are classes of the same kind, the call graph has allCalleesOf(), boundFunctionsSeenAt() answers an Expected span, and summarizeCall() and memoryAccessedByCallees() take a ProvenValue.
- Guesses and facts, layouts: LayoutSet likewise (new aot/ir/AOTLayoutSet.h): all(), completeMembers(), seen() and written(), made by LayoutSet::complete() and LayoutSet::open(). Error.isError(), ArrayBuffer.isView() and `instanceof` with a built-in class ask the object itself where its family has members without a layout.
- Classes: `new C` of a class expression that is evaluated many times (a class factory, a mixin) is answered by AllocateInstanceOutOfLine for every evaluation. ClassTable::rememberInstanceOfOtherEvaluation() fills a record for the same class with another prototype object, there are 64 records indexed from bit 5 of the prototype object, and a record holds the offset of its allocator (InstanceOfClassBelow::offsetOfAllocator). 24 classes of one factory constructed in rotation take 145 instructions an object.
- Classes: what a base class allocates for a class whose row of predicted classes ends at a class that extends what nobody predicted is an instance of that class (ValueFlowUniverse::objectAllocatedUnder()), unless several classes name that class above them (m_classesNamedAboveSeveralClasses). 1,000 classes that each extend what a function of their own makes of one base class build in 10.7 G instructions at a peak of 256 MB.
- Classes: JSObject::putDirect(), putDirectAccessor() and putDirectCustomAccessor() on a class object of compiled code go through JSObject::putDirectToCompiledClosure(). A static field of that name leaves its module variable first (StaticFields::willPutDirect()), any other name finds the static fields laid out as properties, and didPutDirectOnClosure() hears of added and of replaced properties. So compiled reads see what Error.captureStackTrace(A), spyOn(A, name) and mockRestore() put on a class, and a property that native code adds stands behind the static fields in the order of keys. ClassTable::InternalPutScope marks the puts of the object model itself.
- A function object that becomes a prototype, by a link that is written or under `prototype` of a function, does not count as only called (findPrototypes(), mayBecomePrototype()): it is a full or tested closure. In validating builds emitSplit() puts ValidateType into the arm that is entered because every test in front of it has failed, and a test that the word of a closure decides alone is held against the cell (hasClosureWordThatDecides(), TypeTestsDiffer).
- Proxies: `proxy[index] = value` takes the kept string of an index below NumericStrings::cacheSize in PutByVal and goes on to ThroughProxy.Set, as GetByVal does for a read (loadTextOfIndexForTrap()).
- Proxies: `name in proxy` and `key in proxy` without a `has` trap go on from ThroughProxy.Has to InById with the target, once the frame is gone (PreservingCall::emitBeforeReturn). The ways through a trap test for an exception once.
- Proxies: ThroughProxy records the registers of the slot's header and payload as written (recordClobbers()) and neither saves nor restores them: four instructions fewer an access through a proxy.
- List literals: a NewArray takes its storage from a record. Flow stamps its proven storage on the operation and says that the contents are proven (`elements...: Declared` and the engine flag contentsAreProven in operations.def), and requiredTypeOfOperand() answers for the elements, so the verifier, insertCastsForRequiredTypes(), assumeTypesOfPositionsAtStores() and SplitFreshResults hold them by the general rule (RequiredTypeHolder::ContentsOfLiteral). The creator stops the build with OpcodeWithoutCode where an element does not fit the Int32 or Double storage that the literal names, and CheckPlacement has checkElements().
- One predicate a question: fitsStorageOfLiteral() for lists of numbers, slotHoldsUndefinedAndNull() for the plan of the slots (needsAbsentState()) and for its check (slotAdmits()), and canStoreWithoutConversion(ArrayStorage, double) beside the one on types.
- SinkAllocations follows undefined and null in a field whose slot has room for them (SinkingPolicy::followsUndefinedAndNullInFields), so the arms of a spread in a hot loop define into parts. One rule says what a field of a followed object takes and holds: FieldContents and contentsOf() for whoever reads, admissionOf() for whoever stores.
- A parser by type gives up at a member whose field is an accessor, as at every field that takes no value (canFillField() in AOTJSONParser.cpp).
- ReuseEnvironments puts no ReleaseEnvironment behind a last use that never completes (findReleasePoints(), hasNeverResult()), and a layout whose only release would stand there gets no pool.
- What ToPropertyDescriptor reads from a literal is read by one function, readDescriptorLiteral() (new aot/analysis/AOTDescriptorLiteral.{h,cpp}), which the selection rule in AOTPropertyDefinitionRules.cpp and definitionByDescriptorMayMove() of ModuleVariables both ask. A definition on a function object in a module's initializer whose flag is no constant Boolean stays where it is written.
- Async generators: what is proven of the values that are sent in stands behind the switch on the mode before mergeAwaitsIntoYields() merges an await into the yield, since what the await rejects with arrives at the yield as a value to be thrown (findProofsOfSentValue(), moveProofsOfSentValuesBehindModes()). Where a proof cannot leave its place the await stays apart, and the proofs move while every use is where it was found.
- Modules: the first CommonJS file that stands in front of a module on the way of a load is a request of the loader, as the first file behind it is (LevelOfLoad::firstFileInFrontOfNext, layWayOfLoad(), appendRequestsForLoader()). The loader waits for a file while it runs, so a module that imports f.cjs and m.mjs runs behind the end of f.cjs also where f.cjs requires m.mjs.
- Modules: a CommonJS file that requires an ES module which imports it back, and then throws where nobody gets the error, is answered at every later require() with the namespace object of that import, as under `bun run`. The front end marks such files (ModuleFlags::MayBeImportedWhileItRuns, one bit of ModuleData), dropErrorOfFile() notes the file in the four places that drop the error, noteLoadOfFile() takes the names of a file when the loader comes to it, and flow's requiredValueOf() adds the namespace objects of the file.
- Modules: handCountedImportsToLoader() hands every counted import to the loader under DeferTerminationForAWhile, and a termination that is asked for meanwhile is thrown at the check that each caller has behind the call. runJobsThatAreDue() goes on behind a job that throws, as MicrotaskQueue::drain() does, and decideHowCountedImportGoesOn() forgets an import that leaves its job still counted (forgetCountedImport()).
- Modules, the order that flow draws: a require() of an ES module runs the jobs of the loader before it returns, so computeModuleOrder() has one more node for any module that an import() loads. It leads to every target of an import(), and every function that holds a synchronous load of an ES module leads to it, as does the host where modules are loaded by name. A program without an import() or without such a require() has the graph it had.
- Modules, the order that flow draws: a new mark of the table of built-ins, RunsWaitingJobs, says that an entry or what it makes runs the waiting jobs before a call returns. Where the program reads, calls, constructs or hands on a marked entry, the host leads to that node too (hostRunsWaitingJobs).
- Flow: where a callee holds the unknown object and an operand lists an object that lets in unseen code, runCall() also applies the built-in functions whose rows say that they call their receiver or an argument, or answer a bound function (functionsThatCallOrBindOperand of the heap tables): those that the callee's node lists, or the escaped members under the name that the call spells. applyCallback() and the two readers of the target of a bound function do the same (listsObjectThatLetsInUnseenCode(), builtinFunctionsListedBesideUnknownObject()). So `loader.bind(x)`, `loader.call(x)` and `Reflect.apply(loader, ..)` are followed whatever else the callee may be.
- Flow: runCallGroup() hands the operands out for the stand-in callee of a described call and goes on with the rest of the key, so a bound function that shares a group with the stand-in enters its target (calleeOfDescribedCall()).
- Flow: what is claimed of a field of a layout comes from the writers that a ledger lists (new aot/valueflow/AOTLedgerFields.{h,cpp} and AOTClaimsOfFields.h): claimWhatNeverHappens(), claimStoreCount() and claimContentsAreWhatWasStored() are functions of Writers.
- Flow: ValueFlowCellName names a place that no program can name. ValueFlowRuleContext::read() takes a cell alone, and a read under a name that a program can see is spelled readWhatWasWritten(): it gives what statements and rows wrote, and lookup() adds creation, the table, native code and the loader.
- Flow: new headers aot/valueflow/AOTActors.h, AOTPlaces.h and AOTLedger.h hold the types for who writes, reads and reaches a place (Actor, Place, Write, Read, Reach, LedgerPart, Ledger).
- The table of built-ins: each ShadowRealm has `Symbol.toStringTag` as a name of its own (namesDefinedOnNewInstances in global.builtins.ts).
- Stack frames: Interpreter::appendStackTrace() hands each run of compiled code once to a lean walk (RunWalk, appendShownFramesOfRun(), RunListing) in place of a visit a frame, and a kept ReturnAddressTrace shares its lister of shown frames. getStackTrace() with compiled code, or one host function that it called, on top uses no StackVisitor (tryGetStackTrace()). Suspended async functions are listed straight into the results, and the inlined frames of the function that was asked for last stay decoded.
- Stack frames, in instructions: a frame that is walked takes 200 where it is shown and 305 where the filter refuses it, Error.captureStackTrace(this, Class) ten calls deep 7,922, `new Error` behind ten suspended functions 2,884. In validating builds getStackTrace() holds the quick walk against a visit of each frame (validateFrames(), StackTraceStart::visitsEachCompiledFrame).
- Build time: sortIntegers() leaves a list in order alone and merges up to 8 lists in order. findStranger() looks at the first of the members that may be any object. prototypesOfEachHeir() asks each of many heirs once through its memo, and chainOf() ends at the first step whose chain is known. mayBeStoppedAbove() has one set of the objects that stop stores. chooseDispatchedCallees() puts callees in order behind the test of MaxDispatchCases. summarizeCallOperand() ends its walk over the callees at a summary that allows everything.
- Build time, at 1,000: one mixin over that many bases builds in 23.7 G instructions, functions stored one after another under one name and called there in 24.7 G, stacked mixins in 22.5 G.
- Checking, in builds that verify the program, three more diagnostics. SlotOfOtherForm: no operation takes a slot that holds the functions of an accessor for one that holds a value, or the other way round (verifyFormsOfListedFields()), and constant data fills no slot of an accessor. CopyRunsBehindLess: RegionCloner copies code only to where each stand-in says as much as the value or the guard it stands for (saysAsMuchAs(), provesAsMuchAs()). ProofInFrontOfMode: a type that is taken for proven, without a test, of what AsyncGeneratorYield or StepAsyncGenerator hands back stands behind the mode that comes with it (verifyProofsOfValueBesideMode()).
- Checking: reportOperationsWithoutValue() judges each operand as its rule was shown it (ValueFlowRuleContext::valueShownToRules()).
- Checking: the check of pointers into what a cell owns asks at each place whether a pointer may give cells. A value gives cells up to its last such read, carried backward over blocks, sums and choices, and an owner that the scan can do without is needed up to there. `[1].findLast(Boolean)` builds under `--aot-check=validate-references`.
- Checking, validating builds: the stub through which native code enters compiled code sets VM::didEnterVM (emitEnterAdapter()), and the check of native calls asks the VM alone. So the check of operations (OperationValidationScope) sees an entry by a job or by a step of an async generator.
- Checking, builds with assertions: the run-time table calls every operation that is declared not to collect through CallWithoutCollection<operation>::call, which holds AssertNoGC (NoCollectionGuard, functionInTable in AOTInstance.cpp), and AOT_OPERATION_FRAME_RECORD() passes over the frame of that function. Leaves that preserve most registers and the three operations that take the pending exception are called directly. operationAOTValidateLookup opens a LeafOperationScope.
- Checking, stubs: AOTStubRegisters.h holds the numbers of the machine registers behind the names on both ISAs in every build (stubRegistersOnX86_64, stubRegistersOnARM64), each build holds its own column against gprOf(), and areDistinctOnEveryISA() says in a static_assert on either machine that names are distinct registers on both. On arm64 testaot follows x0 to x30 over the branches of the code of every stub and names a constant or a copy that every path writes again before it is read (findUnreadConstantsAndCopies()).
- heap/: under useZombieMode a sweep overwrites dead cells also where it makes no free list (scribbleDeadCells() in MarkedBlock.cpp, PreciseAllocation::sweep()). A cell of a block with destructors stays zapped, and blocks of Structures and a heap that shuts down are left as they are.
- Tests: 33 new .ir files: the schedules of flow for a loader behind bind and call (8) and for bound functions beside a described call (8), three on the order of modules, three on the verifier's new rules, two on stand-ins in copies, two on members without a layout, and one each on a validated dispatch, a function that becomes a prototype, a release behind a use that never completes, a variable that may be empty and is tested behind the test that its read stood behind, fields that took undefined or null, an async generator's shared arms and one load of storage that serves two loops.
- Tests: native tests for pointers whose owner is needed up to the last read that may give a cell (4), a guarded operation and its frame record (2), a termination that is asked for while counted imports are handed over, the two checks of scratch registers on arm64, a complete list of callees and a complete set of layouts, with static_asserts that no way leads from an Expected to a list or a bool. Three static_asserts in AOTValueFlowCoreTests.cpp hold read() to cells.
- `span = ProvenValue<span>` has two ways to a span, the conversion and the constructor from a range, and a span with both a copy and a move assignment cannot choose. AOTFieldValueNarrowing.cpp, AOTValueFlowResultsFieldsInternal.h and AOTDeferredClosuresAndConstantCollections.cpp write `.value()`.
| if (mode == DontEnumPropertiesMode::Exclude) { | ||
| PropertySlot slot(thisObject, PropertySlot::InternalMethodType::GetOwnProperty); | ||
| getOwnPropertySlot(thisObject, globalObject, name, slot); | ||
| bool hasProperty = getOwnPropertySlot(thisObject, globalObject, name, slot); | ||
| RETURN_IF_EXCEPTION(scope, void()); | ||
| if (!hasProperty) | ||
| continue; | ||
| } | ||
| names.add(name); |
There was a problem hiding this comment.
🟡 nit (optional): Reflect.ownKeys and Object.getOwnPropertyNames on a deferred module namespace now list "then" when the module exports it, although the key is not an own property. The diff dropped the isSymbolLikeKey skip from ModuleNamespace::getOwnPropertyNames, and in Include mode nothing else filters the name before names.add at AOTModules.cpp:2607. Fix: skip a name that getOwnPropertySlot would refuse in both modes, for example keep the isSymbolLikeKey test in front of names.add, while still letting numeric-looking export names through. getOwnPropertySlot at AOTModules.cpp:2552-2555 still answers false for "then" on a deferred namespace, so the listed key has no descriptor.
Why this was flagged
A program does import defer * as ns from "./m" where m has export function then() {}, then calls Reflect.ownKeys(ns) or Object.getOwnPropertyNames(ns). Both reach ModuleNamespace::getOwnPropertyNames with DontEnumPropertiesMode::Include. On the base branch the loop skipped any name for which isSymbolLikeKey was true, which for a deferred namespace (m_isDeferred) includes "then" (AOTModules.cpp:2488-2491). The diff removed that skip; in Include mode the only remaining filter is isAmbiguousExport, so "then" is added at AOTModules.cpp:2607. ModuleNamespace::find still returns nullopt for "then" on a deferred namespace, so getOwnPropertySlot returns false at AOTModules.cpp:2552-2555 and Object.getOwnPropertyDescriptor(ns, "then") is undefined while the key is listed. Exclude mode (Object.keys) is unaffected because the new hasProperty check at :2602-2605 drops it. Users get an own-keys list that names a property the object does not have, which the base did not produce.
Verification: The trigger is a deferred namespace whose module exports a binding named "then", queried with Reflect.ownKeys. The base skipped isSymbolLikeKey names before names.add; the skip is gone, and in Include mode "then" reaches names.add at Source/JavaScriptCore/aot/runtime/AOTModules.cpp:2607 while getOwnPropertySlot (:2552-2555) still refuses it, so Reflect.ownKeys(ns) lists a key with no descriptor.
…e ledger, and loops over typed arrays know what from() and of() make - IR: `Entered : fact` and `AssumeType word, fact`: the read of a module variable takes the fact it relies on as an operand; a load that goes ahead of its fact has the type `T | unspecified`, and the verifier refuses every look at such a word. - Flow: what is claimed about variables, environment fields, fields of layouts, classes and closures is a function of one ledger of writers, readers and reachers. A class of the table lists the own names of its instances or says nothing. Enumerators, native walks and copies read own properties through one function. - Flow: an operation whose operands all have values and whose result has none ends every build with OperationWithoutValue. `--aot-flow=widened` solves twice, once with more given to drawn nodes, and compares. - Types: LayoutSet answers all() or seen(); weights, heat, expected types and guessed layouts are Expected<>; TypeFlags::HasMembersWithoutLayout is gone. - Loops: SeparateUnlikelyLoopPaths and HoistLoopInvariantReads move a read only where it ran on every way to the loop's entry; FunctionAnalyses counts repairs of SSA form that are pending. - Speed: typed arrays made by from() and of() have their class, DataView.byteLength is read in place, for-of over a Buffer walks the storage, a function that returns a class is copied for each named class, index keys are stored by a stub, first reads by name are answered by the stubs' walk, a narrow slot moves so that its neighbor can be wide, the levels of a load are planned level by level. - Run time: a Worker's start asks for room by the size of a block; the operations at the head of a handler are declared as collecting; under useZombieMode a sweep leaves pages alone that it has given back. - Frames: `Array(n)` and `new Array(n)` are listed as the call is written; a symbol that a library module creates is a name only in library text.
…caped counts as called, and element reads go back to their guard - Flow: the source of a copy is read through the objects above it. A loader or evaluator that has escaped counts as called once a value nobody knows is called. Accessors of library prototype objects that the program holds escape. No listing and no retired node takes a host prototype object; the receiver of a write hands on those that come to it. - Flow: what is claimed about fields of layouts, classes below classes and built-in locations begins with the ledger's one relation; who makes an instance is asked of the class it was defined with. A module leads to "any time" only where its own body holds an operation that may run other code. - IR: a capture read and a read of a variable of an enclosing function take the fact of the test they rely on; CallDirect says whether its callee is predicted; an `Entered` that the first turn is sure to reach goes ahead of the loop. - Passes: what moves behind a test that restarts in the generic version begins behind the caught values of a handler. Code generation refuses a claim about storage or position that does not go back to the guard it names. - Representations: a double read out of bytes becomes the one NaN at the read where something is computed from it. - Keys: a symbol that a library module hands out is a key; Object.freeze() prepares its holders, JSObject::freeze(VM&) runs no code. One function makes the key of a module, whether the type of its import is written or made at run time. - Heap: the VMs that share a range keep one last reserve for all of them. - Speed: a class that a function returns is read as if it were written out; a class with a private field below another class makes its fields at construction; `index in object`, stores through a proxy and the text of an index are answered by stubs; the constants of a put-off initializer stand at their uses. - Size: the compiler's Vector grows through one function. - Testing: the report of `--aot-flow=widened` lives in testaot; the check of claims to the back end asks the layout plan what is padding.
There was a problem hiding this comment.
Still open from earlier reviews (2):
- Unresolved: 1 minor or pre-existing, 1 blocking on lines changed since (possibly already fixed).
If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🔴
Source/JavaScriptCore/runtime/JSMicrotask.cpp:1199— A second importer of the entry point can wait forever when the main module's requested graph fails to load, instead of being rejected as on the base branch. JSModuleLoader.cpp:915-918 replaces the entry's load promise with a fresh pending one for a second asker, but the Main step at JSMicrotask.cpp:1197-1199 rejects only the context's loadPromise when loadRequestedModules throws. Fix: on every failure path of the main module's load (the Main step at :1198 and the finishLoadingImportedModule failure at :1237), also reject entry->loadPromise() when it differs from loadPromise and is still pending, as the Requested-rejected path at :1258 already does.Why this was flagged
The host asks for the entry point; hostLoadImportedModule creates a Step::Main context and sets the entry's load promise at Source/JavaScriptCore/runtime/JSModuleLoader.cpp:973. ModuleRegistryEntry::fetchComplete (ModuleRegistryEntry.cpp:291-292) sets the record while that promise is still pending. Before the Main step runs, a second hostLoadImportedModule for the same key reaches JSModuleLoader.cpp:915: the record is set, the promise is Pending, and takeLoadPromiseBelowMainModule returns true, so a new pending promise is stored in the entry at :918 and returned to the second asker. The Main step then runs at JSMicrotask.cpp:1193-1199; if loadRequestedModules throws, only the context's loadPromise is rejected at :1198. Nothing ever settles the replacement promise in the entry, so the second asker's import never resolves or rejects. On the base branch the second asker received the entry's original loadPromise, which :1198 rejects. The new rejection at :1258 only covers the Requested step, not the Main step or the :1237 failure.
Verification: nit — triggers when a second asker for the entry point reaches hostLoadImportedModule before the Step::Main microtask runs, and loadRequestedModules then throws synchronously. Source/JavaScriptCore/runtime/JSModuleLoader.cpp:915-918 replaces the entry's load promise with a fresh pending one. JSMicrotask.cpp:1196-1199 only rejects the context's own promise; the entry's replaced promise is never settled.
… a value counts for every object that reaches it, and flow's walks are compiled once - Flow: a read under a key counts as a read of elements only where every possible key is a number or a name that reads as one. A field that an initializer defines without a value is accounted for by the objects that reach the initializer's `this`, whether the field is declared or added late. - Flow: the order analysis gives a frame to a closure that the function which makes it calls at one place, so what is stored inside is ordered against the code around it. - Flow: the rule that a loader or evaluator which has escaped counts as called at every call of an unknown value is out again. - Type tests: where only `int` of any size is known, an operator tests for int32. A value that has passed two tests in front of a loop keeps both where a later run adopts it as the proof of one. - IR: a fact counts as the test does where closures are asked for their users. A read of a variable of an enclosing function is as it was before it took a fact. - Frames: a method read shortly in front of its call on the same line has no site of its own; its column lies in the call's entry. - Heap: each VM of a shared range also keeps three chunks from its first blocks on. - B3: under a policy that only the AOT client sets, a Phi that fixSSA makes for a demoted value keeps that value's origin. - Built-ins: an undescribed value is an instance of a class that every executable has, or of one that shares a feature with the entry that hands it out. In a file without types no parser is made for a guessed target that lacks a name read on the result. A made name of an import is answered by the image only for a type that makes data of the text. - Size: flow's walks take their functor by reference; partition asks for its median at three places.
### What does this PR do? Moves `WEBKIT_VERSION` from `982277c9dd3e` to `191c6a41380b`, the head of oven-sh/WebKit `main`. > [!NOTE] > The release `autobuild-191c6a41380bb1e2e54be4b6e50ecda83b189f96` was published at 10:39 UTC on 2026-10-27, after this went up. Builds #133617 and #133628 ran before that and failed where they download WebKit (HTTP 404). They say nothing about the change. The PR needs one new build. What the range brings: | Fork PR | What it changes | | --- | --- | | oven-sh/WebKit#912 | The ahead-of-time compiler (890 of the 942 files). Bun does not use it. Outside `aot/`: B3, the marked block cage and its reserve, `Interpreter::getStackTrace`, `ProxyObject`, `JSObject::putDirect`. | | oven-sh/WebKit#916 | The hardened Linux arm64 lanes are compiled without `-mtune`, so that glibc's `_FORTIFY_SOURCE` wrappers are inlined. | | oven-sh/WebKit#917 | The buffer of an old `WeakMap` or `WeakSet` that has shrunk counts until the next full collection. | The pin is the only change Bun needs: - `Heap::didChangeVisitedExtraMemory` is gone. Nothing in Bun calls it. - `Interpreter::getStackTrace` has one more parameter, at the end and with a default. Bun's five callers compile as they are. - The empty table of built-ins in `RemovedFeature.cpp`, which the debug and ASAN builds link: the range adds or removes no `builtinTable*` symbol, no entry of the two list macros and no `extern "C"` hook for the embedder. `BuiltinTable::typedArrayTypeOf`, which is new, is defined in the engine. - No asset is renamed in `lanes.mjs`, and no toolchain pin moves. - `BytecodeList.rb` is unchanged. The one change in the bytecompiler is for private names in object literals, which only built-in code can write, so the hashes in `bundler_bytecode_portable.test.ts` should stay. ### How did you verify your code works? Nothing was built. The list above is from reading the diff of the two commits against Bun's sources. The release has the same 77 asset names as the one of the old pin, all uploaded, and among them the 13 that the `build-bun` jobs of #133628 asked for. All 85 jobs of the fork's build of this commit passed, its JavaScriptCore tests on Linux x64 and arm64 included. `test/js/bun/jsc/webkit-upgrade-191c6a4138.test.ts` covers oven-sh/WebKit#917: | Binary | Result | | --- | --- | | `main`'s CI build (92e819d, linux x64, the old pin) | 0 pass, 2 fail: the heap is 262,032 bytes (`WeakMap`) and 129,498 bytes (`WeakSet`) smaller after the eden collection | | Bun 1.4.4 (an engine from before the bug) | 2 pass | Both the same with `BUN_GARBAGE_COLLECTOR_LEVEL` 0, 1 and 2. It has not run on the new engine yet: CI is the first run. `bun test test/internal/source-lints/` passes (186). --- _Generated by [Claude Code](https://claude.ai/code/session_01YF5TQxMfo4rBWHbttbVAhn)_ --------- Co-authored-by: Claude <[email protected]>
… Structure for an object that is filled, facts on environment fields (#914) Follow-up to #912, from the same branch. Most of it is under `Source/JavaScriptCore/aot`, which only a build with `ENABLE_AOT` compiles. The section "Outside `aot/`" describes the first changes outside it, the pushes below describe theirs, and the last section lists every file outside it. ### Loops - The B3 step `unrollLoops` writes out eight or four turns of a small innermost counted loop. One of them tests the counter against a bound that leaves room for the others, and the loop itself takes the turns that are left. Only likely blocks are copied. - A sum of 32-bit integers that is kept in a double is added as a 64-bit integer while it stays exact. - A loop that goes on while a rising counter is below a falling one gets its range checks as guards at the entry. - A fast loop that ends within the data it walks has no poll. - On x86-64 a small hot loop is kept within lines of the instruction cache. ### Tests of what the IR lowers to - testaot has two new RUN modes. `lower-to-b3` takes IR text and prints B3 as the code generator built it, after one named step of the B3 pipeline, or right before Air. `lower-to-air` prints the final Air of each loop with a count of its instructions. - Blocks print with the hot path first, origins print as the IR operation they came from, heaps print by name, and no address is printed, so one text serves x86-64 and arm64. Only the counts of instructions are per architecture. - The first tests pin the loop that sums a `Float64Array`: the loads and the range check as lowered, the eight loads of the turns that are written out, and a hot loop without a range check, a poll or a second read of the length. ### Guesses and facts - In the copy of a callee, a read of an environment field is a word and a cast that names its fact. Where flow shows that the field is stored before any function that captures the environment can run, the read keeps its type and leans on the entry of the body. - A store into a typed array, a `DataView` or a `Buffer` takes a double with a payload as a `Double`, and the payload does not enter an `ImpureDouble` at a join. ### Analysis - Each layout and each object is asked once for who writes its fields, and writes into escaped classes are gathered once. - A prototype object stops the stores under the names it has and none under another name. - The listed `prototype` of a constructor inherits no removable feature, and a read of it lets the constructor escape. - `valueflow-why` prints the statement behind each hop of an escape and follows unknown callees to where they come from. ### Objects and calls - An object that is given one name after another is a dictionary while it is filled and gets one `Structure` at the end. - `Object.hasOwn(object, index)`, the text of an index as a key, stores under it, `list[-1]` and `-1 in list` are answered in the stub. The type test of a namespace is one load and one compare. - Whole numbers, booleans and `null` of members of unknown type are written by a prelude of `JSONAppendValue`. - `NewObject` narrows a reference where it stores it. - A list of arguments lies on the stack once at each hop between the engine's convention and the compiled one. A shared cold body that only prepares arguments leaves by its last call. - A switch whose arms only choose a value becomes a table of values. - A construction by a function whose `prototype` property changes is not put off. ### Modules - Which groups of modules are loaded together is a table of the image, so `import()` walks no requests. - The words of a file that the first entry point does not bring along are filled when the file is entered. - However a step ends a load, the promise that was left in the entry ends with it. ### Outside `aot/` - `b3/B3UnrollLoops.{h,cpp}`, `b3/B3Generate.cpp`, `b3/B3Limits.h`, `b3/B3CompilationReport.h`, `b3/B3ReduceStrength.cpp`, `Sources.txt`: the step `unrollLoops`, and `Shl(Add(value, c1), c2)` as `Add(Shl(value, c2), c1 << c2)`, both under `LoopPolicy::unrolls`, which only the AOT client sets. - `b3/B3LoopRangeChecks.{h,cpp}`, `b3/B3LoopVersionPlan.cpp`, `b3/B3VersionLoops.cpp`: `planRangeChecksOfMeetingCounters()` and its guards in front of the fast loop; the fast loop drops its poll under `LoopPolicy::limitsOfRangeChecksAreLengthsOfData`, which only the AOT client sets. - `b3/B3CycleForest.cpp`: of a cycle with several entries, a block that polls is the header only if it is reached without a rare edge, and an entry counts as likely only if its predecessor outside the cycle is likely. - `b3/B3LowerMacros.cpp`: `tryBuildValueTable()`, under `SwitchLoweringPolicy::usesValueTables`, which only the AOT client sets. - `b3/B3Generate.{h,cpp}`: `prepareForGeneration()` takes an optional `StepObserver`, called after each step that ran. - `b3/B3Policy.{h,cpp}`: the four fields above, all off by default, and the switch `UnrollLoops`. - `b3/testb3_bun*.{h,cpp}`, `shell/CMakeLists.txt`: tests of the above. - `runtime/Structure.{h,cpp}`, `runtime/JSObjectInlines.h`: `addNewPropertyTransition()` takes the object that gets the property; under `ENABLE(AOT)` and only where the VM has compiled code, a hook may make it a dictionary. - `runtime/JSObject.cpp`, `runtime/VM.cpp`: under `ENABLE(AOT)`, objects that are being filled are finished in front of a delete and in front of the microtasks. - `runtime/ObjectConstructorInlines.h`: `checkStructureForClone()` no longer asks `hasBeenDictionary()`. A `Structure` that is a dictionary is refused above, and one that has been a dictionary and is none has been flattened, which is still asked. - `runtime/JSMicrotask.cpp`: under `ENABLE(AOT)` and only where the VM has compiled code, `moduleLoadStep()` settles the promise in the entry at the end of every step. - `runtime/ErrorConstructor.cpp`, `JSTests/stress/immutable-properties-listed-names.js`: `Error.captureStackTrace()` throws a `TypeError` where `stack` is immutable. - `heap/MarkedBlockCage.{h,cpp}`: a VM that has released the last of its own reserve also takes from the reserve that is kept for all VMs of its range. - `yarr/YarrFlatProgram.h`, `yarr/YarrFlatProgramBuilder.cpp`, `yarr/YarrFlatProgramMatcher.cpp`, `yarr/YarrInterpreter.cpp`, `JSTests/stress/regexp-flat-program-counts-turns-of-alternatives-tried-once.js`: a flat program that counts turns walks the alternatives that are tried at the first place alone and then their copies, as the bytecode does, and makes an attempt at every place. ### Later pushes **AOT: a value that may be unspecified names its fact, a narrowing stays inside the type it narrows, and short texts are joined out of one cache** - IR: a result is `T | unspecified` only where a Return leaves it out, and each use takes `AssumeType word, fact`; the walk over paths that answered the same question is gone. - Types: what `===` leaves of its operand lies inside the operand's type, and one function says whether a built-in object may be an instance of a class. - Flow: evaluated text raises no flag of its own for what it loads by name; a data file of the image is found by name only where the program loads files by name. - Run time: the cache of short texts is made at its own first use; a class without fields below a built-in class is tested by the Structure that `super()` brought back. - Passes: value identities and dominators are built where a pass asks for them. B3UnrollLoops: `far` is `farBound`. **AOT: a cast that holds from a place on names its fact, a member escapes by the name that is read, and a field behind a decided test stays always filled** - IR: the makers of a cast that holds only from a place on name a fact; the runner ties every parted cast in front of the passes that move code out of loops, and the verifier refuses a cast without one. - Flow: a read that hands its value on drops its key into one host node, and each family of escaped instances lets the methods under those names escape. A block whose parameter is `never` with and without the checks in front of it is never entered. What native code makes with a typed array constructor takes its prototype from the new target. - Types: a class part keeps what is expected of its contents beside a proof that says less; in hot blocks a call whose expected receivers find several methods is divided among them. - Modules: the words of files are filled by groups of files, and a body has the test only where it can be entered from outside; the search for what an `import()` loads hands its lists to the count of steps. - Run time: each function of the object's method table has one throw scope. Tests: 25 more loops are pinned by the B3 and the Air that they lower to. **AOT: a reference that may be unspecified is not published as dereferenceable** - Code: `publishKnownProperties()` asks once whether the value may be unspecified; `leastCellSizeOf()` is asked about cells alone. - Tests: the filter of a Structure is asked of one that lies at another place of the table, and of two that share a place the later one has it; the words of the stack behind a function that made two Structures are overwritten in front of the collection that counts them. **AOT: a call of either of two built-ins gives what each makes, a built-in that native code calls may throw, and files of a cycle may enter each other's functions early** - Flow: the class that the table names for a result stands only where every allocation noted at the object names it; every application of a built-in that calls a function may throw an error object, and any value where a parameter runs operand code; what the bodies of files in a cycle reach has an unknown entry; `Reflect.set` with a receiver defines the value on it. - Run time: `JSON.parse(text) as T` remembers the names of a text for each shape and makes the object with its final Structure; a descriptor that is written out is no object; `f.apply` reads its list before it tests the callee; a `require.resolve` that the program stores is the one that is called; the Structure of an object that was filled once is like any other; a mutator that finds no collector thread finishes the collection; a cell in a full range grows into the shared reserve. - Loops: a loop is written out where it walks data or keeps a sum as an integer; on arm64 the turns that are written out share one address; int32 tests stand only in place of a test that the operand gets anyway. - Patterns: the code of a pattern in the image hands a long search to the program that counts turns, and failed searches beside references are kept by operation, position and bounds. - Build cost: masks of memory locations, coverings and identities are computed once or on demand. Tests: several hundred programs are pinned by the B3 and the Air that they lower to. **AOT: a field that is stored by name in an object that is not yet made is found by `in`, and an index that is read is no name** - Passes: where a field stays in its slot, the test whether the slot is filled answers for an object that is not yet made what it answers for the object once it is made. - Flow: a key that is an index marks what is stored under an index above that family, and no longer every name. **AOT: a proxy that is made in sight is written out, a check that names a call in parts throws where the call found nothing, and a native module under a made name is one module** - Passes: a read, `in` or store through `new Proxy(target, handler)` in sight reads the trap off the handler and calls it; where the operand is an object's own definition, allocation sinking asks the description for its type; a field whose closure waits is asked about its stores as about its reads; what walks through casts answers with a type of its own. - Flow: the steps of built-in iterators note what they answer; the listed `prototype` of a host constructor lets the constructor escape under an unknown key too. - Run time: a built-in module that is native code is one module under a name made at run time; an `import()` that the loader answers hands on a promise of its own; frames of functions that are both called and constructed are listed; `ArrayBuffer.prototype.byteLength` is two loads; `indexOf` and `includes` of a text are an inline stub. - Inlining: the head of a callee also goes into a warm call that a loop reaches. JSON: memories of a text's names are kept by the name alone. - An object that was filled in one table counts again as one that has been a dictionary. **AOT: a type test narrows its operand, a typed JSON.parse takes a text with more members than its type lists, and switches in loops at the top level of a module** - Passes: behind an edge of a type test a value is what the test leaves of it, and later tests of the same value are decided; a result is proven once every return has its type; a tally that the counter of its loop bounds is an integer; a switch over few integers in a loop at the top level of a module keeps its table; a declared field that is given what is only expected is read by its slot where nobody keeps the object; the result of defining a property is what its operand holds of objects. - Flow: the methods below listed own keys are found in one step; a function that is printed counts as read; the body of a library module is library code. - Run time: an ArrayBuffer is kept alive over the reads of its length; a request for a module that was put off hands on what it throws; the order of keys of an object with a field stored by name is asked at run time where the field may leave its slot. - JSON: the names of members that a type does not list are remembered by shape; an object with such members is written from one list of its properties. - Heap: where address space is bounded, a part of it is kept unused for requests that may not be refused; a Structure that becomes a dictionary is made before collections are put off; a weak table reports the memory of its buffer when it is visited. - RegExp: the count of turns of code in an image fits a word however long the subject is; the bytecode compiler asks what the JIT counts only where that is read, and once a disjunction. - B3: jumps are threaded through blocks that only test a constant; loops over bytes and words of typed arrays. - Tests: more tests that give the compiler's IR and check the B3 that it becomes. **AOT: a proxy that is made out of sight is written out, a getter defined on a file's exports takes the slot of its field, and the actions that a library sets are recorded behind the engine's own** - Passes: a value that is expected to be the target of a proxy is asked whether it is a proxy; handler and target are read out of it and tested, and anything else takes the access as it is written. - Run time: a getter that Object.defineProperty defines on the exports of a file goes into the slot that the build made for the field. - Image: what a library asks the C library to do on an access to memory that is not there is kept and called behind the table of the places where compiled code reads through null. - WeakMap and WeakSet count their buffers as on main. **AOT: a built-in module answers to a name made at run time, loops that are written out keep their side paths, and the own keys of a built-in are listed in one order** - Modules: one predicate says which records of the image answer to a path; the encoder and the verifier both ask it. - Flow: where native code calls a member under a name, the built-ins that have escaped under that name are among the callees; a call's known receivers answer with the built-ins they find; what happens to the objects that escape together is written apart from the program's own stores; four steps of the solver run on all threads. - Built-ins: a member that is added at its first read keeps that step only where the holder's keys may be listed; process.platform and process.arch are always constants. - Passes: a narrowing that leaves no member stays until the code behind it is cut; tests of one value are looked at only in the blocks that test it; a row of joins ends after 32 merged values; a value that may be undefined or a proxy is tested before its fields are read, and a proxy made out of sight is written out only where the handlers are known. - B3: side paths of a loop that is written out are written out with its turns or lead back into them; a loop that reads words is written out where it walks a list. Air: the ordinals of spilled instructions are a set. - Lowering: Reflect.get with a constant key is a read with a receiver; the text of an index in a literal's computed key takes the road of elements; a list takes the storage that its readers expect in Object.values, map with a built-in callback and for-of over a Map. - Entrances: a shorter entrance declares a parameter with what was tested and what the entrance declares. Stubs: the mark of a list of arguments that is kept elsewhere stands in an argument slot. - Modules: the files of a graph that require() loads run with the synchronous queue open. - Heap: the heaps for which an error is owed are a set, and each is told when it is thrown. - Trimming: the operations of regular expressions have a feature; an accessor outside the prototype objects has no guard. - WTF: what backtrace_symbols() returns goes back to the C library's free on Linux. **AOT: a list literal takes its storage from its own type** - Code generation: the storage of a list literal no longer follows the one cast that reads it. **AOT: what was read out of a proxy is not asked again whether it is one** - Resolving accesses: the arm of `name in proxy` without a trap asks the target once. **AOT: a slot that may be empty is tested before a closure is made of it, and a smaller table entry** - Deferred closures: a field whose slot may be left is read behind a test also where the wide slot is called always filled. - Module variables: the list of answers of a callee has no inline room, so an entry of its table stays small in every build. **AOT: a check of a sum names both operands without their order** - Tests: await-in-a-loop.ir asks for each operand of the sum by itself; a file without text goes. **AOT: a part of an address in a block that leaves the procedure is not shared** - B3: the list of new parts of addresses loses what stands in a block that nothing leads to any more, in front of every reset of reachability. - Modules: the promise of a graph that did not load is rejected on every way out. **AOT: a loop polls unless a length of data bounds it, and a copied class is copied whole** - Loops: the fast version of a loop leaves its poll out only where the length of a view, of a flat string or of an array that holds that many elements bounds it, or a bound of at most 2^20. The test in front of a rotated loop keeps its poll where the cycle around it has none. - Classes: every function that a copied function calls directly is copied with it. A class that an operation outside the copied functions names is not copied. - Allocation sinking: whether a slot has room for undefined and null is asked per allocation. An object made by a constructor function stays sunk where its own test shares guards with the test that members are unchanged. - Modules: an import() that waits for a CommonJS file settles though the file throws. - Proxies: an access is written out for a proxy only where flow sees one arrive beside at most four other known objects. No count over the whole program is left. - Lists: the operations that make a list write down what it holds. A list that declined a conversion to double storage uses up that place's allowance until the next collection. - Methods: a method read under a name that no layout lists, proven to be undefined or a function, gets no test of absence. - Patterns of many names build in linear time and memory. - Memory: array growth, argument lists, operator new and Rust's allocator take what is kept aside when nothing else is left. The page map's parts for the arenas are made ahead. - Size: 76 sources that run rarely are compiled for size. - The check of claims to the back end clears at entry every stack slot that holds no cell. **AOT: a variable of a heap cage test gets a name that no platform header defines** **AOT: a native built-in module is generated once a load, and shorter conversions in front of masks and clamps** - An import of a native built-in module runs its generator once, in the loader's step that makes the module, and keeps what it throws for later imports. - A name imported from "bun" is a copy made where the statement stands, once for each importing file. - `f.apply(receiver, list)` with f no function names `f.apply` in its TypeError. - `x & y` with y a small non-negative integer converts the lowest bits of x alone. - An int32 stored into a Uint8ClampedArray is clamped in 32 bits, and the loop's body is written out eight times. - A store whose receiver is a proxy of the object itself, without a trap that could see it, ends in the object. - Flow analysis keeps the writes of unknown code apart by a mark that no read asks for. - The own keys of a built-in object come in one order and one set, whatever the program uses of it. - Tests: IR tests and native tests for all of the above. **AOT: two reads of one place are merged only where nothing between them writes there** - Where a loop is written out, two reads of one place in a turn become one read only if no block on a way from the first to the second, written out or not, writes there. - The poll of a loop that was turned round stands on the way back into it, not in front of it. - Range checks of a * counter + b leave a loop behind tests at its entry. - The instructions of a build are linear in the number of methods of a class. - `delete proxy.name` and `delete proxy[key]` call the deleteProperty trap of a handler in sight directly. The length of a list read through a get trap that hands on is the list's own. - What an ownKeys, getOwnPropertyDescriptor or defineProperty trap answers is held against what the target itself says of being closed. - An access that is left as written behind a test for a proxy is not written out again. - Filling the cell of a built-in adds no member to the object that holds it. - A namespace or a default import of "bun" that is exported again is a local export, and only `export .. from "bun"` asks for the module. - Two import() at once of files that share a native built-in module begin in the order of their calls, and such a module is generated when the loader reaches it. - Each CommonJS file of a level of an import() whose jobs are counted is asked for through the loader. - The link error of an export statement has the words and the order of the loader's. Frames of eval code say so. `o[KEY]` with a constant of the module is an access by name. - Under CMake the sources of aot/ take aot/support/AOTPrefix.h by -include and no precompiled header. - Tests: testb3 cases, IR tests and native tests for all of the above. **AOT: loops over typed arrays run on vectors, and one place decides whether two reads are one** - A loop that copies, fills or combines the elements of typed arrays one by one runs on vectors behind tests at its entry, with the loop as written for what is left over. The x86-64 assembler has the instructions it needs. - Whether two reads of one place in a written-out loop are one read is decided by the numbering of memory alone. The reads of a loop's bound that are taken for one are noted for the check of moved loads. - Range checks of a * counter + b also leave a loop where the index is reduced by a mask or a remainder. - Listing, storing and deleting the keys of an object with many keys: the keys go from the table into the list directly, and a store or a delete looks the table up twice. - The instructions of a build are linear in the number of fields of a class. - `Object.hasOwn`, `hasOwnProperty` and `getOwnPropertyDescriptor` on a proxy made in sight call the trap of its handler directly. - A computed key that may be one of more than 32 names is any name to the analysis, so an object wrapped key by key costs it a fixed amount. - The accessors and functions that a program puts on `process` are followed where a statement imports node:process. - A handler for a slot is in an image only where a stub that jumps through its table is. - The destroy function of ten kinds of Intl objects is removable with the feature that creates them. - Who asks how much address space is left says what an answer that cannot be counted means: the whole limit for a request of its own, nothing for what is kept aside for others. - What is kept aside is renewed out of the allocator's arenas, and its state lies in the allocator's record of the thread. **AOT: a call says whether it writes the caches of call sites, and patterns made at run time remember a search by what a reference can still read** - A call into the run time writes the caches of call sites unless its own declaration says that it writes nothing of the run time's state. No part of a cache is read ahead of a loop in which a call may fill it anew. - Loops over typed arrays do not run on vectors: the policy leaves the pass off. The pass itself asks how hot a loop is, leaves 64-bit words alone, walks falling and meeting counters, and is smaller. - A pattern made at run time: a search that found nothing is remembered by the bounds that a reference can still read from there, and a run without an upper bound remembers where its whole rest found nothing. - SinkAllocations no longer binds every guard of a layout to the object that it builds late. - The handlers of slots are in every image again. - In a release build the sources of aot/ trap where a check of libstdc++ does not hold, whichever version of the library they are compiled against. A Release lane for glibc looks at the archive for it. - JSON.stringify reserves what a long string needs where the string stands in the middle of a list or ends in an escape. - Objects with many keys: a name that the program does not spell asks for its number once, and a key that is used for properties alone is made a name at once. - A walk over a generator that is written out leaves the reads of next, return and throw where the keys of the generator's prototype are listed. JSON.stringify takes its short way for a Date once Date.prototype has the three members that the long way reads. - A file that runs ahead of the loader and calls import() finds the loader where `bun run` has it. An import() below a require() finds a CommonJS file that the required graph has just asked for. - Exports that nobody reads are removed a second time in front of CallModules, and a file with nothing to run keeps no body. - Live ranges are split around the frame of a loop only where that pays. - Range checks of a * counter + b leave a loop by less code of the compiler. The output is the same. - A cacheable dictionary that is made flat is reported to no cache of names. - The message for `return f.call(..)` and `return f.apply(..)` on what cannot be called names the callee. - A wrapper keeps the summary of effects that its function had. - A proxy that is asked under an integer hands its trap the text of it. - The message for a library module that is not found is what it was. - Under a limit on address space the allocator tells the keeper of what is kept aside who takes fresh small pages, and a store of the program gets its RangeError ahead of the operation. - The check of moved loads follows a load into the copies of a loop. **AOT: an object of a constructor function is made before its prototype property may change, and the front of a loop's version names values of copied blocks** - SinkAllocations makes an object of a constructor function, whose prototype property flow does not call fixed, in front of whatever may end the member guards of its layout or run other code. - The front of a fast version of a loop may name a value of a block that another version copies. Such a value gets a variable, from the maker that demoteValues() uses. - A call writes the caches of call sites where its operation has a cache, where it writes what a lookup may come by, or where it calls a function of the program. A host function goes by its row in the table of built-ins, so a call that only reads leaves a loop again. - A pattern made at run time: the walk over what is reached on one way visits each operation once, and a greedy run that found nothing enters only the places below what is entered. - What JSON.stringify reserves ahead is room in the buffer, and only what it says is text is held against the longest string. A typed list whose short strings need an escape is written into the first reservation. - The finished list of Reflect.ownKeys and Object.getOwnPropertyNames is kept where a symbol stands beside the fields, in the cache that every collection clears. - A field that is created on an object with a property beside its fields finds its step of the key order. - A class finds a static field by an index, and the ledger finds its variables by object and key, so a build is linear in the number of static fields of a class. - Flow: what a function returns that the program laid on a holder of exports comes back to a call by name whose callee nobody knows. Only a read that is called asks for a lookup of its own. The predecessors of retired nodes are connected on all threads. - A guard and a position meet edge by edge. - The check of moved loads follows an entry through demoted values, and keeps its entries where code that nothing leads to is deleted. **AOT: an object that is handed its prototype is built where `new` stands, and native code polls where it enters compiled code** - SinkAllocations: an allocation that is handed its prototype as an operand is built where it stands. - The adapters from native code into compiled code, and the stub that puts a saved frame back on the stack, compare with the stack limit that a request to the thread lowers, and poll out of line. What waits at an await does not go on once its thread was asked to end. - Flow: a built-in that keeps a value which nobody follows carries it out, so what Promise combinators, AbortSignal.abort().reason, SuppressedError, a stream's chunks and a rejected or thrown value hand back keeps its members. - Flow: a set of more than 64 members is tested for a watcher's member, not chained. Helpers that are imported from another file are copied for each file that calls them. - A read of a locked data property whose answer the build knows stays as an initialization where the keys of its holder may be listed. A first read goes by the name that is read. - What is written out for Object.hasOwn and hasOwnProperty on a proxy stands in an inline frame of that built-in. - The own keys of an object without a symbol are looked for in the first list first. A field that is created in a layout whose keys nobody lists looks no step of the key order up. - `i < n` with n: number: the counter is followed through what the branch on the comparison hands on, and the bound is tested ahead of the loop. - handGraphToLoader() and appendJSONTextOfProperty() look at their scope behind the last call that can throw. - A build is linear in the try blocks, loops, yields, cases, parameters and operands of `||` of one function: B3's induction records are found by their value, PlaceTypeTests asks the counters of one loop, and WTF::NaturalLoops finds a loop by its header. - The walk that builds objects ahead of a change of a constructor function's prototype returns at once where no family of the function may take one, and passes cells and other families. - The rounds of flow analysis: watchers, waves, edges into lists and long lists run in shares on all threads. The output is the same. - A pattern made at run time: runs of under eight units are not marked. - The verifier of modules finds what a function mentions by the schema's walkers. The check of moved loads holds the slots of call sites to the tighter form. - The jsc shell gives import.meta, module and require each function of the table of built-ins that it lacks. Such a function says which one is missing when it is called. **Air: a local in optimizeBlockOrder has a name that no system header defines** - `near` is a macro in the headers of Windows. The iterator over the jumps in reach of a rare branch is named inReach. **AOT: an entry of the typed JSON.parse table that is being filled is not handed out again, and one rule orders unbuilt objects with member guards** - JSON.parse into a typed shape: an entry of the table of learned objects has one writer at a time, at any depth of nesting; where none is free the inner object is parsed without being learned. A learn that gives up leaves its entry refused. No object is built from an entry without a plan. - SinkAllocations: one function decides where an unbuilt object is built: in front of whatever may end the member guards of its class or runs other code, and, for an object that is handed its prototype, also in front of whatever reads those guards. It replaces the rule that such an object is never virtual; four tests have their earlier text again. - Flow: the promise of an import() is also rejected with what the loader throws. A copy of an object's own properties lists its records when all else is at rest, so the graph of functions that each copy what they are given grows linearly. A wave's task asks ahead for the rows, messages, values and marks it is about to read. - A module that is linked stays linked, however the link step ends. - A thread tells the run time when it has started; the room that is kept for the next VM follows what a started VM of this process has taken. - Emitters in codegen, builtins, passes, ir, place and image append their values in the order written, whatever order the host compiler evaluates arguments in. eliminateRedundantReads() runs its three steps as statements. - The IR test runner knows the word `windows` in REQUIRES. - Native tests: a termination that is requested ahead of an entry from native code, with 0, 1, 9 and 300 arguments, a class and a resumed async function; a thread that takes small pages. **AOT: the reads of deferred initializers are recorded** - DeferInitializers records a variable that a deferred initializer reads as read, so RemoveUnreadExports keeps its store. ### Every file outside `aot/` - `./`: `Dockerfile` - `JSTests/`: `BUN-TEST-DIFFERENCES.md` - `JSTests/stress/`: `bun-weak-table-emptied-before-an-eden-collection.js`, `immutable-properties-listed-names.js`, `regexp-bytecode-of-deeply-nested-fixed-count-groups.js`, `regexp-flat-program-counts-turns-of-alternatives-tried-once.js`, `regexp-flat-program-memoizes-unbounded-runs.js`, `regexp-flat-program-remembers-failed-searches-beside-references.js`, `regexp-image-code-hands-long-searches-over.js` - `Source/JavaScriptCore/`: `CMakeLists.txt`, `Sources.txt`, `jsc.cpp` - `Source/JavaScriptCore/assembler/`: `MacroAssemblerX86_64.cpp`, `MacroAssemblerX86_64.h`, `X86Assembler.h` - `Source/JavaScriptCore/b3/`: `B3AbstractHeapRepository.cpp`, `B3AbstractHeapRepository.h`, `B3AffineIndex.cpp`, `B3AffineIndex.h`, `B3CompilationReport.h`, `B3ConvertBranchesToSelects.cpp`, `B3CycleForest.cpp`, `B3FixSSA.cpp`, `B3FixSSA.h`, `B3Generate.cpp`, `B3Generate.h`, `B3InductionRecords.cpp`, `B3InductionRecords.h`, `B3Limits.h`, `B3LoopRangeChecks.cpp`, `B3LoopRangeChecks.h`, `B3LoopRegions.cpp`, `B3LoopRegions.h`, `B3LoopUtilities.h`, `B3LoopVersionPlan.cpp`, `B3LoopVersionPlan.h`, `B3LowerMacros.cpp`, `B3MemoryNumbering.cpp`, `B3MemoryNumbering.h`, `B3MovedLoadCheck.cpp`, `B3MovedLoadCheck.h`, `B3PatchpointValue.cpp`, `B3PatchpointValue.h`, `B3Policy.cpp`, `B3Policy.h`, `B3Procedure.cpp`, `B3ReduceStrength.cpp`, `B3RegionCloner.cpp`, `B3RegionCloner.h`, `B3RotateLoops.cpp`, `B3SinkValues.cpp`, `B3StackmapSpecial.cpp`, `B3ThreadJumps.cpp`, `B3UnrollLoops.cpp`, `B3UnrollLoops.h`, `B3VectorizeLoops.cpp`, `B3VectorizeLoops.h`, `B3VersionLoops.cpp`, `testb3_bun.cpp`, `testb3_bun.h`, `testb3_bun_control_flow.cpp`, `testb3_bun_hoisting.cpp`, `testb3_bun_loop_plans.cpp`, `testb3_bun_loops.cpp`, `testb3_bun_placement.cpp`, `testb3_bun_policy.cpp`, `testb3_bun_random_program.h`, `testb3_bun_reductions.cpp`, `testb3_bun_selects.cpp`, `testb3_bun_strided_range_checks.cpp`, `testb3_bun_unroll_loops.cpp`, `testb3_bun_vectorize_loops.cpp` - `Source/JavaScriptCore/b3/air/`: `AirAllocateRegistersByGreedy.cpp`, `AirOptimizeBlockOrder.cpp`, `AirPolicy.cpp`, `AirPolicy.h`, `AirSplitLiveRangesAroundFrame.cpp`, `testair_bun.h`, `testair_bun_shrink_wrap.h` - `Source/JavaScriptCore/heap/`: `AddressSpaceBudget.h`, `Collector.cpp`, `Collector.h`, `CompleteSubspace.cpp`, `GCSegmentedArrayInlines.h`, `Heap.cpp`, `Heap.h`, `LocalAllocator.cpp`, `MarkedBlockCage.cpp`, `MarkedBlockCage.h`, `ReservedRangeHeap.cpp`, `ReservedRangeHeap.h`, `StructureAlignedMemoryAllocator.cpp`, `StructureAlignedMemoryAllocator.h` - `Source/JavaScriptCore/inspector/`: `ContentSearchUtilities.cpp` - `Source/JavaScriptCore/inspector/agents/`: `InspectorDebuggerAgent.cpp` - `Source/JavaScriptCore/interpreter/`: `Interpreter.cpp`, `StackVisitor.cpp`, `StackVisitor.h` - `Source/JavaScriptCore/runtime/`: `AbstractModuleRecord.cpp`, `ButterflyInlines.h`, `Error.cpp`, `ErrorConstructor.cpp`, `IntlDateTimeFormat.cpp`, `IntlDateTimeFormat.h`, `IntlDisplayNames.cpp`, `IntlDisplayNames.h`, `IntlDurationFormat.cpp`, `IntlDurationFormat.h`, `IntlListFormat.cpp`, `IntlListFormat.h`, `IntlLocale.cpp`, `IntlLocale.h`, `IntlNumberFormat.cpp`, `IntlNumberFormat.h`, `IntlPluralRules.cpp`, `IntlPluralRules.h`, `IntlRelativeTimeFormat.cpp`, `IntlRelativeTimeFormat.h`, `IntlSegmenter.cpp`, `IntlSegmenter.h`, `IntlSegments.cpp`, `IntlSegments.h`, `JSMicrotask.cpp`, `JSModuleLoader.cpp`, `JSModuleLoader.h`, `JSONObject.cpp`, `JSObject.cpp`, `JSObjectInlines.h`, `JSPropertyNameEnumerator.cpp`, `JSPropertyNameEnumerator.h`, `JSPropertyNameEnumeratorInlines.h`, `Lookup.cpp`, `MarkedVector.cpp`, `MarkedVector.h`, `ModuleGraphLoadingState.h`, `OptionsList.h`, `ProxyObject.cpp`, `ProxyObject.h`, `RegExp.cpp`, `ScriptExecutable.cpp`, `StackFrame.cpp`, `Structure.cpp`, `Structure.h`, `VM.cpp`, `VM.h` - `Source/JavaScriptCore/shell/`: `CMakeLists.txt`, `ExternalMimallocShims.cpp` - `Source/JavaScriptCore/yarr/`: `YarrFlatProgram.h`, `YarrFlatProgramBuilder.cpp`, `YarrFlatProgramMatcher.cpp`, `YarrInterpreter.cpp`, `YarrJIT.cpp` - `Source/WTF/wtf/`: `AutomaticThread.cpp`, `AutomaticThread.h`, `NaturalLoops.h`, `StackTrace.cpp`, `StackTrace.h` - `Source/WTF/wtf/threads/`: `Signals.cpp`, `Signals.h` - `Source/bmalloc/bmalloc/`: `bmalloc.cpp`, `bmalloc.h`
Follow-up to #906, from the same branch. Everything is under
Source/JavaScriptCore/aot, which only a build withENABLE_AOTcompiles, except what the last section lists.Generated code
inand stores through aProxyread theget,hasandsettraps off the handler and call them from compiled code, also under a small index. A proxy without agettrap reads a data property of its target in the stub, and one without ahastrap asks its target there. A program in which no proxy can be made holds no stubs for traps.Reflect.get(object, key, receiver)andsuper[key]answer a data property in a stub.new C()of a derived class that is reached by value makes one cell.new C()of a class expression that is evaluated many times, such as the class of a factory or a mixin, is answered in a stub for every evaluation. ConstructingPromiseand classes below it takes fewer steps.===and==on strings read a piece cut byslice()where it lies.Reflect.ownKeys()andObject.getOwnPropertySymbols()of objects with fields under symbols are answered from the table of key lists.symbol.description) are cached for primitive receivers, and an element that is added to a compiled object by index is defined without a descriptor.putDirect()reaches the static fields that compiled code keeps in module variables, and stands behind them in the order of keys.Modules
import()settles in the turn in which it settles underbun run: the image says which modules are loaded with the first entry point, the number of jobs of a load is exact across levels, and a further entry point is evaluated by its levels.import()of a synchronous ES module of the program is a promise and one job, without a record or an entry of the loader, until somebody asks for another module.bun run: a file that the loader evaluated itself takes no second step, whoever asks for the entry point while it loads hears of the load one step ahead of the program, and the loader waits for a CommonJS file that stands in front of a module on the way of a load.require()with the namespace object of that import.import()reaches the loader also where a termination is asked for meanwhile, such as avmtimeout. The termination is thrown at the check behind the hand-over.export { c } froma module with two or moreexport *over modules without a table of names is looked up at run time.thenand throw again what the root of their cycle threw, asJSModuleNamespaceObjectdoes.ShadowRealm) runs the host's library modules from their text.Guesses and facts
Expected<T>. It turns into neither its value nor a bool by itself, andpredicted()marks each place that acts on it. What is true in every run is aProvenValue<T>, which onlyProvenmakes. A pass that takes a guess for a fact does not compile.CalleeSet,CalleeList,CalleeCandidates) and the layouts of a type, a test or an access (LayoutSet) answer in these two types.--aot-heat=shuffleddraws the heat of every block, edge and function from a hash: a program means the same under any heat.Analysis
import()loads may run while another module runs: inside arequire()of an ES module, which runs the jobs of the loader, and inside a built-in that the table marks as running the waiting jobs. The order that flow draws between modules says so.callorapply, or handed toReflect.applyis followed whatever else the callee may be. A bound function that is handed out beside library code which constructs an unknown constructor enters its target.ToPropertyDescriptortakes from a literal.Stack frames
Build time
InlineCallstakes a body in at most 32 levels deep.Checking
--aot-check=validate-references, and intestaot, the finished Air of every function is read: a pointer into what a cell owns is not held across a call that may collect unless the cell is. The check also sees a pointer whose own load took over a trap, and asks at each place whether a pointer may still give cells.AssertNoGC.testaotreads the code of every stub for a constant or a copy that is written again before it is read.Outside
aot/Source/WTF/wtf/EnumTraits.h: the table ofenumName()ends at the last named enumerator.interpreter/Interpreter.{h,cpp}:getStackTrace()takes an optional filter, so an embedder's walk ends at the last frame it shows, andappendStackTrace()hands each run of compiled code to one walk.interpreter/StackVisitor.cpp,runtime/JSModuleLoader.cpp,runtime/JSMicrotask.cpp,runtime/ScriptExecutable.cpp,runtime/Error.cpp: a few lines each for the frames, the load promise and the realms above.runtime/JSObject.{h,cpp},runtime/JSObjectInlines.h:putDirectInternal()in the mode that defines an own property leaves forputDirectToCompiledClosure()where the object is a class object of compiled code, underENABLE(AOT).runtime/ProxyObject.{h,cpp}: underENABLE(AOT),getWithTrap(),hasWithTrap(),setWithTrap(),finishHas()andfinishSet()for a caller that has read the trap off the handler itself.heap/MarkedBlock.cpp,heap/PreciseAllocation.cpp: underuseZombieModea sweep overwrites dead cells also where it makes no free list.heap/ReservedRangeHeap.{h,cpp},heap/MarkedBlockCage.cpp:tryEnsureRoomForNewThreads()says whether each of so many threads that have taken nothing from the range yet can take the pieces that a VM takes at its start.heap/HeapProfiler.cpp,inspector/ScriptCallStackFactory.h,tools/VMInspector.h: an include or a declaration of what they themselves use.bytecompiler/NodesCodegen.cpp: a class member under a private name of built-in code is defined under that name.b3/: a pinned constant in a register of the other bank is read throughBitwiseCast(arm64), an access whose trap is attributed to it takes[base + index]only beside a pinned base, the log of moved loads follows blocks that are split or freed, and very many stack slots get their places from live ranges.