Back to TILs

C++ constexpr optimization

Date: 2023-01-14Last modified: 2023-06-27

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
// All calculation is done in compilation time
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 (++20230222053142+eb9440b3d8b4-1~exp1~20230222173238.37)"
	.section	".note.GNU-stack","",@progbits
	.addrsig

References