Code generation (was NOOB)

Bjorn Gustavsson <>
Fri Sep 1 15:46:09 CEST 2006

The compiler will not optimize away anything in this case,
for several reasons.

1. The optimizations are fairly conservative. The compiler
doesn't even try to optimize away list comprehensions.
Earlier versions of the compiler tried to optimize bit syntax
constructions that weren't used, but bitten by bugs we don't
try that anymore. (The unoptimized version would cause a badarg,
and the optimized version would not.)

2. In this case, do_something(E) will fail with a badarith exception
if E is not an integer, so it would not be safe to remove the call,
even if the compiler would attempt to look inside a list comprehension.
Also, X might not be a list, in which case there should be an exception

3. In the case of the do_other/1 function, it calls a function in
another module, so the compiler has no idea whether is it is safe
to remove the call.

We have considered improving the optimization, so that no list would
be built in case 2.


Jay Nelson <> writes:

> Bjorn wrote:
> > Later, just before code generation, variable life times are
> > calculated. The code generator is guided by the life time information,
> > and doesn't generate any code for assigning a variable that
> > will never be used.
> Can you describe what happens in the following two cases?
> foo(X) ->
>    A = [do_something(E) || E <- X],    % <1>
>    [do_other(E) || E <- X],            % <2>
>    ok.
> do_something(E) -> E * 4.
> do_other(E) -> io:write("~w~n", [E]).
> In 1, does the function 'do_something' every get called?
> >From your description, A is thrown out and the fun has no
> side effect.
> In 2, does a list get created on the stack?
> If 1 were changed to call 'do_other' would the code be
> generated differently (because of the side effect)?
> jay

Björn Gustavsson, Erlang/OTP, Ericsson AB

More information about the erlang-questions mailing list