glsl: process bindless/bound layout qualifiers
[mesa.git] / src / compiler / glsl / glsl_parser_extras.cpp
1 /*
2 * Copyright © 2008, 2009 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 #include <inttypes.h> /* for PRIx64 macro */
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <string.h>
27 #include <assert.h>
28
29 #include "main/core.h" /* for struct gl_context */
30 #include "main/context.h"
31 #include "main/debug_output.h"
32 #include "main/formats.h"
33 #include "main/shaderobj.h"
34 #include "util/u_atomic.h" /* for p_atomic_cmpxchg */
35 #include "util/ralloc.h"
36 #include "util/disk_cache.h"
37 #include "util/mesa-sha1.h"
38 #include "ast.h"
39 #include "glsl_parser_extras.h"
40 #include "glsl_parser.h"
41 #include "ir_optimization.h"
42 #include "loop_analysis.h"
43 #include "builtin_functions.h"
44
45 /**
46 * Format a short human-readable description of the given GLSL version.
47 */
48 const char *
49 glsl_compute_version_string(void *mem_ctx, bool is_es, unsigned version)
50 {
51 return ralloc_asprintf(mem_ctx, "GLSL%s %d.%02d", is_es ? " ES" : "",
52 version / 100, version % 100);
53 }
54
55
56 static const unsigned known_desktop_glsl_versions[] =
57 { 110, 120, 130, 140, 150, 330, 400, 410, 420, 430, 440, 450 };
58 static const unsigned known_desktop_gl_versions[] =
59 { 20, 21, 30, 31, 32, 33, 40, 41, 42, 43, 44, 45 };
60
61
62 _mesa_glsl_parse_state::_mesa_glsl_parse_state(struct gl_context *_ctx,
63 gl_shader_stage stage,
64 void *mem_ctx)
65 : ctx(_ctx), cs_input_local_size_specified(false), cs_input_local_size(),
66 switch_state()
67 {
68 assert(stage < MESA_SHADER_STAGES);
69 this->stage = stage;
70
71 this->scanner = NULL;
72 this->translation_unit.make_empty();
73 this->symbols = new(mem_ctx) glsl_symbol_table;
74
75 this->linalloc = linear_alloc_parent(this, 0);
76
77 this->info_log = ralloc_strdup(mem_ctx, "");
78 this->error = false;
79 this->loop_nesting_ast = NULL;
80
81 this->uses_builtin_functions = false;
82
83 /* Set default language version and extensions */
84 this->language_version = 110;
85 this->forced_language_version = ctx->Const.ForceGLSLVersion;
86 this->zero_init = ctx->Const.GLSLZeroInit;
87 this->gl_version = 20;
88 this->compat_shader = true;
89 this->es_shader = false;
90 this->ARB_texture_rectangle_enable = true;
91
92 /* OpenGL ES 2.0 has different defaults from desktop GL. */
93 if (ctx->API == API_OPENGLES2) {
94 this->language_version = 100;
95 this->es_shader = true;
96 this->ARB_texture_rectangle_enable = false;
97 }
98
99 this->extensions = &ctx->Extensions;
100
101 this->Const.MaxLights = ctx->Const.MaxLights;
102 this->Const.MaxClipPlanes = ctx->Const.MaxClipPlanes;
103 this->Const.MaxTextureUnits = ctx->Const.MaxTextureUnits;
104 this->Const.MaxTextureCoords = ctx->Const.MaxTextureCoordUnits;
105 this->Const.MaxVertexAttribs = ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs;
106 this->Const.MaxVertexUniformComponents = ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents;
107 this->Const.MaxVertexTextureImageUnits = ctx->Const.Program[MESA_SHADER_VERTEX].MaxTextureImageUnits;
108 this->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxCombinedTextureImageUnits;
109 this->Const.MaxTextureImageUnits = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits;
110 this->Const.MaxFragmentUniformComponents = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents;
111 this->Const.MinProgramTexelOffset = ctx->Const.MinProgramTexelOffset;
112 this->Const.MaxProgramTexelOffset = ctx->Const.MaxProgramTexelOffset;
113
114 this->Const.MaxDrawBuffers = ctx->Const.MaxDrawBuffers;
115
116 this->Const.MaxDualSourceDrawBuffers = ctx->Const.MaxDualSourceDrawBuffers;
117
118 /* 1.50 constants */
119 this->Const.MaxVertexOutputComponents = ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents;
120 this->Const.MaxGeometryInputComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxInputComponents;
121 this->Const.MaxGeometryOutputComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxOutputComponents;
122 this->Const.MaxFragmentInputComponents = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents;
123 this->Const.MaxGeometryTextureImageUnits = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxTextureImageUnits;
124 this->Const.MaxGeometryOutputVertices = ctx->Const.MaxGeometryOutputVertices;
125 this->Const.MaxGeometryTotalOutputComponents = ctx->Const.MaxGeometryTotalOutputComponents;
126 this->Const.MaxGeometryUniformComponents = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxUniformComponents;
127
128 this->Const.MaxVertexAtomicCounters = ctx->Const.Program[MESA_SHADER_VERTEX].MaxAtomicCounters;
129 this->Const.MaxTessControlAtomicCounters = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxAtomicCounters;
130 this->Const.MaxTessEvaluationAtomicCounters = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxAtomicCounters;
131 this->Const.MaxGeometryAtomicCounters = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxAtomicCounters;
132 this->Const.MaxFragmentAtomicCounters = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAtomicCounters;
133 this->Const.MaxComputeAtomicCounters = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxAtomicCounters;
134 this->Const.MaxCombinedAtomicCounters = ctx->Const.MaxCombinedAtomicCounters;
135 this->Const.MaxAtomicBufferBindings = ctx->Const.MaxAtomicBufferBindings;
136 this->Const.MaxVertexAtomicCounterBuffers =
137 ctx->Const.Program[MESA_SHADER_VERTEX].MaxAtomicBuffers;
138 this->Const.MaxTessControlAtomicCounterBuffers =
139 ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxAtomicBuffers;
140 this->Const.MaxTessEvaluationAtomicCounterBuffers =
141 ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxAtomicBuffers;
142 this->Const.MaxGeometryAtomicCounterBuffers =
143 ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxAtomicBuffers;
144 this->Const.MaxFragmentAtomicCounterBuffers =
145 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxAtomicBuffers;
146 this->Const.MaxComputeAtomicCounterBuffers =
147 ctx->Const.Program[MESA_SHADER_COMPUTE].MaxAtomicBuffers;
148 this->Const.MaxCombinedAtomicCounterBuffers =
149 ctx->Const.MaxCombinedAtomicBuffers;
150 this->Const.MaxAtomicCounterBufferSize =
151 ctx->Const.MaxAtomicBufferSize;
152
153 /* ARB_enhanced_layouts constants */
154 this->Const.MaxTransformFeedbackBuffers = ctx->Const.MaxTransformFeedbackBuffers;
155 this->Const.MaxTransformFeedbackInterleavedComponents = ctx->Const.MaxTransformFeedbackInterleavedComponents;
156
157 /* Compute shader constants */
158 for (unsigned i = 0; i < ARRAY_SIZE(this->Const.MaxComputeWorkGroupCount); i++)
159 this->Const.MaxComputeWorkGroupCount[i] = ctx->Const.MaxComputeWorkGroupCount[i];
160 for (unsigned i = 0; i < ARRAY_SIZE(this->Const.MaxComputeWorkGroupSize); i++)
161 this->Const.MaxComputeWorkGroupSize[i] = ctx->Const.MaxComputeWorkGroupSize[i];
162
163 this->Const.MaxComputeTextureImageUnits = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxTextureImageUnits;
164 this->Const.MaxComputeUniformComponents = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxUniformComponents;
165
166 this->Const.MaxImageUnits = ctx->Const.MaxImageUnits;
167 this->Const.MaxCombinedShaderOutputResources = ctx->Const.MaxCombinedShaderOutputResources;
168 this->Const.MaxImageSamples = ctx->Const.MaxImageSamples;
169 this->Const.MaxVertexImageUniforms = ctx->Const.Program[MESA_SHADER_VERTEX].MaxImageUniforms;
170 this->Const.MaxTessControlImageUniforms = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxImageUniforms;
171 this->Const.MaxTessEvaluationImageUniforms = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxImageUniforms;
172 this->Const.MaxGeometryImageUniforms = ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxImageUniforms;
173 this->Const.MaxFragmentImageUniforms = ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxImageUniforms;
174 this->Const.MaxComputeImageUniforms = ctx->Const.Program[MESA_SHADER_COMPUTE].MaxImageUniforms;
175 this->Const.MaxCombinedImageUniforms = ctx->Const.MaxCombinedImageUniforms;
176
177 /* ARB_viewport_array */
178 this->Const.MaxViewports = ctx->Const.MaxViewports;
179
180 /* tessellation shader constants */
181 this->Const.MaxPatchVertices = ctx->Const.MaxPatchVertices;
182 this->Const.MaxTessGenLevel = ctx->Const.MaxTessGenLevel;
183 this->Const.MaxTessControlInputComponents = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxInputComponents;
184 this->Const.MaxTessControlOutputComponents = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxOutputComponents;
185 this->Const.MaxTessControlTextureImageUnits = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxTextureImageUnits;
186 this->Const.MaxTessEvaluationInputComponents = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxInputComponents;
187 this->Const.MaxTessEvaluationOutputComponents = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxOutputComponents;
188 this->Const.MaxTessEvaluationTextureImageUnits = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxTextureImageUnits;
189 this->Const.MaxTessPatchComponents = ctx->Const.MaxTessPatchComponents;
190 this->Const.MaxTessControlTotalOutputComponents = ctx->Const.MaxTessControlTotalOutputComponents;
191 this->Const.MaxTessControlUniformComponents = ctx->Const.Program[MESA_SHADER_TESS_CTRL].MaxUniformComponents;
192 this->Const.MaxTessEvaluationUniformComponents = ctx->Const.Program[MESA_SHADER_TESS_EVAL].MaxUniformComponents;
193
194 /* GL 4.5 / OES_sample_variables */
195 this->Const.MaxSamples = ctx->Const.MaxSamples;
196
197 this->current_function = NULL;
198 this->toplevel_ir = NULL;
199 this->found_return = false;
200 this->all_invariant = false;
201 this->user_structures = NULL;
202 this->num_user_structures = 0;
203 this->num_subroutines = 0;
204 this->subroutines = NULL;
205 this->num_subroutine_types = 0;
206 this->subroutine_types = NULL;
207
208 /* supported_versions should be large enough to support the known desktop
209 * GLSL versions plus 4 GLES versions (ES 1.00, ES 3.00, ES 3.10, ES 3.20)
210 */
211 STATIC_ASSERT((ARRAY_SIZE(known_desktop_glsl_versions) + 4) ==
212 ARRAY_SIZE(this->supported_versions));
213
214 /* Populate the list of supported GLSL versions */
215 /* FINISHME: Once the OpenGL 3.0 'forward compatible' context or
216 * the OpenGL 3.2 Core context is supported, this logic will need
217 * change. Older versions of GLSL are no longer supported
218 * outside the compatibility contexts of 3.x.
219 */
220 this->num_supported_versions = 0;
221 if (_mesa_is_desktop_gl(ctx)) {
222 for (unsigned i = 0; i < ARRAY_SIZE(known_desktop_glsl_versions); i++) {
223 if (known_desktop_glsl_versions[i] <= ctx->Const.GLSLVersion) {
224 this->supported_versions[this->num_supported_versions].ver
225 = known_desktop_glsl_versions[i];
226 this->supported_versions[this->num_supported_versions].gl_ver
227 = known_desktop_gl_versions[i];
228 this->supported_versions[this->num_supported_versions].es = false;
229 this->num_supported_versions++;
230 }
231 }
232 }
233 if (ctx->API == API_OPENGLES2 || ctx->Extensions.ARB_ES2_compatibility) {
234 this->supported_versions[this->num_supported_versions].ver = 100;
235 this->supported_versions[this->num_supported_versions].gl_ver = 20;
236 this->supported_versions[this->num_supported_versions].es = true;
237 this->num_supported_versions++;
238 }
239 if (_mesa_is_gles3(ctx) || ctx->Extensions.ARB_ES3_compatibility) {
240 this->supported_versions[this->num_supported_versions].ver = 300;
241 this->supported_versions[this->num_supported_versions].gl_ver = 30;
242 this->supported_versions[this->num_supported_versions].es = true;
243 this->num_supported_versions++;
244 }
245 if (_mesa_is_gles31(ctx) || ctx->Extensions.ARB_ES3_1_compatibility) {
246 this->supported_versions[this->num_supported_versions].ver = 310;
247 this->supported_versions[this->num_supported_versions].gl_ver = 31;
248 this->supported_versions[this->num_supported_versions].es = true;
249 this->num_supported_versions++;
250 }
251 if ((ctx->API == API_OPENGLES2 && ctx->Version >= 32) ||
252 ctx->Extensions.ARB_ES3_2_compatibility) {
253 this->supported_versions[this->num_supported_versions].ver = 320;
254 this->supported_versions[this->num_supported_versions].gl_ver = 32;
255 this->supported_versions[this->num_supported_versions].es = true;
256 this->num_supported_versions++;
257 }
258
259 /* Create a string for use in error messages to tell the user which GLSL
260 * versions are supported.
261 */
262 char *supported = ralloc_strdup(this, "");
263 for (unsigned i = 0; i < this->num_supported_versions; i++) {
264 unsigned ver = this->supported_versions[i].ver;
265 const char *const prefix = (i == 0)
266 ? ""
267 : ((i == this->num_supported_versions - 1) ? ", and " : ", ");
268 const char *const suffix = (this->supported_versions[i].es) ? " ES" : "";
269
270 ralloc_asprintf_append(& supported, "%s%u.%02u%s",
271 prefix,
272 ver / 100, ver % 100,
273 suffix);
274 }
275
276 this->supported_version_string = supported;
277
278 if (ctx->Const.ForceGLSLExtensionsWarn)
279 _mesa_glsl_process_extension("all", NULL, "warn", NULL, this);
280
281 this->default_uniform_qualifier = new(this) ast_type_qualifier();
282 this->default_uniform_qualifier->flags.q.shared = 1;
283 this->default_uniform_qualifier->flags.q.column_major = 1;
284
285 this->default_shader_storage_qualifier = new(this) ast_type_qualifier();
286 this->default_shader_storage_qualifier->flags.q.shared = 1;
287 this->default_shader_storage_qualifier->flags.q.column_major = 1;
288
289 this->fs_uses_gl_fragcoord = false;
290 this->fs_redeclares_gl_fragcoord = false;
291 this->fs_origin_upper_left = false;
292 this->fs_pixel_center_integer = false;
293 this->fs_redeclares_gl_fragcoord_with_no_layout_qualifiers = false;
294
295 this->gs_input_prim_type_specified = false;
296 this->tcs_output_vertices_specified = false;
297 this->gs_input_size = 0;
298 this->in_qualifier = new(this) ast_type_qualifier();
299 this->out_qualifier = new(this) ast_type_qualifier();
300 this->fs_early_fragment_tests = false;
301 this->fs_inner_coverage = false;
302 this->fs_post_depth_coverage = false;
303 this->fs_blend_support = 0;
304 memset(this->atomic_counter_offsets, 0,
305 sizeof(this->atomic_counter_offsets));
306 this->allow_extension_directive_midshader =
307 ctx->Const.AllowGLSLExtensionDirectiveMidShader;
308
309 this->cs_input_local_size_variable_specified = false;
310
311 /* ARB_bindless_texture */
312 this->bindless_sampler_specified = false;
313 this->bindless_image_specified = false;
314 this->bound_sampler_specified = false;
315 this->bound_image_specified = false;
316 }
317
318 /**
319 * Determine whether the current GLSL version is sufficiently high to support
320 * a certain feature, and generate an error message if it isn't.
321 *
322 * \param required_glsl_version and \c required_glsl_es_version are
323 * interpreted as they are in _mesa_glsl_parse_state::is_version().
324 *
325 * \param locp is the parser location where the error should be reported.
326 *
327 * \param fmt (and additional arguments) constitute a printf-style error
328 * message to report if the version check fails. Information about the
329 * current and required GLSL versions will be appended. So, for example, if
330 * the GLSL version being compiled is 1.20, and check_version(130, 300, locp,
331 * "foo unsupported") is called, the error message will be "foo unsupported in
332 * GLSL 1.20 (GLSL 1.30 or GLSL 3.00 ES required)".
333 */
334 bool
335 _mesa_glsl_parse_state::check_version(unsigned required_glsl_version,
336 unsigned required_glsl_es_version,
337 YYLTYPE *locp, const char *fmt, ...)
338 {
339 if (this->is_version(required_glsl_version, required_glsl_es_version))
340 return true;
341
342 va_list args;
343 va_start(args, fmt);
344 char *problem = ralloc_vasprintf(this, fmt, args);
345 va_end(args);
346 const char *glsl_version_string
347 = glsl_compute_version_string(this, false, required_glsl_version);
348 const char *glsl_es_version_string
349 = glsl_compute_version_string(this, true, required_glsl_es_version);
350 const char *requirement_string = "";
351 if (required_glsl_version && required_glsl_es_version) {
352 requirement_string = ralloc_asprintf(this, " (%s or %s required)",
353 glsl_version_string,
354 glsl_es_version_string);
355 } else if (required_glsl_version) {
356 requirement_string = ralloc_asprintf(this, " (%s required)",
357 glsl_version_string);
358 } else if (required_glsl_es_version) {
359 requirement_string = ralloc_asprintf(this, " (%s required)",
360 glsl_es_version_string);
361 }
362 _mesa_glsl_error(locp, this, "%s in %s%s",
363 problem, this->get_version_string(),
364 requirement_string);
365
366 return false;
367 }
368
369 /**
370 * Process a GLSL #version directive.
371 *
372 * \param version is the integer that follows the #version token.
373 *
374 * \param ident is a string identifier that follows the integer, if any is
375 * present. Otherwise NULL.
376 */
377 void
378 _mesa_glsl_parse_state::process_version_directive(YYLTYPE *locp, int version,
379 const char *ident)
380 {
381 bool es_token_present = false;
382 bool compat_token_present = false;
383 if (ident) {
384 if (strcmp(ident, "es") == 0) {
385 es_token_present = true;
386 } else if (version >= 150) {
387 if (strcmp(ident, "core") == 0) {
388 /* Accept the token. There's no need to record that this is
389 * a core profile shader since that's the only profile we support.
390 */
391 } else if (strcmp(ident, "compatibility") == 0) {
392 compat_token_present = true;
393
394 if (this->ctx->API != API_OPENGL_COMPAT) {
395 _mesa_glsl_error(locp, this,
396 "the compatibility profile is not supported");
397 }
398 } else {
399 _mesa_glsl_error(locp, this,
400 "\"%s\" is not a valid shading language profile; "
401 "if present, it must be \"core\"", ident);
402 }
403 } else {
404 _mesa_glsl_error(locp, this,
405 "illegal text following version number");
406 }
407 }
408
409 this->es_shader = es_token_present;
410 if (version == 100) {
411 if (es_token_present) {
412 _mesa_glsl_error(locp, this,
413 "GLSL 1.00 ES should be selected using "
414 "`#version 100'");
415 } else {
416 this->es_shader = true;
417 }
418 }
419
420 if (this->es_shader) {
421 this->ARB_texture_rectangle_enable = false;
422 }
423
424 if (this->forced_language_version)
425 this->language_version = this->forced_language_version;
426 else
427 this->language_version = version;
428
429 this->compat_shader = compat_token_present ||
430 (!this->es_shader && this->language_version < 140);
431
432 bool supported = false;
433 for (unsigned i = 0; i < this->num_supported_versions; i++) {
434 if (this->supported_versions[i].ver == this->language_version
435 && this->supported_versions[i].es == this->es_shader) {
436 this->gl_version = this->supported_versions[i].gl_ver;
437 supported = true;
438 break;
439 }
440 }
441
442 if (!supported) {
443 _mesa_glsl_error(locp, this, "%s is not supported. "
444 "Supported versions are: %s",
445 this->get_version_string(),
446 this->supported_version_string);
447
448 /* On exit, the language_version must be set to a valid value.
449 * Later calls to _mesa_glsl_initialize_types will misbehave if
450 * the version is invalid.
451 */
452 switch (this->ctx->API) {
453 case API_OPENGL_COMPAT:
454 case API_OPENGL_CORE:
455 this->language_version = this->ctx->Const.GLSLVersion;
456 break;
457
458 case API_OPENGLES:
459 assert(!"Should not get here.");
460 /* FALLTHROUGH */
461
462 case API_OPENGLES2:
463 this->language_version = 100;
464 break;
465 }
466 }
467 }
468
469
470 /* This helper function will append the given message to the shader's
471 info log and report it via GL_ARB_debug_output. Per that extension,
472 'type' is one of the enum values classifying the message, and
473 'id' is the implementation-defined ID of the given message. */
474 static void
475 _mesa_glsl_msg(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
476 GLenum type, const char *fmt, va_list ap)
477 {
478 bool error = (type == MESA_DEBUG_TYPE_ERROR);
479 GLuint msg_id = 0;
480
481 assert(state->info_log != NULL);
482
483 /* Get the offset that the new message will be written to. */
484 int msg_offset = strlen(state->info_log);
485
486 ralloc_asprintf_append(&state->info_log, "%u:%u(%u): %s: ",
487 locp->source,
488 locp->first_line,
489 locp->first_column,
490 error ? "error" : "warning");
491 ralloc_vasprintf_append(&state->info_log, fmt, ap);
492
493 const char *const msg = &state->info_log[msg_offset];
494 struct gl_context *ctx = state->ctx;
495
496 /* Report the error via GL_ARB_debug_output. */
497 _mesa_shader_debug(ctx, type, &msg_id, msg);
498
499 ralloc_strcat(&state->info_log, "\n");
500 }
501
502 void
503 _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
504 const char *fmt, ...)
505 {
506 va_list ap;
507
508 state->error = true;
509
510 va_start(ap, fmt);
511 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_ERROR, fmt, ap);
512 va_end(ap);
513 }
514
515
516 void
517 _mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
518 const char *fmt, ...)
519 {
520 va_list ap;
521
522 va_start(ap, fmt);
523 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_OTHER, fmt, ap);
524 va_end(ap);
525 }
526
527
528 /**
529 * Enum representing the possible behaviors that can be specified in
530 * an #extension directive.
531 */
532 enum ext_behavior {
533 extension_disable,
534 extension_enable,
535 extension_require,
536 extension_warn
537 };
538
539 /**
540 * Element type for _mesa_glsl_supported_extensions
541 */
542 struct _mesa_glsl_extension {
543 /**
544 * Name of the extension when referred to in a GLSL extension
545 * statement
546 */
547 const char *name;
548
549 /**
550 * Whether this extension is a part of AEP
551 */
552 bool aep;
553
554 /**
555 * Predicate that checks whether the relevant extension is available for
556 * this context.
557 */
558 bool (*available_pred)(const struct gl_context *,
559 gl_api api, uint8_t version);
560
561 /**
562 * Flag in the _mesa_glsl_parse_state struct that should be set
563 * when this extension is enabled.
564 *
565 * See note in _mesa_glsl_extension::supported_flag about "pointer
566 * to member" types.
567 */
568 bool _mesa_glsl_parse_state::* enable_flag;
569
570 /**
571 * Flag in the _mesa_glsl_parse_state struct that should be set
572 * when the shader requests "warn" behavior for this extension.
573 *
574 * See note in _mesa_glsl_extension::supported_flag about "pointer
575 * to member" types.
576 */
577 bool _mesa_glsl_parse_state::* warn_flag;
578
579
580 bool compatible_with_state(const _mesa_glsl_parse_state *state,
581 gl_api api, uint8_t gl_version) const;
582 void set_flags(_mesa_glsl_parse_state *state, ext_behavior behavior) const;
583 };
584
585 /** Checks if the context supports a user-facing extension */
586 #define EXT(name_str, driver_cap, ...) \
587 static MAYBE_UNUSED bool \
588 has_##name_str(const struct gl_context *ctx, gl_api api, uint8_t version) \
589 { \
590 return ctx->Extensions.driver_cap && (version >= \
591 _mesa_extension_table[MESA_EXTENSION_##name_str].version[api]); \
592 }
593 #include "main/extensions_table.h"
594 #undef EXT
595
596 #define EXT(NAME) \
597 { "GL_" #NAME, false, has_##NAME, \
598 &_mesa_glsl_parse_state::NAME##_enable, \
599 &_mesa_glsl_parse_state::NAME##_warn }
600
601 #define EXT_AEP(NAME) \
602 { "GL_" #NAME, true, has_##NAME, \
603 &_mesa_glsl_parse_state::NAME##_enable, \
604 &_mesa_glsl_parse_state::NAME##_warn }
605
606 /**
607 * Table of extensions that can be enabled/disabled within a shader,
608 * and the conditions under which they are supported.
609 */
610 static const _mesa_glsl_extension _mesa_glsl_supported_extensions[] = {
611 /* ARB extensions go here, sorted alphabetically.
612 */
613 EXT(ARB_ES3_1_compatibility),
614 EXT(ARB_ES3_2_compatibility),
615 EXT(ARB_arrays_of_arrays),
616 EXT(ARB_bindless_texture),
617 EXT(ARB_compute_shader),
618 EXT(ARB_compute_variable_group_size),
619 EXT(ARB_conservative_depth),
620 EXT(ARB_cull_distance),
621 EXT(ARB_derivative_control),
622 EXT(ARB_draw_buffers),
623 EXT(ARB_draw_instanced),
624 EXT(ARB_enhanced_layouts),
625 EXT(ARB_explicit_attrib_location),
626 EXT(ARB_explicit_uniform_location),
627 EXT(ARB_fragment_coord_conventions),
628 EXT(ARB_fragment_layer_viewport),
629 EXT(ARB_gpu_shader5),
630 EXT(ARB_gpu_shader_fp64),
631 EXT(ARB_gpu_shader_int64),
632 EXT(ARB_post_depth_coverage),
633 EXT(ARB_sample_shading),
634 EXT(ARB_separate_shader_objects),
635 EXT(ARB_shader_atomic_counter_ops),
636 EXT(ARB_shader_atomic_counters),
637 EXT(ARB_shader_ballot),
638 EXT(ARB_shader_bit_encoding),
639 EXT(ARB_shader_clock),
640 EXT(ARB_shader_draw_parameters),
641 EXT(ARB_shader_group_vote),
642 EXT(ARB_shader_image_load_store),
643 EXT(ARB_shader_image_size),
644 EXT(ARB_shader_precision),
645 EXT(ARB_shader_stencil_export),
646 EXT(ARB_shader_storage_buffer_object),
647 EXT(ARB_shader_subroutine),
648 EXT(ARB_shader_texture_image_samples),
649 EXT(ARB_shader_texture_lod),
650 EXT(ARB_shader_viewport_layer_array),
651 EXT(ARB_shading_language_420pack),
652 EXT(ARB_shading_language_packing),
653 EXT(ARB_tessellation_shader),
654 EXT(ARB_texture_cube_map_array),
655 EXT(ARB_texture_gather),
656 EXT(ARB_texture_multisample),
657 EXT(ARB_texture_query_levels),
658 EXT(ARB_texture_query_lod),
659 EXT(ARB_texture_rectangle),
660 EXT(ARB_uniform_buffer_object),
661 EXT(ARB_vertex_attrib_64bit),
662 EXT(ARB_viewport_array),
663
664 /* KHR extensions go here, sorted alphabetically.
665 */
666 EXT_AEP(KHR_blend_equation_advanced),
667
668 /* OES extensions go here, sorted alphabetically.
669 */
670 EXT(OES_EGL_image_external),
671 EXT(OES_geometry_point_size),
672 EXT(OES_geometry_shader),
673 EXT(OES_gpu_shader5),
674 EXT(OES_primitive_bounding_box),
675 EXT_AEP(OES_sample_variables),
676 EXT_AEP(OES_shader_image_atomic),
677 EXT(OES_shader_io_blocks),
678 EXT_AEP(OES_shader_multisample_interpolation),
679 EXT(OES_standard_derivatives),
680 EXT(OES_tessellation_point_size),
681 EXT(OES_tessellation_shader),
682 EXT(OES_texture_3D),
683 EXT(OES_texture_buffer),
684 EXT(OES_texture_cube_map_array),
685 EXT_AEP(OES_texture_storage_multisample_2d_array),
686 EXT(OES_viewport_array),
687
688 /* All other extensions go here, sorted alphabetically.
689 */
690 EXT(AMD_conservative_depth),
691 EXT(AMD_shader_stencil_export),
692 EXT(AMD_shader_trinary_minmax),
693 EXT(AMD_vertex_shader_layer),
694 EXT(AMD_vertex_shader_viewport_index),
695 EXT(ANDROID_extension_pack_es31a),
696 EXT(EXT_blend_func_extended),
697 EXT(EXT_frag_depth),
698 EXT(EXT_draw_buffers),
699 EXT(EXT_clip_cull_distance),
700 EXT(EXT_geometry_point_size),
701 EXT_AEP(EXT_geometry_shader),
702 EXT_AEP(EXT_gpu_shader5),
703 EXT_AEP(EXT_primitive_bounding_box),
704 EXT(EXT_separate_shader_objects),
705 EXT(EXT_shader_framebuffer_fetch),
706 EXT(EXT_shader_integer_mix),
707 EXT_AEP(EXT_shader_io_blocks),
708 EXT(EXT_shader_samples_identical),
709 EXT(EXT_tessellation_point_size),
710 EXT_AEP(EXT_tessellation_shader),
711 EXT(EXT_texture_array),
712 EXT_AEP(EXT_texture_buffer),
713 EXT_AEP(EXT_texture_cube_map_array),
714 EXT(INTEL_conservative_rasterization),
715 EXT(MESA_shader_integer_functions),
716 EXT(NV_image_formats),
717 };
718
719 #undef EXT
720
721
722 /**
723 * Determine whether a given extension is compatible with the target,
724 * API, and extension information in the current parser state.
725 */
726 bool _mesa_glsl_extension::compatible_with_state(
727 const _mesa_glsl_parse_state *state, gl_api api, uint8_t gl_version) const
728 {
729 return this->available_pred(state->ctx, api, gl_version);
730 }
731
732 /**
733 * Set the appropriate flags in the parser state to establish the
734 * given behavior for this extension.
735 */
736 void _mesa_glsl_extension::set_flags(_mesa_glsl_parse_state *state,
737 ext_behavior behavior) const
738 {
739 /* Note: the ->* operator indexes into state by the
740 * offsets this->enable_flag and this->warn_flag. See
741 * _mesa_glsl_extension::supported_flag for more info.
742 */
743 state->*(this->enable_flag) = (behavior != extension_disable);
744 state->*(this->warn_flag) = (behavior == extension_warn);
745 }
746
747 /**
748 * Find an extension by name in _mesa_glsl_supported_extensions. If
749 * the name is not found, return NULL.
750 */
751 static const _mesa_glsl_extension *find_extension(const char *name)
752 {
753 for (unsigned i = 0; i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
754 if (strcmp(name, _mesa_glsl_supported_extensions[i].name) == 0) {
755 return &_mesa_glsl_supported_extensions[i];
756 }
757 }
758 return NULL;
759 }
760
761 bool
762 _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
763 const char *behavior_string, YYLTYPE *behavior_locp,
764 _mesa_glsl_parse_state *state)
765 {
766 uint8_t gl_version = state->ctx->Extensions.Version;
767 gl_api api = state->ctx->API;
768 ext_behavior behavior;
769 if (strcmp(behavior_string, "warn") == 0) {
770 behavior = extension_warn;
771 } else if (strcmp(behavior_string, "require") == 0) {
772 behavior = extension_require;
773 } else if (strcmp(behavior_string, "enable") == 0) {
774 behavior = extension_enable;
775 } else if (strcmp(behavior_string, "disable") == 0) {
776 behavior = extension_disable;
777 } else {
778 _mesa_glsl_error(behavior_locp, state,
779 "unknown extension behavior `%s'",
780 behavior_string);
781 return false;
782 }
783
784 /* If we're in a desktop context but with an ES shader, use an ES API enum
785 * to verify extension availability.
786 */
787 if (state->es_shader && api != API_OPENGLES2)
788 api = API_OPENGLES2;
789 /* Use the language-version derived GL version to extension checks, unless
790 * we're using meta, which sets the version to the max.
791 */
792 if (gl_version != 0xff)
793 gl_version = state->gl_version;
794
795 if (strcmp(name, "all") == 0) {
796 if ((behavior == extension_enable) || (behavior == extension_require)) {
797 _mesa_glsl_error(name_locp, state, "cannot %s all extensions",
798 (behavior == extension_enable)
799 ? "enable" : "require");
800 return false;
801 } else {
802 for (unsigned i = 0;
803 i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
804 const _mesa_glsl_extension *extension
805 = &_mesa_glsl_supported_extensions[i];
806 if (extension->compatible_with_state(state, api, gl_version)) {
807 _mesa_glsl_supported_extensions[i].set_flags(state, behavior);
808 }
809 }
810 }
811 } else {
812 const _mesa_glsl_extension *extension = find_extension(name);
813 if (extension && extension->compatible_with_state(state, api, gl_version)) {
814 extension->set_flags(state, behavior);
815 if (extension->available_pred == has_ANDROID_extension_pack_es31a) {
816 for (unsigned i = 0;
817 i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
818 const _mesa_glsl_extension *extension =
819 &_mesa_glsl_supported_extensions[i];
820
821 if (!extension->aep)
822 continue;
823 /* AEP should not be enabled if all of the sub-extensions can't
824 * also be enabled. This is not the proper layer to do such
825 * error-checking though.
826 */
827 assert(extension->compatible_with_state(state, api, gl_version));
828 extension->set_flags(state, behavior);
829 }
830 }
831 } else {
832 static const char fmt[] = "extension `%s' unsupported in %s shader";
833
834 if (behavior == extension_require) {
835 _mesa_glsl_error(name_locp, state, fmt,
836 name, _mesa_shader_stage_to_string(state->stage));
837 return false;
838 } else {
839 _mesa_glsl_warning(name_locp, state, fmt,
840 name, _mesa_shader_stage_to_string(state->stage));
841 }
842 }
843 }
844
845 return true;
846 }
847
848
849 /**
850 * Recurses through <type> and <expr> if <expr> is an aggregate initializer
851 * and sets <expr>'s <constructor_type> field to <type>. Gives later functions
852 * (process_array_constructor, et al) sufficient information to do type
853 * checking.
854 *
855 * Operates on assignments involving an aggregate initializer. E.g.,
856 *
857 * vec4 pos = {1.0, -1.0, 0.0, 1.0};
858 *
859 * or more ridiculously,
860 *
861 * struct S {
862 * vec4 v[2];
863 * };
864 *
865 * struct {
866 * S a[2], b;
867 * int c;
868 * } aggregate = {
869 * {
870 * {
871 * {
872 * {1.0, 2.0, 3.0, 4.0}, // a[0].v[0]
873 * {5.0, 6.0, 7.0, 8.0} // a[0].v[1]
874 * } // a[0].v
875 * }, // a[0]
876 * {
877 * {
878 * {1.0, 2.0, 3.0, 4.0}, // a[1].v[0]
879 * {5.0, 6.0, 7.0, 8.0} // a[1].v[1]
880 * } // a[1].v
881 * } // a[1]
882 * }, // a
883 * {
884 * {
885 * {1.0, 2.0, 3.0, 4.0}, // b.v[0]
886 * {5.0, 6.0, 7.0, 8.0} // b.v[1]
887 * } // b.v
888 * }, // b
889 * 4 // c
890 * };
891 *
892 * This pass is necessary because the right-hand side of <type> e = { ... }
893 * doesn't contain sufficient information to determine if the types match.
894 */
895 void
896 _mesa_ast_set_aggregate_type(const glsl_type *type,
897 ast_expression *expr)
898 {
899 ast_aggregate_initializer *ai = (ast_aggregate_initializer *)expr;
900 ai->constructor_type = type;
901
902 /* If the aggregate is an array, recursively set its elements' types. */
903 if (type->is_array()) {
904 /* Each array element has the type type->fields.array.
905 *
906 * E.g., if <type> if struct S[2] we want to set each element's type to
907 * struct S.
908 */
909 for (exec_node *expr_node = ai->expressions.get_head_raw();
910 !expr_node->is_tail_sentinel();
911 expr_node = expr_node->next) {
912 ast_expression *expr = exec_node_data(ast_expression, expr_node,
913 link);
914
915 if (expr->oper == ast_aggregate)
916 _mesa_ast_set_aggregate_type(type->fields.array, expr);
917 }
918
919 /* If the aggregate is a struct, recursively set its fields' types. */
920 } else if (type->is_record()) {
921 exec_node *expr_node = ai->expressions.get_head_raw();
922
923 /* Iterate through the struct's fields. */
924 for (unsigned i = 0; !expr_node->is_tail_sentinel() && i < type->length;
925 i++, expr_node = expr_node->next) {
926 ast_expression *expr = exec_node_data(ast_expression, expr_node,
927 link);
928
929 if (expr->oper == ast_aggregate) {
930 _mesa_ast_set_aggregate_type(type->fields.structure[i].type, expr);
931 }
932 }
933 /* If the aggregate is a matrix, set its columns' types. */
934 } else if (type->is_matrix()) {
935 for (exec_node *expr_node = ai->expressions.get_head_raw();
936 !expr_node->is_tail_sentinel();
937 expr_node = expr_node->next) {
938 ast_expression *expr = exec_node_data(ast_expression, expr_node,
939 link);
940
941 if (expr->oper == ast_aggregate)
942 _mesa_ast_set_aggregate_type(type->column_type(), expr);
943 }
944 }
945 }
946
947 void
948 _mesa_ast_process_interface_block(YYLTYPE *locp,
949 _mesa_glsl_parse_state *state,
950 ast_interface_block *const block,
951 const struct ast_type_qualifier &q)
952 {
953 if (q.flags.q.buffer) {
954 if (!state->has_shader_storage_buffer_objects()) {
955 _mesa_glsl_error(locp, state,
956 "#version 430 / GL_ARB_shader_storage_buffer_object "
957 "required for defining shader storage blocks");
958 } else if (state->ARB_shader_storage_buffer_object_warn) {
959 _mesa_glsl_warning(locp, state,
960 "#version 430 / GL_ARB_shader_storage_buffer_object "
961 "required for defining shader storage blocks");
962 }
963 } else if (q.flags.q.uniform) {
964 if (!state->has_uniform_buffer_objects()) {
965 _mesa_glsl_error(locp, state,
966 "#version 140 / GL_ARB_uniform_buffer_object "
967 "required for defining uniform blocks");
968 } else if (state->ARB_uniform_buffer_object_warn) {
969 _mesa_glsl_warning(locp, state,
970 "#version 140 / GL_ARB_uniform_buffer_object "
971 "required for defining uniform blocks");
972 }
973 } else {
974 if (!state->has_shader_io_blocks()) {
975 if (state->es_shader) {
976 _mesa_glsl_error(locp, state,
977 "GL_OES_shader_io_blocks or #version 320 "
978 "required for using interface blocks");
979 } else {
980 _mesa_glsl_error(locp, state,
981 "#version 150 required for using "
982 "interface blocks");
983 }
984 }
985 }
986
987 /* From the GLSL 1.50.11 spec, section 4.3.7 ("Interface Blocks"):
988 * "It is illegal to have an input block in a vertex shader
989 * or an output block in a fragment shader"
990 */
991 if ((state->stage == MESA_SHADER_VERTEX) && q.flags.q.in) {
992 _mesa_glsl_error(locp, state,
993 "`in' interface block is not allowed for "
994 "a vertex shader");
995 } else if ((state->stage == MESA_SHADER_FRAGMENT) && q.flags.q.out) {
996 _mesa_glsl_error(locp, state,
997 "`out' interface block is not allowed for "
998 "a fragment shader");
999 }
1000
1001 /* Since block arrays require names, and both features are added in
1002 * the same language versions, we don't have to explicitly
1003 * version-check both things.
1004 */
1005 if (block->instance_name != NULL) {
1006 state->check_version(150, 300, locp, "interface blocks with "
1007 "an instance name are not allowed");
1008 }
1009
1010 uint64_t interface_type_mask;
1011 struct ast_type_qualifier temp_type_qualifier;
1012
1013 /* Get a bitmask containing only the in/out/uniform/buffer
1014 * flags, allowing us to ignore other irrelevant flags like
1015 * interpolation qualifiers.
1016 */
1017 temp_type_qualifier.flags.i = 0;
1018 temp_type_qualifier.flags.q.uniform = true;
1019 temp_type_qualifier.flags.q.in = true;
1020 temp_type_qualifier.flags.q.out = true;
1021 temp_type_qualifier.flags.q.buffer = true;
1022 temp_type_qualifier.flags.q.patch = true;
1023 interface_type_mask = temp_type_qualifier.flags.i;
1024
1025 /* Get the block's interface qualifier. The interface_qualifier
1026 * production rule guarantees that only one bit will be set (and
1027 * it will be in/out/uniform).
1028 */
1029 uint64_t block_interface_qualifier = q.flags.i;
1030
1031 block->default_layout.flags.i |= block_interface_qualifier;
1032
1033 if (state->stage == MESA_SHADER_GEOMETRY &&
1034 state->has_explicit_attrib_stream() &&
1035 block->default_layout.flags.q.out) {
1036 /* Assign global layout's stream value. */
1037 block->default_layout.flags.q.stream = 1;
1038 block->default_layout.flags.q.explicit_stream = 0;
1039 block->default_layout.stream = state->out_qualifier->stream;
1040 }
1041
1042 if (state->has_enhanced_layouts() && block->default_layout.flags.q.out) {
1043 /* Assign global layout's xfb_buffer value. */
1044 block->default_layout.flags.q.xfb_buffer = 1;
1045 block->default_layout.flags.q.explicit_xfb_buffer = 0;
1046 block->default_layout.xfb_buffer = state->out_qualifier->xfb_buffer;
1047 }
1048
1049 foreach_list_typed (ast_declarator_list, member, link, &block->declarations) {
1050 ast_type_qualifier& qualifier = member->type->qualifier;
1051 if ((qualifier.flags.i & interface_type_mask) == 0) {
1052 /* GLSLangSpec.1.50.11, 4.3.7 (Interface Blocks):
1053 * "If no optional qualifier is used in a member declaration, the
1054 * qualifier of the variable is just in, out, or uniform as declared
1055 * by interface-qualifier."
1056 */
1057 qualifier.flags.i |= block_interface_qualifier;
1058 } else if ((qualifier.flags.i & interface_type_mask) !=
1059 block_interface_qualifier) {
1060 /* GLSLangSpec.1.50.11, 4.3.7 (Interface Blocks):
1061 * "If optional qualifiers are used, they can include interpolation
1062 * and storage qualifiers and they must declare an input, output,
1063 * or uniform variable consistent with the interface qualifier of
1064 * the block."
1065 */
1066 _mesa_glsl_error(locp, state,
1067 "uniform/in/out qualifier on "
1068 "interface block member does not match "
1069 "the interface block");
1070 }
1071
1072 if (!(q.flags.q.in || q.flags.q.out) && qualifier.flags.q.invariant)
1073 _mesa_glsl_error(locp, state,
1074 "invariant qualifiers can be used only "
1075 "in interface block members for shader "
1076 "inputs or outputs");
1077 }
1078 }
1079
1080 void
1081 _mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
1082 {
1083 if (q->is_subroutine_decl())
1084 printf("subroutine ");
1085
1086 if (q->subroutine_list) {
1087 printf("subroutine (");
1088 q->subroutine_list->print();
1089 printf(")");
1090 }
1091
1092 if (q->flags.q.constant)
1093 printf("const ");
1094
1095 if (q->flags.q.invariant)
1096 printf("invariant ");
1097
1098 if (q->flags.q.attribute)
1099 printf("attribute ");
1100
1101 if (q->flags.q.varying)
1102 printf("varying ");
1103
1104 if (q->flags.q.in && q->flags.q.out)
1105 printf("inout ");
1106 else {
1107 if (q->flags.q.in)
1108 printf("in ");
1109
1110 if (q->flags.q.out)
1111 printf("out ");
1112 }
1113
1114 if (q->flags.q.centroid)
1115 printf("centroid ");
1116 if (q->flags.q.sample)
1117 printf("sample ");
1118 if (q->flags.q.patch)
1119 printf("patch ");
1120 if (q->flags.q.uniform)
1121 printf("uniform ");
1122 if (q->flags.q.buffer)
1123 printf("buffer ");
1124 if (q->flags.q.smooth)
1125 printf("smooth ");
1126 if (q->flags.q.flat)
1127 printf("flat ");
1128 if (q->flags.q.noperspective)
1129 printf("noperspective ");
1130 }
1131
1132
1133 void
1134 ast_node::print(void) const
1135 {
1136 printf("unhandled node ");
1137 }
1138
1139
1140 ast_node::ast_node(void)
1141 {
1142 this->location.source = 0;
1143 this->location.first_line = 0;
1144 this->location.first_column = 0;
1145 this->location.last_line = 0;
1146 this->location.last_column = 0;
1147 }
1148
1149
1150 static void
1151 ast_opt_array_dimensions_print(const ast_array_specifier *array_specifier)
1152 {
1153 if (array_specifier)
1154 array_specifier->print();
1155 }
1156
1157
1158 void
1159 ast_compound_statement::print(void) const
1160 {
1161 printf("{\n");
1162
1163 foreach_list_typed(ast_node, ast, link, &this->statements) {
1164 ast->print();
1165 }
1166
1167 printf("}\n");
1168 }
1169
1170
1171 ast_compound_statement::ast_compound_statement(int new_scope,
1172 ast_node *statements)
1173 {
1174 this->new_scope = new_scope;
1175
1176 if (statements != NULL) {
1177 this->statements.push_degenerate_list_at_head(&statements->link);
1178 }
1179 }
1180
1181
1182 void
1183 ast_expression::print(void) const
1184 {
1185 switch (oper) {
1186 case ast_assign:
1187 case ast_mul_assign:
1188 case ast_div_assign:
1189 case ast_mod_assign:
1190 case ast_add_assign:
1191 case ast_sub_assign:
1192 case ast_ls_assign:
1193 case ast_rs_assign:
1194 case ast_and_assign:
1195 case ast_xor_assign:
1196 case ast_or_assign:
1197 subexpressions[0]->print();
1198 printf("%s ", operator_string(oper));
1199 subexpressions[1]->print();
1200 break;
1201
1202 case ast_field_selection:
1203 subexpressions[0]->print();
1204 printf(". %s ", primary_expression.identifier);
1205 break;
1206
1207 case ast_plus:
1208 case ast_neg:
1209 case ast_bit_not:
1210 case ast_logic_not:
1211 case ast_pre_inc:
1212 case ast_pre_dec:
1213 printf("%s ", operator_string(oper));
1214 subexpressions[0]->print();
1215 break;
1216
1217 case ast_post_inc:
1218 case ast_post_dec:
1219 subexpressions[0]->print();
1220 printf("%s ", operator_string(oper));
1221 break;
1222
1223 case ast_conditional:
1224 subexpressions[0]->print();
1225 printf("? ");
1226 subexpressions[1]->print();
1227 printf(": ");
1228 subexpressions[2]->print();
1229 break;
1230
1231 case ast_array_index:
1232 subexpressions[0]->print();
1233 printf("[ ");
1234 subexpressions[1]->print();
1235 printf("] ");
1236 break;
1237
1238 case ast_function_call: {
1239 subexpressions[0]->print();
1240 printf("( ");
1241
1242 foreach_list_typed (ast_node, ast, link, &this->expressions) {
1243 if (&ast->link != this->expressions.get_head())
1244 printf(", ");
1245
1246 ast->print();
1247 }
1248
1249 printf(") ");
1250 break;
1251 }
1252
1253 case ast_identifier:
1254 printf("%s ", primary_expression.identifier);
1255 break;
1256
1257 case ast_int_constant:
1258 printf("%d ", primary_expression.int_constant);
1259 break;
1260
1261 case ast_uint_constant:
1262 printf("%u ", primary_expression.uint_constant);
1263 break;
1264
1265 case ast_float_constant:
1266 printf("%f ", primary_expression.float_constant);
1267 break;
1268
1269 case ast_double_constant:
1270 printf("%f ", primary_expression.double_constant);
1271 break;
1272
1273 case ast_int64_constant:
1274 printf("%" PRId64 " ", primary_expression.int64_constant);
1275 break;
1276
1277 case ast_uint64_constant:
1278 printf("%" PRIu64 " ", primary_expression.uint64_constant);
1279 break;
1280
1281 case ast_bool_constant:
1282 printf("%s ",
1283 primary_expression.bool_constant
1284 ? "true" : "false");
1285 break;
1286
1287 case ast_sequence: {
1288 printf("( ");
1289 foreach_list_typed (ast_node, ast, link, & this->expressions) {
1290 if (&ast->link != this->expressions.get_head())
1291 printf(", ");
1292
1293 ast->print();
1294 }
1295 printf(") ");
1296 break;
1297 }
1298
1299 case ast_aggregate: {
1300 printf("{ ");
1301 foreach_list_typed (ast_node, ast, link, & this->expressions) {
1302 if (&ast->link != this->expressions.get_head())
1303 printf(", ");
1304
1305 ast->print();
1306 }
1307 printf("} ");
1308 break;
1309 }
1310
1311 default:
1312 assert(0);
1313 break;
1314 }
1315 }
1316
1317 ast_expression::ast_expression(int oper,
1318 ast_expression *ex0,
1319 ast_expression *ex1,
1320 ast_expression *ex2) :
1321 primary_expression()
1322 {
1323 this->oper = ast_operators(oper);
1324 this->subexpressions[0] = ex0;
1325 this->subexpressions[1] = ex1;
1326 this->subexpressions[2] = ex2;
1327 this->non_lvalue_description = NULL;
1328 this->is_lhs = false;
1329 }
1330
1331
1332 void
1333 ast_expression_statement::print(void) const
1334 {
1335 if (expression)
1336 expression->print();
1337
1338 printf("; ");
1339 }
1340
1341
1342 ast_expression_statement::ast_expression_statement(ast_expression *ex) :
1343 expression(ex)
1344 {
1345 /* empty */
1346 }
1347
1348
1349 void
1350 ast_function::print(void) const
1351 {
1352 return_type->print();
1353 printf(" %s (", identifier);
1354
1355 foreach_list_typed(ast_node, ast, link, & this->parameters) {
1356 ast->print();
1357 }
1358
1359 printf(")");
1360 }
1361
1362
1363 ast_function::ast_function(void)
1364 : return_type(NULL), identifier(NULL), is_definition(false),
1365 signature(NULL)
1366 {
1367 /* empty */
1368 }
1369
1370
1371 void
1372 ast_fully_specified_type::print(void) const
1373 {
1374 _mesa_ast_type_qualifier_print(& qualifier);
1375 specifier->print();
1376 }
1377
1378
1379 void
1380 ast_parameter_declarator::print(void) const
1381 {
1382 type->print();
1383 if (identifier)
1384 printf("%s ", identifier);
1385 ast_opt_array_dimensions_print(array_specifier);
1386 }
1387
1388
1389 void
1390 ast_function_definition::print(void) const
1391 {
1392 prototype->print();
1393 body->print();
1394 }
1395
1396
1397 void
1398 ast_declaration::print(void) const
1399 {
1400 printf("%s ", identifier);
1401 ast_opt_array_dimensions_print(array_specifier);
1402
1403 if (initializer) {
1404 printf("= ");
1405 initializer->print();
1406 }
1407 }
1408
1409
1410 ast_declaration::ast_declaration(const char *identifier,
1411 ast_array_specifier *array_specifier,
1412 ast_expression *initializer)
1413 {
1414 this->identifier = identifier;
1415 this->array_specifier = array_specifier;
1416 this->initializer = initializer;
1417 }
1418
1419
1420 void
1421 ast_declarator_list::print(void) const
1422 {
1423 assert(type || invariant);
1424
1425 if (type)
1426 type->print();
1427 else if (invariant)
1428 printf("invariant ");
1429 else
1430 printf("precise ");
1431
1432 foreach_list_typed (ast_node, ast, link, & this->declarations) {
1433 if (&ast->link != this->declarations.get_head())
1434 printf(", ");
1435
1436 ast->print();
1437 }
1438
1439 printf("; ");
1440 }
1441
1442
1443 ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
1444 {
1445 this->type = type;
1446 this->invariant = false;
1447 this->precise = false;
1448 }
1449
1450 void
1451 ast_jump_statement::print(void) const
1452 {
1453 switch (mode) {
1454 case ast_continue:
1455 printf("continue; ");
1456 break;
1457 case ast_break:
1458 printf("break; ");
1459 break;
1460 case ast_return:
1461 printf("return ");
1462 if (opt_return_value)
1463 opt_return_value->print();
1464
1465 printf("; ");
1466 break;
1467 case ast_discard:
1468 printf("discard; ");
1469 break;
1470 }
1471 }
1472
1473
1474 ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
1475 : opt_return_value(NULL)
1476 {
1477 this->mode = ast_jump_modes(mode);
1478
1479 if (mode == ast_return)
1480 opt_return_value = return_value;
1481 }
1482
1483
1484 void
1485 ast_selection_statement::print(void) const
1486 {
1487 printf("if ( ");
1488 condition->print();
1489 printf(") ");
1490
1491 then_statement->print();
1492
1493 if (else_statement) {
1494 printf("else ");
1495 else_statement->print();
1496 }
1497 }
1498
1499
1500 ast_selection_statement::ast_selection_statement(ast_expression *condition,
1501 ast_node *then_statement,
1502 ast_node *else_statement)
1503 {
1504 this->condition = condition;
1505 this->then_statement = then_statement;
1506 this->else_statement = else_statement;
1507 }
1508
1509
1510 void
1511 ast_switch_statement::print(void) const
1512 {
1513 printf("switch ( ");
1514 test_expression->print();
1515 printf(") ");
1516
1517 body->print();
1518 }
1519
1520
1521 ast_switch_statement::ast_switch_statement(ast_expression *test_expression,
1522 ast_node *body)
1523 {
1524 this->test_expression = test_expression;
1525 this->body = body;
1526 }
1527
1528
1529 void
1530 ast_switch_body::print(void) const
1531 {
1532 printf("{\n");
1533 if (stmts != NULL) {
1534 stmts->print();
1535 }
1536 printf("}\n");
1537 }
1538
1539
1540 ast_switch_body::ast_switch_body(ast_case_statement_list *stmts)
1541 {
1542 this->stmts = stmts;
1543 }
1544
1545
1546 void ast_case_label::print(void) const
1547 {
1548 if (test_value != NULL) {
1549 printf("case ");
1550 test_value->print();
1551 printf(": ");
1552 } else {
1553 printf("default: ");
1554 }
1555 }
1556
1557
1558 ast_case_label::ast_case_label(ast_expression *test_value)
1559 {
1560 this->test_value = test_value;
1561 }
1562
1563
1564 void ast_case_label_list::print(void) const
1565 {
1566 foreach_list_typed(ast_node, ast, link, & this->labels) {
1567 ast->print();
1568 }
1569 printf("\n");
1570 }
1571
1572
1573 ast_case_label_list::ast_case_label_list(void)
1574 {
1575 }
1576
1577
1578 void ast_case_statement::print(void) const
1579 {
1580 labels->print();
1581 foreach_list_typed(ast_node, ast, link, & this->stmts) {
1582 ast->print();
1583 printf("\n");
1584 }
1585 }
1586
1587
1588 ast_case_statement::ast_case_statement(ast_case_label_list *labels)
1589 {
1590 this->labels = labels;
1591 }
1592
1593
1594 void ast_case_statement_list::print(void) const
1595 {
1596 foreach_list_typed(ast_node, ast, link, & this->cases) {
1597 ast->print();
1598 }
1599 }
1600
1601
1602 ast_case_statement_list::ast_case_statement_list(void)
1603 {
1604 }
1605
1606
1607 void
1608 ast_iteration_statement::print(void) const
1609 {
1610 switch (mode) {
1611 case ast_for:
1612 printf("for( ");
1613 if (init_statement)
1614 init_statement->print();
1615 printf("; ");
1616
1617 if (condition)
1618 condition->print();
1619 printf("; ");
1620
1621 if (rest_expression)
1622 rest_expression->print();
1623 printf(") ");
1624
1625 body->print();
1626 break;
1627
1628 case ast_while:
1629 printf("while ( ");
1630 if (condition)
1631 condition->print();
1632 printf(") ");
1633 body->print();
1634 break;
1635
1636 case ast_do_while:
1637 printf("do ");
1638 body->print();
1639 printf("while ( ");
1640 if (condition)
1641 condition->print();
1642 printf("); ");
1643 break;
1644 }
1645 }
1646
1647
1648 ast_iteration_statement::ast_iteration_statement(int mode,
1649 ast_node *init,
1650 ast_node *condition,
1651 ast_expression *rest_expression,
1652 ast_node *body)
1653 {
1654 this->mode = ast_iteration_modes(mode);
1655 this->init_statement = init;
1656 this->condition = condition;
1657 this->rest_expression = rest_expression;
1658 this->body = body;
1659 }
1660
1661
1662 void
1663 ast_struct_specifier::print(void) const
1664 {
1665 printf("struct %s { ", name);
1666 foreach_list_typed(ast_node, ast, link, &this->declarations) {
1667 ast->print();
1668 }
1669 printf("} ");
1670 }
1671
1672
1673 ast_struct_specifier::ast_struct_specifier(void *lin_ctx, const char *identifier,
1674 ast_declarator_list *declarator_list)
1675 {
1676 if (identifier == NULL) {
1677 static mtx_t mutex = _MTX_INITIALIZER_NP;
1678 static unsigned anon_count = 1;
1679 unsigned count;
1680
1681 mtx_lock(&mutex);
1682 count = anon_count++;
1683 mtx_unlock(&mutex);
1684
1685 identifier = linear_asprintf(lin_ctx, "#anon_struct_%04x", count);
1686 }
1687 name = identifier;
1688 this->declarations.push_degenerate_list_at_head(&declarator_list->link);
1689 is_declaration = true;
1690 layout = NULL;
1691 }
1692
1693 void ast_subroutine_list::print(void) const
1694 {
1695 foreach_list_typed (ast_node, ast, link, & this->declarations) {
1696 if (&ast->link != this->declarations.get_head())
1697 printf(", ");
1698 ast->print();
1699 }
1700 }
1701
1702 static void
1703 set_shader_inout_layout(struct gl_shader *shader,
1704 struct _mesa_glsl_parse_state *state)
1705 {
1706 /* Should have been prevented by the parser. */
1707 if (shader->Stage == MESA_SHADER_TESS_CTRL ||
1708 shader->Stage == MESA_SHADER_VERTEX) {
1709 assert(!state->in_qualifier->flags.i);
1710 } else if (shader->Stage != MESA_SHADER_GEOMETRY &&
1711 shader->Stage != MESA_SHADER_TESS_EVAL) {
1712 assert(!state->in_qualifier->flags.i);
1713 }
1714
1715 if (shader->Stage != MESA_SHADER_COMPUTE) {
1716 /* Should have been prevented by the parser. */
1717 assert(!state->cs_input_local_size_specified);
1718 assert(!state->cs_input_local_size_variable_specified);
1719 }
1720
1721 if (shader->Stage != MESA_SHADER_FRAGMENT) {
1722 /* Should have been prevented by the parser. */
1723 assert(!state->fs_uses_gl_fragcoord);
1724 assert(!state->fs_redeclares_gl_fragcoord);
1725 assert(!state->fs_pixel_center_integer);
1726 assert(!state->fs_origin_upper_left);
1727 assert(!state->fs_early_fragment_tests);
1728 assert(!state->fs_inner_coverage);
1729 assert(!state->fs_post_depth_coverage);
1730 }
1731
1732 for (unsigned i = 0; i < MAX_FEEDBACK_BUFFERS; i++) {
1733 if (state->out_qualifier->out_xfb_stride[i]) {
1734 unsigned xfb_stride;
1735 if (state->out_qualifier->out_xfb_stride[i]->
1736 process_qualifier_constant(state, "xfb_stride", &xfb_stride,
1737 true)) {
1738 shader->TransformFeedbackBufferStride[i] = xfb_stride;
1739 }
1740 }
1741 }
1742
1743 switch (shader->Stage) {
1744 case MESA_SHADER_TESS_CTRL:
1745 shader->info.TessCtrl.VerticesOut = 0;
1746 if (state->tcs_output_vertices_specified) {
1747 unsigned vertices;
1748 if (state->out_qualifier->vertices->
1749 process_qualifier_constant(state, "vertices", &vertices,
1750 false)) {
1751
1752 YYLTYPE loc = state->out_qualifier->vertices->get_location();
1753 if (vertices > state->Const.MaxPatchVertices) {
1754 _mesa_glsl_error(&loc, state, "vertices (%d) exceeds "
1755 "GL_MAX_PATCH_VERTICES", vertices);
1756 }
1757 shader->info.TessCtrl.VerticesOut = vertices;
1758 }
1759 }
1760 break;
1761 case MESA_SHADER_TESS_EVAL:
1762 shader->info.TessEval.PrimitiveMode = PRIM_UNKNOWN;
1763 if (state->in_qualifier->flags.q.prim_type)
1764 shader->info.TessEval.PrimitiveMode = state->in_qualifier->prim_type;
1765
1766 shader->info.TessEval.Spacing = TESS_SPACING_UNSPECIFIED;
1767 if (state->in_qualifier->flags.q.vertex_spacing)
1768 shader->info.TessEval.Spacing = state->in_qualifier->vertex_spacing;
1769
1770 shader->info.TessEval.VertexOrder = 0;
1771 if (state->in_qualifier->flags.q.ordering)
1772 shader->info.TessEval.VertexOrder = state->in_qualifier->ordering;
1773
1774 shader->info.TessEval.PointMode = -1;
1775 if (state->in_qualifier->flags.q.point_mode)
1776 shader->info.TessEval.PointMode = state->in_qualifier->point_mode;
1777 break;
1778 case MESA_SHADER_GEOMETRY:
1779 shader->info.Geom.VerticesOut = -1;
1780 if (state->out_qualifier->flags.q.max_vertices) {
1781 unsigned qual_max_vertices;
1782 if (state->out_qualifier->max_vertices->
1783 process_qualifier_constant(state, "max_vertices",
1784 &qual_max_vertices, true)) {
1785
1786 if (qual_max_vertices > state->Const.MaxGeometryOutputVertices) {
1787 YYLTYPE loc = state->out_qualifier->max_vertices->get_location();
1788 _mesa_glsl_error(&loc, state,
1789 "maximum output vertices (%d) exceeds "
1790 "GL_MAX_GEOMETRY_OUTPUT_VERTICES",
1791 qual_max_vertices);
1792 }
1793 shader->info.Geom.VerticesOut = qual_max_vertices;
1794 }
1795 }
1796
1797 if (state->gs_input_prim_type_specified) {
1798 shader->info.Geom.InputType = state->in_qualifier->prim_type;
1799 } else {
1800 shader->info.Geom.InputType = PRIM_UNKNOWN;
1801 }
1802
1803 if (state->out_qualifier->flags.q.prim_type) {
1804 shader->info.Geom.OutputType = state->out_qualifier->prim_type;
1805 } else {
1806 shader->info.Geom.OutputType = PRIM_UNKNOWN;
1807 }
1808
1809 shader->info.Geom.Invocations = 0;
1810 if (state->in_qualifier->flags.q.invocations) {
1811 unsigned invocations;
1812 if (state->in_qualifier->invocations->
1813 process_qualifier_constant(state, "invocations",
1814 &invocations, false)) {
1815
1816 YYLTYPE loc = state->in_qualifier->invocations->get_location();
1817 if (invocations > MAX_GEOMETRY_SHADER_INVOCATIONS) {
1818 _mesa_glsl_error(&loc, state,
1819 "invocations (%d) exceeds "
1820 "GL_MAX_GEOMETRY_SHADER_INVOCATIONS",
1821 invocations);
1822 }
1823 shader->info.Geom.Invocations = invocations;
1824 }
1825 }
1826 break;
1827
1828 case MESA_SHADER_COMPUTE:
1829 if (state->cs_input_local_size_specified) {
1830 for (int i = 0; i < 3; i++)
1831 shader->info.Comp.LocalSize[i] = state->cs_input_local_size[i];
1832 } else {
1833 for (int i = 0; i < 3; i++)
1834 shader->info.Comp.LocalSize[i] = 0;
1835 }
1836
1837 shader->info.Comp.LocalSizeVariable =
1838 state->cs_input_local_size_variable_specified;
1839 break;
1840
1841 case MESA_SHADER_FRAGMENT:
1842 shader->redeclares_gl_fragcoord = state->fs_redeclares_gl_fragcoord;
1843 shader->uses_gl_fragcoord = state->fs_uses_gl_fragcoord;
1844 shader->pixel_center_integer = state->fs_pixel_center_integer;
1845 shader->origin_upper_left = state->fs_origin_upper_left;
1846 shader->ARB_fragment_coord_conventions_enable =
1847 state->ARB_fragment_coord_conventions_enable;
1848 shader->EarlyFragmentTests = state->fs_early_fragment_tests;
1849 shader->InnerCoverage = state->fs_inner_coverage;
1850 shader->PostDepthCoverage = state->fs_post_depth_coverage;
1851 shader->BlendSupport = state->fs_blend_support;
1852 break;
1853
1854 default:
1855 /* Nothing to do. */
1856 break;
1857 }
1858
1859 shader->bindless_sampler = state->bindless_sampler_specified;
1860 shader->bindless_image = state->bindless_image_specified;
1861 shader->bound_sampler = state->bound_sampler_specified;
1862 shader->bound_image = state->bound_image_specified;
1863 }
1864
1865 extern "C" {
1866
1867 static void
1868 assign_subroutine_indexes(struct gl_shader *sh,
1869 struct _mesa_glsl_parse_state *state)
1870 {
1871 int j, k;
1872 int index = 0;
1873
1874 for (j = 0; j < state->num_subroutines; j++) {
1875 while (state->subroutines[j]->subroutine_index == -1) {
1876 for (k = 0; k < state->num_subroutines; k++) {
1877 if (state->subroutines[k]->subroutine_index == index)
1878 break;
1879 else if (k == state->num_subroutines - 1) {
1880 state->subroutines[j]->subroutine_index = index;
1881 }
1882 }
1883 index++;
1884 }
1885 }
1886 }
1887
1888 static void
1889 add_builtin_defines(struct _mesa_glsl_parse_state *state,
1890 void (*add_builtin_define)(struct glcpp_parser *, const char *, int),
1891 struct glcpp_parser *data,
1892 unsigned version,
1893 bool es)
1894 {
1895 unsigned gl_version = state->ctx->Extensions.Version;
1896 gl_api api = state->ctx->API;
1897
1898 if (gl_version != 0xff) {
1899 unsigned i;
1900 for (i = 0; i < state->num_supported_versions; i++) {
1901 if (state->supported_versions[i].ver == version &&
1902 state->supported_versions[i].es == es) {
1903 gl_version = state->supported_versions[i].gl_ver;
1904 break;
1905 }
1906 }
1907
1908 if (i == state->num_supported_versions)
1909 return;
1910 }
1911
1912 if (es)
1913 api = API_OPENGLES2;
1914
1915 for (unsigned i = 0;
1916 i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
1917 const _mesa_glsl_extension *extension
1918 = &_mesa_glsl_supported_extensions[i];
1919 if (extension->compatible_with_state(state, api, gl_version)) {
1920 add_builtin_define(data, extension->name, 1);
1921 }
1922 }
1923 }
1924
1925 /* Implements parsing checks that we can't do during parsing */
1926 static void
1927 do_late_parsing_checks(struct _mesa_glsl_parse_state *state)
1928 {
1929 if (state->stage == MESA_SHADER_COMPUTE && !state->has_compute_shader()) {
1930 YYLTYPE loc;
1931 memset(&loc, 0, sizeof(loc));
1932 _mesa_glsl_error(&loc, state, "Compute shaders require "
1933 "GLSL 4.30 or GLSL ES 3.10");
1934 }
1935 }
1936
1937 static void
1938 opt_shader_and_create_symbol_table(struct gl_context *ctx,
1939 struct gl_shader *shader)
1940 {
1941 assert(shader->CompileStatus != compile_failure &&
1942 !shader->ir->is_empty());
1943
1944 struct gl_shader_compiler_options *options =
1945 &ctx->Const.ShaderCompilerOptions[shader->Stage];
1946
1947 /* Do some optimization at compile time to reduce shader IR size
1948 * and reduce later work if the same shader is linked multiple times
1949 */
1950 if (ctx->Const.GLSLOptimizeConservatively) {
1951 /* Run it just once. */
1952 do_common_optimization(shader->ir, false, false, options,
1953 ctx->Const.NativeIntegers);
1954 } else {
1955 /* Repeat it until it stops making changes. */
1956 while (do_common_optimization(shader->ir, false, false, options,
1957 ctx->Const.NativeIntegers))
1958 ;
1959 }
1960
1961 validate_ir_tree(shader->ir);
1962
1963 enum ir_variable_mode other;
1964 switch (shader->Stage) {
1965 case MESA_SHADER_VERTEX:
1966 other = ir_var_shader_in;
1967 break;
1968 case MESA_SHADER_FRAGMENT:
1969 other = ir_var_shader_out;
1970 break;
1971 default:
1972 /* Something invalid to ensure optimize_dead_builtin_uniforms
1973 * doesn't remove anything other than uniforms or constants.
1974 */
1975 other = ir_var_mode_count;
1976 break;
1977 }
1978
1979 optimize_dead_builtin_variables(shader->ir, other);
1980
1981 validate_ir_tree(shader->ir);
1982
1983 /* Retain any live IR, but trash the rest. */
1984 reparent_ir(shader->ir, shader->ir);
1985
1986 /* Destroy the symbol table. Create a new symbol table that contains only
1987 * the variables and functions that still exist in the IR. The symbol
1988 * table will be used later during linking.
1989 *
1990 * There must NOT be any freed objects still referenced by the symbol
1991 * table. That could cause the linker to dereference freed memory.
1992 *
1993 * We don't have to worry about types or interface-types here because those
1994 * are fly-weights that are looked up by glsl_type.
1995 */
1996 foreach_in_list (ir_instruction, ir, shader->ir) {
1997 switch (ir->ir_type) {
1998 case ir_type_function:
1999 shader->symbols->add_function((ir_function *) ir);
2000 break;
2001 case ir_type_variable: {
2002 ir_variable *const var = (ir_variable *) ir;
2003
2004 if (var->data.mode != ir_var_temporary)
2005 shader->symbols->add_variable(var);
2006 break;
2007 }
2008 default:
2009 break;
2010 }
2011 }
2012
2013 _mesa_glsl_initialize_derived_variables(ctx, shader);
2014 }
2015
2016 void
2017 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader,
2018 bool dump_ast, bool dump_hir, bool force_recompile)
2019 {
2020 const char *source = force_recompile && shader->FallbackSource ?
2021 shader->FallbackSource : shader->Source;
2022
2023 if (!force_recompile) {
2024 if (ctx->Cache) {
2025 char buf[41];
2026 disk_cache_compute_key(ctx->Cache, source, strlen(source),
2027 shader->sha1);
2028 if (disk_cache_has_key(ctx->Cache, shader->sha1)) {
2029 /* We've seen this shader before and know it compiles */
2030 if (ctx->_Shader->Flags & GLSL_CACHE_INFO) {
2031 _mesa_sha1_format(buf, shader->sha1);
2032 fprintf(stderr, "deferring compile of shader: %s\n", buf);
2033 }
2034 shader->CompileStatus = compile_skipped;
2035
2036 free((void *)shader->FallbackSource);
2037 shader->FallbackSource = NULL;
2038 return;
2039 }
2040 }
2041 } else {
2042 /* We should only ever end up here if a re-compile has been forced by a
2043 * shader cache miss. In which case we can skip the compile if its
2044 * already be done by a previous fallback or the initial compile call.
2045 */
2046 if (shader->CompileStatus == compile_success)
2047 return;
2048
2049 if (shader->CompileStatus == compiled_no_opts) {
2050 opt_shader_and_create_symbol_table(ctx, shader);
2051 shader->CompileStatus = compile_success;
2052 return;
2053 }
2054 }
2055
2056 struct _mesa_glsl_parse_state *state =
2057 new(shader) _mesa_glsl_parse_state(ctx, shader->Stage, shader);
2058
2059 if (ctx->Const.GenerateTemporaryNames)
2060 (void) p_atomic_cmpxchg(&ir_variable::temporaries_allocate_names,
2061 false, true);
2062
2063 state->error = glcpp_preprocess(state, &source, &state->info_log,
2064 add_builtin_defines, state, ctx);
2065
2066 if (!state->error) {
2067 _mesa_glsl_lexer_ctor(state, source);
2068 _mesa_glsl_parse(state);
2069 _mesa_glsl_lexer_dtor(state);
2070 do_late_parsing_checks(state);
2071 }
2072
2073 if (dump_ast) {
2074 foreach_list_typed(ast_node, ast, link, &state->translation_unit) {
2075 ast->print();
2076 }
2077 printf("\n\n");
2078 }
2079
2080 ralloc_free(shader->ir);
2081 shader->ir = new(shader) exec_list;
2082 if (!state->error && !state->translation_unit.is_empty())
2083 _mesa_ast_to_hir(shader->ir, state);
2084
2085 if (!state->error) {
2086 validate_ir_tree(shader->ir);
2087
2088 /* Print out the unoptimized IR. */
2089 if (dump_hir) {
2090 _mesa_print_ir(stdout, shader->ir, state);
2091 }
2092 }
2093
2094 if (shader->InfoLog)
2095 ralloc_free(shader->InfoLog);
2096
2097 if (!state->error)
2098 set_shader_inout_layout(shader, state);
2099
2100 shader->symbols = new(shader->ir) glsl_symbol_table;
2101 shader->CompileStatus = state->error ? compile_failure : compile_success;
2102 shader->InfoLog = state->info_log;
2103 shader->Version = state->language_version;
2104 shader->IsES = state->es_shader;
2105
2106 if (!state->error && !shader->ir->is_empty()) {
2107 assign_subroutine_indexes(shader, state);
2108 lower_subroutine(shader->ir, state);
2109
2110 if (!ctx->Cache || force_recompile)
2111 opt_shader_and_create_symbol_table(ctx, shader);
2112 else {
2113 reparent_ir(shader->ir, shader->ir);
2114 shader->CompileStatus = compiled_no_opts;
2115 }
2116 }
2117
2118 if (!force_recompile) {
2119 free((void *)shader->FallbackSource);
2120 shader->FallbackSource = NULL;
2121 }
2122
2123 delete state->symbols;
2124 ralloc_free(state);
2125 }
2126
2127 } /* extern "C" */
2128 /**
2129 * Do the set of common optimizations passes
2130 *
2131 * \param ir List of instructions to be optimized
2132 * \param linked Is the shader linked? This enables
2133 * optimizations passes that remove code at
2134 * global scope and could cause linking to
2135 * fail.
2136 * \param uniform_locations_assigned Have locations already been assigned for
2137 * uniforms? This prevents the declarations
2138 * of unused uniforms from being removed.
2139 * The setting of this flag only matters if
2140 * \c linked is \c true.
2141 * \param options The driver's preferred shader options.
2142 * \param native_integers Selects optimizations that depend on the
2143 * implementations supporting integers
2144 * natively (as opposed to supporting
2145 * integers in floating point registers).
2146 */
2147 bool
2148 do_common_optimization(exec_list *ir, bool linked,
2149 bool uniform_locations_assigned,
2150 const struct gl_shader_compiler_options *options,
2151 bool native_integers)
2152 {
2153 const bool debug = false;
2154 GLboolean progress = GL_FALSE;
2155
2156 #define OPT(PASS, ...) do { \
2157 if (debug) { \
2158 fprintf(stderr, "START GLSL optimization %s\n", #PASS); \
2159 const bool opt_progress = PASS(__VA_ARGS__); \
2160 progress = opt_progress || progress; \
2161 if (opt_progress) \
2162 _mesa_print_ir(stderr, ir, NULL); \
2163 fprintf(stderr, "GLSL optimization %s: %s progress\n", \
2164 #PASS, opt_progress ? "made" : "no"); \
2165 } else { \
2166 progress = PASS(__VA_ARGS__) || progress; \
2167 } \
2168 } while (false)
2169
2170 OPT(lower_instructions, ir, SUB_TO_ADD_NEG);
2171
2172 if (linked) {
2173 OPT(do_function_inlining, ir);
2174 OPT(do_dead_functions, ir);
2175 OPT(do_structure_splitting, ir);
2176 }
2177 propagate_invariance(ir);
2178 OPT(do_if_simplification, ir);
2179 OPT(opt_flatten_nested_if_blocks, ir);
2180 OPT(opt_conditional_discard, ir);
2181 OPT(do_copy_propagation, ir);
2182 OPT(do_copy_propagation_elements, ir);
2183
2184 if (options->OptimizeForAOS && !linked)
2185 OPT(opt_flip_matrices, ir);
2186
2187 if (linked && options->OptimizeForAOS) {
2188 OPT(do_vectorize, ir);
2189 }
2190
2191 if (linked)
2192 OPT(do_dead_code, ir, uniform_locations_assigned);
2193 else
2194 OPT(do_dead_code_unlinked, ir);
2195 OPT(do_dead_code_local, ir);
2196 OPT(do_tree_grafting, ir);
2197 OPT(do_constant_propagation, ir);
2198 if (linked)
2199 OPT(do_constant_variable, ir);
2200 else
2201 OPT(do_constant_variable_unlinked, ir);
2202 OPT(do_constant_folding, ir);
2203 OPT(do_minmax_prune, ir);
2204 OPT(do_rebalance_tree, ir);
2205 OPT(do_algebraic, ir, native_integers, options);
2206 OPT(do_lower_jumps, ir, true, true, options->EmitNoMainReturn,
2207 options->EmitNoCont, options->EmitNoLoops);
2208 OPT(do_vec_index_to_swizzle, ir);
2209 OPT(lower_vector_insert, ir, false);
2210 OPT(do_swizzle_swizzle, ir);
2211 OPT(do_noop_swizzle, ir);
2212
2213 OPT(optimize_split_arrays, ir, linked);
2214 OPT(optimize_redundant_jumps, ir);
2215
2216 if (options->MaxUnrollIterations) {
2217 loop_state *ls = analyze_loop_variables(ir);
2218 if (ls->loop_found) {
2219 OPT(set_loop_controls, ir, ls);
2220 OPT(unroll_loops, ir, ls, options);
2221 }
2222 delete ls;
2223 }
2224
2225 #undef OPT
2226
2227 return progress;
2228 }
2229
2230 extern "C" {
2231
2232 /**
2233 * To be called at GL teardown time, this frees compiler datastructures.
2234 *
2235 * After calling this, any previously compiled shaders and shader
2236 * programs would be invalid. So this should happen at approximately
2237 * program exit.
2238 */
2239 void
2240 _mesa_destroy_shader_compiler(void)
2241 {
2242 _mesa_destroy_shader_compiler_caches();
2243
2244 _mesa_glsl_release_types();
2245 }
2246
2247 /**
2248 * Releases compiler caches to trade off performance for memory.
2249 *
2250 * Intended to be used with glReleaseShaderCompiler().
2251 */
2252 void
2253 _mesa_destroy_shader_compiler_caches(void)
2254 {
2255 _mesa_glsl_release_builtin_functions();
2256 }
2257
2258 }