Skip to content

[SILGen] Fix the type of closure thunks that are passed const reference structs #3 #83563

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
30 changes: 15 additions & 15 deletions include/swift/AST/Expr.h
Original file line number Diff line number Diff line change
Expand Up @@ -3368,8 +3368,8 @@ class UnresolvedTypeConversionExpr : public ImplicitConversionExpr {
class FunctionConversionExpr : public ImplicitConversionExpr {
public:
FunctionConversionExpr(Expr *subExpr, Type type)
: ImplicitConversionExpr(ExprKind::FunctionConversion, subExpr, type) {}
: ImplicitConversionExpr(ExprKind::FunctionConversion, subExpr, type) {}

static bool classof(const Expr *E) {
return E->getKind() == ExprKind::FunctionConversion;
}
Expand Down Expand Up @@ -4301,19 +4301,19 @@ class ClosureExpr : public AbstractClosureExpr {
}

public:
ClosureExpr(const DeclAttributes &attributes,
SourceRange bracketRange, VarDecl *capturedSelfDecl,
ParameterList *params, SourceLoc asyncLoc, SourceLoc throwsLoc,
TypeExpr *thrownType, SourceLoc arrowLoc, SourceLoc inLoc,
TypeExpr *explicitResultType, DeclContext *parent)
: AbstractClosureExpr(ExprKind::Closure, Type(), /*Implicit=*/false,
parent),
Attributes(attributes), BracketRange(bracketRange),
CapturedSelfDecl(capturedSelfDecl),
AsyncLoc(asyncLoc), ThrowsLoc(throwsLoc), ArrowLoc(arrowLoc),
InLoc(inLoc), ThrownType(thrownType),
ExplicitResultTypeAndBodyState(explicitResultType, BodyState::Parsed),
Body(nullptr) {
ClosureExpr(const DeclAttributes &attributes, SourceRange bracketRange,
VarDecl *capturedSelfDecl, ParameterList *params,
SourceLoc asyncLoc, SourceLoc throwsLoc, TypeExpr *thrownType,
SourceLoc arrowLoc, SourceLoc inLoc, TypeExpr *explicitResultType,
DeclContext *parent)
: AbstractClosureExpr(ExprKind::Closure, Type(), /*Implicit=*/false,
parent),
Attributes(attributes), BracketRange(bracketRange),
CapturedSelfDecl(capturedSelfDecl), AsyncLoc(asyncLoc),
ThrowsLoc(throwsLoc), ArrowLoc(arrowLoc), InLoc(inLoc),
ThrownType(thrownType),
ExplicitResultTypeAndBodyState(explicitResultType, BodyState::Parsed),
Body(nullptr) {
setParameterList(params);
Bits.ClosureExpr.HasAnonymousClosureVars = false;
Bits.ClosureExpr.ImplicitSelfCapture = false;
Expand Down
8 changes: 3 additions & 5 deletions include/swift/SIL/SILDeclRef.h
Original file line number Diff line number Diff line change
Expand Up @@ -261,11 +261,9 @@ struct SILDeclRef {
/// for the containing ClassDecl.
/// - If 'loc' is a global VarDecl, this returns its GlobalAccessor
/// SILDeclRef.
explicit SILDeclRef(
Loc loc,
bool isForeign = false,
bool isDistributed = false,
bool isDistributedLocal = false);
explicit SILDeclRef(Loc loc, bool isForeign = false,
bool isDistributed = false,
bool isDistributedLocal = false);

/// See above put produces a prespecialization according to the signature.
explicit SILDeclRef(Loc loc, GenericSignature prespecializationSig);
Expand Down
3 changes: 2 additions & 1 deletion include/swift/SIL/SILFunctionBuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ class SILFunctionBuilder {
llvm::function_ref<SILFunction *(SILLocation loc, SILDeclRef constant)>
getOrCreateDeclaration = [](SILLocation loc, SILDeclRef constant)
-> SILFunction * { return nullptr; },
ProfileCounter entryCount = ProfileCounter());
ProfileCounter entryCount = ProfileCounter(),
const clang::Type *foreignType = nullptr);

/// Create a function declaration.
///
Expand Down
19 changes: 11 additions & 8 deletions include/swift/SIL/TypeLowering.h
Original file line number Diff line number Diff line change
Expand Up @@ -875,8 +875,9 @@ class TypeConverter {

/// Returns the formal type, lowered AST type, and SILFunctionType
/// for a constant reference.
const SILConstantInfo &getConstantInfo(TypeExpansionContext context,
SILDeclRef constant);
const SILConstantInfo &
getConstantInfo(TypeExpansionContext context, SILDeclRef constant,
const clang::Type *foreignType = nullptr);

/// Get the generic signature for a constant.
GenericSignatureWithCapturedEnvironments
Expand Down Expand Up @@ -904,11 +905,12 @@ class TypeConverter {
}

/// Returns the SILFunctionType for the given declaration.
CanSILFunctionType getConstantFunctionType(TypeExpansionContext context,
SILDeclRef constant) {
return getConstantInfo(context, constant).SILFnType;
CanSILFunctionType
getConstantFunctionType(TypeExpansionContext context, SILDeclRef constant,
const clang::Type *foreignType = nullptr) {
return getConstantInfo(context, constant, foreignType).SILFnType;
}

/// Returns the SILParameterInfo for the given declaration's `self` parameter.
/// `constant` must refer to a method.
SILParameterInfo getConstantSelfParameter(TypeExpansionContext context,
Expand Down Expand Up @@ -977,8 +979,9 @@ class TypeConverter {
};

/// Derive the lowered formal type of the given constant.
LoweredFormalTypes getLoweredFormalTypes(SILDeclRef constant,
CanAnyFunctionType formalType);
LoweredFormalTypes
getLoweredFormalTypes(SILDeclRef constant, CanAnyFunctionType formalType,
const clang::Type *foreignType = nullptr);

/// Given a function type, yield its bridged formal type.
CanAnyFunctionType getBridgedFunctionType(AbstractionPattern fnPattern,
Expand Down
4 changes: 2 additions & 2 deletions lib/SIL/IR/SILFunctionBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -290,10 +290,10 @@ SILFunction *SILFunctionBuilder::getOrCreateFunction(
SILLocation loc, SILDeclRef constant, ForDefinition_t forDefinition,
llvm::function_ref<SILFunction *(SILLocation loc, SILDeclRef constant)>
getOrCreateDeclaration,
ProfileCounter entryCount) {
ProfileCounter entryCount, const clang::Type *foreignType) {
auto nameTmp = constant.mangle();
auto constantType = mod.Types.getConstantFunctionType(
TypeExpansionContext::minimal(), constant);
TypeExpansionContext::minimal(), constant, foreignType);
SILLinkage linkage = constant.getLinkage(forDefinition);

if (auto fn = mod.lookUpFunction(nameTmp)) {
Expand Down
37 changes: 23 additions & 14 deletions lib/SIL/IR/SILFunctionType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Expr.h"
#include "swift/AST/Type.h"
#define DEBUG_TYPE "libsil"

#include "swift/AST/AnyFunctionRef.h"
Expand Down Expand Up @@ -4320,10 +4322,12 @@ static CanSILFunctionType getUncachedSILFunctionTypeForConstant(
// The type of the native-to-foreign thunk for a swift closure.
if (constant.isForeign && constant.hasClosureExpr() &&
shouldStoreClangType(TC.getDeclRefRepresentation(constant))) {
auto clangType = TC.Context.getClangFunctionType(
origLoweredInterfaceType->getParams(),
origLoweredInterfaceType->getResult(),
FunctionTypeRepresentation::CFunctionPointer);
auto clangType = extInfoBuilder.getClangTypeInfo().getType();
if (!clangType)
clangType = TC.Context.getClangFunctionType(
origLoweredInterfaceType->getParams(),
origLoweredInterfaceType->getResult(),
FunctionTypeRepresentation::CFunctionPointer);
AbstractionPattern pattern =
AbstractionPattern(origLoweredInterfaceType, clangType);
return getSILFunctionTypeForAbstractCFunction(
Expand Down Expand Up @@ -4478,7 +4482,8 @@ getLoweredResultIndices(const SILFunctionType *functionType,

const SILConstantInfo &
TypeConverter::getConstantInfo(TypeExpansionContext expansion,
SILDeclRef constant) {
SILDeclRef constant,
const clang::Type *foreignType) {
if (!DisableConstantInfoCache) {
auto found = ConstantTypes.find(std::make_pair(expansion, constant));
if (found != ConstantTypes.end())
Expand All @@ -4491,7 +4496,8 @@ TypeConverter::getConstantInfo(TypeExpansionContext expansion,

// The lowered type is the formal type, but uncurried and with
// parameters automatically turned into their bridged equivalents.
auto bridgedTypes = getLoweredFormalTypes(constant, formalInterfaceType);
auto bridgedTypes =
getLoweredFormalTypes(constant, formalInterfaceType, foreignType);

CanAnyFunctionType loweredInterfaceType = bridgedTypes.Uncurried;

Expand Down Expand Up @@ -4826,16 +4832,19 @@ static AbstractFunctionDecl *getBridgedFunction(SILDeclRef declRef) {
llvm_unreachable("bad SILDeclRef kind");
}

static AbstractionPattern
getAbstractionPatternForConstant(ASTContext &ctx, SILDeclRef constant,
CanAnyFunctionType fnType,
unsigned numParameterLists) {
static AbstractionPattern getAbstractionPatternForConstant(
ASTContext &ctx, SILDeclRef constant, CanAnyFunctionType fnType,
unsigned numParameterLists, const clang::Type *foreignType) {
if (!constant.isForeign)
return AbstractionPattern(fnType);

if (foreignType)
return AbstractionPattern(fnType, foreignType);

auto bridgedFn = getBridgedFunction(constant);
if (!bridgedFn)
return AbstractionPattern(fnType);

const clang::Decl *clangDecl = bridgedFn->getClangDecl();
if (!clangDecl)
return AbstractionPattern(fnType);
Expand Down Expand Up @@ -4870,17 +4879,17 @@ getAbstractionPatternForConstant(ASTContext &ctx, SILDeclRef constant,

TypeConverter::LoweredFormalTypes
TypeConverter::getLoweredFormalTypes(SILDeclRef constant,
CanAnyFunctionType fnType) {
CanAnyFunctionType fnType,
const clang::Type *foreignType) {
// We always use full bridging when importing a constant because we can
// directly bridge its arguments and results when calling it.
auto bridging = Bridgeability::Full;

unsigned numParameterLists = constant.getParameterListCount();

// Form an abstraction pattern for bridging purposes.
AbstractionPattern bridgingFnPattern =
getAbstractionPatternForConstant(Context, constant, fnType,
numParameterLists);
AbstractionPattern bridgingFnPattern = getAbstractionPatternForConstant(
Context, constant, fnType, numParameterLists, foreignType);

auto extInfo = fnType->getExtInfo();
SILFunctionTypeRepresentation rep = getDeclRefRepresentation(constant);
Expand Down
31 changes: 22 additions & 9 deletions lib/SILGen/Conversion.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
#ifndef SWIFT_LOWERING_CONVERSION_H
#define SWIFT_LOWERING_CONVERSION_H

#include "swift/Basic/Assertions.h"
#include "swift/Basic/ExternalUnion.h"
#include "Initialization.h"
#include "SGFContext.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/ExternalUnion.h"
#include "swift/SIL/AbstractionPattern.h"
#include <optional>

namespace swift {
namespace Lowering {
Expand Down Expand Up @@ -115,6 +117,7 @@ class Conversion {

struct BridgingStorage {
bool IsExplicit;
AbstractionPattern InputOrigType;
};

/// The types we store for reabstracting contexts. In general, when
Expand Down Expand Up @@ -161,11 +164,11 @@ class Conversion {
static_assert(decltype(Types)::union_is_trivially_copyable,
"define the special members if this changes");

Conversion(KindTy kind, CanType sourceType, CanType resultType,
SILType loweredResultTy, bool isExplicit)
Conversion(KindTy kind, AbstractionPattern inputOrigType, CanType sourceType,
CanType resultType, SILType loweredResultTy, bool isExplicit)
: Kind(kind), SourceType(sourceType), ResultType(resultType),
LoweredResultType(loweredResultTy) {
Types.emplaceAggregate<BridgingStorage>(kind, isExplicit);
Types.emplaceAggregate<BridgingStorage>(kind, isExplicit, inputOrigType);
}

Conversion(AbstractionPattern inputOrigType, CanType inputSubstType,
Expand Down Expand Up @@ -236,13 +239,19 @@ class Conversion {
outputOrigType, outputSubstType, outputLoweredTy);
}

static Conversion getBridging(KindTy kind, CanType origType,
CanType resultType, SILType loweredResultTy,
bool isExplicit = false) {
static Conversion
getBridging(KindTy kind, CanType origType, CanType resultType,
SILType loweredResultTy,
std::optional<AbstractionPattern> inputOrigType = std::nullopt,
bool isExplicit = false) {
assert(isBridgingKind(kind));
assert((kind != Subtype || isAllowedConversion(origType, resultType)) &&
"disallowed conversion for subtype relationship");
return Conversion(kind, origType, resultType, loweredResultTy, isExplicit);
if (inputOrigType)
return Conversion(kind, *inputOrigType, origType, resultType,
loweredResultTy, isExplicit);
return Conversion(kind, AbstractionPattern(origType), origType, resultType,
loweredResultTy, isExplicit);
}

static Conversion getSubtype(CanType origType, CanType substType,
Expand Down Expand Up @@ -290,6 +299,10 @@ class Conversion {
return Types.get<BridgingStorage>(Kind).IsExplicit;
}

AbstractionPattern getBridgingOriginalInputType() const {
return Types.get<BridgingStorage>(Kind).InputOrigType;
}

CanType getSourceType() const {
return SourceType;
}
Expand Down
11 changes: 7 additions & 4 deletions lib/SILGen/SILGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -799,7 +799,8 @@ static ActorIsolation getActorIsolationForFunction(SILFunction &fn) {
}

SILFunction *SILGenModule::getFunction(SILDeclRef constant,
ForDefinition_t forDefinition) {
ForDefinition_t forDefinition,
const clang::Type *foreignType) {
// If we already emitted the function, return it.
if (auto emitted = getEmittedFunction(constant, forDefinition))
return emitted;
Expand All @@ -819,9 +820,11 @@ SILFunction *SILGenModule::getFunction(SILDeclRef constant,
auto &IGM = *this;
auto *F = builder.getOrCreateFunction(
getBestLocation(constant), constant, forDefinition,
[&IGM](SILLocation loc, SILDeclRef constant) -> SILFunction * {
return IGM.getFunction(constant, NotForDefinition);
});
[&IGM, foreignType](SILLocation loc,
SILDeclRef constant) -> SILFunction * {
return IGM.getFunction(constant, NotForDefinition, foreignType);
},
ProfileCounter(), foreignType);

F->setDeclRef(constant);
F->setActorIsolation(getActorIsolationForFunction(*F));
Expand Down
7 changes: 4 additions & 3 deletions lib/SILGen/SILGen.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,8 @@ class LLVM_LIBRARY_VISIBILITY SILGenModule : public ASTVisitor<SILGenModule> {
ForDefinition_t forDefinition);

/// Get the function for a SILDeclRef, creating it if necessary.
SILFunction *getFunction(SILDeclRef constant,
ForDefinition_t forDefinition);
SILFunction *getFunction(SILDeclRef constant, ForDefinition_t forDefinition,
const clang::Type *foreignType = nullptr);

/// Get the dynamic dispatch thunk for a SILDeclRef.
SILFunction *getDynamicThunk(SILDeclRef constant,
Expand Down Expand Up @@ -348,7 +348,8 @@ class LLVM_LIBRARY_VISIBILITY SILGenModule : public ASTVisitor<SILGenModule> {
void emitForeignToNativeThunk(SILDeclRef thunk);

/// Emits a thunk from a Swift function to the native Swift convention.
void emitNativeToForeignThunk(SILDeclRef thunk);
void emitNativeToForeignThunk(SILDeclRef thunk,
const clang::Type *foreignType = nullptr);

/// Emits the distributed actor thunk for the decl if there is one associated
/// with it.
Expand Down
8 changes: 4 additions & 4 deletions lib/SILGen/SILGenApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4258,10 +4258,10 @@ class ArgEmitter {
loweredSubstArgType,
param.getSILStorageInterfaceType());
case SILFunctionLanguage::C:
return Conversion::getBridging(Conversion::BridgeToObjC,
arg.getSubstRValueType(),
origParamType.getType(),
param.getSILStorageInterfaceType());
return Conversion::getBridging(
Conversion::BridgeToObjC, arg.getSubstRValueType(),
origParamType.getType(), param.getSILStorageInterfaceType(),
origParamType);
}
llvm_unreachable("bad language");
}();
Expand Down
10 changes: 8 additions & 2 deletions lib/SILGen/SILGenBridging.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1315,8 +1315,9 @@ static SILValue emitObjCUnconsumedArgument(SILGenFunction &SGF,
SILLocation loc,
SILValue arg) {
auto &lowering = SGF.getTypeLowering(arg->getType());
// If address-only, make a +1 copy and operate on that.
if (lowering.isAddressOnly() && SGF.useLoweredAddresses()) {
// If arg is non-trivial and has an address type, make a +1 copy and operate
// on that.
if (!lowering.isTrivial() && arg->getType().isAddress()) {
auto tmp = SGF.emitTemporaryAllocation(loc, arg->getType().getObjectType());
SGF.B.createCopyAddr(loc, arg, tmp, IsNotTake, IsInitialization);
return tmp;
Expand Down Expand Up @@ -1453,6 +1454,11 @@ emitObjCThunkArguments(SILGenFunction &SGF, SILLocation loc, SILDeclRef thunk,
auto buf = SGF.emitTemporaryAllocation(loc, native.getType());
native.forwardInto(SGF, loc, buf);
native = SGF.emitManagedBufferWithCleanup(buf);
} else if (!fnConv.isSILIndirect(nativeInputs[i]) &&
native.getType().isAddress()) {
// Load the value if the argument has an address type and the native
// function expects the argument to be passed directly.
native = SGF.emitManagedLoadCopy(loc, native.getValue());
}

if (nativeInputs[i].isConsumedInCaller()) {
Expand Down
Loading