anv/icd: Advertise the right ABI version
[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 /**
418 * Translate a gl_shader_stage to a short shader stage name for debug
419 * printouts and error messages.
420 */
421 const char *
422 _mesa_shader_stage_to_string(unsigned stage)
423 {
424 switch (stage) {
425 case MESA_SHADER_VERTEX: return "vertex";
426 case MESA_SHADER_FRAGMENT: return "fragment";
427 case MESA_SHADER_GEOMETRY: return "geometry";
428 case MESA_SHADER_COMPUTE: return "compute";
429 case MESA_SHADER_TESS_CTRL: return "tess ctrl";
430 case MESA_SHADER_TESS_EVAL: return "tess eval";
431 }
432
433 unreachable("Unknown shader stage.");
434 }
435
436 /**
437 * Translate a gl_shader_stage to a shader stage abbreviation (VS, GS, FS)
438 * for debug printouts and error messages.
439 */
440 const char *
441 _mesa_shader_stage_to_abbrev(unsigned stage)
442 {
443 switch (stage) {
444 case MESA_SHADER_VERTEX: return "VS";
445 case MESA_SHADER_FRAGMENT: return "FS";
446 case MESA_SHADER_GEOMETRY: return "GS";
447 case MESA_SHADER_COMPUTE: return "CS";
448 case MESA_SHADER_TESS_CTRL: return "TCS";
449 case MESA_SHADER_TESS_EVAL: return "TES";
450 }
451
452 unreachable("Unknown shader stage.");
453 }
454
455 /* This helper function will append the given message to the shader's
456 info log and report it via GL_ARB_debug_output. Per that extension,
457 'type' is one of the enum values classifying the message, and
458 'id' is the implementation-defined ID of the given message. */
459 static void
460 _mesa_glsl_msg(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
461 GLenum type, const char *fmt, va_list ap)
462 {
463 bool error = (type == MESA_DEBUG_TYPE_ERROR);
464 GLuint msg_id = 0;
465
466 assert(state->info_log != NULL);
467
468 /* Get the offset that the new message will be written to. */
469 int msg_offset = strlen(state->info_log);
470
471 ralloc_asprintf_append(&state->info_log, "%u:%u(%u): %s: ",
472 locp->source,
473 locp->first_line,
474 locp->first_column,
475 error ? "error" : "warning");
476 ralloc_vasprintf_append(&state->info_log, fmt, ap);
477
478 const char *const msg = &state->info_log[msg_offset];
479 struct gl_context *ctx = state->ctx;
480
481 /* Report the error via GL_ARB_debug_output. */
482 _mesa_shader_debug(ctx, type, &msg_id, msg, strlen(msg));
483
484 ralloc_strcat(&state->info_log, "\n");
485 }
486
487 void
488 _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
489 const char *fmt, ...)
490 {
491 va_list ap;
492
493 state->error = true;
494
495 va_start(ap, fmt);
496 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_ERROR, fmt, ap);
497 va_end(ap);
498 }
499
500
501 void
502 _mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
503 const char *fmt, ...)
504 {
505 va_list ap;
506
507 va_start(ap, fmt);
508 _mesa_glsl_msg(locp, state, MESA_DEBUG_TYPE_OTHER, fmt, ap);
509 va_end(ap);
510 }
511
512
513 /**
514 * Enum representing the possible behaviors that can be specified in
515 * an #extension directive.
516 */
517 enum ext_behavior {
518 extension_disable,
519 extension_enable,
520 extension_require,
521 extension_warn
522 };
523
524 /**
525 * Element type for _mesa_glsl_supported_extensions
526 */
527 struct _mesa_glsl_extension {
528 /**
529 * Name of the extension when referred to in a GLSL extension
530 * statement
531 */
532 const char *name;
533
534 /** True if this extension is available to desktop GL shaders */
535 bool avail_in_GL;
536
537 /** True if this extension is available to GLES shaders */
538 bool avail_in_ES;
539
540 /**
541 * Flag in the gl_extensions struct indicating whether this
542 * extension is supported by the driver, or
543 * &gl_extensions::dummy_true if supported by all drivers.
544 *
545 * Note: the type (GLboolean gl_extensions::*) is a "pointer to
546 * member" type, the type-safe alternative to the "offsetof" macro.
547 * In a nutshell:
548 *
549 * - foo bar::* p declares p to be an "offset" to a field of type
550 * foo that exists within struct bar
551 * - &bar::baz computes the "offset" of field baz within struct bar
552 * - x.*p accesses the field of x that exists at "offset" p
553 * - x->*p is equivalent to (*x).*p
554 */
555 const GLboolean gl_extensions::* supported_flag;
556
557 /**
558 * Flag in the _mesa_glsl_parse_state struct that should be set
559 * when this extension is enabled.
560 *
561 * See note in _mesa_glsl_extension::supported_flag about "pointer
562 * to member" types.
563 */
564 bool _mesa_glsl_parse_state::* enable_flag;
565
566 /**
567 * Flag in the _mesa_glsl_parse_state struct that should be set
568 * when the shader requests "warn" behavior for this extension.
569 *
570 * See note in _mesa_glsl_extension::supported_flag about "pointer
571 * to member" types.
572 */
573 bool _mesa_glsl_parse_state::* warn_flag;
574
575
576 bool compatible_with_state(const _mesa_glsl_parse_state *state) const;
577 void set_flags(_mesa_glsl_parse_state *state, ext_behavior behavior) const;
578 };
579
580 #define EXT(NAME, GL, ES, SUPPORTED_FLAG) \
581 { "GL_" #NAME, GL, ES, &gl_extensions::SUPPORTED_FLAG, \
582 &_mesa_glsl_parse_state::NAME##_enable, \
583 &_mesa_glsl_parse_state::NAME##_warn }
584
585 /**
586 * Table of extensions that can be enabled/disabled within a shader,
587 * and the conditions under which they are supported.
588 */
589 static const _mesa_glsl_extension _mesa_glsl_supported_extensions[] = {
590 /* API availability */
591 /* name GL ES supported flag */
592
593 /* ARB extensions go here, sorted alphabetically.
594 */
595 EXT(ARB_arrays_of_arrays, true, false, ARB_arrays_of_arrays),
596 EXT(ARB_compute_shader, true, false, ARB_compute_shader),
597 EXT(ARB_conservative_depth, true, false, ARB_conservative_depth),
598 EXT(ARB_derivative_control, true, false, ARB_derivative_control),
599 EXT(ARB_draw_buffers, true, false, dummy_true),
600 EXT(ARB_draw_instanced, true, false, ARB_draw_instanced),
601 EXT(ARB_enhanced_layouts, true, false, ARB_enhanced_layouts),
602 EXT(ARB_explicit_attrib_location, true, false, ARB_explicit_attrib_location),
603 EXT(ARB_explicit_uniform_location, true, false, ARB_explicit_uniform_location),
604 EXT(ARB_fragment_coord_conventions, true, false, ARB_fragment_coord_conventions),
605 EXT(ARB_fragment_layer_viewport, true, false, ARB_fragment_layer_viewport),
606 EXT(ARB_gpu_shader5, true, false, ARB_gpu_shader5),
607 EXT(ARB_gpu_shader_fp64, true, false, ARB_gpu_shader_fp64),
608 EXT(ARB_sample_shading, true, false, ARB_sample_shading),
609 EXT(ARB_separate_shader_objects, true, false, dummy_true),
610 EXT(ARB_shader_atomic_counters, true, false, ARB_shader_atomic_counters),
611 EXT(ARB_shader_bit_encoding, true, false, ARB_shader_bit_encoding),
612 EXT(ARB_shader_clock, true, false, ARB_shader_clock),
613 EXT(ARB_shader_image_load_store, true, false, ARB_shader_image_load_store),
614 EXT(ARB_shader_image_size, true, false, ARB_shader_image_size),
615 EXT(ARB_shader_precision, true, false, ARB_shader_precision),
616 EXT(ARB_shader_stencil_export, true, false, ARB_shader_stencil_export),
617 EXT(ARB_shader_storage_buffer_object, true, true, ARB_shader_storage_buffer_object),
618 EXT(ARB_shader_subroutine, true, false, ARB_shader_subroutine),
619 EXT(ARB_shader_texture_image_samples, true, false, ARB_shader_texture_image_samples),
620 EXT(ARB_shader_texture_lod, true, false, ARB_shader_texture_lod),
621 EXT(ARB_shading_language_420pack, true, false, ARB_shading_language_420pack),
622 EXT(ARB_shading_language_packing, true, false, ARB_shading_language_packing),
623 EXT(ARB_tessellation_shader, true, false, ARB_tessellation_shader),
624 EXT(ARB_texture_cube_map_array, true, false, ARB_texture_cube_map_array),
625 EXT(ARB_texture_gather, true, false, ARB_texture_gather),
626 EXT(ARB_texture_multisample, true, false, ARB_texture_multisample),
627 EXT(ARB_texture_query_levels, true, false, ARB_texture_query_levels),
628 EXT(ARB_texture_query_lod, true, false, ARB_texture_query_lod),
629 EXT(ARB_texture_rectangle, true, false, dummy_true),
630 EXT(ARB_uniform_buffer_object, true, false, ARB_uniform_buffer_object),
631 EXT(ARB_vertex_attrib_64bit, true, false, ARB_vertex_attrib_64bit),
632 EXT(ARB_viewport_array, true, false, ARB_viewport_array),
633
634 /* KHR extensions go here, sorted alphabetically.
635 */
636
637 /* OES extensions go here, sorted alphabetically.
638 */
639 EXT(OES_EGL_image_external, false, true, OES_EGL_image_external),
640 EXT(OES_standard_derivatives, false, true, OES_standard_derivatives),
641 EXT(OES_texture_3D, false, true, dummy_true),
642 EXT(OES_texture_storage_multisample_2d_array, false, true, ARB_texture_multisample),
643
644 /* All other extensions go here, sorted alphabetically.
645 */
646 EXT(AMD_conservative_depth, true, false, ARB_conservative_depth),
647 EXT(AMD_shader_stencil_export, true, false, ARB_shader_stencil_export),
648 EXT(AMD_shader_trinary_minmax, true, false, dummy_true),
649 EXT(AMD_vertex_shader_layer, true, false, AMD_vertex_shader_layer),
650 EXT(AMD_vertex_shader_viewport_index, true, false, AMD_vertex_shader_viewport_index),
651 EXT(EXT_blend_func_extended, false, true, ARB_blend_func_extended),
652 EXT(EXT_draw_buffers, false, true, dummy_true),
653 EXT(EXT_separate_shader_objects, false, true, dummy_true),
654 EXT(EXT_shader_integer_mix, true, true, EXT_shader_integer_mix),
655 EXT(EXT_shader_samples_identical, true, true, EXT_shader_samples_identical),
656 EXT(EXT_texture_array, true, false, EXT_texture_array),
657 };
658
659 #undef EXT
660
661
662 /**
663 * Determine whether a given extension is compatible with the target,
664 * API, and extension information in the current parser state.
665 */
666 bool _mesa_glsl_extension::compatible_with_state(const _mesa_glsl_parse_state *
667 state) const
668 {
669 /* Check that this extension matches whether we are compiling
670 * for desktop GL or GLES.
671 */
672 if (state->es_shader) {
673 if (!this->avail_in_ES) return false;
674 } else {
675 if (!this->avail_in_GL) return false;
676 }
677
678 /* Check that this extension is supported by the OpenGL
679 * implementation.
680 *
681 * Note: the ->* operator indexes into state->extensions by the
682 * offset this->supported_flag. See
683 * _mesa_glsl_extension::supported_flag for more info.
684 */
685 return state->extensions->*(this->supported_flag);
686 }
687
688 /**
689 * Set the appropriate flags in the parser state to establish the
690 * given behavior for this extension.
691 */
692 void _mesa_glsl_extension::set_flags(_mesa_glsl_parse_state *state,
693 ext_behavior behavior) const
694 {
695 /* Note: the ->* operator indexes into state by the
696 * offsets this->enable_flag and this->warn_flag. See
697 * _mesa_glsl_extension::supported_flag for more info.
698 */
699 state->*(this->enable_flag) = (behavior != extension_disable);
700 state->*(this->warn_flag) = (behavior == extension_warn);
701 }
702
703 /**
704 * Find an extension by name in _mesa_glsl_supported_extensions. If
705 * the name is not found, return NULL.
706 */
707 static const _mesa_glsl_extension *find_extension(const char *name)
708 {
709 for (unsigned i = 0; i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
710 if (strcmp(name, _mesa_glsl_supported_extensions[i].name) == 0) {
711 return &_mesa_glsl_supported_extensions[i];
712 }
713 }
714 return NULL;
715 }
716
717
718 bool
719 _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
720 const char *behavior_string, YYLTYPE *behavior_locp,
721 _mesa_glsl_parse_state *state)
722 {
723 ext_behavior behavior;
724 if (strcmp(behavior_string, "warn") == 0) {
725 behavior = extension_warn;
726 } else if (strcmp(behavior_string, "require") == 0) {
727 behavior = extension_require;
728 } else if (strcmp(behavior_string, "enable") == 0) {
729 behavior = extension_enable;
730 } else if (strcmp(behavior_string, "disable") == 0) {
731 behavior = extension_disable;
732 } else {
733 _mesa_glsl_error(behavior_locp, state,
734 "unknown extension behavior `%s'",
735 behavior_string);
736 return false;
737 }
738
739 if (strcmp(name, "all") == 0) {
740 if ((behavior == extension_enable) || (behavior == extension_require)) {
741 _mesa_glsl_error(name_locp, state, "cannot %s all extensions",
742 (behavior == extension_enable)
743 ? "enable" : "require");
744 return false;
745 } else {
746 for (unsigned i = 0;
747 i < ARRAY_SIZE(_mesa_glsl_supported_extensions); ++i) {
748 const _mesa_glsl_extension *extension
749 = &_mesa_glsl_supported_extensions[i];
750 if (extension->compatible_with_state(state)) {
751 _mesa_glsl_supported_extensions[i].set_flags(state, behavior);
752 }
753 }
754 }
755 } else {
756 const _mesa_glsl_extension *extension = find_extension(name);
757 if (extension && extension->compatible_with_state(state)) {
758 extension->set_flags(state, behavior);
759 } else {
760 static const char fmt[] = "extension `%s' unsupported in %s shader";
761
762 if (behavior == extension_require) {
763 _mesa_glsl_error(name_locp, state, fmt,
764 name, _mesa_shader_stage_to_string(state->stage));
765 return false;
766 } else {
767 _mesa_glsl_warning(name_locp, state, fmt,
768 name, _mesa_shader_stage_to_string(state->stage));
769 }
770 }
771 }
772
773 return true;
774 }
775
776
777 /**
778 * Recurses through <type> and <expr> if <expr> is an aggregate initializer
779 * and sets <expr>'s <constructor_type> field to <type>. Gives later functions
780 * (process_array_constructor, et al) sufficient information to do type
781 * checking.
782 *
783 * Operates on assignments involving an aggregate initializer. E.g.,
784 *
785 * vec4 pos = {1.0, -1.0, 0.0, 1.0};
786 *
787 * or more ridiculously,
788 *
789 * struct S {
790 * vec4 v[2];
791 * };
792 *
793 * struct {
794 * S a[2], b;
795 * int c;
796 * } aggregate = {
797 * {
798 * {
799 * {
800 * {1.0, 2.0, 3.0, 4.0}, // a[0].v[0]
801 * {5.0, 6.0, 7.0, 8.0} // a[0].v[1]
802 * } // a[0].v
803 * }, // a[0]
804 * {
805 * {
806 * {1.0, 2.0, 3.0, 4.0}, // a[1].v[0]
807 * {5.0, 6.0, 7.0, 8.0} // a[1].v[1]
808 * } // a[1].v
809 * } // a[1]
810 * }, // a
811 * {
812 * {
813 * {1.0, 2.0, 3.0, 4.0}, // b.v[0]
814 * {5.0, 6.0, 7.0, 8.0} // b.v[1]
815 * } // b.v
816 * }, // b
817 * 4 // c
818 * };
819 *
820 * This pass is necessary because the right-hand side of <type> e = { ... }
821 * doesn't contain sufficient information to determine if the types match.
822 */
823 void
824 _mesa_ast_set_aggregate_type(const glsl_type *type,
825 ast_expression *expr)
826 {
827 ast_aggregate_initializer *ai = (ast_aggregate_initializer *)expr;
828 ai->constructor_type = type;
829
830 /* If the aggregate is an array, recursively set its elements' types. */
831 if (type->is_array()) {
832 /* Each array element has the type type->fields.array.
833 *
834 * E.g., if <type> if struct S[2] we want to set each element's type to
835 * struct S.
836 */
837 for (exec_node *expr_node = ai->expressions.head;
838 !expr_node->is_tail_sentinel();
839 expr_node = expr_node->next) {
840 ast_expression *expr = exec_node_data(ast_expression, expr_node,
841 link);
842
843 if (expr->oper == ast_aggregate)
844 _mesa_ast_set_aggregate_type(type->fields.array, expr);
845 }
846
847 /* If the aggregate is a struct, recursively set its fields' types. */
848 } else if (type->is_record()) {
849 exec_node *expr_node = ai->expressions.head;
850
851 /* Iterate through the struct's fields. */
852 for (unsigned i = 0; !expr_node->is_tail_sentinel() && i < type->length;
853 i++, expr_node = expr_node->next) {
854 ast_expression *expr = exec_node_data(ast_expression, expr_node,
855 link);
856
857 if (expr->oper == ast_aggregate) {
858 _mesa_ast_set_aggregate_type(type->fields.structure[i].type, expr);
859 }
860 }
861 /* If the aggregate is a matrix, set its columns' types. */
862 } else if (type->is_matrix()) {
863 for (exec_node *expr_node = ai->expressions.head;
864 !expr_node->is_tail_sentinel();
865 expr_node = expr_node->next) {
866 ast_expression *expr = exec_node_data(ast_expression, expr_node,
867 link);
868
869 if (expr->oper == ast_aggregate)
870 _mesa_ast_set_aggregate_type(type->column_type(), expr);
871 }
872 }
873 }
874
875 void
876 _mesa_ast_process_interface_block(YYLTYPE *locp,
877 _mesa_glsl_parse_state *state,
878 ast_interface_block *const block,
879 const struct ast_type_qualifier q)
880 {
881 if (q.flags.q.buffer) {
882 if (!state->has_shader_storage_buffer_objects()) {
883 _mesa_glsl_error(locp, state,
884 "#version 430 / GL_ARB_shader_storage_buffer_object "
885 "required for defining shader storage blocks");
886 } else if (state->ARB_shader_storage_buffer_object_warn) {
887 _mesa_glsl_warning(locp, state,
888 "#version 430 / GL_ARB_shader_storage_buffer_object "
889 "required for defining shader storage blocks");
890 }
891 } else if (q.flags.q.uniform) {
892 if (!state->has_uniform_buffer_objects()) {
893 _mesa_glsl_error(locp, state,
894 "#version 140 / GL_ARB_uniform_buffer_object "
895 "required for defining uniform blocks");
896 } else if (state->ARB_uniform_buffer_object_warn) {
897 _mesa_glsl_warning(locp, state,
898 "#version 140 / GL_ARB_uniform_buffer_object "
899 "required for defining uniform blocks");
900 }
901 } else {
902 if (state->es_shader || state->language_version < 150) {
903 _mesa_glsl_error(locp, state,
904 "#version 150 required for using "
905 "interface blocks");
906 }
907 }
908
909 /* From the GLSL 1.50.11 spec, section 4.3.7 ("Interface Blocks"):
910 * "It is illegal to have an input block in a vertex shader
911 * or an output block in a fragment shader"
912 */
913 if ((state->stage == MESA_SHADER_VERTEX) && q.flags.q.in) {
914 _mesa_glsl_error(locp, state,
915 "`in' interface block is not allowed for "
916 "a vertex shader");
917 } else if ((state->stage == MESA_SHADER_FRAGMENT) && q.flags.q.out) {
918 _mesa_glsl_error(locp, state,
919 "`out' interface block is not allowed for "
920 "a fragment shader");
921 }
922
923 /* Since block arrays require names, and both features are added in
924 * the same language versions, we don't have to explicitly
925 * version-check both things.
926 */
927 if (block->instance_name != NULL) {
928 state->check_version(150, 300, locp, "interface blocks with "
929 "an instance name are not allowed");
930 }
931
932 uint64_t interface_type_mask;
933 struct ast_type_qualifier temp_type_qualifier;
934
935 /* Get a bitmask containing only the in/out/uniform/buffer
936 * flags, allowing us to ignore other irrelevant flags like
937 * interpolation qualifiers.
938 */
939 temp_type_qualifier.flags.i = 0;
940 temp_type_qualifier.flags.q.uniform = true;
941 temp_type_qualifier.flags.q.in = true;
942 temp_type_qualifier.flags.q.out = true;
943 temp_type_qualifier.flags.q.buffer = true;
944 interface_type_mask = temp_type_qualifier.flags.i;
945
946 /* Get the block's interface qualifier. The interface_qualifier
947 * production rule guarantees that only one bit will be set (and
948 * it will be in/out/uniform).
949 */
950 uint64_t block_interface_qualifier = q.flags.i;
951
952 block->layout.flags.i |= block_interface_qualifier;
953
954 if (state->stage == MESA_SHADER_GEOMETRY &&
955 state->has_explicit_attrib_stream()) {
956 /* Assign global layout's stream value. */
957 block->layout.flags.q.stream = 1;
958 block->layout.flags.q.explicit_stream = 0;
959 block->layout.stream = state->out_qualifier->stream;
960 }
961
962 foreach_list_typed (ast_declarator_list, member, link, &block->declarations) {
963 ast_type_qualifier& qualifier = member->type->qualifier;
964 if ((qualifier.flags.i & interface_type_mask) == 0) {
965 /* GLSLangSpec.1.50.11, 4.3.7 (Interface Blocks):
966 * "If no optional qualifier is used in a member declaration, the
967 * qualifier of the variable is just in, out, or uniform as declared
968 * by interface-qualifier."
969 */
970 qualifier.flags.i |= block_interface_qualifier;
971 } else if ((qualifier.flags.i & interface_type_mask) !=
972 block_interface_qualifier) {
973 /* GLSLangSpec.1.50.11, 4.3.7 (Interface Blocks):
974 * "If optional qualifiers are used, they can include interpolation
975 * and storage qualifiers and they must declare an input, output,
976 * or uniform variable consistent with the interface qualifier of
977 * the block."
978 */
979 _mesa_glsl_error(locp, state,
980 "uniform/in/out qualifier on "
981 "interface block member does not match "
982 "the interface block");
983 }
984
985 /* From GLSL ES 3.0, chapter 4.3.7 "Interface Blocks":
986 *
987 * "GLSL ES 3.0 does not support interface blocks for shader inputs or
988 * outputs."
989 *
990 * And from GLSL ES 3.0, chapter 4.6.1 "The invariant qualifier":.
991 *
992 * "Only variables output from a shader can be candidates for
993 * invariance."
994 *
995 * From GLSL 4.40 and GLSL 1.50, section "Interface Blocks":
996 *
997 * "If optional qualifiers are used, they can include interpolation
998 * qualifiers, auxiliary storage qualifiers, and storage qualifiers
999 * and they must declare an input, output, or uniform member
1000 * consistent with the interface qualifier of the block"
1001 */
1002 if (qualifier.flags.q.invariant)
1003 _mesa_glsl_error(locp, state,
1004 "invariant qualifiers cannot be used "
1005 "with interface blocks members");
1006 }
1007 }
1008
1009 void
1010 _mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
1011 {
1012 if (q->flags.q.subroutine)
1013 printf("subroutine ");
1014
1015 if (q->flags.q.subroutine_def) {
1016 printf("subroutine (");
1017 q->subroutine_list->print();
1018 printf(")");
1019 }
1020
1021 if (q->flags.q.constant)
1022 printf("const ");
1023
1024 if (q->flags.q.invariant)
1025 printf("invariant ");
1026
1027 if (q->flags.q.attribute)
1028 printf("attribute ");
1029
1030 if (q->flags.q.varying)
1031 printf("varying ");
1032
1033 if (q->flags.q.in && q->flags.q.out)
1034 printf("inout ");
1035 else {
1036 if (q->flags.q.in)
1037 printf("in ");
1038
1039 if (q->flags.q.out)
1040 printf("out ");
1041 }
1042
1043 if (q->flags.q.centroid)
1044 printf("centroid ");
1045 if (q->flags.q.sample)
1046 printf("sample ");
1047 if (q->flags.q.patch)
1048 printf("patch ");
1049 if (q->flags.q.uniform)
1050 printf("uniform ");
1051 if (q->flags.q.buffer)
1052 printf("buffer ");
1053 if (q->flags.q.smooth)
1054 printf("smooth ");
1055 if (q->flags.q.flat)
1056 printf("flat ");
1057 if (q->flags.q.noperspective)
1058 printf("noperspective ");
1059 }
1060
1061
1062 void
1063 ast_node::print(void) const
1064 {
1065 printf("unhandled node ");
1066 }
1067
1068
1069 ast_node::ast_node(void)
1070 {
1071 this->location.source = 0;
1072 this->location.first_line = 0;
1073 this->location.first_column = 0;
1074 this->location.last_line = 0;
1075 this->location.last_column = 0;
1076 }
1077
1078
1079 static void
1080 ast_opt_array_dimensions_print(const ast_array_specifier *array_specifier)
1081 {
1082 if (array_specifier)
1083 array_specifier->print();
1084 }
1085
1086
1087 void
1088 ast_compound_statement::print(void) const
1089 {
1090 printf("{\n");
1091
1092 foreach_list_typed(ast_node, ast, link, &this->statements) {
1093 ast->print();
1094 }
1095
1096 printf("}\n");
1097 }
1098
1099
1100 ast_compound_statement::ast_compound_statement(int new_scope,
1101 ast_node *statements)
1102 {
1103 this->new_scope = new_scope;
1104
1105 if (statements != NULL) {
1106 this->statements.push_degenerate_list_at_head(&statements->link);
1107 }
1108 }
1109
1110
1111 void
1112 ast_expression::print(void) const
1113 {
1114 switch (oper) {
1115 case ast_assign:
1116 case ast_mul_assign:
1117 case ast_div_assign:
1118 case ast_mod_assign:
1119 case ast_add_assign:
1120 case ast_sub_assign:
1121 case ast_ls_assign:
1122 case ast_rs_assign:
1123 case ast_and_assign:
1124 case ast_xor_assign:
1125 case ast_or_assign:
1126 subexpressions[0]->print();
1127 printf("%s ", operator_string(oper));
1128 subexpressions[1]->print();
1129 break;
1130
1131 case ast_field_selection:
1132 subexpressions[0]->print();
1133 printf(". %s ", primary_expression.identifier);
1134 break;
1135
1136 case ast_plus:
1137 case ast_neg:
1138 case ast_bit_not:
1139 case ast_logic_not:
1140 case ast_pre_inc:
1141 case ast_pre_dec:
1142 printf("%s ", operator_string(oper));
1143 subexpressions[0]->print();
1144 break;
1145
1146 case ast_post_inc:
1147 case ast_post_dec:
1148 subexpressions[0]->print();
1149 printf("%s ", operator_string(oper));
1150 break;
1151
1152 case ast_conditional:
1153 subexpressions[0]->print();
1154 printf("? ");
1155 subexpressions[1]->print();
1156 printf(": ");
1157 subexpressions[2]->print();
1158 break;
1159
1160 case ast_array_index:
1161 subexpressions[0]->print();
1162 printf("[ ");
1163 subexpressions[1]->print();
1164 printf("] ");
1165 break;
1166
1167 case ast_function_call: {
1168 subexpressions[0]->print();
1169 printf("( ");
1170
1171 foreach_list_typed (ast_node, ast, link, &this->expressions) {
1172 if (&ast->link != this->expressions.get_head())
1173 printf(", ");
1174
1175 ast->print();
1176 }
1177
1178 printf(") ");
1179 break;
1180 }
1181
1182 case ast_identifier:
1183 printf("%s ", primary_expression.identifier);
1184 break;
1185
1186 case ast_int_constant:
1187 printf("%d ", primary_expression.int_constant);
1188 break;
1189
1190 case ast_uint_constant:
1191 printf("%u ", primary_expression.uint_constant);
1192 break;
1193
1194 case ast_float_constant:
1195 printf("%f ", primary_expression.float_constant);
1196 break;
1197
1198 case ast_double_constant:
1199 printf("%f ", primary_expression.double_constant);
1200 break;
1201
1202 case ast_bool_constant:
1203 printf("%s ",
1204 primary_expression.bool_constant
1205 ? "true" : "false");
1206 break;
1207
1208 case ast_sequence: {
1209 printf("( ");
1210 foreach_list_typed (ast_node, ast, link, & this->expressions) {
1211 if (&ast->link != this->expressions.get_head())
1212 printf(", ");
1213
1214 ast->print();
1215 }
1216 printf(") ");
1217 break;
1218 }
1219
1220 case ast_aggregate: {
1221 printf("{ ");
1222 foreach_list_typed (ast_node, ast, link, & this->expressions) {
1223 if (&ast->link != this->expressions.get_head())
1224 printf(", ");
1225
1226 ast->print();
1227 }
1228 printf("} ");
1229 break;
1230 }
1231
1232 default:
1233 assert(0);
1234 break;
1235 }
1236 }
1237
1238 ast_expression::ast_expression(int oper,
1239 ast_expression *ex0,
1240 ast_expression *ex1,
1241 ast_expression *ex2) :
1242 primary_expression()
1243 {
1244 this->oper = ast_operators(oper);
1245 this->subexpressions[0] = ex0;
1246 this->subexpressions[1] = ex1;
1247 this->subexpressions[2] = ex2;
1248 this->non_lvalue_description = NULL;
1249 }
1250
1251
1252 void
1253 ast_expression_statement::print(void) const
1254 {
1255 if (expression)
1256 expression->print();
1257
1258 printf("; ");
1259 }
1260
1261
1262 ast_expression_statement::ast_expression_statement(ast_expression *ex) :
1263 expression(ex)
1264 {
1265 /* empty */
1266 }
1267
1268
1269 void
1270 ast_function::print(void) const
1271 {
1272 return_type->print();
1273 printf(" %s (", identifier);
1274
1275 foreach_list_typed(ast_node, ast, link, & this->parameters) {
1276 ast->print();
1277 }
1278
1279 printf(")");
1280 }
1281
1282
1283 ast_function::ast_function(void)
1284 : return_type(NULL), identifier(NULL), is_definition(false),
1285 signature(NULL)
1286 {
1287 /* empty */
1288 }
1289
1290
1291 void
1292 ast_fully_specified_type::print(void) const
1293 {
1294 _mesa_ast_type_qualifier_print(& qualifier);
1295 specifier->print();
1296 }
1297
1298
1299 void
1300 ast_parameter_declarator::print(void) const
1301 {
1302 type->print();
1303 if (identifier)
1304 printf("%s ", identifier);
1305 ast_opt_array_dimensions_print(array_specifier);
1306 }
1307
1308
1309 void
1310 ast_function_definition::print(void) const
1311 {
1312 prototype->print();
1313 body->print();
1314 }
1315
1316
1317 void
1318 ast_declaration::print(void) const
1319 {
1320 printf("%s ", identifier);
1321 ast_opt_array_dimensions_print(array_specifier);
1322
1323 if (initializer) {
1324 printf("= ");
1325 initializer->print();
1326 }
1327 }
1328
1329
1330 ast_declaration::ast_declaration(const char *identifier,
1331 ast_array_specifier *array_specifier,
1332 ast_expression *initializer)
1333 {
1334 this->identifier = identifier;
1335 this->array_specifier = array_specifier;
1336 this->initializer = initializer;
1337 }
1338
1339
1340 void
1341 ast_declarator_list::print(void) const
1342 {
1343 assert(type || invariant);
1344
1345 if (type)
1346 type->print();
1347 else if (invariant)
1348 printf("invariant ");
1349 else
1350 printf("precise ");
1351
1352 foreach_list_typed (ast_node, ast, link, & this->declarations) {
1353 if (&ast->link != this->declarations.get_head())
1354 printf(", ");
1355
1356 ast->print();
1357 }
1358
1359 printf("; ");
1360 }
1361
1362
1363 ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
1364 {
1365 this->type = type;
1366 this->invariant = false;
1367 this->precise = false;
1368 }
1369
1370 void
1371 ast_jump_statement::print(void) const
1372 {
1373 switch (mode) {
1374 case ast_continue:
1375 printf("continue; ");
1376 break;
1377 case ast_break:
1378 printf("break; ");
1379 break;
1380 case ast_return:
1381 printf("return ");
1382 if (opt_return_value)
1383 opt_return_value->print();
1384
1385 printf("; ");
1386 break;
1387 case ast_discard:
1388 printf("discard; ");
1389 break;
1390 }
1391 }
1392
1393
1394 ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
1395 : opt_return_value(NULL)
1396 {
1397 this->mode = ast_jump_modes(mode);
1398
1399 if (mode == ast_return)
1400 opt_return_value = return_value;
1401 }
1402
1403
1404 void
1405 ast_selection_statement::print(void) const
1406 {
1407 printf("if ( ");
1408 condition->print();
1409 printf(") ");
1410
1411 then_statement->print();
1412
1413 if (else_statement) {
1414 printf("else ");
1415 else_statement->print();
1416 }
1417
1418 }
1419
1420
1421 ast_selection_statement::ast_selection_statement(ast_expression *condition,
1422 ast_node *then_statement,
1423 ast_node *else_statement)
1424 {
1425 this->condition = condition;
1426 this->then_statement = then_statement;
1427 this->else_statement = else_statement;
1428 }
1429
1430
1431 void
1432 ast_switch_statement::print(void) const
1433 {
1434 printf("switch ( ");
1435 test_expression->print();
1436 printf(") ");
1437
1438 body->print();
1439 }
1440
1441
1442 ast_switch_statement::ast_switch_statement(ast_expression *test_expression,
1443 ast_node *body)
1444 {
1445 this->test_expression = test_expression;
1446 this->body = body;
1447 }
1448
1449
1450 void
1451 ast_switch_body::print(void) const
1452 {
1453 printf("{\n");
1454 if (stmts != NULL) {
1455 stmts->print();
1456 }
1457 printf("}\n");
1458 }
1459
1460
1461 ast_switch_body::ast_switch_body(ast_case_statement_list *stmts)
1462 {
1463 this->stmts = stmts;
1464 }
1465
1466
1467 void ast_case_label::print(void) const
1468 {
1469 if (test_value != NULL) {
1470 printf("case ");
1471 test_value->print();
1472 printf(": ");
1473 } else {
1474 printf("default: ");
1475 }
1476 }
1477
1478
1479 ast_case_label::ast_case_label(ast_expression *test_value)
1480 {
1481 this->test_value = test_value;
1482 }
1483
1484
1485 void ast_case_label_list::print(void) const
1486 {
1487 foreach_list_typed(ast_node, ast, link, & this->labels) {
1488 ast->print();
1489 }
1490 printf("\n");
1491 }
1492
1493
1494 ast_case_label_list::ast_case_label_list(void)
1495 {
1496 }
1497
1498
1499 void ast_case_statement::print(void) const
1500 {
1501 labels->print();
1502 foreach_list_typed(ast_node, ast, link, & this->stmts) {
1503 ast->print();
1504 printf("\n");
1505 }
1506 }
1507
1508
1509 ast_case_statement::ast_case_statement(ast_case_label_list *labels)
1510 {
1511 this->labels = labels;
1512 }
1513
1514
1515 void ast_case_statement_list::print(void) const
1516 {
1517 foreach_list_typed(ast_node, ast, link, & this->cases) {
1518 ast->print();
1519 }
1520 }
1521
1522
1523 ast_case_statement_list::ast_case_statement_list(void)
1524 {
1525 }
1526
1527
1528 void
1529 ast_iteration_statement::print(void) const
1530 {
1531 switch (mode) {
1532 case ast_for:
1533 printf("for( ");
1534 if (init_statement)
1535 init_statement->print();
1536 printf("; ");
1537
1538 if (condition)
1539 condition->print();
1540 printf("; ");
1541
1542 if (rest_expression)
1543 rest_expression->print();
1544 printf(") ");
1545
1546 body->print();
1547 break;
1548
1549 case ast_while:
1550 printf("while ( ");
1551 if (condition)
1552 condition->print();
1553 printf(") ");
1554 body->print();
1555 break;
1556
1557 case ast_do_while:
1558 printf("do ");
1559 body->print();
1560 printf("while ( ");
1561 if (condition)
1562 condition->print();
1563 printf("); ");
1564 break;
1565 }
1566 }
1567
1568
1569 ast_iteration_statement::ast_iteration_statement(int mode,
1570 ast_node *init,
1571 ast_node *condition,
1572 ast_expression *rest_expression,
1573 ast_node *body)
1574 {
1575 this->mode = ast_iteration_modes(mode);
1576 this->init_statement = init;
1577 this->condition = condition;
1578 this->rest_expression = rest_expression;
1579 this->body = body;
1580 }
1581
1582
1583 void
1584 ast_struct_specifier::print(void) const
1585 {
1586 printf("struct %s { ", name);
1587 foreach_list_typed(ast_node, ast, link, &this->declarations) {
1588 ast->print();
1589 }
1590 printf("} ");
1591 }
1592
1593
1594 ast_struct_specifier::ast_struct_specifier(const char *identifier,
1595 ast_declarator_list *declarator_list)
1596 {
1597 if (identifier == NULL) {
1598 static mtx_t mutex = _MTX_INITIALIZER_NP;
1599 static unsigned anon_count = 1;
1600 unsigned count;
1601
1602 mtx_lock(&mutex);
1603 count = anon_count++;
1604 mtx_unlock(&mutex);
1605
1606 identifier = ralloc_asprintf(this, "#anon_struct_%04x", count);
1607 }
1608 name = identifier;
1609 this->declarations.push_degenerate_list_at_head(&declarator_list->link);
1610 is_declaration = true;
1611 }
1612
1613 void ast_subroutine_list::print(void) const
1614 {
1615 foreach_list_typed (ast_node, ast, link, & this->declarations) {
1616 if (&ast->link != this->declarations.get_head())
1617 printf(", ");
1618 ast->print();
1619 }
1620 }
1621
1622 static void
1623 set_shader_inout_layout(struct gl_shader *shader,
1624 struct _mesa_glsl_parse_state *state)
1625 {
1626 /* Should have been prevented by the parser. */
1627 if (shader->Stage == MESA_SHADER_TESS_CTRL) {
1628 assert(!state->in_qualifier->flags.i);
1629 } else if (shader->Stage == MESA_SHADER_TESS_EVAL) {
1630 assert(!state->out_qualifier->flags.i);
1631 } else if (shader->Stage != MESA_SHADER_GEOMETRY) {
1632 assert(!state->in_qualifier->flags.i);
1633 assert(!state->out_qualifier->flags.i);
1634 }
1635
1636 if (shader->Stage != MESA_SHADER_COMPUTE) {
1637 /* Should have been prevented by the parser. */
1638 assert(!state->cs_input_local_size_specified);
1639 }
1640
1641 if (shader->Stage != MESA_SHADER_FRAGMENT) {
1642 /* Should have been prevented by the parser. */
1643 assert(!state->fs_uses_gl_fragcoord);
1644 assert(!state->fs_redeclares_gl_fragcoord);
1645 assert(!state->fs_pixel_center_integer);
1646 assert(!state->fs_origin_upper_left);
1647 assert(!state->fs_early_fragment_tests);
1648 }
1649
1650 switch (shader->Stage) {
1651 case MESA_SHADER_TESS_CTRL:
1652 shader->TessCtrl.VerticesOut = 0;
1653 if (state->tcs_output_vertices_specified) {
1654 unsigned vertices;
1655 if (state->out_qualifier->vertices->
1656 process_qualifier_constant(state, "vertices", &vertices,
1657 false)) {
1658
1659 YYLTYPE loc = state->out_qualifier->vertices->get_location();
1660 if (vertices > state->Const.MaxPatchVertices) {
1661 _mesa_glsl_error(&loc, state, "vertices (%d) exceeds "
1662 "GL_MAX_PATCH_VERTICES", vertices);
1663 }
1664 shader->TessCtrl.VerticesOut = vertices;
1665 }
1666 }
1667 break;
1668 case MESA_SHADER_TESS_EVAL:
1669 shader->TessEval.PrimitiveMode = PRIM_UNKNOWN;
1670 if (state->in_qualifier->flags.q.prim_type)
1671 shader->TessEval.PrimitiveMode = state->in_qualifier->prim_type;
1672
1673 shader->TessEval.Spacing = 0;
1674 if (state->in_qualifier->flags.q.vertex_spacing)
1675 shader->TessEval.Spacing = state->in_qualifier->vertex_spacing;
1676
1677 shader->TessEval.VertexOrder = 0;
1678 if (state->in_qualifier->flags.q.ordering)
1679 shader->TessEval.VertexOrder = state->in_qualifier->ordering;
1680
1681 shader->TessEval.PointMode = -1;
1682 if (state->in_qualifier->flags.q.point_mode)
1683 shader->TessEval.PointMode = state->in_qualifier->point_mode;
1684 break;
1685 case MESA_SHADER_GEOMETRY:
1686 shader->Geom.VerticesOut = 0;
1687 if (state->out_qualifier->flags.q.max_vertices) {
1688 unsigned qual_max_vertices;
1689 if (state->out_qualifier->max_vertices->
1690 process_qualifier_constant(state, "max_vertices",
1691 &qual_max_vertices, true)) {
1692 shader->Geom.VerticesOut = qual_max_vertices;
1693 }
1694 }
1695
1696 if (state->gs_input_prim_type_specified) {
1697 shader->Geom.InputType = state->in_qualifier->prim_type;
1698 } else {
1699 shader->Geom.InputType = PRIM_UNKNOWN;
1700 }
1701
1702 if (state->out_qualifier->flags.q.prim_type) {
1703 shader->Geom.OutputType = state->out_qualifier->prim_type;
1704 } else {
1705 shader->Geom.OutputType = PRIM_UNKNOWN;
1706 }
1707
1708 shader->Geom.Invocations = 0;
1709 if (state->in_qualifier->flags.q.invocations) {
1710 unsigned invocations;
1711 if (state->in_qualifier->invocations->
1712 process_qualifier_constant(state, "invocations",
1713 &invocations, false)) {
1714
1715 YYLTYPE loc = state->in_qualifier->invocations->get_location();
1716 if (invocations > MAX_GEOMETRY_SHADER_INVOCATIONS) {
1717 _mesa_glsl_error(&loc, state,
1718 "invocations (%d) exceeds "
1719 "GL_MAX_GEOMETRY_SHADER_INVOCATIONS",
1720 invocations);
1721 }
1722 shader->Geom.Invocations = invocations;
1723 }
1724 }
1725 break;
1726
1727 case MESA_SHADER_COMPUTE:
1728 if (state->cs_input_local_size_specified) {
1729 for (int i = 0; i < 3; i++)
1730 shader->Comp.LocalSize[i] = state->cs_input_local_size[i];
1731 } else {
1732 for (int i = 0; i < 3; i++)
1733 shader->Comp.LocalSize[i] = 0;
1734 }
1735 break;
1736
1737 case MESA_SHADER_FRAGMENT:
1738 shader->redeclares_gl_fragcoord = state->fs_redeclares_gl_fragcoord;
1739 shader->uses_gl_fragcoord = state->fs_uses_gl_fragcoord;
1740 shader->pixel_center_integer = state->fs_pixel_center_integer;
1741 shader->origin_upper_left = state->fs_origin_upper_left;
1742 shader->ARB_fragment_coord_conventions_enable =
1743 state->ARB_fragment_coord_conventions_enable;
1744 shader->EarlyFragmentTests = state->fs_early_fragment_tests;
1745 break;
1746
1747 default:
1748 /* Nothing to do. */
1749 break;
1750 }
1751 }
1752
1753 extern "C" {
1754
1755 void
1756 _mesa_glsl_compile_shader(struct gl_context *ctx, struct gl_shader *shader,
1757 bool dump_ast, bool dump_hir)
1758 {
1759 struct _mesa_glsl_parse_state *state =
1760 new(shader) _mesa_glsl_parse_state(ctx, shader->Stage, shader);
1761 const char *source = shader->Source;
1762
1763 if (ctx->Const.GenerateTemporaryNames)
1764 (void) p_atomic_cmpxchg(&ir_variable::temporaries_allocate_names,
1765 false, true);
1766
1767 state->error = glcpp_preprocess(state, &source, &state->info_log,
1768 &ctx->Extensions, ctx);
1769
1770 if (!state->error) {
1771 _mesa_glsl_lexer_ctor(state, source);
1772 _mesa_glsl_parse(state);
1773 _mesa_glsl_lexer_dtor(state);
1774 }
1775
1776 if (dump_ast) {
1777 foreach_list_typed(ast_node, ast, link, &state->translation_unit) {
1778 ast->print();
1779 }
1780 printf("\n\n");
1781 }
1782
1783 ralloc_free(shader->ir);
1784 shader->ir = new(shader) exec_list;
1785 if (!state->error && !state->translation_unit.is_empty())
1786 _mesa_ast_to_hir(shader->ir, state);
1787
1788 if (!state->error) {
1789 validate_ir_tree(shader->ir);
1790
1791 /* Print out the unoptimized IR. */
1792 if (dump_hir) {
1793 _mesa_print_ir(stdout, shader->ir, state);
1794 }
1795 }
1796
1797
1798 if (!state->error && !shader->ir->is_empty()) {
1799 struct gl_shader_compiler_options *options =
1800 &ctx->Const.ShaderCompilerOptions[shader->Stage];
1801
1802 lower_subroutine(shader->ir, state);
1803 /* Do some optimization at compile time to reduce shader IR size
1804 * and reduce later work if the same shader is linked multiple times
1805 */
1806 while (do_common_optimization(shader->ir, false, false, options,
1807 ctx->Const.NativeIntegers))
1808 ;
1809
1810 validate_ir_tree(shader->ir);
1811
1812 enum ir_variable_mode other;
1813 switch (shader->Stage) {
1814 case MESA_SHADER_VERTEX:
1815 other = ir_var_shader_in;
1816 break;
1817 case MESA_SHADER_FRAGMENT:
1818 other = ir_var_shader_out;
1819 break;
1820 default:
1821 /* Something invalid to ensure optimize_dead_builtin_uniforms
1822 * doesn't remove anything other than uniforms or constants.
1823 */
1824 other = ir_var_mode_count;
1825 break;
1826 }
1827
1828 optimize_dead_builtin_variables(shader->ir, other);
1829
1830 validate_ir_tree(shader->ir);
1831 }
1832
1833 if (shader->InfoLog)
1834 ralloc_free(shader->InfoLog);
1835
1836 if (!state->error)
1837 set_shader_inout_layout(shader, state);
1838
1839 shader->symbols = new(shader->ir) glsl_symbol_table;
1840 shader->CompileStatus = !state->error;
1841 shader->InfoLog = state->info_log;
1842 shader->Version = state->language_version;
1843 shader->IsES = state->es_shader;
1844 shader->uses_builtin_functions = state->uses_builtin_functions;
1845
1846 /* Retain any live IR, but trash the rest. */
1847 reparent_ir(shader->ir, shader->ir);
1848
1849 /* Destroy the symbol table. Create a new symbol table that contains only
1850 * the variables and functions that still exist in the IR. The symbol
1851 * table will be used later during linking.
1852 *
1853 * There must NOT be any freed objects still referenced by the symbol
1854 * table. That could cause the linker to dereference freed memory.
1855 *
1856 * We don't have to worry about types or interface-types here because those
1857 * are fly-weights that are looked up by glsl_type.
1858 */
1859 foreach_in_list (ir_instruction, ir, shader->ir) {
1860 switch (ir->ir_type) {
1861 case ir_type_function:
1862 shader->symbols->add_function((ir_function *) ir);
1863 break;
1864 case ir_type_variable: {
1865 ir_variable *const var = (ir_variable *) ir;
1866
1867 if (var->data.mode != ir_var_temporary)
1868 shader->symbols->add_variable(var);
1869 break;
1870 }
1871 default:
1872 break;
1873 }
1874 }
1875
1876 _mesa_glsl_initialize_derived_variables(shader);
1877
1878 delete state->symbols;
1879 ralloc_free(state);
1880 }
1881
1882 } /* extern "C" */
1883 /**
1884 * Do the set of common optimizations passes
1885 *
1886 * \param ir List of instructions to be optimized
1887 * \param linked Is the shader linked? This enables
1888 * optimizations passes that remove code at
1889 * global scope and could cause linking to
1890 * fail.
1891 * \param uniform_locations_assigned Have locations already been assigned for
1892 * uniforms? This prevents the declarations
1893 * of unused uniforms from being removed.
1894 * The setting of this flag only matters if
1895 * \c linked is \c true.
1896 * \param max_unroll_iterations Maximum number of loop iterations to be
1897 * unrolled. Setting to 0 disables loop
1898 * unrolling.
1899 * \param options The driver's preferred shader options.
1900 */
1901 bool
1902 do_common_optimization(exec_list *ir, bool linked,
1903 bool uniform_locations_assigned,
1904 const struct gl_shader_compiler_options *options,
1905 bool native_integers)
1906 {
1907 GLboolean progress = GL_FALSE;
1908
1909 progress = lower_instructions(ir, SUB_TO_ADD_NEG) || progress;
1910
1911 if (linked) {
1912 progress = do_function_inlining(ir) || progress;
1913 progress = do_dead_functions(ir) || progress;
1914 progress = do_structure_splitting(ir) || progress;
1915 }
1916 progress = do_if_simplification(ir) || progress;
1917 progress = opt_flatten_nested_if_blocks(ir) || progress;
1918 progress = opt_conditional_discard(ir) || progress;
1919 progress = do_copy_propagation(ir) || progress;
1920 progress = do_copy_propagation_elements(ir) || progress;
1921
1922 if (options->OptimizeForAOS && !linked)
1923 progress = opt_flip_matrices(ir) || progress;
1924
1925 if (linked && options->OptimizeForAOS) {
1926 progress = do_vectorize(ir) || progress;
1927 }
1928
1929 if (linked)
1930 progress = do_dead_code(ir, uniform_locations_assigned) || progress;
1931 else
1932 progress = do_dead_code_unlinked(ir) || progress;
1933 progress = do_dead_code_local(ir) || progress;
1934 progress = do_tree_grafting(ir) || progress;
1935 progress = do_constant_propagation(ir) || progress;
1936 if (linked)
1937 progress = do_constant_variable(ir) || progress;
1938 else
1939 progress = do_constant_variable_unlinked(ir) || progress;
1940 progress = do_constant_folding(ir) || progress;
1941 progress = do_minmax_prune(ir) || progress;
1942 progress = do_rebalance_tree(ir) || progress;
1943 progress = do_algebraic(ir, native_integers, options) || progress;
1944 progress = do_lower_jumps(ir) || progress;
1945 progress = do_vec_index_to_swizzle(ir) || progress;
1946 progress = lower_vector_insert(ir, false) || progress;
1947 progress = do_swizzle_swizzle(ir) || progress;
1948 progress = do_noop_swizzle(ir) || progress;
1949
1950 progress = optimize_split_arrays(ir, linked) || progress;
1951 progress = optimize_redundant_jumps(ir) || progress;
1952
1953 loop_state *ls = analyze_loop_variables(ir);
1954 if (ls->loop_found) {
1955 progress = set_loop_controls(ir, ls) || progress;
1956 progress = unroll_loops(ir, ls, options) || progress;
1957 }
1958 delete ls;
1959
1960 return progress;
1961 }
1962
1963 extern "C" {
1964
1965 /**
1966 * To be called at GL teardown time, this frees compiler datastructures.
1967 *
1968 * After calling this, any previously compiled shaders and shader
1969 * programs would be invalid. So this should happen at approximately
1970 * program exit.
1971 */
1972 void
1973 _mesa_destroy_shader_compiler(void)
1974 {
1975 _mesa_destroy_shader_compiler_caches();
1976
1977 _mesa_glsl_release_types();
1978 }
1979
1980 /**
1981 * Releases compiler caches to trade off performance for memory.
1982 *
1983 * Intended to be used with glReleaseShaderCompiler().
1984 */
1985 void
1986 _mesa_destroy_shader_compiler_caches(void)
1987 {
1988 _mesa_glsl_release_builtin_functions();
1989 }
1990
1991 }