d413e8162e57e1cf8252250a6518e17802005972
[platform/core/ml/nnfw.git] / runtime / onert / core / src / exec / FunctionSequence.cc
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "exec/FunctionSequence.h"
18
19 #include "ir/Operation.h"
20 #include "backend/IDynamicTensorManager.h"
21 #include "backend/ITensorRegistry.h"
22 #include "util/logging.h"
23
24 namespace onert
25 {
26 namespace exec
27 {
28
29 void FunctionSequence::run()
30 {
31   if (_enable_dynamic_shape_inferer)
32   {
33     if (_dynamic_tensor_ctx->op_seq->size() != _functions.size())
34       throw std::runtime_error("operation and functions should be mapped one by one");
35
36     auto op_seq_iter = _dynamic_tensor_ctx->op_seq->begin();
37     for (const auto &function : _functions)
38     {
39       // set shape of output and allocate memory when needed
40       auto &op = _dynamic_tensor_ctx->operations->at(*op_seq_iter);
41       op.accept(*_dynamic_tensor_ctx->dynamic_shape_inferer);
42
43       auto *sub_func_seq = dynamic_cast<FunctionSequence *>(function.get());
44       if (sub_func_seq != nullptr)
45       {
46         sub_func_seq->enableDynamicShapeInferer(true);
47         sub_func_seq->dynamic_tensor_ctx(dynamic_tensor_ctx());
48       }
49
50       // run kernel
51       function->run();
52
53       // deallocate input tensors which is no longer used
54       _dynamic_tensor_ctx->dynamic_tensor_manager->deallocInput(*op_seq_iter);
55
56       op_seq_iter++;
57     }
58   }
59   else
60   {
61     for (const auto &function : _functions)
62     {
63       auto *sub_func_seq = dynamic_cast<FunctionSequence *>(function.get());
64       if (sub_func_seq != nullptr)
65       {
66         sub_func_seq->enableDynamicShapeInferer(false);
67       }
68       function->run();
69     }
70   }
71 }
72
73 void FunctionSequence::prepare()
74 {
75   for (const auto &function : _functions)
76   {
77     function->prepare();
78   }
79 }
80
81 void FunctionSequence::append(std::unique_ptr<IFunction> &&function)
82 {
83   _functions.push_back(std::move(function));
84 }
85
86 void FunctionSequence::iterate(const std::function<void(IFunction &)> &fn)
87 {
88   for (const auto &func : _functions)
89   {
90     fn(*func);
91   }
92 }
93
94 } // namespace exec
95 } // namespace onert