[x86-64] The '-fdelete-null-pointer-checks' pass not removed redundant code
The clang compiler is not optimizing away pointer check in the foo() function in this code. The gcc removes that part of code as dead code after '-fdelete-null-pointer-checks' pass. We can observe these behaviors in platforms like X86, ARM.
The clang assembly code in x86-64; https://godbolt.org/z/nncroxMx4
The gcc assembly code in x86-64; https://godbolt.org/z/YbqPYGon4
#include <stdio.h>
#include <string.h>
char dest[50];
void foo(char* dest, char* src) {
memcpy(dest, src, strlen(src));
if (!src) { // <------- This is redundant check as pointer is already de-referenced
printf("checking -fdelete-null-pointer-checks compiler optimization\n");
printf("This source code is redundant\n");
__builtin_abort ();
}
printf("After check for null pointer\n");
}
int main ()
{
char src[50] = "-fdelete-null-pointer-checks";
foo(dest, src);
return 0;
}
@llvm/issue-subscribers-backend-x86
Author: Ishwara Sharma (IshwaraK)
The clang assembly code in x86-64; https://godbolt.org/z/nncroxMx4
The gcc assembly code in x86-64; https://godbolt.org/z/YbqPYGon4
#include <stdio.h>
#include <string.h>
char dest[50];
void foo(char* dest, char* src) {
memcpy(dest, src, strlen(src));
if (!src) { // <------- This is redundant check as pointer is already de-referenced
printf("checking -fdelete-null-pointer-checks compiler optimization\n");
printf("This source code is redundant\n");
__builtin_abort ();
}
printf("After check for null pointer\n");
}
int main ()
{
char src[50] = "-fdelete-null-pointer-checks";
foo(dest, src);
return 0;
}
This optimization is no longer legal since https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3322.pdf. It's only valid if the length passed to memcpy is known non-zero, in which case Clang does perform the optimization.
This optimization is no longer legal since https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3322.pdf. It's only valid if the length passed to memcpy is known non-zero, in which case Clang does perform the optimization.
But strlen(src) implies that src is nonnull.
Oh sorry, I thought this issue was about the memcpy call, not the strlen call. I agree that this optimization is valid for strlen. It look like we don't infer nonnull for strlen in BuildLibCalls.
Alive2 proof: https://alive2.llvm.org/ce/z/yJfskv
For some reason the code at https://github.com/llvm/llvm-project/blob/9326633abd0e59fc77072488ee8cded4fe83c8a1/llvm/lib/Analysis/ValueTracking.cpp#L2661-L2669 works on the called function instead of querying CallBase attributes.