[clang] Add Clang attribute to ensure that fields are initialized explicitly (PR #102040)
via cfe-commits
cfe-commits at lists.llvm.org
Mon Sep 30 10:03:19 PDT 2024
https://github.com/higher-performance updated https://github.com/llvm/llvm-project/pull/102040
>From 7ea9d3dbb6ff74ca3f7f9b9a0c589e4a0a3366f2 Mon Sep 17 00:00:00 2001
From: higher-performance <higher.performance.github at gmail.com>
Date: Mon, 5 Aug 2024 15:04:19 -0400
Subject: [PATCH 1/2] Add Clang attribute to ensure that fields are initialized
explicitly
---
.../clang/AST/CXXRecordDeclDefinitionBits.def | 9 ++++
clang/include/clang/AST/DeclCXX.h | 5 ++
clang/include/clang/Basic/Attr.td | 8 ++++
clang/include/clang/Basic/AttrDocs.td | 29 ++++++++++++
clang/include/clang/Basic/DiagnosticGroups.td | 1 +
.../clang/Basic/DiagnosticSemaKinds.td | 7 +++
clang/lib/AST/DeclCXX.cpp | 24 ++++++++++
clang/lib/Sema/SemaDeclAttr.cpp | 7 +++
clang/lib/Sema/SemaInit.cpp | 15 ++++++
...a-attribute-supported-attributes-list.test | 1 +
clang/test/SemaCXX/uninitialized.cpp | 46 +++++++++++++++++++
11 files changed, 152 insertions(+)
diff --git a/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def b/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
index 6620840df0ced2..54f28046c63ebb 100644
--- a/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
+++ b/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
@@ -119,6 +119,15 @@ FIELD(HasInitMethod, 1, NO_MERGE)
/// within anonymous unions or structs.
FIELD(HasInClassInitializer, 1, NO_MERGE)
+/// Custom attribute that is True if any field is marked as requiring explicit
+/// initialization with [[clang::requires_explicit_initialization]] in a type
+/// without a user-provided default constructor, or if this is the case for any
+/// base classes and/or member variables whose types are aggregates.
+///
+/// In this case, default-construction is diagnosed, as it would not explicitly
+/// initialize the field.
+FIELD(HasUninitializedExplicitInitFields, 1, NO_MERGE)
+
/// True if any field is of reference type, and does not have an
/// in-class initializer.
///
diff --git a/clang/include/clang/AST/DeclCXX.h b/clang/include/clang/AST/DeclCXX.h
index 252e6e92564142..27994da80243d6 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1152,6 +1152,11 @@ class CXXRecordDecl : public RecordDecl {
/// structs).
bool hasInClassInitializer() const { return data().HasInClassInitializer; }
+ bool hasUninitializedExplicitInitFields() const {
+ return !isUnion() && !hasUserProvidedDefaultConstructor() &&
+ data().HasUninitializedExplicitInitFields;
+ }
+
/// Whether this class or any of its subobjects has any members of
/// reference type which would make value-initialization ill-formed.
///
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index 70fad60d4edbb5..fa7d1b8013d036 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1861,6 +1861,14 @@ def Leaf : InheritableAttr {
let SimpleHandler = 1;
}
+def ExplicitInit : InheritableAttr {
+ let Spellings = [Clang<"requires_explicit_initialization", 0>];
+ let Subjects = SubjectList<[Field], ErrorDiag>;
+ let Documentation = [ExplicitInitDocs];
+ let LangOpts = [CPlusPlus];
+ let SimpleHandler = 1;
+}
+
def LifetimeBound : DeclOrTypeAttr {
let Spellings = [Clang<"lifetimebound", 0>];
let Subjects = SubjectList<[ParmVar, ImplicitObjectParameter], ErrorDiag>;
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 546e5100b79dd9..625dff5b4b7aa9 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1419,6 +1419,35 @@ is not specified.
}];
}
+def ExplicitInitDocs : Documentation {
+ let Category = DocCatField;
+ let Content = [{
+The ``clang::requires_explicit_initialization`` attribute indicates that the
+field of an aggregate must be initialized explicitly by users when the class
+is constructed. Its usage is invalid on non-aggregates.
+
+Example usage:
+
+.. code-block:: c++
+
+ struct some_aggregate {
+ int x;
+ int y [[clang::requires_explicit_initialization]];
+ };
+
+ some_aggregate create() {
+ return {.x = 1}; // error: y is not initialized explicitly
+ }
+
+This attribute is *not* a memory safety feature, and is *not* intended to guard
+against use of uninitialized memory.
+Rather, its intended use is in structs that represent "parameter objects", to
+allow extending them while ensuring that callers do not forget to specify
+values for newly added fields ("parameters").
+
+ }];
+}
+
def NoUniqueAddressDocs : Documentation {
let Category = DocCatField;
let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index 116ce7a04f66f7..3a8b13898e2cd0 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -787,6 +787,7 @@ def Trigraphs : DiagGroup<"trigraphs">;
def UndefinedReinterpretCast : DiagGroup<"undefined-reinterpret-cast">;
def ReinterpretBaseClass : DiagGroup<"reinterpret-base-class">;
def Unicode : DiagGroup<"unicode">;
+def UninitializedExplicitInit : DiagGroup<"uninitialized-explicit-init">;
def UninitializedMaybe : DiagGroup<"conditional-uninitialized">;
def UninitializedSometimes : DiagGroup<"sometimes-uninitialized">;
def UninitializedStaticSelfInit : DiagGroup<"static-self-init">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ce08bd60f76449..6dc386135034d6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2302,6 +2302,10 @@ def err_init_list_bad_dest_type : Error<
def warn_cxx20_compat_aggregate_init_with_ctors : Warning<
"aggregate initialization of type %0 with user-declared constructors "
"is incompatible with C++20">, DefaultIgnore, InGroup<CXX20Compat>;
+def warn_cxx20_compat_requires_explicit_init_non_aggregate : Warning<
+ "explicit initialization of field %0 may not be enforced in C++20 as type %1 "
+ "will become a non-aggregate due to the presence of user-declared "
+ "constructors">, DefaultIgnore, InGroup<CXX20Compat>;
def warn_cxx17_compat_aggregate_init_paren_list : Warning<
"aggregate initialization of type %0 from a parenthesized list of values "
"is a C++20 extension">, DefaultIgnore, InGroup<CXX20>;
@@ -2331,6 +2335,9 @@ def err_init_reference_member_uninitialized : Error<
"reference member of type %0 uninitialized">;
def note_uninit_reference_member : Note<
"uninitialized reference member is here">;
+def warn_field_requires_explicit_init : Warning<
+ "field %0 is not explicitly initialized, but was marked as requiring "
+ "explicit initialization">, InGroup<UninitializedExplicitInit>;
def warn_field_is_uninit : Warning<"field %0 is uninitialized when used here">,
InGroup<Uninitialized>;
def warn_base_class_is_uninit : Warning<
diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index 01143391edab40..d56374ead6d794 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -29,6 +29,7 @@
#include "clang/AST/TypeLoc.h"
#include "clang/AST/UnresolvedSet.h"
#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticSema.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
@@ -81,6 +82,7 @@ CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
HasPrivateFields(false), HasProtectedFields(false),
HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),
HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false),
+ HasUninitializedExplicitInitFields(false),
HasUninitializedReferenceMember(false), HasUninitializedFields(false),
HasInheritedConstructor(false), HasInheritedDefaultConstructor(false),
HasInheritedAssignment(false),
@@ -1111,6 +1113,10 @@ void CXXRecordDecl::addedMember(Decl *D) {
} else if (!T.isCXX98PODType(Context))
data().PlainOldData = false;
+ if (Field->hasAttr<ExplicitInitAttr>() && !Field->hasInClassInitializer()) {
+ data().HasUninitializedExplicitInitFields = true;
+ }
+
if (T->isReferenceType()) {
if (!Field->hasInClassInitializer())
data().HasUninitializedReferenceMember = true;
@@ -1362,6 +1368,10 @@ void CXXRecordDecl::addedMember(Decl *D) {
if (!FieldRec->hasCopyAssignmentWithConstParam())
data().ImplicitCopyAssignmentHasConstParam = false;
+ if (FieldRec->hasUninitializedExplicitInitFields() &&
+ FieldRec->isAggregate() && !Field->hasInClassInitializer())
+ data().HasUninitializedExplicitInitFields = true;
+
if (FieldRec->hasUninitializedReferenceMember() &&
!Field->hasInClassInitializer())
data().HasUninitializedReferenceMember = true;
@@ -2148,6 +2158,20 @@ void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
for (conversion_iterator I = conversion_begin(), E = conversion_end();
I != E; ++I)
I.setAccess((*I)->getAccess());
+
+ ASTContext &Context = getASTContext();
+ if (!Context.getLangOpts().CPlusPlus20 && isAggregate() &&
+ hasUserDeclaredConstructor()) {
+ // Diagnose any aggregate behavior changes in C++20
+ for (field_iterator I = field_begin(), E = field_end(); I != E; ++I) {
+ if (const auto *attr = I->getAttr<ExplicitInitAttr>()) {
+ Context.getDiagnostics().Report(
+ getLocation(),
+ diag::warn_cxx20_compat_requires_explicit_init_non_aggregate)
+ << attr->getRange() << Context.getRecordType(this);
+ }
+ }
+ }
}
bool CXXRecordDecl::mayBeAbstract() const {
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 14cc51cf89665a..6145db10aa4932 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -6014,6 +6014,10 @@ static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
D->addAttr(NoMergeAttr::Create(S.Context, AL));
}
+static void handleExplicitInitAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+ D->addAttr(ExplicitInitAttr::Create(S.Context, AL));
+}
+
static void handleNoUniqueAddressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
D->addAttr(NoUniqueAddressAttr::Create(S.Context, AL));
}
@@ -6919,6 +6923,9 @@ ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL,
case ParsedAttr::AT_NoMerge:
handleNoMergeAttr(S, D, AL);
break;
+ case ParsedAttr::AT_ExplicitInit:
+ handleExplicitInitAttr(S, D, AL);
+ break;
case ParsedAttr::AT_NoUniqueAddress:
handleNoUniqueAddressAttr(S, D, AL);
break;
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 4d11f2a43fcc6b..e89d72e67d854e 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -743,6 +743,14 @@ void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
ILE->updateInit(SemaRef.Context, Init, Filler);
return;
}
+
+ if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>()) {
+ SemaRef.Diag(ILE->getExprLoc(), diag::warn_field_requires_explicit_init)
+ << Field;
+ SemaRef.Diag(Field->getLocation(), diag::note_entity_declared_at)
+ << Field;
+ }
+
// C++1y [dcl.init.aggr]p7:
// If there are fewer initializer-clauses in the list than there are
// members in the aggregate, then each member not explicitly initialized
@@ -4561,6 +4569,13 @@ static void TryConstructorInitialization(Sema &S,
CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
if (Result != OR_Deleted) {
+ if (!IsListInit && Kind.getKind() == InitializationKind::IK_Default &&
+ DestRecordDecl != nullptr && DestRecordDecl->isAggregate() &&
+ DestRecordDecl->hasUninitializedExplicitInitFields()) {
+ S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
+ << "in class";
+ }
+
// C++11 [dcl.init]p6:
// If a program calls for the default initialization of an object
// of a const-qualified type T, T shall be a class type with a
diff --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index baa1816358b156..5cc220e193b28d 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -77,6 +77,7 @@
// CHECK-NEXT: EnumExtensibility (SubjectMatchRule_enum)
// CHECK-NEXT: Error (SubjectMatchRule_function)
// CHECK-NEXT: ExcludeFromExplicitInstantiation (SubjectMatchRule_variable, SubjectMatchRule_function, SubjectMatchRule_record)
+// CHECK-NEXT: ExplicitInit (SubjectMatchRule_field)
// CHECK-NEXT: ExternalSourceSymbol ((SubjectMatchRule_record, SubjectMatchRule_enum, SubjectMatchRule_enum_constant, SubjectMatchRule_field, SubjectMatchRule_function, SubjectMatchRule_namespace, SubjectMatchRule_objc_category, SubjectMatchRule_objc_implementation, SubjectMatchRule_objc_interface, SubjectMatchRule_objc_method, SubjectMatchRule_objc_property, SubjectMatchRule_objc_protocol, SubjectMatchRule_record, SubjectMatchRule_type_alias, SubjectMatchRule_variable))
// CHECK-NEXT: FlagEnum (SubjectMatchRule_enum)
// CHECK-NEXT: Flatten (SubjectMatchRule_function)
diff --git a/clang/test/SemaCXX/uninitialized.cpp b/clang/test/SemaCXX/uninitialized.cpp
index 8a640c9691b321..37cf6d1dd60c0a 100644
--- a/clang/test/SemaCXX/uninitialized.cpp
+++ b/clang/test/SemaCXX/uninitialized.cpp
@@ -1472,3 +1472,49 @@ template<typename T> struct Outer {
};
};
Outer<int>::Inner outerinner;
+
+void aggregate() {
+ struct S {
+ [[clang::requires_explicit_initialization]] int x; // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}}
+ int y;
+ int z = 12;
+ [[clang::requires_explicit_initialization]] int q = 100; // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}}
+ static void foo(S) { }
+ };
+
+ struct D : S { // expected-warning {{not explicitly initialized}}
+ int f1;
+ int f2 [[clang::requires_explicit_initialization]]; // expected-note {{declared}} // expected-note {{declared}}
+ };
+
+ struct C {
+ [[clang::requires_explicit_initialization]] int w;
+ C() = default; // Test pre-C++20 aggregates
+ };
+
+ S::foo(S{1, 2, 3, 4});
+ S::foo(S{.x = 100, .q = 100});
+ S::foo(S{.x = 100}); // expected-warning {{'q' is not explicitly initialized}}
+ S s{.x = 100, .q = 100};
+ (void)s;
+ S t{.q = 100}; // expected-warning {{'x' is not explicitly initialized}}
+ (void)t;
+ S *ptr1 = new S; // expected-warning {{not explicitly initialized}}
+ delete ptr1;
+ S *ptr2 = new S{.x = 100, .q = 100};
+ delete ptr2;
+#if __cplusplus >= 202002L
+ D a({}, 0); // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'f2' is not explicitly initialized}}
+ (void)a;
+#else
+ C a; // expected-warning {{not explicitly initialized}}
+ (void)a;
+#endif
+ D b{.f2 = 1}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}}
+ (void)b;
+ D c{.f1 = 5}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}} expected-warning {{'f2' is not explicitly initialized}}
+ c = {{}, 0}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}} expected-warning {{'f2' is not explicitly initialized}}
+ (void)c;
+ D d; // expected-warning {{not explicitly initialized}} // expected-note {{constructor}}
+ (void)d;
+}
>From 963fb67d0113913e5963481c2602aaf8d86063ff Mon Sep 17 00:00:00 2001
From: higher-performance <higher.performance.github at gmail.com>
Date: Wed, 25 Sep 2024 13:28:46 -0400
Subject: [PATCH 2/2] Implement explicit field initialization checks in
RecordDecl and make it work in both C and C++
---
.../clang/AST/CXXRecordDeclDefinitionBits.def | 9 ---
clang/include/clang/AST/Decl.h | 8 ++
clang/include/clang/AST/DeclBase.h | 10 ++-
clang/include/clang/AST/DeclCXX.h | 5 --
clang/include/clang/Basic/Attr.td | 3 +-
clang/include/clang/Basic/AttrDocs.td | 31 ++++---
.../clang/Basic/DiagnosticSemaKinds.td | 8 +-
clang/lib/AST/Decl.cpp | 1 +
clang/lib/AST/DeclCXX.cpp | 32 ++++++--
clang/lib/Sema/SemaDecl.cpp | 3 +
clang/lib/Sema/SemaInit.cpp | 81 ++++++++++++++++++-
clang/lib/Serialization/ASTReaderDecl.cpp | 1 +
clang/lib/Serialization/ASTWriterDecl.cpp | 4 +-
...a-attribute-supported-attributes-list.test | 1 -
clang/test/Sema/uninit-variables.c | 11 +++
clang/test/SemaCXX/uninitialized.cpp | 35 ++++----
16 files changed, 187 insertions(+), 56 deletions(-)
diff --git a/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def b/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
index 54f28046c63ebb..6620840df0ced2 100644
--- a/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
+++ b/clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
@@ -119,15 +119,6 @@ FIELD(HasInitMethod, 1, NO_MERGE)
/// within anonymous unions or structs.
FIELD(HasInClassInitializer, 1, NO_MERGE)
-/// Custom attribute that is True if any field is marked as requiring explicit
-/// initialization with [[clang::requires_explicit_initialization]] in a type
-/// without a user-provided default constructor, or if this is the case for any
-/// base classes and/or member variables whose types are aggregates.
-///
-/// In this case, default-construction is diagnosed, as it would not explicitly
-/// initialize the field.
-FIELD(HasUninitializedExplicitInitFields, 1, NO_MERGE)
-
/// True if any field is of reference type, and does not have an
/// in-class initializer.
///
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 0600ecc4d14a18..111b5582a4848c 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -4269,6 +4269,14 @@ class RecordDecl : public TagDecl {
RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
}
+ bool hasUninitializedExplicitInitFields() const {
+ return RecordDeclBits.HasUninitializedExplicitInitFields;
+ }
+
+ void setHasUninitializedExplicitInitFields(bool V) {
+ RecordDeclBits.HasUninitializedExplicitInitFields = V;
+ }
+
/// Determine whether this class can be passed in registers. In C++ mode,
/// it must have at least one trivial, non-deleted copy or move constructor.
/// FIXME: This should be set as part of completeDefinition.
diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h
index ee662ed73d7e0e..d2e92cdd5ecc55 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -1668,6 +1668,14 @@ class DeclContext {
LLVM_PREFERRED_TYPE(bool)
uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
+ /// True if any field is marked as requiring explicit initialization with
+ /// [[clang::requires_explicit_initialization]].
+ /// In C++, this is also set for types without a user-provided default
+ /// constructor, and is propagated from any base classes and/or member
+ /// variables whose types are aggregates.
+ LLVM_PREFERRED_TYPE(bool)
+ uint64_t HasUninitializedExplicitInitFields : 1;
+
/// Indicates whether this struct is destroyed in the callee.
LLVM_PREFERRED_TYPE(bool)
uint64_t ParamDestroyedInCallee : 1;
@@ -1682,7 +1690,7 @@ class DeclContext {
/// True if a valid hash is stored in ODRHash. This should shave off some
/// extra storage and prevent CXXRecordDecl to store unused bits.
- uint64_t ODRHash : 26;
+ uint64_t ODRHash : 25;
};
/// Number of inherited and non-inherited bits in RecordDeclBitfields.
diff --git a/clang/include/clang/AST/DeclCXX.h b/clang/include/clang/AST/DeclCXX.h
index 27994da80243d6..252e6e92564142 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1152,11 +1152,6 @@ class CXXRecordDecl : public RecordDecl {
/// structs).
bool hasInClassInitializer() const { return data().HasInClassInitializer; }
- bool hasUninitializedExplicitInitFields() const {
- return !isUnion() && !hasUserProvidedDefaultConstructor() &&
- data().HasUninitializedExplicitInitFields;
- }
-
/// Whether this class or any of its subobjects has any members of
/// reference type which would make value-initialization ill-formed.
///
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index fa7d1b8013d036..7f9ec696fc8380 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1862,10 +1862,9 @@ def Leaf : InheritableAttr {
}
def ExplicitInit : InheritableAttr {
- let Spellings = [Clang<"requires_explicit_initialization", 0>];
+ let Spellings = [Clang<"requires_explicit_initialization", 1>];
let Subjects = SubjectList<[Field], ErrorDiag>;
let Documentation = [ExplicitInitDocs];
- let LangOpts = [CPlusPlus];
let SimpleHandler = 1;
}
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 625dff5b4b7aa9..42c63c86093842 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1426,24 +1426,31 @@ The ``clang::requires_explicit_initialization`` attribute indicates that the
field of an aggregate must be initialized explicitly by users when the class
is constructed. Its usage is invalid on non-aggregates.
-Example usage:
+Note that this attribute is *not* a memory safety feature, and is *not* intended
+to guard against use of uninitialized memory.
+
+Rather, it is intended for use in "parameter-objects", used to simulate the
+passing of named parameters.
+The attribute generates a warning when explicit initializers for such
+"named parameters" are not provided:
.. code-block:: c++
- struct some_aggregate {
- int x;
- int y [[clang::requires_explicit_initialization]];
+ struct ArrayIOParams {
+ size_t count [[clang::requires_explicit_initialization]];
+ size_t element_size [[clang::requires_explicit_initialization]];
+ int flags = 0;
};
- some_aggregate create() {
- return {.x = 1}; // error: y is not initialized explicitly
- }
+ size_t ReadArray(FILE *file, void *buffer, ArrayIOParams params);
-This attribute is *not* a memory safety feature, and is *not* intended to guard
-against use of uninitialized memory.
-Rather, its intended use is in structs that represent "parameter objects", to
-allow extending them while ensuring that callers do not forget to specify
-values for newly added fields ("parameters").
+ int main() {
+ unsigned int buf[512];
+ ReadArray(stdin, buf, {
+ .count = sizeof(buf) / sizeof(*buf),
+ // warning: field 'element_size' is not explicitly initialized
+ });
+ }
}];
}
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6dc386135034d6..b75b10ed4e0952 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2336,8 +2336,8 @@ def err_init_reference_member_uninitialized : Error<
def note_uninit_reference_member : Note<
"uninitialized reference member is here">;
def warn_field_requires_explicit_init : Warning<
- "field %0 is not explicitly initialized, but was marked as requiring "
- "explicit initialization">, InGroup<UninitializedExplicitInit>;
+ "field %select{%1|in %1}0 is not explicitly initialized, but was marked as "
+ "requiring explicit initialization">, InGroup<UninitializedExplicitInit>;
def warn_field_is_uninit : Warning<"field %0 is uninitialized when used here">,
InGroup<Uninitialized>;
def warn_base_class_is_uninit : Warning<
@@ -3148,6 +3148,10 @@ def warn_attribute_ignored_no_calls_in_stmt: Warning<
"statement">,
InGroup<IgnoredAttributes>;
+def warn_attribute_needs_aggregate : Warning<
+ "%0 attribute is ignored in non-aggregate type %1">,
+ InGroup<IgnoredAttributes>;
+
def warn_attribute_ignored_non_function_pointer: Warning<
"%0 attribute is ignored because %1 is not a function pointer">,
InGroup<IgnoredAttributes>;
diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index a14b1b33d35efc..3c3bb2d209ade3 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -5014,6 +5014,7 @@ RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
setHasNonTrivialToPrimitiveDestructCUnion(false);
setHasNonTrivialToPrimitiveCopyCUnion(false);
+ setHasUninitializedExplicitInitFields(false);
setParamDestroyedInCallee(false);
setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs);
setIsRandomized(false);
diff --git a/clang/lib/AST/DeclCXX.cpp b/clang/lib/AST/DeclCXX.cpp
index d56374ead6d794..d261982b5d69a6 100644
--- a/clang/lib/AST/DeclCXX.cpp
+++ b/clang/lib/AST/DeclCXX.cpp
@@ -82,7 +82,6 @@ CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
HasPrivateFields(false), HasProtectedFields(false),
HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),
HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false),
- HasUninitializedExplicitInitFields(false),
HasUninitializedReferenceMember(false), HasUninitializedFields(false),
HasInheritedConstructor(false), HasInheritedDefaultConstructor(false),
HasInheritedAssignment(false),
@@ -460,6 +459,10 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
if (BaseClassDecl->hasMutableFields())
data().HasMutableFields = true;
+ if (BaseClassDecl->hasUninitializedExplicitInitFields() &&
+ BaseClassDecl->isAggregate())
+ setHasUninitializedExplicitInitFields(true);
+
if (BaseClassDecl->hasUninitializedReferenceMember())
data().HasUninitializedReferenceMember = true;
@@ -1114,7 +1117,7 @@ void CXXRecordDecl::addedMember(Decl *D) {
data().PlainOldData = false;
if (Field->hasAttr<ExplicitInitAttr>() && !Field->hasInClassInitializer()) {
- data().HasUninitializedExplicitInitFields = true;
+ setHasUninitializedExplicitInitFields(true);
}
if (T->isReferenceType()) {
@@ -1370,7 +1373,7 @@ void CXXRecordDecl::addedMember(Decl *D) {
if (FieldRec->hasUninitializedExplicitInitFields() &&
FieldRec->isAggregate() && !Field->hasInClassInitializer())
- data().HasUninitializedExplicitInitFields = true;
+ setHasUninitializedExplicitInitFields(true);
if (FieldRec->hasUninitializedReferenceMember() &&
!Field->hasInClassInitializer())
@@ -2160,17 +2163,32 @@ void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
I.setAccess((*I)->getAccess());
ASTContext &Context = getASTContext();
- if (!Context.getLangOpts().CPlusPlus20 && isAggregate() &&
- hasUserDeclaredConstructor()) {
+
+ if (isAggregate() && hasUserDeclaredConstructor() &&
+ !Context.getLangOpts().CPlusPlus20) {
// Diagnose any aggregate behavior changes in C++20
for (field_iterator I = field_begin(), E = field_end(); I != E; ++I) {
if (const auto *attr = I->getAttr<ExplicitInitAttr>()) {
Context.getDiagnostics().Report(
- getLocation(),
+ attr->getLocation(),
diag::warn_cxx20_compat_requires_explicit_init_non_aggregate)
- << attr->getRange() << Context.getRecordType(this);
+ << attr << Context.getRecordType(this);
+ }
+ }
+ }
+
+ if (!isAggregate() && hasUninitializedExplicitInitFields()) {
+ // Diagnose any fields that required explicit initialization in a
+ // non-aggregate type. (Note that the fields may not be directly in this
+ // type, but in a subobject. In such cases we don't emit diagnoses here.)
+ for (field_iterator I = field_begin(), E = field_end(); I != E; ++I) {
+ if (const auto *attr = I->getAttr<ExplicitInitAttr>()) {
+ Context.getDiagnostics().Report(attr->getLocation(),
+ diag::warn_attribute_needs_aggregate)
+ << attr << Context.getRecordType(this);
}
}
+ setHasUninitializedExplicitInitFields(false);
}
}
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 8557c25b93a8da..9a29214779c4ce 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19086,6 +19086,9 @@ void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
}
+ if (FD->hasAttr<ExplicitInitAttr>()) {
+ Record->setHasUninitializedExplicitInitFields(true);
+ }
if (FT.isDestructedType()) {
Record->setNonTrivialToPrimitiveDestroy(true);
Record->setParamDestroyedInCallee(true);
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index e89d72e67d854e..70614e2eafce62 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -268,6 +268,69 @@ static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
updateStringLiteralType(Str, DeclT);
}
+template <class Predicate, class RecordFilter>
+std::enable_if_t<std::is_void_v<decltype(std::declval<Predicate &>()(
+ std::declval<const FieldDecl *>()))>,
+ size_t>
+forEachFieldRecursive(const RecordDecl *Record, Predicate FieldPred,
+ RecordFilter RecordPreFilter) {
+ size_t NumFound = 0;
+ SmallVector<const RecordDecl *> Stack;
+ llvm::SmallDenseSet<const RecordDecl *> Seen;
+ Stack.push_back(Record);
+ while (!Stack.empty()) {
+ const RecordDecl *RD = Stack.back();
+ Stack.pop_back();
+ const size_t OldStackSize = Stack.size();
+ if (RD) {
+ RD = dyn_cast_if_present<RecordDecl>(RD->getCanonicalDecl());
+ }
+ if (RD && Seen.insert(RD).second && RecordPreFilter(RD)) {
+ for (const FieldDecl *Field : RD->fields()) {
+ FieldPred(Field);
+ ++NumFound;
+ QualType FieldType = Field->getType();
+ if (!FieldType.isNull()) {
+ const RecordDecl *FieldRD = FieldType->getAsRecordDecl();
+ if (FieldRD && !Seen.contains(FieldRD) && RecordPreFilter(FieldRD)) {
+ Stack.push_back(FieldRD);
+ }
+ }
+ }
+ if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
+ CXXRD->forallBases([&](const CXXRecordDecl *Base) {
+ if (Base) {
+ Base = Base->getCanonicalDecl();
+ }
+ if (Base && !Seen.contains(Base) && RecordPreFilter(Base)) {
+ Stack.push_back(Base);
+ }
+ return true;
+ });
+ }
+ }
+ // Preserve push order when popping
+ std::reverse(Stack.begin() + OldStackSize, Stack.end());
+ }
+ return NumFound;
+}
+
+size_t emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R) {
+ size_t NumFound = 0;
+ forEachFieldRecursive(
+ R,
+ [&](const FieldDecl *FD) {
+ if (FD->hasAttr<ExplicitInitAttr>()) {
+ S.Diag(FD->getLocation(), diag::note_entity_declared_at) << FD;
+ ++NumFound;
+ }
+ },
+ [](const RecordDecl *RD) {
+ return RD->hasUninitializedExplicitInitFields();
+ });
+ return NumFound;
+}
+
//===----------------------------------------------------------------------===//
// Semantic checking for initializer lists.
//===----------------------------------------------------------------------===//
@@ -746,7 +809,7 @@ void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>()) {
SemaRef.Diag(ILE->getExprLoc(), diag::warn_field_requires_explicit_init)
- << Field;
+ << /* Var-in-Record */ 0 << Field;
SemaRef.Diag(Field->getLocation(), diag::note_entity_declared_at)
<< Field;
}
@@ -4573,7 +4636,8 @@ static void TryConstructorInitialization(Sema &S,
DestRecordDecl != nullptr && DestRecordDecl->isAggregate() &&
DestRecordDecl->hasUninitializedExplicitInitFields()) {
S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init)
- << "in class";
+ << /* Var-in-Record */ 1 << DestRecordDecl;
+ emitUninitializedExplicitInitFields(S, DestRecordDecl);
}
// C++11 [dcl.init]p6:
@@ -6472,6 +6536,19 @@ void InitializationSequence::InitializeFrom(Sema &S,
}
}
+ if (!S.getLangOpts().CPlusPlus &&
+ Kind.getKind() == InitializationKind::IK_Default) {
+ RecordDecl *Rec = DestType->getAsRecordDecl();
+ if (Rec && Rec->hasUninitializedExplicitInitFields()) {
+ VarDecl *Var = dyn_cast_or_null<VarDecl>(Entity.getDecl());
+ if (Var && !Initializer) {
+ S.Diag(Var->getLocation(), diag::warn_field_requires_explicit_init)
+ << /* Var-in-Record */ 1 << Rec;
+ emitUninitializedExplicitInitFields(S, Rec);
+ }
+ }
+ }
+
// - If the destination type is a reference type, see 8.5.3.
if (DestType->isReferenceType()) {
// C++0x [dcl.init.ref]p1:
diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp b/clang/lib/Serialization/ASTReaderDecl.cpp
index 9272e23c7da3fc..b53aa8a649ae6b 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -859,6 +859,7 @@ RedeclarableResult ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
RecordDeclBits.getNextBit());
RD->setHasNonTrivialToPrimitiveDestructCUnion(RecordDeclBits.getNextBit());
RD->setHasNonTrivialToPrimitiveCopyCUnion(RecordDeclBits.getNextBit());
+ RD->setHasUninitializedExplicitInitFields(RecordDeclBits.getNextBit());
RD->setParamDestroyedInCallee(RecordDeclBits.getNextBit());
RD->setArgPassingRestrictions(
(RecordArgPassingKind)RecordDeclBits.getNextBits(/*Width=*/2));
diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp b/clang/lib/Serialization/ASTWriterDecl.cpp
index 555f6325da646b..92145831e4db64 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -574,6 +574,7 @@ void ASTDeclWriter::VisitRecordDecl(RecordDecl *D) {
RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveDefaultInitializeCUnion());
RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveDestructCUnion());
RecordDeclBits.addBit(D->hasNonTrivialToPrimitiveCopyCUnion());
+ RecordDeclBits.addBit(D->hasUninitializedExplicitInitFields());
RecordDeclBits.addBit(D->isParamDestroyedInCallee());
RecordDeclBits.addBits(llvm::to_underlying(D->getArgPassingRestrictions()), 2);
Record.push_back(RecordDeclBits);
@@ -2407,7 +2408,8 @@ void ASTWriter::WriteDeclAbbrevs() {
// isNonTrivialToPrimitiveCopy, isNonTrivialToPrimitiveDestroy,
// hasNonTrivialToPrimitiveDefaultInitializeCUnion,
// hasNonTrivialToPrimitiveDestructCUnion,
- // hasNonTrivialToPrimitiveCopyCUnion, isParamDestroyedInCallee,
+ // hasNonTrivialToPrimitiveCopyCUnion,
+ // hasUninitializedExplicitInitFields, isParamDestroyedInCallee,
// getArgPassingRestrictions
// ODRHash
Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 26));
diff --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index 5cc220e193b28d..baa1816358b156 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -77,7 +77,6 @@
// CHECK-NEXT: EnumExtensibility (SubjectMatchRule_enum)
// CHECK-NEXT: Error (SubjectMatchRule_function)
// CHECK-NEXT: ExcludeFromExplicitInstantiation (SubjectMatchRule_variable, SubjectMatchRule_function, SubjectMatchRule_record)
-// CHECK-NEXT: ExplicitInit (SubjectMatchRule_field)
// CHECK-NEXT: ExternalSourceSymbol ((SubjectMatchRule_record, SubjectMatchRule_enum, SubjectMatchRule_enum_constant, SubjectMatchRule_field, SubjectMatchRule_function, SubjectMatchRule_namespace, SubjectMatchRule_objc_category, SubjectMatchRule_objc_implementation, SubjectMatchRule_objc_interface, SubjectMatchRule_objc_method, SubjectMatchRule_objc_property, SubjectMatchRule_objc_protocol, SubjectMatchRule_record, SubjectMatchRule_type_alias, SubjectMatchRule_variable))
// CHECK-NEXT: FlagEnum (SubjectMatchRule_enum)
// CHECK-NEXT: Flatten (SubjectMatchRule_function)
diff --git a/clang/test/Sema/uninit-variables.c b/clang/test/Sema/uninit-variables.c
index 70a00793fd29ed..c7c478bc8815c5 100644
--- a/clang/test/Sema/uninit-variables.c
+++ b/clang/test/Sema/uninit-variables.c
@@ -551,3 +551,14 @@ struct full_of_empty empty_test_2(void) {
struct full_of_empty e;
return e; // no-warning
}
+
+struct with_explicit_field {
+ int x;
+ int y [[clang::requires_explicit_initialization]]; // expected-note 2{{'y' declared here}}
+};
+
+void aggregate() {
+ struct with_explicit_field a; // expected-warning {{field in 'with_explicit_field' is not explicitly initialized, but was marked as requiring explicit initialization}}
+ struct with_explicit_field b = {1}; // expected-warning {{field 'y' is not explicitly initialized, but was marked as requiring explicit initialization}}
+ (void)(&a != &b);
+}
diff --git a/clang/test/SemaCXX/uninitialized.cpp b/clang/test/SemaCXX/uninitialized.cpp
index 37cf6d1dd60c0a..e7fb80dc3046bf 100644
--- a/clang/test/SemaCXX/uninitialized.cpp
+++ b/clang/test/SemaCXX/uninitialized.cpp
@@ -1474,47 +1474,54 @@ template<typename T> struct Outer {
Outer<int>::Inner outerinner;
void aggregate() {
+ struct NonAgg {
+ NonAgg() { }
+ [[clang::requires_explicit_initialization]] int f; // expected-warning {{'requires_explicit_initialization' attribute is ignored in non-aggregate type 'NonAgg'}}
+ };
+ NonAgg nonagg; // no-warning
+ (void)nonagg;
+
struct S {
- [[clang::requires_explicit_initialization]] int x; // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}}
+ [[clang::requires_explicit_initialization]] int x; // expected-note 7{{'x' declared here}}
int y;
int z = 12;
- [[clang::requires_explicit_initialization]] int q = 100; // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}}
+ [[clang::requires_explicit_initialization]] int q = 100; // expected-note 7{{'q' declared here}}
static void foo(S) { }
};
- struct D : S { // expected-warning {{not explicitly initialized}}
+ struct D : S { // expected-warning {{field in 'S' is not explicitly initialized, but was marked as requiring explicit initialization}}
int f1;
- int f2 [[clang::requires_explicit_initialization]]; // expected-note {{declared}} // expected-note {{declared}}
+ int f2 [[clang::requires_explicit_initialization]]; // expected-note 3{{'f2' declared here}}
};
struct C {
- [[clang::requires_explicit_initialization]] int w;
+ [[clang::requires_explicit_initialization]] int w; // expected-note {{'w' declared here}}
C() = default; // Test pre-C++20 aggregates
};
S::foo(S{1, 2, 3, 4});
S::foo(S{.x = 100, .q = 100});
- S::foo(S{.x = 100}); // expected-warning {{'q' is not explicitly initialized}}
+ S::foo(S{.x = 100}); // expected-warning {{field 'q' is not explicitly initialized, but was marked as requiring explicit initialization}}
S s{.x = 100, .q = 100};
(void)s;
- S t{.q = 100}; // expected-warning {{'x' is not explicitly initialized}}
+ S t{.q = 100}; // expected-warning {{field 'x' is not explicitly initialized, but was marked as requiring explicit initialization}}
(void)t;
- S *ptr1 = new S; // expected-warning {{not explicitly initialized}}
+ S *ptr1 = new S; // expected-warning {{field in 'S' is not explicitly initialized, but was marked as requiring explicit initialization}}
delete ptr1;
S *ptr2 = new S{.x = 100, .q = 100};
delete ptr2;
#if __cplusplus >= 202002L
- D a({}, 0); // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'f2' is not explicitly initialized}}
+ D a({}, 0); // expected-warning {{field 'x' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-warning {{field 'f2' is not explicitly initialized, but was marked as requiring explicit initialization}}
(void)a;
#else
- C a; // expected-warning {{not explicitly initialized}}
+ C a; // expected-warning {{field in 'C' is not explicitly initialized, but was marked as requiring explicit initialization}}
(void)a;
#endif
- D b{.f2 = 1}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}}
+ D b{.f2 = 1}; // expected-warning {{field 'x' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-warning {{field 'q' is not explicitly initialized, but was marked as requiring explicit initialization}}
(void)b;
- D c{.f1 = 5}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}} expected-warning {{'f2' is not explicitly initialized}}
- c = {{}, 0}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}} expected-warning {{'f2' is not explicitly initialized}}
+ D c{.f1 = 5}; // expected-warning {{field 'x' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-warning {{field 'q' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-warning {{field 'f2' is not explicitly initialized, but was marked as requiring explicit initialization}}
+ c = {{}, 0}; // expected-warning {{field 'x' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-warning {{field 'q' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-warning {{field 'f2' is not explicitly initialized, but was marked as requiring explicit initialization}}
(void)c;
- D d; // expected-warning {{not explicitly initialized}} // expected-note {{constructor}}
+ D d; // expected-warning {{field in 'D' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-note {{in implicit default constructor for 'D' first required here}}
(void)d;
}
More information about the cfe-commits
mailing list