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