| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. |
| 4 | // |
| 5 | // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except |
| 6 | // in compliance with the License. You may obtain a copy of the License at |
| 7 | // |
| 8 | // https://opensource.org/licenses/BSD-3-Clause |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software distributed |
| 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 13 | // specific language governing permissions and limitations under the License. |
| 14 | |
| 15 | #include "eliminate_tail_reshape_permute.h" |
| 16 | |
| 17 | #include <algorithm> |
| 18 | |
| 19 | namespace pnnx { |
| 20 | |
| 21 | namespace ncnn { |
| 22 | |
| 23 | void eliminate_tail_reshape_permute(Graph& graph) |
| 24 | { |
| 25 | for (;;) |
| 26 | { |
| 27 | bool need_eliminate = false; |
| 28 | |
| 29 | for (int i = (int)graph.ops.size() - 1; i >= 0; i--) |
| 30 | { |
| 31 | Operator* op = graph.ops[i]; |
| 32 | |
| 33 | if (op->type != "Reshape" && op->type != "Permute") |
| 34 | continue; |
| 35 | |
| 36 | Operand* op_out = op->outputs[0]; |
| 37 | |
| 38 | if (op_out->consumers.size() != 1) |
| 39 | continue; |
| 40 | |
| 41 | Operator* op2 = op_out->consumers[0]; |
| 42 | |
| 43 | if (op2->type != "pnnx.Output") |
| 44 | continue; |
| 45 | |
| 46 | need_eliminate = true; |
| 47 | |
| 48 | op->inputs[0]->remove_consumer(op); |
| 49 | |
| 50 | op->inputs[0]->params = op_out->params; |
| 51 | |
| 52 | for (size_t j = 0; j < op2->inputs.size(); j++) |
| 53 | { |
| 54 | if (op2->inputs[j] == op_out) |
| 55 | op2->inputs[j] = op->inputs[0]; |
| 56 | } |
| 57 | |
| 58 | op->inputs[0]->consumers.push_back(op2); |
| 59 | |
| 60 | op_out->producer = 0; |
| 61 | op_out->consumers.clear(); |
| 62 | |
| 63 | graph.operands.erase(std::find(graph.operands.begin(), graph.operands.end(), op_out)); |
| 64 | delete op_out; |
| 65 | |
| 66 | op->inputs.clear(); |
| 67 | op->outputs.clear(); |
| 68 | |
| 69 | graph.ops.erase(graph.ops.begin() + i); |
| 70 | delete op; |
| 71 | |
| 72 | break; |
| 73 | } |
| 74 | |
| 75 | if (!need_eliminate) |
| 76 | break; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | } // namespace ncnn |
| 81 | |
| 82 | } // namespace pnnx |