[clang] [Clang][CodeGen] Do not set inbounds flag for struct GEP with null base pointers (PR #130734)
Yingwei Zheng via cfe-commits
cfe-commits at lists.llvm.org
Fri Mar 14 00:41:57 PDT 2025
https://github.com/dtcxzyw updated https://github.com/llvm/llvm-project/pull/130734
>From 02065e86c63ab3fbdefd2ce6e963ffeec96e6a24 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng <dtcxzyw2333 at gmail.com>
Date: Tue, 11 Mar 2025 16:20:08 +0800
Subject: [PATCH 1/3] [Clang][CodeGen] Do not set inbounds flag for struct GEP
with null base pointers
---
clang/lib/CodeGen/CGBuilder.h | 15 ++++++++++-----
...nullptr-and-nonzero-offset-in-offsetof-idiom.c | 2 +-
...llptr-and-nonzero-offset-in-offsetof-idiom.cpp | 2 +-
3 files changed, 12 insertions(+), 7 deletions(-)
diff --git a/clang/lib/CodeGen/CGBuilder.h b/clang/lib/CodeGen/CGBuilder.h
index b8036cf6e6a30..11e8818b33397 100644
--- a/clang/lib/CodeGen/CGBuilder.h
+++ b/clang/lib/CodeGen/CGBuilder.h
@@ -223,11 +223,16 @@ class CGBuilderTy : public CGBuilderBaseTy {
const llvm::StructLayout *Layout = DL.getStructLayout(ElTy);
auto Offset = CharUnits::fromQuantity(Layout->getElementOffset(Index));
- return Address(CreateStructGEP(Addr.getElementType(), Addr.getBasePointer(),
- Index, Name),
- ElTy->getElementType(Index),
- Addr.getAlignment().alignmentAtOffset(Offset),
- Addr.isKnownNonNull());
+ // Specially, we don't add inbounds flags if the base pointer is null.
+ // This is a workaround for old-style offsetof macros.
+ llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::noUnsignedWrap();
+ if (!isa<llvm::ConstantPointerNull>(Addr.getBasePointer()))
+ NWFlags |= llvm::GEPNoWrapFlags::inBounds();
+ return Address(
+ CreateConstGEP2_32(Addr.getElementType(), Addr.getBasePointer(), 0,
+ Index, Name, NWFlags),
+ ElTy->getElementType(Index),
+ Addr.getAlignment().alignmentAtOffset(Offset), Addr.isKnownNonNull());
}
/// Given
diff --git a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.c b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.c
index 68c0ee3a3a885..a7cfd77766712 100644
--- a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.c
+++ b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.c
@@ -17,7 +17,7 @@ struct S {
// CHECK-LABEL: @get_offset_of_y_naively(
// 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 nuw ([[STRUCT_S:%.*]], ptr null, i32 0, i32 1) to i64)
//
uintptr_t get_offset_of_y_naively(void) {
return ((uintptr_t)(&(((struct S *)0)->y)));
diff --git a/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp b/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp
index 34d4f4c9e34eb..f00a2c486574c 100644
--- a/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp
+++ b/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp
@@ -10,7 +10,7 @@ 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 nuw ([[STRUCT_S:%.*]], ptr null, i32 0, i32 1) to i64)
//
uintptr_t get_offset_of_y_naively() {
return ((uintptr_t)(&(((S *)nullptr)->y)));
>From 222a6817b910ef0bfad07848400e89fed063a337 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng <dtcxzyw2333 at gmail.com>
Date: Fri, 14 Mar 2025 14:28:55 +0800
Subject: [PATCH 2/3] [Clang][CodeGen] Address review comments.
---
clang/lib/CodeGen/CGBuilder.h | 15 +++++----------
clang/lib/CodeGen/CGExpr.cpp | 27 +++++++++++++++++++--------
clang/lib/CodeGen/CodeGenFunction.h | 3 ++-
3 files changed, 26 insertions(+), 19 deletions(-)
diff --git a/clang/lib/CodeGen/CGBuilder.h b/clang/lib/CodeGen/CGBuilder.h
index 11e8818b33397..b8036cf6e6a30 100644
--- a/clang/lib/CodeGen/CGBuilder.h
+++ b/clang/lib/CodeGen/CGBuilder.h
@@ -223,16 +223,11 @@ class CGBuilderTy : public CGBuilderBaseTy {
const llvm::StructLayout *Layout = DL.getStructLayout(ElTy);
auto Offset = CharUnits::fromQuantity(Layout->getElementOffset(Index));
- // Specially, we don't add inbounds flags if the base pointer is null.
- // This is a workaround for old-style offsetof macros.
- llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::noUnsignedWrap();
- if (!isa<llvm::ConstantPointerNull>(Addr.getBasePointer()))
- NWFlags |= llvm::GEPNoWrapFlags::inBounds();
- return Address(
- CreateConstGEP2_32(Addr.getElementType(), Addr.getBasePointer(), 0,
- Index, Name, NWFlags),
- ElTy->getElementType(Index),
- Addr.getAlignment().alignmentAtOffset(Offset), Addr.isKnownNonNull());
+ return Address(CreateStructGEP(Addr.getElementType(), Addr.getBasePointer(),
+ Index, Name),
+ ElTy->getElementType(Index),
+ Addr.getAlignment().alignmentAtOffset(Offset),
+ Addr.isKnownNonNull());
}
/// Given
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 191912ca7d800..8489bc83662fb 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4738,6 +4738,10 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
}
Expr *BaseExpr = E->getBase();
+ Expr *UnderlyingBaseExpr = BaseExpr;
+ while (auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
+ UnderlyingBaseExpr = BaseMemberExpr->getBase();
+ bool IsBaseConstantNull = getContext().isSentinelNullExpr(UnderlyingBaseExpr);
// If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
LValue BaseLV;
if (E->isArrow()) {
@@ -4759,7 +4763,7 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
NamedDecl *ND = E->getMemberDecl();
if (auto *Field = dyn_cast<FieldDecl>(ND)) {
- LValue LV = EmitLValueForField(BaseLV, Field);
+ LValue LV = EmitLValueForField(BaseLV, Field, IsBaseConstantNull);
setObjCGCLValueClass(getContext(), E, LV);
if (getLangOpts().OpenMP) {
// If the member was explicitly marked as nontemporal, mark it as
@@ -4845,12 +4849,15 @@ unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
/// Get the address of a zero-sized field within a record. The resulting
/// address doesn't necessarily have the right type.
static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
- const FieldDecl *Field) {
+ const FieldDecl *Field,
+ bool IsBaseConstantNull) {
CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
CGF.getContext().getFieldOffset(Field));
if (Offset.isZero())
return Base;
Base = Base.withElementType(CGF.Int8Ty);
+ if (IsBaseConstantNull)
+ return CGF.Builder.CreateConstByteGEP(Base, Offset);
return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
}
@@ -4859,15 +4866,18 @@ static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
///
/// The resulting address doesn't necessarily have the right type.
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
- const FieldDecl *field) {
+ const FieldDecl *field,
+ bool IsBaseConstantNull) {
if (isEmptyFieldForLayout(CGF.getContext(), field))
- return emitAddrOfZeroSizeField(CGF, base, field);
+ return emitAddrOfZeroSizeField(CGF, base, field, IsBaseConstantNull);
const RecordDecl *rec = field->getParent();
unsigned idx =
CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
+ if (IsBaseConstantNull)
+ return CGF.Builder.CreateConstGEP(base, idx, field->getName());
return CGF.Builder.CreateStructGEP(base, idx, field->getName());
}
@@ -4903,8 +4913,8 @@ static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
return false;
}
-LValue CodeGenFunction::EmitLValueForField(LValue base,
- const FieldDecl *field) {
+LValue CodeGenFunction::EmitLValueForField(LValue base, const FieldDecl *field,
+ bool IsBaseConstantNull) {
LValueBaseInfo BaseInfo = base.getBaseInfo();
if (field->isBitField()) {
@@ -5036,7 +5046,7 @@ LValue CodeGenFunction::EmitLValueForField(LValue base,
if (!IsInPreservedAIRegion &&
(!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
// For structs, we GEP to the field that the record layout suggests.
- addr = emitAddrOfFieldStorage(*this, addr, field);
+ addr = emitAddrOfFieldStorage(*this, addr, field, IsBaseConstantNull);
else
// Remember the original struct field index
addr = emitPreserveStructAccess(*this, base, addr, field);
@@ -5080,7 +5090,8 @@ CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
if (!FieldType->isReferenceType())
return EmitLValueForField(Base, Field);
- Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
+ Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field,
+ /*IsBaseConstantNull=*/false);
// Make sure that the address is pointing to the right type.
llvm::Type *llvmType = ConvertTypeForMem(FieldType);
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 018fc66b72a1e..f228a2d08753e 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -4470,7 +4470,8 @@ class CodeGenFunction : public CodeGenTypeCache {
const ObjCIvarDecl *Ivar);
llvm::Value *EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar);
- LValue EmitLValueForField(LValue Base, const FieldDecl *Field);
+ LValue EmitLValueForField(LValue Base, const FieldDecl *Field,
+ bool IsBaseConstantNull = false);
LValue EmitLValueForLambdaField(const FieldDecl *Field);
LValue EmitLValueForLambdaField(const FieldDecl *Field,
llvm::Value *ThisValue);
>From 4177691c2acb35f236ffa01a0a8e299d85094d8b Mon Sep 17 00:00:00 2001
From: Yingwei Zheng <dtcxzyw2333 at gmail.com>
Date: Fri, 14 Mar 2025 15:41:22 +0800
Subject: [PATCH 3/3] [Clang][CodeGen] Add more tests.
---
clang/lib/CodeGen/CGBuilder.h | 18 ++++++++-----
clang/lib/CodeGen/CGExpr.cpp | 8 +++---
...r-and-nonzero-offset-in-offsetof-idiom.cpp | 26 +++++++++++++++++++
3 files changed, 43 insertions(+), 9 deletions(-)
diff --git a/clang/lib/CodeGen/CGBuilder.h b/clang/lib/CodeGen/CGBuilder.h
index b8036cf6e6a30..88ec55b322cf5 100644
--- a/clang/lib/CodeGen/CGBuilder.h
+++ b/clang/lib/CodeGen/CGBuilder.h
@@ -215,19 +215,25 @@ class CGBuilderTy : public CGBuilderBaseTy {
///
/// This API assumes that drilling into a struct like this is always an
/// inbounds and nuw operation.
+ /// Specifically, inbounds flag will not be set if \p IsBaseConstantNull is
+ /// true.
using CGBuilderBaseTy::CreateStructGEP;
Address CreateStructGEP(Address Addr, unsigned Index,
- const llvm::Twine &Name = "") {
+ const llvm::Twine &Name = "",
+ bool IsBaseConstantNull = false) {
llvm::StructType *ElTy = cast<llvm::StructType>(Addr.getElementType());
const llvm::DataLayout &DL = BB->getDataLayout();
const llvm::StructLayout *Layout = DL.getStructLayout(ElTy);
auto Offset = CharUnits::fromQuantity(Layout->getElementOffset(Index));
- return Address(CreateStructGEP(Addr.getElementType(), Addr.getBasePointer(),
- Index, Name),
- ElTy->getElementType(Index),
- Addr.getAlignment().alignmentAtOffset(Offset),
- Addr.isKnownNonNull());
+ llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::noUnsignedWrap();
+ if (!IsBaseConstantNull)
+ NWFlags |= llvm::GEPNoWrapFlags::inBounds();
+ return Address(
+ CreateConstGEP2_32(Addr.getElementType(), Addr.getBasePointer(), 0,
+ Index, Name, NWFlags),
+ ElTy->getElementType(Index),
+ Addr.getAlignment().alignmentAtOffset(Offset), Addr.isKnownNonNull());
}
/// Given
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 8489bc83662fb..2ee2e873347d5 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -4738,6 +4738,9 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
}
Expr *BaseExpr = E->getBase();
+ // Check whether the underlying base pointer is a constant null.
+ // If so, we do not set inbounds flag for GEP to avoid breaking some old-style
+ // offsetof idioms.
Expr *UnderlyingBaseExpr = BaseExpr;
while (auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
UnderlyingBaseExpr = BaseMemberExpr->getBase();
@@ -4876,9 +4879,8 @@ static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
unsigned idx =
CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
- if (IsBaseConstantNull)
- return CGF.Builder.CreateConstGEP(base, idx, field->getName());
- return CGF.Builder.CreateStructGEP(base, idx, field->getName());
+ return CGF.Builder.CreateStructGEP(base, idx, field->getName(),
+ IsBaseConstantNull);
}
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
diff --git a/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp b/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp
index f00a2c486574c..ac45d2e0da4fc 100644
--- a/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp
+++ b/clang/test/CodeGenCXX/catch-nullptr-and-nonzero-offset-in-offsetof-idiom.cpp
@@ -16,6 +16,32 @@ 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 nuw ([[STRUCT_S:%.*]], ptr getelementptr nuw ([[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)));
+}
+
+// CHECK-LABEL: @_Z26get_offset_of_zero_storagev(
+// CHECK-NEXT: entry:
+// CHECK-NEXT: ret i64 ptrtoint (ptr getelementptr (i8, ptr null, i64 16) to i64)
+//
+uintptr_t get_offset_of_zero_storage() {
+ return ((uintptr_t)(&(((T *)nullptr)->e2)));
+}
+
// CHECK-LABEL: @_Z27get_offset_of_y_via_builtinv(
// CHECK-NEXT: entry:
// CHECK-NEXT: ret i64 4
More information about the cfe-commits
mailing list