From 0c218494abbfe1ca7f8eb52fb51a30a7bc2a9bff Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 17:03:10 -0500 Subject: [PATCH 01/23] Compile a cppia script's local functions under the JIT 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 629451b2, 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 --- Changes.md | 2 + src/hx/cppia/Cppia.h | 4 + src/hx/cppia/CppiaFunction.cpp | 29 +++- src/hx/cppia/CppiaModule.cpp | 7 + .../regression/CppiaJitLocalFunctions/Main.hx | 142 ++++++++++++++++++ .../CppiaJitLocalFunctions/Script.hx | 123 +++++++++++++++ .../CppiaJitLocalFunctions/build.hxml | 7 + .../CppiaJitLocalFunctions/stdout.txt | 39 +++++ .../CppiaJitLocalFunctionsDebugger/build.hxml | 10 ++ .../CppiaJitLocalFunctionsDebugger/stdout.txt | 39 +++++ 10 files changed, 398 insertions(+), 4 deletions(-) create mode 100644 test/regression/CppiaJitLocalFunctions/Main.hx create mode 100644 test/regression/CppiaJitLocalFunctions/Script.hx create mode 100644 test/regression/CppiaJitLocalFunctions/build.hxml create mode 100644 test/regression/CppiaJitLocalFunctions/stdout.txt create mode 100644 test/regression/CppiaJitLocalFunctionsDebugger/build.hxml create mode 100644 test/regression/CppiaJitLocalFunctionsDebugger/stdout.txt diff --git a/Changes.md b/Changes.md index e52f55d48..78437de3b 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,8 @@ libhxcpp 6.0.3 (unreleased) ------------------------------------------------------------ +* The cppia JIT compiles a script's local functions, the closures written inside a function or an initializer, as it compiles class functions, when each is first called. No class holds them, so they were never compiled: under the JIT their bodies ran in the interpreter, whether jitted code called them or the host called them back. Jitted code calling a closure is 1.9x faster (closure_call), and the host calling one back 2.5x (native_callback). HXCPP_CPPIA_EAGER_JIT compiles them as the module loads, with the rest (HaxeFoundation/hxcpp#1213) + libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 8b1f8bd81..9e0830e10 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -466,6 +466,10 @@ class CppiaModule std::vector< std::string > linkMisses; ScriptCallable *main; + // Every function the module links. Classes compile their own functions, but + // a local function, written inside a function or an initializer, belongs + // to no class, so the JIT finds it only here + std::vector< ScriptCallable * > functions; std::vector< hx::Resource > resources; // The module's CppiaObject: what keeps it alive once released diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index c3aabf6e6..ec6fda504 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -1,6 +1,7 @@ #include #include "Cppia.h" #include "CppiaStream.h" +#include #include #include @@ -168,6 +169,8 @@ CppiaExpr *ScriptCallable::link(CppiaModule &inModule) StackLayout layout(oldLayout); inModule.layout = &layout; data = &inModule; + // A local function belongs to no class, so the JIT finds it here + inModule.functions.push_back(this); // A module's main, which names no type, uses the first, which a malformed // module may not have @@ -432,16 +435,34 @@ static void SLJIT_FUNC zeroLocals(unsigned char *inLocals, void *inSize) } // The interpreter zeroes a frame's locals; jitted code writes each before -// reading it, but the debugger can read any of them at any time +// reading it, but the debugger can read any of them at any time. A closure's +// captured variables are copied into its frame before its code runs, so only +// the locals around them are cleared void ScriptCallable::genZeroLocals(CppiaCompiler *compiler) { int argEnd = sizeof(void *); for(int i=0;i argEnd) + + std::vector< std::pair > captured; + for(int i=0;istackPos, var->stackPos + sTypeSize[var->expressionType]) ); + } + std::sort(captured.begin(), captured.end()); + + int from = argEnd; + for(int i=0;i<=(int)captured.size();i++) { - compiler->add(sJitArg1.as(jtPointer), sJitFrame.as(jtPointer), argEnd ); - compiler->callNative( (void *)zeroLocals, sJitArg1.as(jtPointer), JitVal((void *)(size_t)(stackSize - argEnd)) ); + int to = i<(int)captured.size() ? captured[i].first : stackSize; + if (to > from) + { + compiler->add(sJitArg1.as(jtPointer), sJitFrame.as(jtPointer), from ); + compiler->callNative( (void *)zeroLocals, sJitArg1.as(jtPointer), JitVal((void *)(size_t)(to - from)) ); + } + if (i<(int)captured.size() && captured[i].second > from) + from = captured[i].second; } } #endif diff --git a/src/hx/cppia/CppiaModule.cpp b/src/hx/cppia/CppiaModule.cpp index ccb910eac..dfd48654f 100644 --- a/src/hx/cppia/CppiaModule.cpp +++ b/src/hx/cppia/CppiaModule.cpp @@ -234,6 +234,10 @@ void CppiaModule::compile() if (main) main->compile(); + + // Those compiled above are skipped + for(size_t i=0;icompile(); } void CppiaModule::markLazy() @@ -243,6 +247,9 @@ void CppiaModule::markLazy() if (main) main->lazy = true; + + for(size_t i=0;ilazy = true; } #endif diff --git a/test/regression/CppiaJitLocalFunctions/Main.hx b/test/regression/CppiaJitLocalFunctions/Main.hx new file mode 100644 index 000000000..65230f0a5 --- /dev/null +++ b/test/regression/CppiaJitLocalFunctions/Main.hx @@ -0,0 +1,142 @@ +// Under the JIT, a script's local functions compile as its class functions do, +// when they are first called, instead of always running in the interpreter. +// The same cases run as compiled code, then as a script with the JIT off and on, +// and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +class CompiledCounter { + var count = 0; + var step:Int; + + public function new(step:Int) + this.step = step; + + public function adder():Int->Int { + return function(x:Int) { + count += step; + return x + count; + }; + } + + public function label(prefix:String):Void->String + return () -> prefix + ":" + count; +} + +class Compiled { + static var doubler = function(x:Int) return x * 2; + + static function fails():Int { + throw "from a callee"; + } + + public static function run() { + var bias = 7; + var step = function(v:Int):Int { + bias = (bias + 3) & 1023; + return (v & 1023) + bias; + }; + var sum = 0; + for (i in 0...1000) + sum += step(i); + Sys.println('captured Int $sum $bias'); + + var counter = new CompiledCounter(5); + var add = counter.adder(); + Sys.println('this ${add(1)} ${add(1)} ${add(10)} ${counter.label("n")()}'); + + function outer(a:Int) + return function(b:Int) return function(c:Int) return a * 100 + b * 10 + c; + Sys.println('nested ${outer(1)(2)(3)} ${outer(4)(5)(6)}'); + + function fib(n:Int):Int + return n < 2 ? n : fib(n - 1) + fib(n - 2); + Sys.println('recursive ${fib(20)}'); + + var half = (x:Float) -> x * 1.5; + var shout = (s:String) -> s + "!"; + var big = (i:Int) -> i > 3; + var boxed = (i:Int) -> (i : Dynamic); + var seen = []; + var note = (i:Int) -> { + seen.push(i); + }; + note(1); + note(2); + var bigBox:Dynamic = big(5); + Sys.println('returns ${half(3)} ${shout("hey")} ${big(2)} ${big(4)} $bigBox ${boxed(9)} $seen'); + + function opt(a:Int, ?b:Int = 5, ?s:String = "d") + return a + b + s; + var optDynamic:Dynamic = opt; + Sys.println('defaults ${opt(1)} ${opt(1, 2)} ${opt(1, 2, "x")} ${optDynamic(1)} ${Reflect.callMethod(null, opt, [3])}'); + + var thrower = function(x:Int):Int { + if (x > 2) + throw "big " + x; + return x; + }; + var caught = []; + for (i in 0...5) + try { + caught.push(Std.string(thrower(i))); + } catch (e:String) { + caught.push(e); + } + var guarded = (x:Int) -> try thrower(x) catch (e:String) -1; + var callsFails = () -> { + var r = fails(); + caught.push("ran on past the throw"); + return r; + }; + try { + callsFails(); + } catch (e:String) { + caught.push(e); + } + try { + [1, 2].map(x -> x > 1 ? throw "in a callback " + x : x); + } catch (e:String) { + caught.push(e); + } + Sys.println('throws $caught ${guarded(1)} ${guarded(7)}'); + + var squares = [for (i in 0...4) () -> i * i]; + Sys.println('loop ${[for (f in squares) f()]}'); + + var values = [3, 1, 2, 5, 4]; + var scaled = values.map(x -> x * 10); + var odd = values.filter(x -> x & 1 == 1); + values.sort((a, b) -> b - a); + var total = Lambda.fold(values, (x, acc) -> acc + x, 100); + Sys.println('host calls $scaled $odd $values $total'); + + Sys.println('initializer ${doubler(21)}'); + + var amount = 0.5; + var addFloat = (x:Float) -> amount += x; + addFloat(1.25); + addFloat(2); + var log = ""; + var append = (s:String) -> log += s; + append("a"); + append("bc"); + Sys.println('captured Float and String $amount $log'); + + var mixed:Dynamic = (a:Int, b:Float) -> a + b; + Sys.println('dynamic call ${mixed(3, 1.5)} ${Reflect.callMethod(null, mixed, [2, 0.25])}'); + } +} diff --git a/test/regression/CppiaJitLocalFunctions/Script.hx b/test/regression/CppiaJitLocalFunctions/Script.hx new file mode 100644 index 000000000..9be2cbb2f --- /dev/null +++ b/test/regression/CppiaJitLocalFunctions/Script.hx @@ -0,0 +1,123 @@ +// The same cases as Compiled in Main.hx, run as a script +class Counter { + var count = 0; + var step:Int; + + public function new(step:Int) + this.step = step; + + public function adder():Int->Int { + return function(x:Int) { + count += step; + return x + count; + }; + } + + public function label(prefix:String):Void->String + return () -> prefix + ":" + count; +} + +class Script { + static var doubler = function(x:Int) return x * 2; + + static function fails():Int { + throw "from a callee"; + } + + static function main() { + var bias = 7; + var step = function(v:Int):Int { + bias = (bias + 3) & 1023; + return (v & 1023) + bias; + }; + var sum = 0; + for (i in 0...1000) + sum += step(i); + Sys.println('captured Int $sum $bias'); + + var counter = new Counter(5); + var add = counter.adder(); + Sys.println('this ${add(1)} ${add(1)} ${add(10)} ${counter.label("n")()}'); + + function outer(a:Int) + return function(b:Int) return function(c:Int) return a * 100 + b * 10 + c; + Sys.println('nested ${outer(1)(2)(3)} ${outer(4)(5)(6)}'); + + function fib(n:Int):Int + return n < 2 ? n : fib(n - 1) + fib(n - 2); + Sys.println('recursive ${fib(20)}'); + + var half = (x:Float) -> x * 1.5; + var shout = (s:String) -> s + "!"; + var big = (i:Int) -> i > 3; + var boxed = (i:Int) -> (i : Dynamic); + var seen = []; + var note = (i:Int) -> { + seen.push(i); + }; + note(1); + note(2); + var bigBox:Dynamic = big(5); + Sys.println('returns ${half(3)} ${shout("hey")} ${big(2)} ${big(4)} $bigBox ${boxed(9)} $seen'); + + function opt(a:Int, ?b:Int = 5, ?s:String = "d") + return a + b + s; + var optDynamic:Dynamic = opt; + Sys.println('defaults ${opt(1)} ${opt(1, 2)} ${opt(1, 2, "x")} ${optDynamic(1)} ${Reflect.callMethod(null, opt, [3])}'); + + var thrower = function(x:Int):Int { + if (x > 2) + throw "big " + x; + return x; + }; + var caught = []; + for (i in 0...5) + try { + caught.push(Std.string(thrower(i))); + } catch (e:String) { + caught.push(e); + } + var guarded = (x:Int) -> try thrower(x) catch (e:String) -1; + var callsFails = () -> { + var r = fails(); + caught.push("ran on past the throw"); + return r; + }; + try { + callsFails(); + } catch (e:String) { + caught.push(e); + } + try { + [1, 2].map(x -> x > 1 ? throw "in a callback " + x : x); + } catch (e:String) { + caught.push(e); + } + Sys.println('throws $caught ${guarded(1)} ${guarded(7)}'); + + var squares = [for (i in 0...4) () -> i * i]; + Sys.println('loop ${[for (f in squares) f()]}'); + + var values = [3, 1, 2, 5, 4]; + var scaled = values.map(x -> x * 10); + var odd = values.filter(x -> x & 1 == 1); + values.sort((a, b) -> b - a); + var total = Lambda.fold(values, (x, acc) -> acc + x, 100); + Sys.println('host calls $scaled $odd $values $total'); + + Sys.println('initializer ${doubler(21)}'); + + var amount = 0.5; + var addFloat = (x:Float) -> amount += x; + addFloat(1.25); + addFloat(2); + var log = ""; + var append = (s:String) -> log += s; + append("a"); + append("bc"); + Sys.println('captured Float and String $amount $log'); + + var mixed:Dynamic = (a:Int, b:Float) -> a + b; + Sys.println('dynamic call ${mixed(3, 1.5)} ${Reflect.callMethod(null, mixed, [2, 0.25])}'); + } +} diff --git a/test/regression/CppiaJitLocalFunctions/build.hxml b/test/regression/CppiaJitLocalFunctions/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaJitLocalFunctions/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaJitLocalFunctions/stdout.txt b/test/regression/CppiaJitLocalFunctions/stdout.txt new file mode 100644 index 000000000..544718936 --- /dev/null +++ b/test/regression/CppiaJitLocalFunctions/stdout.txt @@ -0,0 +1,39 @@ +-- compiled +captured Int 1002432 959 +this 6 11 25 n:15 +nested 123 456 +recursive 6765 +returns 4.5 hey! false true true 9 [1,2] +defaults 6d 3d 3x 6d 8d +throws [0,1,2,big 3,big 4,from a callee,in a callback 2] 1 -1 +loop [0,1,4,9] +host calls [30,10,20,50,40] [3,1,5] [5,4,3,2,1] 115 +initializer 42 +captured Float and String 3.75 abc +dynamic call 4.5 2.25 +-- script, JIT off +captured Int 1002432 959 +this 6 11 25 n:15 +nested 123 456 +recursive 6765 +returns 4.5 hey! false true true 9 [1,2] +defaults 6d 3d 3x 6d 8d +throws [0,1,2,big 3,big 4,from a callee,in a callback 2] 1 -1 +loop [0,1,4,9] +host calls [30,10,20,50,40] [3,1,5] [5,4,3,2,1] 115 +initializer 42 +captured Float and String 3.75 abc +dynamic call 4.5 2.25 +-- script, JIT on +captured Int 1002432 959 +this 6 11 25 n:15 +nested 123 456 +recursive 6765 +returns 4.5 hey! false true true 9 [1,2] +defaults 6d 3d 3x 6d 8d +throws [0,1,2,big 3,big 4,from a callee,in a callback 2] 1 -1 +loop [0,1,4,9] +host calls [30,10,20,50,40] [3,1,5] [5,4,3,2,1] 115 +initializer 42 +captured Float and String 3.75 abc +dynamic call 4.5 2.25 diff --git a/test/regression/CppiaJitLocalFunctionsDebugger/build.hxml b/test/regression/CppiaJitLocalFunctionsDebugger/build.hxml new file mode 100644 index 000000000..7a98315cb --- /dev/null +++ b/test/regression/CppiaJitLocalFunctionsDebugger/build.hxml @@ -0,0 +1,10 @@ +-cp ../CppiaJitLocalFunctions +--main Script +-cppia bin/script.cppia +--next +-cp ../CppiaJitLocalFunctions +--main Main +-cpp bin +-D scriptable +-D HXCPP_DEBUGGER +--dce no diff --git a/test/regression/CppiaJitLocalFunctionsDebugger/stdout.txt b/test/regression/CppiaJitLocalFunctionsDebugger/stdout.txt new file mode 100644 index 000000000..544718936 --- /dev/null +++ b/test/regression/CppiaJitLocalFunctionsDebugger/stdout.txt @@ -0,0 +1,39 @@ +-- compiled +captured Int 1002432 959 +this 6 11 25 n:15 +nested 123 456 +recursive 6765 +returns 4.5 hey! false true true 9 [1,2] +defaults 6d 3d 3x 6d 8d +throws [0,1,2,big 3,big 4,from a callee,in a callback 2] 1 -1 +loop [0,1,4,9] +host calls [30,10,20,50,40] [3,1,5] [5,4,3,2,1] 115 +initializer 42 +captured Float and String 3.75 abc +dynamic call 4.5 2.25 +-- script, JIT off +captured Int 1002432 959 +this 6 11 25 n:15 +nested 123 456 +recursive 6765 +returns 4.5 hey! false true true 9 [1,2] +defaults 6d 3d 3x 6d 8d +throws [0,1,2,big 3,big 4,from a callee,in a callback 2] 1 -1 +loop [0,1,4,9] +host calls [30,10,20,50,40] [3,1,5] [5,4,3,2,1] 115 +initializer 42 +captured Float and String 3.75 abc +dynamic call 4.5 2.25 +-- script, JIT on +captured Int 1002432 959 +this 6 11 25 n:15 +nested 123 456 +recursive 6765 +returns 4.5 hey! false true true 9 [1,2] +defaults 6d 3d 3x 6d 8d +throws [0,1,2,big 3,big 4,from a callee,in a callback 2] 1 -1 +loop [0,1,4,9] +host calls [30,10,20,50,40] [3,1,5] [5,4,3,2,1] 115 +initializer 42 +captured Float and String 3.75 abc +dynamic call 4.5 2.25 From faf90bdecea91a8271c98c6b92e13c7c113244c0 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 17:17:03 -0500 Subject: [PATCH 02/23] Call script closures from cppia scripts without boxing 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 , 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 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 337 +++++++++++++++++- src/hx/cppia/Cppia.h | 11 + src/hx/cppia/CppiaFunction.cpp | 87 +++-- test/regression/CppiaClosureCallTypes/Main.hx | 151 ++++++++ .../CppiaClosureCallTypes/Script.hx | 132 +++++++ .../CppiaClosureCallTypes/build.hxml | 7 + .../CppiaClosureCallTypes/stdout.txt | 93 +++++ 8 files changed, 780 insertions(+), 39 deletions(-) create mode 100644 test/regression/CppiaClosureCallTypes/Main.hx create mode 100644 test/regression/CppiaClosureCallTypes/Script.hx create mode 100644 test/regression/CppiaClosureCallTypes/build.hxml create mode 100644 test/regression/CppiaClosureCallTypes/stdout.txt diff --git a/Changes.md b/Changes.md index 78437de3b..80f642dde 100644 --- a/Changes.md +++ b/Changes.md @@ -3,6 +3,7 @@ libhxcpp 6.0.3 (unreleased) ------------------------------------------------------------ * The cppia JIT compiles a script's local functions, the closures written inside a function or an initializer, as it compiles class functions, when each is first called. No class holds them, so they were never compiled: under the JIT their bodies ran in the interpreter, whether jitted code called them or the host called them back. Jitted code calling a closure is 1.9x faster (closure_call), and the host calling one back 2.5x (native_callback). HXCPP_CPPIA_EAGER_JIT compiles them as the module loads, with the rest (HaxeFoundation/hxcpp#1213) +* A cppia script calling one of its closures, or a bound method held as a value, passes the arguments and takes the result as they are when the function takes the same types, interpreted and under the JIT. Each argument was boxed into a Dynamic for __run and unboxed into the function's frame, and the result boxed and unboxed again, which allocated for most Ints and every Float. Calling a closure that takes and returns an Int is 1.8x faster under the JIT and 1.2x interpreted (closure_call). An argument of another type, more arguments than the function takes, and host functions are boxed as before libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index c9f3b1018..be8981252 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -3389,10 +3389,57 @@ struct GetFieldByName : public CppiaDynamicExpr +// How a call has an argument, so it can pass it to a script closure that takes that +// type without boxing it. A Bool goes as an Int but boxes as a Bool +enum CallArgKind { cakObject, cakInt, cakBool, cakFloat, cakString }; + +static inline ExprType callArgType(unsigned char inKind) +{ + switch(inKind) + { + case cakInt: + case cakBool: return etInt; + case cakFloat: return etFloat; + case cakString: return etString; + default: return etObject; + } +} + +// The bytes an argument of the kind takes in a frame +static inline int callArgSize(unsigned char inKind) +{ + switch(inKind) + { + case cakInt: + case cakBool: return sizeof(int); + case cakFloat: return sizeof(Float); + case cakString: return sizeof(String); + default: return sizeof(hx::Object *); + } +} + +// Puts back ctx's pointer and frame as they were when it was made. Unlike AutoStack, +// it starts no frame, so the arguments still run in the caller's +struct RestoreStack +{ + CppiaCtx *ctx; + unsigned char *pointer; + unsigned char *frame; + + RestoreStack(CppiaCtx *inCtx) : ctx(inCtx), pointer(inCtx->pointer), frame(inCtx->frame) { } + ~RestoreStack() + { + ctx->pointer = pointer; + ctx->frame = frame; + } +}; + struct Call : public CppiaDynamicExpr { Expressions args; CppiaExpr *func; + // Each argument's CallArgKind + std::vector argKinds; Call(CppiaStream &stream) { @@ -3415,15 +3462,84 @@ struct Call : public CppiaDynamicExpr { func = func->link(inModule); LinkExpressions(args,inModule); + argKinds.resize(args.size()); + for(int a=0;agetType()) + { + case etInt: argKinds[a] = args[a]->isBoolInt() ? cakBool : cakInt; break; + case etFloat: argKinds[a] = cakFloat; break; + case etString: argKinds[a] = cakString; break; + default: argKinds[a] = cakObject; + } + } return this; } - hx::Object *runObject(CppiaCtx *ctx) HXCPP_OVERRIDE + + // The function of a script closure that takes each argument as the type the call has + // it in, so the call can put them in its frame as they are; 0 when they must be boxed. + // A closure given more arguments than it takes, which ignores the rest, has them boxed + ScriptCallable *directTarget(hx::Object *inFunction) { - hx::Object *funcVal = func->runObject(ctx); - BCR_CHECK; + ScriptCallable *target = scriptClosureTarget(inFunction); + if (!target) + return 0; + int n = args.size(); + if (n > (int)target->args.size()) + return 0; + for(int a=0;aargs[a].argType!=callArgType(argKinds[a])) + return 0; + return target; + } - CPPIA_CHECK_FUNC(funcVal); + // The array type a closure's argument wants an object converted to, as __run converts it + static inline ArrayType wantedArray(ScriptCallable *inTarget, int inArg) + { + TypeData *type = inTarget->args[inArg].type; + return type ? type->arrayType : arrNotArray; + } + + // Pushes a slot for this and the arguments as they are, then runs the closure in that + // frame, leaving its result at ctx->frame. False if an argument breaks, continues, + // returns or throws, and nothing ran + bool runDirect(CppiaCtx *ctx, hx::Object *inFunction, ScriptCallable *inTarget) + { + unsigned char *frame = ctx->pointer; + ctx->push( (hx::Object *)0 ); + for(int a=0;apushInt(args[a]->runInt(ctx)); + break; + case cakFloat: + ctx->pushFloat(args[a]->runFloat(ctx)); + break; + case cakString: + ctx->pushString(args[a]->runString(ctx)); + break; + default: + { + hx::Object *value = args[a]->runObject(ctx); + ArrayType want = wantedArray(inTarget, a); + if (value && want!=arrNotArray) + value = DynamicToArrayType(value, want); + ctx->pushObject(value); + } + } + BCR_CHECK_RET(false); + } + ctx->frame = frame; + runScriptClosure(ctx, inFunction, args.size(), true); + return true; + } + // Calls inFunction through __run, with each argument boxed + hx::Object *runBoxed(CppiaCtx *ctx, hx::Object *funcVal) + { int size = args.size(); #if (HXCPP_API_LEVEL>=500) Array argArray = Array_obj::__new(size, size); @@ -3507,7 +3623,196 @@ struct Call : public CppiaDynamicExpr return 0; } + // Each run below calls a script closure that takes the arguments as they are with + // them unboxed, and reads its result as it is when it has the type wanted. Anything + // else goes through runBoxed and converts the result as it always has + hx::Object *runObject(CppiaCtx *ctx) HXCPP_OVERRIDE + { + hx::Object *funcVal = func->runObject(ctx); + BCR_CHECK; + CPPIA_CHECK_FUNC(funcVal); + ScriptCallable *target = directTarget(funcVal); + if (!target) + return runBoxed(ctx, funcVal); + RestoreStack restore(ctx); + if (!runDirect(ctx, funcVal, target)) + return 0; + return target->returnType==etObject ? ctx->getObjectPtr() : boxScriptClosureResult(ctx, target); + } + + int runInt(CppiaCtx *ctx) HXCPP_OVERRIDE + { + hx::Object *funcVal = func->runObject(ctx); + BCR_CHECK; + CPPIA_CHECK_FUNC(funcVal); + ScriptCallable *target = directTarget(funcVal); + if (!target) + return ValToInt(runBoxed(ctx, funcVal)); + RestoreStack restore(ctx); + if (!runDirect(ctx, funcVal, target)) + return 0; + return target->returnType==etInt ? ctx->getInt() : ValToInt(boxScriptClosureResult(ctx, target)); + } + + Float runFloat(CppiaCtx *ctx) HXCPP_OVERRIDE + { + hx::Object *funcVal = func->runObject(ctx); + BCR_CHECK; + CPPIA_CHECK_FUNC(funcVal); + ScriptCallable *target = directTarget(funcVal); + if (!target) + return ValToFloat(runBoxed(ctx, funcVal)); + RestoreStack restore(ctx); + if (!runDirect(ctx, funcVal, target)) + return 0; + return target->returnType==etFloat ? ctx->getFloat() : ValToFloat(boxScriptClosureResult(ctx, target)); + } + + String runString(CppiaCtx *ctx) HXCPP_OVERRIDE + { + hx::Object *funcVal = func->runObject(ctx); + BCR_CHECK; + CPPIA_CHECK_FUNC(funcVal); + ScriptCallable *target = directTarget(funcVal); + hx::Object *result = 0; + if (!target) + { + result = runBoxed(ctx, funcVal); + BCR_CHECK; + } + else + { + RestoreStack restore(ctx); + if (!runDirect(ctx, funcVal, target)) + return String(); + if (target->returnType==etString) + return ctx->getString(); + result = boxScriptClosureResult(ctx, target); + } + return result ? result->toString() : String(); + } + + void runVoid(CppiaCtx *ctx) HXCPP_OVERRIDE + { + hx::Object *funcVal = func->runObject(ctx); + BCR_VCHECK; + CPPIA_CHECK_FUNC(funcVal); + ScriptCallable *target = directTarget(funcVal); + if (!target) + { + runBoxed(ctx, funcVal); + return; + } + RestoreStack restore(ctx); + runDirect(ctx, funcVal, target); + } + #ifdef CPPIA_JIT + // The result of a call from jitted code, stored at inSlot as inType + static void storeResult(unsigned char *inSlot, ExprType inType, hx::Object *inValue) + { + switch(inType) + { + case etInt: CppiaCtx::setSlot(inSlot, inValue ? inValue->__ToInt() : 0); break; + case etFloat: CppiaCtx::setSlot(inSlot, inValue ? inValue->__ToDouble() : 0.0); break; + case etString: CppiaCtx::setSlot(inSlot, inValue ? inValue->toString() : String()); break; + case etObject: CppiaCtx::setSlot(inSlot, inValue); break; + default: ; + } + } + + // Boxes the arguments jitted code left after the this slot at inBase, each as its + // kind, and calls inFunction through __run, as callDynamic does + hx::Object *runJitBoxed(CppiaCtx *ctx, hx::Object *inFunction, unsigned char *inBase) + { + int n = args.size(); + unsigned char *slot = inBase + sizeof(hx::Object *); + #define CALL_BOX_ARG(target) \ + switch(argKinds[a]) \ + { \ + case cakInt: target = CppiaCtx::getSlot(slot); break; \ + case cakBool: target = CppiaCtx::getSlot(slot)!=0; break; \ + case cakFloat: target = CppiaCtx::getSlot(slot); break; \ + case cakString: target = CppiaCtx::getSlot(slot); break; \ + default: target = CppiaCtx::getSlot(slot); \ + } \ + slot += callArgSize(argKinds[a]); + + // Each is copied out before the call, whose frame starts at inBase over them +#if (HXCPP_API_LEVEL<500) + if (n<=5) + { + Dynamic boxed[5]; + for(int a=0;apointer = inBase; + switch(n) + { + case 0: return inFunction->__run().mPtr; + case 1: return inFunction->__run(boxed[0]).mPtr; + case 2: return inFunction->__run(boxed[0],boxed[1]).mPtr; + case 3: return inFunction->__run(boxed[0],boxed[1],boxed[2]).mPtr; + case 4: return inFunction->__run(boxed[0],boxed[1],boxed[2],boxed[3]).mPtr; + default: return inFunction->__run(boxed[0],boxed[1],boxed[2],boxed[3],boxed[4]).mPtr; + } + } +#endif + Array argArray = Array_obj::__new(n,n); + for(int a=0;apointer = inBase; + return inFunction->__Run(argArray).mPtr; + } + + // Called by jitted code with ctx->frame at a slot for this and the arguments after + // it, each as its kind. Leaves the result in that slot as RESULT + template + static void SLJIT_FUNC runJit(CppiaCtx *ctx, hx::Object *inFunction, Call *inCall) + { + if (!inFunction) + { + ctx->exception = Dynamic(HX_CSTRING("Null Function")).mPtr; + __hx_stack_set_last_exception(); + return; + } + unsigned char *base = ctx->frame; + unsigned char *oldPointer = ctx->pointer; + TRY_NATIVE + ScriptCallable *target = inCall->directTarget(inFunction); + if (target) + { + unsigned char *slot = base + sizeof(hx::Object *); + for(int a=0;aargs.size();a++) + { + ExprType type = callArgType(inCall->argKinds[a]); + if (type==etObject) + { + hx::Object *value = CppiaCtx::getSlot(slot); + ArrayType want = wantedArray(target, a); + if (value && want!=arrNotArray) + CppiaCtx::setSlot(slot, DynamicToArrayType(value, want)); + } + slot += callArgSize(inCall->argKinds[a]); + } + ctx->pointer = slot; + runScriptClosure(ctx, inFunction, inCall->args.size(), false); + if (!ctx->exception && RESULT!=etVoid && target->returnType!=RESULT) + storeResult(base, (ExprType)RESULT, boxScriptClosureResult(ctx, target)); + } + else + storeResult(base, (ExprType)RESULT, inCall->runJitBoxed(ctx, inFunction, base)); + CATCH_NATIVE + ctx->pointer = oldPointer; + ctx->frame = base; + } + void genCode(CppiaCompiler *compiler, const JitVal &inDest,ExprType destType) HXCPP_OVERRIDE { JitTemp functionObject(compiler, jtPointer); @@ -3516,21 +3821,35 @@ struct Call : public CppiaDynamicExpr { AutoFramePos frame(compiler); + // A slot for this, which a script closure fills, then each argument as the call + // has it + compiler->addFrame(etObject); for(int a=0;agenCode(compiler, JitFramePos(compiler->getCurrentFrameSize(),etObject), etObject); - compiler->addFrame(etObject); + ExprType type = callArgType(argKinds[a]); + args[a]->genCode(compiler, JitFramePos(compiler->getCurrentFrameSize(),type), type); + compiler->addFrame(type); } // restore frame size } compiler->add(sJitCtxFrame, sJitFrame, compiler->getCurrentFrameSize()); - compiler->callNative((void *)callDynamic,sJitCtx,functionObject,JitVal( (int)args.size() ) ); + ExprType resultType = destType==etNull ? etVoid : destType; + void *helper = 0; + switch(resultType) + { + case etInt: helper = (void *)runJit; break; + case etFloat: helper = (void *)runJit; break; + case etString: helper = (void *)runJit; break; + case etObject: helper = (void *)runJit; break; + default: helper = (void *)runJit; + } + compiler->callNative(helper, sJitCtx, functionObject, JitVal((void *)this)); compiler->checkException(); - if (destType!=etVoid) - compiler->convertResult( etObject, inDest, destType ); + if (resultType!=etVoid) + compiler->convertResult( resultType, inDest, destType ); } #endif }; diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 9e0830e10..e21ded1b6 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -411,6 +411,17 @@ CppiaExpr *createStaticAccess(CppiaExpr *inSrc, FieldStorage inType, void *inPtr hx::Object * CPPIA_CALL createClosure(CppiaCtx *ctx, ScriptCallable *inFunction); hx::Object *createMemberClosure(hx::Object *, ScriptCallable *inFunction); ScriptCallable *getClosureFunction(hx::Object *inObj); +// The function inFunction runs when it is a script closure, bound method or not, or 0 +// for any other object +ScriptCallable *scriptClosureTarget(hx::Object *inFunction); +// Runs a script closure, which scriptClosureTarget gave a function for, in the frame +// at ctx->frame: a slot for this, then its first inArgCount arguments as the function's +// own types, with ctx->pointer past them. The result is left at ctx->frame as the +// function's return type. An exception from compiled code is thrown, or with !inThrow +// left in ctx->exception +void runScriptClosure(CppiaCtx *ctx, hx::Object *inClosure, int inArgCount, bool inThrow); +// The result runScriptClosure left, boxed as a call through __run returns it +hx::Object *boxScriptClosureResult(CppiaCtx *ctx, ScriptCallable *inFunction); CppiaClassInfo *getScriptClassInfo(hx::Object *inClass); hx::Object *createEnumClosure(struct CppiaEnumConstructor &inContructor); diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index ec6fda504..8810c5e00 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -876,6 +876,11 @@ void CppiaFunction::markLazy() +// The vtable every CppiaClosure has, which each stores as it is made, so a call can +// tell a script closure from another function object by its first word, without a +// dynamic_cast. Nothing can be a closure while this is still null +static std::atomic sClosureVTable(0); + class CppiaClosure : public hx::Object { public: @@ -888,6 +893,7 @@ class CppiaClosure : public hx::Object CppiaClosure(CppiaCtx *ctx, ScriptCallable *inFunction) { function = inFunction; + noteVTable(); unsigned char *base = ((unsigned char *)this) + sizeof(CppiaClosure); @@ -911,11 +917,23 @@ class CppiaClosure : public hx::Object CppiaClosure(hx::Object *inThis, ScriptCallable *inFunction) { function = inFunction; + noteVTable(); *getThis() = inThis; } + void noteVTable() + { + void *vtable = *(void **)this; + if (sClosureVTable.load(std::memory_order_relaxed)!=vtable) + sClosureVTable.store(vtable, std::memory_order_relaxed); + } - Dynamic doRun(CppiaCtx *ctx, int inHaveArgs) + + // Runs the function in the frame at ctx->frame, which holds a slot for this and + // the first inHaveArgs arguments, with ctx->pointer past them, and leaves its result + // at ctx->frame. An exception from compiled code is thrown, or with !inThrow left in + // ctx->exception + void runInFrame(CppiaCtx *ctx, int inHaveArgs, bool inThrow) { function->addExtraDefaults(ctx,inHaveArgs); function->addStackVarsSpace(ctx); @@ -944,53 +962,44 @@ class CppiaClosure : public hx::Object AutoFrame frame(ctx); code(ctx); } - if (ctx->exception) + if (ctx->exception && inThrow) { Dynamic caught = fromPendingException(ctx->exception); ctx->exception = nullptr; HX_STACK_DO_THROW(caught); } - - { - switch(function->returnType) - { - case etFloat: - return ctx->getFloat(); - case etInt: - if (function->isBoolReturn) - return (bool)ctx->getInt(); - return ctx->getInt(); - case etString: - return ctx->getString(); - case etObject: - return ctx->getObject(); - default: ; - } - } - return null(); + return; } - //printf("Not compiled %d!\n", function->captureVars.size()); #endif function->runFunctionClosure(ctx); ctx->breakContReturn = 0; + } - switch(function->returnType) + // The result runInFrame left, boxed + static hx::Object *boxResult(CppiaCtx *ctx, ScriptCallable *inFunction) + { + switch(inFunction->returnType) { case etFloat: - return ctx->getFloat( ); + return Dynamic(ctx->getFloat()).mPtr; case etInt: - if (function->isBoolReturn) - return (bool)ctx->getInt( ); - return ctx->getInt( ); + if (inFunction->isBoolReturn) + return Dynamic((bool)ctx->getInt()).mPtr; + return Dynamic(ctx->getInt()).mPtr; case etString: - return ctx->getString( ); + return Dynamic(ctx->getString()).mPtr; case etObject: - return ctx->getObject( ); - default: break; + return ctx->getObjectPtr(); + default: ; } + return 0; + } - return null(); + Dynamic doRun(CppiaCtx *ctx, int inHaveArgs) + { + runInFrame(ctx, inHaveArgs, true); + return boxResult(ctx, function); } void pushArgDynamic(CppiaCtx *ctx, int a, Dynamic inValue) @@ -1171,6 +1180,24 @@ ScriptCallable *getClosureFunction(hx::Object *inObj) return closure->function; } +ScriptCallable *scriptClosureTarget(hx::Object *inFunction) +{ + void *vtable = sClosureVTable.load(std::memory_order_relaxed); + if (!inFunction || !vtable || *(void **)inFunction!=vtable) + return 0; + return ((CppiaClosure *)inFunction)->function; +} + +void runScriptClosure(CppiaCtx *ctx, hx::Object *inClosure, int inArgCount, bool inThrow) +{ + ((CppiaClosure *)inClosure)->runInFrame(ctx, inArgCount, inThrow); +} + +hx::Object *boxScriptClosureResult(CppiaCtx *ctx, ScriptCallable *inFunction) +{ + return CppiaClosure::boxResult(ctx, inFunction); +} + diff --git a/test/regression/CppiaClosureCallTypes/Main.hx b/test/regression/CppiaClosureCallTypes/Main.hx new file mode 100644 index 000000000..a53bb2c4c --- /dev/null +++ b/test/regression/CppiaClosureCallTypes/Main.hx @@ -0,0 +1,151 @@ +// A script calling a script closure passes the arguments and takes the result +// as they are when the closure has the same types, instead of boxing each one. +// The same cases run as compiled code, then as a script with the JIT off and on, +// and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +class CompiledHolder { + public var value:Int; + public var callback:Int->Int; + + public function new(value:Int) { + this.value = value; + callback = x -> x + this.value; + } + + public function scaled(x:Int):Int + return x * value; + + public function describe(prefix:String, x:Float):String + return prefix + (x + value); +} + +class Compiled { + static function show(label:String, value:Dynamic) { + var kind = if (value == null) "null" else if (Std.isOfType(value, Bool)) "Bool" else if (Std.isOfType(value, Int)) "Int" else + if (Std.isOfType(value, Float)) "Float" else if (Std.isOfType(value, String)) "String" else "other"; + Sys.println('$label $value $kind'); + } + + static function early(f:Int->Int->Int, stop:Bool):Int { + var r = f(stop ? return -1 : 1, 2); + return r * 10; + } + + public static function run() { + var addInt = (a:Int, b:Int) -> a + b; + var half = (x:Float) -> x / 2; + var shout = (s:String) -> s + "!"; + var not = (b:Bool) -> !b; + var isBig = (i:Int) -> i > 3; + var seen = 0; + var nothing = (i:Int) -> { + seen += i; + }; + var asDynamic = (x:Float) -> (x : Dynamic); + var takesDynamic = (d:Dynamic) -> d; + var takesInts = (a:Array) -> a.length * 100 + a[0]; + var six = (a:Int, b:Int, c:Int, d:Int, e:Int, f:Int) -> a + b * 2 + c * 3 + d * 4 + e * 5 + f * 6; + var inc = (x:Int) -> { + x++; + return x; + }; + + var i:Int = addInt(2, 3); + var f:Float = addInt(2, 3); + var s:String = "" + addInt(2, 3); + var d:Dynamic = addInt(2, 3); + addInt(2, 3); + Sys.println('Int result as Int $i, Float $f, String $s, Dynamic $d'); + show("Int result as Dynamic", addInt(200, 100)); + + var hi:Int = Std.int(half(9)); + var hf:Float = half(9); + var hs:String = "" + half(9); + var hd:Dynamic = half(9); + Sys.println('Float result as Int $hi, Float $hf, String $hs, Dynamic $hd'); + show("whole Float result as Dynamic", half(8)); + show("negative zero result", 1 / half(-0.0)); + + Sys.println('String result ${shout("hey")} ${shout(null)} ${shout("")}'); + var sd:Dynamic = shout("x"); + show("String result as Dynamic", sd); + + show("Bool result as Dynamic", not(false)); + show("Bool result from Int", isBig(5)); + var bi:Bool = isBig(2); + Sys.println('Bool result as Bool $bi, String ${"" + isBig(9)}'); + nothing(4); + nothing(5); + Sys.println('Void result $seen'); + + show("Int to Dynamic", takesDynamic(7)); + show("big Int to Dynamic", takesDynamic(100000)); + show("Bool to Dynamic", takesDynamic(true)); + show("Float to Dynamic", takesDynamic(2.5)); + show("whole Float to Dynamic", takesDynamic(3.0)); + show("String to Dynamic", takesDynamic("s")); + show("Float to Dynamic and back", asDynamic(4.0)); + show("Int to Float", half(7)); + + var ints = [4, 5, 6]; + var intsDynamic:Dynamic = ints; + Sys.println('Array argument ${takesInts(ints)} ${takesInts(intsDynamic)}'); + + Sys.println('six arguments ${six(1, 2, 3, 4, 5, 6)}'); + var v = 5; + Sys.println('argument changed in the callee ${inc(v)} $v'); + Sys.println('nested ${addInt(addInt(1, 2), addInt(addInt(3, 4), 5))}'); + + var holder = new CompiledHolder(10); + var bound = holder.scaled; + var dynamicHolder:Dynamic = holder; + var fields:ArrayInt> = [bound, holder.callback, x -> x - 1]; + Sys.println('bound ${bound(3)} ${holder.callback(3)} ${dynamicHolder.scaled(4)} ${dynamicHolder.describe("d", 0.5)} ${[for (g in fields) g(7)]}'); + + var hostAbs:Float->Float = Math.abs; + var hostString:Dynamic->String = Std.string; + Sys.println('host functions ${hostAbs(-3.5)} ${hostString(12)}'); + + var none:Int->Int = null; + var outcome = try Std.string(none(1)) catch (e:Dynamic) "null function throws"; + Sys.println(outcome); + + var thrower = (x:Int) -> x > 2 ? throw "too big" : x; + var total = 1; + for (k in 0...5) + try { + total += thrower(k); + } catch (e:String) { + total += 100; + } + Sys.println('throws $total'); + + Sys.println('returns from an argument ${early(addInt, false)} ${early(addInt, true)}'); + + function fib(n:Int):Int + return n < 2 ? n : fib(n - 1) + fib(n - 2); + var fibValue:Int->Int = fib; + Sys.println('recursive ${fibValue(15)}'); + + var count = 0; + var counter = () -> ++count; + for (k in 0...3) + counter(); + Sys.println('no arguments ${counter()} $count'); + } +} diff --git a/test/regression/CppiaClosureCallTypes/Script.hx b/test/regression/CppiaClosureCallTypes/Script.hx new file mode 100644 index 000000000..1160fdab6 --- /dev/null +++ b/test/regression/CppiaClosureCallTypes/Script.hx @@ -0,0 +1,132 @@ +// The same cases as Compiled in Main.hx, run as a script +class Holder { + public var value:Int; + public var callback:Int->Int; + + public function new(value:Int) { + this.value = value; + callback = x -> x + this.value; + } + + public function scaled(x:Int):Int + return x * value; + + public function describe(prefix:String, x:Float):String + return prefix + (x + value); +} + +class Script { + static function show(label:String, value:Dynamic) { + var kind = if (value == null) "null" else if (Std.isOfType(value, Bool)) "Bool" else if (Std.isOfType(value, Int)) "Int" else + if (Std.isOfType(value, Float)) "Float" else if (Std.isOfType(value, String)) "String" else "other"; + Sys.println('$label $value $kind'); + } + + static function early(f:Int->Int->Int, stop:Bool):Int { + var r = f(stop ? return -1 : 1, 2); + return r * 10; + } + + static function main() { + var addInt = (a:Int, b:Int) -> a + b; + var half = (x:Float) -> x / 2; + var shout = (s:String) -> s + "!"; + var not = (b:Bool) -> !b; + var isBig = (i:Int) -> i > 3; + var seen = 0; + var nothing = (i:Int) -> { + seen += i; + }; + var asDynamic = (x:Float) -> (x : Dynamic); + var takesDynamic = (d:Dynamic) -> d; + var takesInts = (a:Array) -> a.length * 100 + a[0]; + var six = (a:Int, b:Int, c:Int, d:Int, e:Int, f:Int) -> a + b * 2 + c * 3 + d * 4 + e * 5 + f * 6; + var inc = (x:Int) -> { + x++; + return x; + }; + + var i:Int = addInt(2, 3); + var f:Float = addInt(2, 3); + var s:String = "" + addInt(2, 3); + var d:Dynamic = addInt(2, 3); + addInt(2, 3); + Sys.println('Int result as Int $i, Float $f, String $s, Dynamic $d'); + show("Int result as Dynamic", addInt(200, 100)); + + var hi:Int = Std.int(half(9)); + var hf:Float = half(9); + var hs:String = "" + half(9); + var hd:Dynamic = half(9); + Sys.println('Float result as Int $hi, Float $hf, String $hs, Dynamic $hd'); + show("whole Float result as Dynamic", half(8)); + show("negative zero result", 1 / half(-0.0)); + + Sys.println('String result ${shout("hey")} ${shout(null)} ${shout("")}'); + var sd:Dynamic = shout("x"); + show("String result as Dynamic", sd); + + show("Bool result as Dynamic", not(false)); + show("Bool result from Int", isBig(5)); + var bi:Bool = isBig(2); + Sys.println('Bool result as Bool $bi, String ${"" + isBig(9)}'); + nothing(4); + nothing(5); + Sys.println('Void result $seen'); + + show("Int to Dynamic", takesDynamic(7)); + show("big Int to Dynamic", takesDynamic(100000)); + show("Bool to Dynamic", takesDynamic(true)); + show("Float to Dynamic", takesDynamic(2.5)); + show("whole Float to Dynamic", takesDynamic(3.0)); + show("String to Dynamic", takesDynamic("s")); + show("Float to Dynamic and back", asDynamic(4.0)); + show("Int to Float", half(7)); + + var ints = [4, 5, 6]; + var intsDynamic:Dynamic = ints; + Sys.println('Array argument ${takesInts(ints)} ${takesInts(intsDynamic)}'); + + Sys.println('six arguments ${six(1, 2, 3, 4, 5, 6)}'); + var v = 5; + Sys.println('argument changed in the callee ${inc(v)} $v'); + Sys.println('nested ${addInt(addInt(1, 2), addInt(addInt(3, 4), 5))}'); + + var holder = new Holder(10); + var bound = holder.scaled; + var dynamicHolder:Dynamic = holder; + var fields:ArrayInt> = [bound, holder.callback, x -> x - 1]; + Sys.println('bound ${bound(3)} ${holder.callback(3)} ${dynamicHolder.scaled(4)} ${dynamicHolder.describe("d", 0.5)} ${[for (g in fields) g(7)]}'); + + var hostAbs:Float->Float = Math.abs; + var hostString:Dynamic->String = Std.string; + Sys.println('host functions ${hostAbs(-3.5)} ${hostString(12)}'); + + var none:Int->Int = null; + var outcome = try Std.string(none(1)) catch (e:Dynamic) "null function throws"; + Sys.println(outcome); + + var thrower = (x:Int) -> x > 2 ? throw "too big" : x; + var total = 1; + for (k in 0...5) + try { + total += thrower(k); + } catch (e:String) { + total += 100; + } + Sys.println('throws $total'); + + Sys.println('returns from an argument ${early(addInt, false)} ${early(addInt, true)}'); + + function fib(n:Int):Int + return n < 2 ? n : fib(n - 1) + fib(n - 2); + var fibValue:Int->Int = fib; + Sys.println('recursive ${fibValue(15)}'); + + var count = 0; + var counter = () -> ++count; + for (k in 0...3) + counter(); + Sys.println('no arguments ${counter()} $count'); + } +} diff --git a/test/regression/CppiaClosureCallTypes/build.hxml b/test/regression/CppiaClosureCallTypes/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaClosureCallTypes/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaClosureCallTypes/stdout.txt b/test/regression/CppiaClosureCallTypes/stdout.txt new file mode 100644 index 000000000..36782a40c --- /dev/null +++ b/test/regression/CppiaClosureCallTypes/stdout.txt @@ -0,0 +1,93 @@ +-- compiled +Int result as Int 5, Float 5, String 5, Dynamic 5 +Int result as Dynamic 300 Int +Float result as Int 4, Float 4.5, String 4.5, Dynamic 4.5 +whole Float result as Dynamic 4 Int +negative zero result -Infinity Float +String result hey! null! ! +String result as Dynamic x! String +Bool result as Dynamic true Bool +Bool result from Int true Bool +Bool result as Bool false, String true +Void result 9 +Int to Dynamic 7 Int +big Int to Dynamic 100000 Int +Bool to Dynamic true Bool +Float to Dynamic 2.5 Float +whole Float to Dynamic 3 Int +String to Dynamic s String +Float to Dynamic and back 4 Int +Int to Float 3.5 Float +Array argument 304 304 +six arguments 91 +argument changed in the callee 6 5 +nested 15 +bound 30 13 40 d10.5 [70,17,6] +host functions 3.5 12 +null function throws +throws 204 +returns from an argument 30 -1 +recursive 610 +no arguments 4 4 +-- script, JIT off +Int result as Int 5, Float 5, String 5, Dynamic 5 +Int result as Dynamic 300 Int +Float result as Int 4, Float 4.5, String 4.5, Dynamic 4.5 +whole Float result as Dynamic 4 Int +negative zero result -Infinity Float +String result hey! null! ! +String result as Dynamic x! String +Bool result as Dynamic true Bool +Bool result from Int true Bool +Bool result as Bool false, String true +Void result 9 +Int to Dynamic 7 Int +big Int to Dynamic 100000 Int +Bool to Dynamic true Bool +Float to Dynamic 2.5 Float +whole Float to Dynamic 3 Int +String to Dynamic s String +Float to Dynamic and back 4 Int +Int to Float 3.5 Float +Array argument 304 304 +six arguments 91 +argument changed in the callee 6 5 +nested 15 +bound 30 13 40 d10.5 [70,17,6] +host functions 3.5 12 +null function throws +throws 204 +returns from an argument 30 -1 +recursive 610 +no arguments 4 4 +-- script, JIT on +Int result as Int 5, Float 5, String 5, Dynamic 5 +Int result as Dynamic 300 Int +Float result as Int 4, Float 4.5, String 4.5, Dynamic 4.5 +whole Float result as Dynamic 4 Int +negative zero result -Infinity Float +String result hey! null! ! +String result as Dynamic x! String +Bool result as Dynamic true Bool +Bool result from Int true Bool +Bool result as Bool false, String true +Void result 9 +Int to Dynamic 7 Int +big Int to Dynamic 100000 Int +Bool to Dynamic true Bool +Float to Dynamic 2.5 Float +whole Float to Dynamic 3 Int +String to Dynamic s String +Float to Dynamic and back 4 Int +Int to Float 3.5 Float +Array argument 304 304 +six arguments 91 +argument changed in the callee 6 5 +nested 15 +bound 30 13 40 d10.5 [70,17,6] +host functions 3.5 12 +null function throws +throws 204 +returns from an argument 30 -1 +recursive 610 +no arguments 4 4 From da090510163285d8e87b5fd8a0e0ab6af5973868 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 17:38:15 -0500 Subject: [PATCH 03/23] Read object array elements in place under the cppia JIT 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 , 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, 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 --- Changes.md | 1 + src/hx/cppia/ArrayBuiltin.cpp | 5 +- .../CppiaJitObjectArrayRead/Main.hx | 88 +++++++++++++++++++ .../CppiaJitObjectArrayRead/Script.hx | 67 ++++++++++++++ .../CppiaJitObjectArrayRead/build.hxml | 7 ++ .../CppiaJitObjectArrayRead/stdout.txt | 33 +++++++ 6 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 test/regression/CppiaJitObjectArrayRead/Main.hx create mode 100644 test/regression/CppiaJitObjectArrayRead/Script.hx create mode 100644 test/regression/CppiaJitObjectArrayRead/build.hxml create mode 100644 test/regression/CppiaJitObjectArrayRead/stdout.txt diff --git a/Changes.md b/Changes.md index 80f642dde..9098d391a 100644 --- a/Changes.md +++ b/Changes.md @@ -4,6 +4,7 @@ libhxcpp 6.0.3 (unreleased) * The cppia JIT compiles a script's local functions, the closures written inside a function or an initializer, as it compiles class functions, when each is first called. No class holds them, so they were never compiled: under the JIT their bodies ran in the interpreter, whether jitted code called them or the host called them back. Jitted code calling a closure is 1.9x faster (closure_call), and the host calling one back 2.5x (native_callback). HXCPP_CPPIA_EAGER_JIT compiles them as the module loads, with the rest (HaxeFoundation/hxcpp#1213) * A cppia script calling one of its closures, or a bound method held as a value, passes the arguments and takes the result as they are when the function takes the same types, interpreted and under the JIT. Each argument was boxed into a Dynamic for __run and unboxed into the function's frame, and the result boxed and unboxed again, which allocated for most Ints and every Float. Calling a closure that takes and returns an Int is 1.8x faster under the JIT and 1.2x interpreted (closure_call). An argument of another type, more arguments than the function takes, and host functions are boxed as before +* The cppia JIT reads an element of an array of objects, such as an Array of a script class, in place when the element is wanted as an object, as it reads one wanted as anything else. It called a helper that went through the array's virtual __GetItem and built a Dynamic of the element, which an object element does not need. Under the JIT, virtual calls through an array of objects are 1.4x faster (virtual_call) and allocation that reads one 1.2x (alloc_objects). Arrays of Ints, Bools, Floats and Strings still box their elements through __GetItem libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/cppia/ArrayBuiltin.cpp b/src/hx/cppia/ArrayBuiltin.cpp index 24316231d..413831200 100644 --- a/src/hx/cppia/ArrayBuiltin.cpp +++ b/src/hx/cppia/ArrayBuiltin.cpp @@ -1596,7 +1596,10 @@ struct ArrayBuiltin : public ArrayBuiltinBase thisExpr->genCode(compiler, thisVal, etObject); genNullReferenceExceptionCheck(compiler, thisVal); - if (destType==etObject) + // An Int, Float, Bool or String element is boxed as __GetItem boxes it. + // An object array's element already is the object, so it is read in + // place below, as __GetItem reads it + if (destType==etObject && (ExprType)ExprTypeOf::value!=etObject) { args[0]->genCode(compiler, sJitArg1, etInt); compiler->callNative((void *)objGetIndex, thisVal, sJitArg1.as(jtInt)); diff --git a/test/regression/CppiaJitObjectArrayRead/Main.hx b/test/regression/CppiaJitObjectArrayRead/Main.hx new file mode 100644 index 000000000..5d774cddf --- /dev/null +++ b/test/regression/CppiaJitObjectArrayRead/Main.hx @@ -0,0 +1,88 @@ +// Under the JIT, reading an element of an array of objects as an object loads +// it in place, as reading it as anything else does, instead of calling +// __GetItem through a helper. Arrays of Ints, Bools, Floats and Strings still +// box their elements as __GetItem does. +// The same cases run as compiled code, then as a script with the JIT off and on, +// and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +class CompiledItem { + public var value:Int; + public var next:CompiledItem; + + public function new(value:Int, next:CompiledItem) { + this.value = value; + this.next = next; + } +} + +class Compiled { + static function kind(value:Dynamic):String { + return if (value == null) "null" else if (Std.isOfType(value, Bool)) "Bool" else if (Std.isOfType(value, Int)) "Int" else + if (Std.isOfType(value, Float)) "Float" else if (Std.isOfType(value, String)) "String" else if (Std.isOfType(value, CompiledItem)) + "object" else if (Std.isOfType(value, Array)) "Array" else "other"; + } + + public static function run() { + var items = [new CompiledItem(1, null), null, new CompiledItem(3, new CompiledItem(4, null))]; + var indices = [0, 1, 2, 3, 7, -1, -100, 0x7fffffff, 0x80000000]; + var read = []; + for (i in indices) { + var item = items[i]; + read.push(item == null ? "null" : Std.string(item.value)); + } + Sys.println('items $read'); + Sys.println('fields ${items[0].value} ${items[2].next.value} ${items[1] == null} ${items[2].next.next == null} ${kind(items[2])}'); + var asDynamic:Dynamic = items[2]; + Sys.println('as Dynamic ${asDynamic.value} ${kind(asDynamic)} ${kind(items[5])}'); + + var mixed:Array = [7, true, 2.5, 3.0, "s", null, [1, 2], new CompiledItem(9, null), 100000]; + Sys.println('Dynamic elements ${[for (i in 0...mixed.length + 2) kind(mixed[i])]}'); + var first:Dynamic = mixed[0]; + var flag:Dynamic = mixed[1]; + Sys.println('Dynamic values $first $flag ${mixed[2]} ${mixed[3]} ${mixed[4]} ${mixed[8]}'); + + var nested = [[1, 2], [3], []]; + Sys.println('nested ${nested[0][1]} ${nested[1][0]} ${nested[2].length} ${nested[3] == null} ${kind(nested[1])}'); + + var maybe:Array> = [1, null, 300]; + Sys.println('Null ${[for (i in 0...4) kind(maybe[i])]} ${maybe[0]} ${maybe[2]}'); + + var ints = [5, 600]; + var bools = [true, false]; + var strings = ["a", null]; + var floats = [1.5, 2.0]; + Sys.println('boxed elements ${kind(ints[0])} ${kind(ints[1])} ${kind(ints[2])} ${kind(bools[0])} ${kind(bools[1])} ${kind(strings[0])} ${kind(strings[1])} ${kind(floats[0])} ${kind(floats[1])}'); + + var growing:Array = []; + var sum = 0; + for (i in 0...5000) { + growing.push(new CompiledItem(i, i > 0 ? growing[i - 1] : null)); + sum += growing[i].value + (growing[i].next == null ? 0 : growing[i].next.value); + } + growing.resize(10); + Sys.println('growing $sum ${growing[9].value} ${growing[10] == null} ${growing.length}'); + + var chain = 0; + var walk = growing[9]; + while (walk != null) { + chain++; + walk = walk.next; + } + Sys.println('chain $chain'); + } +} diff --git a/test/regression/CppiaJitObjectArrayRead/Script.hx b/test/regression/CppiaJitObjectArrayRead/Script.hx new file mode 100644 index 000000000..f2a3c96e4 --- /dev/null +++ b/test/regression/CppiaJitObjectArrayRead/Script.hx @@ -0,0 +1,67 @@ +// The same cases as Compiled in Main.hx, run as a script +class Item { + public var value:Int; + public var next:Item; + + public function new(value:Int, next:Item) { + this.value = value; + this.next = next; + } +} + +class Script { + static function kind(value:Dynamic):String { + return if (value == null) "null" else if (Std.isOfType(value, Bool)) "Bool" else if (Std.isOfType(value, Int)) "Int" else + if (Std.isOfType(value, Float)) "Float" else if (Std.isOfType(value, String)) "String" else if (Std.isOfType(value, Item)) + "object" else if (Std.isOfType(value, Array)) "Array" else "other"; + } + + static function main() { + var items = [new Item(1, null), null, new Item(3, new Item(4, null))]; + var indices = [0, 1, 2, 3, 7, -1, -100, 0x7fffffff, 0x80000000]; + var read = []; + for (i in indices) { + var item = items[i]; + read.push(item == null ? "null" : Std.string(item.value)); + } + Sys.println('items $read'); + Sys.println('fields ${items[0].value} ${items[2].next.value} ${items[1] == null} ${items[2].next.next == null} ${kind(items[2])}'); + var asDynamic:Dynamic = items[2]; + Sys.println('as Dynamic ${asDynamic.value} ${kind(asDynamic)} ${kind(items[5])}'); + + var mixed:Array = [7, true, 2.5, 3.0, "s", null, [1, 2], new Item(9, null), 100000]; + Sys.println('Dynamic elements ${[for (i in 0...mixed.length + 2) kind(mixed[i])]}'); + var first:Dynamic = mixed[0]; + var flag:Dynamic = mixed[1]; + Sys.println('Dynamic values $first $flag ${mixed[2]} ${mixed[3]} ${mixed[4]} ${mixed[8]}'); + + var nested = [[1, 2], [3], []]; + Sys.println('nested ${nested[0][1]} ${nested[1][0]} ${nested[2].length} ${nested[3] == null} ${kind(nested[1])}'); + + var maybe:Array> = [1, null, 300]; + Sys.println('Null ${[for (i in 0...4) kind(maybe[i])]} ${maybe[0]} ${maybe[2]}'); + + var ints = [5, 600]; + var bools = [true, false]; + var strings = ["a", null]; + var floats = [1.5, 2.0]; + Sys.println('boxed elements ${kind(ints[0])} ${kind(ints[1])} ${kind(ints[2])} ${kind(bools[0])} ${kind(bools[1])} ${kind(strings[0])} ${kind(strings[1])} ${kind(floats[0])} ${kind(floats[1])}'); + + var growing:Array = []; + var sum = 0; + for (i in 0...5000) { + growing.push(new Item(i, i > 0 ? growing[i - 1] : null)); + sum += growing[i].value + (growing[i].next == null ? 0 : growing[i].next.value); + } + growing.resize(10); + Sys.println('growing $sum ${growing[9].value} ${growing[10] == null} ${growing.length}'); + + var chain = 0; + var walk = growing[9]; + while (walk != null) { + chain++; + walk = walk.next; + } + Sys.println('chain $chain'); + } +} diff --git a/test/regression/CppiaJitObjectArrayRead/build.hxml b/test/regression/CppiaJitObjectArrayRead/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaJitObjectArrayRead/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaJitObjectArrayRead/stdout.txt b/test/regression/CppiaJitObjectArrayRead/stdout.txt new file mode 100644 index 000000000..48a2a2e60 --- /dev/null +++ b/test/regression/CppiaJitObjectArrayRead/stdout.txt @@ -0,0 +1,33 @@ +-- compiled +items [1,null,3,null,null,null,null,null,null] +fields 1 4 true true object +as Dynamic 3 object null +Dynamic elements [Int,Bool,Float,Int,String,null,Array,object,Int,null,null] +Dynamic values 7 true 2.5 3 s 100000 +nested 2 3 0 true Array +Null [Int,null,Int,null] 1 300 +boxed elements Int Int Int Bool Bool String null Float Int +growing 24990001 9 true 10 +chain 10 +-- script, JIT off +items [1,null,3,null,null,null,null,null,null] +fields 1 4 true true object +as Dynamic 3 object null +Dynamic elements [Int,Bool,Float,Int,String,null,Array,object,Int,null,null] +Dynamic values 7 true 2.5 3 s 100000 +nested 2 3 0 true Array +Null [Int,null,Int,null] 1 300 +boxed elements Int Int Int Bool Bool String null Float Int +growing 24990001 9 true 10 +chain 10 +-- script, JIT on +items [1,null,3,null,null,null,null,null,null] +fields 1 4 true true object +as Dynamic 3 object null +Dynamic elements [Int,Bool,Float,Int,String,null,Array,object,Int,null,null] +Dynamic values 7 true 2.5 3 s 100000 +nested 2 3 0 true Array +Null [Int,null,Int,null] 1 300 +boxed elements Int Int Int Bool Bool String null Float Int +growing 24990001 9 true 10 +chain 10 From f635250ae88121d8d9dfce8f9f2b3fc2c767033d Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 18:10:48 -0500 Subject: [PATCH 04/23] Add a cppia workload shaped like BunnyMark's update loop 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 629451b2 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. --- BENCHMARKS.md | 1 + bench/cppia/Script.hx | 75 +++++++++++++++++++++++++++++++ bench/cppia/shared/CppiaBridge.hx | 9 ++++ bench/cppia/shared/HostSprite.hx | 39 ++++++++++++++++ bench/src/CppiaBenchmarks.hx | 1 + 5 files changed, 125 insertions(+) create mode 100644 bench/cppia/shared/HostSprite.hx diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 13c3439b6..1e4bf8866 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -136,6 +136,7 @@ driver also checks that the interpreter and JIT return the same checksum. | `closure_call` | Script calls to a closure that updates a captured variable | | `native_call` | Script-to-native calls with an Int argument and result | | `native_callback` | A native loop calling a script closure that updates a captured variable | +| `bunny_update` | The update loop of OpenFL's BunnyMark over 2,000 script objects that extend a host class, moved through its Float properties, in a listener the host calls once a frame | The native timing harness loads one script module per process. Loading, linking, booting and JIT compilation happen in `setup()`, outside the timed samples. diff --git a/bench/cppia/Script.hx b/bench/cppia/Script.hx index 0c110e15f..557ae29ca 100644 --- a/bench/cppia/Script.hx +++ b/bench/cppia/Script.hx @@ -11,6 +11,7 @@ class Script { case "closure_call": new ClosureCall(); case "native_call": new NativeCall(); case "native_callback": new NativeCallback(); + case "bunny_update": new BunnyUpdate(); default: throw 'Unknown CPPIA workload ${CppiaBridge.name}'; }; } @@ -147,3 +148,77 @@ class NativeCallback implements CppiaWorkload { }); } } + +// Shaped like the update loop of OpenFL's BunnyMark: script objects that extend +// a host display object, moved through its Float properties, read from an +// array, by a listener the host calls once a frame +class Bunny extends HostSprite { + public var speedX:Float = 0; + public var speedY:Float = 0; + + public function new() { + super(); + } +} + +class BunnyUpdate implements CppiaWorkload { + static inline var COUNT = 2000; + static inline var FRAMES = 10; + static inline var GRAVITY = 0.5; + static inline var MAX_X = 800.0; + static inline var MAX_Y = 600.0; + + final bunnies:Array = []; + var seed = 1; + + public function new() { + for (i in 0...COUNT) + bunnies.push(new Bunny()); + } + + // The same numbers each run, interpreted or jitted, where Math.random would not be + function random():Float { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 2147483647.0; + } + + function onFrame(frame:Int):Void { + for (bunny in bunnies) { + bunny.x += bunny.speedX; + bunny.y += bunny.speedY; + bunny.speedY += GRAVITY; + if (bunny.x > MAX_X) { + bunny.speedX *= -1; + bunny.x = MAX_X; + } else if (bunny.x < 0) { + bunny.speedX *= -1; + bunny.x = 0; + } + if (bunny.y > MAX_Y) { + bunny.speedY *= -0.8; + bunny.y = MAX_Y; + if (random() > 0.5) + bunny.speedY -= 3 + random() * 4; + } else if (bunny.y < 0) { + bunny.speedY = 0; + bunny.y = 0; + } + } + } + + public function run():Int { + seed = 1; + for (bunny in bunnies) { + bunny.x = random() * MAX_X; + bunny.y = random() * MAX_Y; + bunny.speedX = random() * 5; + bunny.speedY = random() * 5 - 2.5; + bunny.changes = 0; + } + CppiaBridge.frames(FRAMES, onFrame); + var sum = 0; + for (bunny in bunnies) + sum += Std.int(bunny.x) + Std.int(bunny.y) * 3 + bunny.changes; + return sum; + } +} diff --git a/bench/cppia/shared/CppiaBridge.hx b/bench/cppia/shared/CppiaBridge.hx index aa34843fd..644516ec3 100644 --- a/bench/cppia/shared/CppiaBridge.hx +++ b/bench/cppia/shared/CppiaBridge.hx @@ -5,12 +5,21 @@ package; class CppiaBridge { public static var name:String; public static var workload:CppiaWorkload; + // Builds HostSprite into the host, for script classes to extend + public static var spriteClass:Class = HostSprite; @:noInline public static function step(value:Int):Int { return value ^ (value >>> 3) ^ 0x1357; } + // As a stage dispatches ENTER_FRAME to a listener + @:noInline + public static function frames(count:Int, onFrame:Int->Void):Void { + for (i in 0...count) + onFrame(i); + } + @:noInline public static function repeat(count:Int, callback:Int->Int):Int { var sum = 0; diff --git a/bench/cppia/shared/HostSprite.hx b/bench/cppia/shared/HostSprite.hx new file mode 100644 index 000000000..1458e675b --- /dev/null +++ b/bench/cppia/shared/HostSprite.hx @@ -0,0 +1,39 @@ +package; + +/** + A display object of the host, as OpenFL's DisplayObject is to a script: + Float properties whose setters mark it changed. Script classes extend it. +**/ +@:keep +class HostSprite { + public var x(get, set):Float; + public var y(get, set):Float; + public var changes:Int = 0; + + var _x:Float = 0; + var _y:Float = 0; + + public function new() {} + + function get_x():Float + return _x; + + function set_x(value:Float):Float { + if (value != _x) { + _x = value; + changes++; + } + return value; + } + + function get_y():Float + return _y; + + function set_y(value:Float):Float { + if (value != _y) { + _y = value; + changes++; + } + return value; + } +} diff --git a/bench/src/CppiaBenchmarks.hx b/bench/src/CppiaBenchmarks.hx index da258883f..eb907374d 100644 --- a/bench/src/CppiaBenchmarks.hx +++ b/bench/src/CppiaBenchmarks.hx @@ -23,6 +23,7 @@ class CppiaBenchmarks extends Benchmark { result.push(new CppiaBenchmarks("closure_call", "calls", 200000, 10, jit)); result.push(new CppiaBenchmarks("native_call", "calls", 200000, 50, jit)); result.push(new CppiaBenchmarks("native_callback", "callbacks", 200000, 10, jit)); + result.push(new CppiaBenchmarks("bunny_update", "bunny updates", 20000, 10, jit)); } return result; } From 78ce89157ddcfb3602d79e763286bb95b9071e7a Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 19:17:45 -0500 Subject: [PATCH 05/23] Compare the cppia workloads with HashLink in the bench 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 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. --- BENCHMARKS.md | 13 ++++ bench/Run.hx | 63 ++++++++++++++++++- bench/cppia/shared/CppiaWorkloads.hx | 20 ++++++ bench/hl/HlMain.hx | 94 ++++++++++++++++++++++++++++ bench/src/CppiaBenchmarks.hx | 13 +--- 5 files changed, 190 insertions(+), 13 deletions(-) create mode 100644 bench/cppia/shared/CppiaWorkloads.hx create mode 100644 bench/hl/HlMain.hx diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 1e4bf8866..a1794acce 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -152,6 +152,18 @@ so those flags do not change the native benchmarks. Peak memory for these cases includes the host, loaded module and any JIT code. The `noop` startup row still measures the native executable. +### HashLink as a reference + +`--hl ` also runs the CPPIA workloads on HashLink's JIT. `bench/hl` +builds `Script.hx` and `bench/cppia/shared` straight to HashLink with the same +harness, workload table and timing, so there the host's side of each workload +is HashLink JIT code too, where under cppia it is native C++. Its processes take +turns with the others on the `cppia_jit_` benchmarks and must give the same +checksums, and the CPPIA table gains an HL/JIT column and the JIT's ratio to it. +A host with its framework compiled in should not run a script slower than +HashLink runs the whole application, so a ratio below 1 there is a target. + + ## Running it yourself You need Haxe 4.3, the C++ compiler hxcpp uses on your platform, and curl. @@ -161,6 +173,7 @@ cd bench haxe --run Run # every benchmark, both runtimes haxe --run Run --only map_int,sort_int haxe --run Run --only cppia_interp_native_call,cppia_jit_native_call +haxe --run Run --only cppia_jit_closure_call --hl path/to/hl # with HashLink beside it haxe --run Run --no-build # reuse the last builds haxe --run Run --only gc_object_ids --define HXCPP_GC_GENERATIONAL haxe --run Run --readme # publish: this page and the README summary diff --git a/bench/Run.hx b/bench/Run.hx index 6b61e12a4..f4739d1a1 100644 --- a/bench/Run.hx +++ b/bench/Run.hx @@ -42,6 +42,13 @@ using StringTools; --warmup untimed samples per process (default 2) --no-build reuse the existing builds --out results JSON (default .work/results.json) + --hl also run the CPPIA workloads on HashLink's JIT, as a + reference for the cppia JIT: bench/hl builds them, + with the bridge in bench/cppia/shared, straight to + HashLink, so the host's side runs as HashLink JIT + code. Its processes take turns with the others on + the cppia_jit_ benchmarks and must give the same + checksums, and the CPPIA table gains an HL column --readme publish the results: the full tables go into BENCHMARKS.md and a summary of the key measures into README.md. Needs every benchmark, both runtimes and a @@ -98,6 +105,8 @@ class Run { static var build = true; static var outFile:Null = null; static var writeReadme = false; + static var hlExe:Null = null; + static var hl:Null = null; static function main() { benchDir = FileSystem.absolutePath("."); @@ -148,6 +157,14 @@ class Run { Sys.println('${rt.label}: ${rt.env.compiler}, ${rt.env.pointerBits}-bit, API level ${rt.env.apiLevel}'); } checkComparable(runtimes); + if (hlExe != null && needsCppia()) { + hl = new Runtime("hl", hlLabel(), workDir + "/hl"); + if (build) + buildHl(); + if (!FileSystem.exists(hl.dir + "/bench.hl")) + fail('${hl.label}: ${hl.dir}/bench.hl is missing; run without --no-build'); + Sys.println('${hl.label}: ${hlExe}'); + } var names = listBenchmarks(runtimes[0]); if (needsCppia()) @@ -178,7 +195,7 @@ class Run { failures++; Sys.println('FAILED: ${r.error}'); } else - Sys.println([for (rt in runtimes) '${rt.label} ${formatRate(r.byRuntime.get(rt.name).rate, r.unit)}'].join(", ")); + Sys.println([for (rt in (hl != null && r.byRuntime.exists(hl.name) ? runtimes.concat([hl]) : runtimes)) '${rt.label} ${formatRate(r.byRuntime.get(rt.name).rate, r.unit)}'].join(", ")); results.push(r); } @@ -188,6 +205,7 @@ class Run { haxe: commandOutput("haxe", ["-version"]), libhxcpp: gitDescribe(), runtimes: [for (rt in runtimes) {name: rt.name, label: rt.label, commit: rt.commit, env: rt.env, cppiaEnv: rt.cppiaEnv}], + hashlink: hl == null ? null : {name: hl.name, label: hl.label, exe: hlExe}, skipped: skipped, settings: {runs: runs, samples: samples, warmup: warmup}, startup: [for (rt in runtimes) {name: rt.name, seconds: startup[rt.name]}], @@ -261,6 +279,10 @@ class Run { build = false; case "--out": outFile = FileSystem.absolutePath(value()); + case "--hl": + hlExe = FileSystem.absolutePath(value()); + if (!FileSystem.exists(hlExe)) + fail('--hl: $hlExe does not exist'); case "--readme": writeReadme = true; default: @@ -374,6 +396,24 @@ class Run { return true; } + /** Builds the CPPIA workloads for HashLink with bench/hl's harness. **/ + static function buildHl() { + FileSystem.createDirectory(hl.dir); + Sys.println('Building ${hl.label} (log: ${hl.dir}/build.log)'); + var command = 'haxe -cp "${benchDir}/hl" -cp "${benchDir}/cppia" -cp "${benchDir}/cppia/shared" -main HlMain -hl bench.hl'; + if (inDir(hl.dir, () -> Sys.command('$command > build.log 2>&1')) != 0) { + var log = File.getContent(hl.dir + "/build.log").split("\n"); + Sys.println(log.slice(log.length > 40 ? log.length - 40 : 0).join("\n")); + fail('${hl.label}: build failed'); + } + } + + /** "HashLink 1.16.0", from the executable's own --version. **/ + static function hlLabel():String { + var version = commandOutput(hlExe, ["--version"]); + return version == "" ? "HashLink" : 'HashLink $version'; + } + static function needsCppia():Bool { if (!cppia) return false; @@ -428,6 +468,8 @@ class Run { } static function runBenchmark(name:String, runtimes:Array):BenchResult { + if (hl != null && name.startsWith("cppia_jit_")) + runtimes = runtimes.concat([hl]); var result = new BenchResult(name); var raw = [for (rt in runtimes) rt.name => new Array()]; var checksum:Null = null; @@ -543,6 +585,10 @@ class Run { if (compare) all.push('${modes[mode]} vs stock'); } + if (hl != null && lib != null) { + all.push('HL/JIT, ${hl.label}'); + all.push('JIT vs HL'); + } b.add("| " + all.join(" | ") + " |\n"); b.add("|" + [for (i in 0...all.length) i < first.length ? " --- " : " ---: "].join("|") + "|\n"); for (workload in cppia) { @@ -559,6 +605,15 @@ class Run { row += " | " + ratio(r.byRuntime.get(lib.name).rate, r.byRuntime.get(stock.name).rate, Math.max(r.byRuntime.get(lib.name).spread, r.byRuntime.get(stock.name).spread), LAYOUT_BAND); } + if (hl != null && lib != null) { + var r = byName['cppia_jit_$workload']; + var h = r == null ? null : r.byRuntime.get(hl.name); + if (h == null || r.error != null) + row += " | failed | "; + else + row += " | " + formatRate(h.rate, null) + " ±" + percent(h.spread) + " | " + + ratio(r.byRuntime.get(lib.name).rate, h.rate, Math.max(r.byRuntime.get(lib.name).spread, h.spread), LAYOUT_BAND); + } b.add(row + " |\n"); } } @@ -736,8 +791,10 @@ class Run { /** Runs the benchmark executable and returns its stdout; throws if it fails. **/ static function benchProcess(rt:Runtime, args:Array, cppia = false):String { - var exe = cppia || args[0].startsWith("cppia_") ? rt.cppiaExe : rt.exe; - var p = new Process(exe, args); + var p = if (rt.name == "hl") + new Process(hlExe, [rt.dir + "/bench.hl"].concat(args)); + else + new Process(cppia || args[0].startsWith("cppia_") ? rt.cppiaExe : rt.exe, args); var out = p.stdout.readAll().toString(); var err = p.stderr.readAll().toString(); var code = p.exitCode(); diff --git a/bench/cppia/shared/CppiaWorkloads.hx b/bench/cppia/shared/CppiaWorkloads.hx new file mode 100644 index 000000000..215580179 --- /dev/null +++ b/bench/cppia/shared/CppiaWorkloads.hx @@ -0,0 +1,20 @@ +package; + +/** + The CPPIA workloads, each with what one run() counts as an operation, how + many it does and how many runs make a timed sample. The cppia harness + (bench/src/CppiaBenchmarks.hx) and the HashLink one (bench/hl/HlMain.hx) + both read this, so they time the same work. +**/ +class CppiaWorkloads { + public static final all:Array<{name:String, unit:String, ops:Int, reps:Int}> = [ + {name: "int_loop", unit: "iterations", ops: 500000, reps: 20}, + {name: "float_array", unit: "elements", ops: 200000, reps: 10}, + {name: "alloc_objects", unit: "objects", ops: 125000, reps: 4}, + {name: "virtual_call", unit: "calls", ops: 200000, reps: 10}, + {name: "closure_call", unit: "calls", ops: 200000, reps: 10}, + {name: "native_call", unit: "calls", ops: 200000, reps: 50}, + {name: "native_callback", unit: "callbacks", ops: 200000, reps: 10}, + {name: "bunny_update", unit: "bunny updates", ops: 20000, reps: 10}, + ]; +} diff --git a/bench/hl/HlMain.hx b/bench/hl/HlMain.hx new file mode 100644 index 000000000..76806df76 --- /dev/null +++ b/bench/hl/HlMain.hx @@ -0,0 +1,94 @@ +package; + +import haxe.Json; +import haxe.Timer; + +/** + The CPPIA workloads built for HashLink, as a reference for the cppia JIT. + Script.hx and the bridge in bench/cppia/shared are compiled straight to + HashLink bytecode with this harness, so on HashLink the host's side of + each workload is JIT code too, where under cppia it is native C++. + + hl bench.hl list + hl bench.hl [--warmup N] [--samples N] + + A workload may be named as its cppia benchmark is, cppia_jit_. + It times them as bench/src/Main.hx does, and prints the same BENCH_RESULT + line, so Run.hx (--hl) can run it beside the cppia hosts and require the + same checksum. +**/ +class HlMain { + static function main() { + var args = Sys.args(); + if (args.length == 0) { + Sys.println("usage: hl bench.hl list | [--warmup N] [--samples N]"); + Sys.exit(2); + } + if (args[0] == "list") { + for (w in CppiaWorkloads.all) + Sys.println(w.name); + return; + } + + var warmup = 2; + var samples = 10; + var i = 1; + while (i < args.length) { + switch (args[i]) { + case "--warmup": + warmup = Std.parseInt(args[++i]); + case "--samples": + samples = Std.parseInt(args[++i]); + default: + fail('unknown option ${args[i]}'); + } + i++; + } + + var name = StringTools.startsWith(args[0], "cppia_jit_") ? args[0].substr("cppia_jit_".length) : args[0]; + var entry = null; + for (w in CppiaWorkloads.all) + if (w.name == name) + entry = w; + if (entry == null) + fail('unknown workload $name'); + + CppiaBridge.name = name; + CppiaBridge.workload = null; + @:privateAccess Script.main(); + var workload = CppiaBridge.workload; + + var checksum = 0; + var times:Array = []; + for (s in 0...warmup + samples) { + // Each sample starts from the same heap state, outside the timed section + hl.Gc.major(); + var t0 = Timer.stamp(); + var r = 0; + for (k in 0...entry.reps) + r = (r * 31 + workload.run()) | 0; + var t = Timer.stamp() - t0; + checksum = (checksum * 31 + r) | 0; + if (s >= warmup) + times.push(t); + } + + Sys.println("BENCH_RESULT " + Json.stringify({ + name: args[0], + unit: entry.unit, + ops: entry.ops * entry.reps, + warmup: warmup, + samples: samples, + times: times, + latency: null, + checksum: checksum, + peakRss: 0, + })); + } + + static function fail(message:String):Dynamic { + Sys.stderr().writeString(message + "\n"); + Sys.exit(2); + return null; + } +} diff --git a/bench/src/CppiaBenchmarks.hx b/bench/src/CppiaBenchmarks.hx index eb907374d..f9bc735c0 100644 --- a/bench/src/CppiaBenchmarks.hx +++ b/bench/src/CppiaBenchmarks.hx @@ -15,16 +15,9 @@ class CppiaBenchmarks extends Benchmark { public static function all():Array { var result:Array = []; - for (jit in [false, true]) { - result.push(new CppiaBenchmarks("int_loop", "iterations", 500000, 20, jit)); - result.push(new CppiaBenchmarks("float_array", "elements", 200000, 10, jit)); - result.push(new CppiaBenchmarks("alloc_objects", "objects", 125000, 4, jit)); - result.push(new CppiaBenchmarks("virtual_call", "calls", 200000, 10, jit)); - result.push(new CppiaBenchmarks("closure_call", "calls", 200000, 10, jit)); - result.push(new CppiaBenchmarks("native_call", "calls", 200000, 50, jit)); - result.push(new CppiaBenchmarks("native_callback", "callbacks", 200000, 10, jit)); - result.push(new CppiaBenchmarks("bunny_update", "bunny updates", 20000, 10, jit)); - } + for (jit in [false, true]) + for (w in CppiaWorkloads.all) + result.push(new CppiaBenchmarks(w.name, w.unit, w.ops, w.reps, jit)); return result; } From 8da1825bfa58f44c7530a84bde01bb998e24dfc4 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 19:17:56 -0500 Subject: [PATCH 06/23] Add a cppia workload shaped like an OpenFL application's frame 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. --- BENCHMARKS.md | 1 + bench/cppia/Script.hx | 93 +++++++++++++++++++++++++ bench/cppia/shared/CppiaBridge.hx | 1 + bench/cppia/shared/CppiaWorkloads.hx | 1 + bench/cppia/shared/HostContainer.hx | 68 ++++++++++++++++++ bench/cppia/shared/HostDispatcher.hx | 34 +++++++++ bench/cppia/shared/HostDisplayObject.hx | 72 +++++++++++++++++++ bench/cppia/shared/HostEvent.hx | 12 ++++ 8 files changed, 282 insertions(+) create mode 100644 bench/cppia/shared/HostContainer.hx create mode 100644 bench/cppia/shared/HostDispatcher.hx create mode 100644 bench/cppia/shared/HostDisplayObject.hx create mode 100644 bench/cppia/shared/HostEvent.hx diff --git a/BENCHMARKS.md b/BENCHMARKS.md index a1794acce..42ece1e6a 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -137,6 +137,7 @@ driver also checks that the interpreter and JIT return the same checksum. | `native_call` | Script-to-native calls with an Int argument and result | | `native_callback` | A native loop calling a script closure that updates a captured variable | | `bunny_update` | The update loop of OpenFL's BunnyMark over 2,000 script objects that extend a host class, moved through its Float properties, in a listener the host calls once a frame | +| `openfl_frame` | An OpenFL application's frame: 1,000 script objects extending a host display object, moved by an ENTER_FRAME listener the host calls, one in ten with a closure listener of its own, a small object made each update, dead ones replaced, and a host render reading every transform | The native timing harness loads one script module per process. Loading, linking, booting and JIT compilation happen in `setup()`, outside the timed samples. diff --git a/bench/cppia/Script.hx b/bench/cppia/Script.hx index 557ae29ca..cfd679121 100644 --- a/bench/cppia/Script.hx +++ b/bench/cppia/Script.hx @@ -12,6 +12,7 @@ class Script { case "native_call": new NativeCall(); case "native_callback": new NativeCallback(); case "bunny_update": new BunnyUpdate(); + case "openfl_frame": new OpenflFrame(); default: throw 'Unknown CPPIA workload ${CppiaBridge.name}'; }; } @@ -222,3 +223,95 @@ class BunnyUpdate implements CppiaWorkload { return sum; } } + +// Shaped like an OpenFL application's frame: a scene of script display objects +// that extend the host's, moved by a listener the host calls on ENTER_FRAME, +// one in ten with a listener of its own given as a closure, each update making a +// small object as a Point would, the dead replaced, and the host rendering the +// scene by reading every transform +class Particle extends HostDisplayObject { + public var vx:Float = 0; + public var vy:Float = 0; + public var life:Int = 0; + + public function new() { + super(); + } +} + +class Step { + public var dx:Float; + public var dy:Float; + + public function new(dx:Float, dy:Float) { + this.dx = dx; + this.dy = dy; + } +} + +class Scene extends HostContainer { + public function new() { + super(); + } +} + +class OpenflFrame implements CppiaWorkload { + static inline var COUNT = 1000; + static inline var FRAMES = 10; + + var seed = 1; + var spawned = 0; + var spins = 0; + var scene:Scene; + var particles:Array; + + public function new() {} + + function random():Float { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 2147483647.0; + } + + function spawn():Particle { + var p = new Particle(); + p.x = random() * 800; + p.y = random() * 600; + p.vx = random() * 4 - 2; + p.vy = random() * 4 - 2; + p.life = 3 + Std.int(random() * 80); + if (spawned++ % 10 == 0) + p.addEventListener("enterFrame", e -> { + p.rotation += 3; + spins++; + }); + scene.addChild(p); + return p; + } + + function onEnterFrame(e:HostEvent):Void { + for (i in 0...particles.length) { + var p = particles[i]; + var step = new Step(p.vx, p.vy + 0.1); + p.x += step.dx; + p.y += step.dy; + p.vy = step.dy; + p.alpha = p.life / 80; + if (--p.life <= 0) { + scene.removeChild(p); + particles[i] = spawn(); + } + } + } + + public function run():Int { + seed = 1; + spawned = 0; + spins = 0; + scene = new Scene(); + particles = []; + scene.addEventListener("enterFrame", onEnterFrame); + for (i in 0...COUNT) + particles.push(spawn()); + return HostContainer.runFrames(scene, FRAMES) + spins * 1000 + scene.numChildren; + } +} diff --git a/bench/cppia/shared/CppiaBridge.hx b/bench/cppia/shared/CppiaBridge.hx index 644516ec3..37b23c11c 100644 --- a/bench/cppia/shared/CppiaBridge.hx +++ b/bench/cppia/shared/CppiaBridge.hx @@ -7,6 +7,7 @@ class CppiaBridge { public static var workload:CppiaWorkload; // Builds HostSprite into the host, for script classes to extend public static var spriteClass:Class = HostSprite; + public static var containerClass:Class = HostContainer; @:noInline public static function step(value:Int):Int { diff --git a/bench/cppia/shared/CppiaWorkloads.hx b/bench/cppia/shared/CppiaWorkloads.hx index 215580179..5c551667b 100644 --- a/bench/cppia/shared/CppiaWorkloads.hx +++ b/bench/cppia/shared/CppiaWorkloads.hx @@ -16,5 +16,6 @@ class CppiaWorkloads { {name: "native_call", unit: "calls", ops: 200000, reps: 50}, {name: "native_callback", unit: "callbacks", ops: 200000, reps: 10}, {name: "bunny_update", unit: "bunny updates", ops: 20000, reps: 10}, + {name: "openfl_frame", unit: "object frames", ops: 10000, reps: 5}, ]; } diff --git a/bench/cppia/shared/HostContainer.hx b/bench/cppia/shared/HostContainer.hx new file mode 100644 index 000000000..81168a8ea --- /dev/null +++ b/bench/cppia/shared/HostContainer.hx @@ -0,0 +1,68 @@ +package; + +/** + A display object container of the host, as OpenFL's DisplayObjectContainer + is, and the frame loop a stage runs over it: ENTER_FRAME to every object + with a listener, then a render that reads each object's transform. +**/ +@:keep +class HostContainer extends HostDisplayObject { + var children:Array = []; + + public var numChildren(get, never):Int; + + public function new() { + super(); + } + + function get_numChildren():Int + return children.length; + + public function addChild(child:HostDisplayObject):HostDisplayObject { + if (child.parent != null) + child.parent.removeChild(child); + @:privateAccess child.parent = this; + children.push(child); + return child; + } + + public function removeChild(child:HostDisplayObject):HostDisplayObject { + if (children.remove(child)) + @:privateAccess child.parent = null; + return child; + } + + public function getChildAt(index:Int):HostDisplayObject + return children[index]; + + /** Runs frames as a stage does, and returns what the renders read. **/ + @:noInline + public static function runFrames(root:HostContainer, frames:Int):Int { + var sum = 0; + for (f in 0...frames) { + broadcast(root, new HostEvent("enterFrame")); + sum = (sum * 31 + render(root)) | 0; + } + return sum; + } + + static function broadcast(object:HostDisplayObject, event:HostEvent) { + if (object.hasEventListener(event.type)) + object.dispatchEvent(event); + if (Std.isOfType(object, HostContainer)) { + var container:HostContainer = cast object; + for (i in 0...container.children.length) + broadcast(container.children[i], event); + } + } + + static function render(object:HostDisplayObject):Int { + var sum = object.renderValue(); + if (Std.isOfType(object, HostContainer)) { + var container:HostContainer = cast object; + for (i in 0...container.children.length) + sum += render(container.children[i]); + } + return sum; + } +} diff --git a/bench/cppia/shared/HostDispatcher.hx b/bench/cppia/shared/HostDispatcher.hx new file mode 100644 index 000000000..60b9f6d8b --- /dev/null +++ b/bench/cppia/shared/HostDispatcher.hx @@ -0,0 +1,34 @@ +package; + +/** An event dispatcher of the host, as OpenFL's EventDispatcher is: listeners by type, called in order. **/ +@:keep +class HostDispatcher { + var listeners:MapVoid>> = null; + + public function new() {} + + public function addEventListener(type:String, listener:HostEvent->Void):Void { + if (listeners == null) + listeners = new Map(); + var list = listeners.get(type); + if (list == null) + listeners.set(type, list = []); + list.push(listener); + } + + public function hasEventListener(type:String):Bool { + return listeners != null && listeners.exists(type); + } + + public function dispatchEvent(event:HostEvent):Bool { + if (listeners == null) + return false; + var list = listeners.get(event.type); + if (list == null) + return false; + event.target = this; + for (i in 0...list.length) + list[i](event); + return true; + } +} diff --git a/bench/cppia/shared/HostDisplayObject.hx b/bench/cppia/shared/HostDisplayObject.hx new file mode 100644 index 000000000..859d89ddb --- /dev/null +++ b/bench/cppia/shared/HostDisplayObject.hx @@ -0,0 +1,72 @@ +package; + +/** + A display object of the host, as OpenFL's DisplayObject is: transform + properties whose setters mark it for the next render, in a container. +**/ +@:keep +class HostDisplayObject extends HostDispatcher { + public var x(get, set):Float; + public var y(get, set):Float; + public var rotation(get, set):Float; + public var alpha(get, set):Float; + public var parent(default, null):HostContainer; + + var _x:Float = 0; + var _y:Float = 0; + var _rotation:Float = 0; + var _alpha:Float = 1; + var transformDirty = false; + + public function new() { + super(); + } + + function get_x():Float + return _x; + + function set_x(value:Float):Float { + if (value != _x) { + _x = value; + transformDirty = true; + } + return value; + } + + function get_y():Float + return _y; + + function set_y(value:Float):Float { + if (value != _y) { + _y = value; + transformDirty = true; + } + return value; + } + + function get_rotation():Float + return _rotation; + + function set_rotation(value:Float):Float { + if (value != _rotation) { + _rotation = value; + transformDirty = true; + } + return value; + } + + function get_alpha():Float + return _alpha; + + function set_alpha(value:Float):Float { + _alpha = value; + return value; + } + + /** What a render reads of it, and clears. **/ + public function renderValue():Int { + var v = Std.int(_x) + Std.int(_y) * 3 + Std.int(_rotation) * 7 + Std.int(_alpha * 100) + (transformDirty ? 1 : 0); + transformDirty = false; + return v; + } +} diff --git a/bench/cppia/shared/HostEvent.hx b/bench/cppia/shared/HostEvent.hx new file mode 100644 index 000000000..5a8999201 --- /dev/null +++ b/bench/cppia/shared/HostEvent.hx @@ -0,0 +1,12 @@ +package; + +/** An event of the host, as OpenFL's Event is to a script. **/ +@:keep +class HostEvent { + public var type:String; + public var target:HostDispatcher; + + public function new(type:String) { + this.type = type; + } +} From 81bfce1c1582bf25c5e92a5c0d694556e5797e7c Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 19:30:26 -0500 Subject: [PATCH 07/23] Call compiled script closures directly from jitted cppia code 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 , 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 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 26 ++++ src/hx/cppia/Cppia.h | 16 ++ src/hx/cppia/CppiaFunction.cpp | 95 ++++++++++-- test/regression/CppiaJitClosureDirect/Main.hx | 140 ++++++++++++++++++ .../CppiaJitClosureDirect/Script.hx | 119 +++++++++++++++ .../CppiaJitClosureDirect/build.hxml | 7 + .../CppiaJitClosureDirect/stdout.txt | 24 +++ 8 files changed, 417 insertions(+), 11 deletions(-) create mode 100644 test/regression/CppiaJitClosureDirect/Main.hx create mode 100644 test/regression/CppiaJitClosureDirect/Script.hx create mode 100644 test/regression/CppiaJitClosureDirect/build.hxml create mode 100644 test/regression/CppiaJitClosureDirect/stdout.txt diff --git a/Changes.md b/Changes.md index 9098d391a..f65c3fa73 100644 --- a/Changes.md +++ b/Changes.md @@ -5,6 +5,7 @@ libhxcpp 6.0.3 (unreleased) * The cppia JIT compiles a script's local functions, the closures written inside a function or an initializer, as it compiles class functions, when each is first called. No class holds them, so they were never compiled: under the JIT their bodies ran in the interpreter, whether jitted code called them or the host called them back. Jitted code calling a closure is 1.9x faster (closure_call), and the host calling one back 2.5x (native_callback). HXCPP_CPPIA_EAGER_JIT compiles them as the module loads, with the rest (HaxeFoundation/hxcpp#1213) * A cppia script calling one of its closures, or a bound method held as a value, passes the arguments and takes the result as they are when the function takes the same types, interpreted and under the JIT. Each argument was boxed into a Dynamic for __run and unboxed into the function's frame, and the result boxed and unboxed again, which allocated for most Ints and every Float. Calling a closure that takes and returns an Int is 1.8x faster under the JIT and 1.2x interpreted (closure_call). An argument of another type, more arguments than the function takes, and host functions are boxed as before * The cppia JIT reads an element of an array of objects, such as an Array of a script class, in place when the element is wanted as an object, as it reads one wanted as anything else. It called a helper that went through the array's virtual __GetItem and built a Dynamic of the element, which an object element does not need. Under the JIT, virtual calls through an array of objects are 1.4x faster (virtual_call) and allocation that reads one 1.2x (alloc_objects). Arrays of Ints, Bools, Floats and Strings still box their elements through __GetItem +* Jitted cppia code calls a script closure whose function takes its arguments and gives its result as they are, and is compiled, as it calls a known function: one check of the closure and its function's signature, its captured variables put in the frame, and a call of the compiled code. The general way through a helper, which compiled the function on its first call and boxed what did not match, is left for everything else. Calling a closure that takes and returns an Int is 1.6x faster under the JIT (closure_call), 0.61x of HashLink 1.16's JIT where it was 0.38x libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index be8981252..912a68266 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -3440,6 +3440,8 @@ struct Call : public CppiaDynamicExpr CppiaExpr *func; // Each argument's CallArgKind std::vector argKinds; + // The arguments' types as a script function's signature has them + std::string argSignature; Call(CppiaStream &stream) { @@ -3473,6 +3475,16 @@ struct Call : public CppiaDynamicExpr default: argKinds[a] = cakObject; } } + argSignature = "("; + for(int a=0;aadd(sJitCtxFrame, sJitFrame, compiler->getCurrentFrameSize()); ExprType resultType = destType==etNull ? etVoid : destType; + + // A script closure whose function takes these arguments, and gives the result + // wanted, as they are, and is compiled, is called as a direct call calls, + // with its result where the general way leaves one + int signature = internCallSignature(resultType==etVoid ? argSignature : argSignature + callReturnCode(resultType)); + compiler->callNative((void *)enterScriptClosure, sJitCtx, functionObject, JitVal(signature)); + compiler->move(sJitTemp1.as(jtPointer), sJitReturnReg.as(jtPointer)); + JumpId general = compiler->compare(cmpP_EQUAL, sJitTemp1.as(jtPointer), (void *)0); + compiler->call(sJitTemp1, sJitCtx); + compiler->setMaxPointer(); + JumpId called = compiler->jump(); + compiler->comeFrom(general); + void *helper = 0; switch(resultType) { @@ -3846,6 +3871,7 @@ struct Call : public CppiaDynamicExpr default: helper = (void *)runJit; } compiler->callNative(helper, sJitCtx, functionObject, JitVal((void *)this)); + compiler->comeFrom(called); compiler->checkException(); if (resultType!=etVoid) diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index e21ded1b6..71bbf7875 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -328,6 +328,12 @@ struct ScriptCallable : public CppiaDynamicExpr std::vector captureVars; int captureSize; + // What jitted code calling a closure of this function compares, interned by + // internCallSignature: the arguments' types, and those with the return type. + // 0 for a function a closure cannot be made of + int callSigArgs; + int callSigFull; + ScriptCallable(CppiaStream &stream); ScriptCallable(CppiaExpr *inBody); @@ -422,6 +428,16 @@ ScriptCallable *scriptClosureTarget(hx::Object *inFunction); void runScriptClosure(CppiaCtx *ctx, hx::Object *inClosure, int inArgCount, bool inThrow); // The result runScriptClosure left, boxed as a call through __run returns it hx::Object *boxScriptClosureResult(CppiaCtx *ctx, ScriptCallable *inFunction); +// A number for a call signature, the same for the same text and never 0 +int internCallSignature(const std::string &inSignature); +// The letter a call signature ends with for a function returning inType +char callReturnCode(ExprType inType); +#ifdef CPPIA_JIT +// The compiled code of the script closure inFunction, with its this and captured +// variables written to the frame at ctx->frame, when its function's signature is +// inSignature and its frame fits the stack; 0 when the call must go the general way +CppiaFunc enterScriptClosure(CppiaCtx *ctx, hx::Object *inFunction, int inSignature); +#endif CppiaClassInfo *getScriptClassInfo(hx::Object *inClass); hx::Object *createEnumClosure(struct CppiaEnumConstructor &inContructor); diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index 8810c5e00..bd2785135 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -39,6 +39,8 @@ ScriptCallable::ScriptCallable(CppiaStream &stream) hasDefault.resize(argCount); initVals.resize(argCount); captureSize = 0; + callSigArgs = 0; + callSigFull = 0; hasDefaults = false; staticEntry = false; #ifdef CPPIA_JIT @@ -66,6 +68,8 @@ ScriptCallable::ScriptCallable(CppiaExpr *inBody) : CppiaDynamicExpr(inBody) argCount = 0; stackSize = 0; captureSize = 0; + callSigArgs = 0; + callSigFull = 0; hasDefaults = false; body = inBody; data = 0; @@ -102,6 +106,8 @@ ScriptCallable::ScriptCallable(CppiaModule &inModule,ScriptNamedFunction *inFunc argCount = 0; stackSize = 0; captureSize = 0; + callSigArgs = 0; + callSigFull = 0; hasDefaults = false; //body = inBody; data = 0; @@ -163,6 +169,33 @@ ScriptCallable::~ScriptCallable() #endif } +// Call signatures are interned once for every module, which may link on any thread +int internCallSignature(const std::string &inSignature) +{ + static std::mutex &lock = *new std::mutex(); + static std::map &ids = *new std::map(); + std::lock_guard hold(lock); + std::map::iterator it = ids.find(inSignature); + if (it!=ids.end()) + return it->second; + int id = (int)ids.size() + 1; + ids[inSignature] = id; + return id; +} + +// A Bool comes back as an Int, which a call wanting an Int takes as it is +char callReturnCode(ExprType inType) +{ + switch(inType) + { + case etInt: return 'i'; + case etFloat: return 'f'; + case etString: return 's'; + case etObject: return 'o'; + default: return 'v'; + } +} + CppiaExpr *ScriptCallable::link(CppiaModule &inModule) { StackLayout *oldLayout = inModule.layout; @@ -203,6 +236,20 @@ CppiaExpr *ScriptCallable::link(CppiaModule &inModule) stackSize = layout.size; inModule.layout = oldLayout; + // A call passes an object as it is only where no array conversion is wanted + std::string signature = "("; + for(int a=0;aarrayType!=arrNotArray ? 'a' : 'o'; + } + signature += ")"; + callSigArgs = internCallSignature(signature); + callSigFull = internCallSignature(signature + callReturnCode(returnType)); + position.className = className; position.functionName = functionName; position.fileName = filename; @@ -929,25 +976,29 @@ class CppiaClosure : public hx::Object } - // Runs the function in the frame at ctx->frame, which holds a slot for this and - // the first inHaveArgs arguments, with ctx->pointer past them, and leaves its result - // at ctx->frame. An exception from compiled code is thrown, or with !inThrow left in - // ctx->exception - void runInFrame(CppiaCtx *ctx, int inHaveArgs, bool inThrow) + // Writes this and the captured variables into the frame at inFrame + void enterFrame(unsigned char *inFrame) { - function->addExtraDefaults(ctx,inHaveArgs); - function->addStackVarsSpace(ctx); - unsigned char *base = ((unsigned char *)this) + sizeof(CppiaClosure); - // this pointer... - CppiaCtx::setSlot(ctx->frame, *(hx::Object **)base); + CppiaCtx::setSlot(inFrame, *(hx::Object **)base); for(int i=0;icaptureVars.size();i++) { CppiaStackVar *var = function->captureVars[i]; int size = sTypeSize[var->expressionType]; - memcpy( ctx->frame+var->stackPos, base + var->capturePos, size); + memcpy( inFrame+var->stackPos, base + var->capturePos, size); } + } + + // Runs the function in the frame at ctx->frame, which holds a slot for this and + // the first inHaveArgs arguments, with ctx->pointer past them, and leaves its result + // at ctx->frame. An exception from compiled code is thrown, or with !inThrow left in + // ctx->exception + void runInFrame(CppiaCtx *ctx, int inHaveArgs, bool inThrow) + { + function->addExtraDefaults(ctx,inHaveArgs); + function->addStackVarsSpace(ctx); + enterFrame(ctx->frame); #ifdef CPPIA_JIT CppiaFunc code = function->getCompiled(); @@ -1198,6 +1249,28 @@ hx::Object *boxScriptClosureResult(CppiaCtx *ctx, ScriptCallable *inFunction) return CppiaClosure::boxResult(ctx, inFunction); } +#ifdef CPPIA_JIT +CppiaFunc SLJIT_FUNC enterScriptClosure(CppiaCtx *ctx, hx::Object *inFunction, int inSignature) +{ + void *vtable = sClosureVTable.load(std::memory_order_relaxed); + if (!inFunction || !vtable || *(void **)inFunction!=vtable) + return 0; + CppiaClosure *closure = (CppiaClosure *)inFunction; + ScriptCallable *function = closure->function; + if (function->callSigFull!=inSignature && function->callSigArgs!=inSignature) + return 0; + // Not compiled yet, it compiles on the general way. Its captured variables go + // past the arguments, which the caller's frame made room for, so the whole + // frame must fit before the function's own check of the stack + CppiaFunc code = function->getCompiled(); + unsigned char *frame = ctx->frame; + if (!code || frame + function->stackSize > ctx->stackEnd) + return 0; + closure->enterFrame(frame); + return code; +} +#endif + diff --git a/test/regression/CppiaJitClosureDirect/Main.hx b/test/regression/CppiaJitClosureDirect/Main.hx new file mode 100644 index 000000000..57ad6f0c0 --- /dev/null +++ b/test/regression/CppiaJitClosureDirect/Main.hx @@ -0,0 +1,140 @@ +// Under the JIT, a script calling one of its closures whose function takes the +// arguments and gives the result as they are, and is compiled, calls its code +// directly, as a call of a known function does. Anything else goes the general +// way. +// The same cases run as compiled code, then as a script with the JIT off and on, +// and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +class CompiledCounter { + public var total = 0; + + public function new() {} + + public function add(x:Int):Int { + total += x; + return total; + } + + public function addFloat(x:Float):Int { + total += Std.int(x * 2); + return total; + } +} + +class Compiled { + static function hostLike(x:Int):Int + return x * 100; + + public static function run() { + // One call site, many kinds of function value + var counter = new CompiledCounter(); + var offset = 5; + var functions:Array = [ + (x:Int) -> x + offset, + (x:Float) -> x / 2, + (x:Int) -> "s" + x, + (x:Dynamic) -> x, + counter.add, + counter.addFloat, + hostLike, + Std.string, + Math.abs, + (x:Int, ?y:Int = 3) -> x * y, + null, + ]; + var results = []; + for (round in 0...3) + for (f in functions) { + var call:Int->Dynamic = f; + results.push(try Std.string(call(round + 1)) catch (e:Dynamic) "throws"); + } + Sys.println('one call site ${results.join(",")}'); + + var asInts = []; + for (round in 0...2) + for (f in [(x:Int) -> x + 1, (x:Int) -> x * 3, counter.add, hostLike]) { + var call:Int->Int = f; + asInts.push(call(round + 10)); + } + Sys.println('Int results $asInts ${counter.total}'); + + // Captured variables of each type, read and changed + var i = 1; + var f = 0.5; + var s = "a"; + var b = false; + var o = [1]; + var change = (k:Int) -> { + i += k; + f *= 2; + s += k; + b = !b; + o.push(k); + return i; + }; + var last = 0; + for (k in 0...4) + last = change(k); + Sys.println('captured $last $i $f $s $b $o'); + + // Recursion through a closure that calls itself through a captured variable + var depth:Int->Int = null; + depth = (n:Int) -> { + var a = n * 2; + var c = n + 1; + return n == 0 ? 0 : 1 + depth(n - 1) + (a - 2 * n) + (c - n - 1); + }; + Sys.println('recursion ${depth(500)}'); + + // A throw from a closure called directly, inside and outside a try + var thrower = (x:Int) -> { + if (x % 3 == 2) + throw "at " + x; + return x; + }; + var caught = []; + for (k in 0...6) + try { + caught.push(Std.string(thrower(k))); + } catch (e:String) { + caught.push(e); + } + var guarded = (x:Int) -> { + try { + return thrower(x); + } catch (e:String) { + return -x; + } + }; + Sys.println('throws $caught ${guarded(4)} ${guarded(5)}'); + + // Closures made in a loop, each with its own captured value + var made = [for (k in 0...5) (x:Int) -> x * k + offset]; + var sum = 0; + for (round in 0...3) + for (m in made) + sum += m(round); + Sys.println('made in a loop $sum'); + + // A bound method held as a value, called many times + var bound = counter.add; + for (k in 0...100) + bound(k); + Sys.println('bound ${counter.total}'); + } +} diff --git a/test/regression/CppiaJitClosureDirect/Script.hx b/test/regression/CppiaJitClosureDirect/Script.hx new file mode 100644 index 000000000..f56341f13 --- /dev/null +++ b/test/regression/CppiaJitClosureDirect/Script.hx @@ -0,0 +1,119 @@ +// The same cases as Compiled in Main.hx, run as a script +class Counter { + public var total = 0; + + public function new() {} + + public function add(x:Int):Int { + total += x; + return total; + } + + public function addFloat(x:Float):Int { + total += Std.int(x * 2); + return total; + } +} + +class Script { + static function hostLike(x:Int):Int + return x * 100; + + static function main() { + // One call site, many kinds of function value + var counter = new Counter(); + var offset = 5; + var functions:Array = [ + (x:Int) -> x + offset, + (x:Float) -> x / 2, + (x:Int) -> "s" + x, + (x:Dynamic) -> x, + counter.add, + counter.addFloat, + hostLike, + Std.string, + Math.abs, + (x:Int, ?y:Int = 3) -> x * y, + null, + ]; + var results = []; + for (round in 0...3) + for (f in functions) { + var call:Int->Dynamic = f; + results.push(try Std.string(call(round + 1)) catch (e:Dynamic) "throws"); + } + Sys.println('one call site ${results.join(",")}'); + + var asInts = []; + for (round in 0...2) + for (f in [(x:Int) -> x + 1, (x:Int) -> x * 3, counter.add, hostLike]) { + var call:Int->Int = f; + asInts.push(call(round + 10)); + } + Sys.println('Int results $asInts ${counter.total}'); + + // Captured variables of each type, read and changed + var i = 1; + var f = 0.5; + var s = "a"; + var b = false; + var o = [1]; + var change = (k:Int) -> { + i += k; + f *= 2; + s += k; + b = !b; + o.push(k); + return i; + }; + var last = 0; + for (k in 0...4) + last = change(k); + Sys.println('captured $last $i $f $s $b $o'); + + // Recursion through a closure that calls itself through a captured variable + var depth:Int->Int = null; + depth = (n:Int) -> { + var a = n * 2; + var c = n + 1; + return n == 0 ? 0 : 1 + depth(n - 1) + (a - 2 * n) + (c - n - 1); + }; + Sys.println('recursion ${depth(500)}'); + + // A throw from a closure called directly, inside and outside a try + var thrower = (x:Int) -> { + if (x % 3 == 2) + throw "at " + x; + return x; + }; + var caught = []; + for (k in 0...6) + try { + caught.push(Std.string(thrower(k))); + } catch (e:String) { + caught.push(e); + } + var guarded = (x:Int) -> { + try { + return thrower(x); + } catch (e:String) { + return -x; + } + }; + Sys.println('throws $caught ${guarded(4)} ${guarded(5)}'); + + // Closures made in a loop, each with its own captured value + var made = [for (k in 0...5) (x:Int) -> x * k + offset]; + var sum = 0; + for (round in 0...3) + for (m in made) + sum += m(round); + Sys.println('made in a loop $sum'); + + // A bound method held as a value, called many times + var bound = counter.add; + for (k in 0...100) + bound(k); + Sys.println('bound ${counter.total}'); + } +} diff --git a/test/regression/CppiaJitClosureDirect/build.hxml b/test/regression/CppiaJitClosureDirect/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaJitClosureDirect/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaJitClosureDirect/stdout.txt b/test/regression/CppiaJitClosureDirect/stdout.txt new file mode 100644 index 000000000..8456cce7d --- /dev/null +++ b/test/regression/CppiaJitClosureDirect/stdout.txt @@ -0,0 +1,24 @@ +-- compiled +one call site 6,0.5,s1,1,1,3,100,1,1,3,throws,7,1,s2,2,5,9,200,2,2,6,throws,8,1.5,s3,3,12,18,300,3,3,9,throws +Int results [11,30,28,1000,12,33,39,1100] 39 +captured 7 7 8 a0123 false [1,0,1,2,3] +recursion 500 +throws [0,1,at 2,3,4,at 5] 4 -5 +made in a loop 105 +bound 4989 +-- script, JIT off +one call site 6,0.5,s1,1,1,3,100,1,1,3,throws,7,1,s2,2,5,9,200,2,2,6,throws,8,1.5,s3,3,12,18,300,3,3,9,throws +Int results [11,30,28,1000,12,33,39,1100] 39 +captured 7 7 8 a0123 false [1,0,1,2,3] +recursion 500 +throws [0,1,at 2,3,4,at 5] 4 -5 +made in a loop 105 +bound 4989 +-- script, JIT on +one call site 6,0.5,s1,1,1,3,100,1,1,3,throws,7,1,s2,2,5,9,200,2,2,6,throws,8,1.5,s3,3,12,18,300,3,3,9,throws +Int results [11,30,28,1000,12,33,39,1100] 39 +captured 7 7 8 a0123 false [1,0,1,2,3] +recursion 500 +throws [0,1,at 2,3,4,at 5] 4 -5 +made in a loop 105 +bound 4989 From fdd330c5eac608e76f3927139162b99bfb272098 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 21:42:32 -0500 Subject: [PATCH 08/23] Call unoverridden host methods directly from jitted cppia code 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 , 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 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 51 +++++++- .../CppiaJitHostMethods/HostShape.hx | 51 ++++++++ test/regression/CppiaJitHostMethods/Main.hx | 120 ++++++++++++++++++ test/regression/CppiaJitHostMethods/Script.hx | 98 ++++++++++++++ .../regression/CppiaJitHostMethods/build.hxml | 9 ++ .../regression/CppiaJitHostMethods/stdout.txt | 36 ++++++ test/regression/emscripten-skip.txt | 1 + 8 files changed, 365 insertions(+), 2 deletions(-) create mode 100644 test/regression/CppiaJitHostMethods/HostShape.hx create mode 100644 test/regression/CppiaJitHostMethods/Main.hx create mode 100644 test/regression/CppiaJitHostMethods/Script.hx create mode 100644 test/regression/CppiaJitHostMethods/build.hxml create mode 100644 test/regression/CppiaJitHostMethods/stdout.txt diff --git a/Changes.md b/Changes.md index 5cf9ee946..ff932ca00 100644 --- a/Changes.md +++ b/Changes.md @@ -6,6 +6,7 @@ libhxcpp 6.0.3 (unreleased) * A cppia script calling one of its closures, or a bound method held as a value, passes the arguments and takes the result as they are when the function takes the same types, interpreted and under the JIT. Each argument was boxed into a Dynamic for __run and unboxed into the function's frame, and the result boxed and unboxed again, which allocated for most Ints and every Float. Calling a closure that takes and returns an Int is 1.8x faster under the JIT and 1.2x interpreted (closure_call). An argument of another type, more arguments than the function takes, and host functions are boxed as before * The cppia JIT reads an element of an array of objects, such as an Array of a script class, in place when the element is wanted as an object, as it reads one wanted as anything else. It called a helper that went through the array's virtual __GetItem and built a Dynamic of the element, which an object element does not need. Under the JIT, virtual calls through an array of objects are 1.4x faster (virtual_call) and allocation that reads one 1.2x (alloc_objects). Arrays of Ints, Bools, Floats and Strings still box their elements through __GetItem * Jitted cppia code calls a script closure whose function takes its arguments and gives its result as they are, and is compiled, as it calls a known function: one check of the closure and its function's signature, its captured variables put in the frame, and a call of the compiled code. The general way through a helper, which compiled the function on its first call and boxed what did not match, is left for everything else. Calling a closure that takes and returns an Int is 1.6x faster under the JIT (closure_call), 0.61x of HashLink 1.16's JIT where it was 0.38x +* Jitted cppia code calling a host method or property accessor on a script class that extends a host class calls the host's method directly, as a super call does, when the object is of that host class and no script class overrides the method. It went through the stub the host generates and the host class's virtual method, which checks the script vtable for an override before it runs the host's. Updating script objects through a host display object's properties, as BunnyMark's loop does, is 1.4x faster under the JIT (bunny_update). Script overrides, inherited ones and a host subclass's own still run * Fixed the cppia interpreter reading an argument's slot in place in the script frame when it fills in the argument's default value, and writing a Float or Dynamic default the same way: a frame keeps 4-byte alignment, so on 64-bit an argument after an Int, as b in f(a:Int, ?b:String = "x"), sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. The slots are copied in and out now, as the interpreter's other frame accesses have been since 6.0.0. The JIT, which compiles defaults into the function, was not affected * Fixed Semaphore.tryAcquire(-1) waiting for ever where any other negative timeout returns at once, so a timeout worked out in whole seconds as deadline - now could wait with no limit once the deadline had passed. It was kept for Haxe 5.0.0-preview.1's Lock.wait() (libhxcpp #461), but preview.1's Lock waits through the runtime's own lock, which still takes a negative timeout as no limit, as Haxe 4's does. Only Haxe 5 nightlies from March to November 2026, which libhxcpp does not support, passed -1 to the semaphore; later ones call acquire() for no timeout. Every negative timeout returns at once now, as with stock hxcpp on Linux and macOS (HaxeFoundation/haxe#13114) diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 912a68266..9225d5483 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -1893,6 +1893,10 @@ struct CallHaxe : public CppiaExpr bool isSuper; // The class the script found the function on, to name it if it cannot link String className; + // For a call on a script class that extends the host class: that class, and + // the method's slot in its script vtable, where a script override would be + CppiaClassInfo *receiverClass; + int hostSlot; CallHaxe(CppiaExpr *inSrc,ScriptNamedFunction inFunction, CppiaExpr *inThis, Expressions &ioArgs, bool inIsStatic=false, bool inIsSuper = false, String inClassName = String() ) : CppiaExpr(inSrc) @@ -1903,7 +1907,26 @@ struct CallHaxe : public CppiaExpr isStatic = inIsStatic; isSuper = inIsSuper; className = inClassName; + receiverClass = 0; + hostSlot = -1; } + + // A call of a host method on a script class whose host class is inHostClass + void setReceiver(CppiaClassInfo *inClass, HaxeNativeClass *inHostClass) + { + if (!inClass || !inHostClass || isStatic || isSuper || !function.superExecute || !function.name) + return; + std::vector table; + inHostClass->addVtableEntries(table); + for(int i=0;iadd( sJitCtxFrame, sJitFrame.as(jtPointer), JitVal(framePos) ); void *func = (void *) ( isSuper ? function.superExecute : function.execute); - compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); + + // The script class's objects are host objects of one C++ class, whose method + // checks the script vtable for an override before it runs the host's. An + // object of that class whose script classes do not override the method has + // the host's called directly, as a super call calls it + void *hostVTable = receiverClass && hostSlot>=0 ? receiverClass->getHaxeBaseVTable() : 0; + if (hostVTable) + { + compiler->move(sJitTemp0.as(jtPointer), JitFramePos(framePos).as(jtPointer)); + JumpId isNull = compiler->compare(cmpP_EQUAL, sJitTemp0.as(jtPointer), (void *)0); + JumpId otherClass = compiler->compare(cmpP_NOT_EQUAL, sJitTemp0.star(jtPointer, 0), hostVTable); + compiler->move(sJitTemp1.as(jtPointer), sJitTemp0.star(jtPointer, receiverClass->getScriptVTableOffset())); + JumpId overridden = compiler->compare(cmpP_NOT_EQUAL, sJitTemp1.star(jtPointer, hostSlot*(int)sizeof(void *)), (void *)0); + compiler->callNative( (void *)tryCallHaxe, JitVal((void *)function.superExecute), sJitCtx ); + JumpId called = compiler->jump(); + compiler->comeFrom(isNull); + compiler->comeFrom(otherClass); + compiler->comeFrom(overridden); + compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); + compiler->comeFrom(called); + } + else + compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); genFunctionResult(compiler, inDest, destType, returnType, isBoolInt()); } @@ -4027,7 +4072,9 @@ struct CallMember : public CppiaExpr CPPIALOG("Warning - calling super host '%s' from cppia can lead to infinte recursion\n", field.utf8_str()); //CPPIALOG(" found function %s\n", func.signature ); - replace = new CallHaxe( this, func, thisExpr, args, false, callSuperField && func.superExecute, type->name); + CallHaxe *call = new CallHaxe( this, func, thisExpr, args, false, callSuperField && func.superExecute, type->name); + call->setReceiver(type->cppiaClass, type->haxeBase); + replace = call; } } diff --git a/test/regression/CppiaJitHostMethods/HostShape.hx b/test/regression/CppiaJitHostMethods/HostShape.hx new file mode 100644 index 000000000..2f3fd6895 --- /dev/null +++ b/test/regression/CppiaJitHostMethods/HostShape.hx @@ -0,0 +1,51 @@ +// Host classes that script classes extend +class HostShape { + public var x(get, set):Float; + public var name(get, never):String; + + var _x:Float = 0; + var sets = 0; + + public function new() {} + + function get_x():Float + return _x; + + function set_x(value:Float):Float { + sets++; + return _x = value; + } + + function get_name():String + return "shape"; + + public function area():Float + return 1; + + public function scaled(by:Int, extra:Float, label:String, flag:Bool, other:HostShape):String + return label + ":" + (area() * by + extra) + ":" + flag + ":" + (other == null ? "none" : other.name); + + public function setCount():Int + return sets; + + public function isBig():Bool + return area() > 10; + + public function self():HostShape + return this; +} + +// A host subclass that overrides in native code +class HostSquare extends HostShape { + public var side:Float = 2; + + public function new() { + super(); + } + + override function get_x():Float + return _x + 1000; + + override public function area():Float + return side * side; +} diff --git a/test/regression/CppiaJitHostMethods/Main.hx b/test/regression/CppiaJitHostMethods/Main.hx new file mode 100644 index 000000000..4c4bb8f2f --- /dev/null +++ b/test/regression/CppiaJitHostMethods/Main.hx @@ -0,0 +1,120 @@ +import HostShape; + +// Under the JIT, a call of a host method on a script class that extends the +// host class calls the host method directly when the object is of that host +// class and no script class overrides the method, skipping the check the +// host class makes for an override. Overrides in script, inherited ones and a +// host subclass's own still run. The same cases run as compiled code, then as +// a script with the JIT off and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host + +class CompiledPlain extends HostShape { + public function new() { + super(); + } +} + +class CompiledCircle extends HostShape { + public var radius:Float; + + public function new(radius:Float) { + super(); + this.radius = radius; + } + + override public function area():Float + return 3 * radius * radius; + + override function get_name():String + return "circle"; +} + +class CompiledSmallCircle extends CompiledCircle { + public function new() { + super(1); + } +} + +class CompiledRing extends CompiledCircle { + public function new() { + super(2); + } + + override public function area():Float + return super.area() - 1; +} + +class CompiledFancySquare extends HostSquare { + public function new() { + super(); + } +} + +class CompiledOwnX extends HostShape { + public function new() { + super(); + } + + override function get_x():Float + return -1; +} + +class Compiled { + static function describe(label:String, s:HostShape):String { + return '$label x=${s.x} name=${s.name} area=${s.area()} big=${s.isBig()} sets=${s.setCount()} ' + + s.scaled(2, 0.5, label, true, s.self()); + } + + public static function run() { + var plain = new CompiledPlain(); + var circle = new CompiledCircle(2); + var small = new CompiledSmallCircle(); + var ring = new CompiledRing(); + var fancy = new CompiledFancySquare(); + var own = new CompiledOwnX(); + var host = new HostShape(); + var square = new HostSquare(); + + // Calls through each script class's own type + var total = 0.0; + for (i in 0...100) { + plain.x += 1.5; + circle.x = circle.x + i; + small.x += plain.x; + ring.x = i; + fancy.x += 2; + own.x += 1; + total += plain.area() + circle.area() + small.area() + ring.area() + fancy.area() + own.area(); + } + Sys.println('loop $total'); + Sys.println(describe("plain", plain)); + Sys.println(describe("circle", circle)); + Sys.println(describe("small", small)); + Sys.println(describe("ring", ring)); + Sys.println(describe("fancy", fancy)); + Sys.println(describe("own", own)); + Sys.println(describe("host", host)); + Sys.println(describe("square", square)); + Sys.println('typed ${plain.x} ${plain.name} ${plain.isBig()} ${small.name} ${small.area()} ${fancy.x} ${fancy.area()} ${own.x} ${ring.area()}'); + + // One call site, objects of every class + var all:Array = [plain, circle, small, ring, fancy, own, host, square]; + var names = [for (s in all) s.name + "/" + s.area() + "/" + s.x]; + Sys.println('mixed $names'); + } +} diff --git a/test/regression/CppiaJitHostMethods/Script.hx b/test/regression/CppiaJitHostMethods/Script.hx new file mode 100644 index 000000000..baeef7dea --- /dev/null +++ b/test/regression/CppiaJitHostMethods/Script.hx @@ -0,0 +1,98 @@ +// The same cases as Compiled in Main.hx, run as a script +import HostShape; + +class Plain extends HostShape { + public function new() { + super(); + } +} + +class Circle extends HostShape { + public var radius:Float; + + public function new(radius:Float) { + super(); + this.radius = radius; + } + + override public function area():Float + return 3 * radius * radius; + + override function get_name():String + return "circle"; +} + +class SmallCircle extends Circle { + public function new() { + super(1); + } +} + +class Ring extends Circle { + public function new() { + super(2); + } + + override public function area():Float + return super.area() - 1; +} + +class FancySquare extends HostSquare { + public function new() { + super(); + } +} + +class OwnX extends HostShape { + public function new() { + super(); + } + + override function get_x():Float + return -1; +} + +class Script { + static function describe(label:String, s:HostShape):String { + return '$label x=${s.x} name=${s.name} area=${s.area()} big=${s.isBig()} sets=${s.setCount()} ' + + s.scaled(2, 0.5, label, true, s.self()); + } + + static function main() { + var plain = new Plain(); + var circle = new Circle(2); + var small = new SmallCircle(); + var ring = new Ring(); + var fancy = new FancySquare(); + var own = new OwnX(); + var host = new HostShape(); + var square = new HostSquare(); + + // Calls through each script class's own type + var total = 0.0; + for (i in 0...100) { + plain.x += 1.5; + circle.x = circle.x + i; + small.x += plain.x; + ring.x = i; + fancy.x += 2; + own.x += 1; + total += plain.area() + circle.area() + small.area() + ring.area() + fancy.area() + own.area(); + } + Sys.println('loop $total'); + Sys.println(describe("plain", plain)); + Sys.println(describe("circle", circle)); + Sys.println(describe("small", small)); + Sys.println(describe("ring", ring)); + Sys.println(describe("fancy", fancy)); + Sys.println(describe("own", own)); + Sys.println(describe("host", host)); + Sys.println(describe("square", square)); + Sys.println('typed ${plain.x} ${plain.name} ${plain.isBig()} ${small.name} ${small.area()} ${fancy.x} ${fancy.area()} ${own.x} ${ring.area()}'); + + // One call site, objects of every class + var all:Array = [plain, circle, small, ring, fancy, own, host, square]; + var names = [for (s in all) s.name + "/" + s.area() + "/" + s.x]; + Sys.println('mixed $names'); + } +} diff --git a/test/regression/CppiaJitHostMethods/build.hxml b/test/regression/CppiaJitHostMethods/build.hxml new file mode 100644 index 000000000..850bcd4ce --- /dev/null +++ b/test/regression/CppiaJitHostMethods/build.hxml @@ -0,0 +1,9 @@ +--main Main +-cpp bin +-D scriptable +--dce no +-D dll_export=bin/host_classes.info +--next +--main Script +-cppia bin/script.cppia +-D dll_import=bin/host_classes.info diff --git a/test/regression/CppiaJitHostMethods/stdout.txt b/test/regression/CppiaJitHostMethods/stdout.txt new file mode 100644 index 000000000..ec725ceb3 --- /dev/null +++ b/test/regression/CppiaJitHostMethods/stdout.txt @@ -0,0 +1,36 @@ +-- compiled +loop 3200 +plain x=150 name=shape area=1 big=false sets=100 plain:2.5:true:shape +circle x=4950 name=circle area=12 big=true sets=100 circle:24.5:true:circle +small x=7575 name=circle area=3 big=false sets=100 small:6.5:true:circle +ring x=99 name=circle area=11 big=true sets=100 ring:22.5:true:circle +fancy x=101200 name=shape area=4 big=false sets=100 fancy:8.5:true:shape +own x=-1 name=shape area=1 big=false sets=100 own:2.5:true:shape +host x=0 name=shape area=1 big=false sets=0 host:2.5:true:shape +square x=1000 name=shape area=4 big=false sets=0 square:8.5:true:shape +typed 150 shape false circle 3 101200 4 -1 11 +mixed [shape/1/150,circle/12/4950,circle/3/7575,circle/11/99,shape/4/101200,shape/1/-1,shape/1/0,shape/4/1000] +-- script, JIT off +loop 3200 +plain x=150 name=shape area=1 big=false sets=100 plain:2.5:true:shape +circle x=4950 name=circle area=12 big=true sets=100 circle:24.5:true:circle +small x=7575 name=circle area=3 big=false sets=100 small:6.5:true:circle +ring x=99 name=circle area=11 big=true sets=100 ring:22.5:true:circle +fancy x=101200 name=shape area=4 big=false sets=100 fancy:8.5:true:shape +own x=-1 name=shape area=1 big=false sets=100 own:2.5:true:shape +host x=0 name=shape area=1 big=false sets=0 host:2.5:true:shape +square x=1000 name=shape area=4 big=false sets=0 square:8.5:true:shape +typed 150 shape false circle 3 101200 4 -1 11 +mixed [shape/1/150,circle/12/4950,circle/3/7575,circle/11/99,shape/4/101200,shape/1/-1,shape/1/0,shape/4/1000] +-- script, JIT on +loop 3200 +plain x=150 name=shape area=1 big=false sets=100 plain:2.5:true:shape +circle x=4950 name=circle area=12 big=true sets=100 circle:24.5:true:circle +small x=7575 name=circle area=3 big=false sets=100 small:6.5:true:circle +ring x=99 name=circle area=11 big=true sets=100 ring:22.5:true:circle +fancy x=101200 name=shape area=4 big=false sets=100 fancy:8.5:true:shape +own x=-1 name=shape area=1 big=false sets=100 own:2.5:true:shape +host x=0 name=shape area=1 big=false sets=0 host:2.5:true:shape +square x=1000 name=shape area=4 big=false sets=0 square:8.5:true:shape +typed 150 shape false circle 3 101200 4 -1 11 +mixed [shape/1/150,circle/12/4950,circle/3/7575,circle/11/99,shape/4/101200,shape/1/-1,shape/1/0,shape/4/1000] diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index e2c2c75d2..f65709291 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -23,6 +23,7 @@ CppiaHostArgs: processes CppiaHostFunctionOrder: its host is the first --next section, which -D emscripten does not reach CppiaHostMismatch: its host is the first --next section, which -D emscripten does not reach, and it checks jitted code, and Emscripten has no cppia JIT CppiaJitBuiltins: threads +CppiaJitHostMethods: its host is the first --next section, which -D emscripten does not reach CppiaJitThrowNull: its host is the first --next section, which -D emscripten does not reach CppiaLazyJit: threads, and Emscripten has no cppia JIT CppiaMalformedLoads: compares the cppia JIT, which Emscripten has not From 12e3bb90ada74745cee66b701a649a467cd0c631 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 22:00:56 -0500 Subject: [PATCH 09/23] Give a scriptable host's static functions typed entries for scripts 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 , 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 --- BENCHMARKS.md | 1 + Changes.md | 1 + bench/cppia/Script.hx | 19 ++ bench/cppia/shared/CppiaBridge.hx | 3 + bench/cppia/shared/CppiaWorkloads.hx | 1 + bench/cppia/shared/HostVector.hx | 23 +++ include/hx/Macros.h | 6 + include/hx/Macros.tpl | 6 + include/hx/Scriptable.h | 181 ++++++++++++++++++ include/hxcpp.h | 6 + src/Dynamic.cpp | 66 +++++++ src/hx/cppia/Cppia.cpp | 10 + .../CppiaStaticCallsByName/HostBox.hx | 63 ++++++ .../regression/CppiaStaticCallsByName/Main.hx | 60 ++++++ .../CppiaStaticCallsByName/Script.hx | 40 ++++ .../CppiaStaticCallsByName/build.hxml | 9 + .../CppiaStaticCallsByName/stdout.txt | 36 ++++ test/regression/emscripten-skip.txt | 1 + 18 files changed, 532 insertions(+) create mode 100644 bench/cppia/shared/HostVector.hx create mode 100644 test/regression/CppiaStaticCallsByName/HostBox.hx create mode 100644 test/regression/CppiaStaticCallsByName/Main.hx create mode 100644 test/regression/CppiaStaticCallsByName/Script.hx create mode 100644 test/regression/CppiaStaticCallsByName/build.hxml create mode 100644 test/regression/CppiaStaticCallsByName/stdout.txt diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 42ece1e6a..c6f076d31 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -138,6 +138,7 @@ driver also checks that the interpreter and JIT return the same checksum. | `native_callback` | A native loop calling a script closure that updates a captured variable | | `bunny_update` | The update loop of OpenFL's BunnyMark over 2,000 script objects that extend a host class, moved through its Float properties, in a listener the host calls once a frame | | `openfl_frame` | An OpenFL application's frame: 1,000 script objects extending a host display object, moved by an ENTER_FRAME listener the host calls, one in ten with a closure listener of its own, a small object made each update, dead ones replaced, and a host render reading every transform | +| `call_by_name` | Script calls of an abstract's methods over a host type, which the host gives no binding for, as openfl.Vector's are: length, element reads and writes | The native timing harness loads one script module per process. Loading, linking, booting and JIT compilation happen in `setup()`, outside the timed samples. diff --git a/Changes.md b/Changes.md index ff932ca00..a75a44b8a 100644 --- a/Changes.md +++ b/Changes.md @@ -7,6 +7,7 @@ libhxcpp 6.0.3 (unreleased) * The cppia JIT reads an element of an array of objects, such as an Array of a script class, in place when the element is wanted as an object, as it reads one wanted as anything else. It called a helper that went through the array's virtual __GetItem and built a Dynamic of the element, which an object element does not need. Under the JIT, virtual calls through an array of objects are 1.4x faster (virtual_call) and allocation that reads one 1.2x (alloc_objects). Arrays of Ints, Bools, Floats and Strings still box their elements through __GetItem * Jitted cppia code calls a script closure whose function takes its arguments and gives its result as they are, and is compiled, as it calls a known function: one check of the closure and its function's signature, its captured variables put in the frame, and a call of the compiled code. The general way through a helper, which compiled the function on its first call and boxed what did not match, is left for everything else. Calling a closure that takes and returns an Int is 1.6x faster under the JIT (closure_call), 0.61x of HashLink 1.16's JIT where it was 0.38x * Jitted cppia code calling a host method or property accessor on a script class that extends a host class calls the host's method directly, as a super call does, when the object is of that host class and no script class overrides the method. It went through the stub the host generates and the host class's virtual method, which checks the script vtable for an override before it runs the host's. Updating script objects through a host display object's properties, as BunnyMark's loop does, is 1.4x faster under the JIT (bunny_update). Script overrides, inherited ones and a host subclass's own still run +* A cppia script calling a host static function the host gives it no binding for, as with any method of an abstract over a host type such as openfl.Vector, whose implementation class is private, passes the arguments and takes the result as they are. It called the function's Dynamic wrapper, boxing every Int, Float and Bool on the way in and the result on the way out, and converted an Array argument with a dynamic_cast. In a scriptable build, each static function's wrapper now registers a typed entry, made from the function's own C++ signature, that a script links to as it links to a binding, and an Array of the element type wanted is passed without the cast. Calls by name are 5.9x faster under the JIT and 2x interpreted (call_by_name), 0.73x of HashLink 1.16's JIT where they were 0.12x. A scriptable host is larger by about 2% for the entries; other builds are unchanged * Fixed the cppia interpreter reading an argument's slot in place in the script frame when it fills in the argument's default value, and writing a Float or Dynamic default the same way: a frame keeps 4-byte alignment, so on 64-bit an argument after an Int, as b in f(a:Int, ?b:String = "x"), sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. The slots are copied in and out now, as the interpreter's other frame accesses have been since 6.0.0. The JIT, which compiles defaults into the function, was not affected * Fixed Semaphore.tryAcquire(-1) waiting for ever where any other negative timeout returns at once, so a timeout worked out in whole seconds as deadline - now could wait with no limit once the deadline had passed. It was kept for Haxe 5.0.0-preview.1's Lock.wait() (libhxcpp #461), but preview.1's Lock waits through the runtime's own lock, which still takes a negative timeout as no limit, as Haxe 4's does. Only Haxe 5 nightlies from March to November 2026, which libhxcpp does not support, passed -1 to the semaphore; later ones call acquire() for no timeout. Every negative timeout returns at once now, as with stock hxcpp on Linux and macOS (HaxeFoundation/haxe#13114) diff --git a/bench/cppia/Script.hx b/bench/cppia/Script.hx index cfd679121..e900c2e9b 100644 --- a/bench/cppia/Script.hx +++ b/bench/cppia/Script.hx @@ -13,6 +13,7 @@ class Script { case "native_callback": new NativeCallback(); case "bunny_update": new BunnyUpdate(); case "openfl_frame": new OpenflFrame(); + case "call_by_name": new CallByName(); default: throw 'Unknown CPPIA workload ${CppiaBridge.name}'; }; } @@ -315,3 +316,21 @@ class OpenflFrame implements CppiaWorkload { return HostContainer.runFrames(scene, FRAMES) + spins * 1000 + scene.numChildren; } } + +// Calls a script makes by name: an abstract over a host type whose methods +// the host gives no binding for, as openfl.Vector's are +class CallByName implements CppiaWorkload { + final values = CppiaBridge.vector(1000); + + public function new() {} + + public function run():Int { + var sum = 0; + for (i in 0...100000) { + var slot = i % values.length; + values[slot] = values[slot] * 0.5 + (i & 255); + sum += Std.int(values[slot]); + } + return sum; + } +} diff --git a/bench/cppia/shared/CppiaBridge.hx b/bench/cppia/shared/CppiaBridge.hx index 37b23c11c..88f6158cc 100644 --- a/bench/cppia/shared/CppiaBridge.hx +++ b/bench/cppia/shared/CppiaBridge.hx @@ -8,6 +8,9 @@ class CppiaBridge { // Builds HostSprite into the host, for script classes to extend public static var spriteClass:Class = HostSprite; public static var containerClass:Class = HostContainer; + // Builds HostVector's implementation class into the host + public static function vector(count:Int):HostVector + return new HostVector(count); @:noInline public static function step(value:Int):Int { diff --git a/bench/cppia/shared/CppiaWorkloads.hx b/bench/cppia/shared/CppiaWorkloads.hx index 5c551667b..7fe76fea7 100644 --- a/bench/cppia/shared/CppiaWorkloads.hx +++ b/bench/cppia/shared/CppiaWorkloads.hx @@ -17,5 +17,6 @@ class CppiaWorkloads { {name: "native_callback", unit: "callbacks", ops: 200000, reps: 10}, {name: "bunny_update", unit: "bunny updates", ops: 20000, reps: 10}, {name: "openfl_frame", unit: "object frames", ops: 10000, reps: 5}, + {name: "call_by_name", unit: "calls", ops: 400000, reps: 5}, ]; } diff --git a/bench/cppia/shared/HostVector.hx b/bench/cppia/shared/HostVector.hx new file mode 100644 index 000000000..cb42119d3 --- /dev/null +++ b/bench/cppia/shared/HostVector.hx @@ -0,0 +1,23 @@ +package; + +/** + An abstract over a host type, as openfl.Vector is: its methods are static + functions of a private implementation class, for which the host gives a + script no binding, so a script calls them by name. +**/ +abstract HostVector(Array) { + public var length(get, never):Int; + + public function new(count:Int) { + this = [for (i in 0...count) 0.0]; + } + + function get_length():Int + return this.length; + + @:arrayAccess public function get(index:Int):Float + return this[index]; + + @:arrayAccess public function set(index:Int, value:Float):Float + return this[index] = value; +} diff --git a/include/hx/Macros.h b/include/hx/Macros.h index ea4b86c5d..ae0406292 100644 --- a/include/hx/Macros.h +++ b/include/hx/Macros.h @@ -608,8 +608,10 @@ static ::Dynamic __##class##func() \ { \ ret class::func(); return ::Dynamic(); \ }; \ +HX_SCRIPT_STATIC_STUB_PROBE(class,func) \ ::Dynamic class::func##_dyn() \ {\ + HX_SCRIPT_STATIC_STUB(class,func,__##class##func) \ return ::hx::CreateStaticFunction0(#func,__##class##func); \ } @@ -619,8 +621,10 @@ static ::Dynamic __##class##func(dynamic_arg_list) \ { \ ret class::func(arg_list); return ::Dynamic(); \ }; \ +HX_SCRIPT_STATIC_STUB_PROBE(class,func) \ ::Dynamic class::func##_dyn() \ {\ + HX_SCRIPT_STATIC_STUB(class,func,__##class##func) \ return ::hx::CreateStaticFunction##N(#func,__##class##func); \ } @@ -630,8 +634,10 @@ static ::Dynamic __##class##func(const ::Array< ::Dynamic> &inArgs) \ { \ ret class::func(array_list); return ::Dynamic(); \ }; \ +HX_SCRIPT_STATIC_STUB_PROBE(class,func) \ ::Dynamic class::func##_dyn() \ {\ + HX_SCRIPT_STATIC_STUB(class,func,__##class##func) \ return ::hx::CreateStaticFunctionVar(#func,__##class##func,N); \ } diff --git a/include/hx/Macros.tpl b/include/hx/Macros.tpl index 5f75bde2e..791452be8 100644 --- a/include/hx/Macros.tpl +++ b/include/hx/Macros.tpl @@ -78,8 +78,10 @@ static ::NS::Dynamic __##class##func() \ { \ ret class::func(); return ::NS::Dynamic(); \ }; \ +HX_SCRIPT_STATIC_STUB_PROBE(class,func) \ ::NS::Dynamic class::func##_dyn() \ {\ + HX_SCRIPT_STATIC_STUB(class,func,__##class##func) \ return ::hxNS::CreateStaticFunction0(#func,__##class##func); \ } @@ -89,8 +91,10 @@ static ::NS::Dynamic __##class##func(dynamic_arg_list) \ { \ ret class::func(arg_list); return ::NS::Dynamic(); \ }; \ +HX_SCRIPT_STATIC_STUB_PROBE(class,func) \ ::NS::Dynamic class::func##_dyn() \ {\ + HX_SCRIPT_STATIC_STUB(class,func,__##class##func) \ return ::hxNS::CreateStaticFunction##N(#func,__##class##func); \ } @@ -100,8 +104,10 @@ static ::NS::Dynamic __##class##func(const ::NS::Array< ::NS::Dynamic> &inArgs) { \ ret class::func(array_list); return ::NS::Dynamic(); \ }; \ +HX_SCRIPT_STATIC_STUB_PROBE(class,func) \ ::NS::Dynamic class::func##_dyn() \ {\ + HX_SCRIPT_STATIC_STUB(class,func,__##class##func) \ return ::hxNS::CreateStaticFunctionVar(#func,__##class##func,N); \ } diff --git a/include/hx/Scriptable.h b/include/hx/Scriptable.h index 25dd75b4b..6c2f472ea 100644 --- a/include/hx/Scriptable.h +++ b/include/hx/Scriptable.h @@ -2,6 +2,7 @@ #define INCLUDED_HX_SCRIPTABLE #include +#include #include #ifdef __clang__ #pragma clang diagnostic ignored "-Winvalid-offsetof" @@ -130,6 +131,186 @@ enum SignatureChar }; +// A typed entry for a static function a script calls by name: one of a class +// the host gives no binding for, such as an abstract's implementation class. +// STATIC_HX_DEFINE_DYNAMIC_FUNC registers one for each static function's +// Dynamic wrapper as it is first asked for, and a script calling the function +// then reads and writes the values in its frame as a binding does. A type the +// frame has no slot of its own for goes through Dynamic, as the wrapper +// converts it +#if defined(_MSC_VER) ? (_MSC_VER >= 1900) : (__cplusplus >= 201103L) + +#define HX_SCRIPT_STATIC_STUBS 1 + +struct ScriptStubInfo; +// Registers the entry, if it has one, for the Dynamic wrapper inThunk +HXCPP_EXTERN_CLASS_ATTRIBUTES +bool RegisterScriptStaticStub(void *inThunk, const ScriptStubInfo &inInfo); +// The entry registered for the static function inFunction, if it is one with an entry +HXCPP_EXTERN_CLASS_ATTRIBUTES +bool FindScriptStaticStub(hx::Object *inFunction, StackExecute &outExecute, const char *&outSignature); + +// How a frame holds a value of type T +template struct ScriptSlot +{ + enum { sig = sigObject, size = sizeof(hx::Object *) }; + static inline T get(const unsigned char *inSlot) + { + ::Dynamic value( StackContext::getSlot(inSlot) ); + return value; + } + static inline void put(StackContext *ctx, const T &inValue) + { + ::Dynamic value = inValue; + ctx->returnObject(value); + } +}; +template<> struct ScriptSlot +{ + enum { sig = sigInt, size = sizeof(int) }; + static inline int get(const unsigned char *inSlot) { return StackContext::getSlot(inSlot); } + static inline void put(StackContext *ctx, int inValue) { ctx->returnInt(inValue); } +}; +template<> struct ScriptSlot +{ + enum { sig = sigBool, size = sizeof(int) }; + static inline bool get(const unsigned char *inSlot) { return StackContext::getSlot(inSlot)!=0; } + static inline void put(StackContext *ctx, bool inValue) { ctx->returnInt(inValue ? 1 : 0); } +}; +template<> struct ScriptSlot +{ + enum { sig = sigFloat, size = sizeof(double) }; + static inline double get(const unsigned char *inSlot) { return StackContext::getSlot(inSlot); } + static inline void put(StackContext *ctx, double inValue) { ctx->returnFloat(inValue); } +}; +template<> struct ScriptSlot +{ + enum { sig = sigFloat, size = sizeof(double) }; + static inline float get(const unsigned char *inSlot) { return (float)StackContext::getSlot(inSlot); } + static inline void put(StackContext *ctx, float inValue) { ctx->returnFloat(inValue); } +}; +template<> struct ScriptSlot< ::String > +{ + enum { sig = sigString, size = sizeof(::String) }; + static inline ::String get(const unsigned char *inSlot) { return StackContext::getSlot< ::String >(inSlot); } + static inline void put(StackContext *ctx, const ::String &inValue) { ctx->returnString(inValue); } +}; + +// An array of the element type wanted is passed as it is. A conversion from +// Dynamic finds that with a dynamic_cast, which costs more than the call it is +// for, so an exact one is known by its vtable and anything else is converted +// as the wrapper converts it +template struct ScriptSlot< ::Array > +{ + enum { sig = sigObject, size = sizeof(hx::Object *) }; + static inline ::Array get(const unsigned char *inSlot) + { + hx::Object *ptr = StackContext::getSlot(inSlot); + static void *exact = *(void **)( ::Array_obj::__new(0,0).mPtr ); + if (ptr && *(void **)ptr==exact) + return ::Array( (::Array_obj *)ptr ); + ::Dynamic value(ptr); + return value; + } + static inline void put(StackContext *ctx, const ::Array &inValue) + { + ::Dynamic value = inValue; + ctx->returnObject(value); + } +}; + +template struct ScriptPlain { typedef typename std::remove_cv::type>::type type; }; + +// The type of argument K, and the offset of its slot from the first +template struct ScriptArgAt +{ + typedef typename ScriptArgAt::type type; + enum { offset = ScriptSlot::type>::size + ScriptArgAt::offset }; +}; +template struct ScriptArgAt<0, A0, A...> +{ + typedef typename ScriptPlain::type type; + enum { offset = 0 }; +}; + +template struct ScriptIndices { }; +template struct ScriptMakeIndices : ScriptMakeIndices { }; +template struct ScriptMakeIndices<0, I...> { typedef ScriptIndices type; }; + +template struct ScriptStaticStub; + +template +struct ScriptStaticStub +{ + // The arguments start after the frame's slot for this, which a static leaves empty + template + static inline R call(const unsigned char *inArgs, ScriptIndices) + { + return inFunction( ScriptSlot::type>::get(inArgs + ScriptArgAt::offset)... ); + } + static void CPPIA_CALL execute(StackContext *ctx) + { + ScriptSlot::type>::put(ctx, + call(ctx->frame + sizeof(hx::Object *), typename ScriptMakeIndices<(int)sizeof...(A)>::type()) ); + } + static const char *signature() + { + static const char sig[] = { (char)ScriptSlot::type>::sig, (char)ScriptSlot::type>::sig..., 0 }; + return sig; + } +}; + +template +struct ScriptStaticStub +{ + template + static inline void call(const unsigned char *inArgs, ScriptIndices) + { + inFunction( ScriptSlot::type>::get(inArgs + ScriptArgAt::offset)... ); + } + static void CPPIA_CALL execute(StackContext *ctx) + { + call(ctx->frame + sizeof(hx::Object *), typename ScriptMakeIndices<(int)sizeof...(A)>::type()); + } + static const char *signature() + { + static const char sig[] = { (char)sigVoid, (char)ScriptSlot::type>::sig..., 0 }; + return sig; + } +}; + +struct ScriptStubInfo +{ + StackExecute execute; + const char *signature; +}; + +template +inline ScriptStubInfo scriptStubInfo() +{ + ScriptStubInfo info = { &ScriptStaticStub::execute, ScriptStaticStub::signature() }; + return info; +} + +// Each static function gets a probe, at namespace scope, whose get finds its +// entry. A name with overloads, as some hand-written classes have, has no one +// address to take, so it gets none and keeps the wrapper alone +#define HX_SCRIPT_STATIC_STUB_PROBE(class,func) \ +struct __hx_stub_##class##func \ +{ \ + template static auto get(int) -> decltype(&T::func, ::hx::ScriptStubInfo()) \ + { return ::hx::scriptStubInfo(); } \ + template static ::hx::ScriptStubInfo get(...) \ + { ::hx::ScriptStubInfo none = { 0, 0 }; return none; } \ +}; + +#define HX_SCRIPT_STATIC_STUB(class,func,thunk) \ + static bool __hx_script_stub = ::hx::RegisterScriptStaticStub( (void *)thunk, __hx_stub_##class##func::get(0) ); \ + (void)__hx_script_stub; + +#endif + + struct AutoStack { diff --git a/include/hxcpp.h b/include/hxcpp.h index 04b04daca..3eddfaff9 100755 --- a/include/hxcpp.h +++ b/include/hxcpp.h @@ -408,6 +408,12 @@ typedef PropertyAccessMode PropertyAccess; #ifdef HXCPP_SCRIPTABLE #include #endif +// A static function's Dynamic wrapper registers a typed entry for scripts only +// in a scriptable build with C++11 +#ifndef HX_SCRIPT_STATIC_STUB +#define HX_SCRIPT_STATIC_STUB_PROBE(class,func) +#define HX_SCRIPT_STATIC_STUB(class,func,thunk) +#endif #endif diff --git a/src/Dynamic.cpp b/src/Dynamic.cpp index 137c882b3..35eff2efa 100644 --- a/src/Dynamic.cpp +++ b/src/Dynamic.cpp @@ -700,3 +700,69 @@ void Dynamic::__boot() Static(__ObjcClass) = hx::_hx_RegisterClass(HX_CSTRING("objc::BoxedType"),IsPointer,sNone,sNone, 0,0,&__ObjcClass ); #endif } + + +#ifdef HX_SCRIPT_STATIC_STUBS +#include +#include + +namespace hx +{ + +struct ScriptStaticStubEntry +{ + StackExecute execute; + const char *signature; +}; + +// Filled as wrappers are first asked for, on any thread, and read as scripts link +static std::mutex &scriptStaticStubLock() { static std::mutex &lock = *new std::mutex(); return lock; } +static std::unordered_map &scriptStaticStubs() +{ + static std::unordered_map &stubs = *new std::unordered_map(); + return stubs; +} + +bool RegisterScriptStaticStub(void *inThunk, const ScriptStubInfo &inInfo) +{ + if (!inInfo.execute) + return false; + std::lock_guard hold(scriptStaticStubLock()); + ScriptStaticStubEntry entry = { inInfo.execute, inInfo.signature }; + scriptStaticStubs()[inThunk] = entry; + return true; +} + +// The Dynamic wrapper a static function object calls +static void *staticFunctionThunk(hx::Object *inFunction) +{ + #define HX_STATIC_THUNK(N) \ + if (CStaticFunction##N *f = dynamic_cast(inFunction)) \ + return (void *)f->mFunction; + HX_STATIC_THUNK(0) + HX_STATIC_THUNK(1) + HX_STATIC_THUNK(2) + HX_STATIC_THUNK(3) + HX_STATIC_THUNK(4) + HX_STATIC_THUNK(5) + HX_STATIC_THUNK(Var) + #undef HX_STATIC_THUNK + return 0; +} + +bool FindScriptStaticStub(hx::Object *inFunction, StackExecute &outExecute, const char *&outSignature) +{ + void *thunk = inFunction ? staticFunctionThunk(inFunction) : 0; + if (!thunk) + return false; + std::lock_guard hold(scriptStaticStubLock()); + std::unordered_map::iterator it = scriptStaticStubs().find(thunk); + if (it==scriptStaticStubs().end()) + return false; + outExecute = it->second.execute; + outSignature = it->second.signature; + return true; +} + +} // end namespace hx +#endif diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 9225d5483..a58df5fd6 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -2201,6 +2201,16 @@ struct CallStatic : public CppiaExpr //CPPIALOG("INFO %s -> %p\n", field.out_str(), info); // TODO - create proper glue for static functions Dynamic func = type->haxeClass.mPtr->__Field( field, HX_PROP_NEVER ); + #ifdef HX_SCRIPT_STATIC_STUBS + // A function the host gives no binding for, such as one of an abstract's + // implementation class, is called through the typed entry its wrapper + // registered, as a binding is, when there is one for these arguments + StackExecute execute = 0; + const char *signature = 0; + if (func.mPtr && FindScriptStaticStub(func.mPtr, execute, signature) && (int)strlen(signature)-1==(int)args.size()) + replace = new CallHaxe( this, ScriptNamedFunction(0, execute, signature, true), 0, args, true, false, type->name ); + else + #endif if (func.mPtr) { replace = new CallDynamicFunction(inModule, this, func, args ); diff --git a/test/regression/CppiaStaticCallsByName/HostBox.hx b/test/regression/CppiaStaticCallsByName/HostBox.hx new file mode 100644 index 000000000..dd354a7dd --- /dev/null +++ b/test/regression/CppiaStaticCallsByName/HostBox.hx @@ -0,0 +1,63 @@ +// An abstract over a host type: its methods are static functions of a private +// implementation class, for which the host gives a script no binding, so a +// script calls them by name +abstract HostBox(Array) { + public var length(get, never):Int; + + public function new(count:Int) { + this = [for (i in 0...count) i * 0.5]; + } + + function get_length():Int + return this.length; + + @:arrayAccess public function get(index:Int):Float + return this[index]; + + @:arrayAccess public function set(index:Int, value:Float):Float + return this[index] = value; + + public function label(prefix:String, upper:Bool):String { + var s = prefix + this.length; + return upper ? s.toUpperCase() : s; + } + + public function sumInts(values:Array):Int { + var total = 0; + for (v in values) + total += v; + return total; + } + + public function pick(value:Dynamic):Dynamic + return value; + + public function maybe(?n:Null):Int + return n == null ? -1 : n; + + public function single(value:cpp.Float32):cpp.Float32 + return value * 2; + + public function isLong():Bool + return this.length > 3; + + public function clear():Void { + for (i in 0...this.length) + this[i] = 0; + } + + public function six(a:Int, b:Float, c:String, d:Bool, e:Int, f:Float):String + return '$a $b $c $d $e $f'; + + public function twice(value:haxe.Int64):haxe.Int64 + return value * 2; + + public function fail(x:Int):Int { + if (x > 1) + throw "too big " + x; + return x; + } + + public static function make(count:Int):HostBox + return new HostBox(count); +} diff --git a/test/regression/CppiaStaticCallsByName/Main.hx b/test/regression/CppiaStaticCallsByName/Main.hx new file mode 100644 index 000000000..b1f8ab813 --- /dev/null +++ b/test/regression/CppiaStaticCallsByName/Main.hx @@ -0,0 +1,60 @@ +// A script calling a host static function the host gives no binding for, such +// as one of an abstract's implementation class, calls it through a typed entry +// its Dynamic wrapper registers, with each value as it is, instead of boxing +// every argument and the result. The same cases run as compiled code, then as +// a script with the JIT off and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +class Compiled { + public static function run() { + var box = HostBox.make(5); + var sum = 0.0; + for (round in 0...3) + for (i in 0...box.length) { + box[i] = box[i] * 2 + round; + sum += box[i]; + } + Sys.println('length and elements ${box.length} $sum ${box[0]} ${box[4]}'); + Sys.println('String and Bool ${box.label("n", false)} ${box.label("n", true)} ${box.isLong()}'); + var loose:Array = [1, 2, 3]; + Sys.println('arrays ${box.sumInts([1, 2, 3, 400])} ${box.sumInts([])} ${box.sumInts(cast loose)}'); + var picked:Array = [box.pick(1), box.pick(1000), box.pick(2.5), box.pick("s"), box.pick(true), box.pick(null), box.pick([7])]; + Sys.println('Dynamic $picked'); + Sys.println('optional ${box.maybe()} ${box.maybe(7)} ${box.maybe(null)}'); + Sys.println('Float32 ${box.single(1.25)} ${box.single(3)}'); + Sys.println('six ${box.six(1, 2.5, "c", true, -5, 0.125)}'); + Sys.println('Int64 ${box.twice(haxe.Int64.make(1, 2))} ${box.twice(haxe.Int64.ofInt(-21))}'); + var caught = []; + for (k in 0...4) + try { + caught.push(Std.string(box.fail(k))); + } catch (e:String) { + caught.push(e); + } + Sys.println('throws $caught'); + box.clear(); + Sys.println('Void ${box[0]} ${box[3]} ${box.length}'); + var many = 0; + var other = HostBox.make(1000); + for (i in 0...20000) { + var slot = i % other.length; + other[slot] = other[slot] * 0.5 + (i & 255); + many += Std.int(other[slot]); + } + Sys.println('many calls $many'); + } +} diff --git a/test/regression/CppiaStaticCallsByName/Script.hx b/test/regression/CppiaStaticCallsByName/Script.hx new file mode 100644 index 000000000..5a220747a --- /dev/null +++ b/test/regression/CppiaStaticCallsByName/Script.hx @@ -0,0 +1,40 @@ +// The same cases as Compiled in Main.hx, run as a script +class Script { + static function main() { + var box = HostBox.make(5); + var sum = 0.0; + for (round in 0...3) + for (i in 0...box.length) { + box[i] = box[i] * 2 + round; + sum += box[i]; + } + Sys.println('length and elements ${box.length} $sum ${box[0]} ${box[4]}'); + Sys.println('String and Bool ${box.label("n", false)} ${box.label("n", true)} ${box.isLong()}'); + var loose:Array = [1, 2, 3]; + Sys.println('arrays ${box.sumInts([1, 2, 3, 400])} ${box.sumInts([])} ${box.sumInts(cast loose)}'); + var picked:Array = [box.pick(1), box.pick(1000), box.pick(2.5), box.pick("s"), box.pick(true), box.pick(null), box.pick([7])]; + Sys.println('Dynamic $picked'); + Sys.println('optional ${box.maybe()} ${box.maybe(7)} ${box.maybe(null)}'); + Sys.println('Float32 ${box.single(1.25)} ${box.single(3)}'); + Sys.println('six ${box.six(1, 2.5, "c", true, -5, 0.125)}'); + Sys.println('Int64 ${box.twice(haxe.Int64.make(1, 2))} ${box.twice(haxe.Int64.ofInt(-21))}'); + var caught = []; + for (k in 0...4) + try { + caught.push(Std.string(box.fail(k))); + } catch (e:String) { + caught.push(e); + } + Sys.println('throws $caught'); + box.clear(); + Sys.println('Void ${box[0]} ${box[3]} ${box.length}'); + var many = 0; + var other = HostBox.make(1000); + for (i in 0...20000) { + var slot = i % other.length; + other[slot] = other[slot] * 0.5 + (i & 255); + many += Std.int(other[slot]); + } + Sys.println('many calls $many'); + } +} diff --git a/test/regression/CppiaStaticCallsByName/build.hxml b/test/regression/CppiaStaticCallsByName/build.hxml new file mode 100644 index 000000000..850bcd4ce --- /dev/null +++ b/test/regression/CppiaStaticCallsByName/build.hxml @@ -0,0 +1,9 @@ +--main Main +-cpp bin +-D scriptable +--dce no +-D dll_export=bin/host_classes.info +--next +--main Script +-cppia bin/script.cppia +-D dll_import=bin/host_classes.info diff --git a/test/regression/CppiaStaticCallsByName/stdout.txt b/test/regression/CppiaStaticCallsByName/stdout.txt new file mode 100644 index 000000000..67223e0f1 --- /dev/null +++ b/test/regression/CppiaStaticCallsByName/stdout.txt @@ -0,0 +1,36 @@ +-- compiled +length and elements 5 95 4 20 +String and Bool n5 N5 true +arrays 406 0 6 +Dynamic [1,1000,2.5,s,true,null,[7]] +optional -1 7 -1 +Float32 2.5 6 +six 1 2.5 c true -5 0.125 +Int64 8589934596 -42 +throws [0,1,too big 2,too big 3] +Void 0 0 5 +many calls 5071682 +-- script, JIT off +length and elements 5 95 4 20 +String and Bool n5 N5 true +arrays 406 0 6 +Dynamic [1,1000,2.5,s,true,null,[7]] +optional -1 7 -1 +Float32 2.5 6 +six 1 2.5 c true -5 0.125 +Int64 8589934596 -42 +throws [0,1,too big 2,too big 3] +Void 0 0 5 +many calls 5071682 +-- script, JIT on +length and elements 5 95 4 20 +String and Bool n5 N5 true +arrays 406 0 6 +Dynamic [1,1000,2.5,s,true,null,[7]] +optional -1 7 -1 +Float32 2.5 6 +six 1 2.5 c true -5 0.125 +Int64 8589934596 -42 +throws [0,1,too big 2,too big 3] +Void 0 0 5 +many calls 5071682 diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index f65709291..72186db7d 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -31,6 +31,7 @@ CppiaModuleFree: threads CppiaModuleRetained: threads CppiaNullDynamicArray: its host is the first --next section, which -D emscripten does not reach, and it runs the script under the JIT too, and Emscripten has no cppia JIT CppiaStackSize: threads (std::thread, which needs a pthreads build) +CppiaStaticCallsByName: its host is the first --next section, which -D emscripten does not reach CppiaThreadedLookups: threads DateTimezoneCache: Emscripten takes the local zone from JavaScript and ignores TZ ExitWithBusyWorker: processes and threads From d74ecf2e12e44880b4e1735871c7f80e716b29dd Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 23:07:35 -0500 Subject: [PATCH 10/23] Check unused cppia casts to classes and interfaces under the JIT 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 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 5 +- test/regression/CppiaJitUnusedCasts/Main.hx | 78 +++++++++++++++++++ test/regression/CppiaJitUnusedCasts/Script.hx | 56 +++++++++++++ .../regression/CppiaJitUnusedCasts/build.hxml | 7 ++ .../regression/CppiaJitUnusedCasts/stdout.txt | 36 +++++++++ 6 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 test/regression/CppiaJitUnusedCasts/Main.hx create mode 100644 test/regression/CppiaJitUnusedCasts/Script.hx create mode 100644 test/regression/CppiaJitUnusedCasts/build.hxml create mode 100644 test/regression/CppiaJitUnusedCasts/stdout.txt diff --git a/Changes.md b/Changes.md index 79437e1f9..c3fb9ba2c 100644 --- a/Changes.md +++ b/Changes.md @@ -2,6 +2,7 @@ libhxcpp 6.0.3 (unreleased) ------------------------------------------------------------ +* Fixed a cppia cast to a class or interface whose value goes unused, cast(o, SomeInterface) as a statement, checking nothing under the JIT: a cast that fails ran on, where the interpreter and compiled code throw. Haxe's TestCasts.testInterfaces makes such casts in closures, which the JIT now compiles. The JIT leaves out only the unused casts that cannot fail * The cppia JIT compiles a script's local functions, the closures written inside a function or an initializer, as it compiles class functions, when each is first called. No class holds them, so they were never compiled: under the JIT their bodies ran in the interpreter, whether jitted code called them or the host called them back. Jitted code calling a closure is 1.9x faster (closure_call), and the host calling one back 2.5x (native_callback). HXCPP_CPPIA_EAGER_JIT compiles them as the module loads, with the rest (HaxeFoundation/hxcpp#1213) * A cppia script calling one of its closures, or a bound method held as a value, passes the arguments and takes the result as they are when the function takes the same types, interpreted and under the JIT. Each argument was boxed into a Dynamic for __run and unboxed into the function's frame, and the result boxed and unboxed again, which allocated for most Ints and every Float. Calling a closure that takes and returns an Int is 1.8x faster under the JIT and 1.2x interpreted (closure_call). An argument of another type, more arguments than the function takes, and host functions are boxed as before * The cppia JIT reads an element of an array of objects, such as an Array of a script class, in place when the element is wanted as an object, as it reads one wanted as anything else. It called a helper that went through the array's virtual __GetItem and built a Dynamic of the element, which an object element does not need. Under the JIT, virtual calls through an array of objects are 1.4x faster (virtual_call) and allocation that reads one 1.2x (alloc_objects). Arrays of Ints, Bools, Floats and Strings still box their elements through __GetItem diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index a58df5fd6..e73369416 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -1450,7 +1450,10 @@ struct CastExpr : public CppiaDynamicExpr return; } - if (destType==etNull || destType==etVoid) + // An unused cast that cannot fail is only its value. A cast to a class or + // interface still checks, and an array conversion still runs, as the + // interpreter's do + if ((destType==etNull || destType==etVoid) && op!=castInstance && op!=castDataArray && op!=castDynArray) { value->genCode(compiler); return; diff --git a/test/regression/CppiaJitUnusedCasts/Main.hx b/test/regression/CppiaJitUnusedCasts/Main.hx new file mode 100644 index 000000000..ab8a0dc28 --- /dev/null +++ b/test/regression/CppiaJitUnusedCasts/Main.hx @@ -0,0 +1,78 @@ +// Under the JIT, a cast to a class or interface whose value goes unused, as a +// statement, checked nothing, so a cast that fails ran on, where the +// interpreter and compiled code throw. Haxe's TestCasts.testInterfaces makes +// such casts in closures, which the JIT compiles since local functions are +// compiled. +// The same cases run as compiled code, then as a script with the JIT off and on, +// and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +interface CompiledFirst {} +interface CompiledSecond {} + +class CompiledPlain implements CompiledFirst { + public function new() {} +} + +class CompiledBoth extends CompiledPlain implements CompiledSecond { + public function new() { + super(); + } +} + +class Compiled { + static function attempt(label:String, f:Void->Void) { + try { + f(); + Sys.println('$label passes'); + } catch (e:Dynamic) { + Sys.println('$label throws'); + } + } + + // A cast whose value goes unused, as a statement of a method + static function toSecond(o:Dynamic) { + cast(o, CompiledSecond); + } + + static function toBoth(o:Dynamic) { + cast(o, CompiledBoth); + } + + public static function run() { + var plain = new CompiledPlain(); + var both = new CompiledBoth(); + attempt("plain to first in a closure", function() cast(plain, CompiledFirst)); + attempt("plain to second in a closure", function() cast(plain, CompiledSecond)); + attempt("both to second in a closure", function() cast(both, CompiledSecond)); + attempt("plain to both in a closure", function() cast(plain, CompiledBoth)); + attempt("plain to second in a method", () -> toSecond(plain)); + attempt("both to second in a method", () -> toSecond(both)); + attempt("plain to both in a method", () -> toBoth(plain)); + attempt("both to both in a method", () -> toBoth(both)); + attempt("plain to second, used", function() { + var s:CompiledSecond = cast(plain, CompiledSecond); + Sys.println('used ${s == null}'); + }); + var after = 0; + attempt("a statement after a failed cast", function() { + cast(plain, CompiledSecond); + after++; + }); + Sys.println('ran on past it $after'); + } +} diff --git a/test/regression/CppiaJitUnusedCasts/Script.hx b/test/regression/CppiaJitUnusedCasts/Script.hx new file mode 100644 index 000000000..4ce6d81b5 --- /dev/null +++ b/test/regression/CppiaJitUnusedCasts/Script.hx @@ -0,0 +1,56 @@ +// The same cases as Compiled in Main.hx, run as a script +interface First {} +interface Second {} + +class Plain implements First { + public function new() {} +} + +class Both extends Plain implements Second { + public function new() { + super(); + } +} + +class Script { + static function attempt(label:String, f:Void->Void) { + try { + f(); + Sys.println('$label passes'); + } catch (e:Dynamic) { + Sys.println('$label throws'); + } + } + + // A cast whose value goes unused, as a statement of a method + static function toSecond(o:Dynamic) { + cast(o, Second); + } + + static function toBoth(o:Dynamic) { + cast(o, Both); + } + + static function main() { + var plain = new Plain(); + var both = new Both(); + attempt("plain to first in a closure", function() cast(plain, First)); + attempt("plain to second in a closure", function() cast(plain, Second)); + attempt("both to second in a closure", function() cast(both, Second)); + attempt("plain to both in a closure", function() cast(plain, Both)); + attempt("plain to second in a method", () -> toSecond(plain)); + attempt("both to second in a method", () -> toSecond(both)); + attempt("plain to both in a method", () -> toBoth(plain)); + attempt("both to both in a method", () -> toBoth(both)); + attempt("plain to second, used", function() { + var s:Second = cast(plain, Second); + Sys.println('used ${s == null}'); + }); + var after = 0; + attempt("a statement after a failed cast", function() { + cast(plain, Second); + after++; + }); + Sys.println('ran on past it $after'); + } +} diff --git a/test/regression/CppiaJitUnusedCasts/build.hxml b/test/regression/CppiaJitUnusedCasts/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaJitUnusedCasts/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaJitUnusedCasts/stdout.txt b/test/regression/CppiaJitUnusedCasts/stdout.txt new file mode 100644 index 000000000..d9508c80c --- /dev/null +++ b/test/regression/CppiaJitUnusedCasts/stdout.txt @@ -0,0 +1,36 @@ +-- compiled +plain to first in a closure passes +plain to second in a closure throws +both to second in a closure passes +plain to both in a closure throws +plain to second in a method throws +both to second in a method passes +plain to both in a method throws +both to both in a method passes +plain to second, used throws +a statement after a failed cast throws +ran on past it 0 +-- script, JIT off +plain to first in a closure passes +plain to second in a closure throws +both to second in a closure passes +plain to both in a closure throws +plain to second in a method throws +both to second in a method passes +plain to both in a method throws +both to both in a method passes +plain to second, used throws +a statement after a failed cast throws +ran on past it 0 +-- script, JIT on +plain to first in a closure passes +plain to second in a closure throws +both to second in a closure passes +plain to both in a closure throws +plain to second in a method throws +both to second in a method passes +plain to both in a method throws +both to both in a method passes +plain to second, used throws +a statement after a failed cast throws +ran on past it 0 From 152b1bd082256eecf0210f50f03ce54acd756160 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Fri, 27 Nov 2026 21:06:26 -0500 Subject: [PATCH 11/23] Call script closures from host code without boxing their arguments 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(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 --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, 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. --- Changes.md | 1 + include/Dynamic.h | 22 +- include/cpp/Variant.h | 18 ++ include/hx/TypedCall.h | 303 ++++++++++++++++++ src/Dynamic.cpp | 6 + src/hx/cppia/Cppia.h | 3 + src/hx/cppia/CppiaFunction.cpp | 196 ++++++++++- .../CppiaHostClosureCalls/HostCalls.hx | 229 +++++++++++++ test/regression/CppiaHostClosureCalls/Main.hx | 93 ++++++ .../CppiaHostClosureCalls/Script.hx | 72 +++++ .../CppiaHostClosureCalls/build.hxml | 9 + .../CppiaHostClosureCalls/stdout.txt | 158 +++++++++ test/regression/emscripten-skip.txt | 1 + toolchain/haxe-target.xml | 1 + 14 files changed, 1095 insertions(+), 17 deletions(-) create mode 100644 include/hx/TypedCall.h create mode 100644 test/regression/CppiaHostClosureCalls/HostCalls.hx create mode 100644 test/regression/CppiaHostClosureCalls/Main.hx create mode 100644 test/regression/CppiaHostClosureCalls/Script.hx create mode 100644 test/regression/CppiaHostClosureCalls/build.hxml create mode 100644 test/regression/CppiaHostClosureCalls/stdout.txt diff --git a/Changes.md b/Changes.md index c3fb9ba2c..c2eb325b0 100644 --- a/Changes.md +++ b/Changes.md @@ -12,6 +12,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed the collector marking and moving the variables a cppia closure captures in place in the closure: a closure packs its captures at 4-byte offsets, so on 64-bit a String or object captured after an Int, as text in var count = 1; var text = "x"; function() return count + text, sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. Each capture is copied out to be marked or visited now, and written back if the moving collector moved it. Interpreted and jitted closures were both affected * Fixed the cppia interpreter reading an argument's slot in place in the script frame when it fills in the argument's default value, and writing a Float or Dynamic default the same way: a frame keeps 4-byte alignment, so on 64-bit an argument after an Int, as b in f(a:Int, ?b:String = "x"), sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. The slots are copied in and out now, as the interpreter's other frame accesses have been since 6.0.0. The JIT, which compiles defaults into the function, was not affected * Fixed Semaphore.tryAcquire(-1) waiting for ever where any other negative timeout returns at once, so a timeout worked out in whole seconds as deadline - now could wait with no limit once the deadline had passed. It was kept for Haxe 5.0.0-preview.1's Lock.wait() (libhxcpp #461), but preview.1's Lock waits through the runtime's own lock, which still takes a negative timeout as no limit, as Haxe 4's does. Only Haxe 5 nightlies from March to November 2026, which libhxcpp does not support, passed -1 to the semaphore; later ones call acquire() for no timeout. Every negative timeout returns at once now, as with stock hxcpp on Linux and macOS (HaxeFoundation/haxe#13114) +* Host code calling a cppia script closure, in a scriptable build, passes Int, Float, Bool and String arguments as they are, interpreted and under the JIT. Haxe 4 makes a function value a Dynamic, so a call such as callback(i) boxed each argument into a Dynamic for __run, which the closure unboxed into its frame. Dynamic::operator(), and the Variant a field of an anonymous structure or a Dynamic is read as, now take those arguments as their own types and call hx::callFunction, a typed call in the new hx/TypedCall.h (HXCPP_TYPED_CALLS), which runs a script closure whose function takes exactly those types through its compiled code, as jitted code calling a closure directly runs it. Any other function value, and any argument a closure takes as another type, is boxed as __run had it, so every closure gets the same values, and calls with only objects keep the old overloads. The host calling back a closure that takes and returns an Int is 1.5x faster under the JIT and 1.1x interpreted (native_callback), 0.30x of HashLink 1.16's JIT where it was 0.20x. The result is still boxed, since generated code uses it as a Dynamic, and is now about a third of such a call. No class changes its layout: code compiled against the older headers, such as a prebuilt static library, keeps calling through __run until it is rebuilt libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/include/Dynamic.h b/include/Dynamic.h index 1a4c8818f..497a59704 100644 --- a/include/Dynamic.h +++ b/include/Dynamic.h @@ -8,6 +8,7 @@ // It uses dynamic_cast to provide strongly-typed access to the real class. #include +#include namespace hx { @@ -26,6 +27,11 @@ namespace hx template hx::Object *NewStaticFunction(TReturn (*inFunction)(TArgs...)); + + // hx/TypedCall.h, included at the end of this file + template struct IsTypedCall; + template + TResult callFunction(const ::Dynamic &inFunction, TArgs &&... inArgs); } @@ -353,6 +359,20 @@ class HXCPP_EXTERN_CLASS_ATTRIBUTES Dynamic : public hx::ObjectPtr inline ::Dynamic operator()(const Dynamic& inArg0, const Dynamic& inArg1, const Dynamic& inArg2, const Dynamic& inArg3) { CheckFPtr(); return mPtr->__run(inArg0, inArg1, inArg2, inArg3); } inline ::Dynamic operator()(const Dynamic& inArg0, const Dynamic& inArg1, const Dynamic& inArg2, const Dynamic& inArg3, const Dynamic& inArg4) { CheckFPtr(); return mPtr->__run(inArg0, inArg1, inArg2, inArg3, inArg4); } + #ifdef HXCPP_SCRIPTABLE + // Generated code calls a function value with each argument as its own type, so a + // number, a Bool or a String reaches a script closure as it is, as a call from a + // script passes it, through hx::callFunction. Any other function value gets them + // boxed through __run, as the overloads above would have boxed them. See + // hx::IsTypedCall. Only a scriptable build has script closures, and hx::Object + // differs with HXCPP_SCRIPTABLE, so a program has this throughout or not at all + template + inline typename std::enable_if::value, ::Dynamic>::type operator()(TArgs &&... inArgs) + { + return hx::callFunction< ::Dynamic>(*this, std::forward(inArgs)...); + } + #endif + HX_DECLARE_DYNAMIC_FUNCTIONS; #endif @@ -537,6 +557,6 @@ double operator%(const float &inLHS,const Dynamic &inRHS); template String::String(const cpp::Struct &inRHS) { *this = (String)inRHS; } template String::String(const hx::ObjectPtr &inRHS) { *this = Dynamic(inRHS); } - +#include #endif diff --git a/include/cpp/Variant.h b/include/cpp/Variant.h index 166f31843..6edf639f3 100644 --- a/include/cpp/Variant.h +++ b/include/cpp/Variant.h @@ -1,5 +1,9 @@ #ifndef CPP_VARIANT_TWICE_H +#include + +// hx/TypedCall.h +namespace hx { template struct IsTypedCall; } namespace cpp { @@ -158,6 +162,12 @@ namespace cpp #if (HXCPP_API_LEVEL<500) HX_DECLARE_VARIANT_FUNCTIONS + #ifdef HXCPP_SCRIPTABLE + // A call through a field read as a Variant, as Dynamic::operator() calls one: an + // argument that is a number, a Bool or a String reaches a script closure as it is + template + inline typename std::enable_if::value, ::Dynamic>::type operator()(TArgs &&... inArgs); + #endif #endif @@ -336,6 +346,14 @@ namespace cpp #if (HXCPP_API_LEVEL<500) HX_IMPLEMENT_INLINE_VARIANT_FUNCTIONS + #ifdef HXCPP_SCRIPTABLE + template + inline typename std::enable_if::value, ::Dynamic>::type Variant::operator()(TArgs &&... inArgs) + { + CheckFPtr(); + return hx::callFunction< ::Dynamic>(::Dynamic(valObject), std::forward(inArgs)...); + } + #endif #endif int Variant::asInt() const diff --git a/include/hx/TypedCall.h b/include/hx/TypedCall.h new file mode 100644 index 000000000..31647aa62 --- /dev/null +++ b/include/hx/TypedCall.h @@ -0,0 +1,303 @@ +#ifndef HX_TYPED_CALL_H +#define HX_TYPED_CALL_H + +// Typed calls of Haxe function values. +// +// TResult hx::callFunction(const ::Dynamic &inFunction, inArgs...) +// +// calls inFunction, a function value, with inArgs, for a result of type TResult. +// It gives what calling inFunction through __run gives, with each argument boxed +// into the Dynamic that a parameter of Dynamic::operator() would hold and the +// Dynamic result converted to TResult as generated code converts one, by +// initialising a TResult from it (or dropping it, for void). A null inFunction +// throws as calling it does. +// +// A script closure whose function takes the arguments as their own types, and +// gives TResult as its own, is called without boxing either, and under the JIT +// through its compiled code directly. Arguments and results of other types still +// box where __run would have, so the closure and the caller see the same values. +// +// An argument that is an int, bool, double or ::String goes as it is; float, +// short, unsigned short, signed char, unsigned char, unsigned int, char16_t and +// char32_t as the int or double that their Dynamic holds; anything else as the +// Dynamic it converts to. TResult may be void, int, bool, double, ::String, +// ::Dynamic or any type a Dynamic converts to. +// +// Dynamic::operator() of a scriptable build calls this when one of its arguments +// is a number, a Bool or a String. HXCPP_TYPED_CALLS says it is there, for code +// that calls it directly. It is for API levels below 500, where function values +// run through __run; the cppia runtime's side of it is there at every level. + +#include +#include + +#if (HXCPP_API_LEVEL<500) +#define HXCPP_TYPED_CALLS 1 +#endif + +namespace hx +{ + +// What a typed call hands the cppia runtime: one slot for each argument, which +// the signature's kinds say how to read, and the address of the result +union TypedCallArg +{ + int intValue; + bool boolValue; + double floatValue; + const ::String *stringValue; + hx::Object *objectValue; +}; + +enum TypedCallKind +{ + typedCallVoid = 0, + typedCallInt = 1, + typedCallFloat = 2, + typedCallString = 3, + typedCallObject = 4, + typedCallBool = 5, +}; + +// Each argument's slot. Anything with no slot of its own becomes the Dynamic that +// a parameter of Dynamic::operator() would have held, by the same conversion +template struct TypedCallArgOf +{ + enum { kind = typedCallObject }; + static inline TypedCallArg make(const ::Dynamic &inValue) { TypedCallArg a; a.objectValue = inValue.mPtr; return a; } +}; +template struct TypedCallIntArgOf +{ + enum { kind = KIND }; + static inline TypedCallArg make(T inValue) { TypedCallArg a; a.intValue = (int)inValue; return a; } +}; +// The integer types Dynamic boxes as an Int of the same value +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf : TypedCallIntArgOf { }; +template<> struct TypedCallArgOf +{ + enum { kind = typedCallBool }; + static inline TypedCallArg make(bool inValue) { TypedCallArg a; a.boolValue = inValue; return a; } +}; +template<> struct TypedCallArgOf +{ + enum { kind = typedCallFloat }; + static inline TypedCallArg make(double inValue) { TypedCallArg a; a.floatValue = inValue; return a; } +}; +// Dynamic boxes a float as the double of it +template<> struct TypedCallArgOf +{ + enum { kind = typedCallFloat }; + static inline TypedCallArg make(float inValue) { TypedCallArg a; a.floatValue = inValue; return a; } +}; +template<> struct TypedCallArgOf< ::String> +{ + enum { kind = typedCallString }; + static inline TypedCallArg make(const ::String &inValue) { TypedCallArg a; a.stringValue = &inValue; return a; } +}; + +// How the result comes back: what the script path wrote (get), or the Dynamic of +// the boxed call, converted as generated code initialises a TResult from one. +// A type with no kind of its own is converted from the Dynamic result either way +template struct TypedCallResultOf +{ + enum { kind = typedCallObject }; + typedef hx::Object *Storage; + static inline T convert(const ::Dynamic &inValue) { T result = inValue; return result; } + static inline T get(hx::Object *inValue) { return convert(::Dynamic(inValue)); } +}; +template<> struct TypedCallResultOf< ::Dynamic> +{ + enum { kind = typedCallObject }; + typedef hx::Object *Storage; + static inline ::Dynamic convert(const ::Dynamic &inValue) { return inValue; } + static inline ::Dynamic get(hx::Object *inValue) { return ::Dynamic(inValue); } +}; +template<> struct TypedCallResultOf +{ + enum { kind = typedCallInt }; + typedef int Storage; + static inline int convert(const ::Dynamic &inValue) { int result = inValue; return result; } + static inline int get(int inValue) { return inValue; } +}; +template<> struct TypedCallResultOf +{ + enum { kind = typedCallBool }; + typedef bool Storage; + static inline bool convert(const ::Dynamic &inValue) { bool result = inValue; return result; } + static inline bool get(bool inValue) { return inValue; } +}; +template<> struct TypedCallResultOf +{ + enum { kind = typedCallFloat }; + typedef double Storage; + static inline double convert(const ::Dynamic &inValue) { double result = inValue; return result; } + static inline double get(double inValue) { return inValue; } +}; +template<> struct TypedCallResultOf< ::String> +{ + enum { kind = typedCallString }; + typedef ::String Storage; + static inline ::String convert(const ::Dynamic &inValue) { ::String result = inValue; return result; } + static inline ::String get(const ::String &inValue) { return inValue; } +}; + +// A call's signature, as two compile-time ints: the count in the low 4 bits, then +// 3 bits for each argument's kind, and the result's kind in bits 28 to 30. The +// match code has a Bool as an Int, as a script function takes one, and no +// result: it is what a script function whose arguments are those types has +template struct TypedCallCodes +{ + enum { kinds = 0, match = 0 }; +}; +template struct TypedCallCodes +{ + enum + { + kind = TypedCallArgOf::kind, + kinds = (kind << SHIFT) | TypedCallCodes::kinds, + match = ((kind==typedCallBool ? (int)typedCallInt : (int)kind) << SHIFT) | TypedCallCodes::match, + }; +}; +template struct TypedCallSignature +{ + enum + { + count = sizeof...(TArgs), + match = count | TypedCallCodes<4, TArgs...>::match, + kinds = count | TypedCallCodes<4, TArgs...>::kinds | (TypedCallResultOf::kind << 28), + }; +}; +template struct TypedCallSignature +{ + enum + { + count = sizeof...(TArgs), + match = count | TypedCallCodes<4, TArgs...>::match, + kinds = count | TypedCallCodes<4, TArgs...>::kinds, + }; +}; + +// A typed call of at most this many arguments can take the script path +enum { typedCallMaxArgs = 8 }; + + +// Set before main by the cppia runtime, which a scriptable build links: the vtable +// of its script closures, and the call that runs one, given the signature's match +// and kinds codes, the arguments and where its result goes (0 for void). Until +// then the vtable is null, which no object has. Code built against these headers +// calls them, so they keep this form +typedef void (*ScriptClosureTypedCall)(hx::Object *inClosure, int inMatch, int inKinds, const TypedCallArg *inArgs, void *outResult); +extern HXCPP_EXTERN_CLASS_ATTRIBUTES void *gScriptClosureVTable; +extern HXCPP_EXTERN_CLASS_ATTRIBUTES ScriptClosureTypedCall gScriptClosureTypedCall; + +#if (HXCPP_API_LEVEL<500) + +// The calls Dynamic::operator() makes typed: 1 to 5 arguments, one of them a +// number, a Bool or a String. It deduces every parameter as the argument's own +// type, so it is never a worse match than the overloads taking each as a +// Dynamic, and a better one for that argument: no call becomes ambiguous, and a +// call of anything else keeps those overloads +template struct AnyTypedCallArg : std::false_type { }; +template struct AnyTypedCallArg : std::integral_constant::kind!=(int)typedCallObject || AnyTypedCallArg::value> { }; +template struct IsTypedCall : std::integral_constant= 1) && (sizeof...(TArgs) <= 5) && + AnyTypedCallArg::type...>::value> { }; + +// The call Dynamic::operator() makes, with each argument converted to a Dynamic +// as one of its parameters converts it: __run, or for more than 5 arguments __Run +// with an Array of them +template struct TypedCallBoxedMany +{ + template + static inline ::Dynamic run(hx::Object *inFunction, TArgs &&... inArgs) + { + ::Dynamic function(inFunction); + return function(std::forward(inArgs)...); + } +}; +template<> struct TypedCallBoxedMany +{ + template + static inline ::Dynamic run(hx::Object *inFunction, TArgs &&... inArgs) + { + return inFunction->__run(std::forward(inArgs)...); + } +}; + +template struct TypedCaller +{ + template + static inline TResult call(hx::Object *inFunction, TArgs &&... inArgs) + { + #ifdef HXCPP_SCRIPTABLE + if (*(void **)inFunction==gScriptClosureVTable) + { + typedef TypedCallSignature::type...> Signature; + const TypedCallArg args[sizeof...(TArgs)+1] = { TypedCallArgOf::type>::make(std::forward(inArgs))... }; + typename TypedCallResultOf::Storage result; + gScriptClosureTypedCall(inFunction, Signature::match, Signature::kinds, args, &result); + return TypedCallResultOf::get(result); + } + #endif + return TypedCallResultOf::convert(TypedCallBoxedMany<(sizeof...(TArgs)>5)>::run(inFunction, std::forward(inArgs)...)); + } +}; + +template struct TypedCaller +{ + template + static inline void call(hx::Object *inFunction, TArgs &&... inArgs) + { + #ifdef HXCPP_SCRIPTABLE + if (*(void **)inFunction==gScriptClosureVTable) + { + typedef TypedCallSignature::type...> Signature; + const TypedCallArg args[sizeof...(TArgs)+1] = { TypedCallArgOf::type>::make(std::forward(inArgs))... }; + gScriptClosureTypedCall(inFunction, Signature::match, Signature::kinds, args, 0); + return; + } + #endif + TypedCallBoxedMany<(sizeof...(TArgs)>5)>::run(inFunction, std::forward(inArgs)...); + } +}; + +// Too many arguments for the signature codes: always the boxed call +template struct TypedCaller +{ + template + static inline TResult call(hx::Object *inFunction, TArgs &&... inArgs) + { + return TypedCallResultOf::convert(TypedCallBoxedMany::run(inFunction, std::forward(inArgs)...)); + } +}; +template<> struct TypedCaller +{ + template + static inline void call(hx::Object *inFunction, TArgs &&... inArgs) + { + TypedCallBoxedMany::run(inFunction, std::forward(inArgs)...); + } +}; + +template +inline TResult callFunction(const ::Dynamic &inFunction, TArgs &&... inArgs) +{ + hx::Object *function = inFunction.mPtr; + if (!function) + ::Dynamic::ThrowBadFunctionError(); + return TypedCaller::call(function, std::forward(inArgs)...); +} + +#endif + +} + +#endif diff --git a/src/Dynamic.cpp b/src/Dynamic.cpp index 35eff2efa..20a71ce4f 100644 --- a/src/Dynamic.cpp +++ b/src/Dynamic.cpp @@ -27,6 +27,12 @@ hx::Class __ObjcClass; #endif +// Filled in by the cppia runtime's static initialisation, before anything can call a +// script closure; see hx/TypedCall.h +void *gScriptClosureVTable = 0; +ScriptClosureTypedCall gScriptClosureTypedCall = 0; + + hx::Class &GetBoolClass() { return __BoolClass; } hx::Class &GetIntClass() { return __IntClass; } hx::Class &GetFloatClass() { return __FloatClass; } diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 71bbf7875..67b135337 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -333,6 +333,9 @@ struct ScriptCallable : public CppiaDynamicExpr // 0 for a function a closure cannot be made of int callSigArgs; int callSigFull; + // What a typed call from host code compares, hx::TypedCallSignature's match code + // for a call of exactly these arguments; -1 for one no such call can match + int typedCallMatch; ScriptCallable(CppiaStream &stream); diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index b139cf7bc..e7e7a1c8c 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -36,6 +36,7 @@ ScriptCallable::ScriptCallable(CppiaStream &stream) captureSize = 0; callSigArgs = 0; callSigFull = 0; + typedCallMatch = -1; hasDefaults = false; staticEntry = false; #ifdef CPPIA_JIT @@ -65,6 +66,7 @@ ScriptCallable::ScriptCallable(CppiaExpr *inBody) : CppiaDynamicExpr(inBody) captureSize = 0; callSigArgs = 0; callSigFull = 0; + typedCallMatch = -1; hasDefaults = false; body = inBody; data = 0; @@ -103,6 +105,7 @@ ScriptCallable::ScriptCallable(CppiaModule &inModule,ScriptNamedFunction *inFunc captureSize = 0; callSigArgs = 0; callSigFull = 0; + typedCallMatch = -1; hasDefaults = false; //body = inBody; data = 0; @@ -245,6 +248,27 @@ CppiaExpr *ScriptCallable::link(CppiaModule &inModule) callSigArgs = internCallSignature(signature); callSigFull = internCallSignature(signature + callReturnCode(returnType)); + // An array argument takes an object converted, which a typed call does not give + typedCallMatch = -1; + if (args.size()<=hx::typedCallMaxArgs) + { + typedCallMatch = (int)args.size(); + for(int a=0;aarrayType==arrNotArray) + kind = hx::typedCallObject; + } + typedCallMatch |= kind << (4 + 3*a); + } + } + position.className = className; position.functionName = functionName; position.fileName = filename; @@ -902,10 +926,9 @@ void CppiaFunction::markLazy() -// The vtable every CppiaClosure has, which each stores as it is made, so a call can -// tell a script closure from another function object by its first word, without a -// dynamic_cast. Nothing can be a closure while this is still null -static std::atomic sClosureVTable(0); +// A call tells a script closure from another function object by its first word, +// without a dynamic_cast: every CppiaClosure has the vtable in hx::gScriptClosureVTable, +// which is set before main, below class CppiaClosure : public hx::Object { @@ -919,7 +942,6 @@ class CppiaClosure : public hx::Object CppiaClosure(CppiaCtx *ctx, ScriptCallable *inFunction) { function = inFunction; - noteVTable(); unsigned char *base = ((unsigned char *)this) + sizeof(CppiaClosure); @@ -943,16 +965,11 @@ class CppiaClosure : public hx::Object CppiaClosure(hx::Object *inThis, ScriptCallable *inFunction) { function = inFunction; - noteVTable(); *getThis() = inThis; } - void noteVTable() - { - void *vtable = *(void **)this; - if (sClosureVTable.load(std::memory_order_relaxed)!=vtable) - sClosureVTable.store(vtable, std::memory_order_relaxed); - } + // Only for reading the vtable from: it has no function, nor room for this + CppiaClosure() : function(0) { } // Writes this and the captured variables into the frame at inFrame @@ -1071,6 +1088,144 @@ class CppiaClosure : public hx::Object + // An argument of a typed call that the function does not take as its own type: + // an Int, Float or Bool goes in as it is where the function takes it as that, as + // does a String the function takes as a String, and anything else goes in as + // pushArgDynamic has the Dynamic that __run would have been given, so the frame + // holds the same values + void pushTypedArg(CppiaCtx *ctx, int a, int inKind, const hx::TypedCallArg &inArg) + { + if (a>=function->args.size()) + return; + + ExprType type = function->args[a].argType; + switch(inKind) + { + case hx::typedCallInt: + if (type==etInt) + ctx->pushInt(inArg.intValue); + else if (type==etFloat) + ctx->pushFloat(inArg.intValue); + else + pushArgDynamic(ctx,a,Dynamic(inArg.intValue)); + return; + case hx::typedCallBool: + if (type==etInt) + ctx->pushInt(inArg.boolValue); + else + pushArgDynamic(ctx,a,Dynamic(inArg.boolValue)); + return; + case hx::typedCallFloat: + if (type==etFloat) + ctx->pushFloat(inArg.floatValue); + else + pushArgDynamic(ctx,a,Dynamic(inArg.floatValue)); + return; + case hx::typedCallString: + if (type==etString) + ctx->pushString(*inArg.stringValue); + else + pushArgDynamic(ctx,a,Dynamic(*inArg.stringValue)); + return; + default: + pushArgDynamic(ctx,a,Dynamic(inArg.objectValue)); + } + } + + // The result of a typed call, which wants inKind: as the function left it where + // that is the kind wanted, and otherwise boxed as __run returns it and converted + // as hx::callFunction converts that + void writeTypedResult(CppiaCtx *ctx, int inKind, void *outResult) + { + ExprType type = function->returnType; + switch(inKind) + { + case hx::typedCallVoid: + return; + case hx::typedCallInt: + // A Bool is boxed as one, which gives 1 for any value but 0 + if (type==etInt) + *(int *)outResult = function->isBoolReturn ? (ctx->getInt()!=0) : ctx->getInt(); + else + *(int *)outResult = hx::TypedCallResultOf::convert(boxResult(ctx,function)); + return; + case hx::typedCallBool: + if (type==etInt) + *(bool *)outResult = ctx->getInt()!=0; + else + *(bool *)outResult = hx::TypedCallResultOf::convert(boxResult(ctx,function)); + return; + case hx::typedCallFloat: + if (type==etFloat) + *(double *)outResult = ctx->getFloat(); + else + *(double *)outResult = hx::TypedCallResultOf::convert(boxResult(ctx,function)); + return; + case hx::typedCallString: + if (type==etString) + *(String *)outResult = ctx->getString(); + else + *(String *)outResult = hx::TypedCallResultOf::convert(boxResult(ctx,function)); + return; + default: + *(hx::Object **)outResult = boxResult(ctx,function); + } + } + + // A call from host code through hx::callFunction (hx/TypedCall.h). When the + // function takes exactly these arguments and is compiled, it runs as jitted code + // calling a closure directly runs it: the arguments into a new frame as they are, + // the captured variables after them, and its code called. Otherwise each argument + // goes in as pushTypedArg has it, and the function runs as __run runs it + static void typedCall(hx::Object *inClosure, int inMatch, int inKinds, const hx::TypedCallArg *inArgs, void *outResult) + { + CppiaClosure *closure = (CppiaClosure *)inClosure; + ScriptCallable *function = closure->function; + CppiaCtx *ctx = CppiaCtx::getCurrent(); + AutoStack aut(ctx); + int count = inKinds & 15; + int resultKind = (inKinds>>28) & 7; + + #ifdef CPPIA_JIT + CppiaFunc code; + unsigned char *frame = ctx->pointer; + if (function->typedCallMatch==inMatch && (code = function->getCompiled())!=0 && + frame + function->stackSize <= ctx->stackEnd) + { + ctx->push( (hx::Object *)0 ); + for(int a=0; a>(4+3*a)) & 7 ) + { + case hx::typedCallInt: ctx->pushInt(arg.intValue); break; + case hx::typedCallBool: ctx->pushInt(arg.boolValue); break; + case hx::typedCallFloat: ctx->pushFloat(arg.floatValue); break; + case hx::typedCallString: ctx->pushString(*arg.stringValue); break; + default: ctx->pushObject(arg.objectValue); + } + } + closure->enterFrame(frame); + code(ctx); + ctx->frame = frame; + if (ctx->exception) + { + Dynamic caught = fromPendingException(ctx->exception); + ctx->exception = nullptr; + HX_STACK_DO_THROW(caught); + } + closure->writeTypedResult(ctx, resultKind, outResult); + return; + } + #endif + + ctx->pointer += sizeof(hx::Object *); + for(int a=0; apushTypedArg(ctx, a, (inKinds>>(4+3*a)) & 7, inArgs[a]); + closure->runInFrame(ctx, count, true); + closure->writeTypedResult(ctx, resultKind, outResult); + } + Dynamic __Run(const Array &inArgs) HXCPP_OVERRIDE { CppiaCtx *ctx = CppiaCtx::getCurrent(); @@ -1186,6 +1341,17 @@ class CppiaClosure : public hx::Object String toString() HXCPP_OVERRIDE { return HX_CSTRING("function"); } }; +// Before main, as the inline calls in hx/TypedCall.h read these without a lock +static struct PublishScriptClosure +{ + PublishScriptClosure() + { + CppiaClosure probe; + hx::gScriptClosureVTable = *(void **)&probe; + hx::gScriptClosureTypedCall = CppiaClosure::typedCall; + } +} sPublishScriptClosure; + hx::Object * CPPIA_CALL createClosure(CppiaCtx *ctx, ScriptCallable *inFunction) { return new (inFunction->captureSize) CppiaClosure(ctx,inFunction); @@ -1212,8 +1378,7 @@ ScriptCallable *getClosureFunction(hx::Object *inObj) ScriptCallable *scriptClosureTarget(hx::Object *inFunction) { - void *vtable = sClosureVTable.load(std::memory_order_relaxed); - if (!inFunction || !vtable || *(void **)inFunction!=vtable) + if (!inFunction || *(void **)inFunction!=hx::gScriptClosureVTable) return 0; return ((CppiaClosure *)inFunction)->function; } @@ -1231,8 +1396,7 @@ hx::Object *boxScriptClosureResult(CppiaCtx *ctx, ScriptCallable *inFunction) #ifdef CPPIA_JIT CppiaFunc SLJIT_FUNC enterScriptClosure(CppiaCtx *ctx, hx::Object *inFunction, int inSignature) { - void *vtable = sClosureVTable.load(std::memory_order_relaxed); - if (!inFunction || !vtable || *(void **)inFunction!=vtable) + if (!inFunction || *(void **)inFunction!=hx::gScriptClosureVTable) return 0; CppiaClosure *closure = (CppiaClosure *)inFunction; ScriptCallable *function = closure->function; diff --git a/test/regression/CppiaHostClosureCalls/HostCalls.hx b/test/regression/CppiaHostClosureCalls/HostCalls.hx new file mode 100644 index 000000000..3885ec118 --- /dev/null +++ b/test/regression/CppiaHostClosureCalls/HostCalls.hx @@ -0,0 +1,229 @@ +// Host code that calls function values, compiled into the host for the script to +// pass its closures to. Haxe 4 makes each function value a Dynamic, and calls it +// with every argument as its own C++ type: an int, a double, a bool, a String... +class HostCalls { + public static function kind(value:Dynamic):String { + return if (value == null) "null" else if (Std.isOfType(value, Bool)) "Bool" else if (Std.isOfType(value, Int)) "Int" else + if (Std.isOfType(value, Float)) "Float" else if (Std.isOfType(value, String)) "String" else "other"; + } + + static function show(label:String, value:Dynamic) { + Sys.println('$label $value ${kind(value)}'); + } + + public static function ints(label:String, f:Int->Int) { + var out = []; + for (i in [0, 255, 256, 70000, -1, -2, -70000, 0x7fffffff, 0x80000000]) + out.push(f(i)); + Sys.println('$label ${out.join(" ")}'); + } + + public static function floats(f:Float->Float) { + var out = []; + for (x in [0.0, 1.5, 3.0, -2.0, 255.0, 256.0, 1e300, -1e-300]) + out.push(f(x)); + Sys.println('floats ${out.join(" ")}'); + var negZero = -0.0; + var nan = Math.NaN; + var whole = 7; + Sys.println('floats 1/f(-0.0) ${1 / f(negZero)}, NaN ${Math.isNaN(f(nan))}, from an Int ${f(whole)}'); + } + + public static function bools(f:Bool->Bool) { + var b = true; + Sys.println('bools ${f(true)} ${f(false)} ${f(b) ? "if true" : "if false"}'); + } + + public static function dynamics(f:Dynamic->String) { + var small = 5, big = 300, whole = 2.0, frac = 1.5, negZero = -0.0, b = true; + Sys.println('dynamics ${f(small)}, ${f(big)}, ${f(whole)}, ${f(frac)}, ${f(negZero)}, ${f(b)}, ${f(false)}, ${f("s")}, ${f(null)}'); + } + + public static function nullables(f:Null->String) { + var i = 4; + Sys.println('nullables ${f(i)} ${f(null)}'); + } + + public static function strings(f:Int->String->String) { + var s:String = null; + Sys.println('strings ${f(1, "a")} ${f(2, s)}'); + } + + public static function defaults(f:Int->?Int->String) { + Sys.println('defaults ${f(3)} ${f(3, 4)}'); + } + + public static function mixed(f:Int->Float->Bool->String->Dynamic->String) { + var arr = [1, 2]; + Sys.println('mixed ${f(1, 2.5, true, "s", arr)} ${f(-1, -0.0, false, null, null)} ${f(300, 4.0, true, "t", 9)}'); + } + + public static function five(f:Int->Float->Int->Bool->Int->Float) { + Sys.println('five ${f(1, 0.5, 3, true, 5)}'); + } + + public static function six(f:Int->Int->Int->Int->Int->Int->Int) { + Sys.println('six ${f(1, 2, 3, 4, 5, 600)}'); + } + + public static function float32(f:Int->Float->String) { + var v:cpp.Float32 = 1.25; + Sys.println('float32 ${f(1, v)}'); + } + + public static function arrays(f:Int->Array->Int) { + Sys.println('arrays ${f(10, [1, 2, 3])}'); + } + + // No Int, Float or Bool: the boxed call, as before + public static function objects(f:Array->String->Int) { + Sys.println('objects ${f([4, 5], "xyz")}'); + } + + public static function voids(f:Int->Void) { + f(1); + f(1000); + } + + public static function results(fb:Int->Bool, ff:Int->Float, fs:Int->String, fd:Int->Dynamic) { + var b:Bool = fb(5); + var x:Float = ff(3); + var s:String = fs(2); + Sys.println('results as types $b $x $s'); + show("results Bool", fb(1)); + show("results Float", ff(2)); + show("results whole Float", ff(4)); + show("results String", fs(7)); + show("results Dynamic", fd(2)); + show("results Dynamic", fd(3)); + } + + // Each closure called with an argument of each type, whatever it takes + public static function anyTypes(label:String, f:Dynamic) { + Sys.println('$label ${f(5)} ${f(70000)} ${f(2.7)} ${f(-0.0)} ${f(true)}'); + } + + public static function extraArguments(f:Dynamic) { + Sys.println('extra arguments ${f(1, 2)} ${f(3, 4.5, true)}'); + } + + public static function throws(f:Int->Int) { + try { + f(1); + Sys.println("throws nothing"); + } catch (e:Dynamic) { + Sys.println('throws caught $e'); + } + } + + public static function nullFunction() { + var f:Int->Int = null; + try { + f(1); + Sys.println("null function called"); + } catch (e:Dynamic) { + Sys.println('null function caught $e'); + } + } + + public static function twice(f:Int->Int, x:Int):Int { + return f(f(x)); + } + + // Many calls whose arguments are boxed objects too, with collections between + public static function many(f:Int->String->Dynamic->Int) { + var sum = 0; + for (i in 0...20000) { + sum += f(i, "v" + i, i * 3); + if (i % 5000 == 0) + cpp.vm.Gc.run(true); + } + Sys.println('many $sum'); + } + + // Every C++ type a number reaches a call as, alone and beside an Int + public static function numberTypes(toInt:Int->String, toFloat:Float->String, toDynamic:Dynamic->String) { + var f32:cpp.Float32 = 1.25; + var u8:cpp.UInt8 = 200; + var i8:cpp.Int8 = -100; + var i16:cpp.Int16 = -30000; + var u16:cpp.UInt16 = 60000; + var u32:cpp.UInt32 = 0xB2D05E00; + var i64:cpp.Int64 = 5; + var c:cpp.Char = 65; + Sys.println('number types to Int ${toInt(u8)} ${toInt(i8)} ${toInt(i16)} ${toInt(u16)} ${toInt(c)}'); + Sys.println('number types to Float ${toFloat(f32)}'); + Sys.println('number types to Dynamic ${toDynamic(f32)}, ${toDynamic(u8)}, ${toDynamic(i8)}, ${toDynamic(u16)}, ${toDynamic(u32)}, ${toDynamic(i64)}, ${toDynamic(c)}'); + } + + public static function numberPairs(f:Int->Dynamic->String) { + var f32:cpp.Float32 = -0.5; + var u8:cpp.UInt8 = 255; + var i64:cpp.Int64 = 7; + Sys.println('number pairs ${f(1, f32)} ${f(2, u8)} ${f(3, i64)}'); + } + + // Calls through a field of an anonymous structure, and of a Dynamic, which + // generated code reads as a Variant + public static function fieldCalls(o:{cb:Int->Int, both:Int->Float->String}, d:Dynamic) { + Sys.println('field calls ${o.cb(5)} ${o.both(2, 0.5)} ${d.cb(6)} ${d.both(3, -0.0)} ${d.cb(true)} ${d.both("x", 1)}'); + } + + // A String alone goes as it is too + public static function stringsAlone(f:String->String, fd:Dynamic->String) { + var none:String = null; + Sys.println('strings alone ${f("a")} ${f(none)} ${fd("b")} ${fd(none)}'); + } + + // hx::callFunction as code that knows the result's type would call it, the + // way generated code could, with results of every kind wanted from closures + // of each return type + public static function typedResults(fi:Int->Int, ff:Float->Float, fb:Bool->Bool, fs:String->String, fd:Int->Dynamic, f0:Void->Int, + fv:Int->Void, nine:Int->Int->Int->Int->Int->Int->Int->Int->Int->Int, seven:Int->Float->Bool->String->Int->Float->Int->String) { + var i:Int = untyped __cpp__("::hx::callFunction({0}, 7)", fi); + var x:Float = untyped __cpp__("::hx::callFunction({0}, 1.5)", ff); + var b:Bool = untyped __cpp__("::hx::callFunction({0}, true)", fb); + var s:String = untyped __cpp__("::hx::callFunction< ::String>({0}, {1})", fs, "q"); + Sys.println('typed results $i $x $b $s'); + var asFloat:Float = untyped __cpp__("::hx::callFunction({0}, 7)", fi); + var asBool:Bool = untyped __cpp__("::hx::callFunction({0}, 0)", fi); + var asString:String = untyped __cpp__("::hx::callFunction< ::String>({0}, 7)", fi); + var asDynamic:Dynamic = untyped __cpp__("::hx::callFunction< ::Dynamic>({0}, 7)", fi); + Sys.println('typed results of an Int $asFloat $asBool $asString ${describe(asDynamic)}'); + var floatAsInt:Int = untyped __cpp__("::hx::callFunction({0}, 4.75)", ff); + var floatAsBool:Bool = untyped __cpp__("::hx::callFunction({0}, 0.25)", ff); + var floatAsString:String = untyped __cpp__("::hx::callFunction< ::String>({0}, -0.0)", ff); + var wholeAsDynamic:Dynamic = untyped __cpp__("::hx::callFunction< ::Dynamic>({0}, 2.0)", ff); + Sys.println('typed results of a Float $floatAsInt $floatAsBool $floatAsString ${describe(wholeAsDynamic)}'); + var boolAsInt:Int = untyped __cpp__("::hx::callFunction({0}, false)", fb); + var intToBool:Int = untyped __cpp__("::hx::callFunction({0}, 5)", fb); + var intToBoolAsBool:Bool = untyped __cpp__("::hx::callFunction({0}, 5)", fb); + var boolAsDynamic:Dynamic = untyped __cpp__("::hx::callFunction< ::Dynamic>({0}, false)", fb); + Sys.println('typed results of a Bool $boolAsInt $intToBool $intToBoolAsBool ${describe(boolAsDynamic)}'); + var none:String = null; + var stringAsDynamic:Dynamic = untyped __cpp__("::hx::callFunction< ::Dynamic>({0}, {1})", fs, none); + var stringAsInt:Int = untyped __cpp__("::hx::callFunction({0}, {1})", fs, "r"); + Sys.println('typed results of a String ${describe(stringAsDynamic)} $stringAsInt'); + var dynAsInt:Int = untyped __cpp__("::hx::callFunction({0}, 3)", fd); + var dynAsFloat:Float = untyped __cpp__("::hx::callFunction({0}, 3)", fd); + var dynAsString:String = untyped __cpp__("::hx::callFunction< ::String>({0}, 3)", fd); + Sys.println('typed results of a Dynamic $dynAsInt $dynAsFloat $dynAsString'); + var noArgs:Int = untyped __cpp__("::hx::callFunction({0})", f0); + untyped __cpp__("::hx::callFunction({0}, 40)", fv); + untyped __cpp__("::hx::callFunction({0}, 2)", fv); + var nineArgs:Int = untyped __cpp__("::hx::callFunction({0}, 1, 2, 3, 4, 5, 6, 7, 8, 9)", nine); + var sevenArgs:String = untyped __cpp__("::hx::callFunction< ::String>({0}, 1, 2.5, true, {1}, 5, -0.0, 7)", seven, "s"); + Sys.println('typed results with $noArgs and $nineArgs and $sevenArgs arguments'); + var nullFunction:Int->Int = null; + try { + var never:Int = untyped __cpp__("::hx::callFunction({0}, 1)", nullFunction); + Sys.println('typed results of a null function $never'); + } catch (e:Dynamic) { + Sys.println('typed results of a null function caught $e'); + } + } + + static function describe(d:Dynamic):String { + return '$d ${kind(d)}'; + } +} diff --git a/test/regression/CppiaHostClosureCalls/Main.hx b/test/regression/CppiaHostClosureCalls/Main.hx new file mode 100644 index 000000000..db4a5b6a7 --- /dev/null +++ b/test/regression/CppiaHostClosureCalls/Main.hx @@ -0,0 +1,93 @@ +// Haxe 4 host code calls a function value through Dynamic. A call with an Int, +// Float or Bool argument gives a script closure the arguments as they are, which +// it takes into its frame without boxing them, as a call from a script does; a +// call with none, or of any other function value, boxes them for __run as before. +// Either way the closure gets the same values: a Bool passed to a Dynamic +// parameter is still a Bool, a whole Float an Int box, -0.0 still -0.0. +// The same closures run compiled into the host, then as a script with the JIT +// off and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same closures as Script.hx, compiled into the host +class CompiledCounter { + public var total = 0; + + public function new() {} + + public function add(x:Int):Int { + total += x; + return total; + } +} + +class Compiled { + static function describe(d:Dynamic):String { + var kind = if (d == null) "null" else if (Std.isOfType(d, Bool)) "Bool" else if (Std.isOfType(d, Int)) "Int" else + if (Std.isOfType(d, Float)) "Float" else if (Std.isOfType(d, String)) "String" else "other"; + return '$d $kind'; + } + + static function twice(x:Int):Int + return x * 2; + + public static function run() { + var bias = 7; + HostCalls.ints("ints", x -> { + bias = (bias + 3) & 1023; + return (x & 1023) + bias; + }); + HostCalls.ints("ints negated", x -> -x); + var counter = new CompiledCounter(); + HostCalls.ints("ints bound", counter.add); + HostCalls.ints("ints static", twice); + HostCalls.floats(x -> x * 2); + HostCalls.bools(b -> !b); + HostCalls.dynamics(d -> describe(d)); + HostCalls.nullables(x -> x == null ? "none" : "" + (x + 1)); + HostCalls.strings((i, s) -> i + ":" + s); + HostCalls.defaults(function(a:Int, b:Int = 7):String return a * 10 + b + ""); + HostCalls.mixed((i:Int, x:Float, b:Bool, s:String, d:Dynamic) -> '$i $x $b $s ${describe(d)}'); + HostCalls.five((a:Int, b:Float, c:Int, d:Bool, e:Int) -> a + b * 10 + c * 100 + (d ? 1000 : 0) + e * 10000); + HostCalls.six((a, b, c, d, e, f) -> a + b * 2 + c * 3 + d * 4 + e * 5 + f * 6); + HostCalls.float32((i:Int, x:Float) -> i + " " + x); + HostCalls.arrays((i:Int, a:Array) -> i * 100 + a.length * 10 + a[2]); + HostCalls.objects((a:Array, s:String) -> a[1] * 10 + s.length); + var seen = 0; + HostCalls.voids(i -> { + seen += i; + }); + Sys.println('voids $seen'); + HostCalls.results(i -> i > 3, i -> i * 1.5, i -> "s" + i, i -> (i * 1.5 : Dynamic)); + HostCalls.anyTypes("any Int", (x:Int) -> x + 1); + HostCalls.anyTypes("any Float", (x:Float) -> x / 2); + HostCalls.anyTypes("any Bool", (b:Bool) -> b ? "yes" : "no"); + HostCalls.anyTypes("any String", (s:String) -> s + "!"); + HostCalls.anyTypes("any Dynamic", (d:Dynamic) -> describe(d)); + HostCalls.anyTypes("any Null", (x:Null) -> x == null ? "none" : "" + x); + HostCalls.throws(x -> throw "boom " + x); + HostCalls.nullFunction(); + Sys.println('twice ${HostCalls.twice(x -> HostCalls.twice(y -> y + x, x), 1)}'); + HostCalls.many((i:Int, s:String, d:Dynamic) -> s.length + d - i); + HostCalls.numberTypes(x -> "" + (x + 1), x -> "" + x * 2, d -> describe(d)); + HostCalls.numberPairs((i:Int, d:Dynamic) -> i + " " + describe(d)); + HostCalls.stringsAlone(s -> s + "!", d -> describe(d)); + var fields = {cb: (x:Int) -> x * 7, both: (i:Int, x:Float) -> i + ":" + x}; + HostCalls.fieldCalls(fields, fields); + HostCalls.typedResults(x -> x * 3, x -> x * 2, b -> b, s -> s + "!", i -> (i * 1.5 : Dynamic), () -> 42, i -> Sys.println('void got $i'), + (a, b, c, d, e, f, g, h, k) -> a + b + c + d + e + f + g + h + k, + (a:Int, b:Float, c:Bool, d:String, e:Int, f:Float, g:Int) -> '$a $b $c $d $e $f $g'); + } +} diff --git a/test/regression/CppiaHostClosureCalls/Script.hx b/test/regression/CppiaHostClosureCalls/Script.hx new file mode 100644 index 000000000..d261a5e4a --- /dev/null +++ b/test/regression/CppiaHostClosureCalls/Script.hx @@ -0,0 +1,72 @@ +class Counter { + public var total = 0; + + public function new() {} + + public function add(x:Int):Int { + total += x; + return total; + } +} + +class Script { + static function describe(d:Dynamic):String { + var kind = if (d == null) "null" else if (Std.isOfType(d, Bool)) "Bool" else if (Std.isOfType(d, Int)) "Int" else + if (Std.isOfType(d, Float)) "Float" else if (Std.isOfType(d, String)) "String" else "other"; + return '$d $kind'; + } + + static function twice(x:Int):Int + return x * 2; + + static function main() { + var bias = 7; + HostCalls.ints("ints", x -> { + bias = (bias + 3) & 1023; + return (x & 1023) + bias; + }); + HostCalls.ints("ints negated", x -> -x); + var counter = new Counter(); + HostCalls.ints("ints bound", counter.add); + HostCalls.ints("ints static", twice); + HostCalls.floats(x -> x * 2); + HostCalls.bools(b -> !b); + HostCalls.dynamics(d -> describe(d)); + HostCalls.nullables(x -> x == null ? "none" : "" + (x + 1)); + HostCalls.strings((i, s) -> i + ":" + s); + HostCalls.defaults(function(a:Int, b:Int = 7):String return a * 10 + b + ""); + HostCalls.mixed((i:Int, x:Float, b:Bool, s:String, d:Dynamic) -> '$i $x $b $s ${describe(d)}'); + HostCalls.five((a:Int, b:Float, c:Int, d:Bool, e:Int) -> a + b * 10 + c * 100 + (d ? 1000 : 0) + e * 10000); + HostCalls.six((a, b, c, d, e, f) -> a + b * 2 + c * 3 + d * 4 + e * 5 + f * 6); + HostCalls.float32((i:Int, x:Float) -> i + " " + x); + HostCalls.arrays((i:Int, a:Array) -> i * 100 + a.length * 10 + a[2]); + HostCalls.objects((a:Array, s:String) -> a[1] * 10 + s.length); + var seen = 0; + HostCalls.voids(i -> { + seen += i; + }); + Sys.println('voids $seen'); + HostCalls.results(i -> i > 3, i -> i * 1.5, i -> "s" + i, i -> (i * 1.5 : Dynamic)); + HostCalls.anyTypes("any Int", (x:Int) -> x + 1); + HostCalls.anyTypes("any Float", (x:Float) -> x / 2); + HostCalls.anyTypes("any Bool", (b:Bool) -> b ? "yes" : "no"); + HostCalls.anyTypes("any String", (s:String) -> s + "!"); + HostCalls.anyTypes("any Dynamic", (d:Dynamic) -> describe(d)); + HostCalls.anyTypes("any Null", (x:Null) -> x == null ? "none" : "" + x); + HostCalls.throws(x -> throw "boom " + x); + HostCalls.nullFunction(); + Sys.println('twice ${HostCalls.twice(x -> HostCalls.twice(y -> y + x, x), 1)}'); + HostCalls.many((i:Int, s:String, d:Dynamic) -> s.length + d - i); + HostCalls.numberTypes(x -> "" + (x + 1), x -> "" + x * 2, d -> describe(d)); + HostCalls.numberPairs((i:Int, d:Dynamic) -> i + " " + describe(d)); + HostCalls.stringsAlone(s -> s + "!", d -> describe(d)); + var fields = {cb: (x:Int) -> x * 7, both: (i:Int, x:Float) -> i + ":" + x}; + HostCalls.fieldCalls(fields, fields); + HostCalls.typedResults(x -> x * 3, x -> x * 2, b -> b, s -> s + "!", i -> (i * 1.5 : Dynamic), () -> 42, i -> Sys.println('void got $i'), + (a, b, c, d, e, f, g, h, k) -> a + b + c + d + e + f + g + h + k, + (a:Int, b:Float, c:Bool, d:String, e:Int, f:Float, g:Int) -> '$a $b $c $d $e $f $g'); + // A compiled function value given more arguments than it takes throws, so this + // one is for script closures only, which ignore the rest + HostCalls.extraArguments((x:Int) -> x + 1); + } +} diff --git a/test/regression/CppiaHostClosureCalls/build.hxml b/test/regression/CppiaHostClosureCalls/build.hxml new file mode 100644 index 000000000..850bcd4ce --- /dev/null +++ b/test/regression/CppiaHostClosureCalls/build.hxml @@ -0,0 +1,9 @@ +--main Main +-cpp bin +-D scriptable +--dce no +-D dll_export=bin/host_classes.info +--next +--main Script +-cppia bin/script.cppia +-D dll_import=bin/host_classes.info diff --git a/test/regression/CppiaHostClosureCalls/stdout.txt b/test/regression/CppiaHostClosureCalls/stdout.txt new file mode 100644 index 000000000..7a94f24bd --- /dev/null +++ b/test/regression/CppiaHostClosureCalls/stdout.txt @@ -0,0 +1,158 @@ +-- compiled +ints 10 268 272 387 1045 1047 684 1054 34 +ints negated 0 -255 -256 -70000 1 2 70000 -2147483647 -2147483648 +ints bound 0 255 511 70511 70510 70508 508 -2147483141 507 +ints static 0 510 512 140000 -2 -4 -140000 -2 0 +floats 0 3 6 -4 510 512 2e+300 -2e-300 +floats 1/f(-0.0) -Infinity, NaN true, from an Int 14 +bools false true if false +dynamics 5 Int, 300 Int, 2 Int, 1.5 Float, -0 Int, true Bool, false Bool, s String, null null +nullables 5 none +strings 1:a 2:null +defaults 37 34 +mixed 1 2.5 true s [1,2] other -1 -0 false null null null 300 4 true t 9 Int +five 51306 +six 3655 +float32 1 1.25 +arrays 1033 +objects 53 +voids 1001 +results as types true 4.5 s2 +results Bool false Bool +results Float 3 Int +results whole Float 6 Int +results String s7 String +results Dynamic 3 Int +results Dynamic 4.5 Float +any Int 6 70001 3 1 2 +any Float 2.5 35000 1.35 -0 0.5 +any Bool yes yes yes no yes +any String 5! 70000! 2.7! -0! true! +any Dynamic 5 Int 70000 Int 2.7 Float -0 Int true Bool +any Null 5 70000 2.7 -0 true +throws caught boom 1 +null function caught Null Function Pointer +twice 9 +many 400088890 +number types to Int 201 -99 -29999 60001 66 +number types to Float 2.5 +number types to Dynamic 1.25 Float, 200 Int, -100 Int, 60000 Int, -1294967296 Int, 5 Int, 65 Int +number pairs 1 -0.5 Float 2 255 Int 3 7 Int +strings alone a! null! b String null null +field calls 35 2:0.5 42 3:-0 7 0:1 +typed results 21 3 true q! +typed results of an Int 21 false 21 21 Int +typed results of a Float 9 false -0 4 Int +typed results of a Bool 0 1 true false Bool +typed results of a String null! String 0 +typed results of a Dynamic 4 4.5 4.5 +void got 40 +void got 2 +typed results with 42 and 45 and 1 2.5 true s 5 -0 7 arguments +typed results of a null function caught Null Function Pointer +-- script, JIT off +ints 10 268 272 387 1045 1047 684 1054 34 +ints negated 0 -255 -256 -70000 1 2 70000 -2147483647 -2147483648 +ints bound 0 255 511 70511 70510 70508 508 -2147483141 507 +ints static 0 510 512 140000 -2 -4 -140000 -2 0 +floats 0 3 6 -4 510 512 2e+300 -2e-300 +floats 1/f(-0.0) -Infinity, NaN true, from an Int 14 +bools false true if false +dynamics 5 Int, 300 Int, 2 Int, 1.5 Float, -0 Int, true Bool, false Bool, s String, null null +nullables 5 none +strings 1:a 2:null +defaults 37 34 +mixed 1 2.5 true s [1,2] other -1 -0 false null null null 300 4 true t 9 Int +five 51306 +six 3655 +float32 1 1.25 +arrays 1033 +objects 53 +voids 1001 +results as types true 4.5 s2 +results Bool false Bool +results Float 3 Int +results whole Float 6 Int +results String s7 String +results Dynamic 3 Int +results Dynamic 4.5 Float +any Int 6 70001 3 1 2 +any Float 2.5 35000 1.35 -0 0.5 +any Bool yes yes yes no yes +any String 5! 70000! 2.7! -0! true! +any Dynamic 5 Int 70000 Int 2.7 Float -0 Int true Bool +any Null 5 70000 2.7 -0 true +throws caught boom 1 +null function caught Null Function Pointer +twice 9 +many 400088890 +number types to Int 201 -99 -29999 60001 66 +number types to Float 2.5 +number types to Dynamic 1.25 Float, 200 Int, -100 Int, 60000 Int, -1294967296 Int, 5 Int, 65 Int +number pairs 1 -0.5 Float 2 255 Int 3 7 Int +strings alone a! null! b String null null +field calls 35 2:0.5 42 3:-0 7 0:1 +typed results 21 3 true q! +typed results of an Int 21 false 21 21 Int +typed results of a Float 9 false -0 4 Int +typed results of a Bool 0 1 true false Bool +typed results of a String null! String 0 +typed results of a Dynamic 4 4.5 4.5 +void got 40 +void got 2 +typed results with 42 and 45 and 1 2.5 true s 5 -0 7 arguments +typed results of a null function caught Null Function Pointer +extra arguments 2 4 +-- script, JIT on +ints 10 268 272 387 1045 1047 684 1054 34 +ints negated 0 -255 -256 -70000 1 2 70000 -2147483647 -2147483648 +ints bound 0 255 511 70511 70510 70508 508 -2147483141 507 +ints static 0 510 512 140000 -2 -4 -140000 -2 0 +floats 0 3 6 -4 510 512 2e+300 -2e-300 +floats 1/f(-0.0) -Infinity, NaN true, from an Int 14 +bools false true if false +dynamics 5 Int, 300 Int, 2 Int, 1.5 Float, -0 Int, true Bool, false Bool, s String, null null +nullables 5 none +strings 1:a 2:null +defaults 37 34 +mixed 1 2.5 true s [1,2] other -1 -0 false null null null 300 4 true t 9 Int +five 51306 +six 3655 +float32 1 1.25 +arrays 1033 +objects 53 +voids 1001 +results as types true 4.5 s2 +results Bool false Bool +results Float 3 Int +results whole Float 6 Int +results String s7 String +results Dynamic 3 Int +results Dynamic 4.5 Float +any Int 6 70001 3 1 2 +any Float 2.5 35000 1.35 -0 0.5 +any Bool yes yes yes no yes +any String 5! 70000! 2.7! -0! true! +any Dynamic 5 Int 70000 Int 2.7 Float -0 Int true Bool +any Null 5 70000 2.7 -0 true +throws caught boom 1 +null function caught Null Function Pointer +twice 9 +many 400088890 +number types to Int 201 -99 -29999 60001 66 +number types to Float 2.5 +number types to Dynamic 1.25 Float, 200 Int, -100 Int, 60000 Int, -1294967296 Int, 5 Int, 65 Int +number pairs 1 -0.5 Float 2 255 Int 3 7 Int +strings alone a! null! b String null null +field calls 35 2:0.5 42 3:-0 7 0:1 +typed results 21 3 true q! +typed results of an Int 21 false 21 21 Int +typed results of a Float 9 false -0 4 Int +typed results of a Bool 0 1 true false Bool +typed results of a String null! String 0 +typed results of a Dynamic 4 4.5 4.5 +void got 40 +void got 2 +typed results with 42 and 45 and 1 2.5 true s 5 -0 7 arguments +typed results of a null function caught Null Function Pointer +extra arguments 2 4 diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 72186db7d..06d9ab72d 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -20,6 +20,7 @@ CppiaAdoptLayouts: compares the cppia JIT, which Emscripten has not CppiaArrayAccess: its host is the first --next section, which -D emscripten does not reach CppiaBreakpoints: threads CppiaHostArgs: processes +CppiaHostClosureCalls: its host is the first --next section, which -D emscripten does not reach CppiaHostFunctionOrder: its host is the first --next section, which -D emscripten does not reach CppiaHostMismatch: its host is the first --next section, which -D emscripten does not reach, and it checks jitted code, and Emscripten has no cppia JIT CppiaJitBuiltins: threads diff --git a/toolchain/haxe-target.xml b/toolchain/haxe-target.xml index e8d0310a4..125ce5d6a 100644 --- a/toolchain/haxe-target.xml +++ b/toolchain/haxe-target.xml @@ -72,6 +72,7 @@ + From 2b76f399647100313bd1ef362ac46613f26d636a Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 00:20:09 -0500 Subject: [PATCH 12/23] Add a cppia workload that sorts a script's Ints with its comparator host_sort: Array.sort, which is host code, sorts a copy of a 1000-element Array 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. --- bench/cppia/Script.hx | 27 +++++++++++++++++++++++++++ bench/cppia/shared/CppiaWorkloads.hx | 1 + 2 files changed, 28 insertions(+) diff --git a/bench/cppia/Script.hx b/bench/cppia/Script.hx index e900c2e9b..d3769194d 100644 --- a/bench/cppia/Script.hx +++ b/bench/cppia/Script.hx @@ -14,6 +14,7 @@ class Script { case "bunny_update": new BunnyUpdate(); case "openfl_frame": new OpenflFrame(); case "call_by_name": new CallByName(); + case "host_sort": new HostSort(); default: throw 'Unknown CPPIA workload ${CppiaBridge.name}'; }; } @@ -334,3 +335,29 @@ class CallByName implements CppiaWorkload { return sum; } } + +// Array.sort, which is host code, sorting a script's Ints with a comparator the +// script gives it, as a game sorts its own values by a key +class HostSort implements CppiaWorkload { + final values:Array; + + public function new() { + var seed = 1; + values = [ + for (i in 0...1000) { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + seed % 100000; + } + ]; + } + + public function run():Int { + var sum = 0; + for (r in 0...10) { + var sorted = values.copy(); + sorted.sort(function(a:Int, b:Int):Int return a - b); + sum = (sum * 31 + sorted[r * 97]) | 0; + } + return sum; + } +} diff --git a/bench/cppia/shared/CppiaWorkloads.hx b/bench/cppia/shared/CppiaWorkloads.hx index 7fe76fea7..7def373a1 100644 --- a/bench/cppia/shared/CppiaWorkloads.hx +++ b/bench/cppia/shared/CppiaWorkloads.hx @@ -18,5 +18,6 @@ class CppiaWorkloads { {name: "bunny_update", unit: "bunny updates", ops: 20000, reps: 10}, {name: "openfl_frame", unit: "object frames", ops: 10000, reps: 5}, {name: "call_by_name", unit: "calls", ops: 400000, reps: 5}, + {name: "host_sort", unit: "sorted elements", ops: 10000, reps: 5}, ]; } From 818b6e9f2a65b79554982dbd1fed7bf478450c1b Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 00:20:29 -0500 Subject: [PATCH 13/23] Sort with a script comparator without boxing the values 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 --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. --- Changes.md | 1 + include/Array.h | 92 +++++++++ include/hx/TypedCall.h | 20 ++ src/Dynamic.cpp | 1 + src/hx/cppia/CppiaFunction.cpp | 18 ++ .../CppiaHostSortComparators/Main.hx | 180 ++++++++++++++++++ .../CppiaHostSortComparators/Script.hx | 163 ++++++++++++++++ .../CppiaHostSortComparators/build.hxml | 7 + .../CppiaHostSortComparators/stdout.txt | 51 +++++ 9 files changed, 533 insertions(+) create mode 100644 test/regression/CppiaHostSortComparators/Main.hx create mode 100644 test/regression/CppiaHostSortComparators/Script.hx create mode 100644 test/regression/CppiaHostSortComparators/build.hxml create mode 100644 test/regression/CppiaHostSortComparators/stdout.txt diff --git a/Changes.md b/Changes.md index c2eb325b0..b7ec4cd09 100644 --- a/Changes.md +++ b/Changes.md @@ -13,6 +13,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed the cppia interpreter reading an argument's slot in place in the script frame when it fills in the argument's default value, and writing a Float or Dynamic default the same way: a frame keeps 4-byte alignment, so on 64-bit an argument after an Int, as b in f(a:Int, ?b:String = "x"), sits at an odd multiple of 4, which is undefined behaviour, reported by UBSan, and a fault on a CPU that requires alignment. The slots are copied in and out now, as the interpreter's other frame accesses have been since 6.0.0. The JIT, which compiles defaults into the function, was not affected * Fixed Semaphore.tryAcquire(-1) waiting for ever where any other negative timeout returns at once, so a timeout worked out in whole seconds as deadline - now could wait with no limit once the deadline had passed. It was kept for Haxe 5.0.0-preview.1's Lock.wait() (libhxcpp #461), but preview.1's Lock waits through the runtime's own lock, which still takes a negative timeout as no limit, as Haxe 4's does. Only Haxe 5 nightlies from March to November 2026, which libhxcpp does not support, passed -1 to the semaphore; later ones call acquire() for no timeout. Every negative timeout returns at once now, as with stock hxcpp on Linux and macOS (HaxeFoundation/haxe#13114) * Host code calling a cppia script closure, in a scriptable build, passes Int, Float, Bool and String arguments as they are, interpreted and under the JIT. Haxe 4 makes a function value a Dynamic, so a call such as callback(i) boxed each argument into a Dynamic for __run, which the closure unboxed into its frame. Dynamic::operator(), and the Variant a field of an anonymous structure or a Dynamic is read as, now take those arguments as their own types and call hx::callFunction, a typed call in the new hx/TypedCall.h (HXCPP_TYPED_CALLS), which runs a script closure whose function takes exactly those types through its compiled code, as jitted code calling a closure directly runs it. Any other function value, and any argument a closure takes as another type, is boxed as __run had it, so every closure gets the same values, and calls with only objects keep the old overloads. The host calling back a closure that takes and returns an Int is 1.5x faster under the JIT and 1.1x interpreted (native_callback), 0.30x of HashLink 1.16's JIT where it was 0.20x. The result is still boxed, since generated code uses it as a Dynamic, and is now about a third of such a call. No class changes its layout: code compiled against the older headers, such as a prebuilt static library, keeps calling through __run until it is rebuilt +* Array.sort of Ints, Floats, Bools and the other plain values calls a cppia script comparator that takes two values of the element type with the values as they are, interpreted and under the JIT, in a scriptable build. Sort boxed each value once and called the comparator with the boxes, which the script unboxed again for every comparison. It now sorts the values themselves through hx::callFunction, in the same steps, so the comparator is asked about the same pairs in the same order and the array ends in the same order, whatever it answers, and an Int result is read as it is. Sorting with a script comparator is 2.0x faster under the JIT and 1.3x interpreted (host_sort), 0.43x of HashLink 1.16's JIT where it was 0.22x. A comparator that takes other types, a host function as the comparator, and arrays of objects, Strings and Int64s sort as before libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/include/Array.h b/include/Array.h index 19509b97e..8ac408be7 100644 --- a/include/Array.h +++ b/include/Array.h @@ -1109,6 +1109,27 @@ class Array_obj : public hx::ArrayBase void sort(SorterFunc inSorter); void sortValues(ELEM_ *ioData, int inFrom, int inTo, ELEM_ *ioBuffer, Array &ioBoxed, int *ioIndex, SorterFunc inSorter); +#if (HXCPP_API_LEVEL<500) && defined(HXCPP_SCRIPTABLE) + // A comparator that is a script closure whose function takes two values of + // the element type, called with them as they are (hx/TypedCall.h). One + // that returns an Int has it read as it is, which is what __ToInt gives of + // its box + struct TypedSorter + { + Dynamic mFunc; + bool mIntResult; + + TypedSorter(const Dynamic &inFunc, bool inIntResult) : mFunc(inFunc), mIntResult(inIntResult) { } + bool operator()(const ELEM_ &inA, const ELEM_ &inB) + { + if (mIntResult) + return hx::callFunction(mFunc, inA, inB) < 0; + return hx::callFunction< ::Dynamic>(mFunc, inA, inB)->__ToInt() < 0; + } + }; + void sortTypedValues(ELEM_ *ioData, int inFrom, int inTo, ELEM_ *ioBuffer, TypedSorter &inLess); +#endif + Dynamic iterator() { return new hx::ArrayIterator(this); } Dynamic keyValueIterator() { return new hx::ArrayKeyValueIterator(this); } @@ -1448,6 +1469,55 @@ void Array_obj::sortValues(ELEM_ *ioData, int inFrom, int inTo, ELEM_ *io } +#if (HXCPP_API_LEVEL<500) && defined(HXCPP_SCRIPTABLE) +// As sortValues, with a comparator that takes the values themselves: the same +// sort and the same merges, so the comparator is asked about the same pairs in +// the same order and the values end in the same order, whatever it answers. +// Only the boxes are gone, and the index that sorting through them needed +template +void Array_obj::sortTypedValues(ELEM_ *ioData, int inFrom, int inTo, ELEM_ *ioBuffer, TypedSorter &inLess) +{ + const int n = inTo-inFrom; + if (n<=SORT_BOX_RUN) + { + hx::StableSort(ioData+inFrom, n, inLess); + return; + } + + int mid = inFrom + (n>>1); + sortTypedValues(ioData, inFrom, mid, ioBuffer, inLess); + sortTypedValues(ioData, mid, inTo, ioBuffer, inLess); + + if (!inLess(ioData[mid], ioData[mid-1])) + return; + + int leftLength = mid-inFrom; + for(int i=0;i void Array_obj::sort(SorterFunc inSorter) { @@ -1467,6 +1537,28 @@ void Array_obj::sort(SorterFunc inSorter) const int n = length; if (n<2) return; + +#if (HXCPP_API_LEVEL<500) && defined(HXCPP_SCRIPTABLE) + // A script comparator that takes the values as they are is called with + // them, through the typed path, instead of with boxes of them + if ((int)hx::TypedCallArgOf::kind!=(int)hx::typedCallObject) + { + int resultKind = hx::scriptClosureResultKind(inSorter); + if (resultKind>=0) + { + std::unique_ptr data(new ELEM_[n]); + ::memcpy(data.get(), mBase, n*sizeof(ELEM_)); + std::unique_ptr buffer(n>SORT_BOX_RUN ? new ELEM_[n/2] : nullptr); + TypedSorter sorter(inSorter, resultKind==hx::typedCallInt); + sortTypedValues(data.get(), 0, n, buffer.get(), sorter); + if (length!=n) + return; + ::memcpy(mBase, data.get(), n*sizeof(ELEM_)); + return; + } + } +#endif + const int run = n data(new ELEM_[n]); ::memcpy(data.get(), mBase, n*sizeof(ELEM_)); diff --git a/include/hx/TypedCall.h b/include/hx/TypedCall.h index 31647aa62..afa9bcd84 100644 --- a/include/hx/TypedCall.h +++ b/include/hx/TypedCall.h @@ -196,6 +196,10 @@ enum { typedCallMaxArgs = 8 }; typedef void (*ScriptClosureTypedCall)(hx::Object *inClosure, int inMatch, int inKinds, const TypedCallArg *inArgs, void *outResult); extern HXCPP_EXTERN_CLASS_ATTRIBUTES void *gScriptClosureVTable; extern HXCPP_EXTERN_CLASS_ATTRIBUTES ScriptClosureTypedCall gScriptClosureTypedCall; +// The TypedCallKind of the result a script closure's function gives, when it takes +// exactly the arguments of the match code inMatch, or -1 +typedef int (*ScriptClosureTypedResult)(hx::Object *inClosure, int inMatch); +extern HXCPP_EXTERN_CLASS_ATTRIBUTES ScriptClosureTypedResult gScriptClosureTypedResult; #if (HXCPP_API_LEVEL<500) @@ -296,6 +300,22 @@ inline TResult callFunction(const ::Dynamic &inFunction, TArgs &&... inArgs) return TypedCaller::call(function, std::forward(inArgs)...); } +// The kind of result, a TypedCallKind, that inFunction gives when it is a script +// closure whose function takes exactly arguments of the types TArgs, which +// hx::callFunction then passes without boxing any; -1 for any other function value. +// For code that would box arguments once to make many calls, such as Array.sort +template +inline int scriptClosureResultKind(const ::Dynamic &inFunction) +{ + static_assert(sizeof...(TArgs)<=typedCallMaxArgs, "a typed call takes the script path with at most typedCallMaxArgs arguments"); + #ifdef HXCPP_SCRIPTABLE + hx::Object *function = inFunction.mPtr; + if (function && *(void **)function==gScriptClosureVTable) + return gScriptClosureTypedResult(function, TypedCallSignature::type...>::match); + #endif + return -1; +} + #endif } diff --git a/src/Dynamic.cpp b/src/Dynamic.cpp index 20a71ce4f..6f90ae3e3 100644 --- a/src/Dynamic.cpp +++ b/src/Dynamic.cpp @@ -31,6 +31,7 @@ hx::Class __ObjcClass; // script closure; see hx/TypedCall.h void *gScriptClosureVTable = 0; ScriptClosureTypedCall gScriptClosureTypedCall = 0; +ScriptClosureTypedResult gScriptClosureTypedResult = 0; hx::Class &GetBoolClass() { return __BoolClass; } diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index e7e7a1c8c..dce53ea3e 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -1226,6 +1226,23 @@ class CppiaClosure : public hx::Object closure->writeTypedResult(ctx, resultKind, outResult); } + // For hx::scriptClosureResultKind: what the function returns, when it takes + // exactly the arguments of inMatch + static int typedResult(hx::Object *inClosure, int inMatch) + { + ScriptCallable *function = ((CppiaClosure *)inClosure)->function; + if (function->typedCallMatch!=inMatch) + return -1; + switch(function->returnType) + { + case etInt: return function->isBoolReturn ? hx::typedCallBool : hx::typedCallInt; + case etFloat: return hx::typedCallFloat; + case etString: return hx::typedCallString; + case etObject: return hx::typedCallObject; + default: return hx::typedCallVoid; + } + } + Dynamic __Run(const Array &inArgs) HXCPP_OVERRIDE { CppiaCtx *ctx = CppiaCtx::getCurrent(); @@ -1349,6 +1366,7 @@ static struct PublishScriptClosure CppiaClosure probe; hx::gScriptClosureVTable = *(void **)&probe; hx::gScriptClosureTypedCall = CppiaClosure::typedCall; + hx::gScriptClosureTypedResult = CppiaClosure::typedResult; } } sPublishScriptClosure; diff --git a/test/regression/CppiaHostSortComparators/Main.hx b/test/regression/CppiaHostSortComparators/Main.hx new file mode 100644 index 000000000..573176dcc --- /dev/null +++ b/test/regression/CppiaHostSortComparators/Main.hx @@ -0,0 +1,180 @@ +// Array.sort calls a comparator that is a script closure taking two values of +// the element type with the values as they are, through the typed calls of +// hx/TypedCall.h, instead of with boxes of them. It sorts the same way either +// way, so the comparator is asked about the same pairs in the same order, even +// one that answers at random, throws, or changes the array. +// The same cases run with compiled comparators, which keep the boxes, then as a +// script with the JIT off and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +class Compiled { + static var seed = 1; + static var calls = 0; + + static function next():Int { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed; + } + + static function ints(n:Int, range:Int):Array { + return [for (i in 0...n) next() % range - (range >> 1)]; + } + + // A checksum of the order, so a long array prints as one number + static function digest(a:Array):Int { + var h = 17; + for (v in a) + h = (h * 31 + v) & 0xffffff; + return h; + } + + static function intCompare(a:Int, b:Int):Int { + calls++; + return a - b; + } + + public static function run() { + seed = 1; + var a = ints(20, 1000); + calls = 0; + a.sort(intCompare); + Sys.println('ints $a in $calls calls'); + + // The pairs asked about, in order + var b = [5, 3, 9, 1, 7, 3]; + var asked = []; + b.sort(function(x:Int, y:Int):Int { + asked.push('$x:$y'); + return x - y; + }); + Sys.println('pairs $b asked ${asked.join(" ")}'); + + // Equal keys keep their order + var c = [0x305, 0x101, 0x302, 0x104, 0x201, 0x303, 0x102]; + c.sort((x:Int, y:Int) -> (x >> 8) - (y >> 8)); + Sys.println('stable ${[for (v in c) StringTools.hex(v)]}'); + + // Longer than one run of the merge + var d = ints(40000, 1 << 30); + calls = 0; + d.sort(intCompare); + var ordered = true; + for (i in 1...d.length) + if (d[i - 1] > d[i]) + ordered = false; + Sys.println('long ordered $ordered digest ${digest(d)} in $calls calls'); + + // Answers at random: the order is whatever they make it, and the same every time + var e = ints(40000, 1000); + var answers = 7; + e.sort(function(x:Int, y:Int):Int { + answers = (answers * 1103515245 + 12345) & 0x7fffffff; + return (answers >> 16) % 3 - 1; + }); + Sys.println('random digest ${digest(e)} length ${e.length}'); + + // Collections while it sorts + var f = ints(30000, 100000); + var count = 0; + f.sort(function(x:Int, y:Int):Int { + if (++count % 20000 == 0) + cpp.vm.Gc.run(true); + return y - x; + }); + Sys.println('collected digest ${digest(f)} first ${f[0]} last ${f[f.length - 1]}'); + + var g = [2.5, -0.0, 0.0, -1.5, 1e300, -1e-300, 3.0]; + g.sort((x:Float, y:Float) -> x < y ? -1 : x > y ? 1 : 0); + Sys.println('floats $g 1/g[2] ${1 / g[2]} 1/g[3] ${1 / g[3]}'); + + var h = [true, false, true, true, false]; + h.sort((x:Bool, y:Bool) -> (x ? 1 : 0) - (y ? 1 : 0)); + Sys.println('bools $h'); + + var u:Array = [200, 3, 255, 0, 17]; + u.sort((x:cpp.UInt8, y:cpp.UInt8) -> x - y); + Sys.println('uint8 $u'); + + var s:Array = [1.5, -2.25, 0.125, 8]; + s.sort((x:cpp.Float32, y:cpp.Float32) -> x < y ? 1 : x > y ? -1 : 0); + Sys.println('float32 $s'); + + // Comparators that do not take the values as they are, which keep the boxes + var i = [4, 1, 3, 2]; + i.sort((x:Dynamic, y:Dynamic) -> Std.int(x - y)); + var j = [4, 1, 3, 2]; + var byFloat:Dynamic = (x:Float, y:Float) -> Std.int(y - x); + j.sort(byFloat); + Sys.println('dynamic $i float $j'); + + // Results that are not an Int come back through their box + var k = [3, 1, 2, 5, 4]; + var half:Dynamic = (x:Int, y:Int) -> (x - y) * 0.75; + k.sort(half); + var l = [3, 1, 2]; + var yes:Dynamic = (x:Int, y:Int) -> x > y; + l.sort(yes); + Sys.println('float results $k bool results $l'); + + // Bound methods and static functions + var m = [9, 2, 7]; + m.sort(new CompiledOrder(-1).compare); + var n = [9, 2, 7]; + n.sort(intCompare); + Sys.println('bound $m static $n'); + + // A comparator that throws leaves the array as it was + var o = [5, 4, 3, 2, 1]; + var left = 3; + try { + o.sort(function(x:Int, y:Int):Int { + if (--left == 0) + throw "stop"; + return x - y; + }); + } catch (e:Dynamic) { + Sys.println('throws $e $o'); + } + + // One that changes the length leaves the array as it left it + var p = [3, 2, 1]; + var once = true; + p.sort(function(x:Int, y:Int):Int { + if (once) { + once = false; + p.push(99); + } + return x - y; + }); + Sys.println('grown $p'); + + // A host function as the comparator + var q = [3, 1, 2]; + q.sort(Reflect.compare); + Sys.println('host $q'); + } +} + +class CompiledOrder { + var sign:Int; + + public function new(sign:Int) + this.sign = sign; + + public function compare(x:Int, y:Int):Int + return sign * (x - y); +} diff --git a/test/regression/CppiaHostSortComparators/Script.hx b/test/regression/CppiaHostSortComparators/Script.hx new file mode 100644 index 000000000..50333d9c2 --- /dev/null +++ b/test/regression/CppiaHostSortComparators/Script.hx @@ -0,0 +1,163 @@ +class Script { + static function main() { + ScriptCases.run(); + } +} + +class ScriptCases { + static var seed = 1; + static var calls = 0; + + static function next():Int { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed; + } + + static function ints(n:Int, range:Int):Array { + return [for (i in 0...n) next() % range - (range >> 1)]; + } + + // A checksum of the order, so a long array prints as one number + static function digest(a:Array):Int { + var h = 17; + for (v in a) + h = (h * 31 + v) & 0xffffff; + return h; + } + + static function intCompare(a:Int, b:Int):Int { + calls++; + return a - b; + } + + public static function run() { + seed = 1; + var a = ints(20, 1000); + calls = 0; + a.sort(intCompare); + Sys.println('ints $a in $calls calls'); + + // The pairs asked about, in order + var b = [5, 3, 9, 1, 7, 3]; + var asked = []; + b.sort(function(x:Int, y:Int):Int { + asked.push('$x:$y'); + return x - y; + }); + Sys.println('pairs $b asked ${asked.join(" ")}'); + + // Equal keys keep their order + var c = [0x305, 0x101, 0x302, 0x104, 0x201, 0x303, 0x102]; + c.sort((x:Int, y:Int) -> (x >> 8) - (y >> 8)); + Sys.println('stable ${[for (v in c) StringTools.hex(v)]}'); + + // Longer than one run of the merge + var d = ints(40000, 1 << 30); + calls = 0; + d.sort(intCompare); + var ordered = true; + for (i in 1...d.length) + if (d[i - 1] > d[i]) + ordered = false; + Sys.println('long ordered $ordered digest ${digest(d)} in $calls calls'); + + // Answers at random: the order is whatever they make it, and the same every time + var e = ints(40000, 1000); + var answers = 7; + e.sort(function(x:Int, y:Int):Int { + answers = (answers * 1103515245 + 12345) & 0x7fffffff; + return (answers >> 16) % 3 - 1; + }); + Sys.println('random digest ${digest(e)} length ${e.length}'); + + // Collections while it sorts + var f = ints(30000, 100000); + var count = 0; + f.sort(function(x:Int, y:Int):Int { + if (++count % 20000 == 0) + cpp.vm.Gc.run(true); + return y - x; + }); + Sys.println('collected digest ${digest(f)} first ${f[0]} last ${f[f.length - 1]}'); + + var g = [2.5, -0.0, 0.0, -1.5, 1e300, -1e-300, 3.0]; + g.sort((x:Float, y:Float) -> x < y ? -1 : x > y ? 1 : 0); + Sys.println('floats $g 1/g[2] ${1 / g[2]} 1/g[3] ${1 / g[3]}'); + + var h = [true, false, true, true, false]; + h.sort((x:Bool, y:Bool) -> (x ? 1 : 0) - (y ? 1 : 0)); + Sys.println('bools $h'); + + var u:Array = [200, 3, 255, 0, 17]; + u.sort((x:cpp.UInt8, y:cpp.UInt8) -> x - y); + Sys.println('uint8 $u'); + + var s:Array = [1.5, -2.25, 0.125, 8]; + s.sort((x:cpp.Float32, y:cpp.Float32) -> x < y ? 1 : x > y ? -1 : 0); + Sys.println('float32 $s'); + + // Comparators that do not take the values as they are, which keep the boxes + var i = [4, 1, 3, 2]; + i.sort((x:Dynamic, y:Dynamic) -> Std.int(x - y)); + var j = [4, 1, 3, 2]; + var byFloat:Dynamic = (x:Float, y:Float) -> Std.int(y - x); + j.sort(byFloat); + Sys.println('dynamic $i float $j'); + + // Results that are not an Int come back through their box + var k = [3, 1, 2, 5, 4]; + var half:Dynamic = (x:Int, y:Int) -> (x - y) * 0.75; + k.sort(half); + var l = [3, 1, 2]; + var yes:Dynamic = (x:Int, y:Int) -> x > y; + l.sort(yes); + Sys.println('float results $k bool results $l'); + + // Bound methods and static functions + var m = [9, 2, 7]; + m.sort(new ScriptCasesOrder(-1).compare); + var n = [9, 2, 7]; + n.sort(intCompare); + Sys.println('bound $m static $n'); + + // A comparator that throws leaves the array as it was + var o = [5, 4, 3, 2, 1]; + var left = 3; + try { + o.sort(function(x:Int, y:Int):Int { + if (--left == 0) + throw "stop"; + return x - y; + }); + } catch (e:Dynamic) { + Sys.println('throws $e $o'); + } + + // One that changes the length leaves the array as it left it + var p = [3, 2, 1]; + var once = true; + p.sort(function(x:Int, y:Int):Int { + if (once) { + once = false; + p.push(99); + } + return x - y; + }); + Sys.println('grown $p'); + + // A host function as the comparator + var q = [3, 1, 2]; + q.sort(Reflect.compare); + Sys.println('host $q'); + } +} + +class ScriptCasesOrder { + var sign:Int; + + public function new(sign:Int) + this.sign = sign; + + public function compare(x:Int, y:Int):Int + return sign * (x - y); +} diff --git a/test/regression/CppiaHostSortComparators/build.hxml b/test/regression/CppiaHostSortComparators/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaHostSortComparators/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaHostSortComparators/stdout.txt b/test/regression/CppiaHostSortComparators/stdout.txt new file mode 100644 index 000000000..67d5d0bde --- /dev/null +++ b/test/regression/CppiaHostSortComparators/stdout.txt @@ -0,0 +1,51 @@ +-- compiled +ints [-471,-448,-416,-315,-212,-192,-179,-134,-26,19,75,90,281,321,347,351,366,386,399,452] in 64 calls +pairs [1,3,3,5,7,9] asked 3:5 9:5 1:5 1:3 7:5 7:9 3:5 3:3 +stable [101,104,102,201,305,302,303] +long ordered true digest 6198907 in 568208 calls +random digest 10240199 length 40000 +collected digest 5403687 first 49998 last -49994 +floats [-1.5,-1e-300,-0,0,2.5,3,1e+300] 1/g[2] -Infinity 1/g[3] Infinity +bools [false,false,true,true,true] +uint8 [0,3,17,200,255] +float32 [8,1.5,0.125,-2.25] +dynamic [1,2,3,4] float [4,3,2,1] +float results [1,3,2,5,4] bool results [3,1,2] +bound [9,7,2] static [2,7,9] +throws stop [5,4,3,2,1] +grown [3,2,1,99] +host [1,2,3] +-- script, JIT off +ints [-471,-448,-416,-315,-212,-192,-179,-134,-26,19,75,90,281,321,347,351,366,386,399,452] in 64 calls +pairs [1,3,3,5,7,9] asked 3:5 9:5 1:5 1:3 7:5 7:9 3:5 3:3 +stable [101,104,102,201,305,302,303] +long ordered true digest 6198907 in 568208 calls +random digest 10240199 length 40000 +collected digest 5403687 first 49998 last -49994 +floats [-1.5,-1e-300,-0,0,2.5,3,1e+300] 1/g[2] -Infinity 1/g[3] Infinity +bools [false,false,true,true,true] +uint8 [0,3,17,200,255] +float32 [8,1.5,0.125,-2.25] +dynamic [1,2,3,4] float [4,3,2,1] +float results [1,3,2,5,4] bool results [3,1,2] +bound [9,7,2] static [2,7,9] +throws stop [5,4,3,2,1] +grown [3,2,1,99] +host [1,2,3] +-- script, JIT on +ints [-471,-448,-416,-315,-212,-192,-179,-134,-26,19,75,90,281,321,347,351,366,386,399,452] in 64 calls +pairs [1,3,3,5,7,9] asked 3:5 9:5 1:5 1:3 7:5 7:9 3:5 3:3 +stable [101,104,102,201,305,302,303] +long ordered true digest 6198907 in 568208 calls +random digest 10240199 length 40000 +collected digest 5403687 first 49998 last -49994 +floats [-1.5,-1e-300,-0,0,2.5,3,1e+300] 1/g[2] -Infinity 1/g[3] Infinity +bools [false,false,true,true,true] +uint8 [0,3,17,200,255] +float32 [8,1.5,0.125,-2.25] +dynamic [1,2,3,4] float [4,3,2,1] +float results [1,3,2,5,4] bool results [3,1,2] +bound [9,7,2] static [2,7,9] +throws stop [5,4,3,2,1] +grown [3,2,1,99] +host [1,2,3] From 7f2efddd746600cc7790caa73bc415948b02080e Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 18:55:05 -0500 Subject: [PATCH 14/23] Copy a cppia closure's captures from a list its function keeps 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 818b6e9f, 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 --- Changes.md | 1 + src/hx/cppia/Cppia.h | 11 ++ src/hx/cppia/CppiaFunction.cpp | 46 ++++-- .../CppiaClosureCaptures/HostRunner.hx | 26 +++ test/regression/CppiaClosureCaptures/Main.hx | 148 ++++++++++++++++++ .../regression/CppiaClosureCaptures/Script.hx | 125 +++++++++++++++ .../CppiaClosureCaptures/build.hxml | 9 ++ .../CppiaClosureCaptures/stdout.txt | 39 +++++ test/regression/emscripten-skip.txt | 1 + 9 files changed, 392 insertions(+), 14 deletions(-) create mode 100644 test/regression/CppiaClosureCaptures/HostRunner.hx create mode 100644 test/regression/CppiaClosureCaptures/Main.hx create mode 100644 test/regression/CppiaClosureCaptures/Script.hx create mode 100644 test/regression/CppiaClosureCaptures/build.hxml create mode 100644 test/regression/CppiaClosureCaptures/stdout.txt diff --git a/Changes.md b/Changes.md index b7ec4cd09..1eaa95a86 100644 --- a/Changes.md +++ b/Changes.md @@ -14,6 +14,7 @@ libhxcpp 6.0.3 (unreleased) * Fixed Semaphore.tryAcquire(-1) waiting for ever where any other negative timeout returns at once, so a timeout worked out in whole seconds as deadline - now could wait with no limit once the deadline had passed. It was kept for Haxe 5.0.0-preview.1's Lock.wait() (libhxcpp #461), but preview.1's Lock waits through the runtime's own lock, which still takes a negative timeout as no limit, as Haxe 4's does. Only Haxe 5 nightlies from March to November 2026, which libhxcpp does not support, passed -1 to the semaphore; later ones call acquire() for no timeout. Every negative timeout returns at once now, as with stock hxcpp on Linux and macOS (HaxeFoundation/haxe#13114) * Host code calling a cppia script closure, in a scriptable build, passes Int, Float, Bool and String arguments as they are, interpreted and under the JIT. Haxe 4 makes a function value a Dynamic, so a call such as callback(i) boxed each argument into a Dynamic for __run, which the closure unboxed into its frame. Dynamic::operator(), and the Variant a field of an anonymous structure or a Dynamic is read as, now take those arguments as their own types and call hx::callFunction, a typed call in the new hx/TypedCall.h (HXCPP_TYPED_CALLS), which runs a script closure whose function takes exactly those types through its compiled code, as jitted code calling a closure directly runs it. Any other function value, and any argument a closure takes as another type, is boxed as __run had it, so every closure gets the same values, and calls with only objects keep the old overloads. The host calling back a closure that takes and returns an Int is 1.5x faster under the JIT and 1.1x interpreted (native_callback), 0.30x of HashLink 1.16's JIT where it was 0.20x. The result is still boxed, since generated code uses it as a Dynamic, and is now about a third of such a call. No class changes its layout: code compiled against the older headers, such as a prebuilt static library, keeps calling through __run until it is rebuilt * Array.sort of Ints, Floats, Bools and the other plain values calls a cppia script comparator that takes two values of the element type with the values as they are, interpreted and under the JIT, in a scriptable build. Sort boxed each value once and called the comparator with the boxes, which the script unboxed again for every comparison. It now sorts the values themselves through hx::callFunction, in the same steps, so the comparator is asked about the same pairs in the same order and the array ends in the same order, whatever it answers, and an Int result is read as it is. Sorting with a script comparator is 2.0x faster under the JIT and 1.3x interpreted (host_sort), 0.43x of HashLink 1.16's JIT where it was 0.22x. A comparator that takes other types, a host function as the comparator, and arrays of objects, Strings and Int64s sort as before +* A cppia closure copies the variables it captures into the frame of each call, and out of the frame that makes it, from a list its function keeps of where each one sits and how big it is, set when the function links, with a move of that size. For each capture it went from the closure to its function, to the function's captured variables, to the variable for its offsets and size, and then called memcpy. Jitted code calling a closure that captures a variable is 13% faster (closure_call), 0.65x of HashLink 1.16's JIT where it was 0.57x, and the host calling one back 5% (native_callback). Interpreted calls are level libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 67b135337..c37ad648e 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -327,6 +327,17 @@ struct ScriptCallable : public CppiaDynamicExpr std::vector captureVars; int captureSize; + // Where each captured variable is, set at link from captureVars, which a + // closure copies by: made, from fromStackPos in the frame making it to + // capturePos in itself, and run, from there to stackPos in its frame + struct CaptureCopy + { + int stackPos; + int capturePos; + int fromStackPos; + int size; + }; + std::vector captureCopies; // What jitted code calling a closure of this function compares, interned by // internCallSignature: the arguments' types, and those with the return type. diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index dce53ea3e..1bb6330b5 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -225,6 +225,13 @@ CppiaExpr *ScriptCallable::link(CppiaModule &inModule) captureVars.swap(layout.captureVars); captureSize = layout.captureSize; + captureCopies.clear(); + for(int i=0;istackPos, var->capturePos, var->fromStackPos, sTypeSize[var->expressionType] }; + captureCopies.push_back(copy); + } #ifdef HXCPP_STACK_SCRIPTABLE std::swap(varMap,layout.varMap); @@ -930,6 +937,20 @@ void CppiaFunction::markLazy() // without a dynamic_cast: every CppiaClosure has the vtable in hx::gScriptClosureVTable, // which is set before main, below +// One captured variable, of a size sTypeSize gives. Captures and frame slots can +// sit at any multiple of 4, so it copies bytes, but by a size the compiler knows +// where it can, which takes a move or two instead of a call +static inline void copyCaptured(unsigned char *outTo, const unsigned char *inFrom, int inSize) +{ + switch(inSize) + { + case 4: memcpy(outTo, inFrom, 4); return; + case 8: memcpy(outTo, inFrom, 8); return; + case 16: memcpy(outTo, inFrom, 16); return; + default: memcpy(outTo, inFrom, inSize); + } +} + class CppiaClosure : public hx::Object { public: @@ -947,12 +968,11 @@ class CppiaClosure : public hx::Object *(hx::Object **)base = ctx->getThis(false); - for(int i=0;icaptureVars.size();i++) - { - CppiaStackVar *var = function->captureVars[i]; - int size = sTypeSize[var->expressionType]; - memcpy( base+var->capturePos, ctx->frame + var->fromStackPos, size ); - } + const unsigned char *frame = ctx->frame; + const ScriptCallable::CaptureCopy *copy = function->captureCopies.data(); + const ScriptCallable::CaptureCopy *end = copy + function->captureCopies.size(); + for(; copycapturePos, frame + copy->fromStackPos, copy->size); } hx::Object **getThis() const @@ -975,15 +995,13 @@ class CppiaClosure : public hx::Object // Writes this and the captured variables into the frame at inFrame void enterFrame(unsigned char *inFrame) { - unsigned char *base = ((unsigned char *)this) + sizeof(CppiaClosure); - CppiaCtx::setSlot(inFrame, *(hx::Object **)base); + const unsigned char *base = ((unsigned char *)this) + sizeof(CppiaClosure); + CppiaCtx::setSlot(inFrame, *(hx::Object * const *)base); - for(int i=0;icaptureVars.size();i++) - { - CppiaStackVar *var = function->captureVars[i]; - int size = sTypeSize[var->expressionType]; - memcpy( inFrame+var->stackPos, base + var->capturePos, size); - } + const ScriptCallable::CaptureCopy *copy = function->captureCopies.data(); + const ScriptCallable::CaptureCopy *end = copy + function->captureCopies.size(); + for(; copystackPos, base + copy->capturePos, copy->size); } // Runs the function in the frame at ctx->frame, which holds a slot for this and diff --git a/test/regression/CppiaClosureCaptures/HostRunner.hx b/test/regression/CppiaClosureCaptures/HostRunner.hx new file mode 100644 index 000000000..eb94beb34 --- /dev/null +++ b/test/regression/CppiaClosureCaptures/HostRunner.hx @@ -0,0 +1,26 @@ +// Host code that calls the closures it is given, compiled into the host for the +// script to pass its closures to +class HostRunner { + public static function sum(count:Int, f:Int->Int):Int { + var total = 0; + for (i in 0...count) + total += f(i); + return total; + } + + public static function each(count:Int, f:Int->Void):Void { + for (i in 0...count) + f(i); + } + + public static function texts(count:Int, f:Int->String):String { + var out = []; + for (i in 0...count) + out.push(f(i)); + return out.join(", "); + } + + public static function floats(f:Float->Float):Float { + return f(1.5) + f(-2.25); + } +} diff --git a/test/regression/CppiaClosureCaptures/Main.hx b/test/regression/CppiaClosureCaptures/Main.hx new file mode 100644 index 000000000..a1dde81c0 --- /dev/null +++ b/test/regression/CppiaClosureCaptures/Main.hx @@ -0,0 +1,148 @@ +// A script closure copies the variables it captures out of the frame that makes +// it, and into the frame of each call of it, one by one, each at its own offset +// in the closure and in the frame. Every kind and size of capture, at offsets +// that differ between the two, written by the closure and by the code that made +// it, nested, made in a loop, of a method, and after a collection, called by the +// script directly, through a Dynamic, by reflection and from host code. +// The same closures run compiled into the host, then as a script with the JIT +// off and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same closures as Script.hx, compiled into the host +class CompiledPoint { + public var x:Int; + public var y:Float; + + public function new(x:Int, y:Float) { + this.x = x; + this.y = y; + } +} + +class CompiledHolder { + public var base = 100; + public var name = "holder"; + + public function new() {} + + // A closure made in a method captures this with the method's own variables + public function maker(step:Int):Int->String { + var scale = 2.5; + return function(k:Int):String { + var before = k + step; + base += step; + return '$name $before $base ${k * scale}'; + }; + } +} + +class Compiled { + // A capture of each kind, each first read after variables of the closure's + // own, so it sits at another offset in the frame than in the closure + static function kinds(i:Int, f:Float, b:Bool, s:String, a:Array, d:Dynamic, p:CompiledPoint, l:haxe.Int64, g:cpp.Float32):Int->String { + return function(k:Int):String { + var first = k * 3; + var text = s + k; + var second = f * k; + var flag = b && k % 2 == 0; + var item = a[k % a.length]; + var third = i + k; + return '$first $text $second $flag $item $third $d ${p.x} ${p.y} ${l + k} ${g * k}'; + }; + } + + // Twelve captures with Ints between the wider ones, so most of them sit at odd + // multiples of 4 + static function many(n:Int):Int->Int { + var a = n, b = n * 1.5, c = n + 1, d = "d" + n, e = n + 2, f = [n, n + 1]; + var g = n + 3, h = n * 0.25, i = n + 4, j:Dynamic = n + 5, k = n + 6, m = new CompiledPoint(n, n * 2.0); + return function(x:Int):Int { + var local = x * 7; + return local + a + Std.int(b) + c + d.length + e + f[1] + g + Std.int(h * 4) + i + (j : Int) + k + m.x + Std.int(m.y); + }; + } + + public static function run() { + var point = new CompiledPoint(7, 0.5); + var ofKinds = kinds(3, 1.25, true, "s", [10, 20, 30], "dyn", point, haxe.Int64.make(1, 2), 0.75); + Sys.println('kinds direct ${ofKinds(0)} | ${ofKinds(5)}'); + var asDynamic:Dynamic = ofKinds; + Sys.println('kinds through a dynamic ${asDynamic(4)}'); + Sys.println('kinds by reflection ${Reflect.callMethod(null, ofKinds, [2])}'); + Sys.println('kinds from the host ${HostRunner.texts(3, ofKinds)}'); + + var wide = many(10); + var total = 0; + for (x in 0...100) + total += wide(x); + Sys.println('many direct $total, from the host ${HostRunner.sum(100, wide)}'); + + // Captures the closure writes, and the code that made it after it + var count = 0; + var log = ""; + var weight = 0.5; + var bump = function(x:Int):Int { + count += x; + log += x; + weight *= 2; + return count; + }; + for (x in 0...4) + bump(x); + count += 100; + Sys.println('written ${bump(1)} $count $log $weight, from the host ${HostRunner.sum(3, bump)} $count $log $weight'); + + // A closure with no captures, and one returning Void from the host + var sink = 0; + var step = 3; + HostRunner.each(5, function(x:Int):Void sink += x * step); + Sys.println('void from the host $sink, none captured ${HostRunner.sum(4, x -> x * 2)}'); + var scale = 0.5; + Sys.println('floats from the host ${HostRunner.floats(x -> x * scale + step)}'); + + // A closure made inside a closure, capturing from both + var outer = 5; + var nest = function(a:Int):Int->Int { + var mid = a * 10; + return function(b:Int):Int return outer + mid + a + b; + }; + var inner = nest(2); + Sys.println('nested ${inner(1)} ${HostRunner.sum(4, inner)} ${nest(3)(4)}'); + + // Closures made in a loop, each with its own captures + var made = [ + for (k in 0...6) { + var label = "c" + k; + var half = k * 0.5; + (x:Int) -> '$label:${x * k}:${half * x}'; + } + ]; + Sys.println('made in a loop ${[for (m in made) m(3)].join(" ")}, from the host ${HostRunner.texts(2, made[4])}'); + + // A closure of a method + var holder = new CompiledHolder(); + var fromMethod = holder.maker(3); + Sys.println('method ${fromMethod(1)}, from the host ${HostRunner.texts(2, fromMethod)}, base ${holder.base}'); + + // Captures still right after a collection + var kept = [for (k in 0...2000) many(k)]; + cpp.vm.Gc.run(true); + var check = 0; + for (k in 0...kept.length) + check += kept[k](k); + Sys.println('after a collection $check'); + } +} diff --git a/test/regression/CppiaClosureCaptures/Script.hx b/test/regression/CppiaClosureCaptures/Script.hx new file mode 100644 index 000000000..7f0e2fe83 --- /dev/null +++ b/test/regression/CppiaClosureCaptures/Script.hx @@ -0,0 +1,125 @@ +// The same cases as Compiled in Main.hx, run as a script +class Point { + public var x:Int; + public var y:Float; + + public function new(x:Int, y:Float) { + this.x = x; + this.y = y; + } +} + +class Holder { + public var base = 100; + public var name = "holder"; + + public function new() {} + + // A closure made in a method captures this with the method's own variables + public function maker(step:Int):Int->String { + var scale = 2.5; + return function(k:Int):String { + var before = k + step; + base += step; + return '$name $before $base ${k * scale}'; + }; + } +} + +class Script { + // A capture of each kind, each first read after variables of the closure's + // own, so it sits at another offset in the frame than in the closure + static function kinds(i:Int, f:Float, b:Bool, s:String, a:Array, d:Dynamic, p:Point, l:haxe.Int64, g:cpp.Float32):Int->String { + return function(k:Int):String { + var first = k * 3; + var text = s + k; + var second = f * k; + var flag = b && k % 2 == 0; + var item = a[k % a.length]; + var third = i + k; + return '$first $text $second $flag $item $third $d ${p.x} ${p.y} ${l + k} ${g * k}'; + }; + } + + // Twelve captures with Ints between the wider ones, so most of them sit at odd + // multiples of 4 + static function many(n:Int):Int->Int { + var a = n, b = n * 1.5, c = n + 1, d = "d" + n, e = n + 2, f = [n, n + 1]; + var g = n + 3, h = n * 0.25, i = n + 4, j:Dynamic = n + 5, k = n + 6, m = new Point(n, n * 2.0); + return function(x:Int):Int { + var local = x * 7; + return local + a + Std.int(b) + c + d.length + e + f[1] + g + Std.int(h * 4) + i + (j : Int) + k + m.x + Std.int(m.y); + }; + } + + static function main() { + var point = new Point(7, 0.5); + var ofKinds = kinds(3, 1.25, true, "s", [10, 20, 30], "dyn", point, haxe.Int64.make(1, 2), 0.75); + Sys.println('kinds direct ${ofKinds(0)} | ${ofKinds(5)}'); + var asDynamic:Dynamic = ofKinds; + Sys.println('kinds through a dynamic ${asDynamic(4)}'); + Sys.println('kinds by reflection ${Reflect.callMethod(null, ofKinds, [2])}'); + Sys.println('kinds from the host ${HostRunner.texts(3, ofKinds)}'); + + var wide = many(10); + var total = 0; + for (x in 0...100) + total += wide(x); + Sys.println('many direct $total, from the host ${HostRunner.sum(100, wide)}'); + + // Captures the closure writes, and the code that made it after it + var count = 0; + var log = ""; + var weight = 0.5; + var bump = function(x:Int):Int { + count += x; + log += x; + weight *= 2; + return count; + }; + for (x in 0...4) + bump(x); + count += 100; + Sys.println('written ${bump(1)} $count $log $weight, from the host ${HostRunner.sum(3, bump)} $count $log $weight'); + + // A closure with no captures, and one returning Void from the host + var sink = 0; + var step = 3; + HostRunner.each(5, function(x:Int):Void sink += x * step); + Sys.println('void from the host $sink, none captured ${HostRunner.sum(4, x -> x * 2)}'); + var scale = 0.5; + Sys.println('floats from the host ${HostRunner.floats(x -> x * scale + step)}'); + + // A closure made inside a closure, capturing from both + var outer = 5; + var nest = function(a:Int):Int->Int { + var mid = a * 10; + return function(b:Int):Int return outer + mid + a + b; + }; + var inner = nest(2); + Sys.println('nested ${inner(1)} ${HostRunner.sum(4, inner)} ${nest(3)(4)}'); + + // Closures made in a loop, each with its own captures + var made = [ + for (k in 0...6) { + var label = "c" + k; + var half = k * 0.5; + (x:Int) -> '$label:${x * k}:${half * x}'; + } + ]; + Sys.println('made in a loop ${[for (m in made) m(3)].join(" ")}, from the host ${HostRunner.texts(2, made[4])}'); + + // A closure of a method + var holder = new Holder(); + var fromMethod = holder.maker(3); + Sys.println('method ${fromMethod(1)}, from the host ${HostRunner.texts(2, fromMethod)}, base ${holder.base}'); + + // Captures still right after a collection + var kept = [for (k in 0...2000) many(k)]; + cpp.vm.Gc.run(true); + var check = 0; + for (k in 0...kept.length) + check += kept[k](k); + Sys.println('after a collection $check'); + } +} diff --git a/test/regression/CppiaClosureCaptures/build.hxml b/test/regression/CppiaClosureCaptures/build.hxml new file mode 100644 index 000000000..850bcd4ce --- /dev/null +++ b/test/regression/CppiaClosureCaptures/build.hxml @@ -0,0 +1,9 @@ +--main Main +-cpp bin +-D scriptable +--dce no +-D dll_export=bin/host_classes.info +--next +--main Script +-cppia bin/script.cppia +-D dll_import=bin/host_classes.info diff --git a/test/regression/CppiaClosureCaptures/stdout.txt b/test/regression/CppiaClosureCaptures/stdout.txt new file mode 100644 index 000000000..4e3ebf7bb --- /dev/null +++ b/test/regression/CppiaClosureCaptures/stdout.txt @@ -0,0 +1,39 @@ +-- compiled +kinds direct 0 s0 0 true 10 3 dyn 7 0.5 4294967298 0 | 15 s5 6.25 false 30 8 dyn 7 0.5 4294967303 3.75 +kinds through a dynamic 12 s4 5 true 20 7 dyn 7 0.5 4294967302 3 +kinds by reflection 6 s2 2.5 true 30 5 dyn 7 0.5 4294967300 1.5 +kinds from the host 0 s0 0 true 10 3 dyn 7 0.5 4294967298 0, 3 s1 1.25 false 20 4 dyn 7 0.5 4294967299 0.75, 6 s2 2.5 true 30 5 dyn 7 0.5 4294967300 1.5 +many direct 50650, from the host 50650 +written 107 107 01231 16, from the host 325 110 01231012 128 +void from the host 30, none captured 12 +floats from the host 5.625 +nested 28 114 42 +made in a loop c0:0:0 c1:3:1.5 c2:6:3 c3:9:4.5 c4:12:6 c5:15:7.5, from the host c4:0:0, c4:4:2 +method holder 4 103 2.5, from the host holder 3 106 0, holder 4 109 2.5, base 109 +after a collection 41031890 +-- script, JIT off +kinds direct 0 s0 0 true 10 3 dyn 7 0.5 4294967298 0 | 15 s5 6.25 false 30 8 dyn 7 0.5 4294967303 3.75 +kinds through a dynamic 12 s4 5 true 20 7 dyn 7 0.5 4294967302 3 +kinds by reflection 6 s2 2.5 true 30 5 dyn 7 0.5 4294967300 1.5 +kinds from the host 0 s0 0 true 10 3 dyn 7 0.5 4294967298 0, 3 s1 1.25 false 20 4 dyn 7 0.5 4294967299 0.75, 6 s2 2.5 true 30 5 dyn 7 0.5 4294967300 1.5 +many direct 50650, from the host 50650 +written 107 107 01231 16, from the host 325 110 01231012 128 +void from the host 30, none captured 12 +floats from the host 5.625 +nested 28 114 42 +made in a loop c0:0:0 c1:3:1.5 c2:6:3 c3:9:4.5 c4:12:6 c5:15:7.5, from the host c4:0:0, c4:4:2 +method holder 4 103 2.5, from the host holder 3 106 0, holder 4 109 2.5, base 109 +after a collection 41031890 +-- script, JIT on +kinds direct 0 s0 0 true 10 3 dyn 7 0.5 4294967298 0 | 15 s5 6.25 false 30 8 dyn 7 0.5 4294967303 3.75 +kinds through a dynamic 12 s4 5 true 20 7 dyn 7 0.5 4294967302 3 +kinds by reflection 6 s2 2.5 true 30 5 dyn 7 0.5 4294967300 1.5 +kinds from the host 0 s0 0 true 10 3 dyn 7 0.5 4294967298 0, 3 s1 1.25 false 20 4 dyn 7 0.5 4294967299 0.75, 6 s2 2.5 true 30 5 dyn 7 0.5 4294967300 1.5 +many direct 50650, from the host 50650 +written 107 107 01231 16, from the host 325 110 01231012 128 +void from the host 30, none captured 12 +floats from the host 5.625 +nested 28 114 42 +made in a loop c0:0:0 c1:3:1.5 c2:6:3 c3:9:4.5 c4:12:6 c5:15:7.5, from the host c4:0:0, c4:4:2 +method holder 4 103 2.5, from the host holder 3 106 0, holder 4 109 2.5, base 109 +after a collection 41031890 diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 06d9ab72d..61f0e4f35 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -19,6 +19,7 @@ CppiaAdoptInstances: threads (std::thread, which needs a pthreads build) CppiaAdoptLayouts: compares the cppia JIT, which Emscripten has not CppiaArrayAccess: its host is the first --next section, which -D emscripten does not reach CppiaBreakpoints: threads +CppiaClosureCaptures: its host is the first --next section, which -D emscripten does not reach CppiaHostArgs: processes CppiaHostClosureCalls: its host is the first --next section, which -D emscripten does not reach CppiaHostFunctionOrder: its host is the first --next section, which -D emscripten does not reach From b7e7e20422aba57534e05209cb9cbb0ed8325725 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 19:04:34 -0500 Subject: [PATCH 15/23] Keep the host's typed call into a compiled cppia closure in line 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 7f2efddd, 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 --- Changes.md | 1 + src/hx/cppia/CppiaFunction.cpp | 99 ++++++++++++++++++++++------------ 2 files changed, 66 insertions(+), 34 deletions(-) diff --git a/Changes.md b/Changes.md index 1eaa95a86..0b8e47378 100644 --- a/Changes.md +++ b/Changes.md @@ -15,6 +15,7 @@ libhxcpp 6.0.3 (unreleased) * Host code calling a cppia script closure, in a scriptable build, passes Int, Float, Bool and String arguments as they are, interpreted and under the JIT. Haxe 4 makes a function value a Dynamic, so a call such as callback(i) boxed each argument into a Dynamic for __run, which the closure unboxed into its frame. Dynamic::operator(), and the Variant a field of an anonymous structure or a Dynamic is read as, now take those arguments as their own types and call hx::callFunction, a typed call in the new hx/TypedCall.h (HXCPP_TYPED_CALLS), which runs a script closure whose function takes exactly those types through its compiled code, as jitted code calling a closure directly runs it. Any other function value, and any argument a closure takes as another type, is boxed as __run had it, so every closure gets the same values, and calls with only objects keep the old overloads. The host calling back a closure that takes and returns an Int is 1.5x faster under the JIT and 1.1x interpreted (native_callback), 0.30x of HashLink 1.16's JIT where it was 0.20x. The result is still boxed, since generated code uses it as a Dynamic, and is now about a third of such a call. No class changes its layout: code compiled against the older headers, such as a prebuilt static library, keeps calling through __run until it is rebuilt * Array.sort of Ints, Floats, Bools and the other plain values calls a cppia script comparator that takes two values of the element type with the values as they are, interpreted and under the JIT, in a scriptable build. Sort boxed each value once and called the comparator with the boxes, which the script unboxed again for every comparison. It now sorts the values themselves through hx::callFunction, in the same steps, so the comparator is asked about the same pairs in the same order and the array ends in the same order, whatever it answers, and an Int result is read as it is. Sorting with a script comparator is 2.0x faster under the JIT and 1.3x interpreted (host_sort), 0.43x of HashLink 1.16's JIT where it was 0.22x. A comparator that takes other types, a host function as the comparator, and arrays of objects, Strings and Int64s sort as before * A cppia closure copies the variables it captures into the frame of each call, and out of the frame that makes it, from a list its function keeps of where each one sits and how big it is, set when the function links, with a move of that size. For each capture it went from the closure to its function, to the function's captured variables, to the variable for its offsets and size, and then called memcpy. Jitted code calling a closure that captures a variable is 13% faster (closure_call), 0.65x of HashLink 1.16's JIT where it was 0.57x, and the host calling one back 5% (native_callback). Interpreted calls are level +* Host code calling a compiled cppia closure back through hx::callFunction, as Dynamic::operator() and Array.sort do in a scriptable build, takes a path that does only what that call needs: the arguments pushed, the captured variables copied and the result written in line, and the compiled code called. It shared one function with the general path, and called out to copy the captures, to write the result and to box it. Under the JIT, the host calling back a closure that takes and returns an Int is 15% faster (native_callback), 0.34x of HashLink 1.16's JIT, and sorting with a script comparator 10% (host_sort). Interpreted calls are level libhxcpp 6.0.2 ------------------------------------------------------------ diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index 1bb6330b5..2376488e3 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -937,6 +937,19 @@ void CppiaFunction::markLazy() // without a dynamic_cast: every CppiaClosure has the vtable in hx::gScriptClosureVTable, // which is set before main, below +// What the typed call from host code keeps out of line, or puts in line, so the +// path a callback takes stays short +#if defined(_MSC_VER) + #define CPPIA_INLINE __forceinline + #define CPPIA_NOINLINE __declspec(noinline) +#elif defined(__GNUC__) || defined(__clang__) + #define CPPIA_INLINE inline __attribute__((always_inline)) + #define CPPIA_NOINLINE __attribute__((noinline)) +#else + #define CPPIA_INLINE inline + #define CPPIA_NOINLINE +#endif + // One captured variable, of a size sTypeSize gives. Captures and frame slots can // sit at any multiple of 4, so it copies bytes, but by a size the compiler knows // where it can, which takes a move or two instead of a call @@ -993,7 +1006,7 @@ class CppiaClosure : public hx::Object // Writes this and the captured variables into the frame at inFrame - void enterFrame(unsigned char *inFrame) + CPPIA_INLINE void enterFrame(unsigned char *inFrame) { const unsigned char *base = ((unsigned char *)this) + sizeof(CppiaClosure); CppiaCtx::setSlot(inFrame, *(hx::Object * const *)base); @@ -1042,7 +1055,7 @@ class CppiaClosure : public hx::Object } // The result runInFrame left, boxed - static hx::Object *boxResult(CppiaCtx *ctx, ScriptCallable *inFunction) + static CPPIA_INLINE hx::Object *boxResult(CppiaCtx *ctx, ScriptCallable *inFunction) { switch(inFunction->returnType) { @@ -1153,7 +1166,7 @@ class CppiaClosure : public hx::Object // The result of a typed call, which wants inKind: as the function left it where // that is the kind wanted, and otherwise boxed as __run returns it and converted // as hx::callFunction converts that - void writeTypedResult(CppiaCtx *ctx, int inKind, void *outResult) + CPPIA_INLINE void writeTypedResult(CppiaCtx *ctx, int inKind, void *outResult) { ExprType type = function->returnType; switch(inKind) @@ -1193,55 +1206,73 @@ class CppiaClosure : public hx::Object // A call from host code through hx::callFunction (hx/TypedCall.h). When the // function takes exactly these arguments and is compiled, it runs as jitted code // calling a closure directly runs it: the arguments into a new frame as they are, - // the captured variables after them, and its code called. Otherwise each argument - // goes in as pushTypedArg has it, and the function runs as __run runs it + // the captured variables after them, and its code called. That is all this does, + // with the captures copied and the result written in line, since a host calls + // back this way once for every event or element; anything else goes to + // typedCallGeneral static void typedCall(hx::Object *inClosure, int inMatch, int inKinds, const hx::TypedCallArg *inArgs, void *outResult) { CppiaClosure *closure = (CppiaClosure *)inClosure; - ScriptCallable *function = closure->function; - CppiaCtx *ctx = CppiaCtx::getCurrent(); - AutoStack aut(ctx); - int count = inKinds & 15; - int resultKind = (inKinds>>28) & 7; #ifdef CPPIA_JIT + ScriptCallable *function = closure->function; CppiaFunc code; - unsigned char *frame = ctx->pointer; - if (function->typedCallMatch==inMatch && (code = function->getCompiled())!=0 && - frame + function->stackSize <= ctx->stackEnd) + if (function->typedCallMatch==inMatch && (code = function->getCompiled())!=0) { - ctx->push( (hx::Object *)0 ); - for(int a=0; apointer; + if (frame + function->stackSize <= ctx->stackEnd) { - const hx::TypedCallArg &arg = inArgs[a]; - switch( (inKinds>>(4+3*a)) & 7 ) + AutoStack aut(ctx); + // The slot for this, which enterFrame fills + ctx->pointer += sizeof(hx::Object *); + int count = inKinds & 15; + for(int a=0; apushInt(arg.intValue); break; - case hx::typedCallBool: ctx->pushInt(arg.boolValue); break; - case hx::typedCallFloat: ctx->pushFloat(arg.floatValue); break; - case hx::typedCallString: ctx->pushString(*arg.stringValue); break; - default: ctx->pushObject(arg.objectValue); + const hx::TypedCallArg &arg = inArgs[a]; + switch( (inKinds>>(4+3*a)) & 7 ) + { + case hx::typedCallInt: ctx->pushInt(arg.intValue); break; + case hx::typedCallBool: ctx->pushInt(arg.boolValue); break; + case hx::typedCallFloat: ctx->pushFloat(arg.floatValue); break; + case hx::typedCallString: ctx->pushString(*arg.stringValue); break; + default: ctx->pushObject(arg.objectValue); + } } + closure->enterFrame(frame); + code(ctx); + ctx->frame = frame; + if (ctx->exception) + throwPending(ctx); + closure->writeTypedResult(ctx, (inKinds>>28) & 7, outResult); + return; } - closure->enterFrame(frame); - code(ctx); - ctx->frame = frame; - if (ctx->exception) - { - Dynamic caught = fromPendingException(ctx->exception); - ctx->exception = nullptr; - HX_STACK_DO_THROW(caught); - } - closure->writeTypedResult(ctx, resultKind, outResult); - return; } #endif + typedCallGeneral(closure, inKinds, inArgs, outResult); + } + + // Any other typed call: each argument goes in as pushTypedArg has it, and the + // function runs as __run runs it + static CPPIA_NOINLINE void typedCallGeneral(CppiaClosure *closure, int inKinds, const hx::TypedCallArg *inArgs, void *outResult) + { + CppiaCtx *ctx = CppiaCtx::getCurrent(); + AutoStack aut(ctx); + int count = inKinds & 15; ctx->pointer += sizeof(hx::Object *); for(int a=0; apushTypedArg(ctx, a, (inKinds>>(4+3*a)) & 7, inArgs[a]); closure->runInFrame(ctx, count, true); - closure->writeTypedResult(ctx, resultKind, outResult); + closure->writeTypedResult(ctx, (inKinds>>28) & 7, outResult); + } + + // Throws what compiled code left in ctx->exception + static CPPIA_NOINLINE void throwPending(CppiaCtx *ctx) + { + Dynamic caught = fromPendingException(ctx->exception); + ctx->exception = nullptr; + HX_STACK_DO_THROW(caught); } // For hx::scriptClosureResultKind: what the function returns, when it takes From 695a02ddec387ee369148997f5c54e39a24dcbe7 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 19:49:05 -0500 Subject: [PATCH 16/23] Call host instance methods from jitted cppia code through typed entries 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 fdd330c5 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 6862d3ed, 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 --- Changes.md | 1 + include/hx/Macros.h | 2 + include/hx/Macros.tpl | 2 + include/hx/Scriptable.h | 223 ++++++++++++++++++ include/hxcpp.h | 5 + src/hx/cppia/Cppia.cpp | 98 +++++++- src/hx/cppia/Cppia.h | 5 + src/hx/cppia/CppiaCompiler.cpp | 16 ++ src/hx/cppia/CppiaCompiler.h | 4 + src/hx/cppia/HaxeNative.cpp | 43 ++++ .../CppiaHostMethodEntries/HostCalc.hx | 85 +++++++ .../CppiaHostMethodEntries/HostCalcChild.hx | 15 ++ .../regression/CppiaHostMethodEntries/Main.hx | 151 ++++++++++++ .../CppiaHostMethodEntries/Script.hx | 125 ++++++++++ .../CppiaHostMethodEntries/build.hxml | 10 + .../CppiaHostMethodEntries/stdout.txt | 39 +++ test/regression/emscripten-skip.txt | 1 + 17 files changed, 823 insertions(+), 2 deletions(-) create mode 100644 test/regression/CppiaHostMethodEntries/HostCalc.hx create mode 100644 test/regression/CppiaHostMethodEntries/HostCalcChild.hx create mode 100644 test/regression/CppiaHostMethodEntries/Main.hx create mode 100644 test/regression/CppiaHostMethodEntries/Script.hx create mode 100644 test/regression/CppiaHostMethodEntries/build.hxml create mode 100644 test/regression/CppiaHostMethodEntries/stdout.txt diff --git a/Changes.md b/Changes.md index 1bedd8dc8..5ed37ce8b 100644 --- a/Changes.md +++ b/Changes.md @@ -12,6 +12,7 @@ libhxcpp 6.1.0 (unreleased) * Array.sort of Ints, Floats, Bools and the other plain values calls a cppia script comparator that takes two values of the element type with the values as they are, interpreted and under the JIT, in a scriptable build. Sort boxed each value once and called the comparator with the boxes, which the script unboxed again for every comparison. It now sorts the values themselves through hx::callFunction, in the same steps, so the comparator is asked about the same pairs in the same order and the array ends in the same order, whatever it answers, and an Int result is read as it is. Sorting with a script comparator is 2.0x faster under the JIT and 1.3x interpreted (host_sort), 0.43x of HashLink 1.16's JIT where it was 0.22x. A comparator that takes other types, a host function as the comparator, and arrays of objects, Strings and Int64s sort as before * A cppia closure copies the variables it captures into the frame of each call, and out of the frame that makes it, from a list its function keeps of where each one sits and how big it is, set when the function links, with a move of that size. For each capture it went from the closure to its function, to the function's captured variables, to the variable for its offsets and size, and then called memcpy. Jitted code calling a closure that captures a variable is 13% faster (closure_call), 0.65x of HashLink 1.16's JIT where it was 0.57x, and the host calling one back 5% (native_callback). Interpreted calls are level * Host code calling a compiled cppia closure back through hx::callFunction, as Dynamic::operator() and Array.sort do in a scriptable build, takes a path that does only what that call needs: the arguments pushed, the captured variables copied and the result written in line, and the compiled code called. It shared one function with the general path, and called out to copy the captures, to write the result and to box it. Under the JIT, the host calling back a closure that takes and returns an Int is 15% faster (native_callback), 0.34x of HashLink 1.16's JIT, and sorting with a script comparator 10% (host_sort). Interpreted calls are level +* Jitted cppia code calls a host instance method that takes up to three Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the object and the arguments in registers, in a scriptable build. It went through the method's script stub, which took the arguments from the script frame and wrote the result back there, by way of a helper that catches what the stub throws. Each instance method's Dynamic wrapper (HX_DEFINE_DYNAMIC_FUNC) now makes two entries: one calling the method virtually, as the stub does, and one calling the class's own, as the stub for a super call does, which a C++ class with pure virtual methods does not get. A scriptable class gives the runtime its methods' entries as it registers, and an entry leaves what the method throws for the script, as the helper does. Updating script objects through a host display object's properties, as BunnyMark's loop does, is 1.56x faster under the JIT (bunny_update), 0.77x of HashLink 1.16's JIT where it was 0.5x, and an OpenFL-shaped frame 7% faster (openfl_frame). Interpreted calls, methods with a String or more than three arguments, and code built against older headers take the stub as before. A scriptable host is larger by about 1.4% for the entries libhxcpp 6.0.3 ------------------------------------------------------------ diff --git a/include/hx/Macros.h b/include/hx/Macros.h index 2832f8955..4adc47266 100644 --- a/include/hx/Macros.h +++ b/include/hx/Macros.h @@ -424,6 +424,7 @@ static ::Dynamic __##class##func( ::hx::Object *inObj) \ { \ ret reinterpret_cast(inObj)->func(); return ::Dynamic(); \ }; \ +HX_SCRIPT_METHOD_ENTRY(class,func) \ ::Dynamic class::func##_dyn() \ {\ return ::hx::CreateMemberFunction0(#func,this,__##class##func); \ @@ -435,6 +436,7 @@ static ::Dynamic __##class##func( ::hx::Object *inObj, dynamic_arg_list) \ { \ ret reinterpret_cast(inObj)->func(arg_list); return ::Dynamic(); \ }; \ +HX_SCRIPT_METHOD_ENTRY(class,func) \ ::Dynamic class::func##_dyn() \ {\ return ::hx::CreateMemberFunction##N(#func,this,__##class##func); \ diff --git a/include/hx/Macros.tpl b/include/hx/Macros.tpl index 791452be8..a74ce4132 100644 --- a/include/hx/Macros.tpl +++ b/include/hx/Macros.tpl @@ -17,6 +17,7 @@ static ::NS::Dynamic __##class##func(::hxNS::Object *inObj) \ { \ ret reinterpret_cast(inObj)->func(); return ::NS::Dynamic(); \ }; \ +HX_SCRIPT_METHOD_ENTRY(class,func) \ ::NS::Dynamic class::func##_dyn() \ {\ return ::hxNS::CreateMemberFunction0(#func,this,__##class##func); \ @@ -28,6 +29,7 @@ static ::NS::Dynamic __##class##func(::hxNS::Object *inObj, dynamic_arg_list) \ { \ ret reinterpret_cast(inObj)->func(arg_list); return ::NS::Dynamic(); \ }; \ +HX_SCRIPT_METHOD_ENTRY(class,func) \ ::NS::Dynamic class::func##_dyn() \ {\ return ::hxNS::CreateMemberFunction##N(#func,this,__##class##func); \ diff --git a/include/hx/Scriptable.h b/include/hx/Scriptable.h index 6c2f472ea..901939b0d 100644 --- a/include/hx/Scriptable.h +++ b/include/hx/Scriptable.h @@ -3,6 +3,8 @@ #include #include +#include +#include #include #ifdef __clang__ #pragma clang diagnostic ignored "-Winvalid-offsetof" @@ -131,6 +133,23 @@ enum SignatureChar }; +// The typed entries of a host instance method, which jitted script code calls +// with the object and the arguments in registers (HX_SCRIPT_METHOD_ENTRIES, below) +struct ScriptMethodEntry +{ + const char *name; + // The method's script signature, which a call's must equal + const char *signature; + void *virtualEntry; + // Null for a C++ class with pure virtual methods + void *superEntry; + ScriptMethodEntry *next; +}; +// Gives the runtime the entries of the methods of the scriptable class inName +HXCPP_EXTERN_CLASS_ATTRIBUTES +void ScriptableRegisterMethodEntries(String inName, ScriptMethodEntry *inEntries); + + // A typed entry for a static function a script calls by name: one of a class // the host gives no binding for, such as an abstract's implementation class. // STATIC_HX_DEFINE_DYNAMIC_FUNC registers one for each static function's @@ -308,6 +327,204 @@ struct __hx_stub_##class##func \ static bool __hx_script_stub = ::hx::RegisterScriptStaticStub( (void *)thunk, __hx_stub_##class##func::get(0) ); \ (void)__hx_script_stub; + +// Typed entries for a host instance method, which jitted script code calls with +// the object and the arguments in registers. The method's script stub takes them +// from the script frame and writes the result back there, and is reached through +// a helper that catches what it throws. HX_DEFINE_DYNAMIC_FUNC makes a pair for +// each 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, which a C++ +// class with pure virtual methods does not get. A scriptable class gives the +// runtime its methods' entries as it registers. An entry leaves what the method +// throws in the context, as the helper does for a stub +#define HX_SCRIPT_METHOD_ENTRIES 1 + +// What an entry leaves in the context when the method throws inValue, or inText +HXCPP_EXTERN_CLASS_ATTRIBUTES void ScriptEntryThrew(hx::Object *inValue); +HXCPP_EXTERN_CLASS_ATTRIBUTES void ScriptEntryThrewText(const char *inText); + +#define HX_SCRIPT_ENTRY_CATCH \ + catch(::Dynamic e) { ::hx::ScriptEntryThrew(e.mPtr); } \ + catch(const char *e) { ::hx::ScriptEntryThrewText(e); } \ + catch(const std::exception &e) { ::hx::ScriptEntryThrewText(e.what()); } + +// How an entry takes and gives a value of type T, as the stub converts one: sig +// is its script signature character, or 0 for a type an entry does not take +template struct ScriptEntryValue { enum { sig = 0 }; }; +template<> struct ScriptEntryValue { enum { sig = sigVoid }; typedef void Raw; }; +template<> struct ScriptEntryValue +{ + enum { sig = sigInt }; + typedef int Raw; + static inline int take(int inValue) { return inValue; } + static inline int give(int inValue) { return inValue; } +}; +template<> struct ScriptEntryValue +{ + enum { sig = sigBool }; + typedef int Raw; + static inline bool take(int inValue) { return inValue!=0; } + static inline int give(bool inValue) { return inValue ? 1 : 0; } +}; +template<> struct ScriptEntryValue +{ + enum { sig = sigFloat }; + typedef double Raw; + static inline double take(double inValue) { return inValue; } + static inline double give(double inValue) { return inValue; } +}; +template<> struct ScriptEntryValue +{ + enum { sig = sigFloat }; + typedef double Raw; + static inline float take(double inValue) { return (float)inValue; } + static inline double give(float inValue) { return inValue; } +}; +template<> struct ScriptEntryValue< ::Dynamic > +{ + enum { sig = sigObject }; + typedef hx::Object *Raw; + static inline ::Dynamic take(hx::Object *inValue) { return ::Dynamic(inValue); } + static inline hx::Object *give(const ::Dynamic &inValue) { return inValue.mPtr; } +}; +template struct ScriptEntryValue< ::hx::ObjectPtr > +{ + enum { sig = sigObject }; + typedef hx::Object *Raw; + static inline ::hx::ObjectPtr take(hx::Object *inValue) { ::hx::ObjectPtr result = ::Dynamic(inValue); return result; } + static inline hx::Object *give(const ::hx::ObjectPtr &inValue) { return ::Dynamic(inValue).mPtr; } +}; +template struct ScriptEntryValue< ::Array > +{ + enum { sig = sigObject }; + typedef hx::Object *Raw; + static inline ::Array take(hx::Object *inValue) + { + static void *exact = *(void **)( ::Array_obj::__new(0,0).mPtr ); + if (inValue && *(void **)inValue==exact) + return ::Array( (::Array_obj *)inValue ); + ::Dynamic value(inValue); + return value; + } + static inline hx::Object *give(const ::Array &inValue) { return ::Dynamic(inValue).mPtr; } +}; + +// The entries made for class C's methods, which HX_SCRIPTABLE_REGISTER_CLASS gives +// the runtime +template struct ScriptMethodEntries +{ + static ScriptMethodEntry *&head() { static ScriptMethodEntry *first = 0; return first; } +}; + +template struct ScriptMethodEntryAdd +{ + ScriptMethodEntry entry; + ScriptMethodEntryAdd(const ScriptMethodEntry &inEntry) : entry(inEntry) + { + if (entry.signature) + { + entry.next = ScriptMethodEntries::head(); + ScriptMethodEntries::head() = &entry; + } + } +}; + +template struct ScriptEntryKinds { enum { ok = 1 }; }; +template struct ScriptEntryKinds +{ + enum { ok = ((int)ScriptEntryValue::type>::sig!=0) && (int)ScriptEntryKinds::ok }; +}; + +// The entries for CALLER's method, whose type is F, on objects of class T. +// CALLER::call calls it virtually and CALLER::call calls T's own +template +struct ScriptMethodEntryCall +{ + typedef ScriptEntryValue::type> Result; + template + static typename Result::Raw CPPIA_CALL entry(hx::Object *inThis, typename ScriptEntryValue::type>::Raw... inArgs) + { + try + { + #ifdef HXCPP_CHECK_POINTER + if (!inThis) + NullReference("This", false); + #endif + return Result::give( CALLER::template call( static_cast(inThis), ScriptEntryValue::type>::take(inArgs)... ) ); + } + HX_SCRIPT_ENTRY_CATCH + return typename Result::Raw(); + } +}; +template +struct ScriptMethodEntryCall +{ + template + static void CPPIA_CALL entry(hx::Object *inThis, typename ScriptEntryValue::type>::Raw... inArgs) + { + try + { + #ifdef HXCPP_CHECK_POINTER + if (!inThis) + NullReference("This", false); + #endif + CALLER::template call( static_cast(inThis), ScriptEntryValue::type>::take(inArgs)... ); + } + HX_SCRIPT_ENTRY_CATCH + } +}; + +template +struct ScriptMethodEntryMake +{ + static ScriptMethodEntry get(const char *) { ScriptMethodEntry none = { 0, 0, 0, 0, 0 }; return none; } +}; +template +struct ScriptMethodEntryMake +{ + static ScriptMethodEntry get(const char *inName) + { + static const char sig[] = { (char)ScriptEntryValue::type>::sig, (char)ScriptEntryValue::type>::sig..., 0 }; + typedef ScriptMethodEntryCall::type, A...> Call; + ScriptMethodEntry entry = { inName, sig, (void *)&Call::template entry, superEntry(std::integral_constant()), 0 }; + return entry; + } + static void *superEntry(std::true_type) { return 0; } + static void *superEntry(std::false_type) + { + typedef ScriptMethodEntryCall::type, A...> Call; + return (void *)&Call::template entry; + } +}; + +template struct ScriptMethodEntryOf +{ + static ScriptMethodEntry get(const char *) { ScriptMethodEntry none = { 0, 0, 0, 0, 0 }; return none; } +}; +template +struct ScriptMethodEntryOf + : ScriptMethodEntryMake< (sizeof...(A)<=3) && (int)ScriptEntryKinds::ok, std::is_abstract::value, CALLER, T, R, A...> +{ +}; + +// Each instance method's Dynamic wrapper makes its entries here, at namespace +// scope. A name with overloads, as some hand-written classes have, has no one +// address to take, so it gets none and keeps its stub +#define HX_SCRIPT_METHOD_ENTRY(class,func) \ +namespace { struct __hx_entry_##class##func \ +{ \ + template static auto call(class *inObj, A &&... inArgs) -> typename std::enable_ifclass::func(std::forward(inArgs)...))>::type \ + { return inObj->class::func(std::forward(inArgs)...); } \ + template static auto call(class *inObj, A &&... inArgs) -> typename std::enable_iffunc(std::forward(inArgs)...))>::type \ + { return inObj->func(std::forward(inArgs)...); } \ + template static auto get(int) -> decltype(&T::func, ::hx::ScriptMethodEntry()) \ + { return ::hx::ScriptMethodEntryOf<__hx_entry_##class##func, T, decltype(&T::func)>::get(#func); } \ + template static ::hx::ScriptMethodEntry get(...) \ + { ::hx::ScriptMethodEntry none = { 0, 0, 0, 0, 0 }; return none; } \ +}; } \ +static ::hx::ScriptMethodEntryAdd __hx_entry_add_##class##func( __hx_entry_##class##func::get(0) ); + #endif @@ -419,8 +636,14 @@ int __scriptable_cppia_stack_size(); #define HX_SCRIPTABLE_REGISTER_INTERFACE(name,class) \ ::hx::ScriptableRegisterInterface( HX_CSTRING(name), __scriptableFunctions, & class##_scriptable ) +#ifdef HX_SCRIPT_METHOD_ENTRIES +#define HX_SCRIPTABLE_REGISTER_CLASS(name,class) \ + ::hx::ScriptableRegisterClass( HX_CSTRING(name), (int)offsetof(class##__scriptable,__scriptVTable) + sizeof(void *), __scriptableFunctions, class##__scriptable::__script_create, class##__scriptable::__script_construct ); \ + ::hx::ScriptableRegisterMethodEntries( HX_CSTRING(name), ::hx::ScriptMethodEntries::head() ) +#else #define HX_SCRIPTABLE_REGISTER_CLASS(name,class) \ ::hx::ScriptableRegisterClass( HX_CSTRING(name), (int)offsetof(class##__scriptable,__scriptVTable) + sizeof(void *), __scriptableFunctions, class##__scriptable::__script_create, class##__scriptable::__script_construct ) +#endif #ifdef HXCPP_VISIT_ALLOCS diff --git a/include/hxcpp.h b/include/hxcpp.h index 3eddfaff9..b2c1eb701 100755 --- a/include/hxcpp.h +++ b/include/hxcpp.h @@ -414,6 +414,11 @@ typedef PropertyAccessMode PropertyAccess; #define HX_SCRIPT_STATIC_STUB_PROBE(class,func) #define HX_SCRIPT_STATIC_STUB(class,func,thunk) #endif +// An instance method's Dynamic wrapper makes typed entries for jitted scripts +// only in a scriptable build with C++11 +#ifndef HX_SCRIPT_METHOD_ENTRY +#define HX_SCRIPT_METHOD_ENTRY(class,func) +#endif #endif diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 347c74855..cd31981cb 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -1900,6 +1900,11 @@ struct CallHaxe : public CppiaExpr // the method's slot in its script vtable, where a script override would be CppiaClassInfo *receiverClass; int hostSlot; + // The method's typed entries, which jitted code calls with the object and the + // arguments in registers: one calling it virtually, as the stub does, and one + // calling the host class's own, as the super stub does + void *virtualEntry; + void *superEntry; CallHaxe(CppiaExpr *inSrc,ScriptNamedFunction inFunction, CppiaExpr *inThis, Expressions &ioArgs, bool inIsStatic=false, bool inIsSuper = false, String inClassName = String() ) : CppiaExpr(inSrc) @@ -1912,6 +1917,21 @@ struct CallHaxe : public CppiaExpr className = inClassName; receiverClass = 0; hostSlot = -1; + virtualEntry = 0; + superEntry = 0; + } + + // The typed entries of the method, found on the host class inHostClass + void setEntries(HaxeNativeClass *inHostClass) + { + if (!inHostClass || isStatic || !function.name || !function.signature) + return; + const ScriptMethodEntry *entry = inHostClass->findMethodEntry(function.name, function.signature); + if (entry) + { + virtualEntry = entry->virtualEntry; + superEntry = entry->superEntry; + } } // A call of a host method on a script class whose host class is inHostClass @@ -2081,6 +2101,68 @@ struct CallHaxe : public CppiaExpr CATCH_NATIVE } + // Calls a typed entry with this and the arguments, which are in the frame at + // framePos, in the registers their kinds take, and leaves the result in the + // frame there, where a stub leaves one + void genEntryCall(CppiaCompiler *compiler, void *inEntry, int framePos) + { + const char *sig = function.signature; + int ints = 0; + int floats = 0; + int pos = framePos; + int argTypes = SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_P, 1); + compiler->move(JitReg(SLJIT_R(ints++),jtPointer), JitFramePos(pos).as(jtPointer)); + pos += sizeof(hx::Object *); + for(int a=1; sig[a]; a++) + { + switch(sig[a]) + { + case sigInt: + case sigBool: + compiler->move(JitReg(SLJIT_R(ints++),jtInt), JitFramePos(pos).as(jtInt)); + argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_32, a+1); + pos += sizeof(int); + break; + case sigFloat: + compiler->move(JitReg(SLJIT_FR(floats++),jtFloat), JitFramePos(pos).as(jtFloat)); + argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_F64, a+1); + pos += sizeof(double); + break; + default: + compiler->move(JitReg(SLJIT_R(ints++),jtPointer), JitFramePos(pos).as(jtPointer)); + argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_P, a+1); + pos += sizeof(hx::Object *); + } + } + switch(sig[0]) + { + case sigInt: case sigBool: argTypes |= SLJIT_ARG_RETURN(SLJIT_ARG_TYPE_32); break; + case sigFloat: argTypes |= SLJIT_ARG_RETURN(SLJIT_ARG_TYPE_F64); break; + case sigObject: argTypes |= SLJIT_ARG_RETURN(SLJIT_ARG_TYPE_P); break; + default: argTypes |= SLJIT_ARG_RETURN(SLJIT_ARG_TYPE_RET_VOID); + } + compiler->callNativeArgs(inEntry, argTypes, ints, floats); + switch(sig[0]) + { + case sigInt: case sigBool: compiler->move(JitFramePos(framePos).as(jtInt), sJitReturnReg.as(jtInt)); break; + case sigFloat: compiler->move(JitFramePos(framePos).as(jtFloat), sJitTempF0); break; + case sigObject: compiler->move(JitFramePos(framePos).as(jtPointer), sJitReturnReg.as(jtPointer)); break; + default: ; + } + } + + // Whether a typed entry can take this call: no String, and at most three arguments + bool entryTakes() const + { + const char *sig = function.signature; + if (!sig || strlen(sig)>4) + return false; + for(const char *s=sig; *s; s++) + if (*s==sigString) + return false; + return true; + } + void genCode(CppiaCompiler *compiler, const JitVal &inDest,ExprType destType) HXCPP_OVERRIDE { int framePos = compiler->getCurrentFrameSize(); @@ -2124,6 +2206,9 @@ struct CallHaxe : public CppiaExpr compiler->add( sJitCtxFrame, sJitFrame.as(jtPointer), JitVal(framePos) ); void *func = (void *) ( isSuper ? function.superExecute : function.execute); + // The typed entry for the call as written: the host's own for a super call + bool entries = entryTakes(); + void *entry = entries ? (isSuper ? superEntry : virtualEntry) : 0; // The script class's objects are host objects of one C++ class, whose method // checks the script vtable for an override before it runs the host's. An @@ -2137,14 +2222,22 @@ struct CallHaxe : public CppiaExpr JumpId otherClass = compiler->compare(cmpP_NOT_EQUAL, sJitTemp0.star(jtPointer, 0), hostVTable); compiler->move(sJitTemp1.as(jtPointer), sJitTemp0.star(jtPointer, receiverClass->getScriptVTableOffset())); JumpId overridden = compiler->compare(cmpP_NOT_EQUAL, sJitTemp1.star(jtPointer, hostSlot*(int)sizeof(void *)), (void *)0); - compiler->callNative( (void *)tryCallHaxe, JitVal((void *)function.superExecute), sJitCtx ); + if (entries && superEntry) + genEntryCall(compiler, superEntry, framePos); + else + compiler->callNative( (void *)tryCallHaxe, JitVal((void *)function.superExecute), sJitCtx ); JumpId called = compiler->jump(); compiler->comeFrom(isNull); compiler->comeFrom(otherClass); compiler->comeFrom(overridden); - compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); + if (entry) + genEntryCall(compiler, entry, framePos); + else + compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); compiler->comeFrom(called); } + else if (entry) + genEntryCall(compiler, entry, framePos); else compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); @@ -4096,6 +4189,7 @@ struct CallMember : public CppiaExpr //CPPIALOG(" found function %s\n", func.signature ); CallHaxe *call = new CallHaxe( this, func, thisExpr, args, false, callSuperField && func.superExecute, type->name); call->setReceiver(type->cppiaClass, type->haxeBase); + call->setEntries(type->haxeBase); replace = call; } } diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index c37ad648e..60f9268de 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -739,12 +739,17 @@ class HaxeNativeClass ScriptNamedFunction *functions; HaxeNativeClass *haxeSuper; int mDataOffset; + // The typed entries of the class's methods, from HX_SCRIPTABLE_REGISTER_CLASS + ScriptMethodEntry *methodEntries; HaxeNativeClass(const std::string &inName, int inDataOffset, ScriptNamedFunction *inFunctions, hx::ScriptableClassFactory inFactory, ScriptNamedFunction inConstruct); void addVtableEntries( std::vector &outVtable); void dump(); ScriptNamedFunction findFunction(const std::string &inName); + // The typed entries of the method findFunction finds for inName, if it has + // them and they take and give what inSignature says + const ScriptMethodEntry *findMethodEntry(const std::string &inName, const char *inSignature); ScriptNamedFunction findStaticFunction(String inName); static HaxeNativeClass *findClass(const std::string &inName); diff --git a/src/hx/cppia/CppiaCompiler.cpp b/src/hx/cppia/CppiaCompiler.cpp index 8d392eee9..e8765bc63 100644 --- a/src/hx/cppia/CppiaCompiler.cpp +++ b/src/hx/cppia/CppiaCompiler.cpp @@ -1435,6 +1435,22 @@ class CppiaJitCompiler : public CppiaCompiler emit_icall(SLJIT_ARGS1(W, P), t, getData(func)); } + void callNativeArgs(void *func, int inArgTypes, int inIntArgs, int inFloatArgs) HXCPP_OVERRIDE + { + makesNativeCalls = true; + if (maxTempCountname;f++) + if (inName == f->name && !f->isStatic) + { + #ifdef HX_SCRIPT_METHOD_ENTRIES + if (inSignature && !strcmp(f->signature,inSignature)) + for(ScriptMethodEntry *e=methodEntries;e;e=e->next) + if (inName==e->name && !strcmp(e->signature,inSignature)) + return e; + #endif + return 0; + } + if (haxeSuper) + return haxeSuper->findMethodEntry(inName, inSignature); + return 0; +} + + ScriptNamedFunction HaxeNativeClass::findStaticFunction(String inName) { if (functions) @@ -284,6 +305,28 @@ HaxeNativeInterface::HaxeNativeInterface(const std::string &inName, scriptTable = inScriptTable; } +#ifdef HX_SCRIPT_METHOD_ENTRIES +void ScriptableRegisterMethodEntries(String inName, ScriptMethodEntry *inEntries) +{ + if (!sScriptRegistered) + return; + ScriptRegisteredMap::iterator it = sScriptRegistered->find(inName.utf8_str()); + if (it!=sScriptRegistered->end()) + it->second->methodEntries = inEntries; +} + +void ScriptEntryThrew(hx::Object *inValue) +{ + CppiaCtx::getCurrent()->exception = hx::toPendingException(inValue); +} + +void ScriptEntryThrewText(const char *inText) +{ + CppiaCtx::getCurrent()->exception = Dynamic(String(inText)).mPtr; +} +#endif + + void ScriptableRegisterInterface( String inName, ScriptNamedFunction *inFunctions, void *inScriptTable) diff --git a/test/regression/CppiaHostMethodEntries/HostCalc.hx b/test/regression/CppiaHostMethodEntries/HostCalc.hx new file mode 100644 index 000000000..544cee9aa --- /dev/null +++ b/test/regression/CppiaHostMethodEntries/HostCalc.hx @@ -0,0 +1,85 @@ +// Host classes the script calls methods of, compiled into the host. Their methods +// take and give every kind a typed entry takes, and some it does not +class HostCalc { + public var value:Float = 0; + public var calls = 0; + + public function new() {} + + public function none():Void + calls++; + + public function getInt():Int + return 7 + calls; + + public function getBool():Bool + return calls % 2 == 0; + + public function getFloat():Float + return 2.5 + calls; + + public function getSelf():HostCalc + return this; + + public function getDynamic():Dynamic + return calls > 0 ? (calls : Dynamic) : null; + + public function addInt(a:Int):Int + return a + 1; + + public function flip(b:Bool):Bool + return !b; + + public function half(x:Float):Float + return x / 2; + + public function mix(a:Int, x:Float, b:Bool):Float + return b ? a + x : a - x; + + public function three(a:Int, b:Int, c:Int):Int + return a * 100 + b * 10 + c; + + // Four arguments, and a String, which an entry does not take + public function four(a:Int, b:Int, c:Int, d:Int):Int + return a + b * 2 + c * 3 + d * 4; + + public function measure(s:String):Int + return s == null ? -1 : s.length; + + public function sumArray(a:Array):Int { + var t = 0; + if (a != null) + for (v in a) + t += v; + return t; + } + + public function valueOf(o:HostCalc):Float + return o == null ? -1 : o.value; + + public function orDefault(n:Null):Int + return n == null ? -1 : n; + + public function single(f:cpp.Float32):cpp.Float32 + return f * 2; + + public function fail(k:Int):Int { + if (k > 1) + throw 'fail $k'; + return k; + } + + public function callBack(f:Int->Int):Int + return f(3) + f(4); + + public function setValue(v:Float):Void + value = v; + + public var prop(get, set):Float; + + function get_prop():Float + return value; + + function set_prop(v:Float):Float + return value = v * 2; +} diff --git a/test/regression/CppiaHostMethodEntries/HostCalcChild.hx b/test/regression/CppiaHostMethodEntries/HostCalcChild.hx new file mode 100644 index 000000000..e3f19656a --- /dev/null +++ b/test/regression/CppiaHostMethodEntries/HostCalcChild.hx @@ -0,0 +1,15 @@ +// A host subclass whose overrides are C++ ones +class HostCalcChild extends HostCalc { + public function new() { + super(); + } + + override public function addInt(a:Int):Int + return a + 1000; + + override public function half(x:Float):Float + return x / 4; + + override function get_prop():Float + return value + 0.5; +} diff --git a/test/regression/CppiaHostMethodEntries/Main.hx b/test/regression/CppiaHostMethodEntries/Main.hx new file mode 100644 index 000000000..1153bc9db --- /dev/null +++ b/test/regression/CppiaHostMethodEntries/Main.hx @@ -0,0 +1,151 @@ +// Jitted script code calls a host instance method through a typed entry that +// takes the object and the arguments in registers, where the method takes up to +// three Ints, Bools, Floats or objects and gives one of those or nothing: the +// entry calling the host class's own method where the object is of that class +// and no script class overrides it, and the virtual one otherwise. Anything +// else takes the method's script stub as before. Every kind of argument and +// result, methods an entry does not take, host overrides, script overrides, +// super calls, host code calling back into the script, a throw and a null +// object, through the host class's type and through script classes' types. +// The same calls run compiled into the host, then as a script with the JIT off +// and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same calls as Script.hx, compiled into the host +class CompiledScriptCalc extends HostCalc { + public function new() { + super(); + } +} + +class CompiledOverCalc extends HostCalc { + public function new() { + super(); + } + + override public function addInt(a:Int):Int + return a + 50; + + override function get_prop():Float + return 99.0; +} + +class CompiledSuperCalc extends HostCalc { + public function new() { + super(); + } + + override public function half(x:Float):Float + return super.half(x) + 1; + + override public function getInt():Int + return super.getInt() * 10; +} + +class Compiled { + // Every method through the host class's type, which reaches any override + static function all(c:HostCalc):String { + var out:Array = []; + c.none(); + out.push(c.getInt()); + out.push(c.getBool()); + out.push(c.getFloat()); + out.push(c.getSelf() == c); + out.push(c.getDynamic()); + out.push(c.addInt(5)); + out.push(c.flip(true)); + out.push(c.half(9)); + out.push(c.mix(3, 0.25, true)); + out.push(c.mix(3, 0.25, false)); + out.push(c.three(1, 2, 3)); + out.push(c.four(1, 2, 3, 4)); + out.push(c.measure("abc")); + out.push(c.measure(null)); + out.push(c.sumArray([1, 2, 3])); + out.push(c.sumArray(null)); + c.setValue(1.5); + out.push(c.valueOf(c)); + out.push(c.valueOf(null)); + out.push(c.orDefault(4)); + out.push(c.orDefault(null)); + out.push(c.single(1.25)); + out.push(c.callBack(x -> x * x)); + c.prop = 3; + out.push(c.prop); + out.push(c.value); + return out.join(" "); + } + + // Some of the same calls through a script class's own type + static function viaScript(c:CompiledScriptCalc):String { + c.none(); + c.prop = 2; + return [c.getInt(), c.addInt(5), c.half(9), c.mix(3, 0.25, true), c.three(1, 2, 3), c.prop, c.valueOf(c)].join(" "); + } + + static function viaOver(c:CompiledOverCalc):String { + c.prop = 2; + return [c.getInt(), c.addInt(5), c.half(9), c.prop, c.value].join(" "); + } + + static function viaSuper(c:CompiledSuperCalc):String { + return [c.getInt(), c.addInt(5), c.half(9)].join(" "); + } + + public static function run() { + var receivers:Array = [new HostCalc(), new HostCalcChild(), new CompiledScriptCalc(), new CompiledOverCalc(), new CompiledSuperCalc()]; + for (c in receivers) + Sys.println('all ${all(c)}'); + Sys.println('script type ${viaScript(new CompiledScriptCalc())}'); + Sys.println('override type ${viaOver(new CompiledOverCalc())}'); + Sys.println('super type ${viaSuper(new CompiledSuperCalc())}'); + + // Enough calls that each loop runs jitted + var c = new CompiledScriptCalc(); + var plain = new HostCalc(); + var t = 0.0; + for (i in 0...20000) { + c.prop = c.prop / 4 + 1; + t += c.half(i) + c.addInt(i) + plain.mix(i, 0.5, i % 2 == 0); + c.setValue(c.prop / 2); + } + Sys.println('loop $t ${c.value}'); + + var caught = []; + for (k in 0...4) + try { + caught.push(Std.string(c.fail(k))); + } catch (e:String) { + caught.push(e); + } + Sys.println('throws $caught'); + + var nullHost:HostCalc = null; + try { + nullHost.getInt(); + Sys.println('null host passes'); + } catch (e:Dynamic) { + Sys.println('null host throws'); + } + var nullScript:CompiledScriptCalc = null; + try { + nullScript.addInt(1); + Sys.println('null script passes'); + } catch (e:Dynamic) { + Sys.println('null script throws'); + } + } +} diff --git a/test/regression/CppiaHostMethodEntries/Script.hx b/test/regression/CppiaHostMethodEntries/Script.hx new file mode 100644 index 000000000..0ff7acf2a --- /dev/null +++ b/test/regression/CppiaHostMethodEntries/Script.hx @@ -0,0 +1,125 @@ +// The same cases as Compiled in Main.hx, run as a script +class ScriptCalc extends HostCalc { + public function new() { + super(); + } +} + +class OverCalc extends HostCalc { + public function new() { + super(); + } + + override public function addInt(a:Int):Int + return a + 50; + + override function get_prop():Float + return 99.0; +} + +class SuperCalc extends HostCalc { + public function new() { + super(); + } + + override public function half(x:Float):Float + return super.half(x) + 1; + + override public function getInt():Int + return super.getInt() * 10; +} + +class Script { + // Every method through the host class's type, which reaches any override + static function all(c:HostCalc):String { + var out:Array = []; + c.none(); + out.push(c.getInt()); + out.push(c.getBool()); + out.push(c.getFloat()); + out.push(c.getSelf() == c); + out.push(c.getDynamic()); + out.push(c.addInt(5)); + out.push(c.flip(true)); + out.push(c.half(9)); + out.push(c.mix(3, 0.25, true)); + out.push(c.mix(3, 0.25, false)); + out.push(c.three(1, 2, 3)); + out.push(c.four(1, 2, 3, 4)); + out.push(c.measure("abc")); + out.push(c.measure(null)); + out.push(c.sumArray([1, 2, 3])); + out.push(c.sumArray(null)); + c.setValue(1.5); + out.push(c.valueOf(c)); + out.push(c.valueOf(null)); + out.push(c.orDefault(4)); + out.push(c.orDefault(null)); + out.push(c.single(1.25)); + out.push(c.callBack(x -> x * x)); + c.prop = 3; + out.push(c.prop); + out.push(c.value); + return out.join(" "); + } + + // Some of the same calls through a script class's own type + static function viaScript(c:ScriptCalc):String { + c.none(); + c.prop = 2; + return [c.getInt(), c.addInt(5), c.half(9), c.mix(3, 0.25, true), c.three(1, 2, 3), c.prop, c.valueOf(c)].join(" "); + } + + static function viaOver(c:OverCalc):String { + c.prop = 2; + return [c.getInt(), c.addInt(5), c.half(9), c.prop, c.value].join(" "); + } + + static function viaSuper(c:SuperCalc):String { + return [c.getInt(), c.addInt(5), c.half(9)].join(" "); + } + + static function main() { + var receivers:Array = [new HostCalc(), new HostCalcChild(), new ScriptCalc(), new OverCalc(), new SuperCalc()]; + for (c in receivers) + Sys.println('all ${all(c)}'); + Sys.println('script type ${viaScript(new ScriptCalc())}'); + Sys.println('override type ${viaOver(new OverCalc())}'); + Sys.println('super type ${viaSuper(new SuperCalc())}'); + + // Enough calls that each loop runs jitted + var c = new ScriptCalc(); + var plain = new HostCalc(); + var t = 0.0; + for (i in 0...20000) { + c.prop = c.prop / 4 + 1; + t += c.half(i) + c.addInt(i) + plain.mix(i, 0.5, i % 2 == 0); + c.setValue(c.prop / 2); + } + Sys.println('loop $t ${c.value}'); + + var caught = []; + for (k in 0...4) + try { + caught.push(Std.string(c.fail(k))); + } catch (e:String) { + caught.push(e); + } + Sys.println('throws $caught'); + + var nullHost:HostCalc = null; + try { + nullHost.getInt(); + Sys.println('null host passes'); + } catch (e:Dynamic) { + Sys.println('null host throws'); + } + var nullScript:ScriptCalc = null; + try { + nullScript.addInt(1); + Sys.println('null script passes'); + } catch (e:Dynamic) { + Sys.println('null script throws'); + } + } +} diff --git a/test/regression/CppiaHostMethodEntries/build.hxml b/test/regression/CppiaHostMethodEntries/build.hxml new file mode 100644 index 000000000..7ae4dcfe0 --- /dev/null +++ b/test/regression/CppiaHostMethodEntries/build.hxml @@ -0,0 +1,10 @@ +--main Main +-cpp bin +-D scriptable +--dce no +-D HXCPP_CHECK_POINTER +-D dll_export=bin/host_classes.info +--next +--main Script +-cppia bin/script.cppia +-D dll_import=bin/host_classes.info diff --git a/test/regression/CppiaHostMethodEntries/stdout.txt b/test/regression/CppiaHostMethodEntries/stdout.txt new file mode 100644 index 000000000..d2335c188 --- /dev/null +++ b/test/regression/CppiaHostMethodEntries/stdout.txt @@ -0,0 +1,39 @@ +-- compiled +all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +all 8 false 3.5 true 1 1005 false 2.25 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6.5 6 +all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +all 8 false 3.5 true 1 55 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 99 6 +all 80 false 3.5 true 1 6 false 5.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +script type 8 6 4.5 3.25 123 4 4 +override type 7 55 4.5 99 4 +super type 70 6 5.5 +loop 499995000 1.3333333333333333 +throws [0,1,fail 2,fail 3] +null host throws +null script throws +-- script, JIT off +all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +all 8 false 3.5 true 1 1005 false 2.25 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6.5 6 +all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +all 8 false 3.5 true 1 55 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 99 6 +all 80 false 3.5 true 1 6 false 5.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +script type 8 6 4.5 3.25 123 4 4 +override type 7 55 4.5 99 4 +super type 70 6 5.5 +loop 499995000 1.3333333333333333 +throws [0,1,fail 2,fail 3] +null host throws +null script throws +-- script, JIT on +all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +all 8 false 3.5 true 1 1005 false 2.25 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6.5 6 +all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +all 8 false 3.5 true 1 55 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 99 6 +all 80 false 3.5 true 1 6 false 5.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 +script type 8 6 4.5 3.25 123 4 4 +override type 7 55 4.5 99 4 +super type 70 6 5.5 +loop 499995000 1.3333333333333333 +throws [0,1,fail 2,fail 3] +null host throws +null script throws diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index 97fbda874..d994b8d1d 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -24,6 +24,7 @@ CppiaClosureCaptures: its host is the first --next section, which -D emscripten CppiaHostArgs: processes CppiaHostClosureCalls: its host is the first --next section, which -D emscripten does not reach CppiaHostFunctionOrder: its host is the first --next section, which -D emscripten does not reach +CppiaHostMethodEntries: its host is the first --next section, which -D emscripten does not reach CppiaHostMismatch: its host is the first --next section, which -D emscripten does not reach, and it checks jitted code, and Emscripten has no cppia JIT CppiaJitBuiltins: threads CppiaJitHostMethods: its host is the first --next section, which -D emscripten does not reach From 20dc6367697fc9992ca3bd8a0a03bd648a153a95 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 20:03:59 -0500 Subject: [PATCH 17/23] Call host static functions from jitted cppia code through typed entries 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 (12e3bb90), 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 695a02dd, 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 --- Changes.md | 1 + include/hx/Scriptable.h | 74 ++++++++++++++++++- src/Dynamic.cpp | 31 ++++++++ src/hx/cppia/Cppia.cpp | 54 +++++++++++--- .../CppiaHostMethodEntries/HostCalc.hx | 27 +++++++ .../regression/CppiaHostMethodEntries/Main.hx | 23 ++++++ .../CppiaHostMethodEntries/Script.hx | 23 ++++++ .../CppiaHostMethodEntries/stdout.txt | 3 + 8 files changed, 225 insertions(+), 11 deletions(-) diff --git a/Changes.md b/Changes.md index 5ed37ce8b..f6097e2ab 100644 --- a/Changes.md +++ b/Changes.md @@ -13,6 +13,7 @@ libhxcpp 6.1.0 (unreleased) * A cppia closure copies the variables it captures into the frame of each call, and out of the frame that makes it, from a list its function keeps of where each one sits and how big it is, set when the function links, with a move of that size. For each capture it went from the closure to its function, to the function's captured variables, to the variable for its offsets and size, and then called memcpy. Jitted code calling a closure that captures a variable is 13% faster (closure_call), 0.65x of HashLink 1.16's JIT where it was 0.57x, and the host calling one back 5% (native_callback). Interpreted calls are level * Host code calling a compiled cppia closure back through hx::callFunction, as Dynamic::operator() and Array.sort do in a scriptable build, takes a path that does only what that call needs: the arguments pushed, the captured variables copied and the result written in line, and the compiled code called. It shared one function with the general path, and called out to copy the captures, to write the result and to box it. Under the JIT, the host calling back a closure that takes and returns an Int is 15% faster (native_callback), 0.34x of HashLink 1.16's JIT, and sorting with a script comparator 10% (host_sort). Interpreted calls are level * Jitted cppia code calls a host instance method that takes up to three Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the object and the arguments in registers, in a scriptable build. It went through the method's script stub, which took the arguments from the script frame and wrote the result back there, by way of a helper that catches what the stub throws. Each instance method's Dynamic wrapper (HX_DEFINE_DYNAMIC_FUNC) now makes two entries: one calling the method virtually, as the stub does, and one calling the class's own, as the stub for a super call does, which a C++ class with pure virtual methods does not get. A scriptable class gives the runtime its methods' entries as it registers, and an entry leaves what the method throws for the script, as the helper does. Updating script objects through a host display object's properties, as BunnyMark's loop does, is 1.56x faster under the JIT (bunny_update), 0.77x of HashLink 1.16's JIT where it was 0.5x, and an OpenFL-shaped frame 7% faster (openfl_frame). Interpreted calls, methods with a String or more than three arguments, and code built against older headers take the stub as before. A scriptable host is larger by about 1.4% for the entries +* Jitted cppia code calls a host static function that takes up to four Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the arguments in registers, in a scriptable build, whether the host gives the script a binding for it or the script calls it by name. Each static function's Dynamic wrapper registers the entry with the function's typed stub. Script-to-native calls are 1.26x faster under the JIT (native_call), ahead of HashLink 1.16's JIT, and calls by name 1.41x (call_by_name), 0.79x of HashLink's JIT where they were 0.56x libhxcpp 6.0.3 ------------------------------------------------------------ diff --git a/include/hx/Scriptable.h b/include/hx/Scriptable.h index 901939b0d..41c07a75f 100644 --- a/include/hx/Scriptable.h +++ b/include/hx/Scriptable.h @@ -321,10 +321,15 @@ struct __hx_stub_##class##func \ { return ::hx::scriptStubInfo(); } \ template static ::hx::ScriptStubInfo get(...) \ { ::hx::ScriptStubInfo none = { 0, 0 }; return none; } \ + template static auto getEntry(int) -> decltype(&T::func, ::hx::ScriptStaticEntryInfo()) \ + { return ::hx::ScriptStaticEntryOf::get(); } \ + template static ::hx::ScriptStaticEntryInfo getEntry(...) \ + { ::hx::ScriptStaticEntryInfo none = { 0, 0 }; return none; } \ }; #define HX_SCRIPT_STATIC_STUB(class,func,thunk) \ - static bool __hx_script_stub = ::hx::RegisterScriptStaticStub( (void *)thunk, __hx_stub_##class##func::get(0) ); \ + static bool __hx_script_stub = ::hx::RegisterScriptStaticStub( (void *)thunk, __hx_stub_##class##func::get(0) ) && \ + ::hx::RegisterScriptStaticEntry( (void *)thunk, __hx_stub_##class##func::getEntry(0) ); \ (void)__hx_script_stub; @@ -508,6 +513,73 @@ struct ScriptMethodEntryOf { }; +// A typed entry for a static function, which jitted script code calls with the +// arguments in registers, for one that takes up to four Ints, Bools, Floats or +// objects and gives one of those or nothing. The function's Dynamic wrapper +// registers it with the stub, as it is first asked for +struct ScriptStaticEntryInfo +{ + void *entry; + const char *signature; +}; +HXCPP_EXTERN_CLASS_ATTRIBUTES +bool RegisterScriptStaticEntry(void *inThunk, const ScriptStaticEntryInfo &inInfo); +// The entry registered for the static function inFunction, if it has one +HXCPP_EXTERN_CLASS_ATTRIBUTES +bool FindScriptStaticEntry(hx::Object *inFunction, void *&outEntry, const char *&outSignature); + +template struct ScriptStaticEntryCall; +template +struct ScriptStaticEntryCall +{ + typedef ScriptEntryValue::type> Result; + static typename Result::Raw CPPIA_CALL entry(typename ScriptEntryValue::type>::Raw... inArgs) + { + try + { + return Result::give( inFunction( ScriptEntryValue::type>::take(inArgs)... ) ); + } + HX_SCRIPT_ENTRY_CATCH + return typename Result::Raw(); + } +}; +template +struct ScriptStaticEntryCall +{ + static void CPPIA_CALL entry(typename ScriptEntryValue::type>::Raw... inArgs) + { + try + { + inFunction( ScriptEntryValue::type>::take(inArgs)... ); + } + HX_SCRIPT_ENTRY_CATCH + } +}; + +template struct ScriptStaticEntryMake +{ + static ScriptStaticEntryInfo get() { ScriptStaticEntryInfo none = { 0, 0 }; return none; } +}; +template struct ScriptStaticEntryMake +{ + static ScriptStaticEntryInfo get() + { + static const char sig[] = { (char)ScriptEntryValue::type>::sig, (char)ScriptEntryValue::type>::sig..., 0 }; + ScriptStaticEntryInfo info = { (void *)&ScriptStaticEntryCall::entry, sig }; + return info; + } +}; + +template struct ScriptStaticEntryOf +{ + static ScriptStaticEntryInfo get() { ScriptStaticEntryInfo none = { 0, 0 }; return none; } +}; +template +struct ScriptStaticEntryOf + : ScriptStaticEntryMake< (sizeof...(A)<=4) && (int)ScriptEntryKinds::ok, R (*)(A...), inFunction, R, A...> +{ +}; + // Each instance method's Dynamic wrapper makes its entries here, at namespace // scope. A name with overloads, as some hand-written classes have, has no one // address to take, so it gets none and keeps its stub diff --git a/src/Dynamic.cpp b/src/Dynamic.cpp index e792eeb3c..5ac1c100a 100644 --- a/src/Dynamic.cpp +++ b/src/Dynamic.cpp @@ -732,6 +732,23 @@ static std::unordered_map &scriptStaticStubs() return stubs; } +// The register entries, by the same wrappers +static std::unordered_map &scriptStaticEntries() +{ + static std::unordered_map &entries = *new std::unordered_map(); + return entries; +} + +bool RegisterScriptStaticEntry(void *inThunk, const ScriptStaticEntryInfo &inInfo) +{ + if (inInfo.entry) + { + std::lock_guard hold(scriptStaticStubLock()); + scriptStaticEntries()[inThunk] = inInfo; + } + return true; +} + bool RegisterScriptStaticStub(void *inThunk, const ScriptStubInfo &inInfo) { if (!inInfo.execute) @@ -773,5 +790,19 @@ bool FindScriptStaticStub(hx::Object *inFunction, StackExecute &outExecute, cons return true; } +bool FindScriptStaticEntry(hx::Object *inFunction, void *&outEntry, const char *&outSignature) +{ + void *thunk = inFunction ? staticFunctionThunk(inFunction) : 0; + if (!thunk) + return false; + std::lock_guard hold(scriptStaticStubLock()); + std::unordered_map::iterator it = scriptStaticEntries().find(thunk); + if (it==scriptStaticEntries().end()) + return false; + outEntry = it->second.entry; + outSignature = it->second.signature; + return true; +} + } // end namespace hx #endif diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index cd31981cb..4548cdb61 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -1905,6 +1905,8 @@ struct CallHaxe : public CppiaExpr // calling the host class's own, as the super stub does void *virtualEntry; void *superEntry; + // A static function's typed entry, which takes the arguments in registers + void *staticEntry; CallHaxe(CppiaExpr *inSrc,ScriptNamedFunction inFunction, CppiaExpr *inThis, Expressions &ioArgs, bool inIsStatic=false, bool inIsSuper = false, String inClassName = String() ) : CppiaExpr(inSrc) @@ -1919,6 +1921,19 @@ struct CallHaxe : public CppiaExpr hostSlot = -1; virtualEntry = 0; superEntry = 0; + staticEntry = 0; + } + + // The typed entry of the static function inFunction, its Dynamic wrapper + void setStaticEntry(hx::Object *inFunction) + { + #ifdef HX_SCRIPT_STATIC_STUBS + void *entry = 0; + const char *signature = 0; + if (isStatic && inFunction && function.signature && FindScriptStaticEntry(inFunction, entry, signature) && + !strcmp(signature, function.signature)) + staticEntry = entry; + #endif } // The typed entries of the method, found on the host class inHostClass @@ -2104,14 +2119,20 @@ struct CallHaxe : public CppiaExpr // Calls a typed entry with this and the arguments, which are in the frame at // framePos, in the registers their kinds take, and leaves the result in the // frame there, where a stub leaves one - void genEntryCall(CppiaCompiler *compiler, void *inEntry, int framePos) + void genEntryCall(CppiaCompiler *compiler, void *inEntry, int framePos, bool inWithThis=true) { const char *sig = function.signature; int ints = 0; int floats = 0; int pos = framePos; - int argTypes = SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_P, 1); - compiler->move(JitReg(SLJIT_R(ints++),jtPointer), JitFramePos(pos).as(jtPointer)); + int argTypes = 0; + // A static's entry takes no object, and its frame's slot for this is empty + int index = 1; + if (inWithThis) + { + argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_P, index++); + compiler->move(JitReg(SLJIT_R(ints++),jtPointer), JitFramePos(pos).as(jtPointer)); + } pos += sizeof(hx::Object *); for(int a=1; sig[a]; a++) { @@ -2120,17 +2141,17 @@ struct CallHaxe : public CppiaExpr case sigInt: case sigBool: compiler->move(JitReg(SLJIT_R(ints++),jtInt), JitFramePos(pos).as(jtInt)); - argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_32, a+1); + argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_32, index++); pos += sizeof(int); break; case sigFloat: compiler->move(JitReg(SLJIT_FR(floats++),jtFloat), JitFramePos(pos).as(jtFloat)); - argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_F64, a+1); + argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_F64, index++); pos += sizeof(double); break; default: compiler->move(JitReg(SLJIT_R(ints++),jtPointer), JitFramePos(pos).as(jtPointer)); - argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_P, a+1); + argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_P, index++); pos += sizeof(hx::Object *); } } @@ -2151,11 +2172,12 @@ struct CallHaxe : public CppiaExpr } } - // Whether a typed entry can take this call: no String, and at most three arguments + // Whether a typed entry can take this call: no String, and at most three + // arguments, or four for a static, whose entry takes no object bool entryTakes() const { const char *sig = function.signature; - if (!sig || strlen(sig)>4) + if (!sig || strlen(sig)>(isStatic ? 5 : 4)) return false; for(const char *s=sig; *s; s++) if (*s==sigString) @@ -2236,6 +2258,8 @@ struct CallHaxe : public CppiaExpr compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); compiler->comeFrom(called); } + else if (isStatic && staticEntry && entries) + genEntryCall(compiler, staticEntry, framePos, false); else if (entry) genEntryCall(compiler, entry, framePos); else @@ -2289,7 +2313,13 @@ struct CallStatic : public CppiaExpr if (func.signature) { //CPPIALOG(" found function %s\n", func.signature ); - replace = new CallHaxe( this, func, 0, args, true, false, type->name ); + CallHaxe *call = new CallHaxe( this, func, 0, args, true, false, type->name ); + #ifdef HX_SCRIPT_STATIC_STUBS + // The wrapper registers the function's typed entry as it is asked for + Dynamic wrapper = type->haxeClass.mPtr->__Field( field, HX_PROP_NEVER ); + call->setStaticEntry(wrapper.mPtr); + #endif + replace = call; } else { @@ -2304,7 +2334,11 @@ struct CallStatic : public CppiaExpr StackExecute execute = 0; const char *signature = 0; if (func.mPtr && FindScriptStaticStub(func.mPtr, execute, signature) && (int)strlen(signature)-1==(int)args.size()) - replace = new CallHaxe( this, ScriptNamedFunction(0, execute, signature, true), 0, args, true, false, type->name ); + { + CallHaxe *call = new CallHaxe( this, ScriptNamedFunction(0, execute, signature, true), 0, args, true, false, type->name ); + call->setStaticEntry(func.mPtr); + replace = call; + } else #endif if (func.mPtr) diff --git a/test/regression/CppiaHostMethodEntries/HostCalc.hx b/test/regression/CppiaHostMethodEntries/HostCalc.hx index 544cee9aa..89cb4e59d 100644 --- a/test/regression/CppiaHostMethodEntries/HostCalc.hx +++ b/test/regression/CppiaHostMethodEntries/HostCalc.hx @@ -4,8 +4,35 @@ class HostCalc { public var value:Float = 0; public var calls = 0; + public static var count = 0; + public function new() {} + // Static functions, whose entries take no object and up to four arguments + public static function sCount():Void + count++; + + public static function sInt(a:Int):Int + return a * 3 + count; + + public static function sMix(a:Int, x:Float, b:Bool, o:HostCalc):Float + return (b ? a : -a) + x + (o == null ? 0.5 : o.value); + + public static function sFive(a:Int, b:Int, c:Int, d:Int, e:Int):Int + return a + b + c + d + e * 10; + + public static function sText(s:String):Int + return s.length; + + public static function sSelf(c:HostCalc):HostCalc + return c; + + public static function sFail(k:Int):Int { + if (k > 0) + throw 'static fail $k'; + return k; + } + public function none():Void calls++; diff --git a/test/regression/CppiaHostMethodEntries/Main.hx b/test/regression/CppiaHostMethodEntries/Main.hx index 1153bc9db..a81d0d2f6 100644 --- a/test/regression/CppiaHostMethodEntries/Main.hx +++ b/test/regression/CppiaHostMethodEntries/Main.hx @@ -105,7 +105,30 @@ class Compiled { return [c.getInt(), c.addInt(5), c.half(9)].join(" "); } + // The host's static functions + static function statics():String { + // The host's state carries over from one run to the next + HostCalc.count = 0; + var c = new HostCalc(); + c.setValue(0.25); + HostCalc.sCount(); + var out:Array = [HostCalc.sInt(4), HostCalc.sMix(3, 0.5, false, c), HostCalc.sMix(3, 0.5, true, null), + HostCalc.sFive(1, 2, 3, 4, 5), HostCalc.sText("four"), HostCalc.sSelf(c) == c, HostCalc.sSelf(null) == null]; + var t = 0; + for (i in 0...20000) + t += HostCalc.sInt(i & 63); + out.push(t); + for (k in 0...2) + try { + out.push(HostCalc.sFail(k)); + } catch (e:String) { + out.push(e); + } + return out.join(" "); + } + public static function run() { + Sys.println('statics ${statics()}'); var receivers:Array = [new HostCalc(), new HostCalcChild(), new CompiledScriptCalc(), new CompiledOverCalc(), new CompiledSuperCalc()]; for (c in receivers) Sys.println('all ${all(c)}'); diff --git a/test/regression/CppiaHostMethodEntries/Script.hx b/test/regression/CppiaHostMethodEntries/Script.hx index 0ff7acf2a..98c66365e 100644 --- a/test/regression/CppiaHostMethodEntries/Script.hx +++ b/test/regression/CppiaHostMethodEntries/Script.hx @@ -79,7 +79,30 @@ class Script { return [c.getInt(), c.addInt(5), c.half(9)].join(" "); } + // The host's static functions + static function statics():String { + // The host's state carries over from one run to the next + HostCalc.count = 0; + var c = new HostCalc(); + c.setValue(0.25); + HostCalc.sCount(); + var out:Array = [HostCalc.sInt(4), HostCalc.sMix(3, 0.5, false, c), HostCalc.sMix(3, 0.5, true, null), + HostCalc.sFive(1, 2, 3, 4, 5), HostCalc.sText("four"), HostCalc.sSelf(c) == c, HostCalc.sSelf(null) == null]; + var t = 0; + for (i in 0...20000) + t += HostCalc.sInt(i & 63); + out.push(t); + for (k in 0...2) + try { + out.push(HostCalc.sFail(k)); + } catch (e:String) { + out.push(e); + } + return out.join(" "); + } + static function main() { + Sys.println('statics ${statics()}'); var receivers:Array = [new HostCalc(), new HostCalcChild(), new ScriptCalc(), new OverCalc(), new SuperCalc()]; for (c in receivers) Sys.println('all ${all(c)}'); diff --git a/test/regression/CppiaHostMethodEntries/stdout.txt b/test/regression/CppiaHostMethodEntries/stdout.txt index d2335c188..519d1eb18 100644 --- a/test/regression/CppiaHostMethodEntries/stdout.txt +++ b/test/regression/CppiaHostMethodEntries/stdout.txt @@ -1,4 +1,5 @@ -- compiled +statics 13 -2.25 4 60 4 true true 1908464 0 static fail 1 all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 all 8 false 3.5 true 1 1005 false 2.25 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6.5 6 all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 @@ -12,6 +13,7 @@ throws [0,1,fail 2,fail 3] null host throws null script throws -- script, JIT off +statics 13 -2.25 4 60 4 true true 1908464 0 static fail 1 all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 all 8 false 3.5 true 1 1005 false 2.25 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6.5 6 all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 @@ -25,6 +27,7 @@ throws [0,1,fail 2,fail 3] null host throws null script throws -- script, JIT on +statics 13 -2.25 4 60 4 true true 1908464 0 static fail 1 all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 all 8 false 3.5 true 1 1005 false 2.25 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6.5 6 all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 From f417921d7015a61c919faa4b0a57bf5758b1eade Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 20:13:14 -0500 Subject: [PATCH 18/23] Keep a typed host call's object and result in registers 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 20dc6367, 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 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 95 ++++++++++++++----- .../regression/CppiaHostMethodEntries/Main.hx | 5 + .../CppiaHostMethodEntries/Script.hx | 5 + .../CppiaHostMethodEntries/stdout.txt | 3 + 5 files changed, 85 insertions(+), 24 deletions(-) diff --git a/Changes.md b/Changes.md index f6097e2ab..64658b420 100644 --- a/Changes.md +++ b/Changes.md @@ -14,6 +14,7 @@ libhxcpp 6.1.0 (unreleased) * Host code calling a compiled cppia closure back through hx::callFunction, as Dynamic::operator() and Array.sort do in a scriptable build, takes a path that does only what that call needs: the arguments pushed, the captured variables copied and the result written in line, and the compiled code called. It shared one function with the general path, and called out to copy the captures, to write the result and to box it. Under the JIT, the host calling back a closure that takes and returns an Int is 15% faster (native_callback), 0.34x of HashLink 1.16's JIT, and sorting with a script comparator 10% (host_sort). Interpreted calls are level * Jitted cppia code calls a host instance method that takes up to three Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the object and the arguments in registers, in a scriptable build. It went through the method's script stub, which took the arguments from the script frame and wrote the result back there, by way of a helper that catches what the stub throws. Each instance method's Dynamic wrapper (HX_DEFINE_DYNAMIC_FUNC) now makes two entries: one calling the method virtually, as the stub does, and one calling the class's own, as the stub for a super call does, which a C++ class with pure virtual methods does not get. A scriptable class gives the runtime its methods' entries as it registers, and an entry leaves what the method throws for the script, as the helper does. Updating script objects through a host display object's properties, as BunnyMark's loop does, is 1.56x faster under the JIT (bunny_update), 0.77x of HashLink 1.16's JIT where it was 0.5x, and an OpenFL-shaped frame 7% faster (openfl_frame). Interpreted calls, methods with a String or more than three arguments, and code built against older headers take the stub as before. A scriptable host is larger by about 1.4% for the entries * Jitted cppia code calls a host static function that takes up to four Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the arguments in registers, in a scriptable build, whether the host gives the script a binding for it or the script calls it by name. Each static function's Dynamic wrapper registers the entry with the function's typed stub. Script-to-native calls are 1.26x faster under the JIT (native_call), ahead of HashLink 1.16's JIT, and calls by name 1.41x (call_by_name), 0.79x of HashLink's JIT where they were 0.56x +* Where every way a host call can go is a typed entry, jitted cppia code keeps the object and the result in registers: a call with no arguments evaluates its object straight into the register the entry takes it in, the result is converted from the register the entry gives it in, and the context's frame, which only a stub reads, is left alone. Each went through the script frame, and the object was read back from it twice. Updating script objects through a host display object's properties is a further 1.18x faster under the JIT (bunny_update), and script-to-native calls 1.17x (native_call) libhxcpp 6.0.3 ------------------------------------------------------------ diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index 4548cdb61..b98d5e1a0 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -2117,9 +2117,10 @@ struct CallHaxe : public CppiaExpr } // Calls a typed entry with this and the arguments, which are in the frame at - // framePos, in the registers their kinds take, and leaves the result in the - // frame there, where a stub leaves one - void genEntryCall(CppiaCompiler *compiler, void *inEntry, int framePos, bool inWithThis=true) + // framePos, in the registers their kinds take: this already in sJitTemp0 with + // inThisInReg. With inResultInFrame it leaves the result in the frame there, + // where a stub leaves one, and otherwise in the register the entry returns it in + void genEntryCall(CppiaCompiler *compiler, void *inEntry, int framePos, bool inWithThis=true, bool inThisInReg=false, bool inResultInFrame=true) { const char *sig = function.signature; int ints = 0; @@ -2131,7 +2132,10 @@ struct CallHaxe : public CppiaExpr if (inWithThis) { argTypes |= SLJIT_ARG_VALUE(SLJIT_ARG_TYPE_P, index++); - compiler->move(JitReg(SLJIT_R(ints++),jtPointer), JitFramePos(pos).as(jtPointer)); + if (inThisInReg) + ints++; + else + compiler->move(JitReg(SLJIT_R(ints++),jtPointer), JitFramePos(pos).as(jtPointer)); } pos += sizeof(hx::Object *); for(int a=1; sig[a]; a++) @@ -2163,6 +2167,8 @@ struct CallHaxe : public CppiaExpr default: argTypes |= SLJIT_ARG_RETURN(SLJIT_ARG_TYPE_RET_VOID); } compiler->callNativeArgs(inEntry, argTypes, ints, floats); + if (!inResultInFrame) + return; switch(sig[0]) { case sigInt: case sigBool: compiler->move(JitFramePos(framePos).as(jtInt), sJitReturnReg.as(jtInt)); break; @@ -2172,6 +2178,28 @@ struct CallHaxe : public CppiaExpr } } + // The result an entry left in its return register, converted as + // genFunctionResult converts one a stub left in the frame + void genEntryResult(CppiaCompiler *compiler, const JitVal &inDest, ExprType destType) + { + compiler->checkException(); + if (destType==etVoid || destType==etNull) + return; + switch(function.signature[0]) + { + case sigInt: case sigBool: + compiler->convert(sJitReturnReg.as(jtInt), etInt, inDest, destType, isBoolInt()); + break; + case sigFloat: + compiler->convert(sJitTempF0, etFloat, inDest, destType); + break; + case sigObject: + compiler->convert(sJitReturnReg.as(jtPointer), etObject, inDest, destType); + break; + default: ; + } + } + // Whether a typed entry can take this call: no String, and at most three // arguments, or four for a static, whose entry takes no object bool entryTakes() const @@ -2189,8 +2217,33 @@ struct CallHaxe : public CppiaExpr { int framePos = compiler->getCurrentFrameSize(); + void *func = (void *) ( isSuper ? function.superExecute : function.execute); + // The typed entry for the call as written: the host's own for a super call + bool entries = entryTakes(); + void *entry = !entries ? 0 : isStatic ? staticEntry : isSuper ? superEntry : virtualEntry; + + // The script class's objects are host objects of one C++ class, whose method + // checks the script vtable for an override before it runs the host's. An + // object of that class whose script classes do not override the method has + // the host's called directly, as a super call calls it + void *hostVTable = receiverClass && hostSlot>=0 ? receiverClass->getHaxeBaseVTable() : 0; + + // Where every way the call can go is a typed entry, no stub reads the frame: + // the context's frame stays as it is, the result stays in the register the + // entry gives it in, and with no arguments to evaluate first, this goes + // straight into the register the entry takes it in + bool onlyEntries = entry && (!hostVTable || superEntry); + bool thisInReg = onlyEntries && !isStatic && args.size()==0; + // Push this ... - if (thisExpr) + if (thisInReg) + { + if (thisExpr) + thisExpr->genCode(compiler, sJitTemp0.as(jtPointer), etObject); + else + compiler->move(sJitTemp0.as(jtPointer), sJitThis); + } + else if (thisExpr) thisExpr->genCode(compiler, JitFramePos(framePos), etObject); else if (isStatic) compiler->move(JitFramePos(framePos), (void *)0); @@ -2224,28 +2277,21 @@ struct CallHaxe : public CppiaExpr } compiler->restoreFrameSize(framePos); - // Store new frame in context ... - compiler->add( sJitCtxFrame, sJitFrame.as(jtPointer), JitVal(framePos) ); + // Store new frame in context, for a stub + if (!onlyEntries) + compiler->add( sJitCtxFrame, sJitFrame.as(jtPointer), JitVal(framePos) ); - void *func = (void *) ( isSuper ? function.superExecute : function.execute); - // The typed entry for the call as written: the host's own for a super call - bool entries = entryTakes(); - void *entry = entries ? (isSuper ? superEntry : virtualEntry) : 0; - - // The script class's objects are host objects of one C++ class, whose method - // checks the script vtable for an override before it runs the host's. An - // object of that class whose script classes do not override the method has - // the host's called directly, as a super call calls it - void *hostVTable = receiverClass && hostSlot>=0 ? receiverClass->getHaxeBaseVTable() : 0; if (hostVTable) { - compiler->move(sJitTemp0.as(jtPointer), JitFramePos(framePos).as(jtPointer)); + // this stays in sJitTemp0 on each way below + if (!thisInReg) + compiler->move(sJitTemp0.as(jtPointer), JitFramePos(framePos).as(jtPointer)); JumpId isNull = compiler->compare(cmpP_EQUAL, sJitTemp0.as(jtPointer), (void *)0); JumpId otherClass = compiler->compare(cmpP_NOT_EQUAL, sJitTemp0.star(jtPointer, 0), hostVTable); compiler->move(sJitTemp1.as(jtPointer), sJitTemp0.star(jtPointer, receiverClass->getScriptVTableOffset())); JumpId overridden = compiler->compare(cmpP_NOT_EQUAL, sJitTemp1.star(jtPointer, hostSlot*(int)sizeof(void *)), (void *)0); if (entries && superEntry) - genEntryCall(compiler, superEntry, framePos); + genEntryCall(compiler, superEntry, framePos, true, true, !onlyEntries); else compiler->callNative( (void *)tryCallHaxe, JitVal((void *)function.superExecute), sJitCtx ); JumpId called = compiler->jump(); @@ -2253,19 +2299,20 @@ struct CallHaxe : public CppiaExpr compiler->comeFrom(otherClass); compiler->comeFrom(overridden); if (entry) - genEntryCall(compiler, entry, framePos); + genEntryCall(compiler, entry, framePos, true, true, !onlyEntries); else compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); compiler->comeFrom(called); } - else if (isStatic && staticEntry && entries) - genEntryCall(compiler, staticEntry, framePos, false); else if (entry) - genEntryCall(compiler, entry, framePos); + genEntryCall(compiler, entry, framePos, !isStatic, thisInReg, !onlyEntries); else compiler->callNative( (void *)tryCallHaxe, JitVal(func), sJitCtx ); - genFunctionResult(compiler, inDest, destType, returnType, isBoolInt()); + if (onlyEntries) + genEntryResult(compiler, inDest, destType); + else + genFunctionResult(compiler, inDest, destType, returnType, isBoolInt()); } #endif diff --git a/test/regression/CppiaHostMethodEntries/Main.hx b/test/regression/CppiaHostMethodEntries/Main.hx index a81d0d2f6..4a76defa0 100644 --- a/test/regression/CppiaHostMethodEntries/Main.hx +++ b/test/regression/CppiaHostMethodEntries/Main.hx @@ -29,6 +29,10 @@ class CompiledScriptCalc extends HostCalc { public function new() { super(); } + + // Host methods called on this, without naming it + public function own():String + return ([getInt(), getFloat(), half(3), getBool(), getSelf() == this, mix(1, 0.5, true)] : Array).join(" "); } class CompiledOverCalc extends HostCalc { @@ -133,6 +137,7 @@ class Compiled { for (c in receivers) Sys.println('all ${all(c)}'); Sys.println('script type ${viaScript(new CompiledScriptCalc())}'); + Sys.println('own ${new CompiledScriptCalc().own()}'); Sys.println('override type ${viaOver(new CompiledOverCalc())}'); Sys.println('super type ${viaSuper(new CompiledSuperCalc())}'); diff --git a/test/regression/CppiaHostMethodEntries/Script.hx b/test/regression/CppiaHostMethodEntries/Script.hx index 98c66365e..02a9e9b8b 100644 --- a/test/regression/CppiaHostMethodEntries/Script.hx +++ b/test/regression/CppiaHostMethodEntries/Script.hx @@ -3,6 +3,10 @@ class ScriptCalc extends HostCalc { public function new() { super(); } + + // Host methods called on this, without naming it + public function own():String + return ([getInt(), getFloat(), half(3), getBool(), getSelf() == this, mix(1, 0.5, true)] : Array).join(" "); } class OverCalc extends HostCalc { @@ -107,6 +111,7 @@ class Script { for (c in receivers) Sys.println('all ${all(c)}'); Sys.println('script type ${viaScript(new ScriptCalc())}'); + Sys.println('own ${new ScriptCalc().own()}'); Sys.println('override type ${viaOver(new OverCalc())}'); Sys.println('super type ${viaSuper(new SuperCalc())}'); diff --git a/test/regression/CppiaHostMethodEntries/stdout.txt b/test/regression/CppiaHostMethodEntries/stdout.txt index 519d1eb18..4116741b3 100644 --- a/test/regression/CppiaHostMethodEntries/stdout.txt +++ b/test/regression/CppiaHostMethodEntries/stdout.txt @@ -6,6 +6,7 @@ all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 all 8 false 3.5 true 1 55 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 99 6 all 80 false 3.5 true 1 6 false 5.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 script type 8 6 4.5 3.25 123 4 4 +own 7 2.5 1.5 true true 1.5 override type 7 55 4.5 99 4 super type 70 6 5.5 loop 499995000 1.3333333333333333 @@ -20,6 +21,7 @@ all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 all 8 false 3.5 true 1 55 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 99 6 all 80 false 3.5 true 1 6 false 5.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 script type 8 6 4.5 3.25 123 4 4 +own 7 2.5 1.5 true true 1.5 override type 7 55 4.5 99 4 super type 70 6 5.5 loop 499995000 1.3333333333333333 @@ -34,6 +36,7 @@ all 8 false 3.5 true 1 6 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 all 8 false 3.5 true 1 55 false 4.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 99 6 all 80 false 3.5 true 1 6 false 5.5 3.25 2.75 123 30 3 -1 6 0 1.5 -1 4 -1 2.5 25 6 6 script type 8 6 4.5 3.25 123 4 4 +own 7 2.5 1.5 true true 1.5 override type 7 55 4.5 99 4 super type 70 6 5.5 loop 499995000 1.3333333333333333 From 12ed1b397e03b247e71527548c7a213c9aa981d1 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 20:39:25 -0500 Subject: [PATCH 19/23] Box Ints and Floats with the allocator's fast path in line 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 f417921d, 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 --- Changes.md | 1 + include/hx/GC.h | 14 +++++ src/Dynamic.cpp | 32 ++++++++-- .../regression/CppiaDynamicBoxes/HostBoxes.hx | 32 ++++++++++ test/regression/CppiaDynamicBoxes/Main.hx | 60 +++++++++++++++++++ test/regression/CppiaDynamicBoxes/Script.hx | 37 ++++++++++++ test/regression/CppiaDynamicBoxes/build.hxml | 9 +++ test/regression/CppiaDynamicBoxes/stdout.txt | 21 +++++++ test/regression/emscripten-skip.txt | 1 + 9 files changed, 201 insertions(+), 6 deletions(-) create mode 100644 test/regression/CppiaDynamicBoxes/HostBoxes.hx create mode 100644 test/regression/CppiaDynamicBoxes/Main.hx create mode 100644 test/regression/CppiaDynamicBoxes/Script.hx create mode 100644 test/regression/CppiaDynamicBoxes/build.hxml create mode 100644 test/regression/CppiaDynamicBoxes/stdout.txt diff --git a/Changes.md b/Changes.md index 64658b420..7414ab166 100644 --- a/Changes.md +++ b/Changes.md @@ -15,6 +15,7 @@ libhxcpp 6.1.0 (unreleased) * Jitted cppia code calls a host instance method that takes up to three Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the object and the arguments in registers, in a scriptable build. It went through the method's script stub, which took the arguments from the script frame and wrote the result back there, by way of a helper that catches what the stub throws. Each instance method's Dynamic wrapper (HX_DEFINE_DYNAMIC_FUNC) now makes two entries: one calling the method virtually, as the stub does, and one calling the class's own, as the stub for a super call does, which a C++ class with pure virtual methods does not get. A scriptable class gives the runtime its methods' entries as it registers, and an entry leaves what the method throws for the script, as the helper does. Updating script objects through a host display object's properties, as BunnyMark's loop does, is 1.56x faster under the JIT (bunny_update), 0.77x of HashLink 1.16's JIT where it was 0.5x, and an OpenFL-shaped frame 7% faster (openfl_frame). Interpreted calls, methods with a String or more than three arguments, and code built against older headers take the stub as before. A scriptable host is larger by about 1.4% for the entries * Jitted cppia code calls a host static function that takes up to four Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the arguments in registers, in a scriptable build, whether the host gives the script a binding for it or the script calls it by name. Each static function's Dynamic wrapper registers the entry with the function's typed stub. Script-to-native calls are 1.26x faster under the JIT (native_call), ahead of HashLink 1.16's JIT, and calls by name 1.41x (call_by_name), 0.79x of HashLink's JIT where they were 0.56x * Where every way a host call can go is a typed entry, jitted cppia code keeps the object and the result in registers: a call with no arguments evaluates its object straight into the register the entry takes it in, the result is converted from the register the entry gives it in, and the context's frame, which only a stub reads, is left alone. Each went through the script frame, and the object was read back from it twice. Updating script objects through a host display object's properties is a further 1.18x faster under the JIT (bunny_update), and script-to-native calls 1.17x (native_call) +* An Int or a Float that a Dynamic holds is boxed with the allocator's fast path in line, where new reached it through calls the compiler left out of line, and Ints from -1 to 1023, not 255, share boxes made once. A whole Float still boxes as an Int from -1 to 255 only, so Type.typeof and Std.isOfType see the same types. The host calling back a script closure that returns an Int is 1.18x faster under the JIT and 1.08x interpreted (native_callback, whose results run from 0 to 2046, so about half are shared boxes). Every boxed Int and Float in Haxe 4 code takes the shorter path libhxcpp 6.0.3 ------------------------------------------------------------ diff --git a/include/hx/GC.h b/include/hx/GC.h index 8ca82ae6a..4cb199989 100644 --- a/include/hx/GC.h +++ b/include/hx/GC.h @@ -444,6 +444,20 @@ class ImmixAllocator // These allocate the function using the garbage-collected malloc inline static void *alloc(ImmixAllocator *alloc, size_t inSize, bool inContainer, const char *inName ) + { + return allocInline(alloc, inSize, inContainer, inName); + } + + // alloc, always in line, for the runtime's own allocations that are made most, + // such as the box of an Int or a Float, which a compiler left calls deep otherwise + #if defined(_MSC_VER) + __forceinline + #elif defined(__GNUC__) || defined(__clang__) + inline __attribute__((always_inline)) + #else + inline + #endif + static void *allocInline(ImmixAllocator *alloc, size_t inSize, bool inContainer, const char *inName ) { if (inSize > IMMIX_MAX_BLOCK_OBJECT_SIZE) return InternalNew(inSize, inContainer); diff --git a/src/Dynamic.cpp b/src/Dynamic.cpp index 5ac1c100a..b3e50f0d8 100644 --- a/src/Dynamic.cpp +++ b/src/Dynamic.cpp @@ -3,6 +3,7 @@ #include #include #include +#include using namespace hx; @@ -360,11 +361,13 @@ Dynamic CreateDynamicStruct(const void *inValue, int inSize, DynamicHandlerFunc // --- Dynamic ------------------------------------------------- -// Boxed values from -1 to 255, made once and shared by every thread. A slot is +// Boxed Ints from -1 to 1023 (whole Floats and Int64s to 255), made once and shared by every thread. A slot is // published with a release and read with an acquire, so a thread that finds a // box also sees it built. Two threads may both make one: the first is kept, and // the other is a small constant allocation that is never used. -static std::atomic sConstDynamicInts[256+1]; +// Ints from -1 to below this are boxed once and shared +enum { sConstIntEnd = 1024 }; +static std::atomic sConstDynamicInts[sConstIntEnd+1]; static std::atomic sConstDynamicInt64s[256+1]; template @@ -385,11 +388,26 @@ static hx::Object *fromSmallInt64(int inVal) return constBox(sConstDynamicInt64s[inVal+1], inVal); } -static hx::Object *fromInt(int inVal) +// A new box for an Int or a Float, made with the allocator's fast path in line, as +// generated code makes one for every such value a Dynamic holds. new reaches it +// through calls the compiler need not inline +template +static inline hx::Object *newBox(VALUE inValue, const char *inName) { - if (inVal>=-1 && inVal<256) + hx::ImmixAllocator *alloc = HX_CTX_GET; + #ifdef HXCPP_DEBUG + if (!alloc) + hx::BadImmixAlloc(); + #endif + void *memory = hx::ImmixAllocator::allocInline(alloc, sizeof(DATA), false, inName); + return ::new (memory) DATA(inValue); +} + +static inline hx::Object *fromInt(int inVal) +{ + if (inVal>=-1 && inVal(sConstDynamicInts[inVal+1], inVal); - return (hx::Object *)new IntData(inVal); + return newBox(inVal, "Int"); } Dynamic::Dynamic(bool inVal) : super( inVal ? hx::DynTrue.mPtr : hx::DynFalse.mPtr ) { } @@ -450,12 +468,14 @@ Dynamic::Dynamic(char32_t inVal) Dynamic::Dynamic(double inVal) { + // A whole Float boxes as an Int from -1 to 255 only, as it always has, since + // Type.typeof and Std.isOfType tell the two boxes apart if ( inVal>=-1 && inVal<256 && (int)inVal==inVal && !(inVal==0 && signbit(inVal)) ) { mPtr = constBox(sConstDynamicInts[(int)inVal+1], (int)inVal); } else - mPtr = (hx::Object *)new DoubleData(inVal); + mPtr = newBox(inVal, "Float"); } diff --git a/test/regression/CppiaDynamicBoxes/HostBoxes.hx b/test/regression/CppiaDynamicBoxes/HostBoxes.hx new file mode 100644 index 000000000..02c96a995 --- /dev/null +++ b/test/regression/CppiaDynamicBoxes/HostBoxes.hx @@ -0,0 +1,32 @@ +// Host code that holds the results of a script's callbacks as Dynamic values, +// compiled into the host for the script to pass its closures to +class HostBoxes { + public static function describe(d:Dynamic):String + return '${Type.typeof(d)} ${Std.isOfType(d, Int)} ${Std.isOfType(d, Float)} $d'; + + public static function ints(values:Array, f:Int->Int):String { + var out = []; + for (v in values) { + var d:Dynamic = f(v); + out.push(describe(d)); + } + return out.join(", "); + } + + public static function floats(values:Array, f:Float->Float):String { + var out = []; + for (v in values) { + var d:Dynamic = f(v); + out.push(describe(d)); + } + return out.join(", "); + } + + // Many results added up, through the boxes the host holds them in + public static function sum(count:Int, f:Int->Int):Float { + var total = 0.0; + for (i in 0...count) + total += f(i); + return total; + } +} diff --git a/test/regression/CppiaDynamicBoxes/Main.hx b/test/regression/CppiaDynamicBoxes/Main.hx new file mode 100644 index 000000000..939d8f0ef --- /dev/null +++ b/test/regression/CppiaDynamicBoxes/Main.hx @@ -0,0 +1,60 @@ +// An Int or a Float a Dynamic holds is boxed: Ints from -1 to 1023, and whole +// Floats from -1 to 255, in boxes made once and shared, the rest in new ones, +// which the runtime allocates in line. A whole Float outside that range keeps a +// Float box, so Type.typeof and Std.isOfType see the same types as before. The +// results of a script's callbacks as the host holds them, and values the script +// boxes itself, on each side of each edge, kept through a collection. +// The same values run compiled into the host, then as a script with the JIT off +// and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same values as Script.hx, compiled into the host +class Compiled { + public static function run() { + var ints = [-2, -1, 0, 1, 255, 256, 1000, 1023, 1024, 1025, 70000, -70000, 0x7fffffff]; + var floats = [-1.0, 0.0, -0.0, 0.5, 255.0, 256.0, 300.0, 1023.0, 1024.0, -2.0, 1e300]; + + Sys.println('host ints ${HostBoxes.ints(ints, x -> x)}'); + Sys.println('host floats ${HostBoxes.floats(floats, x -> x)}'); + + var out = []; + for (i in ints) { + var d:Dynamic = i; + out.push(HostBoxes.describe(d)); + } + Sys.println('script ints ${out.join(", ")}'); + out = []; + for (f in floats) { + var d:Dynamic = f; + out.push(HostBoxes.describe(d)); + } + Sys.println('script floats ${out.join(", ")}'); + + // Shared boxes and new ones, kept through a collection + var kept:Array = [for (i in 0...6000) i - 1000]; + var floatsKept:Array = [for (i in 0...3000) i * 0.5]; + cpp.vm.Gc.run(true); + var t = 0.0; + for (d in kept) + t += d; + for (d in floatsKept) + t += d; + Sys.println('kept $t ${kept[0]} ${kept[1500]} ${kept[5999]} ${floatsKept[2999]}'); + + var bias = 0; + Sys.println('sum ${HostBoxes.sum(5000, x -> (x * 7 + bias++) % 3000 - 500)}'); + } +} diff --git a/test/regression/CppiaDynamicBoxes/Script.hx b/test/regression/CppiaDynamicBoxes/Script.hx new file mode 100644 index 000000000..82ac60407 --- /dev/null +++ b/test/regression/CppiaDynamicBoxes/Script.hx @@ -0,0 +1,37 @@ +// The same cases as Compiled in Main.hx, run as a script +class Script { + static function main() { + var ints = [-2, -1, 0, 1, 255, 256, 1000, 1023, 1024, 1025, 70000, -70000, 0x7fffffff]; + var floats = [-1.0, 0.0, -0.0, 0.5, 255.0, 256.0, 300.0, 1023.0, 1024.0, -2.0, 1e300]; + + Sys.println('host ints ${HostBoxes.ints(ints, x -> x)}'); + Sys.println('host floats ${HostBoxes.floats(floats, x -> x)}'); + + var out = []; + for (i in ints) { + var d:Dynamic = i; + out.push(HostBoxes.describe(d)); + } + Sys.println('script ints ${out.join(", ")}'); + out = []; + for (f in floats) { + var d:Dynamic = f; + out.push(HostBoxes.describe(d)); + } + Sys.println('script floats ${out.join(", ")}'); + + // Shared boxes and new ones, kept through a collection + var kept:Array = [for (i in 0...6000) i - 1000]; + var floatsKept:Array = [for (i in 0...3000) i * 0.5]; + cpp.vm.Gc.run(true); + var t = 0.0; + for (d in kept) + t += d; + for (d in floatsKept) + t += d; + Sys.println('kept $t ${kept[0]} ${kept[1500]} ${kept[5999]} ${floatsKept[2999]}'); + + var bias = 0; + Sys.println('sum ${HostBoxes.sum(5000, x -> (x * 7 + bias++) % 3000 - 500)}'); + } +} diff --git a/test/regression/CppiaDynamicBoxes/build.hxml b/test/regression/CppiaDynamicBoxes/build.hxml new file mode 100644 index 000000000..850bcd4ce --- /dev/null +++ b/test/regression/CppiaDynamicBoxes/build.hxml @@ -0,0 +1,9 @@ +--main Main +-cpp bin +-D scriptable +--dce no +-D dll_export=bin/host_classes.info +--next +--main Script +-cppia bin/script.cppia +-D dll_import=bin/host_classes.info diff --git a/test/regression/CppiaDynamicBoxes/stdout.txt b/test/regression/CppiaDynamicBoxes/stdout.txt new file mode 100644 index 000000000..3f20f2b60 --- /dev/null +++ b/test/regression/CppiaDynamicBoxes/stdout.txt @@ -0,0 +1,21 @@ +-- compiled +host ints TInt true true -2, TInt true true -1, TInt true true 0, TInt true true 1, TInt true true 255, TInt true true 256, TInt true true 1000, TInt true true 1023, TInt true true 1024, TInt true true 1025, TInt true true 70000, TInt true true -70000, TInt true true 2147483647 +host floats TInt true true -1, TInt true true 0, TFloat true true -0, TFloat false true 0.5, TInt true true 255, TFloat true true 256, TFloat true true 300, TFloat true true 1023, TFloat true true 1024, TFloat true true -2, TFloat false true 1e+300 +script ints TInt true true -2, TInt true true -1, TInt true true 0, TInt true true 1, TInt true true 255, TInt true true 256, TInt true true 1000, TInt true true 1023, TInt true true 1024, TInt true true 1025, TInt true true 70000, TInt true true -70000, TInt true true 2147483647 +script floats TInt true true -1, TInt true true 0, TFloat true true -0, TFloat false true 0.5, TInt true true 255, TFloat true true 256, TFloat true true 300, TFloat true true 1023, TFloat true true 1024, TFloat true true -2, TFloat false true 1e+300 +kept 14246250 -1000 500 4999 1499.5 +sum 4855000 +-- script, JIT off +host ints TInt true true -2, TInt true true -1, TInt true true 0, TInt true true 1, TInt true true 255, TInt true true 256, TInt true true 1000, TInt true true 1023, TInt true true 1024, TInt true true 1025, TInt true true 70000, TInt true true -70000, TInt true true 2147483647 +host floats TInt true true -1, TInt true true 0, TFloat true true -0, TFloat false true 0.5, TInt true true 255, TFloat true true 256, TFloat true true 300, TFloat true true 1023, TFloat true true 1024, TFloat true true -2, TFloat false true 1e+300 +script ints TInt true true -2, TInt true true -1, TInt true true 0, TInt true true 1, TInt true true 255, TInt true true 256, TInt true true 1000, TInt true true 1023, TInt true true 1024, TInt true true 1025, TInt true true 70000, TInt true true -70000, TInt true true 2147483647 +script floats TInt true true -1, TInt true true 0, TFloat true true -0, TFloat false true 0.5, TInt true true 255, TFloat true true 256, TFloat true true 300, TFloat true true 1023, TFloat true true 1024, TFloat true true -2, TFloat false true 1e+300 +kept 14246250 -1000 500 4999 1499.5 +sum 4855000 +-- script, JIT on +host ints TInt true true -2, TInt true true -1, TInt true true 0, TInt true true 1, TInt true true 255, TInt true true 256, TInt true true 1000, TInt true true 1023, TInt true true 1024, TInt true true 1025, TInt true true 70000, TInt true true -70000, TInt true true 2147483647 +host floats TInt true true -1, TInt true true 0, TFloat true true -0, TFloat false true 0.5, TInt true true 255, TFloat true true 256, TFloat true true 300, TFloat true true 1023, TFloat true true 1024, TFloat true true -2, TFloat false true 1e+300 +script ints TInt true true -2, TInt true true -1, TInt true true 0, TInt true true 1, TInt true true 255, TInt true true 256, TInt true true 1000, TInt true true 1023, TInt true true 1024, TInt true true 1025, TInt true true 70000, TInt true true -70000, TInt true true 2147483647 +script floats TInt true true -1, TInt true true 0, TFloat true true -0, TFloat false true 0.5, TInt true true 255, TFloat true true 256, TFloat true true 300, TFloat true true 1023, TFloat true true 1024, TFloat true true -2, TFloat false true 1e+300 +kept 14246250 -1000 500 4999 1499.5 +sum 4855000 diff --git a/test/regression/emscripten-skip.txt b/test/regression/emscripten-skip.txt index d994b8d1d..516eb0eb9 100644 --- a/test/regression/emscripten-skip.txt +++ b/test/regression/emscripten-skip.txt @@ -21,6 +21,7 @@ CppiaAdoptLayouts: compares the cppia JIT, which Emscripten has not CppiaArrayAccess: its host is the first --next section, which -D emscripten does not reach CppiaBreakpoints: threads CppiaClosureCaptures: its host is the first --next section, which -D emscripten does not reach +CppiaDynamicBoxes: its host is the first --next section, which -D emscripten does not reach CppiaHostArgs: processes CppiaHostClosureCalls: its host is the first --next section, which -D emscripten does not reach CppiaHostFunctionOrder: its host is the first --next section, which -D emscripten does not reach From ce4bc1a75abf42f69a9604f556de69f604e30c9a Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 20:35:56 -0500 Subject: [PATCH 20/23] Check and enter a cppia closure in line from jitted code 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 6862d3ed, 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 --- Changes.md | 1 + src/hx/cppia/Cppia.cpp | 15 +- src/hx/cppia/Cppia.h | 26 +- src/hx/cppia/CppiaFunction.cpp | 106 ++++++- test/regression/CppiaJitClosureEntry/Main.hx | 295 ++++++++++++++++++ .../regression/CppiaJitClosureEntry/Script.hx | 268 ++++++++++++++++ .../CppiaJitClosureEntry/build.hxml | 7 + .../CppiaJitClosureEntry/stdout.txt | 45 +++ .../CppiaJitClosureEntryDebugger/build.hxml | 10 + .../CppiaJitClosureEntryDebugger/stdout.txt | 45 +++ 10 files changed, 792 insertions(+), 26 deletions(-) create mode 100644 test/regression/CppiaJitClosureEntry/Main.hx create mode 100644 test/regression/CppiaJitClosureEntry/Script.hx create mode 100644 test/regression/CppiaJitClosureEntry/build.hxml create mode 100644 test/regression/CppiaJitClosureEntry/stdout.txt create mode 100644 test/regression/CppiaJitClosureEntryDebugger/build.hxml create mode 100644 test/regression/CppiaJitClosureEntryDebugger/stdout.txt diff --git a/Changes.md b/Changes.md index 7414ab166..a90f64e75 100644 --- a/Changes.md +++ b/Changes.md @@ -16,6 +16,7 @@ libhxcpp 6.1.0 (unreleased) * Jitted cppia code calls a host static function that takes up to four Ints, Bools, Floats or objects, and gives one of those or nothing, through a typed entry that takes the arguments in registers, in a scriptable build, whether the host gives the script a binding for it or the script calls it by name. Each static function's Dynamic wrapper registers the entry with the function's typed stub. Script-to-native calls are 1.26x faster under the JIT (native_call), ahead of HashLink 1.16's JIT, and calls by name 1.41x (call_by_name), 0.79x of HashLink's JIT where they were 0.56x * Where every way a host call can go is a typed entry, jitted cppia code keeps the object and the result in registers: a call with no arguments evaluates its object straight into the register the entry takes it in, the result is converted from the register the entry gives it in, and the context's frame, which only a stub reads, is left alone. Each went through the script frame, and the object was read back from it twice. Updating script objects through a host display object's properties is a further 1.18x faster under the JIT (bunny_update), and script-to-native calls 1.17x (native_call) * An Int or a Float that a Dynamic holds is boxed with the allocator's fast path in line, where new reached it through calls the compiler left out of line, and Ints from -1 to 1023, not 255, share boxes made once. A whole Float still boxes as an Int from -1 to 255 only, so Type.typeof and Std.isOfType see the same types. The host calling back a script closure that returns an Int is 1.18x faster under the JIT and 1.08x interpreted (native_callback, whose results run from 0 to 2046, so about half are shared boxes). Every boxed Int and Float in Haxe 4 code takes the shorter path +* Jitted cppia code calling a script closure checks in line that the value is one, that its function takes the arguments and gives the result as the call has them, that the function is compiled and that its frame fits the stack, and puts this and the captured variables into the frame in line, a word or 4 bytes at a time from a list of moves the function keeps, before it calls the compiled code. It called a helper for all of that on every call, and the native call was most of what the helper cost. Jitted code calling a closure that captures a variable is 10% faster (closure_call). Calls from host code and interpreted calls are level libhxcpp 6.0.3 ------------------------------------------------------------ diff --git a/src/hx/cppia/Cppia.cpp b/src/hx/cppia/Cppia.cpp index b98d5e1a0..435f7ceee 100644 --- a/src/hx/cppia/Cppia.cpp +++ b/src/hx/cppia/Cppia.cpp @@ -4086,21 +4086,22 @@ struct Call : public CppiaDynamicExpr // restore frame size } - compiler->add(sJitCtxFrame, sJitFrame, compiler->getCurrentFrameSize()); + int framePos = compiler->getCurrentFrameSize(); + compiler->add(sJitCtxFrame, sJitFrame, framePos); ExprType resultType = destType==etNull ? etVoid : destType; // A script closure whose function takes these arguments, and gives the result // wanted, as they are, and is compiled, is called as a direct call calls, - // with its result where the general way leaves one + // with its result where the general way leaves one. The checks and the copy + // of its captured variables are in line, so the call makes no other + std::vector general; int signature = internCallSignature(resultType==etVoid ? argSignature : argSignature + callReturnCode(resultType)); - compiler->callNative((void *)enterScriptClosure, sJitCtx, functionObject, JitVal(signature)); - compiler->move(sJitTemp1.as(jtPointer), sJitReturnReg.as(jtPointer)); - JumpId general = compiler->compare(cmpP_EQUAL, sJitTemp1.as(jtPointer), (void *)0); - compiler->call(sJitTemp1, sJitCtx); + genScriptClosureCall(compiler, functionObject, framePos, signature, resultType!=etVoid, general); compiler->setMaxPointer(); JumpId called = compiler->jump(); - compiler->comeFrom(general); + for(int i=0;icomeFrom(general[i]); void *helper = 0; switch(resultType) diff --git a/src/hx/cppia/Cppia.h b/src/hx/cppia/Cppia.h index 60f9268de..b56eda4f6 100644 --- a/src/hx/cppia/Cppia.h +++ b/src/hx/cppia/Cppia.h @@ -338,6 +338,20 @@ struct ScriptCallable : public CppiaDynamicExpr int size; }; std::vector captureCopies; + #ifdef CPPIA_JIT + // The copies a call makes, for jitted code calling a closure of this function + // to make in line: the moves of a word that each capture takes, then the + // moves of the 4 bytes some captures have past their last word, each of the + // two parts ended by a move with a stackPos of -1. jitCaptureMoveList is the + // first move, which jitted code reads + struct JitCaptureMove + { + int stackPos; + int capturePos; + }; + std::vector jitCaptureMoves; + const JitCaptureMove *jitCaptureMoveList; + #endif // What jitted code calling a closure of this function compares, interned by // internCallSignature: the arguments' types, and those with the return type. @@ -447,10 +461,14 @@ int internCallSignature(const std::string &inSignature); // The letter a call signature ends with for a function returning inType char callReturnCode(ExprType inType); #ifdef CPPIA_JIT -// The compiled code of the script closure inFunction, with its this and captured -// variables written to the frame at ctx->frame, when its function's signature is -// inSignature and its frame fits the stack; 0 when the call must go the general way -CppiaFunc enterScriptClosure(CppiaCtx *ctx, hx::Object *inFunction, int inSignature); +// Emits a call of the script closure in inClosure, a temporary, as a call of its +// compiled code, when its function's signature is inSignature, compared with its +// full signature when inReturns and its arguments' otherwise, its code is compiled +// and its frame, at inFramePos in this one and already in ctx->frame, fits the +// stack. Its this and captured variables go into that frame first. Each jump to +// where the call must go the general way instead is added to outGeneral +void genScriptClosureCall(CppiaCompiler *compiler, const JitVal &inClosure, int inFramePos, + int inSignature, bool inReturns, std::vector &outGeneral); #endif CppiaClassInfo *getScriptClassInfo(hx::Object *inClass); hx::Object *createEnumClosure(struct CppiaEnumConstructor &inContructor); diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index 2376488e3..91534ea79 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -11,6 +11,11 @@ namespace hx static int sTypeSize[] = { 0, 0, sizeof(hx::Object *), sizeof(String), sizeof(Float), sizeof(int) }; +#ifdef CPPIA_JIT +// The moves of a function that captures nothing, which one not linked has too +static const ScriptCallable::JitCaptureMove sNoCaptureMoves[] = { { -1, 0 }, { -1, 0 } }; +#endif + // --- ScriptCallable ---------------------------------------------------- String sInvalidArgCount = HX_CSTRING("Invalid arguement count"); @@ -43,6 +48,7 @@ ScriptCallable::ScriptCallable(CppiaStream &stream) compiled = 0; ownsCompiled = false; lazy = false; + jitCaptureMoveList = sNoCaptureMoves; #endif for(int a=0;aexecute; ownsCompiled = false; lazy = false; + jitCaptureMoveList = sNoCaptureMoves; #endif } @@ -233,6 +241,31 @@ CppiaExpr *ScriptCallable::link(CppiaModule &inModule) captureCopies.push_back(copy); } + #ifdef CPPIA_JIT + // Every size is a whole number of 4 bytes, so a capture's words, and on 64 + // bits the 4 bytes some have past them, move all of it + jitCaptureMoves.clear(); + for(int part=0;part<2;part++) + { + for(int i=0;i &outGeneral) { - if (!inFunction || *(void **)inFunction!=hx::gScriptClosureVTable) - return 0; - CppiaClosure *closure = (CppiaClosure *)inFunction; - ScriptCallable *function = closure->function; - if (function->callSigFull!=inSignature && function->callSigArgs!=inSignature) - return 0; + typedef ScriptCallable::JitCaptureMove Move; + JitReg closure = sJitTemp1; + JitReg function = sJitTemp2; + + // A CppiaClosure, told by its vtable as scriptClosureTarget tells it. A call + // that wants no result has the signature of the arguments alone, which only + // callSigArgs can be, and any other has a return type, which only callSigFull + // can have + compiler->move(closure.as(jtPointer), inClosure); + outGeneral.push_back( compiler->compare(cmpP_EQUAL, closure.as(jtPointer), (void *)0) ); + outGeneral.push_back( compiler->compare(cmpP_NOT_EQUAL, closure.star(jtPointer), JitVal(hx::gScriptClosureVTable)) ); + compiler->move(function.as(jtPointer), closure.star(jtPointer, offsetof(CppiaClosure,function))); + int signature = inReturns ? offsetof(ScriptCallable,callSigFull) : offsetof(ScriptCallable,callSigArgs); + outGeneral.push_back( compiler->compare(cmpI_NOT_EQUAL, function.star(jtInt, signature), JitVal(inSignature)) ); + // Not compiled yet, it compiles on the general way. Its captured variables go - // past the arguments, which the caller's frame made room for, so the whole - // frame must fit before the function's own check of the stack - CppiaFunc code = function->getCompiled(); - unsigned char *frame = ctx->frame; - if (!code || frame + function->stackSize > ctx->stackEnd) - return 0; - closure->enterFrame(frame); - return code; + // past the arguments, which this frame made room for, so the whole frame must + // fit before the function's own check of the stack + JitTemp code(compiler, jtPointer); + compiler->move(sJitTemp0.as(jtPointer), function.star(jtPointer, offsetof(ScriptCallable,compiled))); + outGeneral.push_back( compiler->compare(cmpP_EQUAL, sJitTemp0.as(jtPointer), (void *)0) ); + compiler->move(code, sJitTemp0.as(jtPointer)); + compiler->move(sJitTemp0.as(jtInt), function.star(jtInt, offsetof(ScriptCallable,stackSize))); + compiler->add(sJitTemp0.as(jtPointer), sJitTemp0.as(jtPointer), sJitCtxFrame); + outGeneral.push_back( compiler->compare(cmpP_GREATER, sJitTemp0.as(jtPointer), + sJitCtx.star(jtPointer, offsetof(CppiaCtx,stackEnd))) ); + + // What enterFrame writes: this, then each capture by its moves, a word at a + // time and then the 4 bytes past the words, from the closure to the frame + int captures = (int)sizeof(CppiaClosure); + compiler->move(JitFramePos(inFramePos, jtPointer), closure.star(jtPointer, captures)); + JitReg move = sJitTemp2; + compiler->move(move.as(jtPointer), function.star(jtPointer, offsetof(ScriptCallable,jitCaptureMoveList))); + for(int part=0; part<2; part++) + { + JitType type = part==0 ? jtPointer : jtInt; + if (part==1) + { + // On 32 bits a word is 4 bytes, and the second part is always empty + if (sizeof(void *)==sizeof(int)) + break; + // Past the end of the first part + compiler->add(move.as(jtPointer), move.as(jtPointer), JitVal((int)sizeof(Move))); + } + JumpId none = compiler->compare(cmpI_EQUAL, move.star(jtInt, offsetof(Move,stackPos)), JitVal(-1)); + LabelId next = compiler->addLabel(); + compiler->move(sJitTemp0.as(jtInt), move.star(jtInt, offsetof(Move,capturePos))); + compiler->add(sJitTemp0.as(jtPointer), sJitTemp0.as(jtPointer), inClosure); + compiler->move(sJitTemp1.as(jtInt), move.star(jtInt, offsetof(Move,stackPos))); + compiler->add(sJitTemp1.as(jtPointer), sJitTemp1.as(jtPointer), sJitFrame); + compiler->move(sJitTemp1.star(type, inFramePos), sJitTemp0.star(type, captures)); + compiler->add(move.as(jtPointer), move.as(jtPointer), JitVal((int)sizeof(Move))); + compiler->compare(cmpI_NOT_EQUAL, move.star(jtInt, offsetof(Move,stackPos)), JitVal(-1), next); + compiler->comeFrom(none); + } + + compiler->call(code, sJitCtx); } #endif diff --git a/test/regression/CppiaJitClosureEntry/Main.hx b/test/regression/CppiaJitClosureEntry/Main.hx new file mode 100644 index 000000000..f0be67e27 --- /dev/null +++ b/test/regression/CppiaJitClosureEntry/Main.hx @@ -0,0 +1,295 @@ +// Under the JIT, a script calling one of its closures whose function takes the +// arguments and gives the result as they are checks that in line, and writes +// this and the captured variables into the frame in line, a word or 4 bytes at a +// time from a list the function keeps, before calling its code, where it called a +// helper that did all of it. Anything else still goes the general way: null, +// another kind of function, other types, a function not compiled yet, a frame +// that does not fit the stack. +// The same cases run as compiled code, then as a script with the JIT off and on, +// and print the same lines each time. Each script run has a new script stack, +// of 1 MB and then 2 MB, of which 128 KB is committed at first, so that the +// deepest recursion commits more. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + untyped __global__.__scriptable_cppia_set_stack_size((jit ? 2 : 1) * 1024 * 1024); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same cases as Script.hx, compiled into the host +class CompiledHolder { + public var base:Int; + public var name:String; + public var callback:Int->Int; + + public function new(base:Int, name:String) { + this.base = base; + this.name = name; + var shift = 3; + callback = x -> x + shift + this.base; + } + + public function add(x:Int):Int { + base += x; + return base; + } + + // this, an Int and a String, in a closure of a method + public function maker(step:Int, tag:String):Int->Int { + return x -> x * step + base + tag.length + name.length; + } +} + +class Compiled { + static function twice(x:Int):Int + return x * 2; + + // One capture of each kind and size, none, an Int, a Bool, a Float, a String + // and objects, all called through one call site + static function sizes():ArrayString> { + var i = 7; + var b = true; + var f = 2.5; + var s = "str"; + var a = [4, 5, 6]; + var d:Dynamic = "dyn"; + var h = new CompiledHolder(1, "h"); + return [ + x -> "none " + x, + x -> "int " + (x + i), + x -> "bool " + (b && x % 2 == 0), + x -> "float " + (x * f), + x -> "string " + s + x, + x -> "array " + a[x % 3], + x -> "dynamic " + d + x, + x -> "object " + (h.base + x), + ]; + } + + // Ints between wider captures, so the closure has whole words and 4 bytes to + // move, with an argument of each kind that the captures go after + static function mixed(n:Int):(Int, Float, String, Dynamic) -> String { + var i1 = n, s1 = "m" + n, i2 = n + 1, f1 = n * 0.5, i3 = n + 2, o1 = [n], i4 = n + 3; + return (a:Int, b:Float, c:String, d:Dynamic) -> { + var local = a * 10; + return '$local $b $c $d $i1 $s1 $i2 $f1 $i3 ${o1[0]} $i4'; + }; + } + + // Only Ints, which on 64 bits are no whole words + static function intsOnly(n:Int):Int->Int { + var a = n, b = n * 2, c = n * 3; + return x -> x + a + b * 10 + c * 100; + } + + // Only whole words + static function wordsOnly(n:Int):Int->String { + var s = "w" + n, f = n * 1.5, o = [n, n]; + return x -> s + (f + x) + o.length; + } + + // A closure with a small frame calling one with a large one, twelve Strings + // captured and twenty-four of its own, which calls it back. The large frames + // pass where the script stack was first committed to well before the + // deepest, so a call from a small frame finds no room for the large one and + // goes the general way, which commits more + static function deep():Int->Int { + var c0 = "a", c1 = "bb", c2 = "c", c3 = "dd", c4 = "e", c5 = "ff"; + var c6 = "g", c7 = "hh", c8 = "i", c9 = "jj", c10 = "k", c11 = "ll"; + var large:Int->Int = null; + var small = n -> { + var r:Int = large(n); + return r; + }; + large = n -> { + if (n == 0) + return 0; + var l0 = c0 + n, l1 = c1 + n, l2 = c2 + n, l3 = c3 + n, l4 = c4 + n, l5 = c5 + n; + var l6 = c6 + n, l7 = c7 + n, l8 = c8 + n, l9 = c9 + n, l10 = c10 + n, l11 = c11 + n; + var m0 = l0 + c0, m1 = l1 + c1, m2 = l2 + c2, m3 = l3 + c3, m4 = l4 + c4, m5 = l5 + c5; + var m6 = l6 + c6, m7 = l7 + c7, m8 = l8 + c8, m9 = l9 + c9, m10 = l10 + c10, m11 = l11 + c11; + var below:Int = small(n - 1); + var digits = Std.string(n).length; + var lengths = l0.length + l1.length + l2.length + l3.length + l4.length + l5.length + l6.length + l7.length + l8.length + + l9.length + l10.length + l11.length + m0.length + m1.length + m2.length + m3.length + m4.length + m5.length + + m6.length + m7.length + m8.length + m9.length + m10.length + m11.length; + return 1 + below + lengths - 24 * digits - 54; + }; + return small; + } + + public static function run() { + // Each closure's first call compiles it, the general way, and the next + // ones call its code + var bySize = sizes(); + var lines = []; + for (round in 0...3) + lines.push([for (f in bySize) f(round)].join(",")); + Sys.println('sizes ${lines.join(" | ")}'); + + var m = mixed(4); + var m1:String = m(1, 0.5, "x", [1, 2]); + var m2:String = m(2, 1.5, "y", null); + var m3:String = mixed(9)(3, 2.25, "z", "d"); + Sys.println('mixed $m1 | $m2 | $m3'); + var ints = intsOnly(3); + var words = wordsOnly(2); + var i1:Int = ints(1); + var i2:Int = ints(2); + var w1:String = words(1); + var w2:String = words(2); + Sys.println('parts $i1 $i2 $w1 $w2'); + + var k = 5; + var t = "tt"; + var noArgs = () -> k * 10 + t.length; + var noCaptures = () -> 42; + var n1:Int = noArgs(); + var n2:Int = noCaptures(); + Sys.println('no arguments $n1 $n2'); + + // One call site, closures of each layout in turn, with this, bound + // methods and a static function + var holder = new CompiledHolder(10, "holder"); + var site:ArrayInt> = [ + twice, + x -> x + 1, + intsOnly(2), + holder.add, + holder.maker(3, "ab"), + holder.callback, + x -> x * k + t.length, + x -> { + var a:Int = ints(x); + var b:String = words(x); + return a - b.length; + }, + ]; + var sum = 0; + for (round in 0...200) + for (f in site) { + var result:Int = f(round); + sum += result % 1000; + } + Sys.println('one site $sum ${holder.base}'); + + // Results that feed an operator, which are boxed, and the same values + // as they are + var boxed = 0; + for (round in 0...4) + for (f in site) + boxed += f(round) % 1000 + twice(round); + Sys.println('boxed $boxed ${holder.base}'); + + // A closure kept in a field, called through it + var other = new CompiledHolder(20, "other"); + var c1:Int = other.callback(1); + var c2:Int = holder.callback(2); + Sys.println('field $c1 $c2'); + + // Calls whose types are not the function's go the general way + var takesFloat:Dynamic = (x:Float) -> x / 4; + var asIntArgument:Int->Dynamic = takesFloat; + var returnsInt:Dynamic = (x:Int) -> x * 3; + var asFloatResult:Int->Float = returnsInt; + var withDefault:Dynamic = (x:Int, ?y:Int = 3) -> x * y; + var asOneArgument:Int->Int = withDefault; + var host:Int->Dynamic = Std.string; + var takesArray = (a:Array) -> a.length; + var r1:Dynamic = asIntArgument(2); + var r2:Float = asFloatResult(2); + var r3:Int = asOneArgument(4); + var r4:Dynamic = host(6); + var r5:Int = takesArray([1, 2, 3]); + Sys.println('mismatch $r1 $r2 $r3 $r4 $r5'); + + // A result not used: the arguments alone must match + var noted = []; + var note = (x:Int) -> { + noted.push(x); + return x * 2; + }; + for (x in 0...4) + note(x); + Sys.println('result unused $noted'); + + var none:Int->Int = null; + var tries = []; + for (round in 0...2) + tries.push(try { + var r:Int = none(round); + Std.string(r); + } catch (e:Dynamic) "throws"); + Sys.println('null $tries'); + + // A throw from a closure with captures, caught where it was called, and + // through two closures, the outer catching + var sCap = "cap"; + var fCap = 1.5; + var iCap = 4; + var thrower = (x:Int) -> { + if (x % 2 == 1) + throw sCap + x; + return Std.int(x * fCap) + iCap; + }; + var outcome = []; + for (x in 0...5) + try { + var r:Int = thrower(x); + outcome.push(Std.string(r)); + } catch (e:String) { + outcome.push(e); + } + var middle = (x:Int) -> { + var r:Int = thrower(x); + return r * 2; + }; + var outer = (x:Int) -> { + try { + var r:Int = middle(x); + return r; + } catch (e:String) { + return -e.length; + } + }; + var o1:Int = outer(2); + var o2:Int = outer(3); + var o3:Int = thrower(4); + Sys.println('throws $outcome $o1 $o2 $o3'); + + // Recursion through a captured variable, whose first call compiles it + var fib:Int->Int = null; + fib = n -> { + if (n < 2) + return n; + var a:Int = fib(n - 1); + var b:Int = fib(n - 2); + return a + b; + }; + var f20:Int = fib(20); + Sys.println('recursion $f20'); + var down = deep(); + var d1:Int = down(250); + var d2:Int = down(10); + Sys.println('deep $d1 $d2'); + + // Strings and objects captured, called after a collection + var made = [for (n in 0...50) wordsOnly(n)]; + cpp.vm.Gc.run(true); + var length = 0; + for (n in 0...made.length) { + var text:String = made[n](n); + length += text.length; + } + Sys.println('after a collection $length'); + } +} diff --git a/test/regression/CppiaJitClosureEntry/Script.hx b/test/regression/CppiaJitClosureEntry/Script.hx new file mode 100644 index 000000000..c1522025b --- /dev/null +++ b/test/regression/CppiaJitClosureEntry/Script.hx @@ -0,0 +1,268 @@ +// The same cases as Compiled in Main.hx, run as a script +class Holder { + public var base:Int; + public var name:String; + public var callback:Int->Int; + + public function new(base:Int, name:String) { + this.base = base; + this.name = name; + var shift = 3; + callback = x -> x + shift + this.base; + } + + public function add(x:Int):Int { + base += x; + return base; + } + + // this, an Int and a String, in a closure of a method + public function maker(step:Int, tag:String):Int->Int { + return x -> x * step + base + tag.length + name.length; + } +} + +class Script { + static function twice(x:Int):Int + return x * 2; + + // One capture of each kind and size, none, an Int, a Bool, a Float, a String + // and objects, all called through one call site + static function sizes():ArrayString> { + var i = 7; + var b = true; + var f = 2.5; + var s = "str"; + var a = [4, 5, 6]; + var d:Dynamic = "dyn"; + var h = new Holder(1, "h"); + return [ + x -> "none " + x, + x -> "int " + (x + i), + x -> "bool " + (b && x % 2 == 0), + x -> "float " + (x * f), + x -> "string " + s + x, + x -> "array " + a[x % 3], + x -> "dynamic " + d + x, + x -> "object " + (h.base + x), + ]; + } + + // Ints between wider captures, so the closure has whole words and 4 bytes to + // move, with an argument of each kind that the captures go after + static function mixed(n:Int):(Int, Float, String, Dynamic) -> String { + var i1 = n, s1 = "m" + n, i2 = n + 1, f1 = n * 0.5, i3 = n + 2, o1 = [n], i4 = n + 3; + return (a:Int, b:Float, c:String, d:Dynamic) -> { + var local = a * 10; + return '$local $b $c $d $i1 $s1 $i2 $f1 $i3 ${o1[0]} $i4'; + }; + } + + // Only Ints, which on 64 bits are no whole words + static function intsOnly(n:Int):Int->Int { + var a = n, b = n * 2, c = n * 3; + return x -> x + a + b * 10 + c * 100; + } + + // Only whole words + static function wordsOnly(n:Int):Int->String { + var s = "w" + n, f = n * 1.5, o = [n, n]; + return x -> s + (f + x) + o.length; + } + + // A closure with a small frame calling one with a large one, twelve Strings + // captured and twenty-four of its own, which calls it back. The large frames + // pass where the script stack was first committed to well before the + // deepest, so a call from a small frame finds no room for the large one and + // goes the general way, which commits more + static function deep():Int->Int { + var c0 = "a", c1 = "bb", c2 = "c", c3 = "dd", c4 = "e", c5 = "ff"; + var c6 = "g", c7 = "hh", c8 = "i", c9 = "jj", c10 = "k", c11 = "ll"; + var large:Int->Int = null; + var small = n -> { + var r:Int = large(n); + return r; + }; + large = n -> { + if (n == 0) + return 0; + var l0 = c0 + n, l1 = c1 + n, l2 = c2 + n, l3 = c3 + n, l4 = c4 + n, l5 = c5 + n; + var l6 = c6 + n, l7 = c7 + n, l8 = c8 + n, l9 = c9 + n, l10 = c10 + n, l11 = c11 + n; + var m0 = l0 + c0, m1 = l1 + c1, m2 = l2 + c2, m3 = l3 + c3, m4 = l4 + c4, m5 = l5 + c5; + var m6 = l6 + c6, m7 = l7 + c7, m8 = l8 + c8, m9 = l9 + c9, m10 = l10 + c10, m11 = l11 + c11; + var below:Int = small(n - 1); + var digits = Std.string(n).length; + var lengths = l0.length + l1.length + l2.length + l3.length + l4.length + l5.length + l6.length + l7.length + l8.length + + l9.length + l10.length + l11.length + m0.length + m1.length + m2.length + m3.length + m4.length + m5.length + + m6.length + m7.length + m8.length + m9.length + m10.length + m11.length; + return 1 + below + lengths - 24 * digits - 54; + }; + return small; + } + + static function main() { + // Each closure's first call compiles it, the general way, and the next + // ones call its code + var bySize = sizes(); + var lines = []; + for (round in 0...3) + lines.push([for (f in bySize) f(round)].join(",")); + Sys.println('sizes ${lines.join(" | ")}'); + + var m = mixed(4); + var m1:String = m(1, 0.5, "x", [1, 2]); + var m2:String = m(2, 1.5, "y", null); + var m3:String = mixed(9)(3, 2.25, "z", "d"); + Sys.println('mixed $m1 | $m2 | $m3'); + var ints = intsOnly(3); + var words = wordsOnly(2); + var i1:Int = ints(1); + var i2:Int = ints(2); + var w1:String = words(1); + var w2:String = words(2); + Sys.println('parts $i1 $i2 $w1 $w2'); + + var k = 5; + var t = "tt"; + var noArgs = () -> k * 10 + t.length; + var noCaptures = () -> 42; + var n1:Int = noArgs(); + var n2:Int = noCaptures(); + Sys.println('no arguments $n1 $n2'); + + // One call site, closures of each layout in turn, with this, bound + // methods and a static function + var holder = new Holder(10, "holder"); + var site:ArrayInt> = [ + twice, + x -> x + 1, + intsOnly(2), + holder.add, + holder.maker(3, "ab"), + holder.callback, + x -> x * k + t.length, + x -> { + var a:Int = ints(x); + var b:String = words(x); + return a - b.length; + }, + ]; + var sum = 0; + for (round in 0...200) + for (f in site) { + var result:Int = f(round); + sum += result % 1000; + } + Sys.println('one site $sum ${holder.base}'); + + // Results that feed an operator, which are boxed, and the same values + // as they are + var boxed = 0; + for (round in 0...4) + for (f in site) + boxed += f(round) % 1000 + twice(round); + Sys.println('boxed $boxed ${holder.base}'); + + // A closure kept in a field, called through it + var other = new Holder(20, "other"); + var c1:Int = other.callback(1); + var c2:Int = holder.callback(2); + Sys.println('field $c1 $c2'); + + // Calls whose types are not the function's go the general way + var takesFloat:Dynamic = (x:Float) -> x / 4; + var asIntArgument:Int->Dynamic = takesFloat; + var returnsInt:Dynamic = (x:Int) -> x * 3; + var asFloatResult:Int->Float = returnsInt; + var withDefault:Dynamic = (x:Int, ?y:Int = 3) -> x * y; + var asOneArgument:Int->Int = withDefault; + var host:Int->Dynamic = Std.string; + var takesArray = (a:Array) -> a.length; + var r1:Dynamic = asIntArgument(2); + var r2:Float = asFloatResult(2); + var r3:Int = asOneArgument(4); + var r4:Dynamic = host(6); + var r5:Int = takesArray([1, 2, 3]); + Sys.println('mismatch $r1 $r2 $r3 $r4 $r5'); + + // A result not used: the arguments alone must match + var noted = []; + var note = (x:Int) -> { + noted.push(x); + return x * 2; + }; + for (x in 0...4) + note(x); + Sys.println('result unused $noted'); + + var none:Int->Int = null; + var tries = []; + for (round in 0...2) + tries.push(try { + var r:Int = none(round); + Std.string(r); + } catch (e:Dynamic) "throws"); + Sys.println('null $tries'); + + // A throw from a closure with captures, caught where it was called, and + // through two closures, the outer catching + var sCap = "cap"; + var fCap = 1.5; + var iCap = 4; + var thrower = (x:Int) -> { + if (x % 2 == 1) + throw sCap + x; + return Std.int(x * fCap) + iCap; + }; + var outcome = []; + for (x in 0...5) + try { + var r:Int = thrower(x); + outcome.push(Std.string(r)); + } catch (e:String) { + outcome.push(e); + } + var middle = (x:Int) -> { + var r:Int = thrower(x); + return r * 2; + }; + var outer = (x:Int) -> { + try { + var r:Int = middle(x); + return r; + } catch (e:String) { + return -e.length; + } + }; + var o1:Int = outer(2); + var o2:Int = outer(3); + var o3:Int = thrower(4); + Sys.println('throws $outcome $o1 $o2 $o3'); + + // Recursion through a captured variable, whose first call compiles it + var fib:Int->Int = null; + fib = n -> { + if (n < 2) + return n; + var a:Int = fib(n - 1); + var b:Int = fib(n - 2); + return a + b; + }; + var f20:Int = fib(20); + Sys.println('recursion $f20'); + var down = deep(); + var d1:Int = down(250); + var d2:Int = down(10); + Sys.println('deep $d1 $d2'); + + // Strings and objects captured, called after a collection + var made = [for (n in 0...50) wordsOnly(n)]; + cpp.vm.Gc.run(true); + var length = 0; + for (n in 0...made.length) { + var text:String = made[n](n); + length += text.length; + } + Sys.println('after a collection $length'); + } +} diff --git a/test/regression/CppiaJitClosureEntry/build.hxml b/test/regression/CppiaJitClosureEntry/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaJitClosureEntry/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaJitClosureEntry/stdout.txt b/test/regression/CppiaJitClosureEntry/stdout.txt new file mode 100644 index 000000000..c296cce05 --- /dev/null +++ b/test/regression/CppiaJitClosureEntry/stdout.txt @@ -0,0 +1,45 @@ +-- compiled +sizes none 0,int 7,bool true,float 0,string str0,array 4,dynamic dyn0,object 1 | none 1,int 8,bool false,float 2.5,string str1,array 5,dynamic dyn1,object 2 | none 2,int 9,bool true,float 5,string str2,array 6,dynamic dyn2,object 3 +mixed 10 0.5 x [1,2] 4 m4 5 2 6 4 7 | 20 1.5 y null 4 m4 5 2 6 4 7 | 30 2.25 z d 9 m9 10 4.5 11 9 12 +parts 964 965 w242 w252 +no arguments 52 42 +one site 628204 19910 +boxed 17590 19916 +field 24 19921 +mismatch 0.5 6 12 6 3 +result unused [0,1,2,3] +null [throws,throws] +throws [4,cap1,7,cap3,10] 14 -4 10 +recursion 6765 +deep 250 10 +after a collection 346 +-- script, JIT off +sizes none 0,int 7,bool true,float 0,string str0,array 4,dynamic dyn0,object 1 | none 1,int 8,bool false,float 2.5,string str1,array 5,dynamic dyn1,object 2 | none 2,int 9,bool true,float 5,string str2,array 6,dynamic dyn2,object 3 +mixed 10 0.5 x [1,2] 4 m4 5 2 6 4 7 | 20 1.5 y null 4 m4 5 2 6 4 7 | 30 2.25 z d 9 m9 10 4.5 11 9 12 +parts 964 965 w242 w252 +no arguments 52 42 +one site 628204 19910 +boxed 17590 19916 +field 24 19921 +mismatch 0.5 6 12 6 3 +result unused [0,1,2,3] +null [throws,throws] +throws [4,cap1,7,cap3,10] 14 -4 10 +recursion 6765 +deep 250 10 +after a collection 346 +-- script, JIT on +sizes none 0,int 7,bool true,float 0,string str0,array 4,dynamic dyn0,object 1 | none 1,int 8,bool false,float 2.5,string str1,array 5,dynamic dyn1,object 2 | none 2,int 9,bool true,float 5,string str2,array 6,dynamic dyn2,object 3 +mixed 10 0.5 x [1,2] 4 m4 5 2 6 4 7 | 20 1.5 y null 4 m4 5 2 6 4 7 | 30 2.25 z d 9 m9 10 4.5 11 9 12 +parts 964 965 w242 w252 +no arguments 52 42 +one site 628204 19910 +boxed 17590 19916 +field 24 19921 +mismatch 0.5 6 12 6 3 +result unused [0,1,2,3] +null [throws,throws] +throws [4,cap1,7,cap3,10] 14 -4 10 +recursion 6765 +deep 250 10 +after a collection 346 diff --git a/test/regression/CppiaJitClosureEntryDebugger/build.hxml b/test/regression/CppiaJitClosureEntryDebugger/build.hxml new file mode 100644 index 000000000..e638d6b8d --- /dev/null +++ b/test/regression/CppiaJitClosureEntryDebugger/build.hxml @@ -0,0 +1,10 @@ +-cp ../CppiaJitClosureEntry +--main Script +-cppia bin/script.cppia +--next +-cp ../CppiaJitClosureEntry +--main Main +-cpp bin +-D scriptable +-D HXCPP_DEBUGGER +--dce no diff --git a/test/regression/CppiaJitClosureEntryDebugger/stdout.txt b/test/regression/CppiaJitClosureEntryDebugger/stdout.txt new file mode 100644 index 000000000..c296cce05 --- /dev/null +++ b/test/regression/CppiaJitClosureEntryDebugger/stdout.txt @@ -0,0 +1,45 @@ +-- compiled +sizes none 0,int 7,bool true,float 0,string str0,array 4,dynamic dyn0,object 1 | none 1,int 8,bool false,float 2.5,string str1,array 5,dynamic dyn1,object 2 | none 2,int 9,bool true,float 5,string str2,array 6,dynamic dyn2,object 3 +mixed 10 0.5 x [1,2] 4 m4 5 2 6 4 7 | 20 1.5 y null 4 m4 5 2 6 4 7 | 30 2.25 z d 9 m9 10 4.5 11 9 12 +parts 964 965 w242 w252 +no arguments 52 42 +one site 628204 19910 +boxed 17590 19916 +field 24 19921 +mismatch 0.5 6 12 6 3 +result unused [0,1,2,3] +null [throws,throws] +throws [4,cap1,7,cap3,10] 14 -4 10 +recursion 6765 +deep 250 10 +after a collection 346 +-- script, JIT off +sizes none 0,int 7,bool true,float 0,string str0,array 4,dynamic dyn0,object 1 | none 1,int 8,bool false,float 2.5,string str1,array 5,dynamic dyn1,object 2 | none 2,int 9,bool true,float 5,string str2,array 6,dynamic dyn2,object 3 +mixed 10 0.5 x [1,2] 4 m4 5 2 6 4 7 | 20 1.5 y null 4 m4 5 2 6 4 7 | 30 2.25 z d 9 m9 10 4.5 11 9 12 +parts 964 965 w242 w252 +no arguments 52 42 +one site 628204 19910 +boxed 17590 19916 +field 24 19921 +mismatch 0.5 6 12 6 3 +result unused [0,1,2,3] +null [throws,throws] +throws [4,cap1,7,cap3,10] 14 -4 10 +recursion 6765 +deep 250 10 +after a collection 346 +-- script, JIT on +sizes none 0,int 7,bool true,float 0,string str0,array 4,dynamic dyn0,object 1 | none 1,int 8,bool false,float 2.5,string str1,array 5,dynamic dyn1,object 2 | none 2,int 9,bool true,float 5,string str2,array 6,dynamic dyn2,object 3 +mixed 10 0.5 x [1,2] 4 m4 5 2 6 4 7 | 20 1.5 y null 4 m4 5 2 6 4 7 | 30 2.25 z d 9 m9 10 4.5 11 9 12 +parts 964 965 w242 w252 +no arguments 52 42 +one site 628204 19910 +boxed 17590 19916 +field 24 19921 +mismatch 0.5 6 12 6 3 +result unused [0,1,2,3] +null [throws,throws] +throws [4,cap1,7,cap3,10] 14 -4 10 +recursion 6765 +deep 250 10 +after a collection 346 From 373a966514d571e5af5870d05df71cdd2366f797 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 20:59:06 -0500 Subject: [PATCH 21/23] Add a cppia workload whose closure result is an operator's operand 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. --- BENCHMARKS.md | 1 + bench/cppia/Script.hx | 16 ++++++++++++++++ bench/cppia/shared/CppiaWorkloads.hx | 1 + 3 files changed, 18 insertions(+) diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 5680e9ce3..3710ed497 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -141,6 +141,7 @@ driver also checks that the interpreter and JIT return the same checksum. | `call_by_name` | Script calls of an abstract's methods over a host type, which the host gives no binding for, as openfl.Vector's are: length, element reads and writes | | `host_sort` | `Array.sort`, which is host code, sorting a copy of 1,000 script Ints with a comparator the script gives it, ten times a run | | `host_statics` | Script reads and writes of a host class's static object fields | +| `closure_expr` | Script calls to a closure whose result is an operand of an operator, which takes it as a Dynamic | The native timing harness loads one script module per process. Loading, linking, booting and JIT compilation happen in `setup()`, outside the timed samples. diff --git a/bench/cppia/Script.hx b/bench/cppia/Script.hx index de0a80498..2ce97ef64 100644 --- a/bench/cppia/Script.hx +++ b/bench/cppia/Script.hx @@ -16,6 +16,7 @@ class Script { case "call_by_name": new CallByName(); case "host_sort": new HostSort(); case "host_statics": new HostStatics(); + case "closure_expr": new ClosureExpr(); default: throw 'Unknown CPPIA workload ${CppiaBridge.name}'; }; } @@ -377,3 +378,18 @@ class HostStatics implements CppiaWorkload { return sum; } } + +// A closure whose result is an operand of an operator, as fib(n - 1) + fib(n - 2) +// is: a call's result has no type of its own, so the operator takes it as a Dynamic +class ClosureExpr implements CppiaWorkload { + public function new() {} + + public function run():Int { + var scale = 3; + var f = function(x:Int):Int return (x * scale) & 4095; + var sum = 0; + for (i in 0...200000) + sum = (sum + f(i) % 1000) & 0xffffff; + return sum; + } +} diff --git a/bench/cppia/shared/CppiaWorkloads.hx b/bench/cppia/shared/CppiaWorkloads.hx index 3863b3489..bd969374a 100644 --- a/bench/cppia/shared/CppiaWorkloads.hx +++ b/bench/cppia/shared/CppiaWorkloads.hx @@ -20,5 +20,6 @@ class CppiaWorkloads { {name: "call_by_name", unit: "calls", ops: 400000, reps: 5}, {name: "host_sort", unit: "sorted elements", ops: 10000, reps: 5}, {name: "host_statics", unit: "iterations", ops: 200000, reps: 10}, + {name: "closure_expr", unit: "calls", ops: 200000, reps: 10}, ]; } From 142b4d315e4fdbaea463ae4b90319f4a67ace089 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 21:31:56 -0500 Subject: [PATCH 22/23] Add a cppia workload of a script's map and filter 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. --- BENCHMARKS.md | 1 + bench/cppia/Script.hx | 19 +++++++++++++++++++ bench/cppia/shared/CppiaWorkloads.hx | 1 + 3 files changed, 21 insertions(+) diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 3710ed497..ef0660960 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -142,6 +142,7 @@ driver also checks that the interpreter and JIT return the same checksum. | `host_sort` | `Array.sort`, which is host code, sorting a copy of 1,000 script Ints with a comparator the script gives it, ten times a run | | `host_statics` | Script reads and writes of a host class's static object fields | | `closure_expr` | Script calls to a closure whose result is an operand of an operator, which takes it as a Dynamic | +| `script_map` | `Array.map` and `filter` on 1,000 Ints, ten times a run, which Haxe inlines into the script as loops calling the closures | The native timing harness loads one script module per process. Loading, linking, booting and JIT compilation happen in `setup()`, outside the timed samples. diff --git a/bench/cppia/Script.hx b/bench/cppia/Script.hx index 2ce97ef64..7fad9ff3b 100644 --- a/bench/cppia/Script.hx +++ b/bench/cppia/Script.hx @@ -17,6 +17,7 @@ class Script { case "host_sort": new HostSort(); case "host_statics": new HostStatics(); case "closure_expr": new ClosureExpr(); + case "script_map": new ScriptMap(); default: throw 'Unknown CPPIA workload ${CppiaBridge.name}'; }; } @@ -393,3 +394,21 @@ class ClosureExpr implements CppiaWorkload { return sum; } } + +// Array.map and filter on a script's Ints, which Haxe inlines into the script as +// loops calling the closures +class ScriptMap implements CppiaWorkload { + final values = [for (i in 0...1000) i]; + + public function new() {} + + public function run():Int { + var sum = 0; + for (r in 0...10) { + var doubled = values.map(x -> x * 2 + r); + var odd = values.filter(x -> (x + r) & 1 == 1); + sum = (sum * 31 + doubled[r * 97] + odd.length) | 0; + } + return sum; + } +} diff --git a/bench/cppia/shared/CppiaWorkloads.hx b/bench/cppia/shared/CppiaWorkloads.hx index bd969374a..bbc4fff89 100644 --- a/bench/cppia/shared/CppiaWorkloads.hx +++ b/bench/cppia/shared/CppiaWorkloads.hx @@ -21,5 +21,6 @@ class CppiaWorkloads { {name: "host_sort", unit: "sorted elements", ops: 10000, reps: 5}, {name: "host_statics", unit: "iterations", ops: 200000, reps: 10}, {name: "closure_expr", unit: "calls", ops: 200000, reps: 10}, + {name: "script_map", unit: "calls", ops: 20000, reps: 5}, ]; } From 5fa2befe471007ccc3817fec3529bea4ad4f0b32 Mon Sep 17 00:00:00 2001 From: Chris Speciale Date: Sat, 28 Nov 2026 21:31:56 -0500 Subject: [PATCH 23/23] Sort with a script comparator as a run of typed calls 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 ce4bc1a7, 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 --- Changes.md | 1 + include/Array.h | 10 +- include/hx/TypedCall.h | 50 +++++++++ src/Dynamic.cpp | 2 + src/hx/cppia/CppiaFunction.cpp | 79 ++++++++++++++ test/regression/CppiaHostSortRuns/Main.hx | 104 +++++++++++++++++++ test/regression/CppiaHostSortRuns/Script.hx | 80 ++++++++++++++ test/regression/CppiaHostSortRuns/build.hxml | 7 ++ test/regression/CppiaHostSortRuns/stdout.txt | 27 +++++ 9 files changed, 356 insertions(+), 4 deletions(-) create mode 100644 test/regression/CppiaHostSortRuns/Main.hx create mode 100644 test/regression/CppiaHostSortRuns/Script.hx create mode 100644 test/regression/CppiaHostSortRuns/build.hxml create mode 100644 test/regression/CppiaHostSortRuns/stdout.txt diff --git a/Changes.md b/Changes.md index a90f64e75..b4d6b2fbd 100644 --- a/Changes.md +++ b/Changes.md @@ -17,6 +17,7 @@ libhxcpp 6.1.0 (unreleased) * Where every way a host call can go is a typed entry, jitted cppia code keeps the object and the result in registers: a call with no arguments evaluates its object straight into the register the entry takes it in, the result is converted from the register the entry gives it in, and the context's frame, which only a stub reads, is left alone. Each went through the script frame, and the object was read back from it twice. Updating script objects through a host display object's properties is a further 1.18x faster under the JIT (bunny_update), and script-to-native calls 1.17x (native_call) * An Int or a Float that a Dynamic holds is boxed with the allocator's fast path in line, where new reached it through calls the compiler left out of line, and Ints from -1 to 1023, not 255, share boxes made once. A whole Float still boxes as an Int from -1 to 255 only, so Type.typeof and Std.isOfType see the same types. The host calling back a script closure that returns an Int is 1.18x faster under the JIT and 1.08x interpreted (native_callback, whose results run from 0 to 2046, so about half are shared boxes). Every boxed Int and Float in Haxe 4 code takes the shorter path * Jitted cppia code calling a script closure checks in line that the value is one, that its function takes the arguments and gives the result as the call has them, that the function is compiled and that its frame fits the stack, and puts this and the captured variables into the frame in line, a word or 4 bytes at a time from a list of moves the function keeps, before it calls the compiled code. It called a helper for all of that on every call, and the native call was most of what the helper cost. Jitted code calling a closure that captures a variable is 10% faster (closure_call). Calls from host code and interpreted calls are level +* Array.sort with a cppia script comparator calls it as a run of typed calls, hx::TypedCallRun in hx/TypedCall.h: what each comparison checked, that the comparator is a script closure taking the values as they are and compiled, and that its frame fits, is checked once, and each comparison then puts the two values and the captured variables in the frame and runs the compiled code. Sorting with a script comparator is 1.15x faster under the JIT (host_sort). Interpreted sorts are level libhxcpp 6.0.3 ------------------------------------------------------------ diff --git a/include/Array.h b/include/Array.h index 8ac408be7..651048a28 100644 --- a/include/Array.h +++ b/include/Array.h @@ -1116,15 +1116,17 @@ class Array_obj : public hx::ArrayBase // its box struct TypedSorter { - Dynamic mFunc; bool mIntResult; + // The comparisons, as runs of typed calls (hx/TypedCall.h) + hx::TypedCallRun mInts; + hx::TypedCallRun< ::Dynamic, ELEM_, ELEM_> mDynamics; - TypedSorter(const Dynamic &inFunc, bool inIntResult) : mFunc(inFunc), mIntResult(inIntResult) { } + TypedSorter(const Dynamic &inFunc, bool inIntResult) : mIntResult(inIntResult), mInts(inFunc), mDynamics(inFunc) { } bool operator()(const ELEM_ &inA, const ELEM_ &inB) { if (mIntResult) - return hx::callFunction(mFunc, inA, inB) < 0; - return hx::callFunction< ::Dynamic>(mFunc, inA, inB)->__ToInt() < 0; + return mInts(inA, inB) < 0; + return mDynamics(inA, inB)->__ToInt() < 0; } }; void sortTypedValues(ELEM_ *ioData, int inFrom, int inTo, ELEM_ *ioBuffer, TypedSorter &inLess); diff --git a/include/hx/TypedCall.h b/include/hx/TypedCall.h index afa9bcd84..2e38a3082 100644 --- a/include/hx/TypedCall.h +++ b/include/hx/TypedCall.h @@ -200,6 +200,15 @@ extern HXCPP_EXTERN_CLASS_ATTRIBUTES ScriptClosureTypedCall gScriptClosureTypedC // exactly the arguments of the match code inMatch, or -1 typedef int (*ScriptClosureTypedResult)(hx::Object *inClosure, int inMatch); extern HXCPP_EXTERN_CLASS_ATTRIBUTES ScriptClosureTypedResult gScriptClosureTypedResult; +// A run of typed calls of one script closure (hx::TypedCallRun): begin checks once +// what a call through gScriptClosureTypedCall checks each time, and keeps in ioState +// what each call needs, false where the calls cannot go straight to compiled code; +// call then makes one such call. Either may be null, in a runtime without them +typedef bool (*ScriptClosureRunBegin)(hx::Object *inClosure, int inMatch, int inKinds, void **ioState); +typedef void (*ScriptClosureRunCall)(void *const *inState, hx::Object *inClosure, const TypedCallArg *inArgs, void *outResult); +extern HXCPP_EXTERN_CLASS_ATTRIBUTES ScriptClosureRunBegin gScriptClosureRunBegin; +extern HXCPP_EXTERN_CLASS_ATTRIBUTES ScriptClosureRunCall gScriptClosureRunCall; +enum { typedCallRunState = 4 }; #if (HXCPP_API_LEVEL<500) @@ -316,6 +325,47 @@ inline int scriptClosureResultKind(const ::Dynamic &inFunction) return -1; } +// Calls of one function value with arguments of the types TArgs, for host code that +// calls one many times, as Array.sort, map and filter do. Each call gives what +// hx::callFunction gives. A script closure whose calls go straight to its compiled +// code has that checked once, and each call then only puts the arguments and the +// captured variables in its frame and runs it +template +class TypedCallRun +{ + ::Dynamic mFunction; + void *mState[typedCallRunState]; + bool mRun; + +public: + explicit TypedCallRun(const ::Dynamic &inFunction) : mFunction(inFunction), mRun(false) + { + static_assert(sizeof...(TArgs)<=typedCallMaxArgs, "a typed call takes the script path with at most typedCallMaxArgs arguments"); + #ifdef HXCPP_SCRIPTABLE + hx::Object *function = inFunction.mPtr; + if (function && *(void **)function==gScriptClosureVTable && gScriptClosureRunBegin && gScriptClosureRunCall) + { + typedef TypedCallSignature Signature; + mRun = gScriptClosureRunBegin(function, Signature::match, Signature::kinds, mState); + } + #endif + } + + inline TResult operator()(const TArgs &... inArgs) + { + #ifdef HXCPP_SCRIPTABLE + if (mRun) + { + const TypedCallArg args[sizeof...(TArgs)+1] = { TypedCallArgOf::make(inArgs)... }; + typename TypedCallResultOf::Storage result; + gScriptClosureRunCall(mState, mFunction.mPtr, args, &result); + return TypedCallResultOf::get(result); + } + #endif + return callFunction(mFunction, inArgs...); + } +}; + #endif } diff --git a/src/Dynamic.cpp b/src/Dynamic.cpp index b3e50f0d8..a0529623a 100644 --- a/src/Dynamic.cpp +++ b/src/Dynamic.cpp @@ -33,6 +33,8 @@ hx::Class __ObjcClass; void *gScriptClosureVTable = 0; ScriptClosureTypedCall gScriptClosureTypedCall = 0; ScriptClosureTypedResult gScriptClosureTypedResult = 0; +ScriptClosureRunBegin gScriptClosureRunBegin = 0; +ScriptClosureRunCall gScriptClosureRunCall = 0; hx::Class &GetBoolClass() { return __BoolClass; } diff --git a/src/hx/cppia/CppiaFunction.cpp b/src/hx/cppia/CppiaFunction.cpp index 91534ea79..e3d208a96 100644 --- a/src/hx/cppia/CppiaFunction.cpp +++ b/src/hx/cppia/CppiaFunction.cpp @@ -1308,6 +1308,83 @@ class CppiaClosure : public hx::Object HX_STACK_DO_THROW(caught); } + // A run of typed calls (hx::TypedCallRun): what typedCall checks for its compiled + // path, checked once, compiling a function the JIT left to its first call. The + // state is the context, where its pointer and frame are, and the compiled code + static bool runBegin(hx::Object *inClosure, int inMatch, int inKinds, void **ioState) + { + #ifdef CPPIA_JIT + ScriptCallable *function = ((CppiaClosure *)inClosure)->function; + if (function->typedCallMatch!=inMatch) + return false; + CppiaFunc code = function->getCompiled(); + if (!code && function->lazy) + { + function->compileLazy(); + code = function->getCompiled(); + } + if (!code) + return false; + CppiaCtx *ctx = CppiaCtx::getCurrent(); + if (ctx->pointer + function->stackSize > ctx->stackEnd) + return false; + ioState[0] = ctx; + ioState[1] = (void *)code; + ioState[2] = (void *)(size_t)(unsigned int)inKinds; + ioState[3] = 0; + return true; + #else + return false; + #endif + } + + // One call of a run: typedCall's compiled path, with its checks made. The frame + // starts where the context's pointer is now, as each call's does, and the + // context is as it was again before the call returns or throws + static void runCall(void *const *inState, hx::Object *inClosure, const hx::TypedCallArg *inArgs, void *outResult) + { + #ifdef CPPIA_JIT + CppiaClosure *closure = (CppiaClosure *)inClosure; + CppiaCtx *ctx = (CppiaCtx *)inState[0]; + int kinds = (int)(size_t)inState[2]; + unsigned char *pointer = ctx->pointer; + unsigned char *frame = ctx->frame; + if (pointer + closure->function->stackSize > ctx->stackEnd) + { + // Deeper than when the run began, as a call from inside the closure is + typedCall(inClosure, closure->function->typedCallMatch, kinds, inArgs, outResult); + return; + } + ctx->frame = pointer; + ctx->pointer = pointer + sizeof(hx::Object *); + int count = kinds & 15; + for(int a=0; a>(4+3*a)) & 7 ) + { + case hx::typedCallInt: ctx->pushInt(arg.intValue); break; + case hx::typedCallBool: ctx->pushInt(arg.boolValue); break; + case hx::typedCallFloat: ctx->pushFloat(arg.floatValue); break; + case hx::typedCallString: ctx->pushString(*arg.stringValue); break; + default: ctx->pushObject(arg.objectValue); + } + } + closure->enterFrame(pointer); + ((CppiaFunc)inState[1])(ctx); + ctx->frame = pointer; + if (ctx->exception) + { + ctx->pointer = pointer; + ctx->frame = frame; + throwPending(ctx); + } + closure->writeTypedResult(ctx, (kinds>>28) & 7, outResult); + ctx->pointer = pointer; + ctx->frame = frame; + #endif + } + // For hx::scriptClosureResultKind: what the function returns, when it takes // exactly the arguments of inMatch static int typedResult(hx::Object *inClosure, int inMatch) @@ -1449,6 +1526,8 @@ static struct PublishScriptClosure hx::gScriptClosureVTable = *(void **)&probe; hx::gScriptClosureTypedCall = CppiaClosure::typedCall; hx::gScriptClosureTypedResult = CppiaClosure::typedResult; + hx::gScriptClosureRunBegin = CppiaClosure::runBegin; + hx::gScriptClosureRunCall = CppiaClosure::runCall; } } sPublishScriptClosure; diff --git a/test/regression/CppiaHostSortRuns/Main.hx b/test/regression/CppiaHostSortRuns/Main.hx new file mode 100644 index 000000000..6360b28ce --- /dev/null +++ b/test/regression/CppiaHostSortRuns/Main.hx @@ -0,0 +1,104 @@ +// Array.sort, which is host code, calls a script comparator as a run of typed +// calls: what each comparison would check is checked once, and each comparison +// then puts the two values and the captured variables in the comparator's frame +// and runs its compiled code. Comparators made in a loop with captures of their +// own, one counting its calls, a sort inside a comparator and inside a closure, +// Floats, a throw part way and the same comparator after it, collections inside +// the comparator, and long jitted sorts. +// The same sorts run compiled into the host, then as a script with the JIT off +// and on, and print the same lines each time. +function main() { + Sys.println("-- compiled"); + Compiled.run(); + var script = haxe.io.Path.join([haxe.io.Path.directory(Sys.programPath()), "script.cppia"]); + for (jit in [false, true]) { + Sys.println(jit ? "-- script, JIT on" : "-- script, JIT off"); + cpp.cppia.Host.enableJit(jit); + try { + cpp.cppia.Host.runFile(script); + } catch (e:Dynamic) { + Sys.println("error: " + e); + } + } +} + +// The same sorts as Script.hx, compiled into the host +class Compiled { + public static function run() { + var bias = 3; + var base = [for (i in 0...40) (i * 37) % 23 - 5]; + + // Comparators made in a loop, each with its own captures, used one after another + var comparators = [for (k in 0...4) (a:Int, b:Int) -> k % 2 == 0 ? (a * k + bias) - (b * k + bias) : b - a]; + var orders = []; + for (c in comparators) { + var a = base.copy(); + a.sort(c); + orders.push(a.slice(0, 8).join(",")); + } + Sys.println('made in a loop $orders'); + + // A comparator that counts its calls in what it captures + var calls = 0; + var counted = base.copy(); + counted.sort((a, b) -> { + calls++; + a - b; + }); + Sys.println('counted $calls ${counted.slice(0, 10)}'); + + // A sort inside a comparator, run while the outer one's calls are going on + var inner = 0; + var outer = [5, 3, 9, 1, 7]; + outer.sort((a, b) -> { + var w = [a, b, a + b, 2]; + w.sort((p, q) -> q - p); + inner += w[0]; + a - b; + }); + Sys.println('sorted inside $outer $inner'); + + // A sort inside a closure the script calls, and one of Floats + var lists = [[3, 1, 2], [9, 7, 8, 6]].map(l -> { + l.sort((p, q) -> p - q); + l.join("/"); + }); + var floats = [2.5, -1.25, 0.5, 3.75, -0.5]; + floats.sort((a, b) -> a < b ? -1 : a > b ? 1 : 0); + Sys.println('inside a closure $lists $floats'); + + // A throw part way, then the same comparator again + var thrower = (a:Int, b:Int) -> { + if (a == 7 || b == 7) + throw 'at 7'; + return a - b; + }; + try { + var t = [5, 9, 7, 1]; + t.sort(thrower); + } catch (e:String) { + Sys.println('throws $e'); + } + var again = [4, 2, 8, 6]; + again.sort(thrower); + Sys.println('after a throw $again'); + + // Collections inside the comparator + var collected = [for (i in 0...30) (i * 13) % 30]; + collected.sort((a, b) -> { + if ((a + b) % 7 == 0) + cpp.vm.Gc.run(false); + a - b; + }); + Sys.println('collecting ${collected.slice(0, 10)}'); + + // Many comparisons, enough that each runs jitted + var t = 0; + for (r in 0...3) { + var s = [for (i in 0...3000) i]; + s.sort((a, b) -> ((a * 7919 + r) % 3000) - ((b * 7919 + r) % 3000)); + t += s[r] + s[2999]; + } + Sys.println('many $t'); + } +} diff --git a/test/regression/CppiaHostSortRuns/Script.hx b/test/regression/CppiaHostSortRuns/Script.hx new file mode 100644 index 000000000..7fb8c83fb --- /dev/null +++ b/test/regression/CppiaHostSortRuns/Script.hx @@ -0,0 +1,80 @@ +// The same cases as Compiled in Main.hx, run as a script +class Script { + static function main() { + var bias = 3; + var base = [for (i in 0...40) (i * 37) % 23 - 5]; + + // Comparators made in a loop, each with its own captures, used one after another + var comparators = [for (k in 0...4) (a:Int, b:Int) -> k % 2 == 0 ? (a * k + bias) - (b * k + bias) : b - a]; + var orders = []; + for (c in comparators) { + var a = base.copy(); + a.sort(c); + orders.push(a.slice(0, 8).join(",")); + } + Sys.println('made in a loop $orders'); + + // A comparator that counts its calls in what it captures + var calls = 0; + var counted = base.copy(); + counted.sort((a, b) -> { + calls++; + a - b; + }); + Sys.println('counted $calls ${counted.slice(0, 10)}'); + + // A sort inside a comparator, run while the outer one's calls are going on + var inner = 0; + var outer = [5, 3, 9, 1, 7]; + outer.sort((a, b) -> { + var w = [a, b, a + b, 2]; + w.sort((p, q) -> q - p); + inner += w[0]; + a - b; + }); + Sys.println('sorted inside $outer $inner'); + + // A sort inside a closure the script calls, and one of Floats + var lists = [[3, 1, 2], [9, 7, 8, 6]].map(l -> { + l.sort((p, q) -> p - q); + l.join("/"); + }); + var floats = [2.5, -1.25, 0.5, 3.75, -0.5]; + floats.sort((a, b) -> a < b ? -1 : a > b ? 1 : 0); + Sys.println('inside a closure $lists $floats'); + + // A throw part way, then the same comparator again + var thrower = (a:Int, b:Int) -> { + if (a == 7 || b == 7) + throw 'at 7'; + return a - b; + }; + try { + var t = [5, 9, 7, 1]; + t.sort(thrower); + } catch (e:String) { + Sys.println('throws $e'); + } + var again = [4, 2, 8, 6]; + again.sort(thrower); + Sys.println('after a throw $again'); + + // Collections inside the comparator + var collected = [for (i in 0...30) (i * 13) % 30]; + collected.sort((a, b) -> { + if ((a + b) % 7 == 0) + cpp.vm.Gc.run(false); + a - b; + }); + Sys.println('collecting ${collected.slice(0, 10)}'); + + // Many comparisons, enough that each runs jitted + var t = 0; + for (r in 0...3) { + var s = [for (i in 0...3000) i]; + s.sort((a, b) -> ((a * 7919 + r) % 3000) - ((b * 7919 + r) % 3000)); + t += s[r] + s[2999]; + } + Sys.println('many $t'); + } +} diff --git a/test/regression/CppiaHostSortRuns/build.hxml b/test/regression/CppiaHostSortRuns/build.hxml new file mode 100644 index 000000000..d20d36bd4 --- /dev/null +++ b/test/regression/CppiaHostSortRuns/build.hxml @@ -0,0 +1,7 @@ +--main Script +-cppia bin/script.cppia +--next +--main Main +-cpp bin +-D scriptable +--dce no diff --git a/test/regression/CppiaHostSortRuns/stdout.txt b/test/regression/CppiaHostSortRuns/stdout.txt new file mode 100644 index 000000000..c3010e33f --- /dev/null +++ b/test/regression/CppiaHostSortRuns/stdout.txt @@ -0,0 +1,27 @@ +-- compiled +made in a loop [-5,9,0,14,5,-4,10,1,17,16,16,15,15,14,14,13,-5,-5,-4,-4,-3,-3,-2,-2,17,16,16,15,15,14,14,13] +counted 169 [-5,-5,-4,-4,-3,-3,-2,-2,-1,0] +sorted inside [1,3,5,7,9] 60 +inside a closure [1/2/3,6/7/8/9] [-1.25,-0.5,0.5,2.5,3.75] +throws at 7 +after a throw [2,4,6,8] +collecting [0,1,2,3,4,5,6,7,8,9] +many 4926 +-- script, JIT off +made in a loop [-5,9,0,14,5,-4,10,1,17,16,16,15,15,14,14,13,-5,-5,-4,-4,-3,-3,-2,-2,17,16,16,15,15,14,14,13] +counted 169 [-5,-5,-4,-4,-3,-3,-2,-2,-1,0] +sorted inside [1,3,5,7,9] 60 +inside a closure [1/2/3,6/7/8/9] [-1.25,-0.5,0.5,2.5,3.75] +throws at 7 +after a throw [2,4,6,8] +collecting [0,1,2,3,4,5,6,7,8,9] +many 4926 +-- script, JIT on +made in a loop [-5,9,0,14,5,-4,10,1,17,16,16,15,15,14,14,13,-5,-5,-4,-4,-3,-3,-2,-2,17,16,16,15,15,14,14,13] +counted 169 [-5,-5,-4,-4,-3,-3,-2,-2,-1,0] +sorted inside [1,3,5,7,9] 60 +inside a closure [1/2/3,6/7/8/9] [-1.25,-0.5,0.5,2.5,3.75] +throws at 7 +after a throw [2,4,6,8] +collecting [0,1,2,3,4,5,6,7,8,9] +many 4926