emit_context.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <string_view>
  7. #include <fmt/format.h>
  8. #include "common/common_types.h"
  9. #include "shader_recompiler/backend/spirv/emit_context.h"
  10. namespace Shader::Backend::SPIRV {
  11. namespace {
  12. Id ImageType(EmitContext& ctx, const TextureDescriptor& desc) {
  13. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  14. const Id type{ctx.F32[1]};
  15. switch (desc.type) {
  16. case TextureType::Color1D:
  17. return ctx.TypeImage(type, spv::Dim::Dim1D, false, false, false, 1, format);
  18. case TextureType::ColorArray1D:
  19. return ctx.TypeImage(type, spv::Dim::Dim1D, false, true, false, 1, format);
  20. case TextureType::Color2D:
  21. return ctx.TypeImage(type, spv::Dim::Dim2D, false, false, false, 1, format);
  22. case TextureType::ColorArray2D:
  23. return ctx.TypeImage(type, spv::Dim::Dim2D, false, true, false, 1, format);
  24. case TextureType::Color3D:
  25. return ctx.TypeImage(type, spv::Dim::Dim3D, false, false, false, 1, format);
  26. case TextureType::ColorCube:
  27. return ctx.TypeImage(type, spv::Dim::Cube, false, false, false, 1, format);
  28. case TextureType::ColorArrayCube:
  29. return ctx.TypeImage(type, spv::Dim::Cube, false, true, false, 1, format);
  30. case TextureType::Shadow1D:
  31. return ctx.TypeImage(type, spv::Dim::Dim1D, true, false, false, 1, format);
  32. case TextureType::ShadowArray1D:
  33. return ctx.TypeImage(type, spv::Dim::Dim1D, true, true, false, 1, format);
  34. case TextureType::Shadow2D:
  35. return ctx.TypeImage(type, spv::Dim::Dim2D, true, false, false, 1, format);
  36. case TextureType::ShadowArray2D:
  37. return ctx.TypeImage(type, spv::Dim::Dim2D, true, true, false, 1, format);
  38. case TextureType::Shadow3D:
  39. return ctx.TypeImage(type, spv::Dim::Dim3D, true, false, false, 1, format);
  40. case TextureType::ShadowCube:
  41. return ctx.TypeImage(type, spv::Dim::Cube, true, false, false, 1, format);
  42. case TextureType::ShadowArrayCube:
  43. return ctx.TypeImage(type, spv::Dim::Cube, false, true, false, 1, format);
  44. }
  45. throw InvalidArgument("Invalid texture type {}", desc.type);
  46. }
  47. Id DefineVariable(EmitContext& ctx, Id type, std::optional<spv::BuiltIn> builtin,
  48. spv::StorageClass storage_class) {
  49. const Id pointer_type{ctx.TypePointer(storage_class, type)};
  50. const Id id{ctx.AddGlobalVariable(pointer_type, storage_class)};
  51. if (builtin) {
  52. ctx.Decorate(id, spv::Decoration::BuiltIn, *builtin);
  53. }
  54. ctx.interfaces.push_back(id);
  55. return id;
  56. }
  57. Id DefineInput(EmitContext& ctx, Id type, std::optional<spv::BuiltIn> builtin = std::nullopt) {
  58. return DefineVariable(ctx, type, builtin, spv::StorageClass::Input);
  59. }
  60. Id DefineOutput(EmitContext& ctx, Id type, std::optional<spv::BuiltIn> builtin = std::nullopt) {
  61. return DefineVariable(ctx, type, builtin, spv::StorageClass::Output);
  62. }
  63. Id GetAttributeType(EmitContext& ctx, AttributeType type) {
  64. switch (type) {
  65. case AttributeType::Float:
  66. return ctx.F32[4];
  67. case AttributeType::SignedInt:
  68. return ctx.TypeVector(ctx.TypeInt(32, true), 4);
  69. case AttributeType::UnsignedInt:
  70. return ctx.U32[4];
  71. }
  72. throw InvalidArgument("Invalid attribute type {}", type);
  73. }
  74. } // Anonymous namespace
  75. void VectorTypes::Define(Sirit::Module& sirit_ctx, Id base_type, std::string_view name) {
  76. defs[0] = sirit_ctx.Name(base_type, name);
  77. std::array<char, 6> def_name;
  78. for (int i = 1; i < 4; ++i) {
  79. const std::string_view def_name_view(
  80. def_name.data(),
  81. fmt::format_to_n(def_name.data(), def_name.size(), "{}x{}", name, i + 1).size);
  82. defs[i] = sirit_ctx.Name(sirit_ctx.TypeVector(base_type, i + 1), def_name_view);
  83. }
  84. }
  85. EmitContext::EmitContext(const Profile& profile_, IR::Program& program, u32& binding)
  86. : Sirit::Module(0x00010000), profile{profile_}, stage{program.stage} {
  87. AddCapability(spv::Capability::Shader);
  88. DefineCommonTypes(program.info);
  89. DefineCommonConstants();
  90. DefineInterfaces(program.info);
  91. DefineConstantBuffers(program.info, binding);
  92. DefineStorageBuffers(program.info, binding);
  93. DefineTextures(program.info, binding);
  94. DefineLabels(program);
  95. }
  96. EmitContext::~EmitContext() = default;
  97. Id EmitContext::Def(const IR::Value& value) {
  98. if (!value.IsImmediate()) {
  99. return value.Inst()->Definition<Id>();
  100. }
  101. switch (value.Type()) {
  102. case IR::Type::Void:
  103. // Void instructions are used for optional arguments (e.g. texture offsets)
  104. // They are not meant to be used in the SPIR-V module
  105. return Id{};
  106. case IR::Type::U1:
  107. return value.U1() ? true_value : false_value;
  108. case IR::Type::U32:
  109. return Constant(U32[1], value.U32());
  110. case IR::Type::U64:
  111. return Constant(U64, value.U64());
  112. case IR::Type::F32:
  113. return Constant(F32[1], value.F32());
  114. case IR::Type::F64:
  115. return Constant(F64[1], value.F64());
  116. case IR::Type::Label:
  117. return value.Label()->Definition<Id>();
  118. default:
  119. throw NotImplementedException("Immediate type {}", value.Type());
  120. }
  121. }
  122. void EmitContext::DefineCommonTypes(const Info& info) {
  123. void_id = TypeVoid();
  124. U1 = Name(TypeBool(), "u1");
  125. F32.Define(*this, TypeFloat(32), "f32");
  126. U32.Define(*this, TypeInt(32, false), "u32");
  127. input_f32 = Name(TypePointer(spv::StorageClass::Input, F32[1]), "input_f32");
  128. input_u32 = Name(TypePointer(spv::StorageClass::Input, U32[1]), "input_u32");
  129. input_s32 = Name(TypePointer(spv::StorageClass::Input, TypeInt(32, true)), "input_s32");
  130. output_f32 = Name(TypePointer(spv::StorageClass::Output, F32[1]), "output_f32");
  131. if (info.uses_int8) {
  132. AddCapability(spv::Capability::Int8);
  133. U8 = Name(TypeInt(8, false), "u8");
  134. S8 = Name(TypeInt(8, true), "s8");
  135. }
  136. if (info.uses_int16) {
  137. AddCapability(spv::Capability::Int16);
  138. U16 = Name(TypeInt(16, false), "u16");
  139. S16 = Name(TypeInt(16, true), "s16");
  140. }
  141. if (info.uses_int64) {
  142. AddCapability(spv::Capability::Int64);
  143. U64 = Name(TypeInt(64, false), "u64");
  144. }
  145. if (info.uses_fp16) {
  146. AddCapability(spv::Capability::Float16);
  147. F16.Define(*this, TypeFloat(16), "f16");
  148. }
  149. if (info.uses_fp64) {
  150. AddCapability(spv::Capability::Float64);
  151. F64.Define(*this, TypeFloat(64), "f64");
  152. }
  153. }
  154. void EmitContext::DefineCommonConstants() {
  155. true_value = ConstantTrue(U1);
  156. false_value = ConstantFalse(U1);
  157. u32_zero_value = Constant(U32[1], 0U);
  158. }
  159. void EmitContext::DefineInterfaces(const Info& info) {
  160. DefineInputs(info);
  161. DefineOutputs(info);
  162. }
  163. void EmitContext::DefineConstantBuffers(const Info& info, u32& binding) {
  164. if (info.constant_buffer_descriptors.empty()) {
  165. return;
  166. }
  167. if (True(info.used_constant_buffer_types & IR::Type::U8)) {
  168. DefineConstantBuffers(info, &UniformDefinitions::U8, binding, U8, 'u', sizeof(u8));
  169. DefineConstantBuffers(info, &UniformDefinitions::S8, binding, S8, 's', sizeof(s8));
  170. }
  171. if (True(info.used_constant_buffer_types & IR::Type::U16)) {
  172. DefineConstantBuffers(info, &UniformDefinitions::U16, binding, U16, 'u', sizeof(u16));
  173. DefineConstantBuffers(info, &UniformDefinitions::S16, binding, S16, 's', sizeof(s16));
  174. }
  175. if (True(info.used_constant_buffer_types & IR::Type::U32)) {
  176. DefineConstantBuffers(info, &UniformDefinitions::U32, binding, U32[1], 'u', sizeof(u32));
  177. }
  178. if (True(info.used_constant_buffer_types & IR::Type::F32)) {
  179. DefineConstantBuffers(info, &UniformDefinitions::F32, binding, F32[1], 'f', sizeof(f32));
  180. }
  181. if (True(info.used_constant_buffer_types & IR::Type::U64)) {
  182. DefineConstantBuffers(info, &UniformDefinitions::U64, binding, U64, 'u', sizeof(u64));
  183. }
  184. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  185. binding += desc.count;
  186. }
  187. }
  188. void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
  189. if (info.storage_buffers_descriptors.empty()) {
  190. return;
  191. }
  192. AddExtension("SPV_KHR_storage_buffer_storage_class");
  193. const Id array_type{TypeRuntimeArray(U32[1])};
  194. Decorate(array_type, spv::Decoration::ArrayStride, 4U);
  195. const Id struct_type{TypeStruct(array_type)};
  196. Name(struct_type, "ssbo_block");
  197. Decorate(struct_type, spv::Decoration::Block);
  198. MemberName(struct_type, 0, "data");
  199. MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  200. const Id storage_type{TypePointer(spv::StorageClass::StorageBuffer, struct_type)};
  201. storage_u32 = TypePointer(spv::StorageClass::StorageBuffer, U32[1]);
  202. u32 index{};
  203. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  204. const Id id{AddGlobalVariable(storage_type, spv::StorageClass::StorageBuffer)};
  205. Decorate(id, spv::Decoration::Binding, binding);
  206. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  207. Name(id, fmt::format("ssbo{}", index));
  208. std::fill_n(ssbos.data() + index, desc.count, id);
  209. index += desc.count;
  210. binding += desc.count;
  211. }
  212. }
  213. void EmitContext::DefineTextures(const Info& info, u32& binding) {
  214. textures.reserve(info.texture_descriptors.size());
  215. for (const TextureDescriptor& desc : info.texture_descriptors) {
  216. if (desc.count != 1) {
  217. throw NotImplementedException("Array of textures");
  218. }
  219. const Id image_type{ImageType(*this, desc)};
  220. const Id sampled_type{TypeSampledImage(image_type)};
  221. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, sampled_type)};
  222. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  223. Decorate(id, spv::Decoration::Binding, binding);
  224. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  225. Name(id, fmt::format("tex{}_{:02x}", desc.cbuf_index, desc.cbuf_offset));
  226. for (u32 index = 0; index < desc.count; ++index) {
  227. // TODO: Pass count info
  228. textures.push_back(TextureDefinition{
  229. .id{id},
  230. .sampled_type{sampled_type},
  231. .image_type{image_type},
  232. });
  233. }
  234. binding += desc.count;
  235. }
  236. }
  237. void EmitContext::DefineLabels(IR::Program& program) {
  238. for (IR::Block* const block : program.blocks) {
  239. block->SetDefinition(OpLabel());
  240. }
  241. }
  242. void EmitContext::DefineInputs(const Info& info) {
  243. if (info.uses_workgroup_id) {
  244. workgroup_id = DefineInput(*this, U32[3], spv::BuiltIn::WorkgroupId);
  245. }
  246. if (info.uses_local_invocation_id) {
  247. local_invocation_id = DefineInput(*this, U32[3], spv::BuiltIn::LocalInvocationId);
  248. }
  249. if (info.uses_subgroup_invocation_id ||
  250. (profile.warp_size_potentially_larger_than_guest && info.uses_subgroup_vote)) {
  251. subgroup_local_invocation_id =
  252. DefineInput(*this, U32[1], spv::BuiltIn::SubgroupLocalInvocationId);
  253. }
  254. if (info.loads_position) {
  255. const bool is_fragment{stage != Stage::Fragment};
  256. const spv::BuiltIn built_in{is_fragment ? spv::BuiltIn::Position : spv::BuiltIn::FragCoord};
  257. input_position = DefineInput(*this, F32[4], built_in);
  258. }
  259. if (info.loads_instance_id) {
  260. if (profile.support_vertex_instance_id) {
  261. instance_id = DefineInput(*this, U32[1], spv::BuiltIn::InstanceId);
  262. } else {
  263. instance_index = DefineInput(*this, U32[1], spv::BuiltIn::InstanceIndex);
  264. base_instance = DefineInput(*this, U32[1], spv::BuiltIn::BaseInstance);
  265. }
  266. }
  267. if (info.loads_vertex_id) {
  268. if (profile.support_vertex_instance_id) {
  269. vertex_id = DefineInput(*this, U32[1], spv::BuiltIn::VertexId);
  270. } else {
  271. vertex_index = DefineInput(*this, U32[1], spv::BuiltIn::VertexIndex);
  272. base_vertex = DefineInput(*this, U32[1], spv::BuiltIn::BaseVertex);
  273. }
  274. }
  275. if (info.loads_front_face) {
  276. front_face = DefineInput(*this, U1, spv::BuiltIn::FrontFacing);
  277. }
  278. for (size_t index = 0; index < info.loads_generics.size(); ++index) {
  279. if (!info.loads_generics[index]) {
  280. continue;
  281. }
  282. const Id type{GetAttributeType(*this, profile.generic_input_types[index])};
  283. const Id id{DefineInput(*this, type)};
  284. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  285. Name(id, fmt::format("in_attr{}", index));
  286. input_generics[index] = id;
  287. }
  288. }
  289. void EmitContext::DefineConstantBuffers(const Info& info, Id UniformDefinitions::*member_type,
  290. u32 binding, Id type, char type_char, u32 element_size) {
  291. const Id array_type{TypeArray(type, Constant(U32[1], 65536U / element_size))};
  292. Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  293. const Id struct_type{TypeStruct(array_type)};
  294. Name(struct_type, fmt::format("cbuf_block_{}{}", type_char, element_size * CHAR_BIT));
  295. Decorate(struct_type, spv::Decoration::Block);
  296. MemberName(struct_type, 0, "data");
  297. MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  298. const Id struct_pointer_type{TypePointer(spv::StorageClass::Uniform, struct_type)};
  299. const Id uniform_type{TypePointer(spv::StorageClass::Uniform, type)};
  300. uniform_types.*member_type = uniform_type;
  301. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  302. const Id id{AddGlobalVariable(struct_pointer_type, spv::StorageClass::Uniform)};
  303. Decorate(id, spv::Decoration::Binding, binding);
  304. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  305. Name(id, fmt::format("c{}", desc.index));
  306. for (size_t i = 0; i < desc.count; ++i) {
  307. cbufs[desc.index + i].*member_type = id;
  308. }
  309. binding += desc.count;
  310. }
  311. }
  312. void EmitContext::DefineOutputs(const Info& info) {
  313. if (info.stores_position || stage == Stage::VertexB) {
  314. output_position = DefineOutput(*this, F32[4], spv::BuiltIn::Position);
  315. }
  316. for (size_t i = 0; i < info.stores_generics.size(); ++i) {
  317. if (info.stores_generics[i]) {
  318. output_generics[i] = DefineOutput(*this, F32[4]);
  319. Decorate(output_generics[i], spv::Decoration::Location, static_cast<u32>(i));
  320. Name(output_generics[i], fmt::format("out_attr{}", i));
  321. }
  322. }
  323. if (stage == Stage::Fragment) {
  324. for (u32 index = 0; index < 8; ++index) {
  325. if (!info.stores_frag_color[index]) {
  326. continue;
  327. }
  328. frag_color[index] = DefineOutput(*this, F32[4]);
  329. Decorate(frag_color[index], spv::Decoration::Location, index);
  330. Name(frag_color[index], fmt::format("frag_color{}", index));
  331. }
  332. if (info.stores_frag_depth) {
  333. frag_depth = DefineOutput(*this, F32[1]);
  334. Decorate(frag_depth, spv::Decoration::BuiltIn, spv::BuiltIn::FragDepth);
  335. Name(frag_depth, "frag_depth");
  336. }
  337. }
  338. }
  339. } // namespace Shader::Backend::SPIRV