shaderc_metal.cpp 26 KB

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