xref: /aosp_15_r20/external/mesa3d/src/compiler/glsl/builtin_variables.cpp (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2010 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 /**
26  * Building this file with MinGW g++ 7.3 or 7.4 with:
27  *   scons platform=windows toolchain=crossmingw machine=x86 build=profile
28  * triggers an internal compiler error.
29  * Overriding the optimization level to -O1 works around the issue.
30  * MinGW 5.3.1 does not seem to have the bug, neither does 8.3.  So for now
31  * we're simply testing for version 7.x here.
32  */
33 #if defined(__MINGW32__) && __GNUC__ == 7
34 #warning "disabling optimizations for this file to work around compiler bug in MinGW gcc 7.x"
35 #pragma GCC optimize("O1")
36 #endif
37 
38 
39 #include "ir.h"
40 #include "ir_builder.h"
41 #include "linker.h"
42 #include "glsl_parser_extras.h"
43 #include "glsl_symbol_table.h"
44 #include "main/consts_exts.h"
45 #include "main/uniforms.h"
46 #include "program/prog_statevars.h"
47 #include "program/prog_instruction.h"
48 #include "util/compiler.h"
49 #include "builtin_functions.h"
50 
51 using namespace ir_builder;
52 
53 static const struct gl_builtin_uniform_element gl_NumSamples_elements[] = {
54    {NULL, {STATE_NUM_SAMPLES, 0, 0}, SWIZZLE_XXXX}
55 };
56 
57 static const struct gl_builtin_uniform_element gl_DepthRange_elements[] = {
58    {"near", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_XXXX},
59    {"far", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_YYYY},
60    {"diff", {STATE_DEPTH_RANGE, 0, 0}, SWIZZLE_ZZZZ},
61 };
62 
63 static const struct gl_builtin_uniform_element gl_ClipPlane_elements[] = {
64    {NULL, {STATE_CLIPPLANE, 0, 0}, SWIZZLE_XYZW}
65 };
66 
67 static const struct gl_builtin_uniform_element gl_Point_elements[] = {
68    {"size", {STATE_POINT_SIZE}, SWIZZLE_XXXX},
69    {"sizeMin", {STATE_POINT_SIZE}, SWIZZLE_YYYY},
70    {"sizeMax", {STATE_POINT_SIZE}, SWIZZLE_ZZZZ},
71    {"fadeThresholdSize", {STATE_POINT_SIZE}, SWIZZLE_WWWW},
72    {"distanceConstantAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_XXXX},
73    {"distanceLinearAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_YYYY},
74    {"distanceQuadraticAttenuation", {STATE_POINT_ATTENUATION}, SWIZZLE_ZZZZ},
75 };
76 
77 static const struct gl_builtin_uniform_element gl_FrontMaterial_elements[] = {
78    {"emission", {STATE_MATERIAL, MAT_ATTRIB_FRONT_EMISSION}, SWIZZLE_XYZW},
79    {"ambient", {STATE_MATERIAL, MAT_ATTRIB_FRONT_AMBIENT}, SWIZZLE_XYZW},
80    {"diffuse", {STATE_MATERIAL, MAT_ATTRIB_FRONT_DIFFUSE}, SWIZZLE_XYZW},
81    {"specular", {STATE_MATERIAL, MAT_ATTRIB_FRONT_SPECULAR}, SWIZZLE_XYZW},
82    {"shininess", {STATE_MATERIAL, MAT_ATTRIB_FRONT_SHININESS}, SWIZZLE_XXXX},
83 };
84 
85 static const struct gl_builtin_uniform_element gl_BackMaterial_elements[] = {
86    {"emission", {STATE_MATERIAL, MAT_ATTRIB_BACK_EMISSION}, SWIZZLE_XYZW},
87    {"ambient", {STATE_MATERIAL, MAT_ATTRIB_BACK_AMBIENT}, SWIZZLE_XYZW},
88    {"diffuse", {STATE_MATERIAL, MAT_ATTRIB_BACK_DIFFUSE}, SWIZZLE_XYZW},
89    {"specular", {STATE_MATERIAL, MAT_ATTRIB_BACK_SPECULAR}, SWIZZLE_XYZW},
90    {"shininess", {STATE_MATERIAL, MAT_ATTRIB_BACK_SHININESS}, SWIZZLE_XXXX},
91 };
92 
93 static const struct gl_builtin_uniform_element gl_LightSource_elements[] = {
94    {"ambient", {STATE_LIGHT, 0, STATE_AMBIENT}, SWIZZLE_XYZW},
95    {"diffuse", {STATE_LIGHT, 0, STATE_DIFFUSE}, SWIZZLE_XYZW},
96    {"specular", {STATE_LIGHT, 0, STATE_SPECULAR}, SWIZZLE_XYZW},
97    {"position", {STATE_LIGHT, 0, STATE_POSITION}, SWIZZLE_XYZW},
98    {"halfVector", {STATE_LIGHT, 0, STATE_HALF_VECTOR}, SWIZZLE_XYZW},
99    {"spotDirection", {STATE_LIGHT, 0, STATE_SPOT_DIRECTION},
100     MAKE_SWIZZLE4(SWIZZLE_X,
101 		  SWIZZLE_Y,
102 		  SWIZZLE_Z,
103 		  SWIZZLE_Z)},
104    {"spotCosCutoff", {STATE_LIGHT, 0, STATE_SPOT_DIRECTION}, SWIZZLE_WWWW},
105    {"constantAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_XXXX},
106    {"linearAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_YYYY},
107    {"quadraticAttenuation", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_ZZZZ},
108    {"spotExponent", {STATE_LIGHT, 0, STATE_ATTENUATION}, SWIZZLE_WWWW},
109    {"spotCutoff", {STATE_LIGHT, 0, STATE_SPOT_CUTOFF}, SWIZZLE_XXXX},
110 };
111 
112 static const struct gl_builtin_uniform_element gl_LightModel_elements[] = {
113    {"ambient", {STATE_LIGHTMODEL_AMBIENT, 0}, SWIZZLE_XYZW},
114 };
115 
116 static const struct gl_builtin_uniform_element gl_FrontLightModelProduct_elements[] = {
117    {"sceneColor", {STATE_LIGHTMODEL_SCENECOLOR, 0}, SWIZZLE_XYZW},
118 };
119 
120 static const struct gl_builtin_uniform_element gl_BackLightModelProduct_elements[] = {
121    {"sceneColor", {STATE_LIGHTMODEL_SCENECOLOR, 1}, SWIZZLE_XYZW},
122 };
123 
124 static const struct gl_builtin_uniform_element gl_FrontLightProduct_elements[] = {
125    {"ambient", {STATE_LIGHTPROD, 0, MAT_ATTRIB_FRONT_AMBIENT}, SWIZZLE_XYZW},
126    {"diffuse", {STATE_LIGHTPROD, 0, MAT_ATTRIB_FRONT_DIFFUSE}, SWIZZLE_XYZW},
127    {"specular", {STATE_LIGHTPROD, 0, MAT_ATTRIB_FRONT_SPECULAR}, SWIZZLE_XYZW},
128 };
129 
130 static const struct gl_builtin_uniform_element gl_BackLightProduct_elements[] = {
131    {"ambient", {STATE_LIGHTPROD, 0, MAT_ATTRIB_BACK_AMBIENT}, SWIZZLE_XYZW},
132    {"diffuse", {STATE_LIGHTPROD, 0, MAT_ATTRIB_BACK_DIFFUSE}, SWIZZLE_XYZW},
133    {"specular", {STATE_LIGHTPROD, 0, MAT_ATTRIB_BACK_SPECULAR}, SWIZZLE_XYZW},
134 };
135 
136 static const struct gl_builtin_uniform_element gl_TextureEnvColor_elements[] = {
137    {NULL, {STATE_TEXENV_COLOR, 0}, SWIZZLE_XYZW},
138 };
139 
140 static const struct gl_builtin_uniform_element gl_EyePlaneS_elements[] = {
141    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_S}, SWIZZLE_XYZW},
142 };
143 
144 static const struct gl_builtin_uniform_element gl_EyePlaneT_elements[] = {
145    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_T}, SWIZZLE_XYZW},
146 };
147 
148 static const struct gl_builtin_uniform_element gl_EyePlaneR_elements[] = {
149    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_R}, SWIZZLE_XYZW},
150 };
151 
152 static const struct gl_builtin_uniform_element gl_EyePlaneQ_elements[] = {
153    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_EYE_Q}, SWIZZLE_XYZW},
154 };
155 
156 static const struct gl_builtin_uniform_element gl_ObjectPlaneS_elements[] = {
157    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_S}, SWIZZLE_XYZW},
158 };
159 
160 static const struct gl_builtin_uniform_element gl_ObjectPlaneT_elements[] = {
161    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_T}, SWIZZLE_XYZW},
162 };
163 
164 static const struct gl_builtin_uniform_element gl_ObjectPlaneR_elements[] = {
165    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_R}, SWIZZLE_XYZW},
166 };
167 
168 static const struct gl_builtin_uniform_element gl_ObjectPlaneQ_elements[] = {
169    {NULL, {STATE_TEXGEN, 0, STATE_TEXGEN_OBJECT_Q}, SWIZZLE_XYZW},
170 };
171 
172 static const struct gl_builtin_uniform_element gl_Fog_elements[] = {
173    {"color", {STATE_FOG_COLOR}, SWIZZLE_XYZW},
174    {"density", {STATE_FOG_PARAMS}, SWIZZLE_XXXX},
175    {"start", {STATE_FOG_PARAMS}, SWIZZLE_YYYY},
176    {"end", {STATE_FOG_PARAMS}, SWIZZLE_ZZZZ},
177    {"scale", {STATE_FOG_PARAMS}, SWIZZLE_WWWW},
178 };
179 
180 static const struct gl_builtin_uniform_element gl_NormalScale_elements[] = {
181    {NULL, {STATE_NORMAL_SCALE_EYESPACE}, SWIZZLE_XXXX},
182 };
183 
184 static const struct gl_builtin_uniform_element gl_FogParamsOptimizedMESA_elements[] = {
185    {NULL, {STATE_FOG_PARAMS_OPTIMIZED}, SWIZZLE_XYZW},
186 };
187 
188 #define ATTRIB(i) \
189    static const struct gl_builtin_uniform_element gl_CurrentAttribFrag##i##MESA_elements[] = { \
190       {NULL, {STATE_CURRENT_ATTRIB_MAYBE_VP_CLAMPED, i}, SWIZZLE_XYZW}, \
191    };
192 
193 ATTRIB(0)
194 ATTRIB(1)
195 ATTRIB(2)
196 ATTRIB(3)
197 ATTRIB(4)
198 ATTRIB(5)
199 ATTRIB(6)
200 ATTRIB(7)
201 ATTRIB(8)
202 ATTRIB(9)
203 ATTRIB(10)
204 ATTRIB(11)
205 ATTRIB(12)
206 ATTRIB(13)
207 ATTRIB(14)
208 ATTRIB(15)
209 ATTRIB(16)
210 ATTRIB(17)
211 ATTRIB(18)
212 ATTRIB(19)
213 ATTRIB(20)
214 ATTRIB(21)
215 ATTRIB(22)
216 ATTRIB(23)
217 ATTRIB(24)
218 ATTRIB(25)
219 ATTRIB(26)
220 ATTRIB(27)
221 ATTRIB(28)
222 ATTRIB(29)
223 ATTRIB(30)
224 ATTRIB(31)
225 
226 #define MATRIX(name, statevar)				\
227    static const struct gl_builtin_uniform_element name ## _elements[] = { \
228       { NULL, { statevar, 0, 0, 0}, SWIZZLE_XYZW },		\
229       { NULL, { statevar, 0, 1, 1}, SWIZZLE_XYZW },		\
230       { NULL, { statevar, 0, 2, 2}, SWIZZLE_XYZW },		\
231       { NULL, { statevar, 0, 3, 3}, SWIZZLE_XYZW },		\
232    }
233 
234 MATRIX(gl_ModelViewMatrix, STATE_MODELVIEW_MATRIX_TRANSPOSE);
235 MATRIX(gl_ModelViewMatrixInverse, STATE_MODELVIEW_MATRIX_INVTRANS);
236 MATRIX(gl_ModelViewMatrixTranspose, STATE_MODELVIEW_MATRIX);
237 MATRIX(gl_ModelViewMatrixInverseTranspose, STATE_MODELVIEW_MATRIX_INVERSE);
238 
239 MATRIX(gl_ProjectionMatrix, STATE_PROJECTION_MATRIX_TRANSPOSE);
240 MATRIX(gl_ProjectionMatrixInverse, STATE_PROJECTION_MATRIX_INVTRANS);
241 MATRIX(gl_ProjectionMatrixTranspose, STATE_PROJECTION_MATRIX);
242 MATRIX(gl_ProjectionMatrixInverseTranspose, STATE_PROJECTION_MATRIX_INVERSE);
243 
244 MATRIX(gl_ModelViewProjectionMatrix, STATE_MVP_MATRIX_TRANSPOSE);
245 MATRIX(gl_ModelViewProjectionMatrixInverse, STATE_MVP_MATRIX_INVTRANS);
246 MATRIX(gl_ModelViewProjectionMatrixTranspose, STATE_MVP_MATRIX);
247 MATRIX(gl_ModelViewProjectionMatrixInverseTranspose, STATE_MVP_MATRIX_INVERSE);
248 
249 MATRIX(gl_TextureMatrix, STATE_TEXTURE_MATRIX_TRANSPOSE);
250 MATRIX(gl_TextureMatrixInverse, STATE_TEXTURE_MATRIX_INVTRANS);
251 MATRIX(gl_TextureMatrixTranspose, STATE_TEXTURE_MATRIX);
252 MATRIX(gl_TextureMatrixInverseTranspose, STATE_TEXTURE_MATRIX_INVERSE);
253 
254 static const struct gl_builtin_uniform_element gl_NormalMatrix_elements[] = {
255    { NULL, { STATE_MODELVIEW_MATRIX_INVERSE, 0, 0, 0},
256      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z) },
257    { NULL, { STATE_MODELVIEW_MATRIX_INVERSE, 0, 1, 1},
258      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z) },
259    { NULL, { STATE_MODELVIEW_MATRIX_INVERSE, 0, 2, 2},
260      MAKE_SWIZZLE4(SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_Z) },
261 };
262 
263 #undef MATRIX
264 
265 #define STATEVAR(name) {#name, name ## _elements, ARRAY_SIZE(name ## _elements)}
266 
267 static const struct gl_builtin_uniform_desc _mesa_builtin_uniform_desc[] = {
268    STATEVAR(gl_NumSamples),
269    STATEVAR(gl_DepthRange),
270    STATEVAR(gl_ClipPlane),
271    STATEVAR(gl_Point),
272    STATEVAR(gl_FrontMaterial),
273    STATEVAR(gl_BackMaterial),
274    STATEVAR(gl_LightSource),
275    STATEVAR(gl_LightModel),
276    STATEVAR(gl_FrontLightModelProduct),
277    STATEVAR(gl_BackLightModelProduct),
278    STATEVAR(gl_FrontLightProduct),
279    STATEVAR(gl_BackLightProduct),
280    STATEVAR(gl_TextureEnvColor),
281    STATEVAR(gl_EyePlaneS),
282    STATEVAR(gl_EyePlaneT),
283    STATEVAR(gl_EyePlaneR),
284    STATEVAR(gl_EyePlaneQ),
285    STATEVAR(gl_ObjectPlaneS),
286    STATEVAR(gl_ObjectPlaneT),
287    STATEVAR(gl_ObjectPlaneR),
288    STATEVAR(gl_ObjectPlaneQ),
289    STATEVAR(gl_Fog),
290 
291    STATEVAR(gl_ModelViewMatrix),
292    STATEVAR(gl_ModelViewMatrixInverse),
293    STATEVAR(gl_ModelViewMatrixTranspose),
294    STATEVAR(gl_ModelViewMatrixInverseTranspose),
295 
296    STATEVAR(gl_ProjectionMatrix),
297    STATEVAR(gl_ProjectionMatrixInverse),
298    STATEVAR(gl_ProjectionMatrixTranspose),
299    STATEVAR(gl_ProjectionMatrixInverseTranspose),
300 
301    STATEVAR(gl_ModelViewProjectionMatrix),
302    STATEVAR(gl_ModelViewProjectionMatrixInverse),
303    STATEVAR(gl_ModelViewProjectionMatrixTranspose),
304    STATEVAR(gl_ModelViewProjectionMatrixInverseTranspose),
305 
306    STATEVAR(gl_TextureMatrix),
307    STATEVAR(gl_TextureMatrixInverse),
308    STATEVAR(gl_TextureMatrixTranspose),
309    STATEVAR(gl_TextureMatrixInverseTranspose),
310 
311    STATEVAR(gl_NormalMatrix),
312    STATEVAR(gl_NormalScale),
313 
314    STATEVAR(gl_FogParamsOptimizedMESA),
315 
316    STATEVAR(gl_CurrentAttribFrag0MESA),
317    STATEVAR(gl_CurrentAttribFrag1MESA),
318    STATEVAR(gl_CurrentAttribFrag2MESA),
319    STATEVAR(gl_CurrentAttribFrag3MESA),
320    STATEVAR(gl_CurrentAttribFrag4MESA),
321    STATEVAR(gl_CurrentAttribFrag5MESA),
322    STATEVAR(gl_CurrentAttribFrag6MESA),
323    STATEVAR(gl_CurrentAttribFrag7MESA),
324    STATEVAR(gl_CurrentAttribFrag8MESA),
325    STATEVAR(gl_CurrentAttribFrag9MESA),
326    STATEVAR(gl_CurrentAttribFrag10MESA),
327    STATEVAR(gl_CurrentAttribFrag11MESA),
328    STATEVAR(gl_CurrentAttribFrag12MESA),
329    STATEVAR(gl_CurrentAttribFrag13MESA),
330    STATEVAR(gl_CurrentAttribFrag14MESA),
331    STATEVAR(gl_CurrentAttribFrag15MESA),
332    STATEVAR(gl_CurrentAttribFrag16MESA),
333    STATEVAR(gl_CurrentAttribFrag17MESA),
334    STATEVAR(gl_CurrentAttribFrag18MESA),
335    STATEVAR(gl_CurrentAttribFrag19MESA),
336    STATEVAR(gl_CurrentAttribFrag20MESA),
337    STATEVAR(gl_CurrentAttribFrag21MESA),
338    STATEVAR(gl_CurrentAttribFrag22MESA),
339    STATEVAR(gl_CurrentAttribFrag23MESA),
340    STATEVAR(gl_CurrentAttribFrag24MESA),
341    STATEVAR(gl_CurrentAttribFrag25MESA),
342    STATEVAR(gl_CurrentAttribFrag26MESA),
343    STATEVAR(gl_CurrentAttribFrag27MESA),
344    STATEVAR(gl_CurrentAttribFrag28MESA),
345    STATEVAR(gl_CurrentAttribFrag29MESA),
346    STATEVAR(gl_CurrentAttribFrag30MESA),
347    STATEVAR(gl_CurrentAttribFrag31MESA),
348 
349    {NULL, NULL, 0}
350 };
351 
352 
353 namespace {
354 
355 /**
356  * Data structure that accumulates fields for the gl_PerVertex interface
357  * block.
358  */
359 class per_vertex_accumulator
360 {
361 public:
362    per_vertex_accumulator();
363    void add_field(int slot, const glsl_type *type, int precision,
364                   const char *name, enum glsl_interp_mode interp);
365    const glsl_type *construct_interface_instance() const;
366 
367 private:
368    glsl_struct_field fields[14];
369    unsigned num_fields;
370 };
371 
372 
per_vertex_accumulator()373 per_vertex_accumulator::per_vertex_accumulator()
374    : fields(),
375      num_fields(0)
376 {
377 }
378 
379 
380 void
add_field(int slot,const glsl_type * type,int precision,const char * name,enum glsl_interp_mode interp)381 per_vertex_accumulator::add_field(int slot, const glsl_type *type,
382                                   int precision, const char *name,
383                                   enum glsl_interp_mode interp)
384 {
385    assert(this->num_fields < ARRAY_SIZE(this->fields));
386    this->fields[this->num_fields].type = type;
387    this->fields[this->num_fields].name = name;
388    this->fields[this->num_fields].matrix_layout = GLSL_MATRIX_LAYOUT_INHERITED;
389    this->fields[this->num_fields].location = slot;
390    this->fields[this->num_fields].offset = -1;
391    this->fields[this->num_fields].interpolation = interp;
392    this->fields[this->num_fields].centroid = 0;
393    this->fields[this->num_fields].sample = 0;
394    this->fields[this->num_fields].patch = 0;
395    this->fields[this->num_fields].precision = precision;
396    this->fields[this->num_fields].memory_read_only = 0;
397    this->fields[this->num_fields].memory_write_only = 0;
398    this->fields[this->num_fields].memory_coherent = 0;
399    this->fields[this->num_fields].memory_volatile = 0;
400    this->fields[this->num_fields].memory_restrict = 0;
401    this->fields[this->num_fields].image_format = PIPE_FORMAT_NONE;
402    this->fields[this->num_fields].explicit_xfb_buffer = 0;
403    this->fields[this->num_fields].xfb_buffer = -1;
404    this->fields[this->num_fields].xfb_stride = -1;
405    this->num_fields++;
406 }
407 
408 
409 const glsl_type *
construct_interface_instance() const410 per_vertex_accumulator::construct_interface_instance() const
411 {
412    return glsl_interface_type(this->fields, this->num_fields,
413                               GLSL_INTERFACE_PACKING_STD140,
414                               false,
415                               "gl_PerVertex");
416 }
417 
418 
419 class builtin_variable_generator
420 {
421 public:
422    builtin_variable_generator(exec_list *instructions,
423                               struct _mesa_glsl_parse_state *state);
424    void generate_constants();
425    void generate_uniforms();
426    void generate_special_vars();
427    void generate_vs_special_vars();
428    void generate_tcs_special_vars();
429    void generate_tes_special_vars();
430    void generate_gs_special_vars();
431    void generate_fs_special_vars();
432    void generate_cs_special_vars();
433    void generate_varyings();
434 
435 private:
array(const glsl_type * base,unsigned elements)436    const glsl_type *array(const glsl_type *base, unsigned elements)
437    {
438       return glsl_array_type(base, elements, 0);
439    }
440 
type(const char * name)441    const glsl_type *type(const char *name)
442    {
443       return symtab->get_type(name);
444    }
445 
add_input(int slot,const glsl_type * type,int precision,const char * name,enum glsl_interp_mode interp=INTERP_MODE_NONE)446    ir_variable *add_input(int slot, const glsl_type *type, int precision,
447                           const char *name,
448                           enum glsl_interp_mode interp = INTERP_MODE_NONE)
449    {
450       return add_variable(name, type, precision, ir_var_shader_in, slot, interp);
451    }
452 
add_input(int slot,const glsl_type * type,const char * name,enum glsl_interp_mode interp=INTERP_MODE_NONE)453    ir_variable *add_input(int slot, const glsl_type *type, const char *name,
454                           enum glsl_interp_mode interp = INTERP_MODE_NONE)
455    {
456       return add_input(slot, type, GLSL_PRECISION_NONE, name, interp);
457    }
458 
add_output(int slot,const glsl_type * type,int precision,const char * name)459    ir_variable *add_output(int slot, const glsl_type *type, int precision,
460                            const char *name)
461    {
462       return add_variable(name, type, precision, ir_var_shader_out, slot);
463    }
464 
add_output(int slot,const glsl_type * type,const char * name)465    ir_variable *add_output(int slot, const glsl_type *type, const char *name)
466    {
467       return add_output(slot, type, GLSL_PRECISION_NONE, name);
468    }
469 
add_index_output(int slot,int index,const glsl_type * type,int precision,const char * name)470    ir_variable *add_index_output(int slot, int index, const glsl_type *type,
471                                  int precision, const char *name)
472    {
473       return add_index_variable(name, type, precision, ir_var_shader_out, slot,
474                                 index);
475    }
476 
add_system_value(int slot,const glsl_type * type,int precision,const char * name)477    ir_variable *add_system_value(int slot, const glsl_type *type, int precision,
478                                  const char *name)
479    {
480       return add_variable(name, type, precision, ir_var_system_value, slot);
481    }
add_system_value(int slot,const glsl_type * type,const char * name)482    ir_variable *add_system_value(int slot, const glsl_type *type,
483                                  const char *name)
484    {
485       return add_system_value(slot, type, GLSL_PRECISION_NONE, name);
486    }
487 
488    ir_variable *add_variable(const char *name, const glsl_type *type,
489                              int precision, enum ir_variable_mode mode,
490                              int slot, enum glsl_interp_mode interp = INTERP_MODE_NONE);
491    ir_variable *add_index_variable(const char *name, const glsl_type *type,
492                                    int precision, enum ir_variable_mode mode,
493                                    int slot, int index);
494    ir_variable *add_uniform(const glsl_type *type, int precision,
495                             const char *name);
add_uniform(const glsl_type * type,const char * name)496    ir_variable *add_uniform(const glsl_type *type, const char *name)
497    {
498       return add_uniform(type, GLSL_PRECISION_NONE, name);
499    }
500    ir_variable *add_const(const char *name, int precision, int value);
add_const(const char * name,int value)501    ir_variable *add_const(const char *name, int value)
502    {
503       return add_const(name, GLSL_PRECISION_MEDIUM, value);
504    }
505    ir_variable *add_const_ivec3(const char *name, int x, int y, int z);
506    void add_varying(int slot, const glsl_type *type, int precision,
507                     const char *name,
508                     enum glsl_interp_mode interp  = INTERP_MODE_NONE);
add_varying(int slot,const glsl_type * type,const char * name,enum glsl_interp_mode interp=INTERP_MODE_NONE)509    void add_varying(int slot, const glsl_type *type, const char *name,
510                     enum glsl_interp_mode interp = INTERP_MODE_NONE)
511    {
512       add_varying(slot, type, GLSL_PRECISION_NONE, name, interp);
513    }
514 
515    exec_list * const instructions;
516    struct _mesa_glsl_parse_state * const state;
517    glsl_symbol_table * const symtab;
518 
519    /**
520     * True if compatibility-profile-only variables should be included.  (In
521     * desktop GL, these are always included when the GLSL version is 1.30 and
522     * or below).
523     */
524    const bool compatibility;
525 
526    const glsl_type * const bool_t;
527    const glsl_type * const int_t;
528    const glsl_type * const uint_t;
529    const glsl_type * const uint64_t;
530    const glsl_type * const float_t;
531    const glsl_type * const vec2_t;
532    const glsl_type * const vec3_t;
533    const glsl_type * const vec4_t;
534    const glsl_type * const uvec3_t;
535    const glsl_type * const uvec4_t;
536    const glsl_type * const mat3_t;
537    const glsl_type * const mat4_t;
538 
539    per_vertex_accumulator per_vertex_in;
540    per_vertex_accumulator per_vertex_out;
541 };
542 
543 
builtin_variable_generator(exec_list * instructions,struct _mesa_glsl_parse_state * state)544 builtin_variable_generator::builtin_variable_generator(
545    exec_list *instructions, struct _mesa_glsl_parse_state *state)
546    : instructions(instructions), state(state), symtab(state->symbols),
547      compatibility(state->compat_shader || state->ARB_compatibility_enable),
548      bool_t(&glsl_type_builtin_bool), int_t(&glsl_type_builtin_int),
549      uint_t(&glsl_type_builtin_uint),
550      uint64_t(&glsl_type_builtin_uint64_t),
551      float_t(&glsl_type_builtin_float), vec2_t(&glsl_type_builtin_vec2),
552      vec3_t(&glsl_type_builtin_vec3), vec4_t(&glsl_type_builtin_vec4),
553      uvec3_t(&glsl_type_builtin_uvec3), uvec4_t(&glsl_type_builtin_uvec4),
554      mat3_t(&glsl_type_builtin_mat3), mat4_t(&glsl_type_builtin_mat4)
555 {
556 }
557 
558 ir_variable *
add_index_variable(const char * name,const glsl_type * type,int precision,enum ir_variable_mode mode,int slot,int index)559 builtin_variable_generator::add_index_variable(const char *name,
560                                                const glsl_type *type,
561                                                int precision,
562                                                enum ir_variable_mode mode,
563                                                int slot, int index)
564 {
565    ir_variable *var = new(symtab) ir_variable(type, name, mode);
566    var->data.how_declared = ir_var_declared_implicitly;
567 
568    switch (var->data.mode) {
569    case ir_var_auto:
570    case ir_var_shader_in:
571    case ir_var_uniform:
572    case ir_var_system_value:
573       var->data.read_only = true;
574       break;
575    case ir_var_shader_out:
576    case ir_var_shader_storage:
577       break;
578    default:
579       /* The only variables that are added using this function should be
580        * uniforms, shader storage, shader inputs, and shader outputs, constants
581        * (which use ir_var_auto), and system values.
582        */
583       assert(0);
584       break;
585    }
586 
587    var->data.location = slot;
588    var->data.explicit_location = (slot >= 0);
589    var->data.explicit_index = 1;
590    var->data.index = index;
591 
592    if (state->es_shader)
593       var->data.precision = precision;
594 
595    /* Once the variable is created an initialized, add it to the symbol table
596     * and add the declaration to the IR stream.
597     */
598    instructions->push_tail(var);
599 
600    symtab->add_variable(var);
601    return var;
602 }
603 
604 ir_variable *
add_variable(const char * name,const glsl_type * type,int precision,enum ir_variable_mode mode,int slot,enum glsl_interp_mode interp)605 builtin_variable_generator::add_variable(const char *name,
606                                          const glsl_type *type,
607                                          int precision,
608                                          enum ir_variable_mode mode, int slot,
609                                          enum glsl_interp_mode interp)
610 {
611    ir_variable *var = new(symtab) ir_variable(type, name, mode);
612    var->data.how_declared = ir_var_declared_implicitly;
613 
614    switch (var->data.mode) {
615    case ir_var_auto:
616    case ir_var_shader_in:
617    case ir_var_uniform:
618    case ir_var_system_value:
619       var->data.read_only = true;
620       break;
621    case ir_var_shader_out:
622    case ir_var_shader_storage:
623       break;
624    default:
625       /* The only variables that are added using this function should be
626        * uniforms, shader storage, shader inputs, and shader outputs, constants
627        * (which use ir_var_auto), and system values.
628        */
629       assert(0);
630       break;
631    }
632 
633    var->data.location = slot;
634    var->data.explicit_location = (slot >= 0);
635    var->data.explicit_index = 0;
636    var->data.interpolation = interp;
637 
638    if (state->es_shader)
639       var->data.precision = precision;
640 
641    /* Once the variable is created an initialized, add it to the symbol table
642     * and add the declaration to the IR stream.
643     */
644    instructions->push_tail(var);
645 
646    symtab->add_variable(var);
647    return var;
648 }
649 
650 extern "C" const struct gl_builtin_uniform_desc *
_mesa_glsl_get_builtin_uniform_desc(const char * name)651 _mesa_glsl_get_builtin_uniform_desc(const char *name)
652 {
653    for (unsigned i = 0; _mesa_builtin_uniform_desc[i].name != NULL; i++) {
654       if (strcmp(_mesa_builtin_uniform_desc[i].name, name) == 0) {
655          return &_mesa_builtin_uniform_desc[i];
656       }
657    }
658    return NULL;
659 }
660 
661 ir_variable *
add_uniform(const glsl_type * type,int precision,const char * name)662 builtin_variable_generator::add_uniform(const glsl_type *type,
663                                         int precision,
664                                         const char *name)
665 {
666    ir_variable *const uni =
667       add_variable(name, type, precision, ir_var_uniform, -1);
668 
669    const struct gl_builtin_uniform_desc* const statevar =
670       _mesa_glsl_get_builtin_uniform_desc(name);
671    assert(statevar != NULL);
672 
673    const unsigned array_count = glsl_type_is_array(type) ? type->length : 1;
674 
675    ir_state_slot *slots =
676       uni->allocate_state_slots(array_count * statevar->num_elements);
677 
678    for (unsigned a = 0; a < array_count; a++) {
679       for (unsigned j = 0; j < statevar->num_elements; j++) {
680 	 const struct gl_builtin_uniform_element *element =
681 	    &statevar->elements[j];
682 
683 	 memcpy(slots->tokens, element->tokens, sizeof(element->tokens));
684 	 if (glsl_type_is_array(type))
685             slots->tokens[1] = a;
686 
687 	 slots++;
688       }
689    }
690 
691    return uni;
692 }
693 
694 
695 ir_variable *
add_const(const char * name,int precision,int value)696 builtin_variable_generator::add_const(const char *name, int precision,
697                                       int value)
698 {
699    ir_variable *const var = add_variable(name, &glsl_type_builtin_int,
700                                          precision, ir_var_auto, -1);
701    var->constant_value = new(var) ir_constant(value);
702    var->constant_initializer = new(var) ir_constant(value);
703    var->data.has_initializer = true;
704    return var;
705 }
706 
707 
708 ir_variable *
add_const_ivec3(const char * name,int x,int y,int z)709 builtin_variable_generator::add_const_ivec3(const char *name, int x, int y,
710                                             int z)
711 {
712    ir_variable *const var = add_variable(name, &glsl_type_builtin_ivec3,
713                                          GLSL_PRECISION_HIGH,
714                                          ir_var_auto, -1);
715    ir_constant_data data;
716    memset(&data, 0, sizeof(data));
717    data.i[0] = x;
718    data.i[1] = y;
719    data.i[2] = z;
720    var->constant_value = new(var) ir_constant(&glsl_type_builtin_ivec3, &data);
721    var->constant_initializer =
722       new(var) ir_constant(&glsl_type_builtin_ivec3, &data);
723    var->data.has_initializer = true;
724    return var;
725 }
726 
727 
728 void
generate_constants()729 builtin_variable_generator::generate_constants()
730 {
731    add_const("gl_MaxVertexAttribs", state->Const.MaxVertexAttribs);
732    add_const("gl_MaxVertexTextureImageUnits",
733              state->Const.MaxVertexTextureImageUnits);
734    add_const("gl_MaxCombinedTextureImageUnits",
735              state->Const.MaxCombinedTextureImageUnits);
736    add_const("gl_MaxTextureImageUnits", state->Const.MaxTextureImageUnits);
737    add_const("gl_MaxDrawBuffers", state->Const.MaxDrawBuffers);
738 
739    /* Max uniforms/varyings: GLSL ES counts these in units of vectors; desktop
740     * GL counts them in units of "components" or "floats" and also in units
741     * of vectors since GL 4.1
742     */
743    if (!state->es_shader) {
744       add_const("gl_MaxFragmentUniformComponents",
745                 state->Const.MaxFragmentUniformComponents);
746       add_const("gl_MaxVertexUniformComponents",
747                 state->Const.MaxVertexUniformComponents);
748    }
749 
750    if (state->is_version(410, 100)) {
751       add_const("gl_MaxVertexUniformVectors",
752                 state->Const.MaxVertexUniformComponents / 4);
753       add_const("gl_MaxFragmentUniformVectors",
754                 state->Const.MaxFragmentUniformComponents / 4);
755 
756       /* In GLSL ES 3.00, gl_MaxVaryingVectors was split out to separate
757        * vertex and fragment shader constants.
758        */
759       if (state->is_version(0, 300)) {
760          add_const("gl_MaxVertexOutputVectors",
761                    state->consts->Program[MESA_SHADER_VERTEX].MaxOutputComponents / 4);
762          add_const("gl_MaxFragmentInputVectors",
763                    state->consts->Program[MESA_SHADER_FRAGMENT].MaxInputComponents / 4);
764       } else {
765          add_const("gl_MaxVaryingVectors",
766                    state->consts->MaxVarying);
767       }
768 
769       /* EXT_blend_func_extended brings a built in constant
770        * for determining number of dual source draw buffers
771        */
772       if (state->EXT_blend_func_extended_enable) {
773          add_const("gl_MaxDualSourceDrawBuffersEXT",
774                    state->Const.MaxDualSourceDrawBuffers);
775       }
776    }
777 
778    /* gl_MaxVaryingFloats was deprecated in GLSL 1.30+, and was moved to
779     * compat profile in GLSL 4.20. GLSL ES never supported this constant.
780     */
781    if (compatibility || !state->is_version(420, 100))  {
782       add_const("gl_MaxVaryingFloats", state->consts->MaxVarying * 4);
783    }
784 
785    /* Texel offsets were introduced in ARB_shading_language_420pack (which
786     * requires desktop GLSL version 130), and adopted into desktop GLSL
787     * version 4.20 and GLSL ES version 3.00.
788     */
789    if ((state->is_version(130, 0) &&
790         state->ARB_shading_language_420pack_enable) ||
791       state->is_version(420, 300)) {
792       add_const("gl_MinProgramTexelOffset",
793                 state->Const.MinProgramTexelOffset);
794       add_const("gl_MaxProgramTexelOffset",
795                 state->Const.MaxProgramTexelOffset);
796    }
797 
798    if (state->has_clip_distance()) {
799       add_const("gl_MaxClipDistances", state->Const.MaxClipPlanes);
800    }
801    if (state->is_version(130, 0)) {
802       add_const("gl_MaxVaryingComponents", state->consts->MaxVarying * 4);
803    }
804    if (state->has_cull_distance()) {
805       add_const("gl_MaxCullDistances", state->Const.MaxClipPlanes);
806       add_const("gl_MaxCombinedClipAndCullDistances",
807                 state->Const.MaxClipPlanes);
808    }
809 
810    if (state->has_geometry_shader()) {
811       add_const("gl_MaxVertexOutputComponents",
812                 state->Const.MaxVertexOutputComponents);
813       add_const("gl_MaxGeometryInputComponents",
814                 state->Const.MaxGeometryInputComponents);
815       add_const("gl_MaxGeometryOutputComponents",
816                 state->Const.MaxGeometryOutputComponents);
817       add_const("gl_MaxFragmentInputComponents",
818                 state->Const.MaxFragmentInputComponents);
819       add_const("gl_MaxGeometryTextureImageUnits",
820                 state->Const.MaxGeometryTextureImageUnits);
821       add_const("gl_MaxGeometryOutputVertices",
822                 state->Const.MaxGeometryOutputVertices);
823       add_const("gl_MaxGeometryTotalOutputComponents",
824                 state->Const.MaxGeometryTotalOutputComponents);
825       add_const("gl_MaxGeometryUniformComponents",
826                 state->Const.MaxGeometryUniformComponents);
827 
828       /* Note: the GLSL 1.50-4.40 specs require
829        * gl_MaxGeometryVaryingComponents to be present, and to be at least 64.
830        * But they do not define what it means (and there does not appear to be
831        * any corresponding constant in the GL specs).  However,
832        * ARB_geometry_shader4 defines MAX_GEOMETRY_VARYING_COMPONENTS_ARB to
833        * be the maximum number of components available for use as geometry
834        * outputs.  So we assume this is a synonym for
835        * gl_MaxGeometryOutputComponents.
836        */
837       add_const("gl_MaxGeometryVaryingComponents",
838                 state->Const.MaxGeometryOutputComponents);
839    }
840 
841    if (compatibility) {
842       /* Note: gl_MaxLights stopped being listed as an explicit constant in
843        * GLSL 1.30, however it continues to be referred to (as a minimum size
844        * for compatibility-mode uniforms) all the way up through GLSL 4.30, so
845        * this seems like it was probably an oversight.
846        */
847       add_const("gl_MaxLights", state->Const.MaxLights);
848 
849       add_const("gl_MaxClipPlanes", state->Const.MaxClipPlanes);
850 
851       /* Note: gl_MaxTextureUnits wasn't made compatibility-only until GLSL
852        * 1.50, however this seems like it was probably an oversight.
853        */
854       add_const("gl_MaxTextureUnits", state->Const.MaxTextureUnits);
855 
856       /* Note: gl_MaxTextureCoords was left out of GLSL 1.40, but it was
857        * re-introduced in GLSL 1.50, so this seems like it was probably an
858        * oversight.
859        */
860       add_const("gl_MaxTextureCoords", state->Const.MaxTextureCoords);
861    }
862 
863    if (state->has_atomic_counters()) {
864       add_const("gl_MaxVertexAtomicCounters",
865                 state->Const.MaxVertexAtomicCounters);
866       add_const("gl_MaxFragmentAtomicCounters",
867                 state->Const.MaxFragmentAtomicCounters);
868       add_const("gl_MaxCombinedAtomicCounters",
869                 state->Const.MaxCombinedAtomicCounters);
870       add_const("gl_MaxAtomicCounterBindings",
871                 state->Const.MaxAtomicBufferBindings);
872 
873       if (state->has_geometry_shader()) {
874          add_const("gl_MaxGeometryAtomicCounters",
875                    state->Const.MaxGeometryAtomicCounters);
876       }
877       if (state->is_version(110, 320)) {
878          add_const("gl_MaxTessControlAtomicCounters",
879                    state->Const.MaxTessControlAtomicCounters);
880          add_const("gl_MaxTessEvaluationAtomicCounters",
881                    state->Const.MaxTessEvaluationAtomicCounters);
882       }
883    }
884 
885    if (state->is_version(420, 310)) {
886       add_const("gl_MaxVertexAtomicCounterBuffers",
887                 state->Const.MaxVertexAtomicCounterBuffers);
888       add_const("gl_MaxFragmentAtomicCounterBuffers",
889                 state->Const.MaxFragmentAtomicCounterBuffers);
890       add_const("gl_MaxCombinedAtomicCounterBuffers",
891                 state->Const.MaxCombinedAtomicCounterBuffers);
892       add_const("gl_MaxAtomicCounterBufferSize",
893                 state->Const.MaxAtomicCounterBufferSize);
894 
895       if (state->has_geometry_shader()) {
896          add_const("gl_MaxGeometryAtomicCounterBuffers",
897                    state->Const.MaxGeometryAtomicCounterBuffers);
898       }
899       if (state->is_version(110, 320)) {
900          add_const("gl_MaxTessControlAtomicCounterBuffers",
901                    state->Const.MaxTessControlAtomicCounterBuffers);
902          add_const("gl_MaxTessEvaluationAtomicCounterBuffers",
903                    state->Const.MaxTessEvaluationAtomicCounterBuffers);
904       }
905    }
906 
907    if (state->is_version(430, 310) || state->ARB_compute_shader_enable) {
908       add_const("gl_MaxComputeAtomicCounterBuffers",
909                 state->Const.MaxComputeAtomicCounterBuffers);
910       add_const("gl_MaxComputeAtomicCounters",
911                 state->Const.MaxComputeAtomicCounters);
912       add_const("gl_MaxComputeImageUniforms",
913                 state->Const.MaxComputeImageUniforms);
914       add_const("gl_MaxComputeTextureImageUnits",
915                 state->Const.MaxComputeTextureImageUnits);
916       add_const("gl_MaxComputeUniformComponents",
917                 state->Const.MaxComputeUniformComponents);
918 
919       add_const_ivec3("gl_MaxComputeWorkGroupCount",
920                       state->Const.MaxComputeWorkGroupCount[0],
921                       state->Const.MaxComputeWorkGroupCount[1],
922                       state->Const.MaxComputeWorkGroupCount[2]);
923       add_const_ivec3("gl_MaxComputeWorkGroupSize",
924                       state->Const.MaxComputeWorkGroupSize[0],
925                       state->Const.MaxComputeWorkGroupSize[1],
926                       state->Const.MaxComputeWorkGroupSize[2]);
927 
928       /* From the GLSL 4.40 spec, section 7.1 (Built-In Language Variables):
929        *
930        *     The built-in constant gl_WorkGroupSize is a compute-shader
931        *     constant containing the local work-group size of the shader.  The
932        *     size of the work group in the X, Y, and Z dimensions is stored in
933        *     the x, y, and z components.  The constants values in
934        *     gl_WorkGroupSize will match those specified in the required
935        *     local_size_x, local_size_y, and local_size_z layout qualifiers
936        *     for the current shader.  This is a constant so that it can be
937        *     used to size arrays of memory that can be shared within the local
938        *     work group.  It is a compile-time error to use gl_WorkGroupSize
939        *     in a shader that does not declare a fixed local group size, or
940        *     before that shader has declared a fixed local group size, using
941        *     local_size_x, local_size_y, and local_size_z.
942        *
943        * To prevent the shader from trying to refer to gl_WorkGroupSize before
944        * the layout declaration, we don't define it here.  Intead we define it
945        * in ast_cs_input_layout::hir().
946        */
947    }
948 
949    if (state->has_enhanced_layouts()) {
950       add_const("gl_MaxTransformFeedbackBuffers",
951                 state->Const.MaxTransformFeedbackBuffers);
952       add_const("gl_MaxTransformFeedbackInterleavedComponents",
953                 state->Const.MaxTransformFeedbackInterleavedComponents);
954    }
955 
956    if (state->has_shader_image_load_store()) {
957       add_const("gl_MaxImageUnits",
958                 state->Const.MaxImageUnits);
959       add_const("gl_MaxVertexImageUniforms",
960                 state->Const.MaxVertexImageUniforms);
961       add_const("gl_MaxFragmentImageUniforms",
962                 state->Const.MaxFragmentImageUniforms);
963       add_const("gl_MaxCombinedImageUniforms",
964                 state->Const.MaxCombinedImageUniforms);
965 
966       if (state->has_geometry_shader()) {
967          add_const("gl_MaxGeometryImageUniforms",
968                    state->Const.MaxGeometryImageUniforms);
969       }
970 
971       if (!state->es_shader) {
972          add_const("gl_MaxCombinedImageUnitsAndFragmentOutputs",
973                    state->Const.MaxCombinedShaderOutputResources);
974          add_const("gl_MaxImageSamples",
975                    state->Const.MaxImageSamples);
976       }
977 
978       if (state->has_tessellation_shader()) {
979          add_const("gl_MaxTessControlImageUniforms",
980                    state->Const.MaxTessControlImageUniforms);
981          add_const("gl_MaxTessEvaluationImageUniforms",
982                    state->Const.MaxTessEvaluationImageUniforms);
983       }
984    }
985 
986    if (state->is_version(440, 310) ||
987        state->ARB_ES3_1_compatibility_enable) {
988       add_const("gl_MaxCombinedShaderOutputResources",
989                 state->Const.MaxCombinedShaderOutputResources);
990    }
991 
992    if (state->is_version(410, 0) ||
993        state->ARB_viewport_array_enable ||
994        state->OES_viewport_array_enable) {
995       add_const("gl_MaxViewports", GLSL_PRECISION_HIGH,
996                 state->Const.MaxViewports);
997    }
998 
999    if (state->has_tessellation_shader()) {
1000       add_const("gl_MaxPatchVertices", state->Const.MaxPatchVertices);
1001       add_const("gl_MaxTessGenLevel", state->Const.MaxTessGenLevel);
1002       add_const("gl_MaxTessControlInputComponents", state->Const.MaxTessControlInputComponents);
1003       add_const("gl_MaxTessControlOutputComponents", state->Const.MaxTessControlOutputComponents);
1004       add_const("gl_MaxTessControlTextureImageUnits", state->Const.MaxTessControlTextureImageUnits);
1005       add_const("gl_MaxTessEvaluationInputComponents", state->Const.MaxTessEvaluationInputComponents);
1006       add_const("gl_MaxTessEvaluationOutputComponents", state->Const.MaxTessEvaluationOutputComponents);
1007       add_const("gl_MaxTessEvaluationTextureImageUnits", state->Const.MaxTessEvaluationTextureImageUnits);
1008       add_const("gl_MaxTessPatchComponents", state->Const.MaxTessPatchComponents);
1009       add_const("gl_MaxTessControlTotalOutputComponents", state->Const.MaxTessControlTotalOutputComponents);
1010       add_const("gl_MaxTessControlUniformComponents", state->Const.MaxTessControlUniformComponents);
1011       add_const("gl_MaxTessEvaluationUniformComponents", state->Const.MaxTessEvaluationUniformComponents);
1012    }
1013 
1014    if (state->is_version(450, 320) ||
1015        state->OES_sample_variables_enable ||
1016        state->ARB_ES3_1_compatibility_enable)
1017       add_const("gl_MaxSamples", state->Const.MaxSamples);
1018 }
1019 
1020 
1021 /**
1022  * Generate uniform variables (which exist in all types of shaders).
1023  */
1024 void
generate_uniforms()1025 builtin_variable_generator::generate_uniforms()
1026 {
1027    if (state->is_version(400, 320) ||
1028        state->ARB_sample_shading_enable ||
1029        state->OES_sample_variables_enable)
1030       add_uniform(int_t, GLSL_PRECISION_LOW, "gl_NumSamples");
1031    add_uniform(type("gl_DepthRangeParameters"), "gl_DepthRange");
1032 
1033    for (unsigned i = 0; i < VARYING_SLOT_VAR0; i++) {
1034       char name[128];
1035 
1036       snprintf(name, sizeof(name), "gl_CurrentAttribFrag%uMESA", i);
1037       add_uniform(vec4_t, name);
1038    }
1039 
1040    if (compatibility) {
1041       add_uniform(mat4_t, "gl_ModelViewMatrix");
1042       add_uniform(mat4_t, "gl_ProjectionMatrix");
1043       add_uniform(mat4_t, "gl_ModelViewProjectionMatrix");
1044       add_uniform(mat3_t, "gl_NormalMatrix");
1045       add_uniform(mat4_t, "gl_ModelViewMatrixInverse");
1046       add_uniform(mat4_t, "gl_ProjectionMatrixInverse");
1047       add_uniform(mat4_t, "gl_ModelViewProjectionMatrixInverse");
1048       add_uniform(mat4_t, "gl_ModelViewMatrixTranspose");
1049       add_uniform(mat4_t, "gl_ProjectionMatrixTranspose");
1050       add_uniform(mat4_t, "gl_ModelViewProjectionMatrixTranspose");
1051       add_uniform(mat4_t, "gl_ModelViewMatrixInverseTranspose");
1052       add_uniform(mat4_t, "gl_ProjectionMatrixInverseTranspose");
1053       add_uniform(mat4_t, "gl_ModelViewProjectionMatrixInverseTranspose");
1054       add_uniform(float_t, "gl_NormalScale");
1055       add_uniform(type("gl_LightModelParameters"), "gl_LightModel");
1056       add_uniform(vec4_t, "gl_FogParamsOptimizedMESA");
1057 
1058       const glsl_type *const mat4_array_type =
1059 	 array(mat4_t, state->Const.MaxTextureCoords);
1060       add_uniform(mat4_array_type, "gl_TextureMatrix");
1061       add_uniform(mat4_array_type, "gl_TextureMatrixInverse");
1062       add_uniform(mat4_array_type, "gl_TextureMatrixTranspose");
1063       add_uniform(mat4_array_type, "gl_TextureMatrixInverseTranspose");
1064 
1065       add_uniform(array(vec4_t, state->Const.MaxClipPlanes), "gl_ClipPlane");
1066       add_uniform(type("gl_PointParameters"), "gl_Point");
1067 
1068       const glsl_type *const material_parameters_type =
1069 	 type("gl_MaterialParameters");
1070       add_uniform(material_parameters_type, "gl_FrontMaterial");
1071       add_uniform(material_parameters_type, "gl_BackMaterial");
1072 
1073       add_uniform(array(type("gl_LightSourceParameters"),
1074                         state->Const.MaxLights),
1075                   "gl_LightSource");
1076 
1077       const glsl_type *const light_model_products_type =
1078          type("gl_LightModelProducts");
1079       add_uniform(light_model_products_type, "gl_FrontLightModelProduct");
1080       add_uniform(light_model_products_type, "gl_BackLightModelProduct");
1081 
1082       const glsl_type *const light_products_type =
1083          array(type("gl_LightProducts"), state->Const.MaxLights);
1084       add_uniform(light_products_type, "gl_FrontLightProduct");
1085       add_uniform(light_products_type, "gl_BackLightProduct");
1086 
1087       add_uniform(array(vec4_t, state->Const.MaxTextureUnits),
1088                   "gl_TextureEnvColor");
1089 
1090       const glsl_type *const texcoords_vec4 =
1091 	 array(vec4_t, state->Const.MaxTextureCoords);
1092       add_uniform(texcoords_vec4, "gl_EyePlaneS");
1093       add_uniform(texcoords_vec4, "gl_EyePlaneT");
1094       add_uniform(texcoords_vec4, "gl_EyePlaneR");
1095       add_uniform(texcoords_vec4, "gl_EyePlaneQ");
1096       add_uniform(texcoords_vec4, "gl_ObjectPlaneS");
1097       add_uniform(texcoords_vec4, "gl_ObjectPlaneT");
1098       add_uniform(texcoords_vec4, "gl_ObjectPlaneR");
1099       add_uniform(texcoords_vec4, "gl_ObjectPlaneQ");
1100 
1101       add_uniform(type("gl_FogParameters"), "gl_Fog");
1102    }
1103 }
1104 
1105 
1106 /**
1107  * Generate special variables which exist in all shaders.
1108  */
1109 void
generate_special_vars()1110 builtin_variable_generator::generate_special_vars()
1111 {
1112    if (state->ARB_shader_ballot_enable) {
1113       add_system_value(SYSTEM_VALUE_SUBGROUP_SIZE, uint_t, "gl_SubGroupSizeARB");
1114       add_system_value(SYSTEM_VALUE_SUBGROUP_INVOCATION, uint_t, "gl_SubGroupInvocationARB");
1115       add_system_value(SYSTEM_VALUE_SUBGROUP_EQ_MASK, uint64_t, "gl_SubGroupEqMaskARB");
1116       add_system_value(SYSTEM_VALUE_SUBGROUP_GE_MASK, uint64_t, "gl_SubGroupGeMaskARB");
1117       add_system_value(SYSTEM_VALUE_SUBGROUP_GT_MASK, uint64_t, "gl_SubGroupGtMaskARB");
1118       add_system_value(SYSTEM_VALUE_SUBGROUP_LE_MASK, uint64_t, "gl_SubGroupLeMaskARB");
1119       add_system_value(SYSTEM_VALUE_SUBGROUP_LT_MASK, uint64_t, "gl_SubGroupLtMaskARB");
1120    }
1121 
1122    if (state->KHR_shader_subgroup_basic_enable) {
1123       add_system_value(SYSTEM_VALUE_SUBGROUP_SIZE, uint_t, "gl_SubgroupSize");
1124       add_system_value(SYSTEM_VALUE_SUBGROUP_INVOCATION, uint_t, "gl_SubgroupInvocationID");
1125    }
1126 
1127    if (state->KHR_shader_subgroup_ballot_enable) {
1128       add_system_value(SYSTEM_VALUE_SUBGROUP_EQ_MASK, uvec4_t, "gl_SubgroupEqMask");
1129       add_system_value(SYSTEM_VALUE_SUBGROUP_GE_MASK, uvec4_t, "gl_SubgroupGeMask");
1130       add_system_value(SYSTEM_VALUE_SUBGROUP_GT_MASK, uvec4_t, "gl_SubgroupGtMask");
1131       add_system_value(SYSTEM_VALUE_SUBGROUP_LE_MASK, uvec4_t, "gl_SubgroupLeMask");
1132       add_system_value(SYSTEM_VALUE_SUBGROUP_LT_MASK, uvec4_t, "gl_SubgroupLtMask");
1133    }
1134 }
1135 
1136 
1137 /**
1138  * Generate variables which only exist in vertex shaders.
1139  */
1140 void
generate_vs_special_vars()1141 builtin_variable_generator::generate_vs_special_vars()
1142 {
1143    if (state->is_version(130, 300) || state->EXT_gpu_shader4_enable) {
1144       add_system_value(SYSTEM_VALUE_VERTEX_ID, int_t, GLSL_PRECISION_HIGH,
1145                        "gl_VertexID");
1146    }
1147    if (state->is_version(300, 300) && state->OVR_multiview_enable){
1148       add_system_value(SYSTEM_VALUE_VIEW_INDEX, int_t, GLSL_PRECISION_MEDIUM,
1149                       "gl_ViewID_OVR");
1150    }
1151    if (state->is_version(460, 0)) {
1152       add_system_value(SYSTEM_VALUE_BASE_VERTEX, int_t, "gl_BaseVertex");
1153       add_system_value(SYSTEM_VALUE_BASE_INSTANCE, int_t, "gl_BaseInstance");
1154       add_system_value(SYSTEM_VALUE_DRAW_ID, int_t, "gl_DrawID");
1155    }
1156    if (state->EXT_draw_instanced_enable && state->is_version(0, 100))
1157       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, GLSL_PRECISION_HIGH,
1158                        "gl_InstanceIDEXT");
1159 
1160    if (state->ARB_draw_instanced_enable)
1161       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, "gl_InstanceIDARB");
1162 
1163    if (state->ARB_draw_instanced_enable || state->is_version(140, 300) ||
1164        state->EXT_gpu_shader4_enable) {
1165       add_system_value(SYSTEM_VALUE_INSTANCE_ID, int_t, GLSL_PRECISION_HIGH,
1166                        "gl_InstanceID");
1167    }
1168    if (state->ARB_shader_draw_parameters_enable) {
1169       add_system_value(SYSTEM_VALUE_BASE_VERTEX, int_t, "gl_BaseVertexARB");
1170       add_system_value(SYSTEM_VALUE_BASE_INSTANCE, int_t, "gl_BaseInstanceARB");
1171       add_system_value(SYSTEM_VALUE_DRAW_ID, int_t, "gl_DrawIDARB");
1172    }
1173    if (compatibility) {
1174       add_input(VERT_ATTRIB_POS, vec4_t, "gl_Vertex");
1175       add_input(VERT_ATTRIB_NORMAL, vec3_t, "gl_Normal");
1176       add_input(VERT_ATTRIB_COLOR0, vec4_t, "gl_Color");
1177       add_input(VERT_ATTRIB_COLOR1, vec4_t, "gl_SecondaryColor");
1178       add_input(VERT_ATTRIB_TEX0, vec4_t, "gl_MultiTexCoord0");
1179       add_input(VERT_ATTRIB_TEX1, vec4_t, "gl_MultiTexCoord1");
1180       add_input(VERT_ATTRIB_TEX2, vec4_t, "gl_MultiTexCoord2");
1181       add_input(VERT_ATTRIB_TEX3, vec4_t, "gl_MultiTexCoord3");
1182       add_input(VERT_ATTRIB_TEX4, vec4_t, "gl_MultiTexCoord4");
1183       add_input(VERT_ATTRIB_TEX5, vec4_t, "gl_MultiTexCoord5");
1184       add_input(VERT_ATTRIB_TEX6, vec4_t, "gl_MultiTexCoord6");
1185       add_input(VERT_ATTRIB_TEX7, vec4_t, "gl_MultiTexCoord7");
1186       add_input(VERT_ATTRIB_FOG, float_t, "gl_FogCoord");
1187    }
1188 }
1189 
1190 
1191 /**
1192  * Generate variables which only exist in tessellation control shaders.
1193  */
1194 void
generate_tcs_special_vars()1195 builtin_variable_generator::generate_tcs_special_vars()
1196 {
1197    add_system_value(SYSTEM_VALUE_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1198                     "gl_PrimitiveID");
1199    add_system_value(SYSTEM_VALUE_INVOCATION_ID, int_t, GLSL_PRECISION_HIGH,
1200                     "gl_InvocationID");
1201    add_system_value(SYSTEM_VALUE_VERTICES_IN, int_t, GLSL_PRECISION_HIGH,
1202                     "gl_PatchVerticesIn");
1203 
1204    add_output(VARYING_SLOT_TESS_LEVEL_OUTER, array(float_t, 4),
1205               GLSL_PRECISION_HIGH, "gl_TessLevelOuter")->data.patch = 1;
1206    add_output(VARYING_SLOT_TESS_LEVEL_INNER, array(float_t, 2),
1207               GLSL_PRECISION_HIGH, "gl_TessLevelInner")->data.patch = 1;
1208    /* XXX What to do if multiple are flipped on? */
1209    int bbox_slot = state->consts->NoPrimitiveBoundingBoxOutput ? -1 :
1210       VARYING_SLOT_BOUNDING_BOX0;
1211    if (state->EXT_primitive_bounding_box_enable)
1212       add_output(bbox_slot, array(vec4_t, 2), "gl_BoundingBoxEXT")
1213          ->data.patch = 1;
1214    if (state->OES_primitive_bounding_box_enable) {
1215       add_output(bbox_slot, array(vec4_t, 2), GLSL_PRECISION_HIGH,
1216                  "gl_BoundingBoxOES")->data.patch = 1;
1217    }
1218    if (state->is_version(0, 320) || state->ARB_ES3_2_compatibility_enable) {
1219       add_output(bbox_slot, array(vec4_t, 2), GLSL_PRECISION_HIGH,
1220                  "gl_BoundingBox")->data.patch = 1;
1221    }
1222 
1223    /* NOTE: These are completely pointless. Writing these will never go
1224     * anywhere. But the specs demands it. So we add them with a slot of -1,
1225     * which makes the data go nowhere.
1226     */
1227    if (state->NV_viewport_array2_enable) {
1228       add_output(-1, int_t, "gl_Layer");
1229       add_output(-1, int_t, "gl_ViewportIndex");
1230       add_output(-1, array(int_t, 1), "gl_ViewportMask");
1231    }
1232 
1233 }
1234 
1235 
1236 /**
1237  * Generate variables which only exist in tessellation evaluation shaders.
1238  */
1239 void
generate_tes_special_vars()1240 builtin_variable_generator::generate_tes_special_vars()
1241 {
1242    ir_variable *var;
1243 
1244    add_system_value(SYSTEM_VALUE_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1245                     "gl_PrimitiveID");
1246    add_system_value(SYSTEM_VALUE_VERTICES_IN, int_t, GLSL_PRECISION_HIGH,
1247                     "gl_PatchVerticesIn");
1248    add_system_value(SYSTEM_VALUE_TESS_COORD, vec3_t, GLSL_PRECISION_HIGH,
1249                     "gl_TessCoord");
1250    if (this->state->consts->GLSLTessLevelsAsInputs) {
1251       add_input(VARYING_SLOT_TESS_LEVEL_OUTER, array(float_t, 4),
1252                 GLSL_PRECISION_HIGH, "gl_TessLevelOuter")->data.patch = 1;
1253       add_input(VARYING_SLOT_TESS_LEVEL_INNER, array(float_t, 2),
1254                 GLSL_PRECISION_HIGH, "gl_TessLevelInner")->data.patch = 1;
1255    } else {
1256       add_system_value(SYSTEM_VALUE_TESS_LEVEL_OUTER, array(float_t, 4),
1257                        GLSL_PRECISION_HIGH, "gl_TessLevelOuter");
1258       add_system_value(SYSTEM_VALUE_TESS_LEVEL_INNER, array(float_t, 2),
1259                        GLSL_PRECISION_HIGH, "gl_TessLevelInner");
1260    }
1261    if (state->ARB_shader_viewport_layer_array_enable ||
1262        state->NV_viewport_array2_enable) {
1263       var = add_output(VARYING_SLOT_LAYER, int_t, "gl_Layer");
1264       var->data.interpolation = INTERP_MODE_FLAT;
1265       var = add_output(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex");
1266       var->data.interpolation = INTERP_MODE_FLAT;
1267    }
1268    if (state->NV_viewport_array2_enable) {
1269       var = add_output(VARYING_SLOT_VIEWPORT_MASK, array(int_t, 1),
1270                        "gl_ViewportMask");
1271       var->data.interpolation = INTERP_MODE_FLAT;
1272    }
1273 }
1274 
1275 
1276 /**
1277  * Generate variables which only exist in geometry shaders.
1278  */
1279 void
generate_gs_special_vars()1280 builtin_variable_generator::generate_gs_special_vars()
1281 {
1282    ir_variable *var;
1283 
1284    var = add_output(VARYING_SLOT_LAYER, int_t, GLSL_PRECISION_HIGH, "gl_Layer");
1285    var->data.interpolation = INTERP_MODE_FLAT;
1286    if (state->is_version(410, 0) || state->ARB_viewport_array_enable ||
1287        state->OES_viewport_array_enable) {
1288       var = add_output(VARYING_SLOT_VIEWPORT, int_t, GLSL_PRECISION_HIGH,
1289                        "gl_ViewportIndex");
1290       var->data.interpolation = INTERP_MODE_FLAT;
1291    }
1292    if (state->NV_viewport_array2_enable) {
1293       var = add_output(VARYING_SLOT_VIEWPORT_MASK, array(int_t, 1),
1294                        "gl_ViewportMask");
1295       var->data.interpolation = INTERP_MODE_FLAT;
1296    }
1297    if (state->is_version(400, 320) || state->ARB_gpu_shader5_enable ||
1298        state->OES_geometry_shader_enable || state->EXT_geometry_shader_enable) {
1299       add_system_value(SYSTEM_VALUE_INVOCATION_ID, int_t, GLSL_PRECISION_HIGH,
1300                        "gl_InvocationID");
1301    }
1302 
1303    /* Although gl_PrimitiveID appears in tessellation control and tessellation
1304     * evaluation shaders, it has a different function there than it has in
1305     * geometry shaders, so we treat it (and its counterpart gl_PrimitiveIDIn)
1306     * as special geometry shader variables.
1307     *
1308     * Note that although the general convention of suffixing geometry shader
1309     * input varyings with "In" was not adopted into GLSL 1.50, it is used in
1310     * the specific case of gl_PrimitiveIDIn.  So we don't need to treat
1311     * gl_PrimitiveIDIn as an {ARB,EXT}_geometry_shader4-only variable.
1312     */
1313    var = add_input(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1314                    "gl_PrimitiveIDIn");
1315    var->data.interpolation = INTERP_MODE_FLAT;
1316    var = add_output(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1317                     "gl_PrimitiveID");
1318    var->data.interpolation = INTERP_MODE_FLAT;
1319 }
1320 
1321 
1322 /**
1323  * Generate variables which only exist in fragment shaders.
1324  */
1325 void
generate_fs_special_vars()1326 builtin_variable_generator::generate_fs_special_vars()
1327 {
1328    ir_variable *var;
1329 
1330    int frag_coord_precision = (state->is_version(0, 300) ?
1331                                GLSL_PRECISION_HIGH :
1332                                GLSL_PRECISION_MEDIUM);
1333 
1334    if (this->state->consts->GLSLFragCoordIsSysVal) {
1335       add_system_value(SYSTEM_VALUE_FRAG_COORD, vec4_t, frag_coord_precision,
1336                        "gl_FragCoord");
1337    } else {
1338       add_input(VARYING_SLOT_POS, vec4_t, frag_coord_precision, "gl_FragCoord");
1339    }
1340 
1341    if (this->state->consts->GLSLFrontFacingIsSysVal) {
1342       var = add_system_value(SYSTEM_VALUE_FRONT_FACE, bool_t, "gl_FrontFacing");
1343       var->data.interpolation = INTERP_MODE_FLAT;
1344    } else {
1345       var = add_input(VARYING_SLOT_FACE, bool_t, "gl_FrontFacing");
1346       var->data.interpolation = INTERP_MODE_FLAT;
1347    }
1348 
1349    if (state->is_version(120, 100)) {
1350       if (this->state->consts->GLSLPointCoordIsSysVal)
1351          add_system_value(SYSTEM_VALUE_POINT_COORD, vec2_t,
1352                           GLSL_PRECISION_MEDIUM, "gl_PointCoord");
1353       else
1354          add_input(VARYING_SLOT_PNTC, vec2_t, GLSL_PRECISION_MEDIUM,
1355                    "gl_PointCoord");
1356    }
1357 
1358    if (state->has_geometry_shader() || state->EXT_gpu_shader4_enable) {
1359       var = add_input(VARYING_SLOT_PRIMITIVE_ID, int_t, GLSL_PRECISION_HIGH,
1360                       "gl_PrimitiveID");
1361       var->data.interpolation = INTERP_MODE_FLAT;
1362    }
1363 
1364    /* gl_FragColor and gl_FragData were deprecated starting in desktop GLSL
1365     * 1.30, and were relegated to the compatibility profile in GLSL 4.20.
1366     * They were removed from GLSL ES 3.00.
1367     */
1368    if (compatibility || !state->is_version(420, 300)) {
1369       add_output(FRAG_RESULT_COLOR, vec4_t, GLSL_PRECISION_MEDIUM,
1370                  "gl_FragColor");
1371       add_output(FRAG_RESULT_DATA0,
1372                  array(vec4_t, state->Const.MaxDrawBuffers),
1373                  GLSL_PRECISION_MEDIUM,
1374                  "gl_FragData");
1375    }
1376 
1377    if (state->has_framebuffer_fetch() && !state->is_version(130, 300)) {
1378       ir_variable *const var =
1379          add_output(FRAG_RESULT_DATA0,
1380                     array(vec4_t, state->Const.MaxDrawBuffers),
1381                     "gl_LastFragData");
1382       var->data.precision = GLSL_PRECISION_MEDIUM;
1383       var->data.read_only = 1;
1384       var->data.fb_fetch_output = 1;
1385       var->data.memory_coherent = 1;
1386    }
1387 
1388    if (state->has_framebuffer_fetch_zs()) {
1389       ir_variable *const depth_var =
1390          add_output(FRAG_RESULT_DEPTH, float_t,
1391                     GLSL_PRECISION_HIGH, "gl_LastFragDepthARM");
1392       depth_var->data.read_only = 1;
1393       depth_var->data.fb_fetch_output = 1;
1394       depth_var->data.memory_coherent = 1;
1395 
1396       ir_variable *const stencil_var =
1397          add_output(FRAG_RESULT_STENCIL, int_t,
1398                     GLSL_PRECISION_LOW, "gl_LastFragStencilARM");
1399       stencil_var->data.read_only = 1;
1400       stencil_var->data.fb_fetch_output = 1;
1401       stencil_var->data.memory_coherent = 1;
1402    }
1403 
1404    if (state->es_shader && state->language_version == 100 && state->EXT_blend_func_extended_enable) {
1405       add_index_output(FRAG_RESULT_COLOR, 1, vec4_t,
1406                        GLSL_PRECISION_MEDIUM, "gl_SecondaryFragColorEXT");
1407       add_index_output(FRAG_RESULT_DATA0, 1,
1408                        array(vec4_t, state->Const.MaxDualSourceDrawBuffers),
1409                        GLSL_PRECISION_MEDIUM, "gl_SecondaryFragDataEXT");
1410    }
1411 
1412    /* gl_FragDepth has always been in desktop GLSL, but did not appear in GLSL
1413     * ES 1.00.
1414     */
1415    if (state->is_version(110, 300)) {
1416       add_output(FRAG_RESULT_DEPTH, float_t, GLSL_PRECISION_HIGH,
1417                  "gl_FragDepth");
1418    }
1419 
1420    if (state->EXT_frag_depth_enable)
1421       add_output(FRAG_RESULT_DEPTH, float_t, "gl_FragDepthEXT");
1422 
1423    if (state->ARB_shader_stencil_export_enable) {
1424       ir_variable *const var =
1425          add_output(FRAG_RESULT_STENCIL, int_t, "gl_FragStencilRefARB");
1426       if (state->ARB_shader_stencil_export_warn)
1427          var->enable_extension_warning("GL_ARB_shader_stencil_export");
1428    }
1429 
1430    if (state->AMD_shader_stencil_export_enable) {
1431       ir_variable *const var =
1432          add_output(FRAG_RESULT_STENCIL, int_t, "gl_FragStencilRefAMD");
1433       if (state->AMD_shader_stencil_export_warn)
1434          var->enable_extension_warning("GL_AMD_shader_stencil_export");
1435    }
1436 
1437    if (state->is_version(400, 320) ||
1438        state->ARB_sample_shading_enable ||
1439        state->OES_sample_variables_enable) {
1440       add_system_value(SYSTEM_VALUE_SAMPLE_ID, int_t, GLSL_PRECISION_LOW,
1441                        "gl_SampleID");
1442       add_system_value(SYSTEM_VALUE_SAMPLE_POS, vec2_t, GLSL_PRECISION_MEDIUM,
1443                        "gl_SamplePosition");
1444       /* From the ARB_sample_shading specification:
1445        *    "The number of elements in the array is ceil(<s>/32), where
1446        *    <s> is the maximum number of color samples supported by the
1447        *    implementation."
1448        * Since no drivers expose more than 32x MSAA, we can simply set
1449        * the array size to 1 rather than computing it.
1450        */
1451       add_output(FRAG_RESULT_SAMPLE_MASK, array(int_t, 1),
1452                  GLSL_PRECISION_HIGH, "gl_SampleMask");
1453    }
1454 
1455    if (state->is_version(400, 320) ||
1456        state->ARB_gpu_shader5_enable ||
1457        state->OES_sample_variables_enable) {
1458       add_system_value(SYSTEM_VALUE_SAMPLE_MASK_IN, array(int_t, 1),
1459                        GLSL_PRECISION_HIGH, "gl_SampleMaskIn");
1460    }
1461 
1462    if (state->is_version(430, 320) ||
1463        state->ARB_fragment_layer_viewport_enable ||
1464        state->OES_geometry_shader_enable ||
1465        state->EXT_geometry_shader_enable) {
1466       add_varying(VARYING_SLOT_LAYER, int_t, GLSL_PRECISION_HIGH,
1467                   "gl_Layer", INTERP_MODE_FLAT);
1468    }
1469 
1470    if (state->is_version(430, 0) ||
1471        state->ARB_fragment_layer_viewport_enable ||
1472        state->OES_viewport_array_enable) {
1473       add_varying(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex", INTERP_MODE_FLAT);
1474    }
1475 
1476    if (state->is_version(450, 310) || state->ARB_ES3_1_compatibility_enable)
1477       add_system_value(SYSTEM_VALUE_HELPER_INVOCATION, bool_t, "gl_HelperInvocation");
1478 }
1479 
1480 
1481 /**
1482  * Generate variables which only exist in compute shaders.
1483  */
1484 void
generate_cs_special_vars()1485 builtin_variable_generator::generate_cs_special_vars()
1486 {
1487    add_system_value(SYSTEM_VALUE_LOCAL_INVOCATION_ID, uvec3_t,
1488                     "gl_LocalInvocationID");
1489    add_system_value(SYSTEM_VALUE_WORKGROUP_ID, uvec3_t, "gl_WorkGroupID");
1490    add_system_value(SYSTEM_VALUE_NUM_WORKGROUPS, uvec3_t, "gl_NumWorkGroups");
1491 
1492    if (state->ARB_compute_variable_group_size_enable) {
1493       add_system_value(SYSTEM_VALUE_WORKGROUP_SIZE,
1494                        uvec3_t, "gl_LocalGroupSizeARB");
1495    }
1496 
1497    add_system_value(SYSTEM_VALUE_GLOBAL_INVOCATION_ID,
1498                     uvec3_t, "gl_GlobalInvocationID");
1499    add_system_value(SYSTEM_VALUE_LOCAL_INVOCATION_INDEX,
1500                     uint_t, "gl_LocalInvocationIndex");
1501 
1502    if (state->KHR_shader_subgroup_basic_enable) {
1503       add_system_value(SYSTEM_VALUE_NUM_SUBGROUPS, uint_t, "gl_NumSubgroups");
1504       add_system_value(SYSTEM_VALUE_SUBGROUP_ID, uint_t, "gl_SubgroupID");
1505    }
1506 }
1507 
1508 
1509 /**
1510  * Add a single "varying" variable.  The variable's type and direction (input
1511  * or output) are adjusted as appropriate for the type of shader being
1512  * compiled.
1513  */
1514 void
add_varying(int slot,const glsl_type * type,int precision,const char * name,enum glsl_interp_mode interp)1515 builtin_variable_generator::add_varying(int slot, const glsl_type *type,
1516                                         int precision, const char *name,
1517                                         enum glsl_interp_mode interp)
1518 {
1519    switch (state->stage) {
1520    case MESA_SHADER_TESS_CTRL:
1521    case MESA_SHADER_TESS_EVAL:
1522    case MESA_SHADER_GEOMETRY:
1523       this->per_vertex_in.add_field(slot, type, precision, name, interp);
1524       FALLTHROUGH;
1525    case MESA_SHADER_VERTEX:
1526       this->per_vertex_out.add_field(slot, type, precision, name, interp);
1527       break;
1528    case MESA_SHADER_FRAGMENT:
1529       add_input(slot, type, precision, name, interp);
1530       break;
1531    case MESA_SHADER_COMPUTE:
1532       /* Compute shaders don't have varyings. */
1533       break;
1534    default:
1535       break;
1536    }
1537 }
1538 
1539 
1540 /**
1541  * Generate variables that are used to communicate data from one shader stage
1542  * to the next ("varyings").
1543  */
1544 void
generate_varyings()1545 builtin_variable_generator::generate_varyings()
1546 {
1547    const struct gl_shader_compiler_options *options =
1548       &state->consts->ShaderCompilerOptions[state->stage];
1549 
1550    /* gl_Position and gl_PointSize are not visible from fragment shaders. */
1551    if (state->stage != MESA_SHADER_FRAGMENT) {
1552       add_varying(VARYING_SLOT_POS, vec4_t, GLSL_PRECISION_HIGH, "gl_Position");
1553       if (!state->es_shader ||
1554           state->stage == MESA_SHADER_VERTEX ||
1555           (state->stage == MESA_SHADER_GEOMETRY &&
1556            (state->OES_geometry_point_size_enable ||
1557             state->EXT_geometry_point_size_enable)) ||
1558           ((state->stage == MESA_SHADER_TESS_CTRL ||
1559             state->stage == MESA_SHADER_TESS_EVAL) &&
1560            (state->OES_tessellation_point_size_enable ||
1561             state->EXT_tessellation_point_size_enable))) {
1562          add_varying(VARYING_SLOT_PSIZ,
1563                      float_t,
1564                      state->is_version(0, 300) ?
1565                      GLSL_PRECISION_HIGH :
1566                      GLSL_PRECISION_MEDIUM,
1567                      "gl_PointSize");
1568       }
1569       if (state->stage == MESA_SHADER_VERTEX) {
1570          if (state->AMD_vertex_shader_viewport_index_enable ||
1571              state->ARB_shader_viewport_layer_array_enable ||
1572              state->NV_viewport_array2_enable) {
1573             add_varying(VARYING_SLOT_VIEWPORT, int_t, "gl_ViewportIndex", INTERP_MODE_FLAT);
1574          }
1575 
1576          if (state->AMD_vertex_shader_layer_enable ||
1577              state->ARB_shader_viewport_layer_array_enable ||
1578              state->NV_viewport_array2_enable) {
1579             add_varying(VARYING_SLOT_LAYER, int_t, GLSL_PRECISION_HIGH,
1580                         "gl_Layer", INTERP_MODE_FLAT);
1581          }
1582 
1583          /* From the NV_viewport_array2 specification:
1584           *
1585           *    "The variable gl_ViewportMask[] is available as an output variable
1586           *    in the VTG languages. The array has ceil(v/32) elements where v is
1587           *    the maximum number of viewports supported by the implementation."
1588           *
1589           * Since no drivers expose more than 16 viewports, we can simply set the
1590           * array size to 1 rather than computing it and dealing with varying
1591           * slot complication.
1592           */
1593          if (state->NV_viewport_array2_enable)
1594             add_varying(VARYING_SLOT_VIEWPORT_MASK, array(int_t, 1),
1595                         "gl_ViewportMask", INTERP_MODE_FLAT);
1596         }
1597    }
1598 
1599    if (state->has_clip_distance()) {
1600        add_varying(VARYING_SLOT_CLIP_DIST0, array(float_t, 0),
1601                    GLSL_PRECISION_HIGH, "gl_ClipDistance");
1602    }
1603    if (state->has_cull_distance()) {
1604       add_varying(VARYING_SLOT_CULL_DIST0, array(float_t, 0),
1605                   GLSL_PRECISION_HIGH, "gl_CullDistance");
1606    }
1607 
1608    if (compatibility) {
1609       add_varying(VARYING_SLOT_TEX0, array(vec4_t, 0), "gl_TexCoord");
1610       add_varying(VARYING_SLOT_FOGC, float_t, "gl_FogFragCoord");
1611       if (state->stage == MESA_SHADER_FRAGMENT) {
1612          add_varying(VARYING_SLOT_COL0, vec4_t, "gl_Color");
1613          add_varying(VARYING_SLOT_COL1, vec4_t, "gl_SecondaryColor");
1614       } else {
1615          add_varying(VARYING_SLOT_CLIP_VERTEX, vec4_t, "gl_ClipVertex");
1616          add_varying(VARYING_SLOT_COL0, vec4_t, "gl_FrontColor");
1617          add_varying(VARYING_SLOT_BFC0, vec4_t, "gl_BackColor");
1618          add_varying(VARYING_SLOT_COL1, vec4_t, "gl_FrontSecondaryColor");
1619          add_varying(VARYING_SLOT_BFC1, vec4_t, "gl_BackSecondaryColor");
1620       }
1621    }
1622 
1623    /* Section 7.1 (Built-In Language Variables) of the GLSL 4.00 spec
1624     * says:
1625     *
1626     *    "In the tessellation control language, built-in variables are
1627     *    intrinsically declared as:
1628     *
1629     *        in gl_PerVertex {
1630     *            vec4 gl_Position;
1631     *            float gl_PointSize;
1632     *            float gl_ClipDistance[];
1633     *        } gl_in[gl_MaxPatchVertices];"
1634     */
1635    if (state->stage == MESA_SHADER_TESS_CTRL ||
1636        state->stage == MESA_SHADER_TESS_EVAL) {
1637       const glsl_type *per_vertex_in_type =
1638          this->per_vertex_in.construct_interface_instance();
1639       add_variable("gl_in", array(per_vertex_in_type, state->Const.MaxPatchVertices),
1640                    GLSL_PRECISION_NONE, ir_var_shader_in, -1);
1641    }
1642    if (state->stage == MESA_SHADER_GEOMETRY) {
1643       const glsl_type *per_vertex_in_type =
1644          this->per_vertex_in.construct_interface_instance();
1645       add_variable("gl_in", array(per_vertex_in_type, 0),
1646                    GLSL_PRECISION_NONE, ir_var_shader_in, -1);
1647    }
1648    if (state->stage == MESA_SHADER_TESS_CTRL) {
1649       const glsl_type *per_vertex_out_type =
1650          this->per_vertex_out.construct_interface_instance();
1651       add_variable("gl_out", array(per_vertex_out_type, 0),
1652                    GLSL_PRECISION_NONE, ir_var_shader_out, -1);
1653    }
1654    if (state->stage == MESA_SHADER_VERTEX ||
1655        state->stage == MESA_SHADER_TESS_EVAL ||
1656        state->stage == MESA_SHADER_GEOMETRY) {
1657       const glsl_type *per_vertex_out_type =
1658          this->per_vertex_out.construct_interface_instance();
1659       const glsl_struct_field *fields = per_vertex_out_type->fields.structure;
1660       for (unsigned i = 0; i < per_vertex_out_type->length; i++) {
1661          ir_variable *var =
1662             add_variable(fields[i].name, fields[i].type, fields[i].precision,
1663                          ir_var_shader_out, fields[i].location);
1664          var->data.interpolation = fields[i].interpolation;
1665          var->data.centroid = fields[i].centroid;
1666          var->data.sample = fields[i].sample;
1667          var->data.patch = fields[i].patch;
1668          var->init_interface_type(per_vertex_out_type);
1669 
1670          var->data.invariant = fields[i].location == VARYING_SLOT_POS &&
1671                                options->PositionAlwaysInvariant;
1672 
1673          var->data.precise = fields[i].location == VARYING_SLOT_POS &&
1674                                options->PositionAlwaysPrecise;
1675       }
1676    }
1677 }
1678 
1679 
1680 }; /* Anonymous namespace */
1681 
1682 
1683 void
_mesa_glsl_initialize_variables(exec_list * instructions,struct _mesa_glsl_parse_state * state)1684 _mesa_glsl_initialize_variables(exec_list *instructions,
1685 				struct _mesa_glsl_parse_state *state)
1686 {
1687    builtin_variable_generator gen(instructions, state);
1688 
1689    gen.generate_constants();
1690    gen.generate_uniforms();
1691    gen.generate_special_vars();
1692 
1693    gen.generate_varyings();
1694 
1695    switch (state->stage) {
1696    case MESA_SHADER_VERTEX:
1697       gen.generate_vs_special_vars();
1698       break;
1699    case MESA_SHADER_TESS_CTRL:
1700       gen.generate_tcs_special_vars();
1701       break;
1702    case MESA_SHADER_TESS_EVAL:
1703       gen.generate_tes_special_vars();
1704       break;
1705    case MESA_SHADER_GEOMETRY:
1706       gen.generate_gs_special_vars();
1707       break;
1708    case MESA_SHADER_FRAGMENT:
1709       gen.generate_fs_special_vars();
1710       break;
1711    case MESA_SHADER_COMPUTE:
1712       gen.generate_cs_special_vars();
1713       break;
1714    default:
1715       break;
1716    }
1717 }
1718