2 // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
3 // Copyright (C) 2013-2016 LunarG, Inc.
4 // Copyright (C) 2016-2020 Google, Inc.
5 // Modifications Copyright(C) 2021 Advanced Micro Devices, Inc.All rights reserved.
7 // All rights reserved.
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions
13 // Redistributions of source code must retain the above copyright
14 // notice, this list of conditions and the following disclaimer.
16 // Redistributions in binary form must reproduce the above
17 // copyright notice, this list of conditions and the following
18 // disclaimer in the documentation and/or other materials provided
19 // with the distribution.
21 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22 // contributors may be used to endorse or promote products derived
23 // from this software without specific prior written permission.
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 // POSSIBILITY OF SUCH DAMAGE.
39 // this only applies to the standalone wrapper, not the front end in general
40 #ifndef _CRT_SECURE_NO_WARNINGS
41 #define _CRT_SECURE_NO_WARNINGS
44 #include "ResourceLimits.h"
46 #include "DirStackFileIncluder.h"
47 #include "./../glslang/Include/ShHandle.h"
48 #include "./../glslang/Public/ShaderLang.h"
49 #include "../SPIRV/GlslangToSpv.h"
50 #include "../SPIRV/GLSL.std.450.h"
51 #include "../SPIRV/doc.h"
52 #include "../SPIRV/disassemble.h"
64 #include "../glslang/OSDependent/osinclude.h"
66 // Build-time generated includes
67 #include "glslang/build_info.h"
69 #include "glslang/glsl_intrinsic_header.h"
72 GLSLANG_EXPORT void ShOutputHtml();
75 // Command-line options
78 EOptionIntermediate = (1 << 0),
79 EOptionSuppressInfolog = (1 << 1),
80 EOptionMemoryLeakMode = (1 << 2),
81 EOptionRelaxedErrors = (1 << 3),
82 EOptionGiveWarnings = (1 << 4),
83 EOptionLinkProgram = (1 << 5),
84 EOptionMultiThreaded = (1 << 6),
85 EOptionDumpConfig = (1 << 7),
86 EOptionDumpReflection = (1 << 8),
87 EOptionSuppressWarnings = (1 << 9),
88 EOptionDumpVersions = (1 << 10),
89 EOptionSpv = (1 << 11),
90 EOptionHumanReadableSpv = (1 << 12),
91 EOptionVulkanRules = (1 << 13),
92 EOptionDefaultDesktop = (1 << 14),
93 EOptionOutputPreprocessed = (1 << 15),
94 EOptionOutputHexadecimal = (1 << 16),
95 EOptionReadHlsl = (1 << 17),
96 EOptionCascadingErrors = (1 << 18),
97 EOptionAutoMapBindings = (1 << 19),
98 EOptionFlattenUniformArrays = (1 << 20),
99 EOptionNoStorageFormat = (1 << 21),
100 EOptionKeepUncalled = (1 << 22),
101 EOptionHlslOffsets = (1 << 23),
102 EOptionHlslIoMapping = (1 << 24),
103 EOptionAutoMapLocations = (1 << 25),
104 EOptionDebug = (1 << 26),
105 EOptionStdin = (1 << 27),
106 EOptionOptimizeDisable = (1 << 28),
107 EOptionOptimizeSize = (1 << 29),
108 EOptionInvertY = (1 << 30),
109 EOptionDumpBareVersion = (1 << 31),
111 bool targetHlslFunctionality1 = false;
112 bool SpvToolsDisassembler = false;
113 bool SpvToolsValidate = false;
114 bool NaNClamp = false;
115 bool stripDebugInfo = false;
116 bool beQuiet = false;
117 bool VulkanRulesRelaxed = false;
118 bool autoSampledTextures = false;
121 // Return codes from main/exit().
134 // Forward declarations.
136 EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
137 void CompileFile(const char* fileName, ShHandle);
139 char* ReadFileData(const char* fileName);
140 void FreeFileData(char* data);
141 void InfoLogMsg(const char* msg, const char* name, const int num);
143 // Globally track if any compile or link failure.
144 bool CompileFailed = false;
145 bool LinkFailed = false;
147 // array of unique places to leave the shader names and infologs for the asynchronous compiles
148 std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
150 TBuiltInResource Resources;
151 std::string ConfigFile;
154 // Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
156 void ProcessConfigFile()
158 if (ConfigFile.size() == 0)
159 Resources = glslang::DefaultTBuiltInResource;
162 char* configString = ReadFileData(ConfigFile.c_str());
163 glslang::DecodeResourceLimits(&Resources, configString);
164 FreeFileData(configString);
169 int ReflectOptions = EShReflectionDefault;
171 const char* ExecutableName = nullptr;
172 const char* binaryFileName = nullptr;
173 const char* depencyFileName = nullptr;
174 const char* entryPointName = nullptr;
175 const char* sourceEntryPointName = nullptr;
176 const char* shaderStageName = nullptr;
177 const char* variableName = nullptr;
178 bool HlslEnable16BitTypes = false;
179 bool HlslDX9compatible = false;
180 bool HlslDxPositionW = false;
181 bool EnhancedMsgs = false;
182 bool DumpBuiltinSymbols = false;
183 std::vector<std::string> IncludeDirectoryList;
185 // Source environment
186 // (source 'Client' is currently the same as target 'Client')
187 int ClientInputSemanticsVersion = 100;
189 // Target environment
190 glslang::EShClient Client = glslang::EShClientNone; // will stay EShClientNone if only validating
191 glslang::EShTargetClientVersion ClientVersion; // not valid until Client is set
192 glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
193 glslang::EShTargetLanguageVersion TargetVersion; // not valid until TargetLanguage is set
196 int GlslVersion = 0; // GLSL version specified on CLI, overrides #version in shader source
198 std::vector<std::string> Processes; // what should be recorded by OpModuleProcessed, or equivalent
200 // Per descriptor-set binding base data
201 typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
203 std::vector<std::pair<std::string, int>> uniformLocationOverrides;
206 std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
207 std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
208 std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
210 std::vector<std::pair<std::string, glslang::TBlockStorageClass>> blockStorageOverrides;
212 bool setGlobalUniformBlock = false;
213 std::string globalUniformName;
214 unsigned int globalUniformBinding;
215 unsigned int globalUniformSet;
217 bool setGlobalBufferBlock = false;
218 std::string atomicCounterBlockName;
219 unsigned int atomicCounterBlockSet;
221 // Add things like "#define ..." to a preamble to use in the beginning of the shader.
226 bool isSet() const { return text.size() > 0; }
227 const char* get() const { return text.c_str(); }
230 void addDef(std::string def)
232 text.append("#define ");
235 Processes.push_back("define-macro ");
236 Processes.back().append(def);
238 // The first "=" needs to turn into a space
239 const size_t equal = def.find_first_of("=");
240 if (equal != def.npos)
248 void addUndef(std::string undef)
250 text.append("#undef ");
253 Processes.push_back("undef-macro ");
254 Processes.back().append(undef);
261 void fixLine(std::string& line)
263 // Can't go past a newline in the line
264 const size_t end = line.find_first_of("\n");
265 if (end != line.npos)
266 line = line.substr(0, end);
269 std::string text; // contents of preamble
272 // Track the user's #define and #undef from the command line.
273 TPreamble UserPreamble;
274 std::string PreambleString;
277 // Create the default name for saving a binary if -o is not provided.
279 const char* GetBinaryName(EShLanguage stage)
282 if (binaryFileName == nullptr) {
284 case EShLangVertex: name = "vert.spv"; break;
285 case EShLangTessControl: name = "tesc.spv"; break;
286 case EShLangTessEvaluation: name = "tese.spv"; break;
287 case EShLangGeometry: name = "geom.spv"; break;
288 case EShLangFragment: name = "frag.spv"; break;
289 case EShLangCompute: name = "comp.spv"; break;
290 case EShLangRayGen: name = "rgen.spv"; break;
291 case EShLangIntersect: name = "rint.spv"; break;
292 case EShLangAnyHit: name = "rahit.spv"; break;
293 case EShLangClosestHit: name = "rchit.spv"; break;
294 case EShLangMiss: name = "rmiss.spv"; break;
295 case EShLangCallable: name = "rcall.spv"; break;
296 case EShLangMeshNV: name = "mesh.spv"; break;
297 case EShLangTaskNV: name = "task.spv"; break;
298 default: name = "unknown"; break;
301 name = binaryFileName;
307 // *.conf => this is a config file that can set limits/resources
309 bool SetConfigFile(const std::string& name)
314 if (name.compare(name.size() - 5, 5, ".conf") == 0) {
323 // Give error and exit with failure code.
325 void Error(const char* message, const char* detail = nullptr)
327 fprintf(stderr, "%s: Error: ", ExecutableName);
328 if (detail != nullptr)
329 fprintf(stderr, "%s: ", detail);
330 fprintf(stderr, "%s (use -h for usage)\n", message);
335 // Process an optional binding base of one the forms:
336 // --argname [stage] base // base for stage (if given) or all stages (if not)
337 // --argname [stage] [base set]... // set/base pairs: set the base for given binding set.
339 // Where stage is one of the forms accepted by FindLanguage, and base is an integer
341 void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
346 EShLanguage lang = EShLangCount;
348 TPerSetBaseBinding perSetBase;
351 // Parse stage, if given
352 if (!isdigit(argv[arg][0])) {
353 if (argc < 3) // this form needs one more argument
356 lang = FindLanguage(argv[arg++], false);
359 if ((argc - arg) >= 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
360 // Parse a per-set binding base
362 const int baseNum = atoi(argv[arg++]);
363 const int setNum = atoi(argv[arg++]);
364 perSetBase[setNum] = baseNum;
365 } while ((argc - arg) >= 2 && isdigit(argv[arg + 0][0]) && isdigit(argv[arg + 1][0]));
367 // Parse single binding base
368 singleBase = atoi(argv[arg++]);
374 // Set one or all languages
375 const int langMin = (lang < EShLangCount) ? lang+0 : 0;
376 const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
378 for (int lang = langMin; lang < langMax; ++lang) {
379 if (!perSetBase.empty())
380 baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
382 baseBinding[res][lang] = singleBase;
386 void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
391 if (!isdigit(argv[1][0])) {
392 if (argc < 3) // this form needs one more argument
395 // Parse form: --argname stage [regname set base...], or:
396 // --argname stage set
397 const EShLanguage lang = FindLanguage(argv[1], false);
402 while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
403 base[lang].push_back(argv[1]);
409 // Must have one arg, or a multiple of three (for [regname set binding] triples)
410 if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
414 // Parse form: --argname set
415 for (int lang=0; lang<EShLangCount; ++lang)
416 base[lang].push_back(argv[1]);
424 // Process an optional binding base of one the forms:
425 // --argname name {uniform|buffer|push_constant}
426 void ProcessBlockStorage(int& argc, char**& argv, std::vector<std::pair<std::string, glslang::TBlockStorageClass>>& storage)
431 glslang::TBlockStorageClass blockStorage = glslang::EbsNone;
433 std::string strBacking(argv[2]);
434 if (strBacking == "uniform")
435 blockStorage = glslang::EbsUniform;
436 else if (strBacking == "buffer")
437 blockStorage = glslang::EbsStorageBuffer;
438 else if (strBacking == "push_constant")
439 blockStorage = glslang::EbsPushConstant;
441 printf("%s: invalid block storage\n", strBacking.c_str());
445 storage.push_back(std::make_pair(std::string(argv[1]), blockStorage));
451 inline bool isNonDigit(char c) {
452 // a non-digit character valid in a glsl identifier
453 return (c == '_') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
456 // whether string isa valid identifier to be used in glsl
457 bool isValidIdentifier(const char* str) {
458 std::string idn(str);
460 if (idn.length() == 0) {
464 if (idn.length() >= 3 && idn.substr(0, 3) == "gl_") {
465 // identifiers startin with "gl_" are reserved
469 if (!isNonDigit(idn[0])) {
473 for (unsigned int i = 1; i < idn.length(); ++i) {
474 if (!(isdigit(idn[i]) || isNonDigit(idn[i]))) {
482 // Process settings for either the global buffer block or global unfirom block
484 // --argname name set binding
485 void ProcessGlobalBlockSettings(int& argc, char**& argv, std::string* name, unsigned int* set, unsigned int* binding)
490 unsigned int curArg = 1;
492 assert(name || set || binding);
495 if (!isValidIdentifier(argv[curArg])) {
496 printf("%s: invalid identifier\n", argv[curArg]);
499 *name = argv[curArg];
506 int setVal = ::strtol(argv[curArg], NULL, 10);
507 if (errno || setVal < 0) {
508 printf("%s: invalid set\n", argv[curArg]);
518 int bindingVal = ::strtol(argv[curArg], NULL, 10);
519 if (errno || bindingVal < 0) {
520 printf("%s: invalid binding\n", argv[curArg]);
523 *binding = bindingVal;
528 argc -= (curArg - 1);
529 argv += (curArg - 1);
533 // Do all command-line argument parsing. This includes building up the work-items
534 // to be processed later, and saving all the command-line options.
536 // Does not return (it exits) if command-line is fatally flawed.
538 void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
540 for (int res = 0; res < glslang::EResCount; ++res)
541 baseBinding[res].fill(0);
543 ExecutableName = argv[0];
544 workItems.reserve(argc);
546 const auto bumpArg = [&]() {
553 // read a string directly attached to a single-letter option
554 const auto getStringOperand = [&](const char* desc) {
555 if (argv[0][2] == 0) {
556 printf("%s must immediately follow option (no spaces)\n", desc);
562 // read a number attached to a single-letter option
563 const auto getAttachedNumber = [&](const char* desc) {
564 int num = atoi(argv[0] + 2);
566 printf("%s: expected attached non-0 number\n", desc);
572 // minimum needed (without overriding something else) to target Vulkan SPIR-V
573 const auto setVulkanSpv = []() {
574 if (Client == glslang::EShClientNone)
575 ClientVersion = glslang::EShTargetVulkan_1_0;
576 Client = glslang::EShClientVulkan;
577 Options |= EOptionSpv;
578 Options |= EOptionVulkanRules;
579 Options |= EOptionLinkProgram;
582 // minimum needed (without overriding something else) to target OpenGL SPIR-V
583 const auto setOpenGlSpv = []() {
584 if (Client == glslang::EShClientNone)
585 ClientVersion = glslang::EShTargetOpenGL_450;
586 Client = glslang::EShClientOpenGL;
587 Options |= EOptionSpv;
588 Options |= EOptionLinkProgram;
589 // undo a -H default to Vulkan
590 Options &= ~EOptionVulkanRules;
593 const auto getUniformOverride = [getStringOperand]() {
594 const char *arg = getStringOperand("-u<name>:<location>");
595 const char *split = strchr(arg, ':');
597 printf("%s: missing location\n", arg);
601 int location = ::strtol(split + 1, NULL, 10);
603 printf("%s: invalid location\n", arg);
606 return std::make_pair(std::string(arg, split - arg), location);
609 for (bumpArg(); argc >= 1; bumpArg()) {
610 if (argv[0][0] == '-') {
611 switch (argv[0][1]) {
614 std::string lowerword(argv[0]+2);
615 std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
617 // handle --word style options
618 if (lowerword == "auto-map-bindings" || // synonyms
619 lowerword == "auto-map-binding" ||
620 lowerword == "amb") {
621 Options |= EOptionAutoMapBindings;
622 } else if (lowerword == "auto-map-locations" || // synonyms
623 lowerword == "aml") {
624 Options |= EOptionAutoMapLocations;
625 } else if (lowerword == "uniform-base") {
627 Error("no <base> provided", lowerword.c_str());
628 uniformBase = ::strtol(argv[1], NULL, 10);
631 } else if (lowerword == "client") {
633 if (strcmp(argv[1], "vulkan100") == 0)
635 else if (strcmp(argv[1], "opengl100") == 0)
638 Error("expects vulkan100 or opengl100", lowerword.c_str());
640 Error("expects vulkan100 or opengl100", lowerword.c_str());
642 } else if (lowerword == "define-macro" ||
645 UserPreamble.addDef(argv[1]);
647 Error("expects <name[=def]>", argv[0]);
649 } else if (lowerword == "dump-builtin-symbols") {
650 DumpBuiltinSymbols = true;
651 } else if (lowerword == "entry-point") {
652 entryPointName = argv[1];
654 Error("no <name> provided", lowerword.c_str());
656 } else if (lowerword == "flatten-uniform-arrays" || // synonyms
657 lowerword == "flatten-uniform-array" ||
658 lowerword == "fua") {
659 Options |= EOptionFlattenUniformArrays;
660 } else if (lowerword == "glsl-version") {
662 if (strcmp(argv[1], "100") == 0) {
664 } else if (strcmp(argv[1], "110") == 0) {
666 } else if (strcmp(argv[1], "120") == 0) {
668 } else if (strcmp(argv[1], "130") == 0) {
670 } else if (strcmp(argv[1], "140") == 0) {
672 } else if (strcmp(argv[1], "150") == 0) {
674 } else if (strcmp(argv[1], "300es") == 0) {
676 } else if (strcmp(argv[1], "310es") == 0) {
678 } else if (strcmp(argv[1], "320es") == 0) {
680 } else if (strcmp(argv[1], "330") == 0) {
682 } else if (strcmp(argv[1], "400") == 0) {
684 } else if (strcmp(argv[1], "410") == 0) {
686 } else if (strcmp(argv[1], "420") == 0) {
688 } else if (strcmp(argv[1], "430") == 0) {
690 } else if (strcmp(argv[1], "440") == 0) {
692 } else if (strcmp(argv[1], "450") == 0) {
694 } else if (strcmp(argv[1], "460") == 0) {
697 Error("--glsl-version expected one of: 100, 110, 120, 130, 140, 150,\n"
698 "300es, 310es, 320es, 330\n"
699 "400, 410, 420, 430, 440, 450, 460");
702 } else if (lowerword == "hlsl-offsets") {
703 Options |= EOptionHlslOffsets;
704 } else if (lowerword == "hlsl-iomap" ||
705 lowerword == "hlsl-iomapper" ||
706 lowerword == "hlsl-iomapping") {
707 Options |= EOptionHlslIoMapping;
708 } else if (lowerword == "hlsl-enable-16bit-types") {
709 HlslEnable16BitTypes = true;
710 } else if (lowerword == "hlsl-dx9-compatible") {
711 HlslDX9compatible = true;
712 } else if (lowerword == "hlsl-dx-position-w") {
713 HlslDxPositionW = true;
714 } else if (lowerword == "enhanced-msgs") {
716 } else if (lowerword == "auto-sampled-textures") {
717 autoSampledTextures = true;
718 } else if (lowerword == "invert-y" || // synonyms
720 Options |= EOptionInvertY;
721 } else if (lowerword == "keep-uncalled" || // synonyms
723 Options |= EOptionKeepUncalled;
724 } else if (lowerword == "nan-clamp") {
726 } else if (lowerword == "no-storage-format" || // synonyms
727 lowerword == "nsf") {
728 Options |= EOptionNoStorageFormat;
729 } else if (lowerword == "relaxed-errors") {
730 Options |= EOptionRelaxedErrors;
731 } else if (lowerword == "reflect-strict-array-suffix") {
732 ReflectOptions |= EShReflectionStrictArraySuffix;
733 } else if (lowerword == "reflect-basic-array-suffix") {
734 ReflectOptions |= EShReflectionBasicArraySuffix;
735 } else if (lowerword == "reflect-intermediate-io") {
736 ReflectOptions |= EShReflectionIntermediateIO;
737 } else if (lowerword == "reflect-separate-buffers") {
738 ReflectOptions |= EShReflectionSeparateBuffers;
739 } else if (lowerword == "reflect-all-block-variables") {
740 ReflectOptions |= EShReflectionAllBlockVariables;
741 } else if (lowerword == "reflect-unwrap-io-blocks") {
742 ReflectOptions |= EShReflectionUnwrapIOBlocks;
743 } else if (lowerword == "reflect-all-io-variables") {
744 ReflectOptions |= EShReflectionAllIOVariables;
745 } else if (lowerword == "reflect-shared-std140-ubo") {
746 ReflectOptions |= EShReflectionSharedStd140UBO;
747 } else if (lowerword == "reflect-shared-std140-ssbo") {
748 ReflectOptions |= EShReflectionSharedStd140SSBO;
749 } else if (lowerword == "resource-set-bindings" || // synonyms
750 lowerword == "resource-set-binding" ||
751 lowerword == "rsb") {
752 ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
753 } else if (lowerword == "set-block-storage" ||
754 lowerword == "sbs") {
755 ProcessBlockStorage(argc, argv, blockStorageOverrides);
756 } else if (lowerword == "set-atomic-counter-block" ||
757 lowerword == "sacb") {
758 ProcessGlobalBlockSettings(argc, argv, &atomicCounterBlockName, &atomicCounterBlockSet, nullptr);
759 setGlobalBufferBlock = true;
760 } else if (lowerword == "set-default-uniform-block" ||
761 lowerword == "sdub") {
762 ProcessGlobalBlockSettings(argc, argv, &globalUniformName, &globalUniformSet, &globalUniformBinding);
763 setGlobalUniformBlock = true;
764 } else if (lowerword == "shift-image-bindings" || // synonyms
765 lowerword == "shift-image-binding" ||
766 lowerword == "sib") {
767 ProcessBindingBase(argc, argv, glslang::EResImage);
768 } else if (lowerword == "shift-sampler-bindings" || // synonyms
769 lowerword == "shift-sampler-binding" ||
770 lowerword == "ssb") {
771 ProcessBindingBase(argc, argv, glslang::EResSampler);
772 } else if (lowerword == "shift-uav-bindings" || // synonyms
773 lowerword == "shift-uav-binding" ||
774 lowerword == "suavb") {
775 ProcessBindingBase(argc, argv, glslang::EResUav);
776 } else if (lowerword == "shift-texture-bindings" || // synonyms
777 lowerword == "shift-texture-binding" ||
778 lowerword == "stb") {
779 ProcessBindingBase(argc, argv, glslang::EResTexture);
780 } else if (lowerword == "shift-ubo-bindings" || // synonyms
781 lowerword == "shift-ubo-binding" ||
782 lowerword == "shift-cbuffer-bindings" ||
783 lowerword == "shift-cbuffer-binding" ||
784 lowerword == "sub" ||
785 lowerword == "scb") {
786 ProcessBindingBase(argc, argv, glslang::EResUbo);
787 } else if (lowerword == "shift-ssbo-bindings" || // synonyms
788 lowerword == "shift-ssbo-binding" ||
789 lowerword == "sbb") {
790 ProcessBindingBase(argc, argv, glslang::EResSsbo);
791 } else if (lowerword == "source-entrypoint" || // synonyms
792 lowerword == "sep") {
794 Error("no <entry-point> provided", lowerword.c_str());
795 sourceEntryPointName = argv[1];
798 } else if (lowerword == "spirv-dis") {
799 SpvToolsDisassembler = true;
800 } else if (lowerword == "spirv-val") {
801 SpvToolsValidate = true;
802 } else if (lowerword == "stdin") {
803 Options |= EOptionStdin;
804 shaderStageName = argv[1];
805 } else if (lowerword == "suppress-warnings") {
806 Options |= EOptionSuppressWarnings;
807 } else if (lowerword == "target-env") {
809 if (strcmp(argv[1], "vulkan1.0") == 0) {
811 ClientVersion = glslang::EShTargetVulkan_1_0;
812 } else if (strcmp(argv[1], "vulkan1.1") == 0) {
814 ClientVersion = glslang::EShTargetVulkan_1_1;
815 } else if (strcmp(argv[1], "vulkan1.2") == 0) {
817 ClientVersion = glslang::EShTargetVulkan_1_2;
818 } else if (strcmp(argv[1], "vulkan1.3") == 0) {
820 ClientVersion = glslang::EShTargetVulkan_1_3;
821 } else if (strcmp(argv[1], "opengl") == 0) {
823 ClientVersion = glslang::EShTargetOpenGL_450;
824 } else if (strcmp(argv[1], "spirv1.0") == 0) {
825 TargetLanguage = glslang::EShTargetSpv;
826 TargetVersion = glslang::EShTargetSpv_1_0;
827 } else if (strcmp(argv[1], "spirv1.1") == 0) {
828 TargetLanguage = glslang::EShTargetSpv;
829 TargetVersion = glslang::EShTargetSpv_1_1;
830 } else if (strcmp(argv[1], "spirv1.2") == 0) {
831 TargetLanguage = glslang::EShTargetSpv;
832 TargetVersion = glslang::EShTargetSpv_1_2;
833 } else if (strcmp(argv[1], "spirv1.3") == 0) {
834 TargetLanguage = glslang::EShTargetSpv;
835 TargetVersion = glslang::EShTargetSpv_1_3;
836 } else if (strcmp(argv[1], "spirv1.4") == 0) {
837 TargetLanguage = glslang::EShTargetSpv;
838 TargetVersion = glslang::EShTargetSpv_1_4;
839 } else if (strcmp(argv[1], "spirv1.5") == 0) {
840 TargetLanguage = glslang::EShTargetSpv;
841 TargetVersion = glslang::EShTargetSpv_1_5;
842 } else if (strcmp(argv[1], "spirv1.6") == 0) {
843 TargetLanguage = glslang::EShTargetSpv;
844 TargetVersion = glslang::EShTargetSpv_1_6;
846 Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2,\n"
847 "vulkan1.3, opengl, spirv1.0, spirv1.1, spirv1.2, spirv1.3,\n"
848 "spirv1.4, spirv1.5 or spirv1.6");
851 } else if (lowerword == "undef-macro" ||
854 UserPreamble.addUndef(argv[1]);
856 Error("expects <name>", argv[0]);
858 } else if (lowerword == "variable-name" || // synonyms
860 Options |= EOptionOutputHexadecimal;
862 Error("no <C-variable-name> provided", lowerword.c_str());
863 variableName = argv[1];
866 } else if (lowerword == "quiet") {
868 } else if (lowerword == "depfile") {
870 Error("no <depfile-name> provided", lowerword.c_str());
871 depencyFileName = argv[1];
873 } else if (lowerword == "version") {
874 Options |= EOptionDumpVersions;
875 } else if (lowerword == "help") {
879 Error("unrecognized command-line option", argv[0]);
884 Options |= EOptionCascadingErrors;
888 Options |= EOptionReadHlsl;
890 UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
893 uniformLocationOverrides.push_back(getUniformOverride());
896 Options |= EOptionOutputPreprocessed;
902 ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
903 if (ClientInputSemanticsVersion != 100)
904 Error("unknown client version for -G, should be 100");
907 Options |= EOptionHumanReadableSpv;
908 if ((Options & EOptionSpv) == 0) {
914 IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
917 if (argv[0][2] == 'd')
918 Options |= EOptionOptimizeDisable;
919 else if (argv[0][2] == 's')
921 Options |= EOptionOptimizeSize;
923 Error("-Os not available; optimizer not linked");
926 Error("unknown -O option");
929 VulkanRulesRelaxed = true;
933 Error("no <stage> specified for -S");
934 shaderStageName = argv[1];
938 UserPreamble.addUndef(getStringOperand("-U<name>"));
943 ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
944 if (ClientInputSemanticsVersion != 100)
945 Error("unknown client version for -V, should be 100");
948 Options |= EOptionDumpConfig;
951 if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
952 strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
953 Options |= EOptionDumpBareVersion;
955 Options |= EOptionDefaultDesktop;
958 entryPointName = argv[1];
960 Error("no <name> provided for -e");
964 if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
965 targetHlslFunctionality1 = true;
967 Error("-f: expected hlsl_functionality1");
970 // Override previous -g or -g0 argument
971 stripDebugInfo = false;
972 Options &= ~EOptionDebug;
973 if (argv[0][2] == '0')
974 stripDebugInfo = true;
976 Options |= EOptionDebug;
982 Options |= EOptionIntermediate;
985 Options |= EOptionLinkProgram;
988 Options |= EOptionMemoryLeakMode;
992 Error("no <file> provided for -o");
993 binaryFileName = argv[1];
997 Options |= EOptionDumpReflection;
1000 Options |= EOptionRelaxedErrors;
1003 Options |= EOptionSuppressInfolog;
1006 Options |= EOptionMultiThreaded;
1009 Options |= EOptionDumpVersions;
1012 Options |= EOptionSuppressWarnings;
1015 Options |= EOptionOutputHexadecimal;
1018 Error("unrecognized command-line option", argv[0]);
1022 std::string name(argv[0]);
1023 if (! SetConfigFile(name)) {
1024 workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
1029 // Make sure that -S is always specified if --stdin is specified
1030 if ((Options & EOptionStdin) && shaderStageName == nullptr)
1031 Error("must provide -S when --stdin is given");
1033 // Make sure that -E is not specified alongside linking (which includes SPV generation)
1034 // Or things that require linking
1035 if (Options & EOptionOutputPreprocessed) {
1036 if (Options & EOptionLinkProgram)
1037 Error("can't use -E when linking is selected");
1038 if (Options & EOptionDumpReflection)
1039 Error("reflection requires linking, which can't be used when -E when is selected");
1042 // reflection requires linking
1043 if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
1044 Error("reflection requires -l for linking");
1046 // -o or -x makes no sense if there is no target binary
1047 if (binaryFileName && (Options & EOptionSpv) == 0)
1048 Error("no binary generation requested (e.g., -V)");
1050 if ((Options & EOptionFlattenUniformArrays) != 0 &&
1051 (Options & EOptionReadHlsl) == 0)
1052 Error("uniform array flattening only valid when compiling HLSL source.");
1054 if ((Options & EOptionReadHlsl) && (Client == glslang::EShClientOpenGL)) {
1055 Error("Using HLSL input under OpenGL semantics is not currently supported.");
1058 // rationalize client and target language
1059 if (TargetLanguage == glslang::EShTargetNone) {
1060 switch (ClientVersion) {
1061 case glslang::EShTargetVulkan_1_0:
1062 TargetLanguage = glslang::EShTargetSpv;
1063 TargetVersion = glslang::EShTargetSpv_1_0;
1065 case glslang::EShTargetVulkan_1_1:
1066 TargetLanguage = glslang::EShTargetSpv;
1067 TargetVersion = glslang::EShTargetSpv_1_3;
1069 case glslang::EShTargetVulkan_1_2:
1070 TargetLanguage = glslang::EShTargetSpv;
1071 TargetVersion = glslang::EShTargetSpv_1_5;
1073 case glslang::EShTargetVulkan_1_3:
1074 TargetLanguage = glslang::EShTargetSpv;
1075 TargetVersion = glslang::EShTargetSpv_1_6;
1077 case glslang::EShTargetOpenGL_450:
1078 TargetLanguage = glslang::EShTargetSpv;
1079 TargetVersion = glslang::EShTargetSpv_1_0;
1085 if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
1086 Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
1090 // Translate the meaningful subset of command-line options to parser-behavior options.
1092 void SetMessageOptions(EShMessages& messages)
1094 if (Options & EOptionRelaxedErrors)
1095 messages = (EShMessages)(messages | EShMsgRelaxedErrors);
1096 if (Options & EOptionIntermediate)
1097 messages = (EShMessages)(messages | EShMsgAST);
1098 if (Options & EOptionSuppressWarnings)
1099 messages = (EShMessages)(messages | EShMsgSuppressWarnings);
1100 if (Options & EOptionSpv)
1101 messages = (EShMessages)(messages | EShMsgSpvRules);
1102 if (Options & EOptionVulkanRules)
1103 messages = (EShMessages)(messages | EShMsgVulkanRules);
1104 if (Options & EOptionOutputPreprocessed)
1105 messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
1106 if (Options & EOptionReadHlsl)
1107 messages = (EShMessages)(messages | EShMsgReadHlsl);
1108 if (Options & EOptionCascadingErrors)
1109 messages = (EShMessages)(messages | EShMsgCascadingErrors);
1110 if (Options & EOptionKeepUncalled)
1111 messages = (EShMessages)(messages | EShMsgKeepUncalled);
1112 if (Options & EOptionHlslOffsets)
1113 messages = (EShMessages)(messages | EShMsgHlslOffsets);
1114 if (Options & EOptionDebug)
1115 messages = (EShMessages)(messages | EShMsgDebugInfo);
1116 if (HlslEnable16BitTypes)
1117 messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
1118 if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
1119 messages = (EShMessages)(messages | EShMsgHlslLegalization);
1120 if (HlslDX9compatible)
1121 messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
1122 if (DumpBuiltinSymbols)
1123 messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
1125 messages = (EShMessages)(messages | EShMsgEnhanced);
1129 // Thread entry point, for non-linking asynchronous mode.
1131 void CompileShaders(glslang::TWorklist& worklist)
1133 if (Options & EOptionDebug)
1134 Error("cannot generate debug information unless linking to generate code");
1136 glslang::TWorkItem* workItem;
1137 if (Options & EOptionStdin) {
1138 if (worklist.remove(workItem)) {
1139 ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), Options);
1140 if (compiler == nullptr)
1143 CompileFile("stdin", compiler);
1145 if (! (Options & EOptionSuppressInfolog))
1146 workItem->results = ShGetInfoLog(compiler);
1148 ShDestruct(compiler);
1151 while (worklist.remove(workItem)) {
1152 ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), Options);
1156 CompileFile(workItem->name.c_str(), compiler);
1158 if (! (Options & EOptionSuppressInfolog))
1159 workItem->results = ShGetInfoLog(compiler);
1161 ShDestruct(compiler);
1166 // Outputs the given string, but only if it is non-null and non-empty.
1167 // This prevents erroneous newlines from appearing.
1168 void PutsIfNonEmpty(const char* str)
1170 if (str && str[0]) {
1175 // Outputs the given string to stderr, but only if it is non-null and non-empty.
1176 // This prevents erroneous newlines from appearing.
1177 void StderrIfNonEmpty(const char* str)
1180 fprintf(stderr, "%s\n", str);
1183 // Simple bundling of what makes a compilation unit for ease in passing around,
1184 // and separation of handling file IO versus API (programmatic) compilation.
1185 struct ShaderCompUnit {
1187 static const int maxCount = 1;
1188 int count; // live number of strings/names
1189 const char* text[maxCount]; // memory owned/managed externally
1190 std::string fileName[maxCount]; // hold's the memory, but...
1191 const char* fileNameList[maxCount]; // downstream interface wants pointers
1193 ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
1195 ShaderCompUnit(const ShaderCompUnit& rhs)
1199 for (int i = 0; i < count; ++i) {
1200 fileName[i] = rhs.fileName[i];
1201 text[i] = rhs.text[i];
1202 fileNameList[i] = rhs.fileName[i].c_str();
1206 void addString(std::string& ifileName, const char* itext)
1208 assert(count < maxCount);
1209 fileName[count] = ifileName;
1210 text[count] = itext;
1211 fileNameList[count] = fileName[count].c_str();
1216 // Writes a string into a depfile, escaping some special characters following the Makefile rules.
1217 static void writeEscapedDepString(std::ofstream& file, const std::string& str)
1219 for (char c : str) {
1237 // Writes a depfile similar to gcc -MMD foo.c
1238 bool writeDepFile(std::string depfile, std::vector<std::string>& binaryFiles, const std::vector<std::string>& sources)
1240 std::ofstream file(depfile);
1244 for (auto binaryFile = binaryFiles.begin(); binaryFile != binaryFiles.end(); binaryFile++) {
1245 writeEscapedDepString(file, *binaryFile);
1247 for (auto sourceFile = sources.begin(); sourceFile != sources.end(); sourceFile++) {
1249 writeEscapedDepString(file, *sourceFile);
1257 // For linking mode: Will independently parse each compilation unit, but then put them
1258 // in the same program and link them together, making at most one linked module per
1261 // Uses the new C++ interface instead of the old handle-based interface.
1264 void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
1266 // keep track of what to free
1267 std::list<glslang::TShader*> shaders;
1269 EShMessages messages = EShMsgDefault;
1270 SetMessageOptions(messages);
1272 DirStackFileIncluder includer;
1273 std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
1274 includer.pushExternalLocalDirectory(dir); });
1276 std::vector<std::string> sources;
1279 // Per-shader processing...
1282 glslang::TProgram& program = *new glslang::TProgram;
1283 for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
1284 const auto &compUnit = *it;
1285 for (int i = 0; i < compUnit.count; i++) {
1286 sources.push_back(compUnit.fileNameList[i]);
1288 glslang::TShader* shader = new glslang::TShader(compUnit.stage);
1289 shader->setStringsWithLengthsAndNames(compUnit.text, NULL, compUnit.fileNameList, compUnit.count);
1291 shader->setEntryPoint(entryPointName);
1292 if (sourceEntryPointName) {
1293 if (entryPointName == nullptr)
1294 printf("Warning: Changing source entry point name without setting an entry-point name.\n"
1295 "Use '-e <name>'.\n");
1296 shader->setSourceEntryPoint(sourceEntryPointName);
1299 shader->setOverrideVersion(GlslVersion);
1301 std::string intrinsicString = getIntrinsic(compUnit.text, compUnit.count);
1303 PreambleString = "";
1304 if (UserPreamble.isSet())
1305 PreambleString.append(UserPreamble.get());
1307 if (!intrinsicString.empty())
1308 PreambleString.append(intrinsicString);
1310 shader->setPreamble(PreambleString.c_str());
1311 shader->addProcesses(Processes);
1314 // Set IO mapper binding shift values
1315 for (int r = 0; r < glslang::EResCount; ++r) {
1316 const glslang::TResourceType res = glslang::TResourceType(r);
1318 // Set base bindings
1319 shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
1321 // Set bindings for particular resource sets
1322 // TODO: use a range based for loop here, when available in all environments.
1323 for (auto i = baseBindingForSet[res][compUnit.stage].begin();
1324 i != baseBindingForSet[res][compUnit.stage].end(); ++i)
1325 shader->setShiftBindingForSet(res, i->second, i->first);
1327 shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
1328 shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
1330 if (autoSampledTextures)
1331 shader->setTextureSamplerTransformMode(EShTexSampTransUpgradeTextureRemoveSampler);
1333 if (Options & EOptionAutoMapBindings)
1334 shader->setAutoMapBindings(true);
1336 if (Options & EOptionAutoMapLocations)
1337 shader->setAutoMapLocations(true);
1339 for (auto& uniOverride : uniformLocationOverrides) {
1340 shader->addUniformLocationOverride(uniOverride.first.c_str(),
1341 uniOverride.second);
1344 shader->setUniformLocationBase(uniformBase);
1347 if (VulkanRulesRelaxed) {
1348 for (auto& storageOverride : blockStorageOverrides) {
1349 shader->addBlockStorageOverride(storageOverride.first.c_str(),
1350 storageOverride.second);
1353 if (setGlobalBufferBlock) {
1354 shader->setAtomicCounterBlockName(atomicCounterBlockName.c_str());
1355 shader->setAtomicCounterBlockSet(atomicCounterBlockSet);
1358 if (setGlobalUniformBlock) {
1359 shader->setGlobalUniformBlockName(globalUniformName.c_str());
1360 shader->setGlobalUniformSet(globalUniformSet);
1361 shader->setGlobalUniformBinding(globalUniformBinding);
1365 shader->setNanMinMaxClamp(NaNClamp);
1368 shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
1369 if (Options & EOptionHlslIoMapping)
1370 shader->setHlslIoMapping(true);
1373 if (Options & EOptionInvertY)
1374 shader->setInvertY(true);
1376 if (HlslDxPositionW)
1377 shader->setDxPositionW(true);
1380 shader->setEnhancedMsgs();
1382 // Set up the environment, some subsettings take precedence over earlier
1383 // ways of setting things.
1384 if (Options & EOptionSpv) {
1385 shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
1386 : glslang::EShSourceGlsl,
1387 compUnit.stage, Client, ClientInputSemanticsVersion);
1388 shader->setEnvClient(Client, ClientVersion);
1389 shader->setEnvTarget(TargetLanguage, TargetVersion);
1391 if (targetHlslFunctionality1)
1392 shader->setEnvTargetHlslFunctionality1();
1394 if (VulkanRulesRelaxed)
1395 shader->setEnvInputVulkanRulesRelaxed();
1398 shaders.push_back(shader);
1400 const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
1403 if (Options & EOptionOutputPreprocessed) {
1405 if (shader->preprocess(&Resources, defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
1406 PutsIfNonEmpty(str.c_str());
1408 CompileFailed = true;
1410 StderrIfNonEmpty(shader->getInfoLog());
1411 StderrIfNonEmpty(shader->getInfoDebugLog());
1416 if (! shader->parse(&Resources, defaultVersion, false, messages, includer))
1417 CompileFailed = true;
1419 program.addShader(shader);
1421 if (! (Options & EOptionSuppressInfolog) &&
1422 ! (Options & EOptionMemoryLeakMode)) {
1424 PutsIfNonEmpty(compUnit.fileName[0].c_str());
1425 PutsIfNonEmpty(shader->getInfoLog());
1426 PutsIfNonEmpty(shader->getInfoDebugLog());
1431 // Program-level processing...
1435 if (! (Options & EOptionOutputPreprocessed) && ! program.link(messages))
1440 if (Options & EOptionSpv) {
1441 if (!program.mapIO())
1447 if (! (Options & EOptionSuppressInfolog) &&
1448 ! (Options & EOptionMemoryLeakMode)) {
1449 PutsIfNonEmpty(program.getInfoLog());
1450 PutsIfNonEmpty(program.getInfoDebugLog());
1455 if (Options & EOptionDumpReflection) {
1456 program.buildReflection(ReflectOptions);
1457 program.dumpReflection();
1461 std::vector<std::string> outputFiles;
1464 if (Options & EOptionSpv) {
1465 if (CompileFailed || LinkFailed)
1466 printf("SPIR-V is not generated for failed compile or link\n");
1468 for (int stage = 0; stage < EShLangCount; ++stage) {
1469 if (program.getIntermediate((EShLanguage)stage)) {
1470 std::vector<unsigned int> spirv;
1471 spv::SpvBuildLogger logger;
1472 glslang::SpvOptions spvOptions;
1473 if (Options & EOptionDebug)
1474 spvOptions.generateDebugInfo = true;
1475 else if (stripDebugInfo)
1476 spvOptions.stripDebugInfo = true;
1477 spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
1478 spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
1479 spvOptions.disassemble = SpvToolsDisassembler;
1480 spvOptions.validate = SpvToolsValidate;
1481 glslang::GlslangToSpv(*program.getIntermediate((EShLanguage)stage), spirv, &logger, &spvOptions);
1483 // Dump the spv to a file or stdout, etc., but only if not doing
1484 // memory/perf testing, as it's not internal to programmatic use.
1485 if (! (Options & EOptionMemoryLeakMode)) {
1486 printf("%s", logger.getAllMessages().c_str());
1487 if (Options & EOptionOutputHexadecimal) {
1488 glslang::OutputSpvHex(spirv, GetBinaryName((EShLanguage)stage), variableName);
1490 glslang::OutputSpvBin(spirv, GetBinaryName((EShLanguage)stage));
1493 outputFiles.push_back(GetBinaryName((EShLanguage)stage));
1495 if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
1496 spv::Disassemble(std::cout, spirv);
1504 if (depencyFileName && !(CompileFailed || LinkFailed)) {
1505 std::set<std::string> includedFiles = includer.getIncludedFiles();
1506 sources.insert(sources.end(), includedFiles.begin(), includedFiles.end());
1508 writeDepFile(depencyFileName, outputFiles, sources);
1511 // Free everything up, program has to go before the shaders
1512 // because it might have merged stuff from the shaders, and
1513 // the stuff from the shaders has to have its destructors called
1514 // before the pools holding the memory in the shaders is freed.
1516 while (shaders.size() > 0) {
1517 delete shaders.back();
1523 // Do file IO part of compile and link, handing off the pure
1524 // API/programmatic mode to CompileAndLinkShaderUnits(), which can
1525 // be put in a loop for testing memory footprint and performance.
1527 // This is just for linking mode: meaning all the shaders will be put into the
1528 // the same program linked together.
1530 // This means there are a limited number of work items (not multi-threading mode)
1531 // and that the point is testing at the linking level. Hence, to enable
1532 // performance and memory testing, the actual compile/link can be put in
1533 // a loop, independent of processing the work items and file IO.
1535 void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
1537 std::vector<ShaderCompUnit> compUnits;
1539 // If this is using stdin, we can't really detect multiple different file
1540 // units by input type. We need to assume that we're just being given one
1541 // file of a certain type.
1542 if ((Options & EOptionStdin) != 0) {
1543 ShaderCompUnit compUnit(FindLanguage("stdin"));
1544 std::istreambuf_iterator<char> begin(std::cin), end;
1545 std::string tempString(begin, end);
1546 char* fileText = strdup(tempString.c_str());
1547 std::string fileName = "stdin";
1548 compUnit.addString(fileName, fileText);
1549 compUnits.push_back(compUnit);
1551 // Transfer all the work items from to a simple list of
1552 // of compilation units. (We don't care about the thread
1553 // work-item distribution properties in this path, which
1554 // is okay due to the limited number of shaders, know since
1555 // they are all getting linked together.)
1556 glslang::TWorkItem* workItem;
1557 while (Worklist.remove(workItem)) {
1558 ShaderCompUnit compUnit(FindLanguage(workItem->name));
1559 char* fileText = ReadFileData(workItem->name.c_str());
1560 if (fileText == nullptr)
1562 compUnit.addString(workItem->name, fileText);
1563 compUnits.push_back(compUnit);
1567 // Actual call to programmatic processing of compile and link,
1568 // in a loop for testing memory and performance. This part contains
1569 // all the perf/memory that a programmatic consumer will care about.
1570 for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1571 for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
1572 CompileAndLinkShaderUnits(compUnits);
1574 if (Options & EOptionMemoryLeakMode)
1575 glslang::OS_DumpMemoryCounters();
1578 // free memory from ReadFileData, which got stored in a const char*
1579 // as the first string above
1580 for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
1581 FreeFileData(const_cast<char*>(it->text[0]));
1586 glslang::TWorklist workList;
1587 std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
1589 workList.add(item.get());
1593 if (Options & EOptionDumpConfig) {
1594 printf("%s", glslang::GetDefaultTBuiltInResourceString().c_str());
1595 if (workList.empty())
1600 if (Options & EOptionDumpBareVersion) {
1601 printf("%d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR, GLSLANG_VERSION_MINOR,
1602 GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1603 if (workList.empty())
1605 } else if (Options & EOptionDumpVersions) {
1606 printf("Glslang Version: %d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR,
1607 GLSLANG_VERSION_MINOR, GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1608 printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
1609 printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
1610 std::string spirvVersion;
1611 glslang::GetSpirvVersion(spirvVersion);
1612 printf("SPIR-V Version %s\n", spirvVersion.c_str());
1613 printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
1614 printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
1615 printf("SPIR-V Generator Version %d\n", glslang::GetSpirvGeneratorVersion());
1616 printf("GL_KHR_vulkan_glsl version %d\n", 100);
1617 printf("ARB_GL_gl_spirv version %d\n", 100);
1618 if (workList.empty())
1622 if (workList.empty() && ((Options & EOptionStdin) == 0)) {
1626 if (Options & EOptionStdin) {
1627 WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
1628 workList.add(WorkItems.back().get());
1631 ProcessConfigFile();
1633 if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
1634 Error("HLSL requires SPIR-V code generation (or preprocessing only)");
1638 // 1) linking all arguments together, single-threaded, new C++ interface
1639 // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
1641 if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
1642 glslang::InitializeProcess();
1643 glslang::InitializeProcess(); // also test reference counting of users
1644 glslang::InitializeProcess(); // also test reference counting of users
1645 glslang::FinalizeProcess(); // also test reference counting of users
1646 glslang::FinalizeProcess(); // also test reference counting of users
1647 CompileAndLinkShaderFiles(workList);
1648 glslang::FinalizeProcess();
1651 ShInitialize(); // also test reference counting of users
1652 ShFinalize(); // also test reference counting of users
1654 bool printShaderNames = workList.size() > 1;
1656 if (Options & EOptionMultiThreaded) {
1657 std::array<std::thread, 16> threads;
1658 for (unsigned int t = 0; t < threads.size(); ++t) {
1659 threads[t] = std::thread(CompileShaders, std::ref(workList));
1660 if (threads[t].get_id() == std::thread::id()) {
1661 fprintf(stderr, "Failed to create thread\n");
1662 return EFailThreadCreate;
1666 std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
1668 CompileShaders(workList);
1670 // Print out all the resulting infologs
1671 for (size_t w = 0; w < WorkItems.size(); ++w) {
1673 if (printShaderNames || WorkItems[w]->results.size() > 0)
1674 PutsIfNonEmpty(WorkItems[w]->name.c_str());
1675 PutsIfNonEmpty(WorkItems[w]->results.c_str());
1683 return EFailCompile;
1690 int C_DECL main(int argc, char* argv[])
1692 ProcessArguments(WorkItems, argc, argv);
1696 // Loop over the entire init/finalize cycle to watch memory changes
1697 const int iterations = 1;
1699 glslang::OS_DumpMemoryCounters();
1700 for (int i = 0; i < iterations; ++i) {
1703 glslang::OS_DumpMemoryCounters();
1710 // Deduce the language from the filename. Files must end in one of the
1711 // following extensions:
1714 // .tesc = tessellation control
1715 // .tese = tessellation evaluation
1719 // .rgen = ray generation
1720 // .rint = ray intersection
1721 // .rahit = ray any hit
1722 // .rchit = ray closest hit
1723 // .rmiss = ray miss
1724 // .rcall = ray callable
1727 // Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
1728 // where <stage> is one of the stages listed above.
1730 EShLanguage FindLanguage(const std::string& name, bool parseStageName)
1732 std::string stageName;
1733 if (shaderStageName)
1734 stageName = shaderStageName;
1735 else if (parseStageName) {
1736 // Note: "first" extension means "first from the end", i.e.
1737 // if the file is named foo.vert.glsl, then "glsl" is first,
1738 // "vert" is second.
1739 size_t firstExtStart = name.find_last_of(".");
1740 bool hasFirstExt = firstExtStart != std::string::npos;
1741 size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
1742 bool hasSecondExt = secondExtStart != std::string::npos;
1743 std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
1744 bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
1745 if (usesUnifiedExt && firstExt == "hlsl")
1746 Options |= EOptionReadHlsl;
1747 if (hasFirstExt && !usesUnifiedExt)
1748 stageName = firstExt;
1749 else if (usesUnifiedExt && hasSecondExt)
1750 stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
1753 return EShLangVertex;
1758 if (stageName == "vert")
1759 return EShLangVertex;
1760 else if (stageName == "tesc")
1761 return EShLangTessControl;
1762 else if (stageName == "tese")
1763 return EShLangTessEvaluation;
1764 else if (stageName == "geom")
1765 return EShLangGeometry;
1766 else if (stageName == "frag")
1767 return EShLangFragment;
1768 else if (stageName == "comp")
1769 return EShLangCompute;
1770 else if (stageName == "rgen")
1771 return EShLangRayGen;
1772 else if (stageName == "rint")
1773 return EShLangIntersect;
1774 else if (stageName == "rahit")
1775 return EShLangAnyHit;
1776 else if (stageName == "rchit")
1777 return EShLangClosestHit;
1778 else if (stageName == "rmiss")
1780 else if (stageName == "rcall")
1781 return EShLangCallable;
1782 else if (stageName == "mesh")
1783 return EShLangMeshNV;
1784 else if (stageName == "task")
1785 return EShLangTaskNV;
1788 return EShLangVertex;
1792 // Read a file's data into a string, and compile it using the old interface ShCompile,
1793 // for non-linkable results.
1795 void CompileFile(const char* fileName, ShHandle compiler)
1799 if ((Options & EOptionStdin) != 0) {
1800 std::istreambuf_iterator<char> begin(std::cin), end;
1801 std::string tempString(begin, end);
1802 shaderString = strdup(tempString.c_str());
1804 shaderString = ReadFileData(fileName);
1807 // move to length-based strings, rather than null-terminated strings
1808 int* lengths = new int[1];
1809 lengths[0] = (int)strlen(shaderString);
1811 EShMessages messages = EShMsgDefault;
1812 SetMessageOptions(messages);
1814 if (UserPreamble.isSet())
1815 Error("-D and -U options require -l (linking)\n");
1817 for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1818 for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
1819 // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1820 ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1821 // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
1822 // "or should be l", "ine 1", "string 5\n", "float glo", "bal",
1823 // ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
1824 // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
1825 // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1828 if (Options & EOptionMemoryLeakMode)
1829 glslang::OS_DumpMemoryCounters();
1833 FreeFileData(shaderString);
1836 CompileFailed = true;
1840 // print usage to stdout
1844 printf("Usage: glslangValidator [option]... [file]...\n"
1846 "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
1847 " .conf to provide a config file that replaces the default configuration\n"
1848 " (see -c option below for generating a template)\n"
1849 " .vert for a vertex shader\n"
1850 " .tesc for a tessellation control shader\n"
1851 " .tese for a tessellation evaluation shader\n"
1852 " .geom for a geometry shader\n"
1853 " .frag for a fragment shader\n"
1854 " .comp for a compute shader\n"
1855 " .mesh for a mesh shader\n"
1856 " .task for a task shader\n"
1857 " .rgen for a ray generation shader\n"
1858 " .rint for a ray intersection shader\n"
1859 " .rahit for a ray any hit shader\n"
1860 " .rchit for a ray closest hit shader\n"
1861 " .rmiss for a ray miss shader\n"
1862 " .rcall for a ray callable shader\n"
1863 " .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
1864 " .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
1867 " -C cascading errors; risk crash from accumulation of error recoveries\n"
1868 " -D input is HLSL (this is the default when any suffix is .hlsl)\n"
1869 " -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]>\n"
1870 " define a pre-processor macro\n"
1871 " -E print pre-processed GLSL; cannot be used with -l;\n"
1872 " errors will appear on stderr\n"
1873 " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
1874 " default file name is <stage>.spv (-o overrides this);\n"
1875 " 'ver', when present, is the version of the input semantics,\n"
1876 " which will appear in #define GL_SPIRV ver;\n"
1877 " '--client opengl100' is the same as -G100;\n"
1878 " a '--target-env' for OpenGL will also imply '-G';\n"
1879 " currently only supports GLSL\n"
1880 " -H print human readable form of SPIR-V; turns on -V\n"
1881 " -I<dir> add dir to the include search path; includer's directory\n"
1882 " is searched first, followed by left-to-right order of -I\n"
1883 " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
1884 " -Os optimizes SPIR-V to minimize size\n"
1885 " -R use relaxed verification rules for generating Vulkan SPIR-V,\n"
1886 " allowing the use of default uniforms, atomic_uints, and\n"
1887 " gl_VertexID and gl_InstanceID keywords.\n"
1888 " -S <stage> uses specified stage rather than parsing the file extension\n"
1889 " choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
1890 " -U<name> | --undef-macro <name> | --U <name>\n"
1891 " undefine a pre-processor macro\n"
1892 " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
1893 " default file name is <stage>.spv (-o overrides this)\n"
1894 " 'ver', when present, is the version of the input semantics,\n"
1895 " which will appear in #define VULKAN ver\n"
1896 " '--client vulkan100' is the same as -V100\n"
1897 " a '--target-env' for Vulkan will also imply '-V'\n"
1898 " -c configuration dump;\n"
1899 " creates the default configuration file (redirect to a .conf file)\n"
1900 " -d default to desktop (#version 110) when there is no shader #version\n"
1901 " (default is ES version 100)\n"
1902 " -e <name> | --entry-point <name>\n"
1903 " specify <name> as the entry-point function name\n"
1904 " -f{hlsl_functionality1}\n"
1905 " 'hlsl_functionality1' enables use of the\n"
1906 " SPV_GOOGLE_hlsl_functionality1 extension\n"
1907 " -g generate debug information\n"
1908 " -g0 strip debug information\n"
1909 " -h print this usage message\n"
1910 " -i intermediate tree (glslang AST) is printed out\n"
1911 " -l link all input files together to form a single module\n"
1912 " -m memory leak mode\n"
1913 " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
1914 " -q dump reflection query database; requires -l for linking\n"
1915 " -r | --relaxed-errors"
1916 " relaxed GLSL semantic error-checking mode\n"
1917 " -s silence syntax and semantic error reporting\n"
1918 " -t multi-threaded mode\n"
1920 " print version strings\n"
1921 " -w | --suppress-warnings\n"
1922 " suppress GLSL warnings, except as required by \"#extension : warn\"\n"
1923 " -x save binary output as text-based 32-bit hexadecimal numbers\n"
1924 " -u<name>:<loc> specify a uniform location override for --aml\n"
1925 " --uniform-base <base> set a base to use for generated uniform locations\n"
1926 " --auto-map-bindings | --amb automatically bind uniform variables\n"
1927 " without explicit bindings\n"
1928 " --auto-map-locations | --aml automatically locate input/output lacking\n"
1929 " 'location' (fragile, not cross stage)\n"
1930 " --auto-sampled-textures Removes sampler variables and converts\n"
1931 " existing textures to sampled textures\n"
1932 " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
1933 " --depfile <file> writes depfile for build systems\n"
1934 " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
1935 " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
1936 " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
1938 " --glsl-version {100 | 110 | 120 | 130 | 140 | 150 |\n"
1939 " 300es | 310es | 320es | 330\n"
1940 " 400 | 410 | 420 | 430 | 440 | 450 | 460}\n"
1941 " set GLSL version, overrides #version\n"
1942 " in shader sourcen\n"
1943 " --hlsl-offsets allow block offsets to follow HLSL rules\n"
1944 " works independently of source language\n"
1945 " --hlsl-iomap perform IO mapping in HLSL register space\n"
1946 " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
1947 " --hlsl-dx9-compatible interprets sampler declarations as a\n"
1948 " texture/sampler combo like DirectX9 would,\n"
1949 " and recognizes DirectX9-specific semantics\n"
1950 " --hlsl-dx-position-w W component of SV_Position in HLSL fragment\n"
1951 " shaders compatible with DirectX\n"
1952 " --invert-y | --iy invert position.Y output in vertex shader\n"
1953 " --enhanced-msgs print more readable error messages (GLSL only)\n"
1954 " --keep-uncalled | --ku don't eliminate uncalled functions\n"
1955 " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
1956 " --no-storage-format | --nsf use Unknown image format\n"
1957 " --quiet do not print anything to stdout, unless\n"
1958 " requested by another option\n"
1959 " --reflect-strict-array-suffix use strict array suffix rules when\n"
1961 " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
1962 " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
1963 " shaders rather than just vertex/fragment\n"
1964 " --reflect-separate-buffers reflect buffer variables and blocks\n"
1965 " separately to uniforms\n"
1966 " --reflect-all-block-variables reflect all variables in blocks, whether\n"
1967 " inactive or active\n"
1968 " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
1970 " --resource-set-binding [stage] name set binding\n"
1971 " set descriptor set and binding for\n"
1972 " individual resources\n"
1973 " --resource-set-binding [stage] set\n"
1974 " set descriptor set for all resources\n"
1975 " --rsb synonym for --resource-set-binding\n"
1976 " --set-block-backing name {uniform|buffer|push_constant}\n"
1977 " changes the backing type of a uniform, buffer,\n"
1978 " or push_constant block declared in\n"
1979 " in the program, when using -R option.\n"
1980 " This can be used to change the backing\n"
1981 " for existing blocks as well as implicit ones\n"
1982 " such as 'gl_DefaultUniformBlock'.\n"
1983 " --sbs synonym for set-block-storage\n"
1984 " --set-atomic-counter-block name set\n"
1985 " set name, and descriptor set for\n"
1986 " atomic counter blocks, with -R opt\n"
1987 " --sacb synonym for set-atomic-counter-block\n"
1988 " --set-default-uniform-block name set binding\n"
1989 " set name, descriptor set, and binding for\n"
1990 " global default-uniform-block, with -R opt\n"
1991 " --sdub synonym for set-default-uniform-block\n"
1992 " --shift-image-binding [stage] num\n"
1993 " base binding number for images (uav)\n"
1994 " --shift-image-binding [stage] [num set]...\n"
1995 " per-descriptor-set shift values\n"
1996 " --sib synonym for --shift-image-binding\n"
1997 " --shift-sampler-binding [stage] num\n"
1998 " base binding number for samplers\n"
1999 " --shift-sampler-binding [stage] [num set]...\n"
2000 " per-descriptor-set shift values\n"
2001 " --ssb synonym for --shift-sampler-binding\n"
2002 " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
2003 " --shift-ssbo-binding [stage] [num set]...\n"
2004 " per-descriptor-set shift values\n"
2005 " --sbb synonym for --shift-ssbo-binding\n"
2006 " --shift-texture-binding [stage] num\n"
2007 " base binding number for textures\n"
2008 " --shift-texture-binding [stage] [num set]...\n"
2009 " per-descriptor-set shift values\n"
2010 " --stb synonym for --shift-texture-binding\n"
2011 " --shift-uav-binding [stage] num base binding number for UAVs\n"
2012 " --shift-uav-binding [stage] [num set]...\n"
2013 " per-descriptor-set shift values\n"
2014 " --suavb synonym for --shift-uav-binding\n"
2015 " --shift-UBO-binding [stage] num base binding number for UBOs\n"
2016 " --shift-UBO-binding [stage] [num set]...\n"
2017 " per-descriptor-set shift values\n"
2018 " --sub synonym for --shift-UBO-binding\n"
2019 " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
2020 " --spirv-dis output standard-form disassembly; works only\n"
2021 " when a SPIR-V generation option is also used\n"
2022 " --spirv-val execute the SPIRV-Tools validator\n"
2023 " --source-entrypoint <name> the given shader source function is\n"
2024 " renamed to be the <name> given in -e\n"
2025 " --sep synonym for --source-entrypoint\n"
2026 " --stdin read from stdin instead of from a file;\n"
2027 " requires providing the shader stage using -S\n"
2028 " --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | vulkan1.3 | opengl |\n"
2029 " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 |\n"
2030 " spirv1.5 | spirv1.6}\n"
2031 " Set the execution environment that the\n"
2032 " generated code will be executed in.\n"
2034 " * vulkan1.0 under --client vulkan<ver>\n"
2035 " * opengl under --client opengl<ver>\n"
2036 " * spirv1.0 under --target-env vulkan1.0\n"
2037 " * spirv1.3 under --target-env vulkan1.1\n"
2038 " * spirv1.5 under --target-env vulkan1.2\n"
2039 " * spirv1.6 under --target-env vulkan1.3\n"
2040 " Multiple --target-env can be specified.\n"
2041 " --variable-name <name>\n"
2042 " --vn <name> creates a C header file that contains a\n"
2043 " uint32_t array named <name>\n"
2044 " initialized with the shader binary code\n"
2050 #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
2056 const char* filename,
2060 if (!pFile || !filename || !mode) {
2064 FILE* f = fopen(filename, mode);
2080 // Malloc a string of sufficient size and read a string into it.
2082 char* ReadFileData(const char* fileName)
2085 int errorCode = fopen_s(&in, fileName, "r");
2086 if (errorCode || in == nullptr)
2087 Error("unable to open input file");
2090 while (fgetc(in) != EOF)
2093 fseek(in, 0, SEEK_SET);
2095 char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
2096 if ((int)fread(return_data, 1, count, in) != count) {
2098 Error("can't read input file");
2101 return_data[count] = '\0';
2107 void FreeFileData(char* data)
2112 void InfoLogMsg(const char* msg, const char* name, const int num)
2115 printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
2117 printf("#### %s %s INFO LOG ####\n", msg, name);