Skip to content

Also optimize calls to getContiguousArrayStorageType<SomeClass> to ContiguousArrayStorage<AnyObject> under the right deployment setting #41439

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
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
2 changes: 1 addition & 1 deletion include/swift/AST/KnownStdlibTypes.def
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ KNOWN_STDLIB_TYPE_DECL(String, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(StaticString, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(Substring, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(Array, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(_ContiguousArrayStorage, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(_ContiguousArrayStorage, ClassDecl, 1)
KNOWN_STDLIB_TYPE_DECL(Set, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(Sequence, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(Dictionary, NominalTypeDecl, 2)
Expand Down
30 changes: 15 additions & 15 deletions lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1572,7 +1572,9 @@ bool SILCombiner::optimizeIdentityCastComposition(ApplyInst *fInverseApply,
}

/// Should replace a call to `getContiguousArrayStorageType<A>(for:)` by the
/// metadata constructor.
/// metadata constructor of the return type.
/// getContiguousArrayStorageType<Int>(for:)
/// => metatype @thick ContiguousArrayStorage<Int>.Type
/// We know that `getContiguousArrayStorageType` will not return the AnyObject
/// type optimization for any non class or objc existential type instantiation.
static bool shouldReplaceCallByMetadataConstructor(CanType storageMetaTy) {
Expand All @@ -1588,20 +1590,17 @@ static bool shouldReplaceCallByMetadataConstructor(CanType storageMetaTy) {
if (!boundGenericTy)
return false;

for (auto TP : boundGenericTy->getGenericArgs()) {
auto ty = TP->getCanonicalType();
if (ty->getStructOrBoundGenericStruct() ||
ty->getEnumOrBoundGenericEnum() ||
isa<BuiltinVectorType>(ty) ||
isa<BuiltinIntegerType>(ty) ||
isa<BuiltinFloatType>(ty) ||
isa<TupleType>(ty) ||
isa<AnyFunctionType>(ty) ||
(ty->isAnyExistentialType() && !ty->isObjCExistentialType()))
return true;

auto genericArgs = boundGenericTy->getGenericArgs();
if (genericArgs.size() != 1)
return false;
}
auto ty = genericArgs[0]->getCanonicalType();
if (ty->getStructOrBoundGenericStruct() || ty->getEnumOrBoundGenericEnum() ||
isa<BuiltinVectorType>(ty) || isa<BuiltinIntegerType>(ty) ||
isa<BuiltinFloatType>(ty) || isa<TupleType>(ty) ||
isa<AnyFunctionType>(ty) ||
(ty->isAnyExistentialType() && !ty->isObjCExistentialType()))
return true;

return false;
}

Expand Down Expand Up @@ -1641,6 +1640,8 @@ SILInstruction *SILCombiner::visitApplyInst(ApplyInst *AI) {
if (SF->hasSemanticsAttr(semantics::ARRAY_GET_CONTIGUOUSARRAYSTORAGETYPE)) {
auto silTy = AI->getType();
auto storageTy = AI->getType().getASTType();

// getContiguousArrayStorageType<Int> => ContiguousArrayStorage<Int>
if (shouldReplaceCallByMetadataConstructor(storageTy)) {
auto metatype = Builder.createMetatype(AI->getLoc(), silTy);
AI->replaceAllUsesWith(metatype);
Expand All @@ -1650,7 +1651,6 @@ SILInstruction *SILCombiner::visitApplyInst(ApplyInst *AI) {
}
}


// (apply (thin_to_thick_function f)) to (apply f)
if (auto *TTTFI = dyn_cast<ThinToThickFunctionInst>(AI->getCallee())) {
// We currently don't remove any possible retain associated with the thick
Expand Down
66 changes: 65 additions & 1 deletion lib/SILOptimizer/SILCombiner/SILCombinerMiscVisitors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@
#define DEBUG_TYPE "sil-combine"

#include "SILCombiner.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/Basic/STLExtras.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/PatternMatch.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILVisitor.h"
Expand Down Expand Up @@ -2148,6 +2149,43 @@ SILInstruction *SILCombiner::visitFixLifetimeInst(FixLifetimeInst *fli) {
return nullptr;
}

static Optional<SILType>
shouldReplaceCallByContiguousArrayStorageAnyObject(SILFunction &F,
CanType storageMetaTy) {
auto metaTy = dyn_cast<MetatypeType>(storageMetaTy);
if (!metaTy || metaTy->getRepresentation() != MetatypeRepresentation::Thick)
return None;

auto storageTy = metaTy.getInstanceType()->getCanonicalType();
if (!storageTy->is_ContiguousArrayStorage())
return None;

auto boundGenericTy = dyn_cast<BoundGenericType>(storageTy);
if (!boundGenericTy)
return None;

// On SwiftStdlib 5.7 we can replace the call.
auto &ctxt = storageMetaTy->getASTContext();
auto deployment = AvailabilityContext::forDeploymentTarget(ctxt);
if (!deployment.isContainedIn(ctxt.getSwift57Availability()))
return None;

auto genericArgs = boundGenericTy->getGenericArgs();
if (genericArgs.size() != 1)
return None;

auto ty = genericArgs[0]->getCanonicalType();
if (!ty->getClassOrBoundGenericClass() && !ty->isObjCExistentialType())
return None;

auto anyObjectTy = ctxt.getAnyObjectType();
auto arrayStorageTy =
BoundGenericClassType::get(ctxt.get_ContiguousArrayStorageDecl(), nullptr,
{anyObjectTy})
->getCanonicalType();
return F.getTypeLowering(arrayStorageTy).getLoweredType();
}

SILInstruction *
SILCombiner::
visitAllocRefDynamicInst(AllocRefDynamicInst *ARDI) {
Expand Down Expand Up @@ -2209,6 +2247,32 @@ visitAllocRefDynamicInst(AllocRefDynamicInst *ARDI) {
ARDI->getTailAllocatedTypes(),
getCounts(ARDI));
}
} else if (auto *AI = dyn_cast<ApplyInst>(MDVal)) {
SILFunction *SF = AI->getReferencedFunctionOrNull();
if (!SF)
return nullptr;

if (!SF->hasSemanticsAttr(semantics::ARRAY_GET_CONTIGUOUSARRAYSTORAGETYPE))
return nullptr;

auto use = AI->getSingleUse();
if (!use || use->getUser() != ARDI)
return nullptr;

auto silTy = AI->getType();
auto storageTy = AI->getType().getASTType();
// getContiguousArrayStorageType<SomeClass> =>
// ContiguousArrayStorage<AnyObject>
auto instanceTy = shouldReplaceCallByContiguousArrayStorageAnyObject(
*AI->getFunction(), storageTy);
if (!instanceTy)
return nullptr;
NewInst = Builder.createAllocRef(
ARDI->getLoc(), *instanceTy, ARDI->isObjC(), false,
ARDI->getTailAllocatedTypes(), getCounts(ARDI));
NewInst = Builder.createUncheckedRefCast(ARDI->getLoc(), NewInst,
ARDI->getType());
return NewInst;
}
if (NewInst && NewInst->getType() != ARDI->getType()) {
// In case the argument was an upcast of the metatype, we have to upcast the
Expand Down
23 changes: 23 additions & 0 deletions test/SILOptimizer/array_metadata_optimization.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// RUN: %target-swift-frontend -target x86_64-apple-macosx99.99 -parse-as-library -O -module-name=test %s -emit-sil | %FileCheck %s
// RUN: %target-swift-frontend -target x86_64-apple-macosx12.3 -parse-as-library -O -module-name=test %s -emit-sil | %FileCheck %s --check-prefix=NOOPTCLASS

// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib
// REQUIRES: OS=macosx

// CHECK: sil @$s4test12makeArrayInt1xSaySiGSi_tF
// CHECK: alloc_ref [tail_elems $Int * {{.*}} : $Builtin.Word] $_ContiguousArrayStorage<Int>
// NOOPTCLASS: sil @$s4test12makeArrayInt1xSaySiGSi_tF
// NOOPTCLASS: alloc_ref [tail_elems $Int * {{.*}} : $Builtin.Word] $_ContiguousArrayStorage<Int>
public func makeArrayInt(x: Int) -> [Int] {
return [0, 1, x]
}

// CHECK: sil @$s4test14makeArrayClass1xSayAA1CCGAE_tF
// CHECK: alloc_ref [tail_elems $C * {{.*}} : $Builtin.Word] $_ContiguousArrayStorage<AnyObject>
// NOOPTCLASS: sil @$s4test14makeArrayClass1xSayAA1CCGAE_tF
// NOOPTCLASS: function_ref @$ss29getContiguousArrayStorageType3fors01
// NOOPTCLASS: alloc_ref_dynamic [tail_elems $C * {{.*}} : $Builtin.Word]
public class C {}
public func makeArrayClass(x: C) -> [C] {
return [x, x, x]
}
2 changes: 1 addition & 1 deletion test/SILOptimizer/stack_promotion_escaping.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ final public class Escaper {

// CHECK-LABEL: sil [noinline] @$s4test7EscaperC15badStuffHappensyyF : $@convention(method) (@guaranteed Escaper) -> () {
// CHECK: %2 = alloc_ref $Item
// CHECK: alloc_ref_dynamic [stack] [tail_elems $Item * %{{[0-9]+}} : $Builtin.Word]{{.*}} $_ContiguousArrayStorage<Item>
// CHECK: alloc_ref{{(_dynamic)?}} [stack] [tail_elems $Item * %{{[0-9]+}} : $Builtin.Word]{{.*}} $_ContiguousArrayStorage<{{(Item|AnyObject)}}>
// CHECK: return
@inline(never)
public func badStuffHappens() {
Expand Down
2 changes: 1 addition & 1 deletion test/SILOptimizer/static_arrays.swift
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ func takeUnsafePointer(ptr : UnsafePointer<SwiftClass>, len: Int) {
// CHECK-LABEL: sil @{{.*}}passArrayOfClasses
// CHECK: bb0(%0 : $SwiftClass, %1 : $SwiftClass, %2 : $SwiftClass):
// CHECK-NOT: bb1(
// CHECK: alloc_ref_dynamic {{.*}}[tail_elems $SwiftClass *
// CHECK: alloc_ref{{(_dynamic)?}} {{.*}}[tail_elems $SwiftClass *
// CHECK-NOT: bb1(
// CHECK: return
public func passArrayOfClasses(a: SwiftClass, b: SwiftClass, c: SwiftClass) {
Expand Down