2 // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
3 // Copyright (C) 2013-2016 LunarG, Inc.
4 // Copyright (C) 2016-2020 Google, Inc.
6 // All rights reserved.
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions
12 // Redistributions of source code must retain the above copyright
13 // notice, this list of conditions and the following disclaimer.
15 // Redistributions in binary form must reproduce the above
16 // copyright notice, this list of conditions and the following
17 // disclaimer in the documentation and/or other materials provided
18 // with the distribution.
20 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21 // contributors may be used to endorse or promote products derived
22 // from this software without specific prior written permission.
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 // POSSIBILITY OF SUCH DAMAGE.
38 // this only applies to the standalone wrapper, not the front end in general
39 #ifndef _CRT_SECURE_NO_WARNINGS
40 #define _CRT_SECURE_NO_WARNINGS
43 #include "ResourceLimits.h"
45 #include "DirStackFileIncluder.h"
46 #include "./../glslang/Include/ShHandle.h"
47 #include "./../glslang/Include/revision.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"
63 #include "../glslang/OSDependent/osinclude.h"
66 SH_IMPORT_EXPORT void ShOutputHtml();
69 // Command-line options
72 EOptionIntermediate = (1 << 0),
73 EOptionSuppressInfolog = (1 << 1),
74 EOptionMemoryLeakMode = (1 << 2),
75 EOptionRelaxedErrors = (1 << 3),
76 EOptionGiveWarnings = (1 << 4),
77 EOptionLinkProgram = (1 << 5),
78 EOptionMultiThreaded = (1 << 6),
79 EOptionDumpConfig = (1 << 7),
80 EOptionDumpReflection = (1 << 8),
81 EOptionSuppressWarnings = (1 << 9),
82 EOptionDumpVersions = (1 << 10),
83 EOptionSpv = (1 << 11),
84 EOptionHumanReadableSpv = (1 << 12),
85 EOptionVulkanRules = (1 << 13),
86 EOptionDefaultDesktop = (1 << 14),
87 EOptionOutputPreprocessed = (1 << 15),
88 EOptionOutputHexadecimal = (1 << 16),
89 EOptionReadHlsl = (1 << 17),
90 EOptionCascadingErrors = (1 << 18),
91 EOptionAutoMapBindings = (1 << 19),
92 EOptionFlattenUniformArrays = (1 << 20),
93 EOptionNoStorageFormat = (1 << 21),
94 EOptionKeepUncalled = (1 << 22),
95 EOptionHlslOffsets = (1 << 23),
96 EOptionHlslIoMapping = (1 << 24),
97 EOptionAutoMapLocations = (1 << 25),
98 EOptionDebug = (1 << 26),
99 EOptionStdin = (1 << 27),
100 EOptionOptimizeDisable = (1 << 28),
101 EOptionOptimizeSize = (1 << 29),
102 EOptionInvertY = (1 << 30),
103 EOptionDumpBareVersion = (1 << 31),
105 bool targetHlslFunctionality1 = false;
106 bool SpvToolsDisassembler = false;
107 bool SpvToolsValidate = false;
108 bool NaNClamp = false;
109 bool stripDebugInfo = false;
112 // Return codes from main/exit().
125 // Forward declarations.
127 EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
128 void CompileFile(const char* fileName, ShHandle);
130 char* ReadFileData(const char* fileName);
131 void FreeFileData(char* data);
132 void InfoLogMsg(const char* msg, const char* name, const int num);
134 // Globally track if any compile or link failure.
135 bool CompileFailed = false;
136 bool LinkFailed = false;
138 // array of unique places to leave the shader names and infologs for the asynchronous compiles
139 std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
141 TBuiltInResource Resources;
142 std::string ConfigFile;
145 // Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
147 void ProcessConfigFile()
149 if (ConfigFile.size() == 0)
150 Resources = glslang::DefaultTBuiltInResource;
153 char* configString = ReadFileData(ConfigFile.c_str());
154 glslang::DecodeResourceLimits(&Resources, configString);
155 FreeFileData(configString);
160 int ReflectOptions = EShReflectionDefault;
162 const char* ExecutableName = nullptr;
163 const char* binaryFileName = nullptr;
164 const char* entryPointName = nullptr;
165 const char* sourceEntryPointName = nullptr;
166 const char* shaderStageName = nullptr;
167 const char* variableName = nullptr;
168 bool HlslEnable16BitTypes = false;
169 bool HlslDX9compatible = false;
170 bool DumpBuiltinSymbols = false;
171 std::vector<std::string> IncludeDirectoryList;
173 // Source environment
174 // (source 'Client' is currently the same as target 'Client')
175 int ClientInputSemanticsVersion = 100;
177 // Target environment
178 glslang::EShClient Client = glslang::EShClientNone; // will stay EShClientNone if only validating
179 glslang::EShTargetClientVersion ClientVersion; // not valid until Client is set
180 glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
181 glslang::EShTargetLanguageVersion TargetVersion; // not valid until TargetLanguage is set
183 std::vector<std::string> Processes; // what should be recorded by OpModuleProcessed, or equivalent
185 // Per descriptor-set binding base data
186 typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
188 std::vector<std::pair<std::string, int>> uniformLocationOverrides;
191 std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
192 std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
193 std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
195 // Add things like "#define ..." to a preamble to use in the beginning of the shader.
200 bool isSet() const { return text.size() > 0; }
201 const char* get() const { return text.c_str(); }
204 void addDef(std::string def)
206 text.append("#define ");
209 Processes.push_back("define-macro ");
210 Processes.back().append(def);
212 // The first "=" needs to turn into a space
213 const size_t equal = def.find_first_of("=");
214 if (equal != def.npos)
222 void addUndef(std::string undef)
224 text.append("#undef ");
227 Processes.push_back("undef-macro ");
228 Processes.back().append(undef);
235 void fixLine(std::string& line)
237 // Can't go past a newline in the line
238 const size_t end = line.find_first_of("\n");
239 if (end != line.npos)
240 line = line.substr(0, end);
243 std::string text; // contents of preamble
246 // Track the user's #define and #undef from the command line.
247 TPreamble UserPreamble;
250 // Create the default name for saving a binary if -o is not provided.
252 const char* GetBinaryName(EShLanguage stage)
255 if (binaryFileName == nullptr) {
257 case EShLangVertex: name = "vert.spv"; break;
258 case EShLangTessControl: name = "tesc.spv"; break;
259 case EShLangTessEvaluation: name = "tese.spv"; break;
260 case EShLangGeometry: name = "geom.spv"; break;
261 case EShLangFragment: name = "frag.spv"; break;
262 case EShLangCompute: name = "comp.spv"; break;
263 case EShLangRayGen: name = "rgen.spv"; break;
264 case EShLangIntersect: name = "rint.spv"; break;
265 case EShLangAnyHit: name = "rahit.spv"; break;
266 case EShLangClosestHit: name = "rchit.spv"; break;
267 case EShLangMiss: name = "rmiss.spv"; break;
268 case EShLangCallable: name = "rcall.spv"; break;
269 case EShLangMeshNV: name = "mesh.spv"; break;
270 case EShLangTaskNV: name = "task.spv"; break;
271 default: name = "unknown"; break;
274 name = binaryFileName;
280 // *.conf => this is a config file that can set limits/resources
282 bool SetConfigFile(const std::string& name)
287 if (name.compare(name.size() - 5, 5, ".conf") == 0) {
296 // Give error and exit with failure code.
298 void Error(const char* message, const char* detail = nullptr)
300 fprintf(stderr, "%s: Error: ", ExecutableName);
301 if (detail != nullptr)
302 fprintf(stderr, "%s: ", detail);
303 fprintf(stderr, "%s (use -h for usage)\n", message);
308 // Process an optional binding base of one the forms:
309 // --argname [stage] base // base for stage (if given) or all stages (if not)
310 // --argname [stage] [base set]... // set/base pairs: set the base for given binding set.
312 // Where stage is one of the forms accepted by FindLanguage, and base is an integer
314 void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
319 EShLanguage lang = EShLangCount;
321 TPerSetBaseBinding perSetBase;
324 // Parse stage, if given
325 if (!isdigit(argv[arg][0])) {
326 if (argc < 3) // this form needs one more argument
329 lang = FindLanguage(argv[arg++], false);
332 if ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
333 // Parse a per-set binding base
334 while ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
335 const int baseNum = atoi(argv[arg++]);
336 const int setNum = atoi(argv[arg++]);
337 perSetBase[setNum] = baseNum;
340 // Parse single binding base
341 singleBase = atoi(argv[arg++]);
347 // Set one or all languages
348 const int langMin = (lang < EShLangCount) ? lang+0 : 0;
349 const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
351 for (int lang = langMin; lang < langMax; ++lang) {
352 if (!perSetBase.empty())
353 baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
355 baseBinding[res][lang] = singleBase;
359 void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
364 if (!isdigit(argv[1][0])) {
365 if (argc < 3) // this form needs one more argument
368 // Parse form: --argname stage [regname set base...], or:
369 // --argname stage set
370 const EShLanguage lang = FindLanguage(argv[1], false);
375 while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
376 base[lang].push_back(argv[1]);
382 // Must have one arg, or a multiple of three (for [regname set binding] triples)
383 if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
387 // Parse form: --argname set
388 for (int lang=0; lang<EShLangCount; ++lang)
389 base[lang].push_back(argv[1]);
397 // Do all command-line argument parsing. This includes building up the work-items
398 // to be processed later, and saving all the command-line options.
400 // Does not return (it exits) if command-line is fatally flawed.
402 void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
404 for (int res = 0; res < glslang::EResCount; ++res)
405 baseBinding[res].fill(0);
407 ExecutableName = argv[0];
408 workItems.reserve(argc);
410 const auto bumpArg = [&]() {
417 // read a string directly attached to a single-letter option
418 const auto getStringOperand = [&](const char* desc) {
419 if (argv[0][2] == 0) {
420 printf("%s must immediately follow option (no spaces)\n", desc);
426 // read a number attached to a single-letter option
427 const auto getAttachedNumber = [&](const char* desc) {
428 int num = atoi(argv[0] + 2);
430 printf("%s: expected attached non-0 number\n", desc);
436 // minimum needed (without overriding something else) to target Vulkan SPIR-V
437 const auto setVulkanSpv = []() {
438 if (Client == glslang::EShClientNone)
439 ClientVersion = glslang::EShTargetVulkan_1_0;
440 Client = glslang::EShClientVulkan;
441 Options |= EOptionSpv;
442 Options |= EOptionVulkanRules;
443 Options |= EOptionLinkProgram;
446 // minimum needed (without overriding something else) to target OpenGL SPIR-V
447 const auto setOpenGlSpv = []() {
448 if (Client == glslang::EShClientNone)
449 ClientVersion = glslang::EShTargetOpenGL_450;
450 Client = glslang::EShClientOpenGL;
451 Options |= EOptionSpv;
452 Options |= EOptionLinkProgram;
453 // undo a -H default to Vulkan
454 Options &= ~EOptionVulkanRules;
457 const auto getUniformOverride = [getStringOperand]() {
458 const char *arg = getStringOperand("-u<name>:<location>");
459 const char *split = strchr(arg, ':');
461 printf("%s: missing location\n", arg);
465 int location = ::strtol(split + 1, NULL, 10);
467 printf("%s: invalid location\n", arg);
470 return std::make_pair(std::string(arg, split - arg), location);
473 for (bumpArg(); argc >= 1; bumpArg()) {
474 if (argv[0][0] == '-') {
475 switch (argv[0][1]) {
478 std::string lowerword(argv[0]+2);
479 std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
481 // handle --word style options
482 if (lowerword == "auto-map-bindings" || // synonyms
483 lowerword == "auto-map-binding" ||
484 lowerword == "amb") {
485 Options |= EOptionAutoMapBindings;
486 } else if (lowerword == "auto-map-locations" || // synonyms
487 lowerword == "aml") {
488 Options |= EOptionAutoMapLocations;
489 } else if (lowerword == "uniform-base") {
491 Error("no <base> provided", lowerword.c_str());
492 uniformBase = ::strtol(argv[1], NULL, 10);
495 } else if (lowerword == "client") {
497 if (strcmp(argv[1], "vulkan100") == 0)
499 else if (strcmp(argv[1], "opengl100") == 0)
502 Error("expects vulkan100 or opengl100", lowerword.c_str());
504 Error("expects vulkan100 or opengl100", lowerword.c_str());
506 } else if (lowerword == "define-macro" ||
509 UserPreamble.addDef(argv[1]);
511 Error("expects <name[=def]>", argv[0]);
513 } else if (lowerword == "dump-builtin-symbols") {
514 DumpBuiltinSymbols = true;
515 } else if (lowerword == "entry-point") {
516 entryPointName = argv[1];
518 Error("no <name> provided", lowerword.c_str());
520 } else if (lowerword == "flatten-uniform-arrays" || // synonyms
521 lowerword == "flatten-uniform-array" ||
522 lowerword == "fua") {
523 Options |= EOptionFlattenUniformArrays;
524 } else if (lowerword == "hlsl-offsets") {
525 Options |= EOptionHlslOffsets;
526 } else if (lowerword == "hlsl-iomap" ||
527 lowerword == "hlsl-iomapper" ||
528 lowerword == "hlsl-iomapping") {
529 Options |= EOptionHlslIoMapping;
530 } else if (lowerword == "hlsl-enable-16bit-types") {
531 HlslEnable16BitTypes = true;
532 } else if (lowerword == "hlsl-dx9-compatible") {
533 HlslDX9compatible = true;
534 } else if (lowerword == "invert-y" || // synonyms
536 Options |= EOptionInvertY;
537 } else if (lowerword == "keep-uncalled" || // synonyms
539 Options |= EOptionKeepUncalled;
540 } else if (lowerword == "nan-clamp") {
542 } else if (lowerword == "no-storage-format" || // synonyms
543 lowerword == "nsf") {
544 Options |= EOptionNoStorageFormat;
545 } else if (lowerword == "relaxed-errors") {
546 Options |= EOptionRelaxedErrors;
547 } else if (lowerword == "reflect-strict-array-suffix") {
548 ReflectOptions |= EShReflectionStrictArraySuffix;
549 } else if (lowerword == "reflect-basic-array-suffix") {
550 ReflectOptions |= EShReflectionBasicArraySuffix;
551 } else if (lowerword == "reflect-intermediate-io") {
552 ReflectOptions |= EShReflectionIntermediateIO;
553 } else if (lowerword == "reflect-separate-buffers") {
554 ReflectOptions |= EShReflectionSeparateBuffers;
555 } else if (lowerword == "reflect-all-block-variables") {
556 ReflectOptions |= EShReflectionAllBlockVariables;
557 } else if (lowerword == "reflect-unwrap-io-blocks") {
558 ReflectOptions |= EShReflectionUnwrapIOBlocks;
559 } else if (lowerword == "reflect-all-io-variables") {
560 ReflectOptions |= EShReflectionAllIOVariables;
561 } else if (lowerword == "reflect-shared-std140-ubo") {
562 ReflectOptions |= EShReflectionSharedStd140UBO;
563 } else if (lowerword == "reflect-shared-std140-ssbo") {
564 ReflectOptions |= EShReflectionSharedStd140SSBO;
565 } else if (lowerword == "resource-set-bindings" || // synonyms
566 lowerword == "resource-set-binding" ||
567 lowerword == "rsb") {
568 ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
569 } else if (lowerword == "shift-image-bindings" || // synonyms
570 lowerword == "shift-image-binding" ||
571 lowerword == "sib") {
572 ProcessBindingBase(argc, argv, glslang::EResImage);
573 } else if (lowerword == "shift-sampler-bindings" || // synonyms
574 lowerword == "shift-sampler-binding" ||
575 lowerword == "ssb") {
576 ProcessBindingBase(argc, argv, glslang::EResSampler);
577 } else if (lowerword == "shift-uav-bindings" || // synonyms
578 lowerword == "shift-uav-binding" ||
579 lowerword == "suavb") {
580 ProcessBindingBase(argc, argv, glslang::EResUav);
581 } else if (lowerword == "shift-texture-bindings" || // synonyms
582 lowerword == "shift-texture-binding" ||
583 lowerword == "stb") {
584 ProcessBindingBase(argc, argv, glslang::EResTexture);
585 } else if (lowerword == "shift-ubo-bindings" || // synonyms
586 lowerword == "shift-ubo-binding" ||
587 lowerword == "shift-cbuffer-bindings" ||
588 lowerword == "shift-cbuffer-binding" ||
589 lowerword == "sub" ||
590 lowerword == "scb") {
591 ProcessBindingBase(argc, argv, glslang::EResUbo);
592 } else if (lowerword == "shift-ssbo-bindings" || // synonyms
593 lowerword == "shift-ssbo-binding" ||
594 lowerword == "sbb") {
595 ProcessBindingBase(argc, argv, glslang::EResSsbo);
596 } else if (lowerword == "source-entrypoint" || // synonyms
597 lowerword == "sep") {
599 Error("no <entry-point> provided", lowerword.c_str());
600 sourceEntryPointName = argv[1];
603 } else if (lowerword == "spirv-dis") {
604 SpvToolsDisassembler = true;
605 } else if (lowerword == "spirv-val") {
606 SpvToolsValidate = true;
607 } else if (lowerword == "stdin") {
608 Options |= EOptionStdin;
609 shaderStageName = argv[1];
610 } else if (lowerword == "suppress-warnings") {
611 Options |= EOptionSuppressWarnings;
612 } else if (lowerword == "target-env") {
614 if (strcmp(argv[1], "vulkan1.0") == 0) {
616 ClientVersion = glslang::EShTargetVulkan_1_0;
617 } else if (strcmp(argv[1], "vulkan1.1") == 0) {
619 ClientVersion = glslang::EShTargetVulkan_1_1;
620 } else if (strcmp(argv[1], "vulkan1.2") == 0) {
622 ClientVersion = glslang::EShTargetVulkan_1_2;
623 } else if (strcmp(argv[1], "opengl") == 0) {
625 ClientVersion = glslang::EShTargetOpenGL_450;
626 } else if (strcmp(argv[1], "spirv1.0") == 0) {
627 TargetLanguage = glslang::EShTargetSpv;
628 TargetVersion = glslang::EShTargetSpv_1_0;
629 } else if (strcmp(argv[1], "spirv1.1") == 0) {
630 TargetLanguage = glslang::EShTargetSpv;
631 TargetVersion = glslang::EShTargetSpv_1_1;
632 } else if (strcmp(argv[1], "spirv1.2") == 0) {
633 TargetLanguage = glslang::EShTargetSpv;
634 TargetVersion = glslang::EShTargetSpv_1_2;
635 } else if (strcmp(argv[1], "spirv1.3") == 0) {
636 TargetLanguage = glslang::EShTargetSpv;
637 TargetVersion = glslang::EShTargetSpv_1_3;
638 } else if (strcmp(argv[1], "spirv1.4") == 0) {
639 TargetLanguage = glslang::EShTargetSpv;
640 TargetVersion = glslang::EShTargetSpv_1_4;
641 } else if (strcmp(argv[1], "spirv1.5") == 0) {
642 TargetLanguage = glslang::EShTargetSpv;
643 TargetVersion = glslang::EShTargetSpv_1_5;
645 Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2, opengl,\n"
646 "spirv1.0, spirv1.1, spirv1.2, spirv1.3, spirv1.4, or spirv1.5");
649 } else if (lowerword == "undef-macro" ||
652 UserPreamble.addUndef(argv[1]);
654 Error("expects <name>", argv[0]);
656 } else if (lowerword == "variable-name" || // synonyms
658 Options |= EOptionOutputHexadecimal;
660 Error("no <C-variable-name> provided", lowerword.c_str());
661 variableName = argv[1];
664 } else if (lowerword == "version") {
665 Options |= EOptionDumpVersions;
666 } else if (lowerword == "help") {
670 Error("unrecognized command-line option", argv[0]);
675 Options |= EOptionCascadingErrors;
679 Options |= EOptionReadHlsl;
681 UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
684 uniformLocationOverrides.push_back(getUniformOverride());
687 Options |= EOptionOutputPreprocessed;
693 ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
696 Options |= EOptionHumanReadableSpv;
697 if ((Options & EOptionSpv) == 0) {
703 IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
706 if (argv[0][2] == 'd')
707 Options |= EOptionOptimizeDisable;
708 else if (argv[0][2] == 's')
710 Options |= EOptionOptimizeSize;
712 Error("-Os not available; optimizer not linked");
715 Error("unknown -O option");
719 Error("no <stage> specified for -S");
720 shaderStageName = argv[1];
724 UserPreamble.addUndef(getStringOperand("-U<name>"));
729 ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
732 Options |= EOptionDumpConfig;
735 if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
736 strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
737 Options |= EOptionDumpBareVersion;
739 Options |= EOptionDefaultDesktop;
742 entryPointName = argv[1];
744 Error("no <name> provided for -e");
748 if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
749 targetHlslFunctionality1 = true;
751 Error("-f: expected hlsl_functionality1");
754 // Override previous -g or -g0 argument
755 stripDebugInfo = false;
756 Options &= ~EOptionDebug;
757 if (argv[0][2] == '0')
758 stripDebugInfo = true;
760 Options |= EOptionDebug;
766 Options |= EOptionIntermediate;
769 Options |= EOptionLinkProgram;
772 Options |= EOptionMemoryLeakMode;
776 Error("no <file> provided for -o");
777 binaryFileName = argv[1];
781 Options |= EOptionDumpReflection;
784 Options |= EOptionRelaxedErrors;
787 Options |= EOptionSuppressInfolog;
790 Options |= EOptionMultiThreaded;
793 Options |= EOptionDumpVersions;
796 Options |= EOptionSuppressWarnings;
799 Options |= EOptionOutputHexadecimal;
802 Error("unrecognized command-line option", argv[0]);
806 std::string name(argv[0]);
807 if (! SetConfigFile(name)) {
808 workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
813 // Make sure that -S is always specified if --stdin is specified
814 if ((Options & EOptionStdin) && shaderStageName == nullptr)
815 Error("must provide -S when --stdin is given");
817 // Make sure that -E is not specified alongside linking (which includes SPV generation)
818 // Or things that require linking
819 if (Options & EOptionOutputPreprocessed) {
820 if (Options & EOptionLinkProgram)
821 Error("can't use -E when linking is selected");
822 if (Options & EOptionDumpReflection)
823 Error("reflection requires linking, which can't be used when -E when is selected");
826 // reflection requires linking
827 if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
828 Error("reflection requires -l for linking");
830 // -o or -x makes no sense if there is no target binary
831 if (binaryFileName && (Options & EOptionSpv) == 0)
832 Error("no binary generation requested (e.g., -V)");
834 if ((Options & EOptionFlattenUniformArrays) != 0 &&
835 (Options & EOptionReadHlsl) == 0)
836 Error("uniform array flattening only valid when compiling HLSL source.");
838 // rationalize client and target language
839 if (TargetLanguage == glslang::EShTargetNone) {
840 switch (ClientVersion) {
841 case glslang::EShTargetVulkan_1_0:
842 TargetLanguage = glslang::EShTargetSpv;
843 TargetVersion = glslang::EShTargetSpv_1_0;
845 case glslang::EShTargetVulkan_1_1:
846 TargetLanguage = glslang::EShTargetSpv;
847 TargetVersion = glslang::EShTargetSpv_1_3;
849 case glslang::EShTargetVulkan_1_2:
850 TargetLanguage = glslang::EShTargetSpv;
851 TargetVersion = glslang::EShTargetSpv_1_5;
853 case glslang::EShTargetOpenGL_450:
854 TargetLanguage = glslang::EShTargetSpv;
855 TargetVersion = glslang::EShTargetSpv_1_0;
861 if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
862 Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
866 // Translate the meaningful subset of command-line options to parser-behavior options.
868 void SetMessageOptions(EShMessages& messages)
870 if (Options & EOptionRelaxedErrors)
871 messages = (EShMessages)(messages | EShMsgRelaxedErrors);
872 if (Options & EOptionIntermediate)
873 messages = (EShMessages)(messages | EShMsgAST);
874 if (Options & EOptionSuppressWarnings)
875 messages = (EShMessages)(messages | EShMsgSuppressWarnings);
876 if (Options & EOptionSpv)
877 messages = (EShMessages)(messages | EShMsgSpvRules);
878 if (Options & EOptionVulkanRules)
879 messages = (EShMessages)(messages | EShMsgVulkanRules);
880 if (Options & EOptionOutputPreprocessed)
881 messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
882 if (Options & EOptionReadHlsl)
883 messages = (EShMessages)(messages | EShMsgReadHlsl);
884 if (Options & EOptionCascadingErrors)
885 messages = (EShMessages)(messages | EShMsgCascadingErrors);
886 if (Options & EOptionKeepUncalled)
887 messages = (EShMessages)(messages | EShMsgKeepUncalled);
888 if (Options & EOptionHlslOffsets)
889 messages = (EShMessages)(messages | EShMsgHlslOffsets);
890 if (Options & EOptionDebug)
891 messages = (EShMessages)(messages | EShMsgDebugInfo);
892 if (HlslEnable16BitTypes)
893 messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
894 if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
895 messages = (EShMessages)(messages | EShMsgHlslLegalization);
896 if (HlslDX9compatible)
897 messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
898 if (DumpBuiltinSymbols)
899 messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
903 // Thread entry point, for non-linking asynchronous mode.
905 void CompileShaders(glslang::TWorklist& worklist)
907 if (Options & EOptionDebug)
908 Error("cannot generate debug information unless linking to generate code");
910 glslang::TWorkItem* workItem;
911 if (Options & EOptionStdin) {
912 if (worklist.remove(workItem)) {
913 ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), Options);
914 if (compiler == nullptr)
917 CompileFile("stdin", compiler);
919 if (! (Options & EOptionSuppressInfolog))
920 workItem->results = ShGetInfoLog(compiler);
922 ShDestruct(compiler);
925 while (worklist.remove(workItem)) {
926 ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), Options);
930 CompileFile(workItem->name.c_str(), compiler);
932 if (! (Options & EOptionSuppressInfolog))
933 workItem->results = ShGetInfoLog(compiler);
935 ShDestruct(compiler);
940 // Outputs the given string, but only if it is non-null and non-empty.
941 // This prevents erroneous newlines from appearing.
942 void PutsIfNonEmpty(const char* str)
949 // Outputs the given string to stderr, but only if it is non-null and non-empty.
950 // This prevents erroneous newlines from appearing.
951 void StderrIfNonEmpty(const char* str)
954 fprintf(stderr, "%s\n", str);
957 // Simple bundling of what makes a compilation unit for ease in passing around,
958 // and separation of handling file IO versus API (programmatic) compilation.
959 struct ShaderCompUnit {
961 static const int maxCount = 1;
962 int count; // live number of strings/names
963 const char* text[maxCount]; // memory owned/managed externally
964 std::string fileName[maxCount]; // hold's the memory, but...
965 const char* fileNameList[maxCount]; // downstream interface wants pointers
967 ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
969 ShaderCompUnit(const ShaderCompUnit& rhs)
973 for (int i = 0; i < count; ++i) {
974 fileName[i] = rhs.fileName[i];
975 text[i] = rhs.text[i];
976 fileNameList[i] = rhs.fileName[i].c_str();
980 void addString(std::string& ifileName, const char* itext)
982 assert(count < maxCount);
983 fileName[count] = ifileName;
985 fileNameList[count] = fileName[count].c_str();
991 // For linking mode: Will independently parse each compilation unit, but then put them
992 // in the same program and link them together, making at most one linked module per
995 // Uses the new C++ interface instead of the old handle-based interface.
998 void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
1000 // keep track of what to free
1001 std::list<glslang::TShader*> shaders;
1003 EShMessages messages = EShMsgDefault;
1004 SetMessageOptions(messages);
1007 // Per-shader processing...
1010 glslang::TProgram& program = *new glslang::TProgram;
1011 for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
1012 const auto &compUnit = *it;
1013 glslang::TShader* shader = new glslang::TShader(compUnit.stage);
1014 shader->setStringsWithLengthsAndNames(compUnit.text, NULL, compUnit.fileNameList, compUnit.count);
1016 shader->setEntryPoint(entryPointName);
1017 if (sourceEntryPointName) {
1018 if (entryPointName == nullptr)
1019 printf("Warning: Changing source entry point name without setting an entry-point name.\n"
1020 "Use '-e <name>'.\n");
1021 shader->setSourceEntryPoint(sourceEntryPointName);
1023 if (UserPreamble.isSet())
1024 shader->setPreamble(UserPreamble.get());
1025 shader->addProcesses(Processes);
1028 // Set IO mapper binding shift values
1029 for (int r = 0; r < glslang::EResCount; ++r) {
1030 const glslang::TResourceType res = glslang::TResourceType(r);
1032 // Set base bindings
1033 shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
1035 // Set bindings for particular resource sets
1036 // TODO: use a range based for loop here, when available in all environments.
1037 for (auto i = baseBindingForSet[res][compUnit.stage].begin();
1038 i != baseBindingForSet[res][compUnit.stage].end(); ++i)
1039 shader->setShiftBindingForSet(res, i->second, i->first);
1041 shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
1042 shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
1044 if (Options & EOptionAutoMapBindings)
1045 shader->setAutoMapBindings(true);
1047 if (Options & EOptionAutoMapLocations)
1048 shader->setAutoMapLocations(true);
1050 for (auto& uniOverride : uniformLocationOverrides) {
1051 shader->addUniformLocationOverride(uniOverride.first.c_str(),
1052 uniOverride.second);
1055 shader->setUniformLocationBase(uniformBase);
1058 shader->setNanMinMaxClamp(NaNClamp);
1061 shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
1062 if (Options & EOptionHlslIoMapping)
1063 shader->setHlslIoMapping(true);
1066 if (Options & EOptionInvertY)
1067 shader->setInvertY(true);
1069 // Set up the environment, some subsettings take precedence over earlier
1070 // ways of setting things.
1071 if (Options & EOptionSpv) {
1072 shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
1073 : glslang::EShSourceGlsl,
1074 compUnit.stage, Client, ClientInputSemanticsVersion);
1075 shader->setEnvClient(Client, ClientVersion);
1076 shader->setEnvTarget(TargetLanguage, TargetVersion);
1078 if (targetHlslFunctionality1)
1079 shader->setEnvTargetHlslFunctionality1();
1083 shaders.push_back(shader);
1085 const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
1087 DirStackFileIncluder includer;
1088 std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
1089 includer.pushExternalLocalDirectory(dir); });
1091 if (Options & EOptionOutputPreprocessed) {
1093 if (shader->preprocess(&Resources, defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
1094 PutsIfNonEmpty(str.c_str());
1096 CompileFailed = true;
1098 StderrIfNonEmpty(shader->getInfoLog());
1099 StderrIfNonEmpty(shader->getInfoDebugLog());
1104 if (! shader->parse(&Resources, defaultVersion, false, messages, includer))
1105 CompileFailed = true;
1107 program.addShader(shader);
1109 if (! (Options & EOptionSuppressInfolog) &&
1110 ! (Options & EOptionMemoryLeakMode)) {
1111 PutsIfNonEmpty(compUnit.fileName[0].c_str());
1112 PutsIfNonEmpty(shader->getInfoLog());
1113 PutsIfNonEmpty(shader->getInfoDebugLog());
1118 // Program-level processing...
1122 if (! (Options & EOptionOutputPreprocessed) && ! program.link(messages))
1127 if (Options & EOptionSpv) {
1128 if (!program.mapIO())
1134 if (! (Options & EOptionSuppressInfolog) &&
1135 ! (Options & EOptionMemoryLeakMode)) {
1136 PutsIfNonEmpty(program.getInfoLog());
1137 PutsIfNonEmpty(program.getInfoDebugLog());
1142 if (Options & EOptionDumpReflection) {
1143 program.buildReflection(ReflectOptions);
1144 program.dumpReflection();
1149 if (Options & EOptionSpv) {
1150 if (CompileFailed || LinkFailed)
1151 printf("SPIR-V is not generated for failed compile or link\n");
1153 for (int stage = 0; stage < EShLangCount; ++stage) {
1154 if (program.getIntermediate((EShLanguage)stage)) {
1155 std::vector<unsigned int> spirv;
1156 spv::SpvBuildLogger logger;
1157 glslang::SpvOptions spvOptions;
1158 if (Options & EOptionDebug)
1159 spvOptions.generateDebugInfo = true;
1160 else if (stripDebugInfo)
1161 spvOptions.stripDebugInfo = true;
1162 spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
1163 spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
1164 spvOptions.disassemble = SpvToolsDisassembler;
1165 spvOptions.validate = SpvToolsValidate;
1166 glslang::GlslangToSpv(*program.getIntermediate((EShLanguage)stage), spirv, &logger, &spvOptions);
1168 // Dump the spv to a file or stdout, etc., but only if not doing
1169 // memory/perf testing, as it's not internal to programmatic use.
1170 if (! (Options & EOptionMemoryLeakMode)) {
1171 printf("%s", logger.getAllMessages().c_str());
1172 if (Options & EOptionOutputHexadecimal) {
1173 glslang::OutputSpvHex(spirv, GetBinaryName((EShLanguage)stage), variableName);
1175 glslang::OutputSpvBin(spirv, GetBinaryName((EShLanguage)stage));
1178 if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
1179 spv::Disassemble(std::cout, spirv);
1187 // Free everything up, program has to go before the shaders
1188 // because it might have merged stuff from the shaders, and
1189 // the stuff from the shaders has to have its destructors called
1190 // before the pools holding the memory in the shaders is freed.
1192 while (shaders.size() > 0) {
1193 delete shaders.back();
1199 // Do file IO part of compile and link, handing off the pure
1200 // API/programmatic mode to CompileAndLinkShaderUnits(), which can
1201 // be put in a loop for testing memory footprint and performance.
1203 // This is just for linking mode: meaning all the shaders will be put into the
1204 // the same program linked together.
1206 // This means there are a limited number of work items (not multi-threading mode)
1207 // and that the point is testing at the linking level. Hence, to enable
1208 // performance and memory testing, the actual compile/link can be put in
1209 // a loop, independent of processing the work items and file IO.
1211 void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
1213 std::vector<ShaderCompUnit> compUnits;
1215 // If this is using stdin, we can't really detect multiple different file
1216 // units by input type. We need to assume that we're just being given one
1217 // file of a certain type.
1218 if ((Options & EOptionStdin) != 0) {
1219 ShaderCompUnit compUnit(FindLanguage("stdin"));
1220 std::istreambuf_iterator<char> begin(std::cin), end;
1221 std::string tempString(begin, end);
1222 char* fileText = strdup(tempString.c_str());
1223 std::string fileName = "stdin";
1224 compUnit.addString(fileName, fileText);
1225 compUnits.push_back(compUnit);
1227 // Transfer all the work items from to a simple list of
1228 // of compilation units. (We don't care about the thread
1229 // work-item distribution properties in this path, which
1230 // is okay due to the limited number of shaders, know since
1231 // they are all getting linked together.)
1232 glslang::TWorkItem* workItem;
1233 while (Worklist.remove(workItem)) {
1234 ShaderCompUnit compUnit(FindLanguage(workItem->name));
1235 char* fileText = ReadFileData(workItem->name.c_str());
1236 if (fileText == nullptr)
1238 compUnit.addString(workItem->name, fileText);
1239 compUnits.push_back(compUnit);
1243 // Actual call to programmatic processing of compile and link,
1244 // in a loop for testing memory and performance. This part contains
1245 // all the perf/memory that a programmatic consumer will care about.
1246 for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1247 for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
1248 CompileAndLinkShaderUnits(compUnits);
1250 if (Options & EOptionMemoryLeakMode)
1251 glslang::OS_DumpMemoryCounters();
1254 // free memory from ReadFileData, which got stored in a const char*
1255 // as the first string above
1256 for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
1257 FreeFileData(const_cast<char*>(it->text[0]));
1262 glslang::TWorklist workList;
1263 std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
1265 workList.add(item.get());
1269 if (Options & EOptionDumpConfig) {
1270 printf("%s", glslang::GetDefaultTBuiltInResourceString().c_str());
1271 if (workList.empty())
1276 if (Options & EOptionDumpBareVersion) {
1277 printf("%d.%d.%d\n",
1278 glslang::GetSpirvGeneratorVersion(), GLSLANG_MINOR_VERSION, GLSLANG_PATCH_LEVEL);
1279 if (workList.empty())
1281 } else if (Options & EOptionDumpVersions) {
1282 printf("Glslang Version: %d.%d.%d\n",
1283 glslang::GetSpirvGeneratorVersion(), GLSLANG_MINOR_VERSION, GLSLANG_PATCH_LEVEL);
1284 printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
1285 printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
1286 std::string spirvVersion;
1287 glslang::GetSpirvVersion(spirvVersion);
1288 printf("SPIR-V Version %s\n", spirvVersion.c_str());
1289 printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
1290 printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
1291 printf("SPIR-V Generator Version %d\n", glslang::GetSpirvGeneratorVersion());
1292 printf("GL_KHR_vulkan_glsl version %d\n", 100);
1293 printf("ARB_GL_gl_spirv version %d\n", 100);
1294 if (workList.empty())
1298 if (workList.empty() && ((Options & EOptionStdin) == 0)) {
1302 if (Options & EOptionStdin) {
1303 WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
1304 workList.add(WorkItems.back().get());
1307 ProcessConfigFile();
1309 if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
1310 Error("HLSL requires SPIR-V code generation (or preprocessing only)");
1314 // 1) linking all arguments together, single-threaded, new C++ interface
1315 // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
1317 if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
1318 glslang::InitializeProcess();
1319 glslang::InitializeProcess(); // also test reference counting of users
1320 glslang::InitializeProcess(); // also test reference counting of users
1321 glslang::FinalizeProcess(); // also test reference counting of users
1322 glslang::FinalizeProcess(); // also test reference counting of users
1323 CompileAndLinkShaderFiles(workList);
1324 glslang::FinalizeProcess();
1327 ShInitialize(); // also test reference counting of users
1328 ShFinalize(); // also test reference counting of users
1330 bool printShaderNames = workList.size() > 1;
1332 if (Options & EOptionMultiThreaded) {
1333 std::array<std::thread, 16> threads;
1334 for (unsigned int t = 0; t < threads.size(); ++t) {
1335 threads[t] = std::thread(CompileShaders, std::ref(workList));
1336 if (threads[t].get_id() == std::thread::id()) {
1337 fprintf(stderr, "Failed to create thread\n");
1338 return EFailThreadCreate;
1342 std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
1344 CompileShaders(workList);
1346 // Print out all the resulting infologs
1347 for (size_t w = 0; w < WorkItems.size(); ++w) {
1349 if (printShaderNames || WorkItems[w]->results.size() > 0)
1350 PutsIfNonEmpty(WorkItems[w]->name.c_str());
1351 PutsIfNonEmpty(WorkItems[w]->results.c_str());
1359 return EFailCompile;
1366 int C_DECL main(int argc, char* argv[])
1368 ProcessArguments(WorkItems, argc, argv);
1372 // Loop over the entire init/finalize cycle to watch memory changes
1373 const int iterations = 1;
1375 glslang::OS_DumpMemoryCounters();
1376 for (int i = 0; i < iterations; ++i) {
1379 glslang::OS_DumpMemoryCounters();
1386 // Deduce the language from the filename. Files must end in one of the
1387 // following extensions:
1390 // .tesc = tessellation control
1391 // .tese = tessellation evaluation
1395 // .rgen = ray generation
1396 // .rint = ray intersection
1397 // .rahit = ray any hit
1398 // .rchit = ray closest hit
1399 // .rmiss = ray miss
1400 // .rcall = ray callable
1403 // Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
1404 // where <stage> is one of the stages listed above.
1406 EShLanguage FindLanguage(const std::string& name, bool parseStageName)
1408 std::string stageName;
1409 if (shaderStageName)
1410 stageName = shaderStageName;
1411 else if (parseStageName) {
1412 // Note: "first" extension means "first from the end", i.e.
1413 // if the file is named foo.vert.glsl, then "glsl" is first,
1414 // "vert" is second.
1415 size_t firstExtStart = name.find_last_of(".");
1416 bool hasFirstExt = firstExtStart != std::string::npos;
1417 size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
1418 bool hasSecondExt = secondExtStart != std::string::npos;
1419 std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
1420 bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
1421 if (usesUnifiedExt && firstExt == "hlsl")
1422 Options |= EOptionReadHlsl;
1423 if (hasFirstExt && !usesUnifiedExt)
1424 stageName = firstExt;
1425 else if (usesUnifiedExt && hasSecondExt)
1426 stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
1429 return EShLangVertex;
1434 if (stageName == "vert")
1435 return EShLangVertex;
1436 else if (stageName == "tesc")
1437 return EShLangTessControl;
1438 else if (stageName == "tese")
1439 return EShLangTessEvaluation;
1440 else if (stageName == "geom")
1441 return EShLangGeometry;
1442 else if (stageName == "frag")
1443 return EShLangFragment;
1444 else if (stageName == "comp")
1445 return EShLangCompute;
1446 else if (stageName == "rgen")
1447 return EShLangRayGen;
1448 else if (stageName == "rint")
1449 return EShLangIntersect;
1450 else if (stageName == "rahit")
1451 return EShLangAnyHit;
1452 else if (stageName == "rchit")
1453 return EShLangClosestHit;
1454 else if (stageName == "rmiss")
1456 else if (stageName == "rcall")
1457 return EShLangCallable;
1458 else if (stageName == "mesh")
1459 return EShLangMeshNV;
1460 else if (stageName == "task")
1461 return EShLangTaskNV;
1464 return EShLangVertex;
1468 // Read a file's data into a string, and compile it using the old interface ShCompile,
1469 // for non-linkable results.
1471 void CompileFile(const char* fileName, ShHandle compiler)
1475 if ((Options & EOptionStdin) != 0) {
1476 std::istreambuf_iterator<char> begin(std::cin), end;
1477 std::string tempString(begin, end);
1478 shaderString = strdup(tempString.c_str());
1480 shaderString = ReadFileData(fileName);
1483 // move to length-based strings, rather than null-terminated strings
1484 int* lengths = new int[1];
1485 lengths[0] = (int)strlen(shaderString);
1487 EShMessages messages = EShMsgDefault;
1488 SetMessageOptions(messages);
1490 if (UserPreamble.isSet())
1491 Error("-D and -U options require -l (linking)\n");
1493 for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1494 for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
1495 // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1496 ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1497 // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
1498 // "or should be l", "ine 1", "string 5\n", "float glo", "bal",
1499 // ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
1500 // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
1501 // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1504 if (Options & EOptionMemoryLeakMode)
1505 glslang::OS_DumpMemoryCounters();
1509 FreeFileData(shaderString);
1512 CompileFailed = true;
1516 // print usage to stdout
1520 printf("Usage: glslangValidator [option]... [file]...\n"
1522 "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
1523 " .conf to provide a config file that replaces the default configuration\n"
1524 " (see -c option below for generating a template)\n"
1525 " .vert for a vertex shader\n"
1526 " .tesc for a tessellation control shader\n"
1527 " .tese for a tessellation evaluation shader\n"
1528 " .geom for a geometry shader\n"
1529 " .frag for a fragment shader\n"
1530 " .comp for a compute shader\n"
1531 " .mesh for a mesh shader\n"
1532 " .task for a task shader\n"
1533 " .rgen for a ray generation shader\n"
1534 " .rint for a ray intersection shader\n"
1535 " .rahit for a ray any hit shader\n"
1536 " .rchit for a ray closest hit shader\n"
1537 " .rmiss for a ray miss shader\n"
1538 " .rcall for a ray callable shader\n"
1539 " .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
1540 " .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
1543 " -C cascading errors; risk crash from accumulation of error recoveries\n"
1544 " -D input is HLSL (this is the default when any suffix is .hlsl)\n"
1545 " -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]>\n"
1546 " define a pre-processor macro\n"
1547 " -E print pre-processed GLSL; cannot be used with -l;\n"
1548 " errors will appear on stderr\n"
1549 " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
1550 " default file name is <stage>.spv (-o overrides this);\n"
1551 " 'ver', when present, is the version of the input semantics,\n"
1552 " which will appear in #define GL_SPIRV ver;\n"
1553 " '--client opengl100' is the same as -G100;\n"
1554 " a '--target-env' for OpenGL will also imply '-G'\n"
1555 " -H print human readable form of SPIR-V; turns on -V\n"
1556 " -I<dir> add dir to the include search path; includer's directory\n"
1557 " is searched first, followed by left-to-right order of -I\n"
1558 " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
1559 " -Os optimizes SPIR-V to minimize size\n"
1560 " -S <stage> uses specified stage rather than parsing the file extension\n"
1561 " choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
1562 " -U<name> | --undef-macro <name> | --U <name>\n"
1563 " undefine a pre-processor macro\n"
1564 " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
1565 " default file name is <stage>.spv (-o overrides this)\n"
1566 " 'ver', when present, is the version of the input semantics,\n"
1567 " which will appear in #define VULKAN ver\n"
1568 " '--client vulkan100' is the same as -V100\n"
1569 " a '--target-env' for Vulkan will also imply '-V'\n"
1570 " -c configuration dump;\n"
1571 " creates the default configuration file (redirect to a .conf file)\n"
1572 " -d default to desktop (#version 110) when there is no shader #version\n"
1573 " (default is ES version 100)\n"
1574 " -e <name> | --entry-point <name>\n"
1575 " specify <name> as the entry-point function name\n"
1576 " -f{hlsl_functionality1}\n"
1577 " 'hlsl_functionality1' enables use of the\n"
1578 " SPV_GOOGLE_hlsl_functionality1 extension\n"
1579 " -g generate debug information\n"
1580 " -g0 strip debug information\n"
1581 " -h print this usage message\n"
1582 " -i intermediate tree (glslang AST) is printed out\n"
1583 " -l link all input files together to form a single module\n"
1584 " -m memory leak mode\n"
1585 " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
1586 " -q dump reflection query database; requires -l for linking\n"
1587 " -r | --relaxed-errors"
1588 " relaxed GLSL semantic error-checking mode\n"
1589 " -s silence syntax and semantic error reporting\n"
1590 " -t multi-threaded mode\n"
1592 " print version strings\n"
1593 " -w | --suppress-warnings\n"
1594 " suppress GLSL warnings, except as required by \"#extension : warn\"\n"
1595 " -x save binary output as text-based 32-bit hexadecimal numbers\n"
1596 " -u<name>:<loc> specify a uniform location override for --aml\n"
1597 " --uniform-base <base> set a base to use for generated uniform locations\n"
1598 " --auto-map-bindings | --amb automatically bind uniform variables\n"
1599 " without explicit bindings\n"
1600 " --auto-map-locations | --aml automatically locate input/output lacking\n"
1601 " 'location' (fragile, not cross stage)\n"
1602 " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
1603 " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
1604 " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
1605 " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
1607 " --hlsl-offsets allow block offsets to follow HLSL rules\n"
1608 " works independently of source language\n"
1609 " --hlsl-iomap perform IO mapping in HLSL register space\n"
1610 " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
1611 " --hlsl-dx9-compatible interprets sampler declarations as a\n"
1612 " texture/sampler combo like DirectX9 would,\n"
1613 " and recognizes DirectX9-specific semantics\n"
1614 " --invert-y | --iy invert position.Y output in vertex shader\n"
1615 " --keep-uncalled | --ku don't eliminate uncalled functions\n"
1616 " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
1617 " --no-storage-format | --nsf use Unknown image format\n"
1618 " --reflect-strict-array-suffix use strict array suffix rules when\n"
1620 " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
1621 " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
1622 " shaders rather than just vertex/fragment\n"
1623 " --reflect-separate-buffers reflect buffer variables and blocks\n"
1624 " separately to uniforms\n"
1625 " --reflect-all-block-variables reflect all variables in blocks, whether\n"
1626 " inactive or active\n"
1627 " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
1629 " --resource-set-binding [stage] name set binding\n"
1630 " set descriptor set and binding for\n"
1631 " individual resources\n"
1632 " --resource-set-binding [stage] set\n"
1633 " set descriptor set for all resources\n"
1634 " --rsb synonym for --resource-set-binding\n"
1635 " --shift-image-binding [stage] num\n"
1636 " base binding number for images (uav)\n"
1637 " --shift-image-binding [stage] [num set]...\n"
1638 " per-descriptor-set shift values\n"
1639 " --sib synonym for --shift-image-binding\n"
1640 " --shift-sampler-binding [stage] num\n"
1641 " base binding number for samplers\n"
1642 " --shift-sampler-binding [stage] [num set]...\n"
1643 " per-descriptor-set shift values\n"
1644 " --ssb synonym for --shift-sampler-binding\n"
1645 " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
1646 " --shift-ssbo-binding [stage] [num set]...\n"
1647 " per-descriptor-set shift values\n"
1648 " --sbb synonym for --shift-ssbo-binding\n"
1649 " --shift-texture-binding [stage] num\n"
1650 " base binding number for textures\n"
1651 " --shift-texture-binding [stage] [num set]...\n"
1652 " per-descriptor-set shift values\n"
1653 " --stb synonym for --shift-texture-binding\n"
1654 " --shift-uav-binding [stage] num base binding number for UAVs\n"
1655 " --shift-uav-binding [stage] [num set]...\n"
1656 " per-descriptor-set shift values\n"
1657 " --suavb synonym for --shift-uav-binding\n"
1658 " --shift-UBO-binding [stage] num base binding number for UBOs\n"
1659 " --shift-UBO-binding [stage] [num set]...\n"
1660 " per-descriptor-set shift values\n"
1661 " --sub synonym for --shift-UBO-binding\n"
1662 " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
1663 " --spirv-dis output standard-form disassembly; works only\n"
1664 " when a SPIR-V generation option is also used\n"
1665 " --spirv-val execute the SPIRV-Tools validator\n"
1666 " --source-entrypoint <name> the given shader source function is\n"
1667 " renamed to be the <name> given in -e\n"
1668 " --sep synonym for --source-entrypoint\n"
1669 " --stdin read from stdin instead of from a file;\n"
1670 " requires providing the shader stage using -S\n"
1671 " --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | opengl | \n"
1672 " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 | spirv1.5}\n"
1673 " Set the execution environment that the\n"
1674 " generated code will be executed in.\n"
1676 " * vulkan1.0 under --client vulkan<ver>\n"
1677 " * opengl under --client opengl<ver>\n"
1678 " * spirv1.0 under --target-env vulkan1.0\n"
1679 " * spirv1.3 under --target-env vulkan1.1\n"
1680 " * spirv1.5 under --target-env vulkan1.2\n"
1681 " Multiple --target-env can be specified.\n"
1682 " --variable-name <name>\n"
1683 " --vn <name> creates a C header file that contains a\n"
1684 " uint32_t array named <name>\n"
1685 " initialized with the shader binary code\n"
1691 #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
1697 const char* filename,
1701 if (!pFile || !filename || !mode) {
1705 FILE* f = fopen(filename, mode);
1721 // Malloc a string of sufficient size and read a string into it.
1723 char* ReadFileData(const char* fileName)
1726 int errorCode = fopen_s(&in, fileName, "r");
1727 if (errorCode || in == nullptr)
1728 Error("unable to open input file");
1731 while (fgetc(in) != EOF)
1734 fseek(in, 0, SEEK_SET);
1736 char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
1737 if ((int)fread(return_data, 1, count, in) != count) {
1739 Error("can't read input file");
1742 return_data[count] = '\0';
1748 void FreeFileData(char* data)
1753 void InfoLogMsg(const char* msg, const char* name, const int num)
1756 printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
1758 printf("#### %s %s INFO LOG ####\n", msg, name);