StandAlone.cpp 72 KB

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