1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/compiler/xla/service/cpu/external_constant_pool.h"
17
18#include <algorithm>
19#include <cstdlib>
20#include <cstring>
21
22#include "tensorflow/compiler/xla/map_util.h"
23#include "tensorflow/compiler/xla/ptr_util.h"
24#include "tensorflow/compiler/xla/shape_util.h"
25#include "tensorflow/core/lib/gtl/flatset.h"
26
27namespace xla {
28namespace cpu {
29void ExternalConstantPool::Insert(string name, const Literal& literal,
30                                  int64 alignment) {
31  CHECK(!ShapeUtil::IsTuple(literal.shape()));
32  CHECK(alignment > 0 && IsPowerOfTwo(static_cast<uint64>(alignment)));
33  CHECK(entries_.find(name) == entries_.end());
34
35  int64 literal_size = ShapeUtil::ByteSizeOf(literal.shape());
36  void* raw_pointer = tensorflow::port::AlignedMalloc(
37      literal_size, std::max<size_t>(alignment, sizeof(void*)));
38  CHECK(raw_pointer != nullptr) << "failed to allocate " << literal_size
39                                << " bytes with alignment of " << alignment;
40
41  std::memcpy(raw_pointer, literal.untyped_data(), literal_size);
42  entries_.emplace(std::move(name), static_cast<uint8*>(raw_pointer));
43}
44
45const uint8* ExternalConstantPool::Find(const string& name) {
46  auto it = entries_.find(name);
47  return it == entries_.end() ? nullptr : it->second.get();
48}
49}  // namespace cpu
50}  // namespace xla
51