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.git...@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 10ea390dcfe5bd3189da59a77240603dc0232606 Mon Sep 17 00:00:00 2001 From: higher-performance <higher.performance.git...@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/AST/Type.h | 9 ++++++ 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/AST/Type.cpp | 4 +++ clang/lib/Sema/SemaDecl.cpp | 3 ++ clang/lib/Sema/SemaInit.cpp | 16 ++++++++-- clang/lib/Serialization/ASTReaderDecl.cpp | 1 + ...a-attribute-supported-attributes-list.test | 1 - clang/test/Sema/uninit-variables.c | 11 +++++++ clang/test/SemaCXX/uninitialized.cpp | 7 ++++ 17 files changed, 118 insertions(+), 41 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/AST/Type.h b/clang/include/clang/AST/Type.h index ef36a73716454f..18bec21395aa56 100644 --- a/clang/include/clang/AST/Type.h +++ b/clang/include/clang/AST/Type.h @@ -1560,6 +1560,8 @@ class QualType { /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. bool hasNonTrivialToPrimitiveCopyCUnion() const; + bool hasUninitializedExplicitInitFields() const; + /// Determine whether expressions of the given type are forbidden /// from being lvalues in C. /// @@ -1641,6 +1643,7 @@ class QualType { static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); + static bool hasUninitializedExplicitInitFields(const RecordDecl *RD); }; raw_ostream &operator<<(raw_ostream &OS, QualType QT); @@ -7961,6 +7964,12 @@ inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { return false; } +inline bool QualType::hasUninitializedExplicitInitFields() const { + if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) + return hasUninitializedExplicitInitFields(RD); + return false; +} + inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { if (const auto *PT = t.getAs<PointerType>()) { if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) 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..bbd59a386c7283 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/AST/Type.cpp b/clang/lib/AST/Type.cpp index a55e6c8bf02611..ed6a2a25b4a7e4 100644 --- a/clang/lib/AST/Type.cpp +++ b/clang/lib/AST/Type.cpp @@ -2837,6 +2837,10 @@ bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) { return RD->hasNonTrivialToPrimitiveCopyCUnion(); } +bool QualType::hasUninitializedExplicitInitFields(const RecordDecl *RD) { + return RD->hasUninitializedExplicitInitFields(); +} + bool QualType::isWebAssemblyReferenceType() const { return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType(); } 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..13072188cbce20 100644 --- a/clang/lib/Sema/SemaInit.cpp +++ b/clang/lib/Sema/SemaInit.cpp @@ -746,7 +746,7 @@ void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>()) { SemaRef.Diag(ILE->getExprLoc(), diag::warn_field_requires_explicit_init) - << Field; + << false << Field; SemaRef.Diag(Field->getLocation(), diag::note_entity_declared_at) << Field; } @@ -4573,7 +4573,7 @@ static void TryConstructorInitialization(Sema &S, DestRecordDecl != nullptr && DestRecordDecl->isAggregate() && DestRecordDecl->hasUninitializedExplicitInitFields()) { S.Diag(Kind.getLocation(), diag::warn_field_requires_explicit_init) - << "in class"; + << true << DestRecordDecl; } // C++11 [dcl.init]p6: @@ -6472,6 +6472,18 @@ 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) + << true << 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/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..8a19966630c26e 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 {{declared}} +}; + +void aggregate() { + struct with_explicit_field a; // expected-warning {{is not explicitly initialized}} + struct with_explicit_field b = {1}; // expected-warning {{is not explicitly initialized}} + (void)(&a != &b); +} diff --git a/clang/test/SemaCXX/uninitialized.cpp b/clang/test/SemaCXX/uninitialized.cpp index 37cf6d1dd60c0a..85e11c85d30f7a 100644 --- a/clang/test/SemaCXX/uninitialized.cpp +++ b/clang/test/SemaCXX/uninitialized.cpp @@ -1474,6 +1474,13 @@ template<typename T> struct Outer { Outer<int>::Inner outerinner; void aggregate() { + struct NonAgg { + NonAgg() { } + [[clang::requires_explicit_initialization]] int f; // expected-warning {{attribute is ignored}} + }; + NonAgg nonagg; + (void)nonagg; + struct S { [[clang::requires_explicit_initialization]] int x; // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}} // expected-note {{declared}} int y; _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits