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 <backend/cpu_common/MemoryManager.h>
21 #include "MemoryPlannerFactory.h"
22 #include "util/ConfigSource.h"
31 MemoryManager::MemoryManager() : _mem_planner{createMemoryPlanner()}
36 MemoryManager::MemoryManager(const std::string planner_id)
37 : _mem_planner{createMemoryPlanner(planner_id)}
42 cpu_common::IMemoryPlanner *MemoryManager::createMemoryPlanner()
44 auto planner_id = util::getConfigString(util::config::CPU_MEMORY_PLANNER);
45 return cpu_common::MemoryPlannerFactory::get().create(planner_id);
48 cpu_common::IMemoryPlanner *MemoryManager::createMemoryPlanner(const std::string planner_id)
50 return cpu_common::MemoryPlannerFactory::get().create(planner_id);
53 void MemoryManager::claimPlan(const ir::OperandIndex &ind, uint32_t size)
55 _mem_planner->claim(ind, size);
58 void MemoryManager::releasePlan(const ir::OperandIndex &ind) { _mem_planner->release(ind); }
60 void MemoryManager::allocate(void)
62 _mem_alloc = std::make_shared<cpu_common::Allocator>(_mem_planner->capacity());
63 assert(_mem_alloc->base());
66 uint8_t *MemoryManager::getBuffer(const ir::OperandIndex &ind) const
68 assert(_mem_planner->memory_plans().find(ind) != _mem_planner->memory_plans().end());
69 const auto &mem_blk = _mem_planner->memory_plans().at(ind);
70 return _mem_alloc->base() + mem_blk.offset;
73 std::shared_ptr<cpu_common::Allocator> DynamicMemoryManager::allocate(const ir::OperandIndex &ind,
76 auto find = _mem_alloc_map.find(ind);
77 if (find != _mem_alloc_map.end())
78 throw std::runtime_error("Cannot allocate memory for a tensor. It was already allocated.");
80 _mem_alloc_map[ind] = std::make_shared<cpu_common::Allocator>(capacity);
81 return _mem_alloc_map[ind];
84 void DynamicMemoryManager::deallocate(const ir::OperandIndex &ind)
86 auto find = _mem_alloc_map.find(ind);
87 if (find == _mem_alloc_map.end())
88 throw std::runtime_error("Cannot find Allocator for the requested index");
90 find->second->release(); // explicitly erase memory
91 _mem_alloc_map.erase(find); // remove tensor and alloc
94 void DynamicMemoryManager::deallocate(void)
96 for (auto &mem_alloc : _mem_alloc_map)
98 // Release memory buffer of mem_alloc
99 mem_alloc.second->release();
102 _mem_alloc_map.clear();
105 } // namespace cpu_common
106 } // namespace backend