I am trying to introduce a generic function with the semantics of ternary operator: E1 ? E2 : E3. I see that compiler is able to eliminate calculation of one of E2 or E3 depending on E1 condition for the ternary operator. However GCC misses this optimization in case of ternary function call (even when E2/E3 have no side effects).
In the listing below function ternary is written to behave similarly to the ternary operator. However GCC emits potentially heavy call to function f which seems can be eliminated for some input values (exactly how it is done for ternary operator) because f is declared with pure attribute - please look at the godbolt link for assembly code generated by GCC.
Is it something that could be improved in GCC (room for optimization) or does the C++ standard explicitly prohibit such kind of optimizations?
// Very heavy function
int f() __attribute__ ((pure));
inline int ternary(bool cond, int n1, int n2) {
    return cond ? n1 : n2;
}
int foo1(int i) {
    return i == 0 ? f() : 0;
}
int foo2(int i) {
    return ternary(i == 0, f(), 0);
}
Assembly listing with -O3 -std=c++11:
foo1(int):
  test edi, edi
  jne .L2
  jmp f()
.L2:
  xor eax, eax
  ret
foo2(int):
  push rbx
  mov ebx, edi
  call f()
  test ebx, ebx
  mov edx, 0
  pop rbx
  cmovne eax, edx
  ret
 
    