Skip to content

Commit 3e20bae

Browse files
authored
Reapply "[clang] Introduce [[clang::lifetime_capture_by(X)]] (#115823)
Fix compile time regression and memory leak In the previous change, we saw: - Memory leak: https://lab.llvm.org/buildbot/#/builders/169/builds/5193 - 0.5% Compile time regression [link](https://llvm-compile-time-tracker.com/compare.php?from=4a68e4cbd2423dcacada8162ab7c4bb8d7f7e2cf&to=8c4331c1abeb33eabf3cdbefa7f2b6e0540e7f4f&stat=instructions:u) For compile time regression, we make the Param->Idx `StringMap` for **all** functions. This `StringMap` is expensive and should not be computed when none of the params are annotated with `[[clang::lifetime_capture_by(X)]]`. For the memory leak, the small vectors used in Attribute are not destroyed because the attributes are allocated through ASTContext's allocator. We therefore need a raw array in this case.
1 parent 2a1586d commit 3e20bae

11 files changed

+323
-0
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,9 @@ Attribute Changes in Clang
450450
- Fix a bug where clang doesn't automatically apply the ``[[gsl::Owner]]`` or
451451
``[[gsl::Pointer]]`` to STL explicit template specialization decls. (#GH109442)
452452

453+
- Clang now supports ``[[clang::lifetime_capture_by(X)]]``. Similar to lifetimebound, this can be
454+
used to specify when a reference to a function parameter is captured by another capturing entity ``X``.
455+
453456
Improvements to Clang's diagnostics
454457
-----------------------------------
455458

clang/include/clang/Basic/Attr.td

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1889,6 +1889,37 @@ def LifetimeBound : DeclOrTypeAttr {
18891889
let SimpleHandler = 1;
18901890
}
18911891

1892+
def LifetimeCaptureBy : DeclOrTypeAttr {
1893+
let Spellings = [Clang<"lifetime_capture_by", 0>];
1894+
let Subjects = SubjectList<[ParmVar, ImplicitObjectParameter], ErrorDiag>;
1895+
let Args = [VariadicParamOrParamIdxArgument<"Params">];
1896+
let Documentation = [LifetimeCaptureByDocs];
1897+
let AdditionalMembers = [{
1898+
private:
1899+
ArrayRef<IdentifierInfo*> ArgIdents;
1900+
ArrayRef<SourceLocation> ArgLocs;
1901+
1902+
public:
1903+
static constexpr int THIS = 0;
1904+
static constexpr int INVALID = -1;
1905+
static constexpr int UNKNOWN = -2;
1906+
static constexpr int GLOBAL = -3;
1907+
1908+
void setArgs(ArrayRef<IdentifierInfo*> Idents, ArrayRef<SourceLocation> Locs) {
1909+
assert(Idents.size() == params_Size);
1910+
assert(Locs.size() == params_Size);
1911+
ArgIdents = Idents;
1912+
ArgLocs = Locs;
1913+
}
1914+
auto getArgIdents() const { return ArgIdents; }
1915+
auto getArgLocs() const { return ArgLocs; }
1916+
void setParamIdx(size_t Idx, int Val) {
1917+
assert(Idx < params_Size);
1918+
params_[Idx] = Val;
1919+
}
1920+
}];
1921+
}
1922+
18921923
def TrivialABI : InheritableAttr {
18931924
// This attribute does not have a C [[]] spelling because it requires the
18941925
// CPlusPlus language option.

clang/include/clang/Basic/AttrDocs.td

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3918,6 +3918,75 @@ have their lifetimes extended.
39183918
}];
39193919
}
39203920

3921+
def LifetimeCaptureByDocs : Documentation {
3922+
let Category = DocCatFunction;
3923+
let Content = [{
3924+
Similar to `lifetimebound`_, the ``lifetime_capture_by(X)`` attribute on a function
3925+
parameter or implicit object parameter indicates that that objects that are referred to
3926+
by that parameter may also be referred to by the capturing entity ``X``.
3927+
3928+
By default, a reference is considered to refer to its referenced object, a
3929+
pointer is considered to refer to its pointee, a ``std::initializer_list<T>``
3930+
is considered to refer to its underlying array, and aggregates (arrays and
3931+
simple ``struct``\s) are considered to refer to all objects that their
3932+
transitive subobjects refer to.
3933+
3934+
The capturing entity ``X`` can be one of the following:
3935+
- Another (named) function parameter.
3936+
3937+
.. code-block:: c++
3938+
3939+
void addToSet(std::string_view a [[clang::lifetime_capture_by(s)]], std::set<std::string_view>& s) {
3940+
s.insert(a);
3941+
}
3942+
3943+
- ``this`` (in case of member functions).
3944+
3945+
.. code-block:: c++
3946+
3947+
class S {
3948+
void addToSet(std::string_view a [[clang::lifetime_capture_by(this)]]) {
3949+
s.insert(a);
3950+
}
3951+
std::set<std::string_view> s;
3952+
};
3953+
3954+
- 'global', 'unknown' (without quotes).
3955+
3956+
.. code-block:: c++
3957+
3958+
std::set<std::string_view> s;
3959+
void addToSet(std::string_view a [[clang::lifetime_capture_by(global)]]) {
3960+
s.insert(a);
3961+
}
3962+
void addSomewhere(std::string_view a [[clang::lifetime_capture_by(unknown)]]);
3963+
3964+
The attribute can be applied to the implicit ``this`` parameter of a member
3965+
function by writing the attribute after the function type:
3966+
3967+
.. code-block:: c++
3968+
3969+
struct S {
3970+
const char *data(std::set<S*>& s) [[clang::lifetime_capture_by(s)]] {
3971+
s.insert(this);
3972+
}
3973+
};
3974+
3975+
The attribute supports specifying more than one capturing entities:
3976+
3977+
.. code-block:: c++
3978+
3979+
void addToSets(std::string_view a [[clang::lifetime_capture_by(s1, s2)]],
3980+
std::set<std::string_view>& s1,
3981+
std::set<std::string_view>& s2) {
3982+
s1.insert(a);
3983+
s2.insert(a);
3984+
}
3985+
3986+
.. _`lifetimebound`: https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
3987+
}];
3988+
}
3989+
39213990
def TrivialABIDocs : Documentation {
39223991
let Category = DocCatDecl;
39233992
let Content = [{

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3383,6 +3383,20 @@ def err_callback_callee_is_variadic : Error<
33833383
"'callback' attribute callee may not be variadic">;
33843384
def err_callback_implicit_this_not_available : Error<
33853385
"'callback' argument at position %0 references unavailable implicit 'this'">;
3386+
3387+
def err_capture_by_attribute_multiple : Error<
3388+
"multiple 'lifetime_capture' attributes specified">;
3389+
def err_capture_by_attribute_no_entity : Error<
3390+
"'lifetime_capture_by' attribute specifies no capturing entity">;
3391+
def err_capture_by_implicit_this_not_available : Error<
3392+
"'lifetime_capture_by' argument references unavailable implicit 'this'">;
3393+
def err_capture_by_attribute_argument_unknown : Error<
3394+
"'lifetime_capture_by' attribute argument %0 is not a known function parameter"
3395+
"; must be a function parameter, 'this', 'global' or 'unknown'">;
3396+
def err_capture_by_references_itself : Error<"'lifetime_capture_by' argument references itself">;
3397+
def err_capture_by_param_uses_reserved_name : Error<
3398+
"parameter cannot be named '%select{global|unknown}0' while using 'lifetime_capture_by(%select{global|unknown}0)'">;
3399+
33863400
def err_init_method_bad_return_type : Error<
33873401
"init methods must return an object pointer type, not %0">;
33883402
def err_attribute_invalid_size : Error<

clang/include/clang/Sema/Sema.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1760,6 +1760,14 @@ class Sema final : public SemaBase {
17601760
/// Add [[gsl::Pointer]] attributes for std:: types.
17611761
void inferGslPointerAttribute(TypedefNameDecl *TD);
17621762

1763+
LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
1764+
StringRef ParamName);
1765+
// Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
1766+
// can be the name of a function parameter, we need to parse the function
1767+
// declaration and rest of the parameters before processesing 'X'. Therefore
1768+
// do this lazily instead of processing while parsing the annotation itself.
1769+
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
1770+
17631771
/// Add _Nullable attributes for std:: types.
17641772
void inferNullableClassAttribute(CXXRecordDecl *CRD);
17651773

clang/lib/AST/TypePrinter.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include "clang/AST/TextNodeDumper.h"
2626
#include "clang/AST/Type.h"
2727
#include "clang/Basic/AddressSpaces.h"
28+
#include "clang/Basic/AttrKinds.h"
2829
#include "clang/Basic/ExceptionSpecificationType.h"
2930
#include "clang/Basic/IdentifierTable.h"
3031
#include "clang/Basic/LLVM.h"
@@ -1909,6 +1910,14 @@ void TypePrinter::printAttributedAfter(const AttributedType *T,
19091910
OS << " [[clang::lifetimebound]]";
19101911
return;
19111912
}
1913+
if (T->getAttrKind() == attr::LifetimeCaptureBy) {
1914+
OS << " [[clang::lifetime_capture_by(";
1915+
if (auto *attr = dyn_cast_or_null<LifetimeCaptureByAttr>(T->getAttr()))
1916+
llvm::interleaveComma(attr->getArgIdents(), OS,
1917+
[&](auto it) { OS << it->getName(); });
1918+
OS << ")]]";
1919+
return;
1920+
}
19121921

19131922
// The printing of the address_space attribute is handled by the qualifier
19141923
// since it is still stored in the qualifier. Return early to prevent printing
@@ -1976,6 +1985,7 @@ void TypePrinter::printAttributedAfter(const AttributedType *T,
19761985
case attr::SizedBy:
19771986
case attr::SizedByOrNull:
19781987
case attr::LifetimeBound:
1988+
case attr::LifetimeCaptureBy:
19791989
case attr::TypeNonNull:
19801990
case attr::TypeNullable:
19811991
case attr::TypeNullableResult:

clang/lib/Sema/SemaDecl.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16711,6 +16711,7 @@ void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
1671116711
}
1671216712
}
1671316713

16714+
LazyProcessLifetimeCaptureByParams(FD);
1671416715
inferLifetimeBoundAttribute(FD);
1671516716
AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
1671616717

clang/lib/Sema/SemaDeclAttr.cpp

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include "clang/AST/ASTContext.h"
1515
#include "clang/AST/ASTMutationListener.h"
1616
#include "clang/AST/CXXInheritance.h"
17+
#include "clang/AST/Decl.h"
1718
#include "clang/AST/DeclCXX.h"
1819
#include "clang/AST/DeclObjC.h"
1920
#include "clang/AST/DeclTemplate.h"
@@ -64,6 +65,7 @@
6465
#include "llvm/ADT/StringExtras.h"
6566
#include "llvm/Demangle/Demangle.h"
6667
#include "llvm/IR/Assumptions.h"
68+
#include "llvm/IR/DerivedTypes.h"
6769
#include "llvm/MC/MCSectionMachO.h"
6870
#include "llvm/Support/Error.h"
6971
#include "llvm/Support/MathExtras.h"
@@ -3867,6 +3869,119 @@ static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
38673869
S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
38683870
}
38693871

3872+
LifetimeCaptureByAttr *Sema::ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
3873+
StringRef ParamName) {
3874+
// Atleast one capture by is required.
3875+
if (AL.getNumArgs() == 0) {
3876+
Diag(AL.getLoc(), diag::err_capture_by_attribute_no_entity)
3877+
<< AL.getRange();
3878+
return nullptr;
3879+
}
3880+
unsigned N = AL.getNumArgs();
3881+
auto ParamIdents =
3882+
MutableArrayRef<IdentifierInfo *>(new (Context) IdentifierInfo *[N], N);
3883+
auto ParamLocs =
3884+
MutableArrayRef<SourceLocation>(new (Context) SourceLocation[N], N);
3885+
bool IsValid = true;
3886+
for (unsigned I = 0; I < N; ++I) {
3887+
if (AL.isArgExpr(I)) {
3888+
Expr *E = AL.getArgAsExpr(I);
3889+
Diag(E->getExprLoc(), diag::err_capture_by_attribute_argument_unknown)
3890+
<< E << E->getExprLoc();
3891+
IsValid = false;
3892+
continue;
3893+
}
3894+
assert(AL.isArgIdent(I));
3895+
IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3896+
if (IdLoc->Ident->getName() == ParamName) {
3897+
Diag(IdLoc->Loc, diag::err_capture_by_references_itself) << IdLoc->Loc;
3898+
IsValid = false;
3899+
continue;
3900+
}
3901+
ParamIdents[I] = IdLoc->Ident;
3902+
ParamLocs[I] = IdLoc->Loc;
3903+
}
3904+
if (!IsValid)
3905+
return nullptr;
3906+
SmallVector<int> FakeParamIndices(N, LifetimeCaptureByAttr::INVALID);
3907+
auto *CapturedBy =
3908+
LifetimeCaptureByAttr::Create(Context, FakeParamIndices.data(), N, AL);
3909+
CapturedBy->setArgs(ParamIdents, ParamLocs);
3910+
return CapturedBy;
3911+
}
3912+
3913+
static void handleLifetimeCaptureByAttr(Sema &S, Decl *D,
3914+
const ParsedAttr &AL) {
3915+
// Do not allow multiple attributes.
3916+
if (D->hasAttr<LifetimeCaptureByAttr>()) {
3917+
S.Diag(AL.getLoc(), diag::err_capture_by_attribute_multiple)
3918+
<< AL.getRange();
3919+
return;
3920+
}
3921+
auto *PVD = dyn_cast<ParmVarDecl>(D);
3922+
assert(PVD);
3923+
auto *CaptureByAttr = S.ParseLifetimeCaptureByAttr(AL, PVD->getName());
3924+
if (CaptureByAttr)
3925+
D->addAttr(CaptureByAttr);
3926+
}
3927+
3928+
void Sema::LazyProcessLifetimeCaptureByParams(FunctionDecl *FD) {
3929+
bool HasImplicitThisParam = isInstanceMethod(FD);
3930+
SmallVector<LifetimeCaptureByAttr *, 1> Attrs;
3931+
for (ParmVarDecl *PVD : FD->parameters())
3932+
if (auto *A = PVD->getAttr<LifetimeCaptureByAttr>())
3933+
Attrs.push_back(A);
3934+
if (HasImplicitThisParam) {
3935+
TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3936+
if (!TSI)
3937+
return;
3938+
AttributedTypeLoc ATL;
3939+
for (TypeLoc TL = TSI->getTypeLoc();
3940+
(ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3941+
TL = ATL.getModifiedLoc()) {
3942+
if (auto *A = ATL.getAttrAs<LifetimeCaptureByAttr>())
3943+
Attrs.push_back(const_cast<LifetimeCaptureByAttr *>(A));
3944+
}
3945+
}
3946+
if (Attrs.empty())
3947+
return;
3948+
llvm::StringMap<int> NameIdxMapping = {
3949+
{"global", LifetimeCaptureByAttr::GLOBAL},
3950+
{"unknown", LifetimeCaptureByAttr::UNKNOWN}};
3951+
int Idx = 0;
3952+
if (HasImplicitThisParam) {
3953+
NameIdxMapping["this"] = 0;
3954+
Idx++;
3955+
}
3956+
for (const ParmVarDecl *PVD : FD->parameters())
3957+
NameIdxMapping[PVD->getName()] = Idx++;
3958+
auto DisallowReservedParams = [&](StringRef Reserved) {
3959+
for (const ParmVarDecl *PVD : FD->parameters())
3960+
if (PVD->getName() == Reserved)
3961+
Diag(PVD->getLocation(), diag::err_capture_by_param_uses_reserved_name)
3962+
<< (PVD->getName() == "unknown");
3963+
};
3964+
for (auto *CapturedBy : Attrs) {
3965+
const auto &Entities = CapturedBy->getArgIdents();
3966+
for (size_t I = 0; I < Entities.size(); ++I) {
3967+
StringRef Name = Entities[I]->getName();
3968+
auto It = NameIdxMapping.find(Name);
3969+
if (It == NameIdxMapping.end()) {
3970+
auto Loc = CapturedBy->getArgLocs()[I];
3971+
if (!HasImplicitThisParam && Name == "this")
3972+
Diag(Loc, diag::err_capture_by_implicit_this_not_available) << Loc;
3973+
else
3974+
Diag(Loc, diag::err_capture_by_attribute_argument_unknown)
3975+
<< Entities[I] << Loc;
3976+
continue;
3977+
}
3978+
if (Name == "unknown" || Name == "global")
3979+
DisallowReservedParams(Name);
3980+
CapturedBy->setParamIdx(I, It->second);
3981+
}
3982+
}
3983+
}
3984+
38703985
static bool isFunctionLike(const Type &T) {
38713986
// Check for explicit function types.
38723987
// 'called_once' is only supported in Objective-C and it has
@@ -6644,6 +6759,9 @@ ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL,
66446759
case ParsedAttr::AT_Callback:
66456760
handleCallbackAttr(S, D, AL);
66466761
break;
6762+
case ParsedAttr::AT_LifetimeCaptureBy:
6763+
handleLifetimeCaptureByAttr(S, D, AL);
6764+
break;
66476765
case ParsedAttr::AT_CalledOnce:
66486766
handleCalledOnceAttr(S, D, AL);
66496767
break;

clang/lib/Sema/SemaType.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8609,6 +8609,15 @@ static void HandleLifetimeBoundAttr(TypeProcessingState &State,
86098609
}
86108610
}
86118611

8612+
static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
8613+
QualType &CurType, ParsedAttr &PA) {
8614+
if (State.getDeclarator().isDeclarationOfFunction()) {
8615+
auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
8616+
if (Attr)
8617+
CurType = State.getAttributedType(Attr, CurType, CurType);
8618+
}
8619+
}
8620+
86128621
static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
86138622
QualType &CurType,
86148623
const ParsedAttr &Attr, Sema &S) {
@@ -8770,6 +8779,10 @@ static void processTypeAttrs(TypeProcessingState &state, QualType &type,
87708779
if (TAL == TAL_DeclChunk)
87718780
HandleLifetimeBoundAttr(state, type, attr);
87728781
break;
8782+
case ParsedAttr::AT_LifetimeCaptureBy:
8783+
if (TAL == TAL_DeclChunk)
8784+
HandleLifetimeCaptureByAttr(state, type, attr);
8785+
break;
87738786

87748787
case ParsedAttr::AT_NoDeref: {
87758788
// FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// RUN: %clang_cc1 %s -ast-dump | FileCheck %s
2+
3+
// Verify that we print the [[clang::lifetime_capture_by(X)]] attribute.
4+
5+
struct S {
6+
void foo(int &a, int &b) [[clang::lifetime_capture_by(a, b, global)]];
7+
};
8+
9+
// CHECK: CXXMethodDecl {{.*}}clang::lifetime_capture_by(a, b, global)

0 commit comments

Comments
 (0)