Skip to content

Commit 81d63a8

Browse files
cknittclaude
andauthored
Use constant arguments directly when inlining a function in JavaScript (#8942)
* Use constant arguments directly when inlining a function in JavaScript Why: When the JavaScript pass inlines a function called once, it replaced a parameter by a variable argument but bound any other argument with `let`, so a constant argument stayed a variable nothing folds away. The pass now also substitutes numbers, booleans, `undefined` and `null`, the constants the Lambda inliner substitutes too, under the same condition as variables: the parameter is never assigned by a tail call. Strings and anything that allocates stay bound once. JS modified (inlined partial application): Example: let g1 = (x, y) => { let u = x + y (xx, yy) => xx + yy + u } let v = g1(3, 4)(6, ...) Before (js): function v(extra) { let xx = 6; return (xx + extra | 0) + 7 | 0; } After (js): function v(extra) { return (6 + extra | 0) + 7 | 0; } Review: Can a substituted parameter be assigned? No: a parameter a tail call assigns is unmasked in the function's immutable mask and stays bound with `let`, as before for variable arguments (`count` in the new test). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Kr4cjoUi2f5VpMvE6wT9bo Signed-off-by: Christoph Knittel <ck@cca.io> * Keep only the taken branch of a condition on an inlined constant Why: Substituting a boolean argument left conditions such as `true ? b - a : a - b` and `if (false)` in the inlined body. When a parameter replaced by a boolean or integer constant is the condition of a `?:` or an `if`, or is negated, the substitution now keeps only the branch taken, or yields the boolean, as `Js_stmt_make.if_` does for constant conditions during code generation. Other conditions and arithmetic are not folded. JS modified (condition on a constant argument): Example: let logged = { let log = (verbose, x) => { let out = [] if verbose { out->Array.push(Int.toString(x)) } if !verbose { out->Array.push("done") } out->Array.push(verbose ? "verbose" : "brief") out } log(false, ...) } Before (js): function logged(extra) { let out = []; if (false) { out.push(extra.toString()); } if (!false) { out.push("done"); } out.push(false ? "verbose" : "brief"); return out; } After (js): function logged(extra) { let out = []; out.push("done"); out.push("brief"); return out; } Review: Can a declaration in the kept branch clash once the branch is flattened into the enclosing block? No more than for the constant conditions `Js_stmt_make.if_` already flattens: names are allocated per function, so a declaration of the same name elsewhere is renamed. Review: Why not rebuild through `Js_exp_make.econd`? It treats any number condition as true, which is wrong for `0.0`, `NaN` and `0n`, so only boolean and integer constants decide a condition here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Kr4cjoUi2f5VpMvE6wT9bo Signed-off-by: Christoph Knittel <ck@cca.io> --------- Signed-off-by: Christoph Knittel <ck@cca.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f472ee8 commit 81d63a8

6 files changed

Lines changed: 210 additions & 19 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Use constant arguments directly when inlining a function in generated JavaScript, instead of binding them to variables first.

‎compiler/core/js_pass_tailcall_inline.ml‎

Lines changed: 73 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,73 @@
3333
*)
3434

3535
module S = Js_stmt_make
36-
(* module E = Js_exp_make *)
36+
module E = Js_exp_make
3737

3838
let super = Js_record_map.super
3939

40-
let substitue_variables (map : Ident.t Map_ident.t) =
40+
(* The truth value of a condition that is a parameter replaced by a boolean or
41+
integer constant, or its negation. Only such conditions are decided while
42+
substituting: the substitution is what made them constant. *)
43+
let rec substituted_truth (consts : J.expression Map_ident.t) (e : J.expression)
44+
=
45+
match e.expression_desc with
46+
| Var (Id id) -> (
47+
match Map_ident.find_opt id consts with
48+
| Some {expression_desc = Bool b} -> Some b
49+
| Some {expression_desc = Number (Int {i})} -> Some (i <> 0l)
50+
| _ -> None)
51+
| Js_not e -> Option.map not (substituted_truth consts e)
52+
| _ -> None
53+
54+
(* [vars] maps a parameter to the variable argument that replaces it, [consts]
55+
to the constant argument that replaces it. Both apply only to parameters
56+
that are never assigned, so every occurrence of such a parameter is a read.
57+
A conditional whose condition becomes a constant keeps only the branch it
58+
takes, and the negation of such a condition becomes a boolean. *)
59+
let substitute_arguments (vars : Ident.t Map_ident.t)
60+
(consts : J.expression Map_ident.t) =
4161
{
4262
super with
4363
ident =
4464
(fun _ id ->
45-
match Map_ident.find_opt id map with
65+
match Map_ident.find_opt id vars with
4666
| Some id -> id
4767
| None -> id);
68+
expression =
69+
(fun self e ->
70+
match e.expression_desc with
71+
| Var (Id id) -> (
72+
match Map_ident.find_opt id consts with
73+
| Some c -> c
74+
| None -> super.expression self e)
75+
| Cond (pred, ifso, ifnot) -> (
76+
match substituted_truth consts pred with
77+
| Some truth -> self.expression self (if truth then ifso else ifnot)
78+
| None -> super.expression self e)
79+
| Js_not pred -> (
80+
match substituted_truth consts pred with
81+
| Some truth -> E.bool (not truth)
82+
| None -> super.expression self e)
83+
| _ -> super.expression self e);
84+
statement =
85+
(fun self st ->
86+
match st.statement_desc with
87+
| If (pred, ifso, ifnot) -> (
88+
match substituted_truth consts pred with
89+
| Some truth ->
90+
S.block (self.block self (if truth then ifso else ifnot))
91+
| None -> super.statement self st)
92+
| _ -> super.statement self st);
4893
}
4994

95+
(* Constants that are as cheap to repeat as the variable they replace: they
96+
allocate nothing, have no side effect, and print short. The Lambda inliner
97+
substitutes the same kinds of constants for let-bound variables. *)
98+
let is_substitutable_constant (e : J.expression) =
99+
match e.expression_desc with
100+
| Number _ | Bool _ | Undefined _ | Null -> true
101+
| _ -> false
102+
50103
(* 1. recursive value ? let rec x = 1 :: x
51104
non-terminating
52105
2. duplicative identifiers ..
@@ -66,23 +119,28 @@ let substitue_variables (map : Ident.t Map_ident.t) =
66119

67120
let inline_call (immutable_list : bool list) params (args : J.expression list)
68121
processed_blocks =
69-
let map, block =
122+
let substitute param (arg : J.expression) (vars, consts, acc) =
123+
match arg.expression_desc with
124+
| Var (Id id) -> (Map_ident.add param id vars, consts, acc)
125+
| _ when is_substitutable_constant arg ->
126+
(vars, Map_ident.add param arg consts, acc)
127+
| _ -> (vars, consts, S.define_variable ~kind:Variable param arg :: acc)
128+
in
129+
let vars, consts, block =
70130
if immutable_list = [] then
71-
Ext_list.fold_right2 params args (Map_ident.empty, processed_blocks)
72-
(fun param arg (map, acc) ->
73-
match arg.expression_desc with
74-
| Var (Id id) -> (Map_ident.add param id map, acc)
75-
| _ -> (map, S.define_variable ~kind:Variable param arg :: acc))
131+
Ext_list.fold_right2 params args
132+
(Map_ident.empty, Map_ident.empty, processed_blocks)
133+
substitute
76134
else
77135
Ext_list.fold_right3 params args immutable_list
78-
(Map_ident.empty, processed_blocks) (fun param arg mask (map, acc) ->
79-
match (mask, arg.expression_desc) with
80-
| true, Var (Id id) -> (Map_ident.add param id map, acc)
81-
| _ -> (map, S.define_variable ~kind:Variable param arg :: acc))
136+
(Map_ident.empty, Map_ident.empty, processed_blocks)
137+
(fun param arg mask ((vars, consts, acc) as state) ->
138+
if mask then substitute param arg state
139+
else (vars, consts, S.define_variable ~kind:Variable param arg :: acc))
82140
in
83-
if Map_ident.is_empty map then block
141+
if Map_ident.is_empty vars && Map_ident.is_empty consts then block
84142
else
85-
let obj = substitue_variables map in
143+
let obj = substitute_arguments vars consts in
86144
obj.block obj block
87145

88146
(** There is a side effect when traversing dead code, since
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Generated by ReScript, PLEASE EDIT WITH CARE
2+
3+
import * as Mocha from "mocha";
4+
import * as Test_utils from "./test_utils.mjs";
5+
6+
function scaled(extra) {
7+
let label = "value: ";
8+
let a = 1 * 2.5 + -1;
9+
let b = extra * 2.5 - -1;
10+
let c = b - a;
11+
return label + (c + a * b).toString();
12+
}
13+
14+
function intsApplied(extra) {
15+
let s = (2 + (-3 * extra | 0) | 0) - 7 | 0;
16+
let t = (s * -3 | 0) + (7 * 2 | 0) | 0;
17+
return 10n + BigInt((s * t | 0) + -3 | 0);
18+
}
19+
20+
function logged(extra) {
21+
let out = [];
22+
let line = "quiet " + extra.toString();
23+
out.push(line);
24+
out.push("done");
25+
out.push("brief");
26+
return out;
27+
}
28+
29+
function count() {
30+
let _n = 10;
31+
let _acc = 0;
32+
while (true) {
33+
let acc = _acc;
34+
let n = _n;
35+
if (n <= 0) {
36+
return acc;
37+
}
38+
_acc = acc + n | 0;
39+
_n = n - 1 | 0;
40+
continue;
41+
};
42+
}
43+
44+
Mocha.describe("Inline_constant_args_test", () => {
45+
Mocha.test("float, bool and string constants", () => Test_utils.eq("File \"inline_constant_args_test.res\", line 62, characters 7-14", "value: 13.5", scaled(2)));
46+
Mocha.test("int and bigint constants", () => Test_utils.eq("File \"inline_constant_args_test.res\", line 65, characters 7-14", -777n, intsApplied(3)));
47+
Mocha.test("bool constant conditions", () => Test_utils.eq("File \"inline_constant_args_test.res\", line 68, characters 7-14", [
48+
"quiet 4",
49+
"done",
50+
"brief"
51+
], logged(4)));
52+
Mocha.test("reassigned parameter", () => Test_utils.eq("File \"inline_constant_args_test.res\", line 71, characters 7-14", 55, count()));
53+
});
54+
55+
export {
56+
scaled,
57+
intsApplied,
58+
logged,
59+
count,
60+
}
61+
/* Not a pure module */
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
open Mocha
2+
open Test_utils
3+
4+
// The partial applications inline the local functions in JS: constant
5+
// arguments replace the parameters, except the string, which stays bound.
6+
let scaled = {
7+
let scale = (k, offset, flip, label, x, y) => {
8+
let a = x *. k +. offset
9+
let b = y *. k -. offset
10+
let c = if flip {
11+
b -. a
12+
} else {
13+
a -. b
14+
}
15+
label ++ Float.toString(c +. a *. b)
16+
}
17+
scale(2.5, -1., true, "value: ", 1., ...)
18+
}
19+
20+
let intsApplied = {
21+
let ints = (a, b, big, x, y) => {
22+
let s = x + a * y - b
23+
let t = s * a + b * x
24+
big + BigInt.fromInt(s * t + a)
25+
}
26+
ints(-3, 7, 10n, 2, ...)
27+
}
28+
29+
// A condition on a constant argument keeps only the branch it takes.
30+
let logged = {
31+
let log = (verbose, prefix, x) => {
32+
let out = []
33+
if verbose {
34+
let line = prefix ++ Int.toString(x)
35+
out->Array.push(line)
36+
} else {
37+
let line = "quiet " ++ Int.toString(x)
38+
out->Array.push(line)
39+
}
40+
if !verbose {
41+
out->Array.push("done")
42+
}
43+
out->Array.push(verbose ? "verbose" : "brief")
44+
out
45+
}
46+
log(false, "x = ", ...)
47+
}
48+
49+
// [n] is reassigned by the loop, so the constant must stay bound.
50+
let count = () => {
51+
let rec loop = (n, acc) =>
52+
if n > 0 {
53+
loop(n - 1, acc + n)
54+
} else {
55+
acc
56+
}
57+
loop(10, 0)
58+
}
59+
60+
describe(__MODULE__, () => {
61+
test("float, bool and string constants", () => {
62+
eq(__LOC__, "value: 13.5", scaled(2.))
63+
})
64+
test("int and bigint constants", () => {
65+
eq(__LOC__, -777n, intsApplied(3))
66+
})
67+
test("bool constant conditions", () => {
68+
eq(__LOC__, ["quiet 4", "done", "brief"], logged(4))
69+
})
70+
test("reassigned parameter", () => {
71+
eq(__LOC__, 55, count())
72+
})
73+
})

‎tests/tests/src/loop_regression_test.mjs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@ import * as Test_utils from "./test_utils.mjs";
66
function f() {
77
let v = 0;
88
let acc = 0;
9-
let n = 10;
109
while (true) {
11-
if (v > n) {
10+
if (v > 10) {
1211
return acc;
1312
}
1413
acc = acc + v | 0;

‎tests/tests/src/test_demo.mjs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,7 @@ function g1(x, y) {
5555
let x = 14;
5656

5757
function v(extra) {
58-
let xx = 6;
59-
return (xx + extra | 0) + 7 | 0;
58+
return (6 + extra | 0) + 7 | 0;
6059
}
6160

6261
let nil = "Nil";

0 commit comments

Comments
 (0)