[clang] [clang] Add __builtin_is_pointer_interconvertible_with_class and __builtin_is_corresponding_member (PR #246911)
via cfe-commits
cfe-commits at lists.llvm.org
Sun Nov 29 14:44:47 PST 2026
https://github.com/edtice-goog updated https://github.com/llvm/llvm-project/pull/246911
>From 3f7bd245a154b23654b1995faa33d607a2f95c57 Mon Sep 17 00:00:00 2001
From: Ed Tice <edtice at gmail.com>
Date: Sat, 28 Nov 2026 20:19:34 -0500
Subject: [PATCH 1/2] [clang][NFC] Move isLayoutCompatible from Sema to
ASTContext
Sema::IsLayoutCompatible and its helpers are only usable from Sema. Move
them unchanged into ASTContext, as ASTContext::isLayoutCompatible, so that
the AST library (the constant evaluators) can check layout compatibility,
which the P0466R5 traits std::is_corresponding_member and
std::is_pointer_interconvertible_with_class need.
Sema::IsLayoutCompatible remains and forwards to the new function.
Co-Authored-By: Claude Opus 5.5 <noreply at anthropic.com>
---
clang/include/clang/AST/ASTContext.h | 4 +
clang/lib/AST/ASTContext.cpp | 146 ++++++++++++++++++++++++++
clang/lib/Sema/SemaChecking.cpp | 151 +--------------------------
3 files changed, 154 insertions(+), 147 deletions(-)
diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index 9ad16898b32563..c6a56ad7772850 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -3181,6 +3181,10 @@ class ASTContext : public RefCountedBase<ASTContext> {
/// those qualifiers are also ignored in the 'similarity' check.
bool hasSimilarType(QualType T1, QualType T2) const;
+ /// Determine whether two types are layout-compatible
+ /// ([basic.types.general]).
+ bool isLayoutCompatible(QualType T1, QualType T2) const;
+
/// Determine if two types are similar, ignoring only CVR qualifiers.
bool hasCvrSimilarType(QualType T1, QualType T2);
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 3c46873c41359f..bea723bcfa6954 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -7305,6 +7305,152 @@ bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
return false;
}
+//===--- Layout compatibility ----------------------------------------------//
+
+static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
+
+/// Check if two enumeration types are layout-compatible.
+static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
+ const EnumDecl *ED2) {
+ // C++11 [dcl.enum] p8:
+ // Two enumeration types are layout-compatible if they have the same
+ // underlying type.
+ return ED1->isComplete() && ED2->isComplete() &&
+ C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
+}
+
+/// Check if two fields are layout-compatible.
+/// Can be used on union members, which are exempt from alignment requirement
+/// of common initial sequence.
+static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
+ const FieldDecl *Field2,
+ bool AreUnionMembers = false) {
+#ifndef NDEBUG
+ CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
+ CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
+ assert(((Field1Parent->isStructureOrClassType() &&
+ Field2Parent->isStructureOrClassType()) ||
+ (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
+ "Can't evaluate layout compatibility between a struct field and a "
+ "union field.");
+ assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
+ (AreUnionMembers && Field1Parent->isUnionType())) &&
+ "AreUnionMembers should be 'true' for union fields (only).");
+#endif
+
+ if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
+ return false;
+
+ if (Field1->isBitField() != Field2->isBitField())
+ return false;
+
+ if (Field1->isBitField()) {
+ // Make sure that the bit-fields are the same length.
+ unsigned Bits1 = Field1->getBitWidthValue();
+ unsigned Bits2 = Field2->getBitWidthValue();
+
+ if (Bits1 != Bits2)
+ return false;
+ }
+
+ if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
+ Field2->hasAttr<clang::NoUniqueAddressAttr>())
+ return false;
+
+ if (!AreUnionMembers &&
+ Field1->getMaxAlignment() != Field2->getMaxAlignment())
+ return false;
+
+ return true;
+}
+
+/// Check if two standard-layout structs are layout-compatible.
+/// (C++11 [class.mem] p17)
+static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
+ const RecordDecl *RD2) {
+ // Get to the class where the fields are declared
+ if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
+ RD1 = D1CXX->getStandardLayoutBaseWithFields();
+
+ if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
+ RD2 = D2CXX->getStandardLayoutBaseWithFields();
+
+ // Check the fields.
+ return llvm::equal(RD1->fields(), RD2->fields(),
+ [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
+ return isLayoutCompatible(C, F1, F2);
+ });
+}
+
+/// Check if two standard-layout unions are layout-compatible.
+/// (C++11 [class.mem] p18)
+static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
+ const RecordDecl *RD2) {
+ llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
+ RD2->fields());
+
+ for (auto *Field1 : RD1->fields()) {
+ auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
+ return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
+ });
+ if (It == UnmatchedFields.end())
+ return false;
+ [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
+ assert(Result);
+ }
+
+ return UnmatchedFields.empty();
+}
+
+static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
+ const RecordDecl *RD2) {
+ if (RD1->isUnion() != RD2->isUnion())
+ return false;
+
+ if (RD1->isUnion())
+ return isLayoutCompatibleUnion(C, RD1, RD2);
+ else
+ return isLayoutCompatibleStruct(C, RD1, RD2);
+}
+
+/// Check if two types are layout-compatible in C++11 sense.
+static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
+ if (T1.isNull() || T2.isNull())
+ return false;
+
+ // C++20 [basic.types] p11:
+ // Two types cv1 T1 and cv2 T2 are layout-compatible types
+ // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
+ // or layout-compatible standard-layout class types (11.4).
+ T1 = T1.getCanonicalType().getUnqualifiedType();
+ T2 = T2.getCanonicalType().getUnqualifiedType();
+
+ if (C.hasSameType(T1, T2))
+ return true;
+
+ const Type::TypeClass TC1 = T1->getTypeClass();
+ const Type::TypeClass TC2 = T2->getTypeClass();
+
+ if (TC1 != TC2)
+ return false;
+
+ if (TC1 == Type::Enum)
+ return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
+ if (TC1 == Type::Record) {
+ if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
+ return false;
+
+ return isLayoutCompatible(C, T1->castAsRecordDecl(),
+ T2->castAsRecordDecl());
+ }
+
+ return false;
+}
+
+bool ASTContext::isLayoutCompatible(QualType T1, QualType T2) const {
+ return ::isLayoutCompatible(*this, T1, T2);
+}
+
bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
while (true) {
Qualifiers Quals;
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ccb303624182f2..ff03f39d9b7fab 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -16795,150 +16795,8 @@ void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
<< RHSExpr->getSourceRange();
}
-//===--- Layout compatibility ----------------------------------------------//
-
-static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
-
-/// Check if two enumeration types are layout-compatible.
-static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
- const EnumDecl *ED2) {
- // C++11 [dcl.enum] p8:
- // Two enumeration types are layout-compatible if they have the same
- // underlying type.
- return ED1->isComplete() && ED2->isComplete() &&
- C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
-}
-
-/// Check if two fields are layout-compatible.
-/// Can be used on union members, which are exempt from alignment requirement
-/// of common initial sequence.
-static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
- const FieldDecl *Field2,
- bool AreUnionMembers = false) {
-#ifndef NDEBUG
- CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
- CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
- assert(((Field1Parent->isStructureOrClassType() &&
- Field2Parent->isStructureOrClassType()) ||
- (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
- "Can't evaluate layout compatibility between a struct field and a "
- "union field.");
- assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
- (AreUnionMembers && Field1Parent->isUnionType())) &&
- "AreUnionMembers should be 'true' for union fields (only).");
-#endif
-
- if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
- return false;
-
- if (Field1->isBitField() != Field2->isBitField())
- return false;
-
- if (Field1->isBitField()) {
- // Make sure that the bit-fields are the same length.
- unsigned Bits1 = Field1->getBitWidthValue();
- unsigned Bits2 = Field2->getBitWidthValue();
-
- if (Bits1 != Bits2)
- return false;
- }
-
- if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
- Field2->hasAttr<clang::NoUniqueAddressAttr>())
- return false;
-
- if (!AreUnionMembers &&
- Field1->getMaxAlignment() != Field2->getMaxAlignment())
- return false;
-
- return true;
-}
-
-/// Check if two standard-layout structs are layout-compatible.
-/// (C++11 [class.mem] p17)
-static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
- const RecordDecl *RD2) {
- // Get to the class where the fields are declared
- if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
- RD1 = D1CXX->getStandardLayoutBaseWithFields();
-
- if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
- RD2 = D2CXX->getStandardLayoutBaseWithFields();
-
- // Check the fields.
- return llvm::equal(RD1->fields(), RD2->fields(),
- [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
- return isLayoutCompatible(C, F1, F2);
- });
-}
-
-/// Check if two standard-layout unions are layout-compatible.
-/// (C++11 [class.mem] p18)
-static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
- const RecordDecl *RD2) {
- llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
- RD2->fields());
-
- for (auto *Field1 : RD1->fields()) {
- auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
- return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
- });
- if (It == UnmatchedFields.end())
- return false;
- [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
- assert(Result);
- }
-
- return UnmatchedFields.empty();
-}
-
-static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
- const RecordDecl *RD2) {
- if (RD1->isUnion() != RD2->isUnion())
- return false;
-
- if (RD1->isUnion())
- return isLayoutCompatibleUnion(C, RD1, RD2);
- else
- return isLayoutCompatibleStruct(C, RD1, RD2);
-}
-
-/// Check if two types are layout-compatible in C++11 sense.
-static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
- if (T1.isNull() || T2.isNull())
- return false;
-
- // C++20 [basic.types] p11:
- // Two types cv1 T1 and cv2 T2 are layout-compatible types
- // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
- // or layout-compatible standard-layout class types (11.4).
- T1 = T1.getCanonicalType().getUnqualifiedType();
- T2 = T2.getCanonicalType().getUnqualifiedType();
-
- if (C.hasSameType(T1, T2))
- return true;
-
- const Type::TypeClass TC1 = T1->getTypeClass();
- const Type::TypeClass TC2 = T2->getTypeClass();
-
- if (TC1 != TC2)
- return false;
-
- if (TC1 == Type::Enum)
- return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
- if (TC1 == Type::Record) {
- if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
- return false;
-
- return isLayoutCompatible(C, T1->castAsRecordDecl(),
- T2->castAsRecordDecl());
- }
-
- return false;
-}
-
bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
- return isLayoutCompatible(getASTContext(), T1, T2);
+ return getASTContext().isLayoutCompatible(T1, T2);
}
//===-------------- Pointer interconvertibility ----------------------------//
@@ -17211,11 +17069,10 @@ void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
mismatch = false;
} else
if (IsPointerAttr)
- mismatch = !isLayoutCompatible(Context,
- ArgumentType->getPointeeType(),
- RequiredType->getPointeeType());
+ mismatch = !Context.isLayoutCompatible(ArgumentType->getPointeeType(),
+ RequiredType->getPointeeType());
else
- mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
+ mismatch = !Context.isLayoutCompatible(ArgumentType, RequiredType);
if (mismatch)
Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
>From e419f84220d991f59fa2db078040dfb13383808d Mon Sep 17 00:00:00 2001
From: Ed Tice <edtice at gmail.com>
Date: Sat, 28 Nov 2026 20:53:41 -0500
Subject: [PATCH 2/2] [clang] Add
__builtin_is_pointer_interconvertible_with_class and
__builtin_is_corresponding_member
P0466R5 added std::is_pointer_interconvertible_with_class and
std::is_corresponding_member, which a standard library cannot implement
without compiler support. GCC provides
__builtin_is_pointer_interconvertible_with_class(m) and
__builtin_is_corresponding_member(m1, m2), which libstdc++ uses. Clang now
provides both, with the same spelling and semantics.
The class that each trait checks is the class in the type of the pointer to
member, which must be complete. The constant evaluator and the bytecode
interpreter share ASTContext::isPointerInterconvertibleWithClass and
isCorrespondingMember, which follow [meta.member], [basic.compound] and
[class.mem.general]. Corresponding members must also be at the same offset
with the same alignment, which takes #pragma pack and over-aligned typedefs
into account. Where the standard leaves a question open, they follow GCC: an
unnamed bit-field counts as a first member, and a member of an anonymous
struct corresponds to the member at the same position in an anonymous struct
at the same position. A member of an anonymous union does not correspond to
any member (GCC rejects that case), and unlike GCC, a union that is not
standard-layout is not pointer-interconvertible with its members, as
[meta.member] requires.
At run time, CodeGen computes the offsets of the members that the trait
accepts and compares the pointer with a pointer to member at each of them,
using the C++ ABI's constants and comparison, so the builtins work for the
Itanium and Microsoft ABIs and every Microsoft inheritance model.
Addresses #100013.
Co-Authored-By: Claude Opus 5.5 <noreply at anthropic.com>
---
clang/docs/LanguageExtensions.md | 26 ++
clang/docs/ReleaseNotes.md | 5 +
clang/include/clang/AST/ASTContext.h | 14 +
clang/include/clang/Basic/Builtins.td | 12 +
.../clang/Basic/DiagnosticSemaKinds.td | 2 +
clang/lib/AST/ASTContext.cpp | 122 ++++++++
clang/lib/AST/ByteCode/InterpBuiltin.cpp | 28 ++
clang/lib/AST/ExprConstant.cpp | 25 ++
clang/lib/CodeGen/CGBuiltin.cpp | 115 +++++++
clang/lib/Sema/SemaChecking.cpp | 34 ++
...uiltin-pointer-interconvertible-traits.cpp | 159 ++++++++++
...uiltin-pointer-interconvertible-traits.cpp | 295 ++++++++++++++++++
12 files changed, 837 insertions(+)
create mode 100644 clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp
create mode 100644 clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp
diff --git a/clang/docs/LanguageExtensions.md b/clang/docs/LanguageExtensions.md
index a4c7c2ddca5070..df290de2abce9f 100644
--- a/clang/docs/LanguageExtensions.md
+++ b/clang/docs/LanguageExtensions.md
@@ -2200,6 +2200,32 @@ static_assert(__builtin_structured_binding_size(S) == 2);
static_assert(get_binding<1>(S{}) == 42);
```
+### `__builtin_is_pointer_interconvertible_with_class` and `__builtin_is_corresponding_member` (C++)
+
+`__builtin_is_pointer_interconvertible_with_class(m)` and
+`__builtin_is_corresponding_member(m1, m2)` take pointers to members and return
+what `std::is_pointer_interconvertible_with_class` and
+`std::is_corresponding_member` ([meta.member]) return for them. The class that
+each trait checks is the class in the type of the pointer to member, which must
+be complete. GCC provides the same builtins.
+
+```c++
+struct A { int x; int y; };
+struct B { int p; int q; };
+static_assert(__builtin_is_pointer_interconvertible_with_class(&A::x));
+static_assert(!__builtin_is_pointer_interconvertible_with_class(&A::y));
+static_assert(__builtin_is_corresponding_member(&A::y, &B::q));
+```
+
+Both builtins can be used in constant expressions and at run time. Where the
+standard leaves a question open, they follow GCC: an unnamed bit-field counts
+as a first member, and a member of an anonymous struct corresponds to the
+member at the same position in an anonymous struct at the same position in the
+other class, if both are in the common initial sequence of those anonymous
+structs. A member of an anonymous union does not correspond to any member (GCC
+rejects that case), and a union that is not standard-layout is not
+pointer-interconvertible with its members (GCC says it is).
+
## Blocks
The syntax and high-level language feature description is in
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 6bbc910d86b5aa..0f1d4490b4aadf 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -309,6 +309,11 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
#### C++20 Feature Support
+- Added `__builtin_is_pointer_interconvertible_with_class` and
+ `__builtin_is_corresponding_member`, with GCC's spelling and semantics, for
+ standard libraries to implement `std::is_pointer_interconvertible_with_class`
+ and `std::is_corresponding_member` from P0466R5. (#GH100013)
+
- Now clang-scan-deps in P1689 format can find the dependencies described in
module map file. See the documents of standard C++ modules for details.
diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index c6a56ad7772850..fe96f1297cc395 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -3185,6 +3185,20 @@ class ASTContext : public RefCountedBase<ASTContext> {
/// ([basic.types.general]).
bool isLayoutCompatible(QualType T1, QualType T2) const;
+ /// Determine whether a pointer to member of \p RD that points to \p Member
+ /// (null for a null pointer) is pointer-interconvertible with its class, as
+ /// std::is_pointer_interconvertible_with_class determines ([meta.member]).
+ bool isPointerInterconvertibleWithClass(const CXXRecordDecl *RD,
+ const ValueDecl *Member) const;
+
+ /// Determine whether pointers to members of \p RD1 and \p RD2 that point
+ /// to \p Member1 and \p Member2 (null for null pointers) point to
+ /// corresponding members of the common initial sequence of the classes, as
+ /// std::is_corresponding_member determines ([meta.member]).
+ bool isCorrespondingMember(const CXXRecordDecl *RD1, const ValueDecl *Member1,
+ const CXXRecordDecl *RD2,
+ const ValueDecl *Member2) const;
+
/// Determine if two types are similar, ignoring only CVR qualifiers.
bool hasCvrSimilarType(QualType T1, QualType T2);
diff --git a/clang/include/clang/Basic/Builtins.td b/clang/include/clang/Basic/Builtins.td
index 820123e8f6a0f4..1107757f6a34cd 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1259,6 +1259,18 @@ def IsWithinLifetime : LangBuiltin<"CXX_LANG"> {
let Prototype = "bool(void*)";
}
+def IsPointerInterconvertibleWithClass : LangBuiltin<"CXX_LANG"> {
+ let Spellings = ["__builtin_is_pointer_interconvertible_with_class"];
+ let Attributes = [NoThrow, Const, CustomTypeChecking, Constexpr];
+ let Prototype = "bool(...)";
+}
+
+def IsCorrespondingMember : LangBuiltin<"CXX_LANG"> {
+ let Spellings = ["__builtin_is_corresponding_member"];
+ let Attributes = [NoThrow, Const, CustomTypeChecking, Constexpr];
+ let Prototype = "bool(...)";
+}
+
def ClearPadding : Builtin {
let Spellings = ["__builtin_clear_padding"];
let Attributes = [NoThrow, CustomTypeChecking];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 2ae80dc3223501..50f456b6216bac 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -13567,6 +13567,8 @@ def err_builtin_assume_aligned_invalid_arg : Error<
def err_builtin_is_within_lifetime_invalid_arg : Error<
"%select{non-|function }0pointer argument to '__builtin_is_within_lifetime' "
"is not allowed">;
+def err_builtin_member_pointer_trait_arg : Error<
+ "argument to %0 must be a pointer to member, not %1">;
// A multi-component builtin type diagnostic. The first component broadly
// selects a scalar or container type (scalar, vector or matrix). The second
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index bea723bcfa6954..d8b6e07a3271d0 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -7451,6 +7451,128 @@ bool ASTContext::isLayoutCompatible(QualType T1, QualType T2) const {
return ::isLayoutCompatible(*this, T1, T2);
}
+//===--- Pointer-interconvertibility and corresponding members -----------===//
+
+/// The fields from the class of a pointer to member down to the member \p M:
+/// one field, or for a member of an anonymous struct or union, the chain of
+/// anonymous members that leads to it. Empty if \p M is not a data member.
+static SmallVector<const FieldDecl *, 4> getFieldChain(const ValueDecl *M) {
+ SmallVector<const FieldDecl *, 4> Chain;
+ if (const auto *FD = dyn_cast_or_null<FieldDecl>(M))
+ Chain.push_back(FD);
+ else if (const auto *IFD = dyn_cast_or_null<IndirectFieldDecl>(M))
+ for (const NamedDecl *ND : IFD->chain())
+ Chain.push_back(cast<FieldDecl>(ND));
+ return Chain;
+}
+
+bool ASTContext::isPointerInterconvertibleWithClass(
+ const CXXRecordDecl *RD, const ValueDecl *Member) const {
+ // C++20 [meta.member]p2: true if S is a standard-layout type, M is an object
+ // type, m is not null, and each object s of type S is
+ // pointer-interconvertible with its subobject s.*m.
+ RD = RD ? RD->getDefinition() : nullptr;
+ SmallVector<const FieldDecl *, 4> Chain = getFieldChain(Member);
+ if (!RD || RD->isInvalidDecl() || !RD->isStandardLayout() || Chain.empty())
+ return false;
+
+ // The data members of a standard-layout class are all declared in one class,
+ // which is RD or one of its bases.
+ if (Chain.front()->getParent()->getCanonicalDecl() !=
+ RD->getStandardLayoutBaseWithFields()->getCanonicalDecl())
+ return false;
+
+ // [basic.compound]p4: a union is pointer-interconvertible with each of its
+ // members, a standard-layout struct with its first member, and the relation
+ // is transitive, so each field in the chain must be one of those. An unnamed
+ // bit-field is not a member, but like GCC, treat it as coming first.
+ for (const FieldDecl *FD : Chain) {
+ const RecordDecl *Parent = FD->getParent();
+ if (!Parent->isUnion() && *Parent->field_begin() != FD)
+ return false;
+ }
+ return true;
+}
+
+/// Whether \p F1 and \p F2 are at the same offset in their classes, with the
+/// same [[no_unique_address]] attribute.
+static bool haveSamePlacement(const ASTContext &C, const FieldDecl *F1,
+ const FieldDecl *F2) {
+ return F1->hasAttr<NoUniqueAddressAttr>() ==
+ F2->hasAttr<NoUniqueAddressAttr>() &&
+ C.getFieldOffset(F1) == C.getFieldOffset(F2);
+}
+
+/// Whether \p F1 and \p F2 are corresponding entities in the common initial
+/// sequence of two standard-layout structs ([class.mem.general]p23).
+static bool areCorrespondingFields(const ASTContext &C, const FieldDecl *F1,
+ const FieldDecl *F2) {
+ if (!C.isLayoutCompatible(F1->getType(), F2->getType()))
+ return false;
+ if (F1->isBitField() != F2->isBitField())
+ return false;
+ if (F1->isBitField() && F1->getBitWidthValue() != F2->getBitWidthValue())
+ return false;
+ // C++23 [class.mem.general]p23 also requires the same alignment. The
+ // offsets are compared as well, so that #pragma pack and over-aligned
+ // typedefs, which the types do not show, are taken into account.
+ return haveSamePlacement(C, F1, F2) &&
+ C.getDeclAlign(F1) == C.getDeclAlign(F2);
+}
+
+/// Whether the members at the end of \p Chain1 and \p Chain2 correspond in the
+/// common initial sequence of the structs \p RD1 and \p RD2, whose fields are
+/// the first entries of the chains.
+static bool areCorrespondingMembers(const ASTContext &C, const RecordDecl *RD1,
+ ArrayRef<const FieldDecl *> Chain1,
+ const RecordDecl *RD2,
+ ArrayRef<const FieldDecl *> Chain2) {
+ for (auto I1 = RD1->field_begin(), E1 = RD1->field_end(),
+ I2 = RD2->field_begin(), E2 = RD2->field_end();
+ I1 != E1 && I2 != E2; ++I1, ++I2) {
+ bool Corresponding = areCorrespondingFields(C, *I1, *I2);
+ if (*I1 != Chain1.front() || *I2 != Chain2.front()) {
+ if (!Corresponding)
+ return false;
+ continue;
+ }
+ if (Chain1.size() == 1 && Chain2.size() == 1)
+ return Corresponding;
+ // Both members are in anonymous structs at the same position. As GCC
+ // does, look for them in the common initial sequence of those structs,
+ // even if the structs differ after it. Members of anonymous unions have
+ // no defined correspondence.
+ const RecordDecl *Anon1 = (*I1)->getType()->getAsRecordDecl();
+ const RecordDecl *Anon2 = (*I2)->getType()->getAsRecordDecl();
+ if (Chain1.size() == 1 || Chain2.size() == 1 || Anon1->isUnion() ||
+ Anon2->isUnion() || !haveSamePlacement(C, *I1, *I2))
+ return false;
+ return areCorrespondingMembers(C, Anon1, Chain1.drop_front(), Anon2,
+ Chain2.drop_front());
+ }
+ return false;
+}
+
+bool ASTContext::isCorrespondingMember(const CXXRecordDecl *RD1,
+ const ValueDecl *Member1,
+ const CXXRecordDecl *RD2,
+ const ValueDecl *Member2) const {
+ // C++20 [meta.member]p5: true if S1 and S2 are standard-layout struct types,
+ // M1 and M2 are object types, m1 and m2 are not null, and m1 and m2 point to
+ // corresponding members of the common initial sequence of S1 and S2.
+ RD1 = RD1 ? RD1->getDefinition() : nullptr;
+ RD2 = RD2 ? RD2->getDefinition() : nullptr;
+ SmallVector<const FieldDecl *, 4> Chain1 = getFieldChain(Member1);
+ SmallVector<const FieldDecl *, 4> Chain2 = getFieldChain(Member2);
+ if (!RD1 || !RD2 || RD1->isInvalidDecl() || RD2->isInvalidDecl() ||
+ RD1->isUnion() || RD2->isUnion() || !RD1->isStandardLayout() ||
+ !RD2->isStandardLayout() || Chain1.empty() || Chain2.empty())
+ return false;
+ return areCorrespondingMembers(*this, RD1->getStandardLayoutBaseWithFields(),
+ Chain1, RD2->getStandardLayoutBaseWithFields(),
+ Chain2);
+}
+
bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
while (true) {
Qualifiers Quals;
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 35c0eba31ef830..c1dc42ddec8092 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -2668,6 +2668,30 @@ static bool interp__builtin_is_within_lifetime(InterpState &S, CodePtr OpPC,
return true;
}
+static bool interp__builtin_member_pointer_trait(InterpState &S, CodePtr OpPC,
+ const CallExpr *Call) {
+ const CXXRecordDecl *Classes[2] = {};
+ const ValueDecl *Members[2] = {};
+ for (unsigned I = Call->getNumArgs(); I != 0; --I) {
+ MemberPointer MP = S.Stk.pop<MemberPointer>();
+ Classes[I - 1] = Call->getArg(I - 1)
+ ->getType()
+ ->castAs<MemberPointerType>()
+ ->getMostRecentCXXRecordDecl();
+ // After a cast to a pointer to member of a base class, the member is one
+ // of a derived class, not one of the pointer's class.
+ Members[I - 1] = MP.isDerivedMember() ? nullptr : MP.getDecl();
+ }
+ const ASTContext &Ctx = S.getASTContext();
+ bool Result =
+ Call->getBuiltinCallee() == Builtin::BI__builtin_is_corresponding_member
+ ? Ctx.isCorrespondingMember(Classes[0], Members[0], Classes[1],
+ Members[1])
+ : Ctx.isPointerInterconvertibleWithClass(Classes[0], Members[0]);
+ pushInteger(S, Result, Call->getType());
+ return true;
+}
+
static bool interp__builtin_elementwise_int_unaryop(
InterpState &S, CodePtr OpPC, const CallExpr *Call,
llvm::function_ref<APInt(const APSInt &)> Fn) {
@@ -5628,6 +5652,10 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const CallExpr *Call,
case Builtin::BI__builtin_is_within_lifetime:
return interp__builtin_is_within_lifetime(S, OpPC, Call);
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ case Builtin::BI__builtin_is_corresponding_member:
+ return interp__builtin_member_pointer_trait(S, OpPC, Call);
+
case Builtin::BI__builtin_elementwise_add_sat:
return interp__builtin_elementwise_int_binop(
S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 3ead1325191ea1..5cb40f086e4ab1 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -17650,6 +17650,31 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
return Success(*result, E);
return false;
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ case Builtin::BI__builtin_is_corresponding_member: {
+ const CXXRecordDecl *Classes[2] = {};
+ const ValueDecl *Members[2] = {};
+ for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
+ Classes[I] = E->getArg(I)
+ ->getType()
+ ->castAs<MemberPointerType>()
+ ->getMostRecentCXXRecordDecl();
+ MemberPtr MP;
+ if (!EvaluateMemberPointer(E->getArg(I), MP, Info))
+ return false;
+ // After a cast to a pointer to member of a base class, the member is
+ // one of a derived class, not one of the pointer's class.
+ Members[I] = MP.isDerivedMember() ? nullptr : MP.getDecl();
+ }
+ const ASTContext &Ctx = Info.Ctx;
+ if (BuiltinOp == Builtin::BI__builtin_is_corresponding_member)
+ return Success(Ctx.isCorrespondingMember(Classes[0], Members[0],
+ Classes[1], Members[1]),
+ E);
+ return Success(
+ Ctx.isPointerInterconvertibleWithClass(Classes[0], Members[0]), E);
+ }
+
case Builtin::BI__builtin_ctz:
case Builtin::BI__builtin_ctzl:
case Builtin::BI__builtin_ctzll:
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 0b28bc9f43d5d3..13c8a2669075ad 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -2773,6 +2773,116 @@ static void ClearPadding(CodeGenFunction &CGF, Address Src,
}
}
+/// __builtin_is_pointer_interconvertible_with_class and
+/// __builtin_is_corresponding_member on pointers to members that are not
+/// constants: compare each pointer with the members the trait accepts.
+static RValue emitMemberPointerTrait(CodeGenFunction &CGF, const CallExpr *E,
+ bool Corresponding) {
+ ASTContext &Ctx = CGF.getContext();
+ unsigned N = Corresponding ? 2 : 1;
+ const MemberPointerType *Types[2] = {};
+ const CXXRecordDecl *Classes[2] = {};
+ llvm::Value *Values[2] = {};
+ for (unsigned I = 0; I != N; ++I) {
+ Types[I] = E->getArg(I)->getType()->castAs<MemberPointerType>();
+ Classes[I] = Types[I]->getMostRecentCXXRecordDecl()->getDefinition();
+ Values[I] = CGF.EmitScalarExpr(E->getArg(I));
+ }
+
+ // The data members that a pointer of the I'th type can point to, with
+ // their offsets in the class: the named, non-bit-field members of the
+ // class's standard-layout base with fields, including those of its
+ // anonymous structs and unions.
+ using Candidate = std::pair<const ValueDecl *, CharUnits>;
+ auto Candidates = [&](unsigned I) {
+ SmallVector<Candidate, 8> Out;
+ const CXXRecordDecl *RD = Classes[I];
+ if (!Types[I]->isMemberDataPointer() || !RD || RD->isInvalidDecl() ||
+ !RD->isStandardLayout())
+ return Out;
+ // The offset of the base with fields. A standard-layout class has no
+ // virtual bases and at most one base subobject of each type.
+ const CXXRecordDecl *Owner = RD->getStandardLayoutBaseWithFields();
+ CharUnits BaseOffset = CharUnits::Zero();
+ for (const CXXRecordDecl *Cur = RD;
+ Cur->getCanonicalDecl() != Owner->getCanonicalDecl();) {
+ for (const CXXBaseSpecifier &BS : Cur->bases()) {
+ const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
+ if (Base->getCanonicalDecl() == Owner->getCanonicalDecl() ||
+ Base->isDerivedFrom(Owner)) {
+ BaseOffset += Ctx.getASTRecordLayout(Cur).getBaseClassOffset(Base);
+ Cur = Base;
+ break;
+ }
+ }
+ }
+ QualType Pointee = Types[I]->getPointeeType();
+ for (const Decl *D : Owner->decls()) {
+ const FieldDecl *FD = nullptr;
+ if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
+ FD = IFD->getAnonField();
+ else if ((FD = dyn_cast<FieldDecl>(D)) && !FD->getDeclName())
+ continue;
+ if (FD && !FD->isBitField() &&
+ Ctx.hasSameUnqualifiedType(FD->getType(), Pointee)) {
+ const auto *VD = cast<ValueDecl>(D);
+ Out.push_back(
+ {VD, BaseOffset + Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(VD))});
+ }
+ }
+ return Out;
+ };
+ // Whether the I'th pointer points to the member at Offset.
+ CGCXXABI &ABI = CGF.CGM.getCXXABI();
+ auto PointsTo = [&](unsigned I, CharUnits Offset) {
+ llvm::Constant *MP = ABI.EmitMemberDataPointer(Types[I], Offset);
+ return ABI.EmitMemberPointerComparison(CGF, Values[I], MP, Types[I],
+ /*Inequality=*/false);
+ };
+ llvm::Value *Result = nullptr;
+ auto Add = [&](llvm::Value *V) {
+ Result = Result ? CGF.Builder.CreateOr(Result, V) : V;
+ };
+
+ // Members at the same offset have the same pointer to member value, so
+ // compare with each offset once.
+ SmallVector<Candidate, 8> C0 = Candidates(0);
+ if (!Corresponding) {
+ llvm::SmallDenseSet<int64_t, 8> Seen;
+ for (auto [D, Offset] : C0)
+ if (Ctx.isPointerInterconvertibleWithClass(Classes[0], D) &&
+ Seen.insert(Offset.getQuantity()).second)
+ Add(PointsTo(0, Offset));
+ return RValue::get(Result ? Result : CGF.Builder.getFalse());
+ }
+ // Corresponding members have the same field indices, down any chain of
+ // anonymous members.
+ auto Position = [](const ValueDecl *D) {
+ SmallVector<unsigned, 4> Pos;
+ if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
+ for (const NamedDecl *ND : IFD->chain())
+ Pos.push_back(cast<FieldDecl>(ND)->getFieldIndex());
+ else
+ Pos.push_back(cast<FieldDecl>(D)->getFieldIndex());
+ return Pos;
+ };
+ SmallVector<Candidate, 8> C1 = Candidates(1);
+ llvm::SmallDenseSet<std::pair<int64_t, int64_t>, 8> Seen;
+ for (auto [D0, Offset0] : C0) {
+ SmallVector<unsigned, 4> Pos = Position(D0);
+ for (auto [D1, Offset1] : C1) {
+ if (Position(D1) != Pos ||
+ !Ctx.isCorrespondingMember(Classes[0], D0, Classes[1], D1) ||
+ !Seen.insert({Offset0.getQuantity(), Offset1.getQuantity()}).second)
+ continue;
+ llvm::Value *Points0 = PointsTo(0, Offset0);
+ llvm::Value *Points1 = PointsTo(1, Offset1);
+ Add(CGF.Builder.CreateAnd(Points0, Points1));
+ }
+ }
+ return RValue::get(Result ? Result : CGF.Builder.getFalse());
+}
+
RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
const CallExpr *E,
ReturnValueSlot ReturnValue) {
@@ -6094,6 +6204,11 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
return RValue::get(nullptr);
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ case Builtin::BI__builtin_is_corresponding_member:
+ return emitMemberPointerTrait(
+ *this, E, BuiltinID == Builtin::BI__builtin_is_corresponding_member);
+
case Builtin::BI__builtin_is_aligned:
return EmitBuiltinIsAligned(E);
case Builtin::BI__builtin_align_up:
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index ff03f39d9b7fab..ce29413b9ef2a1 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -2347,6 +2347,36 @@ static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
return TheCall;
}
+/// Check a call to __builtin_is_pointer_interconvertible_with_class (one
+/// argument) or __builtin_is_corresponding_member (two arguments). Each
+/// argument is a pointer to member of a complete class.
+static ExprResult BuiltinMemberPointerTrait(Sema &S, CallExpr *TheCall,
+ unsigned NumArgs) {
+ if (S.checkArgCount(TheCall, NumArgs))
+ return ExprError();
+
+ for (unsigned I = 0; I != NumArgs; ++I) {
+ ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
+ if (Arg.isInvalid())
+ return ExprError();
+ TheCall->setArg(I, Arg.get());
+ QualType ArgTy = Arg.get()->getType();
+ SourceLocation Loc = Arg.get()->getExprLoc();
+ const auto *MPT = ArgTy->getAs<MemberPointerType>();
+ if (!MPT) {
+ S.Diag(Loc, diag::err_builtin_member_pointer_trait_arg)
+ << TheCall->getDirectCallee() << ArgTy << Arg.get()->getSourceRange();
+ return ExprError();
+ }
+ CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
+ if (S.RequireCompleteType(Loc, S.Context.getCanonicalTagType(RD),
+ diag::err_incomplete_type) ||
+ S.RequireCompleteType(Loc, ArgTy, diag::err_incomplete_type))
+ return ExprError();
+ }
+ return TheCall;
+}
+
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
if (S.checkArgCount(TheCall, 3))
return ExprError();
@@ -3502,6 +3532,10 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
return BuiltinLaunder(*this, TheCall);
case Builtin::BI__builtin_is_within_lifetime:
return BuiltinIsWithinLifetime(*this, TheCall);
+ case Builtin::BI__builtin_is_pointer_interconvertible_with_class:
+ return BuiltinMemberPointerTrait(*this, TheCall, 1);
+ case Builtin::BI__builtin_is_corresponding_member:
+ return BuiltinMemberPointerTrait(*this, TheCall, 2);
case Builtin::BI__builtin_trivially_relocate:
return BuiltinTriviallyRelocate(*this, TheCall);
case Builtin::BI__builtin_clear_padding: {
diff --git a/clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp b/clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp
new file mode 100644
index 00000000000000..6f34ad7d7ccd53
--- /dev/null
+++ b/clang/test/CodeGenCXX/builtin-pointer-interconvertible-traits.cpp
@@ -0,0 +1,159 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ITANIUM -DINT=i64
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -std=c++20 -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,MSABI -DINT=i32
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -fms-extensions -std=c++20 -emit-llvm -o - %s -DVIRTUAL_MODEL | FileCheck %s --check-prefix=VIRTUAL
+
+// Pointers to members that are not constants are compared with a pointer to
+// member at the offset of each member that the trait accepts.
+
+struct A { int x; int y; };
+struct B { int p; int q; };
+struct Base { int b0; int b1; };
+struct D : Base {};
+union V { int a; float b; };
+union VI { int a; int b; };
+struct Anon { int x; struct { int a; int b; }; };
+struct E1 {};
+struct E2 {};
+struct Emp : E1, E2 { int x; };
+
+// ITANIUM-LABEL: define {{.*}} @_Z16interconvertibleM1Ai(
+// MSABI-LABEL: define {{.*}} @"?interconvertible@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// CHECK-NEXT: ret i1 [[EQ]]
+bool interconvertible(int A::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// ITANIUM-LABEL: define {{.*}} @_Z22interconvertible_unionM1Vi(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_union@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// CHECK-NEXT: ret i1 [[EQ]]
+bool interconvertible_union(int V::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// Each member of a union is at offset 0, so one comparison is enough.
+// ITANIUM-LABEL: define {{.*}} @_Z27interconvertible_union_bothM2VIi(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_union_both@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// CHECK-NEXT: ret i1 [[EQ]]
+bool interconvertible_union_both(int VI::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// The members of D are those of its base.
+// ITANIUM-LABEL: define {{.*}} @_Z26interconvertible_inheritedM1Di(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_inherited@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// CHECK-NEXT: ret i1 [[EQ]]
+bool interconvertible_inherited(int D::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// In the Microsoft ABI, the second empty base takes a byte, so x is at
+// offset 4.
+// ITANIUM-LABEL: define {{.*}} @_Z26interconvertible_emptybaseM3Empi(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_emptybase@@
+// CHECK: [[M:%.*]] = load [[INT]]
+// ITANIUM-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 0
+// MSABI-NEXT: [[EQ:%.*]] = icmp eq [[INT]] [[M]], 4
+// CHECK-NEXT: ret i1 [[EQ]]
+bool interconvertible_emptybase(int Emp::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// No member of A has type float.
+// ITANIUM-LABEL: define {{.*}} @_Z21interconvertible_noneM1Af(
+// MSABI-LABEL: define {{.*}} @"?interconvertible_none@@
+// CHECK-NOT: icmp
+// CHECK: ret i1 false
+bool interconvertible_none(float A::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+
+// ITANIUM-LABEL: define {{.*}} @_Z13correspondingM1AiM1Bi(
+// MSABI-LABEL: define {{.*}} @"?corresponding@@
+// CHECK: [[M1:%.*]] = load [[INT]]
+// CHECK-NEXT: [[M2:%.*]] = load [[INT]]
+// CHECK-NEXT: [[EQ1:%.*]] = icmp eq [[INT]] [[M1]], 0
+// CHECK-NEXT: [[EQ2:%.*]] = icmp eq [[INT]] [[M2]], 0
+// CHECK-NEXT: [[AND1:%.*]] = and i1 [[EQ1]], [[EQ2]]
+// CHECK-NEXT: [[EQ3:%.*]] = icmp eq [[INT]] [[M1]], 4
+// CHECK-NEXT: [[EQ4:%.*]] = icmp eq [[INT]] [[M2]], 4
+// CHECK-NEXT: [[AND2:%.*]] = and i1 [[EQ3]], [[EQ4]]
+// CHECK-NEXT: [[R:%.*]] = or i1 [[AND1]], [[AND2]]
+// CHECK-NEXT: ret i1 [[R]]
+bool corresponding(int A::*m1, int B::*m2) {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+
+// ITANIUM-LABEL: define {{.*}} @_Z23corresponding_inheritedM1AiM1Di(
+// MSABI-LABEL: define {{.*}} @"?corresponding_inherited@@
+// CHECK: [[M1:%.*]] = load [[INT]]
+// CHECK-NEXT: [[M2:%.*]] = load [[INT]]
+// CHECK-NEXT: icmp eq [[INT]] [[M1]], 0
+// CHECK-NEXT: icmp eq [[INT]] [[M2]], 0
+// CHECK-NEXT: and i1
+// CHECK-NEXT: icmp eq [[INT]] [[M1]], 4
+// CHECK-NEXT: icmp eq [[INT]] [[M2]], 4
+// CHECK-NEXT: and i1
+// CHECK-NEXT: [[R:%.*]] = or i1
+// CHECK-NEXT: ret i1 [[R]]
+bool corresponding_inherited(int A::*m1, int D::*m2) {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+
+// Anon::a and Anon::b are members of an anonymous struct at offset 4.
+// ITANIUM-LABEL: define {{.*}} @_Z23corresponding_anonymousM4AnoniS0_(
+// MSABI-LABEL: define {{.*}} @"?corresponding_anonymous@@
+// CHECK: [[M1:%.*]] = load [[INT]]
+// CHECK-NEXT: [[M2:%.*]] = load [[INT]]
+// CHECK-NEXT: icmp eq [[INT]] [[M1]], 0
+// CHECK-NEXT: icmp eq [[INT]] [[M2]], 0
+// CHECK-NEXT: and i1
+// CHECK-NEXT: icmp eq [[INT]] [[M1]], 4
+// CHECK-NEXT: icmp eq [[INT]] [[M2]], 4
+// CHECK-NEXT: and i1
+// CHECK-NEXT: or i1
+// CHECK-NEXT: icmp eq [[INT]] [[M1]], 8
+// CHECK-NEXT: icmp eq [[INT]] [[M2]], 8
+// CHECK-NEXT: and i1
+// CHECK-NEXT: [[R:%.*]] = or i1
+// CHECK-NEXT: ret i1 [[R]]
+bool corresponding_anonymous(int Anon::*m1, int Anon::*m2) {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+
+// ITANIUM-LABEL: define {{.*}} @_Z9constantsv(
+// MSABI-LABEL: define {{.*}} @"?constants@@
+// CHECK-NOT: icmp
+// CHECK: ret i1 true
+bool constants() {
+ return __builtin_is_pointer_interconvertible_with_class(&A::x) &&
+ !__builtin_is_corresponding_member(&A::x, &B::q);
+}
+
+#ifdef VIRTUAL_MODEL
+// A class with the virtual inheritance model has three-field pointers to data
+// members; the comparison is the ABI's.
+#pragma pointers_to_members(full_generality, virtual_inheritance)
+struct Virt { int a; int b; };
+
+// VIRTUAL-LABEL: define {{.*}} @"?interconvertible_virtual_model@@
+// VIRTUAL: [[M:%.*]] = load { i32, i32, i32 }, ptr %m.addr
+// VIRTUAL: [[F0:%.*]] = extractvalue { i32, i32, i32 } [[M]], 0
+// VIRTUAL-NEXT: icmp eq i32 [[F0]], 0
+// VIRTUAL-NEXT: [[F1:%.*]] = extractvalue { i32, i32, i32 } [[M]], 1
+// VIRTUAL-NEXT: icmp eq i32 [[F1]], 0
+// VIRTUAL-NEXT: [[F2:%.*]] = extractvalue { i32, i32, i32 } [[M]], 2
+// VIRTUAL-NEXT: icmp eq i32 [[F2]], 0
+// VIRTUAL-NOT: extractvalue
+// VIRTUAL: ret i1
+bool interconvertible_virtual_model(int Virt::*m) {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+#endif
diff --git a/clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp b/clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp
new file mode 100644
index 00000000000000..a079640d47ab85
--- /dev/null
+++ b/clang/test/SemaCXX/builtin-pointer-interconvertible-traits.cpp
@@ -0,0 +1,295 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++20 -fsyntax-only -verify %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -std=c++20 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -std=c++20 -fsyntax-only -verify %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++17 -fsyntax-only -verify %s
+
+// __builtin_is_pointer_interconvertible_with_class(m) and
+// __builtin_is_corresponding_member(m1, m2), as GCC spells them, implement
+// std::is_pointer_interconvertible_with_class and std::is_corresponding_member
+// ([meta.member]). The class each trait checks is the class of the pointer to
+// member's type.
+
+static_assert(__has_builtin(__builtin_is_pointer_interconvertible_with_class));
+static_assert(__has_builtin(__builtin_is_corresponding_member));
+static_assert(__has_constexpr_builtin(__builtin_is_pointer_interconvertible_with_class));
+static_assert(__has_constexpr_builtin(__builtin_is_corresponding_member));
+
+#define IC(m) __builtin_is_pointer_interconvertible_with_class(m)
+#define CM(m1, m2) __builtin_is_corresponding_member(m1, m2)
+
+#if __has_cpp_attribute(no_unique_address)
+#define NO_UNIQUE_ADDRESS [[no_unique_address]]
+#else
+#define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
+#endif
+
+struct A { int x; int y; };
+struct B { int p; int q; };
+union V { int a; float b; };
+struct Base { int b0; int b1; };
+struct D : Base {};
+struct NSL { int x; private: int y; };
+struct NSL2 { int x; private: int y; };
+struct E {};
+struct DE : E { int x; };
+struct Mf { int x; void f(); };
+struct C1 { const int x; volatile int y; };
+struct C2 { int x; int y; };
+struct Arr { int a[2]; int b; };
+struct Arr2 { int a[2]; int c; };
+struct Arr3 { int a[3]; int c; };
+
+// Pointer-interconvertibility ([basic.compound]): a standard-layout struct and
+// its first member, a union and each of its members.
+static_assert(IC(&A::x));
+static_assert(!IC(&A::y));
+static_assert(IC(&V::a));
+static_assert(IC(&V::b));
+static_assert(IC(&C1::x));
+static_assert(!IC(&C1::y));
+static_assert(IC(&Arr::a));
+static_assert(!IC(&NSL::x)); // not standard-layout
+static_assert(!IC(&Mf::f)); // not a data member
+static_assert(!IC(static_cast<int A::*>(nullptr)));
+
+// Members in a base class: the class is the one in the pointer's type.
+static_assert(IC(&D::b0)); // int Base::*
+static_assert(IC(static_cast<int D::*>(&D::b0)));
+static_assert(!IC(static_cast<int D::*>(&D::b1)));
+static_assert(IC(&DE::x)); // empty base
+static_assert(!IC(static_cast<int E::*>(&DE::x))); // a member of DE, not of E
+
+// A union that is not standard-layout. GCC accepts this; [meta.member] does
+// not.
+struct Virt { virtual void f(); };
+union NU { int a; Virt v; };
+static_assert(!IC(&NU::a));
+
+// An unnamed bit-field is not a member, but as GCC does, treat it as the first
+// member.
+struct UB { int : 4; int x; };
+struct UB0 { int : 0; int x; };
+static_assert(!IC(&UB::x));
+static_assert(!IC(&UB0::x));
+
+struct NE { NO_UNIQUE_ADDRESS E e; int x; };
+static_assert(!IC(&NE::x));
+
+// Members of anonymous structs and unions: pointer-interconvertibility is
+// transitive.
+struct U { union { int a; float b; }; int c; };
+struct U2 { union { int a; float b; }; };
+union UU { union { int a; float b; }; int c; };
+struct Anon { struct { int a; int b; }; int c; };
+struct Nest { struct { struct { int a; }; int b; }; };
+struct S2 { int c; struct { int a; }; };
+union P1 { struct { int a; int b; }; };
+struct P2 { struct { union { int a; float f; }; int b; }; };
+struct Q4 { union { struct { int a; int b; }; float f; }; };
+struct Q7 { struct { union { int a; float b; }; }; };
+static_assert(IC(&U::a));
+static_assert(IC(&U::b));
+static_assert(!IC(&U::c));
+static_assert(IC(&U2::b));
+static_assert(IC(&UU::a));
+static_assert(IC(&UU::c));
+static_assert(IC(&Anon::a));
+static_assert(!IC(&Anon::b));
+static_assert(!IC(&Anon::c));
+static_assert(IC(&Nest::a));
+static_assert(!IC(&Nest::b));
+static_assert(!IC(&S2::a));
+static_assert(IC(&P1::a));
+static_assert(!IC(&P1::b));
+static_assert(IC(&P2::a));
+static_assert(IC(&P2::f));
+static_assert(IC(&Q4::a));
+static_assert(!IC(&Q4::b));
+static_assert(IC(&Q7::b));
+
+// Corresponding members of the common initial sequence ([class.mem.general]).
+struct Bf { int a : 3; int b; };
+struct Bf2 { int a : 3; int c; };
+struct Bf3 { int a : 4; int c; };
+struct L1 { int a; char b; double c; };
+struct L2 { int x; char y; float z; };
+static_assert(CM(&A::x, &B::p));
+static_assert(CM(&A::y, &B::q));
+static_assert(!CM(&A::x, &B::q));
+static_assert(!CM(&A::x, &A::y));
+static_assert(CM(&A::y, &A::y));
+static_assert(CM(&Bf::b, &Bf2::c));
+static_assert(!CM(&Bf::b, &Bf3::c));
+static_assert(CM(&L1::b, &L2::y));
+static_assert(!CM(&L1::c, &L2::z));
+static_assert(CM(&C1::x, &C2::x));
+static_assert(CM(&C1::y, &C2::y));
+static_assert(CM(&Arr::b, &Arr2::c));
+static_assert(!CM(&Arr::b, &Arr3::c));
+static_assert(!CM(&NSL::x, &NSL::x)); // not standard-layout
+static_assert(!CM(&NSL::x, &NSL2::x));
+static_assert(!CM(&V::a, &V::a)); // unions have no common initial sequence
+static_assert(!CM(&V::a, &A::x));
+static_assert(!CM(&Mf::f, &Mf::f));
+static_assert(!CM(static_cast<int A::*>(nullptr), &B::p));
+static_assert(CM(&D::b1, &A::y));
+static_assert(CM(static_cast<int D::*>(&D::b1), &A::y));
+static_assert(CM(&A::x, static_cast<int D::*>(&D::b0)));
+
+// Unnamed bit-fields are part of the common initial sequence.
+struct UB1 { int a; int : 3; int b; };
+struct UB2 { int a; int : 3; int b; };
+struct UB3 { int a; int : 4; int b; };
+struct UB4 { int a; int b; };
+static_assert(CM(&UB1::b, &UB2::b));
+static_assert(!CM(&UB1::b, &UB3::b));
+static_assert(!CM(&UB1::b, &UB4::b));
+
+enum E1 : int {}; enum E2 : int {}; enum E3 : unsigned {};
+struct En1 { E1 e; int z; };
+struct En2 { E2 e; int z; };
+struct En3 { E3 e; int z; };
+struct En4 { int e; int z; };
+static_assert(CM(&En1::e, &En2::e));
+static_assert(CM(&En1::z, &En2::z));
+static_assert(!CM(&En1::z, &En3::z));
+static_assert(!CM(&En1::z, &En4::z));
+
+struct X1 { int i; };
+struct X2 { int i; };
+struct H1 { X1 m; int n; };
+struct H2 { X2 m; int n; };
+static_assert(CM(&H1::m, &H2::m));
+static_assert(CM(&H1::n, &H2::n));
+
+// Corresponding entities have the same alignment (C++23 [class.mem.general]).
+struct AL1 { int a; alignas(8) int b; int c; };
+struct AL2 { int a; int b; int c; };
+static_assert(CM(&AL1::a, &AL2::a));
+static_assert(!CM(&AL1::b, &AL2::b));
+static_assert(!CM(&AL1::c, &AL2::c));
+
+// Both or neither have [[no_unique_address]].
+struct NU1 { int a; NO_UNIQUE_ADDRESS E e; int b; };
+struct NU2 { int a; NO_UNIQUE_ADDRESS E e; int b; };
+struct NU3 { int a; E e; int b; };
+static_assert(CM(&NU1::b, &NU2::b));
+static_assert(CM(&NU1::a, &NU3::a));
+static_assert(!CM(&NU1::b, &NU3::b));
+
+struct Emp1 : E { int a; int b; };
+struct Emp2 { int a; int b; };
+static_assert(IC(&Emp1::a));
+static_assert(CM(&Emp1::b, &Emp2::b));
+
+// Several empty bases. (In the Microsoft ABI, x is not at offset 0.)
+struct EB {};
+struct Emp3 : E, EB { int x; };
+static_assert(IC(&Emp3::x));
+
+// The same alignment requirement, and the same offsets: #pragma pack and
+// over-aligned typedefs change the layout without changing the types.
+struct AL3 { int a; alignas(int) int b; };
+static_assert(CM(&AL3::b, &AL2::b));
+#pragma pack(push, 1)
+struct Pk { char c; int i; };
+#pragma pack(pop)
+struct Up { char c; int i; };
+static_assert(CM(&Pk::c, &Up::c));
+static_assert(!CM(&Pk::i, &Up::i));
+typedef int __attribute__((aligned(8))) Int8;
+struct T8 { char c; Int8 i; };
+struct T4 { char c; int i; };
+static_assert(CM(&T8::c, &T4::c));
+static_assert(!CM(&T8::i, &T4::i));
+
+// As in GCC, members of anonymous structs at the same position correspond if
+// they are in the common initial sequence of those structs.
+struct Anon2 { struct { int a; int b; }; int c; };
+struct Anon3 { struct { int a; float b; }; int c; };
+struct P6 { int x; struct { int a; int b; }; };
+struct P7 { int x; struct { int a; int b; }; };
+struct Deep1 { int a; struct { int b; struct { int c; int d; }; }; };
+struct Deep2 { int a; struct { int b; struct { int c; int d; }; }; };
+struct Deep3 { int a; struct { int b; struct { int c; float d; }; }; };
+static_assert(CM(&Anon::a, &Anon2::a));
+static_assert(CM(&Anon::b, &Anon2::b));
+static_assert(CM(&Anon::c, &Anon2::c));
+static_assert(CM(&Anon::a, &Anon3::a));
+static_assert(!CM(&Anon::b, &Anon3::b));
+static_assert(!CM(&Anon::c, &Anon3::c));
+static_assert(CM(&P6::a, &P7::a));
+static_assert(CM(&P6::b, &P7::b));
+static_assert(CM(&Deep1::d, &Deep2::d));
+static_assert(CM(&Deep1::c, &Deep3::c));
+static_assert(!CM(&Deep1::d, &Deep3::d));
+static_assert(!CM(&Anon::a, &Anon::c));
+
+// Members of anonymous unions have no defined correspondence (GCC rejects
+// these); an anonymous union as a whole can be part of the sequence.
+struct P4 { int x; union { int a; float f; }; };
+struct P5 { int x; union { int a; float f; }; };
+struct P8 { union { int a; float f; }; int y; };
+struct P9 { union { int a; float f; }; int y; };
+static_assert(!CM(&P4::a, &P5::a));
+static_assert(!CM(&P8::a, &P8::a));
+static_assert(CM(&P8::y, &P9::y));
+
+// The shape of the standard library's function templates.
+template <class S, class M>
+constexpr bool is_pointer_interconvertible_with_class(M S::*m) noexcept {
+ return __builtin_is_pointer_interconvertible_with_class(m);
+}
+template <class S1, class S2, class M1, class M2>
+constexpr bool is_corresponding_member(M1 S1::*m1, M2 S2::*m2) noexcept {
+ return __builtin_is_corresponding_member(m1, m2);
+}
+static_assert(is_pointer_interconvertible_with_class(&A::x));
+static_assert(!is_pointer_interconvertible_with_class(&A::y));
+static_assert(is_pointer_interconvertible_with_class<D, int>(&D::b0));
+static_assert(!is_pointer_interconvertible_with_class<D, int>(&D::b1));
+static_assert(is_pointer_interconvertible_with_class<A, const int>(&A::x));
+static_assert(is_corresponding_member(&A::y, &B::q));
+static_assert(!is_corresponding_member(&A::y, &B::p));
+static_assert(is_corresponding_member<D, A, int, int>(&D::b1, &A::y));
+
+// A template parameter.
+template <int A::*P> constexpr bool icParam() { return IC(P); }
+template <int A::*P, int B::*Q> constexpr bool cmParam() { return CM(P, Q); }
+static_assert(icParam<&A::x>());
+static_assert(!icParam<&A::y>());
+static_assert(cmParam<&A::y, &B::q>());
+static_assert(!cmParam<&A::y, &B::p>());
+
+// Pointers that are not constants are allowed; they are compared at run time.
+bool runtime(int A::*m1, int B::*m2) {
+ return IC(m1) && CM(m1, m2);
+}
+int A::*Mutable = &A::x; // expected-note {{declared here}}
+static_assert(IC(Mutable)); // expected-error {{static assertion expression is not an integral constant expression}} \
+ // expected-note {{read of non-constexpr variable 'Mutable' is not allowed in a constant expression}}
+
+struct Incomplete; // expected-note 2 {{forward declaration of 'Incomplete'}}
+template <class T> struct Template { T t; };
+static_assert(IC(&Template<int>::t));
+
+void errors(int *p, int Incomplete::*ip) {
+ (void)IC(p); // expected-error {{argument to '__builtin_is_pointer_interconvertible_with_class' must be a pointer to member, not 'int *'}}
+ (void)CM(&A::x, 0); // expected-error {{argument to '__builtin_is_corresponding_member' must be a pointer to member, not 'int'}}
+ (void)__builtin_is_pointer_interconvertible_with_class(&A::x, &A::y); // expected-error {{too many arguments to function call, expected 1, have 2}}
+ (void)__builtin_is_corresponding_member(&A::x); // expected-error {{too few arguments to function call, expected 2, have 1}}
+ (void)IC(ip); // expected-error {{incomplete type 'Incomplete' where a complete type is required}}
+ (void)CM(&A::x, ip); // expected-error {{incomplete type 'Incomplete' where a complete type is required}}
+}
+
+template <class T> bool dependent(T m) {
+ return __builtin_is_pointer_interconvertible_with_class(m); // expected-error {{argument to '__builtin_is_pointer_interconvertible_with_class' must be a pointer to member, not 'int'}}
+}
+template bool dependent(int A::*);
+template bool dependent(int); // expected-note {{in instantiation of function template specialization 'dependent<int>' requested here}}
+
+// An invalid class.
+struct Invalid { int x; Undeclared y; }; // expected-error {{unknown type name 'Undeclared'}}
+static_assert(!IC(&Invalid::x));
+static_assert(!CM(&Invalid::x, &Invalid::x));
More information about the cfe-commits
mailing list