diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -4158,3 +4158,27 @@ let Subjects = SubjectList<[Record]>; let Documentation = [ReadOnlyPlacementDocs]; } + +def ElementCount : InheritableAttr { + let Spellings = [Clang<"element_count">]; + let Subjects = SubjectList<[Field]>; + let Args = [VariadicIdentifierArgument<"ElementCountFields">]; + let Documentation = [ElementCountDocs]; + let LangOpts = [COnly]; + code AdditionalMembers = [{ + private: + mutable SmallVector CountFieldRanges; + public: + void copyCountFieldSourceRanges(ElementCountAttr *ECA) const { + for (SourceRange SR : CountFieldRanges) + ECA->addCountFieldSourceRange(SR); + } + void addCountFieldSourceRange(ArrayRef Ranges) const { + for (SourceRange SR : Ranges) + CountFieldRanges.push_back(SR); + } + SourceRange getCountFieldSourceRange(unsigned Idx) const { + return CountFieldRanges[Idx]; + } + }]; +} diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td --- a/clang/include/clang/Basic/AttrDocs.td +++ b/clang/include/clang/Basic/AttrDocs.td @@ -6950,3 +6950,72 @@ its underlying representation to be a WebAssembly ``funcref``. }]; } + +def ElementCountDocs : Documentation { + let Category = DocCatField; + let Content = [{ +Clang supports the ``element_count`` attribute for flexible array members. The +field for the ``element_count`` attribute is a field member in the same +structure holding the count of elements in the flexible array. + +For example: + +.. code-block:: c + + struct bar; + + struct foo { + size_t num_fam_elements; + /* ... */ + struct bar *fam[] __attribute__((element_count(num_fam_elements))); + }; + + struct foo *foo_alloc(size_t num_elements) { + struct foo *f; + + f = malloc(sizeof(struct foo) + num_elements * sizeof(struct bar *)); + f->num_fam_elements = num_elements; + return f; + } + +This attribute is used with the ``-fsantize=array-bounds`` flag to trap if a +flexible array access is outside of the number of elements. + +.. code-block:: c + + void mux(struct foo *); + + struct bar *baz(void) { + struct foo *f = foo_alloc(128); + + mux(f); /* Fills in fam element. */ + + return f->fam[256]; /* Trap. */ + } + +It's possible to specify an element in a substructure. The attribute syntax can +take a list of field names to the element count. + +For example: + +.. code-block:: c + + struct bar; + + struct foo { + struct { + size_t num_fam_elements; + } bork; + /* ... */ + struct bar *fam[] __attribute__((element_count(bork, num_fam_elements))); + }; + + struct foo *foo_alloc(size_t num_elements) { + struct foo *f; + + f = malloc(sizeof(struct foo) + num_elements * sizeof(struct bar *)); + f->bork.num_fam_elements = num_elements; + return f; + } + }]; +} diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -3356,6 +3356,9 @@ def err_alignment_dependent_typedef_name : Error< "requested alignment is dependent but declaration is not dependent">; +def warn_element_count_placeholder : Warning< + "element count %0 doesn't exist">; + def warn_alignment_builtin_useless : Warning< "%select{aligning a value|the result of checking whether a value is aligned}0" " to 1 byte is %select{a no-op|always true}0">, InGroup; diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp --- a/clang/lib/AST/ASTImporter.cpp +++ b/clang/lib/AST/ASTImporter.cpp @@ -8765,6 +8765,8 @@ }; class AttrImporter { + friend ASTImporter; + Error Err{Error::success()}; Attr *ToAttr = nullptr; ASTImporter &Importer; @@ -8979,6 +8981,12 @@ From->args_size()); break; } + case attr::ElementCount: { + AI.cloneAttr(FromAttr); + cast(FromAttr)->copyCountFieldSourceRanges( + cast(AI.ToAttr)); + break; + } default: { // The default branch works for attributes that have no arguments to import. diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -946,6 +946,50 @@ return CGF.getVLASize(VAT).NumElts; // Ignore pass_object_size here. It's not applicable on decayed pointers. } + + if (const auto *ME = dyn_cast(CE->getSubExpr())) { + if (ME->isFlexibleArrayMemberLike(CGF.getContext(), + StrictFlexArraysLevel, true)) { + if (const auto *MD = dyn_cast(ME->getMemberDecl())) { + if (const auto ECA = MD->getAttr()) { + const RecordDecl *RD = MD->getParent(); + MemberExpr *Mem = nullptr; + + for (const IdentifierInfo *CountField : ECA->elementCountFields()) { + MemberExpr *TmpMem = nullptr; + + for (FieldDecl *FD : RD->fields()) { + if (FD->getName() != CountField->getName()) + continue; + + if (Mem) + TmpMem = MemberExpr::CreateImplicit( + CGF.getContext(), Mem, Mem->getType()->isPointerType(), + FD, FD->getType(), VK_LValue, OK_Ordinary); + else + TmpMem = MemberExpr::CreateImplicit( + CGF.getContext(), const_cast(ME->getBase()), + ME->isArrow(), FD, FD->getType(), VK_LValue, + OK_Ordinary); + + if (FD->getType()->isRecordType()) + RD = FD->getType()->getAsRecordDecl(); + + break; + } + + Mem = TmpMem; + if (!Mem) break; + } + + if (Mem) { + IndexedType = Base->getType(); + return CGF.EmitAnyExprToTemp(Mem).getScalarVal(); + } + } + } + } + } } QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0}; diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -17686,6 +17686,43 @@ "Broken injected-class-name"); } +static const FieldDecl *FindFieldWithElementCountAttr(const RecordDecl *RD) { + for (const Decl *D : RD->decls()) { + if (const auto *FD = dyn_cast(D)) + if (FD->hasAttr()) + return FD; + + if (const auto *SubRD = dyn_cast(D)) + if (const FieldDecl *FD = FindFieldWithElementCountAttr(SubRD)) + return FD; + } + + return nullptr; +} + +static bool CheckElementCountAttr(const RecordDecl *RD, const FieldDecl *FD, + SourceRange &Loc) { + const ElementCountAttr *ECA = FD->getAttr(); + unsigned Idx = 0; + + for (const IdentifierInfo *II : ECA->elementCountFields()) { + Loc = ECA->getCountFieldSourceRange(Idx++); + + auto DeclIter = llvm::find_if( + RD->fields(), [&](const FieldDecl *FD){ + return II->getName() == FD->getName(); + }); + + if (DeclIter == RD->field_end()) + return false; + + if (auto *SubRD = DeclIter->getType()->getAsRecordDecl()) + RD = SubRD; + } + + return true; +} + void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, SourceRange BraceRange) { AdjustDeclIfTemplate(TagD); @@ -17743,6 +17780,17 @@ [](const FieldDecl *FD) { return FD->isBitField(); })) Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); } + + // Check the "element_count" attribute to ensure that the count field exists + // in the struct. + if (const RecordDecl *RD = dyn_cast(Tag)) { + if (const FieldDecl *FD = FindFieldWithElementCountAttr(RD)) { + SourceRange SR; + if (!CheckElementCountAttr(RD, FD, SR)) + Diag(SR.getBegin(), diag::warn_element_count_placeholder) + << FD->getName() << SR; + } + } } void Sema::ActOnObjCContainerFinishDefinition() { diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -8238,6 +8238,29 @@ D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL)); } +static void handleElementCountAttr(Sema &S, Decl *D, const ParsedAttr &AL) { + // TODO: Probably needs more processing here. See Sema::AddAlignValueAttr. + SmallVector Names; + SmallVector Ranges; + for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) { + if (!AL.isArgIdent(ArgNo)) { + S.Diag(AL.getLoc(), diag::err_attribute_argument_type) + << AL << AANT_ArgumentIdentifier; + return; + } + + IdentifierLoc *IL = AL.getArgAsIdent(ArgNo); + Names.push_back(IL->Ident); + Ranges.push_back(IL->Loc); + } + + ElementCountAttr *ECA = ::new (S.Context) ElementCountAttr(S.Context, AL, + Names.data(), + Names.size()); + ECA->addCountFieldSourceRange(Ranges); + D->addAttr(ECA); +} + static void handleFunctionReturnThunksAttr(Sema &S, Decl *D, const ParsedAttr &AL) { StringRef KindStr; @@ -9142,6 +9165,9 @@ case ParsedAttr::AT_FunctionReturnThunks: handleFunctionReturnThunksAttr(S, D, AL); break; + case ParsedAttr::AT_ElementCount: + handleElementCountAttr(S, D, AL); + break; // Microsoft attributes: case ParsedAttr::AT_LayoutVersion: diff --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test b/clang/test/Misc/pragma-attribute-supported-attributes-list.test --- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test +++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test @@ -61,6 +61,7 @@ // CHECK-NEXT: DiagnoseAsBuiltin (SubjectMatchRule_function) // CHECK-NEXT: DisableSanitizerInstrumentation (SubjectMatchRule_function, SubjectMatchRule_objc_method, SubjectMatchRule_variable_is_global) // CHECK-NEXT: DisableTailCalls (SubjectMatchRule_function, SubjectMatchRule_objc_method) +// CHECK-NEXT: ElementCount (SubjectMatchRule_field) // CHECK-NEXT: EnableIf (SubjectMatchRule_function) // CHECK-NEXT: EnforceTCB (SubjectMatchRule_function, SubjectMatchRule_objc_method) // CHECK-NEXT: EnforceTCBLeaf (SubjectMatchRule_function, SubjectMatchRule_objc_method)