shaderc_metal.cpp 26 KB

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