1 /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/compiler/xla/shape_tree.h"
17
18 namespace xla {
19 namespace internal {
20
IndexTable(const Shape & shape)21 IndexTable::IndexTable(const Shape& shape) : entries_(1) {
22 size_t next_node_id = 0;
23 CreateEntry(entries_[0], shape, next_node_id);
24 }
25
26 // TODO(cjfj): Index table cache?.
CreateEntry(Entry & entry,const Shape & shape,size_t & next_node_id)27 void IndexTable::CreateEntry(Entry& entry, const Shape& shape,
28 size_t& next_node_id) {
29 entry.node_id = next_node_id++;
30 if (!shape.IsTuple()) return;
31
32 // The nodes are in depth-first pre-order. However, in order to efficiently
33 // lookup indices, we generate the index table using breadth-first.
34 size_t children_start_id = entries_.size();
35 entry.children_start_id = children_start_id;
36 // Add entry for children first, before recursing, so they are consecutive.
37 entries_.resize(entries_.size() + shape.tuple_shapes_size());
38 for (size_t i = 0; i < shape.tuple_shapes_size(); ++i) {
39 CreateEntry(entries_[children_start_id + i], shape.tuple_shapes(i),
40 next_node_id);
41 }
42 }
43
operator [](ShapeIndexView index) const44 const IndexTable::Entry& IndexTable::operator[](ShapeIndexView index) const {
45 const Entry* result = &entries_.front();
46 for (int64_t i : index) {
47 CHECK_GE(result->children_start_id, 0);
48 result = &entries_[result->children_start_id + i];
49 }
50 return *result;
51 }
52
53 } // namespace internal
54 } // namespace xla
55