-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
sys_core_fold.erl
3451 lines (3155 loc) · 107 KB
/
sys_core_fold.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 1999-2016. 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%
%%
%% Purpose : Constant folding optimisation for Core
%% Propagate atomic values and fold in values of safe calls to
%% constant arguments. Also detect and remove literals which are
%% ignored in a 'seq'. Could handle lets better by chasing down
%% complex 'arg' expressions and finding values.
%%
%% Try to optimise case expressions by removing unmatchable or
%% unreachable clauses. Also change explicit tuple arg into multiple
%% values and extend clause patterns. We must be careful here not to
%% generate cases which we know to be safe but later stages will not
%% recognise as such, e.g. the following is NOT acceptable:
%%
%% case 'b' of
%% <'b'> -> ...
%% end
%%
%% Variable folding is complicated by variable shadowing, for example
%% in:
%% 'foo'/1 =
%% fun (X) ->
%% let <A> = X
%% in let <X> = Y
%% in ... <use A>
%% If we were to simply substitute X for A then we would be using the
%% wrong X. Our solution is to rename variables that are the values
%% of substitutions. We could rename all shadowing variables but do
%% the minimum. We would then get:
%% 'foo'/1 =
%% fun (X) ->
%% let <A> = X
%% in let <X1> = Y
%% in ... <use A>
%% which is optimised to:
%% 'foo'/1 =
%% fun (X) ->
%% let <X1> = Y
%% in ... <use X>
%%
%% This is done by carefully shadowing variables and substituting
%% values. See details when defining functions.
%%
%% It would be possible to extend to replace repeated evaluation of
%% "simple" expressions by the value (variable) of the first call.
%% For example, after a "let Z = X+1" then X+1 would be replaced by Z
%% where X is valid. The Sub uses the full Core expression as key.
%% It would complicate handling of patterns as we would have to remove
%% all values where the key contains pattern variables.
-module(sys_core_fold).
-export([module/2,format_error/1]).
-import(lists, [map/2,foldl/3,foldr/3,mapfoldl/3,all/2,any/2,
reverse/1,reverse/2,member/2,nth/2,flatten/1,
unzip/1,keyfind/3]).
-import(cerl, [ann_c_cons/3,ann_c_map/3,ann_c_tuple/2]).
-include("core_parse.hrl").
%%-define(DEBUG, 1).
-ifdef(DEBUG).
-define(ASSERT(E),
case E of
true -> ok;
false ->
io:format("~p, line ~p: assertion failed\n", [?MODULE,?LINE]),
exit(assertion_failed)
end).
-else.
-define(ASSERT(E), ignore).
-endif.
%% Variable value info.
-record(sub, {v=[], %Variable substitutions
s=cerl_sets:new() :: cerl_sets:set(), %Variables in scope
t=#{} :: map(), %Types
in_guard=false}). %In guard or not.
-type type_info() :: cerl:cerl() | 'bool' | 'integer'.
-type yes_no_maybe() :: 'yes' | 'no' | 'maybe'.
-type sub() :: #sub{}.
-spec module(cerl:c_module(), [compile:option()]) ->
{'ok', cerl:c_module(), [_]}.
module(#c_module{defs=Ds0}=Mod, Opts) ->
put(bin_opt_info, member(bin_opt_info, Opts)),
put(no_inline_list_funcs, not member(inline_list_funcs, Opts)),
case get(new_var_num) of
undefined -> put(new_var_num, 0);
_ -> ok
end,
init_warnings(),
Ds1 = [function_1(D) || D <- Ds0],
erase(no_inline_list_funcs),
erase(bin_opt_info),
{ok,Mod#c_module{defs=Ds1},get_warnings()}.
function_1({#c_var{name={F,Arity}}=Name,B0}) ->
try
B = expr(B0, value, sub_new()), %This must be a fun!
{Name,B}
catch
Class:Error ->
Stack = erlang:get_stacktrace(),
io:fwrite("Function: ~w/~w\n", [F,Arity]),
erlang:raise(Class, Error, Stack)
end.
%% body(Expr, Sub) -> Expr.
%% body(Expr, Context, Sub) -> Expr.
%% No special handling of anything except values.
body(Body, Sub) ->
body(Body, value, Sub).
body(#c_values{anno=A,es=Es0}, Ctxt, Sub) ->
Es1 = expr_list(Es0, Ctxt, Sub),
case Ctxt of
value ->
#c_values{anno=A,es=Es1};
effect ->
make_effect_seq(Es1, Sub)
end;
body(E, Ctxt, Sub) ->
?ASSERT(verify_scope(E, Sub)),
expr(E, Ctxt, Sub).
%% guard(Expr, Sub) -> Expr.
%% Do guard expression. We optimize it in the same way as
%% expressions in function bodies.
guard(Expr, Sub) ->
?ASSERT(verify_scope(Expr, Sub)),
expr(Expr, value, Sub#sub{in_guard=true}).
%% opt_guard_try(Expr) -> Expr.
%%
opt_guard_try(#c_seq{arg=Arg,body=Body0}=Seq) ->
Body = opt_guard_try(Body0),
case {Arg,Body} of
{#c_call{module=#c_literal{val=Mod},
name=#c_literal{val=Name},
args=Args},#c_literal{val=false}} ->
%% We have sequence consisting of a call (evaluated
%% for a possible exception and/or side effect only),
%% followed by 'false'.
%% Since the sequence is inside a try block that will
%% default to 'false' if any exception occurs, not
%% evalutating the call will not change the behaviour
%% provided that the call has no side effects.
case erl_bifs:is_pure(Mod, Name, length(Args)) of
false ->
%% Not a pure BIF (meaning that this is not
%% a guard and that we must keep the call).
Seq#c_seq{body=Body};
true ->
%% The BIF has no side effects, so it can
%% be safely removed.
Body
end;
{_,_} ->
Seq#c_seq{body=Body}
end;
opt_guard_try(#c_case{clauses=Cs}=Term) ->
Term#c_case{clauses=opt_guard_try_list(Cs)};
opt_guard_try(#c_clause{body=B0}=Term) ->
Term#c_clause{body=opt_guard_try(B0)};
opt_guard_try(#c_let{arg=Arg,body=B0}=Term) ->
case opt_guard_try(B0) of
#c_literal{}=B ->
opt_guard_try(#c_seq{arg=Arg,body=B});
B ->
Term#c_let{body=B}
end;
opt_guard_try(Term) -> Term.
opt_guard_try_list([C|Cs]) ->
[opt_guard_try(C)|opt_guard_try_list(Cs)];
opt_guard_try_list([]) -> [].
%% expr(Expr, Sub) -> Expr.
%% expr(Expr, Context, Sub) -> Expr.
expr(Expr, Sub) ->
expr(Expr, value, Sub).
expr(#c_var{}=V, Ctxt, Sub) ->
%% Return void() in effect context to potentially shorten the life time
%% of the variable and potentially generate better code
%% (for instance, if the variable no longer needs to survive a function
%% call, there will be no need to save it in the stack frame).
case Ctxt of
effect -> void();
value -> sub_get_var(V, Sub)
end;
expr(#c_literal{val=Val}=L, Ctxt, _Sub) ->
case Ctxt of
effect ->
case Val of
[] ->
%% Keep as [] - might give slightly better code.
L;
_ when is_atom(Val) ->
%% For cleanliness replace with void().
void();
_ ->
%% Warn and replace with void().
add_warning(L, useless_building),
void()
end;
value -> L
end;
expr(#c_cons{anno=Anno,hd=H0,tl=T0}=Cons, Ctxt, Sub) ->
H1 = expr(H0, Ctxt, Sub),
T1 = expr(T0, Ctxt, Sub),
case Ctxt of
effect ->
add_warning(Cons, useless_building),
expr(make_effect_seq([H1,T1], Sub), Ctxt, Sub);
value ->
ann_c_cons(Anno, H1, T1)
end;
expr(#c_tuple{anno=Anno,es=Es0}=Tuple, Ctxt, Sub) ->
Es = expr_list(Es0, Ctxt, Sub),
case Ctxt of
effect ->
add_warning(Tuple, useless_building),
expr(make_effect_seq(Es, Sub), Ctxt, Sub);
value ->
ann_c_tuple(Anno, Es)
end;
expr(#c_map{anno=Anno,arg=V0,es=Es0}=Map, Ctxt, Sub) ->
Es = pair_list(Es0, Ctxt, Sub),
case Ctxt of
effect ->
add_warning(Map, useless_building),
expr(make_effect_seq(Es, Sub), Ctxt, Sub);
value ->
V = expr(V0, Ctxt, Sub),
ann_c_map(Anno,V,Es)
end;
expr(#c_binary{segments=Ss}=Bin0, Ctxt, Sub) ->
%% Warn for useless building, but always build the binary
%% anyway to preserve a possible exception.
case Ctxt of
effect -> add_warning(Bin0, useless_building);
value -> ok
end,
Bin1 = Bin0#c_binary{segments=bitstr_list(Ss, Sub)},
Bin = bin_un_utf(Bin1),
eval_binary(Bin);
expr(#c_fun{}=Fun, effect, _) ->
%% A fun is created, but not used. Warn, and replace with the void value.
add_warning(Fun, useless_building),
void();
expr(#c_fun{vars=Vs0,body=B0}=Fun, Ctxt0, Sub0) ->
{Vs1,Sub1} = var_list(Vs0, Sub0),
Ctxt = case Ctxt0 of
{letrec,Ctxt1} -> Ctxt1;
value -> value
end,
B1 = body(B0, Ctxt, Sub1),
Fun#c_fun{vars=Vs1,body=B1};
expr(#c_seq{arg=Arg0,body=B0}=Seq0, Ctxt, Sub) ->
%% Optimise away pure literal arg as its value is ignored.
B1 = body(B0, Ctxt, Sub),
Arg = body(Arg0, effect, Sub),
case will_fail(Arg) of
true ->
Arg;
false ->
%% Arg cannot be "values" here - only a single value
%% make sense here.
case is_safe_simple(Arg, Sub) of
true -> B1;
false -> Seq0#c_seq{arg=Arg,body=B1}
end
end;
expr(#c_let{}=Let0, Ctxt, Sub) ->
Let = opt_case_in_let(Let0),
case simplify_let(Let, Sub) of
impossible ->
%% The argument for the let is "simple", i.e. has no
%% complex structures such as let or seq that can be entered.
?ASSERT(verify_scope(Let, Sub)),
opt_simple_let(Let, Ctxt, Sub);
Expr ->
%% The let body was successfully moved into the let argument.
%% Now recursively re-process the new expression.
expr(Expr, Ctxt, sub_new_preserve_types(Sub))
end;
expr(#c_letrec{body=#c_var{}}=Letrec, effect, _Sub) ->
%% This is named fun in an 'effect' context. Warn and ignore.
add_warning(Letrec, useless_building),
void();
expr(#c_letrec{defs=Fs0,body=B0}=Letrec, Ctxt, Sub) ->
Fs1 = map(fun ({Name,Fb}) ->
{Name,expr(Fb, {letrec,Ctxt}, Sub)}
end, Fs0),
B1 = body(B0, Ctxt, Sub),
Letrec#c_letrec{defs=Fs1,body=B1};
expr(#c_case{}=Case0, Ctxt, Sub) ->
%% Ideally, the compiler should only emit warnings when there is
%% a real mistake in the code being compiled. We use the follow
%% heuristics in an attempt to approach that ideal:
%%
%% * If the guard for a clause always fails, we will emit a
%% warning.
%%
%% * If a case expression is a literal, we will emit no warnings
%% for clauses that will not match or for clauses that are
%% shadowed after a clause that will always match. That means
%% that code such as:
%%
%% case ?DEBUG of
%% false -> ok;
%% true -> ...
%% end
%%
%% (where ?DEBUG expands to either 'true' or 'false') will not
%% produce any warnings.
%%
%% * If the case expression is not literal, warnings will be
%% emitted for every clause that don't match and for all
%% clauses following a clause that will always match.
%%
%% * If no clause will ever match, there will be a warning
%% (in addition to any warnings that may have been emitted
%% according to the rules above).
%%
case opt_bool_case(Case0) of
#c_case{arg=Arg0,clauses=Cs0}=Case1 ->
Arg1 = body(Arg0, value, Sub),
LitExpr = cerl:is_literal(Arg1),
{Arg2,Cs1} = case_opt(Arg1, Cs0, Sub),
Cs2 = clauses(Arg2, Cs1, Ctxt, Sub, LitExpr),
Case = Case1#c_case{arg=Arg2,clauses=Cs2},
warn_no_clause_match(Case1, Case),
Expr = eval_case(Case, Sub),
case move_case_into_arg(Case, Sub) of
impossible ->
bsm_an(Expr);
Other ->
expr(Other, Ctxt, sub_new_preserve_types(Sub))
end;
Other ->
expr(Other, Ctxt, Sub)
end;
expr(#c_receive{clauses=Cs0,timeout=T0,action=A0}=Recv, Ctxt, Sub) ->
Cs1 = clauses(#c_var{name='_'}, Cs0, Ctxt, Sub, false),
T1 = expr(T0, value, Sub),
A1 = body(A0, Ctxt, Sub),
Recv#c_receive{clauses=Cs1,timeout=T1,action=A1};
expr(#c_apply{anno=Anno,op=Op0,args=As0}=App, _, Sub) ->
Op1 = expr(Op0, value, Sub),
As1 = expr_list(As0, value, Sub),
case Op1 of
#c_var{} ->
App#c_apply{op=Op1,args=As1};
_ ->
add_warning(App, invalid_call),
Err = #c_call{anno=Anno,
module=#c_literal{val=erlang},
name=#c_literal{val=error},
args=[#c_tuple{es=[#c_literal{val='badfun'},
Op1]}]},
make_effect_seq(As1++[Err], Sub)
end;
expr(#c_call{module=M0,name=N0}=Call0, Ctxt, Sub) ->
M1 = expr(M0, value, Sub),
N1 = expr(N0, value, Sub),
Call = Call0#c_call{module=M1,name=N1},
case useless_call(Ctxt, Call) of
no -> call(Call, M1, N1, Sub);
{yes,Seq} -> expr(Seq, Ctxt, Sub)
end;
expr(#c_primop{args=As0}=Prim, _, Sub) ->
As1 = expr_list(As0, value, Sub),
Prim#c_primop{args=As1};
expr(#c_catch{body=B0}=Catch, _, Sub) ->
%% We can remove catch if the value is simple
B1 = body(B0, value, Sub),
case is_safe_simple(B1, Sub) of
true -> B1;
false -> Catch#c_catch{body=B1}
end;
expr(#c_try{arg=E0,vars=[#c_var{name=X}],body=#c_var{name=X},
handler=#c_literal{val=false}=False}=Try, _, Sub) ->
%% Since guard may call expr/2, we must do some optimization of
%% the kind of try's that occur in guards.
E1 = body(E0, value, Sub),
case will_fail(E1) of
false ->
%% Remove any calls that are evaluated for effect only.
E2 = opt_guard_try(E1),
%% We can remove try/catch if the expression is an
%% expression that cannot fail.
case is_safe_bool_expr(E2, Sub) orelse is_safe_simple(E2, Sub) of
true -> E2;
false -> Try#c_try{arg=E2}
end;
true ->
%% Expression will always fail.
False
end;
expr(#c_try{anno=A,arg=E0,vars=Vs0,body=B0,evars=Evs0,handler=H0}=Try, _, Sub0) ->
%% Here is the general try/catch construct outside of guards.
%% We can remove try if the value is simple and replace it with a let.
E1 = body(E0, value, Sub0),
{Vs1,Sub1} = var_list(Vs0, Sub0),
B1 = body(B0, value, Sub1),
case is_safe_simple(E1, Sub0) of
true ->
expr(#c_let{anno=A,vars=Vs1,arg=E1,body=B1}, value, Sub0);
false ->
{Evs1,Sub2} = var_list(Evs0, Sub0),
H1 = body(H0, value, Sub2),
Try#c_try{arg=E1,vars=Vs1,body=B1,evars=Evs1,handler=H1}
end.
expr_list(Es, Ctxt, Sub) ->
[expr(E, Ctxt, Sub) || E <- Es].
pair_list(Es, Ctxt, Sub) ->
[pair(E, Ctxt, Sub) || E <- Es].
pair(#c_map_pair{key=K,val=V}, effect, Sub) ->
make_effect_seq([K,V], Sub);
pair(#c_map_pair{key=K0,val=V0}=Pair, value=Ctxt, Sub) ->
K = expr(K0, Ctxt, Sub),
V = expr(V0, Ctxt, Sub),
Pair#c_map_pair{key=K,val=V}.
bitstr_list(Es, Sub) ->
[bitstr(E, Sub) || E <- Es].
bitstr(#c_bitstr{val=Val,size=Size}=BinSeg, Sub) ->
BinSeg#c_bitstr{val=expr(Val, Sub),size=expr(Size, value, Sub)}.
%% is_safe_simple(Expr, Sub) -> true | false.
%% A safe simple cannot fail with badarg and is safe to use
%% in a guard.
%%
%% Currently, we don't attempt to check binaries because they
%% are difficult to check.
is_safe_simple(#c_var{}=Var, _) ->
not cerl:is_c_fname(Var);
is_safe_simple(#c_cons{hd=H,tl=T}, Sub) ->
is_safe_simple(H, Sub) andalso is_safe_simple(T, Sub);
is_safe_simple(#c_tuple{es=Es}, Sub) -> is_safe_simple_list(Es, Sub);
is_safe_simple(#c_literal{}, _) -> true;
is_safe_simple(#c_call{module=#c_literal{val=erlang},
name=#c_literal{val=Name},
args=Args}, Sub) when is_atom(Name) ->
NumArgs = length(Args),
case erl_internal:bool_op(Name, NumArgs) of
true ->
%% Boolean operators are safe if the arguments are boolean.
all(fun(C) -> is_boolean_type(C, Sub) =:= yes end, Args);
false ->
%% We need a rather complicated test to ensure that
%% we only allow safe calls that are allowed in a guard.
%% (Note that is_function/2 is a type test, but is not safe.)
erl_bifs:is_safe(erlang, Name, NumArgs) andalso
(erl_internal:comp_op(Name, NumArgs) orelse
erl_internal:new_type_test(Name, NumArgs))
end;
is_safe_simple(_, _) -> false.
is_safe_simple_list(Es, Sub) -> all(fun(E) -> is_safe_simple(E, Sub) end, Es).
%% will_fail(Expr) -> true|false.
%% Determine whether the expression will fail with an exception.
%% Return true if the expression always will fail with an exception,
%% i.e. never return normally.
will_fail(#c_let{arg=A,body=B}) ->
will_fail(A) orelse will_fail(B);
will_fail(#c_call{module=#c_literal{val=Mod},name=#c_literal{val=Name},args=Args}) ->
erl_bifs:is_exit_bif(Mod, Name, length(Args));
will_fail(#c_primop{name=#c_literal{val=match_fail},args=[_]}) -> true;
will_fail(_) -> false.
%% bin_un_utf(#c_binary{}) -> #c_binary{}
%% Convert any literal UTF-8/16/32 literals to byte-sized
%% integer fields.
bin_un_utf(#c_binary{anno=Anno,segments=Ss}=Bin) ->
Bin#c_binary{segments=bin_un_utf_1(Ss, Anno)}.
bin_un_utf_1([#c_bitstr{val=#c_literal{},type=#c_literal{val=utf8}}=H|T],
Anno) ->
bin_un_utf_eval(H, Anno) ++ bin_un_utf_1(T, Anno);
bin_un_utf_1([#c_bitstr{val=#c_literal{},type=#c_literal{val=utf16}}=H|T],
Anno) ->
bin_un_utf_eval(H, Anno) ++ bin_un_utf_1(T, Anno);
bin_un_utf_1([#c_bitstr{val=#c_literal{},type=#c_literal{val=utf32}}=H|T],
Anno) ->
bin_un_utf_eval(H, Anno) ++ bin_un_utf_1(T, Anno);
bin_un_utf_1([H|T], Anno) ->
[H|bin_un_utf_1(T, Anno)];
bin_un_utf_1([], _) -> [].
bin_un_utf_eval(Bitstr, Anno) ->
Segments = [Bitstr],
case eval_binary(#c_binary{anno=Anno,segments=Segments}) of
#c_literal{anno=Anno,val=Bytes} when is_binary(Bytes) ->
[#c_bitstr{anno=Anno,
val=#c_literal{anno=Anno,val=B},
size=#c_literal{anno=Anno,val=8},
unit=#c_literal{anno=Anno,val=1},
type=#c_literal{anno=Anno,val=integer},
flags=#c_literal{anno=Anno,val=[unsigned,big]}} ||
B <- binary_to_list(Bytes)];
_ ->
Segments
end.
%% eval_binary(#c_binary{}) -> #c_binary{} | #c_literal{}
%% Evaluate a binary at compile time if possible to create
%% a binary literal.
eval_binary(#c_binary{anno=Anno,segments=Ss}=Bin) ->
try
#c_literal{anno=Anno,val=eval_binary_1(Ss, <<>>)}
catch
throw:impossible ->
Bin;
throw:{badarg,Warning} ->
add_warning(Bin, Warning),
#c_call{anno=Anno,
module=#c_literal{val=erlang},
name=#c_literal{val=error},
args=[#c_literal{val=badarg}]}
end.
eval_binary_1([#c_bitstr{val=#c_literal{val=Val},size=#c_literal{val=Sz},
unit=#c_literal{val=Unit},type=#c_literal{val=Type},
flags=#c_literal{val=Flags}}|Ss], Acc0) ->
Endian = case member(big, Flags) of
true ->
big;
false ->
case member(little, Flags) of
true -> little;
false -> throw(impossible) %Native endian.
end
end,
%% Make sure that the size is reasonable.
case Type of
binary when is_bitstring(Val) ->
if
Sz =:= all ->
ok;
Sz*Unit =< bit_size(Val) ->
ok;
true ->
%% Field size is greater than the actual binary - will fail.
throw({badarg,embedded_binary_size})
end;
integer when is_integer(Val) ->
%% Estimate the number of bits needed to to hold the integer
%% literal. Check whether the field size is reasonable in
%% proportion to the number of bits needed.
if
Sz*Unit =< 256 ->
%% Don't be cheap - always accept fields up to this size.
ok;
true ->
case count_bits(Val) of
BitsNeeded when 2*BitsNeeded >= Sz*Unit ->
ok;
_ ->
%% More than about half of the field size will be
%% filled out with zeroes - not acceptable.
throw(impossible)
end
end;
float when is_float(Val) ->
%% Bad float size.
case Sz*Unit of
32 -> ok;
64 -> ok;
_ -> throw(impossible)
end;
utf8 -> ok;
utf16 -> ok;
utf32 -> ok;
_ ->
throw(impossible)
end,
%% Evaluate the field.
try eval_binary_2(Acc0, Val, Sz, Unit, Type, Endian) of
Acc -> eval_binary_1(Ss, Acc)
catch
error:_ ->
throw(impossible)
end;
eval_binary_1([], Acc) -> Acc;
eval_binary_1(_, _) -> throw(impossible).
eval_binary_2(Acc, Val, Size, Unit, integer, little) ->
<<Acc/bitstring,Val:(Size*Unit)/little>>;
eval_binary_2(Acc, Val, Size, Unit, integer, big) ->
<<Acc/bitstring,Val:(Size*Unit)/big>>;
eval_binary_2(Acc, Val, _Size, _Unit, utf8, _) ->
try
<<Acc/bitstring,Val/utf8>>
catch
error:_ ->
throw({badarg,bad_unicode})
end;
eval_binary_2(Acc, Val, _Size, _Unit, utf16, big) ->
try
<<Acc/bitstring,Val/big-utf16>>
catch
error:_ ->
throw({badarg,bad_unicode})
end;
eval_binary_2(Acc, Val, _Size, _Unit, utf16, little) ->
try
<<Acc/bitstring,Val/little-utf16>>
catch
error:_ ->
throw({badarg,bad_unicode})
end;
eval_binary_2(Acc, Val, _Size, _Unit, utf32, big) ->
try
<<Acc/bitstring,Val/big-utf32>>
catch
error:_ ->
throw({badarg,bad_unicode})
end;
eval_binary_2(Acc, Val, _Size, _Unit, utf32, little) ->
try
<<Acc/bitstring,Val/little-utf32>>
catch
error:_ ->
throw({badarg,bad_unicode})
end;
eval_binary_2(Acc, Val, Size, Unit, float, little) ->
<<Acc/bitstring,Val:(Size*Unit)/little-float>>;
eval_binary_2(Acc, Val, Size, Unit, float, big) ->
<<Acc/bitstring,Val:(Size*Unit)/big-float>>;
eval_binary_2(Acc, Val, all, Unit, binary, _) ->
case bit_size(Val) of
Size when Size rem Unit =:= 0 ->
<<Acc/bitstring,Val:Size/bitstring>>;
Size ->
throw({badarg,{embedded_unit,Unit,Size}})
end;
eval_binary_2(Acc, Val, Size, Unit, binary, _) ->
<<Acc/bitstring,Val:(Size*Unit)/bitstring>>.
%% Count the number of bits approximately needed to store Int.
%% (We don't need an exact result for this purpose.)
count_bits(Int) ->
count_bits_1(abs(Int), 64).
count_bits_1(0, Bits) -> Bits;
count_bits_1(Int, Bits) -> count_bits_1(Int bsr 64, Bits+64).
%% useless_call(Context, #c_call{}) -> no | {yes,Expr}
%% Check whether the function is called only for effect,
%% and if the function either has no effect whatsoever or
%% the only effect is an exception. Generate appropriate
%% warnings. If the call is "useless" (has no effect),
%% a rewritten expression consisting of a sequence of
%% the arguments only is returned.
useless_call(effect, #c_call{module=#c_literal{val=Mod},
name=#c_literal{val=Name},
args=Args}=Call) ->
A = length(Args),
case erl_bifs:is_safe(Mod, Name, A) of
false ->
case erl_bifs:is_pure(Mod, Name, A) of
true -> add_warning(Call, result_ignored);
false -> ok
end,
no;
true ->
add_warning(Call, {no_effect,{Mod,Name,A}}),
{yes,make_effect_seq(Args, sub_new())}
end;
useless_call(_, _) -> no.
%% make_effect_seq([Expr], Sub) -> #c_seq{}|void()
%% Convert a list of expressions evaluated in effect context to a chain of
%% #c_seq{}. The body in the innermost #c_seq{} will be void().
%% Anything that will not have any effect will be thrown away.
make_effect_seq([H|T], Sub) ->
case is_safe_simple(H, Sub) of
true -> make_effect_seq(T, Sub);
false -> #c_seq{arg=H,body=make_effect_seq(T, Sub)}
end;
make_effect_seq([], _) -> void().
%% Handling remote calls. The module/name fields have been processed.
call(#c_call{args=As}=Call, #c_literal{val=M}=M0, #c_literal{val=N}=N0, Sub) ->
case get(no_inline_list_funcs) of
true ->
call_1(Call, M0, N0, As, Sub);
false ->
case sys_core_fold_lists:call(Call, M, N, As) of
none ->
call_1(Call, M, N, As, Sub);
Core ->
expr(Core, Sub)
end
end;
call(#c_call{args=As}=Call, M, N, Sub) ->
call_1(Call, M, N, As, Sub).
call_1(Call, M, N, As0, Sub) ->
As1 = expr_list(As0, value, Sub),
fold_call(Call#c_call{args=As1}, M, N, As1, Sub).
%% fold_call(Call, Mod, Name, Args, Sub) -> Expr.
%% Try to safely evaluate the call. Just try to evaluate arguments,
%% do the call and convert return values to literals. If this
%% succeeds then use the new value, otherwise just fail and use
%% original call. Do this at every level.
%%
%% We attempt to evaluate calls to certain BIFs even if the
%% arguments are not literals. For instance, we evaluate length/1
%% if the shape of the list is known, and element/2 and setelement/3
%% if the position is constant and the shape of the tuple is known.
%%
fold_call(Call, #c_literal{val=M}, #c_literal{val=F}, Args, Sub) ->
fold_call_1(Call, M, F, Args, Sub);
fold_call(Call, _M, _N, _Args, _Sub) -> Call.
fold_call_1(Call, erlang, apply, [Mod,Func,Args], _) ->
simplify_apply(Call, Mod, Func, Args);
fold_call_1(Call, Mod, Name, Args, Sub) ->
NumArgs = length(Args),
case erl_bifs:is_pure(Mod, Name, NumArgs) of
false -> Call; %Not pure - keep call.
true -> fold_call_2(Call, Mod, Name, Args, Sub)
end.
fold_call_2(Call, Module, Name, Args, Sub) ->
case all(fun cerl:is_literal/1, Args) of
true ->
%% All arguments are literals.
fold_lit_args(Call, Module, Name, Args);
false ->
%% At least one non-literal argument.
fold_non_lit_args(Call, Module, Name, Args, Sub)
end.
fold_lit_args(Call, Module, Name, Args0) ->
Args = [cerl:concrete(A) || A <- Args0],
try apply(Module, Name, Args) of
Val ->
case cerl:is_literal_term(Val) of
true ->
cerl:ann_abstract(cerl:get_ann(Call), Val);
false ->
%% Successful evaluation, but it was not possible
%% to express the computed value as a literal.
Call
end
catch
error:Reason ->
%% Evaluation of the function failed. Warn and replace
%% the call with a call to erlang:error/1.
eval_failure(Call, Reason)
end.
%% fold_non_lit_args(Call, Module, Name, Args, Sub) -> Expr.
%% Attempt to evaluate some pure BIF calls with one or more
%% non-literals arguments.
%%
fold_non_lit_args(Call, erlang, is_boolean, [Arg], Sub) ->
eval_is_boolean(Call, Arg, Sub);
fold_non_lit_args(Call, erlang, element, [Arg1,Arg2], Sub) ->
eval_element(Call, Arg1, Arg2, Sub);
fold_non_lit_args(Call, erlang, length, [Arg], _) ->
eval_length(Call, Arg);
fold_non_lit_args(Call, erlang, '++', [Arg1,Arg2], _) ->
eval_append(Call, Arg1, Arg2);
fold_non_lit_args(Call, lists, append, [Arg1,Arg2], _) ->
eval_append(Call, Arg1, Arg2);
fold_non_lit_args(Call, erlang, setelement, [Arg1,Arg2,Arg3], _) ->
eval_setelement(Call, Arg1, Arg2, Arg3);
fold_non_lit_args(Call, erlang, is_record, [Arg1,Arg2,Arg3], Sub) ->
eval_is_record(Call, Arg1, Arg2, Arg3, Sub);
fold_non_lit_args(Call, erlang, N, Args, Sub) ->
NumArgs = length(Args),
case erl_internal:comp_op(N, NumArgs) of
true ->
eval_rel_op(Call, N, Args, Sub);
false ->
case erl_internal:bool_op(N, NumArgs) of
true ->
eval_bool_op(Call, N, Args, Sub);
false ->
Call
end
end;
fold_non_lit_args(Call, _, _, _, _) -> Call.
%% Evaluate a relational operation using type information.
eval_rel_op(Call, Op, [#c_var{name=V},#c_var{name=V}], _) ->
Bool = erlang:Op(same, same),
#c_literal{anno=cerl:get_ann(Call),val=Bool};
eval_rel_op(Call, '=:=', [Term,#c_literal{val=true}], Sub) ->
%% BoolVar =:= true ==> BoolVar
case is_boolean_type(Term, Sub) of
yes -> Term;
maybe -> Call;
no -> #c_literal{val=false}
end;
eval_rel_op(Call, '==', Ops, Sub) ->
case is_exact_eq_ok(Ops, Sub) of
true ->
Name = #c_literal{anno=cerl:get_ann(Call),val='=:='},
Call#c_call{name=Name};
false ->
Call
end;
eval_rel_op(Call, '/=', Ops, Sub) ->
case is_exact_eq_ok(Ops, Sub) of
true ->
Name = #c_literal{anno=cerl:get_ann(Call),val='=/='},
Call#c_call{name=Name};
false ->
Call
end;
eval_rel_op(Call, _, _, _) -> Call.
is_exact_eq_ok([A,B]=L, Sub) ->
case is_int_type(A, Sub) =:= yes andalso is_int_type(B, Sub) =:= yes of
true -> true;
false -> is_exact_eq_ok_1(L)
end.
is_exact_eq_ok_1([#c_literal{val=Lit}|_]) ->
is_non_numeric(Lit);
is_exact_eq_ok_1([_|T]) ->
is_exact_eq_ok_1(T);
is_exact_eq_ok_1([]) -> false.
is_non_numeric([H|T]) ->
is_non_numeric(H) andalso is_non_numeric(T);
is_non_numeric(Tuple) when is_tuple(Tuple) ->
is_non_numeric_tuple(Tuple, tuple_size(Tuple));
is_non_numeric(Map) when is_map(Map) ->
%% Note that 17.x and 18.x compare keys in different ways.
%% Be very conservative -- require that both keys and values
%% are non-numeric.
is_non_numeric(maps:to_list(Map));
is_non_numeric(Num) when is_number(Num) ->
false;
is_non_numeric(_) -> true.
is_non_numeric_tuple(Tuple, El) when El >= 1 ->
is_non_numeric(element(El, Tuple)) andalso
is_non_numeric_tuple(Tuple, El-1);
is_non_numeric_tuple(_Tuple, 0) -> true.
%% Evaluate a bool op using type information. We KNOW that
%% there must be at least one non-literal argument (i.e.
%% there is no need to handle the case that all argments
%% are literal).
eval_bool_op(Call, 'and', [#c_literal{val=true},Term], Sub) ->
eval_bool_op_1(Call, Term, Term, Sub);
eval_bool_op(Call, 'and', [Term,#c_literal{val=true}], Sub) ->
eval_bool_op_1(Call, Term, Term, Sub);
eval_bool_op(Call, 'and', [#c_literal{val=false}=Res,Term], Sub) ->
eval_bool_op_1(Call, Res, Term, Sub);
eval_bool_op(Call, 'and', [Term,#c_literal{val=false}=Res], Sub) ->
eval_bool_op_1(Call, Res, Term, Sub);
eval_bool_op(Call, _, _, _) -> Call.
eval_bool_op_1(Call, Res, Term, Sub) ->
case is_boolean_type(Term, Sub) of
yes -> Res;
no -> eval_failure(Call, badarg);
maybe -> Call
end.
%% Evaluate is_boolean/1 using type information.
eval_is_boolean(Call, Term, Sub) ->
case is_boolean_type(Term, Sub) of
no -> #c_literal{val=false};
yes -> #c_literal{val=true};
maybe -> Call
end.
%% eval_length(Call, List) -> Val.
%% Evaluates the length for the prefix of List which has a known
%% shape.
%%
eval_length(Call, Core) -> eval_length(Call, Core, 0).
eval_length(Call, #c_literal{val=Val}, Len0) ->
try
Len = Len0 + length(Val),
#c_literal{anno=Call#c_call.anno,val=Len}
catch
_:_ ->
eval_failure(Call, badarg)
end;
eval_length(Call, #c_cons{tl=T}, Len) ->
eval_length(Call, T, Len+1);
eval_length(Call, _List, 0) ->
Call; %Could do nothing
eval_length(Call, List, Len) ->
A = Call#c_call.anno,
#c_call{anno=A,
module=#c_literal{anno=A,val=erlang},
name=#c_literal{anno=A,val='+'},
args=[#c_literal{anno=A,val=Len},Call#c_call{args=[List]}]}.
%% eval_append(Call, FirstList, SecondList) -> Val.
%% Evaluates the constant part of '++' expression.
%%
eval_append(Call, #c_literal{val=Cs1}=S1, #c_literal{val=Cs2}) ->
try
S1#c_literal{val=Cs1 ++ Cs2}
catch error:badarg ->
eval_failure(Call, badarg)
end;
eval_append(Call, #c_literal{val=Cs}, List) when length(Cs) =< 4 ->
Anno = Call#c_call.anno,
foldr(fun (C, L) ->
ann_c_cons(Anno, #c_literal{val=C}, L)
end, List, Cs);
eval_append(Call, #c_cons{anno=Anno,hd=H,tl=T}, List) ->
ann_c_cons(Anno, H, eval_append(Call, T, List));
eval_append(Call, X, Y) ->
Call#c_call{args=[X,Y]}. %Rebuild call arguments.
%% eval_element(Call, Pos, Tuple, Types) -> Val.
%% Evaluates element/2 if the position Pos is a literal and
%% the shape of the tuple Tuple is known.
%%
eval_element(Call, #c_literal{val=Pos}, Tuple, Types)
when is_integer(Pos) ->
case get_type(Tuple, Types) of
none ->
Call;
Type ->
Es = case cerl:is_c_tuple(Type) of
false -> [];
true -> cerl:tuple_es(Type)
end,
if
1 =< Pos, Pos =< length(Es) ->
El = lists:nth(Pos, Es),
try
cerl:set_ann(pat_to_expr(El), [compiler_generated])
catch
throw:impossible ->
Call
end;
true ->
%% Index outside tuple or not a tuple.
eval_failure(Call, badarg)
end
end;
eval_element(Call, Pos, Tuple, Sub) ->
case is_int_type(Pos, Sub) =:= no orelse
is_tuple_type(Tuple, Sub) =:= no of
true ->