Skip to content

Commit 718390a

Browse files
committed
Add a helper function for emitting a switch_enum that breaks down an Optional.
1 parent 0d16cbf commit 718390a

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

include/swift/SIL/SILBuilder.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2706,6 +2706,17 @@ class SILBuilder {
27062706
CaseCounts, DefaultCount, forwardingOwnershipKind));
27072707
}
27082708

2709+
/// A convenience function to decompose a scalar optional value with a
2710+
/// switch_enum. Returns the object value, which will only be valid
2711+
/// in `someBB`. Don't forget to switch insertion blocks after
2712+
/// calling this.
2713+
SILPhiArgument *createSwitchOptional(
2714+
SILLocation loc, SILValue operand,
2715+
SILBasicBlock *someBB, SILBasicBlock *noneBB,
2716+
ValueOwnershipKind forwardingOwnershipKind,
2717+
ProfileCounter someCount = ProfileCounter(),
2718+
ProfileCounter noneCount = ProfileCounter());
2719+
27092720
SwitchEnumAddrInst *createSwitchEnumAddr(
27102721
SILLocation Loc, SILValue Operand, SILBasicBlock *DefaultBB,
27112722
ArrayRef<std::pair<EnumElementDecl *, SILBasicBlock *>> CaseBBs,

lib/SIL/IR/SILBuilder.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,25 @@ void SILBuilder::emitScopedBorrowOperation(SILLocation loc, SILValue original,
681681
createEndBorrow(loc, value);
682682
}
683683

684+
SILPhiArgument *SILBuilder::createSwitchOptional(
685+
SILLocation loc, SILValue operand,
686+
SILBasicBlock *someBB, SILBasicBlock *noneBB,
687+
ValueOwnershipKind forwardingOwnershipKind,
688+
ProfileCounter someCount,
689+
ProfileCounter noneCount) {
690+
ProfileCounter counts[] = {someCount, noneCount};
691+
std::optional<ArrayRef<ProfileCounter>> countsArg = std::nullopt;
692+
if (someCount || noneCount) countsArg = counts;
693+
694+
auto &ctx = getASTContext();
695+
auto sei = createSwitchEnum(loc, operand, /*default*/ nullptr,
696+
{{ctx.getOptionalSomeDecl(), someBB},
697+
{ctx.getOptionalNoneDecl(), noneBB}},
698+
countsArg, /*default*/ProfileCounter(),
699+
forwardingOwnershipKind);
700+
return sei->createResult(someBB, operand->getType().unwrapOptionalType());
701+
}
702+
684703
/// Attempt to propagate ownership from \p operand to the returned forwarding
685704
/// ownership where the forwarded value has type \p targetType. If this fails,
686705
/// return Owned forwarding ownership instead.

0 commit comments

Comments
 (0)