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 #include "tensorflow/lite/delegates/gpu/gl/gl_shader.h"
17
18 #include "tensorflow/lite/delegates/gpu/common/status.h"
19 #include "tensorflow/lite/delegates/gpu/gl/gl_call.h"
20 #include "tensorflow/lite/delegates/gpu/gl/gl_errors.h"
21
22 namespace tflite {
23 namespace gpu {
24 namespace gl {
25
GlShader(GlShader && shader)26 GlShader::GlShader(GlShader&& shader) : id_(shader.id_) { shader.id_ = 0; }
27
Invalidate()28 void GlShader::Invalidate() {
29 if (id_) {
30 glDeleteShader(id_);
31 id_ = 0;
32 }
33 }
34
operator =(GlShader && shader)35 GlShader& GlShader::operator=(GlShader&& shader) {
36 if (this != &shader) {
37 Invalidate();
38 std::swap(id_, shader.id_);
39 }
40 return *this;
41 }
42
~GlShader()43 GlShader::~GlShader() { Invalidate(); }
44
CompileShader(GLenum shader_type,const std::string & shader_source,GlShader * gl_shader)45 absl::Status GlShader::CompileShader(GLenum shader_type,
46 const std::string& shader_source,
47 GlShader* gl_shader) {
48 // NOTE: code compilation can fail due to gl errors happened before
49 GLuint shader_id;
50 RETURN_IF_ERROR(TFLITE_GPU_CALL_GL(glCreateShader, &shader_id, shader_type));
51 GlShader shader(shader_id);
52
53 const char* src = shader_source.c_str();
54 RETURN_IF_ERROR(
55 TFLITE_GPU_CALL_GL(glShaderSource, shader.id(), 1, &src, nullptr));
56
57 glCompileShader(shader.id());
58
59 #ifndef __EMSCRIPTEN__
60 // This check is not recommended on WebGL, since it will force a wait on the
61 // GPU process.
62 // Didn't check for opengl errors here because we want to get better logs
63 // if it didn't compile.
64 GLint compiled = GL_FALSE;
65 glGetShaderiv(shader.id(), GL_COMPILE_STATUS, &compiled);
66 if (!compiled) {
67 GLint info_log_len = 0;
68 glGetShaderiv(shader.id(), GL_INFO_LOG_LENGTH, &info_log_len);
69 std::string errors(info_log_len, 0);
70 glGetShaderInfoLog(shader.id(), info_log_len, nullptr, &errors[0]);
71 return absl::InternalError("Shader compilation failed: " + errors +
72 "\nProblem shader is:\n" + shader_source);
73 }
74 #endif // !__EMSCRIPTEN__
75
76 *gl_shader = std::move(shader);
77 return absl::OkStatus();
78 }
79
80 } // namespace gl
81 } // namespace gpu
82 } // namespace tflite
83