2 * Copyright © 2008, 2009 Intel Corporation
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:
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
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.
29 #include "main/core.h" /* for struct gl_context */
34 #include "glsl_parser_extras.h"
35 #include "glsl_parser.h"
36 #include "ir_optimization.h"
37 #include "loop_analysis.h"
39 _mesa_glsl_parse_state::_mesa_glsl_parse_state(struct gl_context *_ctx,
40 GLenum target, void *mem_ctx)
44 case GL_VERTEX_SHADER: this->target = vertex_shader; break;
45 case GL_FRAGMENT_SHADER: this->target = fragment_shader; break;
46 case GL_GEOMETRY_SHADER: this->target = geometry_shader; break;
50 this->translation_unit.make_empty();
51 this->symbols = new(mem_ctx) glsl_symbol_table;
52 this->info_log = ralloc_strdup(mem_ctx, "");
54 this->loop_nesting_ast = NULL;
55 this->switch_state.switch_nesting_ast = NULL;
57 this->num_builtins_to_link = 0;
59 /* Set default language version and extensions */
60 this->language_version = 110;
61 this->es_shader = false;
62 this->ARB_texture_rectangle_enable = true;
64 /* OpenGL ES 2.0 has different defaults from desktop GL. */
65 if (ctx->API == API_OPENGLES2) {
66 this->language_version = 100;
67 this->es_shader = true;
68 this->ARB_texture_rectangle_enable = false;
71 this->extensions = &ctx->Extensions;
73 this->Const.MaxLights = ctx->Const.MaxLights;
74 this->Const.MaxClipPlanes = ctx->Const.MaxClipPlanes;
75 this->Const.MaxTextureUnits = ctx->Const.MaxTextureUnits;
76 this->Const.MaxTextureCoords = ctx->Const.MaxTextureCoordUnits;
77 this->Const.MaxVertexAttribs = ctx->Const.VertexProgram.MaxAttribs;
78 this->Const.MaxVertexUniformComponents = ctx->Const.VertexProgram.MaxUniformComponents;
79 this->Const.MaxVaryingFloats = ctx->Const.MaxVarying * 4;
80 this->Const.MaxVertexTextureImageUnits = ctx->Const.MaxVertexTextureImageUnits;
81 this->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxCombinedTextureImageUnits;
82 this->Const.MaxTextureImageUnits = ctx->Const.MaxTextureImageUnits;
83 this->Const.MaxFragmentUniformComponents = ctx->Const.FragmentProgram.MaxUniformComponents;
85 this->Const.MaxDrawBuffers = ctx->Const.MaxDrawBuffers;
87 /* Note: Once the OpenGL 3.0 'forward compatible' context or the OpenGL 3.2
88 * Core context is supported, this logic will need change. Older versions of
89 * GLSL are no longer supported outside the compatibility contexts of 3.x.
91 this->Const.GLSL_100ES = (ctx->API == API_OPENGLES2)
92 || ctx->Extensions.ARB_ES2_compatibility;
93 this->Const.GLSL_110 = (ctx->API == API_OPENGL);
94 this->Const.GLSL_120 = (ctx->API == API_OPENGL)
95 && (ctx->Const.GLSLVersion >= 120);
96 this->Const.GLSL_130 = (ctx->API == API_OPENGL)
97 && (ctx->Const.GLSLVersion >= 130);
98 this->Const.GLSL_140 = (ctx->API == API_OPENGL)
99 && (ctx->Const.GLSLVersion >= 140);
101 const unsigned lowest_version =
102 (ctx->API == API_OPENGLES2) || ctx->Extensions.ARB_ES2_compatibility
104 const unsigned highest_version =
105 (ctx->API == API_OPENGL) ? ctx->Const.GLSLVersion : 100;
106 char *supported = ralloc_strdup(this, "");
108 for (unsigned ver = lowest_version; ver <= highest_version; ver += 10) {
109 const char *const prefix = (ver == lowest_version)
111 : ((ver == highest_version) ? ", and " : ", ");
113 ralloc_asprintf_append(& supported, "%s%d.%02d%s",
115 ver / 100, ver % 100,
116 (ver == 100) ? " ES" : "");
119 this->supported_version_string = supported;
121 if (ctx->Const.ForceGLSLExtensionsWarn)
122 _mesa_glsl_process_extension("all", NULL, "warn", NULL, this);
126 _mesa_glsl_shader_target_name(enum _mesa_glsl_parser_targets target)
129 case vertex_shader: return "vertex";
130 case fragment_shader: return "fragment";
131 case geometry_shader: return "geometry";
134 assert(!"Should not get here.");
138 /* This helper function will append the given message to the shader's
139 info log and report it via GL_ARB_debug_output. Per that extension,
140 'type' is one of the enum values classifying the message, and
141 'id' is the implementation-defined ID of the given message. */
143 _mesa_glsl_msg(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
144 GLenum type, GLuint id, const char *fmt, va_list ap)
146 bool error = (type == GL_DEBUG_TYPE_ERROR_ARB);
148 assert(state->info_log != NULL);
150 /* Get the offset that the new message will be written to. */
151 int msg_offset = strlen(state->info_log);
153 ralloc_asprintf_append(&state->info_log, "%u:%u(%u): %s: ",
157 error ? "error" : "warning");
158 ralloc_vasprintf_append(&state->info_log, fmt, ap);
160 const char *const msg = &state->info_log[msg_offset];
161 struct gl_context *ctx = state->ctx;
162 /* Report the error via GL_ARB_debug_output. */
164 _mesa_shader_debug(ctx, type, id, msg, strlen(msg));
166 ralloc_strcat(&state->info_log, "\n");
170 _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
171 const char *fmt, ...)
174 GLenum type = GL_DEBUG_TYPE_ERROR_ARB;
179 _mesa_glsl_msg(locp, state, type, SHADER_ERROR_UNKNOWN, fmt, ap);
185 _mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
186 const char *fmt, ...)
189 GLenum type = GL_DEBUG_TYPE_OTHER_ARB;
192 _mesa_glsl_msg(locp, state, type, 0, fmt, ap);
198 * Enum representing the possible behaviors that can be specified in
199 * an #extension directive.
209 * Element type for _mesa_glsl_supported_extensions
211 struct _mesa_glsl_extension {
213 * Name of the extension when referred to in a GLSL extension
218 /** True if this extension is available to vertex shaders */
221 /** True if this extension is available to geometry shaders */
224 /** True if this extension is available to fragment shaders */
227 /** True if this extension is available to desktop GL shaders */
230 /** True if this extension is available to GLES shaders */
234 * Flag in the gl_extensions struct indicating whether this
235 * extension is supported by the driver, or
236 * &gl_extensions::dummy_true if supported by all drivers.
238 * Note: the type (GLboolean gl_extensions::*) is a "pointer to
239 * member" type, the type-safe alternative to the "offsetof" macro.
242 * - foo bar::* p declares p to be an "offset" to a field of type
243 * foo that exists within struct bar
244 * - &bar::baz computes the "offset" of field baz within struct bar
245 * - x.*p accesses the field of x that exists at "offset" p
246 * - x->*p is equivalent to (*x).*p
248 const GLboolean gl_extensions::* supported_flag;
251 * Flag in the _mesa_glsl_parse_state struct that should be set
252 * when this extension is enabled.
254 * See note in _mesa_glsl_extension::supported_flag about "pointer
257 bool _mesa_glsl_parse_state::* enable_flag;
260 * Flag in the _mesa_glsl_parse_state struct that should be set
261 * when the shader requests "warn" behavior for this extension.
263 * See note in _mesa_glsl_extension::supported_flag about "pointer
266 bool _mesa_glsl_parse_state::* warn_flag;
269 bool compatible_with_state(const _mesa_glsl_parse_state *state) const;
270 void set_flags(_mesa_glsl_parse_state *state, ext_behavior behavior) const;
273 #define EXT(NAME, VS, GS, FS, GL, ES, SUPPORTED_FLAG) \
274 { "GL_" #NAME, VS, GS, FS, GL, ES, &gl_extensions::SUPPORTED_FLAG, \
275 &_mesa_glsl_parse_state::NAME##_enable, \
276 &_mesa_glsl_parse_state::NAME##_warn }
279 * Table of extensions that can be enabled/disabled within a shader,
280 * and the conditions under which they are supported.
282 static const _mesa_glsl_extension _mesa_glsl_supported_extensions[] = {
283 /* target availability API availability */
284 /* name VS GS FS GL ES supported flag */
285 EXT(ARB_conservative_depth, false, false, true, true, false, ARB_conservative_depth),
286 EXT(ARB_draw_buffers, false, false, true, true, false, dummy_true),
287 EXT(ARB_draw_instanced, true, false, false, true, false, ARB_draw_instanced),
288 EXT(ARB_explicit_attrib_location, true, false, true, true, false, ARB_explicit_attrib_location),
289 EXT(ARB_fragment_coord_conventions, true, false, true, true, false, ARB_fragment_coord_conventions),
290 EXT(ARB_texture_rectangle, true, false, true, true, false, dummy_true),
291 EXT(EXT_texture_array, true, false, true, true, false, EXT_texture_array),
292 EXT(ARB_shader_texture_lod, true, false, true, true, false, ARB_shader_texture_lod),
293 EXT(ARB_shader_stencil_export, false, false, true, true, false, ARB_shader_stencil_export),
294 EXT(AMD_conservative_depth, false, false, true, true, false, ARB_conservative_depth),
295 EXT(AMD_shader_stencil_export, false, false, true, true, false, ARB_shader_stencil_export),
296 EXT(OES_texture_3D, true, false, true, false, true, EXT_texture3D),
297 EXT(OES_EGL_image_external, true, false, true, false, true, OES_EGL_image_external),
298 EXT(ARB_shader_bit_encoding, true, true, true, true, false, ARB_shader_bit_encoding),
305 * Determine whether a given extension is compatible with the target,
306 * API, and extension information in the current parser state.
308 bool _mesa_glsl_extension::compatible_with_state(const _mesa_glsl_parse_state *
311 /* Check that this extension matches the type of shader we are
314 switch (state->target) {
316 if (!this->avail_in_VS) {
320 case geometry_shader:
321 if (!this->avail_in_GS) {
325 case fragment_shader:
326 if (!this->avail_in_FS) {
331 assert (!"Unrecognized shader target");
335 /* Check that this extension matches whether we are compiling
336 * for desktop GL or GLES.
338 if (state->es_shader) {
339 if (!this->avail_in_ES) return false;
341 if (!this->avail_in_GL) return false;
344 /* Check that this extension is supported by the OpenGL
347 * Note: the ->* operator indexes into state->extensions by the
348 * offset this->supported_flag. See
349 * _mesa_glsl_extension::supported_flag for more info.
351 return state->extensions->*(this->supported_flag);
355 * Set the appropriate flags in the parser state to establish the
356 * given behavior for this extension.
358 void _mesa_glsl_extension::set_flags(_mesa_glsl_parse_state *state,
359 ext_behavior behavior) const
361 /* Note: the ->* operator indexes into state by the
362 * offsets this->enable_flag and this->warn_flag. See
363 * _mesa_glsl_extension::supported_flag for more info.
365 state->*(this->enable_flag) = (behavior != extension_disable);
366 state->*(this->warn_flag) = (behavior == extension_warn);
370 * Find an extension by name in _mesa_glsl_supported_extensions. If
371 * the name is not found, return NULL.
373 static const _mesa_glsl_extension *find_extension(const char *name)
375 for (unsigned i = 0; i < Elements(_mesa_glsl_supported_extensions); ++i) {
376 if (strcmp(name, _mesa_glsl_supported_extensions[i].name) == 0) {
377 return &_mesa_glsl_supported_extensions[i];
385 _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
386 const char *behavior_string, YYLTYPE *behavior_locp,
387 _mesa_glsl_parse_state *state)
389 ext_behavior behavior;
390 if (strcmp(behavior_string, "warn") == 0) {
391 behavior = extension_warn;
392 } else if (strcmp(behavior_string, "require") == 0) {
393 behavior = extension_require;
394 } else if (strcmp(behavior_string, "enable") == 0) {
395 behavior = extension_enable;
396 } else if (strcmp(behavior_string, "disable") == 0) {
397 behavior = extension_disable;
399 _mesa_glsl_error(behavior_locp, state,
400 "Unknown extension behavior `%s'",
405 if (strcmp(name, "all") == 0) {
406 if ((behavior == extension_enable) || (behavior == extension_require)) {
407 _mesa_glsl_error(name_locp, state, "Cannot %s all extensions",
408 (behavior == extension_enable)
409 ? "enable" : "require");
413 i < Elements(_mesa_glsl_supported_extensions); ++i) {
414 const _mesa_glsl_extension *extension
415 = &_mesa_glsl_supported_extensions[i];
416 if (extension->compatible_with_state(state)) {
417 _mesa_glsl_supported_extensions[i].set_flags(state, behavior);
422 const _mesa_glsl_extension *extension = find_extension(name);
423 if (extension && extension->compatible_with_state(state)) {
424 extension->set_flags(state, behavior);
426 static const char *const fmt = "extension `%s' unsupported in %s shader";
428 if (behavior == extension_require) {
429 _mesa_glsl_error(name_locp, state, fmt,
430 name, _mesa_glsl_shader_target_name(state->target));
433 _mesa_glsl_warning(name_locp, state, fmt,
434 name, _mesa_glsl_shader_target_name(state->target));
443 _mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
445 if (q->flags.q.constant)
448 if (q->flags.q.invariant)
449 printf("invariant ");
451 if (q->flags.q.attribute)
452 printf("attribute ");
454 if (q->flags.q.varying)
457 if (q->flags.q.in && q->flags.q.out)
467 if (q->flags.q.centroid)
469 if (q->flags.q.uniform)
471 if (q->flags.q.smooth)
475 if (q->flags.q.noperspective)
476 printf("noperspective ");
481 ast_node::print(void) const
483 printf("unhandled node ");
487 ast_node::ast_node(void)
489 this->location.source = 0;
490 this->location.line = 0;
491 this->location.column = 0;
496 ast_opt_array_size_print(bool is_array, const ast_expression *array_size)
510 ast_compound_statement::print(void) const
514 foreach_list_const(n, &this->statements) {
515 ast_node *ast = exec_node_data(ast_node, n, link);
523 ast_compound_statement::ast_compound_statement(int new_scope,
524 ast_node *statements)
526 this->new_scope = new_scope;
528 if (statements != NULL) {
529 this->statements.push_degenerate_list_at_head(&statements->link);
535 ast_expression::print(void) const
549 subexpressions[0]->print();
550 printf("%s ", operator_string(oper));
551 subexpressions[1]->print();
554 case ast_field_selection:
555 subexpressions[0]->print();
556 printf(". %s ", primary_expression.identifier);
565 printf("%s ", operator_string(oper));
566 subexpressions[0]->print();
571 subexpressions[0]->print();
572 printf("%s ", operator_string(oper));
575 case ast_conditional:
576 subexpressions[0]->print();
578 subexpressions[1]->print();
580 subexpressions[2]->print();
583 case ast_array_index:
584 subexpressions[0]->print();
586 subexpressions[1]->print();
590 case ast_function_call: {
591 subexpressions[0]->print();
594 foreach_list_const (n, &this->expressions) {
595 if (n != this->expressions.get_head())
598 ast_node *ast = exec_node_data(ast_node, n, link);
607 printf("%s ", primary_expression.identifier);
610 case ast_int_constant:
611 printf("%d ", primary_expression.int_constant);
614 case ast_uint_constant:
615 printf("%u ", primary_expression.uint_constant);
618 case ast_float_constant:
619 printf("%f ", primary_expression.float_constant);
622 case ast_bool_constant:
624 primary_expression.bool_constant
630 foreach_list_const(n, & this->expressions) {
631 if (n != this->expressions.get_head())
634 ast_node *ast = exec_node_data(ast_node, n, link);
647 ast_expression::ast_expression(int oper,
652 this->oper = ast_operators(oper);
653 this->subexpressions[0] = ex0;
654 this->subexpressions[1] = ex1;
655 this->subexpressions[2] = ex2;
656 this->non_lvalue_description = NULL;
661 ast_expression_statement::print(void) const
670 ast_expression_statement::ast_expression_statement(ast_expression *ex) :
678 ast_function::print(void) const
680 return_type->print();
681 printf(" %s (", identifier);
683 foreach_list_const(n, & this->parameters) {
684 ast_node *ast = exec_node_data(ast_node, n, link);
692 ast_function::ast_function(void)
693 : is_definition(false), signature(NULL)
700 ast_fully_specified_type::print(void) const
702 _mesa_ast_type_qualifier_print(& qualifier);
708 ast_parameter_declarator::print(void) const
712 printf("%s ", identifier);
713 ast_opt_array_size_print(is_array, array_size);
718 ast_function_definition::print(void) const
726 ast_declaration::print(void) const
728 printf("%s ", identifier);
729 ast_opt_array_size_print(is_array, array_size);
733 initializer->print();
738 ast_declaration::ast_declaration(const char *identifier, int is_array,
739 ast_expression *array_size,
740 ast_expression *initializer)
742 this->identifier = identifier;
743 this->is_array = is_array;
744 this->array_size = array_size;
745 this->initializer = initializer;
750 ast_declarator_list::print(void) const
752 assert(type || invariant);
757 printf("invariant ");
759 foreach_list_const (ptr, & this->declarations) {
760 if (ptr != this->declarations.get_head())
763 ast_node *ast = exec_node_data(ast_node, ptr, link);
771 ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
774 this->invariant = false;
778 ast_jump_statement::print(void) const
782 printf("continue; ");
789 if (opt_return_value)
790 opt_return_value->print();
801 ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
803 this->mode = ast_jump_modes(mode);
805 if (mode == ast_return)
806 opt_return_value = return_value;
811 ast_selection_statement::print(void) const
817 then_statement->print();
819 if (else_statement) {
821 else_statement->print();
827 ast_selection_statement::ast_selection_statement(ast_expression *condition,
828 ast_node *then_statement,
829 ast_node *else_statement)
831 this->condition = condition;
832 this->then_statement = then_statement;
833 this->else_statement = else_statement;
838 ast_switch_statement::print(void) const
841 test_expression->print();
848 ast_switch_statement::ast_switch_statement(ast_expression *test_expression,
851 this->test_expression = test_expression;
857 ast_switch_body::print(void) const
867 ast_switch_body::ast_switch_body(ast_case_statement_list *stmts)
873 void ast_case_label::print(void) const
875 if (test_value != NULL) {
885 ast_case_label::ast_case_label(ast_expression *test_value)
887 this->test_value = test_value;
891 void ast_case_label_list::print(void) const
893 foreach_list_const(n, & this->labels) {
894 ast_node *ast = exec_node_data(ast_node, n, link);
901 ast_case_label_list::ast_case_label_list(void)
906 void ast_case_statement::print(void) const
909 foreach_list_const(n, & this->stmts) {
910 ast_node *ast = exec_node_data(ast_node, n, link);
917 ast_case_statement::ast_case_statement(ast_case_label_list *labels)
919 this->labels = labels;
923 void ast_case_statement_list::print(void) const
925 foreach_list_const(n, & this->cases) {
926 ast_node *ast = exec_node_data(ast_node, n, link);
932 ast_case_statement_list::ast_case_statement_list(void)
938 ast_iteration_statement::print(void) const
944 init_statement->print();
952 rest_expression->print();
978 ast_iteration_statement::ast_iteration_statement(int mode,
981 ast_expression *rest_expression,
984 this->mode = ast_iteration_modes(mode);
985 this->init_statement = init;
986 this->condition = condition;
987 this->rest_expression = rest_expression;
993 ast_struct_specifier::print(void) const
995 printf("struct %s { ", name);
996 foreach_list_const(n, &this->declarations) {
997 ast_node *ast = exec_node_data(ast_node, n, link);
1004 ast_struct_specifier::ast_struct_specifier(const char *identifier,
1005 ast_node *declarator_list)
1007 if (identifier == NULL) {
1008 static unsigned anon_count = 1;
1009 identifier = ralloc_asprintf(this, "#anon_struct_%04x", anon_count);
1013 this->declarations.push_degenerate_list_at_head(&declarator_list->link);
1017 * Do the set of common optimizations passes
1019 * \param ir List of instructions to be optimized
1020 * \param linked Is the shader linked? This enables
1021 * optimizations passes that remove code at
1022 * global scope and could cause linking to
1024 * \param uniform_locations_assigned Have locations already been assigned for
1025 * uniforms? This prevents the declarations
1026 * of unused uniforms from being removed.
1027 * The setting of this flag only matters if
1028 * \c linked is \c true.
1029 * \param max_unroll_iterations Maximum number of loop iterations to be
1030 * unrolled. Setting to 0 forces all loops
1034 do_common_optimization(exec_list *ir, bool linked,
1035 bool uniform_locations_assigned,
1036 unsigned max_unroll_iterations)
1038 GLboolean progress = GL_FALSE;
1040 progress = lower_instructions(ir, SUB_TO_ADD_NEG) || progress;
1043 progress = do_function_inlining(ir) || progress;
1044 progress = do_dead_functions(ir) || progress;
1045 progress = do_structure_splitting(ir) || progress;
1047 progress = do_if_simplification(ir) || progress;
1048 progress = do_copy_propagation(ir) || progress;
1049 progress = do_copy_propagation_elements(ir) || progress;
1051 progress = do_dead_code(ir, uniform_locations_assigned) || progress;
1053 progress = do_dead_code_unlinked(ir) || progress;
1054 progress = do_dead_code_local(ir) || progress;
1055 progress = do_tree_grafting(ir) || progress;
1056 progress = do_constant_propagation(ir) || progress;
1058 progress = do_constant_variable(ir) || progress;
1060 progress = do_constant_variable_unlinked(ir) || progress;
1061 progress = do_constant_folding(ir) || progress;
1062 progress = do_algebraic(ir) || progress;
1063 progress = do_lower_jumps(ir) || progress;
1064 progress = do_vec_index_to_swizzle(ir) || progress;
1065 progress = do_swizzle_swizzle(ir) || progress;
1066 progress = do_noop_swizzle(ir) || progress;
1068 progress = optimize_split_arrays(ir, linked) || progress;
1069 progress = optimize_redundant_jumps(ir) || progress;
1071 loop_state *ls = analyze_loop_variables(ir);
1072 if (ls->loop_found) {
1073 progress = set_loop_controls(ir, ls) || progress;
1074 progress = unroll_loops(ir, ls, max_unroll_iterations) || progress;
1084 * To be called at GL teardown time, this frees compiler datastructures.
1086 * After calling this, any previously compiled shaders and shader
1087 * programs would be invalid. So this should happen at approximately
1091 _mesa_destroy_shader_compiler(void)
1093 _mesa_destroy_shader_compiler_caches();
1095 _mesa_glsl_release_types();
1099 * Releases compiler caches to trade off performance for memory.
1101 * Intended to be used with glReleaseShaderCompiler().
1104 _mesa_destroy_shader_compiler_caches(void)
1106 _mesa_glsl_release_functions();