Giter Site home page Giter Site logo

khronosgroup / glslang Goto Github PK

View Code? Open in Web Editor NEW
2.8K 116.0 803.0 72.53 MB

Khronos-reference front end for GLSL/ESSL, partial front end for HLSL, and a SPIR-V generator.

License: Other

CMake 0.63% Shell 0.68% C++ 75.75% GLSL 16.65% JavaScript 2.23% C 1.33% Yacc 2.32% Python 0.25% HLSL 0.03% Makefile 0.12%
glsl hlsl compiler spir-v glslang glslangvalidator shader essl validator

glslang's Introduction

Continuous Integration Continuous Deployment OpenSSF Scorecard

News

  1. OGLCompiler and HLSL stub libraries have been fully removed from the build.

  2. OVERRIDE_MSVCCRT has been removed in favor of CMAKE_MSVC_RUNTIME_LIBRARY

Users are encouraged to utilize the standard approach via CMAKE_MSVC_RUNTIME_LIBRARY.

Glslang Components and Status

There are several components:

Reference Validator and GLSL/ESSL -> AST Front End

An OpenGL GLSL and OpenGL|ES GLSL (ESSL) front-end for reference validation and translation of GLSL/ESSL into an internal abstract syntax tree (AST).

Status: Virtually complete, with results carrying similar weight as the specifications.

HLSL -> AST Front End

An HLSL front-end for translation of an approximation of HLSL to glslang's AST form.

Status: Partially complete. Semantics are not reference quality and input is not validated. This is in contrast to the DXC project, which receives a much larger investment and attempts to have definitive/reference-level semantics.

See issue 362 and issue 701 for current status.

AST -> SPIR-V Back End

Translates glslang's AST to the Khronos-specified SPIR-V intermediate language.

Status: Virtually complete.

Reflector

An API for getting reflection information from the AST, reflection types/variables/etc. from the HLL source (not the SPIR-V).

Status: There is a large amount of functionality present, but no specification/goal to measure completeness against. It is accurate for the input HLL and AST, but only approximate for what would later be emitted for SPIR-V.

Standalone Wrapper

glslang is command-line tool for accessing the functionality above.

Status: Complete.

Tasks waiting to be done are documented as GitHub issues.

Other References

Also see the Khronos landing page for glslang as a reference front end:

https://www.khronos.org/opengles/sdk/tools/Reference-Compiler/

The above page, while not kept up to date, includes additional information regarding glslang as a reference validator.

How to Use Glslang

Execution of Standalone Wrapper

To use the standalone binary form, execute glslang, and it will print a usage statement. Basic operation is to give it a file containing a shader, and it will print out warnings/errors and optionally an AST.

The applied stage-specific rules are based on the file extension:

  • .vert for a vertex shader
  • .tesc for a tessellation control shader
  • .tese for a tessellation evaluation shader
  • .geom for a geometry shader
  • .frag for a fragment shader
  • .comp for a compute shader

For ray tracing pipeline shaders:

  • .rgen for a ray generation shader
  • .rint for a ray intersection shader
  • .rahit for a ray any-hit shader
  • .rchit for a ray closest-hit shader
  • .rmiss for a ray miss shader
  • .rcall for a callable shader

There is also a non-shader extension:

  • .conf for a configuration file of limits, see usage statement for example

Building (CMake)

Instead of building manually, you can also download the binaries for your platform directly from the main-tot release on GitHub. Those binaries are automatically uploaded by the buildbots after successful testing and they always reflect the current top of the tree of the main branch.

Dependencies

  • A C++17 compiler. (For MSVS: use 2019 or later.)
  • CMake: for generating compilation targets.
  • make: Linux, ninja is an alternative, if configured.
  • Python 3.x: for executing SPIRV-Tools scripts. (Optional if not using SPIRV-Tools and the 'External' subdirectory does not exist.)
  • bison: optional, but needed when changing the grammar (glslang.y).
  • googletest: optional, but should use if making any changes to glslang.

Build steps

The following steps assume a Bash shell. On Windows, that could be the Git Bash shell or some other shell of your choosing.

1) Check-Out this project

cd <parent of where you want glslang to be>
git clone https://github.com/KhronosGroup/glslang.git

2) Check-Out External Projects

./update_glslang_sources.py

3) Configure

Assume the source directory is $SOURCE_DIR and the build directory is $BUILD_DIR. First ensure the build directory exists, then navigate to it:

mkdir -p $BUILD_DIR
cd $BUILD_DIR

For building on Linux:

cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$(pwd)/install" $SOURCE_DIR
# "Release" (for CMAKE_BUILD_TYPE) could also be "Debug" or "RelWithDebInfo"

For building on Android:

cmake $SOURCE_DIR -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX="$(pwd)/install" -DANDROID_ABI=arm64-v8a -DCMAKE_BUILD_TYPE=Release -DANDROID_STL=c++_static -DANDROID_PLATFORM=android-24 -DCMAKE_SYSTEM_NAME=Android -DANDROID_TOOLCHAIN=clang -DANDROID_ARM_MODE=arm -DCMAKE_MAKE_PROGRAM=$ANDROID_NDK_HOME/prebuilt/linux-x86_64/bin/make -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake
# If on Windows will be -DCMAKE_MAKE_PROGRAM=%ANDROID_NDK_HOME%\prebuilt\windows-x86_64\bin\make.exe
# -G is needed for building on Windows
# -DANDROID_ABI can also be armeabi-v7a for 32 bit

For building on Windows:

cmake $SOURCE_DIR -DCMAKE_INSTALL_PREFIX="$(pwd)/install"
# The CMAKE_INSTALL_PREFIX part is for testing (explained later).

The CMake GUI also works for Windows (version 3.4.1 tested).

Also, consider using git config --global core.fileMode false (or with --local) on Windows to prevent the addition of execution permission on files.

4) Build and Install

# for Linux:
make -j4 install

# for Windows:
cmake --build . --config Release --target install
# "Release" (for --config) could also be "Debug", "MinSizeRel", or "RelWithDebInfo"

If using MSVC, after running CMake to configure, use the Configuration Manager to check the INSTALL project.

If you want to enable testing via CMake set GLSLANG_TESTS=ON when configuring the build.

GLSLANG_TESTS is off by default to streamline the packaging / Vulkan SDK process.

Building (GN)

glslang can also be built with the GN build system.

1) Install depot_tools

Download depot_tools.zip, extract to a directory, and add this directory to your PATH.

2) Synchronize dependencies and generate build files

This only needs to be done once after updating glslang.

With the current directory set to your glslang checkout, type:

./update_glslang_sources.py
gclient sync --gclientfile=standalone.gclient
gn gen out/Default

3) Build

With the current directory set to your glslang checkout, type:

cd out/Default
ninja

If you need to change the GLSL grammar

The grammar in glslang/MachineIndependent/glslang.y has to be recompiled with bison if it changes, the output files are committed to the repo to avoid every developer needing to have bison configured to compile the project when grammar changes are quite infrequent. For windows you can get binaries from GnuWin32.

The command to rebuild is:

bison --defines=MachineIndependent/glslang_tab.cpp.h
      -t MachineIndependent/glslang.y
      -o MachineIndependent/glslang_tab.cpp

The above command is also available in the bash script in updateGrammar, when executed from the glslang subdirectory of the glslang repository.

Building to WASM for the Web and Node

Building a standalone JS/WASM library for the Web and Node

Use the steps in Build Steps, with the following notes/exceptions:

  • emsdk needs to be present in your executable search path, PATH for Bash-like environments:
  • Wrap cmake call: emcmake cmake
  • Set -DENABLE_OPT=OFF.
  • Set -DENABLE_HLSL=OFF if HLSL is not needed.
  • For a standalone JS/WASM library, turn on -DENABLE_GLSLANG_JS=ON.
  • To get a fully minimized build, make sure to use brotli to compress the .js and .wasm files
  • Note that by default, Emscripten allocates a very small stack size, which may cause stack overflows when compiling large shaders. Use the STACK_SIZE compiler setting to increase the stack size.

Example:

emcmake cmake -DCMAKE_BUILD_TYPE=Release -DENABLE_GLSLANG_JS=ON \
    -DENABLE_HLSL=OFF -DENABLE_OPT=OFF ..

Building glslang - Using vcpkg

You can download and install glslang using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install glslang

The glslang port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Testing

Right now, there are two test harnesses existing in glslang: one is Google Test, one is the runtests script. The former runs unit tests and single-shader single-threaded integration tests, while the latter runs multiple-shader linking tests and multi-threaded tests.

Tests may erroneously fail or pass if using ALLOW_EXTERNAL_SPIRV_TOOLS with any commit other than the one specified in known_good.json.

Running tests

The runtests script requires compiled binaries to be installed into $BUILD_DIR/install. Please make sure you have supplied the correct configuration to CMake (using -DCMAKE_INSTALL_PREFIX) when building; otherwise, you may want to modify the path in the runtests script.

Running Google Test-backed tests:

cd $BUILD_DIR

# for Linux:
ctest

# for Windows:
ctest -C {Debug|Release|RelWithDebInfo|MinSizeRel}

# or, run the test binary directly
# (which gives more fine-grained control like filtering):
<dir-to-glslangtests-in-build-dir>/glslangtests

Running runtests script-backed tests:

cd $SOURCE_DIR/Test && ./runtests

If some tests fail with validation errors, there may be a mismatch between the version of spirv-val on the system and the version of glslang. In this case, it is necessary to run update_glslang_sources.py. See "Check-Out External Projects" above for more details.

Contributing tests

Test results should always be included with a pull request that modifies functionality.

If you are writing unit tests, please use the Google Test framework and place the tests under the gtests/ directory.

Integration tests are placed in the Test/ directory. It contains test input and a subdirectory baseResults/ that contains the expected results of the tests. Both the tests and baseResults/ are under source-code control.

Google Test runs those integration tests by reading the test input, compiling them, and then compare against the expected results in baseResults/. The integration tests to run via Google Test is registered in various gtests/*.FromFile.cpp source files. glslangtests provides a command-line option --update-mode, which, if supplied, will overwrite the golden files under the baseResults/ directory with real output from that invocation. For more information, please check gtests/ directory's README.

For the runtests script, it will generate current results in the localResults/ directory and diff them against the baseResults/. When you want to update the tracked test results, they need to be copied from localResults/ to baseResults/. This can be done by the bump shell script.

You can add your own private list of tests, not tracked publicly, by using localtestlist to list non-tracked tests. This is automatically read by runtests and included in the diff and bump process.

Programmatic Interfaces

Another piece of software can programmatically translate shaders to an AST using one of two different interfaces:

  • A new C++ class-oriented interface, or
  • The original C functional interface

The main() in StandAlone/StandAlone.cpp shows examples using both styles.

C++ Class Interface (new, preferred)

This interface is in roughly the last 1/3 of ShaderLang.h. It is in the glslang namespace and contains the following, here with suggested calls for generating SPIR-V:

const char* GetEsslVersionString();
const char* GetGlslVersionString();
bool InitializeProcess();
void FinalizeProcess();

class TShader
    setStrings(...);
    setEnvInput(EShSourceHlsl or EShSourceGlsl, stage,  EShClientVulkan or EShClientOpenGL, 100);
    setEnvClient(EShClientVulkan or EShClientOpenGL, EShTargetVulkan_1_0 or EShTargetVulkan_1_1 or EShTargetOpenGL_450);
    setEnvTarget(EShTargetSpv, EShTargetSpv_1_0 or EShTargetSpv_1_3);
    bool parse(...);
    const char* getInfoLog();

class TProgram
    void addShader(...);
    bool link(...);
    const char* getInfoLog();
    Reflection queries

For just validating (not generating code), substitute these calls:

    setEnvInput(EShSourceHlsl or EShSourceGlsl, stage,  EShClientNone, 0);
    setEnvClient(EShClientNone, 0);
    setEnvTarget(EShTargetNone, 0);

See ShaderLang.h and the usage of it in StandAlone/StandAlone.cpp for more details. There is a block comment giving more detail above the calls for setEnvInput, setEnvClient, and setEnvTarget.

C Functional Interface (original)

This interface is in roughly the first 2/3 of ShaderLang.h, and referred to as the Sh*() interface, as all the entry points start Sh.

The Sh*() interface takes a "compiler" call-back object, which it calls after building call back that is passed the AST and can then execute a back end on it.

The following is a simplified resulting run-time call stack:

ShCompile(shader, compiler) -> compiler(AST) -> <back end>

In practice, ShCompile() takes shader strings, default version, and warning/error and other options for controlling compilation.

C Functional Interface (new)

This interface is located glslang_c_interface.h and exposes functionality similar to the C++ interface. The following snippet is a complete example showing how to compile GLSL into SPIR-V 1.5 for Vulkan 1.2.

#include <glslang/Include/glslang_c_interface.h>

// Required for use of glslang_default_resource
#include <glslang/Public/resource_limits_c.h>

typedef struct SpirVBinary {
    uint32_t *words; // SPIR-V words
    int size; // number of words in SPIR-V binary
} SpirVBinary;

SpirVBinary compileShaderToSPIRV_Vulkan(glslang_stage_t stage, const char* shaderSource, const char* fileName) {
    const glslang_input_t input = {
        .language = GLSLANG_SOURCE_GLSL,
        .stage = stage,
        .client = GLSLANG_CLIENT_VULKAN,
        .client_version = GLSLANG_TARGET_VULKAN_1_2,
        .target_language = GLSLANG_TARGET_SPV,
        .target_language_version = GLSLANG_TARGET_SPV_1_5,
        .code = shaderSource,
        .default_version = 100,
        .default_profile = GLSLANG_NO_PROFILE,
        .force_default_version_and_profile = false,
        .forward_compatible = false,
        .messages = GLSLANG_MSG_DEFAULT_BIT,
        .resource = glslang_default_resource(),
    };

    glslang_shader_t* shader = glslang_shader_create(&input);

    SpirVBinary bin = {
        .words = NULL,
        .size = 0,
    };
    if (!glslang_shader_preprocess(shader, &input))	{
        printf("GLSL preprocessing failed %s\n", fileName);
        printf("%s\n", glslang_shader_get_info_log(shader));
        printf("%s\n", glslang_shader_get_info_debug_log(shader));
        printf("%s\n", input.code);
        glslang_shader_delete(shader);
        return bin;
    }

    if (!glslang_shader_parse(shader, &input)) {
        printf("GLSL parsing failed %s\n", fileName);
        printf("%s\n", glslang_shader_get_info_log(shader));
        printf("%s\n", glslang_shader_get_info_debug_log(shader));
        printf("%s\n", glslang_shader_get_preprocessed_code(shader));
        glslang_shader_delete(shader);
        return bin;
    }

    glslang_program_t* program = glslang_program_create();
    glslang_program_add_shader(program, shader);

    if (!glslang_program_link(program, GLSLANG_MSG_SPV_RULES_BIT | GLSLANG_MSG_VULKAN_RULES_BIT)) {
        printf("GLSL linking failed %s\n", fileName);
        printf("%s\n", glslang_program_get_info_log(program));
        printf("%s\n", glslang_program_get_info_debug_log(program));
        glslang_program_delete(program);
        glslang_shader_delete(shader);
        return bin;
    }

    glslang_program_SPIRV_generate(program, stage);

    bin.size = glslang_program_SPIRV_get_size(program);
    bin.words = malloc(bin.size * sizeof(uint32_t));
    glslang_program_SPIRV_get(program, bin.words);

    const char* spirv_messages = glslang_program_SPIRV_get_messages(program);
    if (spirv_messages)
        printf("(%s) %s\b", fileName, spirv_messages);

    glslang_program_delete(program);
    glslang_shader_delete(shader);

    return bin;
}

Basic Internal Operation

  • Initial lexical analysis is done by the preprocessor in MachineIndependent/Preprocessor, and then refined by a GLSL scanner in MachineIndependent/Scan.cpp. There is currently no use of flex.

  • Code is parsed using bison on MachineIndependent/glslang.y with the aid of a symbol table and an AST. The symbol table is not passed on to the back-end; the intermediate representation stands on its own. The tree is built by the grammar productions, many of which are offloaded into ParseHelper.cpp, and by Intermediate.cpp.

  • The intermediate representation is very high-level, and represented as an in-memory tree. This serves to lose no information from the original program, and to have efficient transfer of the result from parsing to the back-end. In the AST, constants are propagated and folded, and a very small amount of dead code is eliminated.

    To aid linking and reflection, the last top-level branch in the AST lists all global symbols.

  • The primary algorithm of the back-end compiler is to traverse the tree (high-level intermediate representation), and create an internal object code representation. There is an example of how to do this in MachineIndependent/intermOut.cpp.

  • Reduction of the tree to a linear byte-code style low-level intermediate representation is likely a good way to generate fully optimized code.

  • There is currently some dead old-style linker-type code still lying around.

  • Memory pool: parsing uses types derived from C++ std types, using a custom allocator that puts them in a memory pool. This makes allocation of individual container/contents just few cycles and deallocation free. This pool is popped after the AST is made and processed.

    The use is simple: if you are going to call new, there are three cases:

    • the object comes from the pool (its base class has the macro POOL_ALLOCATOR_NEW_DELETE in it) and you do not have to call delete

    • it is a TString, in which case call NewPoolTString(), which gets it from the pool, and there is no corresponding delete

    • the object does not come from the pool, and you have to do normal C++ memory management of what you new

  • Features can be protected by version/extension/stage/profile: See the comment in glslang/MachineIndependent/Versions.cpp.

glslang's People

Contributors

alan-baker avatar alelenv avatar amdrexu avatar antiagainst avatar arcady-lunarg avatar baldurk avatar ben-clayton avatar chaocnv avatar corporateshark avatar dankbaker avatar dependabot[bot] avatar dgkoch avatar dj2 avatar dneto0 avatar greg-lunarg avatar jeffbolznv avatar jeremy-lunarg avatar johnkslang avatar juan-lunarg avatar mbechard avatar ncesario-lunarg avatar neslimsah avatar pmistrynv avatar qining avatar ruoyuamd avatar shabbyx avatar shchchowamd avatar sparmarnv avatar zhiqianxia avatar zoddicus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

glslang's Issues

Missing functionality: struct comparison

When trying to compile a shader which contains struct comparison the following error is reported: Missing functionality: Composite comparison of non-vectors.

Test case:

#version 140
in highp vec4 a_position;

struct S { int a; int b; };

void main (void)
{
    S a, b;
    if(a==b) {}

    gl_Postion = a_position;
}

Compiled with the glslangValidator test.vert -V command.

Root CMakeLists forces visual studio compiler to 2012/v110

I noticed while changing the CMakeLists.txt files for the osinclude pull request that there is this line in the root CMakeLists.txt:

    set(CMAKE_GENERATOR_TOOLSET "v110" CACHE STRING "Platform Toolset" FORCE)

I'm not sure why this toolset is important (is it a minimum, since C++11 features are used that don't work in v100? or is using a higher toolset undesirable?), but it means a bit of fiddling locally if you don't have 2012 installed.

Perhaps there is a way to check in CMake if that toolset exists before forcing it?

[spirv] opphi generation

Is there a way to make glslang generate some basic spirv using intermediate
object ids which would be used in an opphi instruction (which can use only intermediate object id).
It seems the variable/opstore/opload work around is always used.

[SPIRV] gl_PerVertex struct for gl_in does not mark members as builtin in eval shaders

Seems like a bug since it's inconsistent with geometry shader behavior for example.

#version 450

layout(fractional_even_spacing, quads, ccw, point_mode) in;
patch in vec4 vFoo;

void main()
{
    gl_Position = vec4(gl_in[0].gl_Position.xy + vFoo.xy + gl_TessCoord.xy, 0.0, 1.0);
}

                          Source GLSL 450
                          Capability Tessellation
           1:             ExtInstImport  "GLSL.std.450"
                          MemoryModel Logical GLSL450
                          EntryPoint TessellationEvaluation 4  "main"
                          ExecutionMode 4 InputQuads
                          Name 4  "main"
                          Name 11  "gl_PerVertex"
                          MemberName 11(gl_PerVertex) 0  "gl_Position"
                          MemberName 11(gl_PerVertex) 1  "gl_PointSize"
                          MemberName 11(gl_PerVertex) 2  "gl_ClipDistance"
                          MemberName 11(gl_PerVertex) 3  "gl_CullDistance"
                          Name 13  ""
                          Name 16  "gl_PerVertex"
                          MemberName 16(gl_PerVertex) 0  "gl_Position"
                          MemberName 16(gl_PerVertex) 1  "gl_PointSize"
                          MemberName 16(gl_PerVertex) 2  "gl_ClipDistance"
                          MemberName 16(gl_PerVertex) 3  "gl_CullDistance"
                          Name 20  "gl_in"
                          Name 26  "vFoo"
                          Name 32  "gl_TessCoord"
                          MemberDecorate 11(gl_PerVertex) 0 BuiltIn Position
                          MemberDecorate 11(gl_PerVertex) 1 BuiltIn PointSize
                          MemberDecorate 11(gl_PerVertex) 2 BuiltIn ClipDistance
                          MemberDecorate 11(gl_PerVertex) 3 BuiltIn CullDistance
                          Decorate 11(gl_PerVertex) Block *Associated with gl_out, marked builtin*
                          Decorate 16(gl_PerVertex) Block *The input is not*

clang static analyzer: potential memory leaks and unitialized values

When running the code through the clang static analyzer (for instance in Xcode -> Product -> Analyzer), there's a small number of warnings (mostly uncritical like 'Values stored to X is never read'), but there are a couple of more critical warning in glslangValidator/StandAlone.cpp where memory is not freed, and a function is potentially called with an unitialized value (very likely a false positive because the code should return, but easy to fix).

Here's a list of the critical warnings (everything that is not a 'is never read' warning):

Potential leak of memory pointed to by 'config' in StandAlone.cpp/ProcessConfigFile():

If there's no config file given, a default 'config' is used which is allocated here: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L239, the static analyzer thinks that is is never freed.

Apart from that warning, there are several allocations happening in ReadFileData(), which don't seem to have a corresponding free() call (for instance here: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L965.

Also in FreeFileData() it looks like only the 'node pointers' are freed, not the array that contains the pointers allocated here: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L953

Potential leak of memory pointed to by 'program':

The object created here: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L619

...is not deleted when this if is taken: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L627

Potential leak of memory pointed to by 'return_data':

The memory allocated here: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L953

Is not freed when this 'if' is taken: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L956

Function call argument is an unitialized value:

This is very likely a false positive, but easy to fix: clang analyzer says that the 'FILE* in' here: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L948

...can remain unitialized if the call to fopen_s returns with an error when fgetc() is called here: https://github.com/KhronosGroup/glslang/blob/master/StandAlone/StandAlone.cpp#L960

This is the list of 'Value stored in X is never read', some of these may point to actual bugs, not sure:

Value stored to 'ch' is never read:

https://github.com/KhronosGroup/glslang/blob/master/glslang/MachineIndependent/preprocessor/PpContext.h#L411

Value stored to 'fragOutHasLocation' is never read:

https://github.com/KhronosGroup/glslang/blob/master/glslang/MachineIndependent/linkValidate.cpp#L557

Value stored to 'token' is never read:

https://github.com/KhronosGroup/glslang/blob/master/glslang/MachineIndependent/preprocessor/Pp.cpp#L831

Value stored to 'isVersion' is never read:

https://github.com/KhronosGroup/glslang/blob/master/glslang/MachineIndependent/preprocessor/Pp.cpp#L867

Value stored to 'exp' is never read:

https://github.com/KhronosGroup/glslang/blob/master/glslang/MachineIndependent/preprocessor/PpScanner.cpp#L182

Value stored to 'word' is never read:

https://github.com/KhronosGroup/glslang/blob/master/SPIRV/SPVRemapper.cpp#L457
https://github.com/KhronosGroup/glslang/blob/master/SPIRV/SPVRemapper.cpp#L469

Value stored to 'nextInst' during its initialization is never read:

https://github.com/KhronosGroup/glslang/blob/master/SPIRV/SPVRemapper.cpp#L469

And that is all :) I can provide a pull request for most of these if you want (the only part that's a bit more complex is the allocation/free stuff around ReadFileData / FreeFileData).

C-style #include and #line directive support in glslang

We plan to implement the #include and #line directive support via GLSL extensions, so the default glslang behaviour remains as today. We believe it will benefit the community to put the extension implementation into glslang.

Specifically, we plan to introduce two extensions: GL_GOOGLE_cpp_style_line_directive and GL_GOOGLE_include_directive. The first one allows #line to accept a constant string (for a filename) as its second parameter and substitute __FILE__ accordingly. The second one enables #include support.

There will be a couple of commits for this issue, falling into the following three categories:

  1. preliminary work to make the preprocessor handle line numbers correctly
  2. add support for GL_GOOGLE_cpp_style_line_direcitve
  3. add support for GL_GOOGLE_include_directive

Catching link errors?

Hello.

Given m.vert:

#version 330 core

vec4 f();

void
main()
{
  gl_Position = f();
}

... and m.frag:

#version 330 core

layout(location = 0) out vec4 out_rgba;

void
main()
{
  out_rgba = vec4(1.0);
}

Validating with glslangValidator -l m.vert m.frag gives:

m.vert
m.frag

Linked vertex stage:


Linked fragment stage:


No error is indicated, despite the definition for f not having been given anywhere. Is there a way to get the validator to catch errors of this type? In C-like languages, that would obviously become a link-time error.

Migrate `Todo.txt` to individual issues

Currently a bit messy in my opinion and can be unclear to those not familiar (what does +/- mean? missing features, bugs?). Would be easier to keep up to date and see who's working on what.

Generating functions improperly

I am working on a Spir-V Decompiler and am looking at some binaries produced by glslang. It incorrectly generates opcode 54 (OpFunction) with only a 4 byte word count, followed by multiple other OpFunction opcodes. This is incorrect, because it should be immediately followed by 55, OpFunctionParameter, for each argument, and then followed by a 56 for OpFuncitonEnd. There is no generated OpFunctionParameter or OpFuncitonEnd in the created binary. Both source and binary are attached. Compiled using version 2.2.687

Poll: Minimum required MSVC version?

What should be the minimum version of MSVC required for glslang?

I'd been setting the bar at 2012 to be conservative across a broad base, but many submissions require 2013, which I then fix to work on 2012. (2012 supports a broad set of C++11, but not all those supported by 2013.)

Any input on a required minimum version?

[SPIR-V] texelFetch not yet implemented

This seems like a pretty glaring omission. I took a look at the code and it doesn't look like this should take much time for someone who knows what they're doing with it. However, my knowledge of the glslang code-base is slim at best and I wasn't seeing exactly how it should be added.

SPV "missing functionality" calls exit(1) or will crash

The MissingFunctionality() function in SPIRV/SpvBuilder.cpp here calls exit(1) unconditionally. This is a problem if glslang is used as a library and not as part of the standalone validator, because then there's no hope of recovering or continuing execution if the application can handle SPIR-V failing to compile.

There's also at least one case - I'd guess more - where if this exit() call is removed then the code will crash later on. I ran into this in GlslangToSpv.cpp around line 808:

    case glslang::EOpFunctionCall:
    {
        if (node->isUserDefined())
            result = handleUserFunctionCall(node);
        else
            result = handleBuiltInFunctionCall(node);

        if (! result) {
            spv::MissingFunctionality("glslang function call");
            glslang::TConstUnionArray emptyConsts;
            int nextConst = 0;
            result = createSpvConstant(node->getType(), emptyConsts, nextConst);
        }
        builder.clearAccessChain();
        builder.setAccessChainRValue(result);

        return false;
    }

Where setAccessChainRValue ends up accessign a NULL pointer when it calls getTypeId().

In standard C++ preprocessors, 'defined' is an invalid macro name.

The GLSL specification (this text appears to be the same in all versions of the specification) says this:

#define and #undef functionality are defined as is standard for C++ preprocessors for macro definitions
both with and without macro parameters.

So it follows that using defined as a macro name should throw an error, as is standard for C and C++ preprocessors, defined is not a valid macro name.
For example, clang gives:

test.c:1:9: error: 'defined' cannot be used as a macro name
#define defined definer
        ^

and GCC gives almost identically:

test.c:1:9: error: "defined" cannot be used as a macro name
 #define defined definer
         ^

Change "glslangValidator" -> "glslang"

glslangValidator is becoming a SPIR-V front end, as well as a validator. Khronos decided it should be name just "glslang". So this change in the built executable name will likely occur at some point.

Are there any concerns about doing this?

[spirv] loop merge and 1 pass transform

A loop merge block (loop header) would need some special setup before any of its spirv instructions is parsed.
Meaning you would have, in the label instruction processing of this block, to parse ahead to look up for a loop merge instruction and then know if you have to emit the loop setup machine instructions.
Then, the 'one pass transform' would not be "per spirv instruction" but "per spirv block". Am I wrong? Do I miss something?

Use Github releases

Git is very fast and efficient for tracking line-oriented text files, however it is fairly weak at working with binaries. The common case is that git will rewrite the entire binary file, and both will need to be downloaded with the repository, making Git clones(and some other operations) slower than they need to be. It will get far slower over time if binaries are updated in the repository more and more times.

Github has a mechanism for releasing binaries. It's pretty convenient and makes it simple for people to pick up older releases if the need may arise. It also allows you to do pre-releases, which people are not encouraged to use in a production setting, but can try out nonetheless.

Another benefit of this, is that in the future the build process can be automated and releases can be updated every time you push a release tag.

Doesn't properly handle write-masked SSBO stores when converting to SPIR-V

Consider the following shader:

layout(location = 0) in vec2 data;
layout(set = 0, binding = 0, std140) buffer Storage {
   vec4 arr[];
} ssbo;

void main()
{
   if (gl_VertexID % 2 == 0) {
      ssbo.arr[gl_VertexID / 2].xz = data;
   } else {
      ssbo.arr[gl_VertexID / 2].yw = data;
   }
}

The two SSBO stores should only alter the components of the SSBO specified by the swizzle. I can invoke this shader as a SIMD8 shader on a Broadwell in such a way that one SIMD8 shader invocation will take vertices with an even gl_VertexID and another will take the odd ones. This means that one EU (execution unit) will only execute the first case and the other will only execute the second case. GLSLang converts this shader to the following SPIR-V:

                              Source GLSL 430
                              SourceExtension  "GL_GOOGLE_cpp_style_line_directive"
                              SourceExtension  "GL_GOOGLE_include_directive"
                              Capability Shader
               1:             ExtInstImport  "GLSL.std.450"
                              MemoryModel Logical GLSL450
                              EntryPoint Vertex 4  "main"
                              Name 4  "main"
                              Name 8  "gl_VertexID"
                              Name 20  "Storage"
                              MemberName 20(Storage) 0  "arr"
                              Name 22  "ssbo"
                              Name 27  "data"
                              Name 40  "gl_InstanceID"
                              Decorate 8(gl_VertexID) BuiltIn VertexId
                              Decorate 19 ArrayStride 16
                              MemberDecorate 20(Storage) 0 Offset 0
                              Decorate 20(Storage) BufferBlock
                              Decorate 22(ssbo) DescriptorSet 0
                              Decorate 22(ssbo) Binding 0
                              Decorate 27(data) Location 0
                              Decorate 40(gl_InstanceID) BuiltIn InstanceId
               2:             TypeVoid
               3:             TypeFunction 2
               6:             TypeInt 32 1
               7:             TypePointer Input 6(int)
  8(gl_VertexID):      7(ptr) Variable Input
              10:      6(int) Constant 2
              12:      6(int) Constant 0
              13:             TypeBool
              17:             TypeFloat 32
              18:             TypeVector 17(float) 4
              19:             TypeRuntimeArray 18(fvec4)
     20(Storage):             TypeStruct 19
              21:             TypePointer Uniform 20(Storage)
        22(ssbo):     21(ptr) Variable Uniform
              25:             TypeVector 17(float) 2
              26:             TypePointer Input 25(fvec2)
        27(data):     26(ptr) Variable Input
              29:             TypePointer Uniform 18(fvec4)
40(gl_InstanceID):      7(ptr) Variable Input
         4(main):           2 Function None 3
               5:             Label
               9:      6(int) Load 8(gl_VertexID)
              11:      6(int) SMod 9 10
              14:    13(bool) IEqual 11 12
                              SelectionMerge 16 None
                              BranchConditional 14 15 33
              15:               Label
              23:      6(int)   Load 8(gl_VertexID)
              24:      6(int)   SDiv 23 10
              28:   25(fvec2)   Load 27(data)
              30:     29(ptr)   AccessChain 22(ssbo) 12 24
              31:   18(fvec4)   Load 30
              32:   18(fvec4)   VectorShuffle 31 28 4 1 5 3
                                Store 30 32
                                Branch 16
              33:               Label
              34:      6(int)   Load 8(gl_VertexID)
              35:      6(int)   SDiv 34 10
              36:   25(fvec2)   Load 27(data)
              37:     29(ptr)   AccessChain 22(ssbo) 12 35
              38:   18(fvec4)   Load 37
              39:   18(fvec4)   VectorShuffle 38 36 0 4 2 5
                                Store 37 39
                                Branch 16
              16:             Label
                              Return
                              FunctionEnd

As you can see, in both cases, it does a load, a vector-shuffle, and a store. This creates a race condition where both EU's could, in theory, do the load at the same time, execute the vector-shuffle, and then both store all 4 components. Whoever gets to the store first wins the race and the other thread's data gets stompped.

We found a similar bug in the GLSL compiler in upstream mesa recently which was causing it to fail compute shader conformance tests.

Move to enum-based texturing calls, instead of text based.

Would like to move to enum-based operators for texturing and image operations.

Currently, almost all built-in functions are mapped to the TOperator enum, and can be dealt with numerically. However, this is not true for texturing and imaging operations. It would be better to do all this consistently and eliminate text-based comparisons.

As consumers of glslang would break and need to adapt to this, this is a place to gather input. (As is the Khronos public bug 1346.)

See

const bool PureOperatorBuiltins = false;  // could break backward compatibility; pending feedback

in Initialize.cpp, where this is currently set up, but turned off.

Need to exit after first ERROR

#endif
#endif
#endif
#endif
#endif
#endif
#endif

#if
#else

and a number of similar inputs exercise a segmentation fault bug in glslang::TPpContext::tStringInput::scan.

[SPIR-V] Remove shadowed "param" variables when possible

For purposes of readability and potentially performance, it would be nice to avoid the shadowed "params" variable where appropriate.

Typical code-gen when passing simple in arguments to functions get first copyed to a separate variable (via OpStore).

#version 310 es

vec4 foo(float v)
{
    return vec4(v);
}

void main()
{
    float v = 10.0;
    gl_Position = foo(v);
}

Compiles into

         4(main):           2 Function None 3
               5:             Label
           16(v):      7(ptr) Variable Function
       23(param):      7(ptr) Variable Function
                              Store 16(v) 17
              24:    6(float) Load 16(v)
                              Store 23(param) 24
              25:    8(fvec4) FunctionCall 11(foo(f1;) 23(param)
              27:     26(ptr) AccessChain 20 22
                              Store 27 25
                              Return
                              FunctionEnd

There is no need for this param variable, and it only adds clutter when disassembling and reading the SPIR-V.

For out/inout arguments, param shadowing makes more sense though due to GLSL's weird semantics with out/inout arguments.

SPIRV: Token layout of OpAtomicXXX instructions is incorrect

According to latest SPIRV spec, the first source operand "Pointer" should be a pointer variable. Because OpAtomicXXX will be applied to shader image atomic operations, this pointer could be a pointer to a variable or be an image texel pointer.

GLSL:

version 450

buffer Buffer
{
uint u1;
} buf;

void main()
{
atomicAdd(buf.u1, 1);
}

Faulted SPIRV:
16: 7(int) Constant 1
...
14: 13(ptr) AccessChain 10(buf) 12
15: 7(int) Load 14
17: 7(int) AtomicIAdd 15 Device None 16

Correct SPIRV
15: 7(int) Constant 1
...
14: 13(ptr) AccessChain 10(buf) 12
16: 7(int) AtomicIAdd 14 Device None 15

The load operation is unnecessary.

spirv return block

Return statements in loops inside a void-returning function generates a branch instruction which targets
the function terminating return block.
It means there is a branch from inside a nested flow control
to an outside return block. There is no other other way than performing a full 2 pass transform in order to know if a branch targets a return block.
Additionnaly, if a return block in not in the nested flow control, we cannot use statically allocated hardware resource.
Do I miss something?

[SPIR-V] GLES 3.1 bitfield*() ops unimplemented

bitfieldInsert/Extract/Reverse et. al. are currently unimplemented in SPIR-V output.

#version 310 es

layout(location = 0) out int FragColor;
flat in int v0;
flat in int v1;

void main()
{
    FragColor = bitfieldInsert(v0, v1, 10, 5);
}
test.frag
Warning, version 310 is not yet complete; most version-specific features are present, but some are missing.


Linked fragment stage:


Missing functionality: integer aggregate

Reason for glslang/MachineIndependent/unistd.h?

Can anybody shed any light on why there's an empty unistd.h in glslang/MachineIndependent/ ? From a quick grep, I don't see that actually get used anywhere in glslang.

This is causing problems when being built into a test app in an environment where we can't use the CMake build system. This empty file is then getting picked up due to include path sharing, breaking other code which needs a real unistd.h.

Thanks,
//Mark

[SPIRV] spacing parameters and winding layouts are ignored for tess eval shaders

#version 450

layout(fractional_even_spacing, quads, ccw, point_mode) in;
patch in vec4 vFoo;

void main()
{
    gl_Position = vec4(vFoo.xy + gl_TessCoord.xy, 0.0, 1.0);
}

                          Source GLSL 450
                          Capability Tessellation
           1:             ExtInstImport  "GLSL.std.450"
                          MemoryModel Logical GLSL450
                          EntryPoint TessellationEvaluation 4  "main"
                          ExecutionMode 4 InputQuads *Only InputQuads is added*
                          Name 4  "main"
                          Name 11  "gl_PerVertex"
                          MemberName 11(gl_PerVertex) 0  "gl_Position"
                          MemberName 11(gl_PerVertex) 1  "gl_PointSize"
                          MemberName 11(gl_PerVertex) 2  "gl_ClipDistance"
                          MemberName 11(gl_PerVertex) 3  "gl_CullDistance"
                          Name 13  ""
                          Name 17  "vFoo"
                          Name 23  "gl_TessCoord"
                          ...

Versioning

revision.h is intended for auto-updated versioning on each change, but this is not working under GitHub; a mechanism needs to be put in place for it.

Use sized types in SPIR-V generation

The SPIR-V generator currently uses unsigned int for all its internal representation. However there is no guarantee for this type to be 32 bits (one SPIR-V word) wide.

There are two solutions to this:

  • Change the official Khronos headers to generate uint32_t for the Id typedef and underlying types for enums.
  • Change the glslang code to only use uint32_t internally.

I would prefer the first option (together with other improvements to the C++ headers) but that requires changing the Khronos code generator and I have no idea whether that is public and if so where to find it/contribute to it (the Khronos bugtracker only has a section for the specification, not the interface files).

In any case, the glslang code as it is right now may produce faulty SPIR-V binaries or fail to load valid SPIR-V binaries if the condition sizeof(unsigned int) * CHAR_BIT == 32 does not hold on the host platform. As a plus, if the platform does not have an exact 32 bit wide integer the code would fail to compile as the exactly sized typedefs are optional.

There may be similar issues with float and double if they don't follow the IEEE 754 standard or have unexpected sizes.

[SPIR-V] short circuiting of logical operators

The GLSL and ESSL specifications say the following about the order of evaluation of the logical operators in 5.9 Expressions

The logical binary operators and (&&), or (||), and exclusive or (^^) operate only on two
Boolean expressions and result in a Boolean expression. And (&&) will only evaluate the right
hand operand if the left hand operand evaluated to true. Or (||) will only evaluate the right hand
operand if the left hand operand evaluated to false. Exclusive or (^^) will always evaluate both
operands.

This behavior doesn't seem to be translated to SPIR-V. The code always evaluates both sides and combines them with OpLogicalXX. Wouldn't the correct behavior be a conditional branch to evaluate the second operand depending on the first?

[SPIRV] Invalid SSA and missing OpPhi?

version 450

layout(location = 0) in vec4 in_position;

void main()
{
float y;

    if(in_position[0]>50.0)
            y=1.0;
    else
            y=2.0;

    gl_Position[0] = y;

}

It seems to generate invalid SSA because it is assigning 2 times a variable, probably because it misses a phi SSA function.
Or do I miss something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.