• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2020 Huawei Technologies Co., Ltd
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 "tools/converter/optimizer.h"
18 #include "src/common/log_adapter.h"
19 #include "src/common/log_util.h"
20 
21 namespace mindspore {
22 namespace lite {
~Optimizer()23 Optimizer::~Optimizer() {
24   for (auto pass : graph_passes_) {
25     if (pass != nullptr) {
26       delete (pass);
27     }
28   }
29 
30   for (auto pass : node_passes_) {
31     if (pass != nullptr) {
32       delete (pass);
33     }
34   }
35 }
36 
AddPass(GraphPass * graphPass)37 void Optimizer::AddPass(GraphPass *graphPass) {
38   if (graphPass != nullptr) {
39     this->graph_passes_.emplace_back(graphPass);
40   }
41 }
42 
AddPass(NodePass * nodePass)43 void Optimizer::AddPass(NodePass *nodePass) {
44   if (nodePass != nullptr) {
45     this->node_passes_.emplace_back(nodePass);
46   }
47 }
48 
Run(schema::MetaGraphT * graphDefT)49 STATUS Optimizer::Run(schema::MetaGraphT *graphDefT) {
50   MS_ASSERT(graphDefT != nullptr);
51   STATUS status;
52   bool ifNotChanged = true;
53   // each node should go through all node pass not each node pass go through all node
54   for (auto &opDef : graphDefT->nodes) {
55     for (auto pass : this->node_passes_) {
56       auto graph_node = new (std::nothrow) GraphNode(graphDefT, opDef.get());
57       if (graph_node == nullptr) {
58         return RET_ERROR;
59       }
60       CHECK_NULL_RETURN(pass);
61       status = pass->Run(graph_node);
62       delete graph_node;
63       if (status != RET_OK && status != RET_NO_CHANGE && status != RET_INFER_INVALID) {
64         MS_LOG(ERROR) << "Run NodePass failed";
65         return status;
66       } else {
67         if (status == RET_OK) {
68           ifNotChanged = false;
69         }
70       }
71     }
72   }
73 
74   for (auto pass : this->graph_passes_) {
75     CHECK_NULL_RETURN(pass);
76     status = pass->Run(graphDefT);
77     if (status != RET_OK && status != RET_NO_CHANGE && status != RET_INFER_INVALID) {
78       MS_LOG(ERROR) << "Run GraphPass failed";
79       return status;
80     } else {
81       if (status == RET_OK) {
82         ifNotChanged = false;
83       }
84     }
85   }
86   return ifNotChanged ? RET_NO_CHANGE : RET_OK;
87 }
88 }  // namespace lite
89 }  // namespace mindspore
90