1 /* Copyright 2018 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_XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ 17 #define TENSORFLOW_COMPILER_XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ 18 19 #include <utility> 20 #include <variant> 21 22 #include "tensorflow/compiler/xla/stream_executor/device_memory.h" 23 24 namespace stream_executor { 25 26 // Allows to represent a value that is either a host scalar or a scalar stored 27 // on the device. 28 template <typename T> 29 class HostOrDeviceScalar { 30 public: HostOrDeviceScalar(T host_value)31 explicit HostOrDeviceScalar(T host_value) : value_(std::move(host_value)) {} HostOrDeviceScalar(DeviceMemory<T> device_ptr)32 explicit HostOrDeviceScalar(DeviceMemory<T> device_ptr) 33 : value_(std::move(device_ptr)) { 34 CHECK_EQ(1, device_ptr.ElementCount()); 35 } 36 on_device()37 bool on_device() const { 38 return std::holds_alternative<DeviceMemory<T>>(value_); 39 } 40 opaque()41 const void* opaque() const { 42 return on_device() ? std::get<DeviceMemory<T>>(value_).opaque() 43 : &std::get<T>(value_); 44 } 45 46 private: 47 std::variant<T, DeviceMemory<T>> value_; 48 }; 49 50 } // namespace stream_executor 51 52 #endif // TENSORFLOW_COMPILER_XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ 53