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