yum-mirror/glslang

git clone https://git.yummers.dev/yum-mirror/glslang

mmmhj2Implement <system> include for the standalone wrapper (#4154)b11b0383

vulkan-sdk-1.4.350.0
94.5 KiB2291 linesraw
1//
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.
6//
7// All rights reserved.
8//
9// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions
11// are met:
12//
13//    Redistributions of source code must retain the above copyright
14//    notice, this list of conditions and the following disclaimer.
15//
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.
20//
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.
24//
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.
37//
38
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
42#endif
43
44#include "glslang/Public/ResourceLimits.h"
45#include "Worklist.h"
46#include "DirStackFileIncluder.h"
47#include "./../glslang/Public/ShaderLang.h"
48#include "../glslang/MachineIndependent/localintermediate.h"
49#include "../SPIRV/GlslangToSpv.h"
50#include "../SPIRV/GLSL.std.450.h"
51#include "../SPIRV/disassemble.h"
52
53#include <array>
54#include <atomic>
55#include <cctype>
56#include <cmath>
57#include <cstdlib>
58#include <cstring>
59#include <iterator>
60#include <map>
61#include <memory>
62#include <set>
63#include <thread>
64#include <type_traits>
65
66#include "../glslang/OSDependent/osinclude.h"
67
68// Build-time generated includes
69#include "glslang/build_info.h"
70
71#include "glslang/glsl_intrinsic_header.h"
72
73extern "C" {
74    GLSLANG_EXPORT void ShOutputHtml();
75}
76
77// Command-line options
78enum TOptions : uint64_t {
79    EOptionNone = 0,
80    EOptionIntermediate = (1ull << 0),
81    EOptionSuppressInfolog = (1ull << 1),
82    EOptionMemoryLeakMode = (1ull << 2),
83    EOptionRelaxedErrors = (1ull << 3),
84    EOptionGiveWarnings = (1ull << 4),
85    EOptionLinkProgram = (1ull << 5),
86    EOptionMultiThreaded = (1ull << 6),
87    EOptionDumpConfig = (1ull << 7),
88    EOptionDumpReflection = (1ull << 8),
89    EOptionSuppressWarnings = (1ull << 9),
90    EOptionDumpVersions = (1ull << 10),
91    EOptionSpv = (1ull << 11),
92    EOptionHumanReadableSpv = (1ull << 12),
93    EOptionVulkanRules = (1ull << 13),
94    EOptionDefaultDesktop = (1ull << 14),
95    EOptionOutputPreprocessed = (1ull << 15),
96    EOptionOutputHexadecimal = (1ull << 16),
97    EOptionReadHlsl = (1ull << 17),
98    EOptionCascadingErrors = (1ull << 18),
99    EOptionAutoMapBindings = (1ull << 19),
100    EOptionFlattenUniformArrays = (1ull << 20),
101    EOptionNoStorageFormat = (1ull << 21),
102    EOptionKeepUncalled = (1ull << 22),
103    EOptionHlslOffsets = (1ull << 23),
104    EOptionHlslIoMapping = (1ull << 24),
105    EOptionAutoMapLocations = (1ull << 25),
106    EOptionDebug = (1ull << 26),
107    EOptionStdin = (1ull << 27),
108    EOptionOptimizeDisable = (1ull << 28),
109    EOptionOptimizeSize = (1ull << 29),
110    EOptionInvertY = (1ull << 30),
111    EOptionDumpBareVersion = (1ull << 31),
112    EOptionCompileOnly = (1ull << 32),
113    EOptionDisplayErrorColumn = (1ull << 33),
114    EOptionLinkTimeOptimization = (1ull << 34),
115    EOptionValidateCrossStageIO = (1ull << 35),
116    EOptionBindingsPerResourceType = (1ull << 36),
117};
118bool targetHlslFunctionality1 = false;
119bool SpvToolsDisassembler = false;
120bool SpvToolsValidate = false;
121bool NaNClamp = false;
122bool stripDebugInfo = false;
123bool emitNonSemanticShaderDebugInfo = false;
124bool emitNonSemanticShaderDebugSource = false;
125bool beQuiet = false;
126bool VulkanRulesRelaxed = false;
127bool autoSampledTextures = false;
128
129//
130// Return codes from main/exit().
131//
132enum TFailCode {
133    ESuccess = 0,
134    EFailUsage,
135    EFailCompile,
136    EFailLink,
137    EFailCompilerCreate,
138    EFailThreadCreate,
139    EFailLinkerCreate
140};
141
142//
143// Forward declarations.
144//
145EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
146void CompileFile(const char* fileName, ShHandle);
147void usage();
148char* ReadFileData(const char* fileName);
149void FreeFileData(char* data);
150void InfoLogMsg(const char* msg, const char* name, const int num);
151
152// Globally track if any compile or link failure.
153std::atomic<int8_t> CompileFailed{0};
154std::atomic<int8_t> LinkFailed{0};
155std::atomic<int8_t> CompileOrLinkFailed{0};
156
157// array of unique places to leave the shader names and infologs for the asynchronous compiles
158std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
159
160std::string ConfigFile;
161
162//
163// Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
164//
165void ProcessConfigFile()
166{
167    if (ConfigFile.size() == 0)
168        *GetResources() = *GetDefaultResources();
169    else {
170        char* configString = ReadFileData(ConfigFile.c_str());
171        DecodeResourceLimits(GetResources(),  configString);
172        FreeFileData(configString);
173    }
174}
175
176int ReflectOptions = EShReflectionDefault;
177std::underlying_type_t<TOptions> Options = EOptionNone;
178const char* ExecutableName = nullptr;
179const char* binaryFileName = nullptr;
180const char* depencyFileName = nullptr;
181const char* entryPointName = nullptr;
182const char* sourceEntryPointName = nullptr;
183const char* shaderStageName = nullptr;
184const char* variableName = nullptr;
185bool HlslEnable16BitTypes = false;
186bool HlslDX9compatible = false;
187bool HlslDxPositionW = false;
188bool EnhancedMsgs = false;
189bool AbsolutePath = false;
190bool DumpBuiltinSymbols = false;
191std::vector<std::string> IncludeDirectoryList;
192
193// Source environment
194// (source 'Client' is currently the same as target 'Client')
195int ClientInputSemanticsVersion = 100;
196
197// Target environment
198glslang::EShClient Client = glslang::EShClientNone;  // will stay EShClientNone if only validating
199glslang::EShTargetClientVersion ClientVersion;       // not valid until Client is set
200glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
201glslang::EShTargetLanguageVersion TargetVersion;     // not valid until TargetLanguage is set
202
203// GLSL version
204int GlslVersion = 0; // GLSL version specified on CLI, overrides #version in shader source
205
206std::vector<std::string> Processes;                     // what should be recorded by OpModuleProcessed, or equivalent
207
208// Per descriptor-set binding base data
209typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
210
211std::vector<std::pair<std::string, int>> uniformLocationOverrides;
212int uniformBase = 0;
213
214std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
215std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
216std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
217
218std::vector<std::pair<std::string, glslang::TBlockStorageClass>> blockStorageOverrides;
219
220bool setGlobalUniformBlock = false;
221std::string globalUniformName;
222unsigned int globalUniformBinding;
223unsigned int globalUniformSet;
224
225bool setGlobalBufferBlock = false;
226std::string atomicCounterBlockName;
227unsigned int atomicCounterBlockSet;
228
229// Add things like "#define ..." to a preamble to use in the beginning of the shader.
230class TPreamble {
231public:
232    TPreamble() { }
233
234    bool isSet() const { return text.size() > 0; }
235    const char* get() const { return text.c_str(); }
236
237    // #define...
238    void addDef(std::string def)
239    {
240        text.append("#define ");
241        fixLine(def);
242
243        Processes.push_back("define-macro ");
244        Processes.back().append(def);
245
246        // The first "=" needs to turn into a space
247        const size_t equal = def.find_first_of("=");
248        if (equal != def.npos)
249            def[equal] = ' ';
250
251        text.append(def);
252        text.append("\n");
253    }
254
255    // #undef...
256    void addUndef(std::string undef)
257    {
258        text.append("#undef ");
259        fixLine(undef);
260
261        Processes.push_back("undef-macro ");
262        Processes.back().append(undef);
263
264        text.append(undef);
265        text.append("\n");
266    }
267
268    void addText(std::string preambleText)
269    {
270        fixLine(preambleText);
271
272        Processes.push_back("preamble-text");
273        Processes.back().append(preambleText);
274
275        text.append(preambleText);
276        text.append("\n");
277    }
278
279protected:
280    void fixLine(std::string& line)
281    {
282        // Can't go past a newline in the line
283        const size_t end = line.find_first_of("\n");
284        if (end != line.npos)
285            line = line.substr(0, end);
286    }
287
288    std::string text;  // contents of preamble
289};
290
291// Track the user's #define and #undef from the command line.
292TPreamble UserPreamble;
293std::string PreambleString;
294
295//
296// Create the default name for saving a binary if -o is not provided.
297//
298const char* GetBinaryName(EShLanguage stage)
299{
300    const char* name;
301    if (binaryFileName == nullptr) {
302        switch (stage) {
303        case EShLangVertex:          name = "vert.spv";    break;
304        case EShLangTessControl:     name = "tesc.spv";    break;
305        case EShLangTessEvaluation:  name = "tese.spv";    break;
306        case EShLangGeometry:        name = "geom.spv";    break;
307        case EShLangFragment:        name = "frag.spv";    break;
308        case EShLangCompute:         name = "comp.spv";    break;
309        case EShLangRayGen:          name = "rgen.spv";    break;
310        case EShLangIntersect:       name = "rint.spv";    break;
311        case EShLangAnyHit:          name = "rahit.spv";   break;
312        case EShLangClosestHit:      name = "rchit.spv";   break;
313        case EShLangMiss:            name = "rmiss.spv";   break;
314        case EShLangCallable:        name = "rcall.spv";   break;
315        case EShLangMesh :           name = "mesh.spv";    break;
316        case EShLangTask :           name = "task.spv";    break;
317        default:                     name = "unknown";     break;
318        }
319    } else
320        name = binaryFileName;
321
322    return name;
323}
324
325//
326// *.conf => this is a config file that can set limits/resources
327//
328bool SetConfigFile(const std::string& name)
329{
330    if (name.size() < 5)
331        return false;
332
333    if (name.compare(name.size() - 5, 5, ".conf") == 0) {
334        ConfigFile = name;
335        return true;
336    }
337
338    return false;
339}
340
341//
342// Give error and exit with failure code.
343//
344void Error(const char* message, const char* detail = nullptr)
345{
346    fprintf(stderr, "%s: Error: ", ExecutableName);
347    if (detail != nullptr)
348        fprintf(stderr, "%s: ", detail);
349    fprintf(stderr, "%s (use -h for usage)\n", message);
350    exit(EFailUsage);
351}
352
353//
354// Process an optional binding base of one the forms:
355//   --argname [stage] base            // base for stage (if given) or all stages (if not)
356//   --argname [stage] [base set]...   // set/base pairs: set the base for given binding set.
357
358// Where stage is one of the forms accepted by FindLanguage, and base is an integer
359//
360void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
361{
362    if (argc < 2)
363        usage();
364
365    EShLanguage lang = EShLangCount;
366    int singleBase = 0;
367    TPerSetBaseBinding perSetBase;
368    int arg = 1;
369
370    // Parse stage, if given
371    if (!isdigit(argv[arg][0])) {
372        if (argc < 3) // this form needs one more argument
373            usage();
374
375        lang = FindLanguage(argv[arg++], false);
376    }
377
378    if ((argc - arg) >= 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
379        // Parse a per-set binding base
380        do {
381            const int baseNum = atoi(argv[arg++]);
382            const int setNum = atoi(argv[arg++]);
383            perSetBase[setNum] = baseNum;
384        } while ((argc - arg) >= 2 && isdigit(argv[arg + 0][0]) && isdigit(argv[arg + 1][0]));
385    } else {
386        // Parse single binding base
387        singleBase = atoi(argv[arg++]);
388    }
389
390    argc -= (arg-1);
391    argv += (arg-1);
392
393    // Set one or all languages
394    const int langMin = (lang < EShLangCount) ? lang+0 : 0;
395    const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
396
397    for (int lang = langMin; lang < langMax; ++lang) {
398        if (!perSetBase.empty())
399            baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
400        else
401            baseBinding[res][lang] = singleBase;
402    }
403}
404
405void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
406{
407    if (argc < 2)
408        usage();
409
410    if (!isdigit(argv[1][0])) {
411        if (argc < 3) // this form needs one more argument
412            usage();
413
414        // Parse form: --argname stage [regname set base...], or:
415        //             --argname stage set
416        const EShLanguage lang = FindLanguage(argv[1], false);
417
418        argc--;
419        argv++;
420
421        while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
422            base[lang].push_back(argv[1]);
423
424            argc--;
425            argv++;
426        }
427
428        // Must have one arg, or a multiple of three (for [regname set binding] triples)
429        if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
430            usage();
431
432    } else {
433        // Parse form: --argname set
434        for (int lang=0; lang<EShLangCount; ++lang)
435            base[lang].push_back(argv[1]);
436
437        argc--;
438        argv++;
439    }
440}
441
442//
443// Process an optional binding base of one the forms:
444//   --argname name {uniform|buffer|push_constant}
445void ProcessBlockStorage(int& argc, char**& argv, std::vector<std::pair<std::string, glslang::TBlockStorageClass>>& storage)
446{
447    if (argc < 3)
448        usage();
449
450    glslang::TBlockStorageClass blockStorage = glslang::EbsNone;
451
452    std::string strBacking(argv[2]);
453    if (strBacking == "uniform")
454        blockStorage = glslang::EbsUniform;
455    else if (strBacking == "buffer")
456        blockStorage = glslang::EbsStorageBuffer;
457    else if (strBacking == "push_constant")
458        blockStorage = glslang::EbsPushConstant;
459    else {
460        printf("%s: invalid block storage\n", strBacking.c_str());
461        usage();
462    }
463
464    storage.push_back(std::make_pair(std::string(argv[1]), blockStorage));
465
466    argc -= 2;
467    argv += 2;
468}
469
470inline bool isNonDigit(char c) {
471    // a non-digit character valid in a glsl identifier
472    return (c == '_') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
473}
474
475// whether string isa  valid identifier to be used in glsl
476bool isValidIdentifier(const char* str) {
477    std::string idn(str);
478
479    if (idn.length() == 0) {
480        return false;
481    }
482
483    if (idn.length() >= 3 && idn.substr(0, 3) == "gl_") {
484        // identifiers startin with "gl_" are reserved
485        return false;
486    }
487
488    if (!isNonDigit(idn[0])) {
489        return false;
490    }
491
492    for (unsigned int i = 1; i < idn.length(); ++i) {
493        if (!(isdigit(idn[i]) || isNonDigit(idn[i]))) {
494            return false;
495        }
496    }
497
498    return true;
499}
500
501// Process settings for either the global buffer block or global unfirom block
502// of the form:
503//      --argname name set binding
504void ProcessGlobalBlockSettings(int& argc, char**& argv, std::string* name, unsigned int* set, unsigned int* binding)
505{
506    if (argc < 4)
507        usage();
508
509    unsigned int curArg = 1;
510
511    assert(name || set || binding);
512
513    if (name) {
514        if (!isValidIdentifier(argv[curArg])) {
515            printf("%s: invalid identifier\n", argv[curArg]);
516            usage();
517        }
518        *name = argv[curArg];
519
520        curArg++;
521    }
522
523    if (set) {
524        errno = 0;
525        int setVal = static_cast<int>(::strtol(argv[curArg], nullptr, 10));
526        if (errno || setVal < 0) {
527            printf("%s: invalid set\n", argv[curArg]);
528            usage();
529        }
530        *set = setVal;
531
532        curArg++;
533    }
534
535    if (binding) {
536        errno = 0;
537        int bindingVal = static_cast<int>(::strtol(argv[curArg], nullptr, 10));
538        if (errno || bindingVal < 0) {
539            printf("%s: invalid binding\n", argv[curArg]);
540            usage();
541        }
542        *binding = bindingVal;
543
544        curArg++;
545    }
546
547    argc -= (curArg - 1);
548    argv += (curArg - 1);
549}
550
551//
552// Do all command-line argument parsing.  This includes building up the work-items
553// to be processed later, and saving all the command-line options.
554//
555// Does not return (it exits) if command-line is fatally flawed.
556//
557void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
558{
559    for (int res = 0; res < glslang::EResCount; ++res)
560        baseBinding[res].fill(0);
561
562    ExecutableName = argv[0];
563    workItems.reserve(argc);
564
565    const auto bumpArg = [&]() {
566        if (argc > 0) {
567            argc--;
568            argv++;
569        }
570    };
571
572    // read a string directly attached to a single-letter option
573    const auto getStringOperand = [&](const char* desc) {
574        if (argv[0][2] == 0) {
575            printf("%s must immediately follow option (no spaces)\n", desc);
576            exit(EFailUsage);
577        }
578        return argv[0] + 2;
579    };
580
581    // read a number attached to a single-letter option
582    const auto getAttachedNumber = [&](const char* desc) {
583        int num = atoi(argv[0] + 2);
584        if (num == 0) {
585            printf("%s: expected attached non-0 number\n", desc);
586            exit(EFailUsage);
587        }
588        return num;
589    };
590
591    // minimum needed (without overriding something else) to target Vulkan SPIR-V
592    const auto setVulkanSpv = []() {
593        if (Client == glslang::EShClientNone)
594            ClientVersion = glslang::EShTargetVulkan_1_0;
595        Client = glslang::EShClientVulkan;
596        Options |= EOptionSpv;
597        Options |= EOptionVulkanRules;
598        Options |= EOptionLinkProgram;
599    };
600
601    // minimum needed (without overriding something else) to target OpenGL SPIR-V
602    const auto setOpenGlSpv = []() {
603        if (Client == glslang::EShClientNone)
604            ClientVersion = glslang::EShTargetOpenGL_450;
605        Client = glslang::EShClientOpenGL;
606        Options |= EOptionSpv;
607        Options |= EOptionLinkProgram;
608        // undo a -H default to Vulkan
609        Options &= ~EOptionVulkanRules;
610    };
611
612    const auto getUniformOverride = [getStringOperand]() {
613        const char *arg = getStringOperand("-u<name>:<location>");
614        const char *split = strchr(arg, ':');
615        if (split == nullptr) {
616            printf("%s: missing location\n", arg);
617            exit(EFailUsage);
618        }
619        errno = 0;
620        int location = static_cast<int>(::strtol(split + 1, nullptr, 10));
621        if (errno) {
622            printf("%s: invalid location\n", arg);
623            exit(EFailUsage);
624        }
625        return std::make_pair(std::string(arg, split - arg), location);
626    };
627
628    for (bumpArg(); argc >= 1; bumpArg()) {
629        if (argv[0][0] == '-') {
630            switch (argv[0][1]) {
631            case '-':
632                {
633                    std::string lowerword(argv[0]+2);
634                    std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
635
636                    // handle --word style options
637                    if (lowerword == "auto-map-bindings" ||  // synonyms
638                        lowerword == "auto-map-binding"  ||
639                        lowerword == "amb") {
640                        Options |= EOptionAutoMapBindings;
641                    } else if (lowerword == "auto-map-locations" || // synonyms
642                               lowerword == "aml") {
643                        Options |= EOptionAutoMapLocations;
644                    } else if (lowerword == "uniform-base") {
645                        if (argc <= 1)
646                            Error("no <base> provided", lowerword.c_str());
647                        uniformBase = static_cast<int>(::strtol(argv[1], nullptr, 10));
648                        bumpArg();
649                        break;
650                    } else if (lowerword == "client") {
651                        if (argc > 1) {
652                            if (strcmp(argv[1], "vulkan100") == 0)
653                                setVulkanSpv();
654                            else if (strcmp(argv[1], "opengl100") == 0)
655                                setOpenGlSpv();
656                            else
657                                Error("expects vulkan100 or opengl100", lowerword.c_str());
658                        } else
659                            Error("expects vulkan100 or opengl100", lowerword.c_str());
660                        bumpArg();
661                    } else if (lowerword == "define-macro" ||
662                               lowerword == "d") {
663                        if (argc > 1)
664                            UserPreamble.addDef(argv[1]);
665                        else
666                            Error("expects <name[=def]>", argv[0]);
667                        bumpArg();
668                    } else if (lowerword == "dump-builtin-symbols") {
669                        DumpBuiltinSymbols = true;
670                    } else if (lowerword == "entry-point") {
671                        entryPointName = argv[1];
672                        if (argc <= 1)
673                            Error("no <name> provided", lowerword.c_str());
674                        bumpArg();
675                    } else if (lowerword == "flatten-uniform-arrays" || // synonyms
676                               lowerword == "flatten-uniform-array"  ||
677                               lowerword == "fua") {
678                        Options |= EOptionFlattenUniformArrays;
679                    } else if (lowerword == "glsl-version") {
680                        if (argc > 1) {
681                            if (strcmp(argv[1], "100") == 0) {
682                                GlslVersion = 100;
683                            } else if (strcmp(argv[1], "110") == 0) {
684                                GlslVersion = 110;
685                            } else if (strcmp(argv[1], "120") == 0) {
686                                GlslVersion = 120;
687                            } else if (strcmp(argv[1], "130") == 0) {
688                                GlslVersion = 130;
689                            } else if (strcmp(argv[1], "140") == 0) {
690                                GlslVersion = 140;
691                            } else if (strcmp(argv[1], "150") == 0) {
692                                GlslVersion = 150;
693                            } else if (strcmp(argv[1], "300es") == 0) {
694                                GlslVersion = 300;
695                            } else if (strcmp(argv[1], "310es") == 0) {
696                                GlslVersion = 310;
697                            } else if (strcmp(argv[1], "320es") == 0) {
698                                GlslVersion = 320;
699                            } else if (strcmp(argv[1], "330") == 0) {
700                                GlslVersion = 330;
701                            } else if (strcmp(argv[1], "400") == 0) {
702                                GlslVersion = 400;
703                            } else if (strcmp(argv[1], "410") == 0) {
704                                GlslVersion = 410;
705                            } else if (strcmp(argv[1], "420") == 0) {
706                                GlslVersion = 420;
707                            } else if (strcmp(argv[1], "430") == 0) {
708                                GlslVersion = 430;
709                            } else if (strcmp(argv[1], "440") == 0) {
710                                GlslVersion = 440;
711                            } else if (strcmp(argv[1], "450") == 0) {
712                                GlslVersion = 450;
713                            } else if (strcmp(argv[1], "460") == 0) {
714                                GlslVersion = 460;
715                            } else
716                                Error("--glsl-version expected one of: 100, 110, 120, 130, 140, 150,\n"
717                                      "300es, 310es, 320es, 330\n"
718                                      "400, 410, 420, 430, 440, 450, 460");
719                        }
720                        bumpArg();
721                    } else if (lowerword == "hlsl-offsets") {
722                        Options |= EOptionHlslOffsets;
723                    } else if (lowerword == "hlsl-iomap" ||
724                               lowerword == "hlsl-iomapper" ||
725                               lowerword == "hlsl-iomapping") {
726                        Options |= EOptionHlslIoMapping;
727                    } else if (lowerword == "hlsl-enable-16bit-types") {
728                        HlslEnable16BitTypes = true;
729                    } else if (lowerword == "hlsl-dx9-compatible") {
730                        HlslDX9compatible = true;
731                    } else if (lowerword == "hlsl-dx-position-w") {
732                        HlslDxPositionW = true;
733                    } else if (lowerword == "enhanced-msgs") {
734                        EnhancedMsgs = true;
735                    } else if (lowerword == "absolute-path") {
736                        AbsolutePath = true;
737                    } else if (lowerword == "auto-sampled-textures") {
738                        autoSampledTextures = true;
739                    } else if (lowerword == "invert-y" ||  // synonyms
740                               lowerword == "iy") {
741                        Options |= EOptionInvertY;
742                    } else if (lowerword == "keep-uncalled" || // synonyms
743                               lowerword == "ku") {
744                        Options |= EOptionKeepUncalled;
745                    } else if (lowerword == "nan-clamp") {
746                        NaNClamp = true;
747                    } else if (lowerword == "no-storage-format" || // synonyms
748                               lowerword == "nsf") {
749                        Options |= EOptionNoStorageFormat;
750                    } else if (lowerword == "preamble-text" ||
751                               lowerword == "p") {
752                        if (argc > 1)
753                            UserPreamble.addText(argv[1]);
754                        else
755                            Error("expects <text>", argv[0]);
756                        bumpArg();
757                    } else if (lowerword == "relaxed-errors") {
758                        Options |= EOptionRelaxedErrors;
759                    } else if (lowerword == "reflect-strict-array-suffix") {
760                        ReflectOptions |= EShReflectionStrictArraySuffix;
761                    } else if (lowerword == "reflect-basic-array-suffix") {
762                        ReflectOptions |= EShReflectionBasicArraySuffix;
763                    } else if (lowerword == "reflect-intermediate-io") {
764                        ReflectOptions |= EShReflectionIntermediateIO;
765                    } else if (lowerword == "reflect-separate-buffers") {
766                        ReflectOptions |= EShReflectionSeparateBuffers;
767                    } else if (lowerword == "reflect-all-block-variables") {
768                        ReflectOptions |= EShReflectionAllBlockVariables;
769                    } else if (lowerword == "reflect-unwrap-io-blocks") {
770                        ReflectOptions |= EShReflectionUnwrapIOBlocks;
771                    } else if (lowerword == "reflect-all-io-variables") {
772                        ReflectOptions |= EShReflectionAllIOVariables;
773                    } else if (lowerword == "reflect-shared-std140-ubo") {
774                        ReflectOptions |= EShReflectionSharedStd140UBO;
775                    } else if (lowerword == "reflect-shared-std140-ssbo") {
776                        ReflectOptions |= EShReflectionSharedStd140SSBO;
777                    } else if (lowerword == "resource-set-bindings" ||  // synonyms
778                               lowerword == "resource-set-binding"  ||
779                               lowerword == "rsb") {
780                        ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
781                    } else if (lowerword == "set-block-storage" ||
782                               lowerword == "sbs") {
783                        ProcessBlockStorage(argc, argv, blockStorageOverrides);
784                    } else if (lowerword == "set-atomic-counter-block" ||
785                               lowerword == "sacb") {
786                        ProcessGlobalBlockSettings(argc, argv, &atomicCounterBlockName, &atomicCounterBlockSet, nullptr);
787                        setGlobalBufferBlock = true;
788                    } else if (lowerword == "set-default-uniform-block" ||
789                               lowerword == "sdub") {
790                        ProcessGlobalBlockSettings(argc, argv, &globalUniformName, &globalUniformSet, &globalUniformBinding);
791                        setGlobalUniformBlock = true;
792                    } else if (lowerword == "shift-image-bindings" ||  // synonyms
793                               lowerword == "shift-image-binding"  ||
794                               lowerword == "sib") {
795                        ProcessBindingBase(argc, argv, glslang::EResImage);
796                    } else if (lowerword == "shift-sampler-bindings" || // synonyms
797                               lowerword == "shift-sampler-binding"  ||
798                               lowerword == "ssb") {
799                        ProcessBindingBase(argc, argv, glslang::EResSampler);
800                    } else if (lowerword == "shift-uav-bindings" ||  // synonyms
801                               lowerword == "shift-uav-binding"  ||
802                               lowerword == "suavb") {
803                        ProcessBindingBase(argc, argv, glslang::EResUav);
804                    } else if (lowerword == "shift-texture-bindings" ||  // synonyms
805                               lowerword == "shift-texture-binding"  ||
806                               lowerword == "stb") {
807                        ProcessBindingBase(argc, argv, glslang::EResTexture);
808                    } else if (lowerword == "shift-ubo-bindings" ||  // synonyms
809                               lowerword == "shift-ubo-binding"  ||
810                               lowerword == "shift-cbuffer-bindings" ||
811                               lowerword == "shift-cbuffer-binding"  ||
812                               lowerword == "sub" ||
813                               lowerword == "scb") {
814                        ProcessBindingBase(argc, argv, glslang::EResUbo);
815                    } else if (lowerword == "shift-ssbo-bindings" ||  // synonyms
816                               lowerword == "shift-ssbo-binding"  ||
817                               lowerword == "sbb") {
818                        ProcessBindingBase(argc, argv, glslang::EResSsbo);
819                    } else if (lowerword == "shift-combined-sampler-bindings" ||
820                               lowerword == "shift-combined-sampler-binding" ||
821                               lowerword == "scsb") {
822                        ProcessBindingBase(argc, argv, glslang::EResCombinedSampler);
823                    } else if (lowerword == "shift-as-bindings" ||
824                               lowerword == "shift-as-binding" ||
825                               lowerword == "sab") {
826                        ProcessBindingBase(argc, argv, glslang::EResAs);
827                    } else if (lowerword == "source-entrypoint" || // synonyms
828                               lowerword == "sep") {
829                        if (argc <= 1)
830                            Error("no <entry-point> provided", lowerword.c_str());
831                        sourceEntryPointName = argv[1];
832                        bumpArg();
833                        break;
834                    } else if (lowerword == "spirv-dis") {
835                        SpvToolsDisassembler = true;
836                    } else if (lowerword == "spirv-val") {
837                        SpvToolsValidate = true;
838                    } else if (lowerword == "stdin") {
839                        Options |= EOptionStdin;
840                        shaderStageName = argv[1];
841                    } else if (lowerword == "suppress-warnings") {
842                        Options |= EOptionSuppressWarnings;
843                    } else if (lowerword == "target-env") {
844                        if (argc > 1) {
845                            if (strcmp(argv[1], "vulkan1.0") == 0) {
846                                setVulkanSpv();
847                                ClientVersion = glslang::EShTargetVulkan_1_0;
848                            } else if (strcmp(argv[1], "vulkan1.1") == 0) {
849                                setVulkanSpv();
850                                ClientVersion = glslang::EShTargetVulkan_1_1;
851                            } else if (strcmp(argv[1], "vulkan1.2") == 0) {
852                                setVulkanSpv();
853                                ClientVersion = glslang::EShTargetVulkan_1_2;
854                            } else if (strcmp(argv[1], "vulkan1.3") == 0) {
855                                setVulkanSpv();
856                                ClientVersion = glslang::EShTargetVulkan_1_3;
857                            } else if (strcmp(argv[1], "vulkan1.4") == 0) {
858                                setVulkanSpv();
859                                ClientVersion = glslang::EShTargetVulkan_1_4;
860                            } else if (strcmp(argv[1], "opengl") == 0) {
861                                setOpenGlSpv();
862                                ClientVersion = glslang::EShTargetOpenGL_450;
863                            } else if (strcmp(argv[1], "spirv1.0") == 0) {
864                                TargetLanguage = glslang::EShTargetSpv;
865                                TargetVersion = glslang::EShTargetSpv_1_0;
866                            } else if (strcmp(argv[1], "spirv1.1") == 0) {
867                                TargetLanguage = glslang::EShTargetSpv;
868                                TargetVersion = glslang::EShTargetSpv_1_1;
869                            } else if (strcmp(argv[1], "spirv1.2") == 0) {
870                                TargetLanguage = glslang::EShTargetSpv;
871                                TargetVersion = glslang::EShTargetSpv_1_2;
872                            } else if (strcmp(argv[1], "spirv1.3") == 0) {
873                                TargetLanguage = glslang::EShTargetSpv;
874                                TargetVersion = glslang::EShTargetSpv_1_3;
875                            } else if (strcmp(argv[1], "spirv1.4") == 0) {
876                                TargetLanguage = glslang::EShTargetSpv;
877                                TargetVersion = glslang::EShTargetSpv_1_4;
878                            } else if (strcmp(argv[1], "spirv1.5") == 0) {
879                                TargetLanguage = glslang::EShTargetSpv;
880                                TargetVersion = glslang::EShTargetSpv_1_5;
881                            } else if (strcmp(argv[1], "spirv1.6") == 0) {
882                                TargetLanguage = glslang::EShTargetSpv;
883                                TargetVersion = glslang::EShTargetSpv_1_6;
884                            } else
885                                Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2,\n"
886                                      "vulkan1.3, vulkan1.4, opengl, spirv1.0, spirv1.1, spirv1.2, spirv1.3,\n"
887                                      "spirv1.4, spirv1.5 or spirv1.6");
888                        }
889                        bumpArg();
890                    } else if (lowerword == "undef-macro" ||
891                               lowerword == "u") {
892                        if (argc > 1)
893                            UserPreamble.addUndef(argv[1]);
894                        else
895                            Error("expects <name>", argv[0]);
896                        bumpArg();
897                    } else if (lowerword == "variable-name" || // synonyms
898                               lowerword == "vn") {
899                        Options |= EOptionOutputHexadecimal;
900                        if (argc <= 1)
901                            Error("no <C-variable-name> provided", lowerword.c_str());
902                        variableName = argv[1];
903                        bumpArg();
904                        break;
905                    } else if (lowerword == "quiet") {
906                        beQuiet = true;
907                    } else if (lowerword == "depfile") {
908                        if (argc <= 1)
909                            Error("no <depfile-name> provided", lowerword.c_str());
910                        depencyFileName = argv[1];
911                        bumpArg();
912                    } else if (lowerword == "version") {
913                        Options |= EOptionDumpVersions;
914                    } else if (lowerword == "no-link") {
915                        Options |= EOptionCompileOnly;
916                    } else if (lowerword == "error-column") {
917                        Options |= EOptionDisplayErrorColumn;
918                    } else if (lowerword == "lto") {
919                        Options |= EOptionLinkTimeOptimization;
920                    } else if (lowerword == "validate-io") {
921                        Options |= EOptionValidateCrossStageIO;
922                    } else if (lowerword == "bindings-per-resource-type") {
923                        Options |= EOptionBindingsPerResourceType;
924                    } else if (lowerword == "help") {
925                        usage();
926                        break;
927                    } else {
928                        Error("unrecognized command-line option", argv[0]);
929                    }
930                }
931                break;
932            case 'C':
933                Options |= EOptionCascadingErrors;
934                break;
935            case 'D':
936                if (argv[0][2] == 0)
937                    Options |= EOptionReadHlsl;
938                else
939                    UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
940                break;
941            case 'u':
942                uniformLocationOverrides.push_back(getUniformOverride());
943                break;
944            case 'E':
945                Options |= EOptionOutputPreprocessed;
946                break;
947            case 'G':
948                // OpenGL client
949                setOpenGlSpv();
950                if (argv[0][2] != 0)
951                    ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
952                if (ClientInputSemanticsVersion != 100)
953                    Error("unknown client version for -G, should be 100");
954                break;
955            case 'H':
956                Options |= EOptionHumanReadableSpv;
957                if ((Options & EOptionSpv) == 0) {
958                    // default to Vulkan
959                    setVulkanSpv();
960                }
961                break;
962            case 'I':
963                IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
964                break;
965            case 'O':
966                if (argv[0][2] == 'd')
967                    Options |= EOptionOptimizeDisable;
968                else if (argv[0][2] == 's')
969#if ENABLE_OPT
970                    Options |= EOptionOptimizeSize;
971#else
972                    Error("-Os not available; optimizer not linked");
973#endif
974                else
975                    Error("unknown -O option");
976                break;
977            case 'P':
978                UserPreamble.addText(getStringOperand("-P<text>"));
979                break;
980            case 'R':
981                VulkanRulesRelaxed = true;
982                break;
983            case 'S':
984                if (argc <= 1)
985                    Error("no <stage> specified for -S");
986                shaderStageName = argv[1];
987                bumpArg();
988                break;
989            case 'U':
990                UserPreamble.addUndef(getStringOperand("-U<name>"));
991                break;
992            case 'V':
993                setVulkanSpv();
994                if (argv[0][2] != 0)
995                    ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
996                if (ClientInputSemanticsVersion != 100)
997                    Error("unknown client version for -V, should be 100");
998                break;
999            case 'c':
1000                Options |= EOptionDumpConfig;
1001                break;
1002            case 'd':
1003                if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
1004                    strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
1005                    Options |= EOptionDumpBareVersion;
1006                else
1007                    Options |= EOptionDefaultDesktop;
1008                break;
1009            case 'e':
1010                entryPointName = argv[1];
1011                if (argc <= 1)
1012                    Error("no <name> provided for -e");
1013                bumpArg();
1014                break;
1015            case 'f':
1016                if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
1017                    targetHlslFunctionality1 = true;
1018                else
1019                    Error("-f: expected hlsl_functionality1");
1020                break;
1021            case 'g':
1022                // Override previous -g or -g0 argument
1023                stripDebugInfo = false;
1024                emitNonSemanticShaderDebugInfo = false;
1025                Options &= ~EOptionDebug;
1026                if (argv[0][2] == '0')
1027                    stripDebugInfo = true;
1028                else {
1029                    Options |= EOptionDebug;
1030                    if (argv[0][2] == 'V') {
1031                        emitNonSemanticShaderDebugInfo = true;
1032                        if (argv[0][3] == 'S') {
1033                            emitNonSemanticShaderDebugSource = true;
1034                        } else {
1035                            emitNonSemanticShaderDebugSource = false;
1036                        }
1037                    }
1038                }
1039                break;
1040            case 'h':
1041                usage();
1042                break;
1043            case 'i':
1044                Options |= EOptionIntermediate;
1045                break;
1046            case 'l':
1047                Options |= EOptionLinkProgram;
1048                break;
1049            case 'm':
1050                Options |= EOptionMemoryLeakMode;
1051                break;
1052            case 'o':
1053                if (argc <= 1)
1054                    Error("no <file> provided for -o");
1055                binaryFileName = argv[1];
1056                bumpArg();
1057                break;
1058            case 'q':
1059                Options |= EOptionDumpReflection;
1060                break;
1061            case 'r':
1062                Options |= EOptionRelaxedErrors;
1063                break;
1064            case 's':
1065                Options |= EOptionSuppressInfolog;
1066                break;
1067            case 't':
1068                Options |= EOptionMultiThreaded;
1069                break;
1070            case 'v':
1071                Options |= EOptionDumpVersions;
1072                break;
1073            case 'w':
1074                Options |= EOptionSuppressWarnings;
1075                break;
1076            case 'x':
1077                Options |= EOptionOutputHexadecimal;
1078                break;
1079            default:
1080                Error("unrecognized command-line option", argv[0]);
1081                break;
1082            }
1083        } else {
1084            std::string name(argv[0]);
1085            if (! SetConfigFile(name)) {
1086                workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
1087            }
1088        }
1089    }
1090
1091    // Make sure that -S is always specified if --stdin is specified
1092    if ((Options & EOptionStdin) && shaderStageName == nullptr)
1093        Error("must provide -S when --stdin is given");
1094
1095    // Make sure that -E is not specified alongside linking (which includes SPV generation)
1096    // Or things that require linking
1097    if (Options & EOptionOutputPreprocessed) {
1098        if (Options & EOptionLinkProgram)
1099            Error("can't use -E when linking is selected");
1100        if (Options & EOptionDumpReflection)
1101            Error("reflection requires linking, which can't be used when -E when is selected");
1102    }
1103
1104    // reflection requires linking
1105    if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
1106        Error("reflection requires -l for linking");
1107
1108    // link time optimization makes no sense unless linking
1109    if ((Options & EOptionLinkTimeOptimization) && !(Options & EOptionLinkProgram))
1110        Error("link time optimization requires -l for linking");
1111
1112    // cross stage IO validation makes no sense unless linking
1113    if ((Options & EOptionValidateCrossStageIO) && !(Options & EOptionLinkProgram))
1114        Error("cross stage IO validation requires -l for linking");
1115
1116    // -o or -x makes no sense if there is no target binary
1117    if (binaryFileName && (Options & EOptionSpv) == 0)
1118        Error("no binary generation requested (e.g., -V)");
1119
1120    if ((Options & EOptionFlattenUniformArrays) != 0 &&
1121        (Options & EOptionReadHlsl) == 0)
1122        Error("uniform array flattening only valid when compiling HLSL source.");
1123
1124    if ((Options & EOptionReadHlsl) && (Client == glslang::EShClientOpenGL)) {
1125        Error("Using HLSL input under OpenGL semantics is not currently supported.");
1126    }
1127
1128    // rationalize client and target language
1129    if (TargetLanguage == glslang::EShTargetNone) {
1130        switch (ClientVersion) {
1131        case glslang::EShTargetVulkan_1_0:
1132            TargetLanguage = glslang::EShTargetSpv;
1133            TargetVersion = glslang::EShTargetSpv_1_0;
1134            break;
1135        case glslang::EShTargetVulkan_1_1:
1136            TargetLanguage = glslang::EShTargetSpv;
1137            TargetVersion = glslang::EShTargetSpv_1_3;
1138            break;
1139        case glslang::EShTargetVulkan_1_2:
1140            TargetLanguage = glslang::EShTargetSpv;
1141            TargetVersion = glslang::EShTargetSpv_1_5;
1142            break;
1143        case glslang::EShTargetVulkan_1_3:
1144            TargetLanguage = glslang::EShTargetSpv;
1145            TargetVersion = glslang::EShTargetSpv_1_6;
1146            break;
1147        case glslang::EShTargetVulkan_1_4:
1148            TargetLanguage = glslang::EShTargetSpv;
1149            TargetVersion = glslang::EShTargetSpv_1_6;
1150            break;
1151        case glslang::EShTargetOpenGL_450:
1152            TargetLanguage = glslang::EShTargetSpv;
1153            TargetVersion = glslang::EShTargetSpv_1_0;
1154            break;
1155        default:
1156            break;
1157        }
1158    }
1159    if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
1160        Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
1161}
1162
1163//
1164// Translate the meaningful subset of command-line options to parser-behavior options.
1165//
1166void SetMessageOptions(EShMessages& messages)
1167{
1168    if (Options & EOptionRelaxedErrors)
1169        messages = (EShMessages)(messages | EShMsgRelaxedErrors);
1170    if (Options & EOptionIntermediate)
1171        messages = (EShMessages)(messages | EShMsgAST);
1172    if (Options & EOptionSuppressWarnings)
1173        messages = (EShMessages)(messages | EShMsgSuppressWarnings);
1174    if (Options & EOptionSpv)
1175        messages = (EShMessages)(messages | EShMsgSpvRules);
1176    if (Options & EOptionVulkanRules)
1177        messages = (EShMessages)(messages | EShMsgVulkanRules);
1178    if (Options & EOptionOutputPreprocessed)
1179        messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
1180    if (Options & EOptionReadHlsl)
1181        messages = (EShMessages)(messages | EShMsgReadHlsl);
1182    if (Options & EOptionCascadingErrors)
1183        messages = (EShMessages)(messages | EShMsgCascadingErrors);
1184    if (Options & EOptionKeepUncalled)
1185        messages = (EShMessages)(messages | EShMsgKeepUncalled);
1186    if (Options & EOptionHlslOffsets)
1187        messages = (EShMessages)(messages | EShMsgHlslOffsets);
1188    if (Options & EOptionDebug)
1189        messages = (EShMessages)(messages | EShMsgDebugInfo);
1190    if (HlslEnable16BitTypes)
1191        messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
1192    if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
1193        messages = (EShMessages)(messages | EShMsgHlslLegalization);
1194    if (HlslDX9compatible)
1195        messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
1196    if (DumpBuiltinSymbols)
1197        messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
1198    if (EnhancedMsgs)
1199        messages = (EShMessages)(messages | EShMsgEnhanced);
1200    if (AbsolutePath)
1201        messages = (EShMessages)(messages | EShMsgAbsolutePath);
1202    if (Options & EOptionDisplayErrorColumn)
1203        messages = (EShMessages)(messages | EShMsgDisplayErrorColumn);
1204    if (Options & EOptionLinkTimeOptimization)
1205        messages = (EShMessages)(messages | EShMsgLinkTimeOptimization);
1206    if (Options & EOptionValidateCrossStageIO)
1207        messages = (EShMessages)(messages | EShMsgValidateCrossStageIO);
1208}
1209
1210//
1211// Thread entry point, for non-linking asynchronous mode.
1212//
1213void CompileShaders(glslang::TWorklist& worklist)
1214{
1215    if (Options & EOptionDebug)
1216        Error("cannot generate debug information unless linking to generate code");
1217
1218    // NOTE: TWorkList::remove is thread-safe
1219    glslang::TWorkItem* workItem;
1220    if (Options & EOptionStdin) {
1221        if (worklist.remove(workItem)) {
1222            ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), 0);
1223            if (compiler == nullptr)
1224                return;
1225
1226            CompileFile("stdin", compiler);
1227
1228            if (! (Options & EOptionSuppressInfolog))
1229                workItem->results = ShGetInfoLog(compiler);
1230
1231            ShDestruct(compiler);
1232        }
1233    } else {
1234        while (worklist.remove(workItem)) {
1235            ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), 0);
1236            if (compiler == nullptr)
1237                return;
1238
1239
1240            CompileFile(workItem->name.c_str(), compiler);
1241
1242            if (! (Options & EOptionSuppressInfolog))
1243                workItem->results = ShGetInfoLog(compiler);
1244
1245            ShDestruct(compiler);
1246        }
1247    }
1248}
1249
1250// Outputs the given string, but only if it is non-null and non-empty.
1251// This prevents erroneous newlines from appearing.
1252void PutsIfNonEmpty(const char* str)
1253{
1254    if (str && str[0]) {
1255        puts(str);
1256    }
1257}
1258
1259// Outputs the given string to stderr, but only if it is non-null and non-empty.
1260// This prevents erroneous newlines from appearing.
1261void StderrIfNonEmpty(const char* str)
1262{
1263    if (str && str[0])
1264        fprintf(stderr, "%s\n", str);
1265}
1266
1267// Simple bundling of what makes a compilation unit for ease in passing around,
1268// and separation of handling file IO versus API (programmatic) compilation.
1269struct ShaderCompUnit {
1270    EShLanguage stage;
1271    static const int maxCount = 1;
1272    int count;                          // live number of strings/names
1273    const char* text[maxCount];         // memory owned/managed externally
1274    std::string fileName[maxCount];     // hold's the memory, but...
1275    const char* fileNameList[maxCount]; // downstream interface wants pointers
1276
1277    ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
1278
1279    ShaderCompUnit(const ShaderCompUnit& rhs)
1280    {
1281        stage = rhs.stage;
1282        count = rhs.count;
1283        for (int i = 0; i < count; ++i) {
1284            fileName[i] = rhs.fileName[i];
1285            text[i] = rhs.text[i];
1286            fileNameList[i] = rhs.fileName[i].c_str();
1287        }
1288    }
1289
1290    void addString(std::string& ifileName, const char* itext)
1291    {
1292        assert(count < maxCount);
1293        fileName[count] = ifileName;
1294        text[count] = itext;
1295        fileNameList[count] = fileName[count].c_str();
1296        ++count;
1297    }
1298};
1299
1300// Writes a string into a depfile, escaping some special characters following the Makefile rules.
1301static void writeEscapedDepString(std::ofstream& file, const std::string& str)
1302{
1303    for (char c : str) {
1304        switch (c) {
1305        case ' ':
1306        case ':':
1307        case '#':
1308        case '[':
1309        case ']':
1310        case '\\':
1311            file << '\\';
1312            break;
1313        case '$':
1314            file << '$';
1315            break;
1316        }
1317        file << c;
1318    }
1319}
1320
1321// Writes a depfile similar to gcc -MMD foo.c
1322bool writeDepFile(std::string depfile, std::vector<std::string>& binaryFiles, const std::vector<std::string>& sources)
1323{
1324    std::ofstream file(depfile);
1325    if (file.fail())
1326        return false;
1327
1328    for (auto binaryFile = binaryFiles.begin(); binaryFile != binaryFiles.end(); binaryFile++) {
1329        writeEscapedDepString(file, *binaryFile);
1330        file << ":";
1331        for (auto sourceFile = sources.begin(); sourceFile != sources.end(); sourceFile++) {
1332            file << " ";
1333            writeEscapedDepString(file, *sourceFile);
1334        }
1335        file << std::endl;
1336    }
1337    return true;
1338}
1339
1340//
1341// For linking mode: Will independently parse each compilation unit, but then put them
1342// in the same program and link them together, making at most one linked module per
1343// pipeline stage.
1344//
1345// Uses the new C++ interface instead of the old handle-based interface.
1346//
1347
1348void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
1349{
1350    // keep track of what to free
1351    std::list<glslang::TShader*> shaders;
1352
1353    EShMessages messages = EShMsgDefault;
1354    SetMessageOptions(messages);
1355
1356    DirStackFileIncluder includer;
1357    std::for_each(IncludeDirectoryList.begin(), IncludeDirectoryList.end(), [&includer](const std::string& dir) {
1358        includer.pushExternalDirectory(dir); });
1359
1360    std::vector<std::string> sources;
1361
1362    //
1363    // Per-shader processing...
1364    //
1365
1366    glslang::TProgram& program = *new glslang::TProgram;
1367    const bool compileOnly = (Options & EOptionCompileOnly) != 0;
1368    for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
1369        const auto &compUnit = *it;
1370        for (int i = 0; i < compUnit.count; i++) {
1371            sources.push_back(compUnit.fileNameList[i]);
1372        }
1373        glslang::TShader* shader = new glslang::TShader(compUnit.stage);
1374        shader->setStringsWithLengthsAndNames(compUnit.text, nullptr, compUnit.fileNameList, compUnit.count);
1375        if (entryPointName)
1376            shader->setEntryPoint(entryPointName);
1377        if (sourceEntryPointName) {
1378            if (entryPointName == nullptr)
1379                printf("Warning: Changing source entry point name without setting an entry-point name.\n"
1380                       "Use '-e <name>'.\n");
1381            shader->setSourceEntryPoint(sourceEntryPointName);
1382        }
1383
1384        if (compileOnly)
1385            shader->setCompileOnly();
1386
1387        shader->setOverrideVersion(GlslVersion);
1388
1389        std::string intrinsicString = getIntrinsic(compUnit.text, compUnit.count);
1390
1391        PreambleString = "";
1392        if (UserPreamble.isSet())
1393            PreambleString.append(UserPreamble.get());
1394
1395        if (!intrinsicString.empty())
1396            PreambleString.append(intrinsicString);
1397
1398        shader->setPreamble(PreambleString.c_str());
1399        shader->addProcesses(Processes);
1400
1401        // Set IO mapper binding shift values
1402        for (int r = 0; r < glslang::EResCount; ++r) {
1403            const glslang::TResourceType res = glslang::TResourceType(r);
1404
1405            // Set base bindings
1406            shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
1407
1408            // Set bindings for particular resource sets
1409            // TODO: use a range based for loop here, when available in all environments.
1410            for (auto i = baseBindingForSet[res][compUnit.stage].begin();
1411                 i != baseBindingForSet[res][compUnit.stage].end(); ++i)
1412                shader->setShiftBindingForSet(res, i->second, i->first);
1413        }
1414        shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
1415        shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
1416
1417        if (autoSampledTextures)
1418            shader->setTextureSamplerTransformMode(EShTexSampTransUpgradeTextureRemoveSampler);
1419
1420        if (Options & EOptionAutoMapBindings)
1421            shader->setAutoMapBindings(true);
1422
1423        if (Options & EOptionAutoMapLocations)
1424            shader->setAutoMapLocations(true);
1425
1426        for (auto& uniOverride : uniformLocationOverrides) {
1427            shader->addUniformLocationOverride(uniOverride.first.c_str(),
1428                                               uniOverride.second);
1429        }
1430
1431        shader->setUniformLocationBase(uniformBase);
1432
1433        if (VulkanRulesRelaxed) {
1434            for (auto& storageOverride : blockStorageOverrides) {
1435                shader->addBlockStorageOverride(storageOverride.first.c_str(),
1436                    storageOverride.second);
1437            }
1438
1439            if (setGlobalBufferBlock) {
1440                shader->setAtomicCounterBlockName(atomicCounterBlockName.c_str());
1441                shader->setAtomicCounterBlockSet(atomicCounterBlockSet);
1442            }
1443
1444            if (setGlobalUniformBlock) {
1445                shader->setGlobalUniformBlockName(globalUniformName.c_str());
1446                shader->setGlobalUniformSet(globalUniformSet);
1447                shader->setGlobalUniformBinding(globalUniformBinding);
1448            }
1449        }
1450
1451        shader->setNanMinMaxClamp(NaNClamp);
1452
1453#ifdef ENABLE_HLSL
1454        shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
1455        if (Options & EOptionHlslIoMapping)
1456            shader->setHlslIoMapping(true);
1457#endif
1458
1459        if (Options & EOptionInvertY)
1460            shader->setInvertY(true);
1461
1462        if (HlslDxPositionW)
1463            shader->setDxPositionW(true);
1464
1465        if (EnhancedMsgs)
1466            shader->setEnhancedMsgs();
1467
1468        if (emitNonSemanticShaderDebugInfo)
1469            shader->setDebugInfo(true);
1470
1471        if (Options & EOptionBindingsPerResourceType)
1472            shader->setBindingsPerResourceType();
1473
1474        // Set up the environment, some subsettings take precedence over earlier
1475        // ways of setting things.
1476        if (Options & EOptionSpv) {
1477            shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
1478                                                            : glslang::EShSourceGlsl,
1479                                compUnit.stage, Client, ClientInputSemanticsVersion);
1480            shader->setEnvClient(Client, ClientVersion);
1481            shader->setEnvTarget(TargetLanguage, TargetVersion);
1482#ifdef ENABLE_HLSL
1483            if (targetHlslFunctionality1)
1484                shader->setEnvTargetHlslFunctionality1();
1485#endif
1486            if (VulkanRulesRelaxed)
1487                shader->setEnvInputVulkanRulesRelaxed();
1488        }
1489
1490        shaders.push_back(shader);
1491
1492        const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
1493
1494        if (Options & EOptionOutputPreprocessed) {
1495            std::string str;
1496            if (shader->preprocess(GetResources(), defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
1497                PutsIfNonEmpty(str.c_str());
1498            } else {
1499                CompileFailed = 1;
1500            }
1501            StderrIfNonEmpty(shader->getInfoLog());
1502            StderrIfNonEmpty(shader->getInfoDebugLog());
1503            continue;
1504        }
1505
1506        if (! shader->parse(GetResources(), defaultVersion, false, messages, includer))
1507            CompileFailed = 1;
1508
1509        if (!compileOnly)
1510            program.addShader(shader);
1511
1512        if (! (Options & EOptionSuppressInfolog) &&
1513            ! (Options & EOptionMemoryLeakMode)) {
1514            if (!beQuiet)
1515                PutsIfNonEmpty(compUnit.fileName[0].c_str());
1516            PutsIfNonEmpty(shader->getInfoLog());
1517            PutsIfNonEmpty(shader->getInfoDebugLog());
1518        }
1519    }
1520
1521    //
1522    // Program-level processing...
1523    //
1524
1525    if (!compileOnly) {
1526        // Link
1527        if (!(Options & EOptionOutputPreprocessed) && !program.link(messages))
1528            LinkFailed = true;
1529
1530        // Map IO
1531        if (Options & EOptionSpv) {
1532            if (!program.mapIO())
1533                LinkFailed = true;
1534        }
1535
1536        // Report
1537        if (!(Options & EOptionSuppressInfolog) && !(Options & EOptionMemoryLeakMode)) {
1538            PutsIfNonEmpty(program.getInfoLog());
1539            PutsIfNonEmpty(program.getInfoDebugLog());
1540        }
1541
1542        // Reflect
1543        if (Options & EOptionDumpReflection) {
1544            program.buildReflection(ReflectOptions);
1545            program.dumpReflection();
1546        }
1547    }
1548
1549    std::vector<std::string> outputFiles;
1550
1551    // Dump SPIR-V
1552    if (Options & EOptionSpv) {
1553#ifdef ENABLE_SPIRV
1554        CompileOrLinkFailed.fetch_or(CompileFailed);
1555        CompileOrLinkFailed.fetch_or(LinkFailed);
1556        if (static_cast<bool>(CompileOrLinkFailed.load()))
1557            printf("SPIR-V is not generated for failed compile or link\n");
1558        else {
1559            std::vector<glslang::TIntermediate*> intermediates;
1560            if (!compileOnly) {
1561                for (int stage = 0; stage < EShLangCount; ++stage) {
1562                    if (auto* i = program.getIntermediate((EShLanguage)stage)) {
1563                        intermediates.emplace_back(i);
1564                    }
1565                }
1566            } else {
1567                for (const auto* shader : shaders) {
1568                    if (auto* i = shader->getIntermediate()) {
1569                        intermediates.emplace_back(i);
1570                    }
1571                }
1572            }
1573            for (auto* intermediate : intermediates) {
1574                std::vector<unsigned int> spirv;
1575                spv::SpvBuildLogger logger;
1576                glslang::SpvOptions spvOptions;
1577                if (Options & EOptionDebug) {
1578                    spvOptions.generateDebugInfo = true;
1579                    if (emitNonSemanticShaderDebugInfo) {
1580                        spvOptions.emitNonSemanticShaderDebugInfo = true;
1581                        if (emitNonSemanticShaderDebugSource) {
1582                            spvOptions.emitNonSemanticShaderDebugSource = true;
1583                        }
1584                    }
1585                } else if (stripDebugInfo)
1586                    spvOptions.stripDebugInfo = true;
1587                spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
1588                spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
1589                spvOptions.disassemble = SpvToolsDisassembler;
1590                spvOptions.validate = SpvToolsValidate;
1591                spvOptions.compileOnly = compileOnly;
1592                glslang::GlslangToSpv(*intermediate, spirv, &logger, &spvOptions);
1593
1594                // Dump the spv to a file or stdout, etc., but only if not doing
1595                // memory/perf testing, as it's not internal to programmatic use.
1596                if (!(Options & EOptionMemoryLeakMode)) {
1597                    printf("%s", logger.getAllMessages().c_str());
1598                    const auto filename = GetBinaryName(intermediate->getStage());
1599                    if (Options & EOptionOutputHexadecimal) {
1600                        if (!glslang::OutputSpvHex(spirv, filename, variableName))
1601                            exit(EFailUsage);
1602                    } else {
1603                        if (!glslang::OutputSpvBin(spirv, filename))
1604                            exit(EFailUsage);
1605                    }
1606
1607                    outputFiles.push_back(filename);
1608                    if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
1609                        spv::Disassemble(std::cout, spirv);
1610                }
1611            }
1612        }
1613#else
1614        Error("This configuration of glslang does not have SPIR-V support");
1615#endif
1616    }
1617
1618    CompileOrLinkFailed.fetch_or(CompileFailed);
1619    CompileOrLinkFailed.fetch_or(LinkFailed);
1620    if (depencyFileName && !static_cast<bool>(CompileOrLinkFailed.load())) {
1621        std::set<std::string> includedFiles = includer.getIncludedFiles();
1622        sources.insert(sources.end(), includedFiles.begin(), includedFiles.end());
1623
1624        writeDepFile(depencyFileName, outputFiles, sources);
1625    }
1626
1627    // Free everything up, program has to go before the shaders
1628    // because it might have merged stuff from the shaders, and
1629    // the stuff from the shaders has to have its destructors called
1630    // before the pools holding the memory in the shaders is freed.
1631    delete &program;
1632    while (shaders.size() > 0) {
1633        delete shaders.back();
1634        shaders.pop_back();
1635    }
1636}
1637
1638//
1639// Do file IO part of compile and link, handing off the pure
1640// API/programmatic mode to CompileAndLinkShaderUnits(), which can
1641// be put in a loop for testing memory footprint and performance.
1642//
1643// This is just for linking mode: meaning all the shaders will be put into the
1644// the same program linked together.
1645//
1646// This means there are a limited number of work items (not multi-threading mode)
1647// and that the point is testing at the linking level. Hence, to enable
1648// performance and memory testing, the actual compile/link can be put in
1649// a loop, independent of processing the work items and file IO.
1650//
1651void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
1652{
1653    std::vector<ShaderCompUnit> compUnits;
1654
1655    // If this is using stdin, we can't really detect multiple different file
1656    // units by input type. We need to assume that we're just being given one
1657    // file of a certain type.
1658    if ((Options & EOptionStdin) != 0) {
1659        ShaderCompUnit compUnit(FindLanguage("stdin"));
1660        std::istreambuf_iterator<char> begin(std::cin), end;
1661        std::string tempString(begin, end);
1662        char* fileText = strdup(tempString.c_str());
1663        std::string fileName = "stdin";
1664        compUnit.addString(fileName, fileText);
1665        compUnits.push_back(compUnit);
1666    } else {
1667        // Transfer all the work items from to a simple list of
1668        // of compilation units.  (We don't care about the thread
1669        // work-item distribution properties in this path, which
1670        // is okay due to the limited number of shaders, know since
1671        // they are all getting linked together.)
1672        glslang::TWorkItem* workItem;
1673        while (Worklist.remove(workItem)) {
1674            ShaderCompUnit compUnit(FindLanguage(workItem->name));
1675            char* fileText = ReadFileData(workItem->name.c_str());
1676            if (fileText == nullptr)
1677                usage();
1678            compUnit.addString(workItem->name, fileText);
1679            compUnits.push_back(compUnit);
1680        }
1681    }
1682
1683    // Actual call to programmatic processing of compile and link,
1684    // in a loop for testing memory and performance.  This part contains
1685    // all the perf/memory that a programmatic consumer will care about.
1686    for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1687        for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
1688           CompileAndLinkShaderUnits(compUnits);
1689
1690        if (Options & EOptionMemoryLeakMode)
1691            glslang::OS_DumpMemoryCounters();
1692    }
1693
1694    // free memory from ReadFileData, which got stored in a const char*
1695    // as the first string above
1696    for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
1697        FreeFileData(const_cast<char*>(it->text[0]));
1698}
1699
1700int singleMain()
1701{
1702    glslang::TWorklist workList;
1703    std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
1704        assert(item);
1705        workList.add(item.get());
1706    });
1707
1708    if (Options & EOptionDumpConfig) {
1709        printf("%s", GetDefaultTBuiltInResourceString().c_str());
1710        if (workList.empty())
1711            return ESuccess;
1712    }
1713
1714    if (Options & EOptionDumpBareVersion) {
1715        int spirvGeneratorVersion = 0;
1716#ifdef ENABLE_SPIRV
1717        spirvGeneratorVersion = glslang::GetSpirvGeneratorVersion();
1718#endif
1719        printf("%d:%d.%d.%d%s\n", spirvGeneratorVersion, GLSLANG_VERSION_MAJOR, GLSLANG_VERSION_MINOR,
1720                GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1721        if (workList.empty())
1722            return ESuccess;
1723    } else if (Options & EOptionDumpVersions) {
1724        int spirvGeneratorVersion = 0;
1725#ifdef ENABLE_SPIRV
1726        spirvGeneratorVersion = glslang::GetSpirvGeneratorVersion();
1727#endif
1728        printf("Glslang Version: %d:%d.%d.%d%s\n", spirvGeneratorVersion, GLSLANG_VERSION_MAJOR,
1729                GLSLANG_VERSION_MINOR, GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1730        printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
1731        printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
1732        std::string spirvVersion;
1733#if ENABLE_SPIRV
1734        glslang::GetSpirvVersion(spirvVersion);
1735#endif
1736        printf("SPIR-V Version %s\n", spirvVersion.c_str());
1737        printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
1738        printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
1739        printf("SPIR-V Generator Version %d\n", spirvGeneratorVersion);
1740        printf("GL_KHR_vulkan_glsl version %d\n", 100);
1741        printf("ARB_GL_gl_spirv version %d\n", 100);
1742        if (workList.empty())
1743            return ESuccess;
1744    }
1745
1746    if (workList.empty() && ((Options & EOptionStdin) == 0)) {
1747        usage();
1748    }
1749
1750    if (Options & EOptionStdin) {
1751        WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
1752        workList.add(WorkItems.back().get());
1753    }
1754
1755    ProcessConfigFile();
1756
1757    if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
1758        Error("HLSL requires SPIR-V code generation (or preprocessing only)");
1759
1760    //
1761    // Two modes:
1762    // 1) linking all arguments together, single-threaded, new C++ interface
1763    // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
1764    //
1765    if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
1766        glslang::InitializeProcess();
1767        glslang::InitializeProcess();  // also test reference counting of users
1768        glslang::InitializeProcess();  // also test reference counting of users
1769        glslang::FinalizeProcess();    // also test reference counting of users
1770        glslang::FinalizeProcess();    // also test reference counting of users
1771        CompileAndLinkShaderFiles(workList);
1772        glslang::FinalizeProcess();
1773    } else {
1774        ShInitialize();
1775        ShInitialize();  // also test reference counting of users
1776        ShFinalize();    // also test reference counting of users
1777
1778        bool printShaderNames = workList.size() > 1;
1779
1780        if (Options & EOptionMultiThreaded) {
1781            std::array<std::thread, 16> threads;
1782            for (unsigned int t = 0; t < threads.size(); ++t) {
1783                threads[t] = std::thread(CompileShaders, std::ref(workList));
1784                if (threads[t].get_id() == std::thread::id()) {
1785                    fprintf(stderr, "Failed to create thread\n");
1786                    return EFailThreadCreate;
1787                }
1788            }
1789
1790            std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
1791        } else
1792            CompileShaders(workList);
1793
1794        // Print out all the resulting infologs
1795        for (size_t w = 0; w < WorkItems.size(); ++w) {
1796            if (WorkItems[w]) {
1797                if (printShaderNames || WorkItems[w]->results.size() > 0)
1798                    PutsIfNonEmpty(WorkItems[w]->name.c_str());
1799                PutsIfNonEmpty(WorkItems[w]->results.c_str());
1800            }
1801        }
1802
1803        ShFinalize();
1804    }
1805
1806    if (CompileFailed.load())
1807        return EFailCompile;
1808    if (LinkFailed.load())
1809        return EFailLink;
1810
1811    return 0;
1812}
1813
1814int C_DECL main(int argc, char* argv[])
1815{
1816    ProcessArguments(WorkItems, argc, argv);
1817
1818    int ret = 0;
1819
1820    // Loop over the entire init/finalize cycle to watch memory changes
1821    const int iterations = 1;
1822    if (iterations > 1)
1823        glslang::OS_DumpMemoryCounters();
1824    for (int i = 0; i < iterations; ++i) {
1825        ret = singleMain();
1826        if (iterations > 1)
1827            glslang::OS_DumpMemoryCounters();
1828    }
1829
1830    return ret;
1831}
1832
1833//
1834//   Deduce the language from the filename.  Files must end in one of the
1835//   following extensions:
1836//
1837//   .vert = vertex
1838//   .tesc = tessellation control
1839//   .tese = tessellation evaluation
1840//   .geom = geometry
1841//   .frag = fragment
1842//   .comp = compute
1843//   .rgen = ray generation
1844//   .rint = ray intersection
1845//   .rahit = ray any hit
1846//   .rchit = ray closest hit
1847//   .rmiss = ray miss
1848//   .rcall = ray callable
1849//   .mesh  = mesh
1850//   .task  = task
1851//   Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
1852//   where <stage> is one of the stages listed above.
1853//
1854EShLanguage FindLanguage(const std::string& name, bool parseStageName)
1855{
1856    std::string stageName;
1857    if (shaderStageName)
1858        stageName = shaderStageName;
1859    else if (parseStageName) {
1860        // Note: "first" extension means "first from the end", i.e.
1861        // if the file is named foo.vert.glsl, then "glsl" is first,
1862        // "vert" is second.
1863        size_t firstExtStart = name.find_last_of(".");
1864        bool hasFirstExt = firstExtStart != std::string::npos;
1865        size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
1866        bool hasSecondExt = secondExtStart != std::string::npos;
1867        std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
1868        bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
1869        if (usesUnifiedExt && firstExt == "hlsl")
1870            Options |= EOptionReadHlsl;
1871        if (hasFirstExt && !usesUnifiedExt)
1872            stageName = firstExt;
1873        else if (usesUnifiedExt && hasSecondExt)
1874            stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
1875        else {
1876            usage();
1877            return EShLangVertex;
1878        }
1879    } else
1880        stageName = name;
1881
1882    if (stageName == "vert")
1883        return EShLangVertex;
1884    else if (stageName == "tesc")
1885        return EShLangTessControl;
1886    else if (stageName == "tese")
1887        return EShLangTessEvaluation;
1888    else if (stageName == "geom")
1889        return EShLangGeometry;
1890    else if (stageName == "frag")
1891        return EShLangFragment;
1892    else if (stageName == "comp")
1893        return EShLangCompute;
1894    else if (stageName == "rgen")
1895        return EShLangRayGen;
1896    else if (stageName == "rint")
1897        return EShLangIntersect;
1898    else if (stageName == "rahit")
1899        return EShLangAnyHit;
1900    else if (stageName == "rchit")
1901        return EShLangClosestHit;
1902    else if (stageName == "rmiss")
1903        return EShLangMiss;
1904    else if (stageName == "rcall")
1905        return EShLangCallable;
1906    else if (stageName == "mesh")
1907        return EShLangMesh;
1908    else if (stageName == "task")
1909        return EShLangTask;
1910
1911    usage();
1912    return EShLangVertex;
1913}
1914
1915//
1916// Read a file's data into a string, and compile it using the old interface ShCompile,
1917// for non-linkable results.
1918//
1919void CompileFile(const char* fileName, ShHandle compiler)
1920{
1921    int ret = 0;
1922    char* shaderString;
1923    if ((Options & EOptionStdin) != 0) {
1924        std::istreambuf_iterator<char> begin(std::cin), end;
1925        std::string tempString(begin, end);
1926        shaderString = strdup(tempString.c_str());
1927    } else {
1928        shaderString = ReadFileData(fileName);
1929    }
1930
1931    // move to length-based strings, rather than null-terminated strings
1932    int* lengths = new int[1];
1933    lengths[0] = (int)strlen(shaderString);
1934
1935    EShMessages messages = EShMsgDefault;
1936    SetMessageOptions(messages);
1937
1938    if (UserPreamble.isSet())
1939        Error("-D, -U and -P options require -l (linking)\n");
1940
1941    for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1942        for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
1943            // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1944            ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, GetResources(), 0,
1945                            (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages, fileName);
1946            // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
1947            //                         "or should be l", "ine 1", "string 5\n", "float glo", "bal",
1948            //                         ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
1949            // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
1950            // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1951        }
1952
1953        if (Options & EOptionMemoryLeakMode)
1954            glslang::OS_DumpMemoryCounters();
1955    }
1956
1957    delete [] lengths;
1958    FreeFileData(shaderString);
1959
1960    if (ret == 0)
1961        CompileFailed = true;
1962}
1963
1964//
1965//   print usage to stdout
1966//
1967void usage()
1968{
1969    printf("Usage: glslang [option]... [file]...\n"
1970           "\n"
1971           "'file' with one of the following three endings can be auto-classified:\n"
1972           "1) .<stage>, where <stage> is one of:\n"
1973           "    vert    for a vertex shader\n"
1974           "    tesc    for a tessellation control shader\n"
1975           "    tese    for a tessellation evaluation shader\n"
1976           "    geom    for a geometry shader\n"
1977           "    frag    for a fragment shader\n"
1978           "    comp    for a compute shader\n"
1979           "    mesh    for a mesh shader\n"
1980           "    task    for a task shader\n"
1981           "    rgen    for a ray generation shader\n"
1982           "    rint    for a ray intersection shader\n"
1983           "    rahit   for a ray any hit shader\n"
1984           "    rchit   for a ray closest hit shader\n"
1985           "    rmiss   for a ray miss shader\n"
1986           "    rcall   for a ray callable shader\n"
1987           "2) .<stage>.glsl or .<stage>.hlsl compound suffix, where stage options are\n"
1988           "   described above\n"
1989           "3) .conf, to provide a config file that replaces the default configuration (see\n"
1990           "   -c option below for generating a template)\n"
1991           "\n"
1992           "Options:\n"
1993           "  -C          cascading errors; risk crash from accumulation of error recoveries\n"
1994           "  -D          input is HLSL (this is the default when any suffix is .hlsl)\n"
1995           "  -D<name[=def]> | --D <name[=def]> | --define-macro <name[=def]>\n"
1996           "              define a pre-processor macro\n"
1997           "  -E          print pre-processed GLSL; cannot be used with -l; errors will\n"
1998           "              appear on stderr\n"
1999           "  -G[ver]     create SPIR-V binary under OpenGL semantics; turns on -l; default\n"
2000           "              file name is <stage>.spv (-o overrides this); ver, when present,\n"
2001           "              is the version of the input semantics which will appear in\n"
2002           "              '#define GL_SPIRV ver'; --client opengl100 is the same as -G100; a\n"
2003           "              --target-env for OpenGL will also imply -G; currently only\n"
2004           "              supports GLSL\n"
2005           "  -H          print human readable form of SPIR-V; turns on -V\n"
2006           "  -I<dir>     add <dir> to the include search path; includer's directory is\n"
2007           "              searched first, followed by left-to-right order of -I\n"
2008           "  -Od         disables optimization; may cause illegal SPIR-V for HLSL\n"
2009           "  -Os         optimizes SPIR-V to minimize size\n"
2010           "  -P<text> | --P <text> | --preamble-text <text>\n"
2011           "              inject custom preamble text which is treated as if it appeared\n"
2012           "              immediately after the version declaration (if any)\n"
2013           "  -R          use relaxed verification rules for generating Vulkan SPIR-V,\n"
2014           "              allowing the use of default uniforms, atomic_uints, and the\n"
2015           "              gl_VertexID and gl_InstanceID keywords\n"
2016           "  -S <stage>  uses the specified <stage> rather than parsing the file extension;\n"
2017           "              choices for <stage> include vert, tesc, tese, geom, frag, and\n"
2018           "              comp; a full list of options is given above\n"
2019           "  -U<name> | --undef-macro <name> | --U <name>\n"
2020           "              undefine a pre-processor macro\n"
2021           "  -V[ver]     create SPIR-V binary under Vulkan semantics; turns on -l; default\n"
2022           "              file name is <stage>.spv (-o overrides this); ver, when present,\n"
2023           "              is the version of the input semantics which will appear in\n"
2024           "              '#define VULKAN ver'; --client vulkan100 is the same as -V100; a\n"
2025           "              '--target-env' for Vulkan will also imply '-V'\n"
2026           "  -c          configuration dump; creates the default configuration file\n"
2027           "              (redirect to a .conf file)\n"
2028           "  -d          default to desktop (#version 110) when there is no shader #version\n"
2029           "              (default is ES version 100)\n"
2030           "  -e <name> | --entry-point <name>\n"
2031           "              specify <name> as the entry-point function name\n"
2032           "  -f{hlsl_functionality1}\n"
2033           "              'hlsl_functionality1' enables use of the\n"
2034           "              SPV_GOOGLE_hlsl_functionality1 extension\n"
2035           "  -g          generate debug information\n"
2036           "  -g0         strip debug information\n"
2037           "  -gV         generate nonsemantic shader debug information\n"
2038           "  -gVS        generate nonsemantic shader debug information with source\n"
2039           "  -h | --help print this usage message\n"
2040           "  -i          intermediate tree (glslang AST) is printed out\n"
2041           "  -l          link all input files together to form a single module\n"
2042           "  -m          memory leak mode\n"
2043           "  -o <file>   save binary to <file>; requires a binary option (e.g., -V)\n"
2044           "  -q          dump reflection query database; requires -l for linking\n"
2045           "  -r | --relaxed-errors\n"
2046           "              relaxed GLSL semantic error-checking mode\n"
2047           "  -s          silence syntax and semantic error reporting\n"
2048           "  -t          multi-threaded mode\n"
2049           "  -u<name>:<loc>\n"
2050           "              specify a uniform location override for --aml\n"
2051           "  -v | --version\n"
2052           "              print version strings\n"
2053           "  -w | --suppress-warnings\n"
2054           "              suppress GLSL warnings, except as required by '#extension : warn'\n"
2055           "  -x          save binary output as text-based 32-bit hexadecimal numbers\n"
2056           "  --absolute-path                   prints absolute path for messages\n"
2057           "  --auto-map-binding | --auto-map-bindings | --amb\n"
2058           "                                    automatically bind uniform variables without\n"
2059           "                                    explicit bindings\n"
2060           "  --auto-map-locations | --aml      automatically locate input/output lacking\n"
2061           "                                    'location' (fragile, not cross stage)\n"
2062           "  --auto-sampled-textures           removes sampler variables and converts\n"
2063           "                                    existing textures to sampled textures\n"
2064           "  --client {vulkan<ver> | opengl<ver>}\n"
2065           "                                    see -V and -G\n"
2066           "  --depfile <file>                  writes depfile for build systems\n"
2067           "  --dump-builtin-symbols            prints builtin symbol table prior each\n"
2068           "                                    compile\n"
2069           "  -dumpfullversion | -dumpversion   print bare major.minor.patchlevel\n"
2070           "  --enhanced-msgs                   print more readable error messages (GLSL\n"
2071           "                                    only)\n"
2072           "  --error-column                    display the column of the error along the\n"
2073           "                                    line\n"
2074           "  --flatten-uniform-array | --flatten-uniform-arrays | --fua\n"
2075           "                                    flatten uniform texture/sampler arrays to\n"
2076           "                                    scalars\n"
2077           "  --glsl-version {100 | 110 | 120 | 130 | 140 | 150 |\n"
2078           "                  300es | 310es | 320es | 330 |\n"
2079           "                  400 | 410 | 420 | 430 | 440 | 450 | 460}\n"
2080           "                                    set GLSL version; overrides #version in\n"
2081           "                                    shader source\n"
2082           "  --hlsl-dx-position-w              W component of SV_Position in HLSL fragment\n"
2083           "                                    shaders compatible with DirectX\n"
2084           "  --hlsl-dx9-compatible             interprets sampler declarations as a\n"
2085           "                                    texture/sampler combo like DirectX9 would,\n"
2086           "                                    and recognizes DirectX9-specific semantics\n"
2087           "  --hlsl-enable-16bit-types         allow 16-bit types in SPIR-V for HLSL\n"
2088           "  --hlsl-iomap | --hlsl-iomapper | --hlsl-iomapping\n"
2089           "                                    perform IO mapping in HLSL register space\n"
2090           "  --hlsl-offsets                    allow block offsets to follow HLSL rules;\n"
2091           "                                    works independently of source language\n"
2092           "  --invert-y | --iy                 invert position.Y output in vertex shader\n"
2093           "  --keep-uncalled | --ku            don't eliminate uncalled functions\n"
2094           "  --lto                             perform link time optimization\n"
2095           "  --nan-clamp                       favor non-NaN operand in min, max, and clamp\n"
2096           "  --no-link                         only compile shader; do not link (GLSL only)\n"
2097           "                                    NOTE: this option will set the export\n"
2098           "                                          linkage attribute on all functions\n"
2099           "  --no-storage-format | --nsf       use Unknown image format\n"
2100           "  --quiet                           do not print anything to stdout unless\n"
2101           "                                    requested by another option\n"
2102           "  --reflect-all-block-variables     reflect all variables in blocks, whether\n"
2103           "                                    inactive or active\n"
2104           "  --reflect-basic-array-suffix      arrays of basic types will have trailing [0]\n"
2105           "  --reflect-intermediate-io         reflection includes inputs/outputs of linked\n"
2106           "                                    shaders rather than just vertex/fragment\n"
2107           "  --reflect-separate-buffers        reflect buffer variables and blocks\n"
2108           "                                    separately to uniforms\n"
2109           "  --reflect-strict-array-suffix     use strict array suffix rules when\n"
2110           "                                    reflecting\n"
2111           "  --reflect-unwrap-io-blocks        unwrap input/output blocks the same as\n"
2112           "                                    uniform blocks\n"
2113           "  --resource-set-binding <stage> [name] <set> [binding]...\n"
2114           "                                    set descriptor set and binding for\n"
2115           "                                    individual resources\n"
2116           "  --resource-set-binding [stage] <set>\n"
2117           "                                    set descriptor set for all resources\n"
2118           "  --resource-set-bindings | --rsb   synonyms for --resource-set-binding\n"
2119           "  --set-atomic-counter-block <name> <set>\n"
2120           "                                    set name and descriptor set for atomic\n"
2121           "                                    counter blocks with -R opt\n"
2122           "  --sacb                            synonym for set-atomic-counter-block\n"
2123           "  --set-block-backing name {uniform | buffer | push_constant}\n"
2124           "                                    changes the backing type of a uniform,\n"
2125           "                                    buffer, or push_constant block declared in\n"
2126           "                                    the program when using the -R option; this\n"
2127           "                                    can be used to change the backing for\n"
2128           "                                    existing blocks as well as implicit ones\n"
2129           "                                    such as 'gl_DefaultUniformBlock'\n"
2130           "  --set-default-uniform-block <name> <set> <binding>\n"
2131           "                                    set name, descriptor set, and binding for\n"
2132           "                                    global default-uniform-block with -R opt\n"
2133           "  --sdub                            synonym for set-default-uniform-block\n"
2134           "  --shift-image-binding [stage] <num>\n"
2135           "                                    base binding number for images (UAV)\n"
2136           "  --shift-image-binding [stage] <num> <set>...\n"
2137           "                                    per-descriptor-set shift values\n"
2138           "  --shift-image-bindings | --sib    synonyms for --shift-image-binding\n"
2139           "  --shift-sampler-binding [stage] <num>\n"
2140           "                                    base binding number for samplers\n"
2141           "  --shift-sampler-binding [stage] <num> <set>...\n"
2142           "                                    per-descriptor-set shift values\n"
2143           "  --shift-sampler-bindings | --ssb  synonyms for --shift-sampler-binding\n"
2144           "  --shift-ssbo-binding [stage] <num>\n"
2145           "                                    base binding number for SSBOs\n"
2146           "  --shift-ssbo-binding [stage] <num> <set>...\n"
2147           "                                    per-descriptor-set shift values\n"
2148           "  --shift-ssbo-bindings | --sbb     synonyms for --shift-ssbo-binding\n"
2149           "  --shift-texture-binding [stage] <num>\n"
2150           "                                    base binding number for textures\n"
2151           "  --shift-texture-binding [stage] <num> <set>...\n"
2152           "                                    per-descriptor-set shift values\n"
2153           "  --shift-texture-bindings | --stb  synonyms for --shift-texture-binding\n"
2154           "  --shift-uav-binding [stage] <num> base binding number for UAVs\n"
2155           "  --shift-uav-binding [stage] <num> <set>...\n"
2156           "                                    per-descriptor-set shift values\n"
2157           "  --shift-uav-bindings | --suavb    synonyms for --shift-uav-binding\n"
2158           "  --shift-ubo-binding [stage] <num> base binding number for UBOs\n"
2159           "  --shift-ubo-binding [stage] <num> <set>...\n"
2160           "                                    per-descriptor-set shift values\n"
2161           "  --shift-ubo-bindings | --sub |\n"
2162           "  --shift-cbuffer-binding | --shift-cbuffer-bindings | --scb\n"
2163           "                                    synonyms for --shift-ubo-binding\n"
2164           "  --shift-combined-sampler-binding [stage] <num>\n"
2165           "                                    base binding number for combined samplers\n"
2166           "  --shift-combined-sampler-binding [stage] <num> <set>...\n"
2167           "                                    per-descriptor-set shift values\n"
2168           "  --shift-combined-sampler-bindings | --scsb\n"
2169           "                                    synonyms for --shift-combined-sampler-binding\n"
2170           "  --shift-as-binding [stage] <num>\n"
2171           "                                    base binding number for acceleration structures\n"
2172           "  --shift-as-binding [stage] <num> <set>...\n"
2173           "                                    per-descriptor-set shift values\n"
2174           "  --shift-as-bindings | --sab\n"
2175           "                                    synonyms for --shift-as-binding\n"
2176           "  --spirv-dis                       output standard-form disassembly; works only\n"
2177           "                                    when a SPIR-V generation option is also used\n"
2178           "  --spirv-val                       execute the SPIRV-Tools validator\n"
2179           "  --source-entrypoint <name> | --sep <name>\n"
2180           "                                    the given shader source function is renamed\n"
2181           "                                    to be the <name> given in -e\n"
2182           "  --stdin                           read from stdin instead of from a file;\n"
2183           "                                    requires providing the shader stage using -S\n"
2184           "  --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | vulkan1.3 | vulkan1.4 |\n"
2185           "                opengl | spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 |\n"
2186           "                spirv1.4 | spirv1.5 | spirv1.6}\n"
2187           "                                    set the execution environment the generated\n"
2188           "                                    code will be executed in; defaults to:\n"
2189           "                                     * vulkan1.0 under --client vulkan<ver>\n"
2190           "                                     * opengl    under --client opengl<ver>\n"
2191           "                                     * spirv1.0  under --target-env vulkan1.0\n"
2192           "                                     * spirv1.3  under --target-env vulkan1.1\n"
2193           "                                     * spirv1.5  under --target-env vulkan1.2\n"
2194           "                                     * spirv1.6  under --target-env vulkan1.3\n"
2195           "                                     * spirv1.6  under --target-env vulkan1.4\n"
2196           "                                    multiple --target-env can be specified\n"
2197           "  --uniform-base <base>             set a base to use for generated uniform\n"
2198           "                                    locations\n"
2199           "  --variable-name <name> | --vn <name>\n"
2200           "                                    creates a C header file that contains a\n"
2201           "                                    uint32_t array named <name> initialized with\n"
2202           "                                    the shader binary code\n"
2203           "  --validate-io                     validate cross stage IO\n"
2204           "  --bindings-per-resource-type\n");
2205
2206    exit(EFailUsage);
2207}
2208
2209#if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
2210
2211#include <errno.h>
2212
2213int fopen_s(
2214   FILE** pFile,
2215   const char* filename,
2216   const char* mode
2217)
2218{
2219   if (!pFile || !filename || !mode) {
2220      return EINVAL;
2221   }
2222
2223   FILE* f = fopen(filename, mode);
2224   if (! f) {
2225      if (errno != 0) {
2226         return errno;
2227      } else {
2228         return ENOENT;
2229      }
2230   }
2231   *pFile = f;
2232
2233   return 0;
2234}
2235
2236#endif
2237
2238//
2239//   Malloc a string of sufficient size and read a string into it.
2240//
2241char* ReadFileData(const char* fileName)
2242{
2243    FILE *in = nullptr;
2244    int errorCode = fopen_s(&in, fileName, "r");
2245    if (errorCode || in == nullptr)
2246        Error("unable to open input file");
2247
2248    int count = 0;
2249    while (fgetc(in) != EOF)
2250        count++;
2251
2252    fseek(in, 0, SEEK_SET);
2253
2254    if (count > 3) {
2255        unsigned char head[3];
2256        if (fread(head, 1, 3, in) == 3) {
2257            if (head[0] == 0xef && head[1] == 0xbb && head[2] == 0xbf) {
2258                // skip BOM
2259                count -= 3;
2260            } else {
2261                fseek(in, 0, SEEK_SET);
2262            }
2263        } else {
2264            Error("can't read input file");
2265        }
2266    }
2267
2268    char* return_data = (char*)malloc(count + 1);  // freed in FreeFileData()
2269    if ((int)fread(return_data, 1, count, in) != count) {
2270        free(return_data);
2271        Error("can't read input file");
2272    }
2273
2274    return_data[count] = '\0';
2275    fclose(in);
2276
2277    return return_data;
2278}
2279
2280void FreeFileData(char* data)
2281{
2282    free(data);
2283}
2284
2285void InfoLogMsg(const char* msg, const char* name, const int num)
2286{
2287    if (num >= 0 )
2288        printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
2289    else
2290        printf("#### %s %s INFO LOG ####\n", msg, name);
2291}