StandAlone.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  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 == "resource-set-bindings" || // synonyms
  494. lowerword == "resource-set-binding" ||
  495. lowerword == "rsb") {
  496. ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
  497. } else if (lowerword == "shift-image-bindings" || // synonyms
  498. lowerword == "shift-image-binding" ||
  499. lowerword == "sib") {
  500. ProcessBindingBase(argc, argv, glslang::EResImage);
  501. } else if (lowerword == "shift-sampler-bindings" || // synonyms
  502. lowerword == "shift-sampler-binding" ||
  503. lowerword == "ssb") {
  504. ProcessBindingBase(argc, argv, glslang::EResSampler);
  505. } else if (lowerword == "shift-uav-bindings" || // synonyms
  506. lowerword == "shift-uav-binding" ||
  507. lowerword == "suavb") {
  508. ProcessBindingBase(argc, argv, glslang::EResUav);
  509. } else if (lowerword == "shift-texture-bindings" || // synonyms
  510. lowerword == "shift-texture-binding" ||
  511. lowerword == "stb") {
  512. ProcessBindingBase(argc, argv, glslang::EResTexture);
  513. } else if (lowerword == "shift-ubo-bindings" || // synonyms
  514. lowerword == "shift-ubo-binding" ||
  515. lowerword == "shift-cbuffer-bindings" ||
  516. lowerword == "shift-cbuffer-binding" ||
  517. lowerword == "sub" ||
  518. lowerword == "scb") {
  519. ProcessBindingBase(argc, argv, glslang::EResUbo);
  520. } else if (lowerword == "shift-ssbo-bindings" || // synonyms
  521. lowerword == "shift-ssbo-binding" ||
  522. lowerword == "sbb") {
  523. ProcessBindingBase(argc, argv, glslang::EResSsbo);
  524. } else if (lowerword == "source-entrypoint" || // synonyms
  525. lowerword == "sep") {
  526. if (argc <= 1)
  527. Error("no <entry-point> provided", lowerword.c_str());
  528. sourceEntryPointName = argv[1];
  529. bumpArg();
  530. break;
  531. } else if (lowerword == "spirv-dis") {
  532. SpvToolsDisassembler = true;
  533. } else if (lowerword == "spirv-val") {
  534. SpvToolsValidate = true;
  535. } else if (lowerword == "stdin") {
  536. Options |= EOptionStdin;
  537. shaderStageName = argv[1];
  538. } else if (lowerword == "suppress-warnings") {
  539. Options |= EOptionSuppressWarnings;
  540. } else if (lowerword == "target-env") {
  541. if (argc > 1) {
  542. if (strcmp(argv[1], "vulkan1.0") == 0) {
  543. setVulkanSpv();
  544. ClientVersion = glslang::EShTargetVulkan_1_0;
  545. } else if (strcmp(argv[1], "vulkan1.1") == 0) {
  546. setVulkanSpv();
  547. ClientVersion = glslang::EShTargetVulkan_1_1;
  548. } else if (strcmp(argv[1], "vulkan1.2") == 0) {
  549. setVulkanSpv();
  550. ClientVersion = glslang::EShTargetVulkan_1_2;
  551. } else if (strcmp(argv[1], "opengl") == 0) {
  552. setOpenGlSpv();
  553. ClientVersion = glslang::EShTargetOpenGL_450;
  554. } else if (strcmp(argv[1], "spirv1.0") == 0) {
  555. TargetLanguage = glslang::EShTargetSpv;
  556. TargetVersion = glslang::EShTargetSpv_1_0;
  557. } else if (strcmp(argv[1], "spirv1.1") == 0) {
  558. TargetLanguage = glslang::EShTargetSpv;
  559. TargetVersion = glslang::EShTargetSpv_1_1;
  560. } else if (strcmp(argv[1], "spirv1.2") == 0) {
  561. TargetLanguage = glslang::EShTargetSpv;
  562. TargetVersion = glslang::EShTargetSpv_1_2;
  563. } else if (strcmp(argv[1], "spirv1.3") == 0) {
  564. TargetLanguage = glslang::EShTargetSpv;
  565. TargetVersion = glslang::EShTargetSpv_1_3;
  566. } else if (strcmp(argv[1], "spirv1.4") == 0) {
  567. TargetLanguage = glslang::EShTargetSpv;
  568. TargetVersion = glslang::EShTargetSpv_1_4;
  569. } else if (strcmp(argv[1], "spirv1.5") == 0) {
  570. TargetLanguage = glslang::EShTargetSpv;
  571. TargetVersion = glslang::EShTargetSpv_1_5;
  572. } else
  573. Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2, opengl,\n"
  574. "spirv1.0, spirv1.1, spirv1.2, spirv1.3, spirv1.4, or spirv1.5");
  575. }
  576. bumpArg();
  577. } else if (lowerword == "undef-macro" ||
  578. lowerword == "u") {
  579. if (argc > 1)
  580. UserPreamble.addUndef(argv[1]);
  581. else
  582. Error("expects <name>", argv[0]);
  583. bumpArg();
  584. } else if (lowerword == "variable-name" || // synonyms
  585. lowerword == "vn") {
  586. Options |= EOptionOutputHexadecimal;
  587. if (argc <= 1)
  588. Error("no <C-variable-name> provided", lowerword.c_str());
  589. variableName = argv[1];
  590. bumpArg();
  591. break;
  592. } else if (lowerword == "version") {
  593. Options |= EOptionDumpVersions;
  594. } else if (lowerword == "help") {
  595. usage();
  596. break;
  597. } else {
  598. Error("unrecognized command-line option", argv[0]);
  599. }
  600. }
  601. break;
  602. case 'C':
  603. Options |= EOptionCascadingErrors;
  604. break;
  605. case 'D':
  606. if (argv[0][2] == 0)
  607. Options |= EOptionReadHlsl;
  608. else
  609. UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
  610. break;
  611. case 'u':
  612. uniformLocationOverrides.push_back(getUniformOverride());
  613. break;
  614. case 'E':
  615. Options |= EOptionOutputPreprocessed;
  616. break;
  617. case 'G':
  618. // OpenGL client
  619. setOpenGlSpv();
  620. if (argv[0][2] != 0)
  621. ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
  622. break;
  623. case 'H':
  624. Options |= EOptionHumanReadableSpv;
  625. if ((Options & EOptionSpv) == 0) {
  626. // default to Vulkan
  627. setVulkanSpv();
  628. }
  629. break;
  630. case 'I':
  631. IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
  632. break;
  633. case 'O':
  634. if (argv[0][2] == 'd')
  635. Options |= EOptionOptimizeDisable;
  636. else if (argv[0][2] == 's')
  637. #if ENABLE_OPT
  638. Options |= EOptionOptimizeSize;
  639. #else
  640. Error("-Os not available; optimizer not linked");
  641. #endif
  642. else
  643. Error("unknown -O option");
  644. break;
  645. case 'S':
  646. if (argc <= 1)
  647. Error("no <stage> specified for -S");
  648. shaderStageName = argv[1];
  649. bumpArg();
  650. break;
  651. case 'U':
  652. UserPreamble.addUndef(getStringOperand("-U<name>"));
  653. break;
  654. case 'V':
  655. setVulkanSpv();
  656. if (argv[0][2] != 0)
  657. ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
  658. break;
  659. case 'c':
  660. Options |= EOptionDumpConfig;
  661. break;
  662. case 'd':
  663. if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
  664. strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
  665. Options |= EOptionDumpBareVersion;
  666. else
  667. Options |= EOptionDefaultDesktop;
  668. break;
  669. case 'e':
  670. entryPointName = argv[1];
  671. if (argc <= 1)
  672. Error("no <name> provided for -e");
  673. bumpArg();
  674. break;
  675. case 'f':
  676. if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
  677. targetHlslFunctionality1 = true;
  678. else
  679. Error("-f: expected hlsl_functionality1");
  680. break;
  681. case 'g':
  682. Options |= EOptionDebug;
  683. break;
  684. case 'h':
  685. usage();
  686. break;
  687. case 'i':
  688. Options |= EOptionIntermediate;
  689. break;
  690. case 'l':
  691. Options |= EOptionLinkProgram;
  692. break;
  693. case 'm':
  694. Options |= EOptionMemoryLeakMode;
  695. break;
  696. case 'o':
  697. if (argc <= 1)
  698. Error("no <file> provided for -o");
  699. binaryFileName = argv[1];
  700. bumpArg();
  701. break;
  702. case 'q':
  703. Options |= EOptionDumpReflection;
  704. break;
  705. case 'r':
  706. Options |= EOptionRelaxedErrors;
  707. break;
  708. case 's':
  709. Options |= EOptionSuppressInfolog;
  710. break;
  711. case 't':
  712. Options |= EOptionMultiThreaded;
  713. break;
  714. case 'v':
  715. Options |= EOptionDumpVersions;
  716. break;
  717. case 'w':
  718. Options |= EOptionSuppressWarnings;
  719. break;
  720. case 'x':
  721. Options |= EOptionOutputHexadecimal;
  722. break;
  723. default:
  724. Error("unrecognized command-line option", argv[0]);
  725. break;
  726. }
  727. } else {
  728. std::string name(argv[0]);
  729. if (! SetConfigFile(name)) {
  730. workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
  731. }
  732. }
  733. }
  734. // Make sure that -S is always specified if --stdin is specified
  735. if ((Options & EOptionStdin) && shaderStageName == nullptr)
  736. Error("must provide -S when --stdin is given");
  737. // Make sure that -E is not specified alongside linking (which includes SPV generation)
  738. // Or things that require linking
  739. if (Options & EOptionOutputPreprocessed) {
  740. if (Options & EOptionLinkProgram)
  741. Error("can't use -E when linking is selected");
  742. if (Options & EOptionDumpReflection)
  743. Error("reflection requires linking, which can't be used when -E when is selected");
  744. }
  745. // reflection requires linking
  746. if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
  747. Error("reflection requires -l for linking");
  748. // -o or -x makes no sense if there is no target binary
  749. if (binaryFileName && (Options & EOptionSpv) == 0)
  750. Error("no binary generation requested (e.g., -V)");
  751. if ((Options & EOptionFlattenUniformArrays) != 0 &&
  752. (Options & EOptionReadHlsl) == 0)
  753. Error("uniform array flattening only valid when compiling HLSL source.");
  754. // rationalize client and target language
  755. if (TargetLanguage == glslang::EShTargetNone) {
  756. switch (ClientVersion) {
  757. case glslang::EShTargetVulkan_1_0:
  758. TargetLanguage = glslang::EShTargetSpv;
  759. TargetVersion = glslang::EShTargetSpv_1_0;
  760. break;
  761. case glslang::EShTargetVulkan_1_1:
  762. TargetLanguage = glslang::EShTargetSpv;
  763. TargetVersion = glslang::EShTargetSpv_1_3;
  764. break;
  765. case glslang::EShTargetVulkan_1_2:
  766. TargetLanguage = glslang::EShTargetSpv;
  767. TargetVersion = glslang::EShTargetSpv_1_5;
  768. break;
  769. case glslang::EShTargetOpenGL_450:
  770. TargetLanguage = glslang::EShTargetSpv;
  771. TargetVersion = glslang::EShTargetSpv_1_0;
  772. break;
  773. default:
  774. break;
  775. }
  776. }
  777. if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
  778. Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
  779. }
  780. //
  781. // Translate the meaningful subset of command-line options to parser-behavior options.
  782. //
  783. void SetMessageOptions(EShMessages& messages)
  784. {
  785. if (Options & EOptionRelaxedErrors)
  786. messages = (EShMessages)(messages | EShMsgRelaxedErrors);
  787. if (Options & EOptionIntermediate)
  788. messages = (EShMessages)(messages | EShMsgAST);
  789. if (Options & EOptionSuppressWarnings)
  790. messages = (EShMessages)(messages | EShMsgSuppressWarnings);
  791. if (Options & EOptionSpv)
  792. messages = (EShMessages)(messages | EShMsgSpvRules);
  793. if (Options & EOptionVulkanRules)
  794. messages = (EShMessages)(messages | EShMsgVulkanRules);
  795. if (Options & EOptionOutputPreprocessed)
  796. messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
  797. if (Options & EOptionReadHlsl)
  798. messages = (EShMessages)(messages | EShMsgReadHlsl);
  799. if (Options & EOptionCascadingErrors)
  800. messages = (EShMessages)(messages | EShMsgCascadingErrors);
  801. if (Options & EOptionKeepUncalled)
  802. messages = (EShMessages)(messages | EShMsgKeepUncalled);
  803. if (Options & EOptionHlslOffsets)
  804. messages = (EShMessages)(messages | EShMsgHlslOffsets);
  805. if (Options & EOptionDebug)
  806. messages = (EShMessages)(messages | EShMsgDebugInfo);
  807. if (HlslEnable16BitTypes)
  808. messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
  809. if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
  810. messages = (EShMessages)(messages | EShMsgHlslLegalization);
  811. if (HlslDX9compatible)
  812. messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
  813. if (DumpBuiltinSymbols)
  814. messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
  815. }
  816. //
  817. // Thread entry point, for non-linking asynchronous mode.
  818. //
  819. void CompileShaders(glslang::TWorklist& worklist)
  820. {
  821. if (Options & EOptionDebug)
  822. Error("cannot generate debug information unless linking to generate code");
  823. glslang::TWorkItem* workItem;
  824. if (Options & EOptionStdin) {
  825. if (worklist.remove(workItem)) {
  826. ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), Options);
  827. if (compiler == nullptr)
  828. return;
  829. CompileFile("stdin", compiler);
  830. if (! (Options & EOptionSuppressInfolog))
  831. workItem->results = ShGetInfoLog(compiler);
  832. ShDestruct(compiler);
  833. }
  834. } else {
  835. while (worklist.remove(workItem)) {
  836. ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), Options);
  837. if (compiler == 0)
  838. return;
  839. CompileFile(workItem->name.c_str(), compiler);
  840. if (! (Options & EOptionSuppressInfolog))
  841. workItem->results = ShGetInfoLog(compiler);
  842. ShDestruct(compiler);
  843. }
  844. }
  845. }
  846. // Outputs the given string, but only if it is non-null and non-empty.
  847. // This prevents erroneous newlines from appearing.
  848. void PutsIfNonEmpty(const char* str)
  849. {
  850. if (str && str[0]) {
  851. puts(str);
  852. }
  853. }
  854. // Outputs the given string to stderr, but only if it is non-null and non-empty.
  855. // This prevents erroneous newlines from appearing.
  856. void StderrIfNonEmpty(const char* str)
  857. {
  858. if (str && str[0])
  859. fprintf(stderr, "%s\n", str);
  860. }
  861. // Simple bundling of what makes a compilation unit for ease in passing around,
  862. // and separation of handling file IO versus API (programmatic) compilation.
  863. struct ShaderCompUnit {
  864. EShLanguage stage;
  865. static const int maxCount = 1;
  866. int count; // live number of strings/names
  867. const char* text[maxCount]; // memory owned/managed externally
  868. std::string fileName[maxCount]; // hold's the memory, but...
  869. const char* fileNameList[maxCount]; // downstream interface wants pointers
  870. ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
  871. ShaderCompUnit(const ShaderCompUnit& rhs)
  872. {
  873. stage = rhs.stage;
  874. count = rhs.count;
  875. for (int i = 0; i < count; ++i) {
  876. fileName[i] = rhs.fileName[i];
  877. text[i] = rhs.text[i];
  878. fileNameList[i] = rhs.fileName[i].c_str();
  879. }
  880. }
  881. void addString(std::string& ifileName, const char* itext)
  882. {
  883. assert(count < maxCount);
  884. fileName[count] = ifileName;
  885. text[count] = itext;
  886. fileNameList[count] = fileName[count].c_str();
  887. ++count;
  888. }
  889. };
  890. //
  891. // For linking mode: Will independently parse each compilation unit, but then put them
  892. // in the same program and link them together, making at most one linked module per
  893. // pipeline stage.
  894. //
  895. // Uses the new C++ interface instead of the old handle-based interface.
  896. //
  897. void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
  898. {
  899. // keep track of what to free
  900. std::list<glslang::TShader*> shaders;
  901. EShMessages messages = EShMsgDefault;
  902. SetMessageOptions(messages);
  903. //
  904. // Per-shader processing...
  905. //
  906. glslang::TProgram& program = *new glslang::TProgram;
  907. for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
  908. const auto &compUnit = *it;
  909. glslang::TShader* shader = new glslang::TShader(compUnit.stage);
  910. shader->setStringsWithLengthsAndNames(compUnit.text, NULL, compUnit.fileNameList, compUnit.count);
  911. if (entryPointName)
  912. shader->setEntryPoint(entryPointName);
  913. if (sourceEntryPointName) {
  914. if (entryPointName == nullptr)
  915. printf("Warning: Changing source entry point name without setting an entry-point name.\n"
  916. "Use '-e <name>'.\n");
  917. shader->setSourceEntryPoint(sourceEntryPointName);
  918. }
  919. if (UserPreamble.isSet())
  920. shader->setPreamble(UserPreamble.get());
  921. shader->addProcesses(Processes);
  922. #ifndef GLSLANG_WEB
  923. // Set IO mapper binding shift values
  924. for (int r = 0; r < glslang::EResCount; ++r) {
  925. const glslang::TResourceType res = glslang::TResourceType(r);
  926. // Set base bindings
  927. shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
  928. // Set bindings for particular resource sets
  929. // TODO: use a range based for loop here, when available in all environments.
  930. for (auto i = baseBindingForSet[res][compUnit.stage].begin();
  931. i != baseBindingForSet[res][compUnit.stage].end(); ++i)
  932. shader->setShiftBindingForSet(res, i->second, i->first);
  933. }
  934. shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
  935. shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
  936. if (Options & EOptionAutoMapBindings)
  937. shader->setAutoMapBindings(true);
  938. if (Options & EOptionAutoMapLocations)
  939. shader->setAutoMapLocations(true);
  940. for (auto& uniOverride : uniformLocationOverrides) {
  941. shader->addUniformLocationOverride(uniOverride.first.c_str(),
  942. uniOverride.second);
  943. }
  944. shader->setUniformLocationBase(uniformBase);
  945. #endif
  946. shader->setNanMinMaxClamp(NaNClamp);
  947. #ifdef ENABLE_HLSL
  948. shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
  949. if (Options & EOptionHlslIoMapping)
  950. shader->setHlslIoMapping(true);
  951. #endif
  952. if (Options & EOptionInvertY)
  953. shader->setInvertY(true);
  954. // Set up the environment, some subsettings take precedence over earlier
  955. // ways of setting things.
  956. if (Options & EOptionSpv) {
  957. shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
  958. : glslang::EShSourceGlsl,
  959. compUnit.stage, Client, ClientInputSemanticsVersion);
  960. shader->setEnvClient(Client, ClientVersion);
  961. shader->setEnvTarget(TargetLanguage, TargetVersion);
  962. #ifdef ENABLE_HLSL
  963. if (targetHlslFunctionality1)
  964. shader->setEnvTargetHlslFunctionality1();
  965. #endif
  966. }
  967. shaders.push_back(shader);
  968. const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
  969. DirStackFileIncluder includer;
  970. std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
  971. includer.pushExternalLocalDirectory(dir); });
  972. #ifndef GLSLANG_WEB
  973. if (Options & EOptionOutputPreprocessed) {
  974. std::string str;
  975. if (shader->preprocess(&Resources, defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
  976. PutsIfNonEmpty(str.c_str());
  977. } else {
  978. CompileFailed = true;
  979. }
  980. StderrIfNonEmpty(shader->getInfoLog());
  981. StderrIfNonEmpty(shader->getInfoDebugLog());
  982. continue;
  983. }
  984. #endif
  985. if (! shader->parse(&Resources, defaultVersion, false, messages, includer))
  986. CompileFailed = true;
  987. program.addShader(shader);
  988. if (! (Options & EOptionSuppressInfolog) &&
  989. ! (Options & EOptionMemoryLeakMode)) {
  990. PutsIfNonEmpty(compUnit.fileName[0].c_str());
  991. PutsIfNonEmpty(shader->getInfoLog());
  992. PutsIfNonEmpty(shader->getInfoDebugLog());
  993. }
  994. }
  995. //
  996. // Program-level processing...
  997. //
  998. // Link
  999. if (! (Options & EOptionOutputPreprocessed) && ! program.link(messages))
  1000. LinkFailed = true;
  1001. #ifndef GLSLANG_WEB
  1002. // Map IO
  1003. if (Options & EOptionSpv) {
  1004. if (!program.mapIO())
  1005. LinkFailed = true;
  1006. }
  1007. #endif
  1008. // Report
  1009. if (! (Options & EOptionSuppressInfolog) &&
  1010. ! (Options & EOptionMemoryLeakMode)) {
  1011. PutsIfNonEmpty(program.getInfoLog());
  1012. PutsIfNonEmpty(program.getInfoDebugLog());
  1013. }
  1014. #ifndef GLSLANG_WEB
  1015. // Reflect
  1016. if (Options & EOptionDumpReflection) {
  1017. program.buildReflection(ReflectOptions);
  1018. program.dumpReflection();
  1019. }
  1020. #endif
  1021. // Dump SPIR-V
  1022. if (Options & EOptionSpv) {
  1023. if (CompileFailed || LinkFailed)
  1024. printf("SPIR-V is not generated for failed compile or link\n");
  1025. else {
  1026. for (int stage = 0; stage < EShLangCount; ++stage) {
  1027. if (program.getIntermediate((EShLanguage)stage)) {
  1028. std::vector<unsigned int> spirv;
  1029. spv::SpvBuildLogger logger;
  1030. glslang::SpvOptions spvOptions;
  1031. if (Options & EOptionDebug)
  1032. spvOptions.generateDebugInfo = true;
  1033. spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
  1034. spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
  1035. spvOptions.disassemble = SpvToolsDisassembler;
  1036. spvOptions.validate = SpvToolsValidate;
  1037. glslang::GlslangToSpv(*program.getIntermediate((EShLanguage)stage), spirv, &logger, &spvOptions);
  1038. // Dump the spv to a file or stdout, etc., but only if not doing
  1039. // memory/perf testing, as it's not internal to programmatic use.
  1040. if (! (Options & EOptionMemoryLeakMode)) {
  1041. printf("%s", logger.getAllMessages().c_str());
  1042. if (Options & EOptionOutputHexadecimal) {
  1043. glslang::OutputSpvHex(spirv, GetBinaryName((EShLanguage)stage), variableName);
  1044. } else {
  1045. glslang::OutputSpvBin(spirv, GetBinaryName((EShLanguage)stage));
  1046. }
  1047. #ifndef GLSLANG_WEB
  1048. if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
  1049. spv::Disassemble(std::cout, spirv);
  1050. #endif
  1051. }
  1052. }
  1053. }
  1054. }
  1055. }
  1056. // Free everything up, program has to go before the shaders
  1057. // because it might have merged stuff from the shaders, and
  1058. // the stuff from the shaders has to have its destructors called
  1059. // before the pools holding the memory in the shaders is freed.
  1060. delete &program;
  1061. while (shaders.size() > 0) {
  1062. delete shaders.back();
  1063. shaders.pop_back();
  1064. }
  1065. }
  1066. //
  1067. // Do file IO part of compile and link, handing off the pure
  1068. // API/programmatic mode to CompileAndLinkShaderUnits(), which can
  1069. // be put in a loop for testing memory footprint and performance.
  1070. //
  1071. // This is just for linking mode: meaning all the shaders will be put into the
  1072. // the same program linked together.
  1073. //
  1074. // This means there are a limited number of work items (not multi-threading mode)
  1075. // and that the point is testing at the linking level. Hence, to enable
  1076. // performance and memory testing, the actual compile/link can be put in
  1077. // a loop, independent of processing the work items and file IO.
  1078. //
  1079. void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
  1080. {
  1081. std::vector<ShaderCompUnit> compUnits;
  1082. // If this is using stdin, we can't really detect multiple different file
  1083. // units by input type. We need to assume that we're just being given one
  1084. // file of a certain type.
  1085. if ((Options & EOptionStdin) != 0) {
  1086. ShaderCompUnit compUnit(FindLanguage("stdin"));
  1087. std::istreambuf_iterator<char> begin(std::cin), end;
  1088. std::string tempString(begin, end);
  1089. char* fileText = strdup(tempString.c_str());
  1090. std::string fileName = "stdin";
  1091. compUnit.addString(fileName, fileText);
  1092. compUnits.push_back(compUnit);
  1093. } else {
  1094. // Transfer all the work items from to a simple list of
  1095. // of compilation units. (We don't care about the thread
  1096. // work-item distribution properties in this path, which
  1097. // is okay due to the limited number of shaders, know since
  1098. // they are all getting linked together.)
  1099. glslang::TWorkItem* workItem;
  1100. while (Worklist.remove(workItem)) {
  1101. ShaderCompUnit compUnit(FindLanguage(workItem->name));
  1102. char* fileText = ReadFileData(workItem->name.c_str());
  1103. if (fileText == nullptr)
  1104. usage();
  1105. compUnit.addString(workItem->name, fileText);
  1106. compUnits.push_back(compUnit);
  1107. }
  1108. }
  1109. // Actual call to programmatic processing of compile and link,
  1110. // in a loop for testing memory and performance. This part contains
  1111. // all the perf/memory that a programmatic consumer will care about.
  1112. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1113. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
  1114. CompileAndLinkShaderUnits(compUnits);
  1115. if (Options & EOptionMemoryLeakMode)
  1116. glslang::OS_DumpMemoryCounters();
  1117. }
  1118. // free memory from ReadFileData, which got stored in a const char*
  1119. // as the first string above
  1120. for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
  1121. FreeFileData(const_cast<char*>(it->text[0]));
  1122. }
  1123. int singleMain()
  1124. {
  1125. glslang::TWorklist workList;
  1126. std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
  1127. assert(item);
  1128. workList.add(item.get());
  1129. });
  1130. #ifndef GLSLANG_WEB
  1131. if (Options & EOptionDumpConfig) {
  1132. printf("%s", glslang::GetDefaultTBuiltInResourceString().c_str());
  1133. if (workList.empty())
  1134. return ESuccess;
  1135. }
  1136. #endif
  1137. if (Options & EOptionDumpBareVersion) {
  1138. printf("%d.%d.%d\n",
  1139. glslang::GetSpirvGeneratorVersion(), GLSLANG_MINOR_VERSION, GLSLANG_PATCH_LEVEL);
  1140. if (workList.empty())
  1141. return ESuccess;
  1142. } else if (Options & EOptionDumpVersions) {
  1143. printf("Glslang Version: %d.%d.%d\n",
  1144. glslang::GetSpirvGeneratorVersion(), GLSLANG_MINOR_VERSION, GLSLANG_PATCH_LEVEL);
  1145. printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
  1146. printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
  1147. std::string spirvVersion;
  1148. glslang::GetSpirvVersion(spirvVersion);
  1149. printf("SPIR-V Version %s\n", spirvVersion.c_str());
  1150. printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
  1151. printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
  1152. printf("SPIR-V Generator Version %d\n", glslang::GetSpirvGeneratorVersion());
  1153. printf("GL_KHR_vulkan_glsl version %d\n", 100);
  1154. printf("ARB_GL_gl_spirv version %d\n", 100);
  1155. if (workList.empty())
  1156. return ESuccess;
  1157. }
  1158. if (workList.empty() && ((Options & EOptionStdin) == 0)) {
  1159. usage();
  1160. }
  1161. if (Options & EOptionStdin) {
  1162. WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
  1163. workList.add(WorkItems.back().get());
  1164. }
  1165. ProcessConfigFile();
  1166. if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
  1167. Error("HLSL requires SPIR-V code generation (or preprocessing only)");
  1168. //
  1169. // Two modes:
  1170. // 1) linking all arguments together, single-threaded, new C++ interface
  1171. // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
  1172. //
  1173. if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
  1174. glslang::InitializeProcess();
  1175. glslang::InitializeProcess(); // also test reference counting of users
  1176. glslang::InitializeProcess(); // also test reference counting of users
  1177. glslang::FinalizeProcess(); // also test reference counting of users
  1178. glslang::FinalizeProcess(); // also test reference counting of users
  1179. CompileAndLinkShaderFiles(workList);
  1180. glslang::FinalizeProcess();
  1181. } else {
  1182. ShInitialize();
  1183. ShInitialize(); // also test reference counting of users
  1184. ShFinalize(); // also test reference counting of users
  1185. bool printShaderNames = workList.size() > 1;
  1186. if (Options & EOptionMultiThreaded) {
  1187. std::array<std::thread, 16> threads;
  1188. for (unsigned int t = 0; t < threads.size(); ++t) {
  1189. threads[t] = std::thread(CompileShaders, std::ref(workList));
  1190. if (threads[t].get_id() == std::thread::id()) {
  1191. fprintf(stderr, "Failed to create thread\n");
  1192. return EFailThreadCreate;
  1193. }
  1194. }
  1195. std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
  1196. } else
  1197. CompileShaders(workList);
  1198. // Print out all the resulting infologs
  1199. for (size_t w = 0; w < WorkItems.size(); ++w) {
  1200. if (WorkItems[w]) {
  1201. if (printShaderNames || WorkItems[w]->results.size() > 0)
  1202. PutsIfNonEmpty(WorkItems[w]->name.c_str());
  1203. PutsIfNonEmpty(WorkItems[w]->results.c_str());
  1204. }
  1205. }
  1206. ShFinalize();
  1207. }
  1208. if (CompileFailed)
  1209. return EFailCompile;
  1210. if (LinkFailed)
  1211. return EFailLink;
  1212. return 0;
  1213. }
  1214. int C_DECL main(int argc, char* argv[])
  1215. {
  1216. ProcessArguments(WorkItems, argc, argv);
  1217. int ret = 0;
  1218. // Loop over the entire init/finalize cycle to watch memory changes
  1219. const int iterations = 1;
  1220. if (iterations > 1)
  1221. glslang::OS_DumpMemoryCounters();
  1222. for (int i = 0; i < iterations; ++i) {
  1223. ret = singleMain();
  1224. if (iterations > 1)
  1225. glslang::OS_DumpMemoryCounters();
  1226. }
  1227. return ret;
  1228. }
  1229. //
  1230. // Deduce the language from the filename. Files must end in one of the
  1231. // following extensions:
  1232. //
  1233. // .vert = vertex
  1234. // .tesc = tessellation control
  1235. // .tese = tessellation evaluation
  1236. // .geom = geometry
  1237. // .frag = fragment
  1238. // .comp = compute
  1239. // .rgen = ray generation
  1240. // .rint = ray intersection
  1241. // .rahit = ray any hit
  1242. // .rchit = ray closest hit
  1243. // .rmiss = ray miss
  1244. // .rcall = ray callable
  1245. // .mesh = mesh
  1246. // .task = task
  1247. // Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
  1248. // where <stage> is one of the stages listed above.
  1249. //
  1250. EShLanguage FindLanguage(const std::string& name, bool parseStageName)
  1251. {
  1252. std::string stageName;
  1253. if (shaderStageName)
  1254. stageName = shaderStageName;
  1255. else if (parseStageName) {
  1256. // Note: "first" extension means "first from the end", i.e.
  1257. // if the file is named foo.vert.glsl, then "glsl" is first,
  1258. // "vert" is second.
  1259. size_t firstExtStart = name.find_last_of(".");
  1260. bool hasFirstExt = firstExtStart != std::string::npos;
  1261. size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
  1262. bool hasSecondExt = secondExtStart != std::string::npos;
  1263. std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
  1264. bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
  1265. if (usesUnifiedExt && firstExt == "hlsl")
  1266. Options |= EOptionReadHlsl;
  1267. if (hasFirstExt && !usesUnifiedExt)
  1268. stageName = firstExt;
  1269. else if (usesUnifiedExt && hasSecondExt)
  1270. stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
  1271. else {
  1272. usage();
  1273. return EShLangVertex;
  1274. }
  1275. } else
  1276. stageName = name;
  1277. if (stageName == "vert")
  1278. return EShLangVertex;
  1279. else if (stageName == "tesc")
  1280. return EShLangTessControl;
  1281. else if (stageName == "tese")
  1282. return EShLangTessEvaluation;
  1283. else if (stageName == "geom")
  1284. return EShLangGeometry;
  1285. else if (stageName == "frag")
  1286. return EShLangFragment;
  1287. else if (stageName == "comp")
  1288. return EShLangCompute;
  1289. else if (stageName == "rgen")
  1290. return EShLangRayGen;
  1291. else if (stageName == "rint")
  1292. return EShLangIntersect;
  1293. else if (stageName == "rahit")
  1294. return EShLangAnyHit;
  1295. else if (stageName == "rchit")
  1296. return EShLangClosestHit;
  1297. else if (stageName == "rmiss")
  1298. return EShLangMiss;
  1299. else if (stageName == "rcall")
  1300. return EShLangCallable;
  1301. else if (stageName == "mesh")
  1302. return EShLangMeshNV;
  1303. else if (stageName == "task")
  1304. return EShLangTaskNV;
  1305. usage();
  1306. return EShLangVertex;
  1307. }
  1308. //
  1309. // Read a file's data into a string, and compile it using the old interface ShCompile,
  1310. // for non-linkable results.
  1311. //
  1312. void CompileFile(const char* fileName, ShHandle compiler)
  1313. {
  1314. int ret = 0;
  1315. char* shaderString;
  1316. if ((Options & EOptionStdin) != 0) {
  1317. std::istreambuf_iterator<char> begin(std::cin), end;
  1318. std::string tempString(begin, end);
  1319. shaderString = strdup(tempString.c_str());
  1320. } else {
  1321. shaderString = ReadFileData(fileName);
  1322. }
  1323. // move to length-based strings, rather than null-terminated strings
  1324. int* lengths = new int[1];
  1325. lengths[0] = (int)strlen(shaderString);
  1326. EShMessages messages = EShMsgDefault;
  1327. SetMessageOptions(messages);
  1328. if (UserPreamble.isSet())
  1329. Error("-D and -U options require -l (linking)\n");
  1330. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1331. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
  1332. // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1333. ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1334. // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
  1335. // "or should be l", "ine 1", "string 5\n", "float glo", "bal",
  1336. // ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
  1337. // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
  1338. // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1339. }
  1340. if (Options & EOptionMemoryLeakMode)
  1341. glslang::OS_DumpMemoryCounters();
  1342. }
  1343. delete [] lengths;
  1344. FreeFileData(shaderString);
  1345. if (ret == 0)
  1346. CompileFailed = true;
  1347. }
  1348. //
  1349. // print usage to stdout
  1350. //
  1351. void usage()
  1352. {
  1353. printf("Usage: glslangValidator [option]... [file]...\n"
  1354. "\n"
  1355. "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
  1356. " .conf to provide a config file that replaces the default configuration\n"
  1357. " (see -c option below for generating a template)\n"
  1358. " .vert for a vertex shader\n"
  1359. " .tesc for a tessellation control shader\n"
  1360. " .tese for a tessellation evaluation shader\n"
  1361. " .geom for a geometry shader\n"
  1362. " .frag for a fragment shader\n"
  1363. " .comp for a compute shader\n"
  1364. " .mesh for a mesh shader\n"
  1365. " .task for a task shader\n"
  1366. " .rgen for a ray generation shader\n"
  1367. " .rint for a ray intersection shader\n"
  1368. " .rahit for a ray any hit shader\n"
  1369. " .rchit for a ray closest hit shader\n"
  1370. " .rmiss for a ray miss shader\n"
  1371. " .rcall for a ray callable shader\n"
  1372. " .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
  1373. " .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
  1374. "\n"
  1375. "Options:\n"
  1376. " -C cascading errors; risk crash from accumulation of error recoveries\n"
  1377. " -D input is HLSL (this is the default when any suffix is .hlsl)\n"
  1378. " -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]>\n"
  1379. " define a pre-processor macro\n"
  1380. " -E print pre-processed GLSL; cannot be used with -l;\n"
  1381. " errors will appear on stderr\n"
  1382. " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
  1383. " default file name is <stage>.spv (-o overrides this);\n"
  1384. " 'ver', when present, is the version of the input semantics,\n"
  1385. " which will appear in #define GL_SPIRV ver;\n"
  1386. " '--client opengl100' is the same as -G100;\n"
  1387. " a '--target-env' for OpenGL will also imply '-G'\n"
  1388. " -H print human readable form of SPIR-V; turns on -V\n"
  1389. " -I<dir> add dir to the include search path; includer's directory\n"
  1390. " is searched first, followed by left-to-right order of -I\n"
  1391. " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
  1392. " -Os optimizes SPIR-V to minimize size\n"
  1393. " -S <stage> uses specified stage rather than parsing the file extension\n"
  1394. " choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
  1395. " -U<name> | --undef-macro <name> | --U <name>\n"
  1396. " undefine a pre-processor macro\n"
  1397. " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
  1398. " default file name is <stage>.spv (-o overrides this)\n"
  1399. " 'ver', when present, is the version of the input semantics,\n"
  1400. " which will appear in #define VULKAN ver\n"
  1401. " '--client vulkan100' is the same as -V100\n"
  1402. " a '--target-env' for Vulkan will also imply '-V'\n"
  1403. " -c configuration dump;\n"
  1404. " creates the default configuration file (redirect to a .conf file)\n"
  1405. " -d default to desktop (#version 110) when there is no shader #version\n"
  1406. " (default is ES version 100)\n"
  1407. " -e <name> | --entry-point <name>\n"
  1408. " specify <name> as the entry-point function name\n"
  1409. " -f{hlsl_functionality1}\n"
  1410. " 'hlsl_functionality1' enables use of the\n"
  1411. " SPV_GOOGLE_hlsl_functionality1 extension\n"
  1412. " -g generate debug information\n"
  1413. " -h print this usage message\n"
  1414. " -i intermediate tree (glslang AST) is printed out\n"
  1415. " -l link all input files together to form a single module\n"
  1416. " -m memory leak mode\n"
  1417. " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
  1418. " -q dump reflection query database; requires -l for linking\n"
  1419. " -r | --relaxed-errors"
  1420. " relaxed GLSL semantic error-checking mode\n"
  1421. " -s silence syntax and semantic error reporting\n"
  1422. " -t multi-threaded mode\n"
  1423. " -v | --version\n"
  1424. " print version strings\n"
  1425. " -w | --suppress-warnings\n"
  1426. " suppress GLSL warnings, except as required by \"#extension : warn\"\n"
  1427. " -x save binary output as text-based 32-bit hexadecimal numbers\n"
  1428. " -u<name>:<loc> specify a uniform location override for --aml\n"
  1429. " --uniform-base <base> set a base to use for generated uniform locations\n"
  1430. " --auto-map-bindings | --amb automatically bind uniform variables\n"
  1431. " without explicit bindings\n"
  1432. " --auto-map-locations | --aml automatically locate input/output lacking\n"
  1433. " 'location' (fragile, not cross stage)\n"
  1434. " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
  1435. " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
  1436. " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
  1437. " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
  1438. " scalars\n"
  1439. " --hlsl-offsets allow block offsets to follow HLSL rules\n"
  1440. " works independently of source language\n"
  1441. " --hlsl-iomap perform IO mapping in HLSL register space\n"
  1442. " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
  1443. " --hlsl-dx9-compatible interprets sampler declarations as a\n"
  1444. " texture/sampler combo like DirectX9 would.\n"
  1445. " --invert-y | --iy invert position.Y output in vertex shader\n"
  1446. " --keep-uncalled | --ku don't eliminate uncalled functions\n"
  1447. " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
  1448. " --no-storage-format | --nsf use Unknown image format\n"
  1449. " --reflect-strict-array-suffix use strict array suffix rules when\n"
  1450. " reflecting\n"
  1451. " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
  1452. " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
  1453. " shaders rather than just vertex/fragment\n"
  1454. " --reflect-separate-buffers reflect buffer variables and blocks\n"
  1455. " separately to uniforms\n"
  1456. " --reflect-all-block-variables reflect all variables in blocks, whether\n"
  1457. " inactive or active\n"
  1458. " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
  1459. " uniform blocks\n"
  1460. " --resource-set-binding [stage] name set binding\n"
  1461. " set descriptor set and binding for\n"
  1462. " individual resources\n"
  1463. " --resource-set-binding [stage] set\n"
  1464. " set descriptor set for all resources\n"
  1465. " --rsb synonym for --resource-set-binding\n"
  1466. " --shift-image-binding [stage] num\n"
  1467. " base binding number for images (uav)\n"
  1468. " --shift-image-binding [stage] [num set]...\n"
  1469. " per-descriptor-set shift values\n"
  1470. " --sib synonym for --shift-image-binding\n"
  1471. " --shift-sampler-binding [stage] num\n"
  1472. " base binding number for samplers\n"
  1473. " --shift-sampler-binding [stage] [num set]...\n"
  1474. " per-descriptor-set shift values\n"
  1475. " --ssb synonym for --shift-sampler-binding\n"
  1476. " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
  1477. " --shift-ssbo-binding [stage] [num set]...\n"
  1478. " per-descriptor-set shift values\n"
  1479. " --sbb synonym for --shift-ssbo-binding\n"
  1480. " --shift-texture-binding [stage] num\n"
  1481. " base binding number for textures\n"
  1482. " --shift-texture-binding [stage] [num set]...\n"
  1483. " per-descriptor-set shift values\n"
  1484. " --stb synonym for --shift-texture-binding\n"
  1485. " --shift-uav-binding [stage] num base binding number for UAVs\n"
  1486. " --shift-uav-binding [stage] [num set]...\n"
  1487. " per-descriptor-set shift values\n"
  1488. " --suavb synonym for --shift-uav-binding\n"
  1489. " --shift-UBO-binding [stage] num base binding number for UBOs\n"
  1490. " --shift-UBO-binding [stage] [num set]...\n"
  1491. " per-descriptor-set shift values\n"
  1492. " --sub synonym for --shift-UBO-binding\n"
  1493. " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
  1494. " --spirv-dis output standard-form disassembly; works only\n"
  1495. " when a SPIR-V generation option is also used\n"
  1496. " --spirv-val execute the SPIRV-Tools validator\n"
  1497. " --source-entrypoint <name> the given shader source function is\n"
  1498. " renamed to be the <name> given in -e\n"
  1499. " --sep synonym for --source-entrypoint\n"
  1500. " --stdin read from stdin instead of from a file;\n"
  1501. " requires providing the shader stage using -S\n"
  1502. " --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | opengl | \n"
  1503. " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 | spirv1.5}\n"
  1504. " Set the execution environment that the\n"
  1505. " generated code will be executed in.\n"
  1506. " Defaults to:\n"
  1507. " * vulkan1.0 under --client vulkan<ver>\n"
  1508. " * opengl under --client opengl<ver>\n"
  1509. " * spirv1.0 under --target-env vulkan1.0\n"
  1510. " * spirv1.3 under --target-env vulkan1.1\n"
  1511. " * spirv1.5 under --target-env vulkan1.2\n"
  1512. " Multiple --target-env can be specified.\n"
  1513. " --variable-name <name>\n"
  1514. " --vn <name> creates a C header file that contains a\n"
  1515. " uint32_t array named <name>\n"
  1516. " initialized with the shader binary code\n"
  1517. );
  1518. exit(EFailUsage);
  1519. }
  1520. #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
  1521. #include <errno.h>
  1522. int fopen_s(
  1523. FILE** pFile,
  1524. const char* filename,
  1525. const char* mode
  1526. )
  1527. {
  1528. if (!pFile || !filename || !mode) {
  1529. return EINVAL;
  1530. }
  1531. FILE* f = fopen(filename, mode);
  1532. if (! f) {
  1533. if (errno != 0) {
  1534. return errno;
  1535. } else {
  1536. return ENOENT;
  1537. }
  1538. }
  1539. *pFile = f;
  1540. return 0;
  1541. }
  1542. #endif
  1543. //
  1544. // Malloc a string of sufficient size and read a string into it.
  1545. //
  1546. char* ReadFileData(const char* fileName)
  1547. {
  1548. FILE *in = nullptr;
  1549. int errorCode = fopen_s(&in, fileName, "r");
  1550. if (errorCode || in == nullptr)
  1551. Error("unable to open input file");
  1552. int count = 0;
  1553. while (fgetc(in) != EOF)
  1554. count++;
  1555. fseek(in, 0, SEEK_SET);
  1556. char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
  1557. if ((int)fread(return_data, 1, count, in) != count) {
  1558. free(return_data);
  1559. Error("can't read input file");
  1560. }
  1561. return_data[count] = '\0';
  1562. fclose(in);
  1563. return return_data;
  1564. }
  1565. void FreeFileData(char* data)
  1566. {
  1567. free(data);
  1568. }
  1569. void InfoLogMsg(const char* msg, const char* name, const int num)
  1570. {
  1571. if (num >= 0 )
  1572. printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
  1573. else
  1574. printf("#### %s %s INFO LOG ####\n", msg, name);
  1575. }