Skip to content

[6.0 cherry-pick] [embedded] Compile-time (literal) KeyPaths for Embedded Swift #72562

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 5 commits into from
Mar 26, 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
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ swift_compiler_sources(Optimizer
SimplifyDestructure.swift
SimplifyGlobalValue.swift
SimplifyInitEnumDataAddr.swift
SimplifyKeyPath.swift
SimplifyLoad.swift
SimplifyPartialApply.swift
SimplifyPointerToAddress.swift
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ extension ApplyInst : OnoneSimplifyable {
if tryTransformThickToThinCallee(of: self, context) {
return
}
if context.tryOptimizeKeypath(apply: self) {
context.erase(instruction: self)
return
}
_ = context.tryDevirtualize(apply: self, isMandatory: false)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//===--- SimplifyKeyPath.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import SIL

extension KeyPathInst : OnoneSimplifyable {
func simplify(_ context: SimplifyContext) {
if allUsesRemovable(instruction: self) {
if parentFunction.hasOwnership {
let builder = Builder(after: self, context)
for operand in self.operands {
if !operand.value.type.isTrivial(in: parentFunction) {
builder.createDestroyValue(operand: operand.value)
}
}
}
context.erase(instructionIncludingAllUsers: self)
}
}
}

fileprivate func allUsesRemovable(instruction: Instruction) -> Bool {
for result in instruction.results {
for use in result.uses {
if !(use.instruction is UpcastInst || use.instruction is DestroyValueInst || use.instruction is BeginBorrowInst || use.instruction is EndBorrowInst) {
return false
}
if !allUsesRemovable(instruction: use.instruction) {
return false
}
}
}
return true
}
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ extension MutatingContext {
}
return nil
}

func tryOptimizeKeypath(apply: FullApplySite) -> Bool {
return _bridged.tryOptimizeKeypath(apply.bridged)
}

func inlineFunction(apply: FullApplySite, mandatoryInline: Bool) {
// This is only a best-effort attempt to notity the new cloned instructions as changed.
Expand Down
2 changes: 2 additions & 0 deletions include/swift/AST/DiagnosticsSIL.def
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,8 @@ ERROR(embedded_swift_metatype_type,none,
"cannot use metatype of type %0 in embedded Swift", (Type))
ERROR(embedded_swift_metatype,none,
"cannot use metatype in embedded Swift", ())
ERROR(embedded_swift_keypath,none,
"cannot use key path in embedded Swift", ())
ERROR(embedded_swift_allocating_type,none,
"cannot use allocating type %0 in -no-allocations mode", (Type))
ERROR(embedded_swift_allocating,none,
Expand Down
1 change: 1 addition & 0 deletions include/swift/SILOptimizer/OptimizerBridging.h
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ struct BridgedPassContext {
bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const;
bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const;
SWIFT_IMPORT_UNSAFE DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const;
bool tryOptimizeKeypath(BridgedInstruction apply) const;
SWIFT_IMPORT_UNSAFE OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const;
SWIFT_IMPORT_UNSAFE swift::SILVTable * _Nullable specializeVTableForType(BridgedType type,
BridgedFunction function) const;
Expand Down
7 changes: 7 additions & 0 deletions include/swift/SILOptimizer/Utils/InstOptUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,13 @@ bool specializeAppliesInFunction(SILFunction &F,
SILTransform *transform,
bool isMandatory);

bool tryOptimizeKeypath(ApplyInst *AI, SILBuilder Builder);
bool tryOptimizeKeypathApplication(ApplyInst *AI, SILFunction *callee, SILBuilder Builder);
bool tryOptimizeKeypathOffsetOf(ApplyInst *AI, FuncDecl *calleeFn,
KeyPathInst *kp, SILBuilder Builder);
bool tryOptimizeKeypathKVCString(ApplyInst *AI, FuncDecl *calleeFn,
KeyPathInst *kp, SILBuilder Builder);

/// Instantiate the specified type by recursively tupling and structing the
/// unique instances of the empty types and undef "instances" of the non-empty
/// types aggregated together at each level.
Expand Down
4 changes: 4 additions & 0 deletions lib/SILOptimizer/Mandatory/PerformanceDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,10 @@ bool PerformanceDiagnostics::visitInst(SILInstruction *inst,
diagnose(loc, diag::embedded_swift_value_deinit, impactType.getASTType());
return true;
}
if (isa<KeyPathInst>(inst)) {
diagnose(loc, diag::embedded_swift_keypath);
return true;
}
if (!allowedMetadataUseInEmbeddedSwift(inst)) {
PrettyStackTracePerformanceDiagnostics stackTrace("metatype", inst);
if (impactType) {
Expand Down
5 changes: 5 additions & 0 deletions lib/SILOptimizer/PassManager/PassManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1600,6 +1600,11 @@ BridgedPassContext::DevirtResult BridgedPassContext::tryDevirtualizeApply(Bridge
return {{nullptr}, false};
}

bool BridgedPassContext::tryOptimizeKeypath(BridgedInstruction apply) const {
SILBuilder builder(apply.unbridged());
return ::tryOptimizeKeypath(apply.getAs<ApplyInst>(), builder);
}

OptionalBridgedValue BridgedPassContext::constantFoldBuiltin(BridgedInstruction builtin) const {
auto bi = builtin.getAs<BuiltinInst>();
std::optional<bool> resultsInError;
Expand Down
6 changes: 0 additions & 6 deletions lib/SILOptimizer/SILCombiner/SILCombiner.h
Original file line number Diff line number Diff line change
Expand Up @@ -330,13 +330,7 @@ class SILCombiner :
SILInstruction *optimizeApplyOfConvertFunctionInst(FullApplySite AI,
ConvertFunctionInst *CFI);

bool tryOptimizeKeypath(ApplyInst *AI);
bool tryOptimizeInoutKeypath(BeginApplyInst *AI);
bool tryOptimizeKeypathApplication(ApplyInst *AI, SILFunction *callee);
bool tryOptimizeKeypathOffsetOf(ApplyInst *AI, FuncDecl *calleeFn,
KeyPathInst *kp);
bool tryOptimizeKeypathKVCString(ApplyInst *AI, FuncDecl *calleeFn,
KeyPathInst *kp);

/// Sinks owned forwarding instructions to their uses if they do not have
/// non-debug non-consuming uses. Deletes any debug_values and destroy_values
Expand Down
27 changes: 13 additions & 14 deletions lib/SILOptimizer/SILCombiner/SILCombinerApplyVisitors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,8 @@ SILCombiner::optimizeApplyOfConvertFunctionInst(FullApplySite AI,
/// %addr = struct_element_addr/ref_element_addr %root_object
/// ...
/// load/store %addr
bool SILCombiner::tryOptimizeKeypathApplication(ApplyInst *AI,
SILFunction *callee) {
bool swift::tryOptimizeKeypathApplication(ApplyInst *AI,
SILFunction *callee, SILBuilder Builder) {
if (AI->getNumArguments() != 3)
return false;

Expand Down Expand Up @@ -303,7 +303,6 @@ bool SILCombiner::tryOptimizeKeypathApplication(ApplyInst *AI,
}
});

eraseInstFromFunction(*AI);
++NumOptimizedKeypaths;
return true;
}
Expand All @@ -329,9 +328,9 @@ bool SILCombiner::tryOptimizeKeypathApplication(ApplyInst *AI,
/// %offset_builtin_int = unchecked_trivial_bit_cast %offset_ptr
/// %offset_int = struct $Int (%offset_builtin_int)
/// %offset = enum $Optional<Int>, #Optional.some!enumelt, %offset_int
bool SILCombiner::tryOptimizeKeypathOffsetOf(ApplyInst *AI,
bool swift::tryOptimizeKeypathOffsetOf(ApplyInst *AI,
FuncDecl *calleeFn,
KeyPathInst *kp) {
KeyPathInst *kp, SILBuilder Builder) {
auto *accessor = dyn_cast<AccessorDecl>(calleeFn);
if (!accessor || !accessor->isGetter())
return false;
Expand Down Expand Up @@ -432,7 +431,6 @@ bool SILCombiner::tryOptimizeKeypathOffsetOf(ApplyInst *AI,
result = Builder.createOptionalNone(loc, AI->getType());
}
AI->replaceAllUsesWith(result);
eraseInstFromFunction(*AI);
++NumOptimizedKeypaths;
return true;
}
Expand All @@ -444,9 +442,9 @@ bool SILCombiner::tryOptimizeKeypathOffsetOf(ApplyInst *AI,
/// %string = apply %keypath_kvcString_method(%kp)
/// With:
/// %string = string_literal "blah"
bool SILCombiner::tryOptimizeKeypathKVCString(ApplyInst *AI,
bool swift::tryOptimizeKeypathKVCString(ApplyInst *AI,
FuncDecl *calleeFn,
KeyPathInst *kp) {
KeyPathInst *kp, SILBuilder Builder) {
if (!calleeFn->getAttrs()
.hasSemanticsAttr(semantics::KEYPATH_KVC_KEY_PATH_STRING))
return false;
Expand Down Expand Up @@ -499,14 +497,13 @@ bool SILCombiner::tryOptimizeKeypathKVCString(ApplyInst *AI,
}

AI->replaceAllUsesWith(literalValue);
eraseInstFromFunction(*AI);
++NumOptimizedKeypaths;
return true;
}

bool SILCombiner::tryOptimizeKeypath(ApplyInst *AI) {
bool swift::tryOptimizeKeypath(ApplyInst *AI, SILBuilder Builder) {
if (SILFunction *callee = AI->getReferencedFunctionOrNull()) {
return tryOptimizeKeypathApplication(AI, callee);
return tryOptimizeKeypathApplication(AI, callee, Builder);
}

// Try optimize keypath method calls.
Expand All @@ -530,10 +527,10 @@ bool SILCombiner::tryOptimizeKeypath(ApplyInst *AI) {
if (!kp || !kp->hasPattern())
return false;

if (tryOptimizeKeypathOffsetOf(AI, calleeFn, kp))
if (tryOptimizeKeypathOffsetOf(AI, calleeFn, kp, Builder))
return true;

if (tryOptimizeKeypathKVCString(AI, calleeFn, kp))
if (tryOptimizeKeypathKVCString(AI, calleeFn, kp, Builder))
return true;

return false;
Expand Down Expand Up @@ -1465,8 +1462,10 @@ SILInstruction *SILCombiner::visitApplyInst(ApplyInst *AI) {
if (auto *CFI = dyn_cast<ConvertFunctionInst>(callee))
return optimizeApplyOfConvertFunctionInst(AI, CFI);

if (tryOptimizeKeypath(AI))
if (tryOptimizeKeypath(AI, Builder)) {
eraseInstFromFunction(*AI);
return nullptr;
}

// Optimize readonly functions with no meaningful users.
SILFunction *SF = AI->getReferencedFunctionOrNull();
Expand Down
24 changes: 19 additions & 5 deletions lib/SILOptimizer/Utils/KeyPathProjector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "swift/SILOptimizer/Utils/KeyPathProjector.h"

#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/InstructionUtils.h"

using namespace swift;

Expand Down Expand Up @@ -119,8 +120,13 @@ class StoredPropertyProjector : public ComponentProjector {
} else {
// Accessing a class member -> reading the class
parent->project(AccessType::Get, [&](SILValue parentValue) {
SingleValueInstruction *Ref = builder.createLoad(loc, parentValue,
LoadOwnershipQualifier::Unqualified);
SingleValueInstruction *Borrow = nullptr;
SingleValueInstruction *Ref;
if (builder.hasOwnership()) {
Ref = Borrow = builder.createLoadBorrow(loc, parentValue);
} else {
Ref = builder.createLoad(loc, parentValue, LoadOwnershipQualifier::Unqualified);
}

// If we were previously accessing a class member, we're done now.
insertEndAccess(beginAccess, builder);
Expand All @@ -134,6 +140,9 @@ class StoredPropertyProjector : public ComponentProjector {
// decl or in a superclass of it. Just handle this to be on the safe
// side.
callback(SILValue());
if (Borrow) {
builder.createEndBorrow(loc, Borrow);
}
return;
}
Ref = builder.createUpcast(loc, Ref, superCl);
Expand Down Expand Up @@ -162,6 +171,10 @@ class StoredPropertyProjector : public ComponentProjector {
if (beginAccess == addr) {
insertEndAccess(beginAccess, builder);
}

if (Borrow) {
builder.createEndBorrow(loc, Borrow);
}
});
}
}
Expand Down Expand Up @@ -669,9 +682,10 @@ class CompleteKeyPathProjector : public KeyPathProjector {

KeyPathInst *
KeyPathProjector::getLiteralKeyPath(SILValue keyPath) {
if (auto *upCast = dyn_cast<UpcastInst>(keyPath))
keyPath = upCast->getOperand();
// TODO: Look through other conversions, copies, etc.?
while (auto *upCast = dyn_cast<UpcastInst>(keyPath)) {
keyPath = lookThroughOwnershipInsts(upCast->getOperand());
}

return dyn_cast<KeyPathInst>(keyPath);
}

Expand Down
4 changes: 2 additions & 2 deletions stdlib/public/core/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ split_embedded_sources(
NORMAL IntegerParsing.swift
EMBEDDED Integers.swift
NORMAL Join.swift
NORMAL KeyPath.swift
EMBEDDED KeyPath.swift
NORMAL KeyValuePairs.swift
EMBEDDED LazyCollection.swift
EMBEDDED LazySequence.swift
Expand Down Expand Up @@ -125,7 +125,7 @@ split_embedded_sources(
NORMAL PrefixWhile.swift
NORMAL Prespecialize.swift
NORMAL Print.swift
NORMAL PtrAuth.swift
EMBEDDED PtrAuth.swift
EMBEDDED Random.swift
EMBEDDED RandomAccessCollection.swift
EMBEDDED Range.swift
Expand Down
18 changes: 1 addition & 17 deletions stdlib/public/core/EmbeddedStubs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import SwiftShims
public struct String: Hashable {
public var utf8CString: ContiguousArray<CChar> { fatalError() }
public init() {}
public init(validatingCString: UnsafePointer<CChar>) { fatalError() }
}

@_unavailableInEmbedded
Expand Down Expand Up @@ -242,20 +243,3 @@ public enum DecodingError: Error {
case keyNotFound(any CodingKey, Context)
case dataCorrupted(Context)
}

/// KeyPath

@_unavailableInEmbedded
public class AnyKeyPath {
@usableFromInline
internal var _storedInlineOffset: Int? { fatalError() }
}

@_unavailableInEmbedded
public class PartialKeyPath<Root>: AnyKeyPath { }

@_unavailableInEmbedded
public class KeyPath<Root, Value>: PartialKeyPath<Root> { }

@_unavailableInEmbedded
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> { }
Loading