Back to TILs

C++ asm_fibo_01

Table of contents

The compiler optimization will reduce this function to a single integer value.

main:
	.cfi_startproc
	mov	eax, 6765   # the result of fib(20) 
	ret
constexpr int fib(int n) {
  if (n == 1 || n == 2) {
    return 1;
  } else {
    return fib(n - 1) + fib(n - 2);
  }
}
int main() {
  constexpr int fib20 = fib(20);
  return fib20;
}

Assembly code generated

The assembly code generation from C++ code can be achieved by using this Makefile generic target:

%.s: %.cpp
  $(CXX) -std=c++17 -fverbose-asm -masm=intel -S -Os $^ -o $@
	.text
	.intel_syntax noprefix
	.file	"asm_fibo_01.cpp"
	.globl	main                            # -- Begin function main
	.type	main,@function
main:                                   # @main
	.cfi_startproc
# %bb.0:
	mov	eax, 6765
	ret
.Lfunc_end0:
	.size	main, .Lfunc_end0-main
	.cfi_endproc
                                        # -- End function
	.ident	"Debian clang version 16.0.0 (++20221229090856+f3c9342a3d56-1~exp1~20221229090952.514)"
	.section	".note.GNU-stack","",@progbits
	.addrsig

References