Skip to content

Commit bfd78d6

Browse files
committed
[SemanticARCOpts] Strip some lexical borrow scopes.
If a value's lifetime is preserved by a different lexical scope, it is fine to strip a different scope. Specifically, if it is preserved by being a guaranteed argument or a nested borrow of an outer lexical scope, allow a lexical borrow scope to be stripped.
1 parent cde250a commit bfd78d6

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

lib/SILOptimizer/SemanticARC/BorrowScopeOpts.cpp

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,35 @@
2424
using namespace swift;
2525
using namespace swift::semanticarc;
2626

27+
/// Whether the provided lexical begin_borrow instruction is redundant.
28+
///
29+
/// A begin_borrow [lexical] is redundant if the borrowed value's lifetime is
30+
/// otherwise guaranteed. That happens if:
31+
/// - the value is a guaranteed argument to the function
32+
/// - the value is itself a begin_borrow [lexical]
33+
static bool isRedundantLexicalBeginBorrow(BeginBorrowInst *bbi) {
34+
assert(bbi->isLexical());
35+
auto value = bbi->getOperand();
36+
if (auto *outerBBI = dyn_cast<BeginBorrowInst>(value)) {
37+
return outerBBI->isLexical();
38+
}
39+
if (auto *arg = dyn_cast<SILFunctionArgument>(value)) {
40+
return arg->getOwnershipKind() == OwnershipKind::Guaranteed;
41+
}
42+
return false;
43+
}
44+
2745
bool SemanticARCOptVisitor::visitBeginBorrowInst(BeginBorrowInst *bbi) {
2846
// Quickly check if we are supposed to perform this transformation.
2947
if (!ctx.shouldPerform(ARCTransformKind::RedundantBorrowScopeElimPeephole))
3048
return false;
3149

3250
// Lexical borrow scopes must remain in order to ensure that value lifetimes
3351
// are not observably shortened.
34-
if (bbi->isLexical())
35-
return false;
52+
if (bbi->isLexical()) {
53+
if (!isRedundantLexicalBeginBorrow(bbi))
54+
return false;
55+
}
3656

3757
auto kind = bbi->getOperand().getOwnershipKind();
3858
SmallVector<EndBorrowInst *, 16> endBorrows;

0 commit comments

Comments
 (0)