diff --git a/changes/inline-literal-arg-once.fix.md b/changes/inline-literal-arg-once.fix.md new file mode 100644 index 0000000000..b55b9008cb --- /dev/null +++ b/changes/inline-literal-arg-once.fix.md @@ -0,0 +1 @@ +- Fix inlining that built a record, tuple or option literal argument again at each use of the parameter. diff --git a/compiler/backend/lam_beta_reduce.ml b/compiler/backend/lam_beta_reduce.ml index b155ad6831..88d99b2cc8 100644 --- a/compiler/backend/lam_beta_reduce.ml +++ b/compiler/backend/lam_beta_reduce.ml @@ -123,7 +123,8 @@ let propagate_beta_reduce (meta : Lam_stats.t) (params : Ident.t list) List.fold_left2 (fun (rest_bindings, acc) old_param ((arg : Lambda.t), effects_after) -> match arg with - | Lconst _ -> (rest_bindings, arg :: acc) + | Lconst c when not (Lambda.const_has_identity c) -> + (rest_bindings, arg :: acc) | Lvar _ when can_move ~assignable ~effects_after old_param body arg -> (rest_bindings, arg :: acc) @@ -170,7 +171,8 @@ let propagate_beta_reduce_with_map (meta : Lam_stats.t) ((p, arg) :: rest_bindings, Lambda.var p :: acc) in match arg with - | Lconst _ -> (rest_bindings, arg :: acc) + | Lconst c when not (Lambda.const_has_identity c) -> + (rest_bindings, arg :: acc) | Lvar _ -> if can_move ~assignable ~effects_after old_param body arg then (rest_bindings, arg :: acc) diff --git a/compiler/backend/lam_pass_remove_alias.ml b/compiler/backend/lam_pass_remove_alias.ml index 0c12d7c657..655994382d 100644 --- a/compiler/backend/lam_pass_remove_alias.ml +++ b/compiler/backend/lam_pass_remove_alias.ml @@ -279,6 +279,17 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t = (Ext_list.map_snd sw simpl) (Option.map simpl d) | None -> Lambda_traverse.shallow_map_sharing simpl lam) + | Lswitch (Lvar s, sw) -> ( + (* Take the case for the constant the scrutinee is bound to. When no + case is chosen, keep the variable: a block constant would be built + again. *) + match Hash_ident.find_opt meta.ident_tbl s with + | Some (Constant c) -> ( + match Lambda.switch (Lambda.const c) sw with + | Lswitch (_, sw') when sw' == sw -> + Lambda_traverse.shallow_map_sharing simpl lam + | action -> simpl action) + | Some _ | None -> Lambda_traverse.shallow_map_sharing simpl lam) | _ -> Lambda_traverse.shallow_map_sharing simpl lam in simpl lam diff --git a/compiler/typing/lambda.ml b/compiler/typing/lambda.ml index 5c289e56df..85263275bf 100644 --- a/compiler/typing/lambda.ml +++ b/compiler/typing/lambda.ml @@ -601,6 +601,21 @@ let rec const_is_allocating (c : structured_constant) : bool = | Const_module_alias -> false +(* Whether a constant compiles to an object literal, whose identity the program + can observe, such as a record or a [Some] around one. Excludes a nested none + such as [Some(None)]: [Primitive_option.some] returns one frozen marker + object for each nesting depth, so every copy is the same object and [===] + still holds. *) +let rec const_has_identity (c : structured_constant) : bool = + match c with + | Const_block _ -> true + | Const_some t -> const_has_identity t + | Const_js_null | Const_js_undefined _ | Const_js_true | Const_js_false + | Const_int _ | Const_assertfalse | Const_constructor _ | Const_char _ + | Const_string _ | Const_float _ | Const_bigint _ | Const_polyvar _ + | Const_module_alias -> + false + let rec const_eq_approx (x : structured_constant) (y : structured_constant) = match x with | Const_module_alias -> y = Const_module_alias diff --git a/compiler/typing/lambda.mli b/compiler/typing/lambda.mli index 4b5e70dd05..4becfaf430 100644 --- a/compiler/typing/lambda.mli +++ b/compiler/typing/lambda.mli @@ -446,6 +446,8 @@ val const_some_none_depth : structured_constant -> int val const_is_allocating : structured_constant -> bool +val const_has_identity : structured_constant -> bool + val lfunction_can_be_inlined : lfunction -> bool (** Whether the function may give way to the code it runs: its body replacing a call to it, or the call it forwards to replacing the function itself. An diff --git a/tests/compiler_tests/src/gpr_1822_test.mjs b/tests/compiler_tests/src/gpr_1822_test.mjs index 5f1123d773..5fe939a8b6 100644 --- a/tests/compiler_tests/src/gpr_1822_test.mjs +++ b/tests/compiler_tests/src/gpr_1822_test.mjs @@ -5,12 +5,7 @@ import * as Test_utils from "./test_utils.mjs"; Mocha.describe("Gpr_1822_test", () => { Mocha.test("gpr_1822_test", () => { - let myShape = { - TAG: "Circle", - _0: 10 - }; - let area; - area = myShape.TAG === "Circle" ? 100 * 3.14 : 10 * myShape._1 | 0; + let area = 100 * 3.14; Test_utils.eq("File \"gpr_1822_test.res\", line 16, characters 7-14", area, 314); }); }); diff --git a/tests/compiler_tests/src/gpr_5280_optimize_test.mjs b/tests/compiler_tests/src/gpr_5280_optimize_test.mjs index d9b2adb7ef..387786679d 100644 --- a/tests/compiler_tests/src/gpr_5280_optimize_test.mjs +++ b/tests/compiler_tests/src/gpr_5280_optimize_test.mjs @@ -6,12 +6,10 @@ let a = { _0: "#ffff" }; -let c; - -c = typeof a !== "object" ? "orange" : "white"; +let c = "white"; export { a, c, } -/* c Not a pure module */ +/* No side effect */ diff --git a/tests/compiler_tests/src/inline_condition_with_pattern_matching.mjs b/tests/compiler_tests/src/inline_condition_with_pattern_matching.mjs index dfc175147f..21d056e816 100644 --- a/tests/compiler_tests/src/inline_condition_with_pattern_matching.mjs +++ b/tests/compiler_tests/src/inline_condition_with_pattern_matching.mjs @@ -1,61 +1,31 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -let person1 = { +let Test1_person1 = { TAG: "Teacher", age: 12345 }; -let message; - -if (person1.TAG === "Teacher") { - message = "b"; -} else { - let tmp = 12345; - message = typeof tmp !== "object" || tmp.TAG === "Vacations" ? "a" : "b"; -} - let Test1 = { - person1: person1, - message: message + person1: Test1_person1, + message: "b" }; -let person2 = { +let message = `Hello Jane.`; + +let Test2_person2 = { TAG: "Teacher", name: "Jane", age: 12345 }; -let message$1; - -if (person2.TAG === "Teacher") { - message$1 = `Hello Jane.`; -} else { - let name = "Jane"; - let match = person2.reportCard; - if (match.passing) { - message$1 = `Congrats ${name}, nice GPA of ${match.gpa.toString()} you got there!`; - } else { - let exit = 0; - let tmp$1 = 12345; - if (typeof tmp$1 !== "object") { - message$1 = tmp$1 === "Sick" ? `How are you feeling?` : `Good luck next semester ${name}!`; - } else { - exit = 1; - } - if (exit === 1) { - message$1 = person2.reportCard.gpa !== 0.0 ? `Good luck next semester ${name}!` : `Come back in ${(12345)._0.toString()} days!`; - } - } -} - let Test2 = { - person2: person2, - message: message$1 + person2: Test2_person2, + message: message }; export { Test1, Test2, } -/* message Not a pure module */ +/* No side effect */ diff --git a/tests/compiler_tests/src/inline_literal_arg_identity_test.mjs b/tests/compiler_tests/src/inline_literal_arg_identity_test.mjs new file mode 100644 index 0000000000..e5e5cc5944 --- /dev/null +++ b/tests/compiler_tests/src/inline_literal_arg_identity_test.mjs @@ -0,0 +1,53 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; + +function same(b) { + return b === b; +} + +function samePair(p) { + return p === p; +} + +function sameOption(o) { + return o === o; +} + +function sum(b) { + return b.x + b.y | 0; +} + +Mocha.describe("Inline_literal_arg_identity_test", () => { + Mocha.test("a record literal", () => { + let b = { + x: 1, + y: 2 + }; + Test_utils.ok("File \"inline_literal_arg_identity_test.res\", line 22, characters 36-43", b === b); + }); + Mocha.test("a tuple literal", () => { + let p = [ + 1, + 2 + ]; + Test_utils.ok("File \"inline_literal_arg_identity_test.res\", line 23, characters 35-42", p === p); + }); + Mocha.test("an option of a record literal", () => { + let o = { + x: 1, + y: 2 + }; + Test_utils.ok("File \"inline_literal_arg_identity_test.res\", line 24, characters 49-56", o === o); + }); + Mocha.test("fields of a record literal", () => Test_utils.eq("File \"inline_literal_arg_identity_test.res\", line 25, characters 46-53", 3, 3)); +}); + +export { + same, + samePair, + sameOption, + sum, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/inline_literal_arg_identity_test.res b/tests/compiler_tests/src/inline_literal_arg_identity_test.res new file mode 100644 index 0000000000..427de2f9d1 --- /dev/null +++ b/tests/compiler_tests/src/inline_literal_arg_identity_test.res @@ -0,0 +1,26 @@ +open Mocha +open Test_utils + +// An inlined function reads a literal argument as one value: the literal is +// built once, not at each use of the parameter. + +type xy = {x: int, y: int} + +@inline +let same = (b: xy) => b === b + +@inline +let samePair = (p: (int, int)) => p === p + +@inline +let sameOption = (o: option) => o === o + +@inline +let sum = (b: xy) => b.x + b.y + +describe(__MODULE__, () => { + test("a record literal", () => ok(__LOC__, same({x: 1, y: 2}))) + test("a tuple literal", () => ok(__LOC__, samePair((1, 2)))) + test("an option of a record literal", () => ok(__LOC__, sameOption(Some({x: 1, y: 2})))) + test("fields of a record literal", () => eq(__LOC__, sum({x: 1, y: 2}), 3)) +}) diff --git a/tests/compiler_tests/src/inline_record_test.mjs b/tests/compiler_tests/src/inline_record_test.mjs index 21bfc929ae..62cdf4cc8e 100644 --- a/tests/compiler_tests/src/inline_record_test.mjs +++ b/tests/compiler_tests/src/inline_record_test.mjs @@ -81,10 +81,6 @@ function ff1(x) { } } -let b = { - TAG: "B" -}; - Mocha.describe("Inline_record_test", () => { Mocha.test("inline record basic operations", () => { Test_utils.eq("File \"inline_record_test.res\", line 75, characters 7-14", f(v), 3); @@ -165,10 +161,6 @@ Mocha.describe("Inline_record_test", () => { Test_utils.eq("File \"inline_record_test.res\", line 123, characters 6-13", tmp, 11); }); Mocha.test("empty record operations", () => { - if (typeof b !== "object") { - console.log("A!"); - return; - } console.log("B"); }); Mocha.test("record pattern matching", () => { @@ -188,6 +180,10 @@ let vvv = { more: /* [] */0 }; +let b = { + TAG: "B" +}; + let r = { y: 10 }; diff --git a/tests/compiler_tests/src/record_regression.mjs b/tests/compiler_tests/src/record_regression.mjs index 9f23990ec2..1abb0d3e71 100644 --- a/tests/compiler_tests/src/record_regression.mjs +++ b/tests/compiler_tests/src/record_regression.mjs @@ -61,19 +61,6 @@ function setAA(ao) { }; } -let ir0 = { - TAG: "V0", - x0: "v0", - x3: 3 -}; - -let ir1 = { - TAG: "V0", - x0: "v0", - x1: "v1", - x3: 3 -}; - let ir2 = { TAG: "V0", x0: "v0", @@ -88,41 +75,29 @@ let ir3 = { y1: 1 }; -let pm0; - -pm0 = ir0.TAG === "V0" ? [ - "v0", - 3 - ] : [ - "v0", - undefined - ]; - -let pm1; - -pm1 = ir1.TAG === "V0" ? [ - "v0", - "v1", - 3 - ] : [ - "v0", - "n/a", - "v1" - ]; - -let pm2; - -pm2 = ir2.TAG === "V0" ? [ - "v0", - "v1", - 2, - 3 - ] : [ - "v0", - "n/a", - 0, - "v1" - ]; +let pm0 = [ + "v0", + 3 +]; + +let pm1_1 = "v1"; + +let pm1 = [ + "v0", + pm1_1, + 3 +]; + +let pm2_1 = "v1"; + +let pm2_2 = 2; + +let pm2 = [ + "v0", + pm2_1, + pm2_2, + 3 +]; function inlinedRecord(ir) { if (ir.TAG !== "V0") { @@ -219,6 +194,19 @@ let h = newrecord$2; let h10 = newrecord$3; +let ir0 = { + TAG: "V0", + x0: "v0", + x3: 3 +}; + +let ir1 = { + TAG: "V0", + x0: "v0", + x1: "v1", + x3: 3 +}; + let ir4 = { TAG: "V0", x: 3 diff --git a/tests/ounit_tests/ounit_constant_argument_tests.ml b/tests/ounit_tests/ounit_constant_argument_tests.ml new file mode 100644 index 0000000000..cdc90fc088 --- /dev/null +++ b/tests/ounit_tests/ounit_constant_argument_tests.ml @@ -0,0 +1,87 @@ +let ( >:: ), ( >::: ) = OUnit.(( >:: ), ( >::: )) + +let loc = Location.none + +let meta () = + Lam_stats.make ~export_idents:[] ~export_ident_sets:Set_ident.empty + +(* A tuple constant: it compiles to an array literal, a new object *) +let block = Lambda.Const_block (Blk_tuple, [Const_int 1l; Const_int 2l]) + +(* [Some(None)]: it compiles to a [Primitive_option.some] call *) +let nested_none = Lambda.Const_some (Const_js_undefined {is_unit = false}) + +(* [b === b] *) +let same b = + Lambda.prim ~primitive:(Pjscomp Ceq) ~args:[Lambda.var b; Lambda.var b] loc + +let rec count_constants (lam : Lambda.t) = + match lam with + | Lconst _ -> 1 + | _ -> + let count = ref 0 in + ignore + (Lambda_traverse.shallow_exists + (fun child -> + count := !count + count_constants child; + false) + lam); + !count + +(* [switch v { | 1 => 1 }], with [fail] as the default action *) +let switch_on v ~fail = + Lambda.switch (Lambda.var v) + { + sw_consts_full = false; + sw_consts = [(Switch_int 1, Lambda.const (Const_int 1l))]; + sw_blocks_full = false; + sw_blocks = []; + sw_failaction = fail; + sw_dispatch = Switch_direct; + } + +(* [let v = in switch v { ... }], after the alias pass *) +let simplify_switch_on_block ~fail = + let v = Ident.create "v" in + let lam = Lambda.let_ Strict v (Lambda.const block) (switch_on v ~fail) in + let meta = meta () in + Lam_pass_collect.collect_info meta lam; + Lam_pass_remove_alias.simplify_alias meta lam + +let suites = + __FILE__ + >::: [ + ( "an argument with an identity is bound once, not copied" >:: fun _ -> + let b = Ident.create "b" in + let lam = + Lam_beta_reduce.propagate_beta_reduce (meta ()) [b] (same b) + [Lambda.const block] + in + OUnit.assert_equal ~printer:string_of_int 1 (count_constants lam); + match lam with + | Llet (_, id, Lconst _, Lprim {args = [Lvar x; Lvar y]}) -> + OUnit.assert_bool "both uses read the binding" + (Ident.same id x && Ident.same id y) + | _ -> OUnit.assert_failure "expected a let around the comparison" ); + ( "a nested none argument is repeated" >:: fun _ -> + let b = Ident.create "b" in + let lam = + Lam_beta_reduce.propagate_beta_reduce (meta ()) [b] (same b) + [Lambda.const nested_none] + in + match lam with + | Lprim {args = [Lconst _; Lconst _]} -> () + | _ -> OUnit.assert_failure "expected the constant at both uses" ); + ( "a switch on a variable bound to a constant takes its case" + >:: fun _ -> + match + simplify_switch_on_block ~fail:(Some (Lambda.const (Const_int 0l))) + with + | Llet (_, _, _, Lconst (Const_int 0l)) -> () + | _ -> OUnit.assert_failure "expected the failure action" ); + ( "a switch that takes no case keeps the variable" >:: fun _ -> + match simplify_switch_on_block ~fail:None with + | Llet (_, id, _, Lswitch (Lvar x, _)) -> + OUnit.assert_bool "the switch reads the binding" (Ident.same id x) + | _ -> OUnit.assert_failure "expected the switch on the variable" ); + ] diff --git a/tests/ounit_tests/ounit_tests_main.ml b/tests/ounit_tests/ounit_tests_main.ml index 3c601f70c7..dae5859369 100644 --- a/tests/ounit_tests/ounit_tests_main.ml +++ b/tests/ounit_tests/ounit_tests_main.ml @@ -22,6 +22,7 @@ let suites = Ounit_lam_size_tests.suites; Ounit_lam_bounded_vars_tests.suites; Ounit_sroa_tests.suites; + Ounit_constant_argument_tests.suites; Ounit_ast_mapper0_tests.suites; Ounit_ast_helper_tests.suites; Ounit_constructor_arguments_tests.suites;