Skip to content

[SILGen] Don't peephole closures with abstraction differences in the thrown error #71577

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
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: 7 additions & 0 deletions lib/SIL/IR/TypeLowering.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3246,6 +3246,13 @@ TypeConverter::computeLoweredRValueType(TypeExpansionContext forExpansion,
AnyFunctionType::ExtInfo baseExtInfo;
if (auto origFnType = origType.getAs<AnyFunctionType>()) {
baseExtInfo = origFnType->getExtInfo();

if (baseExtInfo.getThrownError()) {
if (auto substThrownError = substFnType->getEffectiveThrownErrorType())
baseExtInfo = baseExtInfo.withThrows(true, *substThrownError);
else
baseExtInfo = baseExtInfo.withThrows(false, Type());
}
} else {
baseExtInfo = substFnType->getExtInfo();
}
Expand Down
28 changes: 22 additions & 6 deletions lib/SILGen/SILGenExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1903,12 +1903,21 @@ static ManagedValue convertFunctionRepresentation(SILGenFunction &SGF,
llvm_unreachable("bad representation");
}

/// Whether the given abstraction pattern as an opaque thrown error.
static bool hasOpaqueThrownError(const AbstractionPattern &pattern) {
if (auto thrownPattern = pattern.getFunctionThrownErrorType())
return thrownPattern->isTypeParameterOrOpaqueArchetype();

return false;
}

// Ideally our prolog/epilog emission would be able to handle all possible
// reabstractions and conversions. Until then, this returns true if a closure
// literal of type `literalType` can be directly emitted by SILGen as
// `convertedType`.
static bool canPeepholeLiteralClosureConversion(Type literalType,
Type convertedType) {
static bool canPeepholeLiteralClosureConversion(
Type literalType, Type convertedType,
const std::optional<AbstractionPattern> &closurePattern) {
auto literalFnType = literalType->getAs<FunctionType>();
auto convertedFnType = convertedType->getAs<FunctionType>();

Expand All @@ -1919,22 +1928,28 @@ static bool canPeepholeLiteralClosureConversion(Type literalType,
if (literalFnType->isEqual(convertedFnType)) {
return true;
}

// Are the types equivalent aside from effects (throws) or coeffects
// (escaping)? Then we should emit the literal as having the destination type
// (co)effects, even if it doesn't exercise them.
//
// TODO: We could also in principle let `async` through here, but that
// interferes with the implementation of `reasync`.
auto literalWithoutEffects = literalFnType->getExtInfo().intoBuilder()
.withThrows(false, Type())
.withNoEscape(false)
.build();

auto convertedWithoutEffects = convertedFnType->getExtInfo().intoBuilder()
.withThrows(false, Type())
.withNoEscape(false)
.build();

// If the closure pattern has an abstract thrown error, we are unable to
// emit the literal with a difference in the thrown error type.
if (!(closurePattern && hasOpaqueThrownError(*closurePattern))) {
literalWithoutEffects = literalWithoutEffects.withThrows(false, Type());
convertedWithoutEffects = convertedWithoutEffects.withThrows(false, Type());
}

if (literalFnType->withExtInfo(literalWithoutEffects)
->isEqual(convertedFnType->withExtInfo(convertedWithoutEffects))) {
return true;
Expand Down Expand Up @@ -2000,7 +2015,8 @@ RValue RValueEmitter::visitFunctionConversionExpr(FunctionConversionExpr *e,

if ((isa<AbstractClosureExpr>(subExpr) || isa<CaptureListExpr>(subExpr))
&& canPeepholeLiteralClosureConversion(subExpr->getType(),
e->getType())) {
e->getType(),
C.getAbstractionPattern())) {
// If we're emitting into a context with a preferred abstraction pattern
// already, carry that along.
auto origType = C.getAbstractionPattern();
Expand Down
24 changes: 24 additions & 0 deletions test/SILGen/typed_throws.swift
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,30 @@ func throwAndPatternMatchCatch<E: Error>(_ body: () throws(E) -> Void) throws(E)
}
}

enum MyResult<Success, Failure: Error> {
case success(Success)
case failure(Failure)

@inlinable
init(catching body: () throws(Failure) -> Success) {
do {
self = .success(try body())
} catch {
self = .failure(error)
}
}
}

func formerReabstractionCrash() {
// CHECK-LABEL: sil private [ossa] @$s12typed_throws24formerReabstractionCrashyyFAA8MyResultOySSs5Error_pGyXEfU_ : $@convention(thin) () -> @owned MyResult<String, any Error> {
// CHECK: function_ref @$s12typed_throws24formerReabstractionCrashyyFAA8MyResultOySSs5Error_pGyXEfU_SSyXEfU_ : $@convention(thin) () -> @owned String
// CHECK-NEXT: thin_to_thick_function
// CHECK-NEXT: convert_function {{%.*}} : $@noescape @callee_guaranteed () -> @owned String to $@noescape @callee_guaranteed () -> (@owned String, @error any Error)
let _: MyResult<String, Error>? = {
return MyResult{"hello"}
}()
}

// CHECK-LABEL: sil_vtable MySubclass {
// CHECK-NEXT: #MyClass.init!allocator: <E where E : Error> (MyClass.Type) -> (() throws(E) -> ()) throws(E) -> MyClass : @$s12typed_throws10MySubclassC4bodyACyyxYKXE_txYKcs5ErrorRzlufC [override]
// CHECK-NEXT: #MyClass.f: (MyClass) -> () throws -> () : @$s12typed_throws10MySubclassC1fyyAA0C5ErrorOYKFAA0C5ClassCADyyKFTV [override]
Expand Down