Skip to content

Parse explicit lifetime dependence specifiers in SIL #72431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions include/swift/AST/LifetimeDependence.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ namespace swift {

class AbstractFunctionDecl;
class LifetimeDependentReturnTypeRepr;
class SILParameterInfo;

enum class LifetimeDependenceKind : uint8_t {
Copy = 0,
Expand Down Expand Up @@ -138,12 +139,6 @@ class LifetimeDependenceInfo {
unsigned index,
ValueOwnership ownership);

static std::optional<LifetimeDependenceInfo>
fromTypeRepr(AbstractFunctionDecl *afd, Type resultType, bool allowIndex);

static std::optional<LifetimeDependenceInfo> infer(AbstractFunctionDecl *afd,
Type resultType);

public:
LifetimeDependenceInfo()
: inheritLifetimeParamIndices(nullptr),
Expand Down Expand Up @@ -193,12 +188,30 @@ class LifetimeDependenceInfo {
std::optional<LifetimeDependenceKind>
getLifetimeDependenceOnParam(unsigned paramIndex);

/// Builds LifetimeDependenceInfo from a swift decl, either from the explicit
/// lifetime dependence specifiers or by inference based on types and
/// ownership modifiers.
static std::optional<LifetimeDependenceInfo>
get(AbstractFunctionDecl *decl, Type resultType, bool allowIndex = false);

/// Builds LifetimeDependenceInfo from the bitvectors passes as parameters.
static LifetimeDependenceInfo
get(ASTContext &ctx, const SmallBitVector &inheritLifetimeIndices,
const SmallBitVector &scopeLifetimeIndices);

/// Builds LifetimeDependenceInfo from a swift decl
static std::optional<LifetimeDependenceInfo>
fromTypeRepr(AbstractFunctionDecl *afd, Type resultType, bool allowIndex);

/// Builds LifetimeDependenceInfo from SIL
static std::optional<LifetimeDependenceInfo>
fromTypeRepr(LifetimeDependentReturnTypeRepr *lifetimeDependentRepr,
SmallVectorImpl<SILParameterInfo> &params, bool hasSelfParam,
DeclContext *dc);

/// Infer LifetimeDependenceInfo
static std::optional<LifetimeDependenceInfo> infer(AbstractFunctionDecl *afd,
Type resultType);
};

} // namespace swift
Expand Down
21 changes: 21 additions & 0 deletions include/swift/AST/Types.h
Original file line number Diff line number Diff line change
Expand Up @@ -4155,6 +4155,25 @@ inline bool isGuaranteedParameter(ParameterConvention conv) {
llvm_unreachable("bad convention kind");
}

inline bool isMutatingParameter(ParameterConvention conv) {
switch (conv) {
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable:
case ParameterConvention::Pack_Inout:
return true;

case ParameterConvention::Direct_Guaranteed:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Pack_Guaranteed:
case ParameterConvention::Indirect_In:
case ParameterConvention::Direct_Unowned:
case ParameterConvention::Direct_Owned:
case ParameterConvention::Pack_Owned:
return false;
}
llvm_unreachable("bad convention kind");
}

/// Returns true if conv indicates a pack parameter.
inline bool isPackParameter(ParameterConvention conv) {
switch (conv) {
Expand All @@ -4175,6 +4194,8 @@ inline bool isPackParameter(ParameterConvention conv) {
llvm_unreachable("bad convention kind");
}

StringRef getStringForParameterConvention(ParameterConvention conv);

/// A parameter type and the rules for passing it.
class SILParameterInfo {
public:
Expand Down
2 changes: 1 addition & 1 deletion include/swift/Parse/Parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -1212,7 +1212,7 @@ class Parser {
return true;
if (Context.LangOpts.hasFeature(Feature::NonescapableTypes) &&
(Tok.isContextualKeyword("_resultDependsOn") ||
Tok.isLifetimeDependenceToken()))
Tok.isLifetimeDependenceToken(isInSILMode())))
return true;
return false;
}
Expand Down
9 changes: 7 additions & 2 deletions include/swift/Parse/Token.h
Original file line number Diff line number Diff line change
Expand Up @@ -267,9 +267,14 @@ class Token {
return MultilineString;
}

bool isLifetimeDependenceToken() const {
bool isLifetimeDependenceToken(bool isInSILMode) const {
return isContextualKeyword("_copy") || isContextualKeyword("_consume") ||
isContextualKeyword("_borrow") || isContextualKeyword("_mutate");
isContextualKeyword("_borrow") || isContextualKeyword("_mutate") ||
// SIL tests are currently written with _inherit/_scope
// Once we have dependsOn()/dependsOn(borrowed:) other tokens go
// away.
(isInSILMode &&
(isContextualKeyword("_inherit") || isContextualKeyword("_scope")));
}

/// Count of extending escaping '#'.
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/ASTPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7436,7 +7436,7 @@ std::string GenericSignature::getAsString() const {
return out.str();
}

static StringRef getStringForParameterConvention(ParameterConvention conv) {
StringRef swift::getStringForParameterConvention(ParameterConvention conv) {
switch (conv) {
case ParameterConvention::Indirect_In: return "@in ";
case ParameterConvention::Indirect_In_Guaranteed: return "@in_guaranteed ";
Expand Down
6 changes: 3 additions & 3 deletions lib/Parse/ParseDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5048,13 +5048,13 @@ ParserStatus Parser::parseTypeAttribute(TypeOrCustomAttr &result,

static std::optional<LifetimeDependenceKind>
getLifetimeDependenceKind(const Token &T) {
if (T.isContextualKeyword("_copy")) {
if (T.isContextualKeyword("_copy") || T.isContextualKeyword("_inherit")) {
return LifetimeDependenceKind::Copy;
}
if (T.isContextualKeyword("_consume")) {
return LifetimeDependenceKind::Consume;
}
if (T.isContextualKeyword("_borrow")) {
if (T.isContextualKeyword("_borrow") || T.isContextualKeyword("_scope")) {
return LifetimeDependenceKind::Borrow;
}
if (T.isContextualKeyword("_mutate")) {
Expand Down Expand Up @@ -5454,7 +5454,7 @@ ParserStatus Parser::ParsedTypeAttributeList::slowParse(Parser &P) {
continue;
}

if (Tok.isLifetimeDependenceToken()) {
if (Tok.isLifetimeDependenceToken(P.isInSILMode())) {
if (!P.Context.LangOpts.hasFeature(Feature::NonescapableTypes)) {
P.diagnose(Tok, diag::requires_experimental_feature,
"lifetime dependence specifier", false,
Expand Down
75 changes: 75 additions & 0 deletions lib/Sema/LifetimeDependence.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,81 @@ LifetimeDependenceInfo::fromTypeRepr(AbstractFunctionDecl *afd, Type resultType,
/*isExplicit*/ true);
}

// This utility is similar to its overloaded version that builds the
// LifetimeDependenceInfo from the swift decl. Reason for duplicated code is the
// apis on type and ownership is different in SIL compared to Sema.
std::optional<LifetimeDependenceInfo> LifetimeDependenceInfo::fromTypeRepr(
LifetimeDependentReturnTypeRepr *lifetimeDependentRepr,
SmallVectorImpl<SILParameterInfo> &params, bool hasSelfParam,
DeclContext *dc) {
auto &ctx = dc->getASTContext();
auto &diags = ctx.Diags;
auto capacity = hasSelfParam ? params.size() : params.size() + 1;

SmallBitVector inheritLifetimeParamIndices(capacity);
SmallBitVector scopeLifetimeParamIndices(capacity);

auto updateLifetimeDependenceInfo = [&](LifetimeDependenceSpecifier specifier,
unsigned paramIndexToSet,
ParameterConvention paramConvention) {
auto loc = specifier.getLoc();
auto kind = specifier.getLifetimeDependenceKind();

// Once we have dependsOn()/dependsOn(scoped:) syntax, this enum values will
// be Scope and Inherit.
if (kind == LifetimeDependenceKind::Borrow &&
(!isGuaranteedParameter(paramConvention) &&
!isMutatingParameter(paramConvention))) {
diags.diagnose(loc, diag::lifetime_dependence_cannot_use_kind, "_scope",
getStringForParameterConvention(paramConvention));
return true;
}

if (inheritLifetimeParamIndices.test(paramIndexToSet) ||
scopeLifetimeParamIndices.test(paramIndexToSet)) {
diags.diagnose(loc, diag::lifetime_dependence_duplicate_param_id);
return true;
}
if (kind == LifetimeDependenceKind::Copy) {
inheritLifetimeParamIndices.set(paramIndexToSet);
} else {
assert(kind == LifetimeDependenceKind::Borrow);
scopeLifetimeParamIndices.set(paramIndexToSet);
}
return false;
};

for (auto specifier : lifetimeDependentRepr->getLifetimeDependencies()) {
assert(specifier.getSpecifierKind() ==
LifetimeDependenceSpecifier::SpecifierKind::Ordered);
auto index = specifier.getIndex();
if (index > params.size()) {
diags.diagnose(specifier.getLoc(),
diag::lifetime_dependence_invalid_param_index, index);
return std::nullopt;
}
if (index == 0 && !hasSelfParam) {
diags.diagnose(specifier.getLoc(),
diag::lifetime_dependence_invalid_self);
return std::nullopt;
}
auto param = index == 0 ? params.back() : params[index - 1];
auto paramConvention = param.getConvention();
if (updateLifetimeDependenceInfo(specifier, index, paramConvention)) {
return std::nullopt;
}
}

return LifetimeDependenceInfo(
inheritLifetimeParamIndices.any()
? IndexSubset::get(ctx, inheritLifetimeParamIndices)
: nullptr,
scopeLifetimeParamIndices.any()
? IndexSubset::get(ctx, scopeLifetimeParamIndices)
: nullptr,
/*isExplicit*/ true);
}

std::optional<LifetimeDependenceInfo>
LifetimeDependenceInfo::infer(AbstractFunctionDecl *afd, Type resultType) {
auto *dc = afd->getDeclContext();
Expand Down
23 changes: 21 additions & 2 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4082,7 +4082,6 @@ NeverNullType TypeResolver::resolveASTFunctionType(
// TODO: maybe make this the place that claims @escaping.
bool noescape = isDefaultNoEscapeContext(parentOptions);

// TODO: Handle LifetimeDependenceInfo here.
FunctionType::ExtInfoBuilder extInfoBuilder(
FunctionTypeRepresentation::Swift, noescape, repr->isThrowing(), thrownTy,
diffKind, /*clangFunctionType*/ nullptr, isolation,
Expand Down Expand Up @@ -4293,7 +4292,6 @@ NeverNullType TypeResolver::resolveSILFunctionType(FunctionTypeRepr *repr,
}
}

// TODO: Handle LifetimeDependenceInfo here.
auto extInfoBuilder = SILFunctionType::ExtInfoBuilder(
representation, pseudogeneric, noescape, sendable, async, unimplementable,
isolation, diffKind, clangFnType, LifetimeDependenceInfo());
Expand Down Expand Up @@ -4466,6 +4464,19 @@ NeverNullType TypeResolver::resolveSILFunctionType(FunctionTypeRepr *repr,
extInfoBuilder = extInfoBuilder.withClangFunctionType(clangFnType);
}

std::optional<LifetimeDependenceInfo> lifetimeDependenceInfo;
if (auto *lifetimeDependentTypeRepr =
dyn_cast<LifetimeDependentReturnTypeRepr>(
repr->getResultTypeRepr())) {
lifetimeDependenceInfo = LifetimeDependenceInfo::fromTypeRepr(
lifetimeDependentTypeRepr, params, extInfoBuilder.hasSelfParam(),
getDeclContext());
if (lifetimeDependenceInfo.has_value()) {
extInfoBuilder =
extInfoBuilder.withLifetimeDependenceInfo(*lifetimeDependenceInfo);
}
}

return SILFunctionType::get(genericSig.getCanonicalSignature(),
extInfoBuilder.build(), coroutineKind,
callee, params, yields, results, errorResult,
Expand Down Expand Up @@ -4579,6 +4590,14 @@ bool TypeResolver::resolveSingleSILResult(

options.setContext(TypeResolverContext::FunctionResult);

// Look through LifetimeDependentReturnTypeRepr.
// LifetimeDependentReturnTypeRepr will be processed separately when building
// SILFunctionType.
if (auto *lifetimeDependentTypeRepr =
dyn_cast<LifetimeDependentReturnTypeRepr>(repr)) {
repr = lifetimeDependentTypeRepr->getBase();
}

if (auto attrRepr = dyn_cast<AttributedTypeRepr>(repr)) {
TypeAttrSet attrs(getASTContext());
auto repr = attrs.accumulate(attrRepr);
Expand Down
77 changes: 77 additions & 0 deletions test/SIL/Parser/lifetime_dependence.sil
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// RUN: %target-sil-opt %s \
// RUN: -enable-experimental-feature NonescapableTypes \
// RUN: -enable-experimental-feature NoncopyableGenerics | %FileCheck %s

sil_stage canonical

import Builtin
import Swift

struct BufferView : ~Escapable {
@_hasStorage let ptr: UnsafeRawBufferPointer { get }
@_unsafeNonescapableResult @inlinable init(_ ptr: UnsafeRawBufferPointer)
init(_ ptr: UnsafeRawBufferPointer, _ a: borrowing Array<Int>) -> _borrow(a) Self
}

func derive(_ x: borrowing BufferView) -> _borrow(x) BufferView

func consumeAndCreate(_ x: consuming BufferView) -> _copy(x) BufferView

sil hidden [unsafe_nonescapable_result] @bufferviewinit1 : $@convention(method) (UnsafeRawBufferPointer, @thin BufferView.Type) -> @owned BufferView {
bb0(%0 : $UnsafeRawBufferPointer, %1 : $@thin BufferView.Type):
%2 = alloc_stack [var_decl] $BufferView, var, name "self", implicit
debug_value %0 : $UnsafeRawBufferPointer, let, name "ptr", argno 1
%4 = begin_access [modify] [static] %2 : $*BufferView
%5 = struct_element_addr %4 : $*BufferView, #BufferView.ptr
store %0 to %5 : $*UnsafeRawBufferPointer
end_access %4 : $*BufferView
%8 = struct $BufferView (%0 : $UnsafeRawBufferPointer)
destroy_addr %2 : $*BufferView
dealloc_stack %2 : $*BufferView
return %8 : $BufferView
}

// CHECK-LABEL: sil hidden @bufferviewtest2 : $@convention(method) (UnsafeRawBufferPointer, @guaranteed Array<Int>, @thin BufferView.Type) -> _scope(2) @owned BufferView {
sil hidden @bufferviewtest2 : $@convention(method) (UnsafeRawBufferPointer, @guaranteed Array<Int>, @thin BufferView.Type) -> _scope(2) @owned BufferView {
bb0(%0 : $UnsafeRawBufferPointer, %1 : @noImplicitCopy $Array<Int>, %2 : $@thin BufferView.Type):
%3 = alloc_stack [var_decl] $BufferView, var, name "self", implicit
%6 = begin_access [modify] [static] %3 : $*BufferView
%7 = struct_element_addr %6 : $*BufferView, #BufferView.ptr
store %0 to %7 : $*UnsafeRawBufferPointer
end_access %6 : $*BufferView
%10 = struct $BufferView (%0 : $UnsafeRawBufferPointer)
destroy_addr %3 : $*BufferView
dealloc_stack %3 : $*BufferView
return %10 : $BufferView
}

// CHECK-LABEL: sil hidden @derive : $@convention(thin) (@guaranteed BufferView) -> _scope(1) @owned BufferView {
sil hidden @derive : $@convention(thin) (@guaranteed BufferView) -> _scope(1) @owned BufferView {
bb0(%0 : @noImplicitCopy $BufferView):
%2 = metatype $@thin BufferView.Type
%3 = struct_extract %0 : $BufferView, #BufferView.ptr
%4 = function_ref @bufferviewinit1 : $@convention(method) (UnsafeRawBufferPointer, @thin BufferView.Type) -> @owned BufferView
%5 = apply %4(%3, %2) : $@convention(method) (UnsafeRawBufferPointer, @thin BufferView.Type) -> @owned BufferView
return %5 : $BufferView
}

// CHECK-LABEL: sil hidden @consumeAndCreate : $@convention(thin) (@owned BufferView) -> _inherit(1) @owned BufferView {
sil hidden @consumeAndCreate : $@convention(thin) (@owned BufferView) -> _inherit(1) @owned BufferView {
bb0(%0 : @noImplicitCopy @_eagerMove $BufferView):
%1 = alloc_stack [var_decl] [moveable_value_debuginfo] $BufferView, var, name "x"
%2 = struct_extract %0 : $BufferView, #BufferView.ptr
%3 = struct_extract %2 : $UnsafeRawBufferPointer, #UnsafeRawBufferPointer._position
%4 = struct_extract %0 : $BufferView, #BufferView.ptr
%5 = struct_extract %4 : $UnsafeRawBufferPointer, #UnsafeRawBufferPointer._end
store %0 to %1 : $*BufferView
%7 = metatype $@thin BufferView.Type
%8 = begin_access [read] [static] %1 : $*BufferView
%9 = struct $UnsafeRawBufferPointer (%3 : $Optional<UnsafeRawPointer>, %5 : $Optional<UnsafeRawPointer>)
end_access %8 : $*BufferView
%11 = function_ref @bufferviewinit1 : $@convention(method) (UnsafeRawBufferPointer, @thin BufferView.Type) -> @owned BufferView
%12 = apply %11(%9, %7) : $@convention(method) (UnsafeRawBufferPointer, @thin BufferView.Type) -> @owned BufferView
destroy_addr %1 : $*BufferView
dealloc_stack %1 : $*BufferView
return %12 : $BufferView
}