https://github.com/rapidsna updated https://github.com/llvm/llvm-project/pull/233582
>From 8c1fd59605f9d2384c1946e4e5b42b7510b5f8c4 Mon Sep 17 00:00:00 2001 From: Yeoul Na <[email protected]> Date: Fri, 18 Sep 2026 00:28:21 -0700 Subject: [PATCH 1/3] [BoundsSafety] Handle the counted_by family as a type attribute (non-late parsing only) counted_by / sized_by (and their _or_null variants) were handled as declaration-position attributes through handleCountedByAttrField. Build the type during type construction instead, and handle them properly as type-position attributes. Building the node in type position also allows the new way of late-parsing type attributes: create a type node in place and fill it in once late parsing is done. That will be enabled in follow-up commits. User-visible changes: - [[clang::counted_by]] on a field's pointer declarator, as in `int * [[clang::counted_by(n)]] p;`, is now accepted instead of being rejected as "cannot be applied to types". It's still rejected on a non-field declarator chunk. - A counted_by-family attribute on a nested pointer, as in `int *__counted_by(n) *pp;`, is now rejected. It was previously applied to the outer pointer instead. - A counted_by-family attribute on a function return type is now diagnosed as not yet supported. - A second counted_by-family attribute on the same pointer is now an error (without -fbounds-safety). - A counted_by-family attribute on an Objective-C instance variable is now supported; it previously hit an assertion. Under -fexperimental-late-parse-attributes, the GNU spelling is still late-parsed and handled as a declaration attribute. The [[]] spelling isn't late-parsed, so it's handled as a type attribute in both modes. Assisted-by: Opus 5.5 --- .../clang/Basic/DiagnosticSemaKinds.td | 6 + clang/include/clang/Sema/Sema.h | 36 ++- clang/lib/Sema/SemaBoundsSafety.cpp | 233 +++++++----------- clang/lib/Sema/SemaDeclAttr.cpp | 47 ++-- clang/lib/Sema/SemaType.cpp | 166 ++++++++++++- .../AST/attr-counted-by-or-null-struct-ptrs.c | 23 -- clang/test/AST/attr-counted-by-rejected.c | 29 +++ clang/test/AST/attr-counted-by-struct-ptrs.c | 50 ++-- .../AST/attr-sized-by-or-null-struct-ptrs.c | 24 -- clang/test/AST/attr-sized-by-struct-ptrs.c | 24 -- .../attr-counted-by-multiple-on-pointer.c | 84 +++++++ ...ruct-ptrs-completable-incomplete-pointee.c | 13 +- .../attr-counted-by-or-null-struct-ptrs.c | 16 +- clang/test/Sema/attr-counted-by-return-type.c | 55 +++++ .../attr-counted-by-std-syntax-on-chunk.c | 21 ++ ...ruct-ptrs-completable-incomplete-pointee.c | 9 +- clang/test/Sema/attr-counted-by-struct-ptrs.c | 46 +++- clang/test/Sema/attr-counted-by-vla.c | 8 + .../Sema/attr-sized-by-or-null-struct-ptrs.c | 16 +- clang/test/Sema/attr-sized-by-struct-ptrs.c | 16 +- clang/test/SemaObjC/attr-counted-by-ivar.m | 44 ++++ 21 files changed, 661 insertions(+), 305 deletions(-) create mode 100644 clang/test/AST/attr-counted-by-rejected.c create mode 100644 clang/test/Sema/attr-counted-by-multiple-on-pointer.c create mode 100644 clang/test/Sema/attr-counted-by-return-type.c create mode 100644 clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c create mode 100644 clang/test/SemaObjC/attr-counted-by-ivar.m diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 4e3f729b4f36d4..b7d0c1d9b96c5b 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -7281,6 +7281,12 @@ def note_counted_by_counter_field : Note< def err_counted_by_on_nested_pointer : Error< "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' attribute on nested pointer type is not allowed">; +def err_counted_by_on_return_type : Error< + "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' attribute on a function return type is not yet supported">; +def err_counted_by_on_bounds_attributed_type : Error< + "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}0' attribute " + "cannot be applied to a pointer that already has a " + "'%select{counted_by|sized_by|counted_by_or_null|sized_by_or_null}1' attribute">; let CategoryName = "ARC Semantic Issue" in { diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index ba215e7e18d7ba..8fc823a159092a 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -2557,21 +2557,38 @@ class Sema final : public SemaBase { bool UpdateFlags = true); /// Check a counted_by-family attribute in type position and initialize - /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer, array - /// and function declarator chunks enclosing the attribute. + /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer and + /// array declarator chunks enclosing the attribute, up to the nearest + /// function chunk. \p OnReturnType is true if a function chunk encloses it, + /// i.e. the attribute is in a function's return type. /// /// \returns false after diagnosing an attribute that must be dropped (see /// ValidateBoundsAttrTypeShape). bool ValidateBoundsAttrTypeForTypePosition( QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc, - SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags &Flags); + SourceRange AttrRange, unsigned PointerNestLevel, bool OnReturnType, + BoundsAttrFlags &Flags); - /// Check if applying the specified attribute variant from the "counted by" - /// family of attributes to FieldDecl \p FD is semantically valid. If - /// semantically invalid diagnostics will be emitted explaining the problems. + /// Check where a counted_by-family attribute of kind \p Kind sits in its + /// declarator, as described by \p PointerNestLevel and \p OnReturnType (see + /// ValidateBoundsAttrTypeForTypePosition). /// - /// \param FD The FieldDecl to apply the attribute to + /// \returns false after diagnosing an attribute in an unsupported position. + bool ValidateBoundsAttrPosition(BoundsAttributedType::BoundsAttrKind Kind, + SourceLocation AttrLoc, SourceRange AttrRange, + unsigned PointerNestLevel, bool OnReturnType); + + /// Check if applying the specified attribute variant from the "counted by" + /// family of attributes to a field of record \p RD, with type \p Ty, is + /// semantically valid. If semantically invalid diagnostics will be emitted + /// explaining the problems. This doesn't need the FieldDecl, so it can run + /// before the field's type is built. + /// + /// \param DC The record the field is declared in, or the Objective-C + /// container of an instance variable + /// \param Ty The type the attribute applies to /// \param E The count expression on the attribute + /// \param Loc, Range Where to report problems with the field itself /// \param CountInBytes If true the attribute is from the "sized_by" family of /// attributes. If the false the attribute is from /// "counted_by" family of attributes. @@ -2584,6 +2601,11 @@ class Sema final : public SemaBase { /// `counted_by_or_null` attribute. /// /// \returns false iff semantically valid. + bool CheckCountedByAttrInRecord(const DeclContext *DC, QualType Ty, Expr *E, + SourceLocation Loc, SourceRange Range, + bool CountInBytes, bool OrNull); + + /// Like CheckCountedByAttrInRecord, for the field \p FD. bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, bool OrNull); diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp index cebc680297cd9c..dd78f335a0844c 100644 --- a/clang/lib/Sema/SemaBoundsSafety.cpp +++ b/clang/lib/Sema/SemaBoundsSafety.cpp @@ -54,8 +54,8 @@ Sema::BoundsAttrFlags Sema::BoundsAttrFlags::get(AttributeCommonInfo::Kind K) { return Flags; } -static const RecordDecl *GetEnclosingNamedOrTopAnonRecord(const FieldDecl *FD) { - const auto *RD = FD->getParent(); +static const RecordDecl * +GetEnclosingNamedOrTopAnonRecord(const RecordDecl *RD) { // An unnamed struct is treated as anonymous struct at this point. // A struct may not be fully processed yet to determine // whether it's anonymous or not. In that case, this function treats it as @@ -100,6 +100,19 @@ bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc, BoundsAttributedType::BoundsAttrKind Kind = getBoundsAttrKind(Flags); + // A pointer takes only one bounds attribute. This sees one applied eagerly + // or late, since a late-parsed one is an incomplete CountAttributedType until + // its count is parsed. + // + // TODO: Converge with the -fbounds-safety attribute model checks in + // checkBoundsAttrTypeConflictsAndMisc. + if (!getLangOpts().hasBoundsSafetyAttributes()) + if (const auto *CATy = Ty->getAs<CountAttributedType>()) { + Diag(AttrLoc, diag::err_counted_by_on_bounds_attributed_type) + << Kind << CATy->getKind() << AttrRange; + return false; + } + // counted_by and sized_by require a pointer or array. if (!Ty->isPointerType() && !Ty->isArrayType()) { Diag(AttrLoc, diag::err_count_attr_not_on_ptr_or_flexible_array_member) @@ -164,7 +177,7 @@ bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc, // Exception: void has an implicit size of 1 byte for pointer arithmetic // (following GNU convention). Therefore, counted_by on void* is allowed // and behaves equivalently to sized_by (treating the count as bytes). - if (PointeeTy->isVoidType() && !getLangOpts().hasBoundsSafetyAttributes()) { + if (PointeeTy->isVoidType()) { // Emit a warning that this is a GNU extension. Diag(AttrLoc, diag::ext_gnu_counted_by_void_ptr) << Kind; Diag(AttrLoc, diag::note_gnu_counted_by_void_ptr_use_sized_by) << Kind; @@ -180,7 +193,7 @@ bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc, InvalidTypeKind = CountedByInvalidPointeeTypeKind::FUNCTION; } else if (!Flags.CountInBytes && PointeeTy->isStructureTypeWithFlexibleArrayMember()) { - if (Ty->isArrayType()) { + if (!getLangOpts().BoundsSafety && Ty->isArrayType()) { // This is a workaround for the Linux kernel that has already adopted // `counted_by` on a FAM where the pointee is a struct with a FAM. This // should be an error because computing the bounds of the array cannot @@ -213,15 +226,18 @@ bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc, return true; } -bool Sema::ValidateBoundsAttrTypeForTypePosition( - QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc, - SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags &Flags) { - Flags = BoundsAttrFlags::get(AttrKind); - - if (!ValidateBoundsAttrTypeShape(Ty, AttrLoc, AttrRange, Flags, - /*AttrSpelling=*/{}, /*AllowRedecl=*/false, - /*AttrArg=*/nullptr, /*UpdateFlags=*/false)) +bool Sema::ValidateBoundsAttrPosition(BoundsAttributedType::BoundsAttrKind Kind, + SourceLocation AttrLoc, + SourceRange AttrRange, + unsigned PointerNestLevel, + bool OnReturnType) { + // FIXME: Support function return types, with a count that refers to the + // function's parameters. Their nesting is then checked below, relative to + // the return type. + if (OnReturnType) { + Diag(AttrLoc, diag::err_counted_by_on_return_type) << Kind << AttrRange; return false; + } // Currently, only attributes at the outermost level of the declared type // are supported. @@ -230,143 +246,57 @@ bool Sema::ValidateBoundsAttrTypeForTypePosition( // void f(int *__counted_by(*len) *buf, int *len); // See https://github.com/llvm/llvm-project/issues/166411. if (PointerNestLevel > 0) { - Diag(AttrLoc, diag::err_counted_by_on_nested_pointer) - << getBoundsAttrKind(Flags); + Diag(AttrLoc, diag::err_counted_by_on_nested_pointer) << Kind; return false; } return true; } -bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, - bool OrNull) { - // Check the context the attribute is used in +bool Sema::ValidateBoundsAttrTypeForTypePosition( + QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc, + SourceRange AttrRange, unsigned PointerNestLevel, bool OnReturnType, + BoundsAttrFlags &Flags) { + Flags = BoundsAttrFlags::get(AttrKind); - unsigned Kind = getCountAttrKind(CountInBytes, OrNull); + if (!ValidateBoundsAttrTypeShape(Ty, AttrLoc, AttrRange, Flags, + /*AttrSpelling=*/{}, /*AllowRedecl=*/false, + /*AttrArg=*/nullptr, /*UpdateFlags=*/false)) + return false; - if (FD->getParent()->isUnion()) { - Diag(FD->getBeginLoc(), diag::err_count_attr_in_union) - << Kind << FD->getSourceRange(); - return true; - } + if (!ValidateBoundsAttrPosition(getBoundsAttrKind(Flags), AttrLoc, AttrRange, + PointerNestLevel, OnReturnType)) + return false; - const auto FieldTy = FD->getType(); - if (FieldTy->isArrayType() && (CountInBytes || OrNull)) { - Diag(FD->getBeginLoc(), - diag::err_count_attr_not_on_ptr_or_flexible_array_member) - << Kind << FD->getLocation() << /* suggest counted_by */ 1; - return true; - } - if (!FieldTy->isArrayType() && !FieldTy->isPointerType()) { - Diag(FD->getBeginLoc(), - diag::err_count_attr_not_on_ptr_or_flexible_array_member) - << Kind << FD->getLocation() << /* do not suggest counted_by */ 0; - return true; - } + return true; +} - LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel = - LangOptions::StrictFlexArraysLevelKind::IncompleteOnly; - if (FieldTy->isArrayType() && - !Decl::isFlexibleArrayMemberLike(getASTContext(), FD, FieldTy, - StrictFlexArraysLevel, true)) { - Diag(FD->getBeginLoc(), - diag::err_counted_by_attr_on_array_not_flexible_array_member) - << Kind << FD->getLocation(); - return true; - } +bool Sema::CheckCountedByAttrInRecord(const DeclContext *DC, QualType Ty, + Expr *E, SourceLocation Loc, + SourceRange Range, bool CountInBytes, + bool OrNull) { + unsigned Kind = getCountAttrKind(CountInBytes, OrNull); - CountedByInvalidPointeeTypeKind InvalidTypeKind = - CountedByInvalidPointeeTypeKind::VALID; - QualType PointeeTy; - int SelectPtrOrArr = 0; - if (FieldTy->isPointerType()) { - PointeeTy = FieldTy->getPointeeType(); - SelectPtrOrArr = 0; - } else { - assert(FieldTy->isArrayType()); - const ArrayType *AT = getASTContext().getAsArrayType(FieldTy); - PointeeTy = AT->getElementType(); - SelectPtrOrArr = 1; - } - // Note: The `Decl::isFlexibleArrayMemberLike` check earlier on means - // only `PointeeTy->isStructureTypeWithFlexibleArrayMember()` is reachable - // when `FieldTy->isArrayType()`. - bool ShouldWarn = false; - if (!CountInBytes && PointeeTy->isAlwaysIncompleteType()) { - // In general using `counted_by` or `counted_by_or_null` on - // pointers where the pointee is an incomplete type are problematic. This is - // because it isn't possible to compute the pointer's bounds without knowing - // the pointee type size. At the same time it is common to forward declare - // types in header files. - // - // E.g.: - // - // struct Handle; - // struct Wrapper { - // size_t count; - // struct Handle* __counted_by(count) handles; - // } - // - // To allow the above code pattern but still prevent the pointee type from - // being incomplete in places where bounds checks are needed the following - // scheme is used: - // - // * When the pointee type might not always be an incomplete type (i.e. - // a type that is currently incomplete but might be completed later - // on in the translation unit) the attribute is allowed by this method - // but later uses of the FieldDecl are checked that the pointee type - // is complete see `BoundsSafetyCheckAssignmentToCountAttrPtr`, - // `BoundsSafetyCheckInitialization`, and - // `BoundsSafetyCheckUseOfCountAttrPtr` - // - // * When the pointee type is always an incomplete type (e.g. - // `void` in strict C mode) the attribute is disallowed by this method - // because we know the type can never be completed so there's no reason - // to allow it. - // - // Exception: void has an implicit size of 1 byte for pointer arithmetic - // (following GNU convention). Therefore, counted_by on void* is allowed - // and behaves equivalently to sized_by (treating the count as bytes). - bool IsVoidPtr = PointeeTy->isVoidType(); - if (IsVoidPtr) { - // Emit a warning that this is a GNU extension. - Diag(FD->getBeginLoc(), diag::ext_gnu_counted_by_void_ptr) << Kind; - Diag(FD->getBeginLoc(), diag::note_gnu_counted_by_void_ptr_use_sized_by) - << Kind; - assert(InvalidTypeKind == CountedByInvalidPointeeTypeKind::VALID); - } else { - InvalidTypeKind = CountedByInvalidPointeeTypeKind::INCOMPLETE; - } - } else if (PointeeTy->isSizelessType()) { - InvalidTypeKind = CountedByInvalidPointeeTypeKind::SIZELESS; - } else if (PointeeTy->isFunctionType()) { - InvalidTypeKind = CountedByInvalidPointeeTypeKind::FUNCTION; - } else if (!CountInBytes && - PointeeTy->isStructureTypeWithFlexibleArrayMember()) { - if (FieldTy->isArrayType() && !getLangOpts().BoundsSafety) { - // This is a workaround for the Linux kernel that has already adopted - // `counted_by` on a FAM where the pointee is a struct with a FAM. This - // should be an error because computing the bounds of the array cannot be - // done correctly without manually traversing every struct object in the - // array at runtime. To allow the code to be built this error is - // downgraded to a warning. - ShouldWarn = true; - } - InvalidTypeKind = CountedByInvalidPointeeTypeKind::FLEXIBLE_ARRAY_MEMBER; - } + // Check the context the attribute is used in. It's null for an Objective-C + // instance variable. + const auto *RD = dyn_cast<RecordDecl>(DC); + assert((RD || isa<ObjCContainerDecl>(DC)) && "not a field or an ivar"); - if (InvalidTypeKind != CountedByInvalidPointeeTypeKind::VALID) { - unsigned DiagID = ShouldWarn - ? diag::warn_counted_by_attr_elt_type_unknown_size - : diag::err_counted_by_attr_pointee_unknown_size; - Diag(FD->getBeginLoc(), DiagID) - << SelectPtrOrArr << PointeeTy << (int)InvalidTypeKind - << (ShouldWarn ? 1 : 0) << Kind << FD->getSourceRange(); + if (RD && RD->isUnion()) { + Diag(Loc, diag::err_count_attr_in_union) << Kind << Range; return true; } - // Check the expression + // Only a flexible array member takes the attribute among arrays. Whether it's + // the last field isn't known until the record is complete; ActOnFields + // rejects a flexible array member that isn't. + if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) { + Diag(Loc, diag::err_counted_by_attr_on_array_not_flexible_array_member) + << Kind << Range; + return true; + } + // Validate the expression type if (!E->getType()->isIntegerType() || E->getType()->isBooleanType()) { Diag(E->getBeginLoc(), diag::err_count_attr_argument_not_integer) << Kind << E->getSourceRange(); @@ -381,6 +311,7 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, return true; } + // Validate count field references auto *CountDecl = DRE->getDecl(); FieldDecl *CountFD = dyn_cast<FieldDecl>(CountDecl); if (auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl)) { @@ -396,8 +327,25 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, return true; } - if (FD->getParent() != CountFD->getParent()) { - if (CountFD->getParent()->isUnion()) { + // A field's count can't be an instance variable, as in a struct declared in + // an ivar list. An instance variable's count is one of the same ivar list, + // which is all name lookup finds there. + const auto *CountRD = dyn_cast<RecordDecl>(CountFD->getDeclContext()); + if (!RD || !CountRD) { + assert((RD || DC == CountFD->getDeclContext()) && + "ivar count outside its ivar list"); + if (!RD) + return false; + Diag(E->getBeginLoc(), diag::err_count_attr_param_not_in_same_struct) + << CountFD << Kind << Ty->isArrayType() << E->getSourceRange(); + Diag(CountFD->getBeginLoc(), + diag::note_flexible_array_counted_by_attr_field) + << CountFD << CountFD->getSourceRange(); + return true; + } + + if (RD != CountRD) { + if (CountRD->isUnion()) { Diag(CountFD->getBeginLoc(), diag::err_count_attr_refer_to_union) << Kind << CountFD->getSourceRange(); return true; @@ -405,12 +353,12 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, // Whether CountRD is an anonymous struct is not determined at this // point. Thus, an additional diagnostic in case it's not anonymous struct // is done later in `Parser::ParseStructDeclaration`. - auto *RD = GetEnclosingNamedOrTopAnonRecord(FD); - auto *CountRD = GetEnclosingNamedOrTopAnonRecord(CountFD); + auto *TopRD = GetEnclosingNamedOrTopAnonRecord(RD); + auto *TopCountRD = GetEnclosingNamedOrTopAnonRecord(CountRD); - if (RD != CountRD) { + if (TopRD != TopCountRD) { Diag(E->getBeginLoc(), diag::err_count_attr_param_not_in_same_struct) - << CountFD << Kind << FieldTy->isArrayType() << E->getSourceRange(); + << CountFD << Kind << Ty->isArrayType() << E->getSourceRange(); Diag(CountFD->getBeginLoc(), diag::note_flexible_array_counted_by_attr_field) << CountFD << CountFD->getSourceRange(); @@ -420,6 +368,13 @@ bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, return false; } +bool Sema::CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, + bool OrNull) { + return CheckCountedByAttrInRecord(FD->getDeclContext(), FD->getType(), E, + FD->getBeginLoc(), FD->getSourceRange(), + CountInBytes, OrNull); +} + static void EmitIncompleteCountedByPointeeNotes(Sema &S, const CountAttributedType *CATy, NamedDecl *IncompleteTyDecl) { diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index e57f1de9c11007..7337a88948b286 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -7109,41 +7109,34 @@ static void handleNoPFPAttrField(Sema &S, Decl *D, const ParsedAttr &AL) { D->addAttr(NoFieldProtectionAttr::Create(S.Context, AL)); } +// Only reached for a GNU counted_by-family attribute that +// -fexperimental-late-parse-attributes late-parses as a declaration attribute; +// every other one is handled by HandleCountedByAttrOnType. +// FIXME: Remove once late parsing switches over to the type-attribute path. static void handleCountedByAttrField(Sema &S, Decl *D, const ParsedAttr &AL) { + // Already applied, or diagnosed, as a type attribute. + if (AL.isUsedAsTypeAttr()) + return; + auto *CountExpr = AL.getArgAsExpr(0); if (!CountExpr) return; - bool CountInBytes; - bool OrNull; - switch (AL.getKind()) { - case ParsedAttr::AT_CountedBy: - CountInBytes = false; - OrNull = false; - break; - case ParsedAttr::AT_CountedByOrNull: - CountInBytes = false; - OrNull = true; - break; - case ParsedAttr::AT_SizedBy: - CountInBytes = true; - OrNull = false; - break; - case ParsedAttr::AT_SizedByOrNull: - CountInBytes = true; - OrNull = true; - break; - default: - llvm_unreachable("unexpected counted_by family attribute"); - } - - FieldDecl *FD = cast<FieldDecl>(D); - if (S.CheckCountedByAttrOnField(FD, CountExpr, CountInBytes, OrNull)) + auto *FD = cast<FieldDecl>(D); + Sema::BoundsAttrFlags Flags = Sema::BoundsAttrFlags::get(AL.getKind()); + if (!S.ValidateBoundsAttrTypeShape(FD->getType(), AL.getLoc(), AL.getRange(), + Flags, /*AttrSpelling=*/{}, + /*AllowRedecl=*/false, /*AttrArg=*/nullptr, + /*UpdateFlags=*/false)) + return; + if (S.CheckCountedByAttrOnField(FD, CountExpr, Flags.CountInBytes, + Flags.OrNull)) return; QualType CAT = S.BuildCountAttributedArrayOrPointerType( - FD->getType(), CountExpr, CountInBytes, OrNull); - FD->setType(CAT); + FD->getType(), CountExpr, Flags.CountInBytes, Flags.OrNull); + if (!CAT.isNull()) + FD->setType(CAT); } static void handleFunctionReturnThunksAttr(Sema &S, Decl *D, diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index e16630ce9cd844..33d0e45f604e56 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -6481,6 +6481,7 @@ GetTypeSourceInfoForDeclarator(TypeProcessingState &State, break; } + case TypeLoc::CountAttributed: case TypeLoc::Adjusted: case TypeLoc::BTFTagAttributed: { CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); @@ -9050,6 +9051,125 @@ static void HandleHLSLParamModifierAttr(TypeProcessingState &State, } } +/// Return true if the type built at \p chunkIndex is part of a function's +/// return type, i.e. a function chunk wraps it at any level. In both +/// `int *__counted_by(n) (*fp)(void)` and `int *__counted_by(n) *(*fp)(void)`, +/// the attributed pointer is in the return type of the function `fp` points to. +/// +/// Chunk 0 is the one closest to the identifier, which is the outermost part of +/// the type, so the type built by chunk i is wrapped by chunk i - 1. A +/// parameter has its own declarator, so it is never part of \p D's chunks. +static bool isOnFunctionReturnType(const Declarator &D, unsigned chunkIndex) { + assert(chunkIndex <= D.getNumTypeObjects()); + for (unsigned i = chunkIndex; i != 0; --i) + if (D.getTypeObject(i - 1).Kind == DeclaratorChunk::Function) + return true; + return false; +} + +/// Return the number of pointer and array chunks that wrap the type built at +/// \p chunkIndex, up to the nearest function chunk. The level is relative to +/// the type the attribute belongs to: the declared type, or the return type of +/// the nearest enclosing function. +/// +/// In `int *__counted_by(n) *pp`, the attributed pointer is chunk 1, wrapped by +/// the pointer at chunk 0, so its level is 1. In +/// `int *__counted_by(n) *(*fp)(void)`, the attributed pointer is chunk 4, +/// wrapped by the pointer at chunk 3 and then the function at chunk 2, so its +/// level is 1, relative to the return type. +static unsigned getPointerNestLevel(const Declarator &D, unsigned chunkIndex) { + assert(chunkIndex <= D.getNumTypeObjects()); + unsigned Level = 0; + for (unsigned i = chunkIndex; i != 0; --i) { + switch (D.getTypeObject(i - 1).Kind) { + case DeclaratorChunk::Function: + return Level; + case DeclaratorChunk::Pointer: + case DeclaratorChunk::Array: + ++Level; + break; + default: + break; + } + } + return Level; +} + +/// A counted_by-family attribute written in the decl-spec applies to the +/// top-level type of each declarator. Move it to the top-level declarator +/// chunk, skipping parentheses, so that `__counted_by(n) int *p` is handled +/// like `int *__counted_by(n) p`. Return false if there is no such chunk, in +/// which case the decl-spec type is the top-level type. +/// +/// FIXME: One written after the type specifier, as in +/// `int __counted_by(n) *p`, should apply to the adjacent type and be +/// rejected. Moving it to the top-level type is an existing bug, kept for now. +/// See https://github.com/llvm/llvm-project/issues/241454. +static bool distributeBoundsAttrFromDeclSpec(TypeProcessingState &State, + ParsedAttr &Attr) { + Declarator &D = State.getDeclarator(); + for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { + DeclaratorChunk &Chunk = D.getTypeObject(i); + if (Chunk.Kind == DeclaratorChunk::Paren) + continue; + // The DeclSpec attributes are shared by every declarator, so restore + // them once this one is processed. + State.saveDeclSpecAttrs(); + moveAttrFromListToList(Attr, State.getCurrentAttributes(), + Chunk.getAttrs()); + return true; + } + return false; +} + +static void HandleCountedByAttrOnType(TypeProcessingState &State, + QualType &CurType, ParsedAttr &Attr) { + Sema &S = State.getSema(); + + // This attribute is only supported in C. + if (!Attr.diagnoseLangOpts(S)) { + Attr.setInvalid(); + return; + } + + auto *CountExpr = Attr.getArgAsExpr(0); + if (!CountExpr) + return; + + const Declarator &D = State.getDeclarator(); + unsigned chunkIndex = State.getCurrentChunkIndex(); + + Sema::BoundsAttrFlags Flags; + if (!S.ValidateBoundsAttrTypeForTypePosition( + CurType, Attr.getKind(), Attr.getLoc(), Attr.getRange(), + getPointerNestLevel(D, chunkIndex), + isOnFunctionReturnType(D, chunkIndex), Flags)) { + Attr.setInvalid(); + return; + } + + // For a field, check the record and the count before building the type, so + // a rejected attribute never produces a CountAttributedType. The record, or + // the Objective-C container of an instance variable, being defined is the + // current context. + if (D.getContext() == DeclaratorContext::Member) { + if (S.CheckCountedByAttrInRecord(S.CurContext, CurType, CountExpr, + Attr.getLoc(), Attr.getRange(), + Flags.CountInBytes, Flags.OrNull)) { + Attr.setInvalid(); + return; + } + } + + QualType NewType = S.BuildCountAttributedArrayOrPointerType( + CurType, CountExpr, Flags.CountInBytes, Flags.OrNull); + if (NewType.isNull()) { + Attr.setInvalid(); + return; + } + CurType = NewType; +} + bool Sema::ProcessLateParsedTypeAttr(LateParsedTypeAttrInfo &LA, QualType &QT) { // A DeclSpec attribute runs this once per declarator, as in // `IP __counted_by(n) a, b;`. Reuse one node, as the eager path does, so no @@ -9060,10 +9180,11 @@ bool Sema::ProcessLateParsedTypeAttr(LateParsedTypeAttrInfo &LA, QualType &QT) { } // Nesting is checked once the enclosing declarator chunks wrap the node. - BoundsAttrFlags Flags; - if (!ValidateBoundsAttrTypeForTypePosition(QT, LA.Kind, LA.NameLoc, - SourceRange(LA.NameLoc), - /*PointerNestLevel=*/0, Flags)) + BoundsAttrFlags Flags = BoundsAttrFlags::get(LA.Kind); + if (!ValidateBoundsAttrTypeShape(QT, LA.NameLoc, SourceRange(LA.NameLoc), + Flags, /*AttrSpelling=*/{}, + /*AllowRedecl=*/false, /*AttrArg=*/nullptr, + /*UpdateFlags=*/false)) return false; // The argument isn't parsed yet, so build the type without a count. @@ -9319,6 +9440,37 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type, break; } + case ParsedAttr::AT_CountedBy: + case ParsedAttr::AT_CountedByOrNull: + case ParsedAttr::AT_SizedBy: + case ParsedAttr::AT_SizedByOrNull: { + // FIXME: Only the GNU spelling is late-parsed, and the late-parsing path + // hasn't been switched to the new mechanism to support type-position + // attributes yet. Leave a late-parsed one to declaration attribute + // processing. + if (state.getSema().getLangOpts().ExperimentalLateParseAttributes && + attr.isGNUAttribute()) + break; + // The attribute only applies to fields for now. Leave it to declaration + // attribute processing, which diagnoses the GNU spelling. That doesn't + // see a [[]] one on a declarator chunk, so diagnose it here as the + // default case would. + if (state.getDeclarator().getContext() != DeclaratorContext::Member) { + if (!attr.isGNUAttribute() && TAL == TAL_DeclChunk) { + state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) + << attr << attr.isRegularKeywordAttribute(); + attr.setUsedAsTypeAttr(); + } + break; + } + if (TAL == TAL_DeclSpec && attr.isGNUAttribute() && + distributeBoundsAttrFromDeclSpec(state, attr)) + break; + HandleCountedByAttrOnType(state, type, attr); + attr.setUsedAsTypeAttr(); + break; + } + MS_TYPE_ATTRS_CASELIST: if (!handleMSPointerTypeQualifierAttr(state, attr, type)) attr.setUsedAsTypeAttr(); @@ -10090,7 +10242,11 @@ QualType Sema::BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull) { - assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType()); + // Accept any array or pointer type here. The caller has checked the field + // and its count (see CheckCountedByAttrInRecord), so the count is a + // DeclRefExpr and an array is a flexible array member. + assert(WrappedTy->isArrayType() || WrappedTy->isPointerType()); + assert(isa<DeclRefExpr>(CountExpr) && "count must be checked by the caller"); llvm::SmallVector<TypeCoupledDeclRefInfo, 1> Decls; BuildTypeCoupledDecls(CountExpr, Decls); diff --git a/clang/test/AST/attr-counted-by-or-null-struct-ptrs.c b/clang/test/AST/attr-counted-by-or-null-struct-ptrs.c index d42547003f0b38..ca603402f0a345 100644 --- a/clang/test/AST/attr-counted-by-or-null-struct-ptrs.c +++ b/clang/test/AST/attr-counted-by-or-null-struct-ptrs.c @@ -56,29 +56,6 @@ struct on_member_pointer_complete_ty_ty_pos { struct size_known *__counted_by_or_null(count) buf; }; -// TODO: This should be forbidden but isn't due to counted_by_or_null being treated as a -// declaration attribute. The attribute ends up on the outer most pointer -// (allowed by sema) even though syntactically its supposed to be on the inner -// pointer (would not allowed by sema due to pointee being a function type). -// CHECK-LABEL: RecordDecl {{.+}} struct on_member_pointer_fn_ptr_ty_ty_pos_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} fn_ptr 'void (** __counted_by_or_null(count))(void)':'void (**)(void)' -struct on_member_pointer_fn_ptr_ty_ty_pos_inner { - int count; - void (* __counted_by_or_null(count) * fn_ptr)(void); -}; - -// FIXME: The generated AST here is wrong. The attribute should be on the inner -// pointer. -// CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known ** __counted_by_or_null(count)':'struct size_known **' -struct on_nested_pointer_inner { - int count; - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__counted_by_or_null` can only be nested when used in function parameters. - struct size_known *__counted_by_or_null(count) *buf; -}; // CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_outer definition // CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' diff --git a/clang/test/AST/attr-counted-by-rejected.c b/clang/test/AST/attr-counted-by-rejected.c new file mode 100644 index 00000000000000..f39ccb0c0e03a7 --- /dev/null +++ b/clang/test/AST/attr-counted-by-rejected.c @@ -0,0 +1,29 @@ +// RUN: not %clang_cc1 %s -ast-dump | FileCheck %s +// RUN: not %clang_cc1 -fexperimental-late-parse-attributes %s -ast-dump | FileCheck %s + +// A rejected counted_by-family attribute leaves the field's type unchanged, +// qualifiers included. + +#define __counted_by(f) __attribute__((counted_by(f))) + +struct size_known { + int field; +}; + +// CHECK-LABEL: RecordDecl {{.+}} union on_pointer_in_union definition +// CHECK-NEXT: |-FieldDecl {{.+}} count 'int' +// CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known *volatile' +union on_pointer_in_union { + int count; + struct size_known *__counted_by(count) volatile buf; +}; + +typedef struct size_known *SKP; + +// CHECK-LABEL: RecordDecl {{.+}} struct on_pointer_non_int_count definition +// CHECK-NEXT: |-FieldDecl {{.+}} count 'double' +// CHECK-NEXT: `-FieldDecl {{.+}} buf 'const SKP':'struct size_known *const' +struct on_pointer_non_int_count { + double count; + const SKP __counted_by(count) buf; +}; diff --git a/clang/test/AST/attr-counted-by-struct-ptrs.c b/clang/test/AST/attr-counted-by-struct-ptrs.c index afef9c8c3b95d2..ff703420518887 100644 --- a/clang/test/AST/attr-counted-by-struct-ptrs.c +++ b/clang/test/AST/attr-counted-by-struct-ptrs.c @@ -45,8 +45,6 @@ struct on_pointer_anon_count { //============================================================================== // __counted_by on struct member pointer in type attribute position //============================================================================== -// TODO: Correctly parse counted_by as a type attribute. Currently it is parsed -// as a declaration attribute // CHECK-LABEL: RecordDecl {{.+}} struct on_member_pointer_complete_ty_ty_pos definition // CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' @@ -56,30 +54,6 @@ struct on_member_pointer_complete_ty_ty_pos { struct size_known *__counted_by(count) buf; }; -// TODO: This should be forbidden but isn't due to counted_by being treated as a -// declaration attribute. The attribute ends up on the outer most pointer -// (allowed by sema) even though syntactically its supposed to be on the inner -// pointer (would not allowed by sema due to pointee being a function type). -// CHECK-LABEL: RecordDecl {{.+}} struct on_member_pointer_fn_ptr_ty_ty_pos_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} fn_ptr 'void (** __counted_by(count))(void)':'void (**)(void)' -struct on_member_pointer_fn_ptr_ty_ty_pos_inner { - int count; - void (* __counted_by(count) * fn_ptr)(void); -}; - -// FIXME: The generated AST here is wrong. The attribute should be on the inner -// pointer. -// CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known ** __counted_by(count)':'struct size_known **' -struct on_nested_pointer_inner { - int count; - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__counted_by` can only be nested when used in function parameters. - struct size_known *__counted_by(count) *buf; -}; - // CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_outer definition // CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' // CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known ** __counted_by(count)':'struct size_known **' @@ -116,3 +90,27 @@ struct on_pointer_anon_count_ty_pos { }; struct size_known *__counted_by(count) buf; }; + +//============================================================================== +// __counted_by in declaration-specifier position applies to the top-level type +//============================================================================== + +// CHECK-LABEL: RecordDecl {{.+}} struct on_pointer_decl_spec_pos definition +// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' +// CHECK-NEXT: |-FieldDecl {{.+}} buf 'struct size_known * __counted_by(count)':'struct size_known *' +// CHECK-NEXT: |-FieldDecl {{.+}} buf2 'struct size_known * __counted_by(count)':'struct size_known *' +// CHECK-NEXT: |-FieldDecl {{.+}} a 'struct size_known * __counted_by(count)':'struct size_known *' +// CHECK-NEXT: |-FieldDecl {{.+}} b 'struct size_known * __counted_by(count)':'struct size_known *' +// CHECK-NEXT: |-FieldDecl {{.+}} pp 'struct size_known ** __counted_by(count)':'struct size_known **' +// CHECK-NEXT: `-FieldDecl {{.+}} par 'struct size_known * __counted_by(count)':'struct size_known *' +struct on_pointer_decl_spec_pos { + int count; + __counted_by(count) struct size_known *buf; + // FIXME: After the type specifier, this should apply to the adjacent type, + // which isn't a pointer, and be rejected. + // See https://github.com/llvm/llvm-project/issues/241454. + struct size_known __counted_by(count) *buf2; + __counted_by(count) struct size_known *a, *b; + __counted_by(count) struct size_known **pp; + __counted_by(count) struct size_known *(par); +}; diff --git a/clang/test/AST/attr-sized-by-or-null-struct-ptrs.c b/clang/test/AST/attr-sized-by-or-null-struct-ptrs.c index 7273280e4b60c0..2592d0fd5cb4e5 100644 --- a/clang/test/AST/attr-sized-by-or-null-struct-ptrs.c +++ b/clang/test/AST/attr-sized-by-or-null-struct-ptrs.c @@ -56,30 +56,6 @@ struct on_member_pointer_complete_ty_ty_pos { struct size_known *__sized_by_or_null(count) buf; }; -// TODO: This should be forbidden but isn't due to sized_by_or_null being treated as a -// declaration attribute. The attribute ends up on the outer most pointer -// (allowed by sema) even though syntactically its supposed to be on the inner -// pointer (would not allowed by sema due to pointee being a function type). -// CHECK-LABEL: RecordDecl {{.+}} struct on_member_pointer_fn_ptr_ty_ty_pos_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} fn_ptr 'void (** __sized_by_or_null(count))(void)':'void (**)(void)' -struct on_member_pointer_fn_ptr_ty_ty_pos_inner { - int count; - void (* __sized_by_or_null(count) * fn_ptr)(void); -}; - -// FIXME: The generated AST here is wrong. The attribute should be on the inner -// pointer. -// CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known ** __sized_by_or_null(count)':'struct size_known **' -struct on_nested_pointer_inner { - int count; - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__sized_by_or_null` can only be nested when used in function parameters. - struct size_known *__sized_by_or_null(count) *buf; -}; - // CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_outer definition // CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' // CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known ** __sized_by_or_null(count)':'struct size_known **' diff --git a/clang/test/AST/attr-sized-by-struct-ptrs.c b/clang/test/AST/attr-sized-by-struct-ptrs.c index 738eaf8cbf36b2..4d7797fa823956 100644 --- a/clang/test/AST/attr-sized-by-struct-ptrs.c +++ b/clang/test/AST/attr-sized-by-struct-ptrs.c @@ -56,30 +56,6 @@ struct on_member_pointer_complete_ty_ty_pos { struct size_known *__sized_by(count) buf; }; -// TODO: This should be forbidden but isn't due to sized_by being treated as a -// declaration attribute. The attribute ends up on the outer most pointer -// (allowed by sema) even though syntactically its supposed to be on the inner -// pointer (would not allowed by sema due to pointee being a function type). -// CHECK-LABEL: RecordDecl {{.+}} struct on_member_pointer_fn_ptr_ty_ty_pos_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} fn_ptr 'void (** __sized_by(count))(void)':'void (**)(void)' -struct on_member_pointer_fn_ptr_ty_ty_pos_inner { - int count; - void (* __sized_by(count) * fn_ptr)(void); -}; - -// FIXME: The generated AST here is wrong. The attribute should be on the inner -// pointer. -// CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_inner definition -// CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' -// CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known ** __sized_by(count)':'struct size_known **' -struct on_nested_pointer_inner { - int count; - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__sized_by` can only be nested when used in function parameters. - struct size_known *__sized_by(count) *buf; -}; - // CHECK-LABEL: RecordDecl {{.+}} struct on_nested_pointer_outer definition // CHECK-NEXT: |-FieldDecl {{.+}} referenced count 'int' // CHECK-NEXT: `-FieldDecl {{.+}} buf 'struct size_known ** __sized_by(count)':'struct size_known **' diff --git a/clang/test/Sema/attr-counted-by-multiple-on-pointer.c b/clang/test/Sema/attr-counted-by-multiple-on-pointer.c new file mode 100644 index 00000000000000..67e702a1cb45f1 --- /dev/null +++ b/clang/test/Sema/attr-counted-by-multiple-on-pointer.c @@ -0,0 +1,84 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +// A pointer can have only one counted_by-family attribute. A second one used +// to stack another CountAttributedType on the first. + +#define __counted_by(f) __attribute__((counted_by(f))) +#define __counted_by_or_null(f) __attribute__((counted_by_or_null(f))) +#define __sized_by(f) __attribute__((sized_by(f))) +#define __sized_by_or_null(f) __attribute__((sized_by_or_null(f))) + +typedef int *IP; + +struct same_attr { + int n; + int m; + // expected-error@+1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + int *__counted_by(n) __counted_by(m) p; +}; + +struct same_count { + int n; + // expected-error@+1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + int *__counted_by(n) __counted_by(n) p; +}; + +struct different_attrs { + int n; + int m; + // expected-error@+1{{'sized_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + int *__counted_by(n) __sized_by(m) p; + // expected-error@+1{{'counted_by_or_null' attribute cannot be applied to a pointer that already has a 'sized_by_or_null' attribute}} + int *__sized_by_or_null(n) __counted_by_or_null(m) q; +}; + +// One in declaration-specifier position, shared by both declarators, is +// diagnosed once. +struct shared_decl_spec { + int n; + int m; + // expected-error@+1{{'sized_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + IP __counted_by(n) __sized_by(m) a, b; +}; + +// One in declaration-specifier position and one in the declarator. +struct decl_spec_and_declarator { + int n; + int m; + // expected-error@+1{{'sized_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + IP __counted_by(n) a __sized_by(m); +}; + +// One in the pointer chunk and one after the declarator. +struct chunk_and_after_declarator { + int n; + int m; + // expected-error@+1{{'sized_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + int *__counted_by(n) p __sized_by(m); +}; + +// One in declaration-specifier position, which moves to the pointer, and one in +// the pointer chunk. +struct decl_spec_and_chunk { + int n; + int m; + // FIXME: Diagnose the one written second, 'sized_by'. + // expected-error@+1{{'counted_by' attribute cannot be applied to a pointer that already has a 'sized_by' attribute}} + __counted_by(n) int *__sized_by(m) p; +}; + +// Two in declaration-specifier position, which both move to the pointer. +struct two_decl_spec { + int n; + int m; + // expected-error@+1{{'sized_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + __counted_by(n) __sized_by(m) int *p; +}; + +// A flexible array member can have only one too. +struct flexible_array_member { + int n; + int m; + // expected-error@+1{{'counted_by' attribute cannot be applied to a pointer that already has a 'counted_by' attribute}} + int arr[] __counted_by(n) __counted_by(m); +}; diff --git a/clang/test/Sema/attr-counted-by-or-null-struct-ptrs-completable-incomplete-pointee.c b/clang/test/Sema/attr-counted-by-or-null-struct-ptrs-completable-incomplete-pointee.c index cff5a14c70b993..955e781b5679b3 100644 --- a/clang/test/Sema/attr-counted-by-or-null-struct-ptrs-completable-incomplete-pointee.c +++ b/clang/test/Sema/attr-counted-by-or-null-struct-ptrs-completable-incomplete-pointee.c @@ -1,5 +1,5 @@ -// RUN: %clang_cc1 -fsyntax-only -verify %s -// RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -verify %s +// RUN: %clang_cc1 -fsyntax-only -verify=expected,immediate %s +// RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -verify=expected,late %s #define __counted_by_or_null(f) __attribute__((counted_by_or_null(f))) @@ -616,10 +616,11 @@ struct IncompleteTy3; struct CBBufFAMofCountedByPtrs { int size; - // TODO: This is misleading. The attribute is written in the type position - // but clang currently doesn't treat it like that and it gets treated as - // an attribute on the array, rather than on the element type. - // expected-error@+1{{'counted_by_or_null' only applies to pointers; did you mean to use 'counted_by'?}} + // The attribute is written on the element type, so it's a nested pointer. + // With -fexperimental-late-parse-attributes it's still treated as an + // attribute on the array until late parsing handles type attributes. + // late-error@+2{{'counted_by_or_null' only applies to pointers; did you mean to use 'counted_by'?}} + // immediate-error@+1{{'counted_by_or_null' attribute on nested pointer type is not allowed}} struct IncompleteTy3* __counted_by_or_null(size) arr[]; }; diff --git a/clang/test/Sema/attr-counted-by-or-null-struct-ptrs.c b/clang/test/Sema/attr-counted-by-or-null-struct-ptrs.c index 0fd739ca7d4c34..1bd625b0329cc6 100644 --- a/clang/test/Sema/attr-counted-by-or-null-struct-ptrs.c +++ b/clang/test/Sema/attr-counted-by-or-null-struct-ptrs.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -fsyntax-only -Wpointer-arith -verify %s +// RUN: %clang_cc1 -fsyntax-only -Wpointer-arith -verify=expected,immediate %s // RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -Wpointer-arith -verify %s #define __counted_by_or_null(f) __attribute__((counted_by_or_null(f))) @@ -158,10 +158,13 @@ struct on_member_pointer_fn_ptr_ty_ty_pos { fn_ptr_ty __counted_by_or_null(count) fn_ptr; }; -// TODO: This should be forbidden but isn't due to counted_by_or_null being treated -// as a declaration attribute. +// Forbidden: the pointee is a function type. With +// -fexperimental-late-parse-attributes it's still treated as a declaration +// attribute on the outermost pointer until late parsing handles type +// attributes. struct on_member_pointer_fn_ptr_ty_ty_pos_inner { int count; + // immediate-error@+1{{'counted_by_or_null' cannot be applied to a pointer with pointee of unknown size because 'void (void)' is a function type}} void (* __counted_by_or_null(count) * fn_ptr)(void); }; @@ -181,9 +184,12 @@ struct on_member_pointer_struct_with_annotated_vla_ty_pos { }; struct on_nested_pointer_inner { - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__counted_by_or_null` can only be nested when used in function parameters. + // Nested bounds attributes are not allowed. With + // -fexperimental-late-parse-attributes it's still treated as a declaration + // attribute on the outermost pointer until late parsing handles type + // attributes. int count; + // immediate-error@+1{{'counted_by_or_null' attribute on nested pointer type is not allowed}} struct size_known *__counted_by_or_null(count) *buf; }; diff --git a/clang/test/Sema/attr-counted-by-return-type.c b/clang/test/Sema/attr-counted-by-return-type.c new file mode 100644 index 00000000000000..4719711a911af8 --- /dev/null +++ b/clang/test/Sema/attr-counted-by-return-type.c @@ -0,0 +1,55 @@ +// RUN: %clang_cc1 -fblocks -fsyntax-only -verify %s + +// counted_by-family attributes aren't supported yet on function return types, +// including the return type of the function a function-pointer or +// block-pointer member points to. They're rejected with a dedicated diagnostic. +// They used to be reported as a nested pointer, because the function chunk +// counted as a level of pointer nesting. + +#define __counted_by(f) __attribute__((counted_by(f))) +#define __sized_by(f) __attribute__((sized_by(f))) +#define __counted_by_or_null(f) __attribute__((counted_by_or_null(f))) +#define __sized_by_or_null(f) __attribute__((sized_by_or_null(f))) + +extern int g; + +// Outside a struct, the attribute isn't on a field, so it's diagnosed as such +// before its position is considered. +// expected-error@+1{{'counted_by' attribute only applies to non-static data members}} +int *__counted_by(g) fn(void); +// expected-error@+1{{'sized_by' attribute only applies to non-static data members}} +char *__sized_by(4) fn_const(void); + +struct fn_ptr_return { + int n; + // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int *__counted_by(n) (*fp)(void); +}; + +struct block_ptr_return { + int n; + // expected-error@+1{{'counted_by_or_null' attribute on a function return type is not yet supported}} + int *__counted_by_or_null(n) (^bp)(void); +}; + +struct fn_ptr_array_return { + int n; + // expected-error@+1{{'sized_by_or_null' attribute on a function return type is not yet supported}} + char *__sized_by_or_null(n) (*fpa[2])(void); +}; + +// A counted pointer nested anywhere in a return type is rejected as being on +// the return type. Its nesting is measured relative to the return type. +struct fn_ptr_return_nested { + int n; + // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int *__counted_by(n) *(*fp)(void); +}; + +// Nesting stops at the function: the pointer to the function and the array +// holding it don't count toward the return type's nesting. +struct fn_ptr_array_nested_return { + int n; + // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int *__counted_by(n) *(*fpa[2])(void); +}; diff --git a/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c b/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c new file mode 100644 index 00000000000000..a0d4cc5ebdfa3d --- /dev/null +++ b/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c @@ -0,0 +1,21 @@ +// RUN: %clang_cc1 -std=c23 -fsyntax-only -verify %s +// RUN: %clang_cc1 -std=c23 -fsyntax-only -fexperimental-late-parse-attributes -verify %s +// RUN: not %clang_cc1 -std=c23 -fsyntax-only -ast-dump %s 2>/dev/null | FileCheck %s +// RUN: not %clang_cc1 -std=c23 -fsyntax-only -fexperimental-late-parse-attributes -ast-dump %s 2>/dev/null | FileCheck %s + +// A [[]] counted_by-family attribute on a declarator chunk is a type +// attribute. It applies to a field's pointer, and is rejected rather than +// dropped elsewhere. It isn't late-parsed, so the late-parsing mode handles it +// the same way. + +void f(int n, int *[[clang::counted_by(n)]] p); // expected-error{{'clang::counted_by' attribute cannot be applied to types}} + +int gn; +int *[[clang::sized_by(gn)]] gp; // expected-error{{'clang::sized_by' attribute cannot be applied to types}} + +struct S { + int n; + // CHECK: FieldDecl {{.*}} p 'int * __counted_by_or_null(n)':'int *' + int *[[clang::counted_by_or_null(n)]] p; + int *[[clang::counted_by(n)]] *pp; // expected-error{{'counted_by' attribute on nested pointer type is not allowed}} +}; diff --git a/clang/test/Sema/attr-counted-by-struct-ptrs-completable-incomplete-pointee.c b/clang/test/Sema/attr-counted-by-struct-ptrs-completable-incomplete-pointee.c index d28a2086b51b88..073c039b3810a4 100644 --- a/clang/test/Sema/attr-counted-by-struct-ptrs-completable-incomplete-pointee.c +++ b/clang/test/Sema/attr-counted-by-struct-ptrs-completable-incomplete-pointee.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -fsyntax-only -verify %s +// RUN: %clang_cc1 -fsyntax-only -verify=expected,immediate %s // RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -verify %s #define __counted_by(f) __attribute__((counted_by(f))) @@ -616,9 +616,10 @@ struct IncompleteTy3; struct CBBufFAMofCountedByPtrs { int size; - // TODO: This is misleading. The attribute is written in the type position - // but clang currently doesn't treat it like that and it gets treated as - // an attribute on the array, rather than on the element type. + // The attribute is written on the element type, so it's a nested pointer. + // With -fexperimental-late-parse-attributes it's still treated as an + // attribute on the array until late parsing handles type attributes. + // immediate-error@+1{{'counted_by' attribute on nested pointer type is not allowed}} struct IncompleteTy3* __counted_by(size) arr[]; }; diff --git a/clang/test/Sema/attr-counted-by-struct-ptrs.c b/clang/test/Sema/attr-counted-by-struct-ptrs.c index a42f3895695a32..9070fd36bf8140 100644 --- a/clang/test/Sema/attr-counted-by-struct-ptrs.c +++ b/clang/test/Sema/attr-counted-by-struct-ptrs.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -fsyntax-only -Wpointer-arith -verify %s +// RUN: %clang_cc1 -fsyntax-only -Wpointer-arith -verify=expected,immediate %s // RUN: %clang_cc1 -fsyntax-only -Wpointer-arith -fexperimental-late-parse-attributes %s -verify #define __counted_by(f) __attribute__((counted_by(f))) @@ -157,10 +157,13 @@ struct on_member_pointer_fn_ptr_ty_ty_pos { fn_ptr_ty __counted_by(count) fn_ptr; }; -// TODO: This should be forbidden but isn't due to counted_by being treated -// as a declaration attribute. +// Forbidden: the pointee is a function type. With +// -fexperimental-late-parse-attributes it's still treated as a declaration +// attribute on the outermost pointer until late parsing handles type +// attributes. struct on_member_pointer_fn_ptr_ty_ty_pos_inner { int count; + // immediate-error@+1{{'counted_by' cannot be applied to a pointer with pointee of unknown size because 'void (void)' is a function type}} void (* __counted_by(count) * fn_ptr)(void); }; @@ -180,12 +183,45 @@ struct on_member_pointer_struct_with_annotated_vla_ty_pos { }; struct on_nested_pointer_inner { - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__counted_by` can only be nested when used in function parameters. + // Nested bounds attributes are not allowed. With + // -fexperimental-late-parse-attributes it's still treated as a declaration + // attribute on the outermost pointer until late parsing handles type + // attributes. int count; + // immediate-error@+1{{'counted_by' attribute on nested pointer type is not allowed}} struct size_known *__counted_by(count) *buf; }; +// In the declaration specifiers, the attribute applies to the top-level +// pointer. +struct on_pointer_decl_spec_pos { + int count; + __counted_by(count) struct size_known *buf; + const __counted_by(count) struct size_known *buf2; + // FIXME: After the type specifier, this should apply to the adjacent type, + // which isn't a pointer, and be rejected. + // See https://github.com/llvm/llvm-project/issues/241454. + struct size_known __counted_by(count) *buf3; + __counted_by(count) struct size_known *(buf4); +}; + +// The attribute only applies to fields. +// expected-error@+1{{'counted_by' attribute only applies to non-static data members}} +__counted_by(10) struct size_known *on_decl_spec_pos_fn(void); + +// The record and the count are checked before the field's type is built. +union on_pointer_in_union { + int count; + // expected-error@+1{{'counted_by' cannot be applied to a union member}} + struct size_known *__counted_by(count) volatile buf; +}; + +struct on_pointer_non_int_count { + double count; + // expected-error@+1{{'counted_by' requires a non-boolean integer type argument}} + struct size_known *__counted_by(count) buf; +}; + struct on_nested_pointer_outer { int count; struct size_known **__counted_by(count) buf; diff --git a/clang/test/Sema/attr-counted-by-vla.c b/clang/test/Sema/attr-counted-by-vla.c index 5b1b4833dce7df..2ae8398f19791a 100644 --- a/clang/test/Sema/attr-counted-by-vla.c +++ b/clang/test/Sema/attr-counted-by-vla.c @@ -106,6 +106,14 @@ struct not_a_c99_fam { struct bar *non_c99_fam[0] __counted_by(count); // expected-error {{'counted_by' on arrays only applies to C99 flexible array members}} }; +// A flexible array member that isn't the last field is rejected as such, not +// by counted_by. +struct fam_not_last { + int count; + struct bar *fam[] __counted_by(count); // expected-error {{flexible array member 'fam' with type}} + int x; // expected-note {{next field declaration is here}} +}; + struct annotated_with_anon_struct { unsigned long flags; struct { diff --git a/clang/test/Sema/attr-sized-by-or-null-struct-ptrs.c b/clang/test/Sema/attr-sized-by-or-null-struct-ptrs.c index 82819e5cf43fff..201d34c4d20676 100644 --- a/clang/test/Sema/attr-sized-by-or-null-struct-ptrs.c +++ b/clang/test/Sema/attr-sized-by-or-null-struct-ptrs.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -fsyntax-only -verify %s +// RUN: %clang_cc1 -fsyntax-only -verify=expected,immediate %s // RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -verify %s #define __sized_by_or_null(f) __attribute__((sized_by_or_null(f))) @@ -149,10 +149,13 @@ struct on_member_pointer_fn_ptr_ty_ty_pos { fn_ptr_ty __sized_by_or_null(size) fn_ptr; }; -// TODO: This should be forbidden but isn't due to sized_by_or_null being treated -// as a declaration attribute. +// Forbidden: the pointee is a function type. With +// -fexperimental-late-parse-attributes it's still treated as a declaration +// attribute on the outermost pointer until late parsing handles type +// attributes. struct on_member_pointer_fn_ptr_ty_ty_pos_inner { int size; + // immediate-error@+1{{'sized_by_or_null' cannot be applied to a pointer with pointee of unknown size because 'void (void)' is a function type}} void (* __sized_by_or_null(size) * fn_ptr)(void); }; @@ -167,9 +170,12 @@ struct on_member_pointer_struct_with_annotated_vla_ty_pos { }; struct on_nested_pointer_inner { - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__sized_by_or_null` can only be nested when used in function parameters. + // Nested bounds attributes are not allowed. With + // -fexperimental-late-parse-attributes it's still treated as a declaration + // attribute on the outermost pointer until late parsing handles type + // attributes. int size; + // immediate-error@+1{{'sized_by_or_null' attribute on nested pointer type is not allowed}} struct size_known *__sized_by_or_null(size) *buf; }; diff --git a/clang/test/Sema/attr-sized-by-struct-ptrs.c b/clang/test/Sema/attr-sized-by-struct-ptrs.c index 6dc76b8bc7081e..adfa8d82f7d906 100644 --- a/clang/test/Sema/attr-sized-by-struct-ptrs.c +++ b/clang/test/Sema/attr-sized-by-struct-ptrs.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -fsyntax-only -verify %s +// RUN: %clang_cc1 -fsyntax-only -verify=expected,immediate %s // RUN: %clang_cc1 -fexperimental-late-parse-attributes -fsyntax-only -verify %s #define __sized_by(f) __attribute__((sized_by(f))) @@ -149,10 +149,13 @@ struct on_member_pointer_fn_ptr_ty_ty_pos { fn_ptr_ty __sized_by(size) fn_ptr; }; -// TODO: This should be forbidden but isn't due to sized_by being treated -// as a declaration attribute. +// Forbidden: the pointee is a function type. With +// -fexperimental-late-parse-attributes it's still treated as a declaration +// attribute on the outermost pointer until late parsing handles type +// attributes. struct on_member_pointer_fn_ptr_ty_ty_pos_inner { int size; + // immediate-error@+1{{'sized_by' cannot be applied to a pointer with pointee of unknown size because 'void (void)' is a function type}} void (* __sized_by(size) * fn_ptr)(void); }; @@ -167,9 +170,12 @@ struct on_member_pointer_struct_with_annotated_vla_ty_pos { }; struct on_nested_pointer_inner { - // TODO: This should be disallowed because in the `-fbounds-safety` model - // `__sized_by` can only be nested when used in function parameters. + // Nested bounds attributes are not allowed. With + // -fexperimental-late-parse-attributes it's still treated as a declaration + // attribute on the outermost pointer until late parsing handles type + // attributes. int size; + // immediate-error@+1{{'sized_by' attribute on nested pointer type is not allowed}} struct size_known *__sized_by(size) *buf; }; diff --git a/clang/test/SemaObjC/attr-counted-by-ivar.m b/clang/test/SemaObjC/attr-counted-by-ivar.m new file mode 100644 index 00000000000000..273e760bcefd0a --- /dev/null +++ b/clang/test/SemaObjC/attr-counted-by-ivar.m @@ -0,0 +1,44 @@ +// RUN: %clang_cc1 -fsyntax-only -Wno-objc-root-class -verify=expected,eager %s +// RUN: %clang_cc1 -fsyntax-only -Wno-objc-root-class -verify -fexperimental-late-parse-attributes %s +// RUN: not %clang_cc1 -fsyntax-only -Wno-objc-root-class -ast-dump %s 2>/dev/null | FileCheck %s + +// counted_by-family attributes apply to Objective-C instance variables, with +// a count that's an instance variable of the same ivar list. + +#define __counted_by(f) __attribute__((counted_by(f))) +#define __sized_by(f) __attribute__((sized_by(f))) + +int global; // #global + +@interface I { + int n; // #n + // CHECK: ObjCIvarDecl {{.*}} p 'int * __counted_by(n)':'int *' + int *__counted_by(n) p; + // CHECK: ObjCIvarDecl {{.*}} q 'char * __sized_by(n)':'char *' + char *__sized_by(n) q; + // expected-error@+1{{'counted_by' argument must be a simple declaration reference}} + int *__counted_by(n + 1) r; + // expected-error@+2{{field 'global' in 'counted_by' not inside structure}} + // expected-note@#global{{'global' declared here}} + int *__counted_by(global) s; + // FIXME: The late-parsed one is applied to the outer pointer instead. + // eager-error@+1{{'counted_by' attribute on nested pointer type is not allowed}} + int *__counted_by(n) *pp; + // A struct declared in the ivar list can't count with an instance variable. + struct T { + // expected-error@+2{{'counted_by' field 'n' isn't within the same struct as the annotated pointer}} + // expected-note@#n{{'n' declared here}} + int *__counted_by(n) t; + } st; +} +@end + +@interface J +@end + +@implementation J { + int m; + // CHECK: ObjCIvarDecl {{.*}} u 'int * __counted_by(m)':'int *' + int *__counted_by(m) u; +} +@end >From 71c9eb023d875af3dbda1006c6e9e0de9adeff79 Mon Sep 17 00:00:00 2001 From: Yeoul Na <[email protected]> Date: Thu, 12 Nov 2026 15:28:53 -0800 Subject: [PATCH 2/3] Address comments --- clang/include/clang/Sema/Sema.h | 8 ++++---- clang/lib/Sema/SemaBoundsSafety.cpp | 4 +--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h index 8fc823a159092a..8f49db399f9471 100644 --- a/clang/include/clang/Sema/Sema.h +++ b/clang/include/clang/Sema/Sema.h @@ -2559,8 +2559,8 @@ class Sema final : public SemaBase { /// Check a counted_by-family attribute in type position and initialize /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer and /// array declarator chunks enclosing the attribute, up to the nearest - /// function chunk. \p OnReturnType is true if a function chunk encloses it, - /// i.e. the attribute is in a function's return type. + /// function declarator chunk. \p OnReturnType is true if a function chunk + /// encloses it, i.e. the attribute is in a function's return type. /// /// \returns false after diagnosing an attribute that must be dropped (see /// ValidateBoundsAttrTypeShape). @@ -2579,8 +2579,8 @@ class Sema final : public SemaBase { unsigned PointerNestLevel, bool OnReturnType); /// Check if applying the specified attribute variant from the "counted by" - /// family of attributes to a field of record \p RD, with type \p Ty, is - /// semantically valid. If semantically invalid diagnostics will be emitted + /// family of attributes to a field of \p DC, with type \p Ty, is + /// semantically valid. If semantically invalid, diagnostics will be emitted /// explaining the problems. This doesn't need the FieldDecl, so it can run /// before the field's type is built. /// diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp index dd78f335a0844c..4dc2f0aad5b841 100644 --- a/clang/lib/Sema/SemaBoundsSafety.cpp +++ b/clang/lib/Sema/SemaBoundsSafety.cpp @@ -287,9 +287,7 @@ bool Sema::CheckCountedByAttrInRecord(const DeclContext *DC, QualType Ty, return true; } - // Only a flexible array member takes the attribute among arrays. Whether it's - // the last field isn't known until the record is complete; ActOnFields - // rejects a flexible array member that isn't. + // Only a flexible array member takes the attribute among arrays. if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) { Diag(Loc, diag::err_counted_by_attr_on_array_not_flexible_array_member) << Kind << Range; >From 13efaf9158532b4417177be51b3932a42c7304f0 Mon Sep 17 00:00:00 2001 From: Yeoul Na <[email protected]> Date: Thu, 19 Nov 2026 17:03:51 -0800 Subject: [PATCH 3/3] Address comments: Add more test coverage and some style fixes --- clang/lib/Sema/SemaBoundsSafety.cpp | 16 ++++---- clang/test/Sema/attr-counted-by-return-type.c | 7 ++++ .../attr-counted-by-std-syntax-on-chunk.c | 38 +++++++++++++++++++ clang/test/Sema/attr-counted-by-struct-ptrs.c | 27 +++++++++++++ 4 files changed, 80 insertions(+), 8 deletions(-) diff --git a/clang/lib/Sema/SemaBoundsSafety.cpp b/clang/lib/Sema/SemaBoundsSafety.cpp index 4dc2f0aad5b841..89e91c51e1aa38 100644 --- a/clang/lib/Sema/SemaBoundsSafety.cpp +++ b/clang/lib/Sema/SemaBoundsSafety.cpp @@ -106,12 +106,12 @@ bool Sema::ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc, // // TODO: Converge with the -fbounds-safety attribute model checks in // checkBoundsAttrTypeConflictsAndMisc. - if (!getLangOpts().hasBoundsSafetyAttributes()) - if (const auto *CATy = Ty->getAs<CountAttributedType>()) { - Diag(AttrLoc, diag::err_counted_by_on_bounds_attributed_type) - << Kind << CATy->getKind() << AttrRange; - return false; - } + if (const auto *CATy = Ty->getAs<CountAttributedType>(); + CATy && !getLangOpts().hasBoundsSafetyAttributes()) { + Diag(AttrLoc, diag::err_counted_by_on_bounds_attributed_type) + << Kind << CATy->getKind() << AttrRange; + return false; + } // counted_by and sized_by require a pointer or array. if (!Ty->isPointerType() && !Ty->isArrayType()) { @@ -351,8 +351,8 @@ bool Sema::CheckCountedByAttrInRecord(const DeclContext *DC, QualType Ty, // Whether CountRD is an anonymous struct is not determined at this // point. Thus, an additional diagnostic in case it's not anonymous struct // is done later in `Parser::ParseStructDeclaration`. - auto *TopRD = GetEnclosingNamedOrTopAnonRecord(RD); - auto *TopCountRD = GetEnclosingNamedOrTopAnonRecord(CountRD); + const RecordDecl *TopRD = GetEnclosingNamedOrTopAnonRecord(RD); + const RecordDecl *TopCountRD = GetEnclosingNamedOrTopAnonRecord(CountRD); if (TopRD != TopCountRD) { Diag(E->getBeginLoc(), diag::err_count_attr_param_not_in_same_struct) diff --git a/clang/test/Sema/attr-counted-by-return-type.c b/clang/test/Sema/attr-counted-by-return-type.c index 4719711a911af8..768faa0b606691 100644 --- a/clang/test/Sema/attr-counted-by-return-type.c +++ b/clang/test/Sema/attr-counted-by-return-type.c @@ -53,3 +53,10 @@ struct fn_ptr_array_nested_return { // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} int *__counted_by(n) *(*fpa[2])(void); }; + +// A function pointer whose return type is another function pointer. +struct fn_ptr_returning_fn_ptr { + int n; + // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int *__counted_by(n) (*(*fpfp)(void))(void); +}; diff --git a/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c b/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c index a0d4cc5ebdfa3d..32db0e2945255b 100644 --- a/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c +++ b/clang/test/Sema/attr-counted-by-std-syntax-on-chunk.c @@ -19,3 +19,41 @@ struct S { int *[[clang::counted_by_or_null(n)]] p; int *[[clang::counted_by(n)]] *pp; // expected-error{{'counted_by' attribute on nested pointer type is not allowed}} }; + +// Declarators nest, so the position of an attribute is measured from the chunk +// it's on. An attribute anywhere in the return type of a function a pointer +// points to is on a return type, however deeply that function is nested. +struct ReturnTypes { + int n; + // A function pointer returning a function pointer returning a pointer. + // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int *[[clang::counted_by(n)]] (*(*fpfp)(void))(void); + // The same, returning a pointer to a counted array. + // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int (*(*(*fpfp_arr)(void))(void))[] [[clang::counted_by(n)]]; + // A pointer to an array of function pointers that return a pointer to a + // counted array. + // expected-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int (*(*(*pafp)[4])(void))[] [[clang::counted_by(n)]]; +}; + +// An array behind a pointer is nested. +struct PointerToArray { + int n; + // expected-error@+1{{'counted_by' attribute on nested pointer type is not allowed}} + int (*pa)[] [[clang::counted_by(n)]]; +}; + +// A flexible array member is the one array that takes the attribute, with or +// without parentheses around its name. +struct FlexibleArrayMember { + int n; + // CHECK: FieldDecl {{.*}} fam 'int[] __counted_by(n)':'int[]' + int fam[] [[clang::counted_by(n)]]; +}; + +struct ParenthesizedFlexibleArrayMember { + int n; + // CHECK: FieldDecl {{.*}} fam 'int[] __counted_by(n)':'int[]' + int (fam)[] [[clang::counted_by(n)]]; +}; diff --git a/clang/test/Sema/attr-counted-by-struct-ptrs.c b/clang/test/Sema/attr-counted-by-struct-ptrs.c index 9070fd36bf8140..85725420929a33 100644 --- a/clang/test/Sema/attr-counted-by-struct-ptrs.c +++ b/clang/test/Sema/attr-counted-by-struct-ptrs.c @@ -227,6 +227,33 @@ struct on_nested_pointer_outer { struct size_known **__counted_by(count) buf; }; +// The attribute on a pointer's chunk is checked against where the chunk is in +// the declarator. An array chunk counts as a level of nesting, just like a +// pointer chunk does. +struct on_pointers_to_arrays { + int count; + // On the outermost pointer, to an array of known size. + int (*__counted_by(count) ok)[4]; + // On the outermost pointer, parenthesized. + int (*__counted_by(count) ok_paren); + // On the outermost pointer, to an array of unknown size. + // expected-error@+1{{'counted_by' cannot be applied to a pointer with pointee of unknown size because 'int[]' is an incomplete type}} + int (*__counted_by(count) incomplete)[]; + // The same, with the attribute after the declarator, where it applies to the + // whole declared type, which is the pointer. + // expected-error@+1{{'counted_by' cannot be applied to a pointer with pointee of unknown size because 'int[]' is an incomplete type}} + int (*incomplete_trailing)[] __counted_by(count); + // On a pointer inside the array a pointer points to. With + // -fexperimental-late-parse-attributes it's still treated as a declaration + // attribute on the outermost pointer until late parsing handles type + // attributes. + // immediate-error@+1{{'counted_by' attribute on nested pointer type is not allowed}} + int *__counted_by(count) (*nested)[4]; + // On the return type of a function pointer, in an array a pointer points to. + // immediate-error@+1{{'counted_by' attribute on a function return type is not yet supported}} + int *__counted_by(count) (*(*(*fn_ptr_return)[4])(void))(void); +}; + struct on_pointer_anon_buf_ty_pos { int count; struct { _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
