|
| 1 | +//===--- BorrowScopeOpts.cpp ----------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2020 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 | +/// \file |
| 14 | +/// |
| 15 | +/// Optimizations that attempt to simplify and or eliminate borrow scopes. Today |
| 16 | +/// we only eliminate scopes, but we could also eliminate redundant scopes by |
| 17 | +/// converting struct_extract operations to use destructure operations. |
| 18 | +/// |
| 19 | +//===----------------------------------------------------------------------===// |
| 20 | + |
| 21 | +#include "SemanticARCOptVisitor.h" |
| 22 | + |
| 23 | +using namespace swift; |
| 24 | +using namespace swift::semanticarc; |
| 25 | + |
| 26 | +bool SemanticARCOptVisitor::visitBeginBorrowInst(BeginBorrowInst *bbi) { |
| 27 | + auto kind = bbi->getOperand().getOwnershipKind(); |
| 28 | + SmallVector<EndBorrowInst *, 16> endBorrows; |
| 29 | + for (auto *op : bbi->getUses()) { |
| 30 | + if (!op->isConsumingUse()) { |
| 31 | + // Make sure that this operand can accept our arguments kind. |
| 32 | + auto map = op->getOwnershipKindMap(); |
| 33 | + if (map.canAcceptKind(kind)) |
| 34 | + continue; |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + // Otherwise, this borrow is being consumed. See if our consuming inst is an |
| 39 | + // end_borrow. If it isn't, then return false, this scope is |
| 40 | + // needed. Otherwise, add the end_borrow to our list of end borrows. |
| 41 | + auto *ebi = dyn_cast<EndBorrowInst>(op->getUser()); |
| 42 | + if (!ebi) { |
| 43 | + return false; |
| 44 | + } |
| 45 | + endBorrows.push_back(ebi); |
| 46 | + } |
| 47 | + |
| 48 | + // At this point, we know that the begin_borrow's operand can be |
| 49 | + // used as an argument to all non-end borrow uses. Eliminate the |
| 50 | + // begin borrow and end borrows. |
| 51 | + while (!endBorrows.empty()) { |
| 52 | + auto *ebi = endBorrows.pop_back_val(); |
| 53 | + eraseInstruction(ebi); |
| 54 | + } |
| 55 | + |
| 56 | + eraseAndRAUWSingleValueInstruction(bbi, bbi->getOperand()); |
| 57 | + return true; |
| 58 | +} |
0 commit comments