-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
beam_ssa_opt.erl
3169 lines (2897 loc) · 115 KB
/
beam_ssa_opt.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2018-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%%
%%% This is a collection of various optimizations that don't need a separate
%%% pass by themselves and/or are mutually beneficial to other passes.
%%%
%%% The optimizations are applied in "phases," each with a list of sub-passes
%%% to run. These sub-passes are applied on all functions in a module before
%%% moving on to the next phase, which lets us gather module-level information
%%% in one phase and then apply it in the next without having to risk working
%%% with incomplete information.
%%%
%%% Each sub-pass operates on a #opt_st{} record and a func_info_db(), where
%%% the former is just a #b_function{} whose blocks can be represented either
%%% in linear or map form, and the latter is a map with information about all
%%% functions in the module (see beam_ssa_opt.hrl for more details).
%%%
-module(beam_ssa_opt).
-export([module/2]).
-include("beam_ssa_opt.hrl").
-import(lists, [all/2,append/1,duplicate/2,flatten/1,foldl/3,
keyfind/3,last/1,mapfoldl/3,member/2,
partition/2,reverse/1,reverse/2,
splitwith/2,sort/1,takewhile/2,unzip/1]).
-define(MAX_REPETITIONS, 16).
-spec module(beam_ssa:b_module(), [compile:option()]) ->
{'ok',beam_ssa:b_module()}.
module(Module, Opts) ->
FuncDb = case proplists:get_value(no_module_opt, Opts, false) of
false -> build_func_db(Module);
true -> #{}
end,
%% Passes that perform module-level optimizations are often aided by
%% optimizing callers before callees and vice versa, so we optimize all
%% functions in call order, alternating the order every time.
StMap0 = build_st_map(Module),
Order = get_call_order_po(StMap0, FuncDb),
Phases = [{once, Order, prologue_passes(Opts)},
{module, module_passes(Opts)},
{fixpoint, Order, repeated_passes(Opts)},
{once, Order, epilogue_passes(Opts)}],
StMap = run_phases(Phases, StMap0, FuncDb),
{ok, finish(Module, StMap)}.
run_phases([{module, Passes} | Phases], StMap0, FuncDb0) ->
{StMap, FuncDb} = compile:run_sub_passes(Passes, {StMap0, FuncDb0}),
run_phases(Phases, StMap, FuncDb);
run_phases([{once, FuncIds0, Passes} | Phases], StMap0, FuncDb0) ->
FuncIds = skip_removed(FuncIds0, StMap0),
{StMap, FuncDb} = phase(FuncIds, Passes, StMap0, FuncDb0),
run_phases(Phases, StMap, FuncDb);
run_phases([{fixpoint, FuncIds0, Passes} | Phases], StMap0, FuncDb0) ->
FuncIds = skip_removed(FuncIds0, StMap0),
RevFuncIds = reverse(FuncIds),
Order = {FuncIds, RevFuncIds},
{StMap, FuncDb} = fixpoint(RevFuncIds, Order, Passes,
StMap0, FuncDb0, ?MAX_REPETITIONS),
run_phases(Phases, StMap, FuncDb);
run_phases([], StMap, _FuncDb) ->
StMap.
skip_removed(FuncIds, StMap) ->
[F || F <- FuncIds, is_map_key(F, StMap)].
%% Run the given passes until a fixpoint is reached.
fixpoint(_FuncIds, _Order, _Passes, StMap, FuncDb, 0) ->
%% Too many repetitions. Give up and return what we have.
{StMap, FuncDb};
fixpoint(FuncIds0, Order0, Passes, StMap0, FuncDb0, N) ->
{StMap, FuncDb} = phase(FuncIds0, Passes, StMap0, FuncDb0),
Repeat = changed(FuncIds0, FuncDb0, FuncDb, StMap0, StMap),
case sets:is_empty(Repeat) of
true ->
%% No change. Fixpoint reached.
{StMap, FuncDb};
false ->
%% Repeat the optimizations for functions whose code has
%% changed or for which there is potentially updated type
%% information.
{OrderA, OrderB} = Order0,
Order = {OrderB, OrderA},
FuncIds = [Id || Id <- OrderA, sets:is_element(Id, Repeat)],
fixpoint(FuncIds, Order, Passes, StMap, FuncDb, N - 1)
end.
phase([FuncId | Ids], Ps, StMap, FuncDb0) ->
try compile:run_sub_passes(Ps, {map_get(FuncId, StMap), FuncDb0}) of
{St, FuncDb} ->
phase(Ids, Ps, StMap#{ FuncId => St }, FuncDb)
catch
Class:Error:Stack ->
#b_local{name=#b_literal{val=Name},arity=Arity} = FuncId,
io:fwrite("Function: ~w/~w\n", [Name,Arity]),
erlang:raise(Class, Error, Stack)
end;
phase([], _Ps, StMap, FuncDb) ->
{StMap, FuncDb}.
changed(PrevIds, FuncDb0, FuncDb, StMap0, StMap) ->
%% Find all functions in FuncDb that can be reached by changes
%% of argument and/or return types. Those are the functions that
%% may gain from running the optimization passes again.
%%
%% Note that we examine all functions in FuncDb, not only functions
%% optimized in the previous run, because the argument types can
%% have been updated for functions not included in the previous run.
F = fun(Id, A) ->
case sets:is_element(Id, A) of
true ->
A;
false ->
{#func_info{arg_types=ATs0,succ_types=ST0},
#func_info{arg_types=ATs1,succ_types=ST1}} =
{map_get(Id, FuncDb0),map_get(Id, FuncDb)},
%% If the argument types have changed for this
%% function, re-optimize this function and all
%% functions it calls directly or indirectly.
%%
%% If the return type has changed, re-optimize
%% this function and all functions that call
%% this function directly or indirectly.
Opts = case ATs0 =:= ATs1 of
true -> [];
false -> [called]
end ++
case ST0 =:= ST1 of
true -> [];
false -> [callers]
end,
case Opts of
[] -> A;
[_|_] -> add_changed([Id], Opts, FuncDb, A)
end
end
end,
Ids = foldl(F, sets:new([{version, 2}]), maps:keys(FuncDb)),
%% From all functions that were optimized in the previous run,
%% find the functions that had any change in the SSA code. Those
%% functions might gain from being optimized again. (For example,
%% when beam_ssa_dead has shortcut branches, the types for some
%% variables could become narrower, giving beam_ssa_type new
%% opportunities for optimization.)
%%
%% Note that the functions examined could be functions with module-level
%% optimization turned off (and thus not included in FuncDb).
foldl(fun(Id, A) ->
case sets:is_element(Id, A) of
true ->
%% Already scheduled for another optimization.
%% No need to compare the SSA code.
A;
false ->
%% Compare the SSA code before and after optimization.
case {map_get(Id, StMap0),map_get(Id, StMap)} of
{Same,Same} -> A;
{_,_} -> sets:add_element(Id, A)
end
end
end, Ids, PrevIds).
add_changed([Id|Ids], Opts, FuncDb, S0) when is_map_key(Id, FuncDb) ->
case sets:is_element(Id, S0) of
true ->
add_changed(Ids, Opts, FuncDb, S0);
false ->
S1 = sets:add_element(Id, S0),
#func_info{in=In,out=Out} = map_get(Id, FuncDb),
S2 = case member(callers, Opts) of
true -> add_changed(In, Opts, FuncDb, S1);
false -> S1
end,
S = case member(called, Opts) of
true -> add_changed(Out, Opts, FuncDb, S2);
false -> S2
end,
add_changed(Ids, Opts, FuncDb, S)
end;
add_changed([_|Ids], Opts, FuncDb, S) ->
%% This function is exempt from module-level optimization and will not
%% provide any more information.
add_changed(Ids, Opts, FuncDb, S);
add_changed([], _, _, S) -> S.
%%
get_func_id(F) ->
{_Mod, Name, Arity} = beam_ssa:get_anno(func_info, F),
#b_local{name=#b_literal{val=Name}, arity=Arity}.
-spec build_st_map(#b_module{}) -> st_map().
build_st_map(#b_module{body=Fs}) ->
build_st_map_1(Fs, #{}).
build_st_map_1([F | Fs], Map) ->
#b_function{anno=Anno,args=Args,cnt=Counter,bs=Bs} = F,
St = #opt_st{anno=Anno,args=Args,cnt=Counter,ssa=Bs},
build_st_map_1(Fs, Map#{ get_func_id(F) => St });
build_st_map_1([], Map) ->
Map.
-spec finish(#b_module{}, st_map()) -> #b_module{}.
finish(#b_module{body=Fs0}=Module, StMap) ->
Module#b_module{body=finish_1(Fs0, StMap)}.
finish_1([F0 | Fs], StMap) ->
FuncId = get_func_id(F0),
case StMap of
#{ FuncId := #opt_st{anno=Anno,cnt=Counter,ssa=Blocks} } ->
F = F0#b_function{anno=Anno,bs=Blocks,cnt=Counter},
[F | finish_1(Fs, StMap)];
#{} ->
finish_1(Fs, StMap)
end;
finish_1([], _StMap) ->
[].
%%
-define(PASS(N), {N,fun N/1}).
prologue_passes(Opts) ->
Ps = [?PASS(ssa_opt_split_blocks),
?PASS(ssa_opt_coalesce_phis),
?PASS(ssa_opt_tail_phis),
?PASS(ssa_opt_element),
?PASS(ssa_opt_linearize),
?PASS(ssa_opt_tuple_size),
?PASS(ssa_opt_record),
?PASS(ssa_opt_cse), % Helps the first type pass.
?PASS(ssa_opt_live)], % ...
passes_1(Ps, Opts).
module_passes(Opts) ->
Ps0 = [{ssa_opt_bc_size,
fun({StMap, FuncDb}) ->
{beam_ssa_bc_size:opt(StMap), FuncDb}
end},
{ssa_opt_type_start,
fun({StMap, FuncDb}) ->
beam_ssa_type:opt_start(StMap, FuncDb)
end}],
passes_1(Ps0, Opts).
%% These passes all benefit from each other (in roughly this order), so they
%% are repeated as required.
repeated_passes(Opts) ->
Ps = [?PASS(ssa_opt_live),
?PASS(ssa_opt_ne),
?PASS(ssa_opt_bs_puts),
?PASS(ssa_opt_dead),
?PASS(ssa_opt_cse),
?PASS(ssa_opt_tail_phis),
?PASS(ssa_opt_sink),
?PASS(ssa_opt_tuple_size),
?PASS(ssa_opt_record),
?PASS(ssa_opt_try),
?PASS(ssa_opt_type_continue)], %Must run after ssa_opt_dead to
%clean up phi nodes.
passes_1(Ps, Opts).
epilogue_passes(Opts) ->
Ps = [?PASS(ssa_opt_type_finish),
?PASS(ssa_opt_float),
?PASS(ssa_opt_sw),
%% Run live one more time to clean up after the previous
%% epilogue passes.
?PASS(ssa_opt_live),
?PASS(ssa_opt_bsm),
?PASS(ssa_opt_bsm_shortcut),
?PASS(ssa_opt_sink),
?PASS(ssa_opt_blockify),
?PASS(ssa_opt_merge_blocks),
?PASS(ssa_opt_get_tuple_element),
?PASS(ssa_opt_tail_calls),
?PASS(ssa_opt_trim_unreachable),
?PASS(ssa_opt_unfold_literals)],
passes_1(Ps, Opts).
passes_1(Ps, Opts0) ->
Negations = [{list_to_atom("no_"++atom_to_list(N)),N} ||
{N,_} <- Ps],
Opts = proplists:substitute_negations(Negations, Opts0),
[case proplists:get_value(Name, Opts, true) of
true ->
P;
false ->
{NoName,Name} = keyfind(Name, 2, Negations),
{NoName,fun(S) -> S end}
end || {Name,_}=P <- Ps].
%% Builds a function information map with basic information about incoming and
%% outgoing local calls, as well as whether the function is exported.
-spec build_func_db(#b_module{}) -> func_info_db().
build_func_db(#b_module{body=Fs,attributes=Attr,exports=Exports0}) ->
Exports = fdb_exports(Attr, Exports0),
try
fdb_fs(Fs, Exports, #{})
catch
%% All module-level optimizations are invalid when a NIF can override a
%% function, so we have to bail out.
throw:load_nif -> #{}
end.
fdb_exports([{on_load, L} | Attrs], Exports) ->
%% Functions marked with on_load must be treated as exported to prevent
%% them from being optimized away when unused.
fdb_exports(Attrs, flatten(L) ++ Exports);
fdb_exports([_Attr | Attrs], Exports) ->
fdb_exports(Attrs, Exports);
fdb_exports([], Exports) ->
gb_sets:from_list(Exports).
fdb_fs([#b_function{ args=Args,bs=Bs }=F | Fs], Exports, FuncDb0) ->
Id = get_func_id(F),
#b_local{name=#b_literal{val=Name}, arity=Arity} = Id,
Exported = gb_sets:is_element({Name, Arity}, Exports),
ArgTypes = duplicate(length(Args), #{}),
FuncDb1 = case FuncDb0 of
%% We may have an entry already if someone's called us.
#{ Id := Info } ->
FuncDb0#{ Id := Info#func_info{ exported=Exported,
arg_types=ArgTypes }};
#{} ->
FuncDb0#{ Id => #func_info{ exported=Exported,
arg_types=ArgTypes }}
end,
RPO = beam_ssa:rpo(Bs),
FuncDb = beam_ssa:fold_blocks(fun(_L, #b_blk{is=Is}, FuncDb) ->
fdb_is(Is, Id, FuncDb)
end, RPO, FuncDb1, Bs),
fdb_fs(Fs, Exports, FuncDb);
fdb_fs([], _Exports, FuncDb) ->
FuncDb.
fdb_is([#b_set{op=call,
args=[#b_local{}=Callee | _]} | Is],
Caller, FuncDb) ->
fdb_is(Is, Caller, fdb_update(Caller, Callee, FuncDb));
fdb_is([#b_set{op=call,
args=[#b_remote{mod=#b_literal{val=erlang},
name=#b_literal{val=load_nif}},
_Path, _LoadInfo]} | _Is], _Caller, _FuncDb) ->
throw(load_nif);
fdb_is([#b_set{op=MakeFun,
args=[#b_local{}=Callee | _]} | Is],
Caller, FuncDb) when MakeFun =:= make_fun;
MakeFun =:= old_make_fun ->
%% The make_fun instruction's type depends on the return type of the
%% function in question, so we treat this as a function call.
fdb_is(Is, Caller, fdb_update(Caller, Callee, FuncDb));
fdb_is([_ | Is], Caller, FuncDb) ->
fdb_is(Is, Caller, FuncDb);
fdb_is([], _Caller, FuncDb) ->
FuncDb.
fdb_update(Caller, Callee, FuncDb) ->
CallerVertex = maps:get(Caller, FuncDb, #func_info{}),
CalleeVertex = maps:get(Callee, FuncDb, #func_info{}),
Calls = ordsets:add_element(Callee, CallerVertex#func_info.out),
CalledBy = ordsets:add_element(Caller, CalleeVertex#func_info.in),
FuncDb#{ Caller => CallerVertex#func_info{out=Calls},
Callee => CalleeVertex#func_info{in=CalledBy} }.
%% Returns the post-order of all local calls in this module. That is,
%% called functions will be ordered before the functions calling them.
%%
%% Functions where module-level optimization is disabled are added last in
%% arbitrary order.
get_call_order_po(StMap, FuncDb) ->
Order = gco_po(FuncDb),
Order ++ maps:fold(fun(K, _V, Acc) ->
case is_map_key(K, FuncDb) of
false -> [K | Acc];
true -> Acc
end
end, [], StMap).
gco_po(FuncDb) ->
All = sort(maps:keys(FuncDb)),
{RPO,_} = gco_rpo(All, FuncDb, sets:new([{version, 2}]), []),
reverse(RPO).
gco_rpo([Id|Ids], FuncDb, Seen0, Acc0) ->
case sets:is_element(Id, Seen0) of
true ->
gco_rpo(Ids, FuncDb, Seen0, Acc0);
false ->
#func_info{out=Successors} = map_get(Id, FuncDb),
Seen1 = sets:add_element(Id, Seen0),
{Acc,Seen} = gco_rpo(Successors, FuncDb, Seen1, Acc0),
gco_rpo(Ids, FuncDb, Seen, [Id|Acc])
end;
gco_rpo([], _, Seen, Acc) ->
{Acc,Seen}.
%%%
%%% Trivial sub passes.
%%%
ssa_opt_dead({#opt_st{ssa=Linear}=St, FuncDb}) ->
{St#opt_st{ssa=beam_ssa_dead:opt(Linear)}, FuncDb}.
ssa_opt_linearize({#opt_st{ssa=Blocks}=St, FuncDb}) ->
{St#opt_st{ssa=beam_ssa:linearize(Blocks)}, FuncDb}.
ssa_opt_type_continue({#opt_st{ssa=Linear0,args=Args,anno=Anno}=St0, FuncDb0}) ->
{Linear, FuncDb} = beam_ssa_type:opt_continue(Linear0, Args, Anno, FuncDb0),
{St0#opt_st{ssa=Linear}, FuncDb}.
ssa_opt_type_finish({#opt_st{args=Args,anno=Anno0}=St0, FuncDb0}) ->
{Anno, FuncDb} = beam_ssa_type:opt_finish(Args, Anno0, FuncDb0),
{St0#opt_st{anno=Anno}, FuncDb}.
ssa_opt_blockify({#opt_st{ssa=Linear}=St, FuncDb}) ->
{St#opt_st{ssa=maps:from_list(Linear)}, FuncDb}.
ssa_opt_trim_unreachable({#opt_st{ssa=Blocks}=St, FuncDb}) ->
{St#opt_st{ssa=beam_ssa:trim_unreachable(Blocks)}, FuncDb}.
ssa_opt_merge_blocks({#opt_st{ssa=Blocks0}=St, FuncDb}) ->
RPO = beam_ssa:rpo(Blocks0),
Blocks = beam_ssa:merge_blocks(RPO, Blocks0),
{St#opt_st{ssa=Blocks}, FuncDb}.
%%%
%%% Split blocks before certain instructions to enable more optimizations.
%%%
%%% Splitting before element/2 enables the optimization that swaps
%%% element/2 instructions.
%%%
%%% Splitting before call and make_fun instructions gives more opportunities
%%% for sinking get_tuple_element instructions.
%%%
ssa_opt_split_blocks({#opt_st{ssa=Blocks0,cnt=Count0}=St, FuncDb}) ->
P = fun(#b_set{op={bif,element}}) -> true;
(#b_set{op=call}) -> true;
(#b_set{op=bs_init_writable}) -> true;
(#b_set{op=make_fun}) -> true;
(#b_set{op=old_make_fun}) -> true;
(_) -> false
end,
RPO = beam_ssa:rpo(Blocks0),
{Blocks,Count} = beam_ssa:split_blocks(RPO, P, Blocks0, Count0),
{St#opt_st{ssa=Blocks,cnt=Count}, FuncDb}.
%%%
%%% Coalesce phi nodes.
%%%
%%% Nested cases can led to code such as this:
%%%
%%% 10:
%%% _1 = phi {literal value1, label 8}, {Var, label 9}
%%% br 11
%%%
%%% 11:
%%% _2 = phi {_1, label 10}, {literal false, label 3}
%%%
%%% The phi nodes can be coalesced like this:
%%%
%%% 11:
%%% _2 = phi {literal value1, label 8}, {Var, label 9}, {literal false, label 3}
%%%
%%% Coalescing can help other optimizations, and can in some cases reduce register
%%% shuffling (if the phi variables for two phi nodes happens to be allocated to
%%% different registers).
%%%
ssa_opt_coalesce_phis({#opt_st{ssa=Blocks0}=St, FuncDb}) ->
Ls = beam_ssa:rpo(Blocks0),
Blocks = c_phis_1(Ls, Blocks0),
{St#opt_st{ssa=Blocks}, FuncDb}.
c_phis_1([L|Ls], Blocks0) ->
case map_get(L, Blocks0) of
#b_blk{is=[#b_set{op=phi}|_]}=Blk ->
Blocks = c_phis_2(L, Blk, Blocks0),
c_phis_1(Ls, Blocks);
#b_blk{} ->
c_phis_1(Ls, Blocks0)
end;
c_phis_1([], Blocks) -> Blocks.
c_phis_2(L, #b_blk{is=Is0}=Blk0, Blocks0) ->
case c_phis_args(Is0, Blocks0) of
none ->
Blocks0;
{_,_,Preds}=Info ->
Is = c_rewrite_phis(Is0, Info),
Blk = Blk0#b_blk{is=Is},
Blocks = Blocks0#{L:=Blk},
c_fix_branches(Preds, L, Blocks)
end.
c_phis_args([#b_set{op=phi,args=Args0}|Is], Blocks) ->
case c_phis_args_1(Args0, Blocks) of
none ->
c_phis_args(Is, Blocks);
Res ->
Res
end;
c_phis_args(_, _Blocks) -> none.
c_phis_args_1([{Var,Pred}|As], Blocks) ->
case c_get_pred_vars(Var, Pred, Blocks) of
none ->
c_phis_args_1(As, Blocks);
Result ->
Result
end;
c_phis_args_1([], _Blocks) -> none.
c_get_pred_vars(Var, Pred, Blocks) ->
case map_get(Pred, Blocks) of
#b_blk{is=[#b_set{op=phi,dst=Var,args=Args}]} ->
{Var,Pred,Args};
#b_blk{} ->
none
end.
c_rewrite_phis([#b_set{op=phi,args=Args0}=I|Is], Info) ->
Args = c_rewrite_phi(Args0, Info),
[I#b_set{args=Args}|c_rewrite_phis(Is, Info)];
c_rewrite_phis(Is, _Info) -> Is.
c_rewrite_phi([{Var,Pred}|As], {Var,Pred,Values}) ->
Values ++ As;
c_rewrite_phi([{Value,Pred}|As], {_,Pred,Values}) ->
[{Value,P} || {_,P} <- Values] ++ As;
c_rewrite_phi([A|As], Info) ->
[A|c_rewrite_phi(As, Info)];
c_rewrite_phi([], _Info) -> [].
c_fix_branches([{_,Pred}|As], L, Blocks0) ->
#b_blk{last=Last0} = Blk0 = map_get(Pred, Blocks0),
#b_br{bool=#b_literal{val=true}} = Last0, %Assertion.
Last = Last0#b_br{bool=#b_literal{val=true},succ=L,fail=L},
Blk = Blk0#b_blk{last=Last},
Blocks = Blocks0#{Pred:=Blk},
c_fix_branches(As, L, Blocks);
c_fix_branches([], _, Blocks) -> Blocks.
%%%
%%% Eliminate phi nodes in the tail of a function.
%%%
%%% Try to eliminate short blocks that starts with a phi node
%%% and end in a return. For example:
%%%
%%% Result = phi { Res1, 4 }, { literal true, 5 }
%%% Ret = put_tuple literal ok, Result
%%% ret Ret
%%%
%%% The code in this block can be inserted at the end blocks 4 and
%%% 5. Thus, the following code can be inserted into block 4:
%%%
%%% Ret:1 = put_tuple literal ok, Res1
%%% ret Ret:1
%%%
%%% And the following code into block 5:
%%%
%%% Ret:2 = put_tuple literal ok, literal true
%%% ret Ret:2
%%%
%%% Which can be further simplified to:
%%%
%%% ret literal {ok, true}
%%%
%%% This transformation may lead to more code improvements:
%%%
%%% - Stack trimming
%%% - Fewer test_heap instructions
%%% - Smaller stack frames
%%%
ssa_opt_tail_phis({#opt_st{ssa=SSA0,cnt=Count0}=St, FuncDb}) ->
{SSA,Count} = opt_tail_phis(SSA0, Count0),
{St#opt_st{ssa=SSA,cnt=Count}, FuncDb}.
opt_tail_phis(Blocks, Count) when is_map(Blocks) ->
opt_tail_phis(maps:values(Blocks), Blocks, Count);
opt_tail_phis(Linear0, Count0) when is_list(Linear0) ->
Blocks0 = maps:from_list(Linear0),
{Blocks,Count} = opt_tail_phis(Blocks0, Count0),
{beam_ssa:linearize(Blocks),Count}.
opt_tail_phis([#b_blk{is=Is0,last=Last}|Bs], Blocks0, Count0) ->
case {Is0,Last} of
{[#b_set{op=phi,args=[_,_|_]}|_],#b_ret{arg=#b_var{}}=Ret} ->
{Phis,Is} = splitwith(fun(#b_set{op=Op}) -> Op =:= phi end, Is0),
case suitable_tail_ops(Is) of
true ->
{Blocks,Count} = opt_tail_phi(Phis, Is, Ret,
Blocks0, Count0),
opt_tail_phis(Bs, Blocks, Count);
false ->
opt_tail_phis(Bs, Blocks0, Count0)
end;
{_,_} ->
opt_tail_phis(Bs, Blocks0, Count0)
end;
opt_tail_phis([], Blocks, Count) ->
{Blocks,Count}.
opt_tail_phi(Phis0, Is, Ret, Blocks0, Count0) ->
Phis = rel2fam(reduce_phis(Phis0)),
{Blocks,Count,Cost} =
foldl(fun(PhiArg, Acc) ->
opt_tail_phi_arg(PhiArg, Is, Ret, Acc)
end, {Blocks0,Count0,0}, Phis),
MaxCost = length(Phis) * 3 + 2,
if
Cost =< MaxCost ->
%% The transformation would cause at most a slight
%% increase in code size if no more optimizations
%% can be applied.
{Blocks,Count};
true ->
%% The code size would be increased too much.
{Blocks0,Count0}
end.
reduce_phis([#b_set{dst=PhiDst,args=PhiArgs}|Is]) ->
[{L,{PhiDst,Val}} || {Val,L} <- PhiArgs] ++ reduce_phis(Is);
reduce_phis([]) -> [].
opt_tail_phi_arg({PredL,Sub0}, Is0, Ret0, {Blocks0,Count0,Cost0}) ->
Blk0 = map_get(PredL, Blocks0),
#b_blk{is=IsPrefix,last=#b_br{succ=Next,fail=Next}} = Blk0,
Sub1 = maps:from_list(Sub0),
{Is1,Count,Sub} = new_names(Is0, Sub1, Count0, []),
Is2 = [sub(I, Sub) || I <- Is1],
Cost = build_cost(Is2, Cost0),
Is = IsPrefix ++ Is2,
Ret = sub(Ret0, Sub),
Blk = Blk0#b_blk{is=Is,last=Ret},
Blocks = Blocks0#{PredL:=Blk},
{Blocks,Count,Cost}.
new_names([#b_set{dst=Dst}=I|Is], Sub0, Count0, Acc) ->
{NewDst,Count} = new_var(Dst, Count0),
Sub = Sub0#{Dst=>NewDst},
new_names(Is, Sub, Count, [I#b_set{dst=NewDst}|Acc]);
new_names([], Sub, Count, Acc) ->
{reverse(Acc),Count,Sub}.
suitable_tail_ops(Is) ->
all(fun(#b_set{op=Op}) ->
is_suitable_tail_op(Op)
end, Is).
is_suitable_tail_op({bif,_}) -> true;
is_suitable_tail_op(put_list) -> true;
is_suitable_tail_op(put_tuple) -> true;
is_suitable_tail_op(_) -> false.
build_cost([#b_set{op=put_list,args=Args}|Is], Cost) ->
case are_all_literals(Args) of
true ->
build_cost(Is, Cost);
false ->
build_cost(Is, Cost + 1)
end;
build_cost([#b_set{op=put_tuple,args=Args}|Is], Cost) ->
case are_all_literals(Args) of
true ->
build_cost(Is, Cost);
false ->
build_cost(Is, Cost + length(Args) + 1)
end;
build_cost([#b_set{op={bif,_},args=Args}|Is], Cost) ->
case are_all_literals(Args) of
true ->
build_cost(Is, Cost);
false ->
build_cost(Is, Cost + 1)
end;
build_cost([], Cost) -> Cost.
are_all_literals(Args) ->
all(fun(#b_literal{}) -> true;
(_) -> false
end, Args).
%%%
%%% Order element/2 calls.
%%%
%%% Order an unbroken chain of element/2 calls for the same tuple
%%% with the same failure label so that the highest element is
%%% retrieved first. That will allow the other element/2 calls to
%%% be replaced with get_tuple_element/3 instructions.
%%%
ssa_opt_element({#opt_st{ssa=Blocks}=St, FuncDb}) ->
%% Collect the information about element instructions in this
%% function.
GetEls = collect_element_calls(beam_ssa:linearize(Blocks)),
%% Collect the element instructions into chains. The
%% element calls in each chain are ordered in reverse
%% execution order.
Chains = collect_chains(GetEls, []),
%% For each chain, swap the first element call with the
%% element call with the highest index.
{St#opt_st{ssa=swap_element_calls(Chains, Blocks)}, FuncDb}.
collect_element_calls([{L,#b_blk{is=Is0,last=Last}}|Bs]) ->
case {Is0,Last} of
{[#b_set{op={bif,element},dst=Element,
args=[#b_literal{val=N},#b_var{}=Tuple]},
#b_set{op={succeeded,guard},dst=Bool,args=[Element]}],
#b_br{bool=Bool,succ=Succ,fail=Fail}} ->
Info = {L,Succ,{Tuple,Fail},N},
[Info|collect_element_calls(Bs)];
{_,_} ->
collect_element_calls(Bs)
end;
collect_element_calls([]) -> [].
collect_chains([{This,_,V,_}=El|Els], [{_,This,V,_}|_]=Chain) ->
%% Add to the previous chain.
collect_chains(Els, [El|Chain]);
collect_chains([El|Els], [_,_|_]=Chain) ->
%% Save the previous chain and start a new chain.
[Chain|collect_chains(Els, [El])];
collect_chains([El|Els], _Chain) ->
%% The previous chain is too short; discard it and start a new.
collect_chains(Els, [El]);
collect_chains([], [_,_|_]=Chain) ->
%% Save the last chain.
[Chain];
collect_chains([], _) -> [].
swap_element_calls([[{L,_,_,N}|_]=Chain|Chains], Blocks0) ->
Blocks = swap_element_calls_1(Chain, {N,L}, Blocks0),
swap_element_calls(Chains, Blocks);
swap_element_calls([], Blocks) -> Blocks.
swap_element_calls_1([{L1,_,_,N1}], {N2,L2}, Blocks) when N2 > N1 ->
%% We have reached the end of the chain, and the first
%% element instrution to be executed. Its index is lower
%% than the maximum index found while traversing the chain,
%% so we will need to swap the instructions.
#{L1:=Blk1,L2:=Blk2} = Blocks,
[#b_set{dst=Dst1}=GetEl1,Succ1] = Blk1#b_blk.is,
[#b_set{dst=Dst2}=GetEl2,Succ2] = Blk2#b_blk.is,
Is1 = [GetEl2,Succ1#b_set{args=[Dst2]}],
Is2 = [GetEl1,Succ2#b_set{args=[Dst1]}],
Blocks#{L1:=Blk1#b_blk{is=Is1},L2:=Blk2#b_blk{is=Is2}};
swap_element_calls_1([{L,_,_,N1}|Els], {N2,_}, Blocks) when N1 > N2 ->
swap_element_calls_1(Els, {N2,L}, Blocks);
swap_element_calls_1([_|Els], Highest, Blocks) ->
swap_element_calls_1(Els, Highest, Blocks);
swap_element_calls_1([], _, Blocks) ->
%% Nothing to do. The element call with highest index
%% is already the first one to be executed.
Blocks.
%%%
%%% Record optimization.
%%%
%%% Replace tuple matching with an is_tagged_tuple instruction
%%% when applicable.
%%%
ssa_opt_record({#opt_st{ssa=Linear}=St, FuncDb}) ->
Blocks = maps:from_list(Linear),
{St#opt_st{ssa=record_opt(Linear, Blocks)}, FuncDb}.
record_opt([{L,#b_blk{is=Is0,last=Last}=Blk0}|Bs], Blocks) ->
Is = record_opt_is(Is0, Last, Blocks),
Blk = Blk0#b_blk{is=Is},
[{L,Blk}|record_opt(Bs, Blocks)];
record_opt([], _Blocks) -> [].
record_opt_is([#b_set{op={bif,is_tuple},dst=Bool,args=[Tuple]}=Set],
Last, Blocks) ->
case is_tagged_tuple(Tuple, Bool, Last, Blocks) of
{yes,Size,Tag} ->
Args = [Tuple,Size,Tag],
[Set#b_set{op=is_tagged_tuple,args=Args}];
no ->
[Set]
end;
record_opt_is([I|Is]=Is0, #b_br{bool=Bool}=Last, Blocks) ->
case is_tagged_tuple_1(Is0, Last, Blocks) of
{yes,_Fail,Tuple,Arity,Tag} ->
Args = [Tuple,Arity,Tag],
[I#b_set{op=is_tagged_tuple,dst=Bool,args=Args}];
no ->
[I|record_opt_is(Is, Last, Blocks)]
end;
record_opt_is([I|Is], Last, Blocks) ->
[I|record_opt_is(Is, Last, Blocks)];
record_opt_is([], _Last, _Blocks) -> [].
is_tagged_tuple(#b_var{}=Tuple, Bool,
#b_br{bool=Bool,succ=Succ,fail=Fail},
Blocks) ->
#b_blk{is=Is,last=Last} = map_get(Succ, Blocks),
case is_tagged_tuple_1(Is, Last, Blocks) of
{yes,Fail,Tuple,Arity,Tag} ->
{yes,Arity,Tag};
_ ->
no
end;
is_tagged_tuple(_, _, _, _) -> no.
is_tagged_tuple_1(Is, Last, Blocks) ->
case {Is,Last} of
{[#b_set{op={bif,tuple_size},dst=ArityVar,
args=[#b_var{}=Tuple]},
#b_set{op={bif,'=:='},
dst=Bool,
args=[ArityVar, #b_literal{val=ArityVal}=Arity]}],
#b_br{bool=Bool,succ=Succ,fail=Fail}}
when is_integer(ArityVal) ->
SuccBlk = map_get(Succ, Blocks),
case is_tagged_tuple_2(SuccBlk, Tuple, Fail) of
no ->
no;
{yes,Tag} ->
{yes,Fail,Tuple,Arity,Tag}
end;
_ ->
no
end.
is_tagged_tuple_2(#b_blk{is=Is,
last=#b_br{bool=#b_var{}=Bool,fail=Fail}},
Tuple, Fail) ->
is_tagged_tuple_3(Is, Bool, Tuple);
is_tagged_tuple_2(#b_blk{}, _, _) -> no.
is_tagged_tuple_3([#b_set{op=get_tuple_element,
dst=TagVar,
args=[#b_var{}=Tuple,#b_literal{val=0}]}|Is],
Bool, Tuple) ->
is_tagged_tuple_4(Is, Bool, TagVar);
is_tagged_tuple_3([_|Is], Bool, Tuple) ->
is_tagged_tuple_3(Is, Bool, Tuple);
is_tagged_tuple_3([], _, _) -> no.
is_tagged_tuple_4([#b_set{op={bif,'=:='},dst=Bool,
args=[#b_var{}=TagVar,
#b_literal{val=TagVal}=Tag]}],
Bool, TagVar) when is_atom(TagVal) ->
{yes,Tag};
is_tagged_tuple_4([_|Is], Bool, TagVar) ->
is_tagged_tuple_4(Is, Bool, TagVar);
is_tagged_tuple_4([], _, _) -> no.
%%%
%%% Common subexpression elimination (CSE).
%%%
%%% Eliminate repeated evaluation of identical expressions. To avoid
%%% increasing the size of the stack frame, we don't eliminate
%%% subexpressions across instructions that clobber the X registers.
%%%
ssa_opt_cse({#opt_st{ssa=Linear}=St, FuncDb}) ->
M = #{0 => #{}, ?EXCEPTION_BLOCK => #{}},
{St#opt_st{ssa=cse(Linear, #{}, M)}, FuncDb}.
cse([{L,#b_blk{is=Is0,last=Last0}=Blk}|Bs], Sub0, M0) ->
Es0 = map_get(L, M0),
{Is1,Es,Sub} = cse_is(Is0, Es0, Sub0, []),
Last = sub(Last0, Sub),
M = cse_successors(Is1, Blk, Es, M0),
Is = reverse(Is1),
[{L,Blk#b_blk{is=Is,last=Last}}|cse(Bs, Sub, M)];
cse([], _, _) -> [].
cse_successors([#b_set{op={succeeded,_},args=[Src]},Bif|_], Blk, EsSucc, M0) ->
case cse_suitable(Bif) of
true ->
%% The previous instruction only has a valid value at the success branch.
%% We must remove the substitution for Src from the failure branch.
#b_blk{last=#b_br{succ=Succ,fail=Fail}} = Blk,
M = cse_successors_1([Succ], EsSucc, M0),
EsFail = maps:filter(fun(_, Val) -> Val =/= Src end, EsSucc),
cse_successors_1([Fail], EsFail, M);
false ->
%% There can't be any replacement for Src in EsSucc. No need for
%% any special handling.
cse_successors_1(beam_ssa:successors(Blk), EsSucc, M0)
end;
cse_successors(_Is, Blk, Es, M) ->
cse_successors_1(beam_ssa:successors(Blk), Es, M).
cse_successors_1([L|Ls], Es0, M) ->
case M of
#{L:=Es1} when map_size(Es1) =:= 0 ->
%% The map is already empty. No need to do anything
%% since the intersection will be empty.
cse_successors_1(Ls, Es0, M);
#{L:=Es1} ->
Es = cse_intersection(Es0, Es1),
cse_successors_1(Ls, Es0, M#{L:=Es});
#{} ->
cse_successors_1(Ls, Es0, M#{L=>Es0})
end;
cse_successors_1([], _, M) -> M.
%% Calculate the intersection of the two maps. Both keys and values
%% must match.
cse_intersection(M1, M2) ->
if
map_size(M1) < map_size(M2) ->
cse_intersection_1(maps:to_list(M1), M2, M1);
true ->
cse_intersection_1(maps:to_list(M2), M1, M2)
end.
cse_intersection_1([{Key,Value}|KVs], M, Result) ->
case M of
#{Key := Value} ->
cse_intersection_1(KVs, M, Result);
#{} ->
cse_intersection_1(KVs, M, maps:remove(Key, Result))
end;
cse_intersection_1([], _, Result) -> Result.
cse_is([#b_set{op={succeeded,_},dst=Bool,args=[Src]}=I0|Is], Es, Sub0, Acc) ->
I = sub(I0, Sub0),
case I of
#b_set{args=[Src]} ->
cse_is(Is, Es, Sub0, [I|Acc]);
#b_set{} ->
%% The previous instruction has been eliminated. Eliminate the
%% 'succeeded' instruction too.
Sub = Sub0#{Bool=>#b_literal{val=true}},
cse_is(Is, Es, Sub, Acc)
end;
cse_is([#b_set{dst=Dst}=I0|Is], Es0, Sub0, Acc) ->
I = sub(I0, Sub0),
case beam_ssa:clobbers_xregs(I) of
true ->
%% Retaining the expressions map across calls and other
%% clobbering instructions would work, but it would cause
%% the common subexpressions to be saved to Y registers,
%% which would probably increase the size of the stack
%% frame.
cse_is(Is, #{}, Sub0, [I|Acc]);
false ->
case cse_expr(I) of
none ->
%% Not suitable for CSE.
cse_is(Is, Es0, Sub0, [I|Acc]);
{ok,ExprKey} ->
case Es0 of
#{ExprKey:=Src} ->
Sub = Sub0#{Dst=>Src},
cse_is(Is, Es0, Sub, Acc);
#{} ->
Es1 = Es0#{ExprKey=>Dst},
Es = cse_add_inferred_exprs(I, Es1),
cse_is(Is, Es, Sub0, [I|Acc])
end
end
end;