shaderc_spirv.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "shaderc.h"
  6. BX_PRAGMA_DIAGNOSTIC_PUSH()
  7. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4100) // error C4100: 'inclusionDepth' : unreferenced formal parameter
  8. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4265) // error C4265: 'spv::spirvbin_t': class has virtual functions, but destructor is not virtual
  9. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow") // warning: declaration of 'userData' shadows a member of 'glslang::TShader::Includer::IncludeResult'
  10. #define ENABLE_OPT 1
  11. #include <ShaderLang.h>
  12. #include <ResourceLimits.h>
  13. #include <SPIRV/SPVRemapper.h>
  14. #include <SPIRV/GlslangToSpv.h>
  15. #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
  16. #include <spirv_msl.hpp>
  17. #include <spirv-tools/optimizer.hpp>
  18. BX_PRAGMA_DIAGNOSTIC_POP()
  19. namespace bgfx
  20. {
  21. static bx::DefaultAllocator s_allocator;
  22. bx::AllocatorI* g_allocator = &s_allocator;
  23. struct TinyStlAllocator
  24. {
  25. static void* static_allocate(size_t _bytes);
  26. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  27. };
  28. void* TinyStlAllocator::static_allocate(size_t _bytes)
  29. {
  30. return BX_ALLOC(g_allocator, _bytes);
  31. }
  32. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  33. {
  34. if (NULL != _ptr)
  35. {
  36. BX_FREE(g_allocator, _ptr);
  37. }
  38. }
  39. } // namespace bgfx
  40. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  41. #include <tinystl/allocator.h>
  42. #include <tinystl/string.h>
  43. #include <tinystl/unordered_map.h>
  44. #include <tinystl/vector.h>
  45. namespace stl = tinystl;
  46. #include "../../src/shader_spirv.h"
  47. namespace bgfx { namespace spirv
  48. {
  49. const TBuiltInResource resourceLimits =
  50. {
  51. 32, // MaxLights
  52. 6, // MaxClipPlanes
  53. 32, // MaxTextureUnits
  54. 32, // MaxTextureCoords
  55. 64, // MaxVertexAttribs
  56. 4096, // MaxVertexUniformComponents
  57. 64, // MaxVaryingFloats
  58. 32, // MaxVertexTextureImageUnits
  59. 80, // MaxCombinedTextureImageUnits
  60. 32, // MaxTextureImageUnits
  61. 4096, // MaxFragmentUniformComponents
  62. 32, // MaxDrawBuffers
  63. 128, // MaxVertexUniformVectors
  64. 8, // MaxVaryingVectors
  65. 16, // MaxFragmentUniformVectors
  66. 16, // MaxVertexOutputVectors
  67. 15, // MaxFragmentInputVectors
  68. -8, // MinProgramTexelOffset
  69. 7, // MaxProgramTexelOffset
  70. 8, // MaxClipDistances
  71. 65535, // MaxComputeWorkGroupCountX
  72. 65535, // MaxComputeWorkGroupCountY
  73. 65535, // MaxComputeWorkGroupCountZ
  74. 1024, // MaxComputeWorkGroupSizeX
  75. 1024, // MaxComputeWorkGroupSizeY
  76. 64, // MaxComputeWorkGroupSizeZ
  77. 1024, // MaxComputeUniformComponents
  78. 16, // MaxComputeTextureImageUnits
  79. 8, // MaxComputeImageUniforms
  80. 8, // MaxComputeAtomicCounters
  81. 1, // MaxComputeAtomicCounterBuffers
  82. 60, // MaxVaryingComponents
  83. 64, // MaxVertexOutputComponents
  84. 64, // MaxGeometryInputComponents
  85. 128, // MaxGeometryOutputComponents
  86. 128, // MaxFragmentInputComponents
  87. 8, // MaxImageUnits
  88. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  89. 8, // MaxCombinedShaderOutputResources
  90. 0, // MaxImageSamples
  91. 0, // MaxVertexImageUniforms
  92. 0, // MaxTessControlImageUniforms
  93. 0, // MaxTessEvaluationImageUniforms
  94. 0, // MaxGeometryImageUniforms
  95. 8, // MaxFragmentImageUniforms
  96. 8, // MaxCombinedImageUniforms
  97. 16, // MaxGeometryTextureImageUnits
  98. 256, // MaxGeometryOutputVertices
  99. 1024, // MaxGeometryTotalOutputComponents
  100. 1024, // MaxGeometryUniformComponents
  101. 64, // MaxGeometryVaryingComponents
  102. 128, // MaxTessControlInputComponents
  103. 128, // MaxTessControlOutputComponents
  104. 16, // MaxTessControlTextureImageUnits
  105. 1024, // MaxTessControlUniformComponents
  106. 4096, // MaxTessControlTotalOutputComponents
  107. 128, // MaxTessEvaluationInputComponents
  108. 128, // MaxTessEvaluationOutputComponents
  109. 16, // MaxTessEvaluationTextureImageUnits
  110. 1024, // MaxTessEvaluationUniformComponents
  111. 120, // MaxTessPatchComponents
  112. 32, // MaxPatchVertices
  113. 64, // MaxTessGenLevel
  114. 16, // MaxViewports
  115. 0, // MaxVertexAtomicCounters
  116. 0, // MaxTessControlAtomicCounters
  117. 0, // MaxTessEvaluationAtomicCounters
  118. 0, // MaxGeometryAtomicCounters
  119. 8, // MaxFragmentAtomicCounters
  120. 8, // MaxCombinedAtomicCounters
  121. 1, // MaxAtomicCounterBindings
  122. 0, // MaxVertexAtomicCounterBuffers
  123. 0, // MaxTessControlAtomicCounterBuffers
  124. 0, // MaxTessEvaluationAtomicCounterBuffers
  125. 0, // MaxGeometryAtomicCounterBuffers
  126. 1, // MaxFragmentAtomicCounterBuffers
  127. 1, // MaxCombinedAtomicCounterBuffers
  128. 16384, // MaxAtomicCounterBufferSize
  129. 4, // MaxTransformFeedbackBuffers
  130. 64, // MaxTransformFeedbackInterleavedComponents
  131. 8, // MaxCullDistances
  132. 8, // MaxCombinedClipAndCullDistances
  133. 4, // MaxSamples
  134. 0, // maxMeshOutputVerticesNV;
  135. 0, // maxMeshOutputPrimitivesNV;
  136. 0, // maxMeshWorkGroupSizeX_NV;
  137. 0, // maxMeshWorkGroupSizeY_NV;
  138. 0, // maxMeshWorkGroupSizeZ_NV;
  139. 0, // maxTaskWorkGroupSizeX_NV;
  140. 0, // maxTaskWorkGroupSizeY_NV;
  141. 0, // maxTaskWorkGroupSizeZ_NV;
  142. 0, // maxMeshViewCountNV
  143. { // limits
  144. true, // nonInductiveForLoops
  145. true, // whileLoops
  146. true, // doWhileLoops
  147. true, // generalUniformIndexing
  148. true, // generalAttributeMatrixVectorIndexing
  149. true, // generalVaryingIndexing
  150. true, // generalSamplerIndexing
  151. true, // generalVariableIndexing
  152. true, // generalConstantMatrixVectorIndexing
  153. },
  154. };
  155. bool printAsm(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  156. {
  157. BX_UNUSED(_userData);
  158. char temp[512];
  159. toString(temp, sizeof(temp), _instruction);
  160. BX_TRACE("%5d: %s", _offset, temp);
  161. return true;
  162. }
  163. struct SpvReflection
  164. {
  165. struct TypeId
  166. {
  167. enum Enum
  168. {
  169. Void,
  170. Bool,
  171. Int32,
  172. Int64,
  173. Uint32,
  174. Uint64,
  175. Float,
  176. Double,
  177. Vector,
  178. Matrix,
  179. Count
  180. };
  181. TypeId()
  182. : baseType(Enum::Count)
  183. , type(Enum::Count)
  184. , numComponents(0)
  185. {
  186. }
  187. Enum baseType;
  188. Enum type;
  189. uint32_t numComponents;
  190. stl::string toString()
  191. {
  192. stl::string result;
  193. switch (type)
  194. {
  195. case Float:
  196. result.append("float");
  197. break;
  198. case Vector:
  199. bx::stringPrintf(result, "vec%d"
  200. , numComponents
  201. );
  202. break;
  203. case Matrix:
  204. bx::stringPrintf(result, "mat%d"
  205. , numComponents
  206. );
  207. default:
  208. break;
  209. }
  210. return result;
  211. }
  212. };
  213. struct Id
  214. {
  215. struct Variable
  216. {
  217. Variable()
  218. : decoration(SpvDecoration::Count)
  219. , builtin(SpvBuiltin::Count)
  220. , storageClass(SpvStorageClass::Count)
  221. , location(UINT32_MAX)
  222. , offset(UINT32_MAX)
  223. , type(UINT32_MAX)
  224. {
  225. }
  226. stl::string name;
  227. SpvDecoration::Enum decoration;
  228. SpvBuiltin::Enum builtin;
  229. SpvStorageClass::Enum storageClass;
  230. uint32_t location;
  231. uint32_t offset;
  232. uint32_t type;
  233. };
  234. typedef stl::vector<Variable> MemberArray;
  235. Variable var;
  236. MemberArray members;
  237. };
  238. typedef stl::unordered_map<uint32_t, TypeId> TypeIdMap;
  239. typedef stl::unordered_map<uint32_t, Id> IdMap;
  240. TypeIdMap typeIdMap;
  241. IdMap idMap;
  242. stl::string getTypeName(uint32_t _typeId)
  243. {
  244. return getTypeId(_typeId).toString();
  245. }
  246. Id& getId(uint32_t _id)
  247. {
  248. IdMap::iterator it = idMap.find(_id);
  249. if (it == idMap.end() )
  250. {
  251. Id id;
  252. stl::pair<IdMap::iterator, bool> result = idMap.insert(stl::make_pair(_id, id) );
  253. it = result.first;
  254. }
  255. return it->second;
  256. }
  257. Id::Variable& get(uint32_t _id, uint32_t _idx)
  258. {
  259. Id& id = getId(_id);
  260. id.members.resize(bx::uint32_max(_idx+1, uint32_t(id.members.size() ) ) );
  261. return id.members[_idx];
  262. }
  263. TypeId& getTypeId(uint32_t _id)
  264. {
  265. TypeIdMap::iterator it = typeIdMap.find(_id);
  266. if (it == typeIdMap.end() )
  267. {
  268. TypeId id;
  269. stl::pair<TypeIdMap::iterator, bool> result = typeIdMap.insert(stl::make_pair(_id, id) );
  270. it = result.first;
  271. }
  272. return it->second;
  273. }
  274. void update(uint32_t _id, const stl::string& _name)
  275. {
  276. getId(_id).var.name = _name;
  277. }
  278. BX_NO_INLINE void update(Id::Variable& _variable, SpvDecoration::Enum _decoration, uint32_t _literal)
  279. {
  280. _variable.decoration = _decoration;
  281. switch (_decoration)
  282. {
  283. case SpvDecoration::Location:
  284. _variable.location = _literal;
  285. break;
  286. case SpvDecoration::Offset:
  287. _variable.offset = _literal;
  288. break;
  289. case SpvDecoration::BuiltIn:
  290. _variable.builtin = SpvBuiltin::Enum(_literal);
  291. break;
  292. default:
  293. break;
  294. }
  295. }
  296. BX_NO_INLINE void update(Id::Variable& _variable, uint32_t _type, SpvStorageClass::Enum _storageClass)
  297. {
  298. _variable.type = _type;
  299. _variable.storageClass = _storageClass;
  300. }
  301. void update(uint32_t _id, SpvDecoration::Enum _decoration, uint32_t _literal)
  302. {
  303. update(getId(_id).var, _decoration, _literal);
  304. }
  305. void update(uint32_t _id, uint32_t _type, SpvStorageClass::Enum _storageClass)
  306. {
  307. update(getId(_id).var, _type, _storageClass);
  308. }
  309. void update(uint32_t _id, uint32_t _idx, const stl::string& _name)
  310. {
  311. Id::Variable& var = get(_id, _idx);
  312. var.name = _name;
  313. }
  314. BX_NO_INLINE void update(uint32_t _id, uint32_t _idx, SpvDecoration::Enum _decoration, uint32_t _literal)
  315. {
  316. update(get(_id, _idx), _decoration, _literal);
  317. }
  318. void update(uint32_t _id, TypeId::Enum _type)
  319. {
  320. TypeId& type = getTypeId(_id);
  321. type.type = _type;
  322. }
  323. void update(uint32_t _id, TypeId::Enum _type, uint32_t _baseTypeId, uint32_t _numComonents)
  324. {
  325. TypeId& type = getTypeId(_id);
  326. type.type = _type;
  327. type.baseType = getTypeId(_baseTypeId).type;
  328. type.numComponents = _numComonents;
  329. }
  330. };
  331. bool spvParse(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  332. {
  333. BX_UNUSED(_offset);
  334. SpvReflection* spv = (SpvReflection*)_userData;
  335. switch (_instruction.opcode)
  336. {
  337. case SpvOpcode::Name:
  338. spv->update(_instruction.result
  339. , _instruction.operand[0].literalString
  340. );
  341. break;
  342. case SpvOpcode::Decorate:
  343. spv->update(_instruction.operand[0].data
  344. , SpvDecoration::Enum(_instruction.operand[1].data)
  345. , _instruction.operand[2].data
  346. );
  347. break;
  348. case SpvOpcode::MemberName:
  349. spv->update(_instruction.result
  350. , _instruction.operand[0].data
  351. , _instruction.operand[1].literalString
  352. );
  353. break;
  354. case SpvOpcode::MemberDecorate:
  355. spv->update(_instruction.operand[0].data
  356. , _instruction.operand[1].data
  357. , SpvDecoration::Enum(_instruction.operand[2].data)
  358. , _instruction.operand[3].data
  359. );
  360. break;
  361. case SpvOpcode::Variable:
  362. spv->update(_instruction.result
  363. , _instruction.type
  364. , SpvStorageClass::Enum(_instruction.operand[0].data)
  365. );
  366. break;
  367. case SpvOpcode::TypeVoid:
  368. spv->update(_instruction.result, SpvReflection::TypeId::Void);
  369. break;
  370. case SpvOpcode::TypeBool:
  371. spv->update(_instruction.result, SpvReflection::TypeId::Bool);
  372. break;
  373. case SpvOpcode::TypeInt:
  374. spv->update(_instruction.result
  375. , 32 == _instruction.operand[0].data
  376. ? 0 == _instruction.operand[1].data
  377. ? SpvReflection::TypeId::Uint32
  378. : SpvReflection::TypeId::Int32
  379. : 0 == _instruction.operand[1].data
  380. ? SpvReflection::TypeId::Uint64
  381. : SpvReflection::TypeId::Int64
  382. );
  383. break;
  384. case SpvOpcode::TypeFloat:
  385. spv->update(_instruction.result
  386. , 32 == _instruction.operand[0].data
  387. ? SpvReflection::TypeId::Float
  388. : SpvReflection::TypeId::Double
  389. );
  390. break;
  391. case SpvOpcode::TypeVector:
  392. spv->update(_instruction.result
  393. , SpvReflection::TypeId::Vector
  394. , _instruction.operand[0].data
  395. , _instruction.operand[1].data
  396. );
  397. break;
  398. case SpvOpcode::TypeMatrix:
  399. spv->update(_instruction.result
  400. , SpvReflection::TypeId::Matrix
  401. , _instruction.operand[0].data
  402. , _instruction.operand[1].data
  403. );
  404. break;
  405. case SpvOpcode::TypeImage:
  406. case SpvOpcode::TypeSampler:
  407. case SpvOpcode::TypeSampledImage:
  408. break;
  409. case SpvOpcode::TypeStruct:
  410. for (uint32_t ii = 0, num = _instruction.numOperands; ii < num; ++ii)
  411. {
  412. SpvReflection::Id::Variable& var = spv->get(_instruction.result, ii);
  413. var.type = _instruction.operand[ii].data;
  414. }
  415. break;
  416. default:
  417. break;
  418. }
  419. return true;
  420. }
  421. #define DBG(...) // bx::debugPrintf(__VA_ARGS__)
  422. void disassemble(bx::WriterI* _writer, bx::ReaderSeekerI* _reader, bx::Error* _err)
  423. {
  424. BX_UNUSED(_writer);
  425. uint32_t magic;
  426. bx::peek(_reader, magic);
  427. SpvReflection spvx;
  428. if (magic == SPV_CHUNK_HEADER)
  429. {
  430. SpirV spirv;
  431. read(_reader, spirv, _err);
  432. parse(spirv.shader, spvParse, &spvx, _err);
  433. for (SpvReflection::IdMap::const_iterator it = spvx.idMap.begin(), itEnd = spvx.idMap.end(); it != itEnd; ++it)
  434. {
  435. const SpvReflection::Id& id = it->second;
  436. uint32_t num = uint32_t(id.members.size() );
  437. if (0 < num
  438. && 0 != bx::strCmp(id.var.name.c_str(), "gl_PerVertex") )
  439. {
  440. DBG("%3d: %s %d %s\n"
  441. , it->first
  442. , id.var.name.c_str()
  443. , id.var.location
  444. , getName(id.var.storageClass)
  445. );
  446. DBG("{\n");
  447. for (uint32_t ii = 0; ii < num; ++ii)
  448. {
  449. const SpvReflection::Id::Variable& var = id.members[ii];
  450. DBG("\t\t%s %s %d %s\n"
  451. , spvx.getTypeName(var.type).c_str()
  452. , var.name.c_str()
  453. , var.offset
  454. , getName(var.storageClass)
  455. );
  456. BX_UNUSED(var);
  457. }
  458. DBG("}\n");
  459. }
  460. }
  461. }
  462. }
  463. static EShLanguage getLang(char _p)
  464. {
  465. switch (_p)
  466. {
  467. case 'c': return EShLangCompute;
  468. case 'f': return EShLangFragment;
  469. case 'v': return EShLangVertex;
  470. default: return EShLangCount;
  471. }
  472. }
  473. // static void printError(spv_message_level_t, const char*, const spv_position_t&, const char* _message)
  474. // {
  475. // fprintf(stderr, "%s\n", _message);
  476. // }
  477. static const char* s_attribName[] =
  478. {
  479. "a_position",
  480. "a_normal",
  481. "a_tangent",
  482. "a_bitangent",
  483. "a_color0",
  484. "a_color1",
  485. "a_color2",
  486. "a_color3",
  487. "a_indices",
  488. "a_weight",
  489. "a_texcoord0",
  490. "a_texcoord1",
  491. "a_texcoord2",
  492. "a_texcoord3",
  493. "a_texcoord4",
  494. "a_texcoord5",
  495. "a_texcoord6",
  496. "a_texcoord7",
  497. };
  498. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  499. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  500. {
  501. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  502. {
  503. if (0 == bx::strCmp(s_attribName[ii], _name) )
  504. {
  505. return bgfx::Attrib::Enum(ii);
  506. }
  507. }
  508. return bgfx::Attrib::Count;
  509. }
  510. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  511. {
  512. BX_UNUSED(_version);
  513. glslang::InitializeProcess();
  514. glslang::TProgram* program = new glslang::TProgram;
  515. EShLanguage stage = getLang(_options.shaderType);
  516. if (EShLangCount == stage)
  517. {
  518. fprintf(stderr, "Error: Unknown shader type '%c'.\n", _options.shaderType);
  519. return false;
  520. }
  521. glslang::TShader* shader = new glslang::TShader(stage);
  522. EShMessages messages = EShMessages(0
  523. | EShMsgDefault
  524. | EShMsgReadHlsl
  525. | EShMsgVulkanRules
  526. | EShMsgSpvRules
  527. );
  528. shader->setEntryPoint("main");
  529. const char* shaderStrings[] = { _code.c_str() };
  530. shader->setStrings(
  531. shaderStrings
  532. , BX_COUNTOF(shaderStrings)
  533. );
  534. bool compiled = shader->parse(&resourceLimits
  535. , 110
  536. , false
  537. , messages
  538. );
  539. bool linked = false;
  540. bool validated = true;
  541. if (!compiled)
  542. {
  543. const char* log = shader->getInfoLog();
  544. if (NULL != log)
  545. {
  546. int32_t source = 0;
  547. int32_t line = 0;
  548. int32_t column = 0;
  549. int32_t start = 0;
  550. int32_t end = INT32_MAX;
  551. bx::StringView err = bx::strFind(log, "ERROR:");
  552. bool found = false;
  553. if (!err.isEmpty() )
  554. {
  555. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  556. if (found)
  557. {
  558. ++line;
  559. }
  560. }
  561. if (found)
  562. {
  563. start = bx::uint32_imax(1, line-10);
  564. end = start + 20;
  565. }
  566. printCode(_code.c_str(), line, start, end, column);
  567. fprintf(stderr, "%s\n", log);
  568. }
  569. }
  570. else
  571. {
  572. program->addShader(shader);
  573. linked = true
  574. && program->link(messages)
  575. && program->mapIO()
  576. ;
  577. if (!linked)
  578. {
  579. const char* log = program->getInfoLog();
  580. if (NULL != log)
  581. {
  582. fprintf(stderr, "%s\n", log);
  583. }
  584. }
  585. else
  586. {
  587. uint16_t size = 0;
  588. program->buildReflection();
  589. if (_firstPass)
  590. {
  591. const size_t strLength = bx::strLen("uniform");
  592. // first time through, we just find unused uniforms and get rid of them
  593. std::string output;
  594. bx::Error err;
  595. LineReader reader(_code.c_str() );
  596. while (err.isOk() )
  597. {
  598. char str[4096];
  599. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  600. if (err.isOk() )
  601. {
  602. std::string strLine(str, len);
  603. size_t index = strLine.find("uniform ");
  604. if (index != std::string::npos)
  605. {
  606. bool found = false;
  607. if (!bx::findIdentifierMatch(strLine.c_str(), "SamplerState").isEmpty())
  608. {
  609. found = true;
  610. }
  611. else
  612. {
  613. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  614. {
  615. // matching lines like: uniform u_name;
  616. // we want to replace "uniform" with "static" so that it's no longer
  617. // included in the uniform blob that the application must upload
  618. // we can't just remove them, because unused functions might still reference
  619. // them and cause a compile error when they're gone
  620. if (!bx::findIdentifierMatch(strLine.c_str(), program->getUniformName(ii)).isEmpty())
  621. {
  622. found = true;
  623. break;
  624. }
  625. }
  626. }
  627. if (!found)
  628. {
  629. strLine = strLine.replace(index, strLength, "static");
  630. }
  631. }
  632. output += strLine;
  633. }
  634. }
  635. // recompile with the unused uniforms converted to statics
  636. return compile(_options, _version, output.c_str(), _writer, false);
  637. }
  638. {
  639. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  640. bx::write(_writer, count);
  641. uint32_t fragmentBit = _options.shaderType == 'f' ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  642. for (uint16_t ii = 0; ii < count; ++ii)
  643. {
  644. Uniform un;
  645. un.name = program->getUniformName(ii);
  646. un.num = uint8_t(program->getUniformArraySize(ii) );
  647. const uint32_t offset = program->getUniformBufferOffset(ii);
  648. un.regIndex = uint16_t(offset);
  649. un.regCount = un.num;
  650. switch (program->getUniformType(ii))
  651. {
  652. case 0x1404: // GL_INT:
  653. un.type = UniformType::Sampler;
  654. break;
  655. case 0x8B52: // GL_FLOAT_VEC4:
  656. un.type = UniformType::Vec4;
  657. break;
  658. case 0x8B5B: // GL_FLOAT_MAT3:
  659. un.type = UniformType::Mat3;
  660. un.regCount *= 3;
  661. break;
  662. case 0x8B5C: // GL_FLOAT_MAT4:
  663. un.type = UniformType::Mat4;
  664. un.regCount *= 4;
  665. break;
  666. default:
  667. un.type = UniformType::End;
  668. break;
  669. }
  670. size += un.regCount*16;
  671. uint8_t nameSize = (uint8_t)un.name.size();
  672. bx::write(_writer, nameSize);
  673. bx::write(_writer, un.name.c_str(), nameSize);
  674. bx::write(_writer, uint8_t(un.type | fragmentBit));
  675. bx::write(_writer, un.num);
  676. bx::write(_writer, un.regIndex);
  677. bx::write(_writer, un.regCount);
  678. BX_TRACE("%s, %s, %d, %d, %d"
  679. , un.name.c_str()
  680. , getUniformTypeName(un.type)
  681. , un.num
  682. , un.regIndex
  683. , un.regCount
  684. );
  685. }
  686. }
  687. if (g_verbose)
  688. {
  689. program->dumpReflection();
  690. }
  691. BX_UNUSED(spv::MemorySemanticsAllMemory);
  692. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  693. std::vector<uint32_t> spirv;
  694. glslang::SpvOptions options;
  695. options.disableOptimizer = false;
  696. glslang::GlslangToSpv(*intermediate, spirv, &options);
  697. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  698. auto print_msg_to_stderr = [](spv_message_level_t, const char*,
  699. const spv_position_t&, const char* m) {
  700. fprintf(stderr, "error:%s\n", m);
  701. };
  702. opt.SetMessageConsumer(print_msg_to_stderr);
  703. opt.RegisterLegalizationPasses();
  704. if (!opt.Run(spirv.data(), spirv.size(), &spirv))
  705. {
  706. compiled = false;
  707. }
  708. else
  709. {
  710. bx::Error err;
  711. bx::WriterI* writer = bx::getDebugOut();
  712. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  713. disassemble(writer, &reader, &err);
  714. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0))
  715. {
  716. if (g_verbose)
  717. {
  718. glslang::SpirvToolsDisassemble(std::cout, spirv);
  719. }
  720. spirv_cross::CompilerMSL msl(std::move(spirv));
  721. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  722. msl.rename_entry_point("main", "xlatMtlMain", spv::ExecutionModel::ExecutionModelGLCompute);
  723. for (auto &resource : resources.uniform_buffers)
  724. {
  725. msl.set_name(resource.id, "_mtl_u");
  726. }
  727. for (auto &resource : resources.storage_buffers)
  728. {
  729. unsigned binding = msl.get_decoration(resource.id, spv::DecorationBinding);
  730. msl.set_decoration(resource.id, spv::DecorationBinding, binding + 1);
  731. // workaround spirv -> msl codegen problem: same name was used as struct type and function parameter name
  732. msl.set_name(resource.id, "_" + msl.get_name(resource.id));
  733. }
  734. std::string source = msl.compile();
  735. for (int i = 0; i < 3; ++i)
  736. {
  737. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  738. bx::write(_writer, dim);
  739. }
  740. uint32_t shaderSize = (uint32_t)source.size();
  741. bx::write(_writer, shaderSize);
  742. bx::write(_writer, source.c_str(), shaderSize);
  743. uint8_t nul = 0;
  744. bx::write(_writer, nul);
  745. }
  746. else
  747. {
  748. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  749. bx::write(_writer, shaderSize);
  750. bx::write(_writer, spirv.data(), shaderSize);
  751. uint8_t nul = 0;
  752. bx::write(_writer, nul);
  753. }
  754. //
  755. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  756. bx::write(_writer, numAttr);
  757. for (uint8_t ii = 0; ii < numAttr; ++ii)
  758. {
  759. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  760. if (bgfx::Attrib::Count != attr)
  761. {
  762. bx::write(_writer, bgfx::attribToId(attr) );
  763. }
  764. else
  765. {
  766. bx::write(_writer, uint16_t(UINT16_MAX) );
  767. }
  768. }
  769. bx::write(_writer, size);
  770. }
  771. }
  772. }
  773. delete program;
  774. delete shader;
  775. glslang::FinalizeProcess();
  776. return compiled && linked && validated;
  777. }
  778. } // namespace spirv
  779. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  780. {
  781. return spirv::compile(_options, _version, _code, _writer, true);
  782. }
  783. } // namespace bgfx