shaderc_metal.cpp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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 uint16_t writeUniformArray(bx::WriterI* _writer, const UniformArray& uniforms, bool isFragmentShader)
  495. {
  496. uint16_t size = 0;
  497. uint16_t count = static_cast<uint16_t>(uniforms.size());
  498. bx::write(_writer, count);
  499. uint32_t fragmentBit = isFragmentShader ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  500. for (uint16_t ii = 0; ii < count; ++ii)
  501. {
  502. const Uniform& un = uniforms[ii];
  503. size += un.regCount*16;
  504. uint8_t nameSize = (uint8_t)un.name.size();
  505. bx::write(_writer, nameSize);
  506. bx::write(_writer, un.name.c_str(), nameSize);
  507. bx::write(_writer, uint8_t(un.type | fragmentBit));
  508. bx::write(_writer, un.num);
  509. bx::write(_writer, un.regIndex);
  510. bx::write(_writer, un.regCount);
  511. BX_TRACE("%s, %s, %d, %d, %d"
  512. , un.name.c_str()
  513. , getUniformTypeName(un.type)
  514. , un.num
  515. , un.regIndex
  516. , un.regCount
  517. );
  518. }
  519. return size;
  520. }
  521. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  522. {
  523. BX_UNUSED(_version);
  524. glslang::InitializeProcess();
  525. glslang::TProgram* program = new glslang::TProgram;
  526. EShLanguage stage = getLang(_options.shaderType);
  527. if (EShLangCount == stage)
  528. {
  529. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  530. return false;
  531. }
  532. glslang::TShader* shader = new glslang::TShader(stage);
  533. EShMessages messages = EShMessages(0
  534. | EShMsgDefault
  535. | EShMsgReadHlsl
  536. | EShMsgVulkanRules
  537. | EShMsgSpvRules
  538. );
  539. shader->setEntryPoint("main");
  540. shader->setAutoMapBindings(true);
  541. const int textureBindingOffset = 16;
  542. shader->setShiftBinding(glslang::EResTexture, textureBindingOffset);
  543. shader->setShiftBinding(glslang::EResSampler, textureBindingOffset);
  544. shader->setShiftBinding(glslang::EResImage, textureBindingOffset);
  545. const char* shaderStrings[] = { _code.c_str() };
  546. shader->setStrings(
  547. shaderStrings
  548. , BX_COUNTOF(shaderStrings)
  549. );
  550. bool compiled = shader->parse(&resourceLimits
  551. , 110
  552. , false
  553. , messages
  554. );
  555. bool linked = false;
  556. bool validated = true;
  557. if (!compiled)
  558. {
  559. const char* log = shader->getInfoLog();
  560. if (NULL != log)
  561. {
  562. int32_t source = 0;
  563. int32_t line = 0;
  564. int32_t column = 0;
  565. int32_t start = 0;
  566. int32_t end = INT32_MAX;
  567. bx::StringView err = bx::strFind(log, "ERROR:");
  568. bool found = false;
  569. if (!err.isEmpty() )
  570. {
  571. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  572. if (found)
  573. {
  574. ++line;
  575. }
  576. }
  577. if (found)
  578. {
  579. start = bx::uint32_imax(1, line-10);
  580. end = start + 20;
  581. }
  582. printCode(_code.c_str(), line, start, end, column);
  583. bx::printf("%s\n", log);
  584. }
  585. }
  586. else
  587. {
  588. program->addShader(shader);
  589. linked = true
  590. && program->link(messages)
  591. && program->mapIO()
  592. ;
  593. if (!linked)
  594. {
  595. const char* log = program->getInfoLog();
  596. if (NULL != log)
  597. {
  598. bx::printf("%s\n", log);
  599. }
  600. }
  601. else
  602. {
  603. program->buildReflection();
  604. if (_firstPass)
  605. {
  606. // first time through, we just find unused uniforms and get rid of them
  607. std::string output;
  608. bx::Error err;
  609. LineReader reader(_code.c_str() );
  610. while (err.isOk() )
  611. {
  612. char str[4096];
  613. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  614. if (err.isOk() )
  615. {
  616. std::string strLine(str, len);
  617. size_t index = strLine.find("uniform ");
  618. if (index != std::string::npos)
  619. {
  620. bool found = false;
  621. if (!bx::findIdentifierMatch(strLine.c_str(), "SamplerState").isEmpty() ||
  622. !bx::findIdentifierMatch(strLine.c_str(), "SamplerComparisonState").isEmpty())
  623. {
  624. found = true;
  625. }
  626. else
  627. {
  628. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  629. {
  630. // matching lines like: uniform u_name;
  631. // we want to replace "uniform" with "static" so that it's no longer
  632. // included in the uniform blob that the application must upload
  633. // we can't just remove them, because unused functions might still reference
  634. // them and cause a compile error when they're gone
  635. if (!bx::findIdentifierMatch(strLine.c_str(), program->getUniformName(ii)).isEmpty())
  636. {
  637. found = true;
  638. break;
  639. }
  640. }
  641. }
  642. if (!found)
  643. {
  644. strLine = strLine.replace(index, 7 /* uniform */, "static");
  645. }
  646. }
  647. output += strLine;
  648. }
  649. }
  650. // recompile with the unused uniforms converted to statics
  651. return compile(_options, _version, output.c_str(), _writer, false);
  652. }
  653. UniformArray uniforms;
  654. {
  655. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  656. for (uint16_t ii = 0; ii < count; ++ii)
  657. {
  658. Uniform un;
  659. un.name = program->getUniformName(ii);
  660. un.num = uint8_t(program->getUniformArraySize(ii) );
  661. const uint32_t offset = program->getUniformBufferOffset(ii);
  662. un.regIndex = uint16_t(offset);
  663. un.regCount = un.num;
  664. switch (program->getUniformType(ii))
  665. {
  666. case 0x1404: // GL_INT:
  667. un.type = UniformType::Sampler;
  668. break;
  669. case 0x8B52: // GL_FLOAT_VEC4:
  670. un.type = UniformType::Vec4;
  671. break;
  672. case 0x8B5B: // GL_FLOAT_MAT3:
  673. un.type = UniformType::Mat3;
  674. un.regCount *= 3;
  675. break;
  676. case 0x8B5C: // GL_FLOAT_MAT4:
  677. un.type = UniformType::Mat4;
  678. un.regCount *= 4;
  679. break;
  680. default:
  681. un.type = UniformType::End;
  682. break;
  683. }
  684. uniforms.push_back(un);
  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 = [](
  699. spv_message_level_t
  700. , const char*
  701. , const spv_position_t&
  702. , const char* m
  703. )
  704. {
  705. bx::printf("Error: %s\n", m);
  706. };
  707. opt.SetMessageConsumer(print_msg_to_stderr);
  708. opt.RegisterLegalizationPasses();
  709. if (!opt.Run(spirv.data(), spirv.size(), &spirv))
  710. {
  711. compiled = false;
  712. }
  713. else
  714. {
  715. bx::Error err;
  716. bx::WriterI* writer = bx::getDebugOut();
  717. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  718. disassemble(writer, &reader, &err);
  719. spirv_cross::CompilerReflection refl(spirv);
  720. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  721. // Loop through the separate_images, and extract the uniform names:
  722. for (auto &resource : resourcesrefl.separate_images)
  723. {
  724. std::string name = refl.get_name(resource.id);
  725. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  726. {
  727. auto uniform_name = name.substr(0, name.length() - 7);
  728. Uniform un;
  729. un.name = uniform_name;
  730. un.type = UniformType::Sampler;
  731. un.num = 0; // needed?
  732. un.regIndex = 0; // needed?
  733. un.regCount = 0; // needed?
  734. uniforms.push_back(un);
  735. }
  736. }
  737. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  738. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0))
  739. {
  740. if (g_verbose)
  741. {
  742. glslang::SpirvToolsDisassemble(std::cout, spirv);
  743. }
  744. spirv_cross::CompilerMSL msl(std::move(spirv));
  745. auto executionModel = msl.get_execution_model();
  746. spirv_cross::MSLResourceBinding newBinding;
  747. newBinding.stage = executionModel;
  748. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  749. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  750. if (!entryPoints.empty())
  751. msl.rename_entry_point(entryPoints[0].name, "xlatMtlMain", entryPoints[0].execution_model);
  752. for (auto &resource : resources.uniform_buffers)
  753. {
  754. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  755. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  756. newBinding.desc_set = set;
  757. newBinding.binding = binding;
  758. newBinding.msl_buffer = 0;
  759. msl.add_msl_resource_binding( newBinding );
  760. msl.set_name(resource.id, "_mtl_u");
  761. }
  762. for (auto &resource : resources.storage_buffers)
  763. {
  764. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  765. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  766. newBinding.desc_set = set;
  767. newBinding.binding = binding;
  768. newBinding.msl_buffer = binding + 1;
  769. msl.add_msl_resource_binding( newBinding );
  770. }
  771. for (auto &resource : resources.separate_samplers)
  772. {
  773. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  774. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  775. newBinding.desc_set = set;
  776. newBinding.binding = binding;
  777. newBinding.msl_texture = binding - textureBindingOffset;
  778. newBinding.msl_sampler = binding - textureBindingOffset;
  779. msl.add_msl_resource_binding( newBinding );
  780. }
  781. for (auto &resource : resources.separate_images)
  782. {
  783. std::string name = msl.get_name(resource.id);
  784. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  785. msl.set_name(resource.id, name.substr(0, name.length() - 7));
  786. unsigned set = msl.get_decoration( resource.id, spv::DecorationDescriptorSet );
  787. unsigned binding = msl.get_decoration( resource.id, spv::DecorationBinding );
  788. newBinding.desc_set = set;
  789. newBinding.binding = binding;
  790. newBinding.msl_texture = binding - textureBindingOffset;
  791. newBinding.msl_sampler = binding - textureBindingOffset;
  792. msl.add_msl_resource_binding( newBinding );
  793. }
  794. for (auto &resource : resources.storage_images)
  795. {
  796. std::string name = msl.get_name(resource.id);
  797. if (name.size() > 7 && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  798. msl.set_name(resource.id, name.substr(0, name.length() - 7));
  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. std::string source = msl.compile();
  808. if ('c' == _options.shaderType)
  809. {
  810. for (int i = 0; i < 3; ++i)
  811. {
  812. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  813. bx::write(_writer, dim);
  814. }
  815. }
  816. uint32_t shaderSize = (uint32_t)source.size();
  817. bx::write(_writer, shaderSize);
  818. bx::write(_writer, source.c_str(), shaderSize);
  819. uint8_t nul = 0;
  820. bx::write(_writer, nul);
  821. }
  822. else
  823. {
  824. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  825. bx::write(_writer, shaderSize);
  826. bx::write(_writer, spirv.data(), shaderSize);
  827. uint8_t nul = 0;
  828. bx::write(_writer, nul);
  829. }
  830. //
  831. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  832. bx::write(_writer, numAttr);
  833. for (uint8_t ii = 0; ii < numAttr; ++ii)
  834. {
  835. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  836. if (bgfx::Attrib::Count != attr)
  837. {
  838. bx::write(_writer, bgfx::attribToId(attr) );
  839. }
  840. else
  841. {
  842. bx::write(_writer, uint16_t(UINT16_MAX) );
  843. }
  844. }
  845. bx::write(_writer, size);
  846. }
  847. }
  848. }
  849. delete program;
  850. delete shader;
  851. glslang::FinalizeProcess();
  852. return compiled && linked && validated;
  853. }
  854. } // namespace metal
  855. bool compileMetalShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  856. {
  857. return metal::compile(_options, _version, _code, _writer, true);
  858. }
  859. } // namespace bgfx