How to compile .ex code into .S assembly, like erl -S

I know one way is to disasm the .beam file
but can I compile it directly from elixir code?

I tried this but it does not work: ERL_COMPILER_OPTIONS='-S -P -E -v' ; elixirc a.ex

I tried this too:(

Under the hood, the Elixir compiler is using compile:noenv_forms/2 (see here) which ignores the ERL_COMPILER_OPTIONS env var.

michalmuskala/decompile has an option to compile to asm forms:

mix archive.install github michalmuskala/decompile
mix decompile <modulename> --to asm

Then what can ERL_COMPILER_OPTIONS be used for?

Oh actually I’m wrong: you can affect the compile options through ERL_COMPILER_OPTIONS. It expects the options as in the compile:file/2 docs though as (a list of) atoms, so 'S' for asm. Mix can’t handle asm results though:

$ ERL_COMPILER_OPTIONS="'S'" mix compile
** (CompileError) mix.exs: could not compile module MyMixProject. We expected the compiler to return a .beam binary but got something else. This usually happens because ERL_COMPILER_OPTIONS or @compile was set to change the compilation outcome in a way that is incompatible with Elixir
1 Like

Setting ERL_COMPILER_OPTIONS drops .S files alongside the files it compiles - for instance, running ERL_COMPILER_OPTIONS="'S'" mix compile on a project locally fails with the message:

$ ERL_COMPILER_OPTIONS="'S'" mix compile
** (CompileError) mix.exs: could not compile module Relay.Mixfile. We expected the compiler to return a .beam binary but got something else. This usually happens because ERL_COMPILER_OPTIONS or @compile was set to change the compilation outcome in a way that is incompatible with Elixir

Which also leaves a mix.exs.S file in the working directory.

You can customize the compiler options on a per-module basis with the @compile attribute (see previous discussion), so a module like this in a file lib/foo.ex:

defmodule Foo do
  @compile :S

  def foo(a, b) do
    a + b
  end
end

Running mix compile when a file has this @compile in it will cause compilation to fail, but will also drop a foo.ex.S file in the current working directory.

2 Likes

啊哈! Thanks!