Skip to content

[WIP] Runtime: Put ObjC class wrapper unwrapping behind a runtime call. #12732

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
Nov 6, 2017
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
7 changes: 6 additions & 1 deletion include/swift/Runtime/Metadata.h
Original file line number Diff line number Diff line change
Expand Up @@ -2749,13 +2749,18 @@ swift_getBlockTypeMetadata3(const void *arg0,
SWIFT_RUNTIME_EXPORT
void
swift_instantiateObjCClass(const ClassMetadata *theClass);
#endif

/// \brief Fetch a uniqued type metadata for an ObjC class.
SWIFT_RUNTIME_EXPORT
const Metadata *
swift_getObjCClassMetadata(const ClassMetadata *theClass);

/// \brief Get the ObjC class object from class type metadata.
SWIFT_RUNTIME_EXPORT
const ClassMetadata *
swift_getObjCClassFromMetadata(const Metadata *theClass);
#endif

/// \brief Fetch a unique type metadata object for a foreign type.
SWIFT_RUNTIME_EXPORT
const ForeignTypeMetadata *
Expand Down
6 changes: 6 additions & 0 deletions include/swift/Runtime/RuntimeFunctions.def
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,12 @@ FUNCTION(GetObjCClassMetadata, swift_getObjCClassMetadata, DefaultCC,
ARGS(ObjCClassPtrTy),
ATTRS(NoUnwind, ReadNone))

// Metadata *swift_getObjCClassFromMetadata(objc_class *theClass);
FUNCTION(GetObjCClassFromMetadata, swift_getObjCClassFromMetadata, DefaultCC,
RETURNS(ObjCClassPtrTy),
ARGS(TypeMetadataPtrTy),
ATTRS(NoUnwind, ReadNone))

// Metadata *swift_getTupleTypeMetadata(size_t numElements,
// Metadata * const *elts,
// const char *labels,
Expand Down
51 changes: 11 additions & 40 deletions lib/IRGen/GenMeta.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ static llvm::Constant *getMangledTypeName(IRGenModule &IGM, CanType type,

llvm::Value *irgen::emitObjCMetadataRefForMetadata(IRGenFunction &IGF,
llvm::Value *classPtr) {
assert(IGF.IGM.Context.LangOpts.EnableObjCInterop);
classPtr = IGF.Builder.CreateBitCast(classPtr, IGF.IGM.ObjCClassPtrTy);

// Fetch the metadata for that class.
Expand Down Expand Up @@ -4215,46 +4216,16 @@ llvm::Value *irgen::emitClassHeapMetadataRefForMetatype(IRGenFunction &IGF,
if (hasKnownSwiftMetadata(IGF.IGM, type))
return metatype;

// Otherwise, we inline a little operation here.

// Load the metatype kind.
auto metatypeKindAddr =
Address(IGF.Builder.CreateStructGEP(/*Ty=*/nullptr, metatype, 0),
IGF.IGM.getPointerAlignment());
auto metatypeKind =
IGF.Builder.CreateLoad(metatypeKindAddr, metatype->getName() + ".kind");

// Compare it with the class wrapper kind.
auto classWrapperKind =
llvm::ConstantInt::get(IGF.IGM.MetadataKindTy,
unsigned(MetadataKind::ObjCClassWrapper));
auto isObjCClassWrapper =
IGF.Builder.CreateICmpEQ(metatypeKind, classWrapperKind,
"isObjCClassWrapper");

// Branch based on that.
llvm::BasicBlock *contBB = IGF.createBasicBlock("metadataForClass.cont");
llvm::BasicBlock *wrapBB = IGF.createBasicBlock("isWrapper");
IGF.Builder.CreateCondBr(isObjCClassWrapper, wrapBB, contBB);
llvm::BasicBlock *origBB = IGF.Builder.GetInsertBlock();

// If it's a wrapper, load from the 'Class' field, which is at index 1.
// TODO: if we guaranteed that this load couldn't crash, we could use
// a select here instead, which might be profitable.
IGF.Builder.emitBlock(wrapBB);
auto classFromWrapper =
emitInvariantLoadFromMetadataAtIndex(IGF, metatype, 1,
IGF.IGM.TypeMetadataPtrTy);
IGF.Builder.CreateBr(contBB);

// Continuation block.
IGF.Builder.emitBlock(contBB);
auto phi = IGF.Builder.CreatePHI(IGF.IGM.TypeMetadataPtrTy, 2,
metatype->getName() + ".class");
phi->addIncoming(metatype, origBB);
phi->addIncoming(classFromWrapper, wrapBB);

return phi;
// Otherwise, we may have to unwrap an ObjC class wrapper.
assert(IGF.IGM.Context.LangOpts.EnableObjCInterop);
metatype = IGF.Builder.CreateBitCast(metatype, IGF.IGM.TypeMetadataPtrTy);

// Fetch the metadata for that class.
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetObjCClassFromMetadataFn(),
metatype);
call->setDoesNotThrow();
call->setDoesNotAccessMemory();
return call;
}

/// Load the correct virtual function for the given class method.
Expand Down
2 changes: 1 addition & 1 deletion stdlib/public/runtime/Casting.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3196,7 +3196,7 @@ SWIFT_CC(swift)
const Metadata *swift::_swift_class_getSuperclass(const Metadata *theClass) {
if (const ClassMetadata *classType = theClass->getClassObject())
if (classHasSuperclass(classType))
return swift_getObjCClassMetadata(classType->SuperClass);
return getMetadataForClass(classType->SuperClass);
return nullptr;
}

Expand Down
22 changes: 15 additions & 7 deletions stdlib/public/runtime/Metadata.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,6 @@ namespace {
/// The uniquing structure for ObjC class-wrapper metadata.
static SimpleGlobalCache<ObjCClassCacheEntry> ObjCClassWrappers;

#endif

const Metadata *
swift::swift_getObjCClassMetadata(const ClassMetadata *theClass) {
// Make calls resilient against receiving a null Objective-C class. This can
Expand All @@ -295,14 +293,24 @@ swift::swift_getObjCClassMetadata(const ClassMetadata *theClass) {
return theClass;
}

#if SWIFT_OBJC_INTEROP
return &ObjCClassWrappers.getOrInsert(theClass).first->Data;
#else
fatalError(/* flags = */ 0,
"swift_getObjCClassMetadata: no Objective-C interop");
#endif
}

const ClassMetadata *
swift::swift_getObjCClassFromMetadata(const Metadata *theMetadata) {
// Unwrap ObjC class wrappers.
if (auto wrapper = dyn_cast<ObjCClassWrapperMetadata>(theMetadata)) {
return wrapper->Class;
}

// Otherwise, the input should already be a Swift class object.
auto theClass = cast<ClassMetadata>(theMetadata);
assert(theClass->isTypeMetadata() && !theClass->isArtificialSubclass());
return theClass;
}

#endif

/***************************************************************************/
/*** Functions *************************************************************/
/***************************************************************************/
Expand Down
5 changes: 3 additions & 2 deletions stdlib/public/runtime/MetadataLookup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,9 @@ const Metadata *TypeMetadataRecord::getCanonicalTypeMetadata() const {
}
case TypeMetadataRecordKind::UniqueDirectClass:
if (auto *ClassMetadata =
static_cast<const ::ClassMetadata *>(getDirectType()))
return swift_getObjCClassMetadata(ClassMetadata);
static_cast<const ::ClassMetadata *>(getDirectType())) {
return getMetadataForClass(ClassMetadata);
}
else
return nullptr;
default:
Expand Down
8 changes: 8 additions & 0 deletions stdlib/public/runtime/Private.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,14 @@ namespace swift {
void (*function)(void *));
#endif

static inline const Metadata *getMetadataForClass(const ClassMetadata *c) {
#if SWIFT_OBJC_INTEROP
return swift_getObjCClassMetadata(c);
#else
return c;
#endif
}

} // end namespace swift

#endif /* SWIFT_RUNTIME_PRIVATE_H */
8 changes: 4 additions & 4 deletions stdlib/public/runtime/ProtocolConformance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,14 +108,14 @@ const Metadata *ProtocolConformanceRecord::getCanonicalTypeMetadata() const {
// metadata. The class additionally may be weak-linked, so we have to check
// for null.
if (auto *ClassMetadata = *getIndirectClass())
return swift_getObjCClassMetadata(ClassMetadata);
return getMetadataForClass(ClassMetadata);
return nullptr;

case TypeMetadataRecordKind::UniqueDirectClass:
// The class may be ObjC, in which case we need to instantiate its Swift
// metadata.
if (auto *ClassMetadata = getDirectClass())
return swift_getObjCClassMetadata(ClassMetadata);
return getMetadataForClass(ClassMetadata);
return nullptr;

case TypeMetadataRecordKind::UniqueNominalTypeDescriptor:
Expand Down Expand Up @@ -394,7 +394,7 @@ searchInConformanceCache(const Metadata *type,
// If the type is a class, try its superclass.
if (const ClassMetadata *classType = type->getClassObject()) {
if (classHasSuperclass(classType)) {
type = swift_getObjCClassMetadata(classType->SuperClass);
type = getMetadataForClass(classType->SuperClass);
goto recur;
}
}
Expand Down Expand Up @@ -433,7 +433,7 @@ bool isRelatedType(const Metadata *type, const void *candidate,
// If the type is a class, try its superclass.
if (const ClassMetadata *classType = type->getClassObject()) {
if (classHasSuperclass(classType)) {
type = swift_getObjCClassMetadata(classType->SuperClass);
type = getMetadataForClass(classType->SuperClass);
continue;
}
}
Expand Down
2 changes: 1 addition & 1 deletion stdlib/public/runtime/Reflection.mm
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ void swift_MagicMirrorData_summary(const Metadata *T, String *result) {
const Metadata *type) {
void *object = *reinterpret_cast<void * const *>(value);
auto isa = _swift_getClass(object);
return swift_getObjCClassMetadata(isa);
return getMetadataForClass(isa);
}

static std::tuple<const Metadata *, const OpaqueValue *>
Expand Down
12 changes: 6 additions & 6 deletions stdlib/public/runtime/SwiftObject.mm
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,7 @@ static Class _swift_getObjCClassOfAllocated(const void *object) {
const Metadata *swift::swift_getObjectType(HeapObject *object) {
auto classAsMetadata = _swift_getClass(object);

#if !SWIFT_OBJC_INTEROP
assert(classAsMetadata &&
classAsMetadata->isTypeMetadata() &&
!classAsMetadata->isArtificialSubclass());
return classAsMetadata;
#else
#if SWIFT_OBJC_INTEROP
// Walk up the superclass chain skipping over artifical Swift classes.
// If we find a non-Swift class use the result of [object class] instead.

Expand All @@ -129,6 +124,11 @@ static Class _swift_getObjCClassOfAllocated(const void *object) {
}
classAsMetadata = reinterpret_cast<const ClassMetadata *>(objcClass);
return swift_getObjCClassMetadata(classAsMetadata);
#else
assert(classAsMetadata &&
classAsMetadata->isTypeMetadata() &&
!classAsMetadata->isArtificialSubclass());
return classAsMetadata;
#endif
}

Expand Down
2 changes: 1 addition & 1 deletion test/ClangImporter/objc_ir.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func propertyAccess(b b: B) {
b.counter = b.counter + 1

// CHECK: call %swift.type* @_T0So1BCMa()
// CHECK: bitcast %swift.type* {{%.+}} to %objc_class*
// CHECK: call %objc_class* @swift_getObjCClassFromMetadata
// CHECK: load i8*, i8** @"\01L_selector(sharedCounter)"
// CHECK: load i8*, i8** @"\01L_selector(setSharedCounter:)"
B.sharedCounter = B.sharedCounter + 1
Expand Down
5 changes: 2 additions & 3 deletions test/IRGen/abitypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,8 @@ class Foo {

// x86_64-macosx: define hidden i8* @_T08abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}FTo(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]]* @_T08abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}F
// x86_64-macosx: [[T0:%.*]] = phi [[TYPE]]* [ [[VALUE]],
// x86_64-macosx: [[T1:%.*]] = bitcast [[TYPE]]* [[T0]] to [[OBJC:%objc_class]]*
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[OBJC]]* [[T1]] to i8*
// x86_64-macosx: [[T0:%.*]] = call [[OBJC:%objc_class]]* @swift_getObjCClassFromMetadata([[TYPE]]* [[VALUE]])
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[OBJC]]* [[T0]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyClass(_ a: AnyClass) -> AnyClass {
return a
Expand Down
12 changes: 2 additions & 10 deletions test/IRGen/metatype.sil
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ bb0(%0 : $@thick X.Type):
// CHECK-LABEL: define{{( protected)?}} swiftcc %objc_class* @foreign_thick_to_objc(%swift.type*)
sil @foreign_thick_to_objc : $@convention(thin) (@thick Gizmo.Type) -> @objc_metatype Gizmo.Type {
bb0(%0 : $@thick Gizmo.Type):
// CHECK: [[KIND_GEP:%[0-9A-Za-z_.]+]] = getelementptr inbounds %swift.type, %swift.type* %0, i32 0, i32 0
// CHECK-NEXT: [[KIND:%[0-9A-Za-z_.]+]] = load i64, i64* [[KIND_GEP]], align 8
// CHECK-NEXT: [[IS_WRAPPER:%[0-9A-Za-z_.]+]] = icmp eq i64 [[KIND]], 14
// CHECK-NEXT: br i1
// CHECK: call %objc_class* @swift_getObjCClassFromMetadata
%1 = thick_to_objc_metatype %0 : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type
// CHECK: ret %objc_class*
return %1 : $@objc_metatype Gizmo.Type
Expand All @@ -61,12 +58,7 @@ bb0(%0 : $@objc_metatype Gizmo.Type):
protocol CP: class {}

// CHECK-LABEL: define{{( protected)?}} swiftcc %objc_class* @archetype_objc_metatype(%swift.type* %T, i8** %T.CP)
// CHECK: [[IS_OBJC_WRAPPER:%.*]] = icmp eq i64 {{%.*}}, 14
// CHECK: br i1 [[IS_OBJC_WRAPPER]], label %isWrapper, label %metadataForClass.cont
// CHECK: isWrapper:
// CHECK: [[WRAPPED_CLASS:%.*]] = load %swift.type*, %swift.type**
// CHECK: metadataForClass.cont:
// CHECK: phi %swift.type* [ %T, %entry ], [ [[WRAPPED_CLASS]], %isWrapper ]
// CHECK: call %objc_class* @swift_getObjCClassFromMetadata
sil @archetype_objc_metatype : $@convention(thin) <T: CP> () -> @objc_metatype T.Type {
entry:
%m = metatype $@objc_metatype T.Type
Expand Down