From de87d9af6e3d65fc9c5dbb36cc6be7081402bd08 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Sat, 5 Dec 2026 10:00:49 +0000 Subject: [PATCH] Inline other modules' functions only in the alias pass Why: A call to another module's `@inline` function could be inlined in two places: early by the alias pass, and late while compiling to JavaScript. The late copy skipped every Lambda pass, so it kept what those passes remove, and it was inlined into a function whose refs were already assigned variables. Since the alias pass now inlines calls with parameters as arguments, the late path only gets calls through an alias, such as `add` from `let {add} = module(List)`. These are now compiled as calls, until the alias pass learns to see through them. The call no longer looks up the other module's `.cmj`: the late path needed its stored body, and the name it returned is the field name the call already has. The backend guide gets a section on the Lambda pipeline, with its single cross-module inlining phase. JS modified (a call through an alias): Example: let {length: l, add} = module(List) let r = list{}->add(l(list{1, 2, 3})) Before (js): let r_0 = Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}}); let r = {hd: r_0, tl: /* [] */0}; After (js): let r = Stdlib_List.add(/* [] */0, Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}})); Review: What do the new tests cover? `inline_late_alias_test` has the cases that broke when a late body was simplified: functions reading a let-bound global, a known tuple or an assigned ref, `Some`s of known values, and refs of the caller assigned by a callback. The alias pass inlines all of them now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq Signed-off-by: Christoph Knittel --- changes/no-late-inline.internal.md | 1 + compiler/backend/README.md | 74 ++++--- compiler/backend/lam_compile.ml | 44 +--- compiler/backend/lam_pass_remove_alias.ml | 5 +- tests/compiler_tests/src/hello_res.mjs | 4 +- .../src/inline_late_alias_lib.mjs | 62 ++++++ .../src/inline_late_alias_lib.res | 44 ++++ .../src/inline_late_alias_test.mjs | 198 ++++++++++++++++++ .../src/inline_late_alias_test.res | 150 +++++++++++++ 9 files changed, 513 insertions(+), 69 deletions(-) create mode 100644 changes/no-late-inline.internal.md create mode 100644 tests/compiler_tests/src/inline_late_alias_lib.mjs create mode 100644 tests/compiler_tests/src/inline_late_alias_lib.res create mode 100644 tests/compiler_tests/src/inline_late_alias_test.mjs create mode 100644 tests/compiler_tests/src/inline_late_alias_test.res diff --git a/changes/no-late-inline.internal.md b/changes/no-late-inline.internal.md new file mode 100644 index 0000000000..3cf1587c7d --- /dev/null +++ b/changes/no-late-inline.internal.md @@ -0,0 +1 @@ +- Inline functions of other modules in one phase, the alias pass, and no longer again while compiling to JavaScript. A call through an alias, such as `add` from `let {add} = module(List)`, is now compiled as a call. diff --git a/compiler/backend/README.md b/compiler/backend/README.md index 7aa8112b95..8183d7f83c 100644 --- a/compiler/backend/README.md +++ b/compiler/backend/README.md @@ -12,34 +12,8 @@ Typedtree translation in `compiler/typing/translcore.ml` and `lam_pass_*.ml` and the other `lam_*.ml` modules : Analyze and transform Lambda. [`lam_compile_main.ml`](lam_compile_main.ml) - coordinates the backend pass sequence; read it before inserting or - reordering a pass. - - The sequence is hand-unrolled rather than iterated to a fixed point. Only - `simplify_alias` reads the statistics, and a fresh `collect_info` runs - immediately before each of its three rounds. `simplify_lets` and `sroa` - compute what they need themselves. Each `-debug-ir` dump is named after the - pass whose output it holds. - - | # | pass | statistics | - |---|---|---| - | 1 | `collapse_var_aliases` | | - | 2 | `deep_flatten` | | - | 3 | `simplify_exits` | | - | 4 | `simplify_alias` | reads a snapshot taken just before | - | 5 | `deep_flatten` | | - | 6 | `simplify_alias` | reads a snapshot taken just before | - | 7 | `deep_flatten` | | - | 8 | `simplify_exits` | | - | 9 | `simplify_alias` | reads a snapshot taken just before | - | 10 | `simplify_lets` | own occurrence count | - | 11 | `sroa` | own field-use classification | - | 12 | `simplify_exits` | | - | 13 | `guard_raises` | | - - A snapshot is fresh when its pass starts, but `simplify_alias` also mutates - the table as it rewrites, so entries can describe an earlier version of the - term by the time the pass finishes. + coordinates the backend pass sequence; read it and the Lambda pipeline + below before inserting or reordering a pass. [`lam_compile.ml`](lam_compile.ml) : Lowers Lambda to JavaScript IR. Primitive-specific and FFI lowering is split @@ -54,6 +28,50 @@ Typedtree translation in `compiler/typing/translcore.ml` and The driver's [`js_implementation.ml`](../driver/js_implementation.ml) runs a source file through all compiler layers. +## Lambda pipeline + +`lam_compile_main.ml` runs the passes in a fixed order. The sequence is +hand-unrolled rather than iterated to a fixed point. Each `-debug-ir` dump +is named after the pass whose output it holds. + +| # | pass | what it does here | +|---|---|---| +| 1 | `collapse_var_aliases` | removes `let x = y` | +| 2 | `deep_flatten` | lifts nested lets, replaces a tuple that is only read field by field with its fields | +| 3 | `simplify_exits` | drops unused static exits, inlines those used once | +| 4 | `collect_info` + `simplify_alias` | first inlining round | +| 5 | `deep_flatten` | normalizes the inlined code | +| 6 | `collect_info` + `simplify_alias` | second round | +| 7 | `deep_flatten`, `simplify_exits` | normalize again | +| 8 | `collect_info` + `simplify_alias` | third round | +| 9 | `simplify_lets` | removes and inlines lets by their uses | +| 10 | `sroa` | turns local refs and mutable records into variables | +| 11 | `simplify_exits` | | +| 12 | `guard_raises` | | + +`simplify_alias` inlines functions and uses what `collect_info` recorded +about each variable: what it is bound to, such as a function, a `Some` or a +block. An inlined body brings new bindings and new known values, so a +later round can resolve more. The facts are collected again before each +round, because the round before rewrote the term and the old entries can +name variables that are gone. The pass also updates the table as it +rewrites, so by its end some entries describe an earlier term. +`deep_flatten` and `simplify_exits` between rounds bring the inlined code +back to the shape the next round expects. `simplify_lets` and `sroa` +compute what they need themselves. + +There is one cross-module inlining phase: `simplify_alias` inlines a full +call of another module's `@inline` function or functor, whose body that +module stored in its `.cmj`. A call it leaves alone is compiled as a call. +Inlining at the JavaScript level (`js_pass_tailcall_inline.ml`) is a +separate step for local functions. + +`sroa` runs last because it is the only pass that creates `Lassign`. Every +pass before it relies on there being none, so a variable keeps the value it +is bound to. With `-check-lam`, `Lam_check.check` checks this after every +pass before `sroa`. A body another module stores was optimized by its own +`sroa`, so a body that assigns a variable is not stored (warning 113). + ## Changing a representation `Lambda.t` is private: every term is built through the constructors in diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 0f61772afa..2c9a97e6f4 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -577,43 +577,15 @@ let compile output_prefix = and compile_external_field_apply (appinfo : Lambda.lambda_apply) (module_id : Ident.t) (field_name : string) (lambda_cxt : Lam_compile_context.t) : Js_output.t = - let ident_info = - Lam_compile_env.query_external_id_info module_id field_name + (* A call that the alias pass did not inline is compiled as a call *) + let args_code, args = compile_arguments lambda_cxt appinfo.ap_args in + let fn = E.ml_var_dot module_id field_name in + let expression = + E.call ~info:(call_info_of_apply lambda_cxt.meta appinfo) fn args in - let ap_args = appinfo.ap_args in - match ident_info.persistent_closed_lambda with - | Some (Lfunction ({params; body; _} as lfunction)) - when List.compare_lengths params ap_args = 0 - && Lambda.lfunction_can_be_inlined lfunction -> - (* TODO: serialize it when exporting to save compile time *) - let _, param_map = - Lam_closure.is_closed_with_map Set_ident.empty params body - in - let inlined = - Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta param_map - params body ap_args - in - (* The inlined body comes from another module, so the variables it - assigns are not in [meta.assignable] yet. *) - let meta = - { - lambda_cxt.meta with - assignable = - Set_ident.union lambda_cxt.meta.assignable - (Lambda_traverse.assigned_variables inlined); - } - in - compile_lambda {lambda_cxt with meta} inlined - | _ -> - let args_code, args = compile_arguments lambda_cxt ap_args in - - let fn = E.ml_var_dot module_id ident_info.name in - let expression = - E.call ~info:(call_info_of_apply lambda_cxt.meta appinfo) fn args - in - let expression = with_source_loc appinfo.ap_loc expression in - Js_output.output_of_block_and_expression lambda_cxt.continuation args_code - expression + let expression = with_source_loc appinfo.ap_loc expression in + Js_output.output_of_block_and_expression lambda_cxt.continuation args_code + expression (* The second return value holds declarations, such as [dummy_obj] placeholders, that are emitted before the bindings diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index e4f6c97799..08e9c75aa0 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -166,9 +166,8 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = and functors store one, and every full call of it is inlined *) when List.compare_lengths params args = 0 && Lambda.lfunction_can_be_inlined lfunction -> - (* Like the inlining in [Lam_compile]: an argument without side - effects that the body reads once takes the parameter's place, - instead of a binding of its own *) + (* An argument without side effects that the body reads once takes + the parameter's place, instead of a binding of its own *) let _, param_map = Lam_closure.is_closed_with_map Set_ident.empty params body in diff --git a/tests/compiler_tests/src/hello_res.mjs b/tests/compiler_tests/src/hello_res.mjs index 803440b662..456027a0c6 100644 --- a/tests/compiler_tests/src/hello_res.mjs +++ b/tests/compiler_tests/src/hello_res.mjs @@ -8,9 +8,9 @@ let a = b - 1 | 0; console.log("hello, res"); -Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}}); +Stdlib_List.add(/* [] */0, Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}})); -Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}}); +Stdlib_List.add(/* [] */0, Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}})); console.log(3); diff --git a/tests/compiler_tests/src/inline_late_alias_lib.mjs b/tests/compiler_tests/src/inline_late_alias_lib.mjs new file mode 100644 index 0000000000..c20d4674c4 --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_lib.mjs @@ -0,0 +1,62 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; + +function id(x) { + return x; +} + +let c = id(3); + +function apply(x, f) { + return f(x); +} + +function apply2(p, v, g) { + return g(v, p); +} + +function unwrapG(x, o) { + if (o !== undefined) { + return [ + Primitive_option.valFromOption(o), + x + ]; + } +} + +function weird(p, o, f) { + f(); + if (o !== undefined) { + return o + p | 0; + } else { + return p; + } +} + +function weirdT(p, t, f) { + f(); + return t[0] + p | 0; +} + +function weirdG(p, o, f) { + f(); + if (o !== undefined) { + return [ + Primitive_option.valFromOption(o), + p + ]; + } +} + +export { + id, + c, + apply, + apply2, + unwrapG, + weird, + weirdT, + weirdG, +} +/* c Not a pure module */ diff --git a/tests/compiler_tests/src/inline_late_alias_lib.res b/tests/compiler_tests/src/inline_late_alias_lib.res new file mode 100644 index 0000000000..f4c3e84464 --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_lib.res @@ -0,0 +1,44 @@ +// Inlined by inline_late_alias_test.res. Each call there passes a parameter of +// the caller. +@inline(never) let id = x => x + +let c = id(3) + +@inline +let apply = (x, f) => f(x) + +@inline +let apply2 = (p: int, v, g) => g(v, p) + +@inline +let unwrapG = (x: int, o: option<'a>) => + switch o { + | Some(v) => Some((v, x)) + | None => None + } + +// [f] may assign the variable the option or the tuple was made from. +@inline +let weird = (p: int, o: option, f) => { + f() + switch o { + | Some(v) => v + p + | None => p + } +} + +@inline +let weirdT = (p: int, t: (int, int), f) => { + f() + let (a, _) = t + a + p +} + +@inline +let weirdG = (p: int, o: option<'a>, f) => { + f() + switch o { + | Some(v) => Some((v, p)) + | None => None + } +} diff --git a/tests/compiler_tests/src/inline_late_alias_test.mjs b/tests/compiler_tests/src/inline_late_alias_test.mjs new file mode 100644 index 0000000000..892ed59b16 --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_test.mjs @@ -0,0 +1,198 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; +import * as Inline_late_alias_lib from "./inline_late_alias_lib.mjs"; + +function letBoundGlobal(p) { + return (p + Inline_late_alias_lib.c | 0) + (p + Inline_late_alias_lib.c | 0) | 0; +} + +function tupleField(p, q) { + return (p + q.length | 0) + (p + q.length | 0) | 0; +} + +function assignedRef(p) { + let r = 0; + r = 10; + return (p + r | 0) + (p + r | 0) | 0; +} + +function assignedRecord(p) { + let r_a = 1; + let r_b = 2; + r_b = 10; + r_a = r_a + r_b | 0; + return ((p + r_b | 0) + (p + r_b | 0) | 0) + r_a | 0; +} + +function someGlobal(p) { + return [ + [ + Inline_late_alias_lib.c, + p + ], + Inline_late_alias_lib.c + ]; +} + +function someField(p, q) { + let a = q[0]; + return [ + [ + a, + p + ], + a + ]; +} + +function someTupleField(p, q) { + return [ + [ + q, + p + ], + q + ]; +} + +function readBeforeCall(p, n) { + let r = 1; + let f = () => { + for (let i = 0; i <= n; ++i) { + r = r + i | 0; + } + }; + let x = r; + f(); + let res = x + p | 0; + return [ + res, + r + ]; +} + +function someBeforeCall(p, n) { + let r = 1; + let f = () => { + for (let i = 0; i <= n; ++i) { + r = r + i | 0; + } + }; + let o = r; + f(); + let res = o + p | 0; + return [ + res, + r + ]; +} + +function tupleBeforeCall(p, n) { + let r = 1; + let f = () => { + for (let i = 0; i <= n; ++i) { + r = r + i | 0; + } + }; + let t_0 = r; + f(); + let res = t_0 + p | 0; + return [ + res, + r + ]; +} + +function genericSomeBeforeCall(p, n, q, q2) { + let r = q; + let f = () => { + for (let _for = 0; _for <= n; ++_for) { + r = q2; + } + }; + let o = Primitive_option.some(r); + f(); + let res = [ + Primitive_option.valFromOption(o), + p + ]; + return [ + res, + r + ]; +} + +Mocha.describe("Inline_late_alias_test", () => { + Mocha.test("a function reading a let-bound global", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 108, characters 7-14", 8, letBoundGlobal(1))); + Mocha.test("a function reading a field of a known tuple", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 112, characters 7-14", 8, tupleField(1, [ + 1, + 2, + 3 + ]))); + Mocha.test("a function reading a ref assigned before the calls", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 116, characters 7-14", 22, assignedRef(1))); + Mocha.test("a function reading a mutable field assigned before the calls", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 120, characters 7-14", 33, assignedRecord(1))); + Mocha.test("a Some of a let-bound global", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 124, characters 7-14", [ + [ + 3, + 1 + ], + 3 + ], someGlobal(1))); + Mocha.test("a Some of a field of a parameter", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 128, characters 7-14", [ + [ + 5, + 1 + ], + 5 + ], someField(1, [ + 5, + 6 + ]))); + Mocha.test("a Some of a field of a known tuple", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 132, characters 7-14", [ + [ + "a", + 1 + ], + "a" + ], someTupleField(1, "a"))); + Mocha.test("an argument read before a call that assigns it", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 136, characters 7-14", [ + 2, + 7 + ], readBeforeCall(1, 3))); + Mocha.test("a Some made before a call that assigns its variable", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 140, characters 7-14", [ + 2, + 7 + ], someBeforeCall(1, 3))); + Mocha.test("a tuple made before a call that assigns its variable", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 144, characters 7-14", [ + 2, + 7 + ], tupleBeforeCall(1, 3))); + Mocha.test("a generic Some made before a call that assigns its variable", () => Test_utils.eq("File \"inline_late_alias_test.res\", line 148, characters 7-14", [ + [ + "a", + 1 + ], + "b" + ], genericSomeBeforeCall(1, 3, "a", "b"))); +}); + +let L; + +export { + L, + letBoundGlobal, + tupleField, + assignedRef, + assignedRecord, + someGlobal, + someField, + someTupleField, + readBeforeCall, + someBeforeCall, + tupleBeforeCall, + genericSomeBeforeCall, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_late_alias_test.res b/tests/compiler_tests/src/inline_late_alias_test.res new file mode 100644 index 0000000000..9c3fff262c --- /dev/null +++ b/tests/compiler_tests/src/inline_late_alias_test.res @@ -0,0 +1,150 @@ +// Calls that pass a parameter of the caller used to be inlined while compiling +// to JavaScript, after the other passes had rewritten the function around them. +// These cases broke when such a body was simplified there. The alias pass +// inlines the calls now, and the caller's refs must still be read in order. +open Mocha +open Test_utils + +module L = Inline_late_alias_lib + +let letBoundGlobal = p => { + let k = L.c + let h = x => x + k + L.apply(p, h) + L.apply(p, h) +} + +let tupleField = (p, q: array) => { + let t = (q, 1) + let (a, _) = t + let h = x => x + Array.length(a) + L.apply(p, h) + L.apply(p, h) +} + +let assignedRef = p => { + let r = ref(0) + let h = x => x + r.contents + r := 10 + L.apply(p, h) + L.apply(p, h) +} + +type pt = {mutable a: int, mutable b: int} + +let assignedRecord = p => { + let r = {a: 1, b: 2} + let h = x => x + r.b + r.b = 10 + r.a = r.a + r.b + L.apply(p, h) + L.apply(p, h) + r.a +} + +let someGlobal = p => { + let y = L.c + let x = Some(y) + (L.unwrapG(p, x), x) +} + +let someField = (p, q: (int, int)) => { + let (a, _) = q + let x = Some(a) + (L.unwrapG(p, x), x) +} + +let someTupleField = (p, q: string) => { + let t = (q, 1) + let (y, _) = t + let x = Some(y) + (L.unwrapG(p, x), x) +} + +let readBeforeCall = (p, n) => { + let r = ref(1) + let f = () => { + for i in 0 to n { + r := r.contents + i + } + } + let res = L.apply2(p, r.contents, (x, pp) => { + f() + x + pp + }) + (res, r.contents) +} + +let someBeforeCall = (p, n) => { + let r = ref(1) + let f = () => { + for i in 0 to n { + r := r.contents + i + } + } + let res = L.weird(p, Some(r.contents), f) + (res, r.contents) +} + +let tupleBeforeCall = (p, n) => { + let r = ref(1) + let f = () => { + for i in 0 to n { + r := r.contents + i + } + } + let res = L.weirdT(p, (r.contents, 2), f) + (res, r.contents) +} + +let genericSomeBeforeCall = (p, n, q: 'a, q2: 'a) => { + let r = ref(q) + let f = () => { + for _ in 0 to n { + r := q2 + } + } + let res = L.weirdG(p, Some(r.contents), f) + (res, r.contents) +} + +describe(__MODULE__, () => { + test("a function reading a let-bound global", () => { + eq(__LOC__, 8, letBoundGlobal(1)) + }) + + test("a function reading a field of a known tuple", () => { + eq(__LOC__, 8, tupleField(1, [1, 2, 3])) + }) + + test("a function reading a ref assigned before the calls", () => { + eq(__LOC__, 22, assignedRef(1)) + }) + + test("a function reading a mutable field assigned before the calls", () => { + eq(__LOC__, 33, assignedRecord(1)) + }) + + test("a Some of a let-bound global", () => { + eq(__LOC__, (Some((3, 1)), Some(3)), someGlobal(1)) + }) + + test("a Some of a field of a parameter", () => { + eq(__LOC__, (Some((5, 1)), Some(5)), someField(1, (5, 6))) + }) + + test("a Some of a field of a known tuple", () => { + eq(__LOC__, (Some(("a", 1)), Some("a")), someTupleField(1, "a")) + }) + + test("an argument read before a call that assigns it", () => { + eq(__LOC__, (2, 7), readBeforeCall(1, 3)) + }) + + test("a Some made before a call that assigns its variable", () => { + eq(__LOC__, (2, 7), someBeforeCall(1, 3)) + }) + + test("a tuple made before a call that assigns its variable", () => { + eq(__LOC__, (2, 7), tupleBeforeCall(1, 3)) + }) + + test("a generic Some made before a call that assigns its variable", () => { + eq(__LOC__, (Some(("a", 1)), "b"), genericSomeBeforeCall(1, 3, "a", "b")) + }) +})