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