[BoundsSafety] `__single` pointers are not null-checked.
In the description of the -fbounds-safety feature, it says "Dereferencing a __single pointer is allowed but it requires a null check."
However, in my testing of the feature preview (implemented here: https://github.com/swiftlang/llvm-project/tree/stable/20240723) it seems like there is no null check performed. I tried compiling the following program:
#include <ptrcheck.h>
int foo(int *__single p) {
return *p;
}
int bar(int *__counted_by_or_null(1) p) {
return *p;
}
$ clang -fbounds-safety -S test.c -O2 -target aarch64
This gives the following assembly (abbreviated):
foo:
ldr w0, [x0]
ret
bar:
cbz x0, .LBB1_3
add x8, x0, #4
cmp x8, x0
b.lo .LBB1_3
ldr w0, [x0]
ret
.LBB1_3:
brk #0x5519
bar contains a check, but foo has no check and directly dereferences the __single input pointer. Please let me know if I am using the wrong version or doing something incorrect. Thank you.
@zyedidia
I tested your example using the stable/20240723 and I observed the same behavior — the __single pointer in foo() is dereferenced without a null check, while __counted_by_or_null in bar() includes the expected null check.
According to the Clang bounds-safety documentation, dereferencing a __single pointer should involve a null check, so it seems like this may be a missing codegen case rather than incorrect usage.
I'm currently exploring the code generation path for bounds-safety and may try a patch to fix this behavior.
Just want to know were you using clang from the Swift toolchain with -fbounds-safety on the stable/20240723 branch?
Thanks for looking into this! Yes I was using Clang from the Swift toolchain on the stable/20240723 branch.
@zyedidia Thanks for filing the issue! You're absolutely right that dereferencing a __single pointer should emit a null check by design. However, we currently don't enable null checks for optimization purposes, since most platforms are protected by zero-page protection (https://en.wikipedia.org/wiki/Zero_page), which catches null dereferences at the hardware level.
As you mentioned in the email, explicit null checks would still be valuable in certain contexts like large struct offsets or to prevent the compiler from exploiting undefined behavior. We plan to add a compiler flag to enable them for __single pointers.