Reputation: 28659
If I have some mathematical equations which rely on inputs which can be zero or non-zero (template argument, known at compile time), will the optimiser evaluate the equations and optimise out expressions it knows will evaluate to 0 or 1.
For example:
double x = y * Eval<type>::value;
if Eval<type>::value
is 0
, x
will always be 0
.
double x = exp(y * Eval<type>::value);
if Eval<type>::value
is 0
, x
will always be 1
.
Can the optimiser figure this out and replace x
with 0
or 1
elsewhere in the code, or will these calculations be carried out at runtime?
I am using gcc 4.7 with -O3
Upvotes: 5
Views: 249
Reputation:
EDIT: I was wrong, the compiler works as expected when using a floating point number.
Well gcc 4.6.3 in -O3
certainly does seem to do this, as long as the expression is integer related.
Example code:
#include <cstdio>
inline int x(double y)
{
if (y == 0)
printf("Hello bob3\n");
else
printf("Why do I bother\n");
};
const int c = 0;
int main()
{
int f;
scanf("%d",&f);
x(f * c);
}
Resulting assembly
.file "foo.cpp"
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "%d"
.LC1:
.string "Hello bob3"
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB13:
.cfi_startproc
subq $24, %rsp
.cfi_def_cfa_offset 32
movl $.LC0, %edi
xorl %eax, %eax
leaq 12(%rsp), %rsi
call scanf
movl $.LC1, %edi
call puts
xorl %eax, %eax
addq $24, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE13:
.size main, .-main
.ident "GCC: (Debian 4.6.3-1) 4.6.3"
.section .note.GNU-stack,"",@progbits
Upvotes: 1