mesa/src/glsl
Kenneth Graunke c87cb98bb4 glsl: Fix crashes caused by Bison error messages involving "'%'".
Invalid shaders containing the character % at an unexpected location
would cause Bison to call yyerror with a message of:

    syntax error, unexpected '%'

Bison expects yyerror() to take a string, while _mesa_glsl_error() is a
printf-style function.  This hit the classic printf string escape issue:

    _mesa_glsl_error(loc, state, "unexpected '%'");       // invalid!
    _mesa_glsl_error(loc, state, "%s", "unexpected '%'"); // correct.

This caused assertion failures after ralloc_asprintf_append called
vsnprintf to determine the length of the text that would be printed:
vsnprintf would see the invalid format and return -1, an invalid length.

The solution is to define a proper yyerror() wrapper function that calls
_mesa_glsl_error with the "%s".  Since we compile with -p "_mesa_glsl",
yyerror is defined as:

    #define yyerror         _mesa_glsl_error

So we have to #undef yyerror in order to be able to declare it.

Bugzilla: https://bugs.freedesktop.org/show_bug.cgi?id=43564
Signed-off-by: Kenneth Graunke <kenneth@whitecape.org>
Reviewed-by: Ian Romanick <ian.d.romanick@intel.com>
Acked-by: Paul Berry <stereotype441@gmail.com>
2011-12-13 22:54:16 -08:00
..
builtins glsl: Fix samplerCubeShadow support in shader compiler 2011-12-07 15:11:29 -08:00
glcpp mesa: rename the AMD_conservative_depth extension flag to ARB 2011-11-22 20:56:50 +01:00
tests glsl: Add unit tests for lower_jumps.cpp 2011-07-22 09:45:11 -07:00
.dir-locals.el glsl2: Move the compiler to the subdirectory it will live in in Mesa. 2010-06-24 15:36:00 -07:00
.gitignore glsl: Create a standalone executable for testing optimization passes. 2011-07-22 09:45:11 -07:00
Android.gen.mk android: build glsl 2011-08-21 02:01:49 +08:00
Android.mk android: include src/glsl/Makefile.sources 2011-11-02 06:36:24 +08:00
ast.h glsl: Create AST structs corresponding to new productions in grammar 2011-11-07 16:31:22 -08:00
ast_expr.cpp Use C-style system headers in C++ code to avoid issues with std:: namespace 2011-02-21 13:07:29 -08:00
ast_function.cpp glsl: Always search for an exact function signature match. 2011-11-14 17:18:12 -08:00
ast_to_hir.cpp glsl: finish up ARB_conservative_depth (v2) 2011-11-22 20:56:50 +01:00
ast_type.cpp glsl: add support for GL_OES_EGL_image_external 2011-11-03 15:09:44 +08:00
autogen.sh glsl2: Move the compiler to the subdirectory it will live in in Mesa. 2010-06-24 15:36:00 -07:00
builtin_stubs.cpp glsl: Silence several "warning: unused parameter" 2011-09-09 12:01:50 -07:00
builtin_types.h glsl: add support for GL_OES_EGL_image_external 2011-11-03 15:09:44 +08:00
builtin_variables.cpp mesa: Make gl_VertexID be a system value like gl_InstanceID. 2011-11-11 08:27:51 -08:00
glsl_lexer.ll glsl: finish up ARB_conservative_depth (v2) 2011-11-22 20:56:50 +01:00
glsl_parser.yy glsl: Fix crashes caused by Bison error messages involving "'%'". 2011-12-13 22:54:16 -08:00
glsl_parser_extras.cpp glsl: convervative_depth is not allowed in the vertex shader 2011-11-22 20:56:50 +01:00
glsl_parser_extras.h glsl: Generate IR for switch statements 2011-11-07 16:31:22 -08:00
glsl_symbol_table.cpp glsl2: Silence unused added variable gcc warning. 2011-03-16 09:16:01 +00:00
glsl_symbol_table.h Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
glsl_types.cpp glsl: add support for GL_OES_EGL_image_external 2011-11-03 15:09:44 +08:00
glsl_types.h mesa,glsl,mapi: Put extern "C" { ... } where appropriate. 2011-11-09 10:24:37 +00:00
hir_field_selection.cpp Use C-style system headers in C++ code to avoid issues with std:: namespace 2011-02-21 13:07:29 -08:00
ir.cpp linker: Check that initializers for global variables match 2011-11-03 13:36:00 -07:00
ir.h glsl: Add a new matching_signature() variant that returns exact/inexact. 2011-11-14 17:17:39 -08:00
ir_basic_block.cpp glsl2: Don't dead-code eliminate a call where the return value is unused. 2010-08-05 12:56:03 -07:00
ir_basic_block.h glsl2: Move the compiler to the subdirectory it will live in in Mesa. 2010-06-24 15:36:00 -07:00
ir_clone.cpp glsl: when cloning a variable, copy the depth layout too 2011-11-19 16:46:59 +01:00
ir_constant_expression.cpp glsl: Handle constant expressions involving ir_binop_equal/nequal. 2011-11-10 22:51:20 -08:00
ir_expression_flattening.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
ir_expression_flattening.h glsl2: Move the compiler to the subdirectory it will live in in Mesa. 2010-06-24 15:36:00 -07:00
ir_function.cpp glsl: Add a new matching_signature() variant that returns exact/inexact. 2011-11-14 17:17:39 -08:00
ir_function_can_inline.cpp glsl: Don't inline function prototypes. 2010-11-25 01:19:53 -08:00
ir_function_detect_recursion.cpp glsl: Silence several "warning: unused parameter" 2011-09-09 12:01:50 -07:00
ir_function_inlining.h glsl2: Move the compiler to the subdirectory it will live in in Mesa. 2010-06-24 15:36:00 -07:00
ir_hierarchical_visitor.cpp glsl2: Set a flag when visiting the assignee of an assignment 2010-09-03 11:55:21 -07:00
ir_hierarchical_visitor.h glsl hierarchical visitor: Do not overwrite base_ir for parameter lists. 2011-09-23 13:28:00 -07:00
ir_hv_accept.cpp glsl hierarchical visitor: Do not overwrite base_ir for parameter lists. 2011-09-23 13:28:00 -07:00
ir_import_prototypes.cpp Use C-style system headers in C++ code to avoid issues with std:: namespace 2011-02-21 13:07:29 -08:00
ir_optimization.h glsl: Add uniform_locations_assigned parameter to do_dead_code opt pass 2011-10-25 17:51:43 -07:00
ir_print_visitor.cpp glsl: Remove pointless uses of glsl_type::get_base_type(). 2011-10-28 11:12:33 -07:00
ir_print_visitor.h glsl: Generate readable unique names at print time. 2011-03-25 16:31:53 -07:00
ir_reader.cpp glsl: Remove pointless uses of glsl_type::get_base_type(). 2011-10-28 11:12:33 -07:00
ir_reader.h glsl2: Rework builtin function generation. 2010-08-13 19:09:36 -07:00
ir_rvalue_visitor.cpp glsl: Add a new ir_txs (textureSize) opcode to ir_texture. 2011-08-23 11:16:30 -07:00
ir_rvalue_visitor.h glsl2: Add a generic visitor class to call back with pointers to each rvalue. 2010-08-13 17:54:46 -07:00
ir_set_program_inouts.cpp mesa: Expose GLSL interpolation qualifiers in gl_fragment_program. 2011-10-27 15:30:58 -07:00
ir_uniform.h mesa,glsl,mapi: Put extern "C" { ... } where appropriate. 2011-11-09 10:24:37 +00:00
ir_validate.cpp glsl: return visit_stop in ir_validate::visit_enter() to silence warning 2011-12-02 07:22:39 -07:00
ir_variable_refcount.cpp glsl2: move constructor into .cpp file to work around compiler bug 2010-08-24 10:01:44 -06:00
ir_variable_refcount.h Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
ir_visitor.h glsl: add ir_control_flow_visitor 2010-09-13 13:03:09 -07:00
link_functions.cpp glsl: When linking, emit functions at the tail of the final linked program. 2011-08-08 12:43:57 -07:00
link_uniforms.cpp linker: Remove erroneous multiply by 4 in uniform usage calculation 2011-11-22 11:50:19 -08:00
linker.cpp mesa: add const flags to skip MaxVarying and MaxUniform linker checks (v2) 2011-12-13 17:49:00 +01:00
linker.h linker: Track uniform locations to new tracking structures 2011-11-07 13:33:16 -08:00
list.h Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
loop_analysis.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
loop_analysis.h glsl: Skip the rest of loop unrolling if no loops were found. 2011-01-18 10:17:37 -08:00
loop_controls.cpp Use C-style system headers in C++ code to avoid issues with std:: namespace 2011-02-21 13:07:29 -08:00
loop_unroll.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
lower_clip_distance.cpp glsl: Implement a lowering pass for gl_ClipDistance. 2011-09-23 13:28:43 -07:00
lower_discard.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
lower_if_to_cond_assign.cpp glsl: Short-circuit lower_if_to_cond_assign when MaxIfDepth is UINT_MAX. 2011-10-21 01:11:20 -07:00
lower_instructions.cpp glsl: Use a separate div_to_mul_rcp lowering flag for integers. 2011-08-31 12:02:18 -07:00
lower_jumps.cpp glsl: Silence several "warning: unused parameter" 2011-09-09 12:01:50 -07:00
lower_mat_op_to_vec.cpp glsl: Use the default values of ir_assignment() in lower_mat_op_to_vec. 2011-06-29 15:10:43 -07:00
lower_noise.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
lower_texture_projection.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
lower_variable_index_to_cond_assign.cpp glsl: Correctly return progress from lower_variable_index_to_cond_assign 2011-07-25 18:45:46 -07:00
lower_vec_index_to_cond_assign.cpp glsl: Compare vector indices in blocks 2011-07-23 01:24:18 -07:00
lower_vec_index_to_swizzle.cpp glsl: Clamp vector indices when lowering to swizzles 2011-11-09 10:50:35 -08:00
lower_vector.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
main.cpp glsl: Add uniform_locations_assigned parameter to do_dead_code opt pass 2011-10-25 17:51:43 -07:00
Makefile glsl: Refactor source lists to Makefile.sources 2011-11-02 06:34:39 +08:00
Makefile.sources glsl: Move ir_variable.cpp to builtin_variables.cpp. 2011-11-11 08:21:34 -08:00
Makefile.template Build mesa glsl with make. 2009-12-10 01:03:15 +01:00
opt_algebraic.cpp Convert everything from the talloc API to the ralloc API. 2011-01-31 10:17:09 -08:00
opt_constant_folding.cpp glsl: Introduce a new "const_in" variable mode. 2011-01-31 11:10:59 -08:00
opt_constant_propagation.cpp glsl: Track initial mask in constant propagation live set 2011-07-06 16:41:34 -07:00
opt_constant_variable.cpp Use C-style system headers in C++ code to avoid issues with std:: namespace 2011-02-21 13:07:29 -08:00
opt_copy_propagation.cpp glsl: Remove extra checks for constant true assignment conditions. 2011-02-04 12:18:38 -06:00
opt_copy_propagation_elements.cpp glsl/opt_cpe: Fix a crash when a kill kills for two reasons. 2011-04-13 10:51:03 -07:00
opt_dead_code.cpp glsl: Add uniform_locations_assigned parameter to do_dead_code opt pass 2011-10-25 17:51:43 -07:00
opt_dead_code_local.cpp Use C-style system headers in C++ code to avoid issues with std:: namespace 2011-02-21 13:07:29 -08:00
opt_dead_functions.cpp Revert "glsl: Skip processing the first function's body in do_dead_functions()." 2011-08-08 12:43:04 -07:00
opt_discard_simplification.cpp glsl: Silence several "warning: unused parameter" 2011-09-09 12:01:50 -07:00
opt_function_inlining.cpp glsl: Remove unneeded headers. 2011-10-04 18:03:22 -07:00
opt_if_simplification.cpp glsl: Silence several "warning: unused parameter" 2011-09-09 12:01:50 -07:00
opt_noop_swizzle.cpp glsl: Fix Doxygen tag \file in recently renamed files 2010-11-17 12:07:24 -08:00
opt_redundant_jumps.cpp glsl: Skip processing expression trees in optimize_redundant_jumps() 2011-03-15 09:49:00 -07:00
opt_structure_splitting.cpp glsl: Reduce processing of expression trees in do_structure_splitting. 2011-03-15 09:49:01 -07:00
opt_swizzle_swizzle.cpp Use C-style system headers in C++ code to avoid issues with std:: namespace 2011-02-21 13:07:29 -08:00
opt_tree_grafting.cpp glsl: Stop tree grafting if a variable is overwritten as an 'out' param. 2011-10-18 12:24:48 -07:00
program.h linker: Make linker_{error,warning} generally available 2011-08-02 08:23:01 -07:00
ralloc.c ralloc: Use _vscprintf on MinGW. 2011-11-01 08:47:39 +00:00
ralloc.h ralloc: Add new [v]asprintf_rewrite_tail functions. 2011-10-25 17:51:43 -07:00
README glsl: Explain file naming convention 2010-09-13 14:06:32 -07:00
s_expression.cpp glsl: Avoid massive ralloc_strndup overhead in S-Expression parsing. 2011-07-20 10:42:43 -07:00
s_expression.h glsl: Avoid massive ralloc_strndup overhead in S-Expression parsing. 2011-07-20 10:42:43 -07:00
SConscript scons: include src/glsl/Makefile.sources 2011-11-02 06:36:58 +08:00
standalone_scaffolding.cpp glsl: add support for GL_OES_EGL_image_external 2011-11-03 15:09:44 +08:00
standalone_scaffolding.h glsl: Move functions into standalone_scaffolding.cpp for later reuse. 2011-07-22 09:45:11 -07:00
strtod.c glsl: new glsl_strtod() wrapper to fix decimal point interpretation 2010-12-14 12:38:38 -07:00
strtod.h glsl: new glsl_strtod() wrapper to fix decimal point interpretation 2010-12-14 12:38:38 -07:00
test.cpp glsl: Create a standalone executable for testing optimization passes. 2011-07-22 09:45:11 -07:00
test_optpass.cpp glsl: Add uniform_locations_assigned parameter to do_dead_code opt pass 2011-10-25 17:51:43 -07:00
test_optpass.h glsl: Create a standalone executable for testing optimization passes. 2011-07-22 09:45:11 -07:00
TODO glsl: Add source location tracking to TODO list 2011-07-27 11:41:14 -07:00

Welcome to Mesa's GLSL compiler.  A brief overview of how things flow:

1) lex and yacc-based preprocessor takes the incoming shader string
and produces a new string containing the preprocessed shader.  This
takes care of things like #if, #ifdef, #define, and preprocessor macro
invocations.  Note that #version, #extension, and some others are
passed straight through.  See glcpp/*

2) lex and yacc-based parser takes the preprocessed string and
generates the AST (abstract syntax tree).  Almost no checking is
performed in this stage.  See glsl_lexer.lpp and glsl_parser.ypp.

3) The AST is converted to "HIR".  This is the intermediate
representation of the compiler.  Constructors are generated, function
calls are resolved to particular function signatures, and all the
semantic checking is performed.  See ast_*.cpp for the conversion, and
ir.h for the IR structures.

4) The driver (Mesa, or main.cpp for the standalone binary) performs
optimizations.  These include copy propagation, dead code elimination,
constant folding, and others.  Generally the driver will call
optimizations in a loop, as each may open up opportunities for other
optimizations to do additional work.  See most files called ir_*.cpp

5) linking is performed.  This does checking to ensure that the
outputs of the vertex shader match the inputs of the fragment shader,
and assigns locations to uniforms, attributes, and varyings.  See
linker.cpp.

6) The driver may perform additional optimization at this point, as
for example dead code elimination previously couldn't remove functions
or global variable usage when we didn't know what other code would be
linked in.

7) The driver performs code generation out of the IR, taking a linked
shader program and producing a compiled program for each stage.  See
ir_to_mesa.cpp for Mesa IR code generation.

FAQ:

Q: What is HIR versus IR versus LIR?

A: The idea behind the naming was that ast_to_hir would produce a
high-level IR ("HIR"), with things like matrix operations, structure
assignments, etc., present.  A series of lowering passes would occur
that do things like break matrix multiplication into a series of dot
products/MADs, make structure assignment be a series of assignment of
components, flatten if statements into conditional moves, and such,
producing a low level IR ("LIR").

However, it now appears that each driver will have different
requirements from a LIR.  A 915-generation chipset wants all functions
inlined, all loops unrolled, all ifs flattened, no variable array
accesses, and matrix multiplication broken down.  The Mesa IR backend
for swrast would like matrices and structure assignment broken down,
but it can support function calls and dynamic branching.  A 965 vertex
shader IR backend could potentially even handle some matrix operations
without breaking them down, but the 965 fragment shader IR backend
would want to break to have (almost) all operations down channel-wise
and perform optimization on that.  As a result, there's no single
low-level IR that will make everyone happy.  So that usage has fallen
out of favor, and each driver will perform a series of lowering passes
to take the HIR down to whatever restrictions it wants to impose
before doing codegen.

Q: How is the IR structured?

A: The best way to get started seeing it would be to run the
standalone compiler against a shader:

./glsl_compiler --dump-lir \
	~/src/piglit/tests/shaders/glsl-orangebook-ch06-bump.frag

So for example one of the ir_instructions in main() contains:

(assign (constant bool (1)) (var_ref litColor)  (expression vec3 * (var_ref Surf
aceColor) (var_ref __retval) ) )

Or more visually:
                     (assign)
                 /       |        \
        (var_ref)  (expression *)  (constant bool 1)
         /          /           \
(litColor)      (var_ref)    (var_ref)
                  /                  \
           (SurfaceColor)          (__retval)

which came from:

litColor = SurfaceColor * max(dot(normDelta, LightDir), 0.0);

(the max call is not represented in this expression tree, as it was a
function call that got inlined but not brought into this expression
tree)

Each of those nodes is a subclass of ir_instruction.  A particular
ir_instruction instance may only appear once in the whole IR tree with
the exception of ir_variables, which appear once as variable
declarations:

(declare () vec3 normDelta)

and multiple times as the targets of variable dereferences:
...
(assign (constant bool (1)) (var_ref __retval) (expression float dot
 (var_ref normDelta) (var_ref LightDir) ) )
...
(assign (constant bool (1)) (var_ref __retval) (expression vec3 -
 (var_ref LightDir) (expression vec3 * (constant float (2.000000))
 (expression vec3 * (expression float dot (var_ref normDelta) (var_ref
 LightDir) ) (var_ref normDelta) ) ) ) )
...

Each node has a type.  Expressions may involve several different types:
(declare (uniform ) mat4 gl_ModelViewMatrix)
((assign (constant bool (1)) (var_ref constructor_tmp) (expression
 vec4 * (var_ref gl_ModelViewMatrix) (var_ref gl_Vertex) ) )

An expression tree can be arbitrarily deep, and the compiler tries to
keep them structured like that so that things like algebraic
optimizations ((color * 1.0 == color) and ((mat1 * mat2) * vec == mat1
* (mat2 * vec))) or recognizing operation patterns for code generation
(vec1 * vec2 + vec3 == mad(vec1, vec2, vec3)) are easier.  This comes
at the expense of additional trickery in implementing some
optimizations like CSE where one must navigate an expression tree.

Q: Why no SSA representation?

A: Converting an IR tree to SSA form makes dead code elmimination,
common subexpression elimination, and many other optimizations much
easier.  However, in our primarily vector-based language, there's some
major questions as to how it would work.  Do we do SSA on the scalar
or vector level?  If we do it at the vector level, we're going to end
up with many different versions of the variable when encountering code
like:

(assign (constant bool (1)) (swiz x (var_ref __retval) ) (var_ref a) ) 
(assign (constant bool (1)) (swiz y (var_ref __retval) ) (var_ref b) ) 
(assign (constant bool (1)) (swiz z (var_ref __retval) ) (var_ref c) ) 

If every masked update of a component relies on the previous value of
the variable, then we're probably going to be quite limited in our
dead code elimination wins, and recognizing common expressions may
just not happen.  On the other hand, if we operate channel-wise, then
we'll be prone to optimizing the operation on one of the channels at
the expense of making its instruction flow different from the other
channels, and a vector-based GPU would end up with worse code than if
we didn't optimize operations on that channel!

Once again, it appears that our optimization requirements are driven
significantly by the target architecture.  For now, targeting the Mesa
IR backend, SSA does not appear to be that important to producing
excellent code, but we do expect to do some SSA-based optimizations
for the 965 fragment shader backend when that is developed.

Q: How should I expand instructions that take multiple backend instructions?

Sometimes you'll have to do the expansion in your code generation --
see, for example, ir_to_mesa.cpp's handling of ir_unop_sqrt.  However,
in many cases you'll want to do a pass over the IR to convert
non-native instructions to a series of native instructions.  For
example, for the Mesa backend we have ir_div_to_mul_rcp.cpp because
Mesa IR (and many hardware backends) only have a reciprocal
instruction, not a divide.  Implementing non-native instructions this
way gives the chance for constant folding to occur, so (a / 2.0)
becomes (a * 0.5) after codegen instead of (a * (1.0 / 2.0))

Q: How shoud I handle my special hardware instructions with respect to IR?

Our current theory is that if multiple targets have an instruction for
some operation, then we should probably be able to represent that in
the IR.  Generally this is in the form of an ir_{bin,un}op expression
type.  For example, we initially implemented fract() using (a -
floor(a)), but both 945 and 965 have instructions to give that result,
and it would also simplify the implementation of mod(), so
ir_unop_fract was added.  The following areas need updating to add a
new expression type:

ir.h (new enum)
ir.cpp:get_num_operands() (used for ir_reader)
ir.cpp:operator_strs (used for ir_reader)
ir_constant_expression.cpp (you probably want to be able to constant fold)
ir_validate.cpp (check users have the right types)

You may also need to update the backends if they will see the new expr type:

../mesa/shaders/ir_to_mesa.cpp

You can then use the new expression from builtins (if all backends
would rather see it), or scan the IR and convert to use your new
expression type (see ir_mod_to_fract, for example).

Q: How is memory management handled in the compiler?

The hierarchical memory allocator "talloc" developed for the Samba
project is used, so that things like optimization passes don't have to
worry about their garbage collection so much.  It has a few nice
features, including low performance overhead and good debugging
support that's trivially available.

Generally, each stage of the compile creates a talloc context and
allocates its memory out of that or children of it.  At the end of the
stage, the pieces still live are stolen to a new context and the old
one freed, or the whole context is kept for use by the next stage.

For IR transformations, a temporary context is used, then at the end
of all transformations, reparent_ir reparents all live nodes under the
shader's IR list, and the old context full of dead nodes is freed.
When developing a single IR transformation pass, this means that you
want to allocate instruction nodes out of the temporary context, so if
it becomes dead it doesn't live on as the child of a live node.  At
the moment, optimization passes aren't passed that temporary context,
so they find it by calling talloc_parent() on a nearby IR node.  The
talloc_parent() call is expensive, so many passes will cache the
result of the first talloc_parent().  Cleaning up all the optimization
passes to take a context argument and not call talloc_parent() is left
as an exercise.

Q: What is the file naming convention in this directory?

Initially, there really wasn't one.  We have since adopted one:

 - Files that implement code lowering passes should be named lower_*
   (e.g., lower_noise.cpp).
 - Files that implement optimization passes should be named opt_*.
 - Files that implement a class that is used throught the code should
   take the name of that class (e.g., ir_hierarchical_visitor.cpp).
 - Files that contain code not fitting in one of the previous
   categories should have a sensible name (e.g., glsl_parser.ypp).