简体   繁体   中英

Will an optimiser deduce mathematical expressions based on compile-time constants?

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

EDIT: I was wrong, the compiler works as expected when using a floating point number.

Well gcc 4.6.3 in -03 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM