[Bug c++/90571] New: Missed optimization opportunity when returning function pointers based on run-time boolean

vittorio.romeo at outlook dot com gcc-bugzilla@gcc.gnu.org
Wed May 22 12:25:00 GMT 2019


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90571

            Bug ID: 90571
           Summary: Missed optimization opportunity when returning
                    function pointers based on run-time boolean
           Product: gcc
           Version: 10.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: vittorio.romeo at outlook dot com
  Target Milestone: ---

Given the following two functions:

    int f() { return 0; }
    int g() { return 1; }

And the following code to invoke one of them depending on a boolean `b`:

    int t0(bool b) { return (b ? &f : &g)(); }
    int t1(bool b) { return b ? f() : g(); }
    int t2(bool b) { return b ? t0(true) : t0(false); }

Both `g++ (trunk)` and `clang++ (trunk)` with `-std=c++2a -Ofast -march=native`
fail to optimize the following code:

    int main(int ac, char**) { return t0(ac & 1); }

Producing the following assembly:

>     main:
>       and edi, 1
>       mov eax, OFFSET FLAT:f()
>       mov edx, OFFSET FLAT:g()
>       cmove rax, rdx
>       jmp rax
> 

Invoking `t1` or `t2` (instead of `t0`) produces the following optimized
assembly:

>     main:
>             mov     eax, edi
>             not     eax
>             and     eax, 1
>             ret

Everything can be reproduced live on **gcc.godbolt.org**:
https://godbolt.org/z/gh7270


More information about the Gcc-bugs mailing list