Skip to content

C++ Interop: import call operators #36075

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 3, 2021
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
41 changes: 28 additions & 13 deletions include/swift/SIL/AbstractionPattern.h
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,12 @@ class AbstractionPattern {
case Kind::CFunctionAsMethodType:
case Kind::CurriedCFunctionAsMethodType:
case Kind::PartialCurriedCFunctionAsMethodType:
case Kind::CXXMethodType:
case Kind::CurriedCXXMethodType:
case Kind::PartialCurriedCXXMethodType:
case Kind::CXXOperatorMethodType:
case Kind::CurriedCXXOperatorMethodType:
case Kind::PartialCurriedCXXOperatorMethodType:
return true;

default:
Expand Down Expand Up @@ -552,9 +558,11 @@ class AbstractionPattern {
}

void initCXXMethod(CanGenericSignature signature, CanType origType,
const clang::CXXMethodDecl *method, Kind kind) {
const clang::CXXMethodDecl *method, Kind kind,
ImportAsMemberStatus memberStatus) {
initSwiftType(signature, origType, kind);
CXXMethod = method;
OtherData = memberStatus.getRawValue();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like it basically mimics the logic for CFunctionAsMethodType.

}

AbstractionPattern() {}
Expand Down Expand Up @@ -715,19 +723,22 @@ class AbstractionPattern {
/// then the uncurried type is:
/// ((RefrigeratorCompartment, Temperature), Refrigerator) -> ()
static AbstractionPattern getCXXMethod(CanType origType,
const clang::CXXMethodDecl *method) {
const clang::CXXMethodDecl *method,
ImportAsMemberStatus memberStatus) {
assert(isa<AnyFunctionType>(origType));
AbstractionPattern pattern;
pattern.initCXXMethod(nullptr, origType, method, Kind::CXXMethodType);
pattern.initCXXMethod(nullptr, origType, method,
Kind::CXXMethodType, memberStatus);
return pattern;
}

static AbstractionPattern
getCXXOperatorMethod(CanType origType, const clang::CXXMethodDecl *method) {
getCXXOperatorMethod(CanType origType, const clang::CXXMethodDecl *method,
ImportAsMemberStatus memberStatus) {
assert(isa<AnyFunctionType>(origType));
AbstractionPattern pattern;
pattern.initCXXMethod(nullptr, origType, method,
Kind::CXXOperatorMethodType);
Kind::CXXOperatorMethodType, memberStatus);
return pattern;
}

Expand All @@ -739,21 +750,23 @@ class AbstractionPattern {
/// then the curried type:
/// (Refrigerator) -> (Compartment, Temperature) -> ()
static AbstractionPattern
getCurriedCXXMethod(CanType origType, const clang::CXXMethodDecl *method) {
getCurriedCXXMethod(CanType origType, const clang::CXXMethodDecl *method,
ImportAsMemberStatus memberStatus) {
assert(isa<AnyFunctionType>(origType));
AbstractionPattern pattern;
pattern.initCXXMethod(nullptr, origType, method,
Kind::CurriedCXXMethodType);
Kind::CurriedCXXMethodType, memberStatus);
return pattern;
}

static AbstractionPattern
getCurriedCXXOperatorMethod(CanType origType,
const clang::CXXMethodDecl *method) {
const clang::CXXMethodDecl *method,
ImportAsMemberStatus memberStatus) {
assert(isa<AnyFunctionType>(origType));
AbstractionPattern pattern;
pattern.initCXXMethod(nullptr, origType, method,
Kind::CurriedCXXOperatorMethodType);
Kind::CurriedCXXOperatorMethodType, memberStatus);
return pattern;
}

Expand Down Expand Up @@ -855,22 +868,24 @@ class AbstractionPattern {
/// (Compartment, Temperature) -> ()
static AbstractionPattern
getPartialCurriedCXXMethod(CanGenericSignature signature, CanType origType,
const clang::CXXMethodDecl *method) {
const clang::CXXMethodDecl *method,
ImportAsMemberStatus memberStatus) {
assert(isa<AnyFunctionType>(origType));
AbstractionPattern pattern;
pattern.initCXXMethod(signature, origType, method,
Kind::PartialCurriedCXXMethodType);
Kind::PartialCurriedCXXMethodType, memberStatus);
return pattern;
}

static AbstractionPattern
getPartialCurriedCXXOperatorMethod(CanGenericSignature signature,
CanType origType,
const clang::CXXMethodDecl *method) {
const clang::CXXMethodDecl *method,
ImportAsMemberStatus memberStatus) {
assert(isa<AnyFunctionType>(origType));
AbstractionPattern pattern;
pattern.initCXXMethod(signature, origType, method,
Kind::PartialCurriedCXXOperatorMethodType);
Kind::PartialCurriedCXXOperatorMethodType, memberStatus);
return pattern;
}

Expand Down
15 changes: 13 additions & 2 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4045,8 +4045,9 @@ namespace {
// functions get imported into Swift as static member functions
// that use an additional parameter for the left-hand side operand
// instead of the receiver object.
mdecl->getDeclName().getNameKind() ==
clang::DeclarationName::CXXOperatorName) {
(mdecl->getDeclName().getNameKind() ==
clang::DeclarationName::CXXOperatorName &&
isImportedAsStatic(mdecl->getOverloadedOperator()))) {
selfIdx = None;
} else {
selfIdx = 0;
Expand Down Expand Up @@ -7927,6 +7928,16 @@ bool importer::isSpecialUIKitStructZeroProperty(const clang::NamedDecl *decl) {
return ident->isStr("UIEdgeInsetsZero") || ident->isStr("UIOffsetZero");
}

bool importer::isImportedAsStatic(const clang::OverloadedOperatorKind op) {
switch (op) {
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
case clang::OO_##Name: return !MemberOnly;
#include "clang/Basic/OperatorKinds.def"
default:
llvm_unreachable("not an operator");
}
}

Type ClangImporter::Implementation::getMainActorType() {
if (MainActorType)
return *MainActorType;
Expand Down
36 changes: 21 additions & 15 deletions lib/ClangImporter/ImportName.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1757,6 +1757,13 @@ ImportedName NameImporter::importNameImpl(const clang::NamedDecl *D,

case clang::DeclarationName::CXXOperatorName: {
auto op = D->getDeclName().getCXXOverloadedOperator();
auto functionDecl = dyn_cast<clang::FunctionDecl>(D);
if (!functionDecl) {
// This can happen for example for templated operators functions.
// We don't support those, yet.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this comment is still true. We can import templated operators.

If you wanted to make a patch to support templated operators, that would also be super helpful. Probably a nfc.

Additionally, I'm not sure we still need the check for !FD, but better safe than sorry, so I'd probably leave it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't really looked yet into how this behaves for templated operators. I'll try & if it works, I'll remove this comment in a separate PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even better. Thank you!

return ImportedName();
}

switch (op) {
case clang::OverloadedOperatorKind::OO_Plus:
case clang::OverloadedOperatorKind::OO_Minus:
Expand All @@ -1775,21 +1782,20 @@ ImportedName NameImporter::importNameImpl(const clang::NamedDecl *D,
case clang::OverloadedOperatorKind::OO_GreaterEqual:
case clang::OverloadedOperatorKind::OO_AmpAmp:
case clang::OverloadedOperatorKind::OO_PipePipe:
if (auto FD = dyn_cast<clang::FunctionDecl>(D)) {
baseName = clang::getOperatorSpelling(op);
isFunction = true;
argumentNames.resize(
FD->param_size() +
// C++ operators that are implemented as non-static member functions
// get imported into Swift as static member functions that use an
// additional parameter for the left-hand side operand instead of
// the receiver object.
(isa<clang::CXXMethodDecl>(D) ? 1 : 0));
} else {
// This can happen for example for templated operators functions.
// We don't support those, yet.
return ImportedName();
}
baseName = clang::getOperatorSpelling(op);
isFunction = true;
argumentNames.resize(
functionDecl->param_size() +
// C++ operators that are implemented as non-static member functions
// get imported into Swift as static member functions that use an
// additional parameter for the left-hand side operand instead of
// the receiver object.
(isa<clang::CXXMethodDecl>(D) ? 1 : 0));
break;
case clang::OverloadedOperatorKind::OO_Call:
baseName = "callAsFunction";
isFunction = true;
addEmptyArgNamesForClangFunction(functionDecl, argumentNames);
break;
default:
// We don't import these yet.
Expand Down
2 changes: 1 addition & 1 deletion lib/ClangImporter/ImportType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1815,7 +1815,7 @@ ParameterList *ClangImporter::Implementation::importFunctionParameterList(
// imported into Swift as static methods that have an additional
// parameter for the left-hand side operand instead of the receiver object.
if (auto CMD = dyn_cast<clang::CXXMethodDecl>(clangDecl)) {
if (clangDecl->isOverloadedOperator()) {
if (clangDecl->isOverloadedOperator() && isImportedAsStatic(clangDecl->getOverloadedOperator())) {
auto param = new (SwiftContext)
ParamDecl(SourceLoc(), SourceLoc(), Identifier(), SourceLoc(),
SwiftContext.getIdentifier("lhs"), dc);
Expand Down
4 changes: 4 additions & 0 deletions lib/ClangImporter/ImporterImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,10 @@ bool shouldSuppressDeclImport(const clang::Decl *decl);
/// but are now renamed using the swift_name attribute.
bool isSpecialUIKitStructZeroProperty(const clang::NamedDecl *decl);

/// \returns true if this operator should be made a static function
/// even if imported as a non-static member function.
bool isImportedAsStatic(clang::OverloadedOperatorKind op);

/// Add command-line arguments for a normal import of Clang code.
void getNormalInvocationArguments(std::vector<std::string> &invocationArgStrs,
ASTContext &ctx);
Expand Down
28 changes: 19 additions & 9 deletions lib/SIL/IR/AbstractionPattern.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,13 @@ AbstractionPattern
AbstractionPattern::getCurriedCXXMethod(CanType origType,
const AbstractFunctionDecl *function) {
auto clangMethod = cast<clang::CXXMethodDecl>(function->getClangDecl());
return getCurriedCXXMethod(origType, clangMethod);
return getCurriedCXXMethod(origType, clangMethod, function->getImportAsMemberStatus());
}

AbstractionPattern AbstractionPattern::getCurriedCXXOperatorMethod(
CanType origType, const AbstractFunctionDecl *function) {
auto clangMethod = cast<clang::CXXMethodDecl>(function->getClangDecl());
return getCurriedCXXOperatorMethod(origType, clangMethod);
return getCurriedCXXOperatorMethod(origType, clangMethod, function->getImportAsMemberStatus());
}

AbstractionPattern
Expand Down Expand Up @@ -529,11 +529,12 @@ AbstractionPattern AbstractionPattern::getFunctionResultType() const {
getImportAsMemberStatus());
case Kind::CurriedCXXMethodType:
return getPartialCurriedCXXMethod(getGenericSignatureForFunctionComponent(),
getResultType(getType()), getCXXMethod());
getResultType(getType()), getCXXMethod(),
getImportAsMemberStatus());
case Kind::CurriedCXXOperatorMethodType:
return getPartialCurriedCXXOperatorMethod(
getGenericSignatureForFunctionComponent(), getResultType(getType()),
getCXXMethod());
getCXXMethod(), getImportAsMemberStatus());
case Kind::PartialCurriedObjCMethodType:
case Kind::ObjCMethodType: {
// If this is a foreign async function, the result type comes from the
Expand Down Expand Up @@ -753,10 +754,19 @@ AbstractionPattern::getFunctionParamType(unsigned index) const {
auto params = cast<AnyFunctionType>(getType()).getParams();
auto paramType = params[index].getParameterType();

// The first parameter holds the left-hand-side operand, which gets passed
// to the C++ function as the this pointer.
if (index == 0)
return getCXXMethodSelfPattern(paramType);
// See importer::isImportedAsStatic
bool isStatic = getImportAsMemberStatus().isStatic();
if (isStatic) {
// The first parameter holds the left-hand-side operand, which gets passed
// to the C++ function as the this pointer.
if (index == 0)
return getCXXMethodSelfPattern(paramType);
} else {
// The last parameter is 'self'.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic might need to change once #34993 lands, but nothing you need to do.

if (getKind() == Kind::CXXOperatorMethodType &&
index == params.size() - 1)
return getCXXMethodSelfPattern(params.back().getParameterType());
}

// A parameter of type () does not correspond to a Clang parameter.
if (paramType->isVoid())
Expand All @@ -766,7 +776,7 @@ AbstractionPattern::getFunctionParamType(unsigned index) const {
auto methodType = getCXXMethod()->getType().getTypePtr();
return AbstractionPattern(
getGenericSignatureForFunctionComponent(), paramType,
getClangFunctionParameterType(methodType, index - 1));
getClangFunctionParameterType(methodType, index - (isStatic ? 1 : 0)));
}
case Kind::CurriedObjCMethodType: {
auto params = cast<AnyFunctionType>(getType()).getParams();
Expand Down
4 changes: 2 additions & 2 deletions lib/SIL/IR/SILFunctionType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2903,8 +2903,8 @@ static CanSILFunctionType getSILFunctionTypeForClangDecl(

if (auto method = dyn_cast<clang::CXXMethodDecl>(clangDecl)) {
AbstractionPattern origPattern = method->isOverloadedOperator() ?
AbstractionPattern::getCXXOperatorMethod(origType, method):
AbstractionPattern::getCXXMethod(origType, method);
AbstractionPattern::getCXXOperatorMethod(origType, method, foreignInfo.Self):
AbstractionPattern::getCXXMethod(origType, method, foreignInfo.Self);
auto conventions = CXXMethodConventions(method);
return getSILFunctionType(TC, TypeExpansionContext::minimal(), origPattern,
substInterfaceType, extInfoBuilder, conventions,
Expand Down
27 changes: 27 additions & 0 deletions test/Interop/Cxx/operators/Inputs/member-inline.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,33 @@ struct LoadableIntWrapper {
LoadableIntWrapper operator-(LoadableIntWrapper rhs) {
return LoadableIntWrapper{.value = value - rhs.value};
}

int operator()() {
return value;
}
int operator()(int x) {
return value + x;
}
int operator()(int x, int y) {
return value + x * y;
}
};

struct AddressOnlyIntWrapper {
int value;

AddressOnlyIntWrapper(int value) : value(value) {}
AddressOnlyIntWrapper(const AddressOnlyIntWrapper &other) : value(other.value) {}

int operator()() {
return value;
}
int operator()(int x) {
return value + x;
}
int operator()(int x, int y) {
return value + x * y;
}
};

struct HasDeletedOperator {
Expand Down
24 changes: 24 additions & 0 deletions test/Interop/Cxx/operators/Inputs/member-out-of-line.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,27 @@
LoadableIntWrapper LoadableIntWrapper::operator+(LoadableIntWrapper rhs) const {
return LoadableIntWrapper{.value = value + rhs.value};
}

int LoadableIntWrapper::operator()() const {
return value;
}

int LoadableIntWrapper::operator()(int x) const {
return value + x;
}

int LoadableIntWrapper::operator()(int x, int y) const {
return value + x * y;
}

int AddressOnlyIntWrapper::operator()() const {
return value;
}

int AddressOnlyIntWrapper::operator()(int x) const {
return value + x;
}

int AddressOnlyIntWrapper::operator()(int x, int y) const {
return value + x * y;
}
14 changes: 14 additions & 0 deletions test/Interop/Cxx/operators/Inputs/member-out-of-line.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@
struct LoadableIntWrapper {
int value;
LoadableIntWrapper operator+(LoadableIntWrapper rhs) const;
int operator()() const;
int operator()(int x) const;
int operator()(int x, int y) const;
};

struct AddressOnlyIntWrapper {
int value;

AddressOnlyIntWrapper(int value) : value(value) {}
AddressOnlyIntWrapper(const AddressOnlyIntWrapper &other) : value(other.value) {}

int operator()() const;
int operator()(int x) const;
int operator()(int x, int y) const;
};

#endif
10 changes: 10 additions & 0 deletions test/Interop/Cxx/operators/member-inline-irgen.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,13 @@ public func sub(_ lhs: inout LoadableIntWrapper, _ rhs: LoadableIntWrapper) -> L

// CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN18LoadableIntWrappermiES_|"\?\?GLoadableIntWrapper@@QEAA\?AU0@U0@@Z")]](%struct.LoadableIntWrapper* {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} {{%[0-9]+}})
// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.LoadableIntWrapper* nonnull dereferenceable(4) {{.*}}, {{i32 %rhs.coerce|\[1 x i32\] %rhs.coerce|i64 %rhs.coerce|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4 %rhs}})

public func call(_ wrapper: inout LoadableIntWrapper, _ arg: Int32) -> Int32 { wrapper(arg) }

// CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN18LoadableIntWrapperclEi|"\?\?GLoadableIntWrapper@@QEAAHH@Z")]](%struct.LoadableIntWrapper* {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} {{%[0-9]+}})
// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.LoadableIntWrapper* nonnull dereferenceable(4) {{.*}}, {{i32 %x|\[1 x i32\] %x|i64 %x|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\) align 4 %rhs}})

public func call(_ wrapper: inout AddressOnlyIntWrapper) -> Int32 { wrapper() }

// CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN21AddressOnlyIntWrapperclEv|"\?\?GAddressOnlyIntWrapper@@QEAAHXZ")]](%struct.AddressOnlyIntWrapper* {{%[0-9]+}})
// CHECK: define linkonce_odr [[RES]] [[NAME]](%struct.AddressOnlyIntWrapper* nonnull dereferenceable(4) {{.*}})
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

// CHECK: struct LoadableIntWrapper {
// CHECK: static func - (lhs: inout LoadableIntWrapper, rhs: LoadableIntWrapper) -> LoadableIntWrapper
// CHECK: mutating func callAsFunction() -> Int32
// CHECK: mutating func callAsFunction(_ x: Int32) -> Int32
// CHECK: mutating func callAsFunction(_ x: Int32, _ y: Int32) -> Int32
// CHECK: }

// CHECK: struct AddressOnlyIntWrapper {
// CHECK: mutating func callAsFunction() -> Int32
// CHECK: mutating func callAsFunction(_ x: Int32) -> Int32
// CHECK: mutating func callAsFunction(_ x: Int32, _ y: Int32) -> Int32
// CHECK: }

// CHECK: struct HasDeletedOperator {
Expand Down
Loading