• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2015 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // ProgramGL.cpp: Implements the class methods for ProgramGL.
8 
9 #include "libANGLE/renderer/gl/ProgramGL.h"
10 
11 #include "common/WorkerThread.h"
12 #include "common/angleutils.h"
13 #include "common/bitset_utils.h"
14 #include "common/debug.h"
15 #include "common/string_utils.h"
16 #include "common/utilities.h"
17 #include "libANGLE/Context.h"
18 #include "libANGLE/ProgramLinkedResources.h"
19 #include "libANGLE/Uniform.h"
20 #include "libANGLE/queryconversions.h"
21 #include "libANGLE/renderer/gl/ContextGL.h"
22 #include "libANGLE/renderer/gl/FunctionsGL.h"
23 #include "libANGLE/renderer/gl/RendererGL.h"
24 #include "libANGLE/renderer/gl/ShaderGL.h"
25 #include "libANGLE/renderer/gl/StateManagerGL.h"
26 #include "libANGLE/trace.h"
27 #include "platform/PlatformMethods.h"
28 #include "platform/autogen/FeaturesGL_autogen.h"
29 
30 namespace rx
31 {
32 namespace
33 {
34 
35 // Returns mapped name of a transform feedback varying. The original name may contain array
36 // brackets with an index inside, which will get copied to the mapped name. The varying must be
37 // known to be declared in the shader.
GetTransformFeedbackVaryingMappedName(const gl::SharedCompiledShaderState & shaderState,const std::string & tfVaryingName)38 std::string GetTransformFeedbackVaryingMappedName(const gl::SharedCompiledShaderState &shaderState,
39                                                   const std::string &tfVaryingName)
40 {
41     ASSERT(shaderState->shaderType != gl::ShaderType::Fragment &&
42            shaderState->shaderType != gl::ShaderType::Compute);
43     const auto &varyings = shaderState->outputVaryings;
44     auto bracketPos      = tfVaryingName.find("[");
45     if (bracketPos != std::string::npos)
46     {
47         auto tfVaryingBaseName = tfVaryingName.substr(0, bracketPos);
48         for (const auto &varying : varyings)
49         {
50             if (varying.name == tfVaryingBaseName)
51             {
52                 std::string mappedNameWithArrayIndex =
53                     varying.mappedName + tfVaryingName.substr(bracketPos);
54                 return mappedNameWithArrayIndex;
55             }
56         }
57     }
58     else
59     {
60         for (const auto &varying : varyings)
61         {
62             if (varying.name == tfVaryingName)
63             {
64                 return varying.mappedName;
65             }
66             else if (varying.isStruct())
67             {
68                 GLuint fieldIndex = 0;
69                 const auto *field = varying.findField(tfVaryingName, &fieldIndex);
70                 if (field == nullptr)
71                 {
72                     continue;
73                 }
74                 ASSERT(field != nullptr && !field->isStruct() &&
75                        (!field->isArray() || varying.isShaderIOBlock));
76                 std::string mappedName;
77                 // If it's an I/O block without an instance name, don't include the block name.
78                 if (!varying.isShaderIOBlock || !varying.name.empty())
79                 {
80                     mappedName = varying.isShaderIOBlock ? varying.mappedStructOrBlockName
81                                                          : varying.mappedName;
82                     mappedName += '.';
83                 }
84                 return mappedName + field->mappedName;
85             }
86         }
87     }
88     UNREACHABLE();
89     return std::string();
90 }
91 
92 }  // anonymous namespace
93 
94 class ProgramGL::LinkTaskGL final : public LinkTask
95 {
96   public:
LinkTaskGL(ProgramGL * program,bool hasNativeParallelCompile,const FunctionsGL * functions,const gl::Extensions & extensions,GLuint programID)97     LinkTaskGL(ProgramGL *program,
98                bool hasNativeParallelCompile,
99                const FunctionsGL *functions,
100                const gl::Extensions &extensions,
101                GLuint programID)
102         : mProgram(program),
103           mHasNativeParallelCompile(hasNativeParallelCompile),
104           mFunctions(functions),
105           mExtensions(extensions),
106           mProgramID(programID)
107     {}
108     ~LinkTaskGL() override = default;
109 
link(const gl::ProgramLinkedResources & resources,const gl::ProgramMergedVaryings & mergedVaryings,std::vector<std::shared_ptr<LinkSubTask>> * linkSubTasksOut,std::vector<std::shared_ptr<LinkSubTask>> * postLinkSubTasksOut)110     void link(const gl::ProgramLinkedResources &resources,
111               const gl::ProgramMergedVaryings &mergedVaryings,
112               std::vector<std::shared_ptr<LinkSubTask>> *linkSubTasksOut,
113               std::vector<std::shared_ptr<LinkSubTask>> *postLinkSubTasksOut) override
114     {
115         ASSERT(linkSubTasksOut && linkSubTasksOut->empty());
116         ASSERT(postLinkSubTasksOut && postLinkSubTasksOut->empty());
117 
118         mProgram->linkJobImpl(mExtensions);
119 
120         // If there is no native parallel compile, do the post-link right away.
121         if (!mHasNativeParallelCompile)
122         {
123             mResult = mProgram->postLinkJobImpl(resources);
124         }
125 
126         // See comment on mResources
127         mResources = &resources;
128         return;
129     }
130 
getResult(const gl::Context * context,gl::InfoLog & infoLog)131     angle::Result getResult(const gl::Context *context, gl::InfoLog &infoLog) override
132     {
133         ANGLE_TRACE_EVENT0("gpu.angle", "LinkTaskGL::getResult");
134 
135         if (mHasNativeParallelCompile)
136         {
137             mResult = mProgram->postLinkJobImpl(*mResources);
138         }
139 
140         return mResult;
141     }
142 
isLinkingInternally()143     bool isLinkingInternally() override
144     {
145         GLint completionStatus = GL_TRUE;
146         if (mHasNativeParallelCompile)
147         {
148             mFunctions->getProgramiv(mProgramID, GL_COMPLETION_STATUS, &completionStatus);
149         }
150         return completionStatus == GL_FALSE;
151     }
152 
153   private:
154     ProgramGL *mProgram;
155     const bool mHasNativeParallelCompile;
156     const FunctionsGL *mFunctions;
157     const gl::Extensions &mExtensions;
158     const GLuint mProgramID;
159 
160     angle::Result mResult = angle::Result::Continue;
161 
162     // Note: resources are kept alive by the front-end for the entire duration of the link,
163     // including during resolve when getResult() and postLink() are called.
164     const gl::ProgramLinkedResources *mResources = nullptr;
165 };
166 
ProgramGL(const gl::ProgramState & data,const FunctionsGL * functions,const angle::FeaturesGL & features,StateManagerGL * stateManager,const std::shared_ptr<RendererGL> & renderer)167 ProgramGL::ProgramGL(const gl::ProgramState &data,
168                      const FunctionsGL *functions,
169                      const angle::FeaturesGL &features,
170                      StateManagerGL *stateManager,
171                      const std::shared_ptr<RendererGL> &renderer)
172     : ProgramImpl(data),
173       mFunctions(functions),
174       mFeatures(features),
175       mStateManager(stateManager),
176       mProgramID(0),
177       mRenderer(renderer)
178 {
179     ASSERT(mFunctions);
180     ASSERT(mStateManager);
181 
182     mProgramID = mFunctions->createProgram();
183 }
184 
185 ProgramGL::~ProgramGL() = default;
186 
destroy(const gl::Context * context)187 void ProgramGL::destroy(const gl::Context *context)
188 {
189     mFunctions->deleteProgram(mProgramID);
190     mProgramID = 0;
191 }
192 
load(const gl::Context * context,gl::BinaryInputStream * stream,std::shared_ptr<LinkTask> * loadTaskOut,egl::CacheGetResult * resultOut)193 angle::Result ProgramGL::load(const gl::Context *context,
194                               gl::BinaryInputStream *stream,
195                               std::shared_ptr<LinkTask> *loadTaskOut,
196                               egl::CacheGetResult *resultOut)
197 {
198     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramGL::load");
199     ProgramExecutableGL *executableGL = getExecutable();
200 
201     // Read the binary format, size and blob
202     GLenum binaryFormat   = stream->readInt<GLenum>();
203     GLint binaryLength    = stream->readInt<GLint>();
204     const uint8_t *binary = stream->data() + stream->offset();
205     stream->skip(binaryLength);
206 
207     // Load the binary
208     mFunctions->programBinary(mProgramID, binaryFormat, binary, binaryLength);
209 
210     // Verify that the program linked.  Ensure failure if program binary is intentionally corrupted,
211     // even if the corruption didn't really cause a failure.
212     if (!checkLinkStatus() ||
213         GetImplAs<ContextGL>(context)->getFeaturesGL().corruptProgramBinaryForTesting.enabled)
214     {
215         return angle::Result::Continue;
216     }
217 
218     executableGL->postLink(mFunctions, mStateManager, mFeatures, mProgramID);
219     executableGL->reapplyUBOBindings();
220 
221     *loadTaskOut = {};
222     *resultOut   = egl::CacheGetResult::Success;
223 
224     return angle::Result::Continue;
225 }
226 
save(const gl::Context * context,gl::BinaryOutputStream * stream)227 void ProgramGL::save(const gl::Context *context, gl::BinaryOutputStream *stream)
228 {
229     GLint binaryLength = 0;
230     mFunctions->getProgramiv(mProgramID, GL_PROGRAM_BINARY_LENGTH, &binaryLength);
231 
232     std::vector<uint8_t> binary(std::max(binaryLength, 1));
233     GLenum binaryFormat = GL_NONE;
234     mFunctions->getProgramBinary(mProgramID, binaryLength, &binaryLength, &binaryFormat,
235                                  binary.data());
236 
237     stream->writeInt(binaryFormat);
238     stream->writeInt(binaryLength);
239 
240     const angle::FeaturesGL &features = GetImplAs<ContextGL>(context)->getFeaturesGL();
241     if (features.corruptProgramBinaryForTesting.enabled)
242     {
243         // Random corruption of the binary data.  Corrupting the first byte has proven to be enough
244         // to later cause the binary load to fail on most platforms.
245         ++binary[0];
246     }
247 
248     stream->writeBytes(binary.data(), binaryLength);
249 
250     // Re-apply UBO bindings to work around driver bugs.
251     if (features.reapplyUBOBindingsAfterUsingBinaryProgram.enabled)
252     {
253         getExecutable()->reapplyUBOBindings();
254     }
255 }
256 
setBinaryRetrievableHint(bool retrievable)257 void ProgramGL::setBinaryRetrievableHint(bool retrievable)
258 {
259     // glProgramParameteri isn't always available on ES backends.
260     if (mFunctions->programParameteri)
261     {
262         mFunctions->programParameteri(mProgramID, GL_PROGRAM_BINARY_RETRIEVABLE_HINT,
263                                       retrievable ? GL_TRUE : GL_FALSE);
264     }
265 }
266 
setSeparable(bool separable)267 void ProgramGL::setSeparable(bool separable)
268 {
269     mFunctions->programParameteri(mProgramID, GL_PROGRAM_SEPARABLE, separable ? GL_TRUE : GL_FALSE);
270 }
271 
prepareForLink(const gl::ShaderMap<ShaderImpl * > & shaders)272 void ProgramGL::prepareForLink(const gl::ShaderMap<ShaderImpl *> &shaders)
273 {
274     for (gl::ShaderType shaderType : gl::AllShaderTypes())
275     {
276         mAttachedShaders[shaderType] = 0;
277 
278         if (shaders[shaderType] != nullptr)
279         {
280             const ShaderGL *shaderGL     = GetAs<ShaderGL>(shaders[shaderType]);
281             mAttachedShaders[shaderType] = shaderGL->getShaderID();
282         }
283     }
284 }
285 
link(const gl::Context * context,std::shared_ptr<LinkTask> * linkTaskOut)286 angle::Result ProgramGL::link(const gl::Context *context, std::shared_ptr<LinkTask> *linkTaskOut)
287 {
288     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramGL::link");
289 
290     *linkTaskOut = std::make_shared<LinkTaskGL>(this, mRenderer->hasNativeParallelCompile(),
291                                                 mFunctions, context->getExtensions(), mProgramID);
292 
293     return angle::Result::Continue;
294 }
295 
linkJobImpl(const gl::Extensions & extensions)296 void ProgramGL::linkJobImpl(const gl::Extensions &extensions)
297 {
298     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramGL::linkJobImpl");
299     const gl::ProgramExecutable &executable = mState.getExecutable();
300     ProgramExecutableGL *executableGL       = getExecutable();
301 
302     if (mAttachedShaders[gl::ShaderType::Compute] != 0)
303     {
304         mFunctions->attachShader(mProgramID, mAttachedShaders[gl::ShaderType::Compute]);
305     }
306     else
307     {
308         // Set the transform feedback state
309         std::vector<std::string> transformFeedbackVaryingMappedNames;
310         const gl::ShaderType tfShaderType =
311             executable.hasLinkedShaderStage(gl::ShaderType::Geometry) ? gl::ShaderType::Geometry
312                                                                       : gl::ShaderType::Vertex;
313         const gl::SharedCompiledShaderState &tfShaderState = mState.getAttachedShader(tfShaderType);
314         for (const auto &tfVarying : mState.getTransformFeedbackVaryingNames())
315         {
316             std::string tfVaryingMappedName =
317                 GetTransformFeedbackVaryingMappedName(tfShaderState, tfVarying);
318             transformFeedbackVaryingMappedNames.push_back(tfVaryingMappedName);
319         }
320 
321         if (transformFeedbackVaryingMappedNames.empty())
322         {
323             // Only clear the transform feedback state if transform feedback varyings have already
324             // been set.
325             if (executableGL->mHasAppliedTransformFeedbackVaryings)
326             {
327                 ASSERT(mFunctions->transformFeedbackVaryings);
328                 mFunctions->transformFeedbackVaryings(mProgramID, 0, nullptr,
329                                                       mState.getTransformFeedbackBufferMode());
330                 executableGL->mHasAppliedTransformFeedbackVaryings = false;
331             }
332         }
333         else
334         {
335             ASSERT(mFunctions->transformFeedbackVaryings);
336             std::vector<const GLchar *> transformFeedbackVaryings;
337             for (const auto &varying : transformFeedbackVaryingMappedNames)
338             {
339                 transformFeedbackVaryings.push_back(varying.c_str());
340             }
341             mFunctions->transformFeedbackVaryings(
342                 mProgramID, static_cast<GLsizei>(transformFeedbackVaryingMappedNames.size()),
343                 &transformFeedbackVaryings[0], mState.getTransformFeedbackBufferMode());
344             executableGL->mHasAppliedTransformFeedbackVaryings = true;
345         }
346 
347         for (const gl::ShaderType shaderType : gl::kAllGraphicsShaderTypes)
348         {
349             if (mAttachedShaders[shaderType] != 0)
350             {
351                 mFunctions->attachShader(mProgramID, mAttachedShaders[shaderType]);
352             }
353         }
354 
355         // Bind attribute locations to match the GL layer.
356         for (const gl::ProgramInput &attribute : executable.getProgramInputs())
357         {
358             if (!attribute.isActive() || attribute.isBuiltIn())
359             {
360                 continue;
361             }
362 
363             mFunctions->bindAttribLocation(mProgramID, attribute.getLocation(),
364                                            attribute.mappedName.c_str());
365         }
366 
367         // Bind the secondary fragment color outputs defined in EXT_blend_func_extended. We only use
368         // the API to bind fragment output locations in case EXT_blend_func_extended is enabled.
369         // Otherwise shader-assigned locations will work.
370         if (extensions.blendFuncExtendedEXT)
371         {
372             const gl::SharedCompiledShaderState &fragmentShader =
373                 mState.getAttachedShader(gl::ShaderType::Fragment);
374             if (fragmentShader && fragmentShader->shaderVersion == 100 &&
375                 mFunctions->standard == STANDARD_GL_DESKTOP)
376             {
377                 const auto &shaderOutputs = fragmentShader->activeOutputVariables;
378                 for (const auto &output : shaderOutputs)
379                 {
380                     // TODO(http://anglebug.com/1085) This could be cleaner if the transformed names
381                     // would be set correctly in ShaderVariable::mappedName. This would require some
382                     // refactoring in the translator. Adding a mapped name dictionary for builtins
383                     // into the symbol table would be one fairly clean way to do it.
384                     if (output.name == "gl_SecondaryFragColorEXT")
385                     {
386                         mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 0,
387                                                                 "webgl_FragColor");
388                         mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 1,
389                                                                 "webgl_SecondaryFragColor");
390                     }
391                     else if (output.name == "gl_SecondaryFragDataEXT")
392                     {
393                         // Basically we should have a loop here going over the output
394                         // array binding "webgl_FragData[i]" and "webgl_SecondaryFragData[i]" array
395                         // indices to the correct color buffers and color indices.
396                         // However I'm not sure if this construct is legal or not, neither ARB or
397                         // EXT version of the spec mention this. They only mention that
398                         // automatically assigned array locations for ESSL 3.00 output arrays need
399                         // to have contiguous locations.
400                         //
401                         // In practice it seems that binding array members works on some drivers and
402                         // fails on others. One option could be to modify the shader translator to
403                         // expand the arrays into individual output variables instead of using an
404                         // array.
405                         //
406                         // For now we're going to have a limitation of assuming that
407                         // GL_MAX_DUAL_SOURCE_DRAW_BUFFERS is *always* 1 and then only bind the
408                         // basename of the variable ignoring any indices. This appears to work
409                         // uniformly.
410                         ASSERT(output.isArray() && output.getOutermostArraySize() == 1);
411 
412                         mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 0, "webgl_FragData");
413                         mFunctions->bindFragDataLocationIndexed(mProgramID, 0, 1,
414                                                                 "webgl_SecondaryFragData");
415                     }
416                 }
417             }
418             else if (fragmentShader && fragmentShader->shaderVersion >= 300)
419             {
420                 // ESSL 3.00 and up.
421                 const auto &outputLocations          = executable.getOutputLocations();
422                 const auto &secondaryOutputLocations = executable.getSecondaryOutputLocations();
423                 for (size_t outputLocationIndex = 0u; outputLocationIndex < outputLocations.size();
424                      ++outputLocationIndex)
425                 {
426                     const gl::VariableLocation &outputLocation =
427                         outputLocations[outputLocationIndex];
428                     if (outputLocation.arrayIndex == 0 && outputLocation.used() &&
429                         !outputLocation.ignored)
430                     {
431                         const gl::ProgramOutput &outputVar =
432                             executable.getOutputVariables()[outputLocation.index];
433                         if (outputVar.pod.location == -1 || outputVar.pod.index == -1)
434                         {
435                             // We only need to assign the location and index via the API in case the
436                             // variable doesn't have a shader-assigned location and index. If a
437                             // variable doesn't have its location set in the shader it doesn't have
438                             // the index set either.
439                             ASSERT(outputVar.pod.index == -1);
440                             mFunctions->bindFragDataLocationIndexed(
441                                 mProgramID, static_cast<int>(outputLocationIndex), 0,
442                                 outputVar.mappedName.c_str());
443                         }
444                     }
445                 }
446                 for (size_t outputLocationIndex = 0u;
447                      outputLocationIndex < secondaryOutputLocations.size(); ++outputLocationIndex)
448                 {
449                     const gl::VariableLocation &outputLocation =
450                         secondaryOutputLocations[outputLocationIndex];
451                     if (outputLocation.arrayIndex == 0 && outputLocation.used() &&
452                         !outputLocation.ignored)
453                     {
454                         const gl::ProgramOutput &outputVar =
455                             executable.getOutputVariables()[outputLocation.index];
456                         if (outputVar.pod.location == -1 || outputVar.pod.index == -1)
457                         {
458                             // We only need to assign the location and index via the API in case the
459                             // variable doesn't have a shader-assigned location and index.  If a
460                             // variable doesn't have its location set in the shader it doesn't have
461                             // the index set either.
462                             ASSERT(outputVar.pod.index == -1);
463                             mFunctions->bindFragDataLocationIndexed(
464                                 mProgramID, static_cast<int>(outputLocationIndex), 1,
465                                 outputVar.mappedName.c_str());
466                         }
467                     }
468                 }
469             }
470         }
471     }
472 
473     mFunctions->linkProgram(mProgramID);
474 }
475 
postLinkJobImpl(const gl::ProgramLinkedResources & resources)476 angle::Result ProgramGL::postLinkJobImpl(const gl::ProgramLinkedResources &resources)
477 {
478     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramGL::postLinkJobImpl");
479 
480     if (mAttachedShaders[gl::ShaderType::Compute] != 0)
481     {
482         mFunctions->detachShader(mProgramID, mAttachedShaders[gl::ShaderType::Compute]);
483     }
484     else
485     {
486         for (const gl::ShaderType shaderType : gl::kAllGraphicsShaderTypes)
487         {
488             if (mAttachedShaders[shaderType] != 0)
489             {
490                 mFunctions->detachShader(mProgramID, mAttachedShaders[shaderType]);
491             }
492         }
493     }
494 
495     // Verify the link
496     if (!checkLinkStatus())
497     {
498         return angle::Result::Stop;
499     }
500 
501     if (mFeatures.alwaysCallUseProgramAfterLink.enabled)
502     {
503         mStateManager->forceUseProgram(mProgramID);
504     }
505 
506     linkResources(resources);
507     getExecutable()->postLink(mFunctions, mStateManager, mFeatures, mProgramID);
508 
509     return angle::Result::Continue;
510 }
511 
validate(const gl::Caps &)512 GLboolean ProgramGL::validate(const gl::Caps & /*caps*/)
513 {
514     // TODO(jmadill): implement validate
515     return true;
516 }
517 
getUniformBlockSize(const std::string &,const std::string & blockMappedName,size_t * sizeOut) const518 bool ProgramGL::getUniformBlockSize(const std::string & /* blockName */,
519                                     const std::string &blockMappedName,
520                                     size_t *sizeOut) const
521 {
522     ASSERT(mProgramID != 0u);
523 
524     GLuint blockIndex = mFunctions->getUniformBlockIndex(mProgramID, blockMappedName.c_str());
525     if (blockIndex == GL_INVALID_INDEX)
526     {
527         *sizeOut = 0;
528         return false;
529     }
530 
531     GLint dataSize = 0;
532     mFunctions->getActiveUniformBlockiv(mProgramID, blockIndex, GL_UNIFORM_BLOCK_DATA_SIZE,
533                                         &dataSize);
534     *sizeOut = static_cast<size_t>(dataSize);
535     return true;
536 }
537 
getUniformBlockMemberInfo(const std::string &,const std::string & memberUniformMappedName,sh::BlockMemberInfo * memberInfoOut) const538 bool ProgramGL::getUniformBlockMemberInfo(const std::string & /* memberUniformName */,
539                                           const std::string &memberUniformMappedName,
540                                           sh::BlockMemberInfo *memberInfoOut) const
541 {
542     GLuint uniformIndex;
543     const GLchar *memberNameGLStr = memberUniformMappedName.c_str();
544     mFunctions->getUniformIndices(mProgramID, 1, &memberNameGLStr, &uniformIndex);
545 
546     if (uniformIndex == GL_INVALID_INDEX)
547     {
548         *memberInfoOut = sh::kDefaultBlockMemberInfo;
549         return false;
550     }
551 
552     mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_OFFSET,
553                                     &memberInfoOut->offset);
554     mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_ARRAY_STRIDE,
555                                     &memberInfoOut->arrayStride);
556     mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_MATRIX_STRIDE,
557                                     &memberInfoOut->matrixStride);
558 
559     // TODO(jmadill): possibly determine this at the gl::Program level.
560     GLint isRowMajorMatrix = 0;
561     mFunctions->getActiveUniformsiv(mProgramID, 1, &uniformIndex, GL_UNIFORM_IS_ROW_MAJOR,
562                                     &isRowMajorMatrix);
563     memberInfoOut->isRowMajorMatrix = gl::ConvertToBool(isRowMajorMatrix);
564     return true;
565 }
566 
getShaderStorageBlockMemberInfo(const std::string &,const std::string & memberUniformMappedName,sh::BlockMemberInfo * memberInfoOut) const567 bool ProgramGL::getShaderStorageBlockMemberInfo(const std::string & /* memberName */,
568                                                 const std::string &memberUniformMappedName,
569                                                 sh::BlockMemberInfo *memberInfoOut) const
570 {
571     const GLchar *memberNameGLStr = memberUniformMappedName.c_str();
572     GLuint index =
573         mFunctions->getProgramResourceIndex(mProgramID, GL_BUFFER_VARIABLE, memberNameGLStr);
574 
575     if (index == GL_INVALID_INDEX)
576     {
577         *memberInfoOut = sh::kDefaultBlockMemberInfo;
578         return false;
579     }
580 
581     constexpr int kPropCount             = 5;
582     std::array<GLenum, kPropCount> props = {
583         {GL_ARRAY_STRIDE, GL_IS_ROW_MAJOR, GL_MATRIX_STRIDE, GL_OFFSET, GL_TOP_LEVEL_ARRAY_STRIDE}};
584     std::array<GLint, kPropCount> params;
585     GLsizei length;
586     mFunctions->getProgramResourceiv(mProgramID, GL_BUFFER_VARIABLE, index, kPropCount,
587                                      props.data(), kPropCount, &length, params.data());
588     ASSERT(kPropCount == length);
589     memberInfoOut->arrayStride         = params[0];
590     memberInfoOut->isRowMajorMatrix    = params[1] != 0;
591     memberInfoOut->matrixStride        = params[2];
592     memberInfoOut->offset              = params[3];
593     memberInfoOut->topLevelArrayStride = params[4];
594 
595     return true;
596 }
597 
getShaderStorageBlockSize(const std::string & name,const std::string & mappedName,size_t * sizeOut) const598 bool ProgramGL::getShaderStorageBlockSize(const std::string &name,
599                                           const std::string &mappedName,
600                                           size_t *sizeOut) const
601 {
602     const GLchar *nameGLStr = mappedName.c_str();
603     GLuint index =
604         mFunctions->getProgramResourceIndex(mProgramID, GL_SHADER_STORAGE_BLOCK, nameGLStr);
605 
606     if (index == GL_INVALID_INDEX)
607     {
608         *sizeOut = 0;
609         return false;
610     }
611 
612     GLenum prop    = GL_BUFFER_DATA_SIZE;
613     GLsizei length = 0;
614     GLint dataSize = 0;
615     mFunctions->getProgramResourceiv(mProgramID, GL_SHADER_STORAGE_BLOCK, index, 1, &prop, 1,
616                                      &length, &dataSize);
617     *sizeOut = static_cast<size_t>(dataSize);
618     return true;
619 }
620 
getAtomicCounterBufferSizeMap(std::map<int,unsigned int> * sizeMapOut) const621 void ProgramGL::getAtomicCounterBufferSizeMap(std::map<int, unsigned int> *sizeMapOut) const
622 {
623     if (mFunctions->getProgramInterfaceiv == nullptr)
624     {
625         return;
626     }
627 
628     int resourceCount = 0;
629     mFunctions->getProgramInterfaceiv(mProgramID, GL_ATOMIC_COUNTER_BUFFER, GL_ACTIVE_RESOURCES,
630                                       &resourceCount);
631 
632     for (int index = 0; index < resourceCount; index++)
633     {
634         constexpr int kPropCount             = 2;
635         std::array<GLenum, kPropCount> props = {{GL_BUFFER_BINDING, GL_BUFFER_DATA_SIZE}};
636         std::array<GLint, kPropCount> params;
637         GLsizei length;
638         mFunctions->getProgramResourceiv(mProgramID, GL_ATOMIC_COUNTER_BUFFER, index, kPropCount,
639                                          props.data(), kPropCount, &length, params.data());
640         ASSERT(kPropCount == length);
641         int bufferBinding           = params[0];
642         unsigned int bufferDataSize = params[1];
643         sizeMapOut->insert(std::pair<int, unsigned int>(bufferBinding, bufferDataSize));
644     }
645 }
646 
checkLinkStatus()647 bool ProgramGL::checkLinkStatus()
648 {
649     GLint linkStatus = GL_FALSE;
650     mFunctions->getProgramiv(mProgramID, GL_LINK_STATUS, &linkStatus);
651     if (linkStatus == GL_FALSE)
652     {
653         // Linking or program binary loading failed, put the error into the info log.
654         GLint infoLogLength = 0;
655         mFunctions->getProgramiv(mProgramID, GL_INFO_LOG_LENGTH, &infoLogLength);
656 
657         // Info log length includes the null terminator, so 1 means that the info log is an empty
658         // string.
659         if (infoLogLength > 1)
660         {
661             std::vector<char> buf(infoLogLength);
662             mFunctions->getProgramInfoLog(mProgramID, infoLogLength, nullptr, &buf[0]);
663 
664             mState.getExecutable().getInfoLog() << buf.data();
665 
666             WARN() << "Program link or binary loading failed: " << buf.data();
667         }
668         else
669         {
670             WARN() << "Program link or binary loading failed with no info log.";
671         }
672 
673         // This may happen under normal circumstances if we're loading program binaries and the
674         // driver or hardware has changed.
675         ASSERT(mProgramID != 0);
676         return false;
677     }
678 
679     return true;
680 }
681 
markUnusedUniformLocations(std::vector<gl::VariableLocation> * uniformLocations,std::vector<gl::SamplerBinding> * samplerBindings,std::vector<gl::ImageBinding> * imageBindings)682 void ProgramGL::markUnusedUniformLocations(std::vector<gl::VariableLocation> *uniformLocations,
683                                            std::vector<gl::SamplerBinding> *samplerBindings,
684                                            std::vector<gl::ImageBinding> *imageBindings)
685 {
686     const gl::ProgramExecutable &executable = mState.getExecutable();
687     const ProgramExecutableGL *executableGL = getExecutable();
688 
689     GLint maxLocation = static_cast<GLint>(uniformLocations->size());
690     for (GLint location = 0; location < maxLocation; ++location)
691     {
692         if (executableGL->mUniformRealLocationMap[location] == -1)
693         {
694             auto &locationRef = (*uniformLocations)[location];
695             if (executable.isSamplerUniformIndex(locationRef.index))
696             {
697                 GLuint samplerIndex = executable.getSamplerIndexFromUniformIndex(locationRef.index);
698                 gl::SamplerBinding &samplerBinding = (*samplerBindings)[samplerIndex];
699                 if (locationRef.arrayIndex <
700                     static_cast<unsigned int>(samplerBinding.textureUnitsCount))
701                 {
702                     // Crop unused sampler bindings in the sampler array.
703                     SetBitField(samplerBinding.textureUnitsCount, locationRef.arrayIndex);
704                 }
705             }
706             else if (executable.isImageUniformIndex(locationRef.index))
707             {
708                 GLuint imageIndex = executable.getImageIndexFromUniformIndex(locationRef.index);
709                 gl::ImageBinding &imageBinding = (*imageBindings)[imageIndex];
710                 if (locationRef.arrayIndex < imageBinding.boundImageUnits.size())
711                 {
712                     // Crop unused image bindings in the image array.
713                     imageBinding.boundImageUnits.resize(locationRef.arrayIndex);
714                 }
715             }
716             // If the location has been previously bound by a glBindUniformLocation call, it should
717             // be marked as ignored. Otherwise it's unused.
718             if (mState.getUniformLocationBindings().getBindingByLocation(location) != -1)
719             {
720                 locationRef.markIgnored();
721             }
722             else
723             {
724                 locationRef.markUnused();
725             }
726         }
727     }
728 }
729 
linkResources(const gl::ProgramLinkedResources & resources)730 void ProgramGL::linkResources(const gl::ProgramLinkedResources &resources)
731 {
732     // Gather interface block info.
733     auto getUniformBlockSize = [this](const std::string &name, const std::string &mappedName,
734                                       size_t *sizeOut) {
735         return this->getUniformBlockSize(name, mappedName, sizeOut);
736     };
737 
738     auto getUniformBlockMemberInfo = [this](const std::string &name, const std::string &mappedName,
739                                             sh::BlockMemberInfo *infoOut) {
740         return this->getUniformBlockMemberInfo(name, mappedName, infoOut);
741     };
742 
743     resources.uniformBlockLinker.linkBlocks(getUniformBlockSize, getUniformBlockMemberInfo);
744 
745     auto getShaderStorageBlockSize = [this](const std::string &name, const std::string &mappedName,
746                                             size_t *sizeOut) {
747         return this->getShaderStorageBlockSize(name, mappedName, sizeOut);
748     };
749 
750     auto getShaderStorageBlockMemberInfo = [this](const std::string &name,
751                                                   const std::string &mappedName,
752                                                   sh::BlockMemberInfo *infoOut) {
753         return this->getShaderStorageBlockMemberInfo(name, mappedName, infoOut);
754     };
755     resources.shaderStorageBlockLinker.linkBlocks(getShaderStorageBlockSize,
756                                                   getShaderStorageBlockMemberInfo);
757 
758     // Gather atomic counter buffer info.
759     std::map<int, unsigned int> sizeMap;
760     getAtomicCounterBufferSizeMap(&sizeMap);
761     resources.atomicCounterBufferLinker.link(sizeMap);
762 }
763 
onUniformBlockBinding(gl::UniformBlockIndex uniformBlockIndex)764 void ProgramGL::onUniformBlockBinding(gl::UniformBlockIndex uniformBlockIndex)
765 {
766     getExecutable()->mDirtyUniformBlockBindings.set(uniformBlockIndex.value);
767 }
768 }  // namespace rx
769