https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128435
Bug ID: 128435
Summary: aach64 gcc optimizes loop to strlen on -O2 even when
it is not available.
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: giuliano.belinassi at gmail dot com
Target Milestone: ---
With the following input:
> typedef unsigned long size_t;
>
> size_t len(const char *str)
> {
> size_t len = 0;
> while (str[len] != '\0')
> ++len;
> return len;
> }
When compiled with -O2 -nostdlib -nodefaultlibs, x86_64 gcc generates:
> "len":
> cmp BYTE PTR [rdi], 0
> je .L3
> sub rsp, 8
> add rdi, 1
> call "strlen"
> add rsp, 8
> add rax, 1
> ret
> .L3:
> xor eax, eax
> ret
which breaks -nostdlib -nodefaultlibs. This optimization must be blocked when
gcc expects the code to not be linked against any libc.
compiler explorer link: https://godbolt.org/z/T7rq3zYGn
I tracked this to back to gcc-12.