yum-mirror/glslang

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

Valentin SarthouAdd --discard-is-terminate option (#4081)c8ec3690

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