1 /*
2  * Copyright © 2011 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23 
24 /**
25  * \file shader_query.cpp
26  * C-to-C++ bridge functions to query GLSL shader data
27  *
28  * \author Ian Romanick <ian.d.romanick@intel.com>
29  */
30 
31 #include "main/context.h"
32 #include "main/enums.h"
33 #include "main/shaderapi.h"
34 #include "main/shaderobj.h"
35 #include "main/uniforms.h"
36 #include "compiler/glsl/glsl_symbol_table.h"
37 #include "compiler/glsl/ir.h"
38 #include "compiler/glsl/program.h"
39 #include "compiler/glsl/string_to_uint_map.h"
40 #include "util/mesa-sha1.h"
41 
42 static GLint
43 program_resource_location(struct gl_program_resource *res,
44                           unsigned array_index);
45 
46 /**
47  * Declare convenience functions to return resource data in a given type.
48  * Warning! this is not type safe so be *very* careful when using these.
49  */
50 #define DECL_RESOURCE_FUNC(name, type) \
51 const type * RESOURCE_ ## name (gl_program_resource *res) { \
52    assert(res->Data); \
53    return (type *) res->Data; \
54 }
55 
56 DECL_RESOURCE_FUNC(VAR, gl_shader_variable);
57 DECL_RESOURCE_FUNC(UBO, gl_uniform_block);
58 DECL_RESOURCE_FUNC(UNI, gl_uniform_storage);
59 DECL_RESOURCE_FUNC(ATC, gl_active_atomic_buffer);
60 DECL_RESOURCE_FUNC(XFV, gl_transform_feedback_varying_info);
61 DECL_RESOURCE_FUNC(XFB, gl_transform_feedback_buffer);
62 DECL_RESOURCE_FUNC(SUB, gl_subroutine_function);
63 
64 static GLenum
mediump_to_highp_type(GLenum type)65 mediump_to_highp_type(GLenum type)
66 {
67    switch (type) {
68    case GL_FLOAT16_NV:
69       return GL_FLOAT;
70    case GL_FLOAT16_VEC2_NV:
71       return GL_FLOAT_VEC2;
72    case GL_FLOAT16_VEC3_NV:
73       return GL_FLOAT_VEC3;
74    case GL_FLOAT16_VEC4_NV:
75       return GL_FLOAT_VEC4;
76    case GL_FLOAT16_MAT2_AMD:
77       return GL_FLOAT_MAT2;
78    case GL_FLOAT16_MAT3_AMD:
79       return GL_FLOAT_MAT3;
80    case GL_FLOAT16_MAT4_AMD:
81       return GL_FLOAT_MAT4;
82    case GL_FLOAT16_MAT2x3_AMD:
83       return GL_FLOAT_MAT2x3;
84    case GL_FLOAT16_MAT2x4_AMD:
85       return GL_FLOAT_MAT2x4;
86    case GL_FLOAT16_MAT3x2_AMD:
87       return GL_FLOAT_MAT3x2;
88    case GL_FLOAT16_MAT3x4_AMD:
89       return GL_FLOAT_MAT3x4;
90    case GL_FLOAT16_MAT4x2_AMD:
91       return GL_FLOAT_MAT4x2;
92    case GL_FLOAT16_MAT4x3_AMD:
93       return GL_FLOAT_MAT4x3;
94    default:
95       return type;
96    }
97 }
98 
99 static void
bind_attrib_location(struct gl_context * ctx,struct gl_shader_program * const shProg,GLuint index,const GLchar * name,bool no_error)100 bind_attrib_location(struct gl_context *ctx,
101                      struct gl_shader_program *const shProg, GLuint index,
102                      const GLchar *name, bool no_error)
103 {
104    if (!name)
105       return;
106 
107    if (!no_error) {
108       if (strncmp(name, "gl_", 3) == 0) {
109          _mesa_error(ctx, GL_INVALID_OPERATION,
110                      "glBindAttribLocation(illegal name)");
111          return;
112       }
113 
114       if (index >= ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs) {
115          _mesa_error(ctx, GL_INVALID_VALUE, "glBindAttribLocation(%u >= %u)",
116                      index, ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs);
117          return;
118       }
119    }
120 
121    /* Replace the current value if it's already in the list.  Add
122     * VERT_ATTRIB_GENERIC0 because that's how the linker differentiates
123     * between built-in attributes and user-defined attributes.
124     */
125    shProg->AttributeBindings->put(index + VERT_ATTRIB_GENERIC0, name);
126 
127    /*
128     * Note that this attribute binding won't go into effect until
129     * glLinkProgram is called again.
130     */
131 }
132 
133 void GLAPIENTRY
_mesa_BindAttribLocation_no_error(GLuint program,GLuint index,const GLchar * name)134 _mesa_BindAttribLocation_no_error(GLuint program, GLuint index,
135                                   const GLchar *name)
136 {
137    GET_CURRENT_CONTEXT(ctx);
138 
139    struct gl_shader_program *const shProg =
140       _mesa_lookup_shader_program(ctx, program);
141    bind_attrib_location(ctx, shProg, index, name, true);
142 }
143 
144 void GLAPIENTRY
_mesa_BindAttribLocation(GLuint program,GLuint index,const GLchar * name)145 _mesa_BindAttribLocation(GLuint program, GLuint index,
146                          const GLchar *name)
147 {
148    GET_CURRENT_CONTEXT(ctx);
149 
150    struct gl_shader_program *const shProg =
151       _mesa_lookup_shader_program_err(ctx, program, "glBindAttribLocation");
152    if (!shProg)
153       return;
154 
155    bind_attrib_location(ctx, shProg, index, name, false);
156 }
157 
158 void GLAPIENTRY
_mesa_GetActiveAttrib(GLuint program,GLuint desired_index,GLsizei maxLength,GLsizei * length,GLint * size,GLenum * type,GLchar * name)159 _mesa_GetActiveAttrib(GLuint program, GLuint desired_index,
160                       GLsizei maxLength, GLsizei * length, GLint * size,
161                       GLenum * type, GLchar * name)
162 {
163    GET_CURRENT_CONTEXT(ctx);
164    struct gl_shader_program *shProg;
165 
166    if (maxLength < 0) {
167       _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveAttrib(maxLength < 0)");
168       return;
169    }
170 
171    shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveAttrib");
172    if (!shProg)
173       return;
174 
175    if (!shProg->data->LinkStatus) {
176       _mesa_error(ctx, GL_INVALID_VALUE,
177                   "glGetActiveAttrib(program not linked)");
178       return;
179    }
180 
181    if (shProg->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
182       _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveAttrib(no vertex shader)");
183       return;
184    }
185 
186    struct gl_program_resource *res =
187       _mesa_program_resource_find_index(shProg, GL_PROGRAM_INPUT,
188                                         desired_index);
189 
190    /* User asked for index that does not exist. */
191    if (!res) {
192       _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveAttrib(index)");
193       return;
194    }
195 
196    const gl_shader_variable *const var = RESOURCE_VAR(res);
197 
198    const char *var_name = var->name;
199 
200    _mesa_copy_string(name, maxLength, length, var_name);
201 
202    if (size)
203       _mesa_program_resource_prop(shProg, res, desired_index, GL_ARRAY_SIZE,
204                                   size, false, "glGetActiveAttrib");
205 
206    if (type)
207       _mesa_program_resource_prop(shProg, res, desired_index, GL_TYPE,
208                                   (GLint *) type, false, "glGetActiveAttrib");
209 }
210 
211 GLint GLAPIENTRY
_mesa_GetAttribLocation(GLuint program,const GLchar * name)212 _mesa_GetAttribLocation(GLuint program, const GLchar * name)
213 {
214    GET_CURRENT_CONTEXT(ctx);
215    struct gl_shader_program *const shProg =
216       _mesa_lookup_shader_program_err(ctx, program, "glGetAttribLocation");
217 
218    if (!shProg) {
219       return -1;
220    }
221 
222    if (!shProg->data->LinkStatus) {
223       _mesa_error(ctx, GL_INVALID_OPERATION,
224                   "glGetAttribLocation(program not linked)");
225       return -1;
226    }
227 
228    if (!name)
229       return -1;
230 
231    /* Not having a vertex shader is not an error.
232     */
233    if (shProg->_LinkedShaders[MESA_SHADER_VERTEX] == NULL)
234       return -1;
235 
236    unsigned array_index = 0;
237    struct gl_program_resource *res =
238       _mesa_program_resource_find_name(shProg, GL_PROGRAM_INPUT, name,
239                                        &array_index);
240 
241    if (!res)
242       return -1;
243 
244    return program_resource_location(res, array_index);
245 }
246 
247 unsigned
_mesa_count_active_attribs(struct gl_shader_program * shProg)248 _mesa_count_active_attribs(struct gl_shader_program *shProg)
249 {
250    if (!shProg->data->LinkStatus
251        || shProg->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
252       return 0;
253    }
254 
255    struct gl_program_resource *res = shProg->data->ProgramResourceList;
256    unsigned count = 0;
257    for (unsigned j = 0; j < shProg->data->NumProgramResourceList;
258         j++, res++) {
259       if (res->Type == GL_PROGRAM_INPUT &&
260           res->StageReferences & (1 << MESA_SHADER_VERTEX))
261          count++;
262    }
263    return count;
264 }
265 
266 
267 size_t
_mesa_longest_attribute_name_length(struct gl_shader_program * shProg)268 _mesa_longest_attribute_name_length(struct gl_shader_program *shProg)
269 {
270    if (!shProg->data->LinkStatus
271        || shProg->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
272       return 0;
273    }
274 
275    struct gl_program_resource *res = shProg->data->ProgramResourceList;
276    size_t longest = 0;
277    for (unsigned j = 0; j < shProg->data->NumProgramResourceList;
278         j++, res++) {
279       if (res->Type == GL_PROGRAM_INPUT &&
280           res->StageReferences & (1 << MESA_SHADER_VERTEX)) {
281 
282          /* From the ARB_gl_spirv spec:
283           *
284           *   "If pname is ACTIVE_ATTRIBUTE_MAX_LENGTH, the length of the
285           *    longest active attribute name, including a null terminator, is
286           *    returned.  If no active attributes exist, zero is returned. If
287           *    no name reflection information is available, one is returned."
288           */
289          const size_t length = RESOURCE_VAR(res)->name != NULL ?
290             strlen(RESOURCE_VAR(res)->name) : 0;
291 
292          if (length >= longest)
293             longest = length + 1;
294       }
295    }
296 
297    return longest;
298 }
299 
300 void static
bind_frag_data_location(struct gl_shader_program * const shProg,const char * name,unsigned colorNumber,unsigned index)301 bind_frag_data_location(struct gl_shader_program *const shProg,
302                         const char *name, unsigned colorNumber,
303                         unsigned index)
304 {
305    /* Replace the current value if it's already in the list.  Add
306     * FRAG_RESULT_DATA0 because that's how the linker differentiates
307     * between built-in attributes and user-defined attributes.
308     */
309    shProg->FragDataBindings->put(colorNumber + FRAG_RESULT_DATA0, name);
310    shProg->FragDataIndexBindings->put(index, name);
311 
312    /*
313     * Note that this binding won't go into effect until
314     * glLinkProgram is called again.
315     */
316 }
317 
318 void GLAPIENTRY
_mesa_BindFragDataLocation(GLuint program,GLuint colorNumber,const GLchar * name)319 _mesa_BindFragDataLocation(GLuint program, GLuint colorNumber,
320 			   const GLchar *name)
321 {
322    _mesa_BindFragDataLocationIndexed(program, colorNumber, 0, name);
323 }
324 
325 void GLAPIENTRY
_mesa_BindFragDataLocation_no_error(GLuint program,GLuint colorNumber,const GLchar * name)326 _mesa_BindFragDataLocation_no_error(GLuint program, GLuint colorNumber,
327                                     const GLchar *name)
328 {
329    GET_CURRENT_CONTEXT(ctx);
330 
331    if (!name)
332       return;
333 
334    struct gl_shader_program *const shProg =
335       _mesa_lookup_shader_program(ctx, program);
336 
337    bind_frag_data_location(shProg, name, colorNumber, 0);
338 }
339 
340 void GLAPIENTRY
_mesa_BindFragDataLocationIndexed(GLuint program,GLuint colorNumber,GLuint index,const GLchar * name)341 _mesa_BindFragDataLocationIndexed(GLuint program, GLuint colorNumber,
342                                   GLuint index, const GLchar *name)
343 {
344    GET_CURRENT_CONTEXT(ctx);
345 
346    struct gl_shader_program *const shProg =
347       _mesa_lookup_shader_program_err(ctx, program, "glBindFragDataLocationIndexed");
348    if (!shProg)
349       return;
350 
351    if (!name)
352       return;
353 
354    if (strncmp(name, "gl_", 3) == 0) {
355       _mesa_error(ctx, GL_INVALID_OPERATION, "glBindFragDataLocationIndexed(illegal name)");
356       return;
357    }
358 
359    if (index > 1) {
360       _mesa_error(ctx, GL_INVALID_VALUE, "glBindFragDataLocationIndexed(index)");
361       return;
362    }
363 
364    if (index == 0 && colorNumber >= ctx->Const.MaxDrawBuffers) {
365       _mesa_error(ctx, GL_INVALID_VALUE, "glBindFragDataLocationIndexed(colorNumber)");
366       return;
367    }
368 
369    if (index == 1 && colorNumber >= ctx->Const.MaxDualSourceDrawBuffers) {
370       _mesa_error(ctx, GL_INVALID_VALUE, "glBindFragDataLocationIndexed(colorNumber)");
371       return;
372    }
373 
374    bind_frag_data_location(shProg, name, colorNumber, index);
375 }
376 
377 void GLAPIENTRY
_mesa_BindFragDataLocationIndexed_no_error(GLuint program,GLuint colorNumber,GLuint index,const GLchar * name)378 _mesa_BindFragDataLocationIndexed_no_error(GLuint program, GLuint colorNumber,
379                                            GLuint index, const GLchar *name)
380 {
381    GET_CURRENT_CONTEXT(ctx);
382 
383    if (!name)
384       return;
385 
386    struct gl_shader_program *const shProg =
387       _mesa_lookup_shader_program(ctx, program);
388 
389    bind_frag_data_location(shProg, name, colorNumber, index);
390 }
391 
392 GLint GLAPIENTRY
_mesa_GetFragDataIndex(GLuint program,const GLchar * name)393 _mesa_GetFragDataIndex(GLuint program, const GLchar *name)
394 {
395    GET_CURRENT_CONTEXT(ctx);
396    struct gl_shader_program *const shProg =
397       _mesa_lookup_shader_program_err(ctx, program, "glGetFragDataIndex");
398 
399    if (!shProg) {
400       return -1;
401    }
402 
403    if (!shProg->data->LinkStatus) {
404       _mesa_error(ctx, GL_INVALID_OPERATION,
405                   "glGetFragDataIndex(program not linked)");
406       return -1;
407    }
408 
409    if (!name)
410       return -1;
411 
412    /* Not having a fragment shader is not an error.
413     */
414    if (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL)
415       return -1;
416 
417    return _mesa_program_resource_location_index(shProg, GL_PROGRAM_OUTPUT,
418                                                 name);
419 }
420 
421 GLint GLAPIENTRY
_mesa_GetFragDataLocation(GLuint program,const GLchar * name)422 _mesa_GetFragDataLocation(GLuint program, const GLchar *name)
423 {
424    GET_CURRENT_CONTEXT(ctx);
425    struct gl_shader_program *const shProg =
426       _mesa_lookup_shader_program_err(ctx, program, "glGetFragDataLocation");
427 
428    if (!shProg) {
429       return -1;
430    }
431 
432    if (!shProg->data->LinkStatus) {
433       _mesa_error(ctx, GL_INVALID_OPERATION,
434                   "glGetFragDataLocation(program not linked)");
435       return -1;
436    }
437 
438    if (!name)
439       return -1;
440 
441    /* Not having a fragment shader is not an error.
442     */
443    if (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL)
444       return -1;
445 
446    unsigned array_index = 0;
447    struct gl_program_resource *res =
448       _mesa_program_resource_find_name(shProg, GL_PROGRAM_OUTPUT, name,
449                                        &array_index);
450 
451    if (!res)
452       return -1;
453 
454    return program_resource_location(res, array_index);
455 }
456 
457 const char*
_mesa_program_resource_name(struct gl_program_resource * res)458 _mesa_program_resource_name(struct gl_program_resource *res)
459 {
460    switch (res->Type) {
461    case GL_UNIFORM_BLOCK:
462    case GL_SHADER_STORAGE_BLOCK:
463       return RESOURCE_UBO(res)->Name;
464    case GL_TRANSFORM_FEEDBACK_VARYING:
465       return RESOURCE_XFV(res)->Name;
466    case GL_PROGRAM_INPUT:
467    case GL_PROGRAM_OUTPUT:
468       return RESOURCE_VAR(res)->name;
469    case GL_UNIFORM:
470    case GL_BUFFER_VARIABLE:
471       return RESOURCE_UNI(res)->name;
472    case GL_VERTEX_SUBROUTINE_UNIFORM:
473    case GL_GEOMETRY_SUBROUTINE_UNIFORM:
474    case GL_FRAGMENT_SUBROUTINE_UNIFORM:
475    case GL_COMPUTE_SUBROUTINE_UNIFORM:
476    case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
477    case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM:
478       return RESOURCE_UNI(res)->name + MESA_SUBROUTINE_PREFIX_LEN;
479    case GL_VERTEX_SUBROUTINE:
480    case GL_GEOMETRY_SUBROUTINE:
481    case GL_FRAGMENT_SUBROUTINE:
482    case GL_COMPUTE_SUBROUTINE:
483    case GL_TESS_CONTROL_SUBROUTINE:
484    case GL_TESS_EVALUATION_SUBROUTINE:
485       return RESOURCE_SUB(res)->name;
486    default:
487       break;
488    }
489    return NULL;
490 }
491 
492 
493 unsigned
_mesa_program_resource_array_size(struct gl_program_resource * res)494 _mesa_program_resource_array_size(struct gl_program_resource *res)
495 {
496    switch (res->Type) {
497    case GL_TRANSFORM_FEEDBACK_VARYING:
498       return RESOURCE_XFV(res)->Size > 1 ?
499              RESOURCE_XFV(res)->Size : 0;
500    case GL_PROGRAM_INPUT:
501    case GL_PROGRAM_OUTPUT:
502       return RESOURCE_VAR(res)->type->length;
503    case GL_UNIFORM:
504    case GL_VERTEX_SUBROUTINE_UNIFORM:
505    case GL_GEOMETRY_SUBROUTINE_UNIFORM:
506    case GL_FRAGMENT_SUBROUTINE_UNIFORM:
507    case GL_COMPUTE_SUBROUTINE_UNIFORM:
508    case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
509    case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM:
510       return RESOURCE_UNI(res)->array_elements;
511    case GL_BUFFER_VARIABLE:
512       /* Unsized arrays */
513       if (RESOURCE_UNI(res)->array_stride > 0 &&
514           RESOURCE_UNI(res)->array_elements == 0)
515          return 1;
516       else
517          return RESOURCE_UNI(res)->array_elements;
518    case GL_VERTEX_SUBROUTINE:
519    case GL_GEOMETRY_SUBROUTINE:
520    case GL_FRAGMENT_SUBROUTINE:
521    case GL_COMPUTE_SUBROUTINE:
522    case GL_TESS_CONTROL_SUBROUTINE:
523    case GL_TESS_EVALUATION_SUBROUTINE:
524    case GL_ATOMIC_COUNTER_BUFFER:
525    case GL_UNIFORM_BLOCK:
526    case GL_SHADER_STORAGE_BLOCK:
527       return 0;
528    default:
529       assert(!"support for resource type not implemented");
530    }
531    return 0;
532 }
533 
534 /**
535  * Checks if array subscript is valid and if so sets array_index.
536  */
537 static bool
valid_array_index(const GLchar * name,unsigned * array_index)538 valid_array_index(const GLchar *name, unsigned *array_index)
539 {
540    long idx = 0;
541    const GLchar *out_base_name_end;
542 
543    idx = parse_program_resource_name(name, strlen(name), &out_base_name_end);
544    if (idx < 0)
545       return false;
546 
547    if (array_index)
548       *array_index = idx;
549 
550    return true;
551 }
552 
553 static uint32_t
compute_resource_key(GLenum programInterface,const char * name,size_t len)554 compute_resource_key(GLenum programInterface, const char *name, size_t len)
555 {
556    return _mesa_hash_data_with_seed(name, len, programInterface + len);
557 }
558 
559 static struct gl_program_resource *
search_resource_hash(struct gl_shader_program * shProg,GLenum programInterface,const char * name,unsigned * array_index)560 search_resource_hash(struct gl_shader_program *shProg,
561                      GLenum programInterface, const char *name,
562                      unsigned *array_index)
563 {
564    const char *base_name_end;
565    size_t len = strlen(name);
566    long index = parse_program_resource_name(name, len, &base_name_end);
567    char *name_copy;
568 
569    /* If dealing with array, we need to get the basename. */
570    if (index >= 0) {
571       name_copy = (char *) malloc(base_name_end - name + 1);
572       memcpy(name_copy, name, base_name_end - name);
573       name_copy[base_name_end - name] = '\0';
574       len = base_name_end - name;
575    } else {
576       name_copy = (char*) name;
577    }
578 
579    uint32_t key = compute_resource_key(programInterface, name_copy, len);
580    struct gl_program_resource *res = (struct gl_program_resource *)
581       _mesa_hash_table_u64_search(shProg->data->ProgramResourceHash, key);
582 
583    if (name_copy != name)
584       free(name_copy);
585 
586    if (res && array_index)
587       *array_index = index >= 0 ? index : 0;
588 
589    return res;
590 }
591 
592 /* Find a program resource with specific name in given interface.
593  */
594 struct gl_program_resource *
_mesa_program_resource_find_name(struct gl_shader_program * shProg,GLenum programInterface,const char * name,unsigned * array_index)595 _mesa_program_resource_find_name(struct gl_shader_program *shProg,
596                                  GLenum programInterface, const char *name,
597                                  unsigned *array_index)
598 {
599    struct gl_program_resource *res = NULL;
600 
601    if (name == NULL)
602       return NULL;
603 
604    /* If we have a name, try the ProgramResourceHash first. */
605    if (shProg->data->ProgramResourceHash)
606       res = search_resource_hash(shProg, programInterface, name, array_index);
607 
608    if (res)
609       return res;
610 
611    res = shProg->data->ProgramResourceList;
612    for (unsigned i = 0; i < shProg->data->NumProgramResourceList; i++, res++) {
613       if (res->Type != programInterface)
614          continue;
615 
616       /* Resource basename. */
617       const char *rname = _mesa_program_resource_name(res);
618 
619       /* Since ARB_gl_spirv lack of name reflections is a possibility */
620       if (rname == NULL)
621          continue;
622 
623       unsigned baselen = strlen(rname);
624       unsigned baselen_without_array_index = baselen;
625       const char *rname_last_square_bracket = strrchr(rname, '[');
626       bool found = false;
627       bool rname_has_array_index_zero = false;
628       /* From ARB_program_interface_query spec:
629        *
630        * "uint GetProgramResourceIndex(uint program, enum programInterface,
631        *                               const char *name);
632        *  [...]
633        *  If <name> exactly matches the name string of one of the active
634        *  resources for <programInterface>, the index of the matched resource is
635        *  returned. Additionally, if <name> would exactly match the name string
636        *  of an active resource if "[0]" were appended to <name>, the index of
637        *  the matched resource is returned. [...]"
638        *
639        * "A string provided to GetProgramResourceLocation or
640        * GetProgramResourceLocationIndex is considered to match an active variable
641        * if:
642        *
643        *  * the string exactly matches the name of the active variable;
644        *
645        *  * if the string identifies the base name of an active array, where the
646        *    string would exactly match the name of the variable if the suffix
647        *    "[0]" were appended to the string; [...]"
648        */
649       /* Remove array's index from interface block name comparison only if
650        * array's index is zero and the resulting string length is the same
651        * than the provided name's length.
652        */
653       if (rname_last_square_bracket) {
654          baselen_without_array_index -= strlen(rname_last_square_bracket);
655          rname_has_array_index_zero =
656             (strcmp(rname_last_square_bracket, "[0]") == 0) &&
657             (baselen_without_array_index == strlen(name));
658       }
659 
660       if (strncmp(rname, name, baselen) == 0)
661          found = true;
662       else if (rname_has_array_index_zero &&
663                strncmp(rname, name, baselen_without_array_index) == 0)
664          found = true;
665 
666       if (found) {
667          switch (programInterface) {
668          case GL_UNIFORM_BLOCK:
669          case GL_SHADER_STORAGE_BLOCK:
670             /* Basename match, check if array or struct. */
671             if (rname_has_array_index_zero ||
672                 name[baselen] == '\0' ||
673                 name[baselen] == '[' ||
674                 name[baselen] == '.') {
675                return res;
676             }
677             break;
678          case GL_TRANSFORM_FEEDBACK_VARYING:
679          case GL_BUFFER_VARIABLE:
680          case GL_UNIFORM:
681          case GL_VERTEX_SUBROUTINE_UNIFORM:
682          case GL_GEOMETRY_SUBROUTINE_UNIFORM:
683          case GL_FRAGMENT_SUBROUTINE_UNIFORM:
684          case GL_COMPUTE_SUBROUTINE_UNIFORM:
685          case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
686          case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM:
687          case GL_VERTEX_SUBROUTINE:
688          case GL_GEOMETRY_SUBROUTINE:
689          case GL_FRAGMENT_SUBROUTINE:
690          case GL_COMPUTE_SUBROUTINE:
691          case GL_TESS_CONTROL_SUBROUTINE:
692          case GL_TESS_EVALUATION_SUBROUTINE:
693             if (name[baselen] == '.') {
694                return res;
695             }
696             FALLTHROUGH;
697          case GL_PROGRAM_INPUT:
698          case GL_PROGRAM_OUTPUT:
699             if (name[baselen] == '\0') {
700                return res;
701             } else if (name[baselen] == '[' &&
702                 valid_array_index(name, array_index)) {
703                return res;
704             }
705             break;
706          default:
707             assert(!"not implemented for given interface");
708          }
709       }
710    }
711    return NULL;
712 }
713 
714 /* Find an uniform or buffer variable program resource with an specific offset
715  * inside a block with an specific binding.
716  *
717  * Valid interfaces are GL_BUFFER_VARIABLE and GL_UNIFORM.
718  */
719 static struct gl_program_resource *
program_resource_find_binding_offset(struct gl_shader_program * shProg,GLenum programInterface,const GLuint binding,const GLint offset)720 program_resource_find_binding_offset(struct gl_shader_program *shProg,
721                                      GLenum programInterface,
722                                      const GLuint binding,
723                                      const GLint offset)
724 {
725 
726    /* First we need to get the BLOCK_INDEX from the BUFFER_BINDING */
727    GLenum blockInterface;
728 
729    switch (programInterface) {
730    case GL_BUFFER_VARIABLE:
731       blockInterface = GL_SHADER_STORAGE_BLOCK;
732       break;
733    case GL_UNIFORM:
734       blockInterface = GL_UNIFORM_BLOCK;
735       break;
736    default:
737       assert("Invalid program interface");
738       return NULL;
739    }
740 
741    int block_index = -1;
742    int starting_index = -1;
743    struct gl_program_resource *res = shProg->data->ProgramResourceList;
744 
745    /* Blocks are added to the resource list in the same order that they are
746     * added to UniformBlocks/ShaderStorageBlocks. Furthermore, all the blocks
747     * of each type (UBO/SSBO) are contiguous, so we can infer block_index from
748     * the resource list.
749     */
750    for (unsigned i = 0; i < shProg->data->NumProgramResourceList; i++, res++) {
751       if (res->Type != blockInterface)
752          continue;
753 
754       /* Store the first index where a resource of the specific interface is. */
755       if (starting_index == -1)
756          starting_index = i;
757 
758       const struct gl_uniform_block *block = RESOURCE_UBO(res);
759 
760       if (block->Binding == binding) {
761          /* For arrays, or arrays of arrays of blocks, we want the resource
762           * for the block with base index. Most properties for members of each
763           * block are inherited from the block with the base index, including
764           * a uniform being active or not.
765           */
766          block_index = i - starting_index - block->linearized_array_index;
767          break;
768       }
769    }
770 
771    if (block_index == -1)
772       return NULL;
773 
774    /* We now look for the resource corresponding to the uniform or buffer
775     * variable using the BLOCK_INDEX and OFFSET.
776     */
777    res = shProg->data->ProgramResourceList;
778    for (unsigned i = 0; i < shProg->data->NumProgramResourceList; i++, res++) {
779       if (res->Type != programInterface)
780          continue;
781 
782       const struct gl_uniform_storage *uniform = RESOURCE_UNI(res);
783 
784       if (uniform->block_index == block_index && uniform->offset == offset) {
785          return res;
786       }
787    }
788 
789    return NULL;
790 }
791 
792 /* Checks if an uniform or buffer variable is in the active program resource
793  * list.
794  *
795  * It takes into accout that for variables coming from SPIR-V binaries their
796  * names could not be available (ARB_gl_spirv). In that case, it will use the
797  * the offset and the block binding to locate the resource.
798  *
799  * Valid interfaces are GL_BUFFER_VARIABLE and GL_UNIFORM.
800  */
801 struct gl_program_resource *
_mesa_program_resource_find_active_variable(struct gl_shader_program * shProg,GLenum programInterface,const gl_uniform_block * block,unsigned index)802 _mesa_program_resource_find_active_variable(struct gl_shader_program *shProg,
803                                             GLenum programInterface,
804                                             const gl_uniform_block *block,
805                                             unsigned index)
806 {
807    struct gl_program_resource *res;
808    struct gl_uniform_buffer_variable uni = block->Uniforms[index];
809 
810    assert(programInterface == GL_UNIFORM ||
811           programInterface == GL_BUFFER_VARIABLE);
812 
813    if (uni.IndexName) {
814       res = _mesa_program_resource_find_name(shProg, programInterface, uni.IndexName,
815                                              NULL);
816    } else {
817       /* As the resource has no associated name (ARB_gl_spirv),
818        * we can use the UBO/SSBO binding and offset to find it.
819        */
820       res = program_resource_find_binding_offset(shProg, programInterface,
821                                                  block->Binding, uni.Offset);
822    }
823 
824    return res;
825 }
826 
827 static GLuint
calc_resource_index(struct gl_shader_program * shProg,struct gl_program_resource * res)828 calc_resource_index(struct gl_shader_program *shProg,
829                     struct gl_program_resource *res)
830 {
831    unsigned i;
832    GLuint index = 0;
833    for (i = 0; i < shProg->data->NumProgramResourceList; i++) {
834       if (&shProg->data->ProgramResourceList[i] == res)
835          return index;
836       if (shProg->data->ProgramResourceList[i].Type == res->Type)
837          index++;
838    }
839    return GL_INVALID_INDEX;
840 }
841 
842 /**
843  * Calculate index for the given resource.
844  */
845 GLuint
_mesa_program_resource_index(struct gl_shader_program * shProg,struct gl_program_resource * res)846 _mesa_program_resource_index(struct gl_shader_program *shProg,
847                              struct gl_program_resource *res)
848 {
849    if (!res)
850       return GL_INVALID_INDEX;
851 
852    switch (res->Type) {
853    case GL_ATOMIC_COUNTER_BUFFER:
854       return RESOURCE_ATC(res) - shProg->data->AtomicBuffers;
855    case GL_VERTEX_SUBROUTINE:
856    case GL_GEOMETRY_SUBROUTINE:
857    case GL_FRAGMENT_SUBROUTINE:
858    case GL_COMPUTE_SUBROUTINE:
859    case GL_TESS_CONTROL_SUBROUTINE:
860    case GL_TESS_EVALUATION_SUBROUTINE:
861       return RESOURCE_SUB(res)->index;
862    case GL_UNIFORM_BLOCK:
863    case GL_SHADER_STORAGE_BLOCK:
864    case GL_TRANSFORM_FEEDBACK_BUFFER:
865    case GL_TRANSFORM_FEEDBACK_VARYING:
866    default:
867       return calc_resource_index(shProg, res);
868    }
869 }
870 
871 /**
872  * Find a program resource that points to given data.
873  */
874 static struct gl_program_resource*
program_resource_find_data(struct gl_shader_program * shProg,void * data)875 program_resource_find_data(struct gl_shader_program *shProg, void *data)
876 {
877    struct gl_program_resource *res = shProg->data->ProgramResourceList;
878    for (unsigned i = 0; i < shProg->data->NumProgramResourceList;
879         i++, res++) {
880       if (res->Data == data)
881          return res;
882    }
883    return NULL;
884 }
885 
886 /* Find a program resource with specific index in given interface.
887  */
888 struct gl_program_resource *
_mesa_program_resource_find_index(struct gl_shader_program * shProg,GLenum programInterface,GLuint index)889 _mesa_program_resource_find_index(struct gl_shader_program *shProg,
890                                   GLenum programInterface, GLuint index)
891 {
892    struct gl_program_resource *res = shProg->data->ProgramResourceList;
893    int idx = -1;
894 
895    for (unsigned i = 0; i < shProg->data->NumProgramResourceList;
896         i++, res++) {
897       if (res->Type != programInterface)
898          continue;
899 
900       switch (res->Type) {
901       case GL_UNIFORM_BLOCK:
902       case GL_ATOMIC_COUNTER_BUFFER:
903       case GL_SHADER_STORAGE_BLOCK:
904       case GL_TRANSFORM_FEEDBACK_BUFFER:
905          if (_mesa_program_resource_index(shProg, res) == index)
906             return res;
907          break;
908       case GL_TRANSFORM_FEEDBACK_VARYING:
909       case GL_PROGRAM_INPUT:
910       case GL_PROGRAM_OUTPUT:
911       case GL_UNIFORM:
912       case GL_VERTEX_SUBROUTINE_UNIFORM:
913       case GL_GEOMETRY_SUBROUTINE_UNIFORM:
914       case GL_FRAGMENT_SUBROUTINE_UNIFORM:
915       case GL_COMPUTE_SUBROUTINE_UNIFORM:
916       case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
917       case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM:
918       case GL_VERTEX_SUBROUTINE:
919       case GL_GEOMETRY_SUBROUTINE:
920       case GL_FRAGMENT_SUBROUTINE:
921       case GL_COMPUTE_SUBROUTINE:
922       case GL_TESS_CONTROL_SUBROUTINE:
923       case GL_TESS_EVALUATION_SUBROUTINE:
924       case GL_BUFFER_VARIABLE:
925          if (++idx == (int) index)
926             return res;
927          break;
928       default:
929          assert(!"not implemented for given interface");
930       }
931    }
932    return NULL;
933 }
934 
935 /* Function returns if resource name is expected to have index
936  * appended into it.
937  *
938  *
939  * Page 61 (page 73 of the PDF) in section 2.11 of the OpenGL ES 3.0
940  * spec says:
941  *
942  *     "If the active uniform is an array, the uniform name returned in
943  *     name will always be the name of the uniform array appended with
944  *     "[0]"."
945  *
946  * The same text also appears in the OpenGL 4.2 spec.  It does not,
947  * however, appear in any previous spec.  Previous specifications are
948  * ambiguous in this regard.  However, either name can later be passed
949  * to glGetUniformLocation (and related APIs), so there shouldn't be any
950  * harm in always appending "[0]" to uniform array names.
951  */
952 static bool
add_index_to_name(struct gl_program_resource * res)953 add_index_to_name(struct gl_program_resource *res)
954 {
955    /* Transform feedback varyings have array index already appended
956     * in their names.
957     */
958    return res->Type != GL_TRANSFORM_FEEDBACK_VARYING;
959 }
960 
961 /* Get name length of a program resource. This consists of
962  * base name + 3 for '[0]' if resource is an array.
963  */
964 extern unsigned
_mesa_program_resource_name_len(struct gl_program_resource * res)965 _mesa_program_resource_name_len(struct gl_program_resource *res)
966 {
967    const char* name = _mesa_program_resource_name(res);
968 
969    /* For shaders constructed from SPIR-V binaries, variables may not
970     * have names associated with them.
971     */
972    if (!name)
973       return 0;
974 
975    unsigned length = strlen(name);
976    if (_mesa_program_resource_array_size(res) && add_index_to_name(res))
977       length += 3;
978    return length;
979 }
980 
981 /* Get full name of a program resource.
982  */
983 bool
_mesa_get_program_resource_name(struct gl_shader_program * shProg,GLenum programInterface,GLuint index,GLsizei bufSize,GLsizei * length,GLchar * name,bool glthread,const char * caller)984 _mesa_get_program_resource_name(struct gl_shader_program *shProg,
985                                 GLenum programInterface, GLuint index,
986                                 GLsizei bufSize, GLsizei *length,
987                                 GLchar *name, bool glthread,
988                                 const char *caller)
989 {
990    GET_CURRENT_CONTEXT(ctx);
991 
992    /* Find resource with given interface and index. */
993    struct gl_program_resource *res =
994       _mesa_program_resource_find_index(shProg, programInterface, index);
995 
996    /* The error INVALID_VALUE is generated if <index> is greater than
997    * or equal to the number of entries in the active resource list for
998    * <programInterface>.
999    */
1000    if (!res) {
1001       _mesa_error_glthread_safe(ctx, GL_INVALID_VALUE, glthread,
1002                                 "%s(index %u)", caller, index);
1003       return false;
1004    }
1005 
1006    if (bufSize < 0) {
1007       _mesa_error_glthread_safe(ctx, GL_INVALID_VALUE, glthread,
1008                                 "%s(bufSize %d)", caller, bufSize);
1009       return false;
1010    }
1011 
1012    GLsizei localLength;
1013 
1014    if (length == NULL)
1015       length = &localLength;
1016 
1017    _mesa_copy_string(name, bufSize, length, _mesa_program_resource_name(res));
1018 
1019    /* The resource name can be NULL for shaders constructed from SPIR-V
1020     * binaries. In that case, we do not add the '[0]'.
1021     */
1022    if (name && name[0] != '\0' &&
1023        _mesa_program_resource_array_size(res) && add_index_to_name(res)) {
1024       int i;
1025 
1026       /* The comparison is strange because *length does *NOT* include the
1027        * terminating NUL, but maxLength does.
1028        */
1029       for (i = 0; i < 3 && (*length + i + 1) < bufSize; i++)
1030          name[*length + i] = "[0]"[i];
1031 
1032       name[*length + i] = '\0';
1033       *length += i;
1034    }
1035    return true;
1036 }
1037 
1038 static GLint
program_resource_location(struct gl_program_resource * res,unsigned array_index)1039 program_resource_location(struct gl_program_resource *res, unsigned array_index)
1040 {
1041    switch (res->Type) {
1042    case GL_PROGRAM_INPUT: {
1043       const gl_shader_variable *var = RESOURCE_VAR(res);
1044 
1045       if (var->location == -1)
1046          return -1;
1047 
1048       /* If the input is an array, fail if the index is out of bounds. */
1049       if (array_index > 0
1050           && array_index >= var->type->length) {
1051          return -1;
1052       }
1053       return var->location +
1054 	     (array_index * var->type->without_array()->matrix_columns);
1055    }
1056    case GL_PROGRAM_OUTPUT:
1057       if (RESOURCE_VAR(res)->location == -1)
1058          return -1;
1059 
1060       /* If the output is an array, fail if the index is out of bounds. */
1061       if (array_index > 0
1062           && array_index >= RESOURCE_VAR(res)->type->length) {
1063          return -1;
1064       }
1065       return RESOURCE_VAR(res)->location + array_index;
1066    case GL_UNIFORM:
1067       /* If the uniform is built-in, fail. */
1068       if (RESOURCE_UNI(res)->builtin)
1069          return -1;
1070 
1071      /* From page 79 of the OpenGL 4.2 spec:
1072       *
1073       *     "A valid name cannot be a structure, an array of structures, or any
1074       *     portion of a single vector or a matrix."
1075       */
1076       if (RESOURCE_UNI(res)->type->without_array()->is_struct())
1077          return -1;
1078 
1079       /* From the GL_ARB_uniform_buffer_object spec:
1080        *
1081        *     "The value -1 will be returned if <name> does not correspond to an
1082        *     active uniform variable name in <program>, if <name> is associated
1083        *     with a named uniform block, or if <name> starts with the reserved
1084        *     prefix "gl_"."
1085        */
1086       if (RESOURCE_UNI(res)->block_index != -1 ||
1087           RESOURCE_UNI(res)->atomic_buffer_index != -1)
1088          return -1;
1089 
1090       FALLTHROUGH;
1091    case GL_VERTEX_SUBROUTINE_UNIFORM:
1092    case GL_GEOMETRY_SUBROUTINE_UNIFORM:
1093    case GL_FRAGMENT_SUBROUTINE_UNIFORM:
1094    case GL_COMPUTE_SUBROUTINE_UNIFORM:
1095    case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
1096    case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM:
1097       /* If the uniform is an array, fail if the index is out of bounds. */
1098       if (array_index > 0
1099           && array_index >= RESOURCE_UNI(res)->array_elements) {
1100          return -1;
1101       }
1102 
1103       /* location in remap table + array element offset */
1104       return RESOURCE_UNI(res)->remap_location + array_index;
1105    default:
1106       return -1;
1107    }
1108 }
1109 
1110 /**
1111  * Function implements following location queries:
1112  *    glGetUniformLocation
1113  */
1114 GLint
_mesa_program_resource_location(struct gl_shader_program * shProg,GLenum programInterface,const char * name)1115 _mesa_program_resource_location(struct gl_shader_program *shProg,
1116                                 GLenum programInterface, const char *name)
1117 {
1118    unsigned array_index = 0;
1119    struct gl_program_resource *res =
1120       _mesa_program_resource_find_name(shProg, programInterface, name,
1121                                        &array_index);
1122 
1123    /* Resource not found. */
1124    if (!res)
1125       return -1;
1126 
1127    return program_resource_location(res, array_index);
1128 }
1129 
1130 static GLint
_get_resource_location_index(struct gl_program_resource * res)1131 _get_resource_location_index(struct gl_program_resource *res)
1132 {
1133    /* Non-existent variable or resource is not referenced by fragment stage. */
1134    if (!res || !(res->StageReferences & (1 << MESA_SHADER_FRAGMENT)))
1135       return -1;
1136 
1137    /* From OpenGL 4.5 spec, 7.3 Program Objects
1138     * "The value -1 will be returned by either command...
1139     *  ... or if name identifies an active variable that does not have a
1140     * valid location assigned.
1141     */
1142    if (RESOURCE_VAR(res)->location == -1)
1143       return -1;
1144    return RESOURCE_VAR(res)->index;
1145 }
1146 
1147 /**
1148  * Function implements following index queries:
1149  *    glGetFragDataIndex
1150  */
1151 GLint
_mesa_program_resource_location_index(struct gl_shader_program * shProg,GLenum programInterface,const char * name)1152 _mesa_program_resource_location_index(struct gl_shader_program *shProg,
1153                                       GLenum programInterface, const char *name)
1154 {
1155    struct gl_program_resource *res =
1156       _mesa_program_resource_find_name(shProg, programInterface, name, NULL);
1157 
1158    return _get_resource_location_index(res);
1159 }
1160 
1161 static uint8_t
stage_from_enum(GLenum ref)1162 stage_from_enum(GLenum ref)
1163 {
1164    switch (ref) {
1165    case GL_REFERENCED_BY_VERTEX_SHADER:
1166       return MESA_SHADER_VERTEX;
1167    case GL_REFERENCED_BY_TESS_CONTROL_SHADER:
1168       return MESA_SHADER_TESS_CTRL;
1169    case GL_REFERENCED_BY_TESS_EVALUATION_SHADER:
1170       return MESA_SHADER_TESS_EVAL;
1171    case GL_REFERENCED_BY_GEOMETRY_SHADER:
1172       return MESA_SHADER_GEOMETRY;
1173    case GL_REFERENCED_BY_FRAGMENT_SHADER:
1174       return MESA_SHADER_FRAGMENT;
1175    case GL_REFERENCED_BY_COMPUTE_SHADER:
1176       return MESA_SHADER_COMPUTE;
1177    default:
1178       assert(!"shader stage not supported");
1179       return MESA_SHADER_STAGES;
1180    }
1181 }
1182 
1183 /**
1184  * Check if resource is referenced by given 'referenced by' stage enum.
1185  * ATC and UBO resources hold stage references of their own.
1186  */
1187 static bool
is_resource_referenced(struct gl_shader_program * shProg,struct gl_program_resource * res,GLuint index,uint8_t stage)1188 is_resource_referenced(struct gl_shader_program *shProg,
1189                        struct gl_program_resource *res,
1190                        GLuint index, uint8_t stage)
1191 {
1192    /* First, check if we even have such a stage active. */
1193    if (!shProg->_LinkedShaders[stage])
1194       return false;
1195 
1196    if (res->Type == GL_ATOMIC_COUNTER_BUFFER)
1197       return RESOURCE_ATC(res)->StageReferences[stage];
1198 
1199    if (res->Type == GL_UNIFORM_BLOCK)
1200       return shProg->data->UniformBlocks[index].stageref & (1 << stage);
1201 
1202    if (res->Type == GL_SHADER_STORAGE_BLOCK)
1203       return shProg->data->ShaderStorageBlocks[index].stageref & (1 << stage);
1204 
1205    return res->StageReferences & (1 << stage);
1206 }
1207 
1208 static unsigned
get_buffer_property(struct gl_shader_program * shProg,struct gl_program_resource * res,const GLenum prop,GLint * val,bool glthread,const char * caller)1209 get_buffer_property(struct gl_shader_program *shProg,
1210                     struct gl_program_resource *res, const GLenum prop,
1211                     GLint *val, bool glthread, const char *caller)
1212 {
1213    GET_CURRENT_CONTEXT(ctx);
1214    if (res->Type != GL_UNIFORM_BLOCK &&
1215        res->Type != GL_ATOMIC_COUNTER_BUFFER &&
1216        res->Type != GL_SHADER_STORAGE_BLOCK &&
1217        res->Type != GL_TRANSFORM_FEEDBACK_BUFFER)
1218       goto invalid_operation;
1219 
1220    if (res->Type == GL_UNIFORM_BLOCK) {
1221       switch (prop) {
1222       case GL_BUFFER_BINDING:
1223          *val = RESOURCE_UBO(res)->Binding;
1224          return 1;
1225       case GL_BUFFER_DATA_SIZE:
1226          *val = RESOURCE_UBO(res)->UniformBufferSize;
1227          return 1;
1228       case GL_NUM_ACTIVE_VARIABLES:
1229          *val = 0;
1230          for (unsigned i = 0; i < RESOURCE_UBO(res)->NumUniforms; i++) {
1231             struct gl_program_resource *uni =
1232                _mesa_program_resource_find_active_variable(
1233                   shProg,
1234                   GL_UNIFORM,
1235                   RESOURCE_UBO(res),
1236                   i);
1237 
1238             if (!uni)
1239                continue;
1240             (*val)++;
1241          }
1242          return 1;
1243       case GL_ACTIVE_VARIABLES: {
1244          unsigned num_values = 0;
1245          for (unsigned i = 0; i < RESOURCE_UBO(res)->NumUniforms; i++) {
1246             struct gl_program_resource *uni =
1247                _mesa_program_resource_find_active_variable(
1248                   shProg,
1249                   GL_UNIFORM,
1250                   RESOURCE_UBO(res),
1251                   i);
1252 
1253             if (!uni)
1254                continue;
1255             *val++ =
1256                _mesa_program_resource_index(shProg, uni);
1257             num_values++;
1258          }
1259          return num_values;
1260       }
1261       }
1262    } else if (res->Type == GL_SHADER_STORAGE_BLOCK) {
1263       switch (prop) {
1264       case GL_BUFFER_BINDING:
1265          *val = RESOURCE_UBO(res)->Binding;
1266          return 1;
1267       case GL_BUFFER_DATA_SIZE:
1268          *val = RESOURCE_UBO(res)->UniformBufferSize;
1269          return 1;
1270       case GL_NUM_ACTIVE_VARIABLES:
1271          *val = 0;
1272          for (unsigned i = 0; i < RESOURCE_UBO(res)->NumUniforms; i++) {
1273             struct gl_program_resource *uni =
1274                _mesa_program_resource_find_active_variable(
1275                   shProg,
1276                   GL_BUFFER_VARIABLE,
1277                   RESOURCE_UBO(res),
1278                   i);
1279 
1280             if (!uni)
1281                continue;
1282             (*val)++;
1283          }
1284          return 1;
1285       case GL_ACTIVE_VARIABLES: {
1286          unsigned num_values = 0;
1287          for (unsigned i = 0; i < RESOURCE_UBO(res)->NumUniforms; i++) {
1288             struct gl_program_resource *uni =
1289                _mesa_program_resource_find_active_variable(
1290                   shProg,
1291                   GL_BUFFER_VARIABLE,
1292                   RESOURCE_UBO(res),
1293                   i);
1294 
1295             if (!uni)
1296                continue;
1297             *val++ =
1298                _mesa_program_resource_index(shProg, uni);
1299             num_values++;
1300          }
1301          return num_values;
1302       }
1303       }
1304    } else if (res->Type == GL_ATOMIC_COUNTER_BUFFER) {
1305       switch (prop) {
1306       case GL_BUFFER_BINDING:
1307          *val = RESOURCE_ATC(res)->Binding;
1308          return 1;
1309       case GL_BUFFER_DATA_SIZE:
1310          *val = RESOURCE_ATC(res)->MinimumSize;
1311          return 1;
1312       case GL_NUM_ACTIVE_VARIABLES:
1313          *val = RESOURCE_ATC(res)->NumUniforms;
1314          return 1;
1315       case GL_ACTIVE_VARIABLES:
1316          for (unsigned i = 0; i < RESOURCE_ATC(res)->NumUniforms; i++) {
1317             /* Active atomic buffer contains index to UniformStorage. Find
1318              * out gl_program_resource via data pointer and then calculate
1319              * index of that uniform.
1320              */
1321             unsigned idx = RESOURCE_ATC(res)->Uniforms[i];
1322             struct gl_program_resource *uni =
1323                program_resource_find_data(shProg,
1324                                           &shProg->data->UniformStorage[idx]);
1325             assert(uni);
1326             *val++ = _mesa_program_resource_index(shProg, uni);
1327          }
1328          return RESOURCE_ATC(res)->NumUniforms;
1329       }
1330    } else if (res->Type == GL_TRANSFORM_FEEDBACK_BUFFER) {
1331       switch (prop) {
1332       case GL_BUFFER_BINDING:
1333          *val = RESOURCE_XFB(res)->Binding;
1334          return 1;
1335       case GL_NUM_ACTIVE_VARIABLES:
1336          *val = RESOURCE_XFB(res)->NumVaryings;
1337          return 1;
1338       case GL_ACTIVE_VARIABLES:
1339          struct gl_transform_feedback_info *linked_xfb =
1340             shProg->last_vert_prog->sh.LinkedTransformFeedback;
1341          for (int i = 0; i < linked_xfb->NumVarying; i++) {
1342             unsigned index = linked_xfb->Varyings[i].BufferIndex;
1343             struct gl_program_resource *buf_res =
1344                _mesa_program_resource_find_index(shProg,
1345                                                  GL_TRANSFORM_FEEDBACK_BUFFER,
1346                                                  index);
1347             assert(buf_res);
1348             if (res == buf_res) {
1349                *val++ = i;
1350             }
1351          }
1352          return RESOURCE_XFB(res)->NumVaryings;
1353       }
1354    }
1355    assert(!"support for property type not implemented");
1356 
1357 invalid_operation:
1358    _mesa_error_glthread_safe(ctx, GL_INVALID_OPERATION, glthread,
1359                              "%s(%s prop %s)", caller,
1360                              _mesa_enum_to_string(res->Type),
1361                              _mesa_enum_to_string(prop));
1362 
1363    return 0;
1364 }
1365 
1366 unsigned
_mesa_program_resource_prop(struct gl_shader_program * shProg,struct gl_program_resource * res,GLuint index,const GLenum prop,GLint * val,bool glthread,const char * caller)1367 _mesa_program_resource_prop(struct gl_shader_program *shProg,
1368                             struct gl_program_resource *res, GLuint index,
1369                             const GLenum prop, GLint *val, bool glthread,
1370                             const char *caller)
1371 {
1372    GET_CURRENT_CONTEXT(ctx);
1373 
1374 #define VALIDATE_TYPE(type)\
1375    if (res->Type != type)\
1376       goto invalid_operation;
1377 
1378 #define VALIDATE_TYPE_2(type1, type2)\
1379    if (res->Type != type1 && res->Type != type2)\
1380       goto invalid_operation;
1381 
1382    switch(prop) {
1383    case GL_NAME_LENGTH:
1384       switch (res->Type) {
1385       case GL_ATOMIC_COUNTER_BUFFER:
1386       case GL_TRANSFORM_FEEDBACK_BUFFER:
1387          goto invalid_operation;
1388       default:
1389          /* Resource name length + terminator. */
1390          *val = _mesa_program_resource_name_len(res) + 1;
1391       }
1392       return 1;
1393    case GL_TYPE:
1394       switch (res->Type) {
1395       case GL_UNIFORM:
1396       case GL_BUFFER_VARIABLE:
1397          *val = RESOURCE_UNI(res)->type->gl_type;
1398          *val = mediump_to_highp_type(*val);
1399          return 1;
1400       case GL_PROGRAM_INPUT:
1401       case GL_PROGRAM_OUTPUT:
1402          *val = RESOURCE_VAR(res)->type->gl_type;
1403          *val = mediump_to_highp_type(*val);
1404          return 1;
1405       case GL_TRANSFORM_FEEDBACK_VARYING:
1406          *val = RESOURCE_XFV(res)->Type;
1407          *val = mediump_to_highp_type(*val);
1408          return 1;
1409       default:
1410          goto invalid_operation;
1411       }
1412    case GL_ARRAY_SIZE:
1413       switch (res->Type) {
1414       case GL_UNIFORM:
1415       case GL_BUFFER_VARIABLE:
1416       case GL_VERTEX_SUBROUTINE_UNIFORM:
1417       case GL_GEOMETRY_SUBROUTINE_UNIFORM:
1418       case GL_FRAGMENT_SUBROUTINE_UNIFORM:
1419       case GL_COMPUTE_SUBROUTINE_UNIFORM:
1420       case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
1421       case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM:
1422 
1423          /* Test if a buffer variable is an array or an unsized array.
1424           * Unsized arrays return zero as array size.
1425           */
1426          if (RESOURCE_UNI(res)->is_shader_storage &&
1427              RESOURCE_UNI(res)->array_stride > 0)
1428             *val = RESOURCE_UNI(res)->array_elements;
1429          else
1430             *val = MAX2(RESOURCE_UNI(res)->array_elements, 1);
1431          return 1;
1432       case GL_PROGRAM_INPUT:
1433       case GL_PROGRAM_OUTPUT:
1434          *val = MAX2(_mesa_program_resource_array_size(res), 1);
1435          return 1;
1436       case GL_TRANSFORM_FEEDBACK_VARYING:
1437          *val = RESOURCE_XFV(res)->Size;
1438          return 1;
1439       default:
1440          goto invalid_operation;
1441       }
1442    case GL_OFFSET:
1443       switch (res->Type) {
1444       case GL_UNIFORM:
1445       case GL_BUFFER_VARIABLE:
1446          *val = RESOURCE_UNI(res)->offset;
1447          return 1;
1448       case GL_TRANSFORM_FEEDBACK_VARYING:
1449          *val = RESOURCE_XFV(res)->Offset;
1450          return 1;
1451       default:
1452          goto invalid_operation;
1453       }
1454    case GL_BLOCK_INDEX:
1455       VALIDATE_TYPE_2(GL_UNIFORM, GL_BUFFER_VARIABLE);
1456       *val = RESOURCE_UNI(res)->block_index;
1457       return 1;
1458    case GL_ARRAY_STRIDE:
1459       VALIDATE_TYPE_2(GL_UNIFORM, GL_BUFFER_VARIABLE);
1460       *val = RESOURCE_UNI(res)->array_stride;
1461       return 1;
1462    case GL_MATRIX_STRIDE:
1463       VALIDATE_TYPE_2(GL_UNIFORM, GL_BUFFER_VARIABLE);
1464       *val = RESOURCE_UNI(res)->matrix_stride;
1465       return 1;
1466    case GL_IS_ROW_MAJOR:
1467       VALIDATE_TYPE_2(GL_UNIFORM, GL_BUFFER_VARIABLE);
1468       *val = RESOURCE_UNI(res)->row_major;
1469       return 1;
1470    case GL_ATOMIC_COUNTER_BUFFER_INDEX:
1471       VALIDATE_TYPE(GL_UNIFORM);
1472       *val = RESOURCE_UNI(res)->atomic_buffer_index;
1473       return 1;
1474    case GL_BUFFER_BINDING:
1475    case GL_BUFFER_DATA_SIZE:
1476    case GL_NUM_ACTIVE_VARIABLES:
1477    case GL_ACTIVE_VARIABLES:
1478       return get_buffer_property(shProg, res, prop, val, glthread, caller);
1479    case GL_REFERENCED_BY_COMPUTE_SHADER:
1480       if (!_mesa_has_compute_shaders(ctx))
1481          goto invalid_enum;
1482       FALLTHROUGH;
1483    case GL_REFERENCED_BY_VERTEX_SHADER:
1484    case GL_REFERENCED_BY_TESS_CONTROL_SHADER:
1485    case GL_REFERENCED_BY_TESS_EVALUATION_SHADER:
1486    case GL_REFERENCED_BY_GEOMETRY_SHADER:
1487    case GL_REFERENCED_BY_FRAGMENT_SHADER:
1488       switch (res->Type) {
1489       case GL_UNIFORM:
1490       case GL_PROGRAM_INPUT:
1491       case GL_PROGRAM_OUTPUT:
1492       case GL_UNIFORM_BLOCK:
1493       case GL_BUFFER_VARIABLE:
1494       case GL_SHADER_STORAGE_BLOCK:
1495       case GL_ATOMIC_COUNTER_BUFFER:
1496          *val = is_resource_referenced(shProg, res, index,
1497                                        stage_from_enum(prop));
1498          return 1;
1499       default:
1500          goto invalid_operation;
1501       }
1502    case GL_LOCATION:
1503       switch (res->Type) {
1504       case GL_UNIFORM:
1505       case GL_VERTEX_SUBROUTINE_UNIFORM:
1506       case GL_GEOMETRY_SUBROUTINE_UNIFORM:
1507       case GL_FRAGMENT_SUBROUTINE_UNIFORM:
1508       case GL_COMPUTE_SUBROUTINE_UNIFORM:
1509       case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
1510       case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM:
1511       case GL_PROGRAM_INPUT:
1512       case GL_PROGRAM_OUTPUT:
1513          *val = program_resource_location(res, 0);
1514          return 1;
1515       default:
1516          goto invalid_operation;
1517       }
1518    case GL_LOCATION_COMPONENT:
1519       switch (res->Type) {
1520       case GL_PROGRAM_INPUT:
1521       case GL_PROGRAM_OUTPUT:
1522          *val = RESOURCE_VAR(res)->component;
1523          return 1;
1524       default:
1525          goto invalid_operation;
1526       }
1527    case GL_LOCATION_INDEX: {
1528       int tmp;
1529       if (res->Type != GL_PROGRAM_OUTPUT)
1530          goto invalid_operation;
1531       tmp = program_resource_location(res, 0);
1532       if (tmp == -1)
1533          *val = -1;
1534       else
1535          *val = _get_resource_location_index(res);
1536       return 1;
1537    }
1538    case GL_NUM_COMPATIBLE_SUBROUTINES:
1539       if (res->Type != GL_VERTEX_SUBROUTINE_UNIFORM &&
1540           res->Type != GL_FRAGMENT_SUBROUTINE_UNIFORM &&
1541           res->Type != GL_GEOMETRY_SUBROUTINE_UNIFORM &&
1542           res->Type != GL_COMPUTE_SUBROUTINE_UNIFORM &&
1543           res->Type != GL_TESS_CONTROL_SUBROUTINE_UNIFORM &&
1544           res->Type != GL_TESS_EVALUATION_SUBROUTINE_UNIFORM)
1545          goto invalid_operation;
1546       *val = RESOURCE_UNI(res)->num_compatible_subroutines;
1547       return 1;
1548    case GL_COMPATIBLE_SUBROUTINES: {
1549       const struct gl_uniform_storage *uni;
1550       struct gl_program *p;
1551       unsigned count, i;
1552       int j;
1553 
1554       if (res->Type != GL_VERTEX_SUBROUTINE_UNIFORM &&
1555           res->Type != GL_FRAGMENT_SUBROUTINE_UNIFORM &&
1556           res->Type != GL_GEOMETRY_SUBROUTINE_UNIFORM &&
1557           res->Type != GL_COMPUTE_SUBROUTINE_UNIFORM &&
1558           res->Type != GL_TESS_CONTROL_SUBROUTINE_UNIFORM &&
1559           res->Type != GL_TESS_EVALUATION_SUBROUTINE_UNIFORM)
1560          goto invalid_operation;
1561       uni = RESOURCE_UNI(res);
1562 
1563       p = shProg->_LinkedShaders[_mesa_shader_stage_from_subroutine_uniform(res->Type)]->Program;
1564       count = 0;
1565       for (i = 0; i < p->sh.NumSubroutineFunctions; i++) {
1566          struct gl_subroutine_function *fn = &p->sh.SubroutineFunctions[i];
1567          for (j = 0; j < fn->num_compat_types; j++) {
1568             if (fn->types[j] == uni->type) {
1569                val[count++] = i;
1570                break;
1571             }
1572          }
1573       }
1574       return count;
1575    }
1576 
1577    case GL_TOP_LEVEL_ARRAY_SIZE:
1578       VALIDATE_TYPE(GL_BUFFER_VARIABLE);
1579       *val = RESOURCE_UNI(res)->top_level_array_size;
1580       return 1;
1581 
1582    case GL_TOP_LEVEL_ARRAY_STRIDE:
1583       VALIDATE_TYPE(GL_BUFFER_VARIABLE);
1584       *val = RESOURCE_UNI(res)->top_level_array_stride;
1585       return 1;
1586 
1587    /* GL_ARB_tessellation_shader */
1588    case GL_IS_PER_PATCH:
1589       switch (res->Type) {
1590       case GL_PROGRAM_INPUT:
1591       case GL_PROGRAM_OUTPUT:
1592          *val = RESOURCE_VAR(res)->patch;
1593          return 1;
1594       default:
1595          goto invalid_operation;
1596       }
1597 
1598    case GL_TRANSFORM_FEEDBACK_BUFFER_INDEX:
1599       VALIDATE_TYPE(GL_TRANSFORM_FEEDBACK_VARYING);
1600       *val = RESOURCE_XFV(res)->BufferIndex;
1601       return 1;
1602    case GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE:
1603       VALIDATE_TYPE(GL_TRANSFORM_FEEDBACK_BUFFER);
1604       *val = RESOURCE_XFB(res)->Stride * 4;
1605       return 1;
1606 
1607    default:
1608       goto invalid_enum;
1609    }
1610 
1611 #undef VALIDATE_TYPE
1612 #undef VALIDATE_TYPE_2
1613 
1614 invalid_enum:
1615    _mesa_error_glthread_safe(ctx, GL_INVALID_ENUM, glthread,
1616                              "%s(%s prop %s)", caller,
1617                              _mesa_enum_to_string(res->Type),
1618                              _mesa_enum_to_string(prop));
1619    return 0;
1620 
1621 invalid_operation:
1622    _mesa_error_glthread_safe(ctx, GL_INVALID_OPERATION, glthread,
1623                              "%s(%s prop %s)", caller,
1624                              _mesa_enum_to_string(res->Type),
1625                              _mesa_enum_to_string(prop));
1626    return 0;
1627 }
1628 
1629 extern void
_mesa_get_program_resourceiv(struct gl_shader_program * shProg,GLenum programInterface,GLuint index,GLsizei propCount,const GLenum * props,GLsizei bufSize,GLsizei * length,GLint * params)1630 _mesa_get_program_resourceiv(struct gl_shader_program *shProg,
1631                              GLenum programInterface, GLuint index, GLsizei propCount,
1632                              const GLenum *props, GLsizei bufSize,
1633                              GLsizei *length, GLint *params)
1634 {
1635    GET_CURRENT_CONTEXT(ctx);
1636    GLint *val = (GLint *) params;
1637    const GLenum *prop = props;
1638    GLsizei amount = 0;
1639 
1640    struct gl_program_resource *res =
1641       _mesa_program_resource_find_index(shProg, programInterface, index);
1642 
1643    /* No such resource found or bufSize negative. */
1644    if (!res || bufSize < 0) {
1645       _mesa_error(ctx, GL_INVALID_VALUE,
1646                   "glGetProgramResourceiv(%s index %d bufSize %d)",
1647                   _mesa_enum_to_string(programInterface), index, bufSize);
1648       return;
1649    }
1650 
1651    /* Write propCount values until error occurs or bufSize reached. */
1652    for (int i = 0; i < propCount && i < bufSize; i++, val++, prop++) {
1653       int props_written =
1654          _mesa_program_resource_prop(shProg, res, index, *prop, val,
1655                                      false, "glGetProgramResourceiv");
1656 
1657       /* Error happened. */
1658       if (props_written == 0)
1659          return;
1660 
1661       amount += props_written;
1662    }
1663 
1664    /* If <length> is not NULL, the actual number of integer values
1665     * written to <params> will be written to <length>.
1666     */
1667    if (length)
1668       *length = amount;
1669 }
1670 
1671 extern void
_mesa_get_program_interfaceiv(struct gl_shader_program * shProg,GLenum programInterface,GLenum pname,GLint * params)1672 _mesa_get_program_interfaceiv(struct gl_shader_program *shProg,
1673                               GLenum programInterface, GLenum pname,
1674                               GLint *params)
1675 {
1676    GET_CURRENT_CONTEXT(ctx);
1677    unsigned i;
1678 
1679    /* Validate pname against interface. */
1680    switch(pname) {
1681    case GL_ACTIVE_RESOURCES:
1682       for (i = 0, *params = 0; i < shProg->data->NumProgramResourceList; i++)
1683          if (shProg->data->ProgramResourceList[i].Type == programInterface)
1684             (*params)++;
1685       break;
1686    case GL_MAX_NAME_LENGTH:
1687       if (programInterface == GL_ATOMIC_COUNTER_BUFFER ||
1688           programInterface == GL_TRANSFORM_FEEDBACK_BUFFER) {
1689          _mesa_error(ctx, GL_INVALID_OPERATION,
1690                      "glGetProgramInterfaceiv(%s pname %s)",
1691                      _mesa_enum_to_string(programInterface),
1692                      _mesa_enum_to_string(pname));
1693          return;
1694       }
1695       /* Name length consists of base name, 3 additional chars '[0]' if
1696        * resource is an array and finally 1 char for string terminator.
1697        */
1698       for (i = 0, *params = 0; i < shProg->data->NumProgramResourceList; i++) {
1699          if (shProg->data->ProgramResourceList[i].Type != programInterface)
1700             continue;
1701          unsigned len =
1702             _mesa_program_resource_name_len(&shProg->data->ProgramResourceList[i]);
1703          *params = MAX2((unsigned)*params, len + 1);
1704       }
1705       break;
1706    case GL_MAX_NUM_ACTIVE_VARIABLES:
1707       switch (programInterface) {
1708       case GL_UNIFORM_BLOCK:
1709          for (i = 0, *params = 0; i < shProg->data->NumProgramResourceList; i++) {
1710             if (shProg->data->ProgramResourceList[i].Type == programInterface) {
1711                struct gl_uniform_block *block =
1712                   (struct gl_uniform_block *)
1713                   shProg->data->ProgramResourceList[i].Data;
1714                *params = MAX2((unsigned)*params, block->NumUniforms);
1715             }
1716          }
1717          break;
1718       case GL_SHADER_STORAGE_BLOCK:
1719          for (i = 0, *params = 0; i < shProg->data->NumProgramResourceList; i++) {
1720             if (shProg->data->ProgramResourceList[i].Type == programInterface) {
1721                struct gl_uniform_block *block =
1722                   (struct gl_uniform_block *)
1723                   shProg->data->ProgramResourceList[i].Data;
1724                GLint block_params = 0;
1725                for (unsigned j = 0; j < block->NumUniforms; j++) {
1726                   struct gl_program_resource *uni =
1727                      _mesa_program_resource_find_active_variable(
1728                         shProg,
1729                         GL_BUFFER_VARIABLE,
1730                         block,
1731                         j);
1732                   if (!uni)
1733                      continue;
1734                   block_params++;
1735                }
1736                *params = MAX2(*params, block_params);
1737             }
1738          }
1739          break;
1740       case GL_ATOMIC_COUNTER_BUFFER:
1741          for (i = 0, *params = 0; i < shProg->data->NumProgramResourceList; i++) {
1742             if (shProg->data->ProgramResourceList[i].Type == programInterface) {
1743                struct gl_active_atomic_buffer *buffer =
1744                   (struct gl_active_atomic_buffer *)
1745                   shProg->data->ProgramResourceList[i].Data;
1746                *params = MAX2((unsigned)*params, buffer->NumUniforms);
1747             }
1748          }
1749          break;
1750       case GL_TRANSFORM_FEEDBACK_BUFFER:
1751          for (i = 0, *params = 0; i < shProg->data->NumProgramResourceList; i++) {
1752             if (shProg->data->ProgramResourceList[i].Type == programInterface) {
1753                struct gl_transform_feedback_buffer *buffer =
1754                   (struct gl_transform_feedback_buffer *)
1755                   shProg->data->ProgramResourceList[i].Data;
1756                *params = MAX2((unsigned)*params, buffer->NumVaryings);
1757             }
1758          }
1759          break;
1760       default:
1761         _mesa_error(ctx, GL_INVALID_OPERATION,
1762                     "glGetProgramInterfaceiv(%s pname %s)",
1763                     _mesa_enum_to_string(programInterface),
1764                     _mesa_enum_to_string(pname));
1765       }
1766       break;
1767    case GL_MAX_NUM_COMPATIBLE_SUBROUTINES:
1768       switch (programInterface) {
1769       case GL_VERTEX_SUBROUTINE_UNIFORM:
1770       case GL_FRAGMENT_SUBROUTINE_UNIFORM:
1771       case GL_GEOMETRY_SUBROUTINE_UNIFORM:
1772       case GL_COMPUTE_SUBROUTINE_UNIFORM:
1773       case GL_TESS_CONTROL_SUBROUTINE_UNIFORM:
1774       case GL_TESS_EVALUATION_SUBROUTINE_UNIFORM: {
1775          for (i = 0, *params = 0; i < shProg->data->NumProgramResourceList; i++) {
1776             if (shProg->data->ProgramResourceList[i].Type == programInterface) {
1777                struct gl_uniform_storage *uni =
1778                   (struct gl_uniform_storage *)
1779                   shProg->data->ProgramResourceList[i].Data;
1780                *params = MAX2((unsigned)*params, uni->num_compatible_subroutines);
1781             }
1782          }
1783          break;
1784       }
1785 
1786       default:
1787          _mesa_error(ctx, GL_INVALID_OPERATION,
1788                      "glGetProgramInterfaceiv(%s pname %s)",
1789                      _mesa_enum_to_string(programInterface),
1790                      _mesa_enum_to_string(pname));
1791       }
1792       break;
1793    default:
1794       _mesa_error(ctx, GL_INVALID_OPERATION,
1795                   "glGetProgramInterfaceiv(pname %s)",
1796                   _mesa_enum_to_string(pname));
1797    }
1798 }
1799 
1800 static bool
validate_io(struct gl_program * producer,struct gl_program * consumer)1801 validate_io(struct gl_program *producer, struct gl_program *consumer)
1802 {
1803    if (producer->sh.data->linked_stages == consumer->sh.data->linked_stages)
1804       return true;
1805 
1806    const bool producer_is_array_stage =
1807       producer->info.stage == MESA_SHADER_TESS_CTRL;
1808    const bool consumer_is_array_stage =
1809       consumer->info.stage == MESA_SHADER_GEOMETRY ||
1810       consumer->info.stage == MESA_SHADER_TESS_CTRL ||
1811       consumer->info.stage == MESA_SHADER_TESS_EVAL;
1812 
1813    bool valid = true;
1814 
1815    gl_shader_variable const **outputs =
1816       (gl_shader_variable const **) calloc(producer->sh.data->NumProgramResourceList,
1817                                            sizeof(gl_shader_variable *));
1818    if (outputs == NULL)
1819       return false;
1820 
1821    /* Section 7.4.1 (Shader Interface Matching) of the OpenGL ES 3.1 spec
1822     * says:
1823     *
1824     *    At an interface between program objects, the set of inputs and
1825     *    outputs are considered to match exactly if and only if:
1826     *
1827     *    - Every declared input variable has a matching output, as described
1828     *      above.
1829     *    - There are no user-defined output variables declared without a
1830     *      matching input variable declaration.
1831     *
1832     * Every input has an output, and every output has an input.  Scan the list
1833     * of producer resources once, and generate the list of outputs.  As inputs
1834     * and outputs are matched, remove the matched outputs from the set.  At
1835     * the end, the set must be empty.  If the set is not empty, then there is
1836     * some output that did not have an input.
1837     */
1838    unsigned num_outputs = 0;
1839    for (unsigned i = 0; i < producer->sh.data->NumProgramResourceList; i++) {
1840       struct gl_program_resource *res =
1841          &producer->sh.data->ProgramResourceList[i];
1842 
1843       if (res->Type != GL_PROGRAM_OUTPUT)
1844          continue;
1845 
1846       gl_shader_variable const *const var = RESOURCE_VAR(res);
1847 
1848       /* Section 7.4.1 (Shader Interface Matching) of the OpenGL ES 3.1 spec
1849        * says:
1850        *
1851        *    Built-in inputs or outputs do not affect interface matching.
1852        */
1853       if (is_gl_identifier(var->name))
1854          continue;
1855 
1856       outputs[num_outputs++] = var;
1857    }
1858 
1859    unsigned match_index = 0;
1860    for (unsigned i = 0; i < consumer->sh.data->NumProgramResourceList; i++) {
1861       struct gl_program_resource *res =
1862          &consumer->sh.data->ProgramResourceList[i];
1863 
1864       if (res->Type != GL_PROGRAM_INPUT)
1865          continue;
1866 
1867       gl_shader_variable const *const consumer_var = RESOURCE_VAR(res);
1868       gl_shader_variable const *producer_var = NULL;
1869 
1870       if (is_gl_identifier(consumer_var->name))
1871          continue;
1872 
1873       /* Inputs with explicit locations match other outputs with explicit
1874        * locations by location instead of by name.
1875        */
1876       if (consumer_var->explicit_location) {
1877          for (unsigned j = 0; j < num_outputs; j++) {
1878             const gl_shader_variable *const var = outputs[j];
1879 
1880             if (var->explicit_location &&
1881                 consumer_var->location == var->location) {
1882                producer_var = var;
1883                match_index = j;
1884                break;
1885             }
1886          }
1887       } else {
1888          for (unsigned j = 0; j < num_outputs; j++) {
1889             const gl_shader_variable *const var = outputs[j];
1890 
1891             if (!var->explicit_location &&
1892                 strcmp(consumer_var->name, var->name) == 0) {
1893                producer_var = var;
1894                match_index = j;
1895                break;
1896             }
1897          }
1898       }
1899 
1900       /* Section 7.4.1 (Shader Interface Matching) of the OpenGL ES 3.1 spec
1901        * says:
1902        *
1903        *    - An output variable is considered to match an input variable in
1904        *      the subsequent shader if:
1905        *
1906        *      - the two variables match in name, type, and qualification; or
1907        *
1908        *      - the two variables are declared with the same location
1909        *        qualifier and match in type and qualification.
1910        */
1911       if (producer_var == NULL) {
1912          valid = false;
1913          goto out;
1914       }
1915 
1916       /* An output cannot match more than one input, so remove the output from
1917        * the set of possible outputs.
1918        */
1919       outputs[match_index] = NULL;
1920       num_outputs--;
1921       if (match_index < num_outputs)
1922          outputs[match_index] = outputs[num_outputs];
1923 
1924       /* Section 7.4.1 (Shader Interface Matching) of the ES 3.2 spec says:
1925        *
1926        *    "Tessellation control shader per-vertex output variables and
1927        *     blocks and tessellation control, tessellation evaluation, and
1928        *     geometry shader per-vertex input variables and blocks are
1929        *     required to be declared as arrays, with each element representing
1930        *     input or output values for a single vertex of a multi-vertex
1931        *     primitive. For the purposes of interface matching, such variables
1932        *     and blocks are treated as though they were not declared as
1933        *     arrays."
1934        *
1935        * So we unwrap those types before matching.
1936        */
1937       const glsl_type *consumer_type = consumer_var->type;
1938       const glsl_type *consumer_interface_type = consumer_var->interface_type;
1939       const glsl_type *producer_type = producer_var->type;
1940       const glsl_type *producer_interface_type = producer_var->interface_type;
1941 
1942       if (consumer_is_array_stage) {
1943          if (consumer_interface_type) {
1944             /* the interface is the array; the underlying types should match */
1945             if (consumer_interface_type->is_array() && !consumer_var->patch)
1946                consumer_interface_type = consumer_interface_type->fields.array;
1947          } else {
1948             if (consumer_type->is_array() && !consumer_var->patch)
1949                consumer_type = consumer_type->fields.array;
1950          }
1951       }
1952 
1953       if (producer_is_array_stage) {
1954          if (producer_interface_type) {
1955             /* the interface is the array; the underlying types should match */
1956             if (producer_interface_type->is_array() && !producer_var->patch)
1957                producer_interface_type = producer_interface_type->fields.array;
1958          } else {
1959             if (producer_type->is_array() && !producer_var->patch)
1960                producer_type = producer_type->fields.array;
1961          }
1962       }
1963 
1964       if (producer_type != consumer_type) {
1965          valid = false;
1966          goto out;
1967       }
1968 
1969       if (producer_interface_type != consumer_interface_type) {
1970          valid = false;
1971          goto out;
1972       }
1973 
1974       /* Section 9.2.2 (Separable Programs) of the GLSL ES spec says:
1975        *
1976        *    Qualifier Class|  Qualifier  |in/out
1977        *    ---------------+-------------+------
1978        *    Storage        |     in      |
1979        *                   |     out     |  N/A
1980        *                   |   uniform   |
1981        *    ---------------+-------------+------
1982        *    Auxiliary      |   centroid  |   No
1983        *    ---------------+-------------+------
1984        *                   |   location  |  Yes
1985        *                   | Block layout|  N/A
1986        *                   |   binding   |  N/A
1987        *                   |   offset    |  N/A
1988        *                   |   format    |  N/A
1989        *    ---------------+-------------+------
1990        *    Interpolation  |   smooth    |
1991        *                   |    flat     |  Yes
1992        *    ---------------+-------------+------
1993        *                   |    lowp     |
1994        *    Precision      |   mediump   |  Yes
1995        *                   |    highp    |
1996        *    ---------------+-------------+------
1997        *    Variance       |  invariant  |   No
1998        *    ---------------+-------------+------
1999        *    Memory         |     all     |  N/A
2000        *
2001        * Note that location mismatches are detected by the loops above that
2002        * find the producer variable that goes with the consumer variable.
2003        */
2004       unsigned producer_interpolation = producer_var->interpolation;
2005       unsigned consumer_interpolation = consumer_var->interpolation;
2006       if (producer_interpolation == INTERP_MODE_NONE)
2007          producer_interpolation = INTERP_MODE_SMOOTH;
2008       if (consumer_interpolation == INTERP_MODE_NONE)
2009          consumer_interpolation = INTERP_MODE_SMOOTH;
2010       if (producer_interpolation != consumer_interpolation) {
2011          valid = false;
2012          goto out;
2013       }
2014 
2015       if (producer_var->precision != consumer_var->precision) {
2016          valid = false;
2017          goto out;
2018       }
2019 
2020       if (producer_var->outermost_struct_type != consumer_var->outermost_struct_type) {
2021          valid = false;
2022          goto out;
2023       }
2024    }
2025 
2026  out:
2027    free(outputs);
2028    return valid && num_outputs == 0;
2029 }
2030 
2031 /**
2032  * Validate inputs against outputs in a program pipeline.
2033  */
2034 extern "C" bool
_mesa_validate_pipeline_io(struct gl_pipeline_object * pipeline)2035 _mesa_validate_pipeline_io(struct gl_pipeline_object *pipeline)
2036 {
2037    struct gl_program **prog = (struct gl_program **) pipeline->CurrentProgram;
2038 
2039    /* Find first active stage in pipeline. */
2040    unsigned idx, prev = 0;
2041    for (idx = 0; idx < ARRAY_SIZE(pipeline->CurrentProgram); idx++) {
2042       if (prog[idx]) {
2043          prev = idx;
2044          break;
2045       }
2046    }
2047 
2048    for (idx = prev + 1; idx < ARRAY_SIZE(pipeline->CurrentProgram); idx++) {
2049       if (prog[idx]) {
2050          /* Pipeline might include both non-compute and a compute program, do
2051           * not attempt to validate varyings between non-compute and compute
2052           * stage.
2053           */
2054          if (prog[idx]->info.stage == MESA_SHADER_COMPUTE)
2055             break;
2056 
2057          if (!validate_io(prog[prev], prog[idx]))
2058             return false;
2059 
2060          prev = idx;
2061       }
2062    }
2063    return true;
2064 }
2065 
2066 extern "C" void
_mesa_create_program_resource_hash(struct gl_shader_program * shProg)2067 _mesa_create_program_resource_hash(struct gl_shader_program *shProg)
2068 {
2069    /* Rebuild resource hash. */
2070    if (shProg->data->ProgramResourceHash)
2071       _mesa_hash_table_u64_destroy(shProg->data->ProgramResourceHash);
2072 
2073    shProg->data->ProgramResourceHash = _mesa_hash_table_u64_create(shProg);
2074 
2075    struct gl_program_resource *res = shProg->data->ProgramResourceList;
2076    for (unsigned i = 0; i < shProg->data->NumProgramResourceList; i++, res++) {
2077       const char *name = _mesa_program_resource_name(res);
2078       if (name) {
2079          uint32_t key = compute_resource_key(res->Type, name, strlen(name));
2080          _mesa_hash_table_u64_insert(shProg->data->ProgramResourceHash, key,
2081                                      res);
2082       }
2083    }
2084 }
2085