Do compilers compose simple functions with constant arguments into unique instructions?

This is what I always considered the truth, but never tested. Consider a very simple function:

int subtractFive(int num) {
    return num -5;
}

If a compile-time constant such as

  getElement(5);

A compiler with optimizations enabled will most likely enable this. However, it is not clear to me whether the number-5 is evaluated at runtime or compile time. Will simplification of an expression be expressed recursively through inline functions this way? Or is it not superior to function?

+4
source share
3 answers

We can just look at the generated assembly to find out. This code:

int subtractFive(int num) {
    return num -5;
}

int main(int argc, char *argv[]) {
  return subtractFive(argc);
}

compiled with g++ -O2gives

leal    -5(%rdi), %eax
ret

, . inlining.

, , , , .

int subtractFive(int num) {
    return num -5;
}

int foo(int i) {
    return subtractFive(i) * 5;
}

int main(int argc, char *argv[]) {
  return foo(argc);
}

-

leal    -25(%rdi,%rdi,4), %eax
ret

, . foo , ( ) (Live).

, , . ,

int subtractFive(int num) {
    return num -5;
}

int foo(int i) {
    return subtractFive(i) * 5;
}

int main() {
  return foo(7);
}

mov     eax, 10
ret

int main () {
    return 10;
}

, , , ( ) , .

+13

;

int foo(int);
int bar(int x) { return x-5; }
int baz() { return foo(bar(5)); }

g++ -O3 asm baz

xorl    %edi, %edi
jmp _Z3fooi

0 foo. , , foo .

, ( " " ).

+3

The smart compiler will evaluate this at compile time and replace getElement (5) because it will never have another result. None of the variables are considered volatile.

+1
source

Source: https://habr.com/ru/post/1598582/


All Articles