From f31db22102bde44c6ee17bc756bdeb109855acea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Muska=C5=82a?= Date: Wed, 9 May 2018 19:41:24 +0200 Subject: Optimise creation of anonymous functions This introduces a similar optimisation for normal funs to what was introduced for external funs in #1725. It is possible to allocate the fun as a literal, if it does not capture the environment (i.e. it does not close over any variables). Unfortunately it's not possible to do this in the compiler due to problems with representation of such functions in the `.beam` files. Fortunately, we can do this in the loader. Simple evaluation shows that functions that don't capture the enviornment consistute over 60% of all funs in the source code of Erlang/OTP itself. The only downside is that we lose a meningful value in the `pid` field of the fun. The goal of this field, beyond debugging, was to be able to identify the original node of a function. To be able to still do this, the functions that are created in the loader are assigned the init pid as the creator. To solve issues with staryp, initially set the `erts_init_process_id` to `ERTS_INVALID_PID` and skip the described optimisation if the value is still uninitialised. --- erts/emulator/test/fun_SUITE.erl | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'erts/emulator/test/fun_SUITE.erl') diff --git a/erts/emulator/test/fun_SUITE.erl b/erts/emulator/test/fun_SUITE.erl index 7d29ebec52..6730003b58 100644 --- a/erts/emulator/test/fun_SUITE.erl +++ b/erts/emulator/test/fun_SUITE.erl @@ -576,7 +576,7 @@ refc_dist(Config) when is_list(Config) -> process_flag(trap_exit, true), Pid = spawn_link(Node, fun() -> receive Fun when is_function(Fun) -> - 2 = fun_refc(Fun), + 3 = fun_refc(Fun), exit({normal,Fun}) end end), F = fun() -> 42 end, @@ -598,7 +598,7 @@ refc_dist_send(Node, F) -> Pid = spawn_link(Node, fun() -> receive {To,Fun} when is_function(Fun) -> wait_until(fun () -> - 2 =:= fun_refc(Fun) + 3 =:= fun_refc(Fun) end), To ! Fun end @@ -626,7 +626,7 @@ refc_dist_reg_send(Node, F) -> Me ! Ref, receive {Me,Fun} when is_function(Fun) -> - 2 = fun_refc(Fun), + 3 = fun_refc(Fun), Me ! Fun end end), @@ -806,11 +806,13 @@ verify_not_undef(Fun, Tag) -> ct:fail("tag ~w not defined in fun_info", [Tag]); {Tag,_} -> ok end. - + id(X) -> X. spawn_call(Node, AFun) -> + Parent = self(), + Init = erlang:whereis(init), Pid = spawn_link(Node, fun() -> receive @@ -821,8 +823,10 @@ spawn_call(Node, AFun) -> _ -> lists:seq(0, Arity-1) end, Res = apply(Fun, Args), - {pid,Creator} = erlang:fun_info(Fun, pid), - Creator ! {result,Res} + case erlang:fun_info(Fun, pid) of + {pid,Init} -> Parent ! {result,Res}; + {pid,Creator} -> Creator ! {result,Res} + end end end), Pid ! {AFun,AFun,AFun}, -- cgit v1.2.3