glibc 2.26 has several hand optimized assembly implementations of strlen
As of glibc-2.26
, a quick:
git ls-files | grep strlen.S
in the glibc tree shows a dozen of assembly hand-optimized implementations for all major archs and variations.
In particular, x86_64 alone has 3 variations:
sysdeps/x86_64/multiarch/strlen-avx2.S
sysdeps/x86_64/multiarch/strlen-sse2.S
sysdeps/x86_64/strlen.S
A quick and dirty way to determine which one is used, is to step debug a test program:
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(void) {
size_t size = 0x80000000, i, result;
char *s = malloc(size);
for (i = 0; i < size; ++i)
s[i] = a ;
s[size - 1] = ;
result = strlen(s);
assert(result == size - 1);
return EXIT_SUCCESS;
}
compiled with:
gcc -ggdb3 -std=c99 -O0 a.c
Off the bat:
disass main
contains:
callq 0x555555554590 <strlen@plt>
so the libc version is being called.
After a few si
instruction level steps into that, GDB reaches:
__strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:52
52 ../sysdeps/x86_64/multiarch/strlen-avx2.S: No such file or directory.
which tells me that strlen-avx2.S
was used.
Then, I further confirm with:
disass __strlen_avx2
and compare the disassembly with the glibc source.
It is not surprising that the AVX2 version was used, since I have an i7-7820HQ CPU with launch date Q1 2017 and AVX2 support, and AVX2 is the most advanced of the assembly implementations, with launch date Q2 2013, while SSE2 is much more ancient from 2004.
This is where a great part of the hardcoreness of glibc comes from: it has a lot of arch optimized hand written assembly code.
Tested in Ubuntu 17.10, gcc 7.2.0, glibc 2.26.
-O3
TODO: with -O3
, gcc does not use glibc s strlen
, it just generates inline assembly, which is mentioned at: https://stackoverflow.com/a/19885891/895245
Is it because it can optimize even better? But its output does not contain AVX2 instructions, so I feel that this is not the case.
https://www.gnu.org/software/gcc/projects/optimize.html mentions:
Deficiencies of GCC s optimizer
glibc has inline assembler versions of various string functions; GCC has some, but not necessarily the same ones on the same architectures. Additional optab entries, like the ones for ffs and strlen, could be provided for several more functions including memset, strchr, strcpy and strrchr.
My simple tests show that the -O3
version is actually faster, so GCC made the right choice.
Asked at: https://www.quora.com/unanswered/How-does-GCC-know-that-its-builtin-implementation-of-strlen-is-faster-than-glibcs-when-using-optimization-level-O3