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 268
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_GLES3_2_SPEC,
43
44 SH_GL_CORE_SPEC,
45 SH_GL_COMPATIBILITY_SPEC,
46 };
47
48 enum ShShaderOutput
49 {
50 // ESSL output only supported in some configurations.
51 SH_ESSL_OUTPUT = 0x8B45,
52
53 // GLSL output only supported in some configurations.
54 SH_GLSL_COMPATIBILITY_OUTPUT = 0x8B46,
55 // Note: GL introduced core profiles in 1.5.
56 SH_GLSL_130_OUTPUT = 0x8B47,
57 SH_GLSL_140_OUTPUT = 0x8B80,
58 SH_GLSL_150_CORE_OUTPUT = 0x8B81,
59 SH_GLSL_330_CORE_OUTPUT = 0x8B82,
60 SH_GLSL_400_CORE_OUTPUT = 0x8B83,
61 SH_GLSL_410_CORE_OUTPUT = 0x8B84,
62 SH_GLSL_420_CORE_OUTPUT = 0x8B85,
63 SH_GLSL_430_CORE_OUTPUT = 0x8B86,
64 SH_GLSL_440_CORE_OUTPUT = 0x8B87,
65 SH_GLSL_450_CORE_OUTPUT = 0x8B88,
66
67 // Prefer using these to specify HLSL output type:
68 SH_HLSL_3_0_OUTPUT = 0x8B48, // D3D 9
69 SH_HLSL_4_1_OUTPUT = 0x8B49, // D3D 11
70 SH_HLSL_4_0_FL9_3_OUTPUT = 0x8B4A, // D3D 11 feature level 9_3
71
72 // Output SPIR-V for the Vulkan backend.
73 SH_SPIRV_VULKAN_OUTPUT = 0x8B4B,
74
75 // Output SPIR-V to be cross compiled to Metal.
76 SH_SPIRV_METAL_OUTPUT = 0x8B4C,
77
78 // Output for MSL
79 SH_MSL_METAL_OUTPUT = 0x8B4D,
80 };
81
82 // Compile options.
83 // The Compile options type is defined in ShaderVars.h, to allow ANGLE to import the ShaderVars
84 // header without needing the ShaderLang header. This avoids some conflicts with glslang.
85 // SH_VALIDATE_LOOP_INDEXING: Validates loop and indexing in the shader to
86 // ensure that they do not exceed the minimum
87 // functionality mandated in GLSL 1.0 spec,
88 // Appendix A, Section 4 and 5.
89 // There is no need to specify this parameter when
90 // compiling for WebGL - it is implied.
91 // SH_OBJECT_CODE: Translates intermediate tree to glsl or hlsl shader, or SPIR-V binary.
92 // Can be queried by calling sh::GetObjectCode().
93 // SH_VARIABLES: Extracts attributes, uniforms, and varyings.
94 // Can be queried by calling ShGetVariableInfo().
95 // SH_LINE_DIRECTIVES: Emits #line directives in HLSL.
96 // SH_SOURCE_PATH: Tracks the source path for shaders.
97 // Can be queried with getSourcePath().
98 const ShCompileOptions SH_VALIDATE_LOOP_INDEXING = UINT64_C(1) << 0;
99 const ShCompileOptions SH_INTERMEDIATE_TREE = UINT64_C(1) << 1;
100 const ShCompileOptions SH_OBJECT_CODE = UINT64_C(1) << 2;
101 const ShCompileOptions SH_VARIABLES = UINT64_C(1) << 3;
102 const ShCompileOptions SH_LINE_DIRECTIVES = UINT64_C(1) << 4;
103 const ShCompileOptions SH_SOURCE_PATH = UINT64_C(1) << 5;
104
105 // If requested, validates the AST after every transformation. Useful for debugging.
106 const ShCompileOptions SH_VALIDATE_AST = UINT64_C(1) << 6;
107
108 // Due to spec difference between GLSL 4.1 or lower and ESSL3, some platforms (for example, Mac OSX
109 // core profile) require a variable's "invariant"/"centroid" qualifiers to match between vertex and
110 // fragment shader. A simple solution to allow such shaders to link is to omit the two qualifiers.
111 // AMD driver in Linux requires invariant qualifier to match between vertex and fragment shaders,
112 // while ESSL3 disallows invariant qualifier in fragment shader and GLSL >= 4.2 doesn't require
113 // invariant qualifier to match between shaders. Remove invariant qualifier from vertex shader to
114 // workaround AMD driver bug.
115 // Note that the two flags take effect on ESSL3 input shaders translated to GLSL 4.1 or lower and to
116 // GLSL 4.2 or newer on Linux AMD.
117 // TODO(zmo): This is not a good long-term solution. Simply dropping these qualifiers may break some
118 // developers' content. A more complex workaround of dynamically generating, compiling, and
119 // re-linking shaders that use these qualifiers should be implemented.
120 const ShCompileOptions SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3 = UINT64_C(1) << 7;
121
122 // This flag works around bug in Intel Mac drivers related to abs(i) where
123 // i is an integer.
124 const ShCompileOptions SH_EMULATE_ABS_INT_FUNCTION = UINT64_C(1) << 8;
125
126 // Enforce the GLSL 1.017 Appendix A section 7 packing restrictions.
127 // This flag only enforces (and can only enforce) the packing
128 // restrictions for uniform variables in both vertex and fragment
129 // shaders. ShCheckVariablesWithinPackingLimits() lets embedders
130 // enforce the packing restrictions for varying variables during
131 // program link time.
132 const ShCompileOptions SH_ENFORCE_PACKING_RESTRICTIONS = UINT64_C(1) << 9;
133
134 // This flag ensures all indirect (expression-based) array indexing
135 // is clamped to the bounds of the array. This ensures, for example,
136 // that you cannot read off the end of a uniform, whether an array
137 // vec234, or mat234 type.
138 const ShCompileOptions SH_CLAMP_INDIRECT_ARRAY_BOUNDS = UINT64_C(1) << 10;
139
140 // This flag limits the complexity of an expression.
141 const ShCompileOptions SH_LIMIT_EXPRESSION_COMPLEXITY = UINT64_C(1) << 11;
142
143 // This flag limits the depth of the call stack.
144 const ShCompileOptions SH_LIMIT_CALL_STACK_DEPTH = UINT64_C(1) << 12;
145
146 // This flag initializes gl_Position to vec4(0,0,0,0) at the
147 // beginning of the vertex shader's main(), and has no effect in the
148 // fragment shader. It is intended as a workaround for drivers which
149 // incorrectly fail to link programs if gl_Position is not written.
150 const ShCompileOptions SH_INIT_GL_POSITION = UINT64_C(1) << 13;
151
152 // This flag replaces
153 // "a && b" with "a ? b : false",
154 // "a || b" with "a ? true : b".
155 // This is to work around a MacOSX driver bug that |b| is executed
156 // independent of |a|'s value.
157 const ShCompileOptions SH_UNFOLD_SHORT_CIRCUIT = UINT64_C(1) << 14;
158
159 // This flag initializes output variables to 0 at the beginning of main().
160 // It is to avoid undefined behaviors.
161 const ShCompileOptions SH_INIT_OUTPUT_VARIABLES = UINT64_C(1) << 15;
162
163 // This flag scalarizes vec/ivec/bvec/mat constructor args.
164 // It is intended as a workaround for Linux/Mac driver bugs.
165 const ShCompileOptions SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS = UINT64_C(1) << 16;
166
167 // This flag overwrites a struct name with a unique prefix.
168 // It is intended as a workaround for drivers that do not handle
169 // struct scopes correctly, including all Mac drivers and Linux AMD.
170 const ShCompileOptions SH_REGENERATE_STRUCT_NAMES = UINT64_C(1) << 17;
171
172 // This flag works around bugs in Mac drivers related to do-while by
173 // transforming them into an other construct.
174 const ShCompileOptions SH_REWRITE_DO_WHILE_LOOPS = UINT64_C(1) << 18;
175
176 // This flag works around a bug in the HLSL compiler optimizer that folds certain
177 // constant pow expressions incorrectly. Only applies to the HLSL back-end. It works
178 // by expanding the integer pow expressions into a series of multiplies.
179 const ShCompileOptions SH_EXPAND_SELECT_HLSL_INTEGER_POW_EXPRESSIONS = UINT64_C(1) << 19;
180
181 // Flatten "#pragma STDGL invariant(all)" into the declarations of
182 // varying variables and built-in GLSL variables. This compiler
183 // option is enabled automatically when needed.
184 const ShCompileOptions SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL = UINT64_C(1) << 20;
185
186 // Some drivers do not take into account the base level of the texture in the results of the
187 // HLSL GetDimensions builtin. This flag instructs the compiler to manually add the base level
188 // offsetting.
189 const ShCompileOptions SH_HLSL_GET_DIMENSIONS_IGNORES_BASE_LEVEL = UINT64_C(1) << 21;
190
191 // This flag works around an issue in translating GLSL function texelFetchOffset on
192 // INTEL drivers. It works by translating texelFetchOffset into texelFetch.
193 const ShCompileOptions SH_REWRITE_TEXELFETCHOFFSET_TO_TEXELFETCH = UINT64_C(1) << 22;
194
195 // This flag works around condition bug of for and while loops in Intel Mac OSX drivers.
196 // Condition calculation is not correct. Rewrite it from "CONDITION" to "CONDITION && true".
197 const ShCompileOptions SH_ADD_AND_TRUE_TO_LOOP_CONDITION = UINT64_C(1) << 23;
198
199 // This flag works around a bug in evaluating unary minus operator on integer on some INTEL
200 // drivers. It works by translating -(int) into ~(int) + 1.
201 const ShCompileOptions SH_REWRITE_INTEGER_UNARY_MINUS_OPERATOR = UINT64_C(1) << 24;
202
203 // This flag works around a bug in evaluating isnan() on some INTEL D3D and Mac OSX drivers.
204 // It works by using an expression to emulate this function.
205 const ShCompileOptions SH_EMULATE_ISNAN_FLOAT_FUNCTION = UINT64_C(1) << 25;
206
207 // This flag will use all uniforms of unused std140 and shared uniform blocks at the
208 // beginning of the vertex/fragment shader's main(). It is intended as a workaround for Mac
209 // drivers with shader version 4.10. In those drivers, they will treat unused
210 // std140 and shared uniform blocks' members as inactive. However, WebGL2.0 based on
211 // OpenGL ES3.0.4 requires all members of a named uniform block declared with a shared or std140
212 // layout qualifier to be considered active. The uniform block itself is also considered active.
213 const ShCompileOptions SH_USE_UNUSED_STANDARD_SHARED_BLOCKS = UINT64_C(1) << 26;
214
215 // This flag works around a bug in unary minus operator on float numbers on Intel
216 // Mac OSX 10.11 drivers. It works by translating -float into 0.0 - float.
217 const ShCompileOptions SH_REWRITE_FLOAT_UNARY_MINUS_OPERATOR = UINT64_C(1) << 27;
218
219 // This flag works around a bug in evaluating atan(y, x) on some NVIDIA OpenGL drivers.
220 // It works by using an expression to emulate this function.
221 const ShCompileOptions SH_EMULATE_ATAN2_FLOAT_FUNCTION = UINT64_C(1) << 28;
222
223 // Set to initialize uninitialized local and global temporary variables. Should only be used with
224 // GLSL output. In HLSL output variables are initialized regardless of if this flag is set.
225 const ShCompileOptions SH_INITIALIZE_UNINITIALIZED_LOCALS = UINT64_C(1) << 29;
226
227 // The flag modifies the shader in the following way:
228 // Every occurrence of gl_InstanceID is replaced by the global temporary variable InstanceID.
229 // Every occurrence of gl_ViewID_OVR is replaced by the varying variable ViewID_OVR.
230 // At the beginning of the body of main() in a vertex shader the following initializers are added:
231 // ViewID_OVR = uint(gl_InstanceID) % num_views;
232 // InstanceID = gl_InstanceID / num_views;
233 // ViewID_OVR is added as a varying variable to both the vertex and fragment shaders.
234 const ShCompileOptions SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW = UINT64_C(1) << 30;
235
236 // With the flag enabled the GLSL/ESSL vertex shader is modified to include code for viewport
237 // selection in the following way:
238 // - Code to enable the extension ARB_shader_viewport_layer_array/NV_viewport_array2 is included.
239 // - Code to select the viewport index or layer is inserted at the beginning of main after
240 // ViewID_OVR's initialization.
241 // - A declaration of the uniform multiviewBaseViewLayerIndex.
242 // Note: The SH_INITIALIZE_BUILTINS_FOR_INSTANCED_MULTIVIEW flag also has to be enabled to have the
243 // temporary variable ViewID_OVR declared and initialized.
244 const ShCompileOptions SH_SELECT_VIEW_IN_NV_GLSL_VERTEX_SHADER = UINT64_C(1) << 31;
245
246 // If the flag is enabled, gl_PointSize is clamped to the maximum point size specified in
247 // ShBuiltInResources in vertex shaders.
248 const ShCompileOptions SH_CLAMP_POINT_SIZE = UINT64_C(1) << 32;
249
250 // Bit 33 is available.
251
252 // Don't use loops to initialize uninitialized variables. Only has an effect if some kind of
253 // variable initialization is turned on.
254 const ShCompileOptions SH_DONT_USE_LOOPS_TO_INITIALIZE_VARIABLES = UINT64_C(1) << 34;
255
256 // Don't use D3D constant register zero when allocating space for uniforms. This is targeted to work
257 // around a bug in NVIDIA D3D driver version 388.59 where in very specific cases the driver would
258 // not handle constant register zero correctly. Only has an effect on HLSL translation.
259 const ShCompileOptions SH_SKIP_D3D_CONSTANT_REGISTER_ZERO = UINT64_C(1) << 35;
260
261 // Clamp gl_FragDepth to the range [0.0, 1.0] in case it is statically used.
262 const ShCompileOptions SH_CLAMP_FRAG_DEPTH = UINT64_C(1) << 36;
263
264 // Rewrite expressions like "v.x = z = expression;". Works around a bug in NVIDIA OpenGL drivers
265 // prior to version 397.31.
266 const ShCompileOptions SH_REWRITE_REPEATED_ASSIGN_TO_SWIZZLED = UINT64_C(1) << 37;
267
268 // Rewrite gl_DrawID as a uniform int
269 const ShCompileOptions SH_EMULATE_GL_DRAW_ID = UINT64_C(1) << 38;
270
271 // This flag initializes shared variables to 0.
272 // It is to avoid ompute shaders being able to read undefined values that could be coming from
273 // another webpage/application.
274 const ShCompileOptions SH_INIT_SHARED_VARIABLES = UINT64_C(1) << 39;
275
276 // Forces the value returned from an atomic operations to be always be resolved. This is targeted to
277 // workaround a bug in NVIDIA D3D driver where the return value from
278 // RWByteAddressBuffer.InterlockedAdd does not get resolved when used in the .yzw components of a
279 // RWByteAddressBuffer.Store operation. Only has an effect on HLSL translation.
280 // http://anglebug.com/3246
281 const ShCompileOptions SH_FORCE_ATOMIC_VALUE_RESOLUTION = UINT64_C(1) << 40;
282
283 // Rewrite gl_BaseVertex and gl_BaseInstance as uniform int
284 const ShCompileOptions SH_EMULATE_GL_BASE_VERTEX_BASE_INSTANCE = UINT64_C(1) << 41;
285
286 // Emulate seamful cube map sampling for OpenGL ES2.0. Currently only applies to the Vulkan
287 // backend, as is done after samplers are moved out of structs. Can likely be made to work on
288 // the other backends as well.
289 const ShCompileOptions SH_EMULATE_SEAMFUL_CUBE_MAP_SAMPLING = UINT64_C(1) << 42;
290
291 // This flag controls how to translate WEBGL_video_texture sampling function.
292 const ShCompileOptions SH_TAKE_VIDEO_TEXTURE_AS_EXTERNAL_OES = UINT64_C(1) << 43;
293
294 // This flag works around a inconsistent behavior in Mac AMD driver where gl_VertexID doesn't
295 // include base vertex value. It replaces gl_VertexID with (gl_VertexID + angle_BaseVertex)
296 // when angle_BaseVertex is available.
297 const ShCompileOptions SH_ADD_BASE_VERTEX_TO_VERTEX_ID = UINT64_C(1) << 44;
298
299 // This works around the dynamic lvalue indexing of swizzled vectors on various platforms.
300 const ShCompileOptions SH_REMOVE_DYNAMIC_INDEXING_OF_SWIZZLED_VECTOR = UINT64_C(1) << 45;
301
302 // This flag works around a slow fxc compile performance issue with dynamic uniform indexing.
303 const ShCompileOptions SH_ALLOW_TRANSLATE_UNIFORM_BLOCK_TO_STRUCTUREDBUFFER = UINT64_C(1) << 46;
304
305 // This flag indicates whether Bresenham line raster emulation code should be generated. This
306 // emulation is necessary if the backend uses a differnet algorithm to draw lines. Currently only
307 // implemented for the Vulkan backend.
308 const ShCompileOptions SH_ADD_BRESENHAM_LINE_RASTER_EMULATION = UINT64_C(1) << 47;
309
310 // This flag allows disabling ARB_texture_rectangle on a per-compile basis. This is necessary
311 // for WebGL contexts becuase ARB_texture_rectangle may be necessary for the WebGL implementation
312 // internally but shouldn't be exposed to WebGL user code.
313 const ShCompileOptions SH_DISABLE_ARB_TEXTURE_RECTANGLE = UINT64_C(1) << 48;
314
315 // This flag works around a driver bug by rewriting uses of row-major matrices
316 // as column-major in ESSL 3.00 and greater shaders.
317 const ShCompileOptions SH_REWRITE_ROW_MAJOR_MATRICES = UINT64_C(1) << 49;
318
319 // Drop any explicit precision qualifiers from shader.
320 const ShCompileOptions SH_IGNORE_PRECISION_QUALIFIERS = UINT64_C(1) << 50;
321
322 // Allow compiler to do early fragment tests as an optimization.
323 const ShCompileOptions SH_EARLY_FRAGMENT_TESTS_OPTIMIZATION = UINT64_C(1) << 51;
324
325 // Allow compiler to insert Android pre-rotation code.
326 const ShCompileOptions SH_ADD_PRE_ROTATION = UINT64_C(1) << 52;
327
328 const ShCompileOptions SH_FORCE_SHADER_PRECISION_HIGHP_TO_MEDIUMP = UINT64_C(1) << 53;
329
330 // Allow compiler to use specialization constant to do pre-rotation and y flip.
331 const ShCompileOptions SH_USE_SPECIALIZATION_CONSTANT = UINT64_C(1) << 54;
332
333 // Ask compiler to generate Vulkan transform feedback emulation support code.
334 const ShCompileOptions SH_ADD_VULKAN_XFB_EMULATION_SUPPORT_CODE = UINT64_C(1) << 55;
335
336 // Ask compiler to generate Vulkan transform feedback support code when using the
337 // VK_EXT_transform_feedback extension.
338 const ShCompileOptions SH_ADD_VULKAN_XFB_EXTENSION_SUPPORT_CODE = UINT64_C(1) << 56;
339
340 // This flag initializes fragment shader's output variables to zero at the beginning of the fragment
341 // shader's main(). It is intended as a workaround for drivers which get context lost if
342 // gl_FragColor is not written.
343 const ShCompileOptions SH_INIT_FRAGMENT_OUTPUT_VARIABLES = UINT64_C(1) << 57;
344
345 // Transitory flag to select between producing SPIR-V directly vs using glslang. Ignored in
346 // non-assert-enabled builds to avoid increasing ANGLE's binary size.
347 const ShCompileOptions SH_GENERATE_SPIRV_THROUGH_GLSLANG = UINT64_C(1) << 58;
348
349 // Insert explicit casts for float/double/unsigned/signed int on macOS 10.15 with Intel driver
350 const ShCompileOptions SH_ADD_EXPLICIT_BOOL_CASTS = UINT64_C(1) << 59;
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 EXT_shader_framebuffer_fetch;
384 int EXT_shader_framebuffer_fetch_non_coherent;
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_multisampled_render_to_texture2;
392 int EXT_YUV_target;
393 int EXT_geometry_shader;
394 int OES_geometry_shader;
395 int OES_shader_io_blocks;
396 int EXT_shader_io_blocks;
397 int EXT_gpu_shader5;
398 int EXT_shader_non_constant_global_initializers;
399 int OES_texture_storage_multisample_2d_array;
400 int OES_texture_3D;
401 int ANGLE_texture_multisample;
402 int ANGLE_multi_draw;
403 // TODO(angleproject:3402) remove after chromium side removal to pass compilation
404 int ANGLE_base_vertex_base_instance;
405 int WEBGL_video_texture;
406 int APPLE_clip_distance;
407 int OES_texture_cube_map_array;
408 int EXT_texture_cube_map_array;
409 int EXT_shadow_samplers;
410 int OES_shader_multisample_interpolation;
411 int OES_shader_image_atomic;
412 int EXT_tessellation_shader;
413 int OES_texture_buffer;
414 int EXT_texture_buffer;
415 int OES_sample_variables;
416 int EXT_clip_cull_distance;
417 int EXT_primitive_bounding_box;
418 int ANGLE_base_vertex_base_instance_shader_builtin;
419
420 // Set to 1 to enable replacing GL_EXT_draw_buffers #extension directives
421 // with GL_NV_draw_buffers in ESSL output. This flag can be used to emulate
422 // EXT_draw_buffers by using it in combination with GLES3.0 glDrawBuffers
423 // function. This applies to Tegra K1 devices.
424 int NV_draw_buffers;
425
426 // Set to 1 if highp precision is supported in the ESSL 1.00 version of the
427 // fragment language. Does not affect versions of the language where highp
428 // support is mandatory.
429 // Default is 0.
430 int FragmentPrecisionHigh;
431
432 // GLSL ES 3.0 constants.
433 int MaxVertexOutputVectors;
434 int MaxFragmentInputVectors;
435 int MinProgramTexelOffset;
436 int MaxProgramTexelOffset;
437
438 // Extension constants.
439
440 // Value of GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT for OpenGL ES output context.
441 // Value of GL_MAX_DUAL_SOURCE_DRAW_BUFFERS for OpenGL output context.
442 // GLES SL version 100 gl_MaxDualSourceDrawBuffersEXT value for EXT_blend_func_extended.
443 int MaxDualSourceDrawBuffers;
444
445 // Value of GL_MAX_VIEWS_OVR.
446 int MaxViewsOVR;
447
448 // Name Hashing.
449 // Set a 64 bit hash function to enable user-defined name hashing.
450 // Default is NULL.
451 ShHashFunction64 HashFunction;
452
453 // The maximum complexity an expression can be when SH_LIMIT_EXPRESSION_COMPLEXITY is turned on.
454 int MaxExpressionComplexity;
455
456 // The maximum depth a call stack can be.
457 int MaxCallStackDepth;
458
459 // The maximum number of parameters a function can have when SH_LIMIT_EXPRESSION_COMPLEXITY is
460 // turned on.
461 int MaxFunctionParameters;
462
463 // GLES 3.1 constants
464
465 // texture gather offset constraints.
466 int MinProgramTextureGatherOffset;
467 int MaxProgramTextureGatherOffset;
468
469 // maximum number of available image units
470 int MaxImageUnits;
471
472 // OES_sample_variables constant
473 // maximum number of available samples
474 int MaxSamples;
475
476 // maximum number of image uniforms in a vertex shader
477 int MaxVertexImageUniforms;
478
479 // maximum number of image uniforms in a fragment shader
480 int MaxFragmentImageUniforms;
481
482 // maximum number of image uniforms in a compute shader
483 int MaxComputeImageUniforms;
484
485 // maximum total number of image uniforms in a program
486 int MaxCombinedImageUniforms;
487
488 // maximum number of uniform locations
489 int MaxUniformLocations;
490
491 // maximum number of ssbos and images in a shader
492 int MaxCombinedShaderOutputResources;
493
494 // maximum number of groups in each dimension
495 std::array<int, 3> MaxComputeWorkGroupCount;
496 // maximum number of threads per work group in each dimension
497 std::array<int, 3> MaxComputeWorkGroupSize;
498
499 // maximum number of total uniform components
500 int MaxComputeUniformComponents;
501
502 // maximum number of texture image units in a compute shader
503 int MaxComputeTextureImageUnits;
504
505 // maximum number of atomic counters in a compute shader
506 int MaxComputeAtomicCounters;
507
508 // maximum number of atomic counter buffers in a compute shader
509 int MaxComputeAtomicCounterBuffers;
510
511 // maximum number of atomic counters in a vertex shader
512 int MaxVertexAtomicCounters;
513
514 // maximum number of atomic counters in a fragment shader
515 int MaxFragmentAtomicCounters;
516
517 // maximum number of atomic counters in a program
518 int MaxCombinedAtomicCounters;
519
520 // maximum binding for an atomic counter
521 int MaxAtomicCounterBindings;
522
523 // maximum number of atomic counter buffers in a vertex shader
524 int MaxVertexAtomicCounterBuffers;
525
526 // maximum number of atomic counter buffers in a fragment shader
527 int MaxFragmentAtomicCounterBuffers;
528
529 // maximum number of atomic counter buffers in a program
530 int MaxCombinedAtomicCounterBuffers;
531
532 // maximum number of buffer object storage in machine units
533 int MaxAtomicCounterBufferSize;
534
535 // maximum number of uniform block bindings
536 int MaxUniformBufferBindings;
537
538 // maximum number of shader storage buffer bindings
539 int MaxShaderStorageBufferBindings;
540
541 // maximum point size (higher limit from ALIASED_POINT_SIZE_RANGE)
542 float MaxPointSize;
543
544 // EXT_geometry_shader constants
545 int MaxGeometryUniformComponents;
546 int MaxGeometryUniformBlocks;
547 int MaxGeometryInputComponents;
548 int MaxGeometryOutputComponents;
549 int MaxGeometryOutputVertices;
550 int MaxGeometryTotalOutputComponents;
551 int MaxGeometryTextureImageUnits;
552 int MaxGeometryAtomicCounterBuffers;
553 int MaxGeometryAtomicCounters;
554 int MaxGeometryShaderStorageBlocks;
555 int MaxGeometryShaderInvocations;
556 int MaxGeometryImageUniforms;
557
558 // EXT_tessellation_shader constants
559 int MaxTessControlInputComponents;
560 int MaxTessControlOutputComponents;
561 int MaxTessControlTextureImageUnits;
562 int MaxTessControlUniformComponents;
563 int MaxTessControlTotalOutputComponents;
564 int MaxTessControlImageUniforms;
565 int MaxTessControlAtomicCounters;
566 int MaxTessControlAtomicCounterBuffers;
567
568 int MaxTessPatchComponents;
569 int MaxPatchVertices;
570 int MaxTessGenLevel;
571
572 int MaxTessEvaluationInputComponents;
573 int MaxTessEvaluationOutputComponents;
574 int MaxTessEvaluationTextureImageUnits;
575 int MaxTessEvaluationUniformComponents;
576 int MaxTessEvaluationImageUniforms;
577 int MaxTessEvaluationAtomicCounters;
578 int MaxTessEvaluationAtomicCounterBuffers;
579
580 // Subpixel bits used in rasterization.
581 int SubPixelBits;
582
583 // APPLE_clip_distance/EXT_clip_cull_distance constant
584 int MaxClipDistances;
585 int MaxCullDistances;
586 int MaxCombinedClipAndCullDistances;
587
588 // Direct-to-metal backend constants:
589
590 // Binding index for driver uniforms:
591 int DriverUniformsBindingIndex;
592 // Binding index for default uniforms:
593 int DefaultUniformsBindingIndex;
594 // Binding index for UBO's argument buffer
595 int UBOArgumentBufferBindingIndex;
596 };
597
598 //
599 // ShHandle held by but opaque to the driver. It is allocated,
600 // managed, and de-allocated by the compiler. Its contents
601 // are defined by and used by the compiler.
602 //
603 // If handle creation fails, 0 will be returned.
604 //
605 using ShHandle = void *;
606
607 namespace sh
608 {
609 using BinaryBlob = std::vector<uint32_t>;
610
611 //
612 // Driver must call this first, once, before doing any other compiler operations.
613 // If the function succeeds, the return value is true, else false.
614 //
615 bool Initialize();
616 //
617 // Driver should call this at shutdown.
618 // If the function succeeds, the return value is true, else false.
619 //
620 bool Finalize();
621
622 //
623 // Initialize built-in resources with minimum expected values.
624 // Parameters:
625 // resources: The object to initialize. Will be comparable with memcmp.
626 //
627 void InitBuiltInResources(ShBuiltInResources *resources);
628
629 //
630 // Returns the a concatenated list of the items in ShBuiltInResources as a null-terminated string.
631 // This function must be updated whenever ShBuiltInResources is changed.
632 // Parameters:
633 // handle: Specifies the handle of the compiler to be used.
634 const std::string &GetBuiltInResourcesString(const ShHandle handle);
635
636 //
637 // Driver calls these to create and destroy compiler objects.
638 //
639 // Returns the handle of constructed compiler, null if the requested compiler is not supported.
640 // Parameters:
641 // type: Specifies the type of shader - GL_FRAGMENT_SHADER or GL_VERTEX_SHADER.
642 // spec: Specifies the language spec the compiler must conform to - SH_GLES2_SPEC or SH_WEBGL_SPEC.
643 // output: Specifies the output code type - for example SH_ESSL_OUTPUT, SH_GLSL_OUTPUT,
644 // SH_HLSL_3_0_OUTPUT or SH_HLSL_4_1_OUTPUT. Note: Each output type may only
645 // be supported in some configurations.
646 // resources: Specifies the built-in resources.
647 ShHandle ConstructCompiler(sh::GLenum type,
648 ShShaderSpec spec,
649 ShShaderOutput output,
650 const ShBuiltInResources *resources);
651 void Destruct(ShHandle handle);
652
653 //
654 // Compiles the given shader source.
655 // If the function succeeds, the return value is true, else false.
656 // Parameters:
657 // handle: Specifies the handle of compiler to be used.
658 // shaderStrings: Specifies an array of pointers to null-terminated strings containing the shader
659 // source code.
660 // numStrings: Specifies the number of elements in shaderStrings array.
661 // compileOptions: A mask of compile options defined above.
662 bool Compile(const ShHandle handle,
663 const char *const shaderStrings[],
664 size_t numStrings,
665 ShCompileOptions compileOptions);
666
667 // Clears the results from the previous compilation.
668 void ClearResults(const ShHandle handle);
669
670 // Return the version of the shader language.
671 int GetShaderVersion(const ShHandle handle);
672
673 // Return the currently set language output type.
674 ShShaderOutput GetShaderOutputType(const ShHandle handle);
675
676 // Returns null-terminated information log for a compiled shader.
677 // Parameters:
678 // handle: Specifies the compiler
679 const std::string &GetInfoLog(const ShHandle handle);
680
681 // Returns null-terminated object code for a compiled shader. Only valid for output types that
682 // generate human-readable code (GLSL, ESSL or HLSL).
683 // Parameters:
684 // handle: Specifies the compiler
685 const std::string &GetObjectCode(const ShHandle handle);
686
687 // Returns object binary blob for a compiled shader. Only valid for output types that
688 // generate binary blob (SPIR-V).
689 // Parameters:
690 // handle: Specifies the compiler
691 const BinaryBlob &GetObjectBinaryBlob(const ShHandle handle);
692
693 // Returns a (original_name, hash) map containing all the user defined names in the shader,
694 // including variable names, function names, struct names, and struct field names.
695 // Parameters:
696 // handle: Specifies the compiler
697 const std::map<std::string, std::string> *GetNameHashingMap(const ShHandle handle);
698
699 // Shader variable inspection.
700 // Returns a pointer to a list of variables of the designated type.
701 // (See ShaderVars.h for type definitions, included above)
702 // Returns NULL on failure.
703 // Parameters:
704 // handle: Specifies the compiler
705 const std::vector<sh::ShaderVariable> *GetUniforms(const ShHandle handle);
706 const std::vector<sh::ShaderVariable> *GetVaryings(const ShHandle handle);
707 const std::vector<sh::ShaderVariable> *GetInputVaryings(const ShHandle handle);
708 const std::vector<sh::ShaderVariable> *GetOutputVaryings(const ShHandle handle);
709 const std::vector<sh::ShaderVariable> *GetAttributes(const ShHandle handle);
710 const std::vector<sh::ShaderVariable> *GetOutputVariables(const ShHandle handle);
711 const std::vector<sh::InterfaceBlock> *GetInterfaceBlocks(const ShHandle handle);
712 const std::vector<sh::InterfaceBlock> *GetUniformBlocks(const ShHandle handle);
713 const std::vector<sh::InterfaceBlock> *GetShaderStorageBlocks(const ShHandle handle);
714 sh::WorkGroupSize GetComputeShaderLocalGroupSize(const ShHandle handle);
715 // Returns the number of views specified through the num_views layout qualifier. If num_views is
716 // not set, the function returns -1.
717 int GetVertexShaderNumViews(const ShHandle handle);
718 // Returns true if compiler has injected instructions for early fragment tests as an optimization
719 bool HasEarlyFragmentTestsOptimization(const ShHandle handle);
720
721 // Returns specialization constant usage bits
722 uint32_t GetShaderSpecConstUsageBits(const ShHandle handle);
723
724 // Returns true if the passed in variables pack in maxVectors followingthe packing rules from the
725 // GLSL 1.017 spec, Appendix A, section 7.
726 // Returns false otherwise. Also look at the SH_ENFORCE_PACKING_RESTRICTIONS
727 // flag above.
728 // Parameters:
729 // maxVectors: the available rows of registers.
730 // variables: an array of variables.
731 bool CheckVariablesWithinPackingLimits(int maxVectors,
732 const std::vector<sh::ShaderVariable> &variables);
733
734 // Gives the compiler-assigned register for a shader storage block.
735 // The method writes the value to the output variable "indexOut".
736 // Returns true if it found a valid shader storage block, false otherwise.
737 // Parameters:
738 // handle: Specifies the compiler
739 // shaderStorageBlockName: Specifies the shader storage block
740 // indexOut: output variable that stores the assigned register
741 bool GetShaderStorageBlockRegister(const ShHandle handle,
742 const std::string &shaderStorageBlockName,
743 unsigned int *indexOut);
744
745 // Gives the compiler-assigned register for a uniform block.
746 // The method writes the value to the output variable "indexOut".
747 // Returns true if it found a valid uniform block, false otherwise.
748 // Parameters:
749 // handle: Specifies the compiler
750 // uniformBlockName: Specifies the uniform block
751 // indexOut: output variable that stores the assigned register
752 bool GetUniformBlockRegister(const ShHandle handle,
753 const std::string &uniformBlockName,
754 unsigned int *indexOut);
755
756 bool ShouldUniformBlockUseStructuredBuffer(const ShHandle handle,
757 const std::string &uniformBlockName);
758 const std::set<std::string> *GetSlowCompilingUniformBlockSet(const ShHandle handle);
759
760 // Gives a map from uniform names to compiler-assigned registers in the default uniform block.
761 // Note that the map contains also registers of samplers that have been extracted from structs.
762 const std::map<std::string, unsigned int> *GetUniformRegisterMap(const ShHandle handle);
763
764 // Sampler, image and atomic counters share registers(t type and u type),
765 // GetReadonlyImage2DRegisterIndex and GetImage2DRegisterIndex return the first index into
766 // a range of reserved registers for image2D/iimage2D/uimage2D variables.
767 // Parameters: handle: Specifies the compiler
768 unsigned int GetReadonlyImage2DRegisterIndex(const ShHandle handle);
769 unsigned int GetImage2DRegisterIndex(const ShHandle handle);
770
771 // The method records these used function names related with image2D/iimage2D/uimage2D, these
772 // functions will be dynamically generated.
773 // Parameters:
774 // handle: Specifies the compiler
775 const std::set<std::string> *GetUsedImage2DFunctionNames(const ShHandle handle);
776
777 bool HasValidGeometryShaderInputPrimitiveType(const ShHandle handle);
778 bool HasValidGeometryShaderOutputPrimitiveType(const ShHandle handle);
779 bool HasValidGeometryShaderMaxVertices(const ShHandle handle);
780 bool HasValidTessGenMode(const ShHandle handle);
781 bool HasValidTessGenSpacing(const ShHandle handle);
782 bool HasValidTessGenVertexOrder(const ShHandle handle);
783 bool HasValidTessGenPointMode(const ShHandle handle);
784 GLenum GetGeometryShaderInputPrimitiveType(const ShHandle handle);
785 GLenum GetGeometryShaderOutputPrimitiveType(const ShHandle handle);
786 int GetGeometryShaderInvocations(const ShHandle handle);
787 int GetGeometryShaderMaxVertices(const ShHandle handle);
788 unsigned int GetShaderSharedMemorySize(const ShHandle handle);
789 int GetTessControlShaderVertices(const ShHandle handle);
790 GLenum GetTessGenMode(const ShHandle handle);
791 GLenum GetTessGenSpacing(const ShHandle handle);
792 GLenum GetTessGenVertexOrder(const ShHandle handle);
793 GLenum GetTessGenPointMode(const ShHandle handle);
794
795 //
796 // Helper function to identify specs that are based on the WebGL spec.
797 //
IsWebGLBasedSpec(ShShaderSpec spec)798 inline bool IsWebGLBasedSpec(ShShaderSpec spec)
799 {
800 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
801 }
802
803 //
804 // Helper function to identify DesktopGL specs
805 //
IsDesktopGLSpec(ShShaderSpec spec)806 inline bool IsDesktopGLSpec(ShShaderSpec spec)
807 {
808 return spec == SH_GL_CORE_SPEC || spec == SH_GL_COMPATIBILITY_SPEC;
809 }
810
811 // Can't prefix with just _ because then we might introduce a double underscore, which is not safe
812 // in GLSL (ESSL 3.00.6 section 3.8: All identifiers containing a double underscore are reserved for
813 // use by the underlying implementation). u is short for user-defined.
814 extern const char kUserDefinedNamePrefix[];
815
816 namespace vk
817 {
818
819 // Specialization constant ids
820 enum class SpecializationConstantId : uint32_t
821 {
822 LineRasterEmulation = 0,
823 SurfaceRotation = 1,
824 DrawableWidth = 2,
825 DrawableHeight = 3,
826
827 InvalidEnum = 4,
828 EnumCount = InvalidEnum,
829 };
830
831 enum class SurfaceRotation : uint32_t
832 {
833 Identity,
834 Rotated90Degrees,
835 Rotated180Degrees,
836 Rotated270Degrees,
837 FlippedIdentity,
838 FlippedRotated90Degrees,
839 FlippedRotated180Degrees,
840 FlippedRotated270Degrees,
841
842 InvalidEnum,
843 EnumCount = InvalidEnum,
844 };
845
846 enum class SpecConstUsage : uint32_t
847 {
848 LineRasterEmulation = 0,
849 YFlip = 1,
850 Rotation = 2,
851 DrawableSize = 3,
852
853 InvalidEnum = 4,
854 EnumCount = InvalidEnum,
855 };
856
857 // Interface block name containing the aggregate default uniforms
858 extern const char kDefaultUniformsNameVS[];
859 extern const char kDefaultUniformsNameTCS[];
860 extern const char kDefaultUniformsNameTES[];
861 extern const char kDefaultUniformsNameGS[];
862 extern const char kDefaultUniformsNameFS[];
863 extern const char kDefaultUniformsNameCS[];
864
865 // Interface block and variable names containing driver uniforms
866 extern const char kDriverUniformsBlockName[];
867 extern const char kDriverUniformsVarName[];
868
869 // Interface block array name used for atomic counter emulation
870 extern const char kAtomicCountersBlockName[];
871
872 // Line raster emulation varying
873 extern const char kLineRasterEmulationPosition[];
874
875 // Transform feedback emulation support
876 extern const char kXfbEmulationGetOffsetsFunctionName[];
877 extern const char kXfbEmulationCaptureFunctionName[];
878 extern const char kXfbEmulationBufferBlockName[];
879 extern const char kXfbEmulationBufferName[];
880 extern const char kXfbEmulationBufferFieldName[];
881
882 // Transform feedback extension support
883 extern const char kXfbExtensionPositionOutName[];
884
885 // EXT_shader_framebuffer_fetch and EXT_shader_framebuffer_fetch_non_coherent
886 extern const char kInputAttachmentName[];
887
888 } // namespace vk
889
890 namespace mtl
891 {
892 // Specialization constant to enable GL_SAMPLE_COVERAGE_VALUE emulation.
893 extern const char kCoverageMaskEnabledConstName[];
894
895 // Specialization constant to emulate rasterizer discard.
896 extern const char kRasterizerDiscardEnabledConstName[];
897 } // namespace mtl
898
899 // For backends that use glslang (the Vulkan shader compiler), i.e. Vulkan and Metal, call these to
900 // initialize and finalize glslang itself. This can be called independently from Initialize() and
901 // Finalize().
902 void InitializeGlslang();
903 void FinalizeGlslang();
904
905 } // namespace sh
906
907 #endif // GLSLANG_SHADERLANG_H_
908