StandAlone.cpp 71 KB

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