I am trying to read a piece of Rust assembly code, but actually, it's harder to read than the ASM code generated by the C/C++ compiler. So, how to analyze the ASM code of the below piece of Rust code?
fn main() {
let closure = |x| println!("{}", x);
let x: fn(x: i32) -> () = closure;
println!("{}", x as i32);
}
The corresponding assembly code like below with some comments (I only pasted the main part, for full version please use this Permalink: https://play.rust-lang.org/?version=nightly&mode=release&edition=2018&gist=e7ba4844f1ce6e881912dc074152988d):
playground::main: # @playground::main
# %bb.0:
subq $72, %rsp
leaq core::ops::function::FnOnce::call_once(%rip), %rax
movl %eax, 4(%rsp)
leaq 4(%rsp), %rax
movq %rax, 8(%rsp)
movq core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt@GOTPCREL(%rip), %rax
movq %rax, 16(%rsp)
leaq .L__unnamed_2(%rip), %rax # the contents of rdx come from .L__unnamed_2(%rip), how to evaluate this part?
movq %rax, 24(%rsp) # the contents of rdi come from rax.
movq $2, 32(%rsp)
movq $0, 40(%rsp)
leaq 8(%rsp), %rax
movq %rax, 56(%rsp)
movq $1, 64(%rsp)
leaq 24(%rsp), %rdi # rdi should be the register holding the value passed to println!.
callq *std::io::stdio::_print@GOTPCREL(%rip)
addq $72, %rsp
retq
# -- End function
main: # @main
# %bb.0:
subq $8, %rsp
movq %rsi, %rcx
movslq %edi, %rdx
leaq playground::main(%rip), %rax
movq %rax, (%rsp)
leaq .L__unnamed_1(%rip), %rsi
movq %rsp, %rdi
callq *std::rt::lang_start_internal@GOTPCREL(%rip)
# kill: def $eax killed $eax killed $rax
popq %rcx
retq
# -- End function
.L__unnamed_1:
.quad core::ptr::drop_in_place<std::rt::lang_start<()>::{{closure}}>
.quad 8 # 0x8
.quad 8 # 0x8
.quad std::rt::lang_start::{{closure}}
.quad std::rt::lang_start::{{closure}}
.quad core::ops::function::FnOnce::call_once{{vtable.shim}}
.L__unnamed_3:
.L__unnamed_4:
.byte 10
.L__unnamed_2:
.quad .L__unnamed_3
.zero 8
.quad .L__unnamed_4
.asciz "\001\000\000\000\000\000\000"
And, I am trying to find how the Rust compiler treats the function pointer of closure versus normal function. So, here I tried to use a closure as an example but seems I cannot find any valid assembly code that corresponds to the use of the variable "x".