1 /* Copyright 2019 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_LITE_DELEGATES_GPU_CL_CL_MEMORY_H_ 17 #define TENSORFLOW_LITE_DELEGATES_GPU_CL_CL_MEMORY_H_ 18 19 #include "tensorflow/lite/delegates/gpu/cl/opencl_wrapper.h" 20 #include "tensorflow/lite/delegates/gpu/common/access_type.h" 21 #include "tensorflow/lite/delegates/gpu/common/status.h" 22 23 namespace tflite { 24 namespace gpu { 25 namespace cl { 26 27 // RAII wrapper for OpenCL memory object. 28 // 29 // Image is moveable but not copyable. 30 class CLMemory { 31 public: 32 // Creates invalid object. CLMemory()33 CLMemory() : CLMemory(nullptr, false) {} 34 CLMemory(cl_mem memory,bool has_ownership)35 CLMemory(cl_mem memory, bool has_ownership) 36 : memory_(memory), has_ownership_(has_ownership) {} 37 38 // Move-only 39 CLMemory(const CLMemory&) = delete; 40 CLMemory& operator=(const CLMemory&) = delete; CLMemory(CLMemory && image)41 CLMemory(CLMemory&& image) 42 : memory_(image.memory_), has_ownership_(image.has_ownership_) { 43 image.memory_ = nullptr; 44 } 45 ~CLMemory()46 ~CLMemory() { Invalidate(); } 47 48 CLMemory& operator=(CLMemory&& image) { 49 if (this != &image) { 50 Invalidate(); 51 std::swap(memory_, image.memory_); 52 has_ownership_ = image.has_ownership_; 53 } 54 return *this; 55 } 56 memory()57 cl_mem memory() const { return memory_; } 58 is_valid()59 bool is_valid() const { return memory_ != nullptr; } 60 61 // @return true if this object actually owns corresponding CL memory 62 // and manages it's lifetime. has_ownership()63 bool has_ownership() const { return has_ownership_; } 64 Release()65 cl_mem Release() { 66 cl_mem to_return = memory_; 67 memory_ = nullptr; 68 return to_return; 69 } 70 71 private: Invalidate()72 void Invalidate() { 73 if (memory_ && has_ownership_) { 74 clReleaseMemObject(memory_); 75 } 76 memory_ = nullptr; 77 } 78 79 cl_mem memory_ = nullptr; 80 bool has_ownership_ = false; 81 }; 82 83 cl_mem_flags ToClMemFlags(AccessType access_type); 84 85 } // namespace cl 86 } // namespace gpu 87 } // namespace tflite 88 89 #endif // TENSORFLOW_LITE_DELEGATES_GPU_CL_CL_MEMORY_H_ 90