1 /* Copyright 2017 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/service/hlo_opcode.h"
17 #include "absl/container/flat_hash_map.h"
18 #include "tensorflow/compiler/xla/types.h"
19 #include "tensorflow/compiler/xla/util.h"
20 
21 namespace xla {
22 
HloOpcodeString(HloOpcode opcode)23 string HloOpcodeString(HloOpcode opcode) {
24   switch (opcode) {
25 #define CASE_OPCODE_STRING(enum_name, opcode_name, ...) \
26   case HloOpcode::enum_name:                            \
27     return opcode_name;
28     HLO_OPCODE_LIST(CASE_OPCODE_STRING)
29 #undef CASE_OPCODE_STRING
30   }
31 }
32 
StringToHloOpcode(const string & opcode_name)33 StatusOr<HloOpcode> StringToHloOpcode(const string& opcode_name) {
34   static auto* opcode_map = new absl::flat_hash_map<string, HloOpcode>({
35 #define STRING_TO_OPCODE_ENTRY(enum_name, opcode_name, ...) \
36   {opcode_name, HloOpcode::enum_name},
37       HLO_OPCODE_LIST(STRING_TO_OPCODE_ENTRY)
38 #undef STRING_TO_OPCODE_ENTRY
39   });
40   auto it = opcode_map->find(opcode_name);
41   if (it == opcode_map->end()) {
42     return InvalidArgument("Unknown opcode: %s", opcode_name);
43   }
44   return it->second;
45 }
46 
HloOpcodeIsComparison(HloOpcode opcode)47 bool HloOpcodeIsComparison(HloOpcode opcode) {
48   return opcode == HloOpcode::kCompare;
49 }
50 
HloOpcodeIsVariadic(HloOpcode opcode)51 bool HloOpcodeIsVariadic(HloOpcode opcode) {
52   switch (opcode) {
53 #define CASE_IS_VARIADIC(enum_name, opcode_name, arity, ...) \
54   case HloOpcode::enum_name:                                 \
55     return arity == kHloOpcodeIsVariadic;
56     HLO_OPCODE_LIST(CASE_IS_VARIADIC)
57 #undef CASE_IS_VARIADIC
58   }
59 }
60 
HloOpcodeArity(HloOpcode opcode)61 absl::optional<int> HloOpcodeArity(HloOpcode opcode) {
62   switch (opcode) {
63 #define CASE_ARITY(enum_name, opcode_name, arity, ...)   \
64   case HloOpcode::enum_name:                             \
65     return arity == kHloOpcodeIsVariadic ? absl::nullopt \
66                                          : absl::make_optional(arity);
67     HLO_OPCODE_LIST(CASE_ARITY)
68 #undef CASE_ARITY
69   }
70 }
71 
72 }  // namespace xla
73