luclima commited on
Commit
b98801e
·
verified ·
1 Parent(s): 23d7891

Upload folder using huggingface_hub (part 50)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. western_ai/usa/tensorflow/tensorflow/compiler/OWNERS_FORCE_SUBMIT_APPROVERS +19 -0
  2. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.cc +183 -0
  3. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.h +119 -0
  4. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async.mlir +15 -0
  5. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async2.mlir +16 -0
  6. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic.mlir +13 -0
  7. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic_attributes.mlir +30 -0
  8. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/custom_attributes.mlir +13 -0
  9. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/unsupported_attributes.mlir +5 -0
  10. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.cc +96 -0
  11. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.h +210 -0
  12. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.cc +75 -0
  13. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.h +36 -0
  14. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.cc +56 -0
  15. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.h +36 -0
  16. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/BUILD +58 -0
  17. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/BUILD +267 -0
  18. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.proto +10 -0
  19. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/hlo_to_kernel.cc +250 -0
  20. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/BUILD +81 -0
  21. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc +174 -0
  22. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h +69 -0
  23. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.td +335 -0
  24. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.td +81 -0
  25. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.cc +506 -0
  26. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h +58 -0
  27. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/BUILD +27 -0
  28. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/broadcast_propagation.mlir +224 -0
  29. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_deallocation.mlir +31 -0
  30. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_reuse.mlir +541 -0
  31. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/bufferize.mlir +20 -0
  32. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/copy_cleanup.mlir +188 -0
  33. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/embed_tf_framework.mlir +86 -0
  34. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/func_to_jit_invocations.mlir +174 -0
  35. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/BUILD +31 -0
  36. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2.mlir +132 -0
  37. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2_unsigned.mlir +132 -0
  38. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/minimum.mlir +132 -0
  39. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/tanh.mlir +11 -0
  40. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/invalid.mlir +7 -0
  41. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/isinf.mlir +19 -0
  42. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/legalize_tensor_reshape.mlir +14 -0
  43. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/merge_assuming_ops.mlir +348 -0
  44. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/ops.mlir +115 -0
  45. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/parallel_loops_to_sequential.mlir +17 -0
  46. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/rewrite_tf_framework_assert.mlir +63 -0
  47. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/shape_simplification.mlir +143 -0
  48. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_abi_knowledge.mlir +355 -0
  49. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_framework_legalize_to_llvm.mlir +249 -0
  50. western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_kernel_gpu_launch_to_llvm.mlir +36 -0
western_ai/usa/tensorflow/tensorflow/compiler/OWNERS_FORCE_SUBMIT_APPROVERS ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file contains the list of senior ICs in the XLA team who can
2
+ # approve force submits in addition to manager approval. See
3
+ # go/foundations-force-submit-policy for full policy.
4
+
5
+ // go/keep-sorted start
6
+ andydavis
7
+ asabne
8
+ berkin
9
+ chenyin
10
+ jikimjikim
11
+ jsreeram
12
+ ksmurthy
13
+ majnemer
14
+ masonchang
15
+ mkuper
16
+ pifon
17
+ pizzud
18
+ // go/keep-sorted end
19
+
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.cc ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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
+ #include "tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.h"
16
+
17
+ #include <algorithm>
18
+ #include <cstdint>
19
+ #include <cstring>
20
+ #include <numeric>
21
+ #include <string>
22
+ #include <utility>
23
+ #include <vector>
24
+
25
+ #include "absl/status/status.h"
26
+ #include "absl/status/statusor.h"
27
+ #include "absl/strings/str_cat.h"
28
+ #include "xla/tsl/platform/errors.h"
29
+ #include "xla/tsl/platform/statusor.h"
30
+ #include "tensorflow/core/framework/attr_value.pb.h"
31
+ #include "tensorflow/core/framework/node_def_util.h"
32
+ #include "tensorflow/core/framework/tensor.h"
33
+ #include "tensorflow/core/tfrt/mlrt/attribute/attribute.h"
34
+ #include "tensorflow/core/tfrt/mlrt/bytecode/bytecode.h"
35
+ #include "tensorflow/core/tfrt/mlrt/bytecode/kernel.h"
36
+ #include "tensorflow/core/tfrt/mlrt/interpreter/context.h"
37
+ #include "tensorflow/core/tfrt/mlrt/interpreter/interpreter_testutil.h"
38
+
39
+ namespace mlrt {
40
+ namespace testing {
41
+
42
+ absl::StatusOr<std::string> EncodeAttribute(const tensorflow::AttrValue& attr) {
43
+ if (attr.has_b()) {
44
+ std::string result;
45
+ result.resize(sizeof(uint8_t));
46
+ uint8_t v = attr.b();
47
+ std::memcpy(result.data(), &v, sizeof(v));
48
+ return result;
49
+ }
50
+
51
+ if (attr.has_i()) {
52
+ std::string result;
53
+ result.resize(sizeof(int64_t));
54
+ int64_t v = attr.i();
55
+ std::memcpy(result.data(), &v, sizeof(v));
56
+ return result;
57
+ }
58
+
59
+ if (attr.has_f()) {
60
+ std::string result;
61
+ result.resize(sizeof(float));
62
+ float v = attr.f();
63
+ std::memcpy(result.data(), &v, sizeof(v));
64
+ return result;
65
+ }
66
+
67
+ if (attr.has_s()) {
68
+ return attr.s();
69
+ }
70
+
71
+ if (attr.has_list()) {
72
+ if (attr.list().s_size() > 0) {
73
+ mlrt::bc::Buffer buffer;
74
+ mlrt::bc::Allocator allocator(&buffer);
75
+ auto ctor = mlrt::bc::New<mlrt::bc::Vector<mlrt::bc::String>>(
76
+ &allocator, attr.list().s_size());
77
+
78
+ for (int i = 0; i < attr.list().s_size(); ++i) {
79
+ ctor.ConstructAt(i, attr.list().s(i));
80
+ }
81
+
82
+ return std::string(buffer.data(), buffer.size());
83
+ }
84
+ }
85
+
86
+ if (attr.has_tensor()) {
87
+ mlrt::bc::Buffer buffer;
88
+ mlrt::bc::Allocator allocator(&buffer);
89
+
90
+ tensorflow::Tensor tensor;
91
+ if (!tensor.FromProto(attr.tensor())) {
92
+ return absl::InvalidArgumentError("Invalid tensor proto.");
93
+ }
94
+
95
+ auto tensor_attr_ctor = mlrt::bc::New<tensorflow::tf_mlrt::TensorAttr>(
96
+ &allocator, tensor.dtype());
97
+
98
+ auto shape = tensor.shape().dim_sizes();
99
+
100
+ tensor_attr_ctor.construct_shape(shape.size())
101
+ .Assign(shape.begin(), shape.end());
102
+
103
+ auto tensor_data = tensor.tensor_data();
104
+ tensor_attr_ctor.construct_data(tensor_data.size())
105
+ .Place(tensor_data.data(), tensor_data.size());
106
+
107
+ return std::string(buffer.data(), buffer.size());
108
+ }
109
+
110
+ // TODO(chky,rohitju): Add more attribute support.
111
+
112
+ return absl::InvalidArgumentError("Unsupported attribute.");
113
+ }
114
+
115
+ namespace {
116
+
117
+ bool CanBeInlined(const tensorflow::AttrValue& attr) {
118
+ return attr.has_b() || attr.has_f();
119
+ }
120
+
121
+ } // namespace
122
+
123
+ absl::Status EncodeAttributes(AttributeTable& attributes,
124
+ const tensorflow::AttrValueMap& attr_map) {
125
+ std::vector<std::pair<std::string, tensorflow::AttrValue>> attrs(
126
+ attr_map.begin(), attr_map.end());
127
+ std::sort(attrs.begin(), attrs.end(),
128
+ [](const auto& x, const auto& y) { return x.first < y.first; });
129
+
130
+ for (int i = 0; i < attrs.size(); ++i) {
131
+ const tensorflow::AttrValue& attr = attrs[i].second;
132
+ TF_ASSIGN_OR_RETURN(auto attr_str, EncodeAttribute(attr));
133
+ if (CanBeInlined(attr)) {
134
+ attributes.AddInline(absl::StrCat(i), attr_str);
135
+ } else {
136
+ attributes.Add(absl::StrCat(i), attr_str);
137
+ }
138
+ }
139
+
140
+ return absl::OkStatus();
141
+ }
142
+
143
+ absl::StatusOr<std::pair<mlrt::bc::Kernel, mlrt::bc::Vector<mlrt::bc::String>>>
144
+ CreateKernelAndAttrs(int num_inputs, int num_outputs,
145
+ mlrt::ExecutionContext& exec_ctx, mlrt::bc::Buffer* buffer,
146
+ const tensorflow::AttrValueMap& attrs) {
147
+ mlrt::bc::Allocator allocator(buffer);
148
+ auto attributes_ctor = mlrt::bc::New<mlrt::bc::Vector<mlrt::bc::String>>(
149
+ &allocator, attrs.size());
150
+ AttributeTable attribute_table(attributes_ctor);
151
+ TF_RETURN_IF_ERROR(EncodeAttributes(attribute_table, attrs));
152
+
153
+ auto kernel_ctor = mlrt::bc::New<mlrt::bc::Kernel>(&allocator);
154
+ kernel_ctor.set_code(0);
155
+
156
+ std::vector<int> input_indices(num_inputs);
157
+ std::iota(input_indices.begin(), input_indices.end(), 0);
158
+ kernel_ctor.construct_arguments(input_indices.size())
159
+ .Assign(input_indices.begin(), input_indices.end());
160
+
161
+ std::vector<int> output_indices(num_outputs);
162
+ std::iota(output_indices.begin(), output_indices.end(), num_inputs);
163
+ kernel_ctor.construct_results(output_indices.size())
164
+ .Assign(output_indices.begin(), output_indices.end());
165
+
166
+ std::vector<uint32_t> attr_indices;
167
+ attr_indices.reserve(attrs.size());
168
+ for (int i = 0; i < attrs.size(); ++i) {
169
+ attr_indices.push_back(attribute_table.GetHandle(absl::StrCat(i)));
170
+ }
171
+
172
+ kernel_ctor.construct_attributes(attr_indices.size())
173
+ .Assign(attr_indices.begin(), attr_indices.end());
174
+
175
+ mlrt::bc::Vector<mlrt::bc::String> attributes(
176
+ buffer->Get(attributes_ctor.address()));
177
+ mlrt::bc::Kernel kernel(buffer->Get(kernel_ctor.address()));
178
+
179
+ return std::make_pair(kernel, attributes);
180
+ }
181
+
182
+ } // namespace testing
183
+ } // namespace mlrt
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.h ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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
+ #ifndef TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_MLRT_TEST_UTILS_H_
16
+ #define TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_MLRT_TEST_UTILS_H_
17
+
18
+ #include <memory>
19
+ #include <numeric>
20
+ #include <string>
21
+ #include <utility>
22
+ #include <vector>
23
+
24
+ #include "absl/status/status.h"
25
+ #include "absl/status/statusor.h"
26
+ #include "absl/strings/str_cat.h"
27
+ #include "absl/strings/string_view.h"
28
+ #include "absl/types/span.h"
29
+ #include "xla/tsl/platform/errors.h"
30
+ #include "xla/tsl/platform/statusor.h"
31
+ #include "tensorflow/core/framework/attr_value.pb.h"
32
+ #include "tensorflow/core/framework/node_def_util.h"
33
+ #include "tensorflow/core/framework/tensor.h"
34
+ #include "tensorflow/core/tfrt/graph_executor/sync_resource_state.h"
35
+ #include "tensorflow/core/tfrt/mlrt/attribute/attribute.h"
36
+ #include "tensorflow/core/tfrt/mlrt/bytecode/bytecode.h"
37
+ #include "tensorflow/core/tfrt/mlrt/bytecode/kernel.h"
38
+ #include "tensorflow/core/tfrt/mlrt/interpreter/context.h"
39
+ #include "tensorflow/core/tfrt/mlrt/interpreter/interpreter_testutil.h"
40
+ #include "tensorflow/core/tfrt/mlrt/interpreter/value.h"
41
+ #include "tensorflow/core/tfrt/stubs/tfrt_native_lowering_stub.h"
42
+ #include "tensorflow/core/tfrt/utils/tensor_util.h"
43
+ #include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime
44
+ #include "tfrt/host_context/execution_context.h" // from @tf_runtime
45
+ #include "tfrt/host_context/host_allocator.h" // from @tf_runtime
46
+ #include "tfrt/host_context/host_context.h" // from @tf_runtime
47
+ #include "tfrt/support/string_util.h" // from @tf_runtime
48
+ #include "tfrt/tensor/dense_host_tensor.h" // from @tf_runtime
49
+ #include "tfrt/tensor/dense_tensor_utils.h" // from @tf_runtime
50
+
51
+ namespace mlrt {
52
+ namespace testing {
53
+
54
+ absl::StatusOr<std::string> EncodeAttribute(const tensorflow::AttrValue& attr);
55
+
56
+ absl::Status EncodeAttributes(AttributeTable& attributes,
57
+ const tensorflow::AttrValueMap& attr_map);
58
+
59
+ absl::StatusOr<std::pair<mlrt::bc::Kernel, mlrt::bc::Vector<mlrt::bc::String>>>
60
+ CreateKernelAndAttrs(int num_inputs, int num_outputs,
61
+ mlrt::ExecutionContext& exec_ctx, mlrt::bc::Buffer* buffer,
62
+ const tensorflow::AttrValueMap& attrs = {});
63
+
64
+ template <typename T>
65
+ absl::Status TestMlrtKernel(
66
+ absl::string_view kernel_name, absl::Span<mlrt::Value> regs,
67
+ tfrt::HostContext* host, int num_inputs, int num_outputs,
68
+ absl::Span<const tensorflow::Tensor> expected_outputs,
69
+ mlrt::KernelRegistry* registry, bool approx_equal = false,
70
+ const tensorflow::AttrValueMap& attrs = {}) {
71
+ mlrt::ExecutionContext execution_context(nullptr);
72
+
73
+ mlrt::bc::Buffer buffer;
74
+ TF_ASSIGN_OR_RETURN(auto kernel_and_attrs,
75
+ CreateKernelAndAttrs(num_inputs, num_outputs,
76
+ execution_context, &buffer, attrs));
77
+
78
+ tensorflow::tfrt_stub::SyncResourceState sync_resource_state;
79
+ tfrt::AddSyncContext(execution_context, *host, &sync_resource_state);
80
+
81
+ auto kernel_fn = registry->Get(kernel_name);
82
+ mlrt::KernelFrame::State state(regs, kernel_and_attrs.second,
83
+ &execution_context);
84
+ mlrt::KernelFrame frame(&state);
85
+ frame.set_kernel(kernel_and_attrs.first);
86
+
87
+ kernel_fn(frame);
88
+
89
+ TF_RETURN_IF_ERROR(execution_context.status());
90
+
91
+ for (int i = 0, j = num_inputs; i < expected_outputs.size(); ++i, ++j) {
92
+ const auto& expected_output = expected_outputs[i];
93
+ auto expected_dht = tfrt::ConvertTfTensorToDHT(expected_output);
94
+ if (!expected_dht) {
95
+ return absl::InternalError(tfrt::StrCat(expected_dht.takeError()));
96
+ }
97
+
98
+ if (!approx_equal) {
99
+ if (!tfrt::TensorEqual<T>(regs[j].Get<tfrt::DenseHostTensor>(),
100
+ *expected_dht)) {
101
+ return absl::InternalError(
102
+ absl::StrCat("wrong result for ", kernel_name));
103
+ }
104
+ } else {
105
+ if (!tfrt::TensorApproxEqual<T>(regs[j].Get<tfrt::DenseHostTensor>(),
106
+ *expected_dht)) {
107
+ return absl::InternalError(
108
+ absl::StrCat("wrong result for ", kernel_name));
109
+ }
110
+ }
111
+ }
112
+
113
+ return absl::OkStatus();
114
+ }
115
+
116
+ } // namespace testing
117
+ } // namespace mlrt
118
+
119
+ #endif // TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_MLRT_TEST_UTILS_H_
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async.mlir ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ func.func @add_i32(%arg0: i32, %arg1: i32) -> i32 {
2
+ %0 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32
3
+ func.return %0 : i32
4
+ }
5
+
6
+ func.func @main(%arg0: i32, %arg1: i32) -> i32 {
7
+ %handle = "mlrt.async"(%arg0, %arg1) {callee = @add_i32} : (i32, i32) -> !mlrt.async_handle
8
+
9
+ "mlrt.await_handle"(%handle) : (!mlrt.async_handle) -> ()
10
+
11
+ %c1 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32
12
+ %c2 = "test_mlbc.add.i32"(%c1, %c1) : (i32, i32) -> i32
13
+
14
+ func.return %c2 : i32
15
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async2.mlir ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ func.func @add_i32(%arg0: i32, %arg1: i32) -> i32 {
2
+ %0 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32
3
+ func.return %0 : i32
4
+ }
5
+
6
+ func.func @main(%arg0: i32, %arg1: i32) -> i32 {
7
+ %c1 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32
8
+
9
+ %handle = "mlrt.async"(%c1, %c1) {callee = @add_i32} : (i32, i32) -> !mlrt.async_handle
10
+
11
+ "mlrt.await_handle"(%handle) : (!mlrt.async_handle) -> ()
12
+
13
+ %c2 = "test_mlbc.add.i32"(%c1, %c1) : (i32, i32) -> i32
14
+
15
+ func.return %c2 : i32
16
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic.mlir ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ func.func @add_i32_10(%c0: i32) -> (i32, i32, i32) {
2
+ %c1 = "test_mlbc.add.i32"(%c0, %c0) : (i32, i32) -> i32
3
+ %c2 = "test_mlbc.sub.i32"(%c1, %c0) : (i32, i32) -> i32
4
+ %c3 = "test_mlbc.add.i32"(%c2, %c0) : (i32, i32) -> i32
5
+ %c4 = "test_mlbc.sub.i32"(%c3, %c0) : (i32, i32) -> i32
6
+ %c5 = "test_mlbc.add.i32"(%c4, %c0) : (i32, i32) -> i32
7
+ %c6 = "test_mlbc.sub.i32"(%c5, %c0) : (i32, i32) -> i32
8
+ %c7 = "test_mlbc.add.i32"(%c6, %c0) : (i32, i32) -> i32
9
+ %c8 = "test_mlbc.sub.i32"(%c7, %c0) : (i32, i32) -> i32
10
+ %c9 = "test_mlbc.add.i32"(%c8, %c0) : (i32, i32) -> i32
11
+ %c10, %c11, %c12 = call @add_i32_10(%c9) : (i32) -> (i32, i32, i32)
12
+ func.return %c0, %c10, %c10 : i32, i32, i32
13
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic_attributes.mlir ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ func.func @simple_attributes() {
2
+ "test_custom.attribute"() {value = "test string"} : () -> ()
3
+ "test_custom.attribute"() {value = "ts"} : () -> ()
4
+ "test_custom.attribute"() {value = 100 : i32} : () -> ()
5
+ "test_custom.attribute"() {value = 200 : i64} : () -> ()
6
+ "test_custom.attribute"() {value = 3.0 : f32} : () -> ()
7
+ "test_custom.attribute"() {value = false} : () -> ()
8
+ "test_custom.attribute"() {value = [0, 1, 2, 3, 4]} : () -> ()
9
+ "test_custom.attribute"() {value = [0 : i32, 1 : i32, 2 : i32, 3 : i32]} : () -> ()
10
+ "test_custom.attribute"() {value = ["string 0", "string 1"]} : () -> ()
11
+ "test_custom.attribute"() {value = @callee} : () -> ()
12
+ "test_custom.attribute"() {value = [@callee0, @callee1]} : () -> ()
13
+ "test_custom.attribute"() {value = array<i32: 0, 1, 2>} : () -> ()
14
+ "test_custom.attribute"() {value = array<i64: 0, 1, 2>} : () -> ()
15
+ "test_custom.attribute"() {value = array<i32>} : () -> ()
16
+ "test_custom.attribute"() {value = array<i1: true, false>} : () -> ()
17
+ func.return
18
+ }
19
+
20
+ func.func @callee() {
21
+ return
22
+ }
23
+
24
+ func.func @callee0() {
25
+ return
26
+ }
27
+
28
+ func.func @callee1() {
29
+ return
30
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/custom_attributes.mlir ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ func.func @add_const_custom_dense_i32_10(%c0: i32) -> i32 {
2
+ %c1 = "test_custom.add.const.i32"(%c0) {value = dense<[0]> : tensor<1xi32>} : (i32) -> i32
3
+ %c2 = "test_custom.add.const.i32"(%c1) {value = dense<[1]> : tensor<1xi32>} : (i32) -> i32
4
+ %c3 = "test_custom.add.const.i32"(%c2) {value = dense<[2]> : tensor<1xi32>} : (i32) -> i32
5
+ %c4 = "test_custom.add.const.i32"(%c3) {value = dense<[3]> : tensor<1xi32>} : (i32) -> i32
6
+ %c5 = "test_custom.add.const.i32"(%c4) {value = dense<[4]> : tensor<1xi32>} : (i32) -> i32
7
+ %c6 = "test_custom.add.const.i32"(%c5) {value = dense<[5]> : tensor<1xi32>} : (i32) -> i32
8
+ %c7 = "test_custom.add.const.i32"(%c6) {value = dense<[6]> : tensor<1xi32>} : (i32) -> i32
9
+ %c8 = "test_custom.add.const.i32"(%c7) {value = dense<[7]> : tensor<1xi32>} : (i32) -> i32
10
+ %c9 = "test_custom.add.const.i32"(%c8) {value = dense<[8]> : tensor<1xi32>} : (i32) -> i32
11
+ %c10 = "test_custom.add.const.i32"(%c9) {value = dense<[9]> : tensor<1xi32>} : (i32) -> i32
12
+ func.return %c10 : i32
13
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/unsupported_attributes.mlir ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ func.func @unsupported_attributes() {
2
+ "test_custom.attribute"() {unit} : () -> ()
3
+ func.return
4
+ }
5
+
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.cc ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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/mlir/tfrt/translate/tfrt_compile_options.h"
17
+
18
+ #include <ostream>
19
+
20
+ #include "absl/strings/str_join.h"
21
+
22
+ namespace tensorflow {
23
+
24
+ std::ostream& operator<<(std::ostream& os,
25
+ TfrtDeviceInfraTarget device_target) {
26
+ switch (device_target) {
27
+ case TfrtDeviceInfraTarget::kCpu:
28
+ return os << "Cpu";
29
+ case TfrtDeviceInfraTarget::kTpurt:
30
+ return os << "Tpurt";
31
+ case TfrtDeviceInfraTarget::kTfFallback:
32
+ return os << "TfFallback";
33
+ case TfrtDeviceInfraTarget::kBridgeFallback:
34
+ return os << "BridgeFallback";
35
+ case TfrtDeviceInfraTarget::kGpu:
36
+ return os << "Gpu";
37
+ }
38
+ }
39
+
40
+ std::ostream& operator<<(std::ostream& os, const TfrtCompileOptions& options) {
41
+ return os << "{" << "variable_device = " << options.variable_device
42
+ << ", default_device = " << options.default_device
43
+ << ", enable_optimizer = " << options.enable_optimizer
44
+ << ", enable_grappler = " << options.enable_grappler
45
+ << ", force_data_format = " << options.force_data_format
46
+ << ", device_target = " << options.device_target
47
+ << ", tpu_fuse_ops = " << options.tpu_fuse_ops
48
+ << ", tpu_move_resource_gather_to_host = "
49
+ << options.tpu_move_resource_gather_to_host
50
+ << ", tpu_gather_table_width_threshold_bytes = "
51
+ << options.tpu_gather_table_width_threshold_bytes
52
+ << ", use_tpu_host_allocator_for_inputs = "
53
+ << options.use_tpu_host_allocator_for_inputs
54
+ << ", hoist_invariant_ops = " << options.hoist_invariant_ops
55
+ << ", enable_while_parallel_iterations = "
56
+ << options.enable_while_parallel_iterations
57
+ << ", cost_threshold = " << options.cost_threshold
58
+ << ", min_num_batch_threads = " << options.min_num_batch_threads
59
+ << ", min_max_enqueued_batches = "
60
+ << options.min_max_enqueued_batches
61
+ << ", batch_padding_policy = " << options.batch_padding_policy
62
+ << ", num_batch_threads = "
63
+ << options.batch_options.num_batch_threads()
64
+ << ", max_batch_size = " << options.batch_options.max_batch_size()
65
+ << ", batch_timeout_micros = "
66
+ << options.batch_options.batch_timeout_micros()
67
+ << ", allowed_batch_sizes = "
68
+ << absl::StrJoin(options.batch_options.allowed_batch_sizes(), ",")
69
+ << ", max_enqueued_batches = "
70
+ << options.batch_options.max_enqueued_batches()
71
+ << ", low_priority_max_batch_size = "
72
+ << options.batch_options.low_priority_max_batch_size()
73
+ << ", low_priority_batch_timeout_micros = "
74
+ << options.batch_options.low_priority_batch_timeout_micros()
75
+ << ", low_priority_allowed_batch_sizes = "
76
+ << absl::StrJoin(
77
+ options.batch_options.low_priority_allowed_batch_sizes(),
78
+ ",")
79
+ << ", low_priority_max_enqueued_batches = "
80
+ << options.batch_options.low_priority_max_enqueued_batches()
81
+ << ", num_warmup_batch_threads = "
82
+ << options.batch_options.num_warmup_batch_threads()
83
+ << ", enable_large_batch_splitting = "
84
+ << options.batch_options.enable_large_batch_splitting()
85
+ << ", mixed_priority_batching_policy = "
86
+ << options.batch_options.mixed_priority_batching_policy()
87
+ << ", merge_inter_dependent_streams = "
88
+ << options.merge_inter_dependent_streams
89
+ << ", decompose_resource_ops = " << options.decompose_resource_ops
90
+ << ", compile_to_sync_tfrt_dialect = "
91
+ << options.compile_to_sync_tfrt_dialect
92
+ << ", batch_queue_global_prioritization_num_threads = "
93
+ << options.batch_queue_global_prioritization_num_threads << "}";
94
+ }
95
+
96
+ } // namespace tensorflow
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.h ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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
+ #ifndef TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_TFRT_COMPILE_OPTIONS_H_
17
+ #define TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_TFRT_COMPILE_OPTIONS_H_
18
+
19
+ #include <cstdint>
20
+ #include <iosfwd>
21
+ #include <ostream>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "tensorflow/core/protobuf/config.pb.h"
26
+
27
+ namespace tensorflow {
28
+
29
+ class BackendCompiler;
30
+
31
+ enum class TfrtDeviceInfraTarget {
32
+ kCpu, // CPU only, no device support.
33
+ kTpurt, // Target TPURT dialect and kernels.
34
+ kTfFallback, // Target TPU kernels in TF Fallback.
35
+ kBridgeFallback, // TPU support but choose kTpurt or kTfFallback depending on
36
+ // whether the graph has unsupported feature in Bridge.
37
+ kGpu, // Target GPU specific compiler passes and runtime
38
+ // initializations.
39
+ };
40
+
41
+ std::ostream& operator<<(std::ostream& os, TfrtDeviceInfraTarget device_target);
42
+
43
+ struct TfrtCompileOptions {
44
+ std::string saved_model_dir;
45
+ // TODO(tfrt-devs): Ideally, compiler should make the decision where
46
+ // to place the variable.
47
+ std::string variable_device = "/job:localhost/replica:0/task:0/device:CPU:0";
48
+ std::string default_device = "/job:localhost/replica:0/task:0/device:CPU:0";
49
+
50
+ // Enable compiler optimization in TFRT dialect.
51
+ bool enable_optimizer = true;
52
+
53
+ // If true, run grappler passes before compiling.
54
+ bool enable_grappler = true;
55
+
56
+ // Graph rewrite options that will be applied on GraphDef before converting to
57
+ // MLIR.
58
+ GraphOptions graph_options;
59
+
60
+ // Force data format for all layout sensitive operations, eg. setting it to
61
+ // "NHWC" will changes all data format in the graph to "NHWC" by inserting
62
+ // or removing related tf.Transpose op. Currently the supported formats are
63
+ // "NHWC" and "NCHW".
64
+ //
65
+ // TODO(tfrt-devs): Ideally compiler should figure out whether the
66
+ // data format should be changed, instead of controlled by users.
67
+ std::string force_data_format;
68
+
69
+ // The target device infrastructure to use. This will trigger target specific
70
+ // compiler passes and runtime initialization.
71
+ TfrtDeviceInfraTarget device_target = TfrtDeviceInfraTarget::kCpu;
72
+
73
+ // The custom compiler for device compilation. Instead of using the enum above
74
+ // to choose predefined device target, users can use this `backend_compiler`
75
+ // to inject their customized implementation.
76
+ BackendCompiler* backend_compiler = nullptr;
77
+
78
+ // If true, use the fused TPU compile_and_execute kernel, which performs all
79
+ // TPU inference related operations, e.g. core selection, h2d/d2h transfers,
80
+ // compile and execute.
81
+ bool tpu_fuse_ops = false;
82
+
83
+ // If true, resource gather ops in the device graph are moved to host graphs
84
+ // in order to saved TPU memory usage. This option is experimental.
85
+ bool tpu_move_resource_gather_to_host = false;
86
+
87
+ // The threshold in bytes that controls whether a resource gather op on TPU
88
+ // should be moved to host. A negative value means there is no threshold. This
89
+ // option is experimental.
90
+ int64_t tpu_gather_table_width_threshold_bytes = -1;
91
+
92
+ // If true, fallback executeops that produce inputs to tpu program will use
93
+ // tpu host allocator. This options is experimental.
94
+ bool use_tpu_host_allocator_for_inputs = false;
95
+
96
+ // To allow unpadded batch for TPU execution.
97
+ enum class TpuAllowUnpaddedBatch {
98
+ // Disable this feature.
99
+ kDisabled,
100
+ // Enable this feature when in-graph batching is detected.
101
+ kAuto,
102
+ // Force to enable this feature.
103
+ kEnforced,
104
+ };
105
+ TpuAllowUnpaddedBatch tpu_allow_unpadded_batch =
106
+ TpuAllowUnpaddedBatch::kDisabled;
107
+
108
+ // If true, the compiler will try to hoist invariant ops (e.g., const ops and
109
+ // their non-side-effecting consumers) to loading phase, which avoids the
110
+ // runtime cost during later running.
111
+ // TODO(tfrt-devs): Set the default value to true after testing as it is
112
+ // supposed to be turned on by default.
113
+ bool hoist_invariant_ops = false;
114
+
115
+ // If true, get_resource_op will be fused during hoisting.
116
+ bool fuse_get_resource_ops_in_hoisting = true;
117
+
118
+ // If true, the compiler will try to sink in the invariant ops (e.g. const
119
+ // ops, var handle ops, etc.) to the nested function (e.g. batch function) to
120
+ // facilitate invariant ops hoisting.
121
+ // TODO(tfrt-devs): Set the default value to true after testing as it is
122
+ // supposed to be turned on by default.
123
+ bool sink_in_invariant_ops = false;
124
+
125
+ // This flag behaves differently for TFRT and MLRT.
126
+ // For TFRT, if true, tf.While's iterations will be parallelized on a
127
+ // best-effort basis. This is currently experimental. MLRT attempts to convert
128
+ // tf.while to tf_mlrt.map_fn regardless of this flag. For tf.While that
129
+ // cannot be converted tf_mlrt.map_fn, MLRT try to parallelize tf.while's
130
+ // iterations on a best-effort basis.
131
+ bool enable_while_parallel_iterations = false;
132
+
133
+ // The cost threshold to decide whether a sequence of operations is cheap, and
134
+ // then whether it can be executed inline. If the cost is smaller than the
135
+ // threshold, it will be considered as cheap operations. Since the cost must
136
+ // be positive integers, setting the threshold to 1 makes all operations
137
+ // expensive.
138
+ uint64_t cost_threshold = 1;
139
+
140
+ // The minimum number of batch threads. This number provides a lower bound on
141
+ // the number of batch threads on top of what is specified in the model. If
142
+ // the number of batch threads is too small (e.g. smaller than the number of
143
+ // parallel hardware accelerator available), it can lead to under utilization
144
+ // of resources.
145
+ int64_t min_num_batch_threads = 1;
146
+
147
+ // The minimum of the maximum number of enqueued batches. This number provides
148
+ // a lower bound on top of what is specified in the model. If the number of
149
+ // max_enqueued_batches is too small, it can lead to under utilization of
150
+ // resources.
151
+ int64_t min_max_enqueued_batches = 1;
152
+
153
+ // If non-zero, all models on this server are switched to use a prioritized
154
+ // batching function using this number of global threads.
155
+ int64_t batch_queue_global_prioritization_num_threads = 0;
156
+
157
+ // If true, the queue implementation will have a separate subqueue for each
158
+ // criticality.
159
+ bool enable_priority_aware_batch_scheduler = false;
160
+
161
+ // If true, the queue implementation will resplit tasks for priority aware
162
+ // scheduling.
163
+ bool enable_priority_aware_batch_scheduler_resplit = false;
164
+
165
+ // If true, enable lazy cancellation filtering in the priority-aware batch
166
+ // scheduler.
167
+ bool enable_batching_task_lazy_cancellation = false;
168
+
169
+ // The policy used by a BatchScheduler to pad (or split) batches.
170
+ std::string batch_padding_policy;
171
+
172
+ // Batching parameters to be rewritten in the existing BatchFunction ops.
173
+ BatchingOptions batch_options;
174
+
175
+ // If true, streams with inter data dependencies will be preferred to be
176
+ // merged for inline execution.
177
+ bool merge_inter_dependent_streams = true;
178
+
179
+ // Whether to enable the DecomposeResourceOpsPass.
180
+ bool decompose_resource_ops = true;
181
+
182
+ // Whether to compile to sync TFRT dialect.
183
+ bool compile_to_sync_tfrt_dialect = false;
184
+
185
+ // Whether to use gpurt.compile_and_execute for GPU.
186
+ // TODO(b/294895431): Remove the flag and default to the fused op.
187
+ bool use_gpu_compile_and_execute_op = false;
188
+
189
+ // If true, MLIR module will be serialized to aot_packages.
190
+ bool serialize_mlir_module_to_aot_packages = false;
191
+
192
+ // Serialized MLIR module file under aot_packages.
193
+ std::string aot_mlir_module_file;
194
+
195
+ // If true, BEF will be serialized to aot_packages.
196
+ bool serialize_bef_to_aot_packages = false;
197
+
198
+ // Serialized BEF file under aot_packages.
199
+ std::string aot_bef_file;
200
+ // If true, use XLA:CPU for CPU computations.
201
+ bool allow_xla_cpu = true;
202
+ // If true, enable asynchronous IFRT execution.
203
+ bool enable_async_ifrt = false;
204
+ };
205
+
206
+ std::ostream& operator<<(std::ostream& os, const TfrtCompileOptions& options);
207
+
208
+ } // namespace tensorflow
209
+
210
+ #endif // TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_TFRT_COMPILE_OPTIONS_H_
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.cc ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2023 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
+ #include "tensorflow/compiler/mlir/tfrt/utils/export.h"
16
+
17
+ #include <memory>
18
+ #include <utility>
19
+
20
+ #include "absl/functional/any_invocable.h"
21
+ #include "absl/status/status.h"
22
+ #include "absl/strings/string_view.h"
23
+ #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
24
+ #include "mlir/IR/BuiltinOps.h" // from @llvm-project
25
+ #include "mlir/Pass/PassManager.h" // from @llvm-project
26
+ #include "mlir/Support/LogicalResult.h" // from @llvm-project
27
+ #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
28
+ #include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
29
+ #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
30
+ #include "tensorflow/compiler/mlir/tf2xla/api/v1/tf_dialect_to_executor.h"
31
+ #include "tensorflow/compiler/mlir/tf2xla/api/v2/tf_executor_to_graph.h"
32
+ #include "tensorflow/core/framework/function.pb.h"
33
+ #include "tsl/platform/errors.h"
34
+ #include "tsl/profiler/lib/traceme.h"
35
+
36
+ namespace tensorflow {
37
+
38
+ absl::Status ExportFunctionDefs(
39
+ mlir::ModuleOp module,
40
+ absl::AnyInvocable<absl::Status(tensorflow::FunctionDef)> callback,
41
+ bool export_tf_original_func_name) {
42
+ tsl::profiler::TraceMe traceme([&]() {
43
+ return tsl::profiler::TraceMeEncode(
44
+ "ExportFunctionDefs",
45
+ {{"module_name", absl::string_view(module.getName().value_or("?"))}});
46
+ });
47
+
48
+ TF_RETURN_IF_ERROR(
49
+ tensorflow::tf2xla::v1::ExportFromTensorflowDialectToExecutor(module));
50
+
51
+ {
52
+ mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
53
+
54
+ mlir::PassManager pm(module.getContext());
55
+ pm.addPass(mlir::CreateBreakUpIslandsPass());
56
+
57
+ if (mlir::failed(pm.run(module))) {
58
+ return diag_handler.ConsumeStatus();
59
+ }
60
+ }
61
+ tensorflow::GraphExportConfig configs;
62
+ configs.export_original_tf_func_name = export_tf_original_func_name;
63
+
64
+ for (auto func : module.getOps<mlir::func::FuncOp>()) {
65
+ tensorflow::FunctionDef function_def;
66
+ TF_RETURN_IF_ERROR(
67
+ tensorflow::tf2xla::v2::ConvertMlirFunctionToFunctionLibraryDef(
68
+ func, configs, &function_def));
69
+ TF_RETURN_IF_ERROR(callback(std::move(function_def)));
70
+ }
71
+
72
+ return absl::OkStatus();
73
+ }
74
+
75
+ } // namespace tensorflow
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2023 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
+ #ifndef TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_EXPORT_H_
16
+ #define TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_EXPORT_H_
17
+
18
+
19
+ #include "absl/functional/any_invocable.h"
20
+ #include "absl/status/status.h"
21
+ #include "mlir/IR/BuiltinOps.h" // from @llvm-project
22
+ #include "tensorflow/core/framework/function.pb.h"
23
+
24
+ namespace tensorflow {
25
+
26
+ // Exports every function in `module` into `tensorflow.FunctionDef` and calls
27
+ // `callback` for each `tensorflow.FunctionDef`. Modifies `module` in place to
28
+ // be suitable for FunctionDef export.
29
+ absl::Status ExportFunctionDefs(
30
+ mlir::ModuleOp module,
31
+ absl::AnyInvocable<absl::Status(tensorflow::FunctionDef)> callback,
32
+ bool export_tf_original_func_name = true);
33
+
34
+ } // namespace tensorflow
35
+
36
+ #endif // TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_EXPORT_H_
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.cc ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/mlir/tfrt/utils/host_context.h"
17
+
18
+ #include <cstdint>
19
+ #include <memory>
20
+
21
+ #include "absl/log/log.h"
22
+ #include "tensorflow/core/platform/logging.h"
23
+ #include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime
24
+ #include "tfrt/host_context/diagnostic.h" // from @tf_runtime
25
+ #include "tfrt/host_context/host_allocator.h" // from @tf_runtime
26
+ #include "tfrt/host_context/host_context.h" // from @tf_runtime
27
+
28
+ namespace tensorflow {
29
+
30
+ using ::tfrt::HostContext;
31
+
32
+ const char* const kDefaultHostDeviceName =
33
+ "/job:localhost/replica:0/task:0/device:CPU:0";
34
+
35
+ std::unique_ptr<HostContext> CreateSingleThreadedHostContext() {
36
+ return std::make_unique<HostContext>(
37
+ [](const tfrt::DecodedDiagnostic& diag) {
38
+ LOG(FATAL) << "Runtime error: " << diag.message() << "\n";
39
+ },
40
+ tfrt::CreateMallocAllocator(), tfrt::CreateSingleThreadedWorkQueue(),
41
+ kDefaultHostDeviceName);
42
+ }
43
+
44
+ std::unique_ptr<HostContext> CreateMultiThreadedHostContext(
45
+ int64_t num_threads) {
46
+ return std::make_unique<HostContext>(
47
+ [](const tfrt::DecodedDiagnostic& diag) {
48
+ LOG(FATAL) << "Runtime error: " << diag.message() << "\n";
49
+ },
50
+ tfrt::CreateMallocAllocator(),
51
+ tfrt::CreateMultiThreadedWorkQueue(num_threads,
52
+ /*num_blocking_threads=*/1),
53
+ kDefaultHostDeviceName);
54
+ }
55
+
56
+ } // namespace tensorflow
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_HOST_CONTEXT_H_
17
+ #define TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_HOST_CONTEXT_H_
18
+
19
+ #include <cstdint>
20
+ #include <memory>
21
+
22
+ #include "absl/base/attributes.h"
23
+ #include "tfrt/host_context/host_context.h" // from @tf_runtime
24
+
25
+ namespace tensorflow {
26
+
27
+ // The name of the default host device for running fallback kernels.
28
+ ABSL_CONST_INIT extern const char* const kDefaultHostDeviceName;
29
+
30
+ std::unique_ptr<tfrt::HostContext> CreateSingleThreadedHostContext();
31
+ std::unique_ptr<tfrt::HostContext> CreateMultiThreadedHostContext(
32
+ int64_t num_threads);
33
+
34
+ } // namespace tensorflow
35
+
36
+ #endif // TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_HOST_CONTEXT_H_
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/BUILD ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ load("@rules_cc//cc:cc_library.bzl", "cc_library")
2
+
3
+ package(
4
+ # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"],
5
+ default_visibility = [
6
+ "//visibility:public",
7
+ ],
8
+ licenses = ["notice"],
9
+ )
10
+
11
+ cc_library(
12
+ name = "translate_cl_options",
13
+ srcs = [
14
+ "tf_mlir_translate_cl.cc",
15
+ ],
16
+ hdrs = [
17
+ "tf_mlir_translate_cl.h",
18
+ ],
19
+ deps = [
20
+ "@llvm-project//llvm:Support",
21
+ ],
22
+ alwayslink = 1,
23
+ )
24
+
25
+ cc_library(
26
+ name = "translate_registration",
27
+ srcs = [
28
+ "tf_mlir_translate_registration.cc",
29
+ ],
30
+ deps = [
31
+ "//tensorflow/compiler/mlir/tensorflow",
32
+ "//tensorflow/compiler/mlir/tensorflow/translate:mlir_roundtrip_flags",
33
+ "//tensorflow/compiler/mlir/tensorflow/translate/tools:file_tf_mlir_translate",
34
+ "//tensorflow/compiler/mlir/tf2xla/api/v2:tf_executor_to_graph",
35
+ "//tensorflow/compiler/mlir/tools:translate_cl_options",
36
+ "//tensorflow/compiler/tf2xla:xla_compiler",
37
+ "//tensorflow/compiler/tf2xla/kernels:xla_ops",
38
+ "//tensorflow/core:core_cpu_base",
39
+ "//tensorflow/core:framework",
40
+ "//tensorflow/core:protos_all_cc",
41
+ "@com_google_absl//absl/container:flat_hash_set",
42
+ "@llvm-project//mlir:IR",
43
+ "@llvm-project//mlir:TranslateLib",
44
+ "@tsl//tsl/platform:protobuf",
45
+ "@xla//xla/client:client_library",
46
+ "@xla//xla/client:compile_only_client",
47
+ "@xla//xla/service/cpu:cpu_compiler",
48
+ "@xla//xla/service/cpu:cpu_transfer_manager",
49
+ "@xla//xla/stream_executor/host:host_platform",
50
+ "@xla//xla/stream_executor/host:host_platform_id",
51
+ ],
52
+ alwayslink = 1,
53
+ )
54
+
55
+ cc_library(
56
+ name = "safe_cast",
57
+ hdrs = ["safe_cast.h"],
58
+ )
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/BUILD ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ load(
2
+ "@local_config_rocm//rocm:build_defs.bzl",
3
+ "if_rocm_is_configured",
4
+ )
5
+ load("@rules_cc//cc:cc_library.bzl", "cc_library")
6
+ load(
7
+ "@xla//xla/stream_executor:build_defs.bzl",
8
+ "if_gpu_is_configured",
9
+ )
10
+ load(
11
+ "@xla//xla/tsl/platform/default:cuda_build_defs.bzl",
12
+ "if_cuda_is_configured",
13
+ )
14
+ load(
15
+ "//tensorflow:tensorflow.bzl",
16
+ "check_deps",
17
+ "tf_cc_binary",
18
+ )
19
+ load(
20
+ "//tensorflow/core/platform:build_config.bzl",
21
+ "tf_proto_library",
22
+ )
23
+ load(
24
+ "//tensorflow/core/platform:build_config_root.bzl",
25
+ "if_llvm_aarch32_available",
26
+ "if_llvm_aarch64_available",
27
+ "if_llvm_powerpc_available",
28
+ "if_llvm_system_z_available",
29
+ "if_llvm_x86_available",
30
+ )
31
+
32
+ package(
33
+ # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"],
34
+ default_visibility = [":friends"],
35
+ licenses = ["notice"],
36
+ )
37
+
38
+ package_group(
39
+ name = "friends",
40
+ packages = [
41
+ "//tensorflow/compiler/...",
42
+ "//tensorflow/core/kernels/mlir_generated/...",
43
+ ],
44
+ )
45
+
46
+ cc_library(
47
+ name = "kernel_creator",
48
+ srcs = ["kernel_creator.cc"],
49
+ hdrs = ["kernel_creator.h"],
50
+ copts = if_cuda_is_configured(["-DGOOGLE_CUDA=1"]) + if_rocm_is_configured(["-DTENSORFLOW_USE_ROCM=1"]),
51
+ deps = [
52
+ "//tensorflow/compiler/mlir/tensorflow:dump_mlir_util",
53
+ "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:bufferize",
54
+ "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:gpu_passes", # fixdeps: keep
55
+ "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:passes",
56
+ "//tensorflow/core:lib",
57
+ "@com_google_absl//absl/status",
58
+ "@com_google_absl//absl/status:statusor",
59
+ "@llvm-project//llvm:Support",
60
+ "@llvm-project//mlir:AffineToStandard",
61
+ "@llvm-project//mlir:ArithDialect",
62
+ "@llvm-project//mlir:ArithTransforms",
63
+ "@llvm-project//mlir:BufferizationTransforms",
64
+ "@llvm-project//mlir:BuiltinToLLVMIRTranslation",
65
+ "@llvm-project//mlir:ComplexDialect",
66
+ "@llvm-project//mlir:ComplexToStandard",
67
+ "@llvm-project//mlir:ControlFlowDialect",
68
+ "@llvm-project//mlir:DataLayoutInterfaces",
69
+ "@llvm-project//mlir:FuncDialect",
70
+ "@llvm-project//mlir:GPUDialect",
71
+ "@llvm-project//mlir:GPUToGPURuntimeTransforms",
72
+ "@llvm-project//mlir:GPUToLLVMIRTranslation",
73
+ "@llvm-project//mlir:GPUToNVVMTransforms",
74
+ "@llvm-project//mlir:GPUTransforms",
75
+ "@llvm-project//mlir:IR",
76
+ "@llvm-project//mlir:LLVMIRTransforms",
77
+ "@llvm-project//mlir:LLVMToLLVMIRTranslation",
78
+ "@llvm-project//mlir:LinalgTransforms",
79
+ "@llvm-project//mlir:MemRefDialect",
80
+ "@llvm-project//mlir:MemRefTransforms",
81
+ "@llvm-project//mlir:NVVMToLLVMIRTranslation",
82
+ "@llvm-project//mlir:NVVMTransforms",
83
+ "@llvm-project//mlir:Parser",
84
+ "@llvm-project//mlir:Pass",
85
+ "@llvm-project//mlir:ROCDLToLLVMIRTranslation",
86
+ "@llvm-project//mlir:ReconcileUnrealizedCasts",
87
+ "@llvm-project//mlir:SCFToControlFlow",
88
+ "@llvm-project//mlir:SCFToGPU",
89
+ "@llvm-project//mlir:SCFTransforms",
90
+ "@llvm-project//mlir:ShapeDialect",
91
+ "@llvm-project//mlir:ShapeToStandard",
92
+ "@llvm-project//mlir:Support",
93
+ "@llvm-project//mlir:TransformUtils",
94
+ "@llvm-project//mlir:Transforms",
95
+ "@stablehlo//:chlo_ops",
96
+ "@stablehlo//:linalg_passes",
97
+ "@stablehlo//:stablehlo_passes",
98
+ "@xla//xla/mlir_hlo",
99
+ "@xla//xla/mlir_hlo:all_passes", # fixdeps: keep
100
+ "@xla//xla/mlir_hlo:mhlo_passes",
101
+ "@xla//xla/mlir_hlo:transforms_gpu_passes",
102
+ "@xla//xla/mlir_hlo:transforms_passes",
103
+ ],
104
+ )
105
+
106
+ check_deps(
107
+ name = "hlo_to_kernel_check_deps",
108
+ disallowed_deps = ["@xla//xla:literal"],
109
+ deps = [":hlo_to_kernel"],
110
+ )
111
+
112
+ tf_cc_binary(
113
+ name = "hlo_to_kernel",
114
+ srcs = ["hlo_to_kernel.cc"],
115
+ visibility = [
116
+ "//tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel:__pkg__",
117
+ "//tensorflow/core/kernels/mlir_generated:__pkg__",
118
+ ],
119
+ deps = [
120
+ ":kernel_creator",
121
+ "//tensorflow/compiler/mlir:init_mlir",
122
+ "//tensorflow/compiler/mlir/tensorflow",
123
+ "//tensorflow/core:lib",
124
+ "@com_google_absl//absl/log",
125
+ "@com_google_absl//absl/status",
126
+ "@com_google_absl//absl/status:statusor",
127
+ "@com_google_absl//absl/strings",
128
+ "@llvm-project//llvm:Analysis",
129
+ "@llvm-project//llvm:CodeGen",
130
+ "@llvm-project//llvm:Core",
131
+ "@llvm-project//llvm:MC",
132
+ "@llvm-project//llvm:Support",
133
+ "@llvm-project//llvm:Target",
134
+ "@llvm-project//llvm:TargetParser",
135
+ "@llvm-project//mlir:BufferizationInterfaces",
136
+ "@llvm-project//mlir:ExecutionEngineUtils",
137
+ "@llvm-project//mlir:IR",
138
+ "@llvm-project//mlir:LLVMToLLVMIRTranslation",
139
+ "@llvm-project//mlir:MemRefTransforms",
140
+ "@llvm-project//mlir:Pass",
141
+ "@llvm-project//mlir:ToLLVMIRTranslation",
142
+ "@xla//xla/service/llvm_ir:llvm_command_line_options",
143
+ ] + if_llvm_aarch32_available([
144
+ "@llvm-project//llvm:ARMCodeGen", # fixdeps: keep
145
+ ]) + if_llvm_aarch64_available([
146
+ "@llvm-project//llvm:AArch64CodeGen", # fixdeps: keep
147
+ ]) + if_llvm_powerpc_available([
148
+ "@llvm-project//llvm:PowerPCCodeGen", # fixdeps: keep
149
+ ]) + if_llvm_system_z_available([
150
+ "@llvm-project//llvm:SystemZCodeGen", # fixdeps: keep
151
+ ]) + if_llvm_x86_available([
152
+ "@llvm-project//llvm:X86CodeGen", # fixdeps: keep
153
+ "@llvm-project//llvm:X86Disassembler", # fixdeps: keep
154
+ ]),
155
+ )
156
+
157
+ tf_cc_binary(
158
+ name = "kernel-gen-opt",
159
+ srcs = ["tools/kernel-gen-opt/kernel-gen-opt.cc"],
160
+ visibility = ["//tensorflow/compiler/mlir/tools/kernel_gen/tests:__subpackages__"],
161
+ deps = [
162
+ "//tensorflow/compiler/mlir/tensorflow",
163
+ "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops",
164
+ "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:gpu_passes", # fixdeps: keep
165
+ "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:passes",
166
+ "@llvm-project//llvm:Support",
167
+ "@llvm-project//mlir:AllPassesAndDialects",
168
+ "@llvm-project//mlir:MlirOptLib",
169
+ "@llvm-project//mlir:RegisterAllDialects",
170
+ "@llvm-project//mlir:RegisterAllPasses",
171
+ "@stablehlo//:register",
172
+ "@xla//xla/mlir_hlo:all_passes",
173
+ "@xla//xla/mlir_hlo:hlo_dialect_registration",
174
+ ],
175
+ )
176
+
177
+ exports_files(["tf_framework_c_interface.h"])
178
+
179
+ cc_library(
180
+ name = "tf_framework_c_interface",
181
+ srcs = ["tf_framework_c_interface.cc"],
182
+ hdrs = ["tf_framework_c_interface.h"],
183
+ copts = if_cuda_is_configured(["-DGOOGLE_CUDA=1"]) + if_rocm_is_configured(["-DTENSORFLOW_USE_ROCM=1"]),
184
+ deps = [
185
+ ":compile_cache_item_proto_cc",
186
+ ":kernel_creator",
187
+ ":tf_gpu_runtime_wrappers",
188
+ ":tf_jit_cache",
189
+ "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops",
190
+ "//tensorflow/core:framework",
191
+ "//tensorflow/core:lib",
192
+ "//tensorflow/core/platform:refcount",
193
+ "@com_google_absl//absl/log",
194
+ "@com_google_absl//absl/log:check",
195
+ "@com_google_absl//absl/strings",
196
+ "@com_google_absl//absl/strings:string_view",
197
+ "@llvm-project//llvm:JITLink",
198
+ "@llvm-project//llvm:OrcShared",
199
+ "@llvm-project//llvm:Support",
200
+ "@llvm-project//mlir:ExecutionEngine",
201
+ "@llvm-project//mlir:ExecutionEngineUtils",
202
+ "@llvm-project//mlir:IR",
203
+ "@llvm-project//mlir:MemRefTransforms",
204
+ "@llvm-project//mlir:Parser",
205
+ "@llvm-project//mlir:Support",
206
+ "@llvm-project//mlir:mlir_c_runner_utils",
207
+ "@llvm-project//mlir:mlir_runner_utils",
208
+ "@xla//xla/stream_executor:stream",
209
+ ],
210
+ )
211
+
212
+ cc_library(
213
+ name = "tf_jit_cache",
214
+ srcs = ["tf_jit_cache.cc"],
215
+ hdrs = ["tf_jit_cache.h"],
216
+ deps = [
217
+ "//tensorflow/core:framework",
218
+ "//tensorflow/core:framework_lite",
219
+ "//tensorflow/core/framework:resource_base",
220
+ "//tensorflow/core/platform:status",
221
+ "@com_google_absl//absl/container:flat_hash_map",
222
+ "@com_google_absl//absl/status",
223
+ "@llvm-project//llvm:Support",
224
+ "@llvm-project//mlir:ExecutionEngine",
225
+ "@tsl//tsl/platform:thread_annotations",
226
+ ],
227
+ )
228
+
229
+ cc_library(
230
+ name = "tf_gpu_runtime_wrappers",
231
+ srcs = if_gpu_is_configured([
232
+ "tf_gpu_runtime_wrappers.cc",
233
+ ]),
234
+ hdrs =
235
+ if_gpu_is_configured([
236
+ "tf_gpu_runtime_wrappers.h",
237
+ ]),
238
+ copts = if_cuda_is_configured(["-DGOOGLE_CUDA=1"]) + if_rocm_is_configured([
239
+ "-DTENSORFLOW_USE_ROCM=1",
240
+ ]),
241
+ deps = [
242
+ "//tensorflow/core:framework",
243
+ "//tensorflow/core/framework:resource_base",
244
+ "//tensorflow/core/platform:logging",
245
+ "//tensorflow/core/platform:mutex",
246
+ "//tensorflow/core/platform:refcount",
247
+ "//tensorflow/core/platform:status",
248
+ "@com_google_absl//absl/container:flat_hash_map",
249
+ "@com_google_absl//absl/status",
250
+ "@com_google_absl//absl/strings",
251
+ "@llvm-project//mlir:mlir_runner_utils",
252
+ "@tsl//tsl/platform:hash",
253
+ "@tsl//tsl/platform:thread_annotations",
254
+ "@xla//xla/stream_executor:stream",
255
+ ] + if_cuda_is_configured([
256
+ "@local_config_cuda//cuda:cuda_headers",
257
+ "@xla//xla/stream_executor/cuda:stream_executor_cuda",
258
+ ]) + if_rocm_is_configured([
259
+ "@local_config_rocm//rocm:rocm_headers",
260
+ "@xla//xla/stream_executor/rocm:stream_executor_rocm",
261
+ ]),
262
+ )
263
+
264
+ tf_proto_library(
265
+ name = "compile_cache_item_proto",
266
+ srcs = ["compile_cache_item.proto"],
267
+ )
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.proto ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ syntax = "proto3";
2
+
3
+ package mlir.kernel_gen;
4
+
5
+ // Protocolbuffer representing a compilation input and output. This will be used
6
+ // for caching JIT compiles of kernels.
7
+ message CompilationCacheItem {
8
+ string original_module = 1;
9
+ string result_module = 2;
10
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/hlo_to_kernel.cc ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The TensorFlow Runtime Authors
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
+ //===- hlo_to_kernel.cc -----------------------------------------*- C++ -*-===//
16
+ //
17
+ // This file implements the entry point to compile a hlo op to a kernel.
18
+ //
19
+ //===----------------------------------------------------------------------===//
20
+ #include <cstdint>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "absl/log/log.h"
26
+ #include "absl/status/status.h"
27
+ #include "absl/status/statusor.h"
28
+ #include "absl/strings/string_view.h"
29
+ #include "llvm/ADT/SmallString.h"
30
+ #include "llvm/Analysis/TargetLibraryInfo.h"
31
+ #include "llvm/CodeGen/CommandFlags.h"
32
+ #include "llvm/IR/LLVMContext.h"
33
+ #include "llvm/IR/LegacyPassManager.h"
34
+ #include "llvm/IR/Module.h"
35
+ #include "llvm/MC/TargetRegistry.h"
36
+ #include "llvm/Support/CodeGen.h"
37
+ #include "llvm/Support/CommandLine.h"
38
+ #include "llvm/Support/SourceMgr.h"
39
+ #include "llvm/Support/TargetSelect.h"
40
+ #include "llvm/Support/raw_ostream.h"
41
+ #include "llvm/Target/TargetMachine.h"
42
+ #include "llvm/TargetParser/Host.h"
43
+ #include "llvm/TargetParser/Triple.h"
44
+ #include "mlir/Dialect/MemRef/Transforms/AllocationOpInterfaceImpl.h" // from @llvm-project
45
+ #include "mlir/ExecutionEngine/OptUtils.h" // from @llvm-project
46
+ #include "mlir/IR/BuiltinOps.h" // from @llvm-project
47
+ #include "mlir/IR/Diagnostics.h" // from @llvm-project
48
+ #include "mlir/IR/MLIRContext.h" // from @llvm-project
49
+ #include "mlir/IR/OwningOpRef.h" // from @llvm-project
50
+ #include "mlir/Pass/PassManager.h" // from @llvm-project
51
+ #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" // from @llvm-project
52
+ #include "mlir/Target/LLVMIR/Export.h" // from @llvm-project
53
+ #include "tensorflow/compiler/mlir/init_mlir.h"
54
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h"
55
+ #include "xla/service/llvm_ir/llvm_command_line_options.h"
56
+ #include "xla/tsl/platform/errors.h"
57
+ #include "xla/tsl/platform/statusor.h"
58
+ #include "tensorflow/core/platform/env.h"
59
+ #include "tensorflow/core/platform/logging.h"
60
+ #include "tensorflow/core/platform/status.h"
61
+
62
+ namespace tensorflow {
63
+ namespace kernel_gen {
64
+ namespace {
65
+
66
+ static llvm::codegen::RegisterCodeGenFlags CGF;
67
+
68
+ std::unique_ptr<llvm::TargetMachine> GetTargetMachine(
69
+ llvm::StringRef host_triple, llvm::Module* module) {
70
+ llvm::Triple triple(module->getTargetTriple());
71
+ if (triple.getTriple().empty()) {
72
+ if (!host_triple.empty()) {
73
+ triple = llvm::Triple(host_triple);
74
+ } else {
75
+ triple = llvm::Triple(llvm::sys::getDefaultTargetTriple());
76
+ }
77
+ module->setTargetTriple(llvm::Triple(triple.getTriple()));
78
+ }
79
+
80
+ std::string error;
81
+ const llvm::Target* target =
82
+ llvm::TargetRegistry::lookupTarget("", triple, error);
83
+ if (!target) {
84
+ return nullptr;
85
+ }
86
+
87
+ llvm::TargetOptions target_options =
88
+ llvm::codegen::InitTargetOptionsFromCodeGenFlags(llvm::Triple());
89
+ return std::unique_ptr<llvm::TargetMachine>(target->createTargetMachine(
90
+ triple, "generic", "", target_options, llvm::Reloc::Model::PIC_));
91
+ }
92
+
93
+ // Compiles the given MLIR module via LLVM into an executable binary format.
94
+ absl::StatusOr<std::string> EmitToBinary(llvm::StringRef host_triple,
95
+ mlir::ModuleOp module) {
96
+ // Translate the module.
97
+ llvm::LLVMContext llvm_context;
98
+ mlir::registerLLVMDialectTranslation(*module->getContext());
99
+ std::unique_ptr<llvm::Module> llvm_module =
100
+ mlir::translateModuleToLLVMIR(module, llvm_context);
101
+
102
+ auto target_machine = GetTargetMachine(host_triple, llvm_module.get());
103
+ llvm_module->setDataLayout(target_machine->createDataLayout());
104
+
105
+ // Run LLVM's mid-level optimizer to clean up the IR.
106
+ if (mlir::makeOptimizingTransformer(
107
+ /*optLevel=*/2, /*sizeLevel=*/0,
108
+ target_machine.get())(llvm_module.get())) {
109
+ return absl::InternalError("Failed to run LLVM optimizer passess");
110
+ }
111
+
112
+ // Set up the output stream.
113
+ llvm::SmallString<8> outstr;
114
+ llvm::raw_svector_ostream ostream(outstr);
115
+ ostream.SetUnbuffered();
116
+
117
+ llvm::legacy::PassManager codegen_passes;
118
+ codegen_passes.add(new llvm::TargetLibraryInfoWrapperPass(
119
+ llvm::Triple(llvm_module->getTargetTriple())));
120
+
121
+ if (target_machine->addPassesToEmitFile(codegen_passes, ostream, nullptr,
122
+ llvm::CodeGenFileType::ObjectFile,
123
+ false)) {
124
+ return absl::InternalError("Failed add passes to emit file");
125
+ }
126
+ codegen_passes.run(*llvm_module);
127
+ return ostream.str().str();
128
+ }
129
+
130
+ absl::Status Run(llvm::StringRef input_file, llvm::StringRef output_file,
131
+ llvm::StringRef host_triple,
132
+ llvm::ArrayRef<std::string> architectures,
133
+ llvm::ArrayRef<int64_t> tile_sizes,
134
+ llvm::ArrayRef<int64_t> unroll_factors, bool print_ptx,
135
+ bool print_llvmir, bool enable_ftz, bool index_64bit,
136
+ bool jit_compile, bool jit_i64_indexed_for_large_tensors) {
137
+ // Read TF code.
138
+ std::string hlo_code;
139
+ TF_RETURN_IF_ERROR(
140
+ ReadFileToString(Env::Default(), input_file.str(), &hlo_code));
141
+
142
+ // Compile.
143
+ mlir::DialectRegistry registry;
144
+ mlir::memref::registerAllocationOpInterfaceExternalModels(registry);
145
+ mlir::MLIRContext context(registry);
146
+
147
+ llvm::SourceMgr source_mgr;
148
+ mlir::SourceMgrDiagnosticHandler source_mgr_handler(source_mgr, &context);
149
+
150
+ TF_ASSIGN_OR_RETURN(
151
+ mlir::OwningOpRef<mlir::ModuleOp> module,
152
+ GenerateKernelForHloCode(context, hlo_code, architectures, tile_sizes,
153
+ unroll_factors, print_ptx, print_llvmir,
154
+ enable_ftz, index_64bit, jit_compile,
155
+ jit_i64_indexed_for_large_tensors,
156
+ /*apply_cl_options=*/true));
157
+
158
+ // Get binary.
159
+ TF_ASSIGN_OR_RETURN(std::string binary, EmitToBinary(host_triple, *module));
160
+
161
+ // Write .a file.
162
+ TF_RETURN_IF_ERROR(
163
+ WriteStringToFile(Env::Default(), output_file.str(), binary));
164
+ return absl::OkStatus();
165
+ }
166
+
167
+ } // namespace
168
+ } // namespace kernel_gen
169
+ } // namespace tensorflow
170
+
171
+ int main(int argc, char** argv) {
172
+ llvm::cl::opt<std::string> input_file("input", llvm::cl::desc("input file"),
173
+ llvm::cl::value_desc("filename"),
174
+ llvm::cl::init("foo.mlir"));
175
+ llvm::cl::opt<std::string> output_file(
176
+ "output", llvm::cl::desc("output file"), llvm::cl::value_desc("filename"),
177
+ llvm::cl::init("foo.bin"));
178
+ llvm::cl::opt<bool> index_64bit("index_64bit",
179
+ llvm::cl::desc("enable 64 bit indexing"),
180
+ llvm::cl::init(false));
181
+ llvm::cl::opt<bool> print_ptx(
182
+ "print-ptx",
183
+ llvm::cl::desc("print generated PTX code per target architecture."),
184
+ llvm::cl::init(false));
185
+ llvm::cl::opt<bool> print_llvmir(
186
+ "print-llvmir", llvm::cl::desc("print llvm ir during lowering to ptx."),
187
+ llvm::cl::init(false));
188
+ llvm::cl::opt<bool> enable_ftz(
189
+ "enable_ftz",
190
+ llvm::cl::desc(
191
+ "enable the denormal flush to zero mode when generating code."),
192
+ llvm::cl::init(false));
193
+ llvm::cl::opt<bool> jit_compile(
194
+ "jit", llvm::cl::desc("Generate only a JIT compiler invocation."),
195
+ llvm::cl::init(false));
196
+ llvm::cl::opt<std::string> host_triple(
197
+ "host-triple", llvm::cl::desc("Override host triple for module"));
198
+ llvm::cl::list<std::string> architectures(
199
+ "arch", llvm::cl::desc("target architectures (e.g. sm_70 or compute_75)"),
200
+ llvm::cl::ZeroOrMore, llvm::cl::CommaSeparated);
201
+ llvm::cl::list<int64_t> tile_sizes(
202
+ "tile_sizes", llvm::cl::desc("tile sizes to use"), llvm::cl::ZeroOrMore,
203
+ llvm::cl::CommaSeparated);
204
+ llvm::cl::list<int64_t> unroll_factors(
205
+ "unroll_factors",
206
+ llvm::cl::desc("factors to unroll by, separated by commas"),
207
+ llvm::cl::ZeroOrMore, llvm::cl::CommaSeparated);
208
+ llvm::cl::opt<bool> jit_i64_indexed_for_large_tensors(
209
+ "jit_i64_indexed_for_large_tensors",
210
+ llvm::cl::desc(
211
+ "Enable JIT compilation of i64-indexed kernels for large inputs."),
212
+ llvm::cl::init(false));
213
+
214
+ tensorflow::InitMlir y(&argc, &argv);
215
+
216
+ #ifdef TF_LLVM_X86_AVAILABLE
217
+ LLVMInitializeX86Target();
218
+ LLVMInitializeX86TargetInfo();
219
+ LLVMInitializeX86TargetMC();
220
+ LLVMInitializeX86AsmPrinter();
221
+ #endif
222
+
223
+ #ifdef TF_LLVM_AARCH64_AVAILABLE
224
+ LLVMInitializeAArch64Target();
225
+ LLVMInitializeAArch64TargetInfo();
226
+ LLVMInitializeAArch64TargetMC();
227
+ LLVMInitializeAArch64AsmPrinter();
228
+ #endif
229
+
230
+ mlir::registerPassManagerCLOptions();
231
+ mlir::registerMLIRContextCLOptions();
232
+
233
+ // Forward cli options to XLA, as it will reset llvm options internally
234
+ // during the first invocation.
235
+ auto& xla_llvm_global_options =
236
+ xla::llvm_ir::LLVMCommandLineOptionsLock::GetGlobalOptions();
237
+ xla_llvm_global_options.insert(xla_llvm_global_options.end(), argv + 1,
238
+ argv + argc);
239
+ llvm::cl::ParseCommandLineOptions(argc, argv, "TF op kernel generator\n");
240
+
241
+ auto status = tensorflow::kernel_gen::Run(
242
+ input_file, output_file, host_triple, architectures, tile_sizes,
243
+ unroll_factors, print_ptx, print_llvmir, enable_ftz, index_64bit,
244
+ jit_compile, jit_i64_indexed_for_large_tensors);
245
+ if (!status.ok()) {
246
+ LOG(ERROR) << status;
247
+ return 1;
248
+ }
249
+ return 0;
250
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/BUILD ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ load("@llvm-project//mlir:tblgen.bzl", "gentbl_cc_library", "td_library")
2
+ load("//tensorflow:tensorflow.default.bzl", "get_compatible_with_portable")
3
+ load("//tensorflow/core/platform:rules_cc.bzl", "cc_library")
4
+
5
+ package(
6
+ # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"],
7
+ default_visibility = [
8
+ "//tensorflow/compiler/mlir/tools/kernel_gen:friends",
9
+ # Allow visibility from the mlir language server.
10
+ "//learning/brain/mlir/mlir_lsp_server:__pkg__",
11
+ ],
12
+ licenses = ["notice"],
13
+ )
14
+
15
+ td_library(
16
+ name = "td_files",
17
+ srcs = [
18
+ "tf_framework_ops.td",
19
+ "tf_status.td",
20
+ ],
21
+ compatible_with = get_compatible_with_portable(),
22
+ deps = [
23
+ "@llvm-project//mlir:AllocationOpInterfaceTdFiles",
24
+ "@llvm-project//mlir:ControlFlowInterfacesTdFiles",
25
+ "@llvm-project//mlir:OpBaseTdFiles",
26
+ "@llvm-project//mlir:SideEffectInterfacesTdFiles",
27
+ ],
28
+ )
29
+
30
+ gentbl_cc_library(
31
+ name = "tf_framework_ops_inc_gen",
32
+ compatible_with = get_compatible_with_portable(),
33
+ tbl_outs = {
34
+ "tf_framework_ops.h.inc": ["-gen-op-decls"],
35
+ "tf_framework_ops.cc.inc": ["-gen-op-defs"],
36
+ "tf_framework_dialect.h.inc": ["-gen-dialect-decls"],
37
+ "tf_framework_dialect.cc.inc": ["-gen-dialect-defs"],
38
+ },
39
+ tblgen = "@llvm-project//mlir:mlir-tblgen",
40
+ td_file = "tf_framework_ops.td",
41
+ deps = [":td_files"],
42
+ )
43
+
44
+ gentbl_cc_library(
45
+ name = "tf_status_inc_gen",
46
+ compatible_with = get_compatible_with_portable(),
47
+ tbl_outs = {
48
+ "tf_status.h.inc": ["-gen-enum-decls"],
49
+ "tf_status.cc.inc": ["-gen-enum-defs"],
50
+ },
51
+ tblgen = "@llvm-project//mlir:mlir-tblgen",
52
+ td_file = "tf_status.td",
53
+ deps = [":td_files"],
54
+ )
55
+
56
+ cc_library(
57
+ name = "tf_framework_ops",
58
+ srcs = [
59
+ "tf_framework_ops.cc",
60
+ "tf_framework_ops.cc.inc",
61
+ "tf_framework_ops.h.inc",
62
+ ],
63
+ hdrs = ["tf_framework_ops.h"],
64
+ deps = [
65
+ ":tf_framework_ops_inc_gen",
66
+ ":tf_status_inc_gen",
67
+ "//tensorflow/core/protobuf:error_codes_proto_impl_cc",
68
+ "@com_google_absl//absl/status",
69
+ "@llvm-project//llvm:Support",
70
+ "@llvm-project//mlir:AllocationOpInterface",
71
+ "@llvm-project//mlir:BufferizationDialect",
72
+ "@llvm-project//mlir:BytecodeOpInterface",
73
+ "@llvm-project//mlir:ControlFlowInterfaces",
74
+ "@llvm-project//mlir:FuncDialect",
75
+ "@llvm-project//mlir:IR",
76
+ "@llvm-project//mlir:MemRefDialect",
77
+ "@llvm-project//mlir:SideEffectInterfaces",
78
+ "@llvm-project//mlir:Support",
79
+ "@xla//xla/tsl/protobuf:error_codes_proto_impl_cc",
80
+ ],
81
+ )
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 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
+ // This file defines the operations used in the tf_framework dialect.
17
+
18
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h"
19
+
20
+ #include <optional>
21
+
22
+ #include "absl/status/status.h"
23
+ #include "llvm/Support/ErrorHandling.h"
24
+ #include "mlir/Dialect/Bufferization/IR/Bufferization.h" // from @llvm-project
25
+ #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
26
+ #include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project
27
+ #include "mlir/IR/Builders.h" // from @llvm-project
28
+ #include "mlir/IR/DialectImplementation.h" // from @llvm-project
29
+ #include "mlir/IR/Operation.h" // from @llvm-project
30
+ #include "mlir/IR/Value.h" // from @llvm-project
31
+ #include "mlir/Support/LLVM.h" // from @llvm-project
32
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.cc.inc"
33
+
34
+ // Generated dialect definitions.
35
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_dialect.cc.inc"
36
+ #include "xla/tsl/protobuf/error_codes.pb.h"
37
+
38
+ namespace mlir {
39
+ namespace kernel_gen {
40
+ namespace tf_framework {
41
+
42
+ void TFFrameworkDialect::initialize() {
43
+ addOperations<
44
+ #define GET_OP_LIST
45
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc.inc"
46
+ >();
47
+ addTypes<JITCallableType, OpKernelContextType>();
48
+ }
49
+
50
+ /// Parse a type registered to this dialect.
51
+ Type TFFrameworkDialect::parseType(DialectAsmParser &parser) const {
52
+ StringRef keyword;
53
+ if (parser.parseKeyword(&keyword)) return Type();
54
+
55
+ if (keyword == "op_kernel_context") {
56
+ return OpKernelContextType::get(getContext());
57
+ }
58
+ if (keyword == "jit_callable") {
59
+ return JITCallableType::get(getContext());
60
+ }
61
+
62
+ parser.emitError(parser.getNameLoc(), "unknown TF Framework type: ")
63
+ << keyword;
64
+ return Type();
65
+ }
66
+
67
+ /// Print a type registered to this dialect.
68
+ void TFFrameworkDialect::printType(Type type, DialectAsmPrinter &os) const {
69
+ if (mlir::isa<OpKernelContextType>(type)) {
70
+ os << "op_kernel_context";
71
+ return;
72
+ }
73
+ if (mlir::isa<JITCallableType>(type)) {
74
+ os << "jit_callable";
75
+ return;
76
+ }
77
+ llvm_unreachable("unexpected TF Framework type kind");
78
+ }
79
+
80
+ //===----------------------------------------------------------------------===//
81
+ // TFAllocOp
82
+ //===----------------------------------------------------------------------===//
83
+ LogicalResult TFAllocOp::verify() {
84
+ TFAllocOp op = *this;
85
+ // Check that the total number of operands matches the number of dynamic
86
+ // dimensions specified in the memref type.
87
+ unsigned result_dyn_dims = op.getType().getNumDynamicDims();
88
+ unsigned dyn_sizes_count = op.getDynSizes().size();
89
+ if (dyn_sizes_count != result_dyn_dims)
90
+ return op.emitOpError()
91
+ << "`dyn_sizes` count " << dyn_sizes_count
92
+ << " does not match dynamic dimensions count in the result type"
93
+ << op.getType();
94
+ return success();
95
+ }
96
+
97
+ std::optional<Operation *> TFAllocOp::buildDealloc(OpBuilder &builder,
98
+ Value alloc) {
99
+ auto funcop = alloc.getParentRegion()->getParentOfType<func::FuncOp>();
100
+ return TFDeallocOp::create(builder, alloc.getLoc(), funcop.getArgument(0),
101
+ alloc)
102
+ .getOperation();
103
+ }
104
+
105
+ std::optional<Value> TFAllocOp::buildClone(OpBuilder &builder, Value alloc) {
106
+ // TODO(herhut): We should have our own clone op if one of these survives.
107
+ return mlir::bufferization::CloneOp::create(builder, alloc.getLoc(), alloc)
108
+ .getResult();
109
+ }
110
+
111
+ //===----------------------------------------------------------------------===//
112
+ // JITExecuteOp
113
+ //===----------------------------------------------------------------------===//
114
+
115
+ std::optional<Operation *> JITExecuteOp::buildDealloc(OpBuilder &builder,
116
+ Value alloc) {
117
+ auto funcop = alloc.getParentRegion()->getParentOfType<func::FuncOp>();
118
+ return TFDeallocOp::create(builder, alloc.getLoc(), funcop.getArgument(0),
119
+ alloc)
120
+ .getOperation();
121
+ }
122
+
123
+ std::optional<Value> JITExecuteOp::buildClone(OpBuilder &builder, Value alloc) {
124
+ // TODO(herhut): We should have our own clone op if one of these survives.
125
+ return mlir::bufferization::CloneOp::create(builder, alloc.getLoc(), alloc)
126
+ .getResult();
127
+ }
128
+
129
+ absl::StatusCode ConvertAttrToEnumValue(ErrorCode error_code) {
130
+ using ::tensorflow::error::Code;
131
+ switch (error_code) {
132
+ case ErrorCode::OK:
133
+ return absl::StatusCode::kOk;
134
+ case ErrorCode::CANCELLED:
135
+ return absl::StatusCode::kCancelled;
136
+ case ErrorCode::UNKNOWN:
137
+ return absl::StatusCode::kUnknown;
138
+ case ErrorCode::INVALID_ARGUMENT:
139
+ return absl::StatusCode::kInvalidArgument;
140
+ case ErrorCode::DEADLINE_EXCEEDED:
141
+ return absl::StatusCode::kDeadlineExceeded;
142
+ case ErrorCode::NOT_FOUND:
143
+ return absl::StatusCode::kNotFound;
144
+ case ErrorCode::ALREADY_EXISTS:
145
+ return absl::StatusCode::kAlreadyExists;
146
+ case ErrorCode::PERMISSION_DENIED:
147
+ return absl::StatusCode::kPermissionDenied;
148
+ case ErrorCode::UNAUTHENTICATED:
149
+ return absl::StatusCode::kUnauthenticated;
150
+ case ErrorCode::RESOURCE_EXHAUSTED:
151
+ return absl::StatusCode::kResourceExhausted;
152
+ case ErrorCode::FAILED_PRECONDITION:
153
+ return absl::StatusCode::kFailedPrecondition;
154
+ case ErrorCode::ABORTED:
155
+ return absl::StatusCode::kAborted;
156
+ case ErrorCode::OUT_OF_RANGE:
157
+ return absl::StatusCode::kOutOfRange;
158
+ case ErrorCode::UNIMPLEMENTED:
159
+ return absl::StatusCode::kUnimplemented;
160
+ case ErrorCode::INTERNAL:
161
+ return absl::StatusCode::kInternal;
162
+ case ErrorCode::UNAVAILABLE:
163
+ return absl::StatusCode::kUnavailable;
164
+ case ErrorCode::DATA_LOSS:
165
+ return absl::StatusCode::kDataLoss;
166
+ }
167
+ }
168
+
169
+ } // namespace tf_framework
170
+ } // namespace kernel_gen
171
+ } // namespace mlir
172
+
173
+ #define GET_OP_CLASSES
174
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc.inc"
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 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
+ // This file defines the operations used in the TFFramework dialect.
17
+ //
18
+ #ifndef TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_IR_TF_FRAMEWORK_OPS_H_
19
+ #define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_IR_TF_FRAMEWORK_OPS_H_
20
+
21
+ #include "absl/status/status.h"
22
+ #include "mlir/Bytecode/BytecodeOpInterface.h" // from @llvm-project
23
+ #include "mlir/Dialect/Bufferization/IR/AllocationOpInterface.h" // from @llvm-project
24
+ #include "mlir/IR/Attributes.h" // from @llvm-project
25
+ #include "mlir/IR/BuiltinTypes.h" // from @llvm-project
26
+ #include "mlir/IR/Dialect.h" // from @llvm-project
27
+ #include "mlir/IR/MLIRContext.h" // from @llvm-project
28
+ #include "mlir/IR/OpDefinition.h" // from @llvm-project
29
+ #include "mlir/IR/OpImplementation.h" // from @llvm-project
30
+ #include "mlir/IR/TypeSupport.h" // from @llvm-project
31
+ #include "mlir/IR/Types.h" // from @llvm-project
32
+ #include "mlir/Interfaces/ControlFlowInterfaces.h" // from @llvm-project
33
+ #include "mlir/Interfaces/SideEffectInterfaces.h" // from @llvm-project
34
+ #include "mlir/Support/LLVM.h" // from @llvm-project
35
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.h.inc"
36
+ #include "tensorflow/core/protobuf/error_codes.pb.h"
37
+
38
+ namespace mlir {
39
+ namespace kernel_gen {
40
+ namespace tf_framework {
41
+
42
+ /// OpKernelContextType corresponds to C++ class OpKernelContext defined in
43
+ /// tensorflow/core/framework/op_kernel.h
44
+ class OpKernelContextType
45
+ : public Type::TypeBase<OpKernelContextType, Type, TypeStorage> {
46
+ public:
47
+ using Base::Base;
48
+ static constexpr StringLiteral name =
49
+ "kernel_gen.tf_framework.op_kernel_context";
50
+ };
51
+
52
+ class JITCallableType
53
+ : public Type::TypeBase<JITCallableType, Type, TypeStorage> {
54
+ public:
55
+ using Base::Base;
56
+ static constexpr StringLiteral name = "kernel_gen.tf_framework.jit_callable";
57
+ };
58
+
59
+ absl::StatusCode ConvertAttrToEnumValue(ErrorCode error_code);
60
+
61
+ } // namespace tf_framework
62
+ } // namespace kernel_gen
63
+ } // namespace mlir
64
+
65
+ #define GET_OP_CLASSES
66
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_dialect.h.inc"
67
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h.inc"
68
+
69
+ #endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_IR_TF_FRAMEWORK_OPS_H_
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.td ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 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
+ // This is the operation definition file for TF Framework ops.
17
+
18
+ #ifndef TF_FRAMEWORK_OPS
19
+ #define TF_FRAMEWORK_OPS
20
+
21
+ include "mlir/IR/OpBase.td"
22
+ include "mlir/Dialect/Bufferization/IR/AllocationOpInterface.td"
23
+ include "mlir/Interfaces/ControlFlowInterfaces.td"
24
+ include "mlir/Interfaces/SideEffectInterfaces.td"
25
+ include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.td"
26
+
27
+ def TFFramework_Dialect : Dialect {
28
+ let name = "tf_framework";
29
+
30
+ let summary = "Types and operations for tf_framework dialect";
31
+ let description = [{
32
+ This dialect contains operations and types for that correspond to
33
+ TensorFlow C++ Framework.
34
+ }];
35
+ let cppNamespace = "::mlir::kernel_gen::tf_framework";
36
+
37
+ let extraClassDeclaration = [{
38
+ static constexpr StringRef kTFEntryAttrName = "tf_entry";
39
+ static constexpr size_t kAllocationAlignment = 16;
40
+ }];
41
+
42
+ let useDefaultTypePrinterParser = 1;
43
+ }
44
+
45
+ def TFFramework_OpKernelContextType : DialectType<TFFramework_Dialect,
46
+ CPred<"llvm::isa<::mlir::kernel_gen::tf_framework::OpKernelContextType>($_self)">,
47
+ "op_kernel_construction">,
48
+ BuildableType<"$_builder.getType<::mlir::kernel_gen::tf_framework::OpKernelContextType>()"> {
49
+ let description = [{
50
+ OpKernelContextType corresponds to C++ class OpKernelContext defined in
51
+ tensorflow/core/framework/op_kernel.h
52
+ }];
53
+ }
54
+
55
+ def TFFramework_JITCallableType : DialectType<TFFramework_Dialect, CPred<
56
+ "llvm::isa<::mlir::kernel_gen::tf_framework::JITCallableType>($_self)">>,
57
+ BuildableType<"$_builder.getType<::mlir::kernel_gen::tf_framework::JITCallableType>()"> {
58
+ let description = [{
59
+ A `callable` represents the result of JIT compilation. Conceptually, it
60
+ corresponds to a function pointer.
61
+ }];
62
+ }
63
+
64
+ // Base class for TF Framework dialect ops.
65
+ class TFFramework_Op<string mnemonic, list<Trait> traits = []> :
66
+ Op<TFFramework_Dialect, mnemonic, traits>;
67
+
68
+ //===----------------------------------------------------------------------===//
69
+ // TFAllocOp
70
+ //===----------------------------------------------------------------------===//
71
+ def TFFramework_TFAllocOp : TFFramework_Op<"alloc", [
72
+ MemoryEffects<[MemAlloc<DefaultResource>]>,
73
+ DeclareOpInterfaceMethods<AllocationOpInterface,
74
+ ["buildDealloc", "buildClone"]>
75
+ ]> {
76
+ let summary = "allocation of tensors that uses TF Framework";
77
+ let description = [{
78
+ Allocation of tensors during kernel execution in the Compute method.
79
+
80
+ This should be used to allocate any temporary or output memref. If
81
+ `output_index` and `input_indices` are given, attempts to forward one of
82
+ the input tensors to the output by calling `OpKernelContext::forward_input`.
83
+
84
+ If the attributes are missing or the forwarding fails, calls
85
+ `Allocator::AllocateRaw` in tensorflow/core/framework/allocator.h.
86
+ }];
87
+
88
+ let arguments = (ins
89
+ TFFramework_OpKernelContextType:$ctx,
90
+ Variadic<Index>:$dyn_sizes,
91
+ OptionalAttr<I32ArrayAttr>:$input_indices,
92
+ OptionalAttr<I32Attr>:$output_index
93
+ );
94
+ let results = (outs Res<AnyMemRef, "", [MemAlloc<DefaultResource>]>:$result);
95
+
96
+ let builders = [
97
+ OpBuilder<(ins "MemRefType":$memref_type, "Value":$ctx),
98
+ [{
99
+ $_state.addOperands(ctx);
100
+ $_state.types.push_back(memref_type);
101
+ }]>,
102
+ OpBuilder<(ins "MemRefType":$memref_type, "Value":$ctx,
103
+ "ValueRange":$dyn_sizes),
104
+ [{
105
+ build($_builder, $_state, memref_type, ctx);
106
+ $_state.addOperands(dyn_sizes);
107
+ }]>];
108
+
109
+ let extraClassDeclaration = [{
110
+ MemRefType getType() { return llvm::cast<MemRefType>(getResult().getType()); }
111
+ static constexpr StringRef kReuseOutputAttrName = "reuse_output";
112
+ static constexpr StringRef kReuseInputCandidatesAttrName =
113
+ "reuse_input_candidates";
114
+ }];
115
+ let assemblyFormat = [{
116
+ `(` $ctx (`,` $dyn_sizes^ )? `)` attr-dict `:` type($result)
117
+ }];
118
+
119
+ let hasVerifier = 1;
120
+ }
121
+
122
+ //===----------------------------------------------------------------------===//
123
+ // TFAssertOp
124
+ //===----------------------------------------------------------------------===//
125
+ def TFFramework_TFAssertOp : TFFramework_Op<"assert"> {
126
+ let summary = "Assert operation with message attribute and error code";
127
+ let description = [{
128
+ Assert operation that propagates the error message to TF Framework.
129
+ }];
130
+
131
+ let arguments = (ins
132
+ TFFramework_OpKernelContextType:$ctx,
133
+ I1:$arg,
134
+ TFFramework_ErrorCodeAttr:$error_code,
135
+ StrAttr:$msg
136
+ );
137
+
138
+ let assemblyFormat = "$ctx `,` $arg `,` $error_code `,` $msg attr-dict";
139
+ }
140
+
141
+ //===----------------------------------------------------------------------===//
142
+ // TFDeallocOp
143
+ //===----------------------------------------------------------------------===//
144
+ def TFFramework_TFDeallocOp : TFFramework_Op<"dealloc",
145
+ [MemoryEffects<[MemFree]>]> {
146
+ let summary = "deallocation of tensors that uses TF Framework";
147
+ let description = [{
148
+ Deallocation of tensors during kernel execution in the Compute method.
149
+
150
+ This should be used to deallocate any temporary memref that was allocated
151
+ with `tf_framework.alloc`.
152
+ Corresponds to `Allocator::DeallocateRaw` in
153
+ tensorflow/core/framework/allocator.h.
154
+ }];
155
+
156
+ let arguments = (ins TFFramework_OpKernelContextType:$ctx,
157
+ Arg<AnyRankedOrUnrankedMemRef, "", [MemFree]>:$memref);
158
+ let assemblyFormat = "`(` $ctx `,` $memref `)` attr-dict `:` type($memref)";
159
+ }
160
+
161
+ //===----------------------------------------------------------------------===//
162
+ // IsValidMemRefOp
163
+ //===----------------------------------------------------------------------===//
164
+ def TFFramework_IsValidMemRefOp : TFFramework_Op<"is_valid_memref", []> {
165
+ let summary = "Op to check if the memref is valid.";
166
+ let description = [{
167
+ The op checks if the allocation was successful so that the underlying ptr
168
+ in the descriptor is not equal to NULL. Also, we check if the number of
169
+ elements is not zero to support empty shapes inputs correctly.
170
+
171
+ is_valid_memref(memref) = ptr(memref) != NULL || num_elements(memref) == 0
172
+ }];
173
+
174
+ let arguments = (ins AnyMemRef:$arg);
175
+ let results = (outs I1:$result);
176
+ let assemblyFormat = [{
177
+ `(` $arg `)` attr-dict `:` type($arg) `->` type($result)
178
+ }];
179
+ }
180
+
181
+ //===----------------------------------------------------------------------===//
182
+ // NullContextOp
183
+ //===----------------------------------------------------------------------===//
184
+ def TFFramework_NullContextOp : TFFramework_Op<"null_context",
185
+ [Pure]> {
186
+ let summary = "Creates a fake TF context that will be lowered to nullptr";
187
+ let description = [{Needed for testing}];
188
+ let results = (outs TFFramework_OpKernelContextType:$result);
189
+ let assemblyFormat = "attr-dict `:` type($result)";
190
+ }
191
+
192
+ //===----------------------------------------------------------------------===//
193
+ // NullMemRefOp
194
+ //===----------------------------------------------------------------------===//
195
+ def TFFramework_NullMemRefOp : TFFramework_Op<"null_memref", []> {
196
+ let summary = "Op to construct unranked memref with 0-rank";
197
+ let description = [{
198
+ The op is needed to construct a throw-away result after error reporting
199
+ happened. It constructs a ranked memref descriptor with 0-rank and
200
+ {NULL, NULL, 0} underlying ranked descriptor of type memref<elem_type>.
201
+ In ranked case it constructs a ranked memref descriptor depending on the
202
+ result type, but sets both allocated and aligned pointers to NULL.
203
+ }];
204
+
205
+ let results = (outs AnyRankedOrUnrankedMemRef:$result);
206
+ let assemblyFormat = "attr-dict `:` type($result)";
207
+ }
208
+
209
+ //===----------------------------------------------------------------------===//
210
+ // ReportErrorOp
211
+ //===----------------------------------------------------------------------===//
212
+ def TFFramework_ReportErrorOp : TFFramework_Op<"report_error", []> {
213
+ let summary = "Operation that propagates error message to TF Framework";
214
+ let description = [{
215
+ Error reporting operation that corresponds to
216
+ `OpKernelContext::CtxFailureWithWarning`.
217
+ }];
218
+
219
+ let arguments = (ins
220
+ TFFramework_OpKernelContextType:$ctx,
221
+ TFFramework_ErrorCodeAttr:$error_code,
222
+ StrAttr:$msg
223
+ );
224
+
225
+ let assemblyFormat = "$ctx `,` $error_code `,` $msg attr-dict";
226
+ }
227
+
228
+ //===----------------------------------------------------------------------===//
229
+ // JITCompileOp
230
+ //===----------------------------------------------------------------------===//
231
+
232
+ def TFFramework_JITCompileOp : TFFramework_Op<"jit_compile", [SingleBlock]> {
233
+ let summary = "Invokes JIT compilation through the TF framework";
234
+ let description = [{
235
+ The op takes an optional TF context, so that it can be added at a later
236
+ stage in the compilation pipeline. The op's body corresponds to a function
237
+ body and the corresponding `tf_framework.jit_compile_yield` represents the
238
+ result value(s).
239
+ }];
240
+
241
+ let arguments = (ins
242
+ Optional<TFFramework_OpKernelContextType>:$ctx
243
+ );
244
+ let results = (outs TFFramework_JITCallableType:$result);
245
+ let regions = (region SizedRegion<1>:$body);
246
+
247
+ let assemblyFormat = "$ctx $body attr-dict";
248
+ }
249
+
250
+ //===----------------------------------------------------------------------===//
251
+ // JITCompileYieldOp
252
+ //===----------------------------------------------------------------------===//
253
+
254
+ def TFFramework_JITCompileYieldOp : TFFramework_Op<"jit_compile_yield", [
255
+ Pure, ReturnLike, Terminator, HasParent<"JITCompileOp">]> {
256
+ let summary = "Yields the results in a `tf_framework.jit_compile` op's body";
257
+ let description = [{
258
+ See `tf_framework.jit_compile`.
259
+ }];
260
+
261
+ let arguments = (ins
262
+ AnyTypeOf<[AnyRankedOrUnrankedMemRef, AnyTensor]>:$result
263
+ );
264
+
265
+ let assemblyFormat = "$result attr-dict `:` type($result)";
266
+ }
267
+
268
+ //===----------------------------------------------------------------------===//
269
+ // JITCompileFromStrOp
270
+ //===----------------------------------------------------------------------===//
271
+
272
+ def TFFramework_JITCompileFromStrOp : TFFramework_Op<"jit_compile_from_str",
273
+ []> {
274
+ let summary = "Invokes JIT compilation through the TF framework";
275
+ let description = [{
276
+ This operation is similar to `tf_framework.jit_compile`. Instead of a body,
277
+ the to-be-compiled function is represented as a string attribute. The string
278
+ shall be the serialized form of a module with a single function named
279
+ `main`.
280
+ }];
281
+
282
+ let arguments = (ins
283
+ Optional<TFFramework_OpKernelContextType>:$ctx,
284
+ StrAttr:$code,
285
+ I64ArrayAttr:$tileSizes,
286
+ I64ArrayAttr:$unrollFactors,
287
+ BoolAttr:$enableFtz,
288
+ BoolAttr:$index64Bit,
289
+ BoolAttr:$cpuCodegen
290
+ );
291
+ let results = (outs TFFramework_JITCallableType:$result);
292
+
293
+ let extraClassDeclaration = [{
294
+ static constexpr StringRef kJITEntryFunctionName = "main";
295
+ }];
296
+
297
+ let assemblyFormat = "($ctx^ `,`)? $code attr-dict";
298
+ }
299
+
300
+ //===----------------------------------------------------------------------===//
301
+ // JITExecuteOp
302
+ //===----------------------------------------------------------------------===//
303
+
304
+ def TFFramework_JITExecuteOp : TFFramework_Op<"jit_execute", [
305
+ AttrSizedOperandSegments,
306
+ MemoryEffects<[MemAlloc<DefaultResource>]>,
307
+ DeclareOpInterfaceMethods<AllocationOpInterface,
308
+ ["buildDealloc", "buildClone"]>]> {
309
+ let summary = "Executes a JIT-compiled function through the TF framework";
310
+ let description = [{
311
+ The op takes an optional TF context, so that it can be added at a later
312
+ stage in the compilation pipeline. The callable must be a JIT-compiled
313
+ function that is the result of either `tf_framework.jit_compile` or
314
+ `tf_framework.jit_compile_from_str`. The remaining operands must be tensor
315
+ or memref arguments and will be forwarded to the callable function. The
316
+ result types must match those of the callable function. Otherwise, the
317
+ execution behavior is undefined.
318
+ }];
319
+
320
+ let arguments = (ins
321
+ Optional<TFFramework_OpKernelContextType>:$ctx,
322
+ TFFramework_JITCallableType:$callable,
323
+ Variadic<AnyTypeOf<[AnyRankedOrUnrankedMemRef, AnyTensor]>>:$inputs
324
+ );
325
+ let results = (outs
326
+ Res<AnyTypeOf<[AnyRankedOrUnrankedMemRef, AnyTensor]> , "",
327
+ [MemAlloc<DefaultResource>]>:$result);
328
+
329
+ let assemblyFormat = [{
330
+ (`ctx` `(` $ctx^ `)`)? $callable `(` $inputs `)` attr-dict
331
+ `:` type($inputs) `->` type($result)
332
+ }];
333
+ }
334
+
335
+ #endif // TF_FRAMEWORK_OPS
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.td ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 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
+ // This is the enum definition file for TF Status attribute.
17
+
18
+ #ifndef TF_FRAMEWORK_STATUS
19
+ #define TF_FRAMEWORK_STATUS
20
+
21
+ include "mlir/IR/EnumAttr.td"
22
+ include "mlir/IR/OpBase.td"
23
+
24
+ def TFFramework_ERROR_CODE_OK
25
+ : I32EnumAttrCase<"OK", 0>;
26
+ def TFFramework_ERROR_CODE_CANCELLED
27
+ : I32EnumAttrCase<"CANCELLED", 1>;
28
+ def TFFramework_ERROR_CODE_UNKNOWN
29
+ : I32EnumAttrCase<"UNKNOWN", 2>;
30
+ def TFFramework_ERROR_CODE_INVALID_ARGUMENT
31
+ : I32EnumAttrCase<"INVALID_ARGUMENT", 3>;
32
+ def TFFramework_ERROR_CODE_DEADLINE_EXCEEDED
33
+ : I32EnumAttrCase<"DEADLINE_EXCEEDED", 4>;
34
+ def TFFramework_ERROR_CODE_NOT_FOUND
35
+ : I32EnumAttrCase<"NOT_FOUND", 5>;
36
+ def TFFramework_ERROR_CODE_ALREADY_EXISTS
37
+ : I32EnumAttrCase<"ALREADY_EXISTS", 6>;
38
+ def TFFramework_ERROR_CODE_PERMISSION_DENIED
39
+ : I32EnumAttrCase<"PERMISSION_DENIED", 7>;
40
+ def TFFramework_ERROR_CODE_UNAUTHENTICATED
41
+ : I32EnumAttrCase<"UNAUTHENTICATED", 16>;
42
+ def TFFramework_ERROR_CODE_RESOURCE_EXHAUSTED
43
+ : I32EnumAttrCase<"RESOURCE_EXHAUSTED", 8>;
44
+ def TFFramework_ERROR_CODE_FAILED_PRECONDITION
45
+ : I32EnumAttrCase<"FAILED_PRECONDITION", 9>;
46
+ def TFFramework_ERROR_CODE_ABORTED
47
+ : I32EnumAttrCase<"ABORTED", 10>;
48
+ def TFFramework_ERROR_CODE_OUT_OF_RANGE
49
+ : I32EnumAttrCase<"OUT_OF_RANGE", 11>;
50
+ def TFFramework_ERROR_CODE_UNIMPLEMENTED
51
+ : I32EnumAttrCase<"UNIMPLEMENTED", 12>;
52
+ def TFFramework_ERROR_CODE_INTERNAL
53
+ : I32EnumAttrCase<"INTERNAL", 13>;
54
+ def TFFramework_ERROR_CODE_UNAVAILABLE
55
+ : I32EnumAttrCase<"UNAVAILABLE", 14>;
56
+ def TFFramework_ERROR_CODE_DATA_LOSS
57
+ : I32EnumAttrCase<"DATA_LOSS", 15>;
58
+
59
+ def TFFramework_ErrorCodeAttr : I32EnumAttr<"ErrorCode", "error code", [
60
+ TFFramework_ERROR_CODE_OK,
61
+ TFFramework_ERROR_CODE_CANCELLED,
62
+ TFFramework_ERROR_CODE_UNKNOWN,
63
+ TFFramework_ERROR_CODE_INVALID_ARGUMENT,
64
+ TFFramework_ERROR_CODE_DEADLINE_EXCEEDED,
65
+ TFFramework_ERROR_CODE_NOT_FOUND,
66
+ TFFramework_ERROR_CODE_ALREADY_EXISTS,
67
+ TFFramework_ERROR_CODE_PERMISSION_DENIED,
68
+ TFFramework_ERROR_CODE_UNAUTHENTICATED,
69
+ TFFramework_ERROR_CODE_RESOURCE_EXHAUSTED,
70
+ TFFramework_ERROR_CODE_FAILED_PRECONDITION,
71
+ TFFramework_ERROR_CODE_ABORTED,
72
+ TFFramework_ERROR_CODE_OUT_OF_RANGE,
73
+ TFFramework_ERROR_CODE_UNIMPLEMENTED,
74
+ TFFramework_ERROR_CODE_INTERNAL,
75
+ TFFramework_ERROR_CODE_UNAVAILABLE,
76
+ TFFramework_ERROR_CODE_DATA_LOSS
77
+ ]> {
78
+ let cppNamespace = "::mlir::kernel_gen::tf_framework";
79
+ }
80
+
81
+ #endif // TF_FRAMEWORK_STATUS
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.cc ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 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
+ //===- kernel_creator.cc ----------------------------------------*- C++ -*-===//
17
+ //
18
+ // This file implements the function to compile a TF kernel function to gpu
19
+ // binary (hsaco for AMD, cubin for NVIDIA) or to a gpu binary with host side.
20
+ //
21
+ //===----------------------------------------------------------------------===//
22
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h"
23
+
24
+ #include <string>
25
+
26
+ #include "absl/status/status.h"
27
+ #include "llvm/ADT/ArrayRef.h"
28
+ #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" // from @llvm-project
29
+ #include "mlir/Conversion/ComplexToStandard/ComplexToStandard.h" // from @llvm-project
30
+ #include "mlir/Conversion/GPUCommon/GPUCommonPass.h" // from @llvm-project
31
+ #include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h" // from @llvm-project
32
+ #include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" // from @llvm-project
33
+ #include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h" // from @llvm-project
34
+ #include "mlir/Conversion/SCFToGPU/SCFToGPUPass.h" // from @llvm-project
35
+ #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" // from @llvm-project
36
+ #include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project
37
+ #include "mlir/Dialect/Arith/Transforms/Passes.h" // from @llvm-project
38
+ #include "mlir/Dialect/Bufferization/Transforms/Passes.h" // from @llvm-project
39
+ #include "mlir/Dialect/Complex/IR/Complex.h" // from @llvm-project
40
+ #include "mlir/Dialect/ControlFlow/IR/ControlFlow.h" // from @llvm-project
41
+ #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
42
+ #include "mlir/Dialect/GPU/IR/GPUDialect.h" // from @llvm-project
43
+ #include "mlir/Dialect/GPU/Transforms/Passes.h" // from @llvm-project
44
+ #include "mlir/Dialect/Linalg/Passes.h" // from @llvm-project
45
+ #include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project
46
+ #include "mlir/Dialect/MemRef/Transforms/Passes.h" // from @llvm-project
47
+ #include "mlir/Dialect/NVVM/Transforms/OptimizeForNVVM.h" // from @llvm-project
48
+ #include "mlir/Dialect/SCF/Transforms/Passes.h" // from @llvm-project
49
+ #include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project
50
+ #include "mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project
51
+ #include "mlir/IR/OwningOpRef.h" // from @llvm-project
52
+ #include "mlir/Interfaces/DataLayoutInterfaces.h" // from @llvm-project
53
+ #include "mlir/Parser/Parser.h" // from @llvm-project
54
+ #include "mlir/Pass/PassManager.h" // from @llvm-project
55
+ #include "mlir/Support/LLVM.h" // from @llvm-project
56
+ #include "mlir/Support/LogicalResult.h" // from @llvm-project
57
+ #include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h" // from @llvm-project
58
+ #include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h" // from @llvm-project
59
+ #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" // from @llvm-project
60
+ #include "mlir/Target/LLVMIR/Dialect/NVVM/NVVMToLLVMIRTranslation.h" // from @llvm-project
61
+ #include "mlir/Target/LLVMIR/Dialect/ROCDL/ROCDLToLLVMIRTranslation.h" // from @llvm-project
62
+ #include "mlir/Transforms/DialectConversion.h" // from @llvm-project
63
+ #include "mlir/Transforms/Passes.h" // from @llvm-project
64
+ #include "stablehlo/conversions/linalg/transforms/Passes.h" // from @stablehlo
65
+ #include "stablehlo/dialect/ChloOps.h" // from @stablehlo
66
+ #include "stablehlo/transforms/Passes.h" // from @stablehlo
67
+ #include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h"
68
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h"
69
+ #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h"
70
+ #include "xla/mlir_hlo/deallocation/transforms/passes.h"
71
+ #include "xla/mlir_hlo/mhlo/IR/hlo_ops.h"
72
+ #include "xla/mlir_hlo/mhlo/transforms/passes.h"
73
+ #include "xla/mlir_hlo/transforms/gpu_passes.h"
74
+ #include "xla/mlir_hlo/transforms/passes.h"
75
+ #include "xla/tsl/platform/errors.h"
76
+ #include "xla/tsl/platform/statusor.h"
77
+ #include "tensorflow/core/platform/errors.h"
78
+ #include "tensorflow/core/platform/status.h"
79
+ #include "tensorflow/core/platform/statusor.h"
80
+
81
+ namespace tensorflow {
82
+ namespace kernel_gen {
83
+ namespace {
84
+
85
+ using mlir::Value;
86
+ using mlir::func::FuncOp;
87
+ using mlir::memref::RankOp;
88
+
89
+ constexpr llvm::StringRef kGpuBinaryAttrName = "gpu.binary";
90
+
91
+ /// Check if the size of the allocation is less than the given size. The
92
+ /// transformation is only applied to small buffers since large buffers could
93
+ /// exceed the stack space.
94
+ bool IsSmallAlloc(Value alloc) {
95
+ constexpr unsigned kMaximumSizeInBytes = 64;
96
+ constexpr unsigned kMaxRankOfAllocatedMemRef = 1;
97
+
98
+ auto type = mlir::dyn_cast<mlir::ShapedType>(alloc.getType());
99
+ if (!type || !alloc.getDefiningOp<mlir::memref::AllocOp>()) return false;
100
+ if (!type.hasStaticShape()) {
101
+ // Check if the dynamic shape dimension of the alloc is produced by RankOp
102
+ // or SelectOp(_, RankOp, RankOp).
103
+ // If this is the case, it is likely to be small. Furthermore, the dimension
104
+ // is limited to the maximum rank of the allocated memref to avoid large
105
+ // values by multiplying several small values.
106
+ if (type.getRank() <= kMaxRankOfAllocatedMemRef) {
107
+ for (Value alloc_arg : alloc.getDefiningOp()->getOperands()) {
108
+ if (auto select = alloc_arg.getDefiningOp<mlir::arith::SelectOp>()) {
109
+ if (!select.getTrueValue().getDefiningOp<RankOp>() ||
110
+ !select.getFalseValue().getDefiningOp<RankOp>())
111
+ return false;
112
+ } else if (!alloc_arg.getDefiningOp<RankOp>()) {
113
+ return false;
114
+ }
115
+ }
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+ unsigned bitwidth = mlir::DataLayout::closest(alloc.getDefiningOp())
121
+ .getTypeSizeInBits(type.getElementType());
122
+ return type.getNumElements() * bitwidth <= kMaximumSizeInBytes * 8;
123
+ }
124
+
125
+ absl::Status LowerHloToJITInvocation(mlir::ModuleOp module,
126
+ llvm::ArrayRef<int64_t> tile_sizes,
127
+ llvm::ArrayRef<int64_t> unroll_factors,
128
+ bool enable_ftz, bool index_64bit,
129
+ bool jit_i64_indexed_for_large_tensors,
130
+ bool apply_cl_options) {
131
+ mlir::PassManager pm(module.getContext());
132
+ if (apply_cl_options) applyTensorflowAndCLOptions(pm);
133
+
134
+ pm.addNestedPass<FuncOp>(
135
+ mlir::kernel_gen::transforms::CreateFuncToJITInvocationPass(
136
+ tile_sizes, unroll_factors, enable_ftz, index_64bit,
137
+ /*cpu_codegen=*/false, jit_i64_indexed_for_large_tensors));
138
+ pm.addPass(mlir::kernel_gen::tf_framework::CreateEmbedTFFrameworkPass());
139
+ pm.addNestedPass<FuncOp>(
140
+ mlir::bufferization::createEmptyTensorToAllocTensorPass());
141
+ pm.addPass(mlir::createComputeOpAndFuncBufferizePass());
142
+
143
+ pm.addPass(mlir::createFinalBufferizePass(
144
+ /*alignment=*/64,
145
+ mlir::kernel_gen::transforms::populateExtraBufferizeDialects,
146
+ mlir::kernel_gen::transforms::populateExtraBufferizePatterns));
147
+
148
+ if (failed(pm.run(module))) {
149
+ return absl::InternalError("Lowering HLO to JIT invocation failed.");
150
+ }
151
+ return absl::OkStatus();
152
+ }
153
+
154
+ absl::Status LowerHlotoLoops(mlir::ModuleOp module,
155
+ llvm::ArrayRef<int64_t> tile_sizes,
156
+ llvm::ArrayRef<int64_t> unroll_factors,
157
+ bool enable_ftz, bool index_64bit,
158
+ bool jit_i64_indexed_for_large_tensors,
159
+ bool apply_cl_options) {
160
+ mlir::PassManager pm(module.getContext());
161
+ if (apply_cl_options) applyTensorflowAndCLOptions(pm);
162
+ if (jit_i64_indexed_for_large_tensors) {
163
+ pm.addNestedPass<FuncOp>(
164
+ mlir::kernel_gen::transforms::CreateFuncToJITInvocationPass(
165
+ tile_sizes, unroll_factors, enable_ftz, index_64bit,
166
+ /*cpu_codegen=*/false,
167
+ /*jit_i64_indexed_for_large_tensors=*/true));
168
+ }
169
+
170
+ pm.addNestedPass<mlir::func::FuncOp>(
171
+ mlir::stablehlo::createChloLegalizeToStablehloPass());
172
+ pm.addPass(mlir::mhlo::createStablehloLegalizeToHloPass());
173
+
174
+ pm.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
175
+ pm.addNestedPass<FuncOp>(mlir::createCSEPass());
176
+ pm.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
177
+ pm.addNestedPass<FuncOp>(mlir::kernel_gen::createShapeSimplificationPass());
178
+ pm.addNestedPass<FuncOp>(mlir::kernel_gen::createMergeAssumingOpsPass());
179
+ pm.addNestedPass<FuncOp>(mlir::kernel_gen::createBroadcastPropagationPass());
180
+ pm.addNestedPass<FuncOp>(mlir::createCanonicalizerPass());
181
+ pm.addNestedPass<FuncOp>(mlir::createCSEPass());
182
+
183
+ // Transform HLO operations to Linalg and standard.
184
+ mlir::mhlo::HloLegalizeToStablehloPassOptions options;
185
+ options.allow_xla_features_ = true; // MinimumBroadcastOp
186
+ pm.addPass(mlir::mhlo::createHloLegalizeToStablehloPass(options));
187
+
188
+ // Allowing implicit captures of scalar inputs causes crashes in kernelgen
189
+ // JIT kernels.
190
+ mlir::stablehlo::StablehloLegalizeToLinalgPassOptions linalg_options;
191
+ linalg_options.captureScalarInputs = false;
192
+ pm.addNestedPass<FuncOp>(
193
+ mlir::stablehlo::createStablehloLegalizeToLinalgPass(linalg_options));
194
+ pm.addPass(mlir::mhlo::createStablehloLegalizeToHloPass());
195
+
196
+ // Convert tensor.reshape to MHLO before running any bufferization passes.
197
+ // We'll need to teach this pipeline how to properly handle tensor.reshape
198
+ // in order to fully deprecate MHLO but in the meantime this ublocks lots of
199
+ // cleanup.
200
+ pm.addNestedPass<FuncOp>(
201
+ ::mlir::kernel_gen::createLegalizeTensorReshapePass());
202
+
203
+ // Remove the remaining references to unsigned types after all HLO compute
204
+ // operations were converted.
205
+ pm.addPass(mlir::stablehlo::createStablehloConvertToSignlessPass());
206
+
207
+ pm.addPass(mlir::createCanonicalizerPass());
208
+ pm.addNestedPass<FuncOp>(mlir::createCSEPass());
209
+
210
+ // Convert operations from the Complex dialect to the Standard/Math dialects.
211
+ pm.addNestedPass<FuncOp>(::mlir::createConvertComplexToStandardPass());
212
+
213
+ // Fuse linalg operations.
214
+ pm.addPass(mlir::memref::createResolveShapedTypeResultDimsPass());
215
+ pm.addPass(mlir::createCanonicalizerPass());
216
+ pm.addNestedPass<FuncOp>(mlir::createLinalgElementwiseOpFusionPass());
217
+
218
+ // Partial bufferization: Transforms in particular HLO and Linalg operations
219
+ // to their corresponding LHLO operations and converts the function signature.
220
+ // Leaves shape operations untouched.
221
+ //
222
+ // TODO(pifon): Rename the pass to CreateHloLinalgBufferizePass or bufferize
223
+ // in 2 steps: first Linalg, then Hlo. That would need refactoring of
224
+ // BufferizeTypeConverter.
225
+ pm.addNestedPass<FuncOp>(
226
+ mlir::bufferization::createEmptyTensorToAllocTensorPass());
227
+ pm.addPass(mlir::createComputeOpAndFuncBufferizePass());
228
+ pm.addNestedPass<FuncOp>(::mlir::createCanonicalizerPass());
229
+ pm.addNestedPass<FuncOp>(::mlir::createCSEPass());
230
+ // Remove copies which are introduced by canonicalizing
231
+ // BufferCastOp(TensorLoadOp).
232
+ pm.addNestedPass<FuncOp>(
233
+ mlir::kernel_gen::transforms::CreateCopyCleanupPass());
234
+ // Find candidates for buffer reuse. This is only successful if buffer size
235
+ // equality can be determined based on `linalg.generic` operations.
236
+ pm.addNestedPass<FuncOp>(
237
+ mlir::kernel_gen::transforms::CreateBufferReusePass());
238
+ // Approximate Tanh using standard operations.
239
+ pm.addNestedPass<FuncOp>(
240
+ ::mlir::mhlo::createLegalizeTrigonometricToApproximationPass());
241
+ // Transform the Linalg ops inside of the loop nest into parallel loops.
242
+ pm.addNestedPass<FuncOp>(::mlir::createConvertLinalgToParallelLoopsPass());
243
+
244
+ // Canonicalize the code to simplify index computations. This is needed so
245
+ // that loop bounds have the same value.
246
+ pm.addNestedPass<FuncOp>(::mlir::createCanonicalizerPass());
247
+ // Run CSE to ensure that loads and stores to the same subview get
248
+ // recognized as such.
249
+ pm.addNestedPass<FuncOp>(::mlir::createCSEPass());
250
+ // Collapse and tile parallel loops for GPU only.
251
+ pm.addNestedPass<FuncOp>(mlir::createCollapseParallelLoopsTo1DPass());
252
+ pm.addNestedPass<FuncOp>(
253
+ mlir::createTileLoopsPass(tile_sizes, unroll_factors));
254
+
255
+ pm.addNestedPass<FuncOp>(::mlir::createCanonicalizerPass());
256
+ pm.addNestedPass<FuncOp>(::mlir::createCSEPass());
257
+ if (failed(pm.run(module))) {
258
+ return absl::InternalError("Lowering HLO to loops failed.");
259
+ }
260
+ return absl::OkStatus();
261
+ }
262
+
263
+ absl::Status LowerLoopsToGPU(mlir::ModuleOp module, bool index_64bit,
264
+ bool apply_cl_options) {
265
+ mlir::PassManager pm(module.getContext());
266
+ if (apply_cl_options) applyTensorflowAndCLOptions(pm);
267
+
268
+ // Greedily map the remaining loop to GPU hardware dimensions.
269
+ pm.addNestedPass<FuncOp>(mlir::createGpuMapParallelLoopsPass());
270
+
271
+ // Expand memref_reshape to its ranked form so that we can propagate
272
+ // scalars and avoid allocation.
273
+ pm.addNestedPass<FuncOp>(mlir::arith::createArithExpandOpsPass());
274
+ pm.addNestedPass<FuncOp>(mlir::memref::createExpandOpsPass());
275
+ pm.addPass(mlir::createCanonicalizerPass());
276
+ pm.addPass(mlir::kernel_gen::transforms::CreateShapeToDescriptorsPass());
277
+ // Before bufferizing further, remove unused tensor_to_memref, so that we do
278
+ // not create allocations for tensor computations that are not actually
279
+ // needed.
280
+ pm.addPass(mlir::createCanonicalizerPass());
281
+ pm.addNestedPass<FuncOp>(mlir::createCSEPass());
282
+ // Before inserting more allocs, map the ones we already have to the
283
+ // tf runtime. That ensures that all allocations for the actual computation
284
+ // end up on the device, whereas allocations for shape computation and host
285
+ // side things remain on the host.
286
+ // Longer term, this should be handled by proper device placement.
287
+ pm.addPass(mlir::kernel_gen::tf_framework::CreateEmbedTFFrameworkPass());
288
+ // Now lower the shape computations, bufferize all remaining ops and insert
289
+ // deallocs.
290
+ pm.addPass(mlir::createFinalBufferizePass(
291
+ /*alignment=*/64,
292
+ mlir::kernel_gen::transforms::populateExtraBufferizeDialects,
293
+ mlir::kernel_gen::transforms::populateExtraBufferizePatterns));
294
+ pm.addNestedPass<FuncOp>(::mlir::bufferization::createBufferHoistingPass());
295
+ pm.addNestedPass<FuncOp>(mlir::bufferization::createPromoteBuffersToStackPass(
296
+ [](Value alloc) { return IsSmallAlloc(alloc); }));
297
+ // Free all temporaries,
298
+ pm.addNestedPass<FuncOp>(mlir::deallocation::createBufferDeallocationPass());
299
+ pm.addPass(mlir::createCanonicalizerPass());
300
+ pm.addNestedPass<FuncOp>(::mlir::createConvertLinalgToLoopsPass());
301
+
302
+ // Apply the mapping and go to GPU. We cannot do this earlier as the GPU
303
+ // dialect requires memrefs.
304
+ pm.addNestedPass<FuncOp>(mlir::createConvertParallelLoopToGpuPass());
305
+
306
+ // Some basic cleanup.
307
+ pm.addNestedPass<FuncOp>(::mlir::createCanonicalizerPass());
308
+ pm.addNestedPass<FuncOp>(::mlir::createCSEPass());
309
+ // Make loops with min bounds into a conditional plus static bounds.
310
+ pm.addNestedPass<FuncOp>(mlir::createForLoopSpecializationPass());
311
+ // Take launches to launches with kernels.
312
+ pm.addPass(mlir::createGpuLaunchSinkIndexComputationsPass());
313
+ const std::string gpuDataLayoutSpec =
314
+ index_64bit ? "#dlti.dl_spec<#dlti.dl_entry<index,64:i64>>"
315
+ : "#dlti.dl_spec<#dlti.dl_entry<index,32:i32>>";
316
+ pm.addPass(
317
+ mlir::createGpuKernelOutliningPass({.dataLayoutStr = gpuDataLayoutSpec}));
318
+
319
+ pm.addPass(::mlir::createLowerAffinePass());
320
+ // Constraints are removed as late as possible and before lowering to CFG.
321
+ pm.addNestedPass<FuncOp>(::mlir::createConvertShapeConstraintsPass());
322
+ pm.addNestedPass<FuncOp>(::mlir::createCanonicalizerPass());
323
+ pm.addPass(::mlir::createSCFToControlFlowPass());
324
+ // Map asserts to the tensorflow framework.
325
+ pm.addPass(mlir::kernel_gen::tf_framework::CreateRewriteTFFrameworkAssert());
326
+ if (failed(pm.run(module))) {
327
+ return absl::InternalError("Lowering to GPU kernels failed.");
328
+ }
329
+ return absl::OkStatus();
330
+ }
331
+
332
+ absl::Status LowerKernelBodiesToLowLevelIr(mlir::ModuleOp module,
333
+ bool apply_cl_options,
334
+ const std::string& architecture) {
335
+ #if !defined(TENSORFLOW_USE_ROCM) && !defined(GOOGLE_CUDA)
336
+ return absl::InternalError(
337
+ "Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined."
338
+ " Did you specify either --config=rocm or --config=cuda ?");
339
+ #endif
340
+
341
+ #if TENSORFLOW_USE_ROCM
342
+ auto gpu_modules = module.getOps<::mlir::gpu::GPUModuleOp>();
343
+ for (::mlir::gpu::GPUModuleOp gpu_module : gpu_modules) {
344
+ gpu_module.walk([&](mlir::gpu::GPUFuncOp gpu_kernel) {
345
+ if (gpu_kernel.isKernel()) {
346
+ gpu_kernel->setAttr(
347
+ "rocdl.max_flat_work_group_size",
348
+ mlir::IntegerAttr::get(
349
+ mlir::IntegerType::get(module.getContext(), 32), 1024));
350
+ }
351
+ });
352
+ }
353
+ #endif
354
+
355
+ mlir::PassManager pm(module.getContext());
356
+ // We cannot verify as the signature of the kernel is rewritten.
357
+ // pm.enableVerifier(false);
358
+ if (apply_cl_options) tensorflow::applyTensorflowAndCLOptions(pm);
359
+ auto& kernelPm = pm.nest<::mlir::gpu::GPUModuleOp>();
360
+ kernelPm.addPass(::mlir::createSCFToControlFlowPass());
361
+ #if TENSORFLOW_USE_ROCM
362
+ kernelPm.addPass(mlir::createGpuKernelToRocdlPass(architecture));
363
+ #elif GOOGLE_CUDA
364
+ kernelPm.addPass(mlir::createGpuKernelToNvvmPass());
365
+ kernelPm.addPass(mlir::NVVM::createNVVMOptimizeForTargetPass());
366
+ #endif
367
+ // Remove all location information to prevent a debug build.
368
+ pm.addPass(::mlir::createStripDebugInfoPass());
369
+
370
+ if (failed(pm.run(module))) {
371
+ return absl::InternalError("Lowering to low-level device IR failed.");
372
+ }
373
+
374
+ return absl::OkStatus();
375
+ }
376
+
377
+ absl::Status AmendKernelLLVMIRWithStaticKnowledge(mlir::ModuleOp module,
378
+ bool apply_cl_options) {
379
+ mlir::PassManager pm(module.getContext());
380
+ if (apply_cl_options) applyTensorflowAndCLOptions(pm);
381
+
382
+ pm.addNestedPass<FuncOp>(
383
+ mlir::kernel_gen::transforms::CreatePropagateShapeKnowledgeToKernels());
384
+ pm.addNestedPass<FuncOp>(
385
+ mlir::kernel_gen::transforms::CreatePropagateTfAbiKnowledgeToKernels());
386
+
387
+ return failed(pm.run(module))
388
+ ? absl::InternalError(
389
+ "Amending LLVMIR with static knowledge failed.")
390
+ : absl::OkStatus();
391
+ }
392
+
393
+ absl::Status GenerateDeviceCode(mlir::ModuleOp module,
394
+ llvm::StringRef gpu_binary_attr_name,
395
+ llvm::ArrayRef<std::string> architectures,
396
+ bool print_ptx, bool print_llvmir,
397
+ bool enable_ftz, bool apply_cl_options) {
398
+ mlir::PassManager pm(module.getContext());
399
+ if (apply_cl_options) applyTensorflowAndCLOptions(pm);
400
+ mlir::registerLLVMDialectTranslation(*module->getContext());
401
+
402
+ auto& kernel_pm = pm.nest<mlir::gpu::GPUModuleOp>();
403
+ // Remove debug information to ensure we do not create debug PTX.
404
+ kernel_pm.addPass(mlir::createStripDebugInfoPass());
405
+ kernel_pm.addPass(mlir::kernel_gen::transforms::CreateGpuKernelToBlobPass(
406
+ gpu_binary_attr_name, architectures, print_ptx, print_llvmir,
407
+ enable_ftz));
408
+
409
+ return failed(pm.run(module))
410
+ ? absl::InternalError("Generating device code failed.")
411
+ : absl::OkStatus();
412
+ }
413
+
414
+ absl::Status LowerHostSideToFinalForm(mlir::ModuleOp module,
415
+ bool apply_cl_options) {
416
+ mlir::PassManager pm(module.getContext());
417
+ if (apply_cl_options) applyTensorflowAndCLOptions(pm);
418
+
419
+ pm.addPass(mlir::kernel_gen::transforms::CreateTFKernelToLLVMPass(
420
+ kGpuBinaryAttrName));
421
+ pm.addPass(mlir::createReconcileUnrealizedCastsPass());
422
+ pm.addPass(mlir::createCanonicalizerPass());
423
+ pm.addPass(mlir::createCSEPass());
424
+
425
+ return failed(pm.run(module))
426
+ ? absl::InternalError("Final lowering of host side failed.")
427
+ : absl::OkStatus();
428
+ }
429
+
430
+ } // namespace
431
+
432
+ absl::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> SetupContextAndParseModule(
433
+ mlir::MLIRContext& context, llvm::StringRef tf_code) {
434
+ mlir::DialectRegistry registry;
435
+ registry.insert<mlir::chlo::ChloDialect, mlir::mhlo::MhloDialect>();
436
+ registry.insert<mlir::shape::ShapeDialect, mlir::scf::SCFDialect,
437
+ mlir::cf::ControlFlowDialect>();
438
+ registry.insert<mlir::complex::ComplexDialect, mlir::func::FuncDialect>();
439
+ mlir::registerBuiltinDialectTranslation(registry);
440
+ mlir::registerGPUDialectTranslation(registry);
441
+ mlir::registerLLVMDialectTranslation(registry);
442
+ mlir::registerNVVMDialectTranslation(registry);
443
+ mlir::registerROCDLDialectTranslation(registry);
444
+ context.appendDialectRegistry(registry);
445
+ mlir::OwningOpRef<mlir::ModuleOp> module =
446
+ mlir::parseSourceString<mlir::ModuleOp>(tf_code, &context);
447
+ if (!module) {
448
+ return absl::Status(absl::StatusCode::kInvalidArgument,
449
+ "invalid kernel IR");
450
+ }
451
+ return module;
452
+ }
453
+
454
+ absl::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> GenerateKernelForHloCode(
455
+ mlir::MLIRContext& context, llvm::StringRef tf_code,
456
+ llvm::ArrayRef<std::string> architectures,
457
+ llvm::ArrayRef<int64_t> tile_sizes, llvm::ArrayRef<int64_t> unroll_factors,
458
+ bool print_ptx, bool print_llvmir, bool enable_ftz, bool index_64bit,
459
+ bool jit_compile, bool jit_i64_indexed_for_large_tensors,
460
+ bool apply_cl_options) {
461
+ if (jit_compile && jit_i64_indexed_for_large_tensors) {
462
+ return absl::Status(
463
+ absl::StatusCode::kInvalidArgument,
464
+ "jit compilation for large tensors "
465
+ "(`jit_i64_indexed_for_large_tensors`) and unconditioned jit "
466
+ "compilation (`jit`) must not be requested together");
467
+ }
468
+
469
+ TF_ASSIGN_OR_RETURN(mlir::OwningOpRef<mlir::ModuleOp> module,
470
+ SetupContextAndParseModule(context, tf_code));
471
+
472
+ if (jit_compile) {
473
+ assert(!jit_i64_indexed_for_large_tensors &&
474
+ "expect to have reported an error earlier");
475
+ TF_RETURN_IF_ERROR(LowerHloToJITInvocation(
476
+ module.get(), tile_sizes, unroll_factors, enable_ftz, index_64bit,
477
+ /*jit_i64_indexed_for_large_tensors=*/false, apply_cl_options));
478
+ } else {
479
+ TF_RETURN_IF_ERROR(LowerHlotoLoops(
480
+ module.get(), tile_sizes, unroll_factors, enable_ftz, index_64bit,
481
+ jit_i64_indexed_for_large_tensors, apply_cl_options));
482
+ TF_RETURN_IF_ERROR(
483
+ LowerLoopsToGPU(module.get(), index_64bit, apply_cl_options));
484
+
485
+ // Note: we're just passing the first architecture out of the list. This
486
+ // should be sufficient for now, but in the future perhaps we'll need
487
+ // restructure this code to generate separate MLIR modules for each
488
+ // architecture.
489
+ const std::string& first_architecture =
490
+ !architectures.empty() ? architectures[0] : "";
491
+ TF_RETURN_IF_ERROR(LowerKernelBodiesToLowLevelIr(
492
+ module.get(), apply_cl_options, first_architecture));
493
+ TF_RETURN_IF_ERROR(
494
+ AmendKernelLLVMIRWithStaticKnowledge(module.get(), apply_cl_options));
495
+ TF_RETURN_IF_ERROR(GenerateDeviceCode(
496
+ module.get(), kGpuBinaryAttrName, architectures, print_ptx,
497
+ print_llvmir, enable_ftz, apply_cl_options));
498
+ }
499
+
500
+ TF_RETURN_IF_ERROR(LowerHostSideToFinalForm(module.get(), apply_cl_options));
501
+
502
+ return module;
503
+ }
504
+
505
+ } // namespace kernel_gen
506
+ } // namespace tensorflow
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2020 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
+ //===- kernel_creator.h -----------------------------------------*- C++ -*-===//
17
+ //
18
+ // This file declares the function to compile a TF kernel function to gpu
19
+ // binary (hsaco for AMD, cubin for NVIDIA) or to a gpu binary with host side.
20
+ //
21
+ //===----------------------------------------------------------------------===//
22
+ #ifndef TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_KERNEL_CREATOR_H_
23
+ #define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_KERNEL_CREATOR_H_
24
+
25
+ #include <cstdint>
26
+ #include <string>
27
+ #include <utility>
28
+
29
+ #include "absl/status/statusor.h"
30
+ #include "llvm/ADT/ArrayRef.h"
31
+ #include "llvm/ADT/StringRef.h"
32
+ #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
33
+ #include "mlir/IR/BuiltinOps.h" // from @llvm-project
34
+ #include "mlir/IR/MLIRContext.h" // from @llvm-project
35
+ #include "mlir/IR/OwningOpRef.h" // from @llvm-project
36
+ #include "tensorflow/core/platform/statusor.h"
37
+
38
+ namespace tensorflow {
39
+ namespace kernel_gen {
40
+
41
+ // Parses tf_code to create a module. An MLIRContext is taken in case any
42
+ // unexpected dialects are needed.
43
+ absl::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> SetupContextAndParseModule(
44
+ mlir::MLIRContext& context, llvm::StringRef tf_code);
45
+
46
+ // Converts TF code to LLVM with or without GPU support.
47
+ absl::StatusOr<mlir::OwningOpRef<mlir::ModuleOp>> GenerateKernelForHloCode(
48
+ mlir::MLIRContext& context, llvm::StringRef tf_code,
49
+ llvm::ArrayRef<std::string> architectures,
50
+ llvm::ArrayRef<int64_t> tile_sizes, llvm::ArrayRef<int64_t> unroll_factors,
51
+ bool print_ptx, bool print_llvmir, bool enable_ftz, bool index_64bit,
52
+ bool jit_compile, bool jit_i64_indexed_for_large_tensors,
53
+ bool apply_cl_options);
54
+
55
+ } // namespace kernel_gen
56
+ } // namespace tensorflow
57
+
58
+ #endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_KERNEL_CREATOR_H_
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/BUILD ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ load("//tensorflow:tensorflow.default.bzl", "filegroup")
2
+ load("//tensorflow/compiler/mlir:glob_lit_test.bzl", "glob_lit_tests")
3
+
4
+ package(
5
+ # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"],
6
+ licenses = ["notice"],
7
+ )
8
+
9
+ glob_lit_tests(
10
+ name = "all_tests",
11
+ data = [":test_utilities"],
12
+ driver = "//tensorflow/compiler/mlir:run_lit.sh",
13
+ test_file_exts = ["mlir"],
14
+ )
15
+
16
+ # Bundle together all of the test utilities that are used by tests.
17
+ filegroup(
18
+ name = "test_utilities",
19
+ testonly = True,
20
+ data = [
21
+ "//tensorflow/compiler/mlir:tf-opt",
22
+ "//tensorflow/compiler/mlir/tools/kernel_gen:kernel-gen-opt",
23
+ "@llvm-project//llvm:FileCheck",
24
+ "@llvm-project//mlir:run_lit.sh",
25
+ "@xla//xla/mlir_hlo:mlir-hlo-opt",
26
+ ],
27
+ )
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/broadcast_propagation.mlir ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s --split-input-file --mhlo-broadcast-propagation | \
2
+ // RUN: FileCheck %s
3
+
4
+ // CHECK-LABEL: @single_bcast
5
+ // CHECK-SAME: %[[ARG0:.*]]: tensor<16x?xf32>, %[[ARG1:.*]]: tensor<16x?xf32>, %[[SHAPE:.*]]: tensor<3xindex>
6
+ func.func @single_bcast(%arg0 : tensor<16x?xf32>, %arg1 : tensor<16x?xf32>,
7
+ %shape : tensor<3xindex>) -> tensor<?x16x?xf32> {
8
+ // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE]])
9
+ // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE]])
10
+ // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[BCASTED_ARG0]], %[[BCASTED_ARG1]] : [[BCASTED_TY:tensor<\?x16x\?xf32>]]
11
+ // CHECK-DAG: %[[MUL:.*]] = mhlo.multiply %[[ADD]], %[[ADD]] : [[BCASTED_TY]]
12
+ // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[ADD]], %[[ADD]] : [[BCASTED_TY]]
13
+ // CHECK-DAG: %[[DIV:.*]] = mhlo.divide %[[MUL]], %[[SUB]] : [[BCASTED_TY]]
14
+ // CHECK: return %[[DIV]] : [[BCASTED_TY]]
15
+ %0 = mhlo.add %arg0, %arg1 : tensor<16x?xf32>
16
+ %1 = mhlo.multiply %0, %0 : tensor<16x?xf32>
17
+ %2 = mhlo.subtract %0, %0 : tensor<16x?xf32>
18
+ %3 = mhlo.divide %1, %2 : tensor<16x?xf32>
19
+ %4 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape) {
20
+ broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>} :
21
+ (tensor<16x?xf32>, tensor<3xindex>) -> tensor<?x16x?xf32>
22
+ func.return %4 : tensor<?x16x?xf32>
23
+ }
24
+
25
+ // -----
26
+
27
+ // CHECK-LABEL: @single_bcast_ensure_order
28
+ // CHECK-SAME: %[[ARG0:.*]]: tensor<16x?xf32>, %[[ARG1:.*]]: tensor<16x?xf32>, %[[SHAPE:.*]]: tensor<3xindex>
29
+ func.func @single_bcast_ensure_order(%arg0 : tensor<16x?xf32>, %arg1 : tensor<16x?xf32>,
30
+ %shape : tensor<3xindex>) -> tensor<?x16x?xf32> {
31
+ // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE]])
32
+ // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE]])
33
+ // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[BCASTED_ARG0]], %[[BCASTED_ARG1]] : [[BCASTED_TY:tensor<\?x16x\?xf32>]]
34
+ // CHECK-DAG: %[[MUL:.*]] = mhlo.multiply %[[ADD]], %[[ADD]] : [[BCASTED_TY]]
35
+ // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[MUL]], %[[MUL]] : [[BCASTED_TY]]
36
+ // CHECK-DAG: %[[DIV:.*]] = mhlo.divide %[[ADD]], %[[SUB]] : [[BCASTED_TY]]
37
+ // CHECK: return %[[DIV]] : [[BCASTED_TY]]
38
+ %0 = mhlo.add %arg0, %arg1 : tensor<16x?xf32>
39
+ %1 = mhlo.multiply %0, %0 : tensor<16x?xf32>
40
+ %2 = mhlo.subtract %1, %1 : tensor<16x?xf32>
41
+ %3 = mhlo.divide %0, %2 : tensor<16x?xf32>
42
+ %4 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape) {
43
+ broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>} :
44
+ (tensor<16x?xf32>, tensor<3xindex>) -> tensor<?x16x?xf32>
45
+ func.return %4 : tensor<?x16x?xf32>
46
+ }
47
+
48
+ // -----
49
+
50
+ // CHECK-LABEL: @double_bcasts
51
+ // CHECK-SAME: %[[ARG0:.*]]: tensor<16x?xf32>, %[[ARG1:.*]]: tensor<16x?xf32>, %[[SHAPE0:.*]]: tensor<3xindex>, %[[SHAPE1:.*]]: tensor<3xindex>
52
+ func.func @double_bcasts(%arg0 : tensor<16x?xf32>, %arg1 : tensor<16x?xf32>,
53
+ %shape0 : tensor<3xindex>, %shape1 : tensor<3xindex>)
54
+ -> (tensor<?x16x?xf32>, tensor<?x16x?xf32>) {
55
+ // CHECK-DAG: %[[BCASTED_ARG00:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE0]]) [[BCAST_DIMS0:<{broadcast_dimensions = dense<\[1, 2\]> : tensor<2xi64>}>]]
56
+ // CHECK-DAG: %[[BCASTED_ARG01:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE1]]) [[BCAST_DIMS1:<{broadcast_dimensions = dense<\[0, 2\]> : tensor<2xi64>}>]]
57
+ // CHECK-DAG: %[[BCASTED_ARG10:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE0]]) [[BCAST_DIMS0]]
58
+ // CHECK-DAG: %[[BCASTED_ARG11:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE1]]) [[BCAST_DIMS1]]
59
+ // CHECK-DAG: %[[ADD0:.*]] = mhlo.add %[[BCASTED_ARG00]], %[[BCASTED_ARG10]] : [[BCAST_TY:tensor<\?x16x\?xf32>]]
60
+ // CHECK-DAG: %[[ADD1:.*]] = mhlo.add %[[BCASTED_ARG01]], %[[BCASTED_ARG11]] : [[BCAST_TY]]
61
+ // CHECK-DAG: %[[MUL0:.*]] = mhlo.multiply %[[ADD0]], %[[ADD0]] : [[BCAST_TY]]
62
+ // CHECK-DAG: %[[MUL1:.*]] = mhlo.multiply %[[ADD1]], %[[ADD1]] : [[BCAST_TY]]
63
+ // CHECK-DAG: %[[SUB0:.*]] = mhlo.subtract %[[ADD0]], %[[ADD0]] : [[BCAST_TY]]
64
+ // CHECK-DAG: %[[SUB1:.*]] = mhlo.subtract %[[ADD1]], %[[ADD1]] : [[BCAST_TY]]
65
+ // CHECK-DAG: %[[DIV0:.*]] = mhlo.divide %[[MUL0]], %[[SUB0]] : [[BCAST_TY]]
66
+ // CHECK-DAG: %[[DIV1:.*]] = mhlo.divide %[[MUL1]], %[[SUB1]] : [[BCAST_TY]]
67
+ // CHECK: return %[[DIV0]], %[[DIV1]] : [[BCAST_TY]], [[BCAST_TY]]
68
+ %0 = mhlo.add %arg0, %arg1 : tensor<16x?xf32>
69
+ %1 = mhlo.multiply %0, %0 : tensor<16x?xf32>
70
+ %2 = mhlo.subtract %0, %0 : tensor<16x?xf32>
71
+ %3 = mhlo.divide %1, %2 : tensor<16x?xf32>
72
+ %4 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape0) {
73
+ broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>} :
74
+ (tensor<16x?xf32>, tensor<3xindex>) -> tensor<?x16x?xf32>
75
+ %5 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape1) {
76
+ broadcast_dimensions = dense<[0, 2]> : tensor<2xi64>} :
77
+ (tensor<16x?xf32>, tensor<3xindex>) -> tensor<?x16x?xf32>
78
+ func.return %4, %5 : tensor<?x16x?xf32>, tensor<?x16x?xf32>
79
+ }
80
+
81
+ // -----
82
+
83
+ // CHECK-LABEL: @late_output_dimensions
84
+ // CHECK: %[[ARG0:.*]]: tensor<?x32xf32>, %[[ARG1:.*]]: tensor<?x32xf32>, %[[ARG2:.*]]: tensor<?x?x?xf32>
85
+ func.func @late_output_dimensions(%arg0 : tensor<?x32xf32>, %arg1 : tensor<?x32xf32>,
86
+ %arg2 : tensor<?x?x?xf32>) -> tensor<?x?x32xf32> {
87
+ // CHECK-DAG: %[[SHAPE:.*]] = shape.shape_of %[[ARG2]]
88
+ // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE]]) <{broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>}>
89
+ // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE]]) <{broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>}>
90
+ // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[BCASTED_ARG0]], %[[BCASTED_ARG1]] : [[BCAST_TY:tensor<\?x\?x32xf32>]]
91
+ // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[SUB]], %[[SUB]] : [[BCAST_TY]]
92
+ // CHECK: return %[[ADD]] : [[BCAST_TY]]
93
+ %0 = mhlo.subtract %arg0, %arg1 : tensor<?x32xf32>
94
+ %1 = shape.shape_of %arg2 : tensor<?x?x?xf32> -> tensor<3xindex>
95
+ %2 = "mhlo.dynamic_broadcast_in_dim"(%0, %1)
96
+ {broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>} :
97
+ (tensor<?x32xf32>, tensor<3xindex>) -> tensor<?x?x32xf32>
98
+ %3 = mhlo.add %2, %2 : tensor<?x?x32xf32>
99
+ func.return %3 : tensor<?x?x32xf32>
100
+ }
101
+
102
+ // -----
103
+
104
+ // CHECK-LABEL: @very_late_output_dimensions
105
+ // CHECK: (%[[ARG0:.*]]: tensor<?x32xf32>, %[[ARG1:.*]]: tensor<?x32xf32>, %[[ARG2:.*]]: tensor<?x?x?xf32>)
106
+ func.func @very_late_output_dimensions(%arg0 : tensor<?x32xf32>,
107
+ %arg1 : tensor<?x32xf32>, %arg2 : tensor<?x?x?xf32>) -> tensor<?x?x32xf32> {
108
+ // CHECK-DAG: %[[S:.*]] = shape.shape_of %[[ARG2:.*]]
109
+ // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[S]])
110
+ // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[S]])
111
+ // CHECK-DAG: %[[ACC0:.*]] = mhlo.add %[[BCASTED_ARG0]], %[[BCASTED_ARG1]]
112
+ // CHECK-DAG: %[[ACC1:.*]] = mhlo.multiply %[[ACC0]], %[[BCASTED_ARG1]]
113
+ // CHECK-DAG: %[[ACC2:.*]] = mhlo.subtract %[[ACC1]], %[[BCASTED_ARG1]]
114
+ // CHECK-DAG: %[[ACC3:.*]] = mhlo.divide %[[ACC2]], %[[BCASTED_ARG1]]
115
+ // CHECK: return %[[ACC3]]
116
+ %acc0 = mhlo.add %arg0, %arg1 : tensor<?x32xf32>
117
+ %acc1 = mhlo.multiply %acc0, %arg1 : tensor<?x32xf32>
118
+ %acc2 = mhlo.subtract %acc1, %arg1 : tensor<?x32xf32>
119
+ %acc3 = mhlo.divide %acc2, %arg1 : tensor<?x32xf32>
120
+ %1 = shape.shape_of %arg2 : tensor<?x?x?xf32> -> tensor<3xindex>
121
+ %3 = "mhlo.dynamic_broadcast_in_dim"(%acc3, %1) <{broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>}> : (tensor<?x32xf32>, tensor<3xindex>) -> tensor<?x?x32xf32>
122
+ func.return %3 : tensor<?x?x32xf32>
123
+ }
124
+
125
+ // -----
126
+
127
+ // CHECK-LABEL: @propagate_within_block
128
+ // CHECK: (%[[ARG0:.*]]: tensor<?x32xf32>, %[[ARG1:.*]]: tensor<?x32xf32>, %[[ARG2:.*]]: tensor<?x32xf32>, %[[W:.*]]: !shape.witness, %[[SHAPE:.*]]: tensor<3xindex>)
129
+ func.func @propagate_within_block(%arg0 : tensor<?x32xf32>, %arg1 : tensor<?x32xf32>,
130
+ %arg2 : tensor<?x32xf32>, %w : !shape.witness, %shape : tensor<3xindex>)
131
+ -> tensor<?x?x32xf32> {
132
+ // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[ARG0]], %[[ARG1]] : tensor<?x32xf32>
133
+ // CHECK: %[[RESULT:.*]] = shape.assuming %[[W]]
134
+ // CHECK-DAG: %[[BCASTED_ARG2:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG2]], %[[SHAPE]])
135
+ // CHECK-DAG: %[[BCASTED_SUB:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[SUB]], %[[SHAPE]])
136
+ // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[BCASTED_SUB]], %[[BCASTED_ARG2]] : tensor<?x?x32xf32>
137
+ // CHECK: shape.assuming_yield %[[ADD]]
138
+ // CHECK: return %[[RESULT]]
139
+ %sub = mhlo.subtract %arg0, %arg1 : tensor<?x32xf32>
140
+ %result = shape.assuming %w -> tensor<?x?x32xf32> {
141
+ %add = mhlo.add %sub, %arg2 : tensor<?x32xf32>
142
+ %bcasted = "mhlo.dynamic_broadcast_in_dim"(%add, %shape)
143
+ {broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>} :
144
+ (tensor<?x32xf32>, tensor<3xindex>) -> tensor<?x?x32xf32>
145
+ shape.assuming_yield %bcasted : tensor<?x?x32xf32>
146
+ }
147
+ func.return %result : tensor<?x?x32xf32>
148
+ }
149
+
150
+ // -----
151
+
152
+ // CHECK-LABEL: @propagate_within_block_2
153
+ // CHECK-SAME: %[[ARG:.*]]: tensor<?x?x?xf32>, %[[S:.*]]: tensor<3xindex>, %[[W:.*]]: !shape.witness
154
+ func.func @propagate_within_block_2(%arg : tensor<?x?x?xf32>,
155
+ %shape: tensor<3xindex>, %w: !shape.witness) -> tensor<?x?x?xf32> {
156
+ // CHECK-DAG: %[[TMP:.*]] = "mhlo.dynamic_broadcast_in_dim"(%arg0, %[[S]])
157
+ // CHECK: %[[RES:.*]] = shape.assuming %[[W]]
158
+ // CHECK-DAG: %[[INNER_RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[TMP]], %[[S]])
159
+ // CHECK: shape.assuming_yield %[[INNER_RES]]
160
+ // CHECK: return %[[RES]]
161
+ %0 = "mhlo.dynamic_broadcast_in_dim"(%arg, %shape)
162
+ {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>}
163
+ : (tensor<?x?x?xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
164
+ %1 = shape.assuming %w -> tensor<?x?x?xf32> {
165
+ %2 = "mhlo.dynamic_broadcast_in_dim"(%0, %shape)
166
+ {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>}
167
+ : (tensor<?x?x?xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
168
+ shape.assuming_yield %2 : tensor<?x?x?xf32>
169
+ }
170
+ func.return %1 : tensor<?x?x?xf32>
171
+ }
172
+
173
+ // -----
174
+
175
+ // CHECK-LABEL: @propagate_across_bcasts_cst_src
176
+ // CHECK-SAME: %[[ARG:.*]]: tensor<1xindex>
177
+ func.func @propagate_across_bcasts_cst_src(%s : tensor<1xindex>) -> tensor<?xi1> {
178
+ // CHECK-DAG: %[[C1:.*]] = mhlo.constant dense<true> : tensor<i1>
179
+ // CHECK-DAG: %[[RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[C1]], %[[ARG]]) <{broadcast_dimensions = dense<> : tensor<0xi64>}> : (tensor<i1>, tensor<1xindex>) -> tensor<?xi1>
180
+ // CHECK: return %[[RES]]
181
+ %0 = mhlo.constant dense<true> : tensor<i1>
182
+ %1 = "mhlo.dynamic_broadcast_in_dim"(%0, %s)
183
+ {broadcast_dimensions = dense<> : tensor<0xi64>}
184
+ : (tensor<i1>, tensor<1xindex>) -> tensor<?xi1>
185
+ %2 = "mhlo.dynamic_broadcast_in_dim"(%1, %s)
186
+ {broadcast_dimensions = dense<0> : tensor<1xi64>}
187
+ : (tensor<?xi1>, tensor<1xindex>) -> tensor<?xi1>
188
+ func.return %2 : tensor<?xi1>
189
+ }
190
+
191
+ // -----
192
+
193
+ // CHECK-LABEL: @compose_bcast_dims
194
+ // CHECK-SAME: %[[ARG:.*]]: tensor<?x?xi1>, %[[S0:.*]]: tensor<3xindex>, %[[S1:.*]]: tensor<4xindex>
195
+ func.func @compose_bcast_dims(%arg : tensor<?x?xi1>, %s0 : tensor<3xindex>, %s1 : tensor<4xindex>) -> tensor<1x?x1x?xi1> {
196
+ // CHECK-DAG: %[[RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG]], %[[S1]]) <{broadcast_dimensions = dense<[1, 3]> : tensor<2xi64>}> : (tensor<?x?xi1>, tensor<4xindex>) -> tensor<1x?x1x?xi1>
197
+ // CHECK: return %[[RES]]
198
+ %1 = "mhlo.dynamic_broadcast_in_dim"(%arg, %s0)
199
+ {broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>}
200
+ : (tensor<?x?xi1>, tensor<3xindex>) -> tensor<1x?x?xi1>
201
+ %2 = "mhlo.dynamic_broadcast_in_dim"(%1, %s1)
202
+ {broadcast_dimensions = dense<[0, 1, 3]> : tensor<3xi64>}
203
+ : (tensor<1x?x?xi1>, tensor<4xindex>) -> tensor<1x?x1x?xi1>
204
+ func.return %2 : tensor<1x?x1x?xi1>
205
+ }
206
+
207
+ // -----
208
+
209
+ // CHECK-LABEL: @propagate_across_bcasts
210
+ // CHECK-SAME: %[[ARG:.*]]: tensor<?x?x?xf32>, %[[S:.*]]: tensor<3xindex>
211
+ func.func @propagate_across_bcasts(%arg : tensor<?x?x?xf32>, %shape : tensor<3xindex>) -> tensor<?x?x?xf32> {
212
+ // CHECK-DAG: %[[RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG]], %[[S]]) <{broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>}> : (tensor<?x?x?xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
213
+ // CHECK: return %[[RES]]
214
+ %0 = "mhlo.dynamic_broadcast_in_dim"(%arg, %shape)
215
+ {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>}
216
+ : (tensor<?x?x?xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
217
+ %1 = "mhlo.dynamic_broadcast_in_dim"(%0, %shape)
218
+ {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>}
219
+ : (tensor<?x?x?xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
220
+ %2 = "mhlo.dynamic_broadcast_in_dim"(%1, %shape)
221
+ {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>}
222
+ : (tensor<?x?x?xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
223
+ func.return %2 : tensor<?x?x?xf32>
224
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_deallocation.mlir ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s --buffer-deallocation | FileCheck %s
2
+
3
+ // CHECK-LABEL: @jit_execute_allocation
4
+ // CHECK-SAME: %[[CTX:.*]]: !tf_framework.op_kernel_context, %[[ARG:.*]]: memref<*xf32>, %[[PRED:.*]]: i1, %[[CALLABLE:.*]]: !tf_framework.jit_callable, %[[SIZE:.*]]: index, %[[SHAPE:.*]]: memref<?xindex>
5
+ func.func @jit_execute_allocation(%ctx: !tf_framework.op_kernel_context,
6
+ %arg: memref<*xf32>, %pred: i1, %callable: !tf_framework.jit_callable,
7
+ %size: index, %shape: memref<?xindex>) -> memref<*xf32> {
8
+ // CHECK: %[[RES:.*]] = scf.if %[[PRED]]
9
+ // CHECK: %[[JIT_EXECUTE:.*]] = tf_framework.jit_execute ctx(%[[CTX]]) %[[CALLABLE]](%[[ARG]])
10
+ // CHECK: %[[INNER_RES:.*]] = bufferization.clone %[[JIT_EXECUTE]]
11
+ // CHECK: tf_framework.dealloc(%[[CTX]], %[[JIT_EXECUTE]])
12
+ // CHECK: scf.yield %[[INNER_RES]]
13
+ // CHECK: else
14
+ // CHECK: %[[ALLOC:.*]] = tf_framework.alloc(%[[CTX]], %[[SIZE]])
15
+ // CHECK: %[[RESHAPE:.*]] = memref.reshape %[[ALLOC]](%[[SHAPE]])
16
+ // CHECK: %[[INNER_RES:.*]] = bufferization.clone %[[RESHAPE]]
17
+ // CHECK: tf_framework.dealloc(%[[CTX]], %[[ALLOC]])
18
+ // CHECK: scf.yield %[[INNER_RES]]
19
+ // CHECK: return %[[RES]]
20
+ %res = scf.if %pred -> (memref<*xf32>) {
21
+ %inner_res = tf_framework.jit_execute ctx(%ctx) %callable(%arg)
22
+ : memref<*xf32> -> memref<*xf32>
23
+ scf.yield %inner_res : memref<*xf32>
24
+ } else {
25
+ %alloc = tf_framework.alloc(%ctx, %size) : memref<?xf32>
26
+ %inner_res = memref.reshape %alloc(%shape)
27
+ : (memref<?xf32>, memref<?xindex>) -> memref<*xf32>
28
+ scf.yield %inner_res : memref<*xf32>
29
+ }
30
+ return %res : memref<*xf32>
31
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_reuse.mlir ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s --buffer-reuse | FileCheck %s
2
+
3
+ // CHECK-LABEL: @unique_reuse_output
4
+ func.func @unique_reuse_output() -> (index, memref<2x3xi64>) attributes {tf_entry} {
5
+ // CHECK: memref.alloc
6
+ // CHECK-SAME: reuse_output = 1 : i32
7
+ %result_0 = arith.constant 1 : index
8
+ %result_1 = memref.alloc() : memref<2x3xi64>
9
+ func.return %result_0, %result_1 : index, memref<2x3xi64>
10
+ }
11
+
12
+ // CHECK-LABEL: @ambiguous_reuse_output
13
+ func.func @ambiguous_reuse_output(%pred : i1)
14
+ -> (memref<2x3xi64>, memref<2x3xi64>) attributes {tf_entry} {
15
+ // CHECK: memref.alloc
16
+ // CHECK: reuse_output = -1 : i32
17
+ %mem = memref.alloc() : memref<2x3xi64>
18
+ %other_mem = memref.alloc() : memref<2x3xi64>
19
+ cf.cond_br %pred, ^bb0, ^bb1
20
+ ^bb0:
21
+ func.return %mem, %other_mem : memref<2x3xi64>, memref<2x3xi64>
22
+ ^bb1:
23
+ func.return %other_mem, %mem : memref<2x3xi64>, memref<2x3xi64>
24
+ }
25
+
26
+ // CHECK-LABEL: @direct_reuse
27
+ func.func @direct_reuse(%not_a_memref : index,
28
+ %smaller : memref<5xi64>,
29
+ %greater : memref<7xi64>,
30
+ %different_element_type : memref<2x3xf32>,
31
+ %reusable_0 : memref<2x3xi64>,
32
+ %reusable_1 : memref<6xi64>) -> memref<2x3xi64>
33
+ attributes {tf_entry} {
34
+ // CHECK: memref.alloc
35
+ // CHECK-SAME: reuse_input_candidates = [1 : i32, 2 : i32, 3 : i32, 4 : i32, 5 : i32]
36
+ %result = memref.alloc() : memref<2x3xi64>
37
+ func.return %result : memref<2x3xi64>
38
+ }
39
+
40
+ // CHECK-LABEL: @local_reuse_with_memref_maps
41
+ func.func @local_reuse_with_memref_maps(
42
+ %arg : memref<?xi64, strided<[3], offset: 2>>, %n : index)
43
+ -> memref<?xi64, strided<[3], offset: 2>> attributes {tf_entry} {
44
+ // CHECK: memref.alloc
45
+ // CHECK-SAME: reuse_input_candidates = [0 : i32]
46
+ %result = memref.alloc(%n) : memref<?xi64, strided<[3], offset: 2>>
47
+ linalg.generic {
48
+ indexing_maps = [affine_map<(i) -> (i)>, affine_map<(i) -> (i)>],
49
+ iterator_types = ["parallel"]
50
+ } ins(%arg : memref<?xi64, strided<[3], offset: 2>>)
51
+ outs(%result : memref<?xi64, strided<[3], offset: 2>>) {
52
+ ^bb0(%a : i64, %b : i64):
53
+ linalg.yield %a : i64
54
+ }
55
+ func.return %result : memref<?xi64, strided<[3], offset: 2>>
56
+ }
57
+
58
+ // CHECK-LABEL: @local_reuse_with_broadcasting_memref_maps
59
+ func.func @local_reuse_with_broadcasting_memref_maps(
60
+ %arg0 : memref<i64>, %arg1 : memref<?xi64>, %n : index)
61
+ -> memref<?xi64> attributes {tf_entry} {
62
+ // CHECK: memref.alloc
63
+ // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32]
64
+ %result = memref.alloc(%n) : memref<?xi64>
65
+ linalg.generic {
66
+ indexing_maps = [affine_map<(i) -> ()>, affine_map<(i) -> (i)>, affine_map<(i) -> (i)>],
67
+ iterator_types = ["parallel"]
68
+ } ins(%arg0, %arg1 : memref<i64>, memref<?xi64>)
69
+ outs(%result : memref<?xi64>) {
70
+ ^bb0(%a : i64, %b : i64, %c : i64):
71
+ %add = arith.addi %a, %b : i64
72
+ linalg.yield %add : i64
73
+ }
74
+ func.return %result : memref<?xi64>
75
+ }
76
+
77
+ // CHECK-LABEL: @local_reuse_with_broadcasting_memref_maps2
78
+ func.func @local_reuse_with_broadcasting_memref_maps2(
79
+ %arg0 : memref<?xi64>, %arg1 : memref<?xi64>)
80
+ -> memref<i64> attributes {tf_entry} {
81
+ // CHECK: memref.alloc
82
+ // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32]
83
+ %result = memref.alloc() : memref<i64>
84
+ linalg.generic {
85
+ indexing_maps = [affine_map<(i) -> (i)>, affine_map<(i) -> (i)>, affine_map<(i) -> ()>],
86
+ iterator_types = ["parallel"]
87
+ } ins(%arg0, %arg1 : memref<?xi64>, memref<?xi64>)
88
+ outs(%result : memref<i64>) {
89
+ ^bb0(%a : i64, %b : i64, %c : i64):
90
+ %add = arith.addi %a, %b : i64
91
+ linalg.yield %add : i64
92
+ }
93
+ func.return %result : memref<i64>
94
+ }
95
+
96
+ // CHECK-LABEL: @local_reuse_with_broadcasting_memref_maps3
97
+ func.func @local_reuse_with_broadcasting_memref_maps3(
98
+ %arg0 : memref<i64>, %arg1 : memref<?xi64>)
99
+ -> memref<i64> attributes {tf_entry} {
100
+ // CHECK: memref.alloc
101
+ // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32]
102
+ %result = memref.alloc() : memref<i64>
103
+ linalg.generic {
104
+ indexing_maps = [affine_map<(i) -> ()>, affine_map<(i) -> (i)>, affine_map<(i) -> ()>],
105
+ iterator_types = ["parallel"]
106
+ } ins(%arg0, %arg1 : memref<i64>, memref<?xi64>)
107
+ outs(%result : memref<i64>) {
108
+ ^bb0(%a : i64, %b : i64, %c : i64):
109
+ %add = arith.addi %a, %b : i64
110
+ linalg.yield %add : i64
111
+ }
112
+ func.return %result : memref<i64>
113
+ }
114
+
115
+ // CHECK-LABEL: @nolocal_reuse_with_broadcasting_memref_maps
116
+ func.func @nolocal_reuse_with_broadcasting_memref_maps(
117
+ %arg0 : memref<?xi64>, %arg1 : memref<?x?xi64>, %n : index)
118
+ -> memref<?xi64> attributes {tf_entry} {
119
+ // CHECK: memref.alloc
120
+ // CHECK-SAME: reuse_input_candidates = [1 : i32]
121
+ %result = memref.alloc(%n) : memref<?xi64>
122
+ linalg.generic {
123
+ indexing_maps = [affine_map<(i,j) -> (i)>, affine_map<(i,j) -> (i,j)>, affine_map<(i,j) -> (j)>],
124
+ iterator_types = ["parallel", "parallel"]
125
+ } ins(%arg0, %arg1 : memref<?xi64>, memref<?x?xi64>)
126
+ outs(%result : memref<?xi64>) {
127
+ ^bb0(%a : i64, %b : i64, %c : i64):
128
+ %add = arith.addi %a, %b : i64
129
+ linalg.yield %add : i64
130
+ }
131
+ func.return %result : memref<?xi64>
132
+ }
133
+
134
+ // CHECK-LABEL: @nolocal_reuse_with_broadcasting_memref_maps2
135
+ func.func @nolocal_reuse_with_broadcasting_memref_maps2(
136
+ %arg0 : memref<?x?x?xi64>, %arg1 : memref<?x?x?xi64>, %n : index)
137
+ -> memref<?x?xi64> attributes {tf_entry} {
138
+ // CHECK: memref.alloc
139
+ // CHECK-SAME: reuse_input_candidates = []
140
+ %result = memref.alloc(%n, %n) : memref<?x?xi64>
141
+ linalg.generic {
142
+ indexing_maps = [affine_map<(i,j,k) -> (i,j,k)>, affine_map<(i,j,k) -> (i,j,k)>, affine_map<(i,j,k) -> (k,i)>],
143
+ iterator_types = ["parallel", "parallel", "parallel"]
144
+ } ins(%arg0, %arg1 : memref<?x?x?xi64>, memref<?x?x?xi64>)
145
+ outs(%result : memref<?x?xi64>) {
146
+ ^bb0(%a : i64, %b : i64, %c : i64):
147
+ %add = arith.addi %a, %b : i64
148
+ linalg.yield %add : i64
149
+ }
150
+ func.return %result : memref<?x?xi64>
151
+ }
152
+
153
+ // CHECK-LABEL: @memref.reinterpret_cast_alias
154
+ func.func @memref.reinterpret_cast_alias(%arg : memref<f32>, %n : index)
155
+ -> memref<?xf32> attributes {tf_entry} {
156
+ %c0 = arith.constant 0 : index
157
+ %reinterpreted = memref.reinterpret_cast %arg to
158
+ offset: [0],
159
+ sizes: [%n],
160
+ strides: [%c0]: memref<f32> to memref<?xf32, strided<[?], offset: ?>>
161
+
162
+ // CHECK: memref.alloc
163
+ // CHECK-SAME: reuse_input_candidates = [0 : i32]
164
+ %result = memref.alloc(%n) : memref<?xf32>
165
+
166
+ // reinterpreted (arg) and result are of same size.
167
+ linalg.generic {
168
+ indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>],
169
+ iterator_types = ["parallel"]
170
+ } ins(%reinterpreted : memref<?xf32, strided<[?], offset: ?>>) outs(%result : memref<?xf32>) {
171
+ ^bb0(%a : f32, %b : f32):
172
+ linalg.yield %a : f32
173
+ }
174
+
175
+ func.return %result : memref<?xf32>
176
+ }
177
+
178
+ // CHECK-LABEL: @memref.cast_alias
179
+ func.func @memref.cast_alias(%arg : memref<*xf32>, %n : index)
180
+ -> memref<?xf32> attributes {tf_entry} {
181
+ %casted = memref.cast %arg : memref<*xf32> to memref<?xf32>
182
+
183
+ // CHECK: memref.alloc
184
+ // CHECK-SAME: reuse_input_candidates = [0 : i32]
185
+ %result = memref.alloc(%n) : memref<?xf32>
186
+
187
+ // reinterpreted (arg) and result are of same size.
188
+ linalg.generic {
189
+ indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>],
190
+ iterator_types = ["parallel"]
191
+ } ins(%casted : memref<?xf32>) outs(%result : memref<?xf32>) {
192
+ ^bb0(%a : f32, %b : f32):
193
+ linalg.yield %a : f32
194
+ }
195
+
196
+ func.return %result : memref<?xf32>
197
+ }
198
+
199
+ // CHECK-LABEL: @indirect_size_equality
200
+ func.func @indirect_size_equality(%arg0 : memref<?xi64>,
201
+ %arg1 : memref<?xi64>,
202
+ %n : index) -> memref<?xi64>
203
+ attributes {tf_entry} {
204
+ // arg0 and arg1 are equal in size.
205
+ linalg.generic {
206
+ indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>],
207
+ iterator_types = ["parallel"]
208
+ } ins(%arg0 : memref<?xi64>) outs(%arg1 : memref<?xi64>) {
209
+ ^bb0(%a : i64, %b : i64):
210
+ linalg.yield %a : i64
211
+ }
212
+
213
+ // CHECK: memref.alloc
214
+ // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32]
215
+ %result = memref.alloc(%n) : memref<?xi64>
216
+
217
+ // arg0 and result are equal in size.
218
+ linalg.generic {
219
+ indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>],
220
+ iterator_types = ["parallel"]
221
+ } ins(%arg0 : memref<?xi64>) outs(%result : memref<?xi64>) {
222
+ ^bb0(%a : i64, %b : i64):
223
+ linalg.yield %a : i64
224
+ }
225
+
226
+ func.return %result : memref<?xi64>
227
+ }
228
+
229
+ // CHECK-LABEL: @livetimes_incompatible
230
+ func.func @livetimes_incompatible(%arg0 : memref<3xi64>)
231
+ -> memref<3xi64> attributes {tf_entry} {
232
+ // CHECK: memref.alloc
233
+ // CHECK-SAME: reuse_input_candidates = []
234
+ %result = memref.alloc() : memref<3xi64>
235
+
236
+ // Use newly allocated buffer.
237
+ %c0 = arith.constant 0 : index
238
+ %0 = memref.load %result[%c0] : memref<3xi64>
239
+
240
+ // Use argument buffer again.
241
+ %1 = memref.load %arg0[%c0] : memref<3xi64>
242
+
243
+ func.return %result : memref<3xi64>
244
+ }
245
+
246
+ // CHECK-LABEL: @never_used
247
+ func.func @never_used(%arg0 : memref<3xi64>) -> memref<3xi64> attributes {tf_entry} {
248
+ // CHECK: memref.alloc
249
+ // CHECK-SAME: reuse_input_candidates = [0 : i32]
250
+ %result = memref.alloc() : memref<3xi64>
251
+ %c0 = arith.constant 0 : index
252
+ %0 = memref.load %arg0[%c0] : memref<3xi64>
253
+ func.return %result : memref<3xi64>
254
+ }
255
+
256
+ // CHECK-LABEL: @branching_reuse
257
+ func.func @branching_reuse(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64>
258
+ attributes {tf_entry} {
259
+ cf.cond_br %pred, ^bb0, ^bb1
260
+ ^bb0:
261
+ // CHECK: memref.alloc
262
+ // CHECK-SAME: reuse_input_candidates = [1 : i32]
263
+ %mem0 = memref.alloc() : memref<6xi64>
264
+
265
+ // Keep buffer argument live in this branch. Reuse is still possible because
266
+ // the newly allocated buffer was not used yet.
267
+ %c0 = arith.constant 0 : index
268
+ memref.load %arg[%c0] : memref<6xi64>
269
+
270
+ cf.br ^bb2(%mem0 : memref<6xi64>)
271
+ ^bb1:
272
+ // CHECK: memref.alloc
273
+ // CHECK-SAME: reuse_input_candidates = [1 : i32]
274
+ %mem1 = memref.alloc() : memref<6xi64>
275
+ cf.br ^bb2(%mem1 : memref<6xi64>)
276
+ ^bb2(%result : memref<6xi64>):
277
+ func.return %result : memref<6xi64>
278
+ }
279
+
280
+ // CHECK-LABEL: @branching_no_reuse
281
+ func.func @branching_no_reuse(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64>
282
+ attributes {tf_entry} {
283
+ cf.cond_br %pred, ^bb0, ^bb1
284
+ ^bb0:
285
+ // CHECK: memref.alloc
286
+ // CHECK-SAME: reuse_input_candidates = []
287
+ %mem0 = memref.alloc() : memref<6xi64>
288
+
289
+ // Use newly allocated memory immediately.
290
+ %c0 = arith.constant 0 : index
291
+ memref.load %mem0[%c0] : memref<6xi64>
292
+
293
+ // Keep buffer argument live in this branch and prevent reuse.
294
+ memref.load %arg[%c0] : memref<6xi64>
295
+
296
+ cf.br ^bb2(%mem0 : memref<6xi64>)
297
+ ^bb1:
298
+ // CHECK: memref.alloc
299
+ // CHECK-SAME: reuse_input_candidates = [1 : i32]
300
+ %mem1 = memref.alloc() : memref<6xi64>
301
+ cf.br ^bb2(%mem1 : memref<6xi64>)
302
+ ^bb2(%result : memref<6xi64>):
303
+ func.return %result : memref<6xi64>
304
+ }
305
+
306
+ // CHECK-LABEL: @branching_reuse_if
307
+ func.func @branching_reuse_if(%pred : i1, %arg : memref<6xi64>)
308
+ -> memref<6xi64> attributes {tf_entry} {
309
+ %result = scf.if %pred -> (memref<6xi64>) {
310
+ // CHECK: memref.alloc
311
+ // CHECK-SAME: reuse_input_candidates = [1 : i32]
312
+ %mem0 = memref.alloc() : memref<6xi64>
313
+
314
+ // Keep buffer argument live in this branch. Reuse is still possible because
315
+ // the newly allocated buffer was not used yet.
316
+ %c0 = arith.constant 0 : index
317
+ memref.load %arg[%c0] : memref<6xi64>
318
+
319
+ scf.yield %mem0 : memref<6xi64>
320
+ } else {
321
+ // CHECK: memref.alloc
322
+ // CHECK-SAME: reuse_input_candidates = [1 : i32]
323
+ %mem1 = memref.alloc() : memref<6xi64>
324
+ scf.yield %mem1 : memref<6xi64>
325
+ }
326
+ func.return %result : memref<6xi64>
327
+ }
328
+
329
+ // CHECK-LABEL: @branching_no_reuse_if
330
+ func.func @branching_no_reuse_if(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64>
331
+ attributes {tf_entry} {
332
+ %result = scf.if %pred -> (memref<6xi64>) {
333
+ // CHECK: memref.alloc
334
+ // CHECK-SAME: reuse_input_candidates = []
335
+ %mem0 = memref.alloc() : memref<6xi64>
336
+
337
+ // Use newly allocated memory immediately.
338
+ %c0 = arith.constant 0 : index
339
+ memref.load %mem0[%c0] : memref<6xi64>
340
+
341
+ // Keep buffer argument live in this branch and prevent reuse.
342
+ memref.load %arg[%c0] : memref<6xi64>
343
+
344
+ scf.yield %mem0 : memref<6xi64>
345
+ } else {
346
+ // CHECK: memref.alloc
347
+ // CHECK-SAME: reuse_input_candidates = [1 : i32]
348
+ %mem1 = memref.alloc() : memref<6xi64>
349
+ scf.yield %mem1 : memref<6xi64>
350
+ }
351
+ func.return %result : memref<6xi64>
352
+ }
353
+
354
+ // CHECK-LABEL: @alloc_before_branching
355
+ // New buffer is first used in the blocks succeeding its allocation block. In
356
+ // both/all cases the newly allocated buffer is used after the buffer argument
357
+ // is no longer live. Because these first uses are not block-local the analysis
358
+ // does not detect this case (yet). It is correct but incomplete.
359
+ func.func @alloc_before_branching(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64>
360
+ attributes {tf_entry} {
361
+ // CHECK: memref.alloc
362
+ // CHECK-SAME: reuse_input_candidates = []
363
+ %mem = memref.alloc() : memref<6xi64>
364
+ %c0 = arith.constant 0 : index
365
+ cf.cond_br %pred, ^bb0, ^bb1
366
+ ^bb0:
367
+ // Last use of `arg` before first use of `mem` (can reuse).
368
+ memref.load %arg[%c0] : memref<6xi64>
369
+ memref.load %mem[%c0] : memref<6xi64>
370
+ func.return %mem : memref<6xi64>
371
+ ^bb1:
372
+ // Last use of `arg` before first use of `mem` (can reuse).
373
+ memref.load %arg[%c0] : memref<6xi64>
374
+ memref.load %mem[%c0] : memref<6xi64>
375
+ func.return %mem : memref<6xi64>
376
+ }
377
+
378
+ // CHECK-LABEL: @alloc_before_branching_2
379
+ func.func @alloc_before_branching_2(%pred : i1, %arg : memref<6xi64>)
380
+ -> memref<6xi64> attributes {tf_entry} {
381
+ // CHECK: memref.alloc()
382
+ // CHECK-SAME: reuse_input_candidates = []
383
+ %mem = memref.alloc() : memref<6xi64>
384
+ %c0 = arith.constant 0 : index
385
+ cf.cond_br %pred, ^bb0, ^bb1
386
+ ^bb0:
387
+ // Last use of `arg` after first use of `mem` (cannot reuse).
388
+ memref.load %mem[%c0] : memref<6xi64>
389
+ memref.load %arg[%c0] : memref<6xi64>
390
+ func.return %mem : memref<6xi64>
391
+ ^bb1:
392
+ // Last use of `arg` before first use of `mem` (can reuse).
393
+ memref.load %arg[%c0] : memref<6xi64>
394
+ memref.load %mem[%c0] : memref<6xi64>
395
+ func.return %mem : memref<6xi64>
396
+ }
397
+
398
+ // CHECK-LABEL: @alloc_before_branching_if
399
+ // New buffer is first used in the blocks succeeding its allocation block. In
400
+ // both/all cases the newly allocated buffer is used after the buffer argument
401
+ // is no longer live. Because these first uses are not block-local the analysis
402
+ // does not detect this case (yet). It is correct but incomplete.
403
+ func.func @alloc_before_branching_if(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64>
404
+ attributes {tf_entry} {
405
+ // CHECK: memref.alloc
406
+ // CHECK-SAME: reuse_input_candidates = []
407
+ %mem = memref.alloc() : memref<6xi64>
408
+ %result = scf.if %pred -> (memref<6xi64>) {
409
+ // Last use of `arg` before first use of `mem` (can reuse).
410
+ %c0 = arith.constant 0 : index
411
+ memref.load %arg[%c0] : memref<6xi64>
412
+ memref.load %mem[%c0] : memref<6xi64>
413
+ scf.yield %mem : memref<6xi64>
414
+ } else {
415
+ // Last use of `arg` before first use of `mem` (can reuse).
416
+ %c0 = arith.constant 0 : index
417
+ memref.load %arg[%c0] : memref<6xi64>
418
+ memref.load %mem[%c0] : memref<6xi64>
419
+ scf.yield %mem : memref<6xi64>
420
+ }
421
+ func.return %result : memref<6xi64>
422
+ }
423
+
424
+ // CHECK-LABEL: @alloc_before_branching_2_if
425
+ func.func @alloc_before_branching_2_if(%pred : i1, %arg : memref<6xi64>)
426
+ -> memref<6xi64> attributes {tf_entry} {
427
+ // CHECK: memref.alloc
428
+ // CHECK-SAME: reuse_input_candidates = []
429
+ %mem = memref.alloc() : memref<6xi64>
430
+ %result = scf.if %pred -> (memref<6xi64>) {
431
+ // Last use of `arg` after first use of `mem` (cannot reuse).
432
+ %c0 = arith.constant 0 : index
433
+ memref.load %mem[%c0] : memref<6xi64>
434
+ memref.load %arg[%c0] : memref<6xi64>
435
+ scf.yield %mem : memref<6xi64>
436
+ } else {
437
+ // Last use of `arg` before first use of `mem` (can reuse).
438
+ %c0 = arith.constant 0 : index
439
+ memref.load %arg[%c0] : memref<6xi64>
440
+ memref.load %mem[%c0] : memref<6xi64>
441
+ scf.yield %mem : memref<6xi64>
442
+ }
443
+ func.return %result : memref<6xi64>
444
+ }
445
+
446
+ // CHECK-LABEL: @abs_unranked_i64
447
+ func.func @abs_unranked_i64(%arg : memref<*xi64>,
448
+ %arg_shape : memref<?xindex>,
449
+ %flat_shape : memref<1xindex>,
450
+ %arg_size : index) -> memref<*xi64>
451
+ attributes {tf_entry} {
452
+ %flat_arg = memref.reshape %arg(%flat_shape)
453
+ : (memref<*xi64>, memref<1xindex>) -> memref<?xi64>
454
+ // CHECK: memref.alloc
455
+ // CHECK-SAME: reuse_input_candidates = [0 : i32, 2 : i32], reuse_output = 0 : i32
456
+ %flat_result = memref.alloc(%arg_size) : memref<?xi64>
457
+ linalg.generic {
458
+ indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>],
459
+ iterator_types = ["parallel"]
460
+ } ins(%flat_arg : memref<?xi64>) outs(%flat_result : memref<?xi64>) {
461
+ ^bb0(%a : i64, %b : i64):
462
+ %c0 = arith.constant 0 : i64
463
+ %a_pos = arith.cmpi sge, %a, %c0 : i64
464
+ %a_neg = arith.subi %c0, %a : i64
465
+ %a_abs = arith.select %a_pos, %a, %a_neg : i64
466
+ linalg.yield %a_abs : i64
467
+ }
468
+ %result = memref.reshape %flat_result(%arg_shape)
469
+ : (memref<?xi64>, memref<?xindex>) -> memref<*xi64>
470
+ func.return %result : memref<*xi64>
471
+ }
472
+
473
+ // CHECK-LABEL: @old_buffer_alias_outside_block
474
+ func.func @old_buffer_alias_outside_block(%arg: memref<3xf32>)
475
+ attributes {llvm.emit_c_interface, tf_entry} {
476
+ %c0 = arith.constant 0 : index
477
+ %c1 = arith.constant 1 : index
478
+ %true = arith.constant true
479
+
480
+ // Alias outside of the block with the new buffer allocation.
481
+ %alias = memref.cast %arg : memref<3xf32> to memref<3xf32>
482
+
483
+ scf.if %true {
484
+
485
+ // Allocation and use of new buffer.
486
+ // CHECK: memref.alloc
487
+ // CHECK-SAME: reuse_input_candidates = [0 : i32]
488
+ %mem = memref.alloc() : memref<3xf32>
489
+ %use = memref.load %mem[%c0] : memref<3xf32>
490
+
491
+ } else {
492
+ }
493
+ func.return
494
+ }
495
+
496
+ // CHECK-LABEL: @index_element_type
497
+ func.func @index_element_type(%arg : memref<2x3xindex>) -> memref<2x3xindex>
498
+ attributes {tf_entry} {
499
+ // CHECK: memref.alloc
500
+ // CHECK-SAME: reuse_input_candidates = [0 : i32]
501
+ %result = memref.alloc() : memref<2x3xindex>
502
+ func.return %result : memref<2x3xindex>
503
+ }
504
+
505
+ // Example as it occurs in the `tf.Abs` kernel for `f32`.
506
+ // CHECK-LABEL: @abs_f32
507
+ func.func @abs_f32(%arg0: memref<*xf32>) -> memref<*xf32>
508
+ attributes {llvm.emit_c_interface, tf_entry} {
509
+ %c0 = arith.constant 0 : index
510
+ %0 = shape.shape_of %arg0 : memref<*xf32> -> tensor<?xindex>
511
+ %1 = shape.num_elements %0 : tensor<?xindex> -> index
512
+ // CHECK-LABEL: memref.alloc
513
+ // CHECK-SAME: reuse_input_candidates = []
514
+ %2 = memref.alloc() : memref<1xindex>
515
+ memref.store %1, %2[%c0] : memref<1xindex>
516
+ %3 = memref.reshape %arg0(%2)
517
+ : (memref<*xf32>, memref<1xindex>) -> memref<?xf32>
518
+ %4 = memref.dim %3, %c0 : memref<?xf32>
519
+ %5 = arith.index_cast %4 : index to i64
520
+ // CHECK-LABEL: memref.alloc
521
+ // CHECK-SAME: reuse_input_candidates = []
522
+ %6 = memref.alloc() : memref<1xi64>
523
+ memref.store %5, %6[%c0] : memref<1xi64>
524
+ %7 = memref.load %6[%c0] : memref<1xi64>
525
+ %8 = arith.index_cast %7 : i64 to index
526
+ // CHECK-LABEL: memref.alloc
527
+ // CHECK-SAME: reuse_input_candidates = [0 : i32]
528
+ %9 = memref.alloc(%8) : memref<?xf32>
529
+ linalg.generic {
530
+ indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>],
531
+ iterator_types = ["parallel"]
532
+ } ins(%3 : memref<?xf32>) outs(%9 : memref<?xf32>) {
533
+ ^bb0(%arg1: f32, %arg2: f32):
534
+ %12 = math.absf %arg1 : f32
535
+ linalg.yield %12 : f32
536
+ }
537
+ %10 = bufferization.to_buffer %0 : tensor<?xindex> to memref<?xindex>
538
+ %11 = memref.reshape %9(%10)
539
+ : (memref<?xf32>, memref<?xindex>) -> memref<*xf32>
540
+ func.return %11 : memref<*xf32>
541
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/bufferize.mlir ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s --split-input-file --mlir-print-op-generic |\
2
+ // RUN: mlir-hlo-opt --allow-unregistered-dialect \
3
+ // RUN: --computeop-and-func-bufferize |\
4
+ // RUN: kernel-gen-opt \
5
+ // RUN: --kernelgen-final-bufferize | FileCheck %s
6
+ // RUN: kernel-gen-opt %s --split-input-file --mlir-print-op-generic |\
7
+ // RUN: mlir-hlo-opt --allow-unregistered-dialect \
8
+ // RUN: --computeop-and-func-bufferize |\
9
+ // RUN: kernel-gen-opt \
10
+ // RUN: --kernelgen-final-bufferize --promote-buffers-to-stack | FileCheck %s
11
+
12
+ // CHECK-LABEL: @jit_execute
13
+ // CHECK-SAME: (%[[F:.*]]: !tf_framework.jit_callable, %[[ARG:.*]]: memref<*xf32>) -> memref<*xf32>
14
+ func.func @jit_execute(%f : !tf_framework.jit_callable, %arg : tensor<*xf32>)
15
+ -> tensor<*xf32> {
16
+ // CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[F]](%[[ARG]]) : memref<*xf32> -> memref<*xf32>
17
+ // CHECK: return %[[RES]] : memref<*xf32>
18
+ %0 = tf_framework.jit_execute %f(%arg) : tensor<*xf32> -> tensor<*xf32>
19
+ func.return %0 : tensor<*xf32>
20
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/copy_cleanup.mlir ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s --copy-cleanup --split-input-file | FileCheck %s
2
+
3
+ #map0 = affine_map<(d0)[s0] -> (d0 * s0)>
4
+ #map1 = affine_map<(d0) -> (d0)>
5
+ builtin.module {
6
+ func.func @Copy(%lhs: memref<?xi16>, %rhs: memref<?xi16>) {
7
+ %c0 = arith.constant 0 : index
8
+ %c1 = arith.constant 1 : index
9
+ %size = memref.dim %rhs, %c0 : memref<?xi16>
10
+ %lhsCasted = memref.reinterpret_cast %lhs to offset: [0], sizes: [%size], strides: [%c0] : memref<?xi16> to memref<?xi16, #map0>
11
+ %lhsAlloc = memref.alloc(%size) : memref<?xi16>
12
+ memref.copy %lhsCasted, %lhsAlloc : memref<?xi16, #map0> to memref<?xi16>
13
+ %rhsCasted = memref.reinterpret_cast %rhs to offset: [0], sizes: [%size], strides: [%c1] : memref<?xi16> to memref<?xi16, #map0>
14
+ %rhsAlloc = memref.alloc(%size) : memref<?xi16>
15
+ memref.copy %rhsCasted, %rhsAlloc : memref<?xi16, #map0> to memref<?xi16>
16
+ %outputAlloc = memref.alloc(%size) : memref<?xi16>
17
+ linalg.generic {indexing_maps = [#map1, #map1, #map1], iterator_types = ["parallel"]} ins(%lhsAlloc, %rhsAlloc : memref<?xi16>, memref<?xi16>) outs(%outputAlloc : memref<?xi16>) {
18
+ ^bb0(%arg1: i16, %arg2: i16, %arg3 : i16):
19
+ %and = arith.andi %arg1, %arg2 : i16
20
+ linalg.yield %and : i16
21
+ }
22
+ func.return
23
+ }
24
+ }
25
+
26
+ // CHECK-DAG: #[[$MAP0:.*]] = affine_map<(d0)[s0] -> (d0 * s0)>
27
+ // CHECK-DAG: #[[$MAP1:.*]] = affine_map<(d0) -> (d0)>
28
+ // CHECK-LABEL: func @Copy(
29
+ // CHECK-SAME: %[[LHS:.*]]: memref<?xi16>, %[[RHS:.*]]: memref<?xi16>) {
30
+ // CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index
31
+ // CHECK-DAG: %[[C1:.*]] = arith.constant 1 : index
32
+ // CHECK: %[[SIZE:.*]] = memref.dim %[[RHS]], %[[C0]] : memref<?xi16>
33
+ // CHECK: %[[LHS_CASTED:.*]] = memref.reinterpret_cast %[[LHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C0]]] : memref<?xi16> to memref<?xi16, #[[$MAP0]]>
34
+ // CHECK: %[[RHS_CASTED:.*]] = memref.reinterpret_cast %[[RHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C1]]] : memref<?xi16> to memref<?xi16, #[[$MAP0]]>
35
+ // CHECK: %[[OUTPUT:.*]] = memref.alloc(%[[SIZE]]) : memref<?xi16>
36
+ // CHECK: linalg.generic {indexing_maps = [#[[$MAP1]], #[[$MAP1]], #[[$MAP1]]], iterator_types = ["parallel"]} ins(%[[LHS_CASTED]], %[[RHS_CASTED]] : memref<?xi16, #[[$MAP0]]>, memref<?xi16, #[[$MAP0]]>) outs(%{{.*}} : memref<?xi16>) {
37
+ // CHECK: ^bb0(%[[ARG1:.*]]: i16, %[[ARG2:.*]]: i16, %[[ARG3:.*]]: i16):
38
+ // CHECK: %[[AND:.*]] = arith.andi %[[ARG1]], %[[ARG2]] : i16
39
+ // CHECK: linalg.yield %[[AND]] : i16
40
+
41
+ // -----
42
+
43
+ // The target of the copy is also used to write.
44
+
45
+ #map0 = affine_map<(d0)[s0] -> (d0 * s0)>
46
+ #map1 = affine_map<(d0) -> (d0)>
47
+ builtin.module {
48
+ func.func @CopyWithWrite(%lhs: memref<?xi16>, %rhs: memref<?xi16>) {
49
+ %c0 = arith.constant 0 : index
50
+ %c1 = arith.constant 1 : index
51
+ %size = memref.dim %rhs, %c0 : memref<?xi16>
52
+ %lhsCasted = memref.reinterpret_cast %lhs to offset: [0], sizes: [%size], strides: [%c0] : memref<?xi16> to memref<?xi16, #map0>
53
+ %lhsAlloc = memref.alloc(%size) : memref<?xi16>
54
+ memref.copy %lhsCasted, %lhsAlloc : memref<?xi16, #map0> to memref<?xi16>
55
+ %rhsCasted = memref.reinterpret_cast %rhs to offset: [0], sizes: [%size], strides: [%c1] : memref<?xi16> to memref<?xi16, #map0>
56
+ %rhsAlloc = memref.alloc(%size) : memref<?xi16>
57
+ memref.copy %rhsCasted, %rhsAlloc : memref<?xi16, #map0> to memref<?xi16>
58
+ linalg.generic {indexing_maps = [#map1, #map1, #map1], iterator_types = ["parallel"]} ins(%lhsAlloc, %rhsAlloc : memref<?xi16>, memref<?xi16>) outs(%rhsAlloc : memref<?xi16>) {
59
+ ^bb0(%arg1: i16, %arg2: i16, %arg3 : i16):
60
+ %and = arith.andi %arg1, %arg2 : i16
61
+ linalg.yield %and : i16
62
+ }
63
+ func.return
64
+ }
65
+ }
66
+
67
+ // CHECK-DAG: #[[$MAP0:.*]] = affine_map<(d0)[s0] -> (d0 * s0)>
68
+ // CHECK-DAG: #[[$MAP1:.*]] = affine_map<(d0) -> (d0)>
69
+ // CHECK-LABEL: func @CopyWithWrite(
70
+ // CHECK-SAME: %[[LHS:.*]]: memref<?xi16>, %[[RHS:.*]]: memref<?xi16>) {
71
+ // CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index
72
+ // CHECK-DAG: %[[C1:.*]] = arith.constant 1 : index
73
+ // CHECK: %[[SIZE:.*]] = memref.dim %[[RHS]], %[[C0]] : memref<?xi16>
74
+ // CHECK: %[[LHS_CASTED:.*]] = memref.reinterpret_cast %[[LHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C0]]] : memref<?xi16> to memref<?xi16, #[[$MAP0]]>
75
+ // CHECK: %[[RHS_CASTED:.*]] = memref.reinterpret_cast %[[RHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C1]]] : memref<?xi16> to memref<?xi16, #[[$MAP0]]>
76
+ // CHECK: %[[RHS_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref<?xi16>
77
+ // CHECK: memref.copy %[[RHS_CASTED]], %[[RHS_ALLOC]]
78
+ // CHECK: linalg.generic {indexing_maps = [#[[$MAP1]], #[[$MAP1]], #[[$MAP1]]], iterator_types = ["parallel"]} ins(%[[LHS_CASTED]], %[[RHS_ALLOC]] : memref<?xi16, #[[$MAP0]]>, memref<?xi16>) outs(%[[RHS_ALLOC]] : memref<?xi16>) {
79
+ // CHECK: ^bb0(%[[ARG1:.*]]: i16, %[[ARG2:.*]]: i16, %[[ARG3:.*]]: i16):
80
+ // CHECK: %[[AND:.*]] = arith.andi %[[ARG1]], %[[ARG2]] : i16
81
+ // CHECK: linalg.yield %[[AND]] : i16
82
+
83
+ // -----
84
+
85
+ // The source of the copy is mutated.
86
+
87
+ #map0 = affine_map<(d0)[s0] -> (d0 * s0)>
88
+ #map1 = affine_map<(d0) -> (d0)>
89
+ builtin.module {
90
+ func.func @CopyWithMutation(%lhs: memref<?xi16>, %rhs: memref<?xi16>) {
91
+ %c0 = arith.constant 0 : index
92
+ %c1 = arith.constant 1 : index
93
+ %c42 = arith.constant 42 : i16
94
+ %size = memref.dim %rhs, %c0 : memref<?xi16>
95
+ %lhsCasted = memref.reinterpret_cast %lhs to offset: [0], sizes: [%size], strides: [%c0] : memref<?xi16> to memref<?xi16, #map0>
96
+ %lhsAlloc = memref.alloc(%size) : memref<?xi16>
97
+ memref.copy %lhsCasted, %lhsAlloc : memref<?xi16, #map0> to memref<?xi16>
98
+ %rhsCasted = memref.reinterpret_cast %rhs to offset: [0], sizes: [%size], strides: [%c1] : memref<?xi16> to memref<?xi16, #map0>
99
+ %rhsAlloc = memref.alloc(%size) : memref<?xi16>
100
+ memref.copy %rhsCasted, %rhsAlloc : memref<?xi16, #map0> to memref<?xi16>
101
+ %outputAlloc = memref.alloc(%size) : memref<?xi16>
102
+ memref.store %c42, %lhs[%c0] : memref<?xi16>
103
+ linalg.generic {indexing_maps = [#map1, #map1, #map1], iterator_types = ["parallel"]} ins(%lhsAlloc, %rhsAlloc : memref<?xi16>, memref<?xi16>) outs(%outputAlloc : memref<?xi16>) {
104
+ ^bb0(%arg1: i16, %arg2: i16, %arg3 : i16):
105
+ %and = arith.andi %arg1, %arg2 : i16
106
+ linalg.yield %and : i16
107
+ }
108
+ func.return
109
+ }
110
+ }
111
+
112
+ // CHECK-DAG: #[[$MAP0:.*]] = affine_map<(d0)[s0] -> (d0 * s0)>
113
+ // CHECK-DAG: #[[$MAP1:.*]] = affine_map<(d0) -> (d0)>
114
+ // CHECK-LABEL: func @CopyWithMutation(
115
+ // CHECK-SAME: %[[LHS:.*]]: memref<?xi16>, %[[RHS:.*]]: memref<?xi16>) {
116
+ // CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index
117
+ // CHECK-DAG: %[[C1:.*]] = arith.constant 1 : index
118
+ // CHECK: %[[SIZE:.*]] = memref.dim %[[RHS]], %[[C0]] : memref<?xi16>
119
+ // CHECK: %[[LHS_CASTED:.*]] = memref.reinterpret_cast %[[LHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C0]]] : memref<?xi16> to memref<?xi16, #[[$MAP0]]>
120
+ // CHECK: %[[LHS_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref<?xi16>
121
+ // CHECK: memref.copy %[[LHS_CASTED]], %[[LHS_ALLOC]]
122
+ // CHECK: %[[RHS_CASTED:.*]] = memref.reinterpret_cast %[[RHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C1]]] : memref<?xi16> to memref<?xi16, #[[$MAP0]]>
123
+ // CHECK: %[[RHS_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref<?xi16>
124
+ // CHECK: memref.copy %[[RHS_CASTED]], %[[RHS_ALLOC]]
125
+ // CHECK: %[[OUTPUT_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref<?xi16>
126
+ // CHECK: linalg.generic {indexing_maps = [#[[$MAP1]], #[[$MAP1]], #[[$MAP1]]], iterator_types = ["parallel"]} ins(%[[LHS_ALLOC]], %[[RHS_ALLOC]] : memref<?xi16>, memref<?xi16>) outs(%[[OUTPUT_ALLOC]] : memref<?xi16>) {
127
+ // CHECK: ^bb0(%[[ARG1:.*]]: i16, %[[ARG2:.*]]: i16, %[[ARG3:.*]]: i16):
128
+ // CHECK: %[[AND:.*]] = arith.andi %[[ARG1]], %[[ARG2]] : i16
129
+ // CHECK: linalg.yield %[[AND]] : i16
130
+
131
+ // -----
132
+
133
+ #map0 = affine_map<(d0) -> (d0)>
134
+ builtin.module {
135
+ func.func @testCopyAfterLinalg(%arg2: memref<4xi32>, %arg3: memref<4xi32>, %arg4: memref<4xi32>) {
136
+ %0 = memref.alloc() : memref<4xi32>
137
+ linalg.generic {indexing_maps = [#map0, #map0, #map0], iterator_types = ["parallel"]} ins(%arg2, %arg3 : memref<4xi32>, memref<4xi32>) outs(%0 : memref<4xi32>) {
138
+ ^bb0(%arg5: i32, %arg6: i32, %arg7: i32):
139
+ %1 = arith.addi %arg5, %arg6 : i32
140
+ linalg.yield %1 : i32
141
+ }
142
+ memref.copy %0, %arg4 : memref<4xi32> to memref<4xi32>
143
+ func.return
144
+ }
145
+ }
146
+
147
+ // CHECK: #[[$MAP0:.*]] = affine_map<(d0) -> (d0)>
148
+ // CHECK-LABEL:func @testCopyAfterLinalg(
149
+ // CHECK-SAME: %[[ARG0:.*]]: memref<4xi32>, %[[ARG1:.*]]: memref<4xi32>, %[[ARG2:.*]]: memref<4xi32>) {
150
+ // CHECK: linalg.generic {indexing_maps = [#[[$MAP0]], #[[$MAP0]], #[[$MAP0]]], iterator_types = ["parallel"]} ins(%[[ARG0]], %[[ARG1]] : memref<4xi32>, memref<4xi32>) outs(%[[ARG2]] : memref<4xi32>) {
151
+ // CHECK: ^bb0(%[[ARG3:.*]]: i32, %[[ARG4:.*]]: i32, %[[ARG5:.*]]: i32):
152
+ // CHECK: %[[R1:.*]] = arith.addi %[[ARG3]], %[[ARG4]] : i32
153
+ // CHECK: linalg.yield %[[R1]] : i32
154
+ // CHECK: }
155
+ // CHECK: return
156
+ // CHECK: }
157
+
158
+ // -----
159
+
160
+ #map0 = affine_map<(d0) -> (d0)>
161
+ builtin.module {
162
+ func.func @testCopyAfterLinalgMutated(%arg2: memref<4xi32>, %arg3: memref<4xi32>, %arg4: memref<4xi32>) {
163
+ %c0 = arith.constant 0 : index
164
+ %c42 = arith.constant 42 : i32
165
+ %0 = memref.alloc() : memref<4xi32>
166
+ linalg.generic {indexing_maps = [#map0, #map0, #map0], iterator_types = ["parallel"]} ins(%arg2, %arg3 : memref<4xi32>, memref<4xi32>) outs(%0 : memref<4xi32>) {
167
+ ^bb0(%arg5: i32, %arg6: i32, %arg7: i32):
168
+ %1 = arith.addi %arg5, %arg6 : i32
169
+ linalg.yield %1 : i32
170
+ }
171
+ memref.copy %0, %arg4 : memref<4xi32> to memref<4xi32>
172
+ memref.store %c42, %0[%c0] : memref<4xi32>
173
+ func.return
174
+ }
175
+ }
176
+
177
+ // CHECK: #[[$MAP0:.*]] = affine_map<(d0) -> (d0)>
178
+ // CHECK-LABEL:func @testCopyAfterLinalgMutated(
179
+ // CHECK-SAME: %[[ARG0:.*]]: memref<4xi32>, %[[ARG1:.*]]: memref<4xi32>, %[[ARG2:.*]]: memref<4xi32>) {
180
+ // CHECK: %[[ALLOC:.*]] = memref.alloc() : memref<4xi32>
181
+ // CHECK: linalg.generic {indexing_maps = [#[[$MAP0]], #[[$MAP0]], #[[$MAP0]]], iterator_types = ["parallel"]} ins(%[[ARG0]], %[[ARG1]] : memref<4xi32>, memref<4xi32>) outs(%[[ALLOC]] : memref<4xi32>) {
182
+ // CHECK: ^bb0(%[[ARG3:.*]]: i32, %[[ARG4:.*]]: i32, %[[ARG5:.*]]: i32):
183
+ // CHECK: %[[R1:.*]] = arith.addi %[[ARG3]], %[[ARG4]] : i32
184
+ // CHECK: linalg.yield %[[R1]] : i32
185
+ // CHECK: }
186
+ // CHECK: memref.copy %[[ALLOC]], %[[ARG2]]
187
+ // CHECK: return
188
+ // CHECK: }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/embed_tf_framework.mlir ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s -split-input-file -verify-diagnostics -embed-tf-framework |\
2
+ // RUN: FileCheck %s
3
+
4
+ // CHECK-LABEL: func @tf_entry(
5
+ // CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context,
6
+ // CHECK-SAME: [[SIZE_0:%.*]]: index,
7
+ // CHECK-SAME: [[SIZE_2:%.*]]: index) -> index attributes {tf_entry} {
8
+ func.func @tf_entry(%size_0 : index , %size_2 : index) -> index
9
+ attributes {tf_entry} {
10
+ %buf = memref.alloc(%size_0, %size_2)[] : memref<?x10x?xf32>
11
+ memref.dealloc %buf : memref<?x10x?xf32>
12
+ func.return %size_0 : index
13
+ }
14
+ // CHECK-NEXT: [[BUF:%.*]] = tf_framework.alloc
15
+ // CHECK-SAME: ([[CTX]], [[SIZE_0]], [[SIZE_2]]) : memref<?x10x?xf32>
16
+
17
+ // CHECK-NEXT: [[IS_VALID:%.*]] = tf_framework.is_valid_memref([[BUF]])
18
+ // CHECK-SAME: memref<?x10x?xf32> -> i1
19
+
20
+ // CHECK-NEXT: tf_framework.assert [[CTX]], [[IS_VALID]],
21
+ // CHECK-SAME: RESOURCE_EXHAUSTED, "failed to allocate memory"
22
+
23
+ // CHECK-NEXT: tf_framework.dealloc([[CTX]], [[BUF]]) : memref<?x10x?xf32>
24
+ // CHECK-NEXT: return [[SIZE_0]] : index
25
+
26
+ // -----
27
+
28
+ // CHECK-LABEL: func @non_tf_entry(
29
+ // CHECK-SAME: [[SIZE_0:%.*]]: index, [[SIZE_2:%.*]]: index) -> index
30
+ func.func @non_tf_entry(%size_0 : index , %size_2 : index) -> index {
31
+ func.return %size_0 : index
32
+ }
33
+
34
+ // -----
35
+
36
+ func.func @tf_entry_no_ctx(%size : index) attributes {tf_entry} {
37
+ // expected-error @+1 {{failed to legalize operation 'memref.alloc' that was explicitly marked illegal}}
38
+ %buf = memref.alloc()[%size] : memref<64xf32, affine_map<(d0)[s0] -> (d0 + s0)>>
39
+ memref.dealloc %buf : memref<64xf32, affine_map<(d0)[s0] -> (d0 + s0)>>
40
+ func.return
41
+ }
42
+
43
+ // -----
44
+
45
+ // CHECK-LABEL: func @assert(
46
+ // CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context
47
+ func.func @assert(%arg0: !tf_framework.op_kernel_context) attributes {tf_entry} {
48
+ %true = arith.constant true
49
+ cf.assert %true, "the one and only"
50
+ func.return
51
+ }
52
+ // CHECK: [[TRUE:%.*]] = arith.constant true
53
+ // CHECK-NEXT: tf_framework.assert [[CTX]], [[TRUE]], INVALID_ARGUMENT
54
+
55
+ // -----
56
+
57
+ // CHECK-LABEL: func @jit_execute
58
+ // CHECK-SAME: %[[CTX:.*]]: !tf_framework.op_kernel_context,
59
+ // CHECK-SAME: %[[F:.*]]: !tf_framework.jit_callable,
60
+ // CHECK-SAME: %[[ARG0:.*]]: tensor<2x?xf32>,
61
+ // CHECK-SAME: %[[ARG1:.*]]: tensor<2x?xf32>
62
+ func.func @jit_execute(%ctx : !tf_framework.op_kernel_context,
63
+ %f : !tf_framework.jit_callable, %arg0 : tensor<2x?xf32>,
64
+ %arg1 : tensor<2x?xf32>) -> tensor<2x?xf32> attributes {tf_entry} {
65
+ // CHECK: %[[RES:.*]] = tf_framework.jit_execute
66
+ // CHECK-SAME: ctx(%[[CTX]]) %[[F]](%[[ARG0]], %[[ARG1]])
67
+ // CHECK: return %[[RES]]
68
+ %0 = tf_framework.jit_execute %f(%arg0, %arg1)
69
+ : tensor<2x?xf32>, tensor<2x?xf32> -> tensor<2x?xf32>
70
+ func.return %0 : tensor<2x?xf32>
71
+ }
72
+
73
+ // -----
74
+
75
+ // CHECK-LABEL: func @jit_compile_from_str
76
+ // CHECK-SAME: (%[[CTX:.*]]: !tf_framework.op_kernel_context)
77
+ func.func @jit_compile_from_str(%ctx : !tf_framework.op_kernel_context)
78
+ -> !tf_framework.jit_callable attributes {tf_entry} {
79
+ // CHECK: %[[RES:.*]] = tf_framework.jit_compile_from_str %[[CTX]], "placeholder"
80
+ // CHECK: return %[[RES]]
81
+ %0 = tf_framework.jit_compile_from_str "placeholder" {
82
+ architectures = ["sm_123", "sm_456"], tileSizes = [1, 2, 3],
83
+ unrollFactors = [4], enableFtz = false,
84
+ index64Bit = false, cpuCodegen = false }
85
+ func.return %0 : !tf_framework.jit_callable
86
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/func_to_jit_invocations.mlir ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s --split-input-file \
2
+ // RUN: --func-to-jit-invocation="tile-sizes=1,2,3 unroll-factors=3,2,1 \
3
+ // RUN: enable-ftz=false cpu-codegen=false" | \
4
+ // RUN: FileCheck %s
5
+
6
+ // RUN: kernel-gen-opt %s --split-input-file \
7
+ // RUN: --func-to-jit-invocation="tile-sizes=1,2,3 unroll-factors=3,2,1 \
8
+ // RUN: enable-ftz=false cpu-codegen=false \
9
+ // RUN: jit_i64_indexed_for_large_tensors=true" | \
10
+ // RUN: FileCheck %s --check-prefix=CHECK-JFLT
11
+
12
+ func.func @unary_tanh(%arg : tensor<?xf32>) -> tensor<?xf32> {
13
+ %0 = mhlo.tanh %arg : tensor<?xf32>
14
+ func.return %0 : tensor<?xf32>
15
+ }
16
+
17
+ // CHECK-LABEL: @unary_tanh
18
+ // CHECK-SAME: %[[ARG:.*]]: tensor<?xf32>
19
+ // CHECK: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str
20
+ // CHECK-SAME: "
21
+ // CHECK-SAME: module {
22
+ // CHECK-SAME: func @main(%[[ARG_JIT:.*]]: tensor<?xf32>) -> tensor<?xf32>
23
+ // CHECK-SAME: attributes {tf_entry}
24
+ // CHECK-SAME: {
25
+ // CHECK-SAME: %[[RES_JIT:.*]] = mhlo.tanh %[[ARG_JIT]]
26
+ // CHECK-SAME: return %[[RES_JIT]]
27
+ // CHECK-SAME: }
28
+ // CHECK-SAME: }
29
+ // CHECK-SAME: "
30
+ // CHECK-SAME: {
31
+ // CHECK-SAME: cpuCodegen = false
32
+ // CHECK-SAME: enableFtz = false
33
+ // CHECK-SAME: tileSizes = [1, 2, 3]
34
+ // CHECK-SAME: unrollFactors = [3, 2, 1]
35
+ // CHECK-SAME: }
36
+ // CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG]])
37
+ // CHECK: return %[[RES]]
38
+
39
+ // CHECK-JFLT-LABEL: @unary_tanh
40
+ // CHECK-JFLT-SAME: %[[ARG0:.*]]: tensor<?xf32>
41
+ // CHECK-JFLT: %[[SHAPE:.*]] = shape.shape_of %[[ARG0]]
42
+ // CHECK-JFLT: %[[NUM:.*]] = shape.num_elements %[[SHAPE]]
43
+ // CHECK-JFLT: %[[LIMIT:.*]] = arith.constant 2147483647
44
+ // CHECK-JFLT: %[[CMPI:.*]] = arith.cmpi sgt, %[[NUM]], %[[LIMIT]]
45
+ // CHECK-JFLT: %[[IF:.*]] = scf.if %[[CMPI]]
46
+ // CHECK-JFLT: %[[JIT:.*]] = tf_framework.jit_compile_from_str
47
+ // CHECK-JFLT-SAME: "module
48
+ // CHECK-JFLT-SAME: cpuCodegen = false
49
+ // CHECK-JFLT-SAME: enableFtz = false
50
+ // CHECK-JFLT-SAME: index64Bit = true
51
+ // CHECK-JFLT-SAME: tileSizes = [1, 2, 3]
52
+ // CHECK-JFLT-SAME: unrollFactors = [3, 2, 1]
53
+ // CHECK-JFLT: %[[JIT_0:.*]] = tf_framework.jit_execute %[[JIT]](%[[ARG0]])
54
+ // CHECK-JFLT: scf.yield %[[JIT_0]]
55
+ // CHECK-JFLT: else
56
+ // CHECK-JFLT: %[[VAL:.*]] = mhlo.tanh %[[ARG0]]
57
+ // CHECK-JFLT: scf.yield %[[VAL]]
58
+ // CHECK-JFLT: return %[[IF]]
59
+
60
+ // -----
61
+
62
+ func.func @binary_sub(%arg0 : tensor<*xf32>, %arg1 : tensor<*xf32>) -> tensor<*xf32> {
63
+ %0 = chlo.broadcast_subtract %arg0, %arg1 : (tensor<*xf32>, tensor<*xf32>) -> tensor<*xf32>
64
+ func.return %0 : tensor<*xf32>
65
+ }
66
+
67
+ // CHECK-LABEL: @binary_sub
68
+ // CHECK-SAME: %[[ARG0:.*]]: tensor<*xf32>, %[[ARG1:.*]]: tensor<*xf32>
69
+ // CHECK: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str
70
+ // CHECK-SAME: "
71
+ // CHECK-SAME: module {
72
+ // CHECK-SAME: func @main(%[[ARG0_JIT:.*]]: tensor<*xf32>, %[[ARG1_JIT:.*]]: tensor<*xf32>) -> tensor<*xf32>
73
+ // CHECK-SAME: attributes {tf_entry}
74
+ // CHECK-SAME: {
75
+ // CHECK-SAME: %[[RES_JIT:.*]] = chlo.broadcast_subtract %[[ARG0_JIT]], %[[ARG1_JIT]]
76
+ // CHECK-SAME: return %[[RES_JIT]]
77
+ // CHECK-SAME: }
78
+ // CHECK-SAME: }
79
+ // CHECK-SAME: "
80
+ // CHECK-SAME: {
81
+ // CHECK-SAME: cpuCodegen = false
82
+ // CHECK-SAME: enableFtz = false
83
+ // CHECK-SAME: tileSizes = [1, 2, 3]
84
+ // CHECK-SAME: unrollFactors = [3, 2, 1]
85
+ // CHECK-SAME: }
86
+ // CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG0]], %[[ARG1]])
87
+ // CHECK: return %[[RES]]
88
+
89
+ // CHECK-JFLT-LABEL: @binary_sub
90
+ // CHECK-JFLT: %[[ARG0:.*]]: tensor<*xf32>, %[[ARG1:.*]]: tensor<*xf32>
91
+ // CHECK-JFLT: %[[SHAPE1:.*]] = shape.shape_of %[[ARG0]] : tensor<*xf32> -> tensor<?xindex>
92
+ // CHECK-JFLT: %[[ELEMENTCOUNT1:.*]] = shape.num_elements %[[SHAPE1]] : tensor<?xindex> -> index
93
+ // CHECK-JFLT: %[[LIMIT:.*]] = arith.constant 2147483647
94
+ // CHECK-JFLT: %[[COMP1:.*]] = arith.cmpi sgt, %[[ELEMENTCOUNT1]], %[[LIMIT]] : index
95
+ // CHECK-JFLT: %[[SHAPE2:.*]] = shape.shape_of %[[ARG1]] : tensor<*xf32> -> tensor<?xindex>
96
+ // CHECK-JFLT: %[[ELEMENTCOUNT2:.*]] = shape.num_elements %[[SHAPE2]] : tensor<?xindex> -> index
97
+ // CHECK-JFLT: %[[COMP2:.*]] = arith.cmpi sgt, %[[ELEMENTCOUNT2]], %[[LIMIT]] : index
98
+ // CHECK-JFLT: %[[COMPRES:.*]] = arith.ori %[[COMP1]], %[[COMP2]] : i1
99
+ // CHECK-JFLT: %[[IFRES:.*]] = scf.if %[[COMPRES]] -> (tensor<*xf32>) {
100
+ // CHECK-JFLT: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str
101
+ // CHECK-JFLT-SAME: "
102
+ // CHECK-JFLT-SAME: module {
103
+ // CHECK-JFLT-SAME: func @main(%[[ARG0_JIT:.*]]: tensor<*xf32>, %[[ARG1_JIT:.*]]: tensor<*xf32>) -> tensor<*xf32>
104
+ // CHECK-JFLT-SAME: attributes {tf_entry}
105
+ // CHECK-JFLT-SAME: {
106
+ // CHECK-JFLT-SAME: %[[RES_JIT:.*]] = chlo.broadcast_subtract %[[ARG0_JIT]], %[[ARG1_JIT]]
107
+ // CHECK-JFLT-SAME: return %[[RES_JIT]]
108
+ // CHECK-JFLT-SAME: }
109
+ // CHECK-JFLT-SAME: }
110
+ // CHECK-JFLT-SAME: "
111
+ // CHECK-JFLT-SAME: {
112
+ // CHECK-JFLT-SAME: cpuCodegen = false
113
+ // CHECK-JFLT-SAME: enableFtz = false
114
+ // CHECK-JFLT-SAME: tileSizes = [1, 2, 3]
115
+ // CHECK-JFLT-SAME: unrollFactors = [3, 2, 1]
116
+ // CHECK-JFLT-SAME: }
117
+ // CHECK-JFLT: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG0]], %[[ARG1]])
118
+ // CHECK-JFLT: scf.yield %[[RES]] : tensor<*xf32>
119
+ // CHECK-JFLT: } else {
120
+ // CHECK-JFLT: %[[RES2:.*]] = chlo.broadcast_subtract %[[ARG0]], %[[ARG1]] : (tensor<*xf32>, tensor<*xf32>) -> tensor<*xf32>
121
+ // CHECK-JFLT: scf.yield %[[RES2]] : tensor<*xf32>
122
+ // CHECK-JFLT: }
123
+ // CHECK-JFLT: return %[[IFRES]]
124
+
125
+ // -----
126
+
127
+ func.func @reciprocal(%arg0: tensor<*xf32>)
128
+ -> tensor<*xf32> attributes {tf_entry, llvm.emit_c_interface} {
129
+ %0 = mhlo.constant dense<1.0> : tensor<f32>
130
+ %1 = chlo.broadcast_divide %0, %arg0 : (tensor<f32>, tensor<*xf32>) -> tensor<*xf32>
131
+ func.return %1 : tensor<*xf32>
132
+ }
133
+
134
+ // CHECK-LABEL: @reciprocal
135
+ // CHECK-SAME: %[[ARG:.*]]: tensor<*xf32>
136
+ // CHECK: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str
137
+ // CHECK-SAME: module {
138
+ // CHECK-SAME: func.func @main(%[[ARG0_JIT:.*]]: tensor<*xf32>) -> tensor<*xf32>
139
+ // CHECK-SAME: %[[CST:.*]] = mhlo.constant dense<1.000000e+00> : tensor<f32>
140
+ // CHECK-SAME: %[[RES_JIT:.*]] = chlo.broadcast_divide %[[CST]], %[[ARG0_JIT]] : (tensor<f32>, tensor<*xf32>) -> tensor<*xf32>
141
+ // CHECK=SAME: return %[[RES_JIT]] : tensor<*xf32>
142
+ // CHECK-SAME: }
143
+ // CHECK-SAME: }
144
+ // CHECK-SAME: {
145
+ // CHECK-SAME: cpuCodegen = false,
146
+ // CHECK-SAME: enableFtz = false,
147
+ // CHECK-SAME: index64Bit = false,
148
+ // CHECK-SAME: tileSizes = [1, 2, 3],
149
+ // CHECK-SAME: unrollFactors = [3, 2, 1]
150
+ // CHECK-SAME: }
151
+ // CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG]]) : tensor<*xf32> -> tensor<*xf32>
152
+ // CHECK: return %[[RES]] : tensor<*xf32>
153
+
154
+ // CHECK-JFLT-LABEL: @reciprocal
155
+ // CHECK-JFLT-SAME: %[[ARG0:.*]]: tensor<*xf32>
156
+ // CHECK-JFLT: %[[SHAPE:.*]] = shape.shape_of %[[ARG0]]
157
+ // CHECK-JFLT: %[[NUM:.*]] = shape.num_elements %[[SHAPE]]
158
+ // CHECK-JFLT: %[[LIMIT:.*]] = arith.constant 2147483647
159
+ // CHECK-JFLT: %[[CMPI:.*]] = arith.cmpi sgt, %[[NUM]], %[[LIMIT]]
160
+ // CHECK-JFLT: %[[IF:.*]] = scf.if %[[CMPI]]
161
+ // CHECK-JFLT: %[[JIT:.*]] = tf_framework.jit_compile_from_str
162
+ // CHECK-JFLT-SAME: "module
163
+ // CHECK-JFLT-SAME: cpuCodegen = false
164
+ // CHECK-JFLT-SAME: enableFtz = false
165
+ // CHECK-JFLT-SAME: index64Bit = true
166
+ // CHECK-JFLT-SAME: tileSizes = [1, 2, 3]
167
+ // CHECK-JFLT-SAME: unrollFactors = [3, 2, 1]
168
+ // CHECK-JFLT: %[[JIT_0:.*]] = tf_framework.jit_execute %[[JIT]](%[[ARG0]])
169
+ // CHECK-JFLT: scf.yield %[[JIT_0]]
170
+ // CHECK-JFLT: else
171
+ // CHECK-JFLT: %[[CST:.*]] = mhlo.constant dense<1.000000e+00> : tensor<f32>
172
+ // CHECK-JFLT: %[[VAL:.*]] = chlo.broadcast_divide %[[CST]], %[[ARG0]] : (tensor<f32>, tensor<*xf32>) -> tensor<*xf32>
173
+ // CHECK-JFLT: scf.yield %[[VAL]]
174
+ // CHECK-JFLT: return %[[IF]]
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/BUILD ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ load("//tensorflow/compiler/mlir:glob_lit_test.bzl", "glob_lit_tests")
2
+
3
+ package(
4
+ # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"],
5
+ licenses = ["notice"],
6
+ )
7
+
8
+ glob_lit_tests(
9
+ name = "all_tests",
10
+ data = [":test_utilities"],
11
+ default_tags = [
12
+ # We need access to the CUDA SDK.
13
+ "gpu",
14
+ "no_rocm",
15
+ "nomsan",
16
+ "notsan",
17
+ ],
18
+ driver = "//tensorflow/compiler/mlir:run_lit.sh",
19
+ hermetic_cuda_data_dir = "%S/../../../../../../../../cuda_nvcc",
20
+ test_file_exts = ["mlir"],
21
+ )
22
+
23
+ # Bundle together all of the test utilities that are used by tests.
24
+ filegroup(
25
+ name = "test_utilities",
26
+ testonly = True,
27
+ data = [
28
+ "//tensorflow/compiler/mlir/tools/kernel_gen:hlo_to_kernel",
29
+ "@llvm-project//mlir:run_lit.sh",
30
+ ],
31
+ )
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2.mlir ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70
2
+
3
+ func.func @AddV2(%arg0: tensor<*xf32>, %arg1: tensor<*xf32>) -> tensor<*xf32> attributes {llvm.emit_c_interface, tf_entry} {
4
+ %0 = shape.const_shape [1, 1, 1, 1, 1] : tensor<5xindex>
5
+ %c5 = arith.constant 5 : index
6
+ %1 = shape.const_shape [1, 1, 1, 1] : tensor<4xindex>
7
+ %c4 = arith.constant 4 : index
8
+ %2 = shape.const_shape [1, 1, 1] : tensor<3xindex>
9
+ %c3 = arith.constant 3 : index
10
+ %3 = shape.const_shape [1, 1] : tensor<2xindex>
11
+ %c2 = arith.constant 2 : index
12
+ %4 = shape.const_shape [1] : tensor<1xindex>
13
+ %c1 = arith.constant 1 : index
14
+ %5 = shape.shape_of %arg0 : tensor<*xf32> -> tensor<?xindex>
15
+ %6 = shape.shape_of %arg1 : tensor<*xf32> -> tensor<?xindex>
16
+ %7 = shape.num_elements %5 : tensor<?xindex> -> index
17
+ %8 = arith.cmpi eq, %7, %c1 : index
18
+ %c_empty = arith.constant dense<> : tensor<0xindex>
19
+ %9 = scf.if %8 -> (tensor<*xf32>) {
20
+ %14 = shape.num_elements %6 : tensor<?xindex> -> index
21
+ %from_elements = tensor.from_elements %14 : tensor<1xindex>
22
+ %15 = tensor.reshape %arg0(%c_empty) : (tensor<*xf32>, tensor<0xindex>) -> tensor<f32>
23
+ %16 = tensor.reshape %arg1(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
24
+ %17 = chlo.broadcast_add %15, %16 : (tensor<f32>, tensor<?xf32>) -> tensor<?xf32>
25
+ %cast = tensor.cast %17 : tensor<?xf32> to tensor<*xf32>
26
+ scf.yield %cast : tensor<*xf32>
27
+ } else {
28
+ %14 = shape.num_elements %6 : tensor<?xindex> -> index
29
+ %15 = arith.cmpi eq, %14, %c1 : index
30
+ %16 = scf.if %15 -> (tensor<*xf32>) {
31
+ %17 = shape.num_elements %5 : tensor<?xindex> -> index
32
+ %from_elements = tensor.from_elements %17 : tensor<1xindex>
33
+ %18 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
34
+ %19 = tensor.reshape %arg1(%c_empty) : (tensor<*xf32>, tensor<0xindex>) -> tensor<f32>
35
+ %20 = chlo.broadcast_add %18, %19 : (tensor<?xf32>, tensor<f32>) -> tensor<?xf32>
36
+ %cast = tensor.cast %20 : tensor<?xf32> to tensor<*xf32>
37
+ scf.yield %cast : tensor<*xf32>
38
+ } else {
39
+ %17 = shape.shape_eq %5, %6 : tensor<?xindex>, tensor<?xindex>
40
+ %18 = scf.if %17 -> (tensor<*xf32>) {
41
+ %19 = shape.any %5, %6 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>
42
+ %20 = shape.num_elements %19 : tensor<?xindex> -> index
43
+ %from_elements = tensor.from_elements %20 : tensor<1xindex>
44
+ %21 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
45
+ %22 = tensor.reshape %arg1(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
46
+ %23 = chlo.broadcast_add %21, %22 : (tensor<?xf32>, tensor<?xf32>) -> tensor<?xf32>
47
+ %cast = tensor.cast %23 : tensor<?xf32> to tensor<*xf32>
48
+ scf.yield %cast : tensor<*xf32>
49
+ } else {
50
+ %19:2 = mhlo.minimum_broadcast_shapes %5, %6 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>, tensor<?xindex>
51
+ %20 = shape.rank %19#0 : tensor<?xindex> -> index
52
+ %21 = shape.rank %19#1 : tensor<?xindex> -> index
53
+ %22 = arith.cmpi sgt, %20, %21 : index
54
+ %23 = arith.select %22, %20, %21 : index
55
+ %24 = arith.cmpi ule, %23, %c1 : index
56
+ %25 = scf.if %24 -> (tensor<*xf32>) {
57
+ %26 = shape.broadcast %19#0, %4 : tensor<?xindex>, tensor<1xindex> -> tensor<?xindex>
58
+ %cast = tensor.cast %26 : tensor<?xindex> to tensor<1xindex>
59
+ %27 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
60
+ %28 = shape.broadcast %19#1, %4 : tensor<?xindex>, tensor<1xindex> -> tensor<?xindex>
61
+ %cast_0 = tensor.cast %28 : tensor<?xindex> to tensor<1xindex>
62
+ %29 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
63
+ %30 = chlo.broadcast_add %27, %29 : (tensor<?xf32>, tensor<?xf32>) -> tensor<?xf32>
64
+ %cast_1 = tensor.cast %30 : tensor<?xf32> to tensor<*xf32>
65
+ scf.yield %cast_1 : tensor<*xf32>
66
+ } else {
67
+ %26 = arith.cmpi ule, %23, %c2 : index
68
+ %27 = scf.if %26 -> (tensor<*xf32>) {
69
+ %28 = shape.broadcast %19#0, %3 : tensor<?xindex>, tensor<2xindex> -> tensor<?xindex>
70
+ %cast = tensor.cast %28 : tensor<?xindex> to tensor<2xindex>
71
+ %29 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<2xindex>) -> tensor<?x?xf32>
72
+ %30 = shape.broadcast %19#1, %3 : tensor<?xindex>, tensor<2xindex> -> tensor<?xindex>
73
+ %cast_0 = tensor.cast %30 : tensor<?xindex> to tensor<2xindex>
74
+ %31 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<2xindex>) -> tensor<?x?xf32>
75
+ %32 = chlo.broadcast_add %29, %31 : (tensor<?x?xf32>, tensor<?x?xf32>) -> tensor<?x?xf32>
76
+ %cast_1 = tensor.cast %32 : tensor<?x?xf32> to tensor<*xf32>
77
+ scf.yield %cast_1 : tensor<*xf32>
78
+ } else {
79
+ %28 = arith.cmpi ule, %23, %c3 : index
80
+ %29 = scf.if %28 -> (tensor<*xf32>) {
81
+ %30 = shape.broadcast %19#0, %2 : tensor<?xindex>, tensor<3xindex> -> tensor<?xindex>
82
+ %cast = tensor.cast %30 : tensor<?xindex> to tensor<3xindex>
83
+ %31 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
84
+ %32 = shape.broadcast %19#1, %2 : tensor<?xindex>, tensor<3xindex> -> tensor<?xindex>
85
+ %cast_0 = tensor.cast %32 : tensor<?xindex> to tensor<3xindex>
86
+ %33 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<3xindex>) -> tensor<?x?x?xf32>
87
+ %34 = chlo.broadcast_add %31, %33 : (tensor<?x?x?xf32>, tensor<?x?x?xf32>) -> tensor<?x?x?xf32>
88
+ %cast_1 = tensor.cast %34 : tensor<?x?x?xf32> to tensor<*xf32>
89
+ scf.yield %cast_1 : tensor<*xf32>
90
+ } else {
91
+ %30 = arith.cmpi ule, %23, %c4 : index
92
+ %31 = scf.if %30 -> (tensor<*xf32>) {
93
+ %32 = shape.broadcast %19#0, %1 : tensor<?xindex>, tensor<4xindex> -> tensor<?xindex>
94
+ %cast = tensor.cast %32 : tensor<?xindex> to tensor<4xindex>
95
+ %33 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<4xindex>) -> tensor<?x?x?x?xf32>
96
+ %34 = shape.broadcast %19#1, %1 : tensor<?xindex>, tensor<4xindex> -> tensor<?xindex>
97
+ %cast_0 = tensor.cast %34 : tensor<?xindex> to tensor<4xindex>
98
+ %35 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<4xindex>) -> tensor<?x?x?x?xf32>
99
+ %36 = chlo.broadcast_add %33, %35 : (tensor<?x?x?x?xf32>, tensor<?x?x?x?xf32>) -> tensor<?x?x?x?xf32>
100
+ %cast_1 = tensor.cast %36 : tensor<?x?x?x?xf32> to tensor<*xf32>
101
+ scf.yield %cast_1 : tensor<*xf32>
102
+ } else {
103
+ %32 = arith.cmpi ule, %23, %c5 : index
104
+ cf.assert %32, "Input for dynamic binary or n-ary op lowering was of a rank greater than 5"
105
+ %33 = shape.broadcast %19#0, %0 : tensor<?xindex>, tensor<5xindex> -> tensor<?xindex>
106
+ %cast = tensor.cast %33 : tensor<?xindex> to tensor<5xindex>
107
+ %34 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<5xindex>) -> tensor<?x?x?x?x?xf32>
108
+ %35 = shape.broadcast %19#1, %0 : tensor<?xindex>, tensor<5xindex> -> tensor<?xindex>
109
+ %cast_0 = tensor.cast %35 : tensor<?xindex> to tensor<5xindex>
110
+ %36 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<5xindex>) -> tensor<?x?x?x?x?xf32>
111
+ %37 = chlo.broadcast_add %34, %36 : (tensor<?x?x?x?x?xf32>, tensor<?x?x?x?x?xf32>) -> tensor<?x?x?x?x?xf32>
112
+ %cast_1 = tensor.cast %37 : tensor<?x?x?x?x?xf32> to tensor<*xf32>
113
+ scf.yield %cast_1 : tensor<*xf32>
114
+ }
115
+ scf.yield %31 : tensor<*xf32>
116
+ }
117
+ scf.yield %29 : tensor<*xf32>
118
+ }
119
+ scf.yield %27 : tensor<*xf32>
120
+ }
121
+ scf.yield %25 : tensor<*xf32>
122
+ }
123
+ scf.yield %18 : tensor<*xf32>
124
+ }
125
+ scf.yield %16 : tensor<*xf32>
126
+ }
127
+ %10 = shape.shape_of %arg0 : tensor<*xf32> -> tensor<?xindex>
128
+ %11 = shape.shape_of %arg1 : tensor<*xf32> -> tensor<?xindex>
129
+ %12 = shape.broadcast %10, %11 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>
130
+ %13 = tensor.reshape %9(%12) : (tensor<*xf32>, tensor<?xindex>) -> tensor<*xf32>
131
+ return %13 : tensor<*xf32>
132
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2_unsigned.mlir ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70
2
+
3
+ func.func @AddV2(%arg0: tensor<*xui32>, %arg1: tensor<*xui32>) -> tensor<*xui32> attributes {llvm.emit_c_interface, tf_entry} {
4
+ %0 = shape.const_shape [1, 1, 1, 1, 1] : tensor<5xindex>
5
+ %c5 = arith.constant 5 : index
6
+ %1 = shape.const_shape [1, 1, 1, 1] : tensor<4xindex>
7
+ %c4 = arith.constant 4 : index
8
+ %2 = shape.const_shape [1, 1, 1] : tensor<3xindex>
9
+ %c3 = arith.constant 3 : index
10
+ %3 = shape.const_shape [1, 1] : tensor<2xindex>
11
+ %c2 = arith.constant 2 : index
12
+ %4 = shape.const_shape [1] : tensor<1xindex>
13
+ %c1 = arith.constant 1 : index
14
+ %5 = shape.shape_of %arg0 : tensor<*xui32> -> tensor<?xindex>
15
+ %6 = shape.shape_of %arg1 : tensor<*xui32> -> tensor<?xindex>
16
+ %7 = shape.num_elements %5 : tensor<?xindex> -> index
17
+ %8 = arith.cmpi eq, %7, %c1 : index
18
+ %c_empty = arith.constant dense<> : tensor<0xindex>
19
+ %9 = scf.if %8 -> (tensor<*xui32>) {
20
+ %14 = shape.num_elements %6 : tensor<?xindex> -> index
21
+ %from_elements = tensor.from_elements %14 : tensor<1xindex>
22
+ %15 = tensor.reshape %arg0(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor<ui32>
23
+ %16 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
24
+ %17 = chlo.broadcast_add %15, %16 : (tensor<ui32>, tensor<?xui32>) -> tensor<?xui32>
25
+ %cast = tensor.cast %17 : tensor<?xui32> to tensor<*xui32>
26
+ scf.yield %cast : tensor<*xui32>
27
+ } else {
28
+ %14 = shape.num_elements %6 : tensor<?xindex> -> index
29
+ %15 = arith.cmpi eq, %14, %c1 : index
30
+ %16 = scf.if %15 -> (tensor<*xui32>) {
31
+ %17 = shape.num_elements %5 : tensor<?xindex> -> index
32
+ %from_elements = tensor.from_elements %17 : tensor<1xindex>
33
+ %18 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
34
+ %19 = tensor.reshape %arg1(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor<ui32>
35
+ %20 = chlo.broadcast_add %18, %19 : (tensor<?xui32>, tensor<ui32>) -> tensor<?xui32>
36
+ %cast = tensor.cast %20 : tensor<?xui32> to tensor<*xui32>
37
+ scf.yield %cast : tensor<*xui32>
38
+ } else {
39
+ %17 = shape.shape_eq %5, %6 : tensor<?xindex>, tensor<?xindex>
40
+ %18 = scf.if %17 -> (tensor<*xui32>) {
41
+ %19 = shape.any %5, %6 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>
42
+ %20 = shape.num_elements %19 : tensor<?xindex> -> index
43
+ %from_elements = tensor.from_elements %20 : tensor<1xindex>
44
+ %21 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
45
+ %22 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
46
+ %23 = chlo.broadcast_add %21, %22 : (tensor<?xui32>, tensor<?xui32>) -> tensor<?xui32>
47
+ %cast = tensor.cast %23 : tensor<?xui32> to tensor<*xui32>
48
+ scf.yield %cast : tensor<*xui32>
49
+ } else {
50
+ %19:2 = mhlo.minimum_broadcast_shapes %5, %6 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>, tensor<?xindex>
51
+ %20 = shape.rank %19#0 : tensor<?xindex> -> index
52
+ %21 = shape.rank %19#1 : tensor<?xindex> -> index
53
+ %22 = arith.cmpi sgt, %20, %21 : index
54
+ %23 = arith.select %22, %20, %21 : index
55
+ %24 = arith.cmpi ule, %23, %c1 : index
56
+ %25 = scf.if %24 -> (tensor<*xui32>) {
57
+ %26 = shape.broadcast %19#0, %4 : tensor<?xindex>, tensor<1xindex> -> tensor<?xindex>
58
+ %cast = tensor.cast %26 : tensor<?xindex> to tensor<1xindex>
59
+ %27 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
60
+ %28 = shape.broadcast %19#1, %4 : tensor<?xindex>, tensor<1xindex> -> tensor<?xindex>
61
+ %cast_0 = tensor.cast %28 : tensor<?xindex> to tensor<1xindex>
62
+ %29 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
63
+ %30 = chlo.broadcast_add %27, %29 : (tensor<?xui32>, tensor<?xui32>) -> tensor<?xui32>
64
+ %cast_1 = tensor.cast %30 : tensor<?xui32> to tensor<*xui32>
65
+ scf.yield %cast_1 : tensor<*xui32>
66
+ } else {
67
+ %26 = arith.cmpi ule, %23, %c2 : index
68
+ %27 = scf.if %26 -> (tensor<*xui32>) {
69
+ %28 = shape.broadcast %19#0, %3 : tensor<?xindex>, tensor<2xindex> -> tensor<?xindex>
70
+ %cast = tensor.cast %28 : tensor<?xindex> to tensor<2xindex>
71
+ %29 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<2xindex>) -> tensor<?x?xui32>
72
+ %30 = shape.broadcast %19#1, %3 : tensor<?xindex>, tensor<2xindex> -> tensor<?xindex>
73
+ %cast_0 = tensor.cast %30 : tensor<?xindex> to tensor<2xindex>
74
+ %31 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<2xindex>) -> tensor<?x?xui32>
75
+ %32 = chlo.broadcast_add %29, %31 : (tensor<?x?xui32>, tensor<?x?xui32>) -> tensor<?x?xui32>
76
+ %cast_1 = tensor.cast %32 : tensor<?x?xui32> to tensor<*xui32>
77
+ scf.yield %cast_1 : tensor<*xui32>
78
+ } else {
79
+ %28 = arith.cmpi ule, %23, %c3 : index
80
+ %29 = scf.if %28 -> (tensor<*xui32>) {
81
+ %30 = shape.broadcast %19#0, %2 : tensor<?xindex>, tensor<3xindex> -> tensor<?xindex>
82
+ %cast = tensor.cast %30 : tensor<?xindex> to tensor<3xindex>
83
+ %31 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<3xindex>) -> tensor<?x?x?xui32>
84
+ %32 = shape.broadcast %19#1, %2 : tensor<?xindex>, tensor<3xindex> -> tensor<?xindex>
85
+ %cast_0 = tensor.cast %32 : tensor<?xindex> to tensor<3xindex>
86
+ %33 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<3xindex>) -> tensor<?x?x?xui32>
87
+ %34 = chlo.broadcast_add %31, %33 : (tensor<?x?x?xui32>, tensor<?x?x?xui32>) -> tensor<?x?x?xui32>
88
+ %cast_1 = tensor.cast %34 : tensor<?x?x?xui32> to tensor<*xui32>
89
+ scf.yield %cast_1 : tensor<*xui32>
90
+ } else {
91
+ %30 = arith.cmpi ule, %23, %c4 : index
92
+ %31 = scf.if %30 -> (tensor<*xui32>) {
93
+ %32 = shape.broadcast %19#0, %1 : tensor<?xindex>, tensor<4xindex> -> tensor<?xindex>
94
+ %cast = tensor.cast %32 : tensor<?xindex> to tensor<4xindex>
95
+ %33 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<4xindex>) -> tensor<?x?x?x?xui32>
96
+ %34 = shape.broadcast %19#1, %1 : tensor<?xindex>, tensor<4xindex> -> tensor<?xindex>
97
+ %cast_0 = tensor.cast %34 : tensor<?xindex> to tensor<4xindex>
98
+ %35 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<4xindex>) -> tensor<?x?x?x?xui32>
99
+ %36 = chlo.broadcast_add %33, %35 : (tensor<?x?x?x?xui32>, tensor<?x?x?x?xui32>) -> tensor<?x?x?x?xui32>
100
+ %cast_1 = tensor.cast %36 : tensor<?x?x?x?xui32> to tensor<*xui32>
101
+ scf.yield %cast_1 : tensor<*xui32>
102
+ } else {
103
+ %32 = arith.cmpi ule, %23, %c5 : index
104
+ cf.assert %32, "Input for dynamic binary or n-ary op lowering was of a rank greater than 5"
105
+ %33 = shape.broadcast %19#0, %0 : tensor<?xindex>, tensor<5xindex> -> tensor<?xindex>
106
+ %cast = tensor.cast %33 : tensor<?xindex> to tensor<5xindex>
107
+ %34 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<5xindex>) -> tensor<?x?x?x?x?xui32>
108
+ %35 = shape.broadcast %19#1, %0 : tensor<?xindex>, tensor<5xindex> -> tensor<?xindex>
109
+ %cast_0 = tensor.cast %35 : tensor<?xindex> to tensor<5xindex>
110
+ %36 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<5xindex>) -> tensor<?x?x?x?x?xui32>
111
+ %37 = chlo.broadcast_add %34, %36 : (tensor<?x?x?x?x?xui32>, tensor<?x?x?x?x?xui32>) -> tensor<?x?x?x?x?xui32>
112
+ %cast_1 = tensor.cast %37 : tensor<?x?x?x?x?xui32> to tensor<*xui32>
113
+ scf.yield %cast_1 : tensor<*xui32>
114
+ }
115
+ scf.yield %31 : tensor<*xui32>
116
+ }
117
+ scf.yield %29 : tensor<*xui32>
118
+ }
119
+ scf.yield %27 : tensor<*xui32>
120
+ }
121
+ scf.yield %25 : tensor<*xui32>
122
+ }
123
+ scf.yield %18 : tensor<*xui32>
124
+ }
125
+ scf.yield %16 : tensor<*xui32>
126
+ }
127
+ %10 = shape.shape_of %arg0 : tensor<*xui32> -> tensor<?xindex>
128
+ %11 = shape.shape_of %arg1 : tensor<*xui32> -> tensor<?xindex>
129
+ %12 = shape.broadcast %10, %11 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>
130
+ %13 = tensor.reshape %9(%12) : (tensor<*xui32>, tensor<?xindex>) -> tensor<*xui32>
131
+ return %13 : tensor<*xui32>
132
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/minimum.mlir ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70
2
+
3
+ func.func @Minimum_GPU_DT_UINT32_DT_UINT32(%arg0: tensor<*xui32>, %arg1: tensor<*xui32>) -> tensor<*xui32> attributes {llvm.emit_c_interface, tf_entry} {
4
+ %0 = shape.const_shape [1, 1, 1, 1, 1] : tensor<5xindex>
5
+ %c5 = arith.constant 5 : index
6
+ %1 = shape.const_shape [1, 1, 1, 1] : tensor<4xindex>
7
+ %c4 = arith.constant 4 : index
8
+ %2 = shape.const_shape [1, 1, 1] : tensor<3xindex>
9
+ %c3 = arith.constant 3 : index
10
+ %3 = shape.const_shape [1, 1] : tensor<2xindex>
11
+ %c2 = arith.constant 2 : index
12
+ %4 = shape.const_shape [1] : tensor<1xindex>
13
+ %c1 = arith.constant 1 : index
14
+ %5 = shape.shape_of %arg0 : tensor<*xui32> -> tensor<?xindex>
15
+ %6 = shape.shape_of %arg1 : tensor<*xui32> -> tensor<?xindex>
16
+ %7 = shape.num_elements %5 : tensor<?xindex> -> index
17
+ %8 = arith.cmpi eq, %7, %c1 : index
18
+ %c_empty = arith.constant dense<> : tensor<0xindex>
19
+ %9 = scf.if %8 -> (tensor<*xui32>) {
20
+ %14 = shape.num_elements %6 : tensor<?xindex> -> index
21
+ %from_elements = tensor.from_elements %14 : tensor<1xindex>
22
+ %15 = tensor.reshape %arg0(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor<ui32>
23
+ %16 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
24
+ %17 = chlo.broadcast_minimum %15, %16 : (tensor<ui32>, tensor<?xui32>) -> tensor<?xui32>
25
+ %cast = tensor.cast %17 : tensor<?xui32> to tensor<*xui32>
26
+ scf.yield %cast : tensor<*xui32>
27
+ } else {
28
+ %14 = shape.num_elements %6 : tensor<?xindex> -> index
29
+ %15 = arith.cmpi eq, %14, %c1 : index
30
+ %16 = scf.if %15 -> (tensor<*xui32>) {
31
+ %17 = shape.num_elements %5 : tensor<?xindex> -> index
32
+ %from_elements = tensor.from_elements %17 : tensor<1xindex>
33
+ %18 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
34
+ %19 = tensor.reshape %arg1(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor<ui32>
35
+ %20 = chlo.broadcast_minimum %18, %19 : (tensor<?xui32>, tensor<ui32>) -> tensor<?xui32>
36
+ %cast = tensor.cast %20 : tensor<?xui32> to tensor<*xui32>
37
+ scf.yield %cast : tensor<*xui32>
38
+ } else {
39
+ %17 = shape.shape_eq %5, %6 : tensor<?xindex>, tensor<?xindex>
40
+ %18 = scf.if %17 -> (tensor<*xui32>) {
41
+ %19 = shape.any %5, %6 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>
42
+ %20 = shape.num_elements %19 : tensor<?xindex> -> index
43
+ %from_elements = tensor.from_elements %20 : tensor<1xindex>
44
+ %21 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
45
+ %22 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
46
+ %23 = chlo.broadcast_minimum %21, %22 : (tensor<?xui32>, tensor<?xui32>) -> tensor<?xui32>
47
+ %cast = tensor.cast %23 : tensor<?xui32> to tensor<*xui32>
48
+ scf.yield %cast : tensor<*xui32>
49
+ } else {
50
+ %19:2 = mhlo.minimum_broadcast_shapes %5, %6 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>, tensor<?xindex>
51
+ %20 = shape.rank %19#0 : tensor<?xindex> -> index
52
+ %21 = shape.rank %19#1 : tensor<?xindex> -> index
53
+ %22 = arith.cmpi sgt, %20, %21 : index
54
+ %23 = arith.select %22, %20, %21 : index
55
+ %24 = arith.cmpi ule, %23, %c1 : index
56
+ %25 = scf.if %24 -> (tensor<*xui32>) {
57
+ %26 = shape.broadcast %19#0, %4 : tensor<?xindex>, tensor<1xindex> -> tensor<?xindex>
58
+ %cast = tensor.cast %26 : tensor<?xindex> to tensor<1xindex>
59
+ %27 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
60
+ %28 = shape.broadcast %19#1, %4 : tensor<?xindex>, tensor<1xindex> -> tensor<?xindex>
61
+ %cast_0 = tensor.cast %28 : tensor<?xindex> to tensor<1xindex>
62
+ %29 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<1xindex>) -> tensor<?xui32>
63
+ %30 = chlo.broadcast_minimum %27, %29 : (tensor<?xui32>, tensor<?xui32>) -> tensor<?xui32>
64
+ %cast_1 = tensor.cast %30 : tensor<?xui32> to tensor<*xui32>
65
+ scf.yield %cast_1 : tensor<*xui32>
66
+ } else {
67
+ %26 = arith.cmpi ule, %23, %c2 : index
68
+ %27 = scf.if %26 -> (tensor<*xui32>) {
69
+ %28 = shape.broadcast %19#0, %3 : tensor<?xindex>, tensor<2xindex> -> tensor<?xindex>
70
+ %cast = tensor.cast %28 : tensor<?xindex> to tensor<2xindex>
71
+ %29 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<2xindex>) -> tensor<?x?xui32>
72
+ %30 = shape.broadcast %19#1, %3 : tensor<?xindex>, tensor<2xindex> -> tensor<?xindex>
73
+ %cast_0 = tensor.cast %30 : tensor<?xindex> to tensor<2xindex>
74
+ %31 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<2xindex>) -> tensor<?x?xui32>
75
+ %32 = chlo.broadcast_minimum %29, %31 : (tensor<?x?xui32>, tensor<?x?xui32>) -> tensor<?x?xui32>
76
+ %cast_1 = tensor.cast %32 : tensor<?x?xui32> to tensor<*xui32>
77
+ scf.yield %cast_1 : tensor<*xui32>
78
+ } else {
79
+ %28 = arith.cmpi ule, %23, %c3 : index
80
+ %29 = scf.if %28 -> (tensor<*xui32>) {
81
+ %30 = shape.broadcast %19#0, %2 : tensor<?xindex>, tensor<3xindex> -> tensor<?xindex>
82
+ %cast = tensor.cast %30 : tensor<?xindex> to tensor<3xindex>
83
+ %31 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<3xindex>) -> tensor<?x?x?xui32>
84
+ %32 = shape.broadcast %19#1, %2 : tensor<?xindex>, tensor<3xindex> -> tensor<?xindex>
85
+ %cast_0 = tensor.cast %32 : tensor<?xindex> to tensor<3xindex>
86
+ %33 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<3xindex>) -> tensor<?x?x?xui32>
87
+ %34 = chlo.broadcast_minimum %31, %33 : (tensor<?x?x?xui32>, tensor<?x?x?xui32>) -> tensor<?x?x?xui32>
88
+ %cast_1 = tensor.cast %34 : tensor<?x?x?xui32> to tensor<*xui32>
89
+ scf.yield %cast_1 : tensor<*xui32>
90
+ } else {
91
+ %30 = arith.cmpi ule, %23, %c4 : index
92
+ %31 = scf.if %30 -> (tensor<*xui32>) {
93
+ %32 = shape.broadcast %19#0, %1 : tensor<?xindex>, tensor<4xindex> -> tensor<?xindex>
94
+ %cast = tensor.cast %32 : tensor<?xindex> to tensor<4xindex>
95
+ %33 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<4xindex>) -> tensor<?x?x?x?xui32>
96
+ %34 = shape.broadcast %19#1, %1 : tensor<?xindex>, tensor<4xindex> -> tensor<?xindex>
97
+ %cast_0 = tensor.cast %34 : tensor<?xindex> to tensor<4xindex>
98
+ %35 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<4xindex>) -> tensor<?x?x?x?xui32>
99
+ %36 = chlo.broadcast_minimum %33, %35 : (tensor<?x?x?x?xui32>, tensor<?x?x?x?xui32>) -> tensor<?x?x?x?xui32>
100
+ %cast_1 = tensor.cast %36 : tensor<?x?x?x?xui32> to tensor<*xui32>
101
+ scf.yield %cast_1 : tensor<*xui32>
102
+ } else {
103
+ %32 = arith.cmpi ule, %23, %c5 : index
104
+ cf.assert %32, "Input for dynamic binary or n-ary op lowering was of a rank greater than 5"
105
+ %33 = shape.broadcast %19#0, %0 : tensor<?xindex>, tensor<5xindex> -> tensor<?xindex>
106
+ %cast = tensor.cast %33 : tensor<?xindex> to tensor<5xindex>
107
+ %34 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<5xindex>) -> tensor<?x?x?x?x?xui32>
108
+ %35 = shape.broadcast %19#1, %0 : tensor<?xindex>, tensor<5xindex> -> tensor<?xindex>
109
+ %cast_0 = tensor.cast %35 : tensor<?xindex> to tensor<5xindex>
110
+ %36 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<5xindex>) -> tensor<?x?x?x?x?xui32>
111
+ %37 = chlo.broadcast_minimum %34, %36 : (tensor<?x?x?x?x?xui32>, tensor<?x?x?x?x?xui32>) -> tensor<?x?x?x?x?xui32>
112
+ %cast_1 = tensor.cast %37 : tensor<?x?x?x?x?xui32> to tensor<*xui32>
113
+ scf.yield %cast_1 : tensor<*xui32>
114
+ }
115
+ scf.yield %31 : tensor<*xui32>
116
+ }
117
+ scf.yield %29 : tensor<*xui32>
118
+ }
119
+ scf.yield %27 : tensor<*xui32>
120
+ }
121
+ scf.yield %25 : tensor<*xui32>
122
+ }
123
+ scf.yield %18 : tensor<*xui32>
124
+ }
125
+ scf.yield %16 : tensor<*xui32>
126
+ }
127
+ %10 = shape.shape_of %arg0 : tensor<*xui32> -> tensor<?xindex>
128
+ %11 = shape.shape_of %arg1 : tensor<*xui32> -> tensor<?xindex>
129
+ %12 = shape.broadcast %10, %11 : tensor<?xindex>, tensor<?xindex> -> tensor<?xindex>
130
+ %13 = tensor.reshape %9(%12) : (tensor<*xui32>, tensor<?xindex>) -> tensor<*xui32>
131
+ return %13 : tensor<*xui32>
132
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/tanh.mlir ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70
2
+
3
+ func.func @tanh(%arg0: tensor<*xf32>) -> tensor<*xf32> attributes {tf_entry} {
4
+ %0 = shape.shape_of %arg0 : tensor<*xf32> -> tensor<?xindex>
5
+ %1 = shape.num_elements %0 : tensor<?xindex> -> index
6
+ %from_elements = tensor.from_elements %1 : tensor<1xindex>
7
+ %2 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
8
+ %3 = mhlo.tanh %2 : tensor<?xf32>
9
+ %4 = tensor.reshape %3(%0) : (tensor<?xf32>, tensor<?xindex>) -> tensor<*xf32>
10
+ return %4 : tensor<*xf32>
11
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/invalid.mlir ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s -split-input-file -verify-diagnostics
2
+
3
+ func.func @alloc_raw(%ctx: !tf_framework.op_kernel_context, %size : index) {
4
+ // expected-error @+1 {{`dyn_sizes` count 1 does not match dynamic dimensions}}
5
+ %buf = tf_framework.alloc(%ctx, %size) : memref<?x10x?xi8>
6
+ func.return
7
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/isinf.mlir ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: tf-opt %s --test-tf-lower-tf --xla-legalize-tf | \
2
+ // RUN: mlir-hlo-opt \
3
+ // RUN: --hlo-legalize-to-stablehlo=allow-xla-features \
4
+ // RUN: --stablehlo-legalize-to-linalg \
5
+ // RUN: --empty-tensor-to-alloc-tensor \
6
+ // RUN: --computeop-and-func-bufferize --canonicalize | \
7
+ // RUN: kernel-gen-opt -allow-unregistered-dialect \
8
+ // RUN: --shape-to-descriptors \
9
+ // RUN: --canonicalize --kernelgen-final-bufferize | \
10
+ // RUN: FileCheck %s
11
+
12
+ // Test whether all shape computations required for isinf can be lowered to
13
+ // the standard dialect, scf and descriptors.
14
+ // CHECK-LABEL: @isinf
15
+ func.func @isinf(%arg0: tensor<?xf32>) -> tensor<?xi1> {
16
+ // CHECK-NOT: shape
17
+ %0 = "tf.IsInf"(%arg0) : (tensor<?xf32>) -> tensor<?xi1>
18
+ func.return %0 : tensor<?xi1>
19
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/legalize_tensor_reshape.mlir ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt --split-input-file --legalize-tensor-reshape %s | FileCheck %s
2
+
3
+ // CHECK-LABEL: func @tanh
4
+ func.func @tanh(%arg0: tensor<*xf32>) -> tensor<*xf32> attributes {tf_entry} {
5
+ %0 = shape.shape_of %arg0 : tensor<*xf32> -> tensor<?xindex>
6
+ %1 = shape.num_elements %0 : tensor<?xindex> -> index
7
+ %from_elements = tensor.from_elements %1 : tensor<1xindex>
8
+ // CHECK: mhlo.dynamic_reshape
9
+ // CHECK-NOT: tensor.reshape
10
+ %2 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor<?xf32>
11
+ %3 = mhlo.tanh %2 : tensor<?xf32>
12
+ %4 = tensor.reshape %3(%0) : (tensor<?xf32>, tensor<?xindex>) -> tensor<*xf32>
13
+ return %4 : tensor<*xf32>
14
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/merge_assuming_ops.mlir ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt --split-input-file --allow-unregistered-dialect \
2
+ // RUN: --mhlo-merge-assuming-ops --canonicalize --cse %s | \
3
+ // RUN: FileCheck %s
4
+
5
+ // Shape computations shall be reified.
6
+ // CHECK-LABEL: @shape_of_unary
7
+ // CHECK-SAME: (%[[ARG:.*]]: tensor<?x32xi16>)
8
+ func.func @shape_of_unary(%arg : tensor<?x32xi16>) {
9
+ // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG]] : tensor<?x32xi16> -> tensor<?xindex>
10
+ // CHECK: "use"(%[[SHAPE]])
11
+ %0 = "mhlo.convert"(%arg) : (tensor<?x32xi16>) -> tensor<?x32xf16>
12
+ %1 = shape.shape_of %0 : tensor<?x32xf16> -> tensor<?xindex>
13
+ "use"(%1) : (tensor<?xindex>) -> ()
14
+ func.return
15
+ }
16
+
17
+ // -----
18
+
19
+ // Shape computations shall be reified.
20
+ // CHECK-LABEL: @shape_of_nary
21
+ // CHECK-SAME: (%[[ARG0:.*]]: tensor<?x32xf16>, %[[ARG1:.*]]: tensor<?x32xf16>)
22
+ func.func @shape_of_nary(%arg0 : tensor<?x32xf16>, %arg1 : tensor<?x32xf16>) {
23
+ // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG0]] : tensor<?x32xf16> -> tensor<?xindex>
24
+ // CHECK: "use"(%[[SHAPE]])
25
+ %0 = mhlo.subtract %arg0, %arg1 : tensor<?x32xf16>
26
+ %1 = mhlo.subtract %0, %arg1 : tensor<?x32xf16>
27
+ %2 = shape.shape_of %1 : tensor<?x32xf16> -> tensor<?xindex>
28
+ "use"(%2) : (tensor<?xindex>) -> ()
29
+ func.return
30
+ }
31
+
32
+ // -----
33
+
34
+ // CHECK-LABEL: @inline_bcasted_shape_operands
35
+ // CHECK-SAME: (%[[A:.*]]: tensor<?xindex>, %[[B:.*]]: tensor<?xindex>, %[[C:.*]]: tensor<?xindex>)
36
+ func.func @inline_bcasted_shape_operands(%a : tensor<?xindex>, %b : tensor<?xindex>,
37
+ %c : tensor<?xindex>) -> !shape.witness {
38
+ // CHECK-NOT: shape.broadcast
39
+ // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[A]], %[[B]], %[[C]]
40
+ // CHECK: return %[[WITNESS]] : !shape.witness
41
+ %0 = shape.broadcast %a, %b : tensor<?xindex>, tensor<?xindex>
42
+ -> tensor<?xindex>
43
+ %1 = shape.cstr_broadcastable %0, %c : tensor<?xindex>, tensor<?xindex>
44
+ func.return %1 : !shape.witness
45
+ }
46
+
47
+ // -----
48
+
49
+ // CHECK-LABEL: @move_shape_of_into_assuming
50
+ // CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<?x32xf32>)
51
+ func.func @move_shape_of_into_assuming(%arg0 : !shape.witness,
52
+ %arg1 : tensor<?x32xf32>) -> tensor<2xindex> {
53
+ // CHECK: %[[ASSUMING_RESULTS:.*]]:3 = shape.assuming %[[ARG0]] -> (tensor<?x32xf32>, tensor<?x32xf32>, tensor<2xindex>) {
54
+ // CHECK: %[[DUMMY_TENSOR:.*]] = "dummy.tensor"() : () -> tensor<?x32xf32>
55
+ // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[DUMMY_TENSOR]]
56
+ // CHECK: shape.assuming_yield %[[ARG1]], %[[DUMMY_TENSOR]], %[[SHAPE]]
57
+ // CHECK: }
58
+ // CHECK-NOT: shape_of
59
+ // CHECK: return %[[ASSUMING_RESULTS]]#2
60
+ %0:2 = shape.assuming %arg0 -> (tensor<?x32xf32>, tensor<?x32xf32>) {
61
+ %1 = "dummy.tensor"() : () -> tensor<?x32xf32>
62
+ shape.assuming_yield %arg1, %1 : tensor<?x32xf32>, tensor<?x32xf32>
63
+ }
64
+ %2 = shape.shape_of %0#1 : tensor<?x32xf32> -> tensor<2xindex>
65
+ "use"(%0#0, %0#1) : (tensor<?x32xf32>, tensor<?x32xf32>) -> ()
66
+ func.return %2 : tensor<2xindex>
67
+ }
68
+
69
+ // -----
70
+
71
+ // CHECK-LABEL: @move_cstr_broadcastable_into_assuming
72
+ // CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2xindex>)
73
+ func.func @move_cstr_broadcastable_into_assuming(%arg0 : !shape.witness,
74
+ %arg1 : tensor<2xindex>) -> !shape.witness {
75
+ // CHECK: %[[ASSUMING_RESULTS:.*]]:3 = shape.assuming %[[ARG0]] -> (tensor<2xindex>, tensor<3xindex>, !shape.witness) {
76
+ // CHECK: %[[DUMMY_TENSOR:.*]] = "dummy.tensor"() : () -> tensor<3xindex>
77
+ // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[ARG1]], %[[DUMMY_TENSOR]]
78
+ // CHECK: shape.assuming_yield %[[ARG1]], %[[DUMMY_TENSOR]], %[[WITNESS]]
79
+ // CHECK: }
80
+ // CHECK-NOT: cstr_broadcastable
81
+ // CHECK: return %[[ASSUMING_RESULTS]]#2
82
+ %0:2 = shape.assuming %arg0 -> (tensor<2xindex>, tensor<3xindex>) {
83
+ %1 = "dummy.tensor"() : () -> tensor<3xindex>
84
+ shape.assuming_yield %arg1, %1 : tensor<2xindex>, tensor<3xindex>
85
+ }
86
+ %1 = shape.cstr_broadcastable %arg1, %0#1 : tensor<2xindex>, tensor<3xindex>
87
+ "use"(%0#0, %0#1) : (tensor<2xindex>, tensor<3xindex>) -> ()
88
+ func.return %1 : !shape.witness
89
+ }
90
+
91
+ // -----
92
+
93
+ // CHECK-LABEL: @not_move_shape_of_into_assuming
94
+ // CHECK-SAME: (%[[W:.*]]: !shape.witness, %[[ARG0:.*]]: tensor<?x32xf32>, %[[ARG1:.*]]: tensor<?x32xf32>)
95
+ func.func @not_move_shape_of_into_assuming(%arg0 : !shape.witness,
96
+ %arg1 : tensor<?x32xf32>, %arg2 : tensor<?x32xf32>) -> tensor<2xindex> {
97
+ // CHECK: %[[S:.*]] = shape.shape_of %[[ARG1]]
98
+ // CHECK: %[[ASS_RES:.*]] = shape.assuming %[[W]]
99
+ // CHECK: shape.assuming_yield %[[ARG0]]
100
+ // CHECK: }
101
+ // CHECK: "some.other.op"(%[[ASS_RES]])
102
+ // CHECK: return %[[S]]
103
+ %0:2 = shape.assuming %arg0 -> (tensor<?x32xf32>, tensor<?x32xf32>) {
104
+ shape.assuming_yield %arg1, %arg2 : tensor<?x32xf32>, tensor<?x32xf32>
105
+ }
106
+ "some.other.op"(%0#0) : (tensor<?x32xf32>) -> ()
107
+ %2 = shape.shape_of %0#1 : tensor<?x32xf32> -> tensor<2xindex>
108
+ func.return %2 : tensor<2xindex>
109
+ }
110
+
111
+ // -----
112
+
113
+ // CHECK-LABEL: @move_cstr_broadcastable_out_of_assuming
114
+ // CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2xindex>, %[[ARG2:.*]]: tensor<3xindex>)
115
+ func.func @move_cstr_broadcastable_out_of_assuming(%arg0 : !shape.witness,
116
+ %arg1 : tensor<2xindex>, %arg2 : tensor<3xindex>) -> !shape.witness {
117
+ // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[ARG1]], %[[ARG2]]
118
+ // CHECK-NOT: assuming
119
+ // CHECK-NOT: cstr_broadcastable
120
+ // CHECK: return %[[WITNESS]]
121
+ %0 = shape.assuming %arg0 -> (!shape.witness) {
122
+ %1 = shape.cstr_broadcastable %arg1, %arg2 : tensor<2xindex>, tensor<3xindex>
123
+ shape.assuming_yield %1 : !shape.witness
124
+ }
125
+ func.return %0 : !shape.witness
126
+ }
127
+
128
+ // -----
129
+
130
+ // CHECK-LABEL: @move_elementwise_into_assuming
131
+ // CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<?xf32>)
132
+ func.func @move_elementwise_into_assuming(%arg0 : !shape.witness,
133
+ %arg1 : tensor<?xf32>) -> tensor<?xf32> {
134
+ // CHECK: %[[RES:.*]] = shape.assuming %[[ARG0]]
135
+ // CHECK: %[[SOME:.*]] = "some.op"
136
+ // CHECK: %[[TANH:.*]] = mhlo.tanh %[[ARG1]]
137
+ // CHECK: %[[BCAST_ADD:.*]] = chlo.broadcast_add %[[TANH]], %[[SOME]]
138
+ // CHECK: shape.assuming_yield %[[BCAST_ADD]]
139
+ // CHECK-NOT: tanh
140
+ // CHECK-NOT: broadcast_add
141
+ // CHECK: return %[[RES]]
142
+ %0:2 = shape.assuming %arg0 -> (tensor<?xf32>, tensor<?xf32>) {
143
+ %1 = "some.op"() : () -> tensor<?xf32>
144
+ shape.assuming_yield %arg1, %1 : tensor<?xf32>, tensor<?xf32>
145
+ }
146
+ %1 = mhlo.tanh %arg1 : tensor<?xf32>
147
+ %2 = chlo.broadcast_add %1, %0#1
148
+ : (tensor<?xf32>, tensor<?xf32>) -> tensor<?xf32>
149
+ func.return %2 : tensor<?xf32>
150
+ }
151
+
152
+ // -----
153
+
154
+ // CHECK-LABEL: @move_shape_of_out_of_assuming
155
+ // CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2x?xf32>)
156
+ func.func @move_shape_of_out_of_assuming(%arg0 : !shape.witness,
157
+ %arg1 : tensor<2x?xf32>) -> tensor<2xindex> {
158
+ // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG1]]
159
+ // CHECK-NOT: assuming
160
+ // CHECK-NOT: cstr_broadcastable
161
+ // CHECK: return %[[SHAPE]]
162
+ %0 = shape.assuming %arg0 -> (tensor<2xindex>) {
163
+ %1 = shape.shape_of %arg1 : tensor<2x?xf32> -> tensor<2xindex>
164
+ shape.assuming_yield %1 : tensor<2xindex>
165
+ }
166
+ func.return %0 : tensor<2xindex>
167
+ }
168
+
169
+ // -----
170
+
171
+ // CHECK-LABEL: @move_shape_of_out_of_assuming
172
+ // CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2x?xf32>)
173
+ func.func @move_shape_of_out_of_assuming(%arg0 : !shape.witness,
174
+ %arg1 : tensor<2x?xf32>) -> tensor<2xindex> {
175
+ // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG1]]
176
+ // CHECK: %{{.*}} = shape.assuming %[[ARG0]] -> (tensor<2x?xf32>) {
177
+ // CHECK: %[[SOME_VAL:.*]] = "some.op"() : () -> tensor<2x?xf32>
178
+ // CHECK: shape.assuming_yield %[[SOME_VAL]] : tensor<2x?xf32>
179
+ // CHECK: }
180
+ // CHECK: return %[[SHAPE]]
181
+ %0:2 = shape.assuming %arg0 -> (tensor<2x?xf32>, tensor<2xindex>) {
182
+ %1 = "some.op"() : () -> (tensor<2x?xf32>)
183
+ %2 = shape.shape_of %arg1 : tensor<2x?xf32> -> tensor<2xindex>
184
+ shape.assuming_yield %1, %2 : tensor<2x?xf32>, tensor<2xindex>
185
+ }
186
+ "use"(%0#0, %0#1) : (tensor<2x?xf32>, tensor<2xindex>) -> ()
187
+ func.return %0#1 : tensor<2xindex>
188
+ }
189
+
190
+ // -----
191
+
192
+ // CHECK-LABEL: @not_move_shape_of_out_of_assuming
193
+ // CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2x?xf32>)
194
+ func.func @not_move_shape_of_out_of_assuming(%arg0 : !shape.witness,
195
+ %arg1 : tensor<2x?xf32>) -> tensor<2xindex> {
196
+ // CHECK-NOT: shape_of
197
+ // CHECK: shape.assuming
198
+ // CHECK-SAME: {
199
+ // CHECK: "some.tensor"
200
+ // CHECK: shape_of
201
+ // CHECK: }
202
+ %0 = shape.assuming %arg0 -> (tensor<2xindex>) {
203
+ %1 = "some.tensor"() : () -> tensor<2x?xf32>
204
+ %2 = shape.shape_of %1 : tensor<2x?xf32> -> tensor<2xindex>
205
+ shape.assuming_yield %2 : tensor<2xindex>
206
+ }
207
+ func.return %0 : tensor<2xindex>
208
+ }
209
+
210
+ // -----
211
+
212
+ // CHECK: @merge_assuming_ops
213
+ // CHECK: (%[[ARG0:.*]]: tensor<?x32xf16>, %[[ARG1:.*]]: tensor<?x32xf16>, %[[ARG2:.*]]: tensor<?x?x32xf16>)
214
+ func.func @merge_assuming_ops(%arg0: tensor<?x32xf16>, %arg1 : tensor<?x32xf16>,
215
+ %arg2: tensor<?x?x32xf16>) -> tensor<?x?x32xf16> {
216
+ // CHECK: %[[SHAPE0:.*]] = shape.shape_of %[[ARG0]]
217
+ // CHECK: %[[SHAPE1:.*]] = shape.shape_of %[[ARG1]]
218
+ // CHECK: %[[SHAPE2:.*]] = shape.shape_of %[[ARG2]]
219
+ // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[SHAPE0]], %[[SHAPE1]], %[[SHAPE2]]
220
+ // CHECK: %[[MERGED:.*]]:2 = shape.assuming %[[WITNESS]]
221
+ // CHECK-SAME: {
222
+ // CHECK: "some.op"
223
+ // CHECK: %[[RESULT0:.*]] = "some.producer"
224
+ // CHECK: "another.op"
225
+ // CHECK: %[[RESULT1:.*]] = "another.producer"
226
+ // CHECK: shape.assuming_yield %[[RESULT0]], %[[RESULT1]]
227
+ // CHECK: }
228
+ // CHECK: return %[[MERGED]]#1
229
+ %0 = shape.shape_of %arg0 : tensor<?x32xf16> -> tensor<2xindex>
230
+ %1 = shape.shape_of %arg1 : tensor<?x32xf16> -> tensor<2xindex>
231
+ %2 = shape.shape_of %arg2 : tensor<?x?x32xf16> -> tensor<3xindex>
232
+ %3 = shape.cstr_broadcastable %0, %1 : tensor<2xindex>, tensor<2xindex>
233
+ %4 = shape.cstr_broadcastable %0, %1, %2 : tensor<2xindex>, tensor<2xindex>,
234
+ tensor<3xindex>
235
+ %5 = shape.assuming %3 -> (tensor<?x32xf16>) {
236
+ "some.op"() : () -> ()
237
+ %6 = "some.producer"() : () -> tensor<?x32xf16>
238
+ shape.assuming_yield %6 : tensor<?x32xf16>
239
+ }
240
+ %7 = shape.assuming %4 -> (tensor<?x?x32xf16>) {
241
+ "another.op"() : () -> ()
242
+ %8 = "another.producer"() : () -> tensor<?x?x32xf16>
243
+ shape.assuming_yield %8 : tensor<?x?x32xf16>
244
+ }
245
+ "use"(%5, %7) : (tensor<?x32xf16>, tensor<?x?x32xf16>) -> ()
246
+ func.return %7 : tensor<?x?x32xf16>
247
+ }
248
+
249
+ // -----
250
+
251
+ // Do not merge assuming ops if witness will not dominate use.
252
+ // CHECK: @do_not_merge_assuming_ops
253
+ func.func @do_not_merge_assuming_ops() {
254
+ // CHECK: shape.assuming
255
+ // CHECK: shape.assuming
256
+ %0 = "some.witness"() : () -> !shape.witness
257
+ %1 = shape.assuming %0 -> (!shape.witness) {
258
+ %2 = "some.witness"() : () -> !shape.witness
259
+ shape.assuming_yield %2 : !shape.witness
260
+ }
261
+ shape.assuming %1 {
262
+ "some.op"() : () -> ()
263
+ shape.assuming_yield
264
+ }
265
+ func.return
266
+ }
267
+
268
+ // -----
269
+
270
+ // CHECK: @eliminate_extent_tensor_cast
271
+ // CHECK-SAME: (%[[ARG:.*]]: tensor<2x?x4xf32>)
272
+ func.func @eliminate_extent_tensor_cast(%arg : tensor<2x?x4xf32>) {
273
+ // CHECK-NOT: shape_of
274
+ // CHECK: %[[RESULT:.*]] = shape.shape_of %[[ARG]] : tensor<2x?x4xf32> -> tensor<3xindex>
275
+ // CHECK-NEXT: "use"(%[[RESULT]]) : (tensor<3xindex>) -> ()
276
+ %0 = shape.shape_of %arg : tensor<2x?x4xf32> -> tensor<?xindex>
277
+ %1 = tensor.cast %0 : tensor<?xindex> to tensor<3xindex>
278
+ "use"(%1) : (tensor<3xindex>) -> ()
279
+ func.return
280
+ }
281
+
282
+ // -----
283
+
284
+ // CHECK-LABEL: @redundant_cstr_broadcastable
285
+ // CHECK-SAME: (%[[ARG0:.*]]: tensor<?xindex>, %[[ARG1:.*]]: tensor<?xindex>)
286
+ func.func @redundant_cstr_broadcastable(%arg0: tensor<?xindex>,
287
+ %arg1 : tensor<?xindex>) {
288
+ // CHECK-DAG: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[ARG0]], %[[ARG1]]
289
+ // CHECK: shape.assuming %[[WITNESS]]
290
+ %0 = shape.cstr_broadcastable %arg0, %arg1 : tensor<?xindex>, tensor<?xindex>
291
+ %1 = shape.cstr_broadcastable %arg0, %arg1 : tensor<?xindex>, tensor<?xindex>
292
+ %2 = shape.assuming_all %0, %1
293
+ shape.assuming %2 -> () {
294
+ "some.op"() : () -> ()
295
+ shape.assuming_yield
296
+ }
297
+ func.return
298
+ }
299
+
300
+ // -----
301
+
302
+ // CHECK-LABEL: @move_assuming_all_over_assuming_region
303
+ // CHECK-SAME: %[[ARG0:.*]]: tensor<?xindex>, %[[ARG1:.*]]: tensor<?xindex>, %[[ARG2:.*]]: tensor<?xindex>, %[[ARG3:.*]]: tensor<?xindex>, %[[ARG4:.*]]: tensor<?xindex>
304
+ func.func @move_assuming_all_over_assuming_region(%arg0: tensor<?xindex>,
305
+ %arg1 : tensor<?xindex>, %arg2 : tensor<?xindex>, %arg3 : tensor<?xindex>,
306
+ %arg4 : tensor<?xindex>) {
307
+ // CHECK-DAG: %[[CSTR0:.*]] = shape.cstr_broadcastable %[[ARG0]], %[[ARG1]]
308
+ // CHECK-DAG: %[[CSTR1:.*]] = shape.cstr_broadcastable %[[ARG1]], %[[ARG2]]
309
+ // CHECK-DAG: %[[CSTR2:.*]] = shape.cstr_broadcastable %[[ARG2]], %[[ARG3]]
310
+ // CHECK-DAG: %[[CSTR3:.*]] = shape.cstr_broadcastable %[[ARG3]], %[[ARG4]]
311
+ // CHECK-DAG: %[[CSTR_ALL:.*]] = shape.assuming_all %[[CSTR0]], %[[CSTR1]], %[[CSTR2]], %[[CSTR3]]
312
+ // CHECK: shape.assuming %[[CSTR_ALL]] {
313
+ // CHECK: "some.op"()
314
+ // CHECK: "some.op"()
315
+ // CHECK: }
316
+ // CHECK: return
317
+ %0 = shape.cstr_broadcastable %arg0, %arg1 : tensor<?xindex>, tensor<?xindex>
318
+ %1 = shape.cstr_broadcastable %arg1, %arg2 : tensor<?xindex>, tensor<?xindex>
319
+ %2 = shape.assuming_all %0, %1
320
+ shape.assuming %2 -> () {
321
+ "some.op"() : () -> ()
322
+ }
323
+ %3 = shape.cstr_broadcastable %arg2, %arg3 : tensor<?xindex>, tensor<?xindex>
324
+ %4 = shape.cstr_broadcastable %arg3, %arg4 : tensor<?xindex>, tensor<?xindex>
325
+ %5 = shape.assuming_all %3, %4
326
+ shape.assuming %5 -> () {
327
+ "some.op"() : () -> ()
328
+ }
329
+ func.return
330
+ }
331
+
332
+ // -----
333
+
334
+ // CHECK-LABEL: @move_down_into_assuming
335
+ // CHECK-SAME: (%[[ARG:.*]]: tensor<?x32xi16>, %[[W:.*]]: !shape.witness)
336
+ func.func @move_down_into_assuming(%arg0: tensor<?x32xi16>, %w: !shape.witness) -> tensor<?x32xf16> {
337
+ // CHECK: %[[RES:.*]] = shape.assuming %[[W]]
338
+ // CHECK: %[[INNER_RES:.*]] = mhlo.convert %[[ARG]]
339
+ // CHECK: shape.assuming_yield %[[INNER_RES]]
340
+ // CHECK: }
341
+ // CHECK: return %[[RES]]
342
+ %0 = mhlo.convert %arg0 : (tensor<?x32xi16>) -> tensor<?x32xf16>
343
+ "some.possibly_side_effecting_op"() : () -> ()
344
+ %4 = shape.assuming %w -> (tensor<?x32xf16>) {
345
+ shape.assuming_yield %0 : tensor<?x32xf16>
346
+ }
347
+ func.return %4 : tensor<?x32xf16>
348
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/ops.mlir ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s | FileCheck %s
2
+ // Verify the printed output can be parsed.
3
+ // RUN: kernel-gen-opt %s | kernel-gen-opt | FileCheck %s
4
+ // Verify the generic form can be parsed.
5
+ // RUN: kernel-gen-opt -mlir-print-op-generic %s | kernel-gen-opt | FileCheck %s
6
+
7
+ // CHECK-LABEL: func @alloc
8
+ func.func @alloc(%ctx: !tf_framework.op_kernel_context,
9
+ %size_0 : index , %size_2 : index) {
10
+ %buf_0 = tf_framework.alloc(%ctx) : memref<10xi8>
11
+ %buf_1 = tf_framework.alloc(%ctx, %size_0, %size_2) : memref<?x10x?xi8>
12
+ func.return
13
+ }
14
+
15
+ // CHECK-LABEL: func @forwarding_alloc
16
+ func.func @forwarding_alloc(%ctx: !tf_framework.op_kernel_context,
17
+ %size_0 : index , %size_2 : index) {
18
+ %buf = tf_framework.alloc(%ctx, %size_0, %size_2) {
19
+ input_indices = [0 : i32, 1 : i32],
20
+ output_index = 0 : i32
21
+ } : memref<?x10x?xi8>
22
+ func.return
23
+ }
24
+
25
+ // CHECK-LABEL: func @dealloc
26
+ func.func @dealloc(%ctx: !tf_framework.op_kernel_context,
27
+ %memref : memref<?x10xf32>) {
28
+ tf_framework.dealloc(%ctx, %memref) : memref<?x10xf32>
29
+ func.return
30
+ }
31
+
32
+ // CHECK-LABEL: func @assert
33
+ func.func @assert(%ctx: !tf_framework.op_kernel_context, %cond: i1) {
34
+ tf_framework.assert %ctx, %cond, "ALREADY_EXISTS", "Or maybe not"
35
+ func.return
36
+ }
37
+
38
+ // CHECK-LABEL: func @report_error
39
+ func.func @report_error(%ctx: !tf_framework.op_kernel_context) {
40
+ tf_framework.report_error %ctx, "INVALID_ARGUMENT", "Everything is awesome"
41
+ func.return
42
+ }
43
+
44
+ // CHECK-LABEL: func @null_memref
45
+ func.func @null_memref() {
46
+ tf_framework.null_memref : memref<*xf32>
47
+ func.return
48
+ }
49
+
50
+ // CHECK-LABEL: func @null_context
51
+ func.func @null_context() {
52
+ tf_framework.null_context : !tf_framework.op_kernel_context
53
+ func.return
54
+ }
55
+
56
+ // CHECK-LABEL: func @is_valid_memref
57
+ func.func @is_valid_memref(%buf: memref<?xf32>) -> i1 {
58
+ %pred = tf_framework.is_valid_memref(%buf) : memref<?xf32> -> i1
59
+ func.return %pred : i1
60
+ }
61
+
62
+ // CHECK-LABEL: func @jit_compile_wo_ctx
63
+ func.func @jit_compile_wo_ctx() -> !tf_framework.jit_callable {
64
+ %callable = tf_framework.jit_compile {
65
+ ^bb0(%arg : tensor<2x?xf32>):
66
+ tf_framework.jit_compile_yield %arg : tensor<2x?xf32>
67
+ }
68
+ func.return %callable : !tf_framework.jit_callable
69
+ }
70
+
71
+ // CHECK-LABEL: func @jit_compile
72
+ func.func @jit_compile(%ctx : !tf_framework.op_kernel_context)
73
+ -> !tf_framework.jit_callable {
74
+ %callable = tf_framework.jit_compile %ctx {
75
+ ^bb0(%arg : tensor<2x?xf32>):
76
+ tf_framework.jit_compile_yield %arg : tensor<2x?xf32>
77
+ }
78
+ func.return %callable : !tf_framework.jit_callable
79
+ }
80
+
81
+ // CHECK-LABEL: func @jit_compile_from_str_wo_ctx
82
+ func.func @jit_compile_from_str_wo_ctx() -> !tf_framework.jit_callable {
83
+ %callable = tf_framework.jit_compile_from_str "placeholder" {
84
+ architectures = ["sm_123", "sm_456"], tileSizes = [1, 2, 3],
85
+ unrollFactors = [4], enableFtz = false,
86
+ index64Bit = false, cpuCodegen = false }
87
+ func.return %callable : !tf_framework.jit_callable
88
+ }
89
+
90
+ // CHECK-LABEL: func @jit_compile_from_str
91
+ func.func @jit_compile_from_str(%ctx : !tf_framework.op_kernel_context)
92
+ -> !tf_framework.jit_callable {
93
+ %callable = tf_framework.jit_compile_from_str %ctx , "placeholder" {
94
+ architectures = ["sm_123", "sm_456"], tileSizes = [1, 2, 3],
95
+ unrollFactors = [4], enableFtz = false,
96
+ index64Bit = false, cpuCodegen = false }
97
+ func.return %callable : !tf_framework.jit_callable
98
+ }
99
+
100
+ // CHECK-LABEL: func @jit_execute_wo_ctx
101
+ func.func @jit_execute_wo_ctx(%callable : !tf_framework.jit_callable,
102
+ %arg : tensor<2x?xf32>) -> tensor<2x?xf32> {
103
+ %0 = tf_framework.jit_execute %callable(%arg)
104
+ : tensor<2x?xf32> -> tensor<2x?xf32>
105
+ func.return %0 : tensor<2x?xf32>
106
+ }
107
+
108
+ // CHECK-LABEL: func @jit_execute
109
+ func.func @jit_execute(%ctx : !tf_framework.op_kernel_context,
110
+ %callable : !tf_framework.jit_callable, %arg : tensor<2x?xf32>)
111
+ -> tensor<2x?xf32> {
112
+ %0 = tf_framework.jit_execute ctx(%ctx) %callable(%arg)
113
+ : tensor<2x?xf32> -> tensor<2x?xf32>
114
+ func.return %0 : tensor<2x?xf32>
115
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/parallel_loops_to_sequential.mlir ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s --parallel-loops-to-sequential | FileCheck %s
2
+
3
+ // CHECK-LABEL: @parallel_loop
4
+ func.func @parallel_loop(%lb_0 : index, %lb_1 : index,
5
+ %ub_0 : index, %ub_1 : index,
6
+ %s_0 : index, %s_1 : index,
7
+ %buf: memref<?x?xindex>) {
8
+ scf.parallel (%i0, %i1) = (%lb_0, %lb_1) to (%ub_0, %ub_1) step (%s_0, %s_1) {
9
+ %sum_elem = arith.addi %i0, %i1 : index
10
+ memref.store %sum_elem, %buf[%i0, %i1] : memref<?x?xindex>
11
+ }
12
+ func.return
13
+ }
14
+ // CHECK: scf.for [[I_0:%.*]] = [[LB_0:%.*]] to [[UB_0:%.*]] step [[S_0:%.*]]
15
+ // CHECK: scf.for [[I_1:%.*]] = [[LB_1:%.*]] to [[UB_1:%.*]] step [[S_1:%.*]]
16
+ // CHECK: [[SUM:%.*]] = arith.addi [[I_0]], [[I_1]] : index
17
+ // CHECK: memref.store [[SUM]], {{%.*}}{{\[}}[[I_0]], [[I_1]]] : memref<?x?xindex>
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/rewrite_tf_framework_assert.mlir ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s -rewrite-tf-framework-assert -split-input-file |\
2
+ // RUN: FileCheck %s
3
+
4
+ // CHECK-LABEL: func @assert(
5
+ // CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context
6
+ func.func @assert(%ctx: !tf_framework.op_kernel_context)
7
+ -> (memref<*xf32>, memref<*xi32>) attributes {tf_entry} {
8
+ %true = arith.constant true
9
+ tf_framework.assert %ctx, %true, INVALID_ARGUMENT, "the one and only"
10
+ %buf_f32 = tf_framework.alloc(%ctx) : memref<2xf32>
11
+ %unranked_f32 = memref.cast %buf_f32 : memref<2xf32> to memref<*xf32>
12
+ %buf_i32 = tf_framework.alloc(%ctx) : memref<3xi32>
13
+ %unranked_i32 = memref.cast %buf_i32 : memref<3xi32> to memref<*xi32>
14
+ func.return %unranked_f32, %unranked_i32 : memref<*xf32>, memref<*xi32>
15
+ }
16
+ // CHECK: [[TRUE:%.*]] = arith.constant true
17
+ // CHECK: cf.cond_br [[TRUE]], ^bb1, ^bb2
18
+ // CHECK: ^bb1:
19
+ // CHECK: [[BUF_F32:%.*]] = tf_framework.alloc([[CTX]]) : memref<2xf32>
20
+ // CHECK: [[OUT_F32:%.*]] = memref.cast [[BUF_F32]]
21
+ // CHECK: [[BUF_I32:%.*]] = tf_framework.alloc([[CTX]]) : memref<3xi32>
22
+ // CHECK: [[OUT_I32:%.*]] = memref.cast [[BUF_I32]]
23
+ // CHECK: return [[OUT_F32]], [[OUT_I32]] : memref<*xf32>, memref<*xi32>
24
+ // CHECK: ^bb2:
25
+ // CHECK: tf_framework.report_error [[CTX]], INVALID_ARGUMENT,
26
+ // CHECK-SAME: "the one and only"
27
+ // CHECK: [[NULL_F32:%.*]] = tf_framework.null_memref : memref<*xf32>
28
+ // CHECK: [[NULL_I32:%.*]] = tf_framework.null_memref : memref<*xi32>
29
+ // CHECK: return [[NULL_F32]], [[NULL_I32]] : memref<*xf32>, memref<*xi32>
30
+
31
+ // -----
32
+
33
+ // CHECK-LABEL: func @double_assert(
34
+ // CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context
35
+ func.func @double_assert(%ctx: !tf_framework.op_kernel_context)
36
+ -> memref<*xf32> attributes {tf_entry} {
37
+ %true = arith.constant true
38
+ %false = arith.constant false
39
+ tf_framework.assert %ctx, %true, INVALID_ARGUMENT, "first assertion"
40
+ tf_framework.assert %ctx, %false, INVALID_ARGUMENT, "second assertion"
41
+ %buf = tf_framework.alloc(%ctx) : memref<2xf32>
42
+ %unranked_buf = memref.cast %buf : memref<2xf32> to memref<*xf32>
43
+ func.return %unranked_buf : memref<*xf32>
44
+ }
45
+ // CHECK-DAG: [[TRUE:%.*]] = arith.constant true
46
+ // CHECK-DAG: [[FALSE:%.*]] = arith.constant false
47
+ // CHECK: cf.cond_br [[TRUE]], ^bb1, ^bb3
48
+ // CHECK: ^bb1:
49
+ // CHECK: cf.cond_br [[FALSE]], ^bb2, ^bb4
50
+ // CHECK: ^bb2:
51
+ // CHECK: [[BUF:%.*]] = tf_framework.alloc([[CTX]]) : memref<2xf32>
52
+ // CHECK: [[OUT:%.*]] = memref.cast [[BUF]]
53
+ // CHECK: return [[OUT]] : memref<*xf32>
54
+ // CHECK: ^bb3:
55
+ // CHECK: tf_framework.report_error [[CTX]], INVALID_ARGUMENT,
56
+ // CHECK-SAME: "first assertion"
57
+ // CHECK: [[NULL:%.*]] = tf_framework.null_memref : memref<*xf32>
58
+ // CHECK: return [[NULL]] : memref<*xf32>
59
+ // CHECK: ^bb4:
60
+ // CHECK: tf_framework.report_error [[CTX]], INVALID_ARGUMENT,
61
+ // CHECK-SAME: "second assertion"
62
+ // CHECK: [[NULL:%.*]] = tf_framework.null_memref : memref<*xf32>
63
+ // CHECK: return [[NULL]] : memref<*xf32>
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/shape_simplification.mlir ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt -split-input-file -shape-simplification %s | FileCheck %s
2
+
3
+ // Incompatible shapes. No folding.
4
+ // CHECK-LABEL: func @f
5
+ func.func @f() -> !shape.shape {
6
+ // CHECK: shape.broadcast
7
+ %0 = shape.const_shape [2] : !shape.shape
8
+ %1 = shape.const_shape [7] : !shape.shape
9
+ %2 = shape.broadcast %0, %1 : !shape.shape, !shape.shape -> !shape.shape
10
+ func.return %2 : !shape.shape
11
+ }
12
+
13
+ // -----
14
+
15
+ // Broadcast of partially dynamic shapes yields a static shape.
16
+ // CHECK-LABEL: func @f
17
+ func.func @f(%arg0 : tensor<42x?x42x?xf32>, %arg1 : tensor<42x?x?xf32>) -> !shape.shape {
18
+ // CHECK: %[[CST:.*]] = shape.const_shape [42, 42, 42, 256] : !shape.shape
19
+ // CHECK: return %[[CST]]
20
+ %0 = shape.const_shape [256] : !shape.shape
21
+ %1 = shape.shape_of %arg0 : tensor<42x?x42x?xf32> -> !shape.shape
22
+ %2 = shape.shape_of %arg1 : tensor<42x?x?xf32> -> !shape.shape
23
+ %3 = shape.broadcast %0, %1, %2 : !shape.shape, !shape.shape, !shape.shape -> !shape.shape
24
+ func.return %3 : !shape.shape
25
+ }
26
+
27
+ // -----
28
+
29
+ // Remove operands that don't contribute to the result.
30
+ // CHECK-LABEL: func @f
31
+ func.func @f(%arg0 : tensor<?x?x42x42xf32>, %arg1 : tensor<42x42xf32>) -> tensor<?xindex> {
32
+ // CHECK: %[[SHAPE0:.*]] = shape.shape_of %arg0 : tensor<?x?x42x42xf32> -> tensor<?xindex>
33
+ // CHECK: return %[[SHAPE0]]
34
+ %0 = shape.const_shape [42, 1] : tensor<2xindex>
35
+ %1 = shape.shape_of %arg0 : tensor<?x?x42x42xf32> -> tensor<?xindex>
36
+ %2 = shape.shape_of %arg1 : tensor<42x42xf32> -> tensor<2xindex>
37
+ %3 = shape.broadcast %0, %1, %2 : tensor<2xindex>, tensor<?xindex>, tensor<2xindex> -> tensor<?xindex>
38
+ func.return %3 : tensor<?xindex>
39
+ }
40
+
41
+ // -----
42
+
43
+ // The constant shape needs to stay alive or the result will be smaller.
44
+ // CHECK-LABEL: func @f
45
+ func.func @f(%arg0 : tensor<?xf32>) -> !shape.shape {
46
+ // CHECK: shape.broadcast
47
+ %0 = shape.const_shape [1, 1] : !shape.shape
48
+ %1 = shape.shape_of %arg0 : tensor<?xf32> -> !shape.shape
49
+ %2 = shape.broadcast %0, %1 : !shape.shape, !shape.shape -> !shape.shape
50
+ func.return %2 : !shape.shape
51
+ }
52
+
53
+ // -----
54
+
55
+ // [256] is the only contributor of that constant, keep it.
56
+ // CHECK-LABEL: func @f
57
+ func.func @f(%arg0 : tensor<?x?xf32>) -> !shape.shape {
58
+ // CHECK: shape.broadcast
59
+ %0 = shape.const_shape [256] : !shape.shape
60
+ %1 = shape.shape_of %arg0 : tensor<?x?xf32> -> !shape.shape
61
+ %2 = shape.broadcast %0, %1 : !shape.shape, !shape.shape -> !shape.shape
62
+ func.return %2 : !shape.shape
63
+ }
64
+
65
+ // -----
66
+
67
+ // CHECK-LABEL: func @static_non1_succeeds
68
+ // CHECK-NEXT: %[[C2:.*]] = arith.constant 2
69
+ // CHECK-NEXT: return %[[C2]]
70
+ func.func @static_non1_succeeds(%arg0 : tensor<?x?xf64>, %arg1 : tensor<?x1xf64>,
71
+ %arg2: tensor<?x2xf64>) -> index {
72
+ %c1 = arith.constant 1 : index
73
+ %1 = shape.shape_of %arg0 : tensor<?x?xf64> -> tensor<2xindex>
74
+ %2 = shape.shape_of %arg1 : tensor<?x1xf64> -> tensor<2xindex>
75
+ %3 = shape.shape_of %arg2 : tensor<?x2xf64> -> tensor<2xindex>
76
+ %4 = shape.broadcast %1, %2, %3 : tensor<2xindex>, tensor<2xindex>,
77
+ tensor<2xindex> -> tensor<2xindex>
78
+ %result = tensor.extract %4[%c1] : tensor<2xindex>
79
+ func.return %result : index
80
+ }
81
+
82
+ // -----
83
+
84
+ // CHECK-LABEL: func @all_static_1s_succeeds
85
+ // CHECK-NEXT: %[[C1:.*]] = arith.constant 1
86
+ // CHECK-NEXT: return %[[C1]]
87
+ func.func @all_static_1s_succeeds(%arg0 : tensor<?x1xf64>, %arg1 : tensor<?x1xf64>)
88
+ -> index {
89
+ %c1 = arith.constant 1 : index
90
+ %1 = shape.shape_of %arg0 : tensor<?x1xf64> -> tensor<2xindex>
91
+ %2 = shape.shape_of %arg1 : tensor<?x1xf64> -> tensor<2xindex>
92
+ %3 = shape.broadcast %1, %2 : tensor<2xindex>, tensor<2xindex>
93
+ -> tensor<2xindex>
94
+ %result = tensor.extract %3[%c1] : tensor<2xindex>
95
+ func.return %result : index
96
+ }
97
+
98
+ // -----
99
+
100
+ // CHECK-LABEL: func @single_non_static_1_succeeds
101
+ // CHECK-SAME: %[[ARG0:.*]]: tensor<?x?xf64>
102
+ // CHECK: %[[C1:.*]] = arith.constant 1
103
+ // CHECK: %[[DIM:.*]] = tensor.dim %[[ARG0]], %[[C1]]
104
+ // CHECK: return %[[DIM]]
105
+ func.func @single_non_static_1_succeeds(%arg0 : tensor<?x?xf64>,
106
+ %arg1 : tensor<?x1xf64>) -> index {
107
+ %c0 = arith.constant 1 : index
108
+ %1 = shape.shape_of %arg0 : tensor<?x?xf64> -> tensor<2xindex>
109
+ %2 = shape.shape_of %arg1 : tensor<?x1xf64> -> tensor<2xindex>
110
+ %3 = shape.broadcast %1, %2 : tensor<2xindex>, tensor<2xindex>
111
+ -> tensor<2xindex>
112
+ %result = tensor.extract %3[%c0] : tensor<2xindex>
113
+ func.return %result : index
114
+ }
115
+
116
+ // -----
117
+
118
+ // CHECK-LABEL: func @multiple_non_static_1_fails
119
+ // CHECK-NEXT: constant 0
120
+ // CHECK-NEXT: shape.shape_of
121
+ // CHECK-NEXT: shape.shape_of
122
+ // CHECK-NEXT: shape.broadcast
123
+ // CHECK-NEXT: %[[RESULT:.*]] = tensor.extract
124
+ // CHECK-NEXT: return %[[RESULT]]
125
+ func.func @multiple_non_static_1_fails(%arg0 : tensor<?x?xf64>,
126
+ %arg1 : tensor<?x1xf64>) -> index {
127
+ %c0 = arith.constant 0 : index
128
+ %1 = shape.shape_of %arg0 : tensor<?x?xf64> -> tensor<2xindex>
129
+ %2 = shape.shape_of %arg1 : tensor<?x1xf64> -> tensor<2xindex>
130
+ %3 = shape.broadcast %1, %2 : tensor<2xindex>, tensor<2xindex>
131
+ -> tensor<2xindex>
132
+ %result = tensor.extract %3[%c0] : tensor<2xindex>
133
+ func.return %result : index
134
+ }
135
+
136
+ // -----
137
+
138
+ // CHECK-LABEL: func @extract_no_crash
139
+ // CHECK-NEXT: tensor.extract
140
+ func.func @extract_no_crash(%arg0 : tensor<index>) -> index {
141
+ %result = tensor.extract %arg0[] : tensor<index>
142
+ func.return %result : index
143
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_abi_knowledge.mlir ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s -allow-unregistered-dialect -propagate-tf-abi-knowledge-to-kernels -split-input-file | FileCheck %s --check-prefixes=CHECK,ABI
2
+ // RUN: kernel-gen-opt %s -allow-unregistered-dialect -propagate-shape-knowledge-to-kernels -split-input-file | FileCheck %s --check-prefixes=CHECK,SHAPE
3
+
4
+ // The input is taken from what is actually used in kernel generator lowering
5
+ // for unary operations.
6
+
7
+ // CHECK-LABEL: module attributes {gpu.container_module}
8
+ module attributes {gpu.container_module} {
9
+ // CHECK-LABEL: func @abs
10
+ func.func @abs(%ctx: !tf_framework.op_kernel_context, %arg0: memref<*xf32>, %size: index)
11
+ attributes {tf_entry} {
12
+ %c0 = arith.constant 0 : index
13
+ %c1 = arith.constant 1 : index
14
+ %13 = memref.alloca() : memref<1xindex>
15
+ memref.store %size, %13[%c0] : memref<1xindex>
16
+ %14 = memref.reshape %arg0(%13) : (memref<*xf32>, memref<1xindex>) -> memref<?xf32>
17
+ %15 = memref.dim %14, %c0 : memref<?xf32>
18
+ %16 = tf_framework.alloc(%ctx, %15) : memref<?xf32>
19
+ gpu.launch_func @abs_kernel::@abs_kernel
20
+ blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1)
21
+ args(%14 : memref<?xf32>, %16 : memref<?xf32>)
22
+ func.return
23
+ }
24
+
25
+ // CHECK-LABEL: gpu.module @abs_kernel
26
+ gpu.module @abs_kernel {
27
+ // CHECK-LABEL: llvm.func @abs_kernel
28
+ // ABI-SAME: %[[ARG0:.*]]: !llvm.ptr, %[[ARG1:.*]]: !llvm.ptr {llvm.align = 16 : index},
29
+ // ABI-SAME: %[[ARG2:.*]]: i64, %[[ARG3:.*]]: i64, %[[ARG4:.*]]: i64, %[[ARG5:.*]]: !llvm.ptr, %[[ARG6:.*]]: !llvm.ptr {llvm.align = 16 : index, llvm.noalias},
30
+ // ABI-SAME: %[[ARG7:.*]]: i64, %[[ARG8:.*]]: i64, %[[ARG9:.*]]: i64
31
+ // SHAPE-SAME: %[[ARG0:.*]]: !llvm.ptr, %[[ARG1:.*]]: !llvm.ptr, %[[ARG2:.*]]: i64, %[[ARG3:.*]]: i64, %[[ARG4:.*]]: i64, %[[ARG5:.*]]: !llvm.ptr, %[[ARG6:.*]]: !llvm.ptr, %[[ARG7:.*]]: i64, %[[ARG8:.*]]: i64, %[[ARG9:.*]]: i64
32
+ llvm.func @abs_kernel(%arg0: !llvm.ptr, %arg1: !llvm.ptr, %arg2: i64, %arg3: i64, %arg4: i64, %arg5: !llvm.ptr, %arg6: !llvm.ptr, %arg7: i64, %arg8: i64, %arg9: i64) attributes {gpu.kernel} {
33
+ // ABI: %[[ZERO:.*]] = llvm.mlir.constant(0 : index)
34
+ // ABI: %[[ONE:.*]] = llvm.mlir.constant(1 : index)
35
+ // CHECK: llvm.mlir.undef
36
+ %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
37
+ // ABI-NEXT: llvm.insertvalue %[[ARG1]]
38
+ // SHAPE-NEXT: llvm.insertvalue %[[ARG0]]
39
+ %1 = llvm.insertvalue %arg0, %0[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
40
+ // CHECK-NEXT: llvm.insertvalue %[[ARG1]]
41
+ %2 = llvm.insertvalue %arg1, %1[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
42
+ // ABI-NEXT: llvm.insertvalue %[[ZERO]]
43
+ // SHAPE-NEXT: llvm.insertvalue %[[ARG2]]
44
+ %3 = llvm.insertvalue %arg2, %2[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
45
+ // CHECK-NEXT: llvm.insertvalue %[[ARG3]]
46
+ %4 = llvm.insertvalue %arg3, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
47
+ // ABI-NEXT: llvm.insertvalue %[[ONE]]
48
+ // SHAPE-NEXT: llvm.insertvalue %[[ARG4]]
49
+ %5 = llvm.insertvalue %arg4, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
50
+ // CHECK-NEXT: llvm.mlir.undef
51
+ %6 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
52
+ // ABI-NEXT: llvm.insertvalue %[[ARG6]]
53
+ // SHAPE-NEXT: llvm.insertvalue %[[ARG5]]
54
+ %7 = llvm.insertvalue %arg5, %6[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
55
+ // CHECK-NEXT: llvm.insertvalue %[[ARG6]]
56
+ %8 = llvm.insertvalue %arg6, %7[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
57
+ // ABI-NEXT: llvm.insertvalue %[[ZERO]]
58
+ // SHAPE-NEXT: llvm.insertvalue %[[ARG7]]
59
+ %9 = llvm.insertvalue %arg7, %8[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
60
+ // ABI-NEXT: llvm.insertvalue %[[ARG8]]
61
+ // SHAPE-NEXT: llvm.insertvalue %[[ARG3]]
62
+ %10 = llvm.insertvalue %arg8, %9[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
63
+ // ABI-NEXT: llvm.insertvalue %[[ONE]]
64
+ // SHAPE-NEXT: llvm.insertvalue %[[ARG4]]
65
+ %11 = llvm.insertvalue %arg9, %10[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
66
+ llvm.return
67
+ // CHECK-NEXT: llvm.return
68
+ }
69
+ }
70
+ }
71
+
72
+ // -----
73
+
74
+ // Binary op without broadcasting (same shape).
75
+
76
+ // CHECK-LABEL: module attributes {gpu.container_module}
77
+ module attributes {gpu.container_module} {
78
+ // CHECK-LABEL: func @add_same_shape
79
+ func.func @add_same_shape(%arg0: !tf_framework.op_kernel_context, %arg1: memref<*xf32>, %arg2: memref<*xf32>, %size: index)
80
+ attributes {tf_entry} {
81
+ %c0 = arith.constant 0 : index
82
+ %c1 = arith.constant 1 : index
83
+ %82 = memref.reinterpret_cast %arg1 to offset: [0], sizes: [%size], strides: [%c1]: memref<*xf32> to memref<?xf32, strided<[?], offset: 0>>
84
+ %83 = memref.reinterpret_cast %arg2 to offset: [0], sizes: [%size], strides: [%c1]: memref<*xf32> to memref<?xf32, strided<[?], offset: 0>>
85
+ %84 = tf_framework.alloc(%arg0, %size) : memref<?xf32>
86
+ gpu.launch_func @AddV2_kernel_1::@AddV2_kernel blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1) args(%size : index, %82 : memref<?xf32, strided<[?], offset: 0>>, %83 : memref<?xf32, strided<[?], offset: 0>>, %84 : memref<?xf32>)
87
+ func.return
88
+ }
89
+
90
+ // CHECK-LABEL: gpu.module @AddV2_kernel_1
91
+ gpu.module @AddV2_kernel_1 {
92
+ // CHECK-LABEL: llvm.func @AddV2_kernel
93
+ // ABI-SAME: {llvm.align = 16 : index}
94
+ // ABI-SAME: {llvm.align = 16 : index}
95
+ // ABI-SAME: {llvm.align = 16 : index, llvm.noalias}
96
+ llvm.func @AddV2_kernel(%arg0: i64, %arg1: !llvm.ptr, %arg2: !llvm.ptr, %arg3: i64, %arg4: i64, %arg5: i64, %arg6: !llvm.ptr, %arg7: !llvm.ptr, %arg8: i64, %arg9: i64, %arg10: i64, %arg11: !llvm.ptr, %arg12: !llvm.ptr, %arg13: i64, %arg14: i64, %arg15: i64) attributes {gpu.kernel} {
97
+ // ABI: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64
98
+ // ABI: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64
99
+ %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
100
+ %1 = llvm.insertvalue %arg1, %0[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
101
+ %2 = llvm.insertvalue %arg2, %1[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
102
+ %3 = llvm.insertvalue %arg3, %2[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
103
+ %4 = llvm.insertvalue %arg4, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
104
+ %5 = llvm.insertvalue %arg5, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
105
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
106
+ // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
107
+ // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
108
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
109
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
110
+ // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
111
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
112
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
113
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
114
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
115
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP:.*]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
116
+ // SHAPE-NEXT: llvm.insertvalue %[[STR:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
117
+ %6 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
118
+ %7 = llvm.insertvalue %arg6, %6[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
119
+ %8 = llvm.insertvalue %arg7, %7[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
120
+ %9 = llvm.insertvalue %arg8, %8[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
121
+ %10 = llvm.insertvalue %arg9, %9[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
122
+ %11 = llvm.insertvalue %arg10, %10[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
123
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
124
+ // ABI-NEXT: llvm.insertvalue %[[PTR1:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
125
+ // ABI-NEXT: llvm.insertvalue %[[PTR1]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
126
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
127
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
128
+ // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
129
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
130
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
131
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
132
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
133
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
134
+ // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
135
+ %12 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
136
+ %13 = llvm.insertvalue %arg11, %12[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
137
+ %14 = llvm.insertvalue %arg12, %13[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
138
+ %15 = llvm.insertvalue %arg13, %14[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
139
+ %16 = llvm.insertvalue %arg14, %15[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
140
+ %17 = llvm.insertvalue %arg15, %16[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
141
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
142
+ // ABI-NEXT: llvm.insertvalue %[[PTR2:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
143
+ // ABI-NEXT: llvm.insertvalue %[[PTR2]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
144
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
145
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
146
+ // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
147
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
148
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
149
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
150
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
151
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
152
+ // SHAPE-NEXT: llvm.insertvalue %[[STR1:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
153
+ // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
154
+ llvm.return
155
+ // CHECK-NEXT: llvm.return
156
+ }
157
+ }
158
+ }
159
+
160
+ // -----
161
+
162
+ // Test binary op with broadcasting - 2d case.
163
+
164
+ // CHECK-LABEL: module attributes {gpu.container_module}
165
+ module attributes {gpu.container_module} {
166
+ // CHECK-LABEL: func @add_same_shape
167
+ func.func @add_same_shape(%arg0: !tf_framework.op_kernel_context, %arg1: memref<*xf32>, %arg2: memref<*xf32>, %size0: index, %size1: index, %stride0: index, %stride1: index)
168
+ attributes {tf_entry} {
169
+ %c1 = arith.constant 1 : index
170
+ %216 = memref.reinterpret_cast %arg1 to offset: [0], sizes: [%size1, %size0], strides: [%size0, %c1]: memref<*xf32> to memref<?x?xf32, strided<[?, ?], offset: 0>>
171
+ %241 = memref.reinterpret_cast %arg2 to offset: [0], sizes: [%size1, %size0], strides: [%size0, %c1]: memref<*xf32> to memref<?x?xf32, strided<[?, ?], offset: 0>>
172
+ %304 = memref.reinterpret_cast %216 to offset: [0], sizes: [%size1, %size0], strides: [%stride1, %stride0]: memref<?x?xf32, strided<[?, ?], offset: 0>> to memref<?x?xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s0 + d1 * s1)>>
173
+ %309 = memref.reinterpret_cast %241 to offset: [0], sizes: [%size1, %size0], strides: [%stride0, %stride1]: memref<?x?xf32, strided<[?, ?], offset: 0>> to memref<?x?xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s0 + d1 * s1)>>
174
+ %310 = tf_framework.alloc(%arg0, %size1, %size0) : memref<?x?xf32>
175
+ gpu.launch_func @AddV2_kernel_3::@AddV2_kernel blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1) args(%size0 : index, %size1 : index, %310 : memref<?x?xf32>, %304 : memref<?x?xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s0 + d1 * s1)>>, %309 : memref<?x?xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s0 + d1 * s1)>>)
176
+ func.return
177
+ }
178
+
179
+ // CHECK-LABEL: gpu.module @AddV2_kernel_3
180
+ gpu.module @AddV2_kernel_3 {
181
+ // CHECK-LABEL: llvm.func @AddV2_kernel
182
+ // ABI-SAME: {llvm.align = 16 : index, llvm.noalias}
183
+ // ABI-SAME: {llvm.align = 16 : index}
184
+ // ABI-SAME: {llvm.align = 16 : index}
185
+ llvm.func @AddV2_kernel(%arg0: i64, %arg1: i64, %arg2: !llvm.ptr, %arg3: !llvm.ptr {llvm.align = 16 : index, llvm.noalias}, %arg4: i64, %arg5: i64, %arg6: i64, %arg7: i64, %arg8: i64, %arg9: !llvm.ptr, %arg10: !llvm.ptr {llvm.align = 16 : index}, %arg11: i64, %arg12: i64, %arg13: i64, %arg14: i64, %arg15: i64, %arg16: !llvm.ptr, %arg17: !llvm.ptr {llvm.align = 16 : index}, %arg18: i64, %arg19: i64, %arg20: i64, %arg21: i64, %arg22: i64) attributes {gpu.kernel} {
186
+ // ABI: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64
187
+ // ABI: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64
188
+ %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
189
+ %1 = llvm.insertvalue %arg2, %0[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
190
+ %2 = llvm.insertvalue %arg3, %1[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
191
+ %3 = llvm.insertvalue %arg4, %2[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
192
+ %4 = llvm.insertvalue %arg5, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
193
+ %5 = llvm.insertvalue %arg7, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
194
+ %6 = llvm.insertvalue %arg6, %5[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
195
+ %7 = llvm.insertvalue %arg8, %6[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
196
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
197
+ // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
198
+ // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
199
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
200
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
201
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
202
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
203
+ // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
204
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
205
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
206
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
207
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
208
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP0:.*]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
209
+ // SHAPE-NEXT: llvm.insertvalue %[[STR0:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
210
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP1:.*]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
211
+ // SHAPE-NEXT: llvm.insertvalue %[[STR1:.*]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
212
+ %8 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
213
+ %9 = llvm.insertvalue %arg9, %8[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
214
+ %10 = llvm.insertvalue %arg10, %9[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
215
+ %11 = llvm.insertvalue %arg11, %10[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
216
+ %12 = llvm.insertvalue %arg12, %11[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
217
+ %13 = llvm.insertvalue %arg14, %12[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
218
+ %14 = llvm.insertvalue %arg13, %13[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
219
+ %15 = llvm.insertvalue %arg15, %14[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
220
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
221
+ // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
222
+ // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
223
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
224
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
225
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
226
+ // ABI-NOT: llvm.insertvalue %[[C1]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
227
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
228
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
229
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
230
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
231
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP0]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
232
+ // SHAPE-NOT: llvm.insertvalue %[[STR0]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
233
+ // SHAPE: llvm.insertvalue %[[SHP1]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
234
+ // SHAPE-NOT: llvm.insertvalue %[[STR1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
235
+ %16 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
236
+ %17 = llvm.insertvalue %arg16, %16[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
237
+ %18 = llvm.insertvalue %arg17, %17[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
238
+ %19 = llvm.insertvalue %arg18, %18[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
239
+ %20 = llvm.insertvalue %arg19, %19[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
240
+ %21 = llvm.insertvalue %arg21, %20[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
241
+ %22 = llvm.insertvalue %arg20, %21[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
242
+ %23 = llvm.insertvalue %arg22, %22[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
243
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
244
+ // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
245
+ // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
246
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
247
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
248
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
249
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
250
+ // ABI-NOT: llvm.insertvalue %[[C1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
251
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
252
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
253
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
254
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
255
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP0]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
256
+ // SHAPE-NOT: llvm.insertvalue %[[STR0]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
257
+ // SHAPE: llvm.insertvalue %[[SHP1]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
258
+ // SHAPE-NOT: llvm.insertvalue %[[STR1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
259
+ llvm.return
260
+ // CHECK: llvm.return
261
+ }
262
+ }
263
+ }
264
+
265
+ // -----
266
+
267
+
268
+ // Test binary op with broadcasting a scalar.
269
+
270
+ #map0 = affine_map<(d0)[s0] -> (d0 * s0)>
271
+
272
+ // CHECK-LABEL: module attributes {gpu.container_module}
273
+ module attributes {gpu.container_module} {
274
+ // CHECK-LABEL: func @add_one_scalar
275
+ func.func @add_one_scalar(%arg0: !tf_framework.op_kernel_context, %arg1: memref<*xf32>, %arg2: memref<*xf32>, %size: index)
276
+ attributes {tf_entry} {
277
+ %c0 = arith.constant 0 : index
278
+ %c1 = arith.constant 1 : index
279
+ %13 = memref.cast %arg1 : memref<*xf32> to memref<f32>
280
+ %26 = memref.reinterpret_cast %arg2 to offset: [0], sizes: [%size], strides: [%c1]: memref<*xf32> to memref<?xf32, strided<[?], offset: 0>>
281
+ %27 = memref.reinterpret_cast %13 to offset: [0], sizes: [%size], strides: [%c0]: memref<f32> to memref<?xf32, #map0>
282
+ %28 = memref.reinterpret_cast %26 to offset: [0], sizes: [%size], strides: [%c1]: memref<?xf32, strided<[?], offset: 0>> to memref<?xf32, #map0>
283
+ %29 = tf_framework.alloc(%arg0, %size) : memref<?xf32>
284
+ gpu.launch_func @AddV2_kernel::@AddV2_kernel blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1) args(%size : index, %29 : memref<?xf32>, %27 : memref<?xf32, #map0>, %28 : memref<?xf32, #map0>)
285
+ func.return
286
+ }
287
+ // CHECK-LABEL: gpu.module @AddV2_kernel
288
+ gpu.module @AddV2_kernel {
289
+ // CHECK-LABEL: llvm.func @AddV2_kernel
290
+ // ABI-SAME: {llvm.align = 16 : index, llvm.noalias}
291
+ // ABI-SAME: {llvm.align = 16 : index}
292
+ // ABI-SAME: {llvm.align = 16 : index}
293
+ llvm.func @AddV2_kernel(%arg0: i64, %arg1: !llvm.ptr, %arg2: !llvm.ptr, %arg3: i64, %arg4: i64, %arg5: i64, %arg6: !llvm.ptr, %arg7: !llvm.ptr, %arg8: i64, %arg9: i64, %arg10: i64, %arg11: !llvm.ptr, %arg12: !llvm.ptr, %arg13: i64, %arg14: i64, %arg15: i64) attributes {gpu.kernel} {
294
+ // ABI: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64
295
+ // ABI: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64
296
+ %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
297
+ %1 = llvm.insertvalue %arg1, %0[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
298
+ %2 = llvm.insertvalue %arg2, %1[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
299
+ %3 = llvm.insertvalue %arg3, %2[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
300
+ %4 = llvm.insertvalue %arg4, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
301
+ %5 = llvm.insertvalue %arg5, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
302
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
303
+ // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
304
+ // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
305
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
306
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
307
+ // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
308
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
309
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
310
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
311
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
312
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP:.*]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
313
+ // SHAPE-NEXT: llvm.insertvalue %[[STR:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
314
+ %6 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
315
+ %7 = llvm.insertvalue %arg6, %6[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
316
+ %8 = llvm.insertvalue %arg7, %7[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
317
+ %9 = llvm.insertvalue %arg8, %8[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
318
+ %10 = llvm.insertvalue %arg9, %9[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
319
+ %11 = llvm.insertvalue %arg10, %10[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
320
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
321
+ // ABI-NEXT: llvm.insertvalue %[[PTR1:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
322
+ // ABI-NEXT: llvm.insertvalue %[[PTR1]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
323
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
324
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
325
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
326
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
327
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
328
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
329
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
330
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
331
+ // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
332
+ %12 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
333
+ %13 = llvm.insertvalue %arg11, %12[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
334
+ %14 = llvm.insertvalue %arg12, %13[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
335
+ %15 = llvm.insertvalue %arg13, %14[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
336
+ %16 = llvm.insertvalue %arg14, %15[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
337
+ %17 = llvm.insertvalue %arg15, %16[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
338
+ // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
339
+ // ABI-NEXT: llvm.insertvalue %[[PTR2:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
340
+ // ABI-NEXT: llvm.insertvalue %[[PTR2]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
341
+ // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
342
+ // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
343
+ // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
344
+ // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
345
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
346
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
347
+ // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
348
+ // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
349
+ // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)>
350
+ llvm.return
351
+ // CHECK: llvm.return
352
+ }
353
+ }
354
+ }
355
+
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_framework_legalize_to_llvm.mlir ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s -tf-kernel-to-llvm -reconcile-unrealized-casts -split-input-file | FileCheck %s
2
+
3
+ // CHECK: llvm.func @_mlir_ciface_tf_alloc
4
+ // CHECK-SAME: (!llvm.ptr, i64, i64, i32, i32, !llvm.ptr) -> !llvm.ptr
5
+
6
+ // CHECK-LABEL: llvm.func @alloc(
7
+ // CHECK-SAME: [[TF_CTX:%.*]]: !llvm.ptr,
8
+ // CHECK-SAME: [[SIZE_0:%.*]]: i64,
9
+ // CHECK-SAME: [[SIZE_2:%.*]]: i64) -> [[DESC_TY:!.*]] {
10
+ func.func @alloc(%ctx: !tf_framework.op_kernel_context,
11
+ %size_0 : index , %size_2 : index) -> memref<?x10x?xf32> {
12
+ %buf = tf_framework.alloc(%ctx, %size_0, %size_2) : memref<?x10x?xf32>
13
+ func.return %buf : memref<?x10x?xf32>
14
+ }
15
+ // Compute number of elements.
16
+ // CHECK: [[SIZE_1A:%.*]] = llvm.mlir.constant(10 : index) : i64
17
+ // CHECK: [[SIZE_1B:%.*]] = llvm.mlir.constant(10 : index) : i64
18
+ // CHECK: [[NUM_ELEM_0:%.*]] = llvm.mul [[SIZE_0]], [[SIZE_1B]] : i64
19
+ // CHECK: [[NUM_ELEMS:%.*]] = llvm.mul [[NUM_ELEM_0]], [[SIZE_2]] : i64
20
+
21
+ // Compute the size of an individual element.
22
+ // CHECK: [[NULL:%.*]] = llvm.mlir.zero : !llvm.ptr
23
+ // CHECK: [[GEP:%.*]] = llvm.getelementptr [[NULL]]{{\[}}1]
24
+ // CHECK-SAME: (!llvm.ptr) -> !llvm.ptr, f32
25
+ // CHECK: [[SIZE_OF_FLOAT:%.*]] = llvm.ptrtoint [[GEP]]
26
+ // CHECK-SAME: !llvm.ptr to i64
27
+
28
+ // Compute output index (-1) and candidate indices (0, NULL).
29
+ // CHECK: [[OUTPUT_INDEX:%.*]] = llvm.mlir.constant(-1 : i32) : i32
30
+ // CHECK-NEXT: [[NUM_CANDIDATES:%.*]] = llvm.mlir.constant(0 : i32) : i32
31
+ // CHECK-NEXT: [[CANDIDATES_PTR:%.*]] = llvm.mlir.zero : !llvm.ptr
32
+
33
+ // Allocate memory.
34
+ // CHECK: [[BYTES_PTR:%.*]] = llvm.call @{{.*}}([[TF_CTX]], [[NUM_ELEMS]],
35
+ // CHECK-SAME: [[SIZE_OF_FLOAT]], [[OUTPUT_INDEX]], [[NUM_CANDIDATES]],
36
+ // CHECK-SAME: [[CANDIDATES_PTR]])
37
+
38
+ // Build memref descriptor.
39
+ // CHECK: [[DESC_0:%.*]] = llvm.mlir.poison : [[DESC_TY]]
40
+
41
+ // Set pointers and offset.
42
+ // CHECK: [[DESC_1:%.*]] = llvm.insertvalue [[BYTES_PTR]], [[DESC_0]][0]
43
+ // CHECK: [[DESC_2:%.*]] = llvm.insertvalue [[BYTES_PTR]], [[DESC_1]][1]
44
+ // CHECK: [[C0:%.*]] = llvm.mlir.constant(0 : index) : i64
45
+ // CHECK: [[DESC_3:%.*]] = llvm.insertvalue [[C0]], [[DESC_2]][2] : [[DESC_TY]]
46
+
47
+ // Set sizes and strides.
48
+ // CHECK: [[STRIDE_2:%.*]] = llvm.mlir.constant(1 : index) : i64
49
+ // CHECK: [[DESC_4:%.*]] = llvm.insertvalue [[SIZE_2]], [[DESC_3]][3, 2]
50
+ // CHECK: [[DESC_5:%.*]] = llvm.insertvalue [[STRIDE_2]], [[DESC_4]][4, 2]
51
+ // CHECK: [[STRIDE_1:%.*]] = llvm.mul [[STRIDE_2]], [[SIZE_2]] : i64
52
+ // CHECK: [[DESC_6:%.*]] = llvm.insertvalue [[SIZE_1A]], [[DESC_5]][3, 1]
53
+ // CHECK: [[DESC_7:%.*]] = llvm.insertvalue [[STRIDE_1]], [[DESC_6]][4, 1]
54
+ // CHECK: [[STRIDE_0:%.*]] = llvm.mul [[STRIDE_1]], [[SIZE_1A]] : i64
55
+ // CHECK: [[DESC_8:%.*]] = llvm.insertvalue [[SIZE_0]], [[DESC_7]][3, 0]
56
+ // CHECK: [[DESC_9:%.*]] = llvm.insertvalue [[STRIDE_0]], [[DESC_8]][4, 0]
57
+ // CHECK: llvm.return [[DESC_9]] : [[DESC_TY]]
58
+
59
+ // -----
60
+
61
+ // CHECK: llvm.func @_mlir_ciface_tf_dealloc(!llvm.ptr, !llvm.ptr)
62
+
63
+ // CHECK-LABEL: llvm.func @dealloc(
64
+ // CHECK-SAME: [[TF_CTX:%[a-z0-9]*]]: !llvm.ptr
65
+ func.func @dealloc(%ctx: !tf_framework.op_kernel_context,
66
+ %memref : memref<?x10xf32>) {
67
+ tf_framework.dealloc(%ctx, %memref) : memref<?x10xf32>
68
+ func.return
69
+ }
70
+ // Extract allocated ptr from the memref descriptor.
71
+ // CHECK: %{{.*}} = llvm.mlir.poison : [[DESC_TY:!.*]]
72
+ // CHECK: [[FLOAT_PTR:%.*]] = llvm.extractvalue %{{.*}}[0] : [[DESC_TY]]
73
+
74
+ // Deallocate.
75
+ // CHECK: llvm.call @_mlir_ciface_tf_dealloc(
76
+ // CHECK-SAME: [[TF_CTX]], [[FLOAT_PTR]]) : (!llvm.ptr, !llvm.ptr) -> ()
77
+
78
+ // -----
79
+
80
+ // CHECK-LABEL: llvm.func @_mlir_ciface_tf_report_error(!llvm.ptr, i32, !llvm.ptr)
81
+ // CHECK: llvm.mlir.global internal constant [[MSG_CONST:@error_message_[0-9]+]]("Everything is awesome\00")
82
+
83
+ func.func @report_error(%ctx: !tf_framework.op_kernel_context) {
84
+ tf_framework.report_error %ctx, "INVALID_ARGUMENT", "Everything is awesome" loc(unknown)
85
+ func.return
86
+ }
87
+ // CHECK: llvm.func @report_error([[CTX:%.*]]: !llvm.ptr)
88
+ // CHECK-NEXT: [[ADDR:%.*]] = llvm.mlir.addressof [[MSG_CONST]]
89
+ // CHECK: [[MSG:%.*]] = llvm.getelementptr [[ADDR]]
90
+ // CHECK: [[CODE:%.*]] = llvm.mlir.constant({{.*}}) : i32
91
+ // CHECK: llvm.call @{{.*}}_tf_report_error([[CTX]], [[CODE]], [[MSG]])
92
+
93
+ // -----
94
+
95
+ // CHECK-LABEL: llvm.func @unranked_null_memref()
96
+ func.func @unranked_null_memref() {
97
+ %null = tf_framework.null_memref : memref<*xf32>
98
+ func.return
99
+ }
100
+ // CHECK: [[C0:%.*]] = llvm.mlir.constant(0 : index) : i64
101
+ // CHECK: [[DESC_0:%.*]] = llvm.mlir.poison : !llvm.struct<(i64, ptr)>
102
+ // CHECK: [[DESC_1:%.*]] = llvm.insertvalue [[C0]], [[DESC_0]][0]
103
+ // CHECK: [[PTR:%.*]] = llvm.alloca {{.*}} x i8
104
+ // CHECK: [[DESC_2:%.*]] = llvm.insertvalue [[PTR]], [[DESC_1]][1]
105
+
106
+ // -----
107
+
108
+ // CHECK-LABEL: llvm.func @ranked_null_memref()
109
+ func.func @ranked_null_memref() {
110
+ %null = tf_framework.null_memref : memref<2x?xf32>
111
+ func.return
112
+ }
113
+ // CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64
114
+ // CHECK-NEXT: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64
115
+ // CHECK-NEXT: %[[C2:.*]] = llvm.mlir.constant(2 : index) : i64
116
+ // CHECK-NEXT: %[[C1_:.*]] = llvm.mlir.constant(1 : index) : i64
117
+
118
+ // CHECK: llvm.mlir.zero
119
+ // CHECK: %[[NULL:.*]] = llvm.mlir.zero : !llvm.ptr
120
+ // CHECK-NEXT: %[[DESC_0:.*]] = llvm.mlir.poison :
121
+ // CHECK-SAME: !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)>
122
+ // CHECK-NEXT: %[[DESC_1:.*]] = llvm.insertvalue %[[NULL]], %[[DESC_0]][0]
123
+ // CHECK-NEXT: %[[DESC_2:.*]] = llvm.insertvalue %[[NULL]], %[[DESC_1]][1]
124
+ // CHECK-NEXT: %[[DESC_3:.*]] = llvm.insertvalue %[[C0]], %[[DESC_2]][2]
125
+ // CHECK-NEXT: %[[DESC_4:.*]] = llvm.insertvalue %[[C2]], %[[DESC_3]][3, 0]
126
+ // CHECK-NEXT: %[[DESC_5:.*]] = llvm.insertvalue %[[C1]], %[[DESC_4]][4, 0]
127
+ // CHECK-NEXT: %[[DESC_6:.*]] = llvm.insertvalue %[[C1]], %[[DESC_5]][3, 1]
128
+ // CHECK-NEXT: %[[DESC_7:.*]] = llvm.insertvalue %[[C1_]], %[[DESC_6]][4, 1]
129
+
130
+ // -----
131
+
132
+ // CHECK-LABEL: llvm.func @is_valid_memref
133
+ func.func @is_valid_memref(%buf: memref<?xf32>) -> i1 {
134
+ %pred = tf_framework.is_valid_memref(%buf) : memref<?xf32> -> i1
135
+ func.return %pred : i1
136
+ }
137
+ // CHECK: %[[MEMREF:.*]] = llvm.insertvalue %{{.*}}, %{{.*}}[4, 0]
138
+
139
+ // CHECK-NEXT: %[[IS_EMPTY:.*]] = llvm.mlir.constant(false) : i1
140
+ // CHECK-NEXT: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64
141
+ // CHECK-NEXT: %[[SIZE:.*]] = llvm.extractvalue %[[MEMREF]][3, 0]
142
+ // CHECK-NEXT: %[[IS_ZERO:.*]] = llvm.icmp "eq" %[[SIZE]], %[[C0]] : i64
143
+ // CHECK-NEXT: %[[IS_EMPTY_:.*]] = llvm.or %[[IS_EMPTY]], %[[IS_ZERO]] : i1
144
+
145
+ // CHECK-NEXT: %[[PTR_F32:.*]] = llvm.extractvalue %[[MEMREF]][0]
146
+ // CHECK-NEXT: %[[NULL_PTR:.*]] = llvm.mlir.zero : !llvm.ptr
147
+ // CHECK-NEXT: %[[NOT_NULL:.*]] = llvm.icmp "ne" %[[PTR_F32]], %[[NULL_PTR]]
148
+
149
+ // CHECK-NEXT: %[[PRED:.*]] = llvm.or %[[NOT_NULL]], %[[IS_EMPTY_]] : i1
150
+ // CHECK-NEXT: llvm.return %[[PRED]]
151
+
152
+ // -----
153
+
154
+ // CHECK-LABEL: llvm.func @_mlir_ciface_tf_jit_compile(!llvm.ptr, !llvm.ptr, i64, !llvm.ptr, i64, !llvm.ptr, i1, i1, i1) -> !llvm.ptr
155
+ // CHECK: llvm.mlir.global internal constant @[[CODE:jit_module_code_[0-9]+]]("placeholder\00")
156
+
157
+ // CHECK: @jit_compile_from_str(%[[CTX:.*]]: !llvm.ptr)
158
+ func.func @jit_compile_from_str(%ctx: !tf_framework.op_kernel_context)
159
+ -> !tf_framework.jit_callable {
160
+ // CHECK: %[[ADDR:.*]] = llvm.mlir.addressof @[[CODE]]
161
+ // CHECK: %[[CODE_PTR:.*]] = llvm.getelementptr %[[ADDR]][0, 0]
162
+
163
+ // Create stack-allocated array for the tile sizes.
164
+ // CHECK: %[[NUM_TILE_SIZES:.*]] = llvm.mlir.constant(3 : i64)
165
+ // CHECK: %[[TILE_SIZES:.*]] = llvm.alloca %[[NUM_TILE_SIZES]] x i64
166
+ // CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : i64)
167
+ // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[TILE_SIZES]][%[[C0]]]
168
+ // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : i64)
169
+ // CHECK: llvm.store %[[C1]], %[[PTR]]
170
+ // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : i64)
171
+ // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[TILE_SIZES]][%[[C1]]]
172
+ // CHECK: %[[C2:.*]] = llvm.mlir.constant(2 : i64)
173
+ // CHECK: llvm.store %[[C2]], %[[PTR]]
174
+ // CHECK: %[[C2:.*]] = llvm.mlir.constant(2 : i64)
175
+ // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[TILE_SIZES]][%[[C2]]]
176
+ // CHECK: %[[C3:.*]] = llvm.mlir.constant(3 : i64)
177
+ // CHECK: llvm.store %[[C3]], %[[PTR]]
178
+
179
+ // Create stack-allocated array for the unroll factors.
180
+ // CHECK: %[[NUM_UNROLL_FACTORS:.*]] = llvm.mlir.constant(1 : i64) : i64
181
+ // CHECK: %[[UNROLL_FACTORS:.*]] = llvm.alloca %[[NUM_UNROLL_FACTORS]] x i64
182
+ // CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : i64)
183
+ // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[UNROLL_FACTORS]][%[[C0]]]
184
+ // CHECK: %[[C4:.*]] = llvm.mlir.constant(4 : i64)
185
+ // CHECK: llvm.store %[[C4]], %[[PTR]]
186
+
187
+ // CHECK-DAG: %[[ENABLE_FTZ:.*]] = llvm.mlir.constant(false)
188
+ // CHECK-DAG: %[[CPU_CODEGEN:.*]] = llvm.mlir.constant(false)
189
+ // CHECK: %[[RES:.*]] = llvm.call @_mlir_ciface_tf_jit_compile
190
+ // CHECK-SAME: %[[CTX]], %[[CODE_PTR]],
191
+ // CHECK-SAME: %[[NUM_TILE_SIZES]], %[[TILE_SIZES]],
192
+ // CHECK-SAME: %[[NUM_UNROLL_FACTORS]], %[[UNROLL_FACTORS]],
193
+ // CHECK-SAME: %[[ENABLE_FTZ]], %[[CPU_CODEGEN]]
194
+ // CHECK: llvm.return %[[RES]]
195
+ %0 = tf_framework.jit_compile_from_str %ctx, "placeholder" {
196
+ tileSizes = [1, 2, 3], unrollFactors = [4],
197
+ enableFtz = false, index64Bit = false, cpuCodegen = false }
198
+ func.return %0 : !tf_framework.jit_callable
199
+ }
200
+
201
+ // -----
202
+
203
+ // CHECK-LABEL: llvm.func @_mlir_ciface_tf_jit_execute(!llvm.ptr, !llvm.ptr, !llvm.ptr, i64, !llvm.ptr)
204
+
205
+ // CHECK: @jit_execute
206
+ // CHECK-SAME: (%[[CTX:.*]]: !llvm.ptr, %[[CALLABLE:.*]]: !llvm.ptr, %[[RANK:.*]]: i64, %[[ARG_DESCR:.*]]: !llvm.ptr)
207
+ func.func @jit_execute(%ctx: !tf_framework.op_kernel_context,
208
+ %callable : !tf_framework.jit_callable, %arg : memref<*xf32>)
209
+ -> memref<*xf32> {
210
+ // CHECK: %[[T0:.*]] = llvm.mlir.poison
211
+ // CHECK: %[[T1:.*]] = llvm.insertvalue %[[RANK]], %[[T0]][0]
212
+ // CHECK: %[[ARG:.*]] = llvm.insertvalue %[[ARG_DESCR]], %[[T1]][1]
213
+ // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : i64)
214
+ // CHECK: %[[RESULT_PTR:.*]] = llvm.alloca %[[C1]] x !llvm.struct<(i64, ptr)>
215
+
216
+ // Copy argument(s) to stack-allocated buffer.
217
+ // CHECK: %[[NUM_ARGS:.*]] = llvm.mlir.constant(1 : i64)
218
+ // CHECK: %[[ARGS_PTR:.*]] = llvm.alloca %[[NUM_ARGS]] x !llvm.struct<(i64, ptr)>
219
+ // CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : i64)
220
+ // CHECK: %[[ARGS0_PTR:.*]] = llvm.getelementptr %[[ARGS_PTR]][%[[C0]]]
221
+ // CHECK: llvm.store %[[ARG]], %[[ARGS0_PTR]]
222
+ // CHECK: llvm.call @_mlir_ciface_tf_jit_execute(%[[CTX]], %[[CALLABLE]], %[[RESULT_PTR]], %[[NUM_ARGS]], %[[ARGS_PTR]])
223
+ // CHECK: %[[RESULT:.*]] = llvm.load %[[RESULT_PTR]]
224
+
225
+ // Copy unranked memref descriptor to stack-allocated memory.
226
+ // ...
227
+ // CHECK: %[[STACK_RESULT_DESCR:.*]] = llvm.alloca %[[RESULT_DESCR_SIZE:[0-9]*]] x i8
228
+ // CHECK: %[[RESULT_DESCR:.*]] = llvm.extractvalue %[[RESULT]][1]
229
+ // CHECK: "llvm.intr.memcpy"(%[[STACK_RESULT_DESCR]], %[[RESULT_DESCR]], %[[RESULT_DESCR_SIZE]]) <{isVolatile = false}>
230
+ // CHECK: llvm.call @free(%[[RESULT_DESCR]])
231
+ // CHECK: %[[T0:.*]] = llvm.mlir.poison
232
+ // CHECK: %[[RANK:.*]] = llvm.extractvalue %[[RESULT]][0]
233
+ // CHECK: %[[T1:.*]] = llvm.insertvalue %[[RANK]], %[[T0]][0]
234
+ // CHECK: %[[RESULT:.*]] = llvm.insertvalue %[[STACK_RESULT_DESCR]], %[[T1]][1]
235
+
236
+ // Copy unranked memref descriptor to heap-allocated memory for return.
237
+ // ...
238
+ // CHECK: %[[HEAP_RESULT_DESCR:.*]] = llvm.call @malloc(%[[RESULT_DESCR_SIZE:[0-9]*]])
239
+ // CHECK: %[[STACK_RESULT_DESCR:.*]] = llvm.extractvalue %[[RESULT]][1]
240
+ // CHECK: "llvm.intr.memcpy"(%[[HEAP_RESULT_DESCR]], %[[STACK_RESULT_DESCR]], %[[RESULT_DESCR_SIZE]]) <{isVolatile = false}>
241
+ // CHECK: %[[T0:.*]] = llvm.mlir.poison
242
+ // CHECK: %[[RANK:.*]] = llvm.extractvalue %[[RESULT]][0]
243
+ // CHECK: %[[T1:.*]] = llvm.insertvalue %[[RANK]], %[[T0]][0]
244
+ // CHECK: %[[RESULT:.*]] = llvm.insertvalue %[[HEAP_RESULT_DESCR]], %[[T1]][1]
245
+ // CHECK: llvm.return %[[RESULT]]
246
+ %0 = tf_framework.jit_execute ctx(%ctx) %callable(%arg)
247
+ : memref<*xf32> -> memref<*xf32>
248
+ func.return %0 : memref<*xf32>
249
+ }
western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_kernel_gpu_launch_to_llvm.mlir ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // RUN: kernel-gen-opt %s -tf-kernel-to-llvm -reconcile-unrealized-casts -split-input-file | FileCheck %s --dump-input=always
2
+
3
+ // CHECK-LABEL: module @main
4
+ module @main attributes {gpu.container_module} {
5
+
6
+ // CHECK-NOT: gpu.module @kernel_module
7
+ gpu.module @kernel_module attributes {gpu.binary_blob = "BLOB!"} {
8
+ llvm.func @the_kernel() attributes {gpu.kernel} {
9
+ llvm.return
10
+ }
11
+ }
12
+
13
+ // CHECK: llvm.func @_mlir_ciface_tf_launch_kernel(!llvm.ptr, !llvm.ptr, !llvm.ptr, i64, i64, i64, i64, i64, i64, !llvm.ptr)
14
+ // CHECK-DAG: llvm.mlir.global internal constant @kernel_module_the_kernel_kernel_name("the_kernel\00")
15
+ // CHECK-DAG: llvm.mlir.global internal constant @kernel_module_blob("BLOB!")
16
+
17
+ // CHECK-LABEL: llvm.func @launch
18
+ // CHECK-SAME: (%[[CTX:.*]]: !llvm.ptr, %{{.*}}: !llvm.ptr, %{{.*}}: !llvm.ptr, %{{.*}}: i64, %{{.*}}: i64, %{{.*}}: i64, %{{.*}}: i64, %{{.*}}: i64
19
+ func.func @launch(%ctx: !tf_framework.op_kernel_context, %memref: memref<?x10xf32>) {
20
+ // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64
21
+ // CHECK: %[[BLOB:.*]] = llvm.mlir.addressof @kernel_module_blob : !llvm.ptr
22
+ // CHECK: %[[BLOB_PTR:.*]] = llvm.getelementptr %[[BLOB]][0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.array<5 x i8>
23
+ // CHECK: %[[NAME:.*]] = llvm.mlir.addressof @kernel_module_the_kernel_kernel_name : !llvm.ptr
24
+ // CHECK: %[[NAME_PTR:.*]] = llvm.getelementptr %[[NAME]][0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.array<11 x i8>
25
+ // CHECK: %[[C7:.*]] = llvm.mlir.constant(7 : i32) : i32
26
+ // CHECK: %[[ARGS:.*]] = llvm.alloca %22 x !llvm.ptr : (i32) -> !llvm.ptr
27
+ // CHECK: llvm.call @_mlir_ciface_tf_launch_kernel(%[[CTX]], %[[BLOB_PTR]], %[[NAME_PTR]], %[[C1]], %[[C1]], %[[C1]], %[[C1]], %[[C1]], %[[C1]], %[[ARGS]])
28
+ %c1 = arith.constant 1 : index
29
+ gpu.launch_func @kernel_module::@the_kernel
30
+ blocks in (%c1, %c1, %c1)
31
+ threads in (%c1, %c1, %c1)
32
+ args(%memref: memref<?x10xf32>)
33
+ func.return
34
+ }
35
+
36
+ }