StandAlone.cpp 69 KB

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