Skip to content

embedded: Fix a few problems with vtable specialization #71579

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 3 commits into from
Feb 14, 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
8 changes: 8 additions & 0 deletions docs/SIL.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1608,6 +1608,7 @@ VTables

decl ::= sil-vtable
sil-vtable ::= 'sil_vtable' identifier '{' sil-vtable-entry* '}'
sil-vtable ::= 'sil_vtable' sil-type '{' sil-vtable-entry* '}'

sil-vtable-entry ::= sil-decl-ref ':' sil-linkage? sil-function-name

Expand Down Expand Up @@ -1670,6 +1671,13 @@ class (such as ``C.bas`` in ``C``'s vtable).
In case the SIL function is a thunk, the function name is preceded with the
linkage of the original implementing function.

If the vtable refers to a specialized class, a SIL type specifies the bound
generic class type::

sil_vtable $G<Int> {
// ...
}

Witness Tables
~~~~~~~~~~~~~~
::
Expand Down
1 change: 1 addition & 0 deletions include/swift/SIL/SILVTable.h
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ class SILVTable final : public SILAllocated<SILVTable>,
/// The ClassDecl mapped to this VTable.
ClassDecl *Class;

/// The class type if this is a specialized vtable, otherwise null.
SILType classType;

/// Whether or not this vtable is serialized, which allows
Expand Down
7 changes: 6 additions & 1 deletion lib/SIL/IR/SILPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3988,7 +3988,12 @@ void SILVTable::print(llvm::raw_ostream &OS, bool Verbose) const {
OS << "sil_vtable ";
if (isSerialized())
OS << "[serialized] ";
OS << getClass()->getName() << " {\n";
if (SILType classTy = getClassType()) {
OS << classTy;
} else {
OS << getClass()->getName();
}
OS << " {\n";

for (auto &entry : getEntries()) {
OS << " ";
Expand Down
52 changes: 32 additions & 20 deletions lib/SIL/Parser/ParseSIL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7452,27 +7452,39 @@ bool SILParserState::parseSILVTable(Parser &P) {
nullptr, nullptr, VTableState, M))
return true;

// Parse the class name.
Identifier Name;
SourceLoc Loc;
if (VTableState.parseSILIdentifier(Name, Loc,
diag::expected_sil_value_name))
return true;

// Find the class decl.
llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res =
lookupTopDecl(P, Name, /*typeLookup=*/true);
assert(Res.is<ValueDecl*>() && "Class look-up should return a Decl");
ValueDecl *VD = Res.get<ValueDecl*>();
if (!VD) {
P.diagnose(Loc, diag::sil_vtable_class_not_found, Name);
return true;
}
ClassDecl *theClass = nullptr;
SILType specializedClassTy;
if (P.Tok.isNot(tok::sil_dollar)) {
// Parse the class name.
Identifier Name;
SourceLoc Loc;
if (VTableState.parseSILIdentifier(Name, Loc,
diag::expected_sil_value_name))
return true;

auto *theClass = dyn_cast<ClassDecl>(VD);
if (!theClass) {
P.diagnose(Loc, diag::sil_vtable_class_not_found, Name);
return true;
// Find the class decl.
llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res =
lookupTopDecl(P, Name, /*typeLookup=*/true);
assert(Res.is<ValueDecl*>() && "Class look-up should return a Decl");
ValueDecl *VD = Res.get<ValueDecl*>();
if (!VD) {
P.diagnose(Loc, diag::sil_vtable_class_not_found, Name);
return true;
}

theClass = dyn_cast<ClassDecl>(VD);
if (!theClass) {
P.diagnose(Loc, diag::sil_vtable_class_not_found, Name);
return true;
}
} else {
if (SILParser(P).parseSILType(specializedClassTy))
return true;
theClass = specializedClassTy.getClassOrBoundGenericClass();
if (!theClass) {
return true;
}
}

SourceLoc LBraceLoc = P.Tok.getLoc();
Expand Down Expand Up @@ -7540,7 +7552,7 @@ bool SILParserState::parseSILVTable(Parser &P) {
P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
LBraceLoc);

SILVTable::create(M, theClass, Serialized, vtableEntries);
SILVTable::create(M, theClass, specializedClassTy, Serialized, vtableEntries);
return false;
}

Expand Down
27 changes: 26 additions & 1 deletion lib/SILOptimizer/Transforms/VTableSpecializer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ namespace {

class VTableSpecializer : public SILModuleTransform {
bool specializeVTables(SILModule &module);
bool specializeVTablesOfSuperclasses(SILModule &module);

/// The entry point to the transformation.
void run() override {
Expand Down Expand Up @@ -85,9 +86,11 @@ static bool specializeVTablesInFunction(SILFunction &func, SILModule &module,
bool VTableSpecializer::specializeVTables(SILModule &module) {
bool changed = false;
for (SILFunction &func : module) {
specializeVTablesInFunction(func, module, this);
changed |= specializeVTablesInFunction(func, module, this);
}

changed |= specializeVTablesOfSuperclasses(module);

for (SILVTable *vtable : module.getVTables()) {
if (vtable->getClass()->isGenericContext()) continue;

Expand All @@ -112,6 +115,28 @@ bool VTableSpecializer::specializeVTables(SILModule &module) {
return changed;
}

bool VTableSpecializer::specializeVTablesOfSuperclasses(SILModule &module) {
bool changed = false;
// The module's vtable table can grow while we are specializing superclass vtables.
for (unsigned i = 0; i < module.getVTables().size(); ++i) {
SILVTable *vtable = module.getVTables()[i];
if (vtable->getClass()->isGenericContext() && !vtable->getClassType())
continue;

SILType superClassTy;
if (SILType classTy = vtable->getClassType()) {
superClassTy = classTy.getSuperclass();
} else {
if (Type superTy = vtable->getClass()->getSuperclass())
superClassTy = SILType::getPrimitiveObjectType(superTy->getCanonicalType());
}
if (superClassTy) {
changed |= (specializeVTableForType(superClassTy, module, this) != nullptr);
}
}
return changed;
}

SILVTable *swift::specializeVTableForType(SILType classTy, SILModule &module,
SILTransform *transform) {
CanType astType = classTy.getASTType();
Expand Down
8 changes: 8 additions & 0 deletions stdlib/public/core/ManagedBuffer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,21 @@ open class ManagedBuffer<Header, Element> {
/// reading the `header` property during `ManagedBuffer.create` is undefined.
public final var header: Header

#if $Embedded
// In embedded mode this initializer has to be public, otherwise derived
// classes cannot be specialized.
public init(_doNotCallMe: ()) {
_internalInvariantFailure("Only initialize these by calling create")
}
#else
// This is really unfortunate. In Swift 5.0, the method descriptor for this
// initializer was public and subclasses would "inherit" it, referencing its
// method descriptor from their class override table.
@usableFromInline
internal init(_doNotCallMe: ()) {
_internalInvariantFailure("Only initialize these by calling create")
}
#endif

@inlinable
deinit {}
Expand Down
11 changes: 11 additions & 0 deletions test/SIL/Parser/basic.sil
Original file line number Diff line number Diff line change
Expand Up @@ -1807,3 +1807,14 @@ sil_vtable Foo2 {
#Foo.subscript!getter: @Foo_subscript_getter [inherited] [nonoverridden]
#Foo.subscript!setter: @Foo_subscript_setter [override]
}

class GenKlass<T> {}

// CHECK-LABEL: sil_vtable GenKlass {
sil_vtable GenKlass {
}

// CHECK-LABEL: sil_vtable $GenKlass<Int> {
sil_vtable $GenKlass<Int> {
}

2 changes: 1 addition & 1 deletion test/embedded/classes-generic-no-stdlib.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public func bar(t: T2) -> MyClass<T2> {
// CHECK-SIL: #MyClass.deinit!deallocator: @$s4main7MyClassCfDAA2T1V_Tg5 // specialized MyClass.__deallocating_deinit
// CHECK-SIL: }

// CHECK-SIL: sil_vtable MyClass {
// CHECK-SIL: sil_vtable $MyClass<T2> {
// CHECK-SIL: #MyClass.t!getter: <T> (MyClass<T>) -> () -> T : @$s4main7MyClassC1txvgAA2T2V_Tg5 // specialized MyClass.t.getter
// CHECK-SIL: #MyClass.t!setter: <T> (MyClass<T>) -> (T) -> () : @$s4main7MyClassC1txvsAA2T2V_Tg5 // specialized MyClass.t.setter
// CHECK-SIL: #MyClass.t!modify: <T> (MyClass<T>) -> () -> () : @$s4main7MyClassC1txvMAA2T2V_Tg5 // specialized MyClass.t.modify
Expand Down
15 changes: 15 additions & 0 deletions test/embedded/generic-classes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,31 @@ func makeItFoo<F: Fooable>(f: F) {
f.foo()
}

class BaseClass<A> {
func test() {}
}

class SubClass1<B>: BaseClass<Int> {
override func test() {}
}

class SubClass2 : SubClass1<Int> {
override func test() { print("SubClass2") }
}

@main
struct Main {
static func main() {
let f = GenericFooableClass<Int>()
makeItFoo(f: f)
let g: GenericFooableClass = GenericFooableSubClass<Int>()
makeItFoo(f: g)
let x = SubClass2()
x.test()
}
}

// CHECK: GenericFooableClass<T>.foo
// CHECK: GenericFooableSubClass<T>.foo
// CHECK: SubClass2

10 changes: 10 additions & 0 deletions test/embedded/managed-buffer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// RUN: %target-swift-emit-ir %s -module-name=main -enable-experimental-feature Embedded | %FileCheck %s

// REQUIRES: swift_in_compiler
// REQUIRES: OS=macosx || OS=linux-gnu

// CHECK: @"$s4main8MyBufferCN" = {{.*global.*}} <{ ptr @"$ss13ManagedBufferCySis5UInt8VGN", ptr @"$s4main8MyBufferCfD", ptr @"$s4main8MyBufferC12_doNotCallMeACyt_tcfC" }>
// CHECK: @"$ss13ManagedBufferCySis5UInt8VGN" = {{.*global.*}} <{ ptr null, ptr @"$ss13ManagedBufferCfDSi_s5UInt8VTg5", ptr @"$ss13ManagedBufferC12_doNotCallMeAByxq_Gyt_tcfCSi_s5UInt8VTg5" }>
final public class MyBuffer: ManagedBuffer<Int, UInt8> {
}