public inbox for gcc-bugs@sourceware.org
help / color / mirror / Atom feed
* [Bug c++/99470] New: Convert fixed index addition to array address offset
@ 2021-03-08 17:20 redbeard0531 at gmail dot com
  2021-03-08 18:05 ` [Bug rtl-optimization/99470] " pinskia at gcc dot gnu.org
                   ` (3 more replies)
  0 siblings, 4 replies; 5+ messages in thread
From: redbeard0531 at gmail dot com @ 2021-03-08 17:20 UTC (permalink / raw)
  To: gcc-bugs

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

            Bug ID: 99470
           Summary: Convert fixed index addition to array address offset
           Product: gcc
           Version: 11.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redbeard0531 at gmail dot com
  Target Milestone: ---

These two functions do the same thing but f() is the cleaner source code
(especially when arr is a std::array) while g() generates better code:

https://gcc.godbolt.org/z/vTT399

#include <cstdint>

inline int8_t arr[256];

bool f(int a, int b) {
    return arr[a+128] == arr[b+128];
}

bool g(int a, int b) {
    return (arr+128)[a] == (arr+128)[b];
}

f(int, int):
        sub     edi, -128
        sub     esi, -128
        lea     rax, arr[rip]
        movsx   rdi, edi
        movsx   rsi, esi
        movzx   edx, BYTE PTR [rax+rsi]
        cmp     BYTE PTR [rax+rdi], dl
        sete    al
        ret
g(int, int):
        lea     rax, arr[rip+128]
        movsx   rdi, edi
        movsx   rsi, esi
        movzx   edx, BYTE PTR [rax+rsi]
        cmp     BYTE PTR [rax+rdi], dl
        sete    al
        ret

In addition to only doing the +128 once, it also ends up being completely free
in g() because the assembler (or linker?) folds the addition into the address
calculation by adjusting the offset of the rip-relative address. In the godbolt
link, you can see that when compiled to binary, the LEA instruction uses the
same form in both f() and g(), so the addition really is free in g().

^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2021-03-09 10:03 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2021-03-08 17:20 [Bug c++/99470] New: Convert fixed index addition to array address offset redbeard0531 at gmail dot com
2021-03-08 18:05 ` [Bug rtl-optimization/99470] " pinskia at gcc dot gnu.org
2021-03-08 18:24 ` pinskia at gcc dot gnu.org
2021-03-08 18:24 ` pinskia at gcc dot gnu.org
2021-03-09 10:03 ` redbeard0531 at gmail dot com

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).