1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 1999-2020. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20%% Purpose : Transform normal Erlang to Core Erlang
21
22%% At this stage all preprocessing has been done. All that is left are
23%% "pure" Erlang functions.
24%%
25%% Core transformation is done in four stages:
26%%
27%% 1. Flatten expressions into an internal core form without doing
28%%    matching.
29%%
30%% 2. Step "forwards" over the icore code annotating each "top-level"
31%%    thing with variable usage.  Detect bound variables in matching
32%%    and replace with explicit guard test.  Annotate "internal-core"
33%%    expressions with variables they use and create.  Convert matches
34%%    to cases when not pure assignments.
35%%
36%% 3. Step "backwards" over icore code using variable usage
37%%    annotations to change implicit exported variables to explicit
38%%    returns.
39%%
40%% 4. Lower receives to more primitive operations.  Split binary
41%%    patterns where a value is matched out and then used used as
42%%    a size in the same pattern.  That simplifies the subsequent
43%%    passes as all variables are within a single pattern are either
44%%    new or used, but never both at the same time.
45%%
46%% To ensure the evaluation order we ensure that all arguments are
47%% safe.  A "safe" is basically a core_lib simple with VERY restricted
48%% binaries.
49%%
50%% We have to be very careful with matches as these create variables.
51%% While we try not to flatten things more than necessary we must make
52%% sure that all matches are at the top level.  For this we use the
53%% type "novars" which are non-match expressions.  Cases and receives
54%% can also create problems due to exports variables so they are not
55%% "novars" either.  I.e. a novars will not export variables.
56%%
57%% Annotations in the #iset, #iletrec, and all other internal records
58%% is kept in a record, #a, not in a list as in proper core.  This is
59%% easier and faster and creates no problems as we have complete control
60%% over all annotations.
61%%
62%% On output, the annotation for most Core Erlang terms will contain
63%% the source line number. A few terms will be marked with the atom
64%% atom 'compiler_generated', to indicate that the compiler has generated
65%% them and that no warning should be generated if they are optimized
66%% away.
67%%
68%%
69%% In this translation:
70%%
71%% call ops are safes
72%% call arguments are safes
73%% match arguments are novars
74%% case arguments are novars
75%% receive timeouts are novars
76%% binaries and maps are novars
77%% let/set arguments are expressions
78%% fun is not a safe
79
80-module(v3_core).
81
82-export([module/2,format_error/1]).
83
84-import(lists, [reverse/1,reverse/2,map/2,member/2,foldl/3,foldr/3,mapfoldl/3,
85                splitwith/2,keyfind/3,sort/1,droplast/1,last/1,
86                duplicate/2]).
87-import(ordsets, [add_element/2,del_element/2,is_element/2,
88		  union/1,union/2,intersection/2,subtract/2]).
89-import(cerl, [ann_c_cons/3,ann_c_tuple/2,c_tuple/1,
90	       ann_c_map/3]).
91
92-include("core_parse.hrl").
93
94%% Matches expansion max segment in v3_kernel.
95-define(COLLAPSE_MAX_SIZE_SEGMENT, 1024).
96
97%% Internal core expressions and help functions.
98%% N.B. annotations fields in place as normal Core expressions.
99
100-record(a, {us=[],ns=[],anno=[]}).		%Internal annotation
101
102-record(iapply,    {anno=#a{},op,args}).
103-record(ibinary,   {anno=#a{},segments}).	%Not used in patterns.
104-record(ibitstr,   {anno=#a{},val,size,unit,type,flags}).
105-record(icall,     {anno=#a{},module,name,args}).
106-record(icase,     {anno=#a{},args,clauses,fc}).
107-record(icatch,    {anno=#a{},body}).
108-record(iclause,   {anno=#a{},pats,guard,body}).
109-record(ifun,      {anno=#a{},id,vars,clauses,fc,name=unnamed}).
110-record(iletrec,   {anno=#a{},defs,body}).
111-record(imatch,    {anno=#a{},pat,guard=[],arg,fc}).
112-record(imap,      {anno=#a{},arg=#c_literal{val=#{}},es,is_pat=false}).
113-record(imappair,  {anno=#a{},op,key,val}).
114-record(iprimop,   {anno=#a{},name,args}).
115-record(iprotect,  {anno=#a{},body}).
116-record(ireceive1, {anno=#a{},clauses}).
117-record(ireceive2, {anno=#a{},clauses,timeout,action}).
118-record(iset,      {anno=#a{},var,arg}).
119-record(itry,      {anno=#a{},args,vars,body,evars,handler}).
120-record(ifilter,   {anno=#a{},arg}).
121-record(igen,      {anno=#a{},acc_pat,acc_guard,
122		    skip_pat,tail,tail_pat,arg}).
123-record(isimple,   {anno=#a{},term :: cerl:cerl()}).
124
125-type iapply()    :: #iapply{}.
126-type ibinary()   :: #ibinary{}.
127-type icall()     :: #icall{}.
128-type icase()     :: #icase{}.
129-type icatch()    :: #icatch{}.
130-type iclause()   :: #iclause{}.
131-type ifun()      :: #ifun{}.
132-type iletrec()   :: #iletrec{}.
133-type imatch()    :: #imatch{}.
134-type imap()      :: #imap{}.
135-type iprimop()   :: #iprimop{}.
136-type iprotect()  :: #iprotect{}.
137-type ireceive1() :: #ireceive1{}.
138-type ireceive2() :: #ireceive2{}.
139-type iset()      :: #iset{}.
140-type itry()      :: #itry{}.
141-type ifilter()   :: #ifilter{}.
142-type igen()      :: #igen{}.
143-type isimple()   :: #isimple{}.
144
145-type i() :: iapply()    | ibinary()   | icall()     | icase()  | icatch()
146           | iclause()   | ifun()      | iletrec()   | imatch() | imap()
147           | iprimop()   | iprotect()  | ireceive1() | ireceive2()
148           | iset()      | itry()      | ifilter()
149           | igen()      | isimple().
150
151-type warning() :: {file:filename(), [{integer(), module(), term()}]}.
152
153-record(core, {vcount=0 :: non_neg_integer(),	%Variable counter
154	       fcount=0 :: non_neg_integer(),	%Function counter
155               gcount=0 :: non_neg_integer(),   %Goto counter
156	       function={none,0} :: fa(),	%Current function.
157	       in_guard=false :: boolean(),	%In guard or not.
158	       wanted=true :: boolean(),	%Result wanted or not.
159	       opts=[]     :: [compile:option()], %Options.
160               dialyzer=false :: boolean(),     %Help dialyzer or not.
161	       ws=[]    :: [warning()],		%Warnings.
162               file=[{file,""}]			%File.
163	      }).
164
165%% XXX: The following type declarations do not belong in this module
166-type fa()        :: {atom(), arity()}.
167-type attribute() :: atom().
168-type form()      :: {function, integer(), atom(), arity(), _}
169                   | {attribute, integer(), attribute(), _}.
170
171-record(imodule, {name = [],
172		  exports = ordsets:new(),
173		  attrs = [],
174		  defs = [],
175		  file = [],
176		  opts = [],
177		  ws = []}).
178
179-spec module([form()], [compile:option()]) ->
180        {'ok',cerl:c_module(),[warning()]}.
181
182module(Forms0, Opts) ->
183    Forms = erl_internal:add_predefined_functions(Forms0),
184    Module = foldl(fun (F, Acc) ->
185			   form(F, Acc, Opts)
186		   end, #imodule{}, Forms),
187    #imodule{name=Mod,exports=Exp0,attrs=As0,defs=Kfs0,ws=Ws} = Module,
188    Exp = case member(export_all, Opts) of
189	      true -> defined_functions(Forms);
190	      false -> Exp0
191	  end,
192    Cexp = [#c_var{name=FA} || {_,_}=FA <- Exp],
193    As = reverse(As0),
194    Kfs = reverse(Kfs0),
195    {ok,#c_module{name=#c_literal{val=Mod},exports=Cexp,attrs=As,defs=Kfs},Ws}.
196
197form({function,_,_,_,_}=F0, Module, Opts) ->
198    #imodule{file=File,defs=Defs,ws=Ws0} = Module,
199    {F,Ws} = function(F0, Ws0, File, Opts),
200    Module#imodule{defs=[F|Defs],ws=Ws};
201form({attribute,_,module,Mod}, Module, _Opts) ->
202    true = is_atom(Mod),
203    Module#imodule{name=Mod};
204form({attribute,_,file,{File,_Line}}=F, #imodule{attrs=As}=Module, _Opts) ->
205    Module#imodule{file=File, attrs=[attribute(F)|As]};
206form({attribute,_,import,_}, Module, _Opts) ->
207    %% Ignore. We have no futher use for imports.
208    Module;
209form({attribute,_,export,Es}, #imodule{exports=Exp0}=Module, _Opts) ->
210    Exp = ordsets:union(ordsets:from_list(Es), Exp0),
211    Module#imodule{exports=Exp};
212form({attribute,_,_,_}=F, #imodule{attrs=As}=Module, _Opts) ->
213    Module#imodule{attrs=[attribute(F)|As]};
214form(_, Module, _Opts) ->
215    %% Ignore uninteresting forms such as 'eof'.
216    Module.
217
218attribute({attribute,A,Name,Val0}) ->
219    Line = [erl_anno:location(A)],
220    Val = if
221	      is_list(Val0) -> Val0;
222	      true -> [Val0]
223	  end,
224    {#c_literal{val=Name, anno=Line}, #c_literal{val=Val, anno=Line}}.
225
226defined_functions(Forms) ->
227    Fs = [{Name,Arity} || {function,_,Name,Arity,_} <- Forms],
228    ordsets:from_list(Fs).
229
230%% function_dump(module_info,_,_,_) -> ok;
231%% function_dump(Name,Arity,Format,Terms) ->
232%%     io:format("~w/~w " ++ Format,[Name,Arity]++Terms),
233%%     ok.
234
235function({function,_,Name,Arity,Cs0}, Ws0, File, Opts) ->
236    try
237        St0 = #core{vcount=0,function={Name,Arity},opts=Opts,
238                    dialyzer=member(dialyzer, Opts),
239                    ws=Ws0,file=[{file,File}]},
240        {B0,St1} = body(Cs0, Name, Arity, St0),
241        %% ok = function_dump(Name, Arity, "body:~n~p~n",[B0]),
242        {B1,St2} = ubody(B0, St1),
243        %% ok = function_dump(Name, Arity, "ubody:~n~p~n",[B1]),
244        {B2,St3} = cbody(B1, St2),
245        %% ok = function_dump(Name, Arity, "cbody:~n~p~n",[B2]),
246        {B3,#core{ws=Ws}} = lbody(B2, St3),
247        %% ok = function_dump(Name, Arity, "lbody:~n~p~n",[B3]),
248        {{#c_var{name={Name,Arity}},B3},Ws}
249    catch
250        Class:Error:Stack ->
251	    io:fwrite("Function: ~w/~w\n", [Name,Arity]),
252	    erlang:raise(Class, Error, Stack)
253    end.
254
255body(Cs0, Name, Arity, St0) ->
256    Anno = lineno_anno(element(2, hd(Cs0)), St0),
257    FunAnno = [{function,{Name,Arity}} | Anno],
258    {Args0,St1} = new_vars(Anno, Arity, St0),
259    Args = reverse(Args0),                      %Nicer order
260    {Cs1,St2} = clauses(Cs0, St1),
261    {Ps,St3} = new_vars(Arity, St2),    %Need new variables here
262    Fc = function_clause(Ps, Anno),
263    {#ifun{anno=#a{anno=FunAnno},id=[],vars=Args,clauses=Cs1,fc=Fc},St3}.
264
265%% clause(Clause, State) -> {Cclause,State}.
266%% clauses([Clause], State) -> {[Cclause],State}.
267%%  Convert clauses. Trap bad pattern aliases.
268
269clauses([C0|Cs0], St0) ->
270    {C,St1} = clause(C0, St0),
271    {Cs,St2} = clauses(Cs0, St1),
272    {[C|Cs],St2};
273clauses([], St) -> {[],St}.
274
275clause({clause,Lc,H0,G0,B0}, St0) ->
276    try head(H0, St0) of
277	{H1,St1} ->
278	    {G1,St2} = guard(G0, St1),
279	    {B1,St3} = exprs(B0, St2),
280            Anno = lineno_anno(Lc, St3),
281            {#iclause{anno=#a{anno=Anno},pats=H1,guard=G1,body=B1},St3}
282    catch
283	throw:nomatch ->
284            %% This pattern can't possibly match. If we simply remove
285            %% the clause, varibles that are used later might not be
286            %% bound. Therefore, we must keep the clause, but rewrite
287            %% the pattern to a pattern that will bind the same
288            %% variables and ensure that the clause can't be executed
289            %% by letting the guard return false.
290            St1 = add_warning(Lc, {nomatch,pattern}, St0),
291            H1 = [sanitize(P) || P <- H0],
292            false = H0 =:= H1,                  %Assertion.
293            G1 = [[{atom,Lc,false}]],
294            LcNoWarn = no_compiler_warning(Lc),
295            clause({clause,LcNoWarn,H1,G1,B0}, St1)
296    end.
297
298clause_arity({clause,_,H0,_,_}) -> length(H0).
299
300%% head([P], State) -> {[P],[Cexpr],State}.
301
302head(Ps, St) ->
303    pattern_list(Ps, St).
304
305%% guard([Expr], State) -> {[Cexpr],State}.
306%%  Build an explict and/or tree of guard alternatives, then traverse
307%%  top-level and/or tree and "protect" inner tests.
308
309guard([], St) -> {[],St};
310guard(Gs0, St0) ->
311    Gs1 = foldr(fun (Gt0, Rhs) ->
312			Gt1 = guard_tests(Gt0),
313			L = element(2, Gt1),
314			{op,L,'or',Gt1,Rhs}
315		end, guard_tests(last(Gs0)), droplast(Gs0)),
316    {Gs,St} = gexpr_top(Gs1, St0#core{in_guard=true}),
317    {Gs,St#core{in_guard=false}}.
318
319guard_tests(Gs) ->
320    L = element(2, hd(Gs)),
321    {protect,L,foldr(fun (G, Rhs) -> {op,L,'and',G,Rhs} end, last(Gs), droplast(Gs))}.
322
323%% gexpr_top(Expr, State) -> {Cexpr,State}.
324%%  Generate an internal core expression of a guard test.  Explicitly
325%%  handle outer boolean expressions and "protect" inner tests in a
326%%  reasonably smart way.
327
328gexpr_top(E0, St0) ->
329    {E1,Eps0,Bools,St1} = gexpr(E0, [], St0),
330    {E,Eps,St} = force_booleans(Bools, E1, Eps0, St1),
331    {Eps++[E],St}.
332
333%% gexpr(Expr, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
334%%  Generate an internal core expression of a guard test.
335
336gexpr({protect,Line,Arg}, Bools0, St0) ->
337    case gexpr(Arg, [], St0) of
338	{E0,[],Bools,St1} ->
339	    {E,Eps,St} = force_booleans(Bools, E0, [], St1),
340	    {E,Eps,Bools0,St};
341	{E0,Eps0,Bools,St1} ->
342	    {E,Eps,St} = force_booleans(Bools, E0, Eps0, St1),
343            Anno = lineno_anno(Line, St),
344	    {#iprotect{anno=#a{anno=Anno},body=Eps++[E]},[],Bools0,St}
345    end;
346gexpr({op,_,'andalso',_,_}=E0, Bools, St0) ->
347    {op,L,'andalso',E1,E2} = right_assoc(E0, 'andalso'),
348    Anno = lineno_anno(L, St0),
349    {#c_var{name=V0},St} = new_var(Anno, St0),
350    V = {var,L,V0},
351    False = {atom,L,false},
352    E = make_bool_switch(L, E1, V, E2, False),
353    gexpr(E, Bools, St);
354gexpr({op,_,'orelse',_,_}=E0, Bools, St0) ->
355    {op,L,'orelse',E1,E2} = right_assoc(E0, 'orelse'),
356    Anno = lineno_anno(L, St0),
357    {#c_var{name=V0},St} = new_var(Anno, St0),
358    V = {var,L,V0},
359    True = {atom,L,true},
360    E = make_bool_switch(L, E1, V, True, E2),
361    gexpr(E, Bools, St);
362gexpr({op,Line,Op,L,R}=E, Bools, St) ->
363    case erl_internal:bool_op(Op, 2) of
364        true ->
365            gexpr_bool(Op, L, R, Bools, St, Line);
366        false ->
367            gexpr_test(E, Bools, St)
368    end;
369gexpr({call,Line,{remote,_,{atom,_,erlang},{atom,_,Op}},[L,R]}=E, Bools, St) ->
370    case erl_internal:bool_op(Op, 2) of
371        true ->
372            gexpr_bool(Op, L, R, Bools, St, Line);
373        false ->
374            gexpr_test(E, Bools, St)
375    end;
376gexpr({op,Line,'not',A}, Bools, St) ->
377    gexpr_not(A, Bools, St, Line);
378gexpr({call,Line,{remote,_,{atom,_,erlang},{atom,_,'not'}},[A]}, Bools, St) ->
379    gexpr_not(A, Bools, St, Line);
380gexpr(E0, Bools, St0) ->
381    gexpr_test(E0, Bools, St0).
382
383%% gexpr_bool(L, R, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
384%%  Generate a guard for boolean operators
385
386gexpr_bool(Op, L, R, Bools0, St0, Line) ->
387    {Le,Lps,Bools1,St1} = gexpr(L, Bools0, St0),
388    {Ll,Llps,St2} = force_safe(Le, St1),
389    {Re,Rps,Bools,St3} = gexpr(R, Bools1, St2),
390    {Rl,Rlps,St4} = force_safe(Re, St3),
391    Anno = lineno_anno(Line, St4),
392    {#icall{anno=#a{anno=Anno}, %Must have an #a{}
393            module=#c_literal{anno=Anno,val=erlang},
394            name=#c_literal{anno=Anno,val=Op},
395            args=[Ll,Rl]},Lps ++ Llps ++ Rps ++ Rlps,Bools,St4}.
396
397%% gexpr_not(Expr, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
398%%  Generate an erlang:'not'/1 guard test.
399
400gexpr_not(A, Bools0, St0, Line) ->
401    {Ae0,Aps,Bools,St1} = gexpr(A, Bools0, St0),
402    case Ae0 of
403        #icall{anno=#a{anno=[v3_core,compiler_generated]},
404               module=#c_literal{val=erlang},
405               name=#c_literal{val='=:='},
406               args=[E,#c_literal{val=true}]}=EqCall ->
407            %%
408            %% We here have the expression:
409            %%
410            %%    not(Expr =:= true)
411            %%
412            %% The annotations tested in the code above guarantees
413            %% that the original expression in the Erlang source
414            %% code was:
415            %%
416            %%    not Expr
417            %%
418            %% That expression can be transformed as follows:
419            %%
420            %%    not Expr  ==>  Expr =:= false
421            %%
422            %% which will produce the same result, but may eliminate
423            %% redundant is_boolean/1 tests (see unforce/3).
424            %%
425            %% Note that this tranformation would not be safe if the
426            %% original expression had been:
427            %%
428            %%    not(Expr =:= true)
429            %%
430            Ae = EqCall#icall{args=[E,#c_literal{val=false}]},
431            {Al,Alps,St2} = force_safe(Ae, St1),
432            {Al,Aps ++ Alps,Bools,St2};
433        Ae ->
434            {Al,Alps,St2} = force_safe(Ae, St1),
435            Anno = lineno_anno(Line, St2),
436            {#icall{anno=#a{anno=Anno}, %Must have an #a{}
437                    module=#c_literal{anno=Anno,val=erlang},
438                    name=#c_literal{anno=Anno,val='not'},
439                    args=[Al]},Aps ++ Alps,Bools,St2}
440    end.
441
442%% gexpr_test(Expr, Bools, State) -> {Cexpr,[PreExp],Bools,State}.
443%%  Generate a guard test.  At this stage we must be sure that we have
444%%  a proper boolean value here so wrap things with an true test if we
445%%  don't know, i.e. if it is not a comparison or a type test.
446
447gexpr_test({atom,L,true}, Bools, St0) ->
448    {#c_literal{anno=lineno_anno(L, St0),val=true},[],Bools,St0};
449gexpr_test({atom,L,false}, Bools, St0) ->
450    {#c_literal{anno=lineno_anno(L, St0),val=false},[],Bools,St0};
451gexpr_test(E0, Bools0, St0) ->
452    {E1,Eps0,St1} = expr(E0, St0),
453    %% Generate "top-level" test and argument calls.
454    case E1 of
455        #icall{anno=Anno,module=#c_literal{val=erlang},
456               name=#c_literal{val=is_function},
457               args=[_,_]} ->
458            %% is_function/2 is not a safe type test. We must force
459            %% it to be protected.
460            Lanno = Anno#a.anno,
461            {New,St2} = new_var(Lanno, St1),
462            {icall_eq_true(New),
463             Eps0 ++ [#iset{anno=Anno,var=New,arg=E1}],Bools0,St2};
464	#icall{anno=Anno,module=#c_literal{val=erlang},name=#c_literal{val=N},args=As} ->
465            %% Note that erl_expand_records has renamed type
466            %% tests to the new names; thus, float/1 as a type
467            %% test will now be named is_float/1.
468	    Ar = length(As),
469	    case erl_internal:new_type_test(N, Ar) orelse
470                erl_internal:comp_op(N, Ar) orelse
471                erl_internal:bool_op(N, Ar) of
472		true -> {E1,Eps0,Bools0,St1};
473		false ->
474		    Lanno = Anno#a.anno,
475		    {New,St2} = new_var(Lanno, St1),
476		    Bools = [New|Bools0],
477		    {icall_eq_true(New),
478		     Eps0 ++ [#iset{anno=Anno,var=New,arg=E1}],Bools,St2}
479	    end;
480	_ ->
481	    Lanno = get_lineno_anno(E1),
482	    ACompGen = #a{anno=[compiler_generated]},
483	    case is_simple(E1) of
484		true ->
485		    Bools = [E1|Bools0],
486		    {icall_eq_true(E1),Eps0,Bools,St1};
487		false ->
488		    {New,St2} = new_var(Lanno, St1),
489		    Bools = [New|Bools0],
490		    {icall_eq_true(New),
491		     Eps0 ++ [#iset{anno=ACompGen,var=New,arg=E1}],Bools,St2}
492	    end
493    end.
494
495icall_eq_true(Arg) ->
496    %% We need to recognize a '=:=' added by this pass, so we will add
497    %% an extra 'v3_core' annotation. (Being paranoid, we don't want
498    %% to trust 'compiler_generated' alone as it could have been added
499    %% by a parse transform.)
500    #icall{anno=#a{anno=[v3_core,compiler_generated]},
501	   module=#c_literal{val=erlang},
502	   name=#c_literal{val='=:='},
503	   args=[Arg,#c_literal{val=true}]}.
504
505%% force_booleans([Var], E, Eps, St) -> Expr.
506%%  Variables used in the top-level of a guard must be booleans.
507%%
508%%  Add necessary is_boolean/1 guard tests to ensure that the guard
509%%  will fail if any of the variables is not a boolean.
510
511force_booleans(Vs0, E, Eps, St) ->
512    Vs1 = [set_anno(V, []) || V <- Vs0],
513
514    %% Prune the list of variables that will need is_boolean/1
515    %% tests. Basically, if the guard consists of simple expressions
516    %% joined by 'and's no is_boolean/1 tests are needed.
517    Vs = unforce(E, Eps, Vs1),
518
519    %% Add is_boolean/1 tests for the remaining variables.
520    force_booleans_1(Vs, E, Eps, St).
521
522force_booleans_1([], E, Eps, St) ->
523    {E,Eps,St};
524force_booleans_1([V|Vs], E0, Eps0, St0) ->
525    {E1,Eps1,St1} = force_safe(E0, St0),
526    ACompGen = #a{anno=[compiler_generated]},
527    Call = #icall{anno=ACompGen,module=#c_literal{val=erlang},
528		  name=#c_literal{val=is_boolean},
529		  args=[V]},
530    {New,St} = new_var([], St1),
531    Iset = #iset{var=New,arg=Call},
532    Eps = Eps0 ++ Eps1 ++ [Iset],
533    E = #icall{anno=ACompGen,
534	       module=#c_literal{val=erlang},name=#c_literal{val='and'},
535	       args=[E1,New]},
536    force_booleans_1(Vs, E, Eps, St).
537
538
539%% unforce(Expr, PreExprList, BoolExprList) -> BoolExprList'.
540%%  Filter BoolExprList. BoolExprList is a list of simple expressions
541%%  (variables or literals) of which we are not sure whether they are booleans.
542%%
543%%  The basic idea for filtering is the following transformation:
544%%
545%%      (E =:= Bool) and is_boolean(E)   ==>  E =:= Bool
546%%
547%%  where E is an arbitrary expression and Bool is 'true' or 'false'.
548%%
549%%  The transformation is still valid if there are other expressions joined
550%%  by 'and' operations:
551%%
552%%      E1 and (E2 =:= true) and E3 and is_boolean(E)   ==>  E1 and (E2 =:= true) and E3
553%%
554%%  but expressions such as:
555%%
556%%     not (E =:= true) and is_boolean(E)
557%%
558%%  or expression using 'or' or 'xor' cannot be transformed in this
559%%  way (such expressions are the reason for adding the is_boolean/1
560%%  test in the first place).
561%%
562unforce(_, _, []) ->
563    [];
564unforce(E, Eps, Vs) ->
565    Tree = unforce_tree(Eps++[E], gb_trees:empty()),
566    unforce(Tree, Vs).
567
568unforce_tree([#iset{var=#c_var{name=V},arg=Arg0}|Es], D0) ->
569    Arg = unforce_tree_subst(Arg0, D0),
570    D = gb_trees:insert(V, Arg, D0),
571    unforce_tree(Es, D);
572unforce_tree([#icall{}=Call], D) ->
573    unforce_tree_subst(Call, D);
574unforce_tree([#c_var{name=V}], D) ->
575    gb_trees:get(V, D).
576
577unforce_tree_subst(#icall{module=#c_literal{val=erlang},
578			  name=#c_literal{val='=:='},
579			  args=[_Expr,#c_literal{val=Bool}]}=Call, _)
580  when is_boolean(Bool) ->
581    %% We have erlang:'=:='(Expr, Bool). We must not expand this call any more
582    %% or we will not recognize is_boolean(Expr) later.
583    Call;
584unforce_tree_subst(#icall{args=Args0}=Call, D) ->
585    Args = map(fun(#c_var{name=V}=Var) ->
586		       case gb_trees:lookup(V, D) of
587			   {value,Val} -> Val;
588			   none -> Var
589		       end;
590		  (Expr) -> Expr
591	       end, Args0),
592    Call#icall{args=Args};
593unforce_tree_subst(Expr, _) -> Expr.
594
595unforce(#icall{module=#c_literal{val=erlang},
596	       name=#c_literal{val=Name},
597	       args=Args}, Vs0) ->
598    case {Name,Args} of
599	{'and',[Arg1,Arg2]} ->
600	    Vs = unforce(Arg1, Vs0),
601	    unforce(Arg2, Vs);
602	{'=:=',[E,#c_literal{val=Bool}]} when is_boolean(Bool) ->
603	    Vs0 -- [set_anno(E, [])];
604	{_,_} ->
605	    %% Give up.
606	    Vs0
607    end;
608unforce(_, Vs) -> Vs.
609
610%% exprs([Expr], State) -> {[Cexpr],State}.
611%%  Flatten top-level exprs.
612
613exprs([E0|Es0], St0) ->
614    {E1,Eps,St1} = expr(E0, St0),
615    {Es1,St2} = exprs(Es0, St1),
616    {Eps ++ [E1] ++ Es1,St2};
617exprs([], St) -> {[],St}.
618
619%% expr(Expr, State) -> {Cexpr,[PreExp],State}.
620%%  Generate an internal core expression.
621
622expr({var,L,V}, St) -> {#c_var{anno=lineno_anno(L, St),name=V},[],St};
623expr({char,L,C}, St) -> {#c_literal{anno=full_anno(L, St),val=C},[],St};
624expr({integer,L,I}, St) -> {#c_literal{anno=full_anno(L, St),val=I},[],St};
625expr({float,L,F}, St) -> {#c_literal{anno=full_anno(L, St),val=F},[],St};
626expr({atom,L,A}, St) -> {#c_literal{anno=full_anno(L, St),val=A},[],St};
627expr({nil,L}, St) -> {#c_literal{anno=full_anno(L, St),val=[]},[],St};
628expr({string,L,S}, St) -> {#c_literal{anno=full_anno(L, St),val=S},[],St};
629expr({cons,L,H0,T0}, St0) ->
630    {H1,Hps,St1} = safe(H0, St0),
631    {T1,Tps,St2} = safe(T0, St1),
632    A = full_anno(L, St2),
633    {annotate_cons(A, H1, T1, St2),Hps ++ Tps,St2};
634expr({lc,L,E,Qs0}, St0) ->
635    {Qs1,St1} = preprocess_quals(L, Qs0, St0),
636    lc_tq(L, E, Qs1, #c_literal{anno=lineno_anno(L, St1),val=[]}, St1);
637expr({bc,L,E,Qs}, St) ->
638    bc_tq(L, E, Qs, St);
639expr({tuple,L,Es0}, St0) ->
640    {Es1,Eps,St1} = safe_list(Es0, St0),
641    A = record_anno(L, St1),
642    {annotate_tuple(A, Es1, St1),Eps,St1};
643expr({map,L,Es0}, St0) ->
644    map_build_pairs(#c_literal{val=#{}}, Es0, full_anno(L, St0), St0);
645expr({map,L,M,Es}, St) ->
646    expr_map(M, Es, L, St);
647expr({bin,L,Es0}, St0) ->
648    try expr_bin(Es0, full_anno(L, St0), St0) of
649	{_,_,_}=Res -> Res
650    catch
651	throw:{bad_binary,Eps,St1} ->
652	    St = add_warning(L, {failed,bad_binary}, St1),
653	    LineAnno = lineno_anno(L, St),
654	    As = [#c_literal{anno=LineAnno,val=badarg}],
655	    {#icall{anno=#a{anno=LineAnno},	%Must have an #a{}
656		    module=#c_literal{anno=LineAnno,val=erlang},
657		    name=#c_literal{anno=LineAnno,val=error},
658		    args=As},Eps,St}
659    end;
660expr({block,_,Es0}, St0) ->
661    %% Inline the block directly.
662    {Es1,St1} = exprs(droplast(Es0), St0),
663    {E1,Eps,St2} = expr(last(Es0), St1),
664    {E1,Es1 ++ Eps,St2};
665expr({'if',L,Cs0}, St0) ->
666    {Cs1,St1} = clauses(Cs0, St0),
667    Lanno = lineno_anno(L, St1),
668    Fc = fail_clause([], Lanno, #c_literal{val=if_clause}),
669    {#icase{anno=#a{anno=Lanno},args=[],clauses=Cs1,fc=Fc},[],St1};
670expr({'case',L,E0,Cs0}, St0) ->
671    {E1,Eps,St1} = novars(E0, St0),
672    {Cs1,St2} = clauses(Cs0, St1),
673    {Fpat,St3} = new_var(St2),
674    Lanno = lineno_anno(L, St2),
675    Fc = fail_clause([Fpat], Lanno, c_tuple([#c_literal{val=case_clause},Fpat])),
676    {#icase{anno=#a{anno=Lanno},args=[E1],clauses=Cs1,fc=Fc},Eps,St3};
677expr({'receive',L,Cs0}, St0) ->
678    {Cs1,St1} = clauses(Cs0, St0),
679    {#ireceive1{anno=#a{anno=lineno_anno(L, St1)},clauses=Cs1},[],St1};
680expr({'receive',L,Cs0,Te0,Tes0}, St0) ->
681    {Te1,Teps,St1} = novars(Te0, St0),
682    {Tes1,St2} = exprs(Tes0, St1),
683    {Cs1,St3} = clauses(Cs0, St2),
684    {#ireceive2{anno=#a{anno=lineno_anno(L, St3)},
685		clauses=Cs1,timeout=Te1,action=Tes1},Teps,St3};
686expr({'try',L,Es0,[],Ecs,[]}, St0) ->
687    %% 'try ... catch ... end'
688    {Es1,St1} = exprs(Es0, St0),
689    {V,St2} = new_var(St1),		%This name should be arbitrary
690    {Evs,Hs,St3} = try_exception(Ecs, St2),
691    Lanno = lineno_anno(L, St3),
692    {#itry{anno=#a{anno=Lanno},args=Es1,vars=[V],body=[V],
693	   evars=Evs,handler=Hs},
694     [],St3};
695expr({'try',L,Es0,Cs0,Ecs,[]}, St0) ->
696    %% 'try ... of ... catch ... end'
697    {Es1,St1} = exprs(Es0, St0),
698    {V,St2} = new_var(St1),		%This name should be arbitrary
699    {Cs1,St3} = clauses(Cs0, St2),
700    {Fpat,St4} = new_var(St3),
701    Lanno = lineno_anno(L, St4),
702    Fc = fail_clause([Fpat], Lanno,
703		     c_tuple([#c_literal{val=try_clause},Fpat])),
704    {Evs,Hs,St5} = try_exception(Ecs, St4),
705    {#itry{anno=#a{anno=lineno_anno(L, St5)},args=Es1,
706	   vars=[V],body=[#icase{anno=#a{anno=Lanno},args=[V],clauses=Cs1,fc=Fc}],
707	   evars=Evs,handler=Hs},
708     [],St5};
709expr({'try',L,Es0,[],[],As0}, St0) ->
710    %% 'try ... after ... end'
711    try_after(L, Es0, As0, St0);
712expr({'try',L,Es,Cs,Ecs,As}, St0) ->
713    %% 'try ... [of ...] [catch ...] after ... end'
714    expr({'try',L,[{'try',L,Es,Cs,Ecs,[]}],[],[],As}, St0);
715expr({'catch',L,E0}, St0) ->
716    {E1,Eps,St1} = expr(E0, St0),
717    Lanno = lineno_anno(L, St1),
718    {#icatch{anno=#a{anno=Lanno},body=Eps ++ [E1]},[],St1};
719expr({'fun',L,{function,F,A}}, St0) ->
720    {Fname,St1} = new_fun_name(St0),
721    Lanno = full_anno(L, St1),
722    Id = {0,0,Fname},
723    {#c_var{anno=Lanno++[{id,Id}],name={F,A}},[],St1};
724expr({'fun',L,{function,M,F,A}}, St0) ->
725    {As,Aps,St1} = safe_list([M,F,A], St0),
726    Lanno = full_anno(L, St1),
727    {#icall{anno=#a{anno=Lanno},
728	    module=#c_literal{val=erlang},
729	    name=#c_literal{val=make_fun},
730	    args=As},Aps,St1};
731expr({'fun',L,{clauses,Cs}}, St) ->
732    fun_tq(Cs, L, St, unnamed);
733expr({named_fun,L,'_',Cs}, St) ->
734    fun_tq(Cs, L, St, unnamed);
735expr({named_fun,L,Name,Cs}, St) ->
736    fun_tq(Cs, L, St, {named,Name});
737expr({call,L,{remote,_,M,F},As0}, St0) ->
738    {[M1,F1|As1],Aps,St1} = safe_list([M,F|As0], St0),
739    Anno = full_anno(L, St1),
740    {#icall{anno=#a{anno=Anno},module=M1,name=F1,args=As1},Aps,St1};
741expr({call,Lc,{atom,Lf,F},As0}, St0) ->
742    {As1,Aps,St1} = safe_list(As0, St0),
743    Op = #c_var{anno=lineno_anno(Lf, St1),name={F,length(As1)}},
744    {#iapply{anno=#a{anno=lineno_anno(Lc, St1)},op=Op,args=As1},Aps,St1};
745expr({call,L,FunExp,As0}, St0) ->
746    {Fun,Fps,St1} = safe(FunExp, St0),
747    {As1,Aps,St2} = safe_list(As0, St1),
748    Lanno = lineno_anno(L, St2),
749    {#iapply{anno=#a{anno=Lanno},op=Fun,args=As1},Fps ++ Aps,St2};
750expr({match,L,P0,E0}, St0) ->
751    %% First fold matches together to create aliases.
752    {P1,E1} = fold_match(E0, P0),
753    St1 = set_wanted(P1, St0),
754    {E2,Eps1,St2} = novars(E1, St1),
755    St3 = St2#core{wanted=St0#core.wanted},
756    {P2,St4} = try
757                   pattern(P1, St3)
758               catch
759                   throw:Thrown ->
760                       {Thrown,St3}
761               end,
762    {Fpat,St5} = new_var(St4),
763    Lanno = lineno_anno(L, St5),
764    Fc = fail_clause([Fpat], Lanno, c_tuple([#c_literal{val=badmatch},Fpat])),
765    case P2 of
766	nomatch ->
767	    %% The pattern will not match. We must take care here to
768	    %% bind all variables that the pattern would have bound
769	    %% so that subsequent expressions do not refer to unbound
770	    %% variables.
771	    %%
772	    %% As an example, this code:
773	    %%
774	    %%   [X] = {Y} = E,
775	    %%   X + Y.
776	    %%
777	    %% will be rewritten to:
778	    %%
779	    %%   error({badmatch,E}),
780	    %%   case E of
781	    %%      {[X],{Y}} ->
782	    %%        X + Y;
783	    %%      Other ->
784	    %%        error({badmatch,Other})
785	    %%   end.
786	    %%
787	    St6 = add_warning(L, {nomatch,pattern}, St5),
788	    {Expr,Eps3,St7} = safe(E1, St6),
789	    SanPat0 = sanitize(P1),
790	    {SanPat,St} = pattern(SanPat0, St7),
791	    Badmatch = c_tuple([#c_literal{val=badmatch},Expr]),
792	    Fail = #iprimop{anno=#a{anno=Lanno},
793			    name=#c_literal{val=match_fail},
794			    args=[Badmatch]},
795	    Eps = Eps3 ++ [Fail],
796	    {#imatch{anno=#a{anno=Lanno},pat=SanPat,arg=Expr,fc=Fc},Eps,St};
797	Other when not is_atom(Other) ->
798            %% We must rewrite top-level aliases to lets to avoid unbound
799            %% variables in code such as:
800            %%
801            %%     <<42:Sz>> = Sz = B
802            %%
803            %% If we would keep the top-level aliases the example would
804            %% be translated like this:
805            %%
806            %% 	   case B of
807            %%         <Sz = #{#<42>(Sz,1,'integer',['unsigned'|['big']])}#>
808            %%            when 'true' ->
809            %%            .
810            %%            .
811            %%            .
812            %%
813            %% Here the variable Sz would be unbound in the binary pattern.
814            %%
815            %% Instead we bind Sz in a let to ensure it is bound when
816            %% used in the binary pattern:
817            %%
818            %%     let <Sz> = B
819            %% 	   in case Sz of
820            %%         <#{#<42>(Sz,1,'integer',['unsigned'|['big']])}#>
821            %%            when 'true' ->
822            %%            .
823            %%            .
824            %%            .
825            %%
826            {P3,E3,Eps2} = letify_aliases(P2, E2),
827            Eps = Eps1 ++ Eps2,
828            {#imatch{anno=#a{anno=Lanno},pat=P3,arg=E3,fc=Fc},Eps,St5}
829    end;
830expr({op,_,'++',{lc,Llc,E,Qs0},More}, St0) ->
831    %% Optimise '++' here because of the list comprehension algorithm.
832    %%
833    %% To avoid achieving quadratic complexity if there is a chain of
834    %% list comprehensions without generators combined with '++', force
835    %% evaluation of More now. Evaluating More here could also reduce the
836    %% number variables in the environment for letrec.
837    {Mc,Mps,St1} = safe(More, St0),
838    {Qs,St2} = preprocess_quals(Llc, Qs0, St1),
839    {Y,Yps,St} = lc_tq(Llc, E, Qs, Mc, St2),
840    {Y,Mps++Yps,St};
841expr({op,_,'andalso',_,_}=E0, St0) ->
842    {op,L,'andalso',E1,E2} = right_assoc(E0, 'andalso'),
843    Anno = lineno_anno(L, St0),
844    {#c_var{name=V0},St} = new_var(Anno, St0),
845    V = {var,L,V0},
846    False = {atom,L,false},
847    E = make_bool_switch(L, E1, V, E2, False),
848    expr(E, St);
849expr({op,_,'orelse',_,_}=E0, St0) ->
850    {op,L,'orelse',E1,E2} = right_assoc(E0, 'orelse'),
851    Anno = lineno_anno(L, St0),
852    {#c_var{name=V0},St} = new_var(Anno, St0),
853    V = {var,L,V0},
854    True = {atom,L,true},
855    E = make_bool_switch(L, E1, V, True, E2),
856    expr(E, St);
857expr({op,L,Op,A0}, St0) ->
858    {A1,Aps,St1} = safe(A0, St0),
859    LineAnno = full_anno(L, St1),
860    {#icall{anno=#a{anno=LineAnno},		%Must have an #a{}
861	    module=#c_literal{anno=LineAnno,val=erlang},
862	    name=#c_literal{anno=LineAnno,val=Op},args=[A1]},Aps,St1};
863expr({op,L,Op,L0,R0}, St0) ->
864    {As,Aps,St1} = safe_list([L0,R0], St0),
865    LineAnno = full_anno(L, St1),
866    {#icall{anno=#a{anno=LineAnno},		%Must have an #a{}
867	    module=#c_literal{anno=LineAnno,val=erlang},
868	    name=#c_literal{anno=LineAnno,val=Op},args=As},Aps,St1}.
869
870%% set_wanted(Pattern, St) -> St'.
871%%  Suppress warnings for expressions that are bound to the '_'
872%%  variable and variables that begin with '_'.
873set_wanted({var,_,'_'}, St) ->
874    St#core{wanted=false};
875set_wanted({var,_,Var}, St) ->
876    case atom_to_list(Var) of
877        "_" ++ _ ->
878            St#core{wanted=false};
879        _ ->
880            St
881    end;
882set_wanted(_, St) -> St.
883
884letify_aliases(#c_alias{var=V,pat=P0}, E0) ->
885    {P1,E1,Eps0} = letify_aliases(P0, V),
886    {P1,E1,[#iset{var=V,arg=E0}|Eps0]};
887letify_aliases(P, E) ->
888    {P,E,[]}.
889
890%% sanitize(Pat) -> SanitizedPattern
891%%  Rewrite Pat so that it will be accepted by pattern/2 and will
892%%  bind the same variables as the original pattern.
893%%
894%%  Here is an example of a pattern that would cause a pattern/2
895%%  to generate a 'nomatch' exception:
896%%
897%%      #{k:=X,k:=Y} = [Z]
898%%
899%%  The sanitized pattern will look like:
900%%
901%%      {{X,Y},[Z]}
902
903sanitize({match,L,P1,P2}) ->
904    {tuple,L,[sanitize(P1),sanitize(P2)]};
905sanitize({cons,L,H,T}) ->
906    {cons,L,sanitize(H),sanitize(T)};
907sanitize({tuple,L,Ps0}) ->
908    Ps = [sanitize(P) || P <- Ps0],
909    {tuple,L,Ps};
910sanitize({bin,L,Segs0}) ->
911    Segs = [Var || {bin_element,_,{var,_,_}=Var,_,_} <- Segs0],
912    {tuple,L,Segs};
913sanitize({map,L,Ps0}) ->
914    Ps = [sanitize(V) || {map_field_exact,_,_,V} <- Ps0],
915    {tuple,L,Ps};
916sanitize({op,L,_Name,P1,P2}) ->
917    {tuple,L,[sanitize(P1),sanitize(P2)]};
918sanitize(P) -> P.
919
920make_bool_switch(L, E, V, T, F) ->
921    NegL = no_compiler_warning(L),
922    Error = {tuple,NegL,[{atom,NegL,badarg},V]},
923    {'case',NegL,E,
924     [{clause,NegL,[{atom,NegL,true}],[],[T]},
925      {clause,NegL,[{atom,NegL,false}],[],[F]},
926      {clause,NegL,[V],[],
927       [{call,NegL,{remote,NegL,{atom,NegL,erlang},{atom,NegL,error}},
928	 [Error]}]}]}.
929
930expr_map(M0, Es0, L, St0) ->
931    {M1,Eps0,St1} = safe_map(M0, St0),
932    Badmap = badmap_term(M1, St1),
933    A = lineno_anno(L, St1),
934    Fc = fail_clause([], [{eval_failure,badmap}|A], Badmap),
935    {M2,Eps1,St2} = map_build_pairs(M1, Es0, full_anno(L, St1), St1),
936    M3 = case Es0 of
937             [] -> M1;
938             [_|_] -> M2
939         end,
940    Cs = [#iclause{
941             anno=#a{anno=[compiler_generated|A]},
942             pats=[],
943             guard=[#icall{anno=#a{anno=A},
944                           module=#c_literal{anno=A,val=erlang},
945                           name=#c_literal{anno=A,val=is_map},
946                           args=[M1]}],
947             body=[M3]}],
948    Eps = Eps0 ++ Eps1,
949    {#icase{anno=#a{anno=A},args=[],clauses=Cs,fc=Fc},Eps,St2}.
950
951safe_map(M0, St0) ->
952    case safe(M0, St0) of
953        {#c_var{},_,_}=Res ->
954            Res;
955        {#c_literal{val=Map},_,_}=Res when is_map(Map) ->
956            Res;
957        {NotMap,Eps0,St1} ->
958            %% Not a map. There will be a syntax error if we try to
959            %% pretty-print the Core Erlang code and then try to parse
960            %% it. To avoid the syntax error, force the term into a
961            %% variable.
962	    {V,St2} = new_var(St1),
963            Anno = cerl:get_ann(NotMap),
964            Eps1 = [#iset{anno=#a{anno=Anno},var=V,arg=NotMap}],
965	    {V,Eps0++Eps1,St2}
966    end.
967
968badmap_term(_Map, #core{in_guard=true}) ->
969    %% The code generator cannot handle complex error reasons
970    %% in guards. But the exact error reason does not matter anyway
971    %% since it is not user-visible.
972    #c_literal{val=badmap};
973badmap_term(Map, #core{in_guard=false}) ->
974    c_tuple([#c_literal{val=badmap},Map]).
975
976map_build_pairs(Map, Es0, Ann, St0) ->
977    {Es,Pre,_,St1} = map_build_pairs_1(Es0, sets:new([{version, 2}]), St0),
978    {ann_c_map(Ann, Map, Es),Pre,St1}.
979
980map_build_pairs_1([{Op0,L,K0,V0}|Es], Used0, St0) ->
981    {K,Pre0,St1} = safe(K0, St0),
982    {V,Pre1,St2} = safe(V0, St1),
983    {Pairs,Pre2,Used1,St3} = map_build_pairs_1(Es, Used0, St2),
984    As = lineno_anno(L, St3),
985    Op = map_op(Op0),
986    {Used2,St4} = maybe_warn_repeated_keys(K, K0, Used1, St3),
987    Pair = cerl:ann_c_map_pair(As, Op, K, V),
988    {[Pair|Pairs],Pre0++Pre1++Pre2,Used2,St4};
989map_build_pairs_1([], Used, St) ->
990    {[],[],Used,St}.
991
992maybe_warn_repeated_keys(Ck, K0, Used, St) ->
993    case cerl:is_literal(Ck) of
994        false -> {Used,St};
995        true ->
996            K = cerl:concrete(Ck),
997            case sets:is_element(K,Used) of
998                true ->
999                    L = erl_parse:first_anno(K0),
1000                    {Used, add_warning(L, {map_key_repeated,K}, St)};
1001                false ->
1002                    {sets:add_element(K,Used), St}
1003            end
1004    end.
1005
1006map_op(map_field_assoc) -> #c_literal{val=assoc};
1007map_op(map_field_exact) -> #c_literal{val=exact}.
1008
1009%% try_exception([ExcpClause], St) -> {[ExcpVar],Handler,St}.
1010
1011try_exception(Ecs0, St0) ->
1012    %% Note that Tag is not needed for rethrow - it is already in Info.
1013    {Evs,St1} = new_vars(3, St0), % Tag, Value, Info
1014    {Ecs1,St2} = clauses(Ecs0, St1),
1015    Ecs2 = try_build_stacktrace(Ecs1, hd(Evs)),
1016    [_,Value,Info] = Evs,
1017    LA = case Ecs2 of
1018	     [] -> [];
1019	     [C|_] -> get_lineno_anno(C)
1020	 end,
1021    Ec = #iclause{anno=#a{anno=[compiler_generated|LA]},
1022		  pats=[c_tuple(Evs)],guard=[#c_literal{val=true}],
1023		  body=[#iprimop{anno=#a{},       %Must have an #a{}
1024				 name=#c_literal{val=raise},
1025				 args=[Info,Value]}]},
1026    Hs = [#icase{anno=#a{anno=LA},args=[c_tuple(Evs)],clauses=Ecs2,fc=Ec}],
1027    {Evs,Hs,St2}.
1028
1029try_after(Line, Es0, As0, St0) ->
1030    %% 'try ... after ... end'
1031    As1 = ta_sanitize_as(As0, Line),
1032
1033    {Es, St1} = exprs(Es0, St0),
1034    {As, St2} = exprs(As1, St1),
1035    {V, St3} = new_var(St2),                    % (must not exist in As1)
1036    LineAnno = lineno_anno(Line, St3),
1037
1038    case is_iexprs_small(As, 20) of
1039        true -> try_after_small(LineAnno, Es, As, V, St3);
1040        false -> try_after_large(LineAnno, Es, As, V, St3)
1041    end.
1042
1043%% 'after' blocks don't have a result, so we match the last expression with '_'
1044%% to suppress false "unmatched return" warnings in tools that look at core
1045%% Erlang, such as `dialyzer`.
1046ta_sanitize_as([Expr], Line) ->
1047    [{match, Line, {var,Line,'_'}, Expr}];
1048ta_sanitize_as([Expr | Exprs], Line) ->
1049    [Expr | ta_sanitize_as(Exprs, Line)].
1050
1051try_after_large(LA, Es, As, V, St0) ->
1052    %% Large 'after' block; break it out into a wrapper function to reduce
1053    %% code size.
1054    Lanno = #a{anno=LA},
1055    {Name, St1} = new_fun_name("after", St0),
1056    Fc = function_clause([], LA),
1057    Fun = #ifun{anno=Lanno,id=[],vars=[],
1058                clauses=[#iclause{anno=Lanno,pats=[],
1059                                  guard=[#c_literal{val=true}],
1060                                  body=As}],
1061                fc=Fc},
1062    App = #iapply{anno=#a{anno=[compiler_generated|LA]},
1063                  op=#c_var{anno=LA,name={Name,0}},
1064                  args=[]},
1065    {Evs, Hs, St} = after_block([App], St1),
1066    Try = #itry{anno=Lanno,
1067                args=Es,
1068                vars=[V],
1069                body=[App,V],
1070                evars=Evs,
1071                handler=Hs},
1072    Letrec = #iletrec{anno=Lanno,defs=[{{Name,0},Fun}],
1073                      body=[Try]},
1074    {Letrec, [], St}.
1075
1076try_after_small(LA, Es, As, V, St0)  ->
1077    %% Small 'after' block; inline it.
1078    Lanno = #a{anno=LA},
1079    {Evs, Hs, St1} = after_block(As, St0),
1080    Try = #itry{anno=Lanno,args=Es,vars=[V],
1081                body=(As ++ [V]),
1082                evars=Evs,handler=Hs},
1083    {Try, [], St1}.
1084
1085after_block(As, St0) ->
1086    %% See above.
1087    {Evs, St1} = new_vars(3, St0),              % Tag, Value, Info
1088    [_,Value,Info] = Evs,
1089    B = As ++ [#iprimop{anno=#a{},              % Must have an #a{}
1090                        name=#c_literal{val=raise},
1091                        args=[Info,Value]}],
1092    Ec = #iclause{anno=#a{anno=[compiler_generated]},
1093                  pats=[c_tuple(Evs)],guard=[#c_literal{val=true}],
1094                  body=B},
1095    Hs = [#icase{anno=#a{},args=[c_tuple(Evs)],clauses=[],fc=Ec}],
1096    {Evs, Hs, St1}.
1097
1098try_build_stacktrace([#iclause{pats=Ps0,body=B0}=C0|Cs], RawStk) ->
1099    [#c_tuple{es=[Class,Exc,Stk]}=Tup] = Ps0,
1100    case Stk of
1101        #c_var{name='_'} ->
1102            %% Stacktrace variable is not used. Nothing to do.
1103            [C0|try_build_stacktrace(Cs, RawStk)];
1104        _ ->
1105            %% Add code to build the stacktrace.
1106            Ps = [Tup#c_tuple{es=[Class,Exc,RawStk]}],
1107            Call = #iprimop{anno=#a{},
1108                            name=#c_literal{val=build_stacktrace},
1109                            args=[RawStk]},
1110            Iset = #iset{var=Stk,arg=Call},
1111            B = [Iset|B0],
1112            C = C0#iclause{pats=Ps,body=B},
1113            [C|try_build_stacktrace(Cs, RawStk)]
1114    end;
1115try_build_stacktrace([], _) -> [].
1116
1117%% is_iexprs_small([Exprs], Threshold) -> boolean().
1118%%  Determines whether a list of expressions is "smaller" than the given
1119%%  threshold. This is largely analogous to cerl_trees:size/1 but operates on
1120%%  our internal #iexprs{} and bails out as soon as the threshold is exceeded.
1121is_iexprs_small(Exprs, Threshold) ->
1122    0 < is_iexprs_small_1(Exprs, Threshold).
1123
1124is_iexprs_small_1(_, 0) ->
1125    0;
1126is_iexprs_small_1([], Threshold) ->
1127    Threshold;
1128is_iexprs_small_1([Expr | Exprs], Threshold0) ->
1129    Threshold = is_iexprs_small_2(Expr, Threshold0 - 1),
1130    is_iexprs_small_1(Exprs, Threshold).
1131
1132is_iexprs_small_2(#iclause{guard=Guards,body=Body}, Threshold0) ->
1133    Threshold = is_iexprs_small_1(Guards, Threshold0),
1134    is_iexprs_small_1(Body, Threshold);
1135is_iexprs_small_2(#itry{body=Body,handler=Handler}, Threshold0) ->
1136    Threshold = is_iexprs_small_1(Body, Threshold0),
1137    is_iexprs_small_1(Handler, Threshold);
1138is_iexprs_small_2(#imatch{guard=Guards}, Threshold) ->
1139    is_iexprs_small_1(Guards, Threshold);
1140is_iexprs_small_2(#icase{clauses=Clauses}, Threshold) ->
1141    is_iexprs_small_1(Clauses, Threshold);
1142is_iexprs_small_2(#ifun{clauses=Clauses}, Threshold) ->
1143    is_iexprs_small_1(Clauses, Threshold);
1144is_iexprs_small_2(#ireceive1{clauses=Clauses}, Threshold) ->
1145    is_iexprs_small_1(Clauses, Threshold);
1146is_iexprs_small_2(#ireceive2{clauses=Clauses}, Threshold) ->
1147    is_iexprs_small_1(Clauses, Threshold);
1148is_iexprs_small_2(#icatch{body=Body}, Threshold) ->
1149    is_iexprs_small_1(Body, Threshold);
1150is_iexprs_small_2(#iletrec{body=Body}, Threshold) ->
1151    is_iexprs_small_1(Body, Threshold);
1152is_iexprs_small_2(#iprotect{body=Body}, Threshold) ->
1153    is_iexprs_small_1(Body, Threshold);
1154is_iexprs_small_2(#iset{arg=Arg}, Threshold) ->
1155    is_iexprs_small_2(Arg, Threshold);
1156is_iexprs_small_2(_, Threshold) ->
1157    Threshold.
1158
1159%% expr_bin([ArgExpr], St) -> {[Arg],[PreExpr],St}.
1160%%  Flatten the arguments of a bin. Do this straight left to right!
1161%%  Note that ibinary needs to have its annotation wrapped in a #a{}
1162%%  record whereas c_literal should not have a wrapped annotation
1163
1164expr_bin(Es0, Anno, St0) ->
1165    Es1 = [bin_element(E) || E <- Es0],
1166    case constant_bin(Es1) of
1167	error ->
1168            case expr_bin_1(Es1, St0) of
1169                {[],Eps,St} ->
1170                    EmptyBin = <<>>,
1171                    {#c_literal{anno=Anno,val=EmptyBin},Eps,St};
1172                {Es,Eps,St} ->
1173                    {#ibinary{anno=#a{anno=Anno},segments=Es},Eps,St}
1174            end;
1175	Bin ->
1176	    {#c_literal{anno=Anno,val=Bin},[],St0}
1177    end.
1178
1179expr_bin_1(Es, St0) ->
1180    Res = foldr(fun (E, {Ces,Eps0,S0}) ->
1181                        try bitstr(E, S0) of
1182                            {Ce,Eps,S1} when is_list(Ces) ->
1183                                {Ce++Ces,Eps ++ Eps0,S1};
1184                            {_Ce,Eps,S1} ->
1185                                {Ces,Eps ++ Eps0,S1}
1186                        catch
1187                            {bad_binary,Eps,S1} ->
1188                                {bad_binary,Eps ++ Eps0,S1}
1189                        end
1190                end, {[],[],St0}, Es),
1191    case Res of
1192        {bad_binary,Eps,St} ->
1193            throw({bad_binary,Eps,St});
1194        {_,_,_}=Res ->
1195            Res
1196    end.
1197
1198bitstrs([E0|Es0], St0) ->
1199    {E,Eps0,St1} = bitstr(E0, St0),
1200    {Es,Eps1,St2} = bitstrs(Es0, St1),
1201    {E++Es,Eps0++Eps1,St2};
1202bitstrs([], St) ->
1203    {[],[],St}.
1204
1205bitstr({bin_element,Line,{string,_,S},{integer,_,8},_}, St) ->
1206    bitstrs(bin_expand_string(S, Line, 0, 0, []), St);
1207bitstr({bin_element,Line,{string,_,[]},Sz0,Ts}, St0) ->
1208    %% Empty string. We must make sure that the type is correct.
1209    {[#c_bitstr{size=Sz}],Eps0,St1} =
1210        bitstr({bin_element,Line,{char,Line,0},Sz0,Ts}, St0),
1211
1212    %% At this point, the type is either a correct literal or
1213    %% an expression.
1214    case Sz of
1215        #c_literal{val=undefined} ->
1216            %% One of the utf* types. The size is not used.
1217            {[],[],St1};
1218        #c_literal{val=Int} when is_integer(Int), Int >= 0 ->
1219            {[],[],St1};
1220        #c_var{} ->
1221            %% Must add a test to verify that the size expression is
1222            %% an integer >= 0.
1223            Erlang = {atom,Line,erlang},
1224            Test0 = {call,Line,{remote,Line,Erlang,{atom,Line,is_integer}},
1225                     [Sz0]},
1226            Test1 = {call,Line,{remote,Line,Erlang,{atom,Line,'>='}},
1227                     [Sz0,{integer,Line,0}]},
1228            Test2 = {op,Line,'andalso',Test0,Test1},
1229            Fail = {call,Line,{remote,Line,Erlang,{atom,Line,error}},
1230                    [{atom,Line,badarg}]},
1231            Test = {op,Line,'orelse',Test2,Fail},
1232            Match = {match,Line,{var,Line,'_'},Test},
1233            {_,Eps1,St2} = expr(Match, St1),
1234            Eps = Eps0 ++ Eps1,
1235            {[],Eps,St2}
1236    end;
1237bitstr({bin_element,Line,{string,_,S},Sz0,Ts}, St0) ->
1238    {[Bitstr],Eps,St1} = bitstr({bin_element,Line,{char,Line,0},Sz0,Ts}, St0),
1239    Es = [Bitstr#c_bitstr{val=#c_literal{anno=full_anno(Line, St1),val=C}} ||
1240             C <- S],
1241    {Es,Eps,St1};
1242bitstr({bin_element,Line,E0,Size0,[Type,{unit,Unit}|Flags]}, St0) ->
1243    {E1,Eps0,St1} = safe(E0, St0),
1244    {Size1,Eps1,St2} = safe(Size0, St1),
1245    Eps = Eps0 ++ Eps1,
1246    case {Type,E1} of
1247	{_,#c_var{}} -> ok;
1248	{integer,#c_literal{val=I}} when is_integer(I) -> ok;
1249	{utf8,#c_literal{val=I}} when is_integer(I) -> ok;
1250	{utf16,#c_literal{val=I}} when is_integer(I) -> ok;
1251	{utf32,#c_literal{val=I}} when is_integer(I) -> ok;
1252	{float,#c_literal{val=V}} when is_number(V) -> ok;
1253	{binary,#c_literal{val=V}} when is_bitstring(V) -> ok;
1254	{_,_} ->
1255            %% Note that the pre expressions may bind variables that
1256            %% are used later or have side effects.
1257	    throw({bad_binary,Eps,St2})
1258    end,
1259    case Size1 of
1260	#c_var{} -> ok;
1261	#c_literal{val=Sz} when is_integer(Sz), Sz >= 0 -> ok;
1262	#c_literal{val=undefined} -> ok;
1263	#c_literal{val=all} -> ok;
1264	_ -> throw({bad_binary,Eps,St2})
1265    end,
1266    {[#c_bitstr{anno=lineno_anno(Line, St2),
1267                val=E1,size=Size1,
1268                unit=#c_literal{val=Unit},
1269                type=#c_literal{val=Type},
1270                flags=#c_literal{val=Flags}}],
1271     Eps,St2}.
1272
1273bin_element({bin_element,Line,Expr,Size0,Type0}) ->
1274    {Size,Type} = make_bit_type(Line, Size0, Type0),
1275    {bin_element,Line,Expr,Size,Type}.
1276
1277make_bit_type(Line, default, Type0) ->
1278    case erl_bits:set_bit_type(default, Type0) of
1279        {ok,all,Bt} -> {make_all_size(Line),erl_bits:as_list(Bt)};
1280	{ok,undefined,Bt} -> {{atom,Line,undefined},erl_bits:as_list(Bt)};
1281        {ok,Size,Bt} -> {{integer,Line,Size},erl_bits:as_list(Bt)}
1282    end;
1283make_bit_type(_Line, {atom,Anno,all}=Size, Type0) ->
1284    case erl_anno:generated(Anno) of
1285        true ->
1286            %% This `all` was created by the compiler from a binary
1287            %% segment without a size.
1288            {ok,Size,Bt} = erl_bits:set_bit_type(Size, Type0),
1289            {Size,erl_bits:as_list(Bt)};
1290        false ->
1291            %% This `all` was present in the source code. It is not
1292            %% a valid size.
1293            throw(nomatch)
1294    end;
1295make_bit_type(_Line, Size0, Type0) ->            %Integer or 'all'
1296    {ok,Size1,Bt} = erl_bits:set_bit_type(Size0, Type0),
1297    Size = case Size1 of
1298               {char,Anno,CharVal} -> {integer,Anno,CharVal};
1299               _ -> Size1
1300           end,
1301    {Size,erl_bits:as_list(Bt)}.
1302
1303make_all_size(Line) ->
1304    Anno = erl_anno:set_generated(true, Line),
1305    {atom,Anno,all}.
1306
1307%% constant_bin([{bin_element,_,_,_,_}]) -> binary() | error
1308%%  If the binary construction is truly constant (no variables,
1309%%  no native fields), and does not contain fields whose expansion
1310%%  become huge (such as <<0:100000000>>), evaluate and return the binary;
1311%%  otherwise return 'error'.
1312
1313constant_bin(Es) ->
1314    try
1315	constant_bin_1(Es)
1316    catch
1317	error -> error
1318    end.
1319
1320constant_bin_1(Es) ->
1321    verify_suitable_fields(Es),
1322    EmptyBindings = erl_eval:new_bindings(),
1323    EvalFun = fun({string,_,S}, B) -> {value,S,B};
1324		 ({integer,_,I}, B) -> {value,I,B};
1325		 ({char,_,C}, B) -> {value,C,B};
1326		 ({float,_,F}, B) -> {value,F,B};
1327		 ({atom,_,undefined}, B) -> {value,undefined,B}
1328	      end,
1329    try eval_bits:expr_grp(Es, EmptyBindings, EvalFun) of
1330	{value,Bin,EmptyBindings} ->
1331	    Bin
1332    catch error:_ ->
1333	    error
1334    end.
1335
1336%% verify_suitable_fields([{bin_element,_,Sz,Opts}=E|Es]) ->
1337
1338verify_suitable_fields([{bin_element,_,Val,SzTerm,Opts}|Es]) ->
1339    case member(big, Opts) orelse member(little, Opts) of
1340	true -> ok;
1341	false -> throw(error)			%Native endian.
1342    end,
1343    {unit,Unit} = keyfind(unit, 1, Opts),
1344    case {SzTerm,Val} of
1345	{{atom,_,undefined},{string,_,_}} ->
1346	    %% UTF-8/16/32.
1347	    ok;
1348	{{atom,_,undefined},{char,_,_}} ->
1349	    %% UTF-8/16/32.
1350	    ok;
1351	{{atom,_,undefined},{integer,_,_}} ->
1352	    %% UTF-8/16/32.
1353	    ok;
1354	{{integer,_,Sz},_} when Sz*Unit =< 256 ->
1355	    %% Don't be cheap - always accept fields up to this size.
1356	    ok;
1357	{{integer,_,Sz0},{integer,_,Int}} ->
1358	    %% Estimate the number of bits needed to to hold the integer
1359	    %% literal. Check whether the field size is reasonable in
1360	    %% proportion to the number of bits needed.
1361	    Sz = Sz0*Unit,
1362	    case count_bits(Int) of
1363		BitsNeeded when 2*BitsNeeded >= Sz ->
1364		    ok;
1365		_ ->
1366		    %% More than about half of the field size will be
1367		    %% filled out with zeroes - not acceptable.
1368		    throw(error)
1369	    end;
1370	{_,_} ->
1371	    %% Reject anything else. There are either variables,
1372	    %% or a float with a huge size or an embedded binary.
1373	    throw(error)
1374    end,
1375    verify_suitable_fields(Es);
1376verify_suitable_fields([]) -> ok.
1377
1378%% Count the number of bits approximately needed to store Int.
1379%% (We don't need an exact result for this purpose.)
1380
1381count_bits(Int) ->
1382    count_bits_1(abs(Int), 64).
1383
1384count_bits_1(0, Bits) -> Bits;
1385count_bits_1(Int, Bits) -> count_bits_1(Int bsr 64, Bits+64).
1386
1387bin_expand_string(S, Line, Val, Size, Last) when Size >= ?COLLAPSE_MAX_SIZE_SEGMENT ->
1388    Combined = make_combined(Line, Val, Size),
1389    [Combined|bin_expand_string(S, Line, 0, 0, Last)];
1390bin_expand_string([H|T], Line, Val, Size, Last) ->
1391    bin_expand_string(T, Line, (Val bsl 8) bor H, Size+8, Last);
1392bin_expand_string([], Line, Val, Size, Last) ->
1393    [make_combined(Line, Val, Size) | Last].
1394
1395make_combined(Line, Val, Size) ->
1396    {bin_element,Line,{integer,Line,Val},
1397     {integer,Line,Size},
1398     [integer,{unit,1},unsigned,big]}.
1399
1400%% fun_tq(Id, [Clauses], Line, State, NameInfo) -> {Fun,[PreExp],State}.
1401
1402fun_tq(Cs0, L, St0, NameInfo) ->
1403    Arity = clause_arity(hd(Cs0)),
1404    {Cs1,St1} = clauses(Cs0, St0),
1405    {Args,St2} = new_vars(Arity, St1),
1406    {Ps,St3} = new_vars(Arity, St2),		%Need new variables here
1407    Anno = full_anno(L, St3),
1408    {Name,St4} = new_fun_name(St3),
1409    Fc = function_clause(Ps, Anno),
1410    Id = {0,0,Name},
1411    Fun = #ifun{anno=#a{anno=Anno},
1412		id=[{id,Id}],				%We KNOW!
1413		vars=Args,clauses=Cs1,fc=Fc,name=NameInfo},
1414    {Fun,[],St4}.
1415
1416%% lc_tq(Line, Exp, [Qualifier], Mc, State) -> {LetRec,[PreExp],State}.
1417%%  This TQ from Simon PJ pp 127-138.
1418
1419lc_tq(Line, E, [#igen{anno=#a{anno=GA}=GAnno,
1420		      acc_pat=AccPat,acc_guard=AccGuard,
1421                      skip_pat=SkipPat,tail=Tail,tail_pat=TailPat,
1422                      arg={Pre,Arg}}|Qs], Mc, St0) ->
1423    {Name,St1} = new_fun_name("lc", St0),
1424    LA = lineno_anno(Line, St1),
1425    LAnno = #a{anno=LA},
1426    F = #c_var{anno=LA,name={Name,1}},
1427    Nc = #iapply{anno=GAnno,op=F,args=[Tail]},
1428    {[FcVar,Var],St2} = new_vars(2, St1),
1429    Fc = bad_generator([FcVar], FcVar, Arg),
1430    SkipClause = #iclause{anno=#a{anno=[skip_clause,compiler_generated|LA]},
1431                          pats=[SkipPat],guard=[],body=[Nc]},
1432    TailClause = #iclause{anno=LAnno,pats=[TailPat],guard=[],body=[Mc]},
1433    {Cs,St4} = case {AccPat,SkipPat} of
1434                   {nomatch,nomatch} ->
1435                       {[TailClause],St2};
1436                   {nomatch,_} ->
1437                       {[SkipClause,TailClause],St2};
1438                   _ ->
1439                       {Lc,Lps,St3} = lc_tq(Line, E, Qs, Nc, St2),
1440                       AccClause = #iclause{anno=LAnno,pats=[AccPat],guard=AccGuard,
1441                                            body=Lps ++ [Lc]},
1442                       {[AccClause,SkipClause,TailClause],St3}
1443               end,
1444    Fun = #ifun{anno=GAnno,id=[],vars=[Var],clauses=Cs,fc=Fc},
1445    {#iletrec{anno=GAnno#a{anno=[list_comprehension|GA]},defs=[{{Name,1},Fun}],
1446              body=Pre ++ [#iapply{anno=GAnno,op=F,args=[Arg]}]},
1447     [],St4};
1448lc_tq(Line, E, [#ifilter{}=Filter|Qs], Mc, St) ->
1449    filter_tq(Line, E, Filter, Mc, St, Qs, fun lc_tq/5);
1450lc_tq(Line, E0, [], Mc0, St0) ->
1451    {H1,Hps,St1} = safe(E0, St0),
1452    {T1,Tps,St} = force_safe(Mc0, St1),
1453    Anno = lineno_anno(Line, St),
1454    E = ann_c_cons(Anno, H1, T1),
1455    {set_anno(E, [compiler_generated|Anno]),Hps ++ Tps,St}.
1456
1457%% bc_tq(Line, Exp, [Qualifier], More, State) -> {LetRec,[PreExp],State}.
1458%%  This TQ from Gustafsson ERLANG'05.
1459%%  More could be transformed before calling bc_tq.
1460
1461bc_tq(Line, Exp, Qs0, St0) ->
1462    {BinVar,St1} = new_var(St0),
1463    {Qs1,St2} = preprocess_quals(Line, Qs0, St1),
1464    {PrePre,Qs} = case Qs1 of
1465                      [#igen{arg={IgenPre,Arg}}=Igen|Igens] ->
1466                          {IgenPre,[Igen#igen{arg={[],Arg}}|Igens]};
1467                      _ ->
1468                          {[],Qs1}
1469                  end,
1470    {E,BcPre,St} = bc_tq1(Line, Exp, Qs, BinVar, St2),
1471    InitialSize = #c_literal{val=256},
1472    Pre = PrePre ++
1473        [#iset{var=BinVar,
1474               arg=#iprimop{anno=#a{anno=lineno_anno(Line, St)},
1475                            name=#c_literal{val=bs_init_writable},
1476                            args=[InitialSize]}}] ++ BcPre,
1477    {E,Pre,St}.
1478
1479bc_tq1(Line, E, [#igen{anno=GAnno,
1480		       acc_pat=AccPat,acc_guard=AccGuard,
1481                       skip_pat=SkipPat,tail=Tail,tail_pat=TailPat,
1482                       arg={Pre,Arg}}|Qs], Mc, St0) ->
1483    {Name,St1} = new_fun_name("lbc", St0),
1484    LA = lineno_anno(Line, St1),
1485    LAnno = #a{anno=LA},
1486    {[_,AccVar]=Vars,St2} = new_vars(LA, 2, St1),
1487    {[_,_]=FcVars,St3} = new_vars(LA, 2, St2),
1488    {IgnoreVar,St4} = new_var(LA, St3),
1489    F = #c_var{anno=LA,name={Name,2}},
1490    Nc = #iapply{anno=GAnno,op=F,args=[Tail,AccVar]},
1491    Fc = bad_generator(FcVars, hd(FcVars), Arg),
1492    SkipClause = #iclause{anno=#a{anno=[compiler_generated,skip_clause|LA]},
1493                          pats=[SkipPat,IgnoreVar],guard=[],body=[Nc]},
1494    TailClause = #iclause{anno=LAnno,pats=[TailPat,IgnoreVar],guard=[],
1495                          body=[AccVar]},
1496    {Cs,St} = case {AccPat,SkipPat} of
1497                  {nomatch,nomatch} ->
1498                      {[TailClause],St4};
1499                  {nomatch,_} ->
1500                      {[SkipClause,TailClause],St4};
1501                  {_,_} ->
1502                      {Bc,Bps,St5} = bc_tq1(Line, E, Qs, AccVar, St4),
1503                      Body = Bps ++ [#iset{var=AccVar,arg=Bc},Nc],
1504                      AccClause = #iclause{anno=LAnno,pats=[AccPat,IgnoreVar],
1505                                           guard=AccGuard,body=Body},
1506                      {[AccClause,SkipClause,TailClause],St5}
1507              end,
1508    Fun = #ifun{anno=LAnno,id=[],vars=Vars,clauses=Cs,fc=Fc},
1509
1510    %% Inlining would disable the size calculation optimization for
1511    %% bs_init_writable.
1512    {#iletrec{anno=LAnno#a{anno=[list_comprehension,no_inline|LA]},
1513              defs=[{{Name,2},Fun}],
1514              body=Pre ++ [#iapply{anno=LAnno,op=F,args=[Arg,Mc]}]},
1515     [],St};
1516bc_tq1(Line, E, [#ifilter{}=Filter|Qs], Mc, St) ->
1517    filter_tq(Line, E, Filter, Mc, St, Qs, fun bc_tq1/5);
1518bc_tq1(_, {bin,Bl,Elements}, [], AccVar, St0) ->
1519    bc_tq_build(Bl, [], AccVar, Elements, St0);
1520bc_tq1(Line, E0, [], AccVar, St0) ->
1521    BsFlags = [binary,{unit,1}],
1522    BsSize = make_all_size(Line),
1523    {E1,Pre0,St1} = safe(E0, St0),
1524    case E1 of
1525	#c_var{name=VarName} ->
1526	    Var = {var,Line,VarName},
1527	    Els = [{bin_element,Line,Var,BsSize,BsFlags}],
1528	    bc_tq_build(Line, Pre0, AccVar, Els, St1);
1529	#c_literal{val=Val} when is_bitstring(Val) ->
1530	    Bits = bit_size(Val),
1531	    <<Int0:Bits>> = Val,
1532	    Int = {integer,Line,Int0},
1533	    Sz = {integer,Line,Bits},
1534	    Els = [{bin_element,Line,Int,Sz,[integer,{unit,1},big]}],
1535	    bc_tq_build(Line, Pre0, AccVar, Els, St1);
1536	_ ->
1537	    %% Any other safe (cons, tuple, literal) is not a
1538	    %% bitstring. Force the evaluation to fail (and
1539	    %% generate a warning).
1540	    Els = [{bin_element,Line,{atom,Line,bad_value},BsSize,BsFlags}],
1541	    bc_tq_build(Line, Pre0, AccVar, Els, St1)
1542    end.
1543
1544bc_tq_build(Line, Pre0, #c_var{name=AccVar}, Elements0, St0) ->
1545    Elements = [{bin_element,Line,{var,Line,AccVar},make_all_size(Line),
1546		 [binary,{unit,1}]}|Elements0],
1547    {E,Pre,St} = expr({bin,Line,Elements}, St0),
1548    #a{anno=A} = Anno0 = get_anno(E),
1549    Anno = Anno0#a{anno=[compiler_generated,single_use|A]},
1550    {set_anno(E, Anno),Pre0++Pre,St}.
1551
1552
1553%% filter_tq(Line, Expr, Filter, Mc, State, [Qualifier], TqFun) ->
1554%%     {Case,[PreExpr],State}.
1555%%  Transform an intermediate comprehension filter to its intermediate case
1556%%  representation.
1557
1558filter_tq(Line, E, #ifilter{anno=#a{anno=LA}=LAnno,arg={Pre,Arg}},
1559          Mc, St0, Qs, TqFun) ->
1560    %% The filter is an expression, it is compiled to a case of degree 1 with
1561    %% 3 clauses, one accumulating, one skipping and the final one throwing
1562    %% {case_clause,Value} where Value is the result of the filter and is not a
1563    %% boolean.
1564    {Lc,Lps,St1} = TqFun(Line, E, Qs, Mc, St0),
1565    {FailPat,St2} = new_var(St1),
1566    Fc = fail_clause([FailPat], LA,
1567                     c_tuple([#c_literal{val=bad_filter},FailPat])),
1568    {#icase{anno=LAnno#a{anno=[list_comprehension|LA]},args=[Arg],
1569            clauses=[#iclause{anno=LAnno,
1570                              pats=[#c_literal{val=true}],guard=[],
1571                              body=Lps ++ [Lc]},
1572                     #iclause{anno=LAnno#a{anno=[compiler_generated|LA]},
1573                              pats=[#c_literal{val=false}],guard=[],
1574                              body=[Mc]}],
1575            fc=Fc},
1576     Pre,St2};
1577filter_tq(Line, E, #ifilter{anno=#a{anno=LA}=LAnno,arg=Guard},
1578          Mc, St0, Qs, TqFun) when is_list(Guard) ->
1579    %% Otherwise it is a guard, compiled to a case of degree 0 with 2 clauses,
1580    %% the first matches if the guard succeeds and the comprehension continues
1581    %% or the second one is selected and the current element is skipped.
1582    {Lc,Lps,St1} = TqFun(Line, E, Qs, Mc, St0),
1583    {#icase{anno=LAnno#a{anno=[list_comprehension|LA]},args=[],
1584            clauses=[#iclause{anno=LAnno,pats=[],guard=Guard,body=Lps ++ [Lc]}],
1585            fc=#iclause{anno=LAnno#a{anno=[compiler_generated|LA]},
1586                        pats=[],guard=[],body=[Mc]}},
1587     [],St1}.
1588
1589%% preprocess_quals(Line, [Qualifier], State) -> {[Qualifier'],State}.
1590%%  Preprocess a list of Erlang qualifiers into its intermediate representation,
1591%%  represented as a list of #igen{} and #ifilter{} records. We recognise guard
1592%%  tests and try to fold them together and join to a preceding generators, this
1593%%  should give us better and more compact code.
1594
1595preprocess_quals(Line, Qs, St) ->
1596    preprocess_quals(Line, Qs, St, []).
1597
1598preprocess_quals(Line, [Q|Qs0], St0, Acc) ->
1599    case is_generator(Q) of
1600        true ->
1601            {Gs,Qs} = splitwith(fun is_guard_test/1, Qs0),
1602            {Gen,St} = generator(Line, Q, Gs, St0),
1603            preprocess_quals(Line, Qs, St, [Gen|Acc]);
1604        false ->
1605            LAnno = #a{anno=lineno_anno(get_qual_anno(Q), St0)},
1606            case is_guard_test(Q) of
1607                true ->
1608                    %% When a filter is a guard test, its argument in the
1609                    %% #ifilter{} record is a list as returned by
1610                    %% lc_guard_tests/2.
1611                    {Gs,Qs} = splitwith(fun is_guard_test/1, Qs0),
1612                    {Cg,St} = lc_guard_tests([Q|Gs], St0),
1613                    Filter = #ifilter{anno=LAnno,arg=Cg},
1614                    preprocess_quals(Line, Qs, St, [Filter|Acc]);
1615                false ->
1616                    %% Otherwise, it is a pair {Pre,Arg} as in a generator
1617                    %% input.
1618                    {Ce,Pre,St} = novars(Q, St0),
1619                    Filter = #ifilter{anno=LAnno,arg={Pre,Ce}},
1620                    preprocess_quals(Line, Qs0, St, [Filter|Acc])
1621            end
1622    end;
1623preprocess_quals(_, [], St, Acc) ->
1624    {reverse(Acc),St}.
1625
1626is_generator({generate,_,_,_}) -> true;
1627is_generator({b_generate,_,_,_}) -> true;
1628is_generator(_) -> false.
1629
1630%% Retrieve the annotation from an Erlang AST form.
1631%% (Use get_anno/1 to retrieve the annotation from Core Erlang forms).
1632
1633get_qual_anno(Abstract) -> element(2, Abstract).
1634
1635%%
1636%% Generators are abstracted as sextuplets:
1637%%  - acc_pat is the accumulator pattern, e.g. [Pat|Tail] for Pat <- Expr.
1638%%  - acc_guard is the list of guards immediately following the current
1639%%    generator in the qualifier list input.
1640%%  - skip_pat is the skip pattern, e.g. <<X,_:X,Tail/bitstring>> for
1641%%    <<X,1:X>> <= Expr.
1642%%  - tail is the variable used in AccPat and SkipPat bound to the rest of the
1643%%    generator input.
1644%%  - tail_pat is the tail pattern, respectively [] and <<_/bitstring>> for list
1645%%    and bit string generators.
1646%%  - arg is a pair {Pre,Arg} where Pre is the list of expressions to be
1647%%    inserted before the comprehension function and Arg is the expression
1648%%    that it should be passed.
1649%%
1650
1651%% generator(Line, Generator, Guard, State) -> {Generator',State}.
1652%%  Transform a given generator into its #igen{} representation.
1653
1654generator(Line, {generate,Lg,P0,E}, Gs, St0) ->
1655    LA = lineno_anno(Line, St0),
1656    GA = lineno_anno(Lg, St0),
1657    {Head,St1} = list_gen_pattern(P0, Line, St0),
1658    {[Tail,Skip],St2} = new_vars(2, St1),
1659    {Cg,St3} = lc_guard_tests(Gs, St2),
1660    {AccPat,SkipPat} = case Head of
1661                           #c_var{} ->
1662                               %% If the generator pattern is a variable, the
1663                               %% pattern from the accumulator clause can be
1664                               %% reused in the skip one. lc_tq and bc_tq1 takes
1665                               %% care of dismissing the latter in that case.
1666                               Cons = ann_c_cons(LA, Head, Tail),
1667                               {Cons,Cons};
1668                           nomatch ->
1669                               %% If it never matches, there is no need for
1670                               %% an accumulator clause.
1671                               {nomatch,ann_c_cons(LA, Skip, Tail)};
1672                           _ ->
1673                               {ann_c_cons(LA, Head, Tail),
1674                                ann_c_cons(LA, Skip, Tail)}
1675                       end,
1676    {Ce,Pre,St4} = safe(E, St3),
1677    Gen = #igen{anno=#a{anno=GA},
1678		acc_pat=AccPat,acc_guard=Cg,skip_pat=SkipPat,
1679                tail=Tail,tail_pat=#c_literal{anno=LA,val=[]},arg={Pre,Ce}},
1680    {Gen,St4};
1681generator(Line, {b_generate,Lg,P,E}, Gs, St0) ->
1682    LA = lineno_anno(Line, St0),
1683    GA = lineno_anno(Lg, St0),
1684    try pattern(P, St0) of
1685        {#ibinary{segments=Segs}=Cp,St1} ->
1686            %% The function append_tail_segment/2 keeps variable
1687            %% patterns as-is, making it possible to have the same
1688            %% skip clause removal as with list generators.
1689            {AccSegs,Tail,TailSeg,St2} = append_tail_segment(Segs, St1),
1690            AccPat = Cp#ibinary{segments=AccSegs},
1691            {Cg,St3} = lc_guard_tests(Gs, St2),
1692            {SkipSegs,St4} = skip_segments(AccSegs, St3, []),
1693            SkipPat = Cp#ibinary{segments=SkipSegs},
1694            {Ce,Pre,St5} = safe(E, St4),
1695            Gen = #igen{anno=#a{anno=GA},acc_pat=AccPat,acc_guard=Cg,
1696                        skip_pat=SkipPat,tail=Tail,
1697                        tail_pat=#ibinary{anno=#a{anno=LA},segments=[TailSeg]},
1698                        arg={Pre,Ce}},
1699            {Gen,St5}
1700    catch
1701        throw:nomatch ->
1702            {Ce,Pre,St1} = safe(E, St0),
1703            Gen = #igen{anno=#a{anno=GA},acc_pat=nomatch,acc_guard=[],
1704                        skip_pat=nomatch,
1705                        tail_pat=#c_var{name='_'},
1706                        arg={Pre,Ce}},
1707            {Gen,St1}
1708    end.
1709
1710append_tail_segment(Segs, St0) ->
1711    {Var,St} = new_var(St0),
1712    Tail = #ibitstr{val=Var,size=[#c_literal{val=all}],
1713                    unit=#c_literal{val=1},
1714                    type=#c_literal{val=binary},
1715                    flags=#c_literal{val=[unsigned,big]}},
1716    {Segs++[Tail],Var,Tail,St}.
1717
1718%% skip_segments(Segments, St0, Acc) -> {SkipSegments,St}.
1719%%  Generate the segments for a binary pattern that can be used
1720%%  in the skip clause that will continue the iteration when
1721%%  the accumulator pattern didn't match.
1722
1723skip_segments([#ibitstr{val=#c_var{}}=B|Rest], St, Acc) ->
1724    %% We must keep the names of existing variables to ensure that
1725    %% patterns such as <<Size,X:Size>> will work.
1726    skip_segments(Rest, St, [B|Acc]);
1727skip_segments([B|Rest], St0, Acc) ->
1728    %% Replace literal or expression with a variable (whose value will
1729    %% be ignored).
1730    {Var,St1} = new_var(St0),
1731    skip_segments(Rest, St1, [B#ibitstr{val=Var}|Acc]);
1732skip_segments([], St, Acc) ->
1733    {reverse(Acc),St}.
1734
1735lc_guard_tests([], St) -> {[],St};
1736lc_guard_tests(Gs0, St0) ->
1737    Gs1 = guard_tests(Gs0),
1738    {Gs,St} = gexpr_top(Gs1, St0#core{in_guard=true}),
1739    {Gs,St#core{in_guard=false}}.
1740
1741list_gen_pattern(P0, Line, St) ->
1742    try
1743	pattern(P0, St)
1744    catch
1745	nomatch -> {nomatch,add_warning(Line, {nomatch,pattern}, St)}
1746    end.
1747
1748%% is_guard_test(Expression) -> true | false.
1749%%  Test if a general expression is a guard test.
1750%%
1751%%  Note that a local function overrides a BIF with the same name.
1752%%  For example, if there is a local function named is_list/1,
1753%%  any unqualified call to is_list/1 will be to the local function.
1754%%  The guard function must be explicitly called as erlang:is_list/1.
1755
1756is_guard_test(E) ->
1757    %% erl_expand_records has added a module prefix to any call
1758    %% to a BIF or imported function. Any call without a module
1759    %% prefix that remains must therefore be to a local function.
1760    IsOverridden = fun({_,_}) -> true end,
1761    erl_lint:is_guard_test(E, [], IsOverridden).
1762
1763%% novars(Expr, State) -> {Novars,[PreExpr],State}.
1764%%  Generate a novars expression, basically a call or a safe.  At this
1765%%  level we do not need to do a deep check.
1766
1767novars(E0, St0) ->
1768    {E1,Eps,St1} = expr(E0, St0),
1769    {Se,Sps,St2} = force_novars(E1, St1),
1770    {Se,Eps ++ Sps,St2}.
1771
1772force_novars(#iapply{}=App, St) -> {App,[],St};
1773force_novars(#icall{}=Call, St) -> {Call,[],St};
1774force_novars(#ifun{}=Fun, St) -> {Fun,[],St};	%These are novars too
1775force_novars(#ibinary{}=Bin, St) -> {Bin,[],St};
1776force_novars(#c_map{}=Bin, St) -> {Bin,[],St};
1777force_novars(Ce, St) ->
1778    force_safe(Ce, St).
1779
1780%% safe(Expr, State) -> {Safe,[PreExpr],State}.
1781%%  Generate an internal safe expression.  These are simples without
1782%%  binaries which can fail.  At this level we do not need to do a
1783%%  deep check.  Must do special things with matches here.
1784
1785safe(E0, St0) ->
1786    {E1,Eps,St1} = expr(E0, St0),
1787    {Se,Sps,St2} = force_safe(E1, St1),
1788    {Se,Eps ++ Sps,St2}.
1789
1790safe_list(Es, St) ->
1791    foldr(fun (E, {Ces,Esp,St0}) ->
1792		  {Ce,Ep,St1} = safe(E, St0),
1793		  {[Ce|Ces],Ep ++ Esp,St1}
1794	  end, {[],[],St}, Es).
1795
1796force_safe(#imatch{pat=P,arg=E}=Imatch, St0) ->
1797    {Le,Lps0,St1} = force_safe(E, St0),
1798    Lps = Lps0 ++ [Imatch#imatch{arg=Le}],
1799
1800    %% Make sure we don't duplicate the expression E. sys_core_fold
1801    %% will usually optimize away the duplicate expression, but may
1802    %% generate a warning while doing so.
1803    case Le of
1804	#c_var{} ->
1805	    %% Le is a variable.
1806	    %% Thus: P = Le, Le.  (Traditional, since the V2 compiler.)
1807	    {Le,Lps,St1};
1808	_ ->
1809	    %% Le is not a variable.
1810	    %% Thus: NewVar = P = Le, NewVar.   (New for R12B-1.)
1811	    %%
1812	    %% Note: It is tempting to rewrite V = Le to V = Le, V,
1813	    %% but that will generate extra warnings in sys_core_fold
1814	    %% for this expression:
1815	    %%
1816	    %%    [{X,Y} || {X,_} <- E, (Y = X) =:= (Y = 1 + 1)]
1817	    %%
1818	    %% (There will be a 'case Y =:= Y of...' which will generate
1819	    %% a warning.)
1820	    {V,St2} = new_var(St1),
1821	    {V,Lps0 ++ [Imatch#imatch{pat=#c_alias{var=V,pat=P},arg=Le}],St2}
1822    end;
1823force_safe(Ce, St0) ->
1824    case is_safe(Ce) of
1825	true -> {Ce,[],St0};
1826	false ->
1827	    {V,St1} = new_var(get_lineno_anno(Ce), St0),
1828	    {V,[#iset{var=V,arg=Ce}],St1}
1829    end.
1830
1831is_safe(#c_cons{}) -> true;
1832is_safe(#c_tuple{}) -> true;
1833is_safe(#c_var{name={_,_}}) -> false;           %Fun. Not safe.
1834is_safe(#c_var{name=_}) -> true;                %Ordinary variable.
1835is_safe(#c_literal{}) -> true;
1836is_safe(_) -> false.
1837
1838%% fold_match(MatchExpr, Pat) -> {MatchPat,Expr}.
1839%%  Fold nested matches into one match with aliased patterns.
1840
1841fold_match({match,L,P0,E0}, P) ->
1842    {P1,E1} = fold_match(E0, P),
1843    {{match,L,P0,P1},E1};
1844fold_match(E, P) -> {P,E}.
1845
1846%% pattern(Pattern, State) -> {CorePat,[PreExp],State}.
1847%%  Transform a pattern by removing line numbers.  We also normalise
1848%%  aliases in patterns to standard form: {alias,Pat,[Var]}.
1849
1850pattern({var,L,V}, St) -> {#c_var{anno=lineno_anno(L, St),name=V},St};
1851pattern({char,L,C}, St) -> {#c_literal{anno=lineno_anno(L, St),val=C},St};
1852pattern({integer,L,I}, St) -> {#c_literal{anno=lineno_anno(L, St),val=I},St};
1853pattern({float,L,F}, St) -> {#c_literal{anno=lineno_anno(L, St),val=F},St};
1854pattern({atom,L,A}, St) -> {#c_literal{anno=lineno_anno(L, St),val=A},St};
1855pattern({string,L,S}, St) -> {#c_literal{anno=lineno_anno(L, St),val=S},St};
1856pattern({nil,L}, St) -> {#c_literal{anno=lineno_anno(L, St),val=[]},St};
1857pattern({cons,L,H,T}, St) ->
1858    {Ph,St1} = pattern(H, St),
1859    {Pt,St2} = pattern(T, St1),
1860    {annotate_cons(lineno_anno(L, St), Ph, Pt, St2),St2};
1861pattern({tuple,L,Ps}, St) ->
1862    {Ps1,St1} = pattern_list(Ps, St),
1863    {annotate_tuple(record_anno(L, St), Ps1, St),St1};
1864pattern({map,L,Pairs}, St0) ->
1865    {Ps,St1} = pattern_map_pairs(Pairs, St0),
1866    {#imap{anno=#a{anno=lineno_anno(L, St1)},es=Ps},St1};
1867pattern({bin,L,Ps}, St0) ->
1868    {Segments,St} = pat_bin(Ps, St0),
1869    {#ibinary{anno=#a{anno=lineno_anno(L, St)},segments=Segments},St};
1870pattern({match,_,P1,P2}, St) ->
1871    {Cp1,St1} = pattern(P1, St),
1872    {Cp2,St2} = pattern(P2, St1),
1873    {pat_alias(Cp1, Cp2),St2};
1874%% Evaluate compile-time expressions.
1875pattern({op,_,'++',{nil,_},R}, St) ->
1876    pattern(R, St);
1877pattern({op,_,'++',{cons,Li,H,T},R}, St) ->
1878    pattern({cons,Li,H,{op,Li,'++',T,R}}, St);
1879pattern({op,_,'++',{string,Li,L},R}, St) ->
1880    pattern(string_to_conses(Li, L, R), St);
1881pattern({op,_Line,_Op,_A}=Op, St) ->
1882    pattern(erl_eval:partial_eval(Op), St);
1883pattern({op,_Line,_Op,_L,_R}=Op, St) ->
1884    pattern(erl_eval:partial_eval(Op), St).
1885
1886%% pattern_map_pairs([MapFieldExact],State) -> [#c_map_pairs{}]
1887pattern_map_pairs(Ps, St0) ->
1888    {CMapPairs,St1} = mapfoldl(fun pattern_map_pair/2, St0, Ps),
1889    {pat_alias_map_pairs(CMapPairs),St1}.
1890
1891pattern_map_pair({map_field_exact,L,K,V}, St0) ->
1892    Ck0 = erl_eval:partial_eval(K),
1893    {Ck,St1} = exprs([Ck0], St0),
1894    {Cv,St2} = pattern(V, St1),
1895    {#imappair{anno=#a{anno=lineno_anno(L, St2)},
1896               op=#c_literal{val=exact},
1897               key=Ck,
1898               val=Cv},St2}.
1899
1900pat_alias_map_pairs(Ps) ->
1901    D0 = foldl(fun(#imappair{key=K0}=Pair, A) ->
1902                       K = map_sort_key(K0, A),
1903                       case A of
1904                           #{K:=Aliases} ->
1905                               A#{K:=[Pair|Aliases]};
1906                           #{} ->
1907                               A#{K=>[Pair]}
1908                       end
1909               end, #{}, Ps),
1910    %% We must sort to ensure that the order remains consistent
1911    %% between compilations.
1912    D = sort(maps:to_list(D0)),
1913    pat_alias_map_pairs_1(D).
1914
1915pat_alias_map_pairs_1([{_,[#imappair{val=V0}=Pair|Vs]}|T]) ->
1916    V = foldl(fun(#imappair{val=V}, Pat) ->
1917		      pat_alias(V, Pat)
1918	      end, V0, Vs),
1919    [Pair#imappair{val=V}|pat_alias_map_pairs_1(T)];
1920pat_alias_map_pairs_1([]) -> [].
1921
1922map_sort_key(Key, KeyMap) ->
1923    case Key of
1924        [#c_literal{}=Lit] ->
1925            {atomic,cerl:set_ann(Lit, [])};
1926        [#c_var{}=Var] ->
1927            {atomic,cerl:set_ann(Var, [])};
1928        _ ->
1929            {expr,map_size(KeyMap)}
1930    end.
1931
1932%% pat_bin([BinElement], State) -> [BinSeg].
1933
1934pat_bin(Ps0, St) ->
1935    Ps = pat_bin_expand_strings(Ps0),
1936    pat_segments(Ps, St).
1937
1938pat_bin_expand_strings(Es0) ->
1939    foldr(fun ({bin_element,Line,{string,_,[_|_]=S},default,default}, Es1) ->
1940                  bin_expand_string(S, Line, 0, 0, Es1);
1941              ({bin_element,Line,{string,_,S},Sz,Ts}, Es1) ->
1942                  foldr(
1943                    fun (C, Es) ->
1944                            [{bin_element,Line,{char,Line,C},Sz,Ts}|Es]
1945                    end, Es1, S);
1946              (E, Es) ->
1947                  [E|Es]
1948	  end, [], Es0).
1949
1950pat_segments([P0|Ps0], St0) ->
1951    {P,St1} = pat_segment(P0, St0),
1952    {Ps,St2} = pat_segments(Ps0, St1),
1953    {[P|Ps],St2};
1954pat_segments([], St) -> {[],St}.
1955
1956pat_segment({bin_element,L,Val,Size0,Type0}, St) ->
1957    {Size1,Type1} = make_bit_type(L, Size0, Type0),
1958    [Type,{unit,Unit}|Flags] = Type1,
1959    Anno = lineno_anno(L, St),
1960    {Pval0,St1} = pattern(Val, St),
1961    Pval = coerce_to_float(Pval0, Type0),
1962    Size = erl_eval:partial_eval(Size1),
1963    {Psize,St2} = exprs([Size], St1),
1964    {#ibitstr{anno=#a{anno=Anno},
1965              val=Pval,size=Psize,
1966              unit=#c_literal{val=Unit},
1967              type=#c_literal{val=Type},
1968              flags=#c_literal{val=Flags}},St2}.
1969
1970coerce_to_float(#c_literal{val=Int}=E, [float|_]) when is_integer(Int) ->
1971    try
1972	E#c_literal{val=float(Int)}
1973    catch
1974        error:badarg -> E
1975    end;
1976coerce_to_float(E, _) -> E.
1977
1978%% pat_alias(CorePat, CorePat) -> AliasPat.
1979%%  Normalise aliases.  Trap bad aliases by throwing 'nomatch'.
1980
1981pat_alias(#c_var{name=V1}=P, #c_var{name=V1}) -> P;
1982pat_alias(#c_var{name=V1}=Var,
1983	  #c_alias{var=#c_var{name=V2},pat=Pat}=Alias) ->
1984    if
1985	V1 =:= V2 ->
1986	    Alias;
1987	true ->
1988	    Alias#c_alias{pat=pat_alias(Var, Pat)}
1989    end;
1990pat_alias(#c_var{}=P1, P2) -> #c_alias{var=P1,pat=P2};
1991
1992pat_alias(#c_alias{var=#c_var{name=V1}}=Alias, #c_var{name=V1}) ->
1993    Alias;
1994pat_alias(#c_alias{var=#c_var{name=V1}=Var1,pat=P1},
1995	  #c_alias{var=#c_var{name=V2}=Var2,pat=P2}) ->
1996    Pat = pat_alias(P1, P2),
1997    if
1998	V1 =:= V2 ->
1999	    #c_alias{var=Var1,pat=Pat};
2000	true ->
2001	    pat_alias(Var1, pat_alias(Var2, Pat))
2002    end;
2003pat_alias(#c_alias{var=#c_var{}=Var,pat=P1}, P2) ->
2004    #c_alias{var=Var,pat=pat_alias(P1, P2)};
2005
2006pat_alias(#imap{es=Es1}=M, #imap{es=Es2}) ->
2007    M#imap{es=pat_alias_map_pairs(Es1 ++ Es2)};
2008
2009pat_alias(P1, #c_var{}=Var) ->
2010    #c_alias{var=Var,pat=P1};
2011pat_alias(P1, #c_alias{pat=P2}=Alias) ->
2012    Alias#c_alias{pat=pat_alias(P1, P2)};
2013
2014pat_alias(P1, P2) ->
2015    %% Aliases between binaries are not allowed, so the only
2016    %% legal patterns that remain are data patterns.
2017    case cerl:is_data(P1) andalso cerl:is_data(P2) of
2018	false -> throw(nomatch);
2019	true -> ok
2020    end,
2021    Type = cerl:data_type(P1),
2022    case cerl:data_type(P2) of
2023	Type -> ok;
2024	_ -> throw(nomatch)
2025    end,
2026    Es1 = cerl:data_es(P1),
2027    Es2 = cerl:data_es(P2),
2028    Es = pat_alias_list(Es1, Es2),
2029    cerl:make_data(Type, Es).
2030
2031%% pat_alias_list([A1], [A2]) -> [A].
2032
2033pat_alias_list([A1|A1s], [A2|A2s]) ->
2034    [pat_alias(A1, A2)|pat_alias_list(A1s, A2s)];
2035pat_alias_list([], []) -> [];
2036pat_alias_list(_, _) -> throw(nomatch).
2037
2038%% pattern_list([P], State) -> {[P],Exprs,St}
2039
2040pattern_list([P0|Ps0], St0) ->
2041    {P1,St1} = pattern(P0, St0),
2042    {Ps1,St2} = pattern_list(Ps0, St1),
2043    {[P1|Ps1],St2};
2044pattern_list([], St) ->
2045    {[],St}.
2046
2047string_to_conses(Line, Cs, Tail) ->
2048    foldr(fun (C, T) -> {cons,Line,{char,Line,C},T} end, Tail, Cs).
2049
2050%% make_vars([Name]) -> [{Var,Name}].
2051
2052make_vars(Vs) -> [ #c_var{name=V} || V <- Vs ].
2053
2054new_fun_name(#core{function={F,A},fcount=I}=St) ->
2055    Name = "-" ++ atom_to_list(F) ++ "/" ++ integer_to_list(A)
2056        ++ "-fun-" ++ integer_to_list(I) ++ "-",
2057    {list_to_atom(Name),St#core{fcount=I+1}}.
2058
2059%% new_fun_name(Type, State) -> {FunName,State}.
2060
2061new_fun_name(Type, #core{fcount=C}=St) ->
2062    {list_to_atom(Type ++ "$^" ++ integer_to_list(C)),St#core{fcount=C+1}}.
2063
2064%% new_var_name(State) -> {VarName,State}.
2065
2066new_var_name(#core{vcount=C}=St) ->
2067    {C,St#core{vcount=C + 1}}.
2068
2069%% new_var(State) -> {{var,Name},State}.
2070%% new_var(LineAnno, State) -> {{var,Name},State}.
2071
2072new_var(St) ->
2073    new_var([], St).
2074
2075new_var(Anno, St0) when is_list(Anno) ->
2076    {New,St} = new_var_name(St0),
2077    {#c_var{anno=Anno,name=New},St}.
2078
2079%% new_vars(Count, State) -> {[Var],State}.
2080%% new_vars(Anno, Count, State) -> {[Var],State}.
2081%%  Make Count new variables.
2082
2083new_vars(N, St) -> new_vars_1(N, [], St, []).
2084new_vars(Anno, N, St) -> new_vars_1(N, Anno, St, []).
2085
2086new_vars_1(N, Anno, St0, Vs) when N > 0 ->
2087    {V,St1} = new_var(Anno, St0),
2088    new_vars_1(N-1, Anno, St1, [V|Vs]);
2089new_vars_1(0, _, St, Vs) -> {Vs,St}.
2090
2091bad_generator(Ps, Generator, Arg) ->
2092    Anno = get_anno(Arg),
2093    Tuple = ann_c_tuple(Anno, [#c_literal{val=bad_generator},Generator]),
2094    fail_clause(Ps, Anno, Tuple).
2095
2096function_clause(Ps, LineAnno) ->
2097    fail_clause(Ps, LineAnno,
2098		ann_c_tuple(LineAnno, [#c_literal{val=function_clause}|Ps])).
2099
2100fail_clause(Pats, Anno, Arg) ->
2101    #iclause{anno=#a{anno=[compiler_generated]},
2102	     pats=Pats,guard=[],
2103	     body=[#iprimop{anno=#a{anno=Anno},name=#c_literal{val=match_fail},
2104			    args=[Arg]}]}.
2105
2106%% Optimization for Dialyzer.
2107right_assoc({op,L1,Op,{op,L2,Op,E1,E2},E3}, Op) ->
2108    right_assoc({op,L2,Op,E1,{op,L1,Op,E2,E3}}, Op);
2109right_assoc(E, _Op) -> E.
2110
2111annotate_tuple(A, Es, #core{dialyzer=Dialyzer}) ->
2112    case Dialyzer of
2113        true ->
2114            %% Do not coalesce constant tuple elements. A Hack.
2115            Node = cerl:ann_c_tuple(A, [cerl:c_var(any)]),
2116            cerl:update_c_tuple_skel(Node, Es);
2117        false ->
2118            ann_c_tuple(A, Es)
2119    end.
2120
2121annotate_cons(A, H, T, #core{dialyzer=Dialyzer}) ->
2122    case Dialyzer of
2123        true ->
2124            %% Do not coalesce constant conses. A Hack.
2125            Node= cerl:ann_c_cons(A, cerl:c_var(any), cerl:c_var(any)),
2126            cerl:update_c_cons_skel(Node, H, T);
2127        false ->
2128            ann_c_cons(A, H, T)
2129    end.
2130
2131ubody(B, St) -> uexpr(B, [], St).
2132
2133%% ufun_clauses([Lclause], [KnownVar], State) -> {[Lclause],State}.
2134
2135ufun_clauses(Lcs, Ks, St0) ->
2136    mapfoldl(fun (Lc, St) -> ufun_clause(Lc, Ks, St) end, St0, Lcs).
2137
2138%% ufun_clause(Lclause, [KnownVar], State) -> {Lclause,State}.
2139
2140ufun_clause(Cl0, Ks, St0) ->
2141    %% Since variables in fun heads shadow previous variables
2142    %% with the same name, we used to send an empty list as the
2143    %% known variables when doing liveness analysis of the patterns
2144    %% (in the upattern functions).
2145    %%
2146    %% With the introduction of expressions in size for binary
2147    %% segments and in map keys, all known variables must be
2148    %% available when analysing those expressions, or some variables
2149    %% might not be seen as used if, for example, the expression includes
2150    %% a case construct.
2151    %%
2152    %% Therefore, we will send in the complete list of known variables
2153    %% when doing liveness analysis of patterns. This is
2154    %% safe because any shadowing variables in a fun head has
2155    %% been renamed.
2156
2157    {Cl1,Pvs,Used,_,St1} = do_uclause(Cl0, Ks, St0),
2158    A0 = get_anno(Cl1),
2159    A = A0#a{us=subtract(Used, Pvs),ns=[]},
2160    {Cl1#iclause{anno=A},St1}.
2161
2162%% uclauses([Lclause], [KnownVar], State) -> {[Lclause],State}.
2163
2164uclauses(Lcs, Ks, St0) ->
2165    mapfoldl(fun (Lc, St) -> uclause(Lc, Ks, St) end, St0, Lcs).
2166
2167%% uclause(Lclause, [KnownVar], State) -> {Lclause,State}.
2168
2169uclause(Cl0, Ks, St0) ->
2170    {Cl1,_Pvs,Used,New,St1} = do_uclause(Cl0, Ks, St0),
2171    A0 = get_anno(Cl1),
2172    A = A0#a{us=Used,ns=New},
2173    {Cl1#iclause{anno=A},St1}.
2174
2175do_uclause(#iclause{anno=A0,pats=Ps0,guard=G0,body=B0}, Ks0, St0) ->
2176    {Ps1,Pg0,Pvs,Pus,St1} = upattern_list(Ps0, Ks0, St0),
2177    Anno = A0#a.anno,
2178    {Pg,A} = case member(skip_clause, Anno) of
2179                 true ->
2180                     %% This is the skip clause for a binary generator.
2181                     %% To ensure that it will properly skip the nonmatching
2182                     %% patterns in generators such as:
2183                     %%
2184                     %%   <<V,V>> <= Gen
2185                     %%
2186                     %% we must remove any generated pre guard.
2187                     {[],A0#a{anno=Anno -- [skip_clause]}};
2188                 false ->
2189                     {Pg0,A0}
2190             end,
2191    Pu = union(Pus, intersection(Pvs, Ks0)),
2192    Pn = subtract(Pvs, Pu),
2193    Ks1 = union(Pn, Ks0),
2194    {G1,St2} = uguard(Pg, G0, Ks1, St1),
2195    Gu = used_in_any(G1),
2196    Gn = new_in_any(G1),
2197    Ks2 = union(Gn, Ks1),
2198    {B1,St3} = uexprs(B0, Ks2, St2),
2199    Used = intersection(union([Pu,Gu,used_in_any(B1)]), Ks0),
2200    New = union([Pn,Gn,new_in_any(B1)]),
2201    {#iclause{anno=A,pats=Ps1,guard=G1,body=B1},Pvs,Used,New,St3}.
2202
2203%% uguard([Test], [Kexpr], [KnownVar], State) -> {[Kexpr],State}.
2204%%  Build a guard expression list by folding in the equality tests.
2205
2206uguard([], [], _, St) -> {[],St};
2207uguard(Pg, [], Ks, St) ->
2208    %% No guard, so fold together equality tests.
2209    uguard(droplast(Pg), [last(Pg)], Ks, St);
2210uguard(Pg, Gs0, Ks, St0) ->
2211    %% Gs0 must contain at least one element here.
2212    {Gs3,St5} = foldr(fun (T, {Gs1,St1}) ->
2213			      {L,St2} = new_var(St1),
2214			      {R,St3} = new_var(St2),
2215			      {[#iset{var=L,arg=T}] ++ droplast(Gs1) ++
2216			       [#iset{var=R,arg=last(Gs1)},
2217				#icall{anno=#a{}, %Must have an #a{}
2218				       module=#c_literal{val=erlang},
2219				       name=#c_literal{val='and'},
2220				       args=[L,R]}],
2221			       St3}
2222		      end, {Gs0,St0}, Pg),
2223    %%ok = io:fwrite("core ~w: ~p~n", [?LINE,Gs3]),
2224    uexprs(Gs3, Ks, St5).
2225
2226%% uexprs([Kexpr], [KnownVar], State) -> {[Kexpr],State}.
2227
2228uexprs([#imatch{anno=A,pat=P0,arg=Arg,fc=Fc}|Les], Ks, St0) ->
2229    case upat_is_new_var(P0, Ks) of
2230	true ->
2231	    %% Assignment to a new variable.
2232	    uexprs([#iset{var=P0,arg=Arg}|Les], Ks, St0);
2233	false when Les =:= [] ->
2234	    %% Need to explicitly return match "value", make
2235	    %% safe for efficiency.
2236	    {La0,Lps,St1} = force_safe(Arg, St0),
2237	    La = mark_compiler_generated(La0),
2238	    Mc = #iclause{anno=A,pats=[P0],guard=[],body=[La]},
2239	    uexprs(Lps ++ [#icase{anno=A,
2240				  args=[La0],clauses=[Mc],fc=Fc}], Ks, St1);
2241	false ->
2242	    Mc = #iclause{anno=A,pats=[P0],guard=[],body=Les},
2243	    uexprs([#icase{anno=A,args=[Arg],
2244			   clauses=[Mc],fc=Fc}], Ks, St0)
2245    end;
2246uexprs([Le0|Les0], Ks, St0) ->
2247    {Le1,St1} = uexpr(Le0, Ks, St0),
2248    {Les1,St2} = uexprs(Les0, union((get_anno(Le1))#a.ns, Ks), St1),
2249    {[Le1|Les1],St2};
2250uexprs([], _, St) -> {[],St}.
2251
2252%% upat_is_new_var(Pattern, [KnownVar]) -> true|false.
2253%%  Test whether the pattern is a single, previously unknown
2254%%  variable.
2255
2256upat_is_new_var(#c_var{name=V}, Ks) ->
2257    not is_element(V, Ks);
2258upat_is_new_var(_, _) ->
2259    false.
2260
2261%% Mark a "safe" as compiler-generated.
2262mark_compiler_generated(#c_cons{anno=A,hd=H,tl=T}) ->
2263    ann_c_cons([compiler_generated|A], mark_compiler_generated(H),
2264	       mark_compiler_generated(T));
2265mark_compiler_generated(#c_tuple{anno=A,es=Es0}) ->
2266    Es = [mark_compiler_generated(E) || E <- Es0],
2267    ann_c_tuple([compiler_generated|A], Es);
2268mark_compiler_generated(#c_var{anno=A}=Var) ->
2269    Var#c_var{anno=[compiler_generated|A]};
2270mark_compiler_generated(#c_literal{anno=A}=Lit) ->
2271    Lit#c_literal{anno=[compiler_generated|A]}.
2272
2273uexpr(#iset{anno=A,var=V,arg=A0}, Ks, St0) ->
2274    {A1,St1} = uexpr(A0, Ks, St0),
2275    {#iset{anno=A#a{us=del_element(V#c_var.name, (get_anno(A1))#a.us),
2276		    ns=add_element(V#c_var.name, (get_anno(A1))#a.ns)},
2277	   var=V,arg=A1},St1};
2278%% imatch done in uexprs.
2279uexpr(#iletrec{anno=A,defs=Fs0,body=B0}, Ks, St0) ->
2280    %%ok = io:fwrite("~w: ~p~n", [?LINE,{Fs0,B0}]),
2281    {Fs1,St1} = mapfoldl(fun ({Name,F0}, S0) ->
2282				 {F1,S1} = uexpr(F0, Ks, S0),
2283				 {{Name,F1},S1}
2284			 end, St0, Fs0),
2285    {B1,St2} = uexprs(B0, Ks, St1),
2286    Used = used_in_any(map(fun ({_,F}) -> F end, Fs1) ++ B1),
2287    {#iletrec{anno=A#a{us=Used,ns=[]},defs=Fs1,body=B1},St2};
2288uexpr(#icase{anno=#a{anno=Anno}=A,args=As0,clauses=Cs0,fc=Fc0}, Ks, St0) ->
2289    %% As0 will never generate new variables.
2290    {As1,St1} = uexpr_list(As0, Ks, St0),
2291    {Cs1,St2} = uclauses(Cs0, Ks, St1),
2292    {Fc1,St3} = uclause(Fc0, Ks, St2),
2293    Used = union(used_in_any(As1), used_in_any(Cs1)),
2294    New = case member(list_comprehension, Anno) of
2295              true -> [];
2296              false -> new_in_all(Cs1)
2297          end,
2298    {#icase{anno=A#a{us=Used,ns=New},args=As1,clauses=Cs1,fc=Fc1},St3};
2299uexpr(#ifun{anno=A0,id=Id,vars=As,clauses=Cs0,fc=Fc0,name=Name}=Fun0, Ks0, St0) ->
2300    {Fun1,St2} = case Ks0 of
2301                     [] ->
2302                         {Fun0,St0};
2303                     [_|_] ->
2304                         {Cs1,St1} = rename_shadowing_clauses(Cs0, Ks0, St0),
2305                         {Fun0#ifun{clauses=Cs1},St1}
2306                 end,
2307    #ifun{clauses=Cs2} = Fun1,
2308    Avs = lit_list_vars(As),
2309    Ks1 = case Name of
2310              unnamed -> Ks0;
2311              {named,FName} -> union(subtract([FName], Avs), Ks0)
2312          end,
2313    Ks2 = union(Avs, Ks1),
2314    {Cs3,St3} = ufun_clauses(Cs2, Ks2, St2),
2315    {Fc1,St4} = ufun_clause(Fc0, Ks2, St3),
2316    Used = subtract(intersection(used_in_any(Cs3), Ks1), Avs),
2317    A1 = A0#a{us=Used,ns=[]},
2318    {#ifun{anno=A1,id=Id,vars=As,clauses=Cs3,fc=Fc1,name=Name},St4};
2319uexpr(#iapply{anno=A,op=Op,args=As}, _, St) ->
2320    Used = union(lit_vars(Op), lit_list_vars(As)),
2321    {#iapply{anno=A#a{us=Used},op=Op,args=As},St};
2322uexpr(#iprimop{anno=A,name=Name,args=As}, _, St) ->
2323    Used = lit_list_vars(As),
2324    {#iprimop{anno=A#a{us=Used},name=Name,args=As},St};
2325uexpr(#icall{anno=A,module=Mod,name=Name,args=As}, _, St) ->
2326    Used = union([lit_vars(Mod),lit_vars(Name),lit_list_vars(As)]),
2327    {#icall{anno=A#a{us=Used},module=Mod,name=Name,args=As},St};
2328uexpr(#itry{anno=A,args=As0,vars=Vs,body=Bs0,evars=Evs,handler=Hs0}, Ks, St0) ->
2329    %% No variables are exported from try/catch. Starting in OTP 24,
2330    %% variables bound in the argument (the code between the 'try' and
2331    %% the 'of' keywords) are exported to the body (the code following
2332    %% the 'of' keyword).
2333    {As1,St1} = uexprs(As0, Ks, St0),
2334    ArgKs = union(Ks, new_in_any(As1)),
2335    {Bs1,St2} = uexprs(Bs0, ArgKs, St1),
2336    {Hs1,St3} = uexprs(Hs0, Ks, St2),
2337    Used = intersection(used_in_any(Bs1++Hs1++As1), Ks),
2338    {#itry{anno=A#a{us=Used,ns=[]},
2339	   args=As1,vars=Vs,body=Bs1,evars=Evs,handler=Hs1},St3};
2340uexpr(#icatch{anno=A,body=Es0}, Ks, St0) ->
2341    {Es1,St1} = uexprs(Es0, Ks, St0),
2342    {#icatch{anno=A#a{us=used_in_any(Es1)},body=Es1},St1};
2343uexpr(#ireceive1{anno=A,clauses=Cs0}, Ks, St0) ->
2344    {Cs1,St1} = uclauses(Cs0, Ks, St0),
2345    {#ireceive1{anno=A#a{us=used_in_any(Cs1),ns=new_in_all(Cs1)},
2346		clauses=Cs1},St1};
2347uexpr(#ireceive2{anno=A,clauses=Cs0,timeout=Te0,action=Tes0}, Ks, St0) ->
2348    %% Te0 will never generate new variables.
2349    {Te1,St1} = uexpr(Te0, Ks, St0),
2350    {Cs1,St2} = uclauses(Cs0, Ks, St1),
2351    {Tes1,St3} = uexprs(Tes0, Ks, St2),
2352    Used = union([used_in_any(Cs1),used_in_any(Tes1),(get_anno(Te1))#a.us]),
2353    New = case Cs1 of
2354	      [] -> new_in_any(Tes1);
2355	      _ -> intersection(new_in_all(Cs1), new_in_any(Tes1))
2356	  end,
2357    {#ireceive2{anno=A#a{us=Used,ns=New},
2358		clauses=Cs1,timeout=Te1,action=Tes1},St3};
2359uexpr(#iprotect{anno=A,body=Es0}, Ks, St0) ->
2360    {Es1,St1} = uexprs(Es0, Ks, St0),
2361    Used = used_in_any(Es1),
2362    {#iprotect{anno=A#a{us=Used},body=Es1},St1}; %No new variables escape!
2363uexpr(#ibinary{anno=A,segments=Ss}, _, St) ->
2364    Used = bitstr_vars(Ss),
2365    {#ibinary{anno=A#a{us=Used},segments=Ss},St};
2366uexpr(#c_literal{}=Lit, _, St) ->
2367    Anno = get_anno(Lit),
2368    {set_anno(Lit, #a{us=[],anno=Anno}),St};
2369uexpr(Simple, _, St) ->
2370    true = is_simple(Simple),			%Sanity check!
2371    Vs = lit_vars(Simple),
2372    Anno = get_anno(Simple),
2373    {#isimple{anno=#a{us=Vs,anno=Anno},term=Simple},St}.
2374
2375uexpr_list(Les0, Ks, St0) ->
2376    mapfoldl(fun (Le, St) -> uexpr(Le, Ks, St) end, St0, Les0).
2377
2378%% upattern(Pat, [KnownVar], State) ->
2379%%              {Pat,[GuardTest],[NewVar],[UsedVar],State}.
2380
2381upattern(#c_var{name='_'}, _, St0) ->
2382    {New,St1} = new_var_name(St0),
2383    {#c_var{name=New},[],[New],[],St1};
2384upattern(#c_var{name=V}=Var, Ks, St0) ->
2385    case is_element(V, Ks) of
2386	true ->
2387	    {N,St1} = new_var_name(St0),
2388	    New = #c_var{name=N},
2389	    LA = get_lineno_anno(Var),
2390	    Test = #icall{anno=#a{anno=LA,us=add_element(N, [V])},
2391			  module=#c_literal{val=erlang},
2392			  name=#c_literal{val='=:='},
2393			  args=[New,Var]},
2394	    %% Test doesn't need protecting.
2395	    {New,[Test],[N],[],St1};
2396	false -> {Var,[],[V],[],St0}
2397    end;
2398upattern(#c_cons{hd=H0,tl=T0}=Cons, Ks, St0) ->
2399    {H1,Hg,Hv,Hu,St1} = upattern(H0, Ks, St0),
2400    {T1,Tg,Tv,Tu,St2} = upattern(T0, union(Hv, Ks), St1),
2401    {Cons#c_cons{hd=H1,tl=T1},Hg ++ Tg,union(Hv, Tv),union(Hu, Tu),St2};
2402upattern(#c_tuple{es=Es0}=Tuple, Ks, St0) ->
2403    {Es1,Esg,Esv,Eus,St1} = upattern_list(Es0, Ks, St0),
2404    {Tuple#c_tuple{es=Es1},Esg,Esv,Eus,St1};
2405upattern(#imap{es=Es0}=Map, Ks, St0) ->
2406    {Es1,Esg,Esv,Eus,St1} = upattern_list(Es0, Ks, St0),
2407    {Map#imap{es=Es1},Esg,Esv,Eus,St1};
2408upattern(#imappair{op=#c_literal{val=exact},key=K0,val=V0}=Pair,Ks,St0) ->
2409    {V,Vg,Vn,Vu,St1} = upattern(V0, Ks, St0),
2410    {K,St2} = uexprs(K0, Ks, St1),
2411    Ku = used_in_expr(K),
2412    {Pair#imappair{key=K,val=V},Vg,Vn,union(Ku, Vu),St2};
2413upattern(#ibinary{segments=Es0}=Bin, Ks, St0) ->
2414    {Es1,Esg,Esv,Eus,St1} = upat_bin(Es0, Ks, St0),
2415    {Bin#ibinary{segments=Es1},Esg,Esv,Eus,St1};
2416upattern(#c_alias{var=V0,pat=P0}=Alias, Ks, St0) ->
2417    {V1,Vg,Vv,Vu,St1} = upattern(V0, Ks, St0),
2418    {P1,Pg,Pv,Pu,St2} = upattern(P0, union(Vv, Ks), St1),
2419    {Alias#c_alias{var=V1,pat=P1},Vg ++ Pg,union(Vv, Pv),union(Vu, Pu),St2};
2420upattern(Other, _, St) -> {Other,[],[],[],St}.	%Constants
2421
2422%% upattern_list([Pat], [KnownVar], State) ->
2423%%                        {[Pat],[GuardTest],[NewVar],[UsedVar],State}.
2424
2425upattern_list([P0|Ps0], Ks, St0) ->
2426    {P1,Pg,Pv,Pu,St1} = upattern(P0, Ks, St0),
2427    {Ps1,Psg,Psv,Psu,St2} = upattern_list(Ps0, union(Pv, Ks), St1),
2428    {[P1|Ps1],Pg ++ Psg,union(Pv, Psv),union(Pu, Psu),St2};
2429upattern_list([], _, St) -> {[],[],[],[],St}.
2430
2431%% upat_bin([Pat], [KnownVar], State) ->
2432%%                        {[Pat],[GuardTest],[NewVar],[UsedVar],State}.
2433upat_bin(Es0, Ks, St0) ->
2434    {Es1,Pg,Pv,Pu0,St1} = upat_bin(Es0, Ks, [], St0),
2435
2436    %% In a clause such as <<Sz:8,V:Sz>> in a function head, Sz will both
2437    %% be new and used; a situation that is not handled properly by
2438    %% uclause/4.  (Basically, since Sz occurs in two sets that are
2439    %% subtracted from each other, Sz will not be added to the list of
2440    %% known variables and will seem to be new the next time it is
2441    %% used in a match.)
2442    %%   Since the variable Sz really is new (it does not use a
2443    %% value bound prior to the binary matching), Sz should only be
2444    %% included in the set of new variables. Thus we should take it
2445    %% out of the set of used variables.
2446
2447    Pu1 = subtract(Pu0, intersection(Pv, Pu0)),
2448    {Es1,Pg,Pv,Pu1,St1}.
2449
2450%% upat_bin([Pat], [KnownVar], [LocalVar], State) ->
2451%%                        {[Pat],[GuardTest],[NewVar],[UsedVar],State}.
2452upat_bin([P0|Ps0], Ks, Bs, St0) ->
2453    {P1,Pg,Pv,Pu,Bs1,St1} = upat_element(P0, Ks, Bs, St0),
2454    {Ps1,Psg,Psv,Psu,St2} = upat_bin(Ps0, union(Pv, Ks), Bs1, St1),
2455    {[P1|Ps1],Pg ++ Psg,union(Pv, Psv),union(Pu, Psu),St2};
2456upat_bin([], _, _, St) -> {[],[],[],[],St}.
2457
2458
2459%% upat_element(Segment, [KnownVar], [LocalVar], State) ->
2460%%        {Segment,[GuardTest],[NewVar],[UsedVar],[LocalVar],State}
2461upat_element(#ibitstr{val=H0,size=Sz0}=Seg, Ks, Bs0, St0) ->
2462    {H1,Hg,Hv,[],St1} = upattern(H0, Ks, St0),
2463    Bs1 = case H0 of
2464	      #c_var{name=Hname} ->
2465		  case H1 of
2466		      #c_var{name=Hname} ->
2467			  Bs0;
2468		      #c_var{name=Other} ->
2469			  [{Hname,Other}|Bs0]
2470		  end;
2471	      _ ->
2472		  Bs0
2473	  end,
2474    case Sz0 of
2475        [#c_var{name=Vname}] ->
2476            {Sz1,Us} = rename_bitstr_size(Vname, Bs0),
2477            {Sz2,St2} = uexprs([Sz1], Ks, St1),
2478            {Seg#ibitstr{val=H1,size=Sz2},Hg,Hv,Us,Bs1,St2};
2479        [#c_literal{}] ->
2480            {Sz1,St2} = uexprs(Sz0, Ks, St1),
2481            Us = [],
2482            {Seg#ibitstr{val=H1,size=Sz1},Hg,Hv,Us,Bs1,St2};
2483        Expr when is_list(Expr) ->
2484            Sz1 = [#iset{var=#c_var{name=Old},arg=#c_var{name=New}} ||
2485                      {Old,New} <- Bs0] ++ Expr,
2486            {Sz2,St2} = uexprs(Sz1, Ks, St1),
2487            Us = used_in_expr(Sz2),
2488            {Seg#ibitstr{val=H1,size=Sz2},Hg,Hv,Us,Bs1,St2}
2489    end.
2490
2491rename_bitstr_size(V, [{V,N}|_]) ->
2492    New = #c_var{name=N},
2493    {New,[N]};
2494rename_bitstr_size(V, [_|Rest]) ->
2495    rename_bitstr_size(V, Rest);
2496rename_bitstr_size(V, []) ->
2497    Old = #c_var{name=V},
2498    {Old,[V]}.
2499
2500used_in_expr([Le|Les]) ->
2501    #a{us=Us,ns=Ns} = get_anno(Le),
2502    Used = used_in_expr(Les),
2503    union(Us, subtract(Used, Ns));
2504used_in_expr([]) -> [].
2505
2506used_in_any(Les) ->
2507    foldl(fun (Le, Ns) -> union((get_anno(Le))#a.us, Ns) end,
2508	  [], Les).
2509
2510new_in_any(Les) ->
2511    foldl(fun (Le, Ns) -> union((get_anno(Le))#a.ns, Ns) end,
2512	  [], Les).
2513
2514new_in_all([Le|Les]) ->
2515    foldl(fun (L, Ns) -> intersection((get_anno(L))#a.ns, Ns) end,
2516	  (get_anno(Le))#a.ns, Les);
2517new_in_all([]) -> [].
2518
2519%%%
2520%%% Rename shadowing variables in fun heads.
2521%%%
2522%%% Pattern variables in fun heads always shadow variables bound in
2523%%% the enclosing environment. Because that is the way that variables
2524%%% behave in Core Erlang, there was previously no need to rename
2525%%% the variables.
2526%%%
2527%%% However, to support splitting of patterns and/or pattern matching
2528%%% compilation in Core Erlang, there is a need to rename all
2529%%% shadowing variables to avoid changing the semantics of the Erlang
2530%%% program.
2531%%%
2532
2533rename_shadowing_clauses([C0|Cs0], Ks, St0) ->
2534    {C,St1} = rename_shadowing_clause(C0, Ks, St0),
2535    {Cs,St} = rename_shadowing_clauses(Cs0, Ks, St1),
2536    {[C|Cs],St};
2537rename_shadowing_clauses([], _Ks, St) ->
2538    {[],St}.
2539
2540rename_shadowing_clause(#iclause{pats=Ps0,guard=G0,body=B0}=C, Ks, St0) ->
2541    Subs = {[],[]},
2542    {Ps,{_Isub,Osub},St} = ren_pats(Ps0, Ks, Subs, St0),
2543    G = case G0 of
2544            [] -> G0;
2545            [_|_] -> Osub ++ G0
2546        end,
2547    B = Osub ++ B0,
2548    {C#iclause{pats=Ps,guard=G,body=B},St}.
2549
2550ren_pats([P0|Ps0], Ks, {_,_}=Subs0, St0) ->
2551    {P,Subs1,St1} = ren_pat(P0, Ks, Subs0, St0),
2552    {Ps,Subs,St} = ren_pats(Ps0, Ks, Subs1, St1),
2553    {[P|Ps],Subs,St};
2554ren_pats([], _Ks, {_,_}=Subs, St) ->
2555    {[],Subs,St}.
2556
2557ren_pat(#c_var{name='_'}=P, _Ks, Subs, St) ->
2558    {P,Subs,St};
2559ren_pat(#c_var{name=V}=Old, Ks, {Isub0,Osub0}=Subs, St0) ->
2560    case member(V, Ks) of
2561        true ->
2562            case ren_is_subst(V, Osub0) of
2563                {yes,New} ->
2564                    {New,Subs,St0};
2565                no ->
2566                    {New,St} = new_var(St0),
2567                    Osub = [#iset{var=Old,arg=New}|Osub0],
2568                    {New,{Isub0,Osub},St}
2569            end;
2570        false ->
2571            {Old,Subs,St0}
2572    end;
2573ren_pat(#c_literal{}=P, _Ks, {_,_}=Subs, St) ->
2574    {P,Subs,St};
2575ren_pat(#c_alias{var=Var0,pat=Pat0}=Alias, Ks, {_,_}=Subs0, St0) ->
2576    {Var,Subs1,St1} = ren_pat(Var0, Ks, Subs0, St0),
2577    {Pat,Subs,St} = ren_pat(Pat0, Ks, Subs1, St1),
2578    {Alias#c_alias{var=Var,pat=Pat},Subs,St};
2579ren_pat(#imap{es=Es0}=Map, Ks, {_,_}=Subs0, St0) ->
2580    {Es,Subs,St} = ren_pat_map(Es0, Ks, Subs0, St0),
2581    {Map#imap{es=Es},Subs,St};
2582ren_pat(#ibinary{segments=Es0}=P, Ks, {Isub,Osub0}, St0) ->
2583    {Es,_Isub,Osub,St} = ren_pat_bin(Es0, Ks, Isub, Osub0, St0),
2584    {P#ibinary{segments=Es},{Isub,Osub},St};
2585ren_pat(P, Ks0, {_,_}=Subs0, St0) ->
2586    Es0 = cerl:data_es(P),
2587    {Es,Subs,St} = ren_pats(Es0, Ks0, Subs0, St0),
2588    {cerl:make_data(cerl:data_type(P), Es),Subs,St}.
2589
2590ren_pat_bin([#ibitstr{val=Val0,size=Sz0}=E|Es0], Ks, Isub0, Osub0, St0) ->
2591    Sz = ren_get_subst(Sz0, Isub0),
2592    {Val,{_,Osub1},St1} = ren_pat(Val0, Ks, {Isub0,Osub0}, St0),
2593    Isub1 = case Val0 of
2594                #c_var{} ->
2595                    [#iset{var=Val0,arg=Val}|Isub0];
2596                _ ->
2597                    Isub0
2598            end,
2599    {Es,Isub,Osub,St} = ren_pat_bin(Es0, Ks, Isub1, Osub1, St1),
2600    {[E#ibitstr{val=Val,size=Sz}|Es],Isub,Osub,St};
2601ren_pat_bin([], _Ks, Isub, Osub, St) ->
2602    {[],Isub,Osub,St}.
2603
2604ren_pat_map([#imappair{val=Val0}=MapPair|Es0], Ks, Subs0, St0) ->
2605    {Val,Subs1,St1} = ren_pat(Val0, Ks, Subs0, St0),
2606    {Es,Subs,St} = ren_pat_map(Es0, Ks, Subs1, St1),
2607    {[MapPair#imappair{val=Val}|Es],Subs,St};
2608ren_pat_map([], _Ks, Subs, St) ->
2609    {[],Subs,St}.
2610
2611ren_get_subst([#c_var{name=V}]=Old, Sub) ->
2612    case ren_is_subst(V, Sub) of
2613        no -> Old;
2614        {yes,New} -> [New]
2615    end;
2616ren_get_subst([#c_literal{}]=Old, _Sub) ->
2617    Old;
2618ren_get_subst(Expr, Sub) when is_list(Expr) ->
2619    Sub ++ Expr.
2620
2621ren_is_subst(V, [#iset{var=#c_var{name=V},arg=Arg}|_]) ->
2622    {yes,Arg};
2623ren_is_subst(V, [_|Sub]) ->
2624    ren_is_subst(V, Sub);
2625ren_is_subst(_V, []) -> no.
2626
2627%% The AfterVars are the variables which are used afterwards.  We need
2628%% this to work out which variables are actually exported and used
2629%% from case/receive.  In subblocks/clauses the AfterVars of the block
2630%% are just the exported variables.
2631
2632cbody(B0, St0) ->
2633    {B1,_,_,St1} = cexpr(B0, [], St0),
2634    {B1,St1}.
2635
2636%% cclause(Lclause, [AfterVar], State) -> {Cclause,State}.
2637%%  The AfterVars are the exported variables.
2638
2639cclause(#iclause{anno=#a{anno=Anno},pats=Ps0,guard=G0,body=B0}, Exp, St0) ->
2640    Ps = cpattern_list(Ps0),
2641    {B1,_Us1,St1} = cexprs(B0, Exp, St0),
2642    {G1,St2} = cguard(G0, St1),
2643    {#c_clause{anno=Anno,pats=Ps,guard=G1,body=B1},St2}.
2644
2645cclauses(Lcs, Es, St0) ->
2646    mapfoldl(fun (Lc, St) -> cclause(Lc, Es, St) end, St0, Lcs).
2647
2648cguard([], St) -> {#c_literal{val=true},St};
2649cguard(Gs, St0) ->
2650    {G,_,St1} = cexprs(Gs, [], St0),
2651    {G,St1}.
2652
2653cpattern_list([P|Ps]) ->
2654    [cpattern(P)|cpattern_list(Ps)];
2655cpattern_list([]) -> [].
2656
2657cpattern(#c_alias{pat=Pat}=Alias) ->
2658    Alias#c_alias{pat=cpattern(Pat)};
2659cpattern(#c_cons{hd=Hd,tl=Tl}=Cons) ->
2660    Cons#c_cons{hd=cpattern(Hd),tl=cpattern(Tl)};
2661cpattern(#c_tuple{es=Es}=Tup) ->
2662    Tup#c_tuple{es=cpattern_list(Es)};
2663cpattern(#imap{anno=#a{anno=Anno},es=Es}) ->
2664    #c_map{anno=Anno,es=cpat_map_pairs(Es),is_pat=true};
2665cpattern(#ibinary{anno=#a{anno=Anno},segments=Segs0}) ->
2666    Segs = [cpat_bin_seg(S) || S <- Segs0],
2667    #c_binary{anno=Anno,segments=Segs};
2668cpattern(Other) -> Other.
2669
2670cpat_map_pairs([#imappair{anno=#a{anno=Anno},op=Op,key=Key0,val=Val0}|T]) ->
2671    {Key,_,_} = cexprs(Key0, [], #core{}),
2672    Val = cpattern(Val0),
2673    Pair = #c_map_pair{anno=Anno,op=Op,key=Key,val=Val},
2674    [Pair|cpat_map_pairs(T)];
2675cpat_map_pairs([]) -> [].
2676
2677cpat_bin_seg(#ibitstr{anno=#a{anno=Anno},val=E,size=Sz0,unit=Unit,
2678                      type=Type,flags=Flags}) ->
2679    {Sz,_,_} = cexprs(Sz0, [], #core{}),
2680    #c_bitstr{anno=Anno,val=E,size=Sz,unit=Unit,type=Type,flags=Flags}.
2681
2682%% cexprs([Lexpr], [AfterVar], State) -> {Cexpr,[AfterVar],State}.
2683%%  Must be sneaky here at the last expr when combining exports for the
2684%%  whole sequence and exports for that expr.
2685
2686cexprs([#iset{var=#c_var{name=Name}=Var}=Iset], As, St) ->
2687    %% Make return value explicit, and make Var true top level.
2688    Isimple = #isimple{anno=#a{us=[Name]},term=Var},
2689    cexprs([Iset,Isimple], As, St);
2690cexprs([Le], As, St0) ->
2691    {Ce,Es,Us,St1} = cexpr(Le, As, St0),
2692    Exp = make_vars(As),			%The export variables
2693    if
2694	Es =:= [] -> {core_lib:make_values([Ce|Exp]),union(Us, As),St1};
2695	true ->
2696	    {R,St2} = new_var(St1),
2697	    {#c_let{anno=get_lineno_anno(Ce),
2698		    vars=[R|make_vars(Es)],arg=Ce,
2699		    body=core_lib:make_values([R|Exp])},
2700	     union(Us, As),St2}
2701    end;
2702cexprs([#iset{anno=#a{anno=A},var=V,arg=A0}|Les], As0, St0) ->
2703    {Ces,As1,St1} = cexprs(Les, As0, St0),
2704    {A1,Es,Us,St2} = cexpr(A0, As1, St1),
2705    {#c_let{anno=A,vars=[V|make_vars(Es)],arg=A1,body=Ces},
2706     union(Us, As1),St2};
2707cexprs([Le|Les], As0, St0) ->
2708    {Ces,As1,St1} = cexprs(Les, As0, St0),
2709    {Ce,Es,Us,St2} = cexpr(Le, As1, St1),
2710    if
2711	Es =:= [] ->
2712	    {#c_seq{arg=Ce,body=Ces},union(Us, As1),St2};
2713	true ->
2714	    {R,St3} = new_var(St2),
2715	    {#c_let{vars=[R|make_vars(Es)],arg=Ce,body=Ces},
2716	     union(Us, As1),St3}
2717    end.
2718
2719%% cexpr(Lexpr, [AfterVar], State) -> {Cexpr,[ExpVar],[UsedVar],State}.
2720
2721cexpr(#iletrec{anno=A,defs=Fs0,body=B0}, As, St0) ->
2722    {Fs1,{_,St1}} = mapfoldl(fun ({{_Name,_Arity}=NA,F0}, {Used,S0}) ->
2723				     {F1,[],Us,S1} = cexpr(F0, [], S0),
2724				     {{#c_var{name=NA},F1},
2725				      {union(Us, Used),S1}}
2726			     end, {[],St0}, Fs0),
2727    Exp = intersection(A#a.ns, As),
2728    {B1,_Us,St2} = cexprs(B0, Exp, St1),
2729    {#c_letrec{anno=A#a.anno,defs=Fs1,body=B1},Exp,A#a.us,St2};
2730cexpr(#icase{anno=A,args=Largs,clauses=Lcs,fc=Lfc}, As, St0) ->
2731    Exp = intersection(A#a.ns, As),		%Exports
2732    {Cargs,St1} = foldr(fun (La, {Cas,Sta}) ->
2733				{Ca,[],_Us1,Stb} = cexpr(La, As, Sta),
2734				{[Ca|Cas],Stb}
2735			end, {[],St0}, Largs),
2736    {Ccs,St2} = cclauses(Lcs, Exp, St1),
2737    {Cfc0,St3} = cclause(Lfc, [], St2),		%Never exports
2738    {Cfc,St4} = c_add_dummy_export(Cfc0, Exp, St3),
2739    {#c_case{anno=A#a.anno,
2740	     arg=core_lib:make_values(Cargs),clauses=Ccs ++ [Cfc]},
2741     Exp,A#a.us,St4};
2742cexpr(#ireceive1{anno=A,clauses=Lcs}, As, St0) ->
2743    Exp = intersection(A#a.ns, As),		%Exports
2744    {Ccs,St1} = cclauses(Lcs, Exp, St0),
2745    True = #c_literal{val=true},
2746    Action = core_lib:make_values(lists:duplicate(1+length(Exp), True)),
2747    {#c_receive{anno=A#a.anno,
2748		clauses=Ccs,
2749		timeout=#c_literal{val=infinity},action=Action},
2750     Exp,A#a.us,St1};
2751cexpr(#ireceive2{anno=A,clauses=Lcs,timeout=Lto,action=Les}, As, St0) ->
2752    Exp = intersection(A#a.ns, As),		%Exports
2753    {Cto,[],_Us1,St1} = cexpr(Lto, As, St0),
2754    {Ccs,St2} = cclauses(Lcs, Exp, St1),
2755    {Ces,_Us2,St3} = cexprs(Les, Exp, St2),
2756    {#c_receive{anno=A#a.anno,
2757		clauses=Ccs,timeout=Cto,action=Ces},
2758     Exp,A#a.us,St3};
2759cexpr(#itry{anno=A,args=La,vars=Vs0,body=Lb,evars=Evs,handler=Lh}, _As, St0) ->
2760    %% No variables are exported from try/catch. Starting in OTP 24,
2761    %% variables bound in the argument (the code between the 'try' and
2762    %% the 'of' keywords) are exported to the body (the code following
2763    %% the 'of' keyword).
2764    AsExp = intersection(new_in_any(La), used_in_any(Lb)),
2765    {Ca,_Us1,St1} = cexprs(La, AsExp, St0),
2766    {Cb,_Us2,St2} = cexprs(Lb, [], St1),
2767    {Ch,_Us3,St3} = cexprs(Lh, [], St2),
2768    Vs = Vs0 ++ [#c_var{name=V} || V <- AsExp],
2769    {#c_try{anno=A#a.anno,arg=Ca,vars=Vs,body=Cb,evars=Evs,handler=Ch},
2770     [],A#a.us,St3};
2771cexpr(#icatch{anno=A,body=Les}, _As, St0) ->
2772    {Ces,_Us1,St1} = cexprs(Les, [], St0),	%Never export!
2773    {#c_catch{body=Ces},[],A#a.us,St1};
2774cexpr(#ifun{name=unnamed}=Fun, As, St0) ->
2775    cfun(Fun, As, St0);
2776cexpr(#ifun{anno=#a{us=Us0}=A0,name={named,Name},fc=#iclause{pats=Ps}}=Fun0,
2777      As, St0) ->
2778    case is_element(Name, Us0) of
2779        false ->
2780            cfun(Fun0, As, St0);
2781        true ->
2782            A1 = A0#a{us=del_element(Name, Us0)},
2783            Fun1 = Fun0#ifun{anno=A1},
2784            {#c_fun{body=Body}=CFun0,[],Us1,St1} = cfun(Fun1, As, St0),
2785            RecVar = #c_var{name={Name,length(Ps)}},
2786            Let = #c_let{vars=[#c_var{name=Name}],arg=RecVar,body=Body},
2787            CFun1 = CFun0#c_fun{body=Let},
2788            Letrec = #c_letrec{anno=A0#a.anno,
2789			       defs=[{RecVar,CFun1}],
2790                               body=RecVar},
2791            {Letrec,[],Us1,St1}
2792    end;
2793cexpr(#iapply{anno=A,op=Op,args=Args}, _As, St) ->
2794    {#c_apply{anno=A#a.anno,op=Op,args=Args},[],A#a.us,St};
2795cexpr(#icall{anno=A,module=Mod,name=Name,args=Args}, _As, St0) ->
2796    Anno = A#a.anno -- [v3_core],
2797    case (not cerl:is_c_atom(Mod)) andalso member(tuple_calls, St0#core.opts) of
2798	true ->
2799	    GenAnno = [compiler_generated|Anno],
2800
2801	    %% Generate the clause that matches on the tuple
2802	    {TupleVar,St1} = new_var(GenAnno, St0),
2803	    {TupleSizeVar, St2} = new_var(GenAnno, St1),
2804	    {TupleModVar, St3} = new_var(GenAnno, St2),
2805	    {TupleArgsVar, St4} = new_var(GenAnno, St3),
2806	    TryVar = cerl:c_var('Try'),
2807
2808	    TupleGuardExpr =
2809		cerl:c_let([TupleSizeVar],
2810			   c_call_erl(tuple_size, [TupleVar]),
2811			   c_call_erl('>', [TupleSizeVar, cerl:c_int(0)])),
2812
2813	    TupleGuard =
2814		cerl:c_try(TupleGuardExpr, [TryVar], TryVar,
2815			   [cerl:c_var('T'),cerl:c_var('R')], cerl:c_atom(false)),
2816
2817	    TupleApply =
2818		cerl:c_let([TupleModVar],
2819			   c_call_erl(element, [cerl:c_int(1),TupleVar]),
2820			   cerl:c_let([TupleArgsVar],
2821				      cerl:make_list(Args ++ [TupleVar]),
2822				      c_call_erl(apply, [TupleModVar,Name,TupleArgsVar]))),
2823
2824	    TupleClause = cerl:ann_c_clause(GenAnno, [TupleVar], TupleGuard, TupleApply),
2825
2826	    %% Generate the fallback clause
2827	    {OtherVar,St5} = new_var(GenAnno, St4),
2828	    OtherApply = cerl:ann_c_call(GenAnno, OtherVar, Name, Args),
2829	    OtherClause = cerl:ann_c_clause(GenAnno, [OtherVar], OtherApply),
2830
2831	    {cerl:ann_c_case(GenAnno, Mod, [TupleClause,OtherClause]),[],A#a.us,St5};
2832	false ->
2833	    {#c_call{anno=Anno,module=Mod,name=Name,args=Args},[],A#a.us,St0}
2834    end;
2835cexpr(#iprimop{anno=A,name=Name,args=Args}, _As, St) ->
2836    {#c_primop{anno=A#a.anno,name=Name,args=Args},[],A#a.us,St};
2837cexpr(#iprotect{anno=A,body=Es}, _As, St0) ->
2838    {Ce,_,St1} = cexprs(Es, [], St0),
2839    V = #c_var{name='Try'},		%The names are arbitrary
2840    Vs = [#c_var{name='T'},#c_var{name='R'}],
2841    {#c_try{anno=A#a.anno,arg=Ce,vars=[V],body=V,
2842	    evars=Vs,handler=#c_literal{val=false}},
2843     [],A#a.us,St1};
2844cexpr(#ibinary{anno=#a{anno=Anno,us=Us},segments=Segs}, _As, St) ->
2845    {#c_binary{anno=Anno,segments=Segs},[],Us,St};
2846cexpr(#c_literal{}=Lit, _As, St) ->
2847    Anno = get_anno(Lit),
2848    Vs = Anno#a.us,
2849    {set_anno(Lit, Anno#a.anno),[],Vs,St};
2850cexpr(#isimple{anno=#a{us=Vs},term=Simple}, _As, St) ->
2851    true = is_simple(Simple),		%Sanity check!
2852    {Simple,[],Vs,St}.
2853
2854cfun(#ifun{anno=A,id=Id,vars=Args,clauses=Lcs,fc=Lfc}, _As, St0) ->
2855    {Ccs,St1} = cclauses(Lcs, [], St0),     %NEVER export!
2856    {Cfc,St2} = cclause(Lfc, [], St1),
2857    Anno = A#a.anno,
2858    {#c_fun{anno=Id++Anno,vars=Args,
2859            body=#c_case{anno=Anno,
2860                         arg=set_anno(core_lib:make_values(Args), Anno),
2861                         clauses=Ccs ++ [Cfc]}},
2862     [],A#a.us,St2}.
2863
2864c_call_erl(Fun, Args) ->
2865    As = [compiler_generated],
2866    cerl:ann_c_call(As, cerl:c_atom(erlang), cerl:c_atom(Fun), Args).
2867
2868
2869c_add_dummy_export(#c_clause{body=B0}=C, [_|_]=Exp, St0) ->
2870    %% Add dummy export in order to always return the correct number
2871    %% of values for the default clause.
2872    {V,St1} = new_var(St0),
2873    B = #c_let{vars=[V],arg=B0,
2874               body=#c_values{es=[V|duplicate(length(Exp), #c_literal{val=[]})]}},
2875    {C#c_clause{body=B},St1};
2876c_add_dummy_export(C, [], St) ->
2877    {C,St}.
2878
2879%%%
2880%%% Lower a `receive` to more primitive operations. Rewrite patterns
2881%%% that use and bind the same variable as nested cases.
2882%%%
2883%%% Here follows an example of how a receive in this Erlang code:
2884%%%
2885%%% foo(Timeout) ->
2886%%%     receive
2887%%%         {tag,Msg} -> Msg
2888%%%     after
2889%%%         Timeout ->
2890%%%             no_message
2891%%%     end.
2892%%%
2893%%% is translated into Core Erlang:
2894%%%
2895%%% 'foo'/1 =
2896%%%     fun (Timeout) ->
2897%%%         ( letrec
2898%%%               'recv$^0'/0 =
2899%%%                   fun () ->
2900%%%                       let <PeekSucceeded,Message> =
2901%%%                           primop 'recv_peek_message'()
2902%%%                       in  case PeekSucceeded of
2903%%%                             <'true'> when 'true' ->
2904%%%                                 case Message of
2905%%%                                   <{'tag',Msg}> when 'true' ->
2906%%%                                       do  primop 'remove_message'()
2907%%%                                           Msg
2908%%%                                   ( <Other> when 'true' ->
2909%%%                                         do  primop 'recv_next'()
2910%%%                                             apply 'recv$^0'/0()
2911%%%                                     -| ['compiler_generated'] )
2912%%%                                 end
2913%%%                             <'false'> when 'true' ->
2914%%%                                 let <TimedOut> =
2915%%%                                     primop 'recv_wait_timeout'(Timeout)
2916%%%                                 in  case TimedOut of
2917%%%                                       <'true'> when 'true' ->
2918%%%                                           do  primop 'timeout'()
2919%%%                                               'no_message'
2920%%%                                       <'false'> when 'true' ->
2921%%%                                           apply 'recv$^0'/0()
2922%%%                                     end
2923%%%                           end
2924%%%           in  apply 'recv$^0'/0()
2925%%%           -| ['letrec_goto'] )
2926
2927lbody(B, St) ->
2928    cerl_trees:mapfold(fun skip_lowering/2, fun lexpr/2, St, B).
2929
2930%% These nodes do not have case or receive within them,
2931%% so we can speed up lowering by not traversing them.
2932skip_lowering(#c_binary{}, _A) -> skip;
2933skip_lowering(#c_call{}, _A) -> skip;
2934skip_lowering(#c_cons{}, _A) -> skip;
2935skip_lowering(#c_literal{}, _A) -> skip;
2936skip_lowering(#c_map{}, _A) -> skip;
2937skip_lowering(#c_primop{}, _A) -> skip;
2938skip_lowering(#c_tuple{}, _A) -> skip;
2939skip_lowering(T, A) -> {T, A}.
2940
2941lexpr(#c_case{}=Case, St) ->
2942    %% Split patterns that bind and use the same variable.
2943    split_case(Case, St);
2944lexpr(#c_receive{clauses=[],timeout=Timeout0,action=Action}, St0) ->
2945    %% Lower a receive with only an after to its primitive operations.
2946    False = #c_literal{val=false},
2947    True = #c_literal{val=true},
2948
2949    {Timeout,Outer0,St1} =
2950        case is_safe(Timeout0) of
2951            true ->
2952                {Timeout0,False,St0};
2953            false ->
2954                {TimeoutVar,Sti0} = new_var(St0),
2955                OuterLet = #c_let{vars=[TimeoutVar],arg=Timeout0,body=False},
2956                {TimeoutVar,OuterLet,Sti0}
2957        end,
2958
2959    MaybeIgnore = case Timeout of
2960                      #c_literal{val=infinity} -> [dialyzer_ignore];
2961                      _ -> []
2962                  end,
2963
2964    {LoopName,St2} = new_fun_name("recv", St1),
2965    LoopFun = #c_var{name={LoopName,0}},
2966    ApplyLoop = #c_apply{anno=[dialyzer_ignore],op=LoopFun,args=[]},
2967
2968    AfterCs = [#c_clause{anno=MaybeIgnore,pats=[True],guard=True,
2969                         body=Action},
2970               #c_clause{anno=[compiler_generated,dialyzer_ignore],
2971                         pats=[False],guard=True,
2972                         body=ApplyLoop}],
2973    {TimeoutBool,St3} = new_var(St2),
2974    TimeoutCase = #c_case{anno=[receive_timeout],arg=TimeoutBool,
2975                          clauses=AfterCs},
2976    TimeoutLet = #c_let{vars=[TimeoutBool],
2977                        arg=primop(recv_wait_timeout, [Timeout]),
2978                        body=TimeoutCase},
2979
2980    Fun = #c_fun{vars=[],body=TimeoutLet},
2981
2982    Letrec = #c_letrec{anno=[letrec_goto,no_inline],
2983                       defs=[{LoopFun,Fun}],
2984                       body=ApplyLoop},
2985
2986    %% If the 'after' expression is unsafe we evaluate it in an outer 'let'.
2987    Outer = case Outer0 of
2988                #c_let{} -> Outer0#c_let{body=Letrec};
2989                _ -> Letrec
2990            end,
2991    {Outer,St3};
2992lexpr(#c_receive{anno=RecvAnno,clauses=Cs0,timeout=Timeout0,action=Action}, St0) ->
2993    %% Lower receive to its primitive operations.
2994    False = #c_literal{val=false},
2995    True = #c_literal{val=true},
2996
2997    {Timeout,Outer0,St1} =
2998        case is_safe(Timeout0) of
2999            true ->
3000                {Timeout0,False,St0};
3001            false ->
3002                {TimeoutVar,Sti0} = new_var(St0),
3003                OuterLet = #c_let{vars=[TimeoutVar],arg=Timeout0,body=False},
3004                {TimeoutVar,OuterLet,Sti0}
3005        end,
3006
3007    MaybeIgnore = case Timeout of
3008                      #c_literal{val=infinity} -> [dialyzer_ignore];
3009                      _ -> []
3010                  end,
3011
3012    {LoopName,St2} = new_fun_name("recv", St1),
3013    LoopFun = #c_var{name={LoopName,0}},
3014    ApplyLoop = #c_apply{anno=[dialyzer_ignore],op=LoopFun,args=[]},
3015
3016    Cs1 = rewrite_cs(Cs0),
3017    RecvNext = #c_seq{arg=primop(recv_next),
3018                      body=ApplyLoop},
3019    RecvNextC = #c_clause{anno=[compiler_generated,dialyzer_ignore],
3020                          pats=[#c_var{name='Other'}],guard=True,body=RecvNext},
3021    Cs = Cs1 ++ [RecvNextC],
3022    {Msg,St3} = new_var(St2),
3023    {MsgCase,St4} = split_case(#c_case{anno=RecvAnno,arg=Msg,clauses=Cs}, St3),
3024
3025    AfterCs = [#c_clause{pats=[True],guard=True,body=Action},
3026               #c_clause{anno=[dialyzer_ignore],pats=[False],guard=True,
3027                         body=ApplyLoop}],
3028    {TimeoutBool,St5} = new_var(St4),
3029    TimeoutCase = #c_case{arg=TimeoutBool,clauses=AfterCs},
3030    TimeoutLet = #c_let{vars=[TimeoutBool],
3031                        arg=primop(recv_wait_timeout, [Timeout]),
3032                        body=TimeoutCase},
3033
3034    {PeekSucceeded,St6} = new_var(St5),
3035    PeekCs = [#c_clause{pats=[True],guard=True,
3036                        body=MsgCase},
3037              #c_clause{anno=MaybeIgnore,
3038                        pats=[False],guard=True,
3039                        body=TimeoutLet}],
3040    PeekCase = #c_case{arg=PeekSucceeded,clauses=PeekCs},
3041    PeekLet = #c_let{vars=[PeekSucceeded,Msg],
3042                     arg=primop(recv_peek_message, [], RecvAnno),
3043                     body=PeekCase},
3044    Fun = #c_fun{vars=[],body=PeekLet},
3045
3046    Letrec = #c_letrec{anno=[letrec_goto,no_inline],
3047                       defs=[{LoopFun,Fun}],
3048                       body=ApplyLoop},
3049
3050    %% If the 'after' expression is unsafe we evaluate it in an outer 'let'.
3051    Outer = case Outer0 of
3052                #c_let{} -> Outer0#c_let{body=Letrec};
3053                _ -> Letrec
3054            end,
3055    {Outer,St6};
3056lexpr(Tree, St) ->
3057    {Tree,St}.
3058
3059rewrite_cs([#c_clause{body=B0}=C|Cs]) ->
3060    B = #c_seq{arg=primop(remove_message),body=B0},
3061    [C#c_clause{body=B}|rewrite_cs(Cs)];
3062rewrite_cs([]) -> [].
3063
3064primop(Name) ->
3065    primop(Name, []).
3066
3067primop(Name, Args) ->
3068    primop(Name, Args, []).
3069
3070primop(Name, Args, Anno) ->
3071    #c_primop{anno=Anno,name=#c_literal{val=Name},args=Args}.
3072
3073%%%
3074%%% Split patterns such as <<Size:32,Tail:Size>> that bind
3075%%% and use a variable in the same pattern. Rewrite to a
3076%%% nested case in a letrec.
3077%%%
3078
3079split_case(#c_case{anno=CaseAnno,arg=Arg,clauses=Cs0}=Case0, St0) ->
3080    Args = case Arg of
3081               #c_values{es=Es} -> Es;
3082               _ -> [Arg]
3083           end,
3084    {VarArgs,St1} = split_var_args(Args, St0),
3085    case split_clauses(Cs0, VarArgs, CaseAnno, St1) of
3086        none ->
3087            {Case0,St0};
3088        {PreCase,AftCs,St2} ->
3089            AftCase = Case0#c_case{arg=core_lib:make_values(VarArgs),
3090                                   clauses=AftCs},
3091            AftFun = #c_fun{vars=[],body=AftCase},
3092            {Letrec,St3} = split_case_letrec(AftFun, PreCase, St2),
3093            Body = split_letify(VarArgs, Args, Letrec, [], []),
3094            {Body,St3}
3095    end.
3096
3097split_var_args(Args, St) ->
3098    mapfoldl(fun(#c_var{}=Var, S0) ->
3099                     {Var,S0};
3100                (#c_literal{}=Lit, S0) ->
3101                     {Lit,S0};
3102                (_, S0) ->
3103                     new_var(S0)
3104             end, St, Args).
3105
3106split_letify([Same|Vs], [Same|Args], Body, VsAcc, ArgAcc) ->
3107    split_letify(Vs, Args, Body, VsAcc, ArgAcc);
3108split_letify([V|Vs], [Arg|Args], Body, VsAcc, ArgAcc) ->
3109    split_letify(Vs, Args, Body, [V|VsAcc], [Arg|ArgAcc]);
3110split_letify([], [], Body, [], []) ->
3111    Body;
3112split_letify([], [], Body, [_|_]=VsAcc, [_|_]=ArgAcc) ->
3113    #c_let{vars=reverse(VsAcc),
3114           arg=core_lib:make_values(reverse(ArgAcc)),
3115           body=Body}.
3116
3117split_case_letrec(#c_fun{anno=FunAnno0}=Fun0, Body, #core{gcount=C}=St0) ->
3118    FunAnno = [compiler_generated|FunAnno0],
3119    Fun = Fun0#c_fun{anno=FunAnno},
3120    Anno = [letrec_goto,no_inline],
3121    DefFunName = goto_func(C),
3122    Letrec = #c_letrec{anno=Anno,defs=[{#c_var{name=DefFunName},Fun}],body=Body},
3123    St = St0#core{gcount=C+1},
3124    lbody(Letrec, St).
3125
3126split_clauses([C0|Cs0], Args, CaseAnno, St0) ->
3127    case split_clauses(Cs0, Args, CaseAnno, St0) of
3128        none ->
3129            case split_clause(C0, St0) of
3130                none ->
3131                    none;
3132                {Ps,Nested,St1} ->
3133                    {Case,St2} = split_reconstruct(Args, Ps, Nested,
3134                                                   C0, CaseAnno, St1),
3135                    {Case,Cs0,St2}
3136            end;
3137        {Case0,Cs,St} ->
3138            #c_case{clauses=NewClauses} = Case0,
3139            Case = Case0#c_case{clauses=[C0|NewClauses]},
3140            {Case,Cs,St}
3141    end;
3142split_clauses([], _, _, _) ->
3143    none.
3144
3145goto_func(Count) ->
3146    {list_to_atom("label^" ++ integer_to_list(Count)),0}.
3147
3148split_reconstruct(Args, Ps, nil, #c_clause{anno=Anno}=C0, CaseAnno, St0) ->
3149    C = C0#c_clause{pats=Ps},
3150    {Fc,St1} = split_fc_clause(Ps, Anno, St0),
3151    {#c_case{anno=CaseAnno,arg=core_lib:make_values(Args),clauses=[C,Fc]},St1};
3152split_reconstruct(Args, Ps, {split,SplitArgs,Pat,Nested}, C, CaseAnno, St) ->
3153    Split = {split,SplitArgs,fun(Body) -> Body end,Pat,Nested},
3154    split_reconstruct(Args, Ps, Split, C, CaseAnno, St);
3155split_reconstruct(Args, Ps, {split,SplitArgs,Wrap,Pat,Nested},
3156                  #c_clause{anno=Anno}=C0, CaseAnno, St0) ->
3157    {InnerCase,St1} = split_reconstruct(SplitArgs, [Pat], Nested, C0,
3158                                        CaseAnno, St0),
3159    {Fc,St2} = split_fc_clause(Args, Anno, St1),
3160    Wrapped = Wrap(InnerCase),
3161    C = C0#c_clause{pats=Ps,guard=#c_literal{val=true},body=Wrapped},
3162    {#c_case{anno=CaseAnno,arg=core_lib:make_values(Args),clauses=[C,Fc]},St2}.
3163
3164split_fc_clause(Args, Anno0, #core{gcount=Count}=St0) ->
3165    Anno = [compiler_generated|Anno0],
3166    Arity = length(Args),
3167    {Vars,St1} = new_vars(Arity, St0),
3168    Op = #c_var{name=goto_func(Count)},
3169    Apply = #c_apply{anno=Anno,op=Op,args=[]},
3170    {#c_clause{anno=[dialyzer_ignore|Anno],pats=Vars,
3171               guard=#c_literal{val=true},body=Apply},St1}.
3172
3173split_clause(#c_clause{pats=Ps0}, St0) ->
3174    case split_pats(Ps0, St0) of
3175        none ->
3176            none;
3177        {Ps,Case,St} ->
3178            {Ps,Case,St}
3179    end.
3180
3181split_pats([P0|Ps0], St0) ->
3182    case split_pats(Ps0, St0) of
3183        none ->
3184            case split_pat(P0, St0) of
3185                none ->
3186                    none;
3187                {P,Case,St} ->
3188                    {[P|Ps0],Case,St}
3189            end;
3190        {Ps,Case,St} ->
3191            {[P0|Ps],Case,St}
3192    end;
3193split_pats([], _) ->
3194    none.
3195
3196split_pat(#c_binary{segments=Segs0}=Bin, St0) ->
3197    Vars = gb_sets:empty(),
3198    case split_bin_segments(Segs0, Vars, St0, []) of
3199        none ->
3200            none;
3201        {TailVar,Wrap,Bef,Aft,St} ->
3202            BefBin = Bin#c_binary{segments=Bef},
3203            {BefBin,{split,[TailVar],Wrap,Bin#c_binary{segments=Aft},nil},St}
3204    end;
3205split_pat(#c_map{es=Es}=Map, St) ->
3206    split_map_pat(Es, Map, St, []);
3207split_pat(#c_var{}, _) ->
3208    none;
3209split_pat(#c_alias{pat=Pat}=Alias0, St0) ->
3210    case split_pat(Pat, St0) of
3211        none ->
3212            none;
3213        {Ps,Split,St1} ->
3214            {Var,St} = new_var(St1),
3215            Alias = Alias0#c_alias{pat=Var},
3216            {Alias,{split,[Var],Ps,Split},St}
3217    end;
3218split_pat(Data, St0) ->
3219    Type = cerl:data_type(Data),
3220    Es = cerl:data_es(Data),
3221    split_data(Es, Type, St0, []).
3222
3223split_map_pat([#c_map_pair{key=Key,val=Val}=E0|Es], Map0, St0, Acc) ->
3224    case eval_map_key(Key, E0, Es, Map0, St0) of
3225        none ->
3226            case split_pat(Val, St0) of
3227                none ->
3228                    split_map_pat(Es, Map0, St0, [E0|Acc]);
3229                {Ps,Split,St1} ->
3230                    {Var,St} = new_var(St1),
3231                    E = E0#c_map_pair{val=Var},
3232                    Map = Map0#c_map{es=reverse(Acc, [E|Es])},
3233                    {Map,{split,[Var],Ps,Split},St}
3234            end;
3235        {MapVar,Split,St1} ->
3236            BefMap0 = Map0#c_map{es=reverse(Acc)},
3237            BefMap = #c_alias{var=MapVar,pat=BefMap0},
3238            {BefMap,Split,St1}
3239    end;
3240split_map_pat([], _, _, _) -> none.
3241
3242eval_map_key(#c_var{}, _E, _Es, _Map, _St) ->
3243    none;
3244eval_map_key(#c_literal{}, _E, _Es, _Map, _St) ->
3245    none;
3246eval_map_key(Key, E0, Es, Map, St0) ->
3247    {[KeyVar,MapVar],St1} = new_vars(2, St0),
3248    E = E0#c_map_pair{key=KeyVar},
3249    AftMap0 = Map#c_map{es=[E|Es]},
3250    {Wrap,CaseArg,AftMap,St2} = wrap_map_key_fun(Key, KeyVar, MapVar, AftMap0, St1),
3251    {MapVar,{split,[CaseArg],Wrap,AftMap,nil},St2}.
3252
3253wrap_map_key_fun(Key, KeyVar, MapVar, AftMap, St0) ->
3254    case is_safe(Key) of
3255        true ->
3256            {fun(Body) ->
3257                     #c_let{vars=[KeyVar],arg=Key,body=Body}
3258             end,MapVar,AftMap,St0};
3259        false ->
3260            {[SuccVar|Evars],St} = new_vars(4, St0),
3261            {fun(Body) ->
3262                     Try = #c_try{arg=Key,vars=[KeyVar],
3263                                  body=#c_values{es=[#c_literal{val=true},KeyVar]},
3264                                  evars=Evars,
3265                                  handler=#c_values{es=[#c_literal{val=false},
3266                                                        #c_literal{val=false}]}},
3267                     #c_let{vars=[SuccVar,KeyVar],arg=Try,body=Body}
3268             end,
3269             #c_tuple{es=[SuccVar,MapVar]},
3270             #c_tuple{es=[#c_literal{val=true},AftMap]},
3271             St}
3272    end.
3273
3274split_data([E|Es0], Type, St0, Acc) ->
3275    case split_pat(E, St0) of
3276        none ->
3277            split_data(Es0, Type, St0, [E|Acc]);
3278        {Ps,Split,St1} ->
3279            {Var,St} = new_var(St1),
3280            Data = cerl:make_data(Type, reverse(Acc, [Var|Es0])),
3281            {Data,{split,[Var],Ps,Split},St}
3282    end;
3283split_data([], _, _, _) -> none.
3284
3285split_bin_segments([#c_bitstr{val=Val,size=Size}=S0|Segs], Vars0, St0, Acc) ->
3286    Vars = case Val of
3287               #c_var{name=V} -> gb_sets:add(V, Vars0);
3288               _ -> Vars0
3289           end,
3290    case Size of
3291        #c_literal{} ->
3292            split_bin_segments(Segs, Vars, St0, [S0|Acc]);
3293        #c_var{name=SizeVar} ->
3294            case gb_sets:is_member(SizeVar, Vars0) of
3295                true ->
3296                    %% The size variable is variable previously bound
3297                    %% in this same segment. Split the clause here to
3298                    %% avoid a variable that is both defined and used
3299                    %% in the same pattern.
3300                    {TailVar,Tail,St} = split_tail_seg(S0, Segs, St0),
3301                    Wrap = fun(Body) -> Body end,
3302                    {TailVar,Wrap,reverse(Acc, [Tail]),[S0|Segs],St};
3303                false ->
3304                    split_bin_segments(Segs, Vars, St0, [S0|Acc])
3305            end;
3306        _ ->
3307            %% The size is an expression. Split the clause here,
3308            %% calculate the expression in a try/catch, and finally
3309            %% continue the match in an inner case.
3310            {TailVar,Tail,St1} = split_tail_seg(S0, Segs, St0),
3311            {SizeVar,St2} = new_var(St1),
3312            S = S0#c_bitstr{size=SizeVar},
3313            {Wrap,St3} = split_wrap(SizeVar, Size, St2),
3314            {TailVar,Wrap,reverse(Acc, [Tail]),[S|Segs],St3}
3315    end;
3316split_bin_segments(_, _, _, _) ->
3317    none.
3318
3319split_tail_seg(#c_bitstr{anno=A}=S, Segs, St0) ->
3320    {TailVar,St} = new_var(St0),
3321    Unit = split_bin_unit([S|Segs], St0),
3322    {TailVar,
3323     #c_bitstr{anno=A,val=TailVar,
3324               size=#c_literal{val=all},
3325               unit=#c_literal{val=Unit},
3326               type=#c_literal{val=binary},
3327               flags=#c_literal{val=[unsigned,big]}},
3328    St}.
3329
3330split_wrap(SizeVar, SizeExpr, St0) ->
3331    {Evars,St1} = new_vars(3, St0),
3332    {fun(Body) ->
3333             Try = #c_try{arg=SizeExpr,vars=[SizeVar],body=SizeVar,
3334                          evars=Evars,handler=#c_literal{val=bad_size}},
3335             #c_let{vars=[SizeVar],arg=Try,body=Body}
3336     end,St1}.
3337
3338split_bin_unit(Ss, #core{dialyzer=Dialyzer}) ->
3339    case Dialyzer of
3340        true ->
3341            %% When a binary match has been rewritten to a nested
3342            %% case like this:
3343            %%
3344            %%    case Bin of
3345            %%      <<Size:32,Tail:Size/bitstring-unit:1>> ->
3346            %%         case Tail of
3347            %%            <<Result/binary-unit:8>> -> Result;
3348            %%         ...
3349            %%    end
3350            %%
3351            %% dialyzer will determine the type of Bin based solely on
3352            %% the binary pattern in the outer case. It will not
3353            %% back-propagate any type information for Tail to Bin. For
3354            %% this example, dialyzer would infer the type of Bin to
3355            %% be <<_:8,_:_*1>>.
3356            %%
3357            %% Help dialyzer to infer a better type by calculating the
3358            %% greatest common unit for the segments in the inner case
3359            %% expression. For this example, the greatest common unit
3360            %% for the pattern in the inner case is 8; it will allow
3361            %% dialyzer to infer the type for Bin to be
3362            %% <<_:32,_:_*8>>.
3363
3364            split_bin_unit_1(Ss, 0);
3365        false ->
3366            %% Return the unit for pattern in the outer case that
3367            %% results in the best code.
3368
3369            1
3370    end.
3371
3372split_bin_unit_1([#c_bitstr{type=#c_literal{val=Type},size=Size,
3373                            unit=#c_literal{val=U}}|Ss],
3374                 GCU) ->
3375    Bits = case {Type,Size} of
3376               {utf8,_} -> 8;
3377               {utf16,_} -> 16;
3378               {utf32,_} -> 32;
3379               {_,#c_literal{val=0}} -> 1;
3380               {_,#c_literal{val=Sz}} when is_integer(Sz) -> Sz * U;
3381               {_,_} -> U
3382           end,
3383    split_bin_unit_1(Ss, gcd(GCU, Bits));
3384split_bin_unit_1([], GCU) -> GCU.
3385
3386gcd(A, B) ->
3387    case A rem B of
3388        0 -> B;
3389        X -> gcd(B, X)
3390    end.
3391
3392%% lit_vars(Literal) -> [Var].
3393
3394lit_vars(Lit) -> lit_vars(Lit, []).
3395
3396lit_vars(#c_cons{hd=H,tl=T}, Vs) -> lit_vars(H, lit_vars(T, Vs));
3397lit_vars(#c_tuple{es=Es}, Vs) -> lit_list_vars(Es, Vs);
3398lit_vars(#c_map{arg=V,es=Es}, Vs) -> lit_vars(V, lit_list_vars(Es, Vs));
3399lit_vars(#c_map_pair{key=K,val=V}, Vs) -> lit_vars(K, lit_vars(V, Vs));
3400lit_vars(#c_var{name=V}, Vs) -> add_element(V, Vs);
3401lit_vars(_, Vs) -> Vs.				%These are atomic
3402
3403lit_list_vars(Ls) -> lit_list_vars(Ls, []).
3404
3405lit_list_vars(Ls, Vs) ->
3406    foldl(fun (L, Vs0) -> lit_vars(L, Vs0) end, Vs, Ls).
3407
3408bitstr_vars(Segs) ->
3409    bitstr_vars(Segs, []).
3410
3411bitstr_vars(Segs, Vs) ->
3412    foldl(fun (#c_bitstr{val=V,size=S}, Vs0) ->
3413 		  lit_vars(V, lit_vars(S, Vs0))
3414	  end, Vs, Segs).
3415
3416record_anno(L, #core{dialyzer=Dialyzer}=St) ->
3417    case erl_anno:record(L) andalso Dialyzer of
3418        true ->
3419            [record | lineno_anno(L, St)];
3420        false ->
3421            full_anno(L, St)
3422    end.
3423
3424full_anno(L, #core{wanted=false}=St) ->
3425    [result_not_wanted|lineno_anno(L, St)];
3426full_anno(L, #core{wanted=true}=St) ->
3427    lineno_anno(L, St).
3428
3429lineno_anno(L, St) ->
3430    Location = erl_anno:location(L),
3431    Generated = erl_anno:generated(L),
3432    CompilerGenerated = [compiler_generated || Generated],
3433    [Location] ++ St#core.file ++ CompilerGenerated.
3434
3435get_lineno_anno(Ce) ->
3436    case get_anno(Ce) of
3437	#a{anno=A} -> A;
3438	A when is_list(A) -> A
3439    end.
3440
3441no_compiler_warning(Anno) ->
3442    erl_anno:set_generated(true, Anno).
3443
3444%%
3445%% The following three functions are used both with cerl:cerl() and with i()'s
3446%%
3447-spec get_anno(cerl:cerl() | i()) -> term().
3448
3449get_anno(C) -> element(2, C).
3450
3451-spec set_anno(cerl:cerl() | i(), term()) -> cerl:cerl().
3452
3453set_anno(C, A) -> setelement(2, C, A).
3454
3455-spec is_simple(cerl:cerl() | i()) -> boolean().
3456
3457is_simple(#c_var{}) -> true;
3458is_simple(#c_literal{}) -> true;
3459is_simple(#c_cons{hd=H,tl=T}) ->
3460    is_simple(H) andalso is_simple(T);
3461is_simple(#c_tuple{es=Es}) -> is_simple_list(Es);
3462is_simple(#c_map{es=Es}) -> is_simple_list(Es);
3463is_simple(#c_map_pair{key=K,val=V}) ->
3464    is_simple(K) andalso is_simple(V);
3465is_simple(_) -> false.
3466
3467-spec is_simple_list([cerl:cerl()]) -> boolean().
3468
3469is_simple_list(Es) -> lists:all(fun is_simple/1, Es).
3470
3471%%%
3472%%% Handling of warnings.
3473%%%
3474
3475-type err_desc() :: {'failed' | 'nomatch' | 'ignored', term()} |
3476                    {'map_key_repeated',term()}.
3477
3478-spec format_error(err_desc()) -> nonempty_string().
3479
3480format_error({nomatch,pattern}) ->
3481    "pattern cannot possibly match";
3482format_error({failed,bad_binary}) ->
3483    "binary construction will fail because of a type mismatch";
3484format_error({map_key_repeated,Key}) ->
3485    %% This warning does not fit neatly into any category.
3486    if
3487        is_atom(Key) ->
3488            io_lib:format("key '~w' will be overridden in expression", [Key]);
3489        true ->
3490            io_lib:format("key ~p will be overridden in expression", [Key])
3491    end.
3492
3493add_warning(Anno, Term, #core{ws=Ws,file=[{file,File}]}=St) ->
3494    case erl_anno:generated(Anno) of
3495        false ->
3496            St#core{ws=[{File,[{erl_anno:location(Anno),?MODULE,Term}]}|Ws]};
3497        true ->
3498            St
3499    end.
3500