[clang] [Clang][CodeGen] Do not set inbounds flag for struct GEP with null base pointers (PR #130734)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Thu Mar 20 07:00:20 PDT 2025


================
@@ -10,12 +10,46 @@ struct S {
 
 // CHECK-LABEL: @_Z23get_offset_of_y_naivelyv(
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:    ret i64 ptrtoint (ptr getelementptr inbounds nuw ([[STRUCT_S:%.*]], ptr null, i32 0, i32 1) to i64)
+// CHECK-NEXT:    ret i64 ptrtoint (ptr getelementptr ([[STRUCT_S:%.*]], ptr null, i32 0, i32 1) to i64)
 //
 uintptr_t get_offset_of_y_naively() {
   return ((uintptr_t)(&(((S *)nullptr)->y)));
 }
 
+struct Empty {};
+
+struct T {
+  int a;
+  S s;
+  [[no_unique_address]] Empty e1;
+  int b;
+  [[no_unique_address]] Empty e2;
+};
+
+// CHECK-LABEL: @_Z30get_offset_of_y_naively_nestedv(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:    ret i64 ptrtoint (ptr getelementptr ([[STRUCT_S:%.*]], ptr getelementptr ([[STRUCT_T:%.*]], ptr null, i32 0, i32 1), i32 0, i32 1) to i64)
+//
+uintptr_t get_offset_of_y_naively_nested() {
+  return ((uintptr_t)(&(((T *)nullptr)->s.y)));
----------------
AaronBallman wrote:

It would be good to have tests for other null pointer constants like `0`, but there's a question of how deep down the rabbit hole we want the extension to go. I think it makes sense to allow it only for null pointer constants, not just any constant expression which converts to a null pointer. But maybe that's too restrictive?

Suggested tests:
```
nullptr_t{} // Should probably be accepted because this is a valid null pointer constant
constexpr void *null_ptr = nullptr; // Should probably be rejected, null_ptr is not a null pointer constant
0 // Should be accepted because this is a valid null pointer constant
(void *)0 // Should only be accepted in C because it's a valid null pointer constant there, but not in C++
```
and you should also ensure the C tests cover these cases as well.

https://github.com/llvm/llvm-project/pull/130734


More information about the cfe-commits mailing list