1- //===--- SimplifyBeginBorrow .swift ------- ---------------------------------===//
1+ //===--- SimplifyBeginAndLoadBorrow .swift ---------------------------------===//
22//
33// This source file is part of the Swift.org open source project
44//
@@ -25,6 +25,45 @@ extension BeginBorrowInst : OnoneSimplifyable {
2525 }
2626}
2727
28+ extension LoadBorrowInst : Simplifyable , SILCombineSimplifyable {
29+ func simplify( _ context: SimplifyContext ) {
30+ if uses. ignoreDebugUses. ignoreUsers ( ofType: EndBorrowInst . self) . isEmpty {
31+ context. erase ( instructionIncludingAllUsers: self )
32+ return
33+ }
34+
35+ // If the load_borrow is followed by a copy_value, combine both into a `load [copy]`:
36+ // ```
37+ // %1 = load_borrow %0
38+ // %2 = some_forwarding_instruction %1 // zero or more forwarding instructions
39+ // %3 = copy_value %2
40+ // end_borrow %1
41+ // ```
42+ // ->
43+ // ```
44+ // %1 = load [copy] %0
45+ // %3 = some_forwarding_instruction %1 // zero or more forwarding instructions
46+ // ```
47+ //
48+ tryCombineWithCopy ( context)
49+ }
50+
51+ private func tryCombineWithCopy( _ context: SimplifyContext ) {
52+ let forwardedValue = lookThroughSingleForwardingUses ( )
53+ guard let singleUser = forwardedValue. uses. ignoreUsers ( ofType: EndBorrowInst . self) . singleUse? . instruction,
54+ let copy = singleUser as? CopyValueInst ,
55+ copy. parentBlock == self . parentBlock else {
56+ return
57+ }
58+ let builder = Builder ( before: self , context)
59+ let loadCopy = builder. createLoad ( fromAddress: address, ownership: . copy)
60+ let forwardedOwnedValue = replace ( guaranteedValue: self , withOwnedValue: loadCopy, context)
61+ copy. uses. replaceAll ( with: forwardedOwnedValue, context)
62+ context. erase ( instruction: copy)
63+ context. erase ( instructionIncludingAllUsers: self )
64+ }
65+ }
66+
2867private func tryReplaceBorrowWithOwnedOperand( beginBorrow: BeginBorrowInst , _ context: SimplifyContext ) {
2968 // The last value of a (potentially empty) forwarding chain, beginning at the `begin_borrow`.
3069 let forwardedValue = beginBorrow. lookThroughSingleForwardingUses ( )
@@ -156,7 +195,7 @@ private extension ForwardingInstruction {
156195}
157196
158197/// Replaces a guaranteed value with an owned value.
159- ///
198+ ///
160199/// If the `guaranteedValue`'s use is a ForwardingInstruction (or forwarding instruction chain),
161200/// it is converted to an owned version of the forwarding instruction (or instruction chain).
162201///
0 commit comments