• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2013-2016 LunarG, Inc.
4 // Copyright (C) 2016-2020 Google, Inc.
5 //
6 // All rights reserved.
7 //
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions
10 // are met:
11 //
12 //    Redistributions of source code must retain the above copyright
13 //    notice, this list of conditions and the following disclaimer.
14 //
15 //    Redistributions in binary form must reproduce the above
16 //    copyright notice, this list of conditions and the following
17 //    disclaimer in the documentation and/or other materials provided
18 //    with the distribution.
19 //
20 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21 //    contributors may be used to endorse or promote products derived
22 //    from this software without specific prior written permission.
23 //
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 // POSSIBILITY OF SUCH DAMAGE.
36 //
37 
38 // this only applies to the standalone wrapper, not the front end in general
39 #ifndef _CRT_SECURE_NO_WARNINGS
40 #define _CRT_SECURE_NO_WARNINGS
41 #endif
42 
43 #include "ResourceLimits.h"
44 #include "Worklist.h"
45 #include "DirStackFileIncluder.h"
46 #include "./../glslang/Include/ShHandle.h"
47 #include "./../glslang/Public/ShaderLang.h"
48 #include "../SPIRV/GlslangToSpv.h"
49 #include "../SPIRV/GLSL.std.450.h"
50 #include "../SPIRV/doc.h"
51 #include "../SPIRV/disassemble.h"
52 
53 #include <cstring>
54 #include <cstdlib>
55 #include <cctype>
56 #include <cmath>
57 #include <array>
58 #include <map>
59 #include <memory>
60 #include <thread>
61 
62 #include "../glslang/OSDependent/osinclude.h"
63 
64 // Build-time generated includes
65 #include "glslang/build_info.h"
66 
67 extern "C" {
68     GLSLANG_EXPORT void ShOutputHtml();
69 }
70 
71 // Command-line options
72 enum TOptions {
73     EOptionNone                 = 0,
74     EOptionIntermediate         = (1 <<  0),
75     EOptionSuppressInfolog      = (1 <<  1),
76     EOptionMemoryLeakMode       = (1 <<  2),
77     EOptionRelaxedErrors        = (1 <<  3),
78     EOptionGiveWarnings         = (1 <<  4),
79     EOptionLinkProgram          = (1 <<  5),
80     EOptionMultiThreaded        = (1 <<  6),
81     EOptionDumpConfig           = (1 <<  7),
82     EOptionDumpReflection       = (1 <<  8),
83     EOptionSuppressWarnings     = (1 <<  9),
84     EOptionDumpVersions         = (1 << 10),
85     EOptionSpv                  = (1 << 11),
86     EOptionHumanReadableSpv     = (1 << 12),
87     EOptionVulkanRules          = (1 << 13),
88     EOptionDefaultDesktop       = (1 << 14),
89     EOptionOutputPreprocessed   = (1 << 15),
90     EOptionOutputHexadecimal    = (1 << 16),
91     EOptionReadHlsl             = (1 << 17),
92     EOptionCascadingErrors      = (1 << 18),
93     EOptionAutoMapBindings      = (1 << 19),
94     EOptionFlattenUniformArrays = (1 << 20),
95     EOptionNoStorageFormat      = (1 << 21),
96     EOptionKeepUncalled         = (1 << 22),
97     EOptionHlslOffsets          = (1 << 23),
98     EOptionHlslIoMapping        = (1 << 24),
99     EOptionAutoMapLocations     = (1 << 25),
100     EOptionDebug                = (1 << 26),
101     EOptionStdin                = (1 << 27),
102     EOptionOptimizeDisable      = (1 << 28),
103     EOptionOptimizeSize         = (1 << 29),
104     EOptionInvertY              = (1 << 30),
105     EOptionDumpBareVersion      = (1 << 31),
106 };
107 bool targetHlslFunctionality1 = false;
108 bool SpvToolsDisassembler = false;
109 bool SpvToolsValidate = false;
110 bool NaNClamp = false;
111 bool stripDebugInfo = false;
112 bool beQuiet = false;
113 
114 //
115 // Return codes from main/exit().
116 //
117 enum TFailCode {
118     ESuccess = 0,
119     EFailUsage,
120     EFailCompile,
121     EFailLink,
122     EFailCompilerCreate,
123     EFailThreadCreate,
124     EFailLinkerCreate
125 };
126 
127 //
128 // Forward declarations.
129 //
130 EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
131 void CompileFile(const char* fileName, ShHandle);
132 void usage();
133 char* ReadFileData(const char* fileName);
134 void FreeFileData(char* data);
135 void InfoLogMsg(const char* msg, const char* name, const int num);
136 
137 // Globally track if any compile or link failure.
138 bool CompileFailed = false;
139 bool LinkFailed = false;
140 
141 // array of unique places to leave the shader names and infologs for the asynchronous compiles
142 std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
143 
144 TBuiltInResource Resources;
145 std::string ConfigFile;
146 
147 //
148 // Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
149 //
ProcessConfigFile()150 void ProcessConfigFile()
151 {
152     if (ConfigFile.size() == 0)
153         Resources = glslang::DefaultTBuiltInResource;
154 #ifndef GLSLANG_WEB
155     else {
156         char* configString = ReadFileData(ConfigFile.c_str());
157         glslang::DecodeResourceLimits(&Resources,  configString);
158         FreeFileData(configString);
159     }
160 #endif
161 }
162 
163 int ReflectOptions = EShReflectionDefault;
164 int Options = 0;
165 const char* ExecutableName = nullptr;
166 const char* binaryFileName = nullptr;
167 const char* entryPointName = nullptr;
168 const char* sourceEntryPointName = nullptr;
169 const char* shaderStageName = nullptr;
170 const char* variableName = nullptr;
171 bool HlslEnable16BitTypes = false;
172 bool HlslDX9compatible = false;
173 bool DumpBuiltinSymbols = false;
174 std::vector<std::string> IncludeDirectoryList;
175 
176 // Source environment
177 // (source 'Client' is currently the same as target 'Client')
178 int ClientInputSemanticsVersion = 100;
179 
180 // Target environment
181 glslang::EShClient Client = glslang::EShClientNone;  // will stay EShClientNone if only validating
182 glslang::EShTargetClientVersion ClientVersion;       // not valid until Client is set
183 glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
184 glslang::EShTargetLanguageVersion TargetVersion;     // not valid until TargetLanguage is set
185 
186 std::vector<std::string> Processes;                     // what should be recorded by OpModuleProcessed, or equivalent
187 
188 // Per descriptor-set binding base data
189 typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
190 
191 std::vector<std::pair<std::string, int>> uniformLocationOverrides;
192 int uniformBase = 0;
193 
194 std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
195 std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
196 std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
197 
198 // Add things like "#define ..." to a preamble to use in the beginning of the shader.
199 class TPreamble {
200 public:
TPreamble()201     TPreamble() { }
202 
isSet() const203     bool isSet() const { return text.size() > 0; }
get() const204     const char* get() const { return text.c_str(); }
205 
206     // #define...
addDef(std::string def)207     void addDef(std::string def)
208     {
209         text.append("#define ");
210         fixLine(def);
211 
212         Processes.push_back("define-macro ");
213         Processes.back().append(def);
214 
215         // The first "=" needs to turn into a space
216         const size_t equal = def.find_first_of("=");
217         if (equal != def.npos)
218             def[equal] = ' ';
219 
220         text.append(def);
221         text.append("\n");
222     }
223 
224     // #undef...
addUndef(std::string undef)225     void addUndef(std::string undef)
226     {
227         text.append("#undef ");
228         fixLine(undef);
229 
230         Processes.push_back("undef-macro ");
231         Processes.back().append(undef);
232 
233         text.append(undef);
234         text.append("\n");
235     }
236 
237 protected:
fixLine(std::string & line)238     void fixLine(std::string& line)
239     {
240         // Can't go past a newline in the line
241         const size_t end = line.find_first_of("\n");
242         if (end != line.npos)
243             line = line.substr(0, end);
244     }
245 
246     std::string text;  // contents of preamble
247 };
248 
249 // Track the user's #define and #undef from the command line.
250 TPreamble UserPreamble;
251 
252 //
253 // Create the default name for saving a binary if -o is not provided.
254 //
GetBinaryName(EShLanguage stage)255 const char* GetBinaryName(EShLanguage stage)
256 {
257     const char* name;
258     if (binaryFileName == nullptr) {
259         switch (stage) {
260         case EShLangVertex:          name = "vert.spv";    break;
261         case EShLangTessControl:     name = "tesc.spv";    break;
262         case EShLangTessEvaluation:  name = "tese.spv";    break;
263         case EShLangGeometry:        name = "geom.spv";    break;
264         case EShLangFragment:        name = "frag.spv";    break;
265         case EShLangCompute:         name = "comp.spv";    break;
266         case EShLangRayGen:          name = "rgen.spv";    break;
267         case EShLangIntersect:       name = "rint.spv";    break;
268         case EShLangAnyHit:          name = "rahit.spv";   break;
269         case EShLangClosestHit:      name = "rchit.spv";   break;
270         case EShLangMiss:            name = "rmiss.spv";   break;
271         case EShLangCallable:        name = "rcall.spv";   break;
272         case EShLangMeshNV:          name = "mesh.spv";    break;
273         case EShLangTaskNV:          name = "task.spv";    break;
274         default:                     name = "unknown";     break;
275         }
276     } else
277         name = binaryFileName;
278 
279     return name;
280 }
281 
282 //
283 // *.conf => this is a config file that can set limits/resources
284 //
SetConfigFile(const std::string & name)285 bool SetConfigFile(const std::string& name)
286 {
287     if (name.size() < 5)
288         return false;
289 
290     if (name.compare(name.size() - 5, 5, ".conf") == 0) {
291         ConfigFile = name;
292         return true;
293     }
294 
295     return false;
296 }
297 
298 //
299 // Give error and exit with failure code.
300 //
Error(const char * message,const char * detail=nullptr)301 void Error(const char* message, const char* detail = nullptr)
302 {
303     fprintf(stderr, "%s: Error: ", ExecutableName);
304     if (detail != nullptr)
305         fprintf(stderr, "%s: ", detail);
306     fprintf(stderr, "%s (use -h for usage)\n", message);
307     exit(EFailUsage);
308 }
309 
310 //
311 // Process an optional binding base of one the forms:
312 //   --argname [stage] base            // base for stage (if given) or all stages (if not)
313 //   --argname [stage] [base set]...   // set/base pairs: set the base for given binding set.
314 
315 // Where stage is one of the forms accepted by FindLanguage, and base is an integer
316 //
ProcessBindingBase(int & argc,char ** & argv,glslang::TResourceType res)317 void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
318 {
319     if (argc < 2)
320         usage();
321 
322     EShLanguage lang = EShLangCount;
323     int singleBase = 0;
324     TPerSetBaseBinding perSetBase;
325     int arg = 1;
326 
327     // Parse stage, if given
328     if (!isdigit(argv[arg][0])) {
329         if (argc < 3) // this form needs one more argument
330             usage();
331 
332         lang = FindLanguage(argv[arg++], false);
333     }
334 
335     if ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
336         // Parse a per-set binding base
337         while ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
338             const int baseNum = atoi(argv[arg++]);
339             const int setNum = atoi(argv[arg++]);
340             perSetBase[setNum] = baseNum;
341         }
342     } else {
343         // Parse single binding base
344         singleBase = atoi(argv[arg++]);
345     }
346 
347     argc -= (arg-1);
348     argv += (arg-1);
349 
350     // Set one or all languages
351     const int langMin = (lang < EShLangCount) ? lang+0 : 0;
352     const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
353 
354     for (int lang = langMin; lang < langMax; ++lang) {
355         if (!perSetBase.empty())
356             baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
357         else
358             baseBinding[res][lang] = singleBase;
359     }
360 }
361 
ProcessResourceSetBindingBase(int & argc,char ** & argv,std::array<std::vector<std::string>,EShLangCount> & base)362 void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
363 {
364     if (argc < 2)
365         usage();
366 
367     if (!isdigit(argv[1][0])) {
368         if (argc < 3) // this form needs one more argument
369             usage();
370 
371         // Parse form: --argname stage [regname set base...], or:
372         //             --argname stage set
373         const EShLanguage lang = FindLanguage(argv[1], false);
374 
375         argc--;
376         argv++;
377 
378         while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
379             base[lang].push_back(argv[1]);
380 
381             argc--;
382             argv++;
383         }
384 
385         // Must have one arg, or a multiple of three (for [regname set binding] triples)
386         if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
387             usage();
388 
389     } else {
390         // Parse form: --argname set
391         for (int lang=0; lang<EShLangCount; ++lang)
392             base[lang].push_back(argv[1]);
393 
394         argc--;
395         argv++;
396     }
397 }
398 
399 //
400 // Do all command-line argument parsing.  This includes building up the work-items
401 // to be processed later, and saving all the command-line options.
402 //
403 // Does not return (it exits) if command-line is fatally flawed.
404 //
ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>> & workItems,int argc,char * argv[])405 void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
406 {
407     for (int res = 0; res < glslang::EResCount; ++res)
408         baseBinding[res].fill(0);
409 
410     ExecutableName = argv[0];
411     workItems.reserve(argc);
412 
413     const auto bumpArg = [&]() {
414         if (argc > 0) {
415             argc--;
416             argv++;
417         }
418     };
419 
420     // read a string directly attached to a single-letter option
421     const auto getStringOperand = [&](const char* desc) {
422         if (argv[0][2] == 0) {
423             printf("%s must immediately follow option (no spaces)\n", desc);
424             exit(EFailUsage);
425         }
426         return argv[0] + 2;
427     };
428 
429     // read a number attached to a single-letter option
430     const auto getAttachedNumber = [&](const char* desc) {
431         int num = atoi(argv[0] + 2);
432         if (num == 0) {
433             printf("%s: expected attached non-0 number\n", desc);
434             exit(EFailUsage);
435         }
436         return num;
437     };
438 
439     // minimum needed (without overriding something else) to target Vulkan SPIR-V
440     const auto setVulkanSpv = []() {
441         if (Client == glslang::EShClientNone)
442             ClientVersion = glslang::EShTargetVulkan_1_0;
443         Client = glslang::EShClientVulkan;
444         Options |= EOptionSpv;
445         Options |= EOptionVulkanRules;
446         Options |= EOptionLinkProgram;
447     };
448 
449     // minimum needed (without overriding something else) to target OpenGL SPIR-V
450     const auto setOpenGlSpv = []() {
451         if (Client == glslang::EShClientNone)
452             ClientVersion = glslang::EShTargetOpenGL_450;
453         Client = glslang::EShClientOpenGL;
454         Options |= EOptionSpv;
455         Options |= EOptionLinkProgram;
456         // undo a -H default to Vulkan
457         Options &= ~EOptionVulkanRules;
458     };
459 
460     const auto getUniformOverride = [getStringOperand]() {
461         const char *arg = getStringOperand("-u<name>:<location>");
462         const char *split = strchr(arg, ':');
463         if (split == NULL) {
464             printf("%s: missing location\n", arg);
465             exit(EFailUsage);
466         }
467         errno = 0;
468         int location = ::strtol(split + 1, NULL, 10);
469         if (errno) {
470             printf("%s: invalid location\n", arg);
471             exit(EFailUsage);
472         }
473         return std::make_pair(std::string(arg, split - arg), location);
474     };
475 
476     for (bumpArg(); argc >= 1; bumpArg()) {
477         if (argv[0][0] == '-') {
478             switch (argv[0][1]) {
479             case '-':
480                 {
481                     std::string lowerword(argv[0]+2);
482                     std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
483 
484                     // handle --word style options
485                     if (lowerword == "auto-map-bindings" ||  // synonyms
486                         lowerword == "auto-map-binding"  ||
487                         lowerword == "amb") {
488                         Options |= EOptionAutoMapBindings;
489                     } else if (lowerword == "auto-map-locations" || // synonyms
490                                lowerword == "aml") {
491                         Options |= EOptionAutoMapLocations;
492                     } else if (lowerword == "uniform-base") {
493                         if (argc <= 1)
494                             Error("no <base> provided", lowerword.c_str());
495                         uniformBase = ::strtol(argv[1], NULL, 10);
496                         bumpArg();
497                         break;
498                     } else if (lowerword == "client") {
499                         if (argc > 1) {
500                             if (strcmp(argv[1], "vulkan100") == 0)
501                                 setVulkanSpv();
502                             else if (strcmp(argv[1], "opengl100") == 0)
503                                 setOpenGlSpv();
504                             else
505                                 Error("expects vulkan100 or opengl100", lowerword.c_str());
506                         } else
507                             Error("expects vulkan100 or opengl100", lowerword.c_str());
508                         bumpArg();
509                     } else if (lowerword == "define-macro" ||
510                                lowerword == "d") {
511                         if (argc > 1)
512                             UserPreamble.addDef(argv[1]);
513                         else
514                             Error("expects <name[=def]>", argv[0]);
515                         bumpArg();
516                     } else if (lowerword == "dump-builtin-symbols") {
517                         DumpBuiltinSymbols = true;
518                     } else if (lowerword == "entry-point") {
519                         entryPointName = argv[1];
520                         if (argc <= 1)
521                             Error("no <name> provided", lowerword.c_str());
522                         bumpArg();
523                     } else if (lowerword == "flatten-uniform-arrays" || // synonyms
524                                lowerword == "flatten-uniform-array"  ||
525                                lowerword == "fua") {
526                         Options |= EOptionFlattenUniformArrays;
527                     } else if (lowerword == "hlsl-offsets") {
528                         Options |= EOptionHlslOffsets;
529                     } else if (lowerword == "hlsl-iomap" ||
530                                lowerword == "hlsl-iomapper" ||
531                                lowerword == "hlsl-iomapping") {
532                         Options |= EOptionHlslIoMapping;
533                     } else if (lowerword == "hlsl-enable-16bit-types") {
534                         HlslEnable16BitTypes = true;
535                     } else if (lowerword == "hlsl-dx9-compatible") {
536                         HlslDX9compatible = true;
537                     } else if (lowerword == "invert-y" ||  // synonyms
538                                lowerword == "iy") {
539                         Options |= EOptionInvertY;
540                     } else if (lowerword == "keep-uncalled" || // synonyms
541                                lowerword == "ku") {
542                         Options |= EOptionKeepUncalled;
543                     } else if (lowerword == "nan-clamp") {
544                         NaNClamp = true;
545                     } else if (lowerword == "no-storage-format" || // synonyms
546                                lowerword == "nsf") {
547                         Options |= EOptionNoStorageFormat;
548                     } else if (lowerword == "relaxed-errors") {
549                         Options |= EOptionRelaxedErrors;
550                     } else if (lowerword == "reflect-strict-array-suffix") {
551                         ReflectOptions |= EShReflectionStrictArraySuffix;
552                     } else if (lowerword == "reflect-basic-array-suffix") {
553                         ReflectOptions |= EShReflectionBasicArraySuffix;
554                     } else if (lowerword == "reflect-intermediate-io") {
555                         ReflectOptions |= EShReflectionIntermediateIO;
556                     } else if (lowerword == "reflect-separate-buffers") {
557                         ReflectOptions |= EShReflectionSeparateBuffers;
558                     } else if (lowerword == "reflect-all-block-variables") {
559                         ReflectOptions |= EShReflectionAllBlockVariables;
560                     } else if (lowerword == "reflect-unwrap-io-blocks") {
561                         ReflectOptions |= EShReflectionUnwrapIOBlocks;
562                     } else if (lowerword == "reflect-all-io-variables") {
563                         ReflectOptions |= EShReflectionAllIOVariables;
564                     } else if (lowerword == "reflect-shared-std140-ubo") {
565                         ReflectOptions |= EShReflectionSharedStd140UBO;
566                     } else if (lowerword == "reflect-shared-std140-ssbo") {
567                         ReflectOptions |= EShReflectionSharedStd140SSBO;
568                     } else if (lowerword == "resource-set-bindings" ||  // synonyms
569                                lowerword == "resource-set-binding"  ||
570                                lowerword == "rsb") {
571                         ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
572                     } else if (lowerword == "shift-image-bindings" ||  // synonyms
573                                lowerword == "shift-image-binding"  ||
574                                lowerword == "sib") {
575                         ProcessBindingBase(argc, argv, glslang::EResImage);
576                     } else if (lowerword == "shift-sampler-bindings" || // synonyms
577                                lowerword == "shift-sampler-binding"  ||
578                                lowerword == "ssb") {
579                         ProcessBindingBase(argc, argv, glslang::EResSampler);
580                     } else if (lowerword == "shift-uav-bindings" ||  // synonyms
581                                lowerword == "shift-uav-binding"  ||
582                                lowerword == "suavb") {
583                         ProcessBindingBase(argc, argv, glslang::EResUav);
584                     } else if (lowerword == "shift-texture-bindings" ||  // synonyms
585                                lowerword == "shift-texture-binding"  ||
586                                lowerword == "stb") {
587                         ProcessBindingBase(argc, argv, glslang::EResTexture);
588                     } else if (lowerword == "shift-ubo-bindings" ||  // synonyms
589                                lowerword == "shift-ubo-binding"  ||
590                                lowerword == "shift-cbuffer-bindings" ||
591                                lowerword == "shift-cbuffer-binding"  ||
592                                lowerword == "sub" ||
593                                lowerword == "scb") {
594                         ProcessBindingBase(argc, argv, glslang::EResUbo);
595                     } else if (lowerword == "shift-ssbo-bindings" ||  // synonyms
596                                lowerword == "shift-ssbo-binding"  ||
597                                lowerword == "sbb") {
598                         ProcessBindingBase(argc, argv, glslang::EResSsbo);
599                     } else if (lowerword == "source-entrypoint" || // synonyms
600                                lowerword == "sep") {
601                         if (argc <= 1)
602                             Error("no <entry-point> provided", lowerword.c_str());
603                         sourceEntryPointName = argv[1];
604                         bumpArg();
605                         break;
606                     } else if (lowerword == "spirv-dis") {
607                         SpvToolsDisassembler = true;
608                     } else if (lowerword == "spirv-val") {
609                         SpvToolsValidate = true;
610                     } else if (lowerword == "stdin") {
611                         Options |= EOptionStdin;
612                         shaderStageName = argv[1];
613                     } else if (lowerword == "suppress-warnings") {
614                         Options |= EOptionSuppressWarnings;
615                     } else if (lowerword == "target-env") {
616                         if (argc > 1) {
617                             if (strcmp(argv[1], "vulkan1.0") == 0) {
618                                 setVulkanSpv();
619                                 ClientVersion = glslang::EShTargetVulkan_1_0;
620                             } else if (strcmp(argv[1], "vulkan1.1") == 0) {
621                                 setVulkanSpv();
622                                 ClientVersion = glslang::EShTargetVulkan_1_1;
623                             } else if (strcmp(argv[1], "vulkan1.2") == 0) {
624                                 setVulkanSpv();
625                                 ClientVersion = glslang::EShTargetVulkan_1_2;
626                             } else if (strcmp(argv[1], "opengl") == 0) {
627                                 setOpenGlSpv();
628                                 ClientVersion = glslang::EShTargetOpenGL_450;
629                             } else if (strcmp(argv[1], "spirv1.0") == 0) {
630                                 TargetLanguage = glslang::EShTargetSpv;
631                                 TargetVersion = glslang::EShTargetSpv_1_0;
632                             } else if (strcmp(argv[1], "spirv1.1") == 0) {
633                                 TargetLanguage = glslang::EShTargetSpv;
634                                 TargetVersion = glslang::EShTargetSpv_1_1;
635                             } else if (strcmp(argv[1], "spirv1.2") == 0) {
636                                 TargetLanguage = glslang::EShTargetSpv;
637                                 TargetVersion = glslang::EShTargetSpv_1_2;
638                             } else if (strcmp(argv[1], "spirv1.3") == 0) {
639                                 TargetLanguage = glslang::EShTargetSpv;
640                                 TargetVersion = glslang::EShTargetSpv_1_3;
641                             } else if (strcmp(argv[1], "spirv1.4") == 0) {
642                                 TargetLanguage = glslang::EShTargetSpv;
643                                 TargetVersion = glslang::EShTargetSpv_1_4;
644                             } else if (strcmp(argv[1], "spirv1.5") == 0) {
645                                 TargetLanguage = glslang::EShTargetSpv;
646                                 TargetVersion = glslang::EShTargetSpv_1_5;
647                             } else
648                                 Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2, opengl,\n"
649                                       "spirv1.0, spirv1.1, spirv1.2, spirv1.3, spirv1.4, or spirv1.5");
650                         }
651                         bumpArg();
652                     } else if (lowerword == "undef-macro" ||
653                                lowerword == "u") {
654                         if (argc > 1)
655                             UserPreamble.addUndef(argv[1]);
656                         else
657                             Error("expects <name>", argv[0]);
658                         bumpArg();
659                     } else if (lowerword == "variable-name" || // synonyms
660                                lowerword == "vn") {
661                         Options |= EOptionOutputHexadecimal;
662                         if (argc <= 1)
663                             Error("no <C-variable-name> provided", lowerword.c_str());
664                         variableName = argv[1];
665                         bumpArg();
666                         break;
667                     } else if (lowerword == "quiet") {
668                         beQuiet = true;
669                     } else if (lowerword == "version") {
670                         Options |= EOptionDumpVersions;
671                     } else if (lowerword == "help") {
672                         usage();
673                         break;
674                     } else {
675                         Error("unrecognized command-line option", argv[0]);
676                     }
677                 }
678                 break;
679             case 'C':
680                 Options |= EOptionCascadingErrors;
681                 break;
682             case 'D':
683                 if (argv[0][2] == 0)
684                     Options |= EOptionReadHlsl;
685                 else
686                     UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
687                 break;
688             case 'u':
689                 uniformLocationOverrides.push_back(getUniformOverride());
690                 break;
691             case 'E':
692                 Options |= EOptionOutputPreprocessed;
693                 break;
694             case 'G':
695                 // OpenGL client
696                 setOpenGlSpv();
697                 if (argv[0][2] != 0)
698                     ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
699                 if (ClientInputSemanticsVersion != 100)
700                     Error("unknown client version for -G, should be 100");
701                 break;
702             case 'H':
703                 Options |= EOptionHumanReadableSpv;
704                 if ((Options & EOptionSpv) == 0) {
705                     // default to Vulkan
706                     setVulkanSpv();
707                 }
708                 break;
709             case 'I':
710                 IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
711                 break;
712             case 'O':
713                 if (argv[0][2] == 'd')
714                     Options |= EOptionOptimizeDisable;
715                 else if (argv[0][2] == 's')
716 #if ENABLE_OPT
717                     Options |= EOptionOptimizeSize;
718 #else
719                     Error("-Os not available; optimizer not linked");
720 #endif
721                 else
722                     Error("unknown -O option");
723                 break;
724             case 'S':
725                 if (argc <= 1)
726                     Error("no <stage> specified for -S");
727                 shaderStageName = argv[1];
728                 bumpArg();
729                 break;
730             case 'U':
731                 UserPreamble.addUndef(getStringOperand("-U<name>"));
732                 break;
733             case 'V':
734                 setVulkanSpv();
735                 if (argv[0][2] != 0)
736                     ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
737                 if (ClientInputSemanticsVersion != 100)
738                     Error("unknown client version for -V, should be 100");
739                 break;
740             case 'c':
741                 Options |= EOptionDumpConfig;
742                 break;
743             case 'd':
744                 if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
745                     strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
746                     Options |= EOptionDumpBareVersion;
747                 else
748                     Options |= EOptionDefaultDesktop;
749                 break;
750             case 'e':
751                 entryPointName = argv[1];
752                 if (argc <= 1)
753                     Error("no <name> provided for -e");
754                 bumpArg();
755                 break;
756             case 'f':
757                 if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
758                     targetHlslFunctionality1 = true;
759                 else
760                     Error("-f: expected hlsl_functionality1");
761                 break;
762             case 'g':
763                 // Override previous -g or -g0 argument
764                 stripDebugInfo = false;
765                 Options &= ~EOptionDebug;
766                 if (argv[0][2] == '0')
767                     stripDebugInfo = true;
768                 else
769                     Options |= EOptionDebug;
770                 break;
771             case 'h':
772                 usage();
773                 break;
774             case 'i':
775                 Options |= EOptionIntermediate;
776                 break;
777             case 'l':
778                 Options |= EOptionLinkProgram;
779                 break;
780             case 'm':
781                 Options |= EOptionMemoryLeakMode;
782                 break;
783             case 'o':
784                 if (argc <= 1)
785                     Error("no <file> provided for -o");
786                 binaryFileName = argv[1];
787                 bumpArg();
788                 break;
789             case 'q':
790                 Options |= EOptionDumpReflection;
791                 break;
792             case 'r':
793                 Options |= EOptionRelaxedErrors;
794                 break;
795             case 's':
796                 Options |= EOptionSuppressInfolog;
797                 break;
798             case 't':
799                 Options |= EOptionMultiThreaded;
800                 break;
801             case 'v':
802                 Options |= EOptionDumpVersions;
803                 break;
804             case 'w':
805                 Options |= EOptionSuppressWarnings;
806                 break;
807             case 'x':
808                 Options |= EOptionOutputHexadecimal;
809                 break;
810             default:
811                 Error("unrecognized command-line option", argv[0]);
812                 break;
813             }
814         } else {
815             std::string name(argv[0]);
816             if (! SetConfigFile(name)) {
817                 workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
818             }
819         }
820     }
821 
822     // Make sure that -S is always specified if --stdin is specified
823     if ((Options & EOptionStdin) && shaderStageName == nullptr)
824         Error("must provide -S when --stdin is given");
825 
826     // Make sure that -E is not specified alongside linking (which includes SPV generation)
827     // Or things that require linking
828     if (Options & EOptionOutputPreprocessed) {
829         if (Options & EOptionLinkProgram)
830             Error("can't use -E when linking is selected");
831         if (Options & EOptionDumpReflection)
832             Error("reflection requires linking, which can't be used when -E when is selected");
833     }
834 
835     // reflection requires linking
836     if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
837         Error("reflection requires -l for linking");
838 
839     // -o or -x makes no sense if there is no target binary
840     if (binaryFileName && (Options & EOptionSpv) == 0)
841         Error("no binary generation requested (e.g., -V)");
842 
843     if ((Options & EOptionFlattenUniformArrays) != 0 &&
844         (Options & EOptionReadHlsl) == 0)
845         Error("uniform array flattening only valid when compiling HLSL source.");
846 
847     // rationalize client and target language
848     if (TargetLanguage == glslang::EShTargetNone) {
849         switch (ClientVersion) {
850         case glslang::EShTargetVulkan_1_0:
851             TargetLanguage = glslang::EShTargetSpv;
852             TargetVersion = glslang::EShTargetSpv_1_0;
853             break;
854         case glslang::EShTargetVulkan_1_1:
855             TargetLanguage = glslang::EShTargetSpv;
856             TargetVersion = glslang::EShTargetSpv_1_3;
857             break;
858         case glslang::EShTargetVulkan_1_2:
859             TargetLanguage = glslang::EShTargetSpv;
860             TargetVersion = glslang::EShTargetSpv_1_5;
861             break;
862         case glslang::EShTargetOpenGL_450:
863             TargetLanguage = glslang::EShTargetSpv;
864             TargetVersion = glslang::EShTargetSpv_1_0;
865             break;
866         default:
867             break;
868         }
869     }
870     if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
871         Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
872 }
873 
874 //
875 // Translate the meaningful subset of command-line options to parser-behavior options.
876 //
SetMessageOptions(EShMessages & messages)877 void SetMessageOptions(EShMessages& messages)
878 {
879     if (Options & EOptionRelaxedErrors)
880         messages = (EShMessages)(messages | EShMsgRelaxedErrors);
881     if (Options & EOptionIntermediate)
882         messages = (EShMessages)(messages | EShMsgAST);
883     if (Options & EOptionSuppressWarnings)
884         messages = (EShMessages)(messages | EShMsgSuppressWarnings);
885     if (Options & EOptionSpv)
886         messages = (EShMessages)(messages | EShMsgSpvRules);
887     if (Options & EOptionVulkanRules)
888         messages = (EShMessages)(messages | EShMsgVulkanRules);
889     if (Options & EOptionOutputPreprocessed)
890         messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
891     if (Options & EOptionReadHlsl)
892         messages = (EShMessages)(messages | EShMsgReadHlsl);
893     if (Options & EOptionCascadingErrors)
894         messages = (EShMessages)(messages | EShMsgCascadingErrors);
895     if (Options & EOptionKeepUncalled)
896         messages = (EShMessages)(messages | EShMsgKeepUncalled);
897     if (Options & EOptionHlslOffsets)
898         messages = (EShMessages)(messages | EShMsgHlslOffsets);
899     if (Options & EOptionDebug)
900         messages = (EShMessages)(messages | EShMsgDebugInfo);
901     if (HlslEnable16BitTypes)
902         messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
903     if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
904         messages = (EShMessages)(messages | EShMsgHlslLegalization);
905     if (HlslDX9compatible)
906         messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
907     if (DumpBuiltinSymbols)
908         messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
909 }
910 
911 //
912 // Thread entry point, for non-linking asynchronous mode.
913 //
CompileShaders(glslang::TWorklist & worklist)914 void CompileShaders(glslang::TWorklist& worklist)
915 {
916     if (Options & EOptionDebug)
917         Error("cannot generate debug information unless linking to generate code");
918 
919     glslang::TWorkItem* workItem;
920     if (Options & EOptionStdin) {
921         if (worklist.remove(workItem)) {
922             ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), Options);
923             if (compiler == nullptr)
924                 return;
925 
926             CompileFile("stdin", compiler);
927 
928             if (! (Options & EOptionSuppressInfolog))
929                 workItem->results = ShGetInfoLog(compiler);
930 
931             ShDestruct(compiler);
932         }
933     } else {
934         while (worklist.remove(workItem)) {
935             ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), Options);
936             if (compiler == 0)
937                 return;
938 
939             CompileFile(workItem->name.c_str(), compiler);
940 
941             if (! (Options & EOptionSuppressInfolog))
942                 workItem->results = ShGetInfoLog(compiler);
943 
944             ShDestruct(compiler);
945         }
946     }
947 }
948 
949 // Outputs the given string, but only if it is non-null and non-empty.
950 // This prevents erroneous newlines from appearing.
PutsIfNonEmpty(const char * str)951 void PutsIfNonEmpty(const char* str)
952 {
953     if (str && str[0]) {
954         puts(str);
955     }
956 }
957 
958 // Outputs the given string to stderr, but only if it is non-null and non-empty.
959 // This prevents erroneous newlines from appearing.
StderrIfNonEmpty(const char * str)960 void StderrIfNonEmpty(const char* str)
961 {
962     if (str && str[0])
963         fprintf(stderr, "%s\n", str);
964 }
965 
966 // Simple bundling of what makes a compilation unit for ease in passing around,
967 // and separation of handling file IO versus API (programmatic) compilation.
968 struct ShaderCompUnit {
969     EShLanguage stage;
970     static const int maxCount = 1;
971     int count;                          // live number of strings/names
972     const char* text[maxCount];         // memory owned/managed externally
973     std::string fileName[maxCount];     // hold's the memory, but...
974     const char* fileNameList[maxCount]; // downstream interface wants pointers
975 
ShaderCompUnitShaderCompUnit976     ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
977 
ShaderCompUnitShaderCompUnit978     ShaderCompUnit(const ShaderCompUnit& rhs)
979     {
980         stage = rhs.stage;
981         count = rhs.count;
982         for (int i = 0; i < count; ++i) {
983             fileName[i] = rhs.fileName[i];
984             text[i] = rhs.text[i];
985             fileNameList[i] = rhs.fileName[i].c_str();
986         }
987     }
988 
addStringShaderCompUnit989     void addString(std::string& ifileName, const char* itext)
990     {
991         assert(count < maxCount);
992         fileName[count] = ifileName;
993         text[count] = itext;
994         fileNameList[count] = fileName[count].c_str();
995         ++count;
996     }
997 };
998 
999 //
1000 // For linking mode: Will independently parse each compilation unit, but then put them
1001 // in the same program and link them together, making at most one linked module per
1002 // pipeline stage.
1003 //
1004 // Uses the new C++ interface instead of the old handle-based interface.
1005 //
1006 
CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)1007 void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
1008 {
1009     // keep track of what to free
1010     std::list<glslang::TShader*> shaders;
1011 
1012     EShMessages messages = EShMsgDefault;
1013     SetMessageOptions(messages);
1014 
1015     //
1016     // Per-shader processing...
1017     //
1018 
1019     glslang::TProgram& program = *new glslang::TProgram;
1020     for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
1021         const auto &compUnit = *it;
1022         glslang::TShader* shader = new glslang::TShader(compUnit.stage);
1023         shader->setStringsWithLengthsAndNames(compUnit.text, NULL, compUnit.fileNameList, compUnit.count);
1024         if (entryPointName)
1025             shader->setEntryPoint(entryPointName);
1026         if (sourceEntryPointName) {
1027             if (entryPointName == nullptr)
1028                 printf("Warning: Changing source entry point name without setting an entry-point name.\n"
1029                        "Use '-e <name>'.\n");
1030             shader->setSourceEntryPoint(sourceEntryPointName);
1031         }
1032         if (UserPreamble.isSet())
1033             shader->setPreamble(UserPreamble.get());
1034         shader->addProcesses(Processes);
1035 
1036 #ifndef GLSLANG_WEB
1037         // Set IO mapper binding shift values
1038         for (int r = 0; r < glslang::EResCount; ++r) {
1039             const glslang::TResourceType res = glslang::TResourceType(r);
1040 
1041             // Set base bindings
1042             shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
1043 
1044             // Set bindings for particular resource sets
1045             // TODO: use a range based for loop here, when available in all environments.
1046             for (auto i = baseBindingForSet[res][compUnit.stage].begin();
1047                  i != baseBindingForSet[res][compUnit.stage].end(); ++i)
1048                 shader->setShiftBindingForSet(res, i->second, i->first);
1049         }
1050         shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
1051         shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
1052 
1053         if (Options & EOptionAutoMapBindings)
1054             shader->setAutoMapBindings(true);
1055 
1056         if (Options & EOptionAutoMapLocations)
1057             shader->setAutoMapLocations(true);
1058 
1059         for (auto& uniOverride : uniformLocationOverrides) {
1060             shader->addUniformLocationOverride(uniOverride.first.c_str(),
1061                                                uniOverride.second);
1062         }
1063 
1064         shader->setUniformLocationBase(uniformBase);
1065 #endif
1066 
1067         shader->setNanMinMaxClamp(NaNClamp);
1068 
1069 #ifdef ENABLE_HLSL
1070         shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
1071         if (Options & EOptionHlslIoMapping)
1072             shader->setHlslIoMapping(true);
1073 #endif
1074 
1075         if (Options & EOptionInvertY)
1076             shader->setInvertY(true);
1077 
1078         // Set up the environment, some subsettings take precedence over earlier
1079         // ways of setting things.
1080         if (Options & EOptionSpv) {
1081             shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
1082                                                             : glslang::EShSourceGlsl,
1083                                 compUnit.stage, Client, ClientInputSemanticsVersion);
1084             shader->setEnvClient(Client, ClientVersion);
1085             shader->setEnvTarget(TargetLanguage, TargetVersion);
1086 #ifdef ENABLE_HLSL
1087             if (targetHlslFunctionality1)
1088                 shader->setEnvTargetHlslFunctionality1();
1089 #endif
1090         }
1091 
1092         shaders.push_back(shader);
1093 
1094         const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
1095 
1096         DirStackFileIncluder includer;
1097         std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
1098             includer.pushExternalLocalDirectory(dir); });
1099 #ifndef GLSLANG_WEB
1100         if (Options & EOptionOutputPreprocessed) {
1101             std::string str;
1102             if (shader->preprocess(&Resources, defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
1103                 PutsIfNonEmpty(str.c_str());
1104             } else {
1105                 CompileFailed = true;
1106             }
1107             StderrIfNonEmpty(shader->getInfoLog());
1108             StderrIfNonEmpty(shader->getInfoDebugLog());
1109             continue;
1110         }
1111 #endif
1112 
1113         if (! shader->parse(&Resources, defaultVersion, false, messages, includer))
1114             CompileFailed = true;
1115 
1116         program.addShader(shader);
1117 
1118         if (! (Options & EOptionSuppressInfolog) &&
1119             ! (Options & EOptionMemoryLeakMode)) {
1120             if (!beQuiet)
1121                 PutsIfNonEmpty(compUnit.fileName[0].c_str());
1122             PutsIfNonEmpty(shader->getInfoLog());
1123             PutsIfNonEmpty(shader->getInfoDebugLog());
1124         }
1125     }
1126 
1127     //
1128     // Program-level processing...
1129     //
1130 
1131     // Link
1132     if (! (Options & EOptionOutputPreprocessed) && ! program.link(messages))
1133         LinkFailed = true;
1134 
1135 #ifndef GLSLANG_WEB
1136     // Map IO
1137     if (Options & EOptionSpv) {
1138         if (!program.mapIO())
1139             LinkFailed = true;
1140     }
1141 #endif
1142 
1143     // Report
1144     if (! (Options & EOptionSuppressInfolog) &&
1145         ! (Options & EOptionMemoryLeakMode)) {
1146         PutsIfNonEmpty(program.getInfoLog());
1147         PutsIfNonEmpty(program.getInfoDebugLog());
1148     }
1149 
1150 #ifndef GLSLANG_WEB
1151     // Reflect
1152     if (Options & EOptionDumpReflection) {
1153         program.buildReflection(ReflectOptions);
1154         program.dumpReflection();
1155     }
1156 #endif
1157 
1158     // Dump SPIR-V
1159     if (Options & EOptionSpv) {
1160         if (CompileFailed || LinkFailed)
1161             printf("SPIR-V is not generated for failed compile or link\n");
1162         else {
1163             for (int stage = 0; stage < EShLangCount; ++stage) {
1164                 if (program.getIntermediate((EShLanguage)stage)) {
1165                     std::vector<unsigned int> spirv;
1166                     spv::SpvBuildLogger logger;
1167                     glslang::SpvOptions spvOptions;
1168                     if (Options & EOptionDebug)
1169                         spvOptions.generateDebugInfo = true;
1170                     else if (stripDebugInfo)
1171                         spvOptions.stripDebugInfo = true;
1172                     spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
1173                     spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
1174                     spvOptions.disassemble = SpvToolsDisassembler;
1175                     spvOptions.validate = SpvToolsValidate;
1176                     glslang::GlslangToSpv(*program.getIntermediate((EShLanguage)stage), spirv, &logger, &spvOptions);
1177 
1178                     // Dump the spv to a file or stdout, etc., but only if not doing
1179                     // memory/perf testing, as it's not internal to programmatic use.
1180                     if (! (Options & EOptionMemoryLeakMode)) {
1181                         printf("%s", logger.getAllMessages().c_str());
1182                         if (Options & EOptionOutputHexadecimal) {
1183                             glslang::OutputSpvHex(spirv, GetBinaryName((EShLanguage)stage), variableName);
1184                         } else {
1185                             glslang::OutputSpvBin(spirv, GetBinaryName((EShLanguage)stage));
1186                         }
1187 #ifndef GLSLANG_WEB
1188                         if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
1189                             spv::Disassemble(std::cout, spirv);
1190 #endif
1191                     }
1192                 }
1193             }
1194         }
1195     }
1196 
1197     // Free everything up, program has to go before the shaders
1198     // because it might have merged stuff from the shaders, and
1199     // the stuff from the shaders has to have its destructors called
1200     // before the pools holding the memory in the shaders is freed.
1201     delete &program;
1202     while (shaders.size() > 0) {
1203         delete shaders.back();
1204         shaders.pop_back();
1205     }
1206 }
1207 
1208 //
1209 // Do file IO part of compile and link, handing off the pure
1210 // API/programmatic mode to CompileAndLinkShaderUnits(), which can
1211 // be put in a loop for testing memory footprint and performance.
1212 //
1213 // This is just for linking mode: meaning all the shaders will be put into the
1214 // the same program linked together.
1215 //
1216 // This means there are a limited number of work items (not multi-threading mode)
1217 // and that the point is testing at the linking level. Hence, to enable
1218 // performance and memory testing, the actual compile/link can be put in
1219 // a loop, independent of processing the work items and file IO.
1220 //
CompileAndLinkShaderFiles(glslang::TWorklist & Worklist)1221 void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
1222 {
1223     std::vector<ShaderCompUnit> compUnits;
1224 
1225     // If this is using stdin, we can't really detect multiple different file
1226     // units by input type. We need to assume that we're just being given one
1227     // file of a certain type.
1228     if ((Options & EOptionStdin) != 0) {
1229         ShaderCompUnit compUnit(FindLanguage("stdin"));
1230         std::istreambuf_iterator<char> begin(std::cin), end;
1231         std::string tempString(begin, end);
1232         char* fileText = strdup(tempString.c_str());
1233         std::string fileName = "stdin";
1234         compUnit.addString(fileName, fileText);
1235         compUnits.push_back(compUnit);
1236     } else {
1237         // Transfer all the work items from to a simple list of
1238         // of compilation units.  (We don't care about the thread
1239         // work-item distribution properties in this path, which
1240         // is okay due to the limited number of shaders, know since
1241         // they are all getting linked together.)
1242         glslang::TWorkItem* workItem;
1243         while (Worklist.remove(workItem)) {
1244             ShaderCompUnit compUnit(FindLanguage(workItem->name));
1245             char* fileText = ReadFileData(workItem->name.c_str());
1246             if (fileText == nullptr)
1247                 usage();
1248             compUnit.addString(workItem->name, fileText);
1249             compUnits.push_back(compUnit);
1250         }
1251     }
1252 
1253     // Actual call to programmatic processing of compile and link,
1254     // in a loop for testing memory and performance.  This part contains
1255     // all the perf/memory that a programmatic consumer will care about.
1256     for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1257         for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
1258            CompileAndLinkShaderUnits(compUnits);
1259 
1260         if (Options & EOptionMemoryLeakMode)
1261             glslang::OS_DumpMemoryCounters();
1262     }
1263 
1264     // free memory from ReadFileData, which got stored in a const char*
1265     // as the first string above
1266     for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
1267         FreeFileData(const_cast<char*>(it->text[0]));
1268 }
1269 
singleMain()1270 int singleMain()
1271 {
1272     glslang::TWorklist workList;
1273     std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
1274         assert(item);
1275         workList.add(item.get());
1276     });
1277 
1278 #ifndef GLSLANG_WEB
1279     if (Options & EOptionDumpConfig) {
1280         printf("%s", glslang::GetDefaultTBuiltInResourceString().c_str());
1281         if (workList.empty())
1282             return ESuccess;
1283     }
1284 #endif
1285 
1286     if (Options & EOptionDumpBareVersion) {
1287         printf("%d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR, GLSLANG_VERSION_MINOR,
1288                 GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1289         if (workList.empty())
1290             return ESuccess;
1291     } else if (Options & EOptionDumpVersions) {
1292         printf("Glslang Version: %d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR,
1293                 GLSLANG_VERSION_MINOR, GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
1294         printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
1295         printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
1296         std::string spirvVersion;
1297         glslang::GetSpirvVersion(spirvVersion);
1298         printf("SPIR-V Version %s\n", spirvVersion.c_str());
1299         printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
1300         printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
1301         printf("SPIR-V Generator Version %d\n", glslang::GetSpirvGeneratorVersion());
1302         printf("GL_KHR_vulkan_glsl version %d\n", 100);
1303         printf("ARB_GL_gl_spirv version %d\n", 100);
1304         if (workList.empty())
1305             return ESuccess;
1306     }
1307 
1308     if (workList.empty() && ((Options & EOptionStdin) == 0)) {
1309         usage();
1310     }
1311 
1312     if (Options & EOptionStdin) {
1313         WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
1314         workList.add(WorkItems.back().get());
1315     }
1316 
1317     ProcessConfigFile();
1318 
1319     if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
1320         Error("HLSL requires SPIR-V code generation (or preprocessing only)");
1321 
1322     //
1323     // Two modes:
1324     // 1) linking all arguments together, single-threaded, new C++ interface
1325     // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
1326     //
1327     if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
1328         glslang::InitializeProcess();
1329         glslang::InitializeProcess();  // also test reference counting of users
1330         glslang::InitializeProcess();  // also test reference counting of users
1331         glslang::FinalizeProcess();    // also test reference counting of users
1332         glslang::FinalizeProcess();    // also test reference counting of users
1333         CompileAndLinkShaderFiles(workList);
1334         glslang::FinalizeProcess();
1335     } else {
1336         ShInitialize();
1337         ShInitialize();  // also test reference counting of users
1338         ShFinalize();    // also test reference counting of users
1339 
1340         bool printShaderNames = workList.size() > 1;
1341 
1342         if (Options & EOptionMultiThreaded) {
1343             std::array<std::thread, 16> threads;
1344             for (unsigned int t = 0; t < threads.size(); ++t) {
1345                 threads[t] = std::thread(CompileShaders, std::ref(workList));
1346                 if (threads[t].get_id() == std::thread::id()) {
1347                     fprintf(stderr, "Failed to create thread\n");
1348                     return EFailThreadCreate;
1349                 }
1350             }
1351 
1352             std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
1353         } else
1354             CompileShaders(workList);
1355 
1356         // Print out all the resulting infologs
1357         for (size_t w = 0; w < WorkItems.size(); ++w) {
1358             if (WorkItems[w]) {
1359                 if (printShaderNames || WorkItems[w]->results.size() > 0)
1360                     PutsIfNonEmpty(WorkItems[w]->name.c_str());
1361                 PutsIfNonEmpty(WorkItems[w]->results.c_str());
1362             }
1363         }
1364 
1365         ShFinalize();
1366     }
1367 
1368     if (CompileFailed)
1369         return EFailCompile;
1370     if (LinkFailed)
1371         return EFailLink;
1372 
1373     return 0;
1374 }
1375 
main(int argc,char * argv[])1376 int C_DECL main(int argc, char* argv[])
1377 {
1378     ProcessArguments(WorkItems, argc, argv);
1379 
1380     int ret = 0;
1381 
1382     // Loop over the entire init/finalize cycle to watch memory changes
1383     const int iterations = 1;
1384     if (iterations > 1)
1385         glslang::OS_DumpMemoryCounters();
1386     for (int i = 0; i < iterations; ++i) {
1387         ret = singleMain();
1388         if (iterations > 1)
1389             glslang::OS_DumpMemoryCounters();
1390     }
1391 
1392     return ret;
1393 }
1394 
1395 //
1396 //   Deduce the language from the filename.  Files must end in one of the
1397 //   following extensions:
1398 //
1399 //   .vert = vertex
1400 //   .tesc = tessellation control
1401 //   .tese = tessellation evaluation
1402 //   .geom = geometry
1403 //   .frag = fragment
1404 //   .comp = compute
1405 //   .rgen = ray generation
1406 //   .rint = ray intersection
1407 //   .rahit = ray any hit
1408 //   .rchit = ray closest hit
1409 //   .rmiss = ray miss
1410 //   .rcall = ray callable
1411 //   .mesh  = mesh
1412 //   .task  = task
1413 //   Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
1414 //   where <stage> is one of the stages listed above.
1415 //
FindLanguage(const std::string & name,bool parseStageName)1416 EShLanguage FindLanguage(const std::string& name, bool parseStageName)
1417 {
1418     std::string stageName;
1419     if (shaderStageName)
1420         stageName = shaderStageName;
1421     else if (parseStageName) {
1422         // Note: "first" extension means "first from the end", i.e.
1423         // if the file is named foo.vert.glsl, then "glsl" is first,
1424         // "vert" is second.
1425         size_t firstExtStart = name.find_last_of(".");
1426         bool hasFirstExt = firstExtStart != std::string::npos;
1427         size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
1428         bool hasSecondExt = secondExtStart != std::string::npos;
1429         std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
1430         bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
1431         if (usesUnifiedExt && firstExt == "hlsl")
1432             Options |= EOptionReadHlsl;
1433         if (hasFirstExt && !usesUnifiedExt)
1434             stageName = firstExt;
1435         else if (usesUnifiedExt && hasSecondExt)
1436             stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
1437         else {
1438             usage();
1439             return EShLangVertex;
1440         }
1441     } else
1442         stageName = name;
1443 
1444     if (stageName == "vert")
1445         return EShLangVertex;
1446     else if (stageName == "tesc")
1447         return EShLangTessControl;
1448     else if (stageName == "tese")
1449         return EShLangTessEvaluation;
1450     else if (stageName == "geom")
1451         return EShLangGeometry;
1452     else if (stageName == "frag")
1453         return EShLangFragment;
1454     else if (stageName == "comp")
1455         return EShLangCompute;
1456     else if (stageName == "rgen")
1457         return EShLangRayGen;
1458     else if (stageName == "rint")
1459         return EShLangIntersect;
1460     else if (stageName == "rahit")
1461         return EShLangAnyHit;
1462     else if (stageName == "rchit")
1463         return EShLangClosestHit;
1464     else if (stageName == "rmiss")
1465         return EShLangMiss;
1466     else if (stageName == "rcall")
1467         return EShLangCallable;
1468     else if (stageName == "mesh")
1469         return EShLangMeshNV;
1470     else if (stageName == "task")
1471         return EShLangTaskNV;
1472 
1473     usage();
1474     return EShLangVertex;
1475 }
1476 
1477 //
1478 // Read a file's data into a string, and compile it using the old interface ShCompile,
1479 // for non-linkable results.
1480 //
CompileFile(const char * fileName,ShHandle compiler)1481 void CompileFile(const char* fileName, ShHandle compiler)
1482 {
1483     int ret = 0;
1484     char* shaderString;
1485     if ((Options & EOptionStdin) != 0) {
1486         std::istreambuf_iterator<char> begin(std::cin), end;
1487         std::string tempString(begin, end);
1488         shaderString = strdup(tempString.c_str());
1489     } else {
1490         shaderString = ReadFileData(fileName);
1491     }
1492 
1493     // move to length-based strings, rather than null-terminated strings
1494     int* lengths = new int[1];
1495     lengths[0] = (int)strlen(shaderString);
1496 
1497     EShMessages messages = EShMsgDefault;
1498     SetMessageOptions(messages);
1499 
1500     if (UserPreamble.isSet())
1501         Error("-D and -U options require -l (linking)\n");
1502 
1503     for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
1504         for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
1505             // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1506             ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1507             // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
1508             //                         "or should be l", "ine 1", "string 5\n", "float glo", "bal",
1509             //                         ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
1510             // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
1511             // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
1512         }
1513 
1514         if (Options & EOptionMemoryLeakMode)
1515             glslang::OS_DumpMemoryCounters();
1516     }
1517 
1518     delete [] lengths;
1519     FreeFileData(shaderString);
1520 
1521     if (ret == 0)
1522         CompileFailed = true;
1523 }
1524 
1525 //
1526 //   print usage to stdout
1527 //
usage()1528 void usage()
1529 {
1530     printf("Usage: glslangValidator [option]... [file]...\n"
1531            "\n"
1532            "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
1533            "    .conf   to provide a config file that replaces the default configuration\n"
1534            "            (see -c option below for generating a template)\n"
1535            "    .vert   for a vertex shader\n"
1536            "    .tesc   for a tessellation control shader\n"
1537            "    .tese   for a tessellation evaluation shader\n"
1538            "    .geom   for a geometry shader\n"
1539            "    .frag   for a fragment shader\n"
1540            "    .comp   for a compute shader\n"
1541            "    .mesh   for a mesh shader\n"
1542            "    .task   for a task shader\n"
1543            "    .rgen    for a ray generation shader\n"
1544            "    .rint    for a ray intersection shader\n"
1545            "    .rahit   for a ray any hit shader\n"
1546            "    .rchit   for a ray closest hit shader\n"
1547            "    .rmiss   for a ray miss shader\n"
1548            "    .rcall   for a ray callable shader\n"
1549            "    .glsl   for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
1550            "    .hlsl   for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
1551            "\n"
1552            "Options:\n"
1553            "  -C          cascading errors; risk crash from accumulation of error recoveries\n"
1554            "  -D          input is HLSL (this is the default when any suffix is .hlsl)\n"
1555            "  -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]>\n"
1556            "              define a pre-processor macro\n"
1557            "  -E          print pre-processed GLSL; cannot be used with -l;\n"
1558            "              errors will appear on stderr\n"
1559            "  -G[ver]     create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
1560            "              default file name is <stage>.spv (-o overrides this);\n"
1561            "              'ver', when present, is the version of the input semantics,\n"
1562            "              which will appear in #define GL_SPIRV ver;\n"
1563            "              '--client opengl100' is the same as -G100;\n"
1564            "              a '--target-env' for OpenGL will also imply '-G'\n"
1565            "  -H          print human readable form of SPIR-V; turns on -V\n"
1566            "  -I<dir>     add dir to the include search path; includer's directory\n"
1567            "              is searched first, followed by left-to-right order of -I\n"
1568            "  -Od         disables optimization; may cause illegal SPIR-V for HLSL\n"
1569            "  -Os         optimizes SPIR-V to minimize size\n"
1570            "  -S <stage>  uses specified stage rather than parsing the file extension\n"
1571            "              choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
1572            "  -U<name> | --undef-macro <name> | --U <name>\n"
1573            "              undefine a pre-processor macro\n"
1574            "  -V[ver]     create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
1575            "              default file name is <stage>.spv (-o overrides this)\n"
1576            "              'ver', when present, is the version of the input semantics,\n"
1577            "              which will appear in #define VULKAN ver\n"
1578            "              '--client vulkan100' is the same as -V100\n"
1579            "              a '--target-env' for Vulkan will also imply '-V'\n"
1580            "  -c          configuration dump;\n"
1581            "              creates the default configuration file (redirect to a .conf file)\n"
1582            "  -d          default to desktop (#version 110) when there is no shader #version\n"
1583            "              (default is ES version 100)\n"
1584            "  -e <name> | --entry-point <name>\n"
1585            "              specify <name> as the entry-point function name\n"
1586            "  -f{hlsl_functionality1}\n"
1587            "              'hlsl_functionality1' enables use of the\n"
1588            "              SPV_GOOGLE_hlsl_functionality1 extension\n"
1589            "  -g          generate debug information\n"
1590            "  -g0         strip debug information\n"
1591            "  -h          print this usage message\n"
1592            "  -i          intermediate tree (glslang AST) is printed out\n"
1593            "  -l          link all input files together to form a single module\n"
1594            "  -m          memory leak mode\n"
1595            "  -o <file>   save binary to <file>, requires a binary option (e.g., -V)\n"
1596            "  -q          dump reflection query database; requires -l for linking\n"
1597            "  -r | --relaxed-errors"
1598            "              relaxed GLSL semantic error-checking mode\n"
1599            "  -s          silence syntax and semantic error reporting\n"
1600            "  -t          multi-threaded mode\n"
1601            "  -v | --version\n"
1602            "              print version strings\n"
1603            "  -w | --suppress-warnings\n"
1604            "              suppress GLSL warnings, except as required by \"#extension : warn\"\n"
1605            "  -x          save binary output as text-based 32-bit hexadecimal numbers\n"
1606            "  -u<name>:<loc> specify a uniform location override for --aml\n"
1607            "  --uniform-base <base> set a base to use for generated uniform locations\n"
1608            "  --auto-map-bindings | --amb       automatically bind uniform variables\n"
1609            "                                    without explicit bindings\n"
1610            "  --auto-map-locations | --aml      automatically locate input/output lacking\n"
1611            "                                    'location' (fragile, not cross stage)\n"
1612            "  --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
1613            "  --dump-builtin-symbols            prints builtin symbol table prior each compile\n"
1614            "  -dumpfullversion | -dumpversion   print bare major.minor.patchlevel\n"
1615            "  --flatten-uniform-arrays | --fua  flatten uniform texture/sampler arrays to\n"
1616            "                                    scalars\n"
1617            "  --hlsl-offsets                    allow block offsets to follow HLSL rules\n"
1618            "                                    works independently of source language\n"
1619            "  --hlsl-iomap                      perform IO mapping in HLSL register space\n"
1620            "  --hlsl-enable-16bit-types         allow 16-bit types in SPIR-V for HLSL\n"
1621            "  --hlsl-dx9-compatible             interprets sampler declarations as a\n"
1622            "                                    texture/sampler combo like DirectX9 would,\n"
1623            "                                    and recognizes DirectX9-specific semantics\n"
1624            "  --invert-y | --iy                 invert position.Y output in vertex shader\n"
1625            "  --keep-uncalled | --ku            don't eliminate uncalled functions\n"
1626            "  --nan-clamp                       favor non-NaN operand in min, max, and clamp\n"
1627            "  --no-storage-format | --nsf       use Unknown image format\n"
1628            "  --quiet                           do not print anything to stdout, unless\n"
1629            "                                    requested by another option\n"
1630            "  --reflect-strict-array-suffix     use strict array suffix rules when\n"
1631            "                                    reflecting\n"
1632            "  --reflect-basic-array-suffix      arrays of basic types will have trailing [0]\n"
1633            "  --reflect-intermediate-io         reflection includes inputs/outputs of linked\n"
1634            "                                    shaders rather than just vertex/fragment\n"
1635            "  --reflect-separate-buffers        reflect buffer variables and blocks\n"
1636            "                                    separately to uniforms\n"
1637            "  --reflect-all-block-variables     reflect all variables in blocks, whether\n"
1638            "                                    inactive or active\n"
1639            "  --reflect-unwrap-io-blocks        unwrap input/output blocks the same as\n"
1640            "                                    uniform blocks\n"
1641            "  --resource-set-binding [stage] name set binding\n"
1642            "                                    set descriptor set and binding for\n"
1643            "                                    individual resources\n"
1644            "  --resource-set-binding [stage] set\n"
1645            "                                    set descriptor set for all resources\n"
1646            "  --rsb                             synonym for --resource-set-binding\n"
1647            "  --shift-image-binding [stage] num\n"
1648            "                                    base binding number for images (uav)\n"
1649            "  --shift-image-binding [stage] [num set]...\n"
1650            "                                    per-descriptor-set shift values\n"
1651            "  --sib                             synonym for --shift-image-binding\n"
1652            "  --shift-sampler-binding [stage] num\n"
1653            "                                    base binding number for samplers\n"
1654            "  --shift-sampler-binding [stage] [num set]...\n"
1655            "                                    per-descriptor-set shift values\n"
1656            "  --ssb                             synonym for --shift-sampler-binding\n"
1657            "  --shift-ssbo-binding [stage] num  base binding number for SSBOs\n"
1658            "  --shift-ssbo-binding [stage] [num set]...\n"
1659            "                                    per-descriptor-set shift values\n"
1660            "  --sbb                             synonym for --shift-ssbo-binding\n"
1661            "  --shift-texture-binding [stage] num\n"
1662            "                                    base binding number for textures\n"
1663            "  --shift-texture-binding [stage] [num set]...\n"
1664            "                                    per-descriptor-set shift values\n"
1665            "  --stb                             synonym for --shift-texture-binding\n"
1666            "  --shift-uav-binding [stage] num   base binding number for UAVs\n"
1667            "  --shift-uav-binding [stage] [num set]...\n"
1668            "                                    per-descriptor-set shift values\n"
1669            "  --suavb                           synonym for --shift-uav-binding\n"
1670            "  --shift-UBO-binding [stage] num   base binding number for UBOs\n"
1671            "  --shift-UBO-binding [stage] [num set]...\n"
1672            "                                    per-descriptor-set shift values\n"
1673            "  --sub                             synonym for --shift-UBO-binding\n"
1674            "  --shift-cbuffer-binding | --scb   synonyms for --shift-UBO-binding\n"
1675            "  --spirv-dis                       output standard-form disassembly; works only\n"
1676            "                                    when a SPIR-V generation option is also used\n"
1677            "  --spirv-val                       execute the SPIRV-Tools validator\n"
1678            "  --source-entrypoint <name>        the given shader source function is\n"
1679            "                                    renamed to be the <name> given in -e\n"
1680            "  --sep                             synonym for --source-entrypoint\n"
1681            "  --stdin                           read from stdin instead of from a file;\n"
1682            "                                    requires providing the shader stage using -S\n"
1683            "  --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | opengl | \n"
1684            "                spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 | spirv1.5}\n"
1685            "                                    Set the execution environment that the\n"
1686            "                                    generated code will be executed in.\n"
1687            "                                    Defaults to:\n"
1688            "                                     * vulkan1.0 under --client vulkan<ver>\n"
1689            "                                     * opengl    under --client opengl<ver>\n"
1690            "                                     * spirv1.0  under --target-env vulkan1.0\n"
1691            "                                     * spirv1.3  under --target-env vulkan1.1\n"
1692            "                                     * spirv1.5  under --target-env vulkan1.2\n"
1693            "                                    Multiple --target-env can be specified.\n"
1694            "  --variable-name <name>\n"
1695            "  --vn <name>                       creates a C header file that contains a\n"
1696            "                                    uint32_t array named <name>\n"
1697            "                                    initialized with the shader binary code\n"
1698            );
1699 
1700     exit(EFailUsage);
1701 }
1702 
1703 #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
1704 
1705 #include <errno.h>
1706 
fopen_s(FILE ** pFile,const char * filename,const char * mode)1707 int fopen_s(
1708    FILE** pFile,
1709    const char* filename,
1710    const char* mode
1711 )
1712 {
1713    if (!pFile || !filename || !mode) {
1714       return EINVAL;
1715    }
1716 
1717    FILE* f = fopen(filename, mode);
1718    if (! f) {
1719       if (errno != 0) {
1720          return errno;
1721       } else {
1722          return ENOENT;
1723       }
1724    }
1725    *pFile = f;
1726 
1727    return 0;
1728 }
1729 
1730 #endif
1731 
1732 //
1733 //   Malloc a string of sufficient size and read a string into it.
1734 //
ReadFileData(const char * fileName)1735 char* ReadFileData(const char* fileName)
1736 {
1737     FILE *in = nullptr;
1738     int errorCode = fopen_s(&in, fileName, "r");
1739     if (errorCode || in == nullptr)
1740         Error("unable to open input file");
1741 
1742     int count = 0;
1743     while (fgetc(in) != EOF)
1744         count++;
1745 
1746     fseek(in, 0, SEEK_SET);
1747 
1748     char* return_data = (char*)malloc(count + 1);  // freed in FreeFileData()
1749     if ((int)fread(return_data, 1, count, in) != count) {
1750         free(return_data);
1751         Error("can't read input file");
1752     }
1753 
1754     return_data[count] = '\0';
1755     fclose(in);
1756 
1757     return return_data;
1758 }
1759 
FreeFileData(char * data)1760 void FreeFileData(char* data)
1761 {
1762     free(data);
1763 }
1764 
InfoLogMsg(const char * msg,const char * name,const int num)1765 void InfoLogMsg(const char* msg, const char* name, const int num)
1766 {
1767     if (num >= 0 )
1768         printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
1769     else
1770         printf("#### %s %s INFO LOG ####\n", msg, name);
1771 }
1772