2 * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "ConstantInsertionPass.h"
19 #include "backend/Backend.h"
21 #include "util/Utils.h"
22 #include "util/logging.h"
31 void ConstantInsertionPass::callback(const ir::OperationIndex &node_index, ir::Operation &node)
33 const auto op_lower_info = _lowered_graph.lower_info().operation.getRawPtr(node_index);
34 const auto backend = op_lower_info->backend();
35 const auto layout = op_lower_info->layout();
36 const auto factor = PermuteFactor{backend, layout};
38 for (const auto input : node.getInputs() | ir::Remove::DUPLICATED | ir::Remove::UNDEFINED)
40 auto &object = _graph.operands().at(input);
42 if (object.isConstant())
44 const auto key = ReplaceKey{input, factor};
45 if (_replace_operands_map.count(key) == 0)
47 ir::Operand new_object(object);
48 new_object.clearDefUse();
49 const auto new_index = _graph.operands().emplace(new_object);
50 _replace_operands_map[key] = new_index;
53 const auto replaced_input = _replace_operands_map[key];
55 // Update the same inputs of a node at once because inputs of an operation have the same
57 node.replaceInputs(input, replaced_input);
60 auto &replaced_object = _graph.operands().at(replaced_input);
61 replaced_object.insertUse(node_index);
63 VERBOSE(ConstInsertPass) << "New operand " << replaced_input << " added(copy of " << input
64 << ") for " << factor << std::endl;
65 // Remove this node from uses of origin operand
66 // Constant operand has no def.
67 assert(!object.getDef().valid());
68 object.removeUse(node_index);
70 // Remove origin operand
71 if (object.getUses().size() == 0)
73 _graph.removeOperand(input);
74 VERBOSE(ConstInsertPass) << "Original operand " << input << " removed - no uses"
80 // Now this runtime does not support the node making output as constant
81 for (const auto &output : node.getOutputs() | ir::Remove::DUPLICATED | ir::Remove::UNDEFINED)
83 UNUSED_RELEASE(output);
84 assert(!_graph.operands().at(output).isConstant());
89 } // namespace compiler