|
| 1 | +//===--- SimplifyCopyBlock.swift ------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import SIL |
| 14 | + |
| 15 | +extension CopyBlockInst : Simplifiable, SILCombineSimplifiable { |
| 16 | + |
| 17 | + /// Removes a `copy_block` if its only uses, beside ownership instructions, are callees of function calls |
| 18 | + /// ``` |
| 19 | + /// %2 = copy_block %0 |
| 20 | + /// %3 = begin_borrow [lexical] %2 |
| 21 | + /// %4 = apply %3() : $@convention(block) @noescape () -> () |
| 22 | + /// end_borrow %3 |
| 23 | + /// destroy_value %2 |
| 24 | + /// ``` |
| 25 | + /// -> |
| 26 | + /// ``` |
| 27 | + /// %4 = apply %0() : $@convention(block) @noescape () -> () |
| 28 | + /// ``` |
| 29 | + /// |
| 30 | + func simplify(_ context: SimplifyContext) { |
| 31 | + // Temporarily guarded with an experimental feature flag. |
| 32 | + if !context.options.hasFeature(.CopyBlockOptimization) { |
| 33 | + return |
| 34 | + } |
| 35 | + |
| 36 | + if hasValidUses(block: self) { |
| 37 | + replaceBlock( self, with: operand.value, context) |
| 38 | + context.erase(instruction: self) |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +private func hasValidUses(block: Value) -> Bool { |
| 44 | + for use in block.uses { |
| 45 | + switch use.instruction { |
| 46 | + case let beginBorrow as BeginBorrowInst: |
| 47 | + if !hasValidUses(block: beginBorrow) { |
| 48 | + return false |
| 49 | + } |
| 50 | + case let apply as FullApplySite where apply.isCallee(operand: use): |
| 51 | + break |
| 52 | + case is EndBorrowInst, is DestroyValueInst: |
| 53 | + break |
| 54 | + default: |
| 55 | + return false |
| 56 | + } |
| 57 | + } |
| 58 | + return true |
| 59 | +} |
| 60 | + |
| 61 | +private func replaceBlock(_ block: Value, with original: Value, _ context: SimplifyContext) { |
| 62 | + for use in block.uses { |
| 63 | + switch use.instruction { |
| 64 | + case let beginBorrow as BeginBorrowInst: |
| 65 | + replaceBlock(beginBorrow, with: original, context) |
| 66 | + context.erase(instruction: beginBorrow) |
| 67 | + case is FullApplySite: |
| 68 | + use.set(to: original, context) |
| 69 | + case is EndBorrowInst, is DestroyValueInst: |
| 70 | + context.erase(instruction: use.instruction) |
| 71 | + default: |
| 72 | + fatalError("unhandled use") |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments