| 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 "dead_code_elimination.h" |
| 16 | |
| 17 | namespace pnnx { |
| 18 | |
| 19 | void dead_code_elimination(Graph& graph) |
| 20 | { |
| 21 | // dead op elimination |
| 22 | for (;;) |
| 23 | { |
| 24 | bool need_eliminate = false; |
| 25 | |
| 26 | for (int i = (int)graph.ops.size() - 1; i >= 0; i--) |
| 27 | { |
| 28 | Operator* op = graph.ops[i]; |
| 29 | |
| 30 | if (op->type == "pnnx.Output") |
| 31 | continue; |
| 32 | |
| 33 | int consumers = 0; |
| 34 | for (const Operand* operand : op->outputs) |
| 35 | { |
| 36 | consumers += (int)operand->consumers.size(); |
| 37 | } |
| 38 | |
| 39 | if (consumers == 0) |
| 40 | { |
| 41 | need_eliminate = true; |
| 42 | |
| 43 | // fprintf(stderr, "delete %s %s\n", op->type.c_str(), op->name.c_str()); |
| 44 | |
| 45 | for (Operand* operand : op->inputs) |
| 46 | { |
| 47 | operand->remove_consumer(op); |
| 48 | } |
| 49 | |
| 50 | op->inputs.clear(); |
| 51 | |
| 52 | for (Operand* operand : op->outputs) |
| 53 | { |
| 54 | operand->producer = 0; |
| 55 | } |
| 56 | |
| 57 | op->outputs.clear(); |
| 58 | |
| 59 | graph.ops.erase(graph.ops.begin() + i); |
| 60 | delete op; |
| 61 | |
| 62 | break; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | if (!need_eliminate) |
| 67 | break; |
| 68 | } |
| 69 | |
| 70 | // dead operand elimination |
| 71 | for (;;) |
| 72 | { |
| 73 | bool need_eliminate = false; |
| 74 | |
| 75 | for (int i = (int)graph.operands.size() - 1; i >= 0; i--) |
| 76 | { |
| 77 | Operand* operand = graph.operands[i]; |
| 78 | |
| 79 | int consumers = (int)operand->consumers.size(); |
| 80 | |
| 81 | if (operand->producer == 0 && consumers == 0) |
| 82 | { |
| 83 | need_eliminate = true; |
| 84 | |
| 85 | // fprintf(stderr, "delete operand %s\n", operand->name.c_str()); |
| 86 | |
| 87 | graph.operands.erase(graph.operands.begin() + i); |
| 88 | delete operand; |
| 89 | |
| 90 | break; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | if (!need_eliminate) |
| 95 | break; |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | } // namespace pnnx |