Skip to content

[6.2] Handle a special case of borrowed from instruction in CopyToBorrowOptimization #80971

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 1 commit into from
Apr 22, 2025
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 @@ -360,6 +360,13 @@ private extension Value {
}

var lookThroughForwardingInstructions: Value {
if let bfi = definingInstruction as? BorrowedFromInst,
!bfi.borrowedPhi.isReborrow,
bfi.enclosingValues.count == 1
{
// Return the single forwarded enclosingValue
return bfi.enclosingValues[0]
}
if let fi = definingInstruction as? ForwardingInstruction,
let forwardedOp = fi.singleForwardedOperand
{
Expand Down
40 changes: 40 additions & 0 deletions test/SILOptimizer/copy-to-borrow-optimization.sil
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// RUN: %target-sil-opt -copy-to-borrow-optimization %s | %FileCheck %s
// REQUIRES: macosx

sil_stage canonical

Expand Down Expand Up @@ -2220,3 +2221,42 @@ sil [ossa] @keep_yield2ed_copy : $@convention(thin) () -> () {
%retval = tuple ()
return %retval : $()
}

// CHECK-LABEL: sil [ossa] @borrowed_from_forward1 : {{.*}} {
// CHECK-NOT: copy_value
// CHECK-LABEL: } // end sil function 'borrowed_from_forward1'
sil [ossa] @borrowed_from_forward1 : $@convention(thin) (@guaranteed C) -> () {
bb0(%0 : @guaranteed $C):
br bb1(%0)

bb1(%1 : @guaranteed $C):
%2 = borrowed %1 from (%0)
%copy = copy_value %2
%useC = function_ref @useC : $@convention(thin) (@guaranteed C) -> ()
apply %useC(%copy) : $@convention(thin) (@guaranteed C) -> ()
destroy_value %copy
%retval = tuple ()
return %retval : $()
}

// CHECK-LABEL: sil [ossa] @borrowed_from_forward2 : {{.*}} {
// CHECK-NOT: copy_value
// CHECK-LABEL: } // end sil function 'borrowed_from_forward2'
sil [ossa] @borrowed_from_forward2 : $@convention(thin) (@guaranteed Array<Int>) -> () {
bb0(%0 : @guaranteed $Array<Int>):
%1 = struct_extract %0, #Array._buffer
%2 = struct_extract %1, #_ArrayBuffer._storage
%3 = struct_extract %2, #_BridgeStorage.rawValue
%4 = unchecked_ref_cast %3 to $__ContiguousArrayStorageBase
br bb1(%4)

bb1(%6 : @guaranteed $__ContiguousArrayStorageBase):
%7 = borrowed %6 from (%0)
%8 = copy_value %7
%9 = begin_borrow %8
%10 = ref_element_addr [immutable] %9, #__ContiguousArrayStorageBase.countAndCapacity
end_borrow %9
destroy_value %8
%13 = tuple ()
return %13
}