Lance Pollard
Lance Pollard

Reputation: 79468

How to generate assembly from Julia code on the command line?

I see there is this macro @code_native, which you can use like:

julia> @code_native 1+1
        .text
        .file   "+"
        .globl  "julia_+_13305"                 # -- Begin function julia_+_13305
        .p2align        4, 0x90
        .type   "julia_+_13305",@function
"julia_+_13305":                        # @"julia_+_13305"
; ┌ @ int.jl:87 within `+`
        .cfi_startproc
# %bb.0:                                # %top
        leaq    (%rdi,%rsi), %rax
        retq
.Lfunc_end0:
        .size   "julia_+_13305", .Lfunc_end0-"julia_+_13305"
        .cfi_endproc
; └
                                        # -- End function
        .section        ".note.GNU-stack","",@progbits

How do you take a source Julia file or text, and run it through this function to get the output assembly as text? Can it be done on the command line somehow? Something like

$ julia --emit-asm file.jl -o file.asm # and it outputs the assembly to another file.asm

I have never used julia but curious about how you can compile it (and I'd like to play with the generated assembly).

Upvotes: 2

Views: 148

Answers (1)

kirklong
kirklong

Reputation: 570

Do you use Linux? If so sending stdout to a file works for me, i.e. if I have the following file called code_native_out.jl which contains:

@code_native 1+1

And I then run this with Julia but redirect stdout to a file:

julia <code_native_out.jl >code_native_out.txt

The output file code_native_out.txt contains what was printed at the REPL (the output from the code_native macro).

Alternatively you can capture what the macro is showing you at the REPL within Julia itself by doing something like:

open("code_native_out.txt","w") do io
    redirect_stdout(io) do
        @code_native 1+1
    end
end

Either way results in the same output file, so pick whatever works best for you.

Edit: if you have something more complicated than just the example shown, you can still do the same thing. For example:

function f(x) #some more complicated function you want to see
    x = 2*x
    x = x+7
    x = "the value of x is $x"
    return x
end

open("code_native_out.txt","w") do io
    redirect_stdout(io) do
        @code_native f(3)
    end
end

This will then spit out the assembly for all of the code evaluated for f(3). If you have a function in another file you want to test, simply include that file first and then you have access to all functions declared there and you can do the same thing:

include("my_file_with_f.jl") #external file that contains function f(x)
open("code_native_out.txt","w") do io
    redirect_stdout(io) do
        @code_native f(3)
    end
end

Upvotes: 2

Related Questions