• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2002 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 #ifndef GLSLANG_SHADERLANG_H_
7 #define GLSLANG_SHADERLANG_H_
8 
9 #include <stddef.h>
10 
11 #include "KHR/khrplatform.h"
12 
13 #include <array>
14 #include <map>
15 #include <set>
16 #include <string>
17 #include <vector>
18 
19 //
20 // This is the platform independent interface between an OGL driver
21 // and the shading language compiler.
22 //
23 
24 // Note: make sure to increment ANGLE_SH_VERSION when changing ShaderVars.h
25 #include "ShaderVars.h"
26 
27 // Version number for shader translation API.
28 // It is incremented every time the API changes.
29 #define ANGLE_SH_VERSION 230
30 
31 enum ShShaderSpec
32 {
33     SH_GLES2_SPEC,
34     SH_WEBGL_SPEC,
35 
36     SH_GLES3_SPEC,
37     SH_WEBGL2_SPEC,
38 
39     SH_GLES3_1_SPEC,
40     SH_WEBGL3_SPEC,
41 
42     SH_GL_CORE_SPEC,
43     SH_GL_COMPATIBILITY_SPEC,
44 };
45 
46 enum ShShaderOutput
47 {
48     // ESSL output only supported in some configurations.
49     SH_ESSL_OUTPUT = 0x8B45,
50 
51     // GLSL output only supported in some configurations.
52     SH_GLSL_COMPATIBILITY_OUTPUT = 0x8B46,
53     // Note: GL introduced core profiles in 1.5.
54     SH_GLSL_130_OUTPUT      = 0x8B47,
55     SH_GLSL_140_OUTPUT      = 0x8B80,
56     SH_GLSL_150_CORE_OUTPUT = 0x8B81,
57     SH_GLSL_330_CORE_OUTPUT = 0x8B82,
58     SH_GLSL_400_CORE_OUTPUT = 0x8B83,
59     SH_GLSL_410_CORE_OUTPUT = 0x8B84,
60     SH_GLSL_420_CORE_OUTPUT = 0x8B85,
61     SH_GLSL_430_CORE_OUTPUT = 0x8B86,
62     SH_GLSL_440_CORE_OUTPUT = 0x8B87,
63     SH_GLSL_450_CORE_OUTPUT = 0x8B88,
64 
65     // Prefer using these to specify HLSL output type:
66     SH_HLSL_3_0_OUTPUT       = 0x8B48,  // D3D 9
67     SH_HLSL_4_1_OUTPUT       = 0x8B49,  // D3D 11
68     SH_HLSL_4_0_FL9_3_OUTPUT = 0x8B4A,  // D3D 11 feature level 9_3
69 
70     // Output specialized GLSL to be fed to glslang for Vulkan SPIR.
71     SH_GLSL_VULKAN_OUTPUT = 0x8B4B,
72 
73     // Output specialized GLSL to be fed to glslang for Vulkan SPIR to be cross compiled to Metal
74     // later.
75     SH_GLSL_METAL_OUTPUT = 0x8B4C,
76 };
77 
78 // Compile options.
79 // The Compile options type is defined in ShaderVars.h, to allow ANGLE to import the ShaderVars
80 // header without needing the ShaderLang header. This avoids some conflicts with glslang.
81 
82 const ShCompileOptions SH_VALIDATE               = 0;
83 const ShCompileOptions SH_VALIDATE_LOOP_INDEXING = UINT64_C(1) << 0;
84 const ShCompileOptions SH_INTERMEDIATE_TREE      = UINT64_C(1) << 1;
85 const ShCompileOptions SH_OBJECT_CODE            = UINT64_C(1) << 2;
86 const ShCompileOptions SH_VARIABLES              = UINT64_C(1) << 3;
87 const ShCompileOptions SH_LINE_DIRECTIVES        = UINT64_C(1) << 4;
88 const ShCompileOptions SH_SOURCE_PATH            = UINT64_C(1) << 5;
89 
90 // This flag will keep invariant declaration for input in fragment shader for GLSL >=4.20 on AMD.
91 // From GLSL >= 4.20, it's optional to add invariant for fragment input, but GPU vendors have
92 // different implementations about this. Some drivers forbid invariant in fragment for GLSL>= 4.20,
93 // e.g. Linux Mesa, some drivers treat that as optional, e.g. NVIDIA, some drivers require invariant
94 // must match between vertex and fragment shader, e.g. AMD. The behavior on AMD is obviously wrong.
95 // Remove invariant for input in fragment shader to workaround the restriction on Intel Mesa.
96 // But don't remove on AMD Linux to avoid triggering the bug on AMD.
97 const ShCompileOptions SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT = UINT64_C(1) << 6;
98 
99 // Due to spec difference between GLSL 4.1 or lower and ESSL3, some platforms (for example, Mac OSX
100 // core profile) require a variable's "invariant"/"centroid" qualifiers to match between vertex and
101 // fragment shader. A simple solution to allow such shaders to link is to omit the two qualifiers.
102 // AMD driver in Linux requires invariant qualifier to match between vertex and fragment shaders,
103 // while ESSL3 disallows invariant qualifier in fragment shader and GLSL >= 4.2 doesn't require
104 // invariant qualifier to match between shaders. Remove invariant qualifier from vertex shader to
105 // workaround AMD driver bug.
106 // Note that the two flags take effect on ESSL3 input shaders translated to GLSL 4.1 or lower and to
107 // GLSL 4.2 or newer on Linux AMD.
108 // TODO(zmo): This is not a good long-term solution. Simply dropping these qualifiers may break some
109 // developers' content. A more complex workaround of dynamically generating, compiling, and
110 // re-linking shaders that use these qualifiers should be implemented.
111 const ShCompileOptions SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3 = UINT64_C(1) << 7;
112 
113 // This flag works around bug in Intel Mac drivers related to abs(i) where
114 // i is an integer.
115 const ShCompileOptions SH_EMULATE_ABS_INT_FUNCTION = UINT64_C(1) << 8;
116 
117 // Enforce the GLSL 1.017 Appendix A section 7 packing restrictions.
118 // This flag only enforces (and can only enforce) the packing
119 // restrictions for uniform variables in both vertex and fragment
120 // shaders. ShCheckVariablesWithinPackingLimits() lets embedders
121 // enforce the packing restrictions for varying variables during
122 // program link time.
123 const ShCompileOptions SH_ENFORCE_PACKING_RESTRICTIONS = UINT64_C(1) << 9;
124 
125 // This flag ensures all indirect (expression-based) array indexing
126 // is clamped to the bounds of the array. This ensures, for example,
127 // that you cannot read off the end of a uniform, whether an array
128 // vec234, or mat234 type. The ShArrayIndexClampingStrategy enum,
129 // specified in the ShBuiltInResources when constructing the
130 // compiler, selects the strategy for the clamping implementation.
131 // TODO(http://anglebug.com/4361): fix for compute shaders.
132 const ShCompileOptions SH_CLAMP_INDIRECT_ARRAY_BOUNDS = UINT64_C(1) << 10;
133 
134 // This flag limits the complexity of an expression.
135 const ShCompileOptions SH_LIMIT_EXPRESSION_COMPLEXITY = UINT64_C(1) << 11;
136 
137 // This flag limits the depth of the call stack.
138 const ShCompileOptions SH_LIMIT_CALL_STACK_DEPTH = UINT64_C(1) << 12;
139 
140 // This flag initializes gl_Position to vec4(0,0,0,0) at the
141 // beginning of the vertex shader's main(), and has no effect in the
142 // fragment shader. It is intended as a workaround for drivers which
143 // incorrectly fail to link programs if gl_Position is not written.
144 const ShCompileOptions SH_INIT_GL_POSITION = UINT64_C(1) << 13;
145 
146 // This flag replaces
147 //   "a && b" with "a ? b : false",
148 //   "a || b" with "a ? true : b".
149 // This is to work around a MacOSX driver bug that |b| is executed
150 // independent of |a|'s value.
151 const ShCompileOptions SH_UNFOLD_SHORT_CIRCUIT = UINT64_C(1) << 14;
152 
153 // This flag initializes output variables to 0 at the beginning of main().
154 // It is to avoid undefined behaviors.
155 const ShCompileOptions SH_INIT_OUTPUT_VARIABLES = UINT64_C(1) << 15;
156 
157 // This flag scalarizes vec/ivec/bvec/mat constructor args.
158 // It is intended as a workaround for Linux/Mac driver bugs.
159 const ShCompileOptions SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS = UINT64_C(1) << 16;
160 
161 // This flag overwrites a struct name with a unique prefix.
162 // It is intended as a workaround for drivers that do not handle
163 // struct scopes correctly, including all Mac drivers and Linux AMD.
164 const ShCompileOptions SH_REGENERATE_STRUCT_NAMES = UINT64_C(1) << 17;
165 
166 // This flag makes the compiler not prune unused function early in the
167 // compilation process. Pruning coupled with SH_LIMIT_CALL_STACK_DEPTH
168 // helps avoid bad shaders causing stack overflows.
169 const ShCompileOptions SH_DONT_PRUNE_UNUSED_FUNCTIONS = UINT64_C(1) << 18;
170 
171 // This flag works around a bug in NVIDIA 331 series drivers related
172 // to pow(x, y) where y is a constant vector.
173 const ShCompileOptions SH_REMOVE_POW_WITH_CONSTANT_EXPONENT = UINT64_C(1) << 19;
174 
175 // This flag works around bugs in Mac drivers related to do-while by
176 // transforming them into an other construct.
177 const ShCompileOptions SH_REWRITE_DO_WHILE_LOOPS = UINT64_C(1) << 20;
178 
179 // This flag works around a bug in the HLSL compiler optimizer that folds certain
180 // constant pow expressions incorrectly. Only applies to the HLSL back-end. It works
181 // by expanding the integer pow expressions into a series of multiplies.
182 const ShCompileOptions SH_EXPAND_SELECT_HLSL_INTEGER_POW_EXPRESSIONS = UINT64_C(1) << 21;
183 
184 // Flatten "#pragma STDGL invariant(all)" into the declarations of
185 // varying variables and built-in GLSL variables. This compiler
186 // option is enabled automatically when needed.
187 const ShCompileOptions SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL = UINT64_C(1) << 22;
188 
189 // Some drivers do not take into account the base level of the texture in the results of the
190 // HLSL GetDimensions builtin.  This flag instructs the compiler to manually add the base level
191 // offsetting.
192 const ShCompileOptions SH_HLSL_GET_DIMENSIONS_IGNORES_BASE_LEVEL = UINT64_C(1) << 23;
193 
194 // This flag works around an issue in translating GLSL function texelFetchOffset on
195 // INTEL drivers. It works by translating texelFetchOffset into texelFetch.
196 const ShCompileOptions SH_REWRITE_TEXELFETCHOFFSET_TO_TEXELFETCH = UINT64_C(1) << 24;
197 
198 // This flag works around condition bug of for and while loops in Intel Mac OSX drivers.
199 // Condition calculation is not correct. Rewrite it from "CONDITION" to "CONDITION && true".
200 const ShCompileOptions SH_ADD_AND_TRUE_TO_LOOP_CONDITION = UINT64_C(1) << 25;
201 
202 // This flag works around a bug in evaluating unary minus operator on integer on some INTEL
203 // drivers. It works by translating -(int) into ~(int) + 1.
204 const ShCompileOptions SH_REWRITE_INTEGER_UNARY_MINUS_OPERATOR = UINT64_C(1) << 26;
205 
206 // This flag works around a bug in evaluating isnan() on some INTEL D3D and Mac OSX drivers.
207 // It works by using an expression to emulate this function.
208 const ShCompileOptions SH_EMULATE_ISNAN_FLOAT_FUNCTION = UINT64_C(1) << 27;
209 
210 // This flag will use all uniforms of unused std140 and shared uniform blocks at the
211 // beginning of the vertex/fragment shader's main(). It is intended as a workaround for Mac
212 // drivers with shader version 4.10. In those drivers, they will treat unused
213 // std140 and shared uniform blocks' members as inactive. However, WebGL2.0 based on
214 // OpenGL ES3.0.4 requires all members of a named uniform block declared with a shared or std140
215 // layout qualifier to be considered active. The uniform block itself is also considered active.
216 const ShCompileOptions SH_USE_UNUSED_STANDARD_SHARED_BLOCKS = UINT64_C(1) << 28;
217 
218 // This flag works around a bug in unary minus operator on float numbers on Intel
219 // Mac OSX 10.11 drivers. It works by translating -float into 0.0 - float.
220 const ShCompileOptions SH_REWRITE_FLOAT_UNARY_MINUS_OPERATOR = UINT64_C(1) << 29;
221 
222 // This flag works around a bug in evaluating atan(y, x) on some NVIDIA OpenGL drivers.
223 // It works by using an expression to emulate this function.
224 const ShCompileOptions SH_EMULATE_ATAN2_FLOAT_FUNCTION = UINT64_C(1) << 30;
225 
226 // Set to initialize uninitialized local and global temporary variables. Should only be used with
227 // GLSL output. In HLSL output variables are initialized regardless of if this flag is set.
228 const ShCompileOptions SH_INITIALIZE_UNINITIALIZED_LOCALS = UINT64_C(1) << 31;
229 
230 // The flag modifies the shader in the following way:
231 // Every occurrence of gl_InstanceID is replaced by the global temporary variable InstanceID.
232 // Every occurrence of gl_ViewID_OVR is replaced by the varying variable ViewID_OVR.
233 // At the beginning of the body of main() in a vertex shader the following initializers are added:
234 // ViewID_OVR = uint(gl_InstanceID) % num_views;
235 // InstanceID = gl_InstanceID / num_views;
236 // ViewID_OVR is added as a varying variable to both the vertex and fragment shaders.
237 const ShCompileOptions SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW = UINT64_C(1) << 32;
238 
239 // With the flag enabled the GLSL/ESSL vertex shader is modified to include code for viewport
240 // selection in the following way:
241 // - Code to enable the extension ARB_shader_viewport_layer_array/NV_viewport_array2 is included.
242 // - Code to select the viewport index or layer is inserted at the beginning of main after
243 // ViewID_OVR's initialization.
244 // - A declaration of the uniform multiviewBaseViewLayerIndex.
245 // Note: The SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW flag also has to be enabled to have the
246 // temporary variable ViewID_OVR declared and initialized.
247 const ShCompileOptions SH_SELECT_VIEW_IN_NV_GLSL_VERTEX_SHADER = UINT64_C(1) << 33;
248 
249 // If the flag is enabled, gl_PointSize is clamped to the maximum point size specified in
250 // ShBuiltInResources in vertex shaders.
251 const ShCompileOptions SH_CLAMP_POINT_SIZE = UINT64_C(1) << 34;
252 
253 // Turn some arithmetic operations that operate on a float vector-scalar pair into vector-vector
254 // operations. This is done recursively. Some scalar binary operations inside vector constructors
255 // are also turned into vector operations.
256 //
257 // This is targeted to work around a bug in NVIDIA OpenGL drivers that was reproducible on NVIDIA
258 // driver version 387.92. It works around the most common occurrences of the bug.
259 const ShCompileOptions SH_REWRITE_VECTOR_SCALAR_ARITHMETIC = UINT64_C(1) << 35;
260 
261 // Don't use loops to initialize uninitialized variables. Only has an effect if some kind of
262 // variable initialization is turned on.
263 const ShCompileOptions SH_DONT_USE_LOOPS_TO_INITIALIZE_VARIABLES = UINT64_C(1) << 36;
264 
265 // Don't use D3D constant register zero when allocating space for uniforms. This is targeted to work
266 // around a bug in NVIDIA D3D driver version 388.59 where in very specific cases the driver would
267 // not handle constant register zero correctly. Only has an effect on HLSL translation.
268 const ShCompileOptions SH_SKIP_D3D_CONSTANT_REGISTER_ZERO = UINT64_C(1) << 37;
269 
270 // Clamp gl_FragDepth to the range [0.0, 1.0] in case it is statically used.
271 const ShCompileOptions SH_CLAMP_FRAG_DEPTH = UINT64_C(1) << 38;
272 
273 // Rewrite expressions like "v.x = z = expression;". Works around a bug in NVIDIA OpenGL drivers
274 // prior to version 397.31.
275 const ShCompileOptions SH_REWRITE_REPEATED_ASSIGN_TO_SWIZZLED = UINT64_C(1) << 39;
276 
277 // Rewrite gl_DrawID as a uniform int
278 const ShCompileOptions SH_EMULATE_GL_DRAW_ID = UINT64_C(1) << 40;
279 
280 // This flag initializes shared variables to 0.
281 // It is to avoid ompute shaders being able to read undefined values that could be coming from
282 // another webpage/application.
283 const ShCompileOptions SH_INIT_SHARED_VARIABLES = UINT64_C(1) << 41;
284 
285 // Forces the value returned from an atomic operations to be always be resolved. This is targeted to
286 // workaround a bug in NVIDIA D3D driver where the return value from
287 // RWByteAddressBuffer.InterlockedAdd does not get resolved when used in the .yzw components of a
288 // RWByteAddressBuffer.Store operation. Only has an effect on HLSL translation.
289 // http://anglebug.com/3246
290 const ShCompileOptions SH_FORCE_ATOMIC_VALUE_RESOLUTION = UINT64_C(1) << 42;
291 
292 // Rewrite gl_BaseVertex and gl_BaseInstance as uniform int
293 const ShCompileOptions SH_EMULATE_GL_BASE_VERTEX_BASE_INSTANCE = UINT64_C(1) << 43;
294 
295 // Emulate seamful cube map sampling for OpenGL ES2.0.  Currently only applies to the Vulkan
296 // backend, as is done after samplers are moved out of structs.  Can likely be made to work on
297 // the other backends as well.
298 const ShCompileOptions SH_EMULATE_SEAMFUL_CUBE_MAP_SAMPLING = UINT64_C(1) << 44;
299 
300 // This flag controls how to translate WEBGL_video_texture sampling function.
301 const ShCompileOptions SH_TAKE_VIDEO_TEXTURE_AS_EXTERNAL_OES = UINT64_C(1) << 45;
302 
303 // If requested, validates the AST after every transformation.  Useful for debugging.
304 const ShCompileOptions SH_VALIDATE_AST = UINT64_C(1) << 46;
305 
306 // Use old version of RewriteStructSamplers, which doesn't produce as many
307 // sampler arrays in parameters. This causes a few tests to pass on Android.
308 const ShCompileOptions SH_USE_OLD_REWRITE_STRUCT_SAMPLERS = UINT64_C(1) << 47;
309 
310 // This flag works around a inconsistent behavior in Mac AMD driver where gl_VertexID doesn't
311 // include base vertex value. It replaces gl_VertexID with (gl_VertexID + angle_BaseVertex)
312 // when angle_BaseVertex is available.
313 const ShCompileOptions SH_ADD_BASE_VERTEX_TO_VERTEX_ID = UINT64_C(1) << 48;
314 
315 // This works around the dynamic lvalue indexing of swizzled vectors on various platforms.
316 const ShCompileOptions SH_REMOVE_DYNAMIC_INDEXING_OF_SWIZZLED_VECTOR = UINT64_C(1) << 49;
317 
318 // This flag works a driver bug that fails to allocate ShaderResourceView for StructuredBuffer
319 // on Windows 7 and earlier.
320 const ShCompileOptions SH_DONT_TRANSLATE_UNIFORM_BLOCK_TO_STRUCTUREDBUFFER = UINT64_C(1) << 50;
321 
322 // This flag indicates whether Bresenham line raster emulation code should be generated.  This
323 // emulation is necessary if the backend uses a differnet algorithm to draw lines.  Currently only
324 // implemented for the Vulkan backend.
325 const ShCompileOptions SH_ADD_BRESENHAM_LINE_RASTER_EMULATION = UINT64_C(1) << 51;
326 
327 // This flag allows disabling ARB_texture_rectangle on a per-compile basis. This is necessary
328 // for WebGL contexts becuase ARB_texture_rectangle may be necessary for the WebGL implementation
329 // internally but shouldn't be exposed to WebGL user code.
330 const ShCompileOptions SH_DISABLE_ARB_TEXTURE_RECTANGLE = UINT64_C(1) << 52;
331 
332 // This flag works around a driver bug by rewriting uses of row-major matrices
333 // as column-major in ESSL 3.00 and greater shaders.
334 const ShCompileOptions SH_REWRITE_ROW_MAJOR_MATRICES = UINT64_C(1) << 53;
335 
336 // Drop any explicit precision qualifiers from shader.
337 const ShCompileOptions SH_IGNORE_PRECISION_QUALIFIERS = UINT64_C(1) << 54;
338 
339 // Allow compiler to do early fragment tests as an optimization.
340 const ShCompileOptions SH_EARLY_FRAGMENT_TESTS_OPTIMIZATION = UINT64_C(1) << 55;
341 
342 // Defines alternate strategies for implementing array index clamping.
343 enum ShArrayIndexClampingStrategy
344 {
345     // Use the clamp intrinsic for array index clamping.
346     SH_CLAMP_WITH_CLAMP_INTRINSIC = 1,
347 
348     // Use a user-defined function for array index clamping.
349     SH_CLAMP_WITH_USER_DEFINED_INT_CLAMP_FUNCTION
350 };
351 
352 // The 64 bits hash function. The first parameter is the input string; the
353 // second parameter is the string length.
354 using ShHashFunction64 = khronos_uint64_t (*)(const char *, size_t);
355 
356 //
357 // Implementation dependent built-in resources (constants and extensions).
358 // The names for these resources has been obtained by stripping gl_/GL_.
359 //
360 struct ShBuiltInResources
361 {
362     // Constants.
363     int MaxVertexAttribs;
364     int MaxVertexUniformVectors;
365     int MaxVaryingVectors;
366     int MaxVertexTextureImageUnits;
367     int MaxCombinedTextureImageUnits;
368     int MaxTextureImageUnits;
369     int MaxFragmentUniformVectors;
370     int MaxDrawBuffers;
371 
372     // Extensions.
373     // Set to 1 to enable the extension, else 0.
374     int OES_standard_derivatives;
375     int OES_EGL_image_external;
376     int OES_EGL_image_external_essl3;
377     int NV_EGL_stream_consumer_external;
378     int ARB_texture_rectangle;
379     int EXT_blend_func_extended;
380     int EXT_draw_buffers;
381     int EXT_frag_depth;
382     int EXT_shader_texture_lod;
383     int WEBGL_debug_shader_precision;
384     int EXT_shader_framebuffer_fetch;
385     int NV_shader_framebuffer_fetch;
386     int NV_shader_noperspective_interpolation;
387     int ARM_shader_framebuffer_fetch;
388     int OVR_multiview;
389     int OVR_multiview2;
390     int EXT_multisampled_render_to_texture;
391     int EXT_YUV_target;
392     int EXT_geometry_shader;
393     int EXT_gpu_shader5;
394     int EXT_shader_non_constant_global_initializers;
395     int OES_texture_storage_multisample_2d_array;
396     int OES_texture_3D;
397     int ANGLE_texture_multisample;
398     int ANGLE_multi_draw;
399     int ANGLE_base_vertex_base_instance;
400     int WEBGL_video_texture;
401     int APPLE_clip_distance;
402     int OES_texture_cube_map_array;
403     int EXT_texture_cube_map_array;
404 
405     // Set to 1 to enable replacing GL_EXT_draw_buffers #extension directives
406     // with GL_NV_draw_buffers in ESSL output. This flag can be used to emulate
407     // EXT_draw_buffers by using it in combination with GLES3.0 glDrawBuffers
408     // function. This applies to Tegra K1 devices.
409     int NV_draw_buffers;
410 
411     // Set to 1 if highp precision is supported in the ESSL 1.00 version of the
412     // fragment language. Does not affect versions of the language where highp
413     // support is mandatory.
414     // Default is 0.
415     int FragmentPrecisionHigh;
416 
417     // GLSL ES 3.0 constants.
418     int MaxVertexOutputVectors;
419     int MaxFragmentInputVectors;
420     int MinProgramTexelOffset;
421     int MaxProgramTexelOffset;
422 
423     // Extension constants.
424 
425     // Value of GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT for OpenGL ES output context.
426     // Value of GL_MAX_DUAL_SOURCE_DRAW_BUFFERS for OpenGL output context.
427     // GLES SL version 100 gl_MaxDualSourceDrawBuffersEXT value for EXT_blend_func_extended.
428     int MaxDualSourceDrawBuffers;
429 
430     // Value of GL_MAX_VIEWS_OVR.
431     int MaxViewsOVR;
432 
433     // Name Hashing.
434     // Set a 64 bit hash function to enable user-defined name hashing.
435     // Default is NULL.
436     ShHashFunction64 HashFunction;
437 
438     // Selects a strategy to use when implementing array index clamping.
439     // Default is SH_CLAMP_WITH_CLAMP_INTRINSIC.
440     ShArrayIndexClampingStrategy ArrayIndexClampingStrategy;
441 
442     // The maximum complexity an expression can be when SH_LIMIT_EXPRESSION_COMPLEXITY is turned on.
443     int MaxExpressionComplexity;
444 
445     // The maximum depth a call stack can be.
446     int MaxCallStackDepth;
447 
448     // The maximum number of parameters a function can have when SH_LIMIT_EXPRESSION_COMPLEXITY is
449     // turned on.
450     int MaxFunctionParameters;
451 
452     // GLES 3.1 constants
453 
454     // texture gather offset constraints.
455     int MinProgramTextureGatherOffset;
456     int MaxProgramTextureGatherOffset;
457 
458     // maximum number of available image units
459     int MaxImageUnits;
460 
461     // maximum number of image uniforms in a vertex shader
462     int MaxVertexImageUniforms;
463 
464     // maximum number of image uniforms in a fragment shader
465     int MaxFragmentImageUniforms;
466 
467     // maximum number of image uniforms in a compute shader
468     int MaxComputeImageUniforms;
469 
470     // maximum total number of image uniforms in a program
471     int MaxCombinedImageUniforms;
472 
473     // maximum number of uniform locations
474     int MaxUniformLocations;
475 
476     // maximum number of ssbos and images in a shader
477     int MaxCombinedShaderOutputResources;
478 
479     // maximum number of groups in each dimension
480     std::array<int, 3> MaxComputeWorkGroupCount;
481     // maximum number of threads per work group in each dimension
482     std::array<int, 3> MaxComputeWorkGroupSize;
483 
484     // maximum number of total uniform components
485     int MaxComputeUniformComponents;
486 
487     // maximum number of texture image units in a compute shader
488     int MaxComputeTextureImageUnits;
489 
490     // maximum number of atomic counters in a compute shader
491     int MaxComputeAtomicCounters;
492 
493     // maximum number of atomic counter buffers in a compute shader
494     int MaxComputeAtomicCounterBuffers;
495 
496     // maximum number of atomic counters in a vertex shader
497     int MaxVertexAtomicCounters;
498 
499     // maximum number of atomic counters in a fragment shader
500     int MaxFragmentAtomicCounters;
501 
502     // maximum number of atomic counters in a program
503     int MaxCombinedAtomicCounters;
504 
505     // maximum binding for an atomic counter
506     int MaxAtomicCounterBindings;
507 
508     // maximum number of atomic counter buffers in a vertex shader
509     int MaxVertexAtomicCounterBuffers;
510 
511     // maximum number of atomic counter buffers in a fragment shader
512     int MaxFragmentAtomicCounterBuffers;
513 
514     // maximum number of atomic counter buffers in a program
515     int MaxCombinedAtomicCounterBuffers;
516 
517     // maximum number of buffer object storage in machine units
518     int MaxAtomicCounterBufferSize;
519 
520     // maximum number of uniform block bindings
521     int MaxUniformBufferBindings;
522 
523     // maximum number of shader storage buffer bindings
524     int MaxShaderStorageBufferBindings;
525 
526     // maximum point size (higher limit from ALIASED_POINT_SIZE_RANGE)
527     float MaxPointSize;
528 
529     // EXT_geometry_shader constants
530     int MaxGeometryUniformComponents;
531     int MaxGeometryUniformBlocks;
532     int MaxGeometryInputComponents;
533     int MaxGeometryOutputComponents;
534     int MaxGeometryOutputVertices;
535     int MaxGeometryTotalOutputComponents;
536     int MaxGeometryTextureImageUnits;
537     int MaxGeometryAtomicCounterBuffers;
538     int MaxGeometryAtomicCounters;
539     int MaxGeometryShaderStorageBlocks;
540     int MaxGeometryShaderInvocations;
541     int MaxGeometryImageUniforms;
542 
543     // Subpixel bits used in rasterization.
544     int SubPixelBits;
545 
546     // APPLE_clip_distance/EXT_clip_cull_distance constant
547     int MaxClipDistances;
548 };
549 
550 //
551 // ShHandle held by but opaque to the driver.  It is allocated,
552 // managed, and de-allocated by the compiler. Its contents
553 // are defined by and used by the compiler.
554 //
555 // If handle creation fails, 0 will be returned.
556 //
557 using ShHandle = void *;
558 
559 namespace sh
560 {
561 
562 //
563 // Driver must call this first, once, before doing any other compiler operations.
564 // If the function succeeds, the return value is true, else false.
565 //
566 bool Initialize();
567 //
568 // Driver should call this at shutdown.
569 // If the function succeeds, the return value is true, else false.
570 //
571 bool Finalize();
572 
573 //
574 // Initialize built-in resources with minimum expected values.
575 // Parameters:
576 // resources: The object to initialize. Will be comparable with memcmp.
577 //
578 void InitBuiltInResources(ShBuiltInResources *resources);
579 
580 //
581 // Returns the a concatenated list of the items in ShBuiltInResources as a null-terminated string.
582 // This function must be updated whenever ShBuiltInResources is changed.
583 // Parameters:
584 // handle: Specifies the handle of the compiler to be used.
585 const std::string &GetBuiltInResourcesString(const ShHandle handle);
586 
587 //
588 // Driver calls these to create and destroy compiler objects.
589 //
590 // Returns the handle of constructed compiler, null if the requested compiler is not supported.
591 // Parameters:
592 // type: Specifies the type of shader - GL_FRAGMENT_SHADER or GL_VERTEX_SHADER.
593 // spec: Specifies the language spec the compiler must conform to - SH_GLES2_SPEC or SH_WEBGL_SPEC.
594 // output: Specifies the output code type - for example SH_ESSL_OUTPUT, SH_GLSL_OUTPUT,
595 //         SH_HLSL_3_0_OUTPUT or SH_HLSL_4_1_OUTPUT. Note: Each output type may only
596 //         be supported in some configurations.
597 // resources: Specifies the built-in resources.
598 ShHandle ConstructCompiler(sh::GLenum type,
599                            ShShaderSpec spec,
600                            ShShaderOutput output,
601                            const ShBuiltInResources *resources);
602 void Destruct(ShHandle handle);
603 
604 //
605 // Compiles the given shader source.
606 // If the function succeeds, the return value is true, else false.
607 // Parameters:
608 // handle: Specifies the handle of compiler to be used.
609 // shaderStrings: Specifies an array of pointers to null-terminated strings containing the shader
610 // source code.
611 // numStrings: Specifies the number of elements in shaderStrings array.
612 // compileOptions: A mask containing the following parameters:
613 // SH_VALIDATE: Validates shader to ensure that it conforms to the spec
614 //              specified during compiler construction.
615 // SH_VALIDATE_LOOP_INDEXING: Validates loop and indexing in the shader to
616 //                            ensure that they do not exceed the minimum
617 //                            functionality mandated in GLSL 1.0 spec,
618 //                            Appendix A, Section 4 and 5.
619 //                            There is no need to specify this parameter when
620 //                            compiling for WebGL - it is implied.
621 // SH_INTERMEDIATE_TREE: Writes intermediate tree to info log.
622 //                       Can be queried by calling sh::GetInfoLog().
623 // SH_OBJECT_CODE: Translates intermediate tree to glsl or hlsl shader.
624 //                 Can be queried by calling sh::GetObjectCode().
625 // SH_VARIABLES: Extracts attributes, uniforms, and varyings.
626 //               Can be queried by calling ShGetVariableInfo().
627 //
628 bool Compile(const ShHandle handle,
629              const char *const shaderStrings[],
630              size_t numStrings,
631              ShCompileOptions compileOptions);
632 
633 // Clears the results from the previous compilation.
634 void ClearResults(const ShHandle handle);
635 
636 // Return the version of the shader language.
637 int GetShaderVersion(const ShHandle handle);
638 
639 // Return the currently set language output type.
640 ShShaderOutput GetShaderOutputType(const ShHandle handle);
641 
642 // Returns null-terminated information log for a compiled shader.
643 // Parameters:
644 // handle: Specifies the compiler
645 const std::string &GetInfoLog(const ShHandle handle);
646 
647 // Returns null-terminated object code for a compiled shader.
648 // Parameters:
649 // handle: Specifies the compiler
650 const std::string &GetObjectCode(const ShHandle handle);
651 
652 // Returns a (original_name, hash) map containing all the user defined names in the shader,
653 // including variable names, function names, struct names, and struct field names.
654 // Parameters:
655 // handle: Specifies the compiler
656 const std::map<std::string, std::string> *GetNameHashingMap(const ShHandle handle);
657 
658 // Shader variable inspection.
659 // Returns a pointer to a list of variables of the designated type.
660 // (See ShaderVars.h for type definitions, included above)
661 // Returns NULL on failure.
662 // Parameters:
663 // handle: Specifies the compiler
664 const std::vector<sh::ShaderVariable> *GetUniforms(const ShHandle handle);
665 const std::vector<sh::ShaderVariable> *GetVaryings(const ShHandle handle);
666 const std::vector<sh::ShaderVariable> *GetInputVaryings(const ShHandle handle);
667 const std::vector<sh::ShaderVariable> *GetOutputVaryings(const ShHandle handle);
668 const std::vector<sh::ShaderVariable> *GetAttributes(const ShHandle handle);
669 const std::vector<sh::ShaderVariable> *GetOutputVariables(const ShHandle handle);
670 const std::vector<sh::InterfaceBlock> *GetInterfaceBlocks(const ShHandle handle);
671 const std::vector<sh::InterfaceBlock> *GetUniformBlocks(const ShHandle handle);
672 const std::vector<sh::InterfaceBlock> *GetShaderStorageBlocks(const ShHandle handle);
673 sh::WorkGroupSize GetComputeShaderLocalGroupSize(const ShHandle handle);
674 // Returns the number of views specified through the num_views layout qualifier. If num_views is
675 // not set, the function returns -1.
676 int GetVertexShaderNumViews(const ShHandle handle);
677 // Returns true if compiler has injected instructions for early fragment tests as an optimization
678 bool HasEarlyFragmentTestsOptimization(const ShHandle handle);
679 
680 // Returns true if the passed in variables pack in maxVectors followingthe packing rules from the
681 // GLSL 1.017 spec, Appendix A, section 7.
682 // Returns false otherwise. Also look at the SH_ENFORCE_PACKING_RESTRICTIONS
683 // flag above.
684 // Parameters:
685 // maxVectors: the available rows of registers.
686 // variables: an array of variables.
687 bool CheckVariablesWithinPackingLimits(int maxVectors,
688                                        const std::vector<sh::ShaderVariable> &variables);
689 
690 // Gives the compiler-assigned register for a shader storage block.
691 // The method writes the value to the output variable "indexOut".
692 // Returns true if it found a valid shader storage block, false otherwise.
693 // Parameters:
694 // handle: Specifies the compiler
695 // shaderStorageBlockName: Specifies the shader storage block
696 // indexOut: output variable that stores the assigned register
697 bool GetShaderStorageBlockRegister(const ShHandle handle,
698                                    const std::string &shaderStorageBlockName,
699                                    unsigned int *indexOut);
700 
701 // Gives the compiler-assigned register for a uniform block.
702 // The method writes the value to the output variable "indexOut".
703 // Returns true if it found a valid uniform block, false otherwise.
704 // Parameters:
705 // handle: Specifies the compiler
706 // uniformBlockName: Specifies the uniform block
707 // indexOut: output variable that stores the assigned register
708 bool GetUniformBlockRegister(const ShHandle handle,
709                              const std::string &uniformBlockName,
710                              unsigned int *indexOut);
711 
712 bool ShouldUniformBlockUseStructuredBuffer(const ShHandle handle,
713                                            const std::string &uniformBlockName);
714 
715 // Gives a map from uniform names to compiler-assigned registers in the default uniform block.
716 // Note that the map contains also registers of samplers that have been extracted from structs.
717 const std::map<std::string, unsigned int> *GetUniformRegisterMap(const ShHandle handle);
718 
719 // Sampler, image and atomic counters share registers(t type and u type),
720 // GetReadonlyImage2DRegisterIndex and GetImage2DRegisterIndex return the first index into
721 // a range of reserved registers for image2D/iimage2D/uimage2D variables.
722 // Parameters: handle: Specifies the compiler
723 unsigned int GetReadonlyImage2DRegisterIndex(const ShHandle handle);
724 unsigned int GetImage2DRegisterIndex(const ShHandle handle);
725 
726 // The method records these used function names related with image2D/iimage2D/uimage2D, these
727 // functions will be dynamically generated.
728 // Parameters:
729 // handle: Specifies the compiler
730 const std::set<std::string> *GetUsedImage2DFunctionNames(const ShHandle handle);
731 
732 bool HasValidGeometryShaderInputPrimitiveType(const ShHandle handle);
733 bool HasValidGeometryShaderOutputPrimitiveType(const ShHandle handle);
734 bool HasValidGeometryShaderMaxVertices(const ShHandle handle);
735 GLenum GetGeometryShaderInputPrimitiveType(const ShHandle handle);
736 GLenum GetGeometryShaderOutputPrimitiveType(const ShHandle handle);
737 int GetGeometryShaderInvocations(const ShHandle handle);
738 int GetGeometryShaderMaxVertices(const ShHandle handle);
739 unsigned int GetShaderSharedMemorySize(const ShHandle handle);
740 
741 //
742 // Helper function to identify specs that are based on the WebGL spec.
743 //
IsWebGLBasedSpec(ShShaderSpec spec)744 inline bool IsWebGLBasedSpec(ShShaderSpec spec)
745 {
746     return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
747 }
748 
749 //
750 // Helper function to identify DesktopGL specs
751 //
IsDesktopGLSpec(ShShaderSpec spec)752 inline bool IsDesktopGLSpec(ShShaderSpec spec)
753 {
754     return spec == SH_GL_CORE_SPEC || spec == SH_GL_COMPATIBILITY_SPEC;
755 }
756 
757 // Can't prefix with just _ because then we might introduce a double underscore, which is not safe
758 // in GLSL (ESSL 3.00.6 section 3.8: All identifiers containing a double underscore are reserved for
759 // use by the underlying implementation). u is short for user-defined.
760 extern const char kUserDefinedNamePrefix[];
761 
762 namespace vk
763 {
764 
765 // Specialization constant ids
766 enum class SpecializationConstantId : uint32_t
767 {
768     LineRasterEmulation = 0,
769 
770     InvalidEnum = 1,
771     EnumCount   = 1,
772 };
773 
774 // Interface block name containing the aggregate default uniforms
775 extern const char kDefaultUniformsNameVS[];
776 extern const char kDefaultUniformsNameTCS[];
777 extern const char kDefaultUniformsNameTES[];
778 extern const char kDefaultUniformsNameGS[];
779 extern const char kDefaultUniformsNameFS[];
780 extern const char kDefaultUniformsNameCS[];
781 
782 // Interface block and variable names containing driver uniforms
783 extern const char kDriverUniformsBlockName[];
784 extern const char kDriverUniformsVarName[];
785 
786 // Interface block array name used for atomic counter emulation
787 extern const char kAtomicCountersBlockName[];
788 
789 // Line raster emulation varying
790 extern const char kLineRasterEmulationPosition[];
791 
792 }  // namespace vk
793 }  // namespace sh
794 
795 #endif  // GLSLANG_SHADERLANG_H_
796