Skip to content

Faster cppia host calls, closures and callbacks under the JIT, with HashLink in the bench - #500

Draft
dimensionscape wants to merge 36 commits into
mainfrom
feature/cppia-perf-b621b5
Draft

dimensionscape wants to merge 36 commits into
mainfrom
feature/cppia-perf-b621b5

Conversation

@dimensionscape

@dimensionscape dimensionscape commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Faster cppia under the JIT: scripts calling into the host, closures and callbacks, and the code the JIT generates, measured against HashLink, for 6.1.0. The Changes.md lines are under 6.1.0, and main is merged in at ff4d17f.

BunnyMark on a real host

zest's OpenFL host built on this branch at 5fa2bef, running BunnyMark (openfl-samples 8.7.0, seeded so every variant draws the same frames) as a cppia script under the JIT, against the same app compiled to HashLink 1.16 and to native C++ with Lime, and zest's host as it was. All four give the same checksum at every count.

On a Windows machine with a GPU, vsync off and no frame cap, medians in ms per frame:

200,000 bunnies update draw frame fps
native Lime (C++) 1.54 1.71 9.58 104
zest, this branch 2.22 2.27 11.01 91
HashLink 1.16 2.03 5.69 21.51 47
zest, its host before 19.60 2.25 29.17 34

At 100,000 bunnies: 186 fps on this branch, 92 on HashLink, 221 native, 65 before. Bunnies held at 60 fps: more than 200,000 on this branch (about 300,000 extrapolated), about 155,000 on HashLink, about 330,000 native, about 109,000 before.

The script's update loop, which moves each bunny through a host Tile's x and y, is within about 10% of HashLink's, where it was 7 to 10 times slower. The frame is half HashLink's because the rest of OpenFL is compiled C++ in the host.

With software rendering (Mesa llvmpipe) the renderer takes most of each frame, so the four are closer: about 20,600 bunnies at 60 fps on this branch, 19,200 on HashLink, 21,200 native and 19,100 before.

The commits after 5fa2bef make jitted script code faster again (bunny_update below is 1.05x of HashLink, where it was level at 5fa2bef), but BunnyMark has not been measured on them.

Bench

--hl <path to hl> builds the cppia workloads for HashLink (bench/hl), runs them in turn with the cppia hosts, requires the same checksums, and adds an HL/JIT column. Windows, Ryzen 9 9950X, MSVC 19.50, Haxe 4.3.7; the three alternating on one pinned core at high priority, 7 processes x 10 samples each, on 832d0ce. The machine was in a slower phase than for this description's last table, so compare the ratios rather than the rates. Rates per second:

Under the JIT main 384fc87 this branch HashLink 1.16 vs main vs HashLink
int_loop 308M 842M 329M 2.73x 2.56x
float_array 107M 188M 67.4M 1.76x 2.79x
alloc_objects 41.0M 52.2M 18.4M 1.27x 2.85x
virtual_call 144M 336M 168M 2.34x 2.00x
native_call 303M 547M 327M 1.81x 1.67x
host_statics 376M 757M 337M 2.01x 2.25x
openfl_frame 5.88M 6.87M 4.40M 1.17x 1.56x
closure_call 11.0M 129M 115M 11.8x 1.12x
host_sort 2.47M 12.4M 11.5M 5.0x 1.08x
bunny_update 16.5M 43.2M 41.2M 2.62x 1.05x
call_by_name 22.2M 194M 191M 8.7x ~1.0x
native_callback 11.8M 46.4M 119M 3.9x 0.39x

closure_expr and script_map are new and have no main column: under the JIT they run at 74.6M and 424M calls/s, where HashLink runs them at 184M and 108M (0.40x and 3.9x).

Interpreted, against main: call_by_name 2.0x, closure_call 1.3x, native_callback 1.19x, the rest level (measured on 5fa2bef; the commits since change jitted code and the host's calls into it).

Each commit message has its own before and after numbers.

Changes

Scripts calling into the host:

  • Typed entries for host instance methods. In a scriptable build, each instance method's Dynamic wrapper (HX_DEFINE_DYNAMIC_FUNC) makes two entries for a method taking up to three Ints, Bools, Floats or objects: one calling it virtually, as its script stub does, and one calling the class's own, as the super stub does. Jitted code calls them with the object and the arguments in registers instead of through the stub, the frame and the helper that catches what the stub throws. On a script class extending the host class, with no script override, it calls the class's own directly.
  • Typed entries for host static functions, bound ones and the ones a script calls by name (an abstract over a host type, as openfl.Vector's methods are), from each static function's Dynamic wrapper.
  • Where every way a host call can go is an entry, the object and the result stay in registers and the context's frame is left alone.

Closures:

  • Local functions compile under the JIT on their first call, as class functions do. They ran in the interpreter. [cppia] Add jit compilation for local functions HaxeFoundation/hxcpp#1213 is the same gap upstream.
  • Calls of script closures from scripts pass arguments and results as they are, and jitted code checks and enters a compiled closure in line and calls its code as a direct call does.
  • A closure's captured variables are copied from a flat list its function keeps, with moves of each one's size.

Host code calling back into scripts:

  • Typed host-to-script calls. Dynamic::operator() (API < 500, scriptable) gives a script closure Int, Float, Bool and String arguments as they are through hx::callFunction (new hx/TypedCall.h), and the typed call into compiled code is kept in line.
  • Array.sort with a script comparator sorts the values without boxing them, in the same steps, and calls the comparator as a run of typed calls (hx::TypedCallRun), checked once for the sort.
  • A compiled entry for each closure function and kinds of call. On the first typed call, the JIT makes an entry that puts the arguments, this and the captured variables in the frame with moves at known offsets, calls the compiled code directly and writes the result, boxing it where the call wants an object. One C++ function did that for every closure, and was nearly half of each comparison in a sort.

Code the JIT generates:

  • Int and Float locals in saved registers, the most used first. Arguments and variables a closure shares stay in the frame, as does every local on 32-bit x86 and in debugger builds, and every Float on x86-64 outside Windows.
  • Operands read where they are: constants as immediates, locals in their register or slot, without a copy through scratch registers.
  • Only the scratch registers a function uses are declared, which spares a native-calling function two callee-saved registers on 64-bit Windows.
  • Int and Float boxes read in line where a Dynamic is an operand, and a closure called directly when its result is wanted as a Dynamic, boxing the result after.

Runtime:

  • Object array elements are read in place under the JIT.
  • Int and Float boxes are made with the allocator's fast path in line, and Ints from -1 to 1023 share boxes made once. A whole Float still boxes as an Int only from -1 to 255, so Type.typeof and Std.isOfType see the same types.

The typed entries make the bench's scriptable host about 3% larger; builds that are not scriptable are unchanged.

What this does not reach

Tests

New, each running the same cases as compiled code and as a script interpreted and jitted, and checking that all three print the same lines: CppiaJitLocalFunctions, CppiaJitLocalFunctionsDebugger, CppiaClosureCallTypes, CppiaJitObjectArrayRead, CppiaJitClosureDirect, CppiaJitHostMethods, CppiaStaticCallsByName, CppiaHostClosureCalls, CppiaHostSortComparators, CppiaClosureCaptures, CppiaHostMethodEntries, CppiaDynamicBoxes, CppiaJitClosureEntry, CppiaJitClosureEntryDebugger, CppiaHostSortRuns, CppiaJitDynamicNumbers, CppiaJitClosureDynamicResults, CppiaJitLocalRegisters, CppiaJitLocalRegistersDebugger, CppiaJitOperands, CppiaJitScratchRegisters, CppiaHostRunEntries. Several were also checked by breaking the code they cover on purpose.

On 5fa2bef, on Windows: all 393 of test/regression; test/cppia interpreted and with -jit (56 each); test/haxe with both collectors (2,698 each); test/std (696); Haxe 4.3.7's tests/unit as plain C++ and scriptable C++ (11,025 each) and as cppia interpreted and jitted (10,982 each); and OpenFL's BunnyMark built scriptable with --dce no.

The commits since change cppia, the typed call header (scriptable builds only) and one static initializer in Dynamic.cpp. On them, on Windows: all 97 test/regression/Cppia* tests and test/cppia interpreted and with -jit; Haxe 4.3.7's tests/unit as scriptable C++ and as cppia interpreted and jitted; test/haxe with both collectors; and BunnyMark built scriptable. After merging main at ff4d17f: test/haxe with both collectors (2,880 each), CppiaAdoptInstances, CppiaHostRunEntries and CppiaHostSortRuns. Other platforms are left to CI.

CI on 50496e7 failed five of the new tests on Linux, macOS and the sanitizers, on what they printed rather than on cppia: floats from multiply-adds, which GCC and Apple clang fuse into one rounding where MSVC and cppia round twice; Strings past an Int converted through atoi, which MSVC saturates and glibc wraps; and a shift by 131, which UBSan stops. 78fa893 makes them print only exact or defined results; built with MSVC fusing multiply-adds, the float tests print the same as the plain build, and all five pass on Windows. On 78fa893 macOS arm64 still printed other values in CppiaJitDynamicNumbers: a Float past an Int, or not a number, taken as an Int through a Dynamic is a plain C++ cast, which x86 makes -2147483648 and arm64 saturates. c65f8be leaves those conversions out as well.

The JIT compiled the functions of a script's classes and its main, or
marked them to compile when first called, and nothing else. A local
function, a closure written inside a function or an initializer, belongs
to no class, so it was never compiled: under the JIT its body always ran
in the interpreter, whether jitted script code called it or the host
called it back. Calling a closure gained little from the JIT, and the
host calling one back gained nothing.

The module now lists every function it links, and the JIT marks the
local ones to compile on their first call, as it marks class functions,
or with HXCPP_CPPIA_EAGER_JIT compiles them as the module loads. A
closure already ran its function's compiled code when there was any, as
a bound method does, so how a closure is called does not change.

bench --base 629451b, 5 processes x 10 samples each:
  cppia_jit_closure_call     13.9M to 26.9M calls/s
  cppia_jit_native_callback  14.7M to 36.1M callbacks/s
The interpreted workloads, and virtual_call and alloc_objects under the
JIT, stayed within their spread.

CppiaJitLocalFunctions runs closures that capture locals, this and each
other, recurse, return each type, take defaults, throw through callees
and the host, and come from a static initializer, as compiled code and
as a script interpreted and jitted, and checks that all three agree.

With HXCPP_DEBUGGER, compiled code clears its frame's locals as it
starts, so the debugger can read any of them, and a closure's captured
variables are among them, copied in before its code runs. Cleared, a
captured Array read as null: CppiaJitLocalFunctions built that way threw
Null Object Reference under the JIT. Only the locals around the captured
variables are cleared now. CppiaJitLocalFunctionsDebugger is the same
test built with HXCPP_DEBUGGER.

HaxeFoundation/hxcpp#1213

Tests: CppiaJitLocalFunctions, CppiaJitLocalFunctionsDebugger, test/regression/Cppia*, test/cppia
A call through a function value, f(x), ran the closure's __run with each
argument boxed into a Dynamic, which the closure unboxed into its frame,
and the closure boxed its result for the caller to unbox again. Most Ints
and every Float allocate a box, so calling an Int->Int closure allocated
twice, interpreted and under the JIT alike.

When the value is a script closure or bound method whose function takes
each argument as the type the call has it in, the call now builds the
function's frame itself, with the arguments as they are, and reads the
result as it is when it has the type wanted. A script closure is known
by its vtable, which every closure stores as it is made, so the check
needs no dynamic_cast. Jitted code writes each argument as its own type
and calls one helper, which takes the same path or, for anything else,
boxes what jitted code wrote and calls __run as before. Arguments of
other types, more arguments than the function takes and host functions
still go through __run, and a result of another type is boxed and
converted as it was, so a Bool passed to Dynamic is still a Bool and a
whole Float returned as Dynamic is still an Int box.

bench --base <the commit before>, 3 processes x 10 samples each:
  cppia_jit_closure_call     27.0M to 48.1M calls/s
  cppia_interp_closure_call   9.7M to 11.5M calls/s
native_callback, where the host calls the closure, stayed within its
spread, as that call still goes through __run.

CppiaClosureCallTypes calls closures with every mix of Int, Bool, Float,
String, Dynamic and Array arguments and results, wanted as each type,
with -0.0 and whole Floats, null Strings, six arguments, a null function,
throws, a return inside an argument, bound methods called directly and
through Dynamic, and host functions, as compiled code and as a script
interpreted and jitted, and checks that all three agree.

Tests: CppiaClosureCallTypes, CppiaJitLocalFunctions, test/regression/Cppia*, test/cppia
Jitted code reading arr[i] where the value is wanted as an object called
objGetIndex, which went through the array's virtual __GetItem and built
a Dynamic of the element. That is what an Int, Bool, Float or String
array needs, as __GetItem boxes the element. An array of objects, which
is every Array of a script class, has nothing to box, and its element
read as an Int, Float or String was already loaded in place, behind the
same unsigned bounds check that __get makes, with null past the end.

Such a read now takes that path for objects too, and only arrays of
other element types call the helper. A profile of the JIT's
alloc_objects had 13% of its time in objGetIndex and __GetItem, for the
script's reads of live[slot].

bench --base <the commit before>, 7 processes x 10 samples each:
  cppia_jit_virtual_call     163M to 229M calls/s
  cppia_jit_alloc_objects    49.8M to 60.6M objects/s
float_array under the JIT and alloc_objects interpreted stayed level,
and int_loop under the JIT read 5% lower, inside the code layout band.

CppiaJitObjectArrayRead reads arrays of a script class, of Dynamic with
Ints, Bools, Floats, Strings, arrays, objects and nulls in it, of arrays
and of Null<Int>, in range and past either end, through fields and as
Dynamic, while one grows and after it shrinks, with Int, Bool, Float and
String arrays read as Dynamic beside them, as compiled code and as a
script interpreted and jitted, and checks that all three agree.

Tests: CppiaJitObjectArrayRead, test/regression/Cppia*, test/cppia
The cppia workloads each time one path against a host of one class, so
none of them had the shape of a real OpenFL script: objects that extend
a host display object and move through its Float properties, read from
an array, in a listener the host calls once a frame. bunny_update runs
the update loop of OpenFL's BunnyMark that way over 2,000 such objects,
ten frames a run, with a seeded generator in place of Math.random so the
interpreter and the JIT agree. HostSprite's setters mark it changed when
a value changes, as DisplayObject's do.

5 processes x 10 samples each, in two runs, in updates/s:
  JIT:          this branch 23.6M, main 629451b 20.0M
                this branch 21.3M, hxcpp 4.3.53 21.5M
  interpreted:  this branch 5.4M, main 5.4M
                this branch 4.6M, hxcpp 4.3.53 4.6M
each within the spread. A profile of the JIT puts about a third of its
time in the host property accessors: each read or write of x and y goes
through CallHaxe, the scriptable stub and the scriptable override's
check for a script override before it reaches the getter or setter.
A host with Lime or OpenFL compiled in, running the application as a
cppia script, should not be slower than HashLink running all of it, so
HashLink's JIT is the reference the cppia JIT is measured against.
bench/hl builds Script.hx and the bridge in bench/cppia/shared straight
to HashLink with a harness that times them as bench/src/Main.hx does,
and Run.hx's new --hl <path to hl> runs it in turn with the cppia hosts
on the cppia_jit_ benchmarks, requires the same checksums, and adds an
HL/JIT column and the JIT's ratio to it to the CPPIA table. The workload
table moves to bench/cppia/shared/CppiaWorkloads.hx, so both harnesses
time the same operations.

This branch's JIT against HashLink 1.16.0, 5 processes x 10 samples:
  int_loop          325M   335M iterations/s   ~0.97x
  float_array       115M  80.3M elements/s      1.43x
  alloc_objects    59.1M  22.0M objects/s       2.68x
  virtual_call      231M   199M calls/s        ~1.16x
  closure_call     46.0M   123M calls/s         0.38x
  native_call       283M   342M calls/s         0.83x
  native_callback  29.8M   131M callbacks/s     0.23x
  bunny_update     20.2M  59.4M updates/s       0.34x
Where the host's native code does the work, cppia is level or ahead. It
loses where calls cross between script and host, or reach a closure.
bunny_update is one loop over host properties. An OpenFL application's
frame does more: a stage broadcasts ENTER_FRAME to the display objects
with listeners, some given as closures, the script moves and replaces
objects and makes small ones as it goes, and the host renders the scene
by reading every transform. openfl_frame does that with host classes in
bench/cppia/shared shaped like OpenFL's EventDispatcher, DisplayObject
and DisplayObjectContainer: 1,000 script objects that extend the host's
display object, an ENTER_FRAME listener bound to the script, one object
in ten with a closure listener of its own, a small script object made
in each update, dead objects removed and replaced, ten frames a run.

5 processes x 10 samples, on the commit before this one:
  interpreted   3.0M object frames/s
  JIT           7.4M object frames/s, HashLink 1.16.0 5.7M (~1.29x)
The host's native dispatch and render make up for the script's calls
into it, so cppia is ahead of HashLink here while it trails it on
bunny_update.
Jitted code calling a closure called a helper, which checked the value
was a script closure taking the arguments as they are, made room for
any defaults, cleared and filled the frame, read the function's code,
and ran it, all for every call. Compared with HashLink's JIT, which the
same script calls a closure 2.7 times as fast in, that helper was most
of the cost.

Each script function now has two interned signatures: its arguments'
types, and those with its return type. Jitted code at a call site passes
its own, made from the arguments it has and the result it wants, to a
small helper that checks the value's vtable and its function's
signature, that the function is compiled and that its frame fits the
stack, writes this and the captured variables into the frame, and
returns the compiled code, which the call site calls as a direct call
does. The general way is kept for anything else: another kind of
function value, other types, defaults to fill, a function not compiled
yet, which compiles there and is called directly after.

bench --base <the commit before>, with HashLink 1.16.0, 5 processes x 10
samples:
  cppia_jit_closure_call   49.4M to 80.0M calls/s, HashLink 132M
  cppia_interp_closure_call stayed at 13.1M to 13.3M
virtual_call, int_loop and openfl_frame under the JIT stayed within
their spread.

CppiaJitClosureDirect calls one call site with closures of each
signature, bound methods, static and host functions and null in turn,
closures that change captured Ints, Floats, Strings, Bools and objects,
one that recurses through a captured variable, throws from closures
called directly and closures made in a loop, as compiled code and as a
script interpreted and jitted, and checks that all three agree.

Tests: CppiaJitClosureDirect, CppiaClosureCallTypes, CppiaJitLocalFunctions, CppiaJitLocalFunctionsDebugger
A script class that extends a host class gets objects of the host's
scriptable subclass, whose every virtual method checks the script vtable
for an override before it calls the host's own. Jitted code calling a
host method or property accessor on such an object went through the
stub the host generates, the virtual method and that check, every time.
BunnyMark's loop, which moves script objects through a host display
object's x and y, spent about a third of its time there.

When the call's static type is a script class, jitted code now compares
the object's C++ vtable with that class's host scriptable vtable and
reads the method's slot in its script vtable. An object of that class
whose script classes do not override the method has the host's method
called through the super stub, which calls it directly. Anything else,
a null object, another host class, a script override or a host
subclass's override, takes the stub as before.

bench --base <the commit before>, with HashLink 1.16.0, 5 processes x 10
samples:
  cppia_jit_bunny_update   26.9M to 37.3M updates/s, HashLink 63.8M
openfl_frame, native_call and virtual_call under the JIT, and
bunny_update interpreted, stayed within their spread.

CppiaJitHostMethods calls a host class's properties and methods, with
every argument and return type, through script classes with no
overrides, with their own, with an override inherited from a script
parent, with a super call, extending a host subclass that overrides in
native code, and through the host type with host objects mixed in, as
compiled code and as a script interpreted and jitted, and checks that
all three agree.

Tests: CppiaJitHostMethods
A script calling a host static function the host gives it no binding
for, as it does any method of an abstract over a host type, whose
implementation class is private, linked the call to the function's
Dynamic wrapper. Every Int, Float and Bool argument was boxed for it,
the result boxed back, and an Array argument converted with a
dynamic_cast, for each call. Reading and writing an openfl.Vector or a
Lime Matrix4 from a script went this way, at about a tenth of the speed
of a call through a binding.

In a scriptable build, STATIC_HX_DEFINE_DYNAMIC_FUNC now gives each
static function's wrapper a typed entry, made by templates in
hx/Scriptable.h from the function's own C++ signature: Int, Bool, Float
and String arguments and results are read and written in the script's
frame as they are, and any other type goes through Dynamic as the
wrapper converts it. The wrapper registers it the first time it is
asked for, so a host pays nothing for functions no script names, and a
name with overloads, which has no one address, keeps the wrapper alone.
A script linking a call by name finds the entry for the wrapper it got
and links to it as to a binding. An Array of the element type wanted is
known by its vtable and passed as it is; any other is converted as
before. The registration needs C++11 and is empty in other builds, and
objects built with older headers keep the wrapper.

bench --base <the commit before>, with HashLink 1.16.0, 5 processes x 10
samples, on the new call_by_name workload (an abstract over a host
array, with length, element reads and element writes):
  cppia_jit_call_by_name     27.9M to 166M calls/s, HashLink 228M
  cppia_interp_call_by_name  20.1M to 39.4M calls/s
native_call and bunny_update under the JIT stayed within their spread.
The bench's scriptable host is 147 KB (1.85%) larger; its native
executable is unchanged.

Macros.h was edited by hand along with Macros.tpl: regenerating it from
the template would drop a fix made to Macros.h alone.

CppiaStaticCallsByName calls an abstract's methods over a host type with
Int, Float, Float32, String, Bool, Array (exact and converted), Dynamic,
optional, Int64 and six arguments, a Void result and a throw, as
compiled code and as a script interpreted and jitted, and checks that
all three agree.

Tests: CppiaStaticCallsByName
The JIT compiled a cast whose value goes unused, such as cast(o, I) as
a statement, as its value alone, for every kind of cast. A cast to a
class or interface is a check that can fail, so one that failed ran on
under the JIT, where the interpreter and compiled code throw. It was so
in jitted methods before, and Haxe's unit suite met it once the JIT
compiled local functions: TestCasts.testInterfaces makes such casts in
closures, as exc(function() cast(v, I2)), and failed three assertions
under the JIT on this branch while passing on main.

Only the unused casts that cannot fail, to Dynamic and the unchecked
Int, Float, Bool and String conversions, are left out now. A cast to a
class or interface checks, and an array conversion runs, as the
interpreter's do.

CppiaJitUnusedCasts casts to an interface and to a class, passing and
failing, as statements in closures and in methods, used, and before a
statement that must not run, as compiled code and as a script
interpreted and jitted, and checks that all three agree. Without the fix
the jitted run let every failing cast through.

Tests: CppiaJitUnusedCasts
Haxe 4 makes a function value a Dynamic, so host code calling one, such
as sum += callback(i) in an engine compiled into a cppia host, went
through Dynamic::operator()(const Dynamic &): the Int was boxed for
__run, which the script closure unboxed into its frame.

hx/TypedCall.h adds a typed call, hx::callFunction<TResult>(f, args...),
with HXCPP_TYPED_CALLS to detect it. Its result is always what __run with
each argument boxed gives, converted to TResult as generated code
converts a Dynamic. For a script closure, known by its vtable, it calls
the cppia runtime with the arguments as they are and a signature code
fixed at compile time: a function that takes exactly those types and is
compiled runs as jitted code calling a closure directly runs it, and any
other pairing unboxes what it can and boxes the rest as __run did.
Dynamic::operator() of a scriptable build, and cpp::Variant's, which
calls through a field of an anonymous structure or a Dynamic use, take
calls of 1 to 5 arguments with a number, a Bool or a String among them
as their own types and call it. That template deduces each argument exactly, so it
is never worse than the overloads taking Dynamic and better for that
argument: no call becomes ambiguous, and calls with only objects, none
or more than 5 keep those overloads. No class changes its layout, so
code compiled against the older headers keeps calling through __run.

The vtable that tells a script closure, which each closure stored as it
was made, is now set once before main, for the header to read without
a lock, and the JIT's direct closure calls read the same.

The result is still boxed, as generated code uses it as a Dynamic. A
result type that boxes only when used as one would have to stand in for
Dynamic in every expression the generator writes around a call, and does
not: ((::String)(f(i))), a String joined to f(i) and f(i) == 3 fail to
compile or are ambiguous. Replacing the box with a cached one measured
it at about a third of such a call.

bench --base <the commit before> --hl, 7 processes x 10 samples each:
  cppia_jit_native_callback     34.3M to 50.0M callbacks/s, HashLink 169M
                                (0.20x to 0.30x of it)
  cppia_interp_native_callback  14.8M to 16.1M callbacks/s
  cppia_jit_bunny_update, openfl_frame, closure_call and int_loop
  stayed within their spread.

CppiaHostClosureCalls has host code call closures with Int, Float, Bool,
String, Dynamic, Null<Int>, Array and object arguments, each C++ number
type, mixes of them, five, six and more than five arguments, defaults,
throws, bound methods, static functions, a null function, nested calls,
calls through anonymous and Dynamic fields and collections between calls, and hx::callFunction with every result
kind from closures of each return type. It prints the same lines with
compiled closures and with script closures interpreted and jitted, and
the same lines as the commit before for every call it could make.

Tests: CppiaHostClosureCalls, test/regression, test/cppia, test/haxe,
test/std, Haxe 4.3.7 tests/unit as cpp, as scriptable cpp and as cppia
interpreted and jitted, OpenFL's BunnyMark built scriptable with --dce no.
tests/unit fails Issue10830 as cpp, as it does on main.
host_sort: Array.sort, which is host code, sorts a copy of a 1000-element
Array<Int> ten times a run with a comparator the script gives it, as a
game sorts its own values by a key. It counts sorted elements. Bench
only.
Array.sort of plain values boxes each value once and calls the
comparator with the boxes (libhxcpp #256), so a cppia script comparator
unboxed both arguments again for every comparison, and its result was
boxed for sort to read back.

In a scriptable build, a comparator that is a script closure whose
function takes two values of the element type now gets the values
themselves, through hx::callFunction, and one that returns an Int has its
result read as it is, which is what __ToInt of its box gave. The sort
takes the same steps as through the boxes, the same insertion runs and
the same merges on the values in place of an index, so the comparator is
asked about the same pairs in the same order and the array ends in the
same order, whatever it answers. hx::scriptClosureResultKind, in
hx/TypedCall.h, tells such a closure and what it returns, with one more
hook the cppia runtime sets before main. A comparator taking other
types, a host function, and arrays of Int64s, objects and Strings sort
as before.

bench --base <the commit before> --hl, 7 processes x 10 samples each:
  cppia_jit_host_sort     3.80M to 7.54M sorted elements/s, HashLink 17.4M
                          (0.22x to 0.43x of it)
  cppia_interp_host_sort  2.91M to 3.92M sorted elements/s
  cppia_jit_int_loop stayed within its spread.

CppiaHostSortComparators sorts Int, Float, Bool, UInt8 and Float32
arrays, short ones and ones longer than a run of the merge, with
comparators that count their calls, list the pairs they are asked about,
answer at random, collect garbage, throw, grow the array, take Dynamic or
Float arguments, return a Float or a Bool, are bound methods or static
functions, or are a host function. It prints the same lines with
compiled comparators and with script comparators interpreted and jitted,
and the same lines as the commit before.

Tests: CppiaHostSortComparators, test/regression/Cppia*, test/cppia,
test/haxe, test/std, Haxe 4.3.7 tests/unit as scriptable cpp and as cppia
interpreted and jitted, OpenFL's BunnyMark built scriptable with --dce no.
tests/unit fails Issue10830 as cpp, as it does on main.
A script closure copies the variables it captures into the frame of
every call, and out of the frame that makes it. For each capture it went
from the closure to its function, to the function's captured variables,
to the variable for its offsets and to a table for its size, and called
memcpy with that size. In a profile of the host calling a jitted closure
back (native_callback), that copy was the largest single item, ahead of
boxing the result.

The function now keeps a flat list of where each capture sits in the
closure, in its own frame and in the frame that makes it, and how big it
is, set when it links. The copies walk that list and move each capture
by its size, which the compiler turns into a move or two.

Against 818b6e9, the two bench hosts alternating on one pinned core at
high priority, 12 processes x 10 samples each, with HashLink 1.16.0:
  cppia_jit_closure_call     99.7M to 113.2M calls/s, HashLink 175M
  cppia_jit_native_callback  49.2M to 51.6M callbacks/s, HashLink 172M
host_sort, alloc_objects and int_loop under the JIT, and closure_call
and native_callback interpreted, stayed within their spread.

CppiaClosureCaptures makes closures that capture every kind and size of
variable, first read after variables of the closure's own so they sit at
other offsets in the frame than in the closure, twelve at once at odd
multiples of 4, written by the closure and by the code that made it,
nested, made in a loop, of a method, and kept through a collection. It
calls them directly, through a Dynamic, by reflection and from host
code, as compiled code and as a script interpreted and jitted, and
checks that all three agree. With the frame offset swapped for the
closure's, it crashes.

Tests: CppiaClosureCaptures
hx::callFunction runs a script closure through CppiaClosure::typedCall.
The path a callback takes, a compiled function taking exactly the
arguments given, shared one function with the general path, so every
call saved the registers that path needs, zeroed the this slot that
enterFrame then wrote, and called out to enterFrame for the captures,
to writeTypedResult for the result and to boxResult for its box.

typedCall now holds only that path, with the capture copy and the result
written in line. The general path is typedCallGeneral, and the throw of
an exception compiled code left is throwPending, both kept out of line.
Each argument, capture and result is handled as before.

Against 7f2efdd, the two bench hosts alternating on one pinned core at
high priority, 12 processes x 10 samples each, with HashLink 1.16.0:
  cppia_jit_native_callback  52.1M to 59.8M callbacks/s, HashLink 176M
  cppia_jit_host_sort        7.93M to 8.68M sorted elements/s, HashLink 18.9M
closure_call and int_loop under the JIT, and native_callback and
closure_call interpreted, stayed within their spread.

CppiaHostClosureCalls, CppiaHostSortComparators and CppiaClosureCaptures
call script closures from host code with every argument and result kind,
captures of every kind, exceptions and the general path, as compiled
code and as a script interpreted and jitted, and check that all three
agree.

Tests: CppiaHostClosureCalls, CppiaHostSortComparators, CppiaClosureCaptures
main adds the host_statics cppia workload, which joins the shared
workload table here, so the cppia and HashLink harnesses both run it.
This branch's Changes.md lines move under libhxcpp 6.1.0, and main has
the unused cppia cast fix (#501) under 6.0.3.
Jitted code calling a host method, such as a display object's x and y
accessors, went through the method's script stub: the object and the
arguments went into the script frame, a helper called the stub so that
what it threw could be caught, the stub read them back out, called the
method and wrote the result to the frame, and the jitted code read it
from there. In a profile of BunnyMark's update loop that was about a
quarter of the time, with more spent setting it up in the jitted code.

In a scriptable build each instance method's Dynamic wrapper
(HX_DEFINE_DYNAMIC_FUNC, in Macros.h and Macros.tpl) now makes typed
entries for a method that takes up to three Ints, Bools, Floats or
objects and gives one of those or nothing: one calling the method
virtually, as the stub does, and one calling the class's own, as the
stub for a super call does. A C++ class with pure virtual methods, such
as the runtime's IteratorBase, gets no super entry. The entries convert
values as the stub does, check for a null object under
HXCPP_CHECK_POINTER, and leave what the method throws in the context, as
the helper does. A name with overloads gets none. A scriptable class
gives the runtime its methods' entries as it registers, and a call links
to the entry of the method it finds when the signatures agree.

Jitted code then passes the object and the arguments in registers. On a
script class extending the host class, where the object is of that class
and no script class overrides the method, it calls the super entry,
where fdd330c called the super stub; otherwise the virtual one. Interpreted calls, a method with a String or more than three
arguments, and code compiled against older headers take the stub.

Against 6862d3e, the two bench hosts alternating on one pinned core at
high priority while other builds were running, 10 processes x 10 samples
each:
  cppia_jit_bunny_update  31.3M to 48.7M bunny updates/s, HashLink 1.16 62.9M
  cppia_jit_openfl_frame  9.45M to 10.15M object frames/s
int_loop under the JIT and bunny_update interpreted stayed within their
spread. The bench's scriptable host is 110 KB larger (1.4%).

CppiaHostMethodEntries calls host methods taking and giving every kind
an entry takes, and some it does not, on host objects, a host subclass
with C++ overrides, script classes with and without overrides and with
super calls, through the host class's type and the script classes'
types, with host code calling back into the script, a throw and a null
object, as compiled code and as a script interpreted and jitted, and
checks that all three agree. With the Int entries changed to add one,
only the jitted run differs.

Tests: CppiaHostMethodEntries
A script's call of a host static function, bound or by name, still went
through a script stub: the arguments into the frame, the helper that
catches what the stub throws, the stub reading them back and writing
the result to the frame.

Each static function's Dynamic wrapper, which already registers a typed
stub for the function (12e3bb9), now also registers a typed entry for a
function that takes up to four Ints, Bools, Floats or objects and gives
one of those or nothing, made from the function's own C++ signature with
the conversions the method entries use. A static call links to it, for a
function the host binds as well as one called by name, when its
signature agrees, and jitted code passes the arguments in registers. The
entry leaves what the function throws for the script, as the helper does.

Against 695a02d, the two bench hosts alternating on one pinned core at
high priority while other builds were running, 10 processes x 10 samples
each, with HashLink 1.16.0 (slower than usual under the same load):
  cppia_jit_native_call   291M to 366M calls/s, HashLink 323M
  cppia_jit_call_by_name  135M to 191M calls/s, HashLink 241M
int_loop and bunny_update under the JIT stayed within their spread.

CppiaHostMethodEntries now also calls host static functions taking and
giving every kind an entry takes, five arguments and a String, which it
does not, objects and null, a throw, and a jitted loop, as compiled code
and as a script interpreted and jitted, and checks that all three agree.
With the Int entries changed to add one, only the jitted run differs.

Tests: CppiaHostMethodEntries, CppiaStaticCallsByName
Jitted code calling a host method through its typed entry still laid the
call out for a stub: it stored the object into the frame and read it
back for the receiver checks and again for the call, set the context's
frame, and stored the result into the frame for genFunctionResult to
read back. In BunnyMark's loop each of those trips through memory sits
on the chain from one property access to the next.

Where every way the call can go is a typed entry, so no stub reads the
frame, a call with no arguments now evaluates its object straight into
the register the entry takes it in, the receiver checks and the call use
that register, the context's frame is left as it is, and the result is
converted from the register the entry gives it in, after the same
exception check. A call with arguments still has its object in the frame
while they are evaluated, and reads it once. A call that can reach a
stub is laid out as before.

Against 20dc636, the two bench hosts alternating on one pinned core at
high priority while other builds were running, 10 processes x 10 samples
each. bunny_update ran in two speed groups on both hosts, so its gain is
the faster groups' (57-59M to 66-71M); one process of the harness gave
69.2M where HashLink 1.16 gave 62.9M on a quiet machine earlier:
  cppia_jit_bunny_update  about 1.18x
  cppia_jit_native_call   458M to 536M calls/s
openfl_frame and int_loop under the JIT stayed within their spread.

CppiaHostMethodEntries now also calls host methods on this without
naming it, from a script class's own method.

Tests: CppiaHostMethodEntries, CppiaJitHostMethods
Every Int or Float a Dynamic holds is boxed, as Haxe 4 code does for the
result of any call through a function value: a host calling back a
script closure that returns an Int boxes the result for the host. The
box came from new, through IntData's operator new, hx::Object's, and
ImmixAllocator::alloc, which the compiler left as calls, so a profile of
native_callback showed five frames for each box.

ImmixAllocator::alloc now calls allocInline, which holds its body and is
always in line, so alloc's code is the same for generated code. The
runtime's Int and Float boxes use allocInline directly. Ints from -1 to
1023, where the shared boxes stopped at 255, are boxed once and shared.
A whole Float still boxes as an Int from -1 to 255 only: Type.typeof and
Std.isOfType tell an Int box from a Float box, so a whole Float of 300
keeps its Float box.

Against f417921, the two bench hosts alternating on one pinned core at
high priority, 12 processes x 10 samples each:
  cppia_jit_native_callback     58.1M to 68.7M callbacks/s
  cppia_interp_native_callback  18.2M to 19.7M callbacks/s
The workload's results run from 0 to 2046, so about half are in the
shared range now. closure_call and int_loop under the JIT stayed within
their spread.

CppiaDynamicBoxes prints the type, Std.isOfType and value of Ints and
Floats on each side of each edge, as results of script callbacks the
host holds as Dynamic and as values the script boxes, and keeps
thousands of boxes through a collection, as compiled code and as a
script interpreted and jitted, and checks that all three agree.

Tests: CppiaDynamicBoxes
Jitted code calling a script closure whose function takes the arguments
and gives the result as the call has them called enterScriptClosure on
every call: a native call that checked the value was a script closure,
that its function's signature was the call's, that the function was
compiled and that its frame fit the stack, wrote this and the captured
variables into the frame, and gave back the compiled code for the call
site to call. The checks and copies are a few loads and stores each,
and the native call around them, with its arguments, saved registers
and return, was most of what it cost.

The call site now emits the same checks in the same order, and each
one that fails jumps to the general way, as a 0 from the helper did. A
call that wants no result can only match the function's signature of
its arguments, and any other only its full signature, so the call site
compares the one it can match. When it links, the function keeps its
captures again as moves of a word, then the moves of the 4 bytes some
captures have past their last word, each part ended by a move with a
stackPos of -1. The call site copies this, walks the two parts with a
move each, and calls the compiled code. enterScriptClosure is gone.

Against 6862d3e, the two bench hosts alternating on one pinned core at
high priority, 12 processes x 10 samples each:
  cppia_jit_closure_call     32.4M to 35.8M calls/s
The machine ran most processes at about a third of its usual speed
through every run (int_loop gave 150M iterations/s where it gives about
460M). Four other runs gave the same 1.10x to 1.12x, and in those runs
the processes that ran at more than twice that speed gave a median of
101M to 110M.
native_callback and int_loop under the JIT, and closure_call
interpreted, stayed within their spread. HashLink was not measured.

CppiaJitClosureEntry calls closures with no captures, with one of each
kind and size, with only Ints, with only whole words, and with both
after an argument of each kind, through one call site in turn with
bound methods, a closure of a method and a static function, and
through a field. It calls them with types that are not the function's,
with the result not used, as null and as a host function, throwing
through one closure and two, recursing on their first call, from a
small frame into a large one past where the script stack was first
committed, and after a collection, as compiled code and as a script
interpreted and jitted, and checks that all three agree. With the
moves of 4 bytes left out it prints other numbers, and with the copy of
this left out it crashes. CppiaJitClosureEntryDebugger runs the same
with HXCPP_DEBUGGER.

Tests: CppiaJitClosureEntry, CppiaJitClosureEntryDebugger
closure_expr calls a closure whose Int result is an operand of %, as
fib(n - 1) + fib(n - 2) uses one. Haxe 4.3.7 writes a closure call to
cppia without a result type and a function type as Dynamic, so the
operator takes the result as a Dynamic, and the arithmetic after it is
Dynamic too. closure_call, whose result goes straight into an Int,
takes the typed call.

Under the JIT it runs at 42M calls/s where HashLink 1.16 runs it at
309M; closure_call runs at 127M against HashLink's 165M. Calling the
closure directly and boxing its result left closure_expr level, so the
gap is the Dynamic arithmetic, which a result type in the cppia the
compiler writes would remove.
script_map maps and filters 1,000 Ints with closures, ten times a run.
Haxe 4.3.7's Array.map and filter are @:runtime inline, so they compile
into the script as loops calling the closures, which take the script's
direct closure calls; the runtime's own map and filter are reached only
through Dynamic. Under the JIT it runs at about 367M calls/s where
HashLink 1.16 runs it at about 138M.
Array.sort calls a script comparator through hx::callFunction for every
comparison, and each call found the thread's context, checked that the
closure takes the values as they are, is compiled and has room for its
frame, and saved and restored the context's stack, before it put the
values in and ran the compiled code.

hx::TypedCallRun, in hx/TypedCall.h, makes those checks once for a run of
calls of one function value, through a runtime hook the cppia runtime
sets before main, and each call then puts the values and the captured
variables in the frame, runs the compiled code and puts the context back
before it returns or throws. A call made from deeper in the stack than
the run began, as one from inside the comparator is, and any function
value the run cannot take, are called as before. The sort's typed
comparator uses it.

Array.map and filter are left as they are: Haxe 4.3.7 inlines them into
the caller as loops, so the runtime's own are reached only through
Dynamic.

Against ce4bc1a, the two bench hosts alternating on one pinned core at
high priority, 12 processes x 10 samples each:
  cppia_jit_host_sort  7.73M to 8.89M sorted elements/s
host_sort interpreted and int_loop under the JIT stayed within their
spread.

CppiaHostSortRuns sorts with comparators made in a loop with captures of
their own, one counting its calls, sorts inside a comparator and inside
a closure, Floats, a comparator that throws part way and is used again,
collections inside the comparator, and long jitted sorts, as compiled
code and as a script interpreted and jitted, and checks that all three
agree. With the run's copy of the captures left out, the jitted run
fails.

Tests: CppiaHostSortRuns, CppiaHostSortComparators
@dimensionscape dimensionscape changed the title Faster cppia closures, callbacks and object array reads, with HashLink in the bench Faster cppia host calls, closures and callbacks under the JIT, with HashLink in the bench Nov 29, 2026
Jitted cppia code took every Dynamic operand of an operator through a
native helper. A conversion to Int or Float called objToInt or
objToFloat, which made the box's virtual __ToInt or __ToDouble call, and
so did the checked cast to Float that Haxe 4.3.7 writes around a Dynamic
operand of -, * and /, after a call to safeBasicCast. % on a Dynamic
converted both operands to Floats and called fmod, a compare boxed the
other operand and called dynamicCompare, and + boxed it and called
Dynamic's operator+. Haxe 4.3.7 gives a script's closure calls a Dynamic
result, so closure_expr's (sum + f(i) % 1000) & 0xffffff took fmod and a
virtual call for every call: a profile showed fmod as a quarter of its
time.

The runtime now publishes the vtables of its Int and Float boxes, and
where each keeps its value, before main, as it does the script
closure's. Jitted code compares an operand's vtable with them and reads
the value in line in the conversions to Int and Float, in the checked
casts to Int (an Int box) and to Float (an Int or a Float box), and in:
  % on Ints in boxes, and an Int and an Int in a box, which divides as
    Ints, with fmod's sign on a remainder of 0, so -4 % 2 is still -0;
    divisors 0 and -1 take fmod
  compares, two Ints as Ints and other numbers as Floats, as hx::IsLess
    and the others compare them
  +, two Ints with a wrap and other numbers as Floats, as Dynamic's +
    adds them; a Float not yet in a box goes the general way, as it
    boxes as an Int when it is whole and below 256
Null, Bools, Strings, Int64s and other objects take the helpers as
before, with the other operand boxed as before.

Against 5fa2bef, base and branch alternating with HashLink 1.16 on one
pinned core at high priority, 10 rounds of one process each x 10
samples. The machine ran each process at one of a few speeds a step of
about 2x apart (int_loop gave 83M to 557M iterations/s), which left the
medians of pinned_ab.py meaningless (closure_expr 11.4M to 13.6M,
interpreted closure_expr, which is unchanged, 1.47x). In the speed most
processes ran at, where HashLink ran closure_expr at 69M to 72M calls/s,
and in a faster one, where it ran at 182M to 198M:
  cppia_jit_closure_expr  10.2M to 13.6M calls/s (1.33x), and
                          28.1M to 35.0M (1.25x)
HashLink is 5.2x to 5.3x ahead, where it was 6.5x to 7.0x.
closure_call (101M to 100M), native_callback (11.2M to 11.2M, 20.1M to
20.2M) and int_loop (151M to 151M) under the JIT, and closure_expr
interpreted (5.3M to 5.3M), stayed level in the same speeds. A profile
of closure_expr after the change has no fmod or virtual calls left;
about two thirds of its time is the call of the closure, which takes
the general way, as the call wants a Dynamic result and the closure
gives an Int.

CppiaJitDynamicNumbers takes Ints in and out of the shared boxes, whole
Floats boxed as Ints and from 256 on as Floats, other Floats, -0, NaN,
the infinities, null, Strings, Bools and Int64s in Dynamics, through
conversions to Int and Float, bit operations and shifts, -, *, / and
negation, % with Ints, Dynamics and Floats on either side, divisors 0
and -1, compares with Dynamics, Ints, Int variables and Floats, + with
Ints and Dynamics kept as a Dynamic, an Int and a Float, Int overflow,
and loops of closure results and Dynamic variables long enough to
collect their boxes, as compiled code and as a script interpreted and
jitted, and checks that all three agree, with the output of 5fa2bef.
With the value of an Int box read 4 bytes past it, the jitted run gives
other numbers on 19 of its lines (an Int box read as 0); without the
sign of a remainder of 0 it prints 0 for -0 on 8; with a Float box
read 4 bytes off in the conversion to Float it prints denormals for
0.5 and -2.5.

Tests: CppiaJitDynamicNumbers, the other test/regression/Cppia* tests, test/cppia with and without -jit
Haxe 4.3.7 writes a call through a function value to cppia with no result
type, so a closure call whose result is an operand of an operator, as in
fib(n - 1) + fib(n - 2) or f(i) % 1000, or goes into a Dynamic, wants an
object. Jitted code took the direct call only when the closure's function
gave the result as the call wanted it, so every such call of a closure
returning an Int, a Float, a Bool or a String went the general way,
through runJit, runInFrame and a box.

A call that wants an object now takes the direct call for a closure whose
function takes the arguments as they are, whatever it returns, and boxes
the result in the frame as the general way boxes it. A Void function's
call still goes the general way. Tried before f9f36f2 this changed
nothing, since fmod in the Dynamic % took the time; with the boxes read
in line, the call was most of what was left.

Against f9f36f2, the two bench hosts alternating on one pinned core at
high priority, 12 processes x 10 samples each, the machine in one of its
slower phases:
  cppia_jit_closure_expr  36.5M to 71.3M calls/s
closure_call and int_loop under the JIT stayed within their spread.

CppiaJitClosureDynamicResults calls closures returning Ints small and
large, Floats, Bools, Strings, Arrays and Null<Int>, as Dynamic values,
through Std.string and Type.typeof and as operands of operators, a
closure whose function takes other arguments, and a recursive local
function, as compiled code and as a script interpreted and jitted, and
checks that all three agree. With the boxed Int off by one, the jitted
run's values and operands differ.

Tests: CppiaJitClosureDynamicResults
Every local of a jitted function lived in its frame slot, so the
counters and sums of a loop went through memory on every use: an
assignment stored to the slot and the next statement loaded it back, a
store-to-load forward on the critical path of each iteration.

A function's own Int and Float locals, its arguments and any variable a
closure shares left out, now live in sljit's saved registers, as many as
the platform leaves after the scratch registers and the context, frame
and this, and Floats in its saved float registers. The first pass over
the function counts each local's uses, a use in a loop counting eight
times one outside it, to three deep, and the most used, with a weight of
three or more, get the registers. When any do, a second pass measures
the code as it will be generated, and if that needs more scratch
registers than the first left room for, every local stays in its slot.
Saved registers keep their values across native calls and script calls,
and across an exception, which jitted code hands back in the context
rather than unwinding. A compound assignment to a local in a register
works on it in place, unless finding its value writes the same local,
which the first pass sees, since the interpreter reads the local first.
32-bit x86, where sljit keeps saved registers past the third in memory,
and builds with HXCPP_DEBUGGER or HXCPP_STACK_SCRIPTABLE, whose debugger
reads every local from the frame, keep them all in the frame, and x86-64
outside Windows keeps its Floats there, as its calling convention saves
no float register.

Three things values in registers make more likely are fixed with it: an
enum parameter of another kind read into a Float register was written
to a temporary and lost, a native call taking two Floats from registers
freed only one of their temporaries, and the generating pass now starts
its temporaries where the measuring passes do.

Against 5fa2bef, the two bench hosts alternating on one pinned core at
high priority, 10 processes x 10 samples each, with HashLink 1.16's JIT:
  cppia_jit_int_loop       150.7M to 197.3M iterations/s  (HL 143.7M)
  cppia_jit_float_array     49.4M to 59.3M elements/s     (HL 24.5M)
  cppia_jit_virtual_call    75.0M to 103.1M calls/s       (HL 78.4M)
  cppia_jit_closure_call    36.3M to 39.5M calls/s        (HL 48.9M)
  cppia_jit_alloc_objects   21.6M to 22.7M objects/s      (HL 7.1M)
  cppia_jit_bunny_update    18.6M to 18.0M updates/s      (HL 17.1M)
  cppia_jit_host_sort       2.69M to 2.67M elements/s     (HL 5.23M)
The machine ran every process at about a third of its usual speed, the
HashLink runs included, so the ratios are what to compare. native_call
went from 158.5M to 216.2M calls/s in the same kind of run, and
interpreted runs stayed within their spread.

CppiaJitLocalRegisters runs Int and Float locals in loops, nested loops,
break and continue, try/catch with a throw from a host call and from a
script call between writes, an Int catch variable, switch, locals live
across native calls, recursion, more locals than registers, captured
variables next to locals in registers, every compound assignment and
increment, compound assignments whose value writes their own target,
conversions between Floats, Ints and Dynamic, enum parameters, a local
function and a member function, as compiled code and as a script
interpreted and jitted, and checks that all three agree.
CppiaJitLocalRegistersDebugger runs the same with HXCPP_DEBUGGER. With
the register left unwritten after a compound assignment made on a
temporary, the jitted compound and value lines change; with the check
for a value writing its own target ignored, the jitted run takes C++'s
order; and with captured variables given registers, the closure reads a
stale value and the captured line changes.

Tests: CppiaJitLocalRegisters, CppiaJitLocalRegistersDebugger
An arithmetic, bitwise or comparison operator under the JIT found its
left operand into a temporary on the stack, then its right into a
scratch register, and read the temporary back, so with its locals in
registers a loop such as int_loop's still stored and loaded each left
operand, and put each constant in a register first.

An expression can now give itself as an operand that takes no code to
find: an Int constant as an immediate, a number wanted as a Float from
where the constant keeps it, and an Int or Float local, in its register
or frame slot, or field of this. When the right operand is one, nothing
runs between finding the left and the operator, so both are read in
place, the left found into a scratch register if it takes code. When
the right takes code, the left is read in place after it if the left is
a constant or a local and finding the right writes no local, which the
first pass over the function sees; not a field of this, which a call
can change. Otherwise the left goes through the temporary as before. A
compound assignment reads such a value in place too.

Against the previous commit, the two bench hosts alternating on one
pinned core at high priority, 10 processes x 10 samples each, with
HashLink 1.16's JIT:
  cppia_jit_int_loop       197.3M to 215.7M iterations/s  (HL 143.7M)
  cppia_jit_float_array     59.3M to 77.6M elements/s     (HL 24.5M)
  cppia_jit_virtual_call   103.1M to 120.3M calls/s       (HL 78.4M)
  cppia_jit_closure_call    39.5M to 45.6M calls/s        (HL 48.9M)
  cppia_jit_alloc_objects   22.7M to 24.2M objects/s      (HL 7.1M)
  cppia_jit_bunny_update    18.0M to 19.2M updates/s      (HL 17.1M)
  cppia_jit_host_sort       2.67M to 2.73M elements/s     (HL 5.23M)
The machine ran every process at about a third of its usual speed, the
HashLink runs included, so the ratios are what to compare.
native_callback went from 20.1M to 21.4M callbacks/s in the same kind
of run, and interpreted runs stayed within their spread.

CppiaJitOperands runs each operator with constants, locals and fields of
this on each side, Int and Float constants as Float operands, shifts by
constants and by locals, Int and Float comparisons with a constant on
either side and with NaN, mixed Ints and Floats, a left that writes the
right and a right that writes the left as Haxe gives them to the
script, rights that take calls and array reads, locals in registers and
in the frame, compound assignments of constants and locals, and
statics, as compiled code and as a script interpreted and jitted, and
checks that all three agree. With the left read in place whatever
finding the right writes, the jitted run reads the left after the right
changed it, and with an operand read from its frame slot while the local
is in a register, the jitted run reads garbage and fails.

Tests: CppiaJitOperands
A jitted function that made a native call on a 64-bit platform declared
four scratch registers more than it used, as shadow space for the call.
sljit 0.95 keeps that space in every frame on 64-bit Windows itself, and
the arguments of a call are already counted as the registers they go
in, so the extra ones bought nothing. On 64-bit Windows two of them are
callee-saved, which the function then saved and restored on every call,
and they took registers its locals could have had: a function making
calls kept three locals in registers there instead of five.

A function declares the scratch registers it uses, and at least one.

Against the previous commit, the two bench hosts alternating on one
pinned core at high priority, 10 processes x 10 samples each, with
HashLink 1.16's JIT:
  cppia_jit_virtual_call   120.3M to 129.8M calls/s       (HL 78.4M)
  cppia_jit_float_array     77.6M to 81.5M elements/s     (HL 24.5M)
  cppia_jit_closure_call    45.6M to 46.9M calls/s        (HL 48.9M)
  cppia_jit_alloc_objects   24.2M to 24.9M objects/s      (HL 7.1M)
  cppia_jit_bunny_update    19.2M to 19.5M updates/s      (HL 17.1M)
  cppia_jit_int_loop       215.7M to 215.9M iterations/s  (HL 143.7M)
  cppia_jit_host_sort       2.73M to 2.75M elements/s     (HL 5.23M)
The machine ran every process at about a third of its usual speed, the
HashLink runs included, so the ratios are what to compare. int_loop
makes no call in its loop. call_by_name went from 84.8M to 88.2M calls/s
in the same kind of run.

CppiaJitScratchRegisters keeps locals in every saved register the
platform leaves across host methods taking their object and three Ints,
Floats or both in registers, host statics taking four and five, a host
method throwing, script calls, Math calls and recursion, and runs a
function with no call, as compiled code and as a script interpreted and
jitted, and checks that all three agree. With the arguments of a host
call left out of the count, sljit stops the jitted run.

Tests: CppiaJitScratchRegisters
Host code calling a compiled script closure, through hx::callFunction as
Dynamic::operator() does or through a run of typed calls as Array.sort
does, went through one C++ function for every closure. It read each
argument's kind from the kinds code and pushed it, walked the capture
list, called the compiled code through a pointer and switched on the
result's kind. Profiling host_sort under the JIT put 46% of the time in
that function, 36% in the sort itself and 15% in the comparator.

The JIT now makes an entry for a function and the kinds of a call's
arguments and result, on the first such call: it puts the arguments,
this and the captured variables in the frame with moves at known
offsets, calls the compiled code directly, and writes the result,
boxing it where the call wants an object. hx::TypedCallRun calls the
entry from the header, and typedCall looks it up on the function. A
call the entry does not make, on a stack that has to grow first, goes
the typed call's way as before, and an exception it leaves is thrown
there. A result the typed call converts another way, such as an Int
wanted from a Float function, has no entry. A function keeps entries
for at most 8 kinds codes.

Against c3d45af, the two bench hosts and HashLink 1.16 alternating on
one pinned core at high priority, 7 processes x 10 samples each:
  cppia_jit_host_sort        6.58M to 11.94M sorted elements/s (1.81x),
                             1.06x of HashLink's 11.31M
  cppia_jit_native_callback  44.6M to 46.2M calls/s (1.04x)
Two later runs of the final build, on a noisier machine, gave host_sort
1.86x and 1.98x. closure_call, call_by_name, bunny_update and int_loop,
which do not use entries, stayed within their spread. closure_expr gave
0.91x in one run, so the box helper jitted closure calls use, which now
shares its switch with the entries, is forced in line as it was; two
later runs gave 1.02x and 1.12x.

CppiaHostRunEntries calls closures from host code with captured
variables of each size and this, sorts Ints, Floats and Bools with
comparators that capture them, sorts with a method, has results boxed
for Haxe 4 host code, calls one function with more kinds of call than
it keeps entries for, throws part way through calls, and recurses
through the host deeper than the script stack first commits, so the
entry leaves a call to the typed call, which grows the stack; the JIT
run goes first, before the interpreted run has grown it. Compiled,
interpreted and jitted, all three agree. Skipping the capture copies,
reading this one word off, counting a Float argument as 4 bytes, or
claiming the too-deep call as made each fail it.

Tests: CppiaHostRunEntries
main adds Array and String indexOf and lastIndexOf overloads for a start read from a Dynamic field (#506), the CppiaAdoptInstances fix (#507) and 6.0.4's section of Changes.md, which goes under this branch's 6.1.0 lines.
CI on 50496e7 failed five tests this branch added, on Linux 64, macOS
arm64 and the three sanitizer jobs, while Windows passed. On each
platform their compiled, interpreted and jitted runs agreed with each
other, but they printed values that depend on the C++ compiler:

- CppiaJitLocalRegisters, CppiaJitLocalRegistersDebugger and
  CppiaJitScratchRegisters printed floats from multiplies by inexact
  constants that feed an add. GCC on the Ubuntu 26.04 runner and Apple
  clang fuse those into one rounding, where MSVC and cppia round twice,
  so compiled code, and the host methods the scripts call, printed
  other last digits, and a sum taken as an Int moved further.
- CppiaJitDynamicNumbers converted Strings such as "10000000000null" to
  Int, which goes through atoi: MSVC's saturates past an Int, glibc's
  wraps.
- CppiaJitOperands shifted by 131 in compiled code, which C++ leaves
  undefined, so UBSan stopped it.

The float cases now multiply by powers of two, so each product is exact
and a fused multiply-add gives what two roundings give; what is left
inexact comes from divisions and square roots, which are never fused.
DynamicNumbers leaves out the ten Strings whose number does not fit an
Int. The shift count is masked to 5 bits, as the hardware did, so that
test prints what it did before.

Built with MSVC fusing multiply-adds (/arch:AVX2 /fp:contract), which
changed a line of CppiaJitLocalRegisters before this, both float tests
print the same as the plain build. Exact results also keep them right
with x87 arithmetic on Linux 32.

Tests: CppiaJitLocalRegisters, CppiaJitLocalRegistersDebugger,
CppiaJitScratchRegisters, CppiaJitDynamicNumbers, CppiaJitOperands
On 78fa893 the test still failed on macOS arm64. A Float past an Int,
or not a number, taken as an Int through a Dynamic is a plain C++ cast,
which x86 makes -2147483648 and arm64 saturates, with NaN giving 0.
Compiled code, the interpreter and the JIT agreed with each other on
each platform, as before; Std.int was not affected, since the runtime
defines its conversion.

The test now leaves those conversions out, as it does a String whose
number is past an Int, in its to Int, bits, Dynamic + Int and as Int
lines, and its closure results use only values that fit an Int. Every
value the macOS run printed differently is now one of those left out.
Int64s still convert, by truncation, which is the same everywhere.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant