emit_context.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  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 <climits>
  7. #include <string_view>
  8. #include <fmt/format.h>
  9. #include "common/common_types.h"
  10. #include "common/div_ceil.h"
  11. #include "shader_recompiler/backend/spirv/emit_context.h"
  12. namespace Shader::Backend::SPIRV {
  13. namespace {
  14. enum class Operation {
  15. Increment,
  16. Decrement,
  17. FPAdd,
  18. FPMin,
  19. FPMax,
  20. };
  21. struct AttrInfo {
  22. Id pointer;
  23. Id id;
  24. bool needs_cast;
  25. };
  26. Id ImageType(EmitContext& ctx, const TextureDescriptor& desc) {
  27. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  28. const Id type{ctx.F32[1]};
  29. const bool depth{desc.is_depth};
  30. switch (desc.type) {
  31. case TextureType::Color1D:
  32. return ctx.TypeImage(type, spv::Dim::Dim1D, depth, false, false, 1, format);
  33. case TextureType::ColorArray1D:
  34. return ctx.TypeImage(type, spv::Dim::Dim1D, depth, true, false, 1, format);
  35. case TextureType::Color2D:
  36. return ctx.TypeImage(type, spv::Dim::Dim2D, depth, false, false, 1, format);
  37. case TextureType::ColorArray2D:
  38. return ctx.TypeImage(type, spv::Dim::Dim2D, depth, true, false, 1, format);
  39. case TextureType::Color3D:
  40. return ctx.TypeImage(type, spv::Dim::Dim3D, depth, false, false, 1, format);
  41. case TextureType::ColorCube:
  42. return ctx.TypeImage(type, spv::Dim::Cube, depth, false, false, 1, format);
  43. case TextureType::ColorArrayCube:
  44. return ctx.TypeImage(type, spv::Dim::Cube, depth, true, false, 1, format);
  45. case TextureType::Buffer:
  46. break;
  47. }
  48. throw InvalidArgument("Invalid texture type {}", desc.type);
  49. }
  50. spv::ImageFormat GetImageFormat(ImageFormat format) {
  51. switch (format) {
  52. case ImageFormat::Typeless:
  53. return spv::ImageFormat::Unknown;
  54. case ImageFormat::R8_UINT:
  55. return spv::ImageFormat::R8ui;
  56. case ImageFormat::R8_SINT:
  57. return spv::ImageFormat::R8i;
  58. case ImageFormat::R16_UINT:
  59. return spv::ImageFormat::R16ui;
  60. case ImageFormat::R16_SINT:
  61. return spv::ImageFormat::R16i;
  62. case ImageFormat::R32_UINT:
  63. return spv::ImageFormat::R32ui;
  64. case ImageFormat::R32G32_UINT:
  65. return spv::ImageFormat::Rg32ui;
  66. case ImageFormat::R32G32B32A32_UINT:
  67. return spv::ImageFormat::Rgba32ui;
  68. }
  69. throw InvalidArgument("Invalid image format {}", format);
  70. }
  71. Id ImageType(EmitContext& ctx, const ImageDescriptor& desc) {
  72. const spv::ImageFormat format{GetImageFormat(desc.format)};
  73. const Id type{ctx.U32[1]};
  74. switch (desc.type) {
  75. case TextureType::Color1D:
  76. return ctx.TypeImage(type, spv::Dim::Dim1D, false, false, false, 2, format);
  77. case TextureType::ColorArray1D:
  78. return ctx.TypeImage(type, spv::Dim::Dim1D, false, true, false, 2, format);
  79. case TextureType::Color2D:
  80. return ctx.TypeImage(type, spv::Dim::Dim2D, false, false, false, 2, format);
  81. case TextureType::ColorArray2D:
  82. return ctx.TypeImage(type, spv::Dim::Dim2D, false, true, false, 2, format);
  83. case TextureType::Color3D:
  84. return ctx.TypeImage(type, spv::Dim::Dim3D, false, false, false, 2, format);
  85. case TextureType::Buffer:
  86. throw NotImplementedException("Image buffer");
  87. default:
  88. break;
  89. }
  90. throw InvalidArgument("Invalid texture type {}", desc.type);
  91. }
  92. Id DefineVariable(EmitContext& ctx, Id type, std::optional<spv::BuiltIn> builtin,
  93. spv::StorageClass storage_class) {
  94. const Id pointer_type{ctx.TypePointer(storage_class, type)};
  95. const Id id{ctx.AddGlobalVariable(pointer_type, storage_class)};
  96. if (builtin) {
  97. ctx.Decorate(id, spv::Decoration::BuiltIn, *builtin);
  98. }
  99. ctx.interfaces.push_back(id);
  100. return id;
  101. }
  102. u32 NumVertices(InputTopology input_topology) {
  103. switch (input_topology) {
  104. case InputTopology::Points:
  105. return 1;
  106. case InputTopology::Lines:
  107. return 2;
  108. case InputTopology::LinesAdjacency:
  109. return 4;
  110. case InputTopology::Triangles:
  111. return 3;
  112. case InputTopology::TrianglesAdjacency:
  113. return 6;
  114. }
  115. throw InvalidArgument("Invalid input topology {}", input_topology);
  116. }
  117. Id DefineInput(EmitContext& ctx, Id type, bool per_invocation,
  118. std::optional<spv::BuiltIn> builtin = std::nullopt) {
  119. switch (ctx.stage) {
  120. case Stage::TessellationControl:
  121. case Stage::TessellationEval:
  122. if (per_invocation) {
  123. type = ctx.TypeArray(type, ctx.Const(32u));
  124. }
  125. break;
  126. case Stage::Geometry:
  127. if (per_invocation) {
  128. const u32 num_vertices{NumVertices(ctx.runtime_info.input_topology)};
  129. type = ctx.TypeArray(type, ctx.Const(num_vertices));
  130. }
  131. break;
  132. default:
  133. break;
  134. }
  135. return DefineVariable(ctx, type, builtin, spv::StorageClass::Input);
  136. }
  137. Id DefineOutput(EmitContext& ctx, Id type, std::optional<u32> invocations,
  138. std::optional<spv::BuiltIn> builtin = std::nullopt) {
  139. if (invocations && ctx.stage == Stage::TessellationControl) {
  140. type = ctx.TypeArray(type, ctx.Const(*invocations));
  141. }
  142. return DefineVariable(ctx, type, builtin, spv::StorageClass::Output);
  143. }
  144. void DefineGenericOutput(EmitContext& ctx, size_t index, std::optional<u32> invocations) {
  145. static constexpr std::string_view swizzle{"xyzw"};
  146. const size_t base_attr_index{static_cast<size_t>(IR::Attribute::Generic0X) + index * 4};
  147. u32 element{0};
  148. while (element < 4) {
  149. const u32 remainder{4 - element};
  150. const TransformFeedbackVarying* xfb_varying{};
  151. if (!ctx.runtime_info.xfb_varyings.empty()) {
  152. xfb_varying = &ctx.runtime_info.xfb_varyings[base_attr_index + element];
  153. xfb_varying = xfb_varying && xfb_varying->components > 0 ? xfb_varying : nullptr;
  154. }
  155. const u32 num_components{xfb_varying ? xfb_varying->components : remainder};
  156. const Id id{DefineOutput(ctx, ctx.F32[num_components], invocations)};
  157. ctx.Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  158. if (element > 0) {
  159. ctx.Decorate(id, spv::Decoration::Component, element);
  160. }
  161. if (xfb_varying) {
  162. ctx.Decorate(id, spv::Decoration::XfbBuffer, xfb_varying->buffer);
  163. ctx.Decorate(id, spv::Decoration::XfbStride, xfb_varying->stride);
  164. ctx.Decorate(id, spv::Decoration::Offset, xfb_varying->offset);
  165. }
  166. if (num_components < 4 || element > 0) {
  167. const std::string_view subswizzle{swizzle.substr(element, num_components)};
  168. ctx.Name(id, fmt::format("out_attr{}_{}", index, subswizzle));
  169. } else {
  170. ctx.Name(id, fmt::format("out_attr{}", index));
  171. }
  172. const GenericElementInfo info{
  173. .id = id,
  174. .first_element = element,
  175. .num_components = num_components,
  176. };
  177. std::fill_n(ctx.output_generics[index].begin() + element, num_components, info);
  178. element += num_components;
  179. }
  180. }
  181. Id GetAttributeType(EmitContext& ctx, AttributeType type) {
  182. switch (type) {
  183. case AttributeType::Float:
  184. return ctx.F32[4];
  185. case AttributeType::SignedInt:
  186. return ctx.TypeVector(ctx.TypeInt(32, true), 4);
  187. case AttributeType::UnsignedInt:
  188. return ctx.U32[4];
  189. case AttributeType::Disabled:
  190. break;
  191. }
  192. throw InvalidArgument("Invalid attribute type {}", type);
  193. }
  194. std::optional<AttrInfo> AttrTypes(EmitContext& ctx, u32 index) {
  195. const AttributeType type{ctx.runtime_info.generic_input_types.at(index)};
  196. switch (type) {
  197. case AttributeType::Float:
  198. return AttrInfo{ctx.input_f32, ctx.F32[1], false};
  199. case AttributeType::UnsignedInt:
  200. return AttrInfo{ctx.input_u32, ctx.U32[1], true};
  201. case AttributeType::SignedInt:
  202. return AttrInfo{ctx.input_s32, ctx.TypeInt(32, true), true};
  203. case AttributeType::Disabled:
  204. return std::nullopt;
  205. }
  206. throw InvalidArgument("Invalid attribute type {}", type);
  207. }
  208. std::string_view StageName(Stage stage) {
  209. switch (stage) {
  210. case Stage::VertexA:
  211. return "vs_a";
  212. case Stage::VertexB:
  213. return "vs";
  214. case Stage::TessellationControl:
  215. return "tcs";
  216. case Stage::TessellationEval:
  217. return "tes";
  218. case Stage::Geometry:
  219. return "gs";
  220. case Stage::Fragment:
  221. return "fs";
  222. case Stage::Compute:
  223. return "cs";
  224. }
  225. throw InvalidArgument("Invalid stage {}", stage);
  226. }
  227. template <typename... Args>
  228. void Name(EmitContext& ctx, Id object, std::string_view format_str, Args&&... args) {
  229. ctx.Name(object,
  230. fmt::format(format_str, StageName(ctx.stage), std::forward<Args>(args)...).c_str());
  231. }
  232. void DefineConstBuffers(EmitContext& ctx, const Info& info, Id UniformDefinitions::*member_type,
  233. u32 binding, Id type, char type_char, u32 element_size) {
  234. const Id array_type{ctx.TypeArray(type, ctx.Const(65536U / element_size))};
  235. ctx.Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  236. const Id struct_type{ctx.TypeStruct(array_type)};
  237. Name(ctx, struct_type, "{}_cbuf_block_{}{}", ctx.stage, type_char, element_size * CHAR_BIT);
  238. ctx.Decorate(struct_type, spv::Decoration::Block);
  239. ctx.MemberName(struct_type, 0, "data");
  240. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  241. const Id struct_pointer_type{ctx.TypePointer(spv::StorageClass::Uniform, struct_type)};
  242. const Id uniform_type{ctx.TypePointer(spv::StorageClass::Uniform, type)};
  243. ctx.uniform_types.*member_type = uniform_type;
  244. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  245. const Id id{ctx.AddGlobalVariable(struct_pointer_type, spv::StorageClass::Uniform)};
  246. ctx.Decorate(id, spv::Decoration::Binding, binding);
  247. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  248. ctx.Name(id, fmt::format("c{}", desc.index));
  249. for (size_t i = 0; i < desc.count; ++i) {
  250. ctx.cbufs[desc.index + i].*member_type = id;
  251. }
  252. if (ctx.profile.supported_spirv >= 0x00010400) {
  253. ctx.interfaces.push_back(id);
  254. }
  255. binding += desc.count;
  256. }
  257. }
  258. void DefineSsbos(EmitContext& ctx, StorageTypeDefinition& type_def,
  259. Id StorageDefinitions::*member_type, const Info& info, u32 binding, Id type,
  260. u32 stride) {
  261. const Id array_type{ctx.TypeRuntimeArray(type)};
  262. ctx.Decorate(array_type, spv::Decoration::ArrayStride, stride);
  263. const Id struct_type{ctx.TypeStruct(array_type)};
  264. ctx.Decorate(struct_type, spv::Decoration::Block);
  265. ctx.MemberDecorate(struct_type, 0, spv::Decoration::Offset, 0U);
  266. const Id struct_pointer{ctx.TypePointer(spv::StorageClass::StorageBuffer, struct_type)};
  267. type_def.array = struct_pointer;
  268. type_def.element = ctx.TypePointer(spv::StorageClass::StorageBuffer, type);
  269. u32 index{};
  270. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  271. const Id id{ctx.AddGlobalVariable(struct_pointer, spv::StorageClass::StorageBuffer)};
  272. ctx.Decorate(id, spv::Decoration::Binding, binding);
  273. ctx.Decorate(id, spv::Decoration::DescriptorSet, 0U);
  274. ctx.Name(id, fmt::format("ssbo{}", index));
  275. if (ctx.profile.supported_spirv >= 0x00010400) {
  276. ctx.interfaces.push_back(id);
  277. }
  278. for (size_t i = 0; i < desc.count; ++i) {
  279. ctx.ssbos[index + i].*member_type = id;
  280. }
  281. index += desc.count;
  282. binding += desc.count;
  283. }
  284. }
  285. Id CasFunction(EmitContext& ctx, Operation operation, Id value_type) {
  286. const Id func_type{ctx.TypeFunction(value_type, value_type, value_type)};
  287. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  288. const Id op_a{ctx.OpFunctionParameter(value_type)};
  289. const Id op_b{ctx.OpFunctionParameter(value_type)};
  290. ctx.AddLabel();
  291. Id result{};
  292. switch (operation) {
  293. case Operation::Increment: {
  294. const Id pred{ctx.OpUGreaterThanEqual(ctx.U1, op_a, op_b)};
  295. const Id incr{ctx.OpIAdd(value_type, op_a, ctx.Constant(value_type, 1))};
  296. result = ctx.OpSelect(value_type, pred, ctx.u32_zero_value, incr);
  297. break;
  298. }
  299. case Operation::Decrement: {
  300. const Id lhs{ctx.OpIEqual(ctx.U1, op_a, ctx.Constant(value_type, 0u))};
  301. const Id rhs{ctx.OpUGreaterThan(ctx.U1, op_a, op_b)};
  302. const Id pred{ctx.OpLogicalOr(ctx.U1, lhs, rhs)};
  303. const Id decr{ctx.OpISub(value_type, op_a, ctx.Constant(value_type, 1))};
  304. result = ctx.OpSelect(value_type, pred, op_b, decr);
  305. break;
  306. }
  307. case Operation::FPAdd:
  308. result = ctx.OpFAdd(value_type, op_a, op_b);
  309. break;
  310. case Operation::FPMin:
  311. result = ctx.OpFMin(value_type, op_a, op_b);
  312. break;
  313. case Operation::FPMax:
  314. result = ctx.OpFMax(value_type, op_a, op_b);
  315. break;
  316. default:
  317. break;
  318. }
  319. ctx.OpReturnValue(result);
  320. ctx.OpFunctionEnd();
  321. return func;
  322. }
  323. Id CasLoop(EmitContext& ctx, Operation operation, Id array_pointer, Id element_pointer,
  324. Id value_type, Id memory_type, spv::Scope scope) {
  325. const bool is_shared{scope == spv::Scope::Workgroup};
  326. const bool is_struct{!is_shared || ctx.profile.support_explicit_workgroup_layout};
  327. const Id cas_func{CasFunction(ctx, operation, value_type)};
  328. const Id zero{ctx.u32_zero_value};
  329. const Id scope_id{ctx.Const(static_cast<u32>(scope))};
  330. const Id loop_header{ctx.OpLabel()};
  331. const Id continue_block{ctx.OpLabel()};
  332. const Id merge_block{ctx.OpLabel()};
  333. const Id func_type{is_shared
  334. ? ctx.TypeFunction(value_type, ctx.U32[1], value_type)
  335. : ctx.TypeFunction(value_type, ctx.U32[1], value_type, array_pointer)};
  336. const Id func{ctx.OpFunction(value_type, spv::FunctionControlMask::MaskNone, func_type)};
  337. const Id index{ctx.OpFunctionParameter(ctx.U32[1])};
  338. const Id op_b{ctx.OpFunctionParameter(value_type)};
  339. const Id base{is_shared ? ctx.shared_memory_u32 : ctx.OpFunctionParameter(array_pointer)};
  340. ctx.AddLabel();
  341. ctx.OpBranch(loop_header);
  342. ctx.AddLabel(loop_header);
  343. ctx.OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  344. ctx.OpBranch(continue_block);
  345. ctx.AddLabel(continue_block);
  346. const Id word_pointer{is_struct ? ctx.OpAccessChain(element_pointer, base, zero, index)
  347. : ctx.OpAccessChain(element_pointer, base, index)};
  348. if (value_type.value == ctx.F32[2].value) {
  349. const Id u32_value{ctx.OpLoad(ctx.U32[1], word_pointer)};
  350. const Id value{ctx.OpUnpackHalf2x16(ctx.F32[2], u32_value)};
  351. const Id new_value{ctx.OpFunctionCall(value_type, cas_func, value, op_b)};
  352. const Id u32_new_value{ctx.OpPackHalf2x16(ctx.U32[1], new_value)};
  353. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  354. zero, u32_new_value, u32_value)};
  355. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, u32_value)};
  356. ctx.OpBranchConditional(success, merge_block, loop_header);
  357. ctx.AddLabel(merge_block);
  358. ctx.OpReturnValue(ctx.OpUnpackHalf2x16(ctx.F32[2], atomic_res));
  359. } else {
  360. const Id value{ctx.OpLoad(memory_type, word_pointer)};
  361. const bool matching_type{value_type.value == memory_type.value};
  362. const Id bitcast_value{matching_type ? value : ctx.OpBitcast(value_type, value)};
  363. const Id cal_res{ctx.OpFunctionCall(value_type, cas_func, bitcast_value, op_b)};
  364. const Id new_value{matching_type ? cal_res : ctx.OpBitcast(memory_type, cal_res)};
  365. const Id atomic_res{ctx.OpAtomicCompareExchange(ctx.U32[1], word_pointer, scope_id, zero,
  366. zero, new_value, value)};
  367. const Id success{ctx.OpIEqual(ctx.U1, atomic_res, value)};
  368. ctx.OpBranchConditional(success, merge_block, loop_header);
  369. ctx.AddLabel(merge_block);
  370. ctx.OpReturnValue(ctx.OpBitcast(value_type, atomic_res));
  371. }
  372. ctx.OpFunctionEnd();
  373. return func;
  374. }
  375. template <typename Desc>
  376. std::string NameOf(Stage stage, const Desc& desc, std::string_view prefix) {
  377. if (desc.count > 1) {
  378. return fmt::format("{}_{}{}_{:02x}x{}", StageName(stage), prefix, desc.cbuf_index,
  379. desc.cbuf_offset, desc.count);
  380. } else {
  381. return fmt::format("{}_{}{}_{:02x}", StageName(stage), prefix, desc.cbuf_index,
  382. desc.cbuf_offset);
  383. }
  384. }
  385. Id DescType(EmitContext& ctx, Id sampled_type, Id pointer_type, u32 count) {
  386. if (count > 1) {
  387. const Id array_type{ctx.TypeArray(sampled_type, ctx.Const(count))};
  388. return ctx.TypePointer(spv::StorageClass::UniformConstant, array_type);
  389. } else {
  390. return pointer_type;
  391. }
  392. }
  393. } // Anonymous namespace
  394. void VectorTypes::Define(Sirit::Module& sirit_ctx, Id base_type, std::string_view name) {
  395. defs[0] = sirit_ctx.Name(base_type, name);
  396. std::array<char, 6> def_name;
  397. for (int i = 1; i < 4; ++i) {
  398. const std::string_view def_name_view(
  399. def_name.data(),
  400. fmt::format_to_n(def_name.data(), def_name.size(), "{}x{}", name, i + 1).size);
  401. defs[static_cast<size_t>(i)] =
  402. sirit_ctx.Name(sirit_ctx.TypeVector(base_type, i + 1), def_name_view);
  403. }
  404. }
  405. EmitContext::EmitContext(const Profile& profile_, const RuntimeInfo& runtime_info_,
  406. IR::Program& program, Bindings& bindings)
  407. : Sirit::Module(profile_.supported_spirv), profile{profile_},
  408. runtime_info{runtime_info_}, stage{program.stage} {
  409. const bool is_unified{profile.unified_descriptor_binding};
  410. u32& uniform_binding{is_unified ? bindings.unified : bindings.uniform_buffer};
  411. u32& storage_binding{is_unified ? bindings.unified : bindings.storage_buffer};
  412. u32& texture_binding{is_unified ? bindings.unified : bindings.texture};
  413. u32& image_binding{is_unified ? bindings.unified : bindings.image};
  414. AddCapability(spv::Capability::Shader);
  415. DefineCommonTypes(program.info);
  416. DefineCommonConstants();
  417. DefineInterfaces(program);
  418. DefineLocalMemory(program);
  419. DefineSharedMemory(program);
  420. DefineSharedMemoryFunctions(program);
  421. DefineConstantBuffers(program.info, uniform_binding);
  422. DefineStorageBuffers(program.info, storage_binding);
  423. DefineTextureBuffers(program.info, texture_binding);
  424. DefineImageBuffers(program.info, image_binding);
  425. DefineTextures(program.info, texture_binding);
  426. DefineImages(program.info, image_binding);
  427. DefineAttributeMemAccess(program.info);
  428. DefineGlobalMemoryFunctions(program.info);
  429. }
  430. EmitContext::~EmitContext() = default;
  431. Id EmitContext::Def(const IR::Value& value) {
  432. if (!value.IsImmediate()) {
  433. return value.InstRecursive()->Definition<Id>();
  434. }
  435. switch (value.Type()) {
  436. case IR::Type::Void:
  437. // Void instructions are used for optional arguments (e.g. texture offsets)
  438. // They are not meant to be used in the SPIR-V module
  439. return Id{};
  440. case IR::Type::U1:
  441. return value.U1() ? true_value : false_value;
  442. case IR::Type::U32:
  443. return Const(value.U32());
  444. case IR::Type::U64:
  445. return Constant(U64, value.U64());
  446. case IR::Type::F32:
  447. return Const(value.F32());
  448. case IR::Type::F64:
  449. return Constant(F64[1], value.F64());
  450. default:
  451. throw NotImplementedException("Immediate type {}", value.Type());
  452. }
  453. }
  454. Id EmitContext::BitOffset8(const IR::Value& offset) {
  455. if (offset.IsImmediate()) {
  456. return Const((offset.U32() % 4) * 8);
  457. }
  458. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(24u));
  459. }
  460. Id EmitContext::BitOffset16(const IR::Value& offset) {
  461. if (offset.IsImmediate()) {
  462. return Const(((offset.U32() / 2) % 2) * 16);
  463. }
  464. return OpBitwiseAnd(U32[1], OpShiftLeftLogical(U32[1], Def(offset), Const(3u)), Const(16u));
  465. }
  466. void EmitContext::DefineCommonTypes(const Info& info) {
  467. void_id = TypeVoid();
  468. U1 = Name(TypeBool(), "u1");
  469. F32.Define(*this, TypeFloat(32), "f32");
  470. U32.Define(*this, TypeInt(32, false), "u32");
  471. S32.Define(*this, TypeInt(32, true), "s32");
  472. private_u32 = Name(TypePointer(spv::StorageClass::Private, U32[1]), "private_u32");
  473. input_f32 = Name(TypePointer(spv::StorageClass::Input, F32[1]), "input_f32");
  474. input_u32 = Name(TypePointer(spv::StorageClass::Input, U32[1]), "input_u32");
  475. input_s32 = Name(TypePointer(spv::StorageClass::Input, TypeInt(32, true)), "input_s32");
  476. output_f32 = Name(TypePointer(spv::StorageClass::Output, F32[1]), "output_f32");
  477. output_u32 = Name(TypePointer(spv::StorageClass::Output, U32[1]), "output_u32");
  478. if (info.uses_int8 && profile.support_int8) {
  479. AddCapability(spv::Capability::Int8);
  480. U8 = Name(TypeInt(8, false), "u8");
  481. S8 = Name(TypeInt(8, true), "s8");
  482. }
  483. if (info.uses_int16 && profile.support_int16) {
  484. AddCapability(spv::Capability::Int16);
  485. U16 = Name(TypeInt(16, false), "u16");
  486. S16 = Name(TypeInt(16, true), "s16");
  487. }
  488. if (info.uses_int64) {
  489. AddCapability(spv::Capability::Int64);
  490. U64 = Name(TypeInt(64, false), "u64");
  491. }
  492. if (info.uses_fp16) {
  493. AddCapability(spv::Capability::Float16);
  494. F16.Define(*this, TypeFloat(16), "f16");
  495. }
  496. if (info.uses_fp64) {
  497. AddCapability(spv::Capability::Float64);
  498. F64.Define(*this, TypeFloat(64), "f64");
  499. }
  500. }
  501. void EmitContext::DefineCommonConstants() {
  502. true_value = ConstantTrue(U1);
  503. false_value = ConstantFalse(U1);
  504. u32_zero_value = Const(0U);
  505. f32_zero_value = Const(0.0f);
  506. }
  507. void EmitContext::DefineInterfaces(const IR::Program& program) {
  508. DefineInputs(program.info);
  509. DefineOutputs(program);
  510. }
  511. void EmitContext::DefineLocalMemory(const IR::Program& program) {
  512. if (program.local_memory_size == 0) {
  513. return;
  514. }
  515. const u32 num_elements{Common::DivCeil(program.local_memory_size, 4U)};
  516. const Id type{TypeArray(U32[1], Const(num_elements))};
  517. const Id pointer{TypePointer(spv::StorageClass::Private, type)};
  518. local_memory = AddGlobalVariable(pointer, spv::StorageClass::Private);
  519. if (profile.supported_spirv >= 0x00010400) {
  520. interfaces.push_back(local_memory);
  521. }
  522. }
  523. void EmitContext::DefineSharedMemory(const IR::Program& program) {
  524. if (program.shared_memory_size == 0) {
  525. return;
  526. }
  527. const auto make{[&](Id element_type, u32 element_size) {
  528. const u32 num_elements{Common::DivCeil(program.shared_memory_size, element_size)};
  529. const Id array_type{TypeArray(element_type, Const(num_elements))};
  530. Decorate(array_type, spv::Decoration::ArrayStride, element_size);
  531. const Id struct_type{TypeStruct(array_type)};
  532. MemberDecorate(struct_type, 0U, spv::Decoration::Offset, 0U);
  533. Decorate(struct_type, spv::Decoration::Block);
  534. const Id pointer{TypePointer(spv::StorageClass::Workgroup, struct_type)};
  535. const Id element_pointer{TypePointer(spv::StorageClass::Workgroup, element_type)};
  536. const Id variable{AddGlobalVariable(pointer, spv::StorageClass::Workgroup)};
  537. Decorate(variable, spv::Decoration::Aliased);
  538. interfaces.push_back(variable);
  539. return std::make_tuple(variable, element_pointer, pointer);
  540. }};
  541. if (profile.support_explicit_workgroup_layout) {
  542. AddExtension("SPV_KHR_workgroup_memory_explicit_layout");
  543. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayoutKHR);
  544. if (program.info.uses_int8) {
  545. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout8BitAccessKHR);
  546. std::tie(shared_memory_u8, shared_u8, std::ignore) = make(U8, 1);
  547. }
  548. if (program.info.uses_int16) {
  549. AddCapability(spv::Capability::WorkgroupMemoryExplicitLayout16BitAccessKHR);
  550. std::tie(shared_memory_u16, shared_u16, std::ignore) = make(U16, 2);
  551. }
  552. if (program.info.uses_int64) {
  553. std::tie(shared_memory_u64, shared_u64, std::ignore) = make(U64, 8);
  554. }
  555. std::tie(shared_memory_u32, shared_u32, shared_memory_u32_type) = make(U32[1], 4);
  556. std::tie(shared_memory_u32x2, shared_u32x2, std::ignore) = make(U32[2], 8);
  557. std::tie(shared_memory_u32x4, shared_u32x4, std::ignore) = make(U32[4], 16);
  558. return;
  559. }
  560. const u32 num_elements{Common::DivCeil(program.shared_memory_size, 4U)};
  561. const Id type{TypeArray(U32[1], Const(num_elements))};
  562. shared_memory_u32_type = TypePointer(spv::StorageClass::Workgroup, type);
  563. shared_u32 = TypePointer(spv::StorageClass::Workgroup, U32[1]);
  564. shared_memory_u32 = AddGlobalVariable(shared_memory_u32_type, spv::StorageClass::Workgroup);
  565. interfaces.push_back(shared_memory_u32);
  566. const Id func_type{TypeFunction(void_id, U32[1], U32[1])};
  567. const auto make_function{[&](u32 mask, u32 size) {
  568. const Id loop_header{OpLabel()};
  569. const Id continue_block{OpLabel()};
  570. const Id merge_block{OpLabel()};
  571. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type)};
  572. const Id offset{OpFunctionParameter(U32[1])};
  573. const Id insert_value{OpFunctionParameter(U32[1])};
  574. AddLabel();
  575. OpBranch(loop_header);
  576. AddLabel(loop_header);
  577. const Id word_offset{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  578. const Id shift_offset{OpShiftLeftLogical(U32[1], offset, Const(3U))};
  579. const Id bit_offset{OpBitwiseAnd(U32[1], shift_offset, Const(mask))};
  580. const Id count{Const(size)};
  581. OpLoopMerge(merge_block, continue_block, spv::LoopControlMask::MaskNone);
  582. OpBranch(continue_block);
  583. AddLabel(continue_block);
  584. const Id word_pointer{OpAccessChain(shared_u32, shared_memory_u32, word_offset)};
  585. const Id old_value{OpLoad(U32[1], word_pointer)};
  586. const Id new_value{OpBitFieldInsert(U32[1], old_value, insert_value, bit_offset, count)};
  587. const Id atomic_res{OpAtomicCompareExchange(U32[1], word_pointer, Const(1U), u32_zero_value,
  588. u32_zero_value, new_value, old_value)};
  589. const Id success{OpIEqual(U1, atomic_res, old_value)};
  590. OpBranchConditional(success, merge_block, loop_header);
  591. AddLabel(merge_block);
  592. OpReturn();
  593. OpFunctionEnd();
  594. return func;
  595. }};
  596. if (program.info.uses_int8) {
  597. shared_store_u8_func = make_function(24, 8);
  598. }
  599. if (program.info.uses_int16) {
  600. shared_store_u16_func = make_function(16, 16);
  601. }
  602. }
  603. void EmitContext::DefineSharedMemoryFunctions(const IR::Program& program) {
  604. if (program.info.uses_shared_increment) {
  605. increment_cas_shared = CasLoop(*this, Operation::Increment, shared_memory_u32_type,
  606. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  607. }
  608. if (program.info.uses_shared_decrement) {
  609. decrement_cas_shared = CasLoop(*this, Operation::Decrement, shared_memory_u32_type,
  610. shared_u32, U32[1], U32[1], spv::Scope::Workgroup);
  611. }
  612. }
  613. void EmitContext::DefineAttributeMemAccess(const Info& info) {
  614. const auto make_load{[&] {
  615. const bool is_array{stage == Stage::Geometry};
  616. const Id end_block{OpLabel()};
  617. const Id default_label{OpLabel()};
  618. const Id func_type_load{is_array ? TypeFunction(F32[1], U32[1], U32[1])
  619. : TypeFunction(F32[1], U32[1])};
  620. const Id func{OpFunction(F32[1], spv::FunctionControlMask::MaskNone, func_type_load)};
  621. const Id offset{OpFunctionParameter(U32[1])};
  622. const Id vertex{is_array ? OpFunctionParameter(U32[1]) : Id{}};
  623. AddLabel();
  624. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  625. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  626. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  627. std::vector<Sirit::Literal> literals;
  628. std::vector<Id> labels;
  629. if (info.loads_position) {
  630. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  631. labels.push_back(OpLabel());
  632. }
  633. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  634. for (u32 i = 0; i < info.input_generics.size(); ++i) {
  635. if (!info.input_generics[i].used) {
  636. continue;
  637. }
  638. literals.push_back(base_attribute_value + i);
  639. labels.push_back(OpLabel());
  640. }
  641. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  642. OpSwitch(compare_index, default_label, literals, labels);
  643. AddLabel(default_label);
  644. OpReturnValue(Const(0.0f));
  645. size_t label_index{0};
  646. if (info.loads_position) {
  647. AddLabel(labels[label_index]);
  648. const Id pointer{is_array
  649. ? OpAccessChain(input_f32, input_position, vertex, masked_index)
  650. : OpAccessChain(input_f32, input_position, masked_index)};
  651. const Id result{OpLoad(F32[1], pointer)};
  652. OpReturnValue(result);
  653. ++label_index;
  654. }
  655. for (size_t i = 0; i < info.input_generics.size(); i++) {
  656. if (!info.input_generics[i].used) {
  657. continue;
  658. }
  659. AddLabel(labels[label_index]);
  660. const auto type{AttrTypes(*this, static_cast<u32>(i))};
  661. if (!type) {
  662. OpReturnValue(Const(0.0f));
  663. ++label_index;
  664. continue;
  665. }
  666. const Id generic_id{input_generics.at(i)};
  667. const Id pointer{is_array
  668. ? OpAccessChain(type->pointer, generic_id, vertex, masked_index)
  669. : OpAccessChain(type->pointer, generic_id, masked_index)};
  670. const Id value{OpLoad(type->id, pointer)};
  671. const Id result{type->needs_cast ? OpBitcast(F32[1], value) : value};
  672. OpReturnValue(result);
  673. ++label_index;
  674. }
  675. AddLabel(end_block);
  676. OpUnreachable();
  677. OpFunctionEnd();
  678. return func;
  679. }};
  680. const auto make_store{[&] {
  681. const Id end_block{OpLabel()};
  682. const Id default_label{OpLabel()};
  683. const Id func_type_store{TypeFunction(void_id, U32[1], F32[1])};
  684. const Id func{OpFunction(void_id, spv::FunctionControlMask::MaskNone, func_type_store)};
  685. const Id offset{OpFunctionParameter(U32[1])};
  686. const Id store_value{OpFunctionParameter(F32[1])};
  687. AddLabel();
  688. const Id base_index{OpShiftRightArithmetic(U32[1], offset, Const(2U))};
  689. const Id masked_index{OpBitwiseAnd(U32[1], base_index, Const(3U))};
  690. const Id compare_index{OpShiftRightArithmetic(U32[1], base_index, Const(2U))};
  691. std::vector<Sirit::Literal> literals;
  692. std::vector<Id> labels;
  693. if (info.stores_position) {
  694. literals.push_back(static_cast<u32>(IR::Attribute::PositionX) >> 2);
  695. labels.push_back(OpLabel());
  696. }
  697. const u32 base_attribute_value = static_cast<u32>(IR::Attribute::Generic0X) >> 2;
  698. for (size_t i = 0; i < info.stores_generics.size(); i++) {
  699. if (!info.stores_generics[i]) {
  700. continue;
  701. }
  702. literals.push_back(base_attribute_value + static_cast<u32>(i));
  703. labels.push_back(OpLabel());
  704. }
  705. if (info.stores_clip_distance) {
  706. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance0) >> 2);
  707. labels.push_back(OpLabel());
  708. literals.push_back(static_cast<u32>(IR::Attribute::ClipDistance4) >> 2);
  709. labels.push_back(OpLabel());
  710. }
  711. OpSelectionMerge(end_block, spv::SelectionControlMask::MaskNone);
  712. OpSwitch(compare_index, default_label, literals, labels);
  713. AddLabel(default_label);
  714. OpReturn();
  715. size_t label_index{0};
  716. if (info.stores_position) {
  717. AddLabel(labels[label_index]);
  718. const Id pointer{OpAccessChain(output_f32, output_position, masked_index)};
  719. OpStore(pointer, store_value);
  720. OpReturn();
  721. ++label_index;
  722. }
  723. for (size_t i = 0; i < info.stores_generics.size(); ++i) {
  724. if (!info.stores_generics[i]) {
  725. continue;
  726. }
  727. if (output_generics[i][0].num_components != 4) {
  728. throw NotImplementedException("Physical stores and transform feedbacks");
  729. }
  730. AddLabel(labels[label_index]);
  731. const Id generic_id{output_generics[i][0].id};
  732. const Id pointer{OpAccessChain(output_f32, generic_id, masked_index)};
  733. OpStore(pointer, store_value);
  734. OpReturn();
  735. ++label_index;
  736. }
  737. if (info.stores_clip_distance) {
  738. AddLabel(labels[label_index]);
  739. const Id pointer{OpAccessChain(output_f32, clip_distances, masked_index)};
  740. OpStore(pointer, store_value);
  741. OpReturn();
  742. ++label_index;
  743. AddLabel(labels[label_index]);
  744. const Id fixed_index{OpIAdd(U32[1], masked_index, Const(4U))};
  745. const Id pointer2{OpAccessChain(output_f32, clip_distances, fixed_index)};
  746. OpStore(pointer2, store_value);
  747. OpReturn();
  748. ++label_index;
  749. }
  750. AddLabel(end_block);
  751. OpUnreachable();
  752. OpFunctionEnd();
  753. return func;
  754. }};
  755. if (info.loads_indexed_attributes) {
  756. indexed_load_func = make_load();
  757. }
  758. if (info.stores_indexed_attributes) {
  759. indexed_store_func = make_store();
  760. }
  761. }
  762. void EmitContext::DefineGlobalMemoryFunctions(const Info& info) {
  763. if (!info.uses_global_memory) {
  764. return;
  765. }
  766. using DefPtr = Id StorageDefinitions::*;
  767. const Id zero{u32_zero_value};
  768. const auto define_body{[&](DefPtr ssbo_member, Id addr, Id element_pointer, u32 shift,
  769. auto&& callback) {
  770. AddLabel();
  771. const size_t num_buffers{info.storage_buffers_descriptors.size()};
  772. for (size_t index = 0; index < num_buffers; ++index) {
  773. if (!info.nvn_buffer_used[index]) {
  774. continue;
  775. }
  776. const auto& ssbo{info.storage_buffers_descriptors[index]};
  777. const Id ssbo_addr_cbuf_offset{Const(ssbo.cbuf_offset / 8)};
  778. const Id ssbo_size_cbuf_offset{Const(ssbo.cbuf_offset / 4 + 2)};
  779. const Id ssbo_addr_pointer{OpAccessChain(
  780. uniform_types.U32x2, cbufs[ssbo.cbuf_index].U32x2, zero, ssbo_addr_cbuf_offset)};
  781. const Id ssbo_size_pointer{OpAccessChain(uniform_types.U32, cbufs[ssbo.cbuf_index].U32,
  782. zero, ssbo_size_cbuf_offset)};
  783. const Id ssbo_addr{OpBitcast(U64, OpLoad(U32[2], ssbo_addr_pointer))};
  784. const Id ssbo_size{OpUConvert(U64, OpLoad(U32[1], ssbo_size_pointer))};
  785. const Id ssbo_end{OpIAdd(U64, ssbo_addr, ssbo_size)};
  786. const Id cond{OpLogicalAnd(U1, OpUGreaterThanEqual(U1, addr, ssbo_addr),
  787. OpULessThan(U1, addr, ssbo_end))};
  788. const Id then_label{OpLabel()};
  789. const Id else_label{OpLabel()};
  790. OpSelectionMerge(else_label, spv::SelectionControlMask::MaskNone);
  791. OpBranchConditional(cond, then_label, else_label);
  792. AddLabel(then_label);
  793. const Id ssbo_id{ssbos[index].*ssbo_member};
  794. const Id ssbo_offset{OpUConvert(U32[1], OpISub(U64, addr, ssbo_addr))};
  795. const Id ssbo_index{OpShiftRightLogical(U32[1], ssbo_offset, Const(shift))};
  796. const Id ssbo_pointer{OpAccessChain(element_pointer, ssbo_id, zero, ssbo_index)};
  797. callback(ssbo_pointer);
  798. AddLabel(else_label);
  799. }
  800. }};
  801. const auto define_load{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  802. const Id function_type{TypeFunction(type, U64)};
  803. const Id func_id{OpFunction(type, spv::FunctionControlMask::MaskNone, function_type)};
  804. const Id addr{OpFunctionParameter(U64)};
  805. define_body(ssbo_member, addr, element_pointer, shift,
  806. [&](Id ssbo_pointer) { OpReturnValue(OpLoad(type, ssbo_pointer)); });
  807. OpReturnValue(ConstantNull(type));
  808. OpFunctionEnd();
  809. return func_id;
  810. }};
  811. const auto define_write{[&](DefPtr ssbo_member, Id element_pointer, Id type, u32 shift) {
  812. const Id function_type{TypeFunction(void_id, U64, type)};
  813. const Id func_id{OpFunction(void_id, spv::FunctionControlMask::MaskNone, function_type)};
  814. const Id addr{OpFunctionParameter(U64)};
  815. const Id data{OpFunctionParameter(type)};
  816. define_body(ssbo_member, addr, element_pointer, shift, [&](Id ssbo_pointer) {
  817. OpStore(ssbo_pointer, data);
  818. OpReturn();
  819. });
  820. OpReturn();
  821. OpFunctionEnd();
  822. return func_id;
  823. }};
  824. const auto define{
  825. [&](DefPtr ssbo_member, const StorageTypeDefinition& type_def, Id type, size_t size) {
  826. const Id element_type{type_def.element};
  827. const u32 shift{static_cast<u32>(std::countr_zero(size))};
  828. const Id load_func{define_load(ssbo_member, element_type, type, shift)};
  829. const Id write_func{define_write(ssbo_member, element_type, type, shift)};
  830. return std::make_pair(load_func, write_func);
  831. }};
  832. std::tie(load_global_func_u32, write_global_func_u32) =
  833. define(&StorageDefinitions::U32, storage_types.U32, U32[1], sizeof(u32));
  834. std::tie(load_global_func_u32x2, write_global_func_u32x2) =
  835. define(&StorageDefinitions::U32x2, storage_types.U32x2, U32[2], sizeof(u32[2]));
  836. std::tie(load_global_func_u32x4, write_global_func_u32x4) =
  837. define(&StorageDefinitions::U32x4, storage_types.U32x4, U32[4], sizeof(u32[4]));
  838. }
  839. void EmitContext::DefineConstantBuffers(const Info& info, u32& binding) {
  840. if (info.constant_buffer_descriptors.empty()) {
  841. return;
  842. }
  843. if (profile.support_descriptor_aliasing) {
  844. if (True(info.used_constant_buffer_types & IR::Type::U8)) {
  845. DefineConstBuffers(*this, info, &UniformDefinitions::U8, binding, U8, 'u', sizeof(u8));
  846. DefineConstBuffers(*this, info, &UniformDefinitions::S8, binding, S8, 's', sizeof(s8));
  847. }
  848. if (True(info.used_constant_buffer_types & IR::Type::U16)) {
  849. DefineConstBuffers(*this, info, &UniformDefinitions::U16, binding, U16, 'u',
  850. sizeof(u16));
  851. DefineConstBuffers(*this, info, &UniformDefinitions::S16, binding, S16, 's',
  852. sizeof(s16));
  853. }
  854. if (True(info.used_constant_buffer_types & IR::Type::U32)) {
  855. DefineConstBuffers(*this, info, &UniformDefinitions::U32, binding, U32[1], 'u',
  856. sizeof(u32));
  857. }
  858. if (True(info.used_constant_buffer_types & IR::Type::F32)) {
  859. DefineConstBuffers(*this, info, &UniformDefinitions::F32, binding, F32[1], 'f',
  860. sizeof(f32));
  861. }
  862. if (True(info.used_constant_buffer_types & IR::Type::U32x2)) {
  863. DefineConstBuffers(*this, info, &UniformDefinitions::U32x2, binding, U32[2], 'u',
  864. sizeof(u32[2]));
  865. }
  866. binding += static_cast<u32>(info.constant_buffer_descriptors.size());
  867. } else {
  868. DefineConstBuffers(*this, info, &UniformDefinitions::U32x4, binding, U32[4], 'u',
  869. sizeof(u32[4]));
  870. for (const ConstantBufferDescriptor& desc : info.constant_buffer_descriptors) {
  871. binding += desc.count;
  872. }
  873. }
  874. }
  875. void EmitContext::DefineStorageBuffers(const Info& info, u32& binding) {
  876. if (info.storage_buffers_descriptors.empty()) {
  877. return;
  878. }
  879. AddExtension("SPV_KHR_storage_buffer_storage_class");
  880. const IR::Type used_types{profile.support_descriptor_aliasing ? info.used_storage_buffer_types
  881. : IR::Type::U32};
  882. if (True(used_types & IR::Type::U8)) {
  883. DefineSsbos(*this, storage_types.U8, &StorageDefinitions::U8, info, binding, U8,
  884. sizeof(u8));
  885. DefineSsbos(*this, storage_types.S8, &StorageDefinitions::S8, info, binding, S8,
  886. sizeof(u8));
  887. }
  888. if (True(used_types & IR::Type::U16)) {
  889. DefineSsbos(*this, storage_types.U16, &StorageDefinitions::U16, info, binding, U16,
  890. sizeof(u16));
  891. DefineSsbos(*this, storage_types.S16, &StorageDefinitions::S16, info, binding, S16,
  892. sizeof(u16));
  893. }
  894. if (True(used_types & IR::Type::U32)) {
  895. DefineSsbos(*this, storage_types.U32, &StorageDefinitions::U32, info, binding, U32[1],
  896. sizeof(u32));
  897. }
  898. if (True(used_types & IR::Type::F32)) {
  899. DefineSsbos(*this, storage_types.F32, &StorageDefinitions::F32, info, binding, F32[1],
  900. sizeof(f32));
  901. }
  902. if (True(used_types & IR::Type::U64)) {
  903. DefineSsbos(*this, storage_types.U64, &StorageDefinitions::U64, info, binding, U64,
  904. sizeof(u64));
  905. }
  906. if (True(used_types & IR::Type::U32x2)) {
  907. DefineSsbos(*this, storage_types.U32x2, &StorageDefinitions::U32x2, info, binding, U32[2],
  908. sizeof(u32[2]));
  909. }
  910. if (True(used_types & IR::Type::U32x4)) {
  911. DefineSsbos(*this, storage_types.U32x4, &StorageDefinitions::U32x4, info, binding, U32[4],
  912. sizeof(u32[4]));
  913. }
  914. for (const StorageBufferDescriptor& desc : info.storage_buffers_descriptors) {
  915. binding += desc.count;
  916. }
  917. const bool needs_function{
  918. info.uses_global_increment || info.uses_global_decrement || info.uses_atomic_f32_add ||
  919. info.uses_atomic_f16x2_add || info.uses_atomic_f16x2_min || info.uses_atomic_f16x2_max ||
  920. info.uses_atomic_f32x2_add || info.uses_atomic_f32x2_min || info.uses_atomic_f32x2_max};
  921. if (needs_function) {
  922. AddCapability(spv::Capability::VariablePointersStorageBuffer);
  923. }
  924. if (info.uses_global_increment) {
  925. increment_cas_ssbo = CasLoop(*this, Operation::Increment, storage_types.U32.array,
  926. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  927. }
  928. if (info.uses_global_decrement) {
  929. decrement_cas_ssbo = CasLoop(*this, Operation::Decrement, storage_types.U32.array,
  930. storage_types.U32.element, U32[1], U32[1], spv::Scope::Device);
  931. }
  932. if (info.uses_atomic_f32_add) {
  933. f32_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  934. storage_types.U32.element, F32[1], U32[1], spv::Scope::Device);
  935. }
  936. if (info.uses_atomic_f16x2_add) {
  937. f16x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  938. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  939. }
  940. if (info.uses_atomic_f16x2_min) {
  941. f16x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  942. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  943. }
  944. if (info.uses_atomic_f16x2_max) {
  945. f16x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  946. storage_types.U32.element, F16[2], F16[2], spv::Scope::Device);
  947. }
  948. if (info.uses_atomic_f32x2_add) {
  949. f32x2_add_cas = CasLoop(*this, Operation::FPAdd, storage_types.U32.array,
  950. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  951. }
  952. if (info.uses_atomic_f32x2_min) {
  953. f32x2_min_cas = CasLoop(*this, Operation::FPMin, storage_types.U32.array,
  954. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  955. }
  956. if (info.uses_atomic_f32x2_max) {
  957. f32x2_max_cas = CasLoop(*this, Operation::FPMax, storage_types.U32.array,
  958. storage_types.U32.element, F32[2], F32[2], spv::Scope::Device);
  959. }
  960. }
  961. void EmitContext::DefineTextureBuffers(const Info& info, u32& binding) {
  962. if (info.texture_buffer_descriptors.empty()) {
  963. return;
  964. }
  965. const spv::ImageFormat format{spv::ImageFormat::Unknown};
  966. image_buffer_type = TypeImage(F32[1], spv::Dim::Buffer, 0U, false, false, 1, format);
  967. sampled_texture_buffer_type = TypeSampledImage(image_buffer_type);
  968. const Id type{TypePointer(spv::StorageClass::UniformConstant, sampled_texture_buffer_type)};
  969. texture_buffers.reserve(info.texture_buffer_descriptors.size());
  970. for (const TextureBufferDescriptor& desc : info.texture_buffer_descriptors) {
  971. if (desc.count != 1) {
  972. throw NotImplementedException("Array of texture buffers");
  973. }
  974. const Id id{AddGlobalVariable(type, spv::StorageClass::UniformConstant)};
  975. Decorate(id, spv::Decoration::Binding, binding);
  976. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  977. Name(id, NameOf(stage, desc, "texbuf"));
  978. texture_buffers.push_back({
  979. .id = id,
  980. .count = desc.count,
  981. });
  982. if (profile.supported_spirv >= 0x00010400) {
  983. interfaces.push_back(id);
  984. }
  985. ++binding;
  986. }
  987. }
  988. void EmitContext::DefineImageBuffers(const Info& info, u32& binding) {
  989. image_buffers.reserve(info.image_buffer_descriptors.size());
  990. for (const ImageBufferDescriptor& desc : info.image_buffer_descriptors) {
  991. if (desc.count != 1) {
  992. throw NotImplementedException("Array of image buffers");
  993. }
  994. const spv::ImageFormat format{GetImageFormat(desc.format)};
  995. const Id image_type{TypeImage(U32[1], spv::Dim::Buffer, false, false, false, 2, format)};
  996. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  997. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  998. Decorate(id, spv::Decoration::Binding, binding);
  999. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1000. Name(id, NameOf(stage, desc, "imgbuf"));
  1001. image_buffers.push_back({
  1002. .id = id,
  1003. .image_type = image_type,
  1004. .count = desc.count,
  1005. });
  1006. if (profile.supported_spirv >= 0x00010400) {
  1007. interfaces.push_back(id);
  1008. }
  1009. ++binding;
  1010. }
  1011. }
  1012. void EmitContext::DefineTextures(const Info& info, u32& binding) {
  1013. textures.reserve(info.texture_descriptors.size());
  1014. for (const TextureDescriptor& desc : info.texture_descriptors) {
  1015. const Id image_type{ImageType(*this, desc)};
  1016. const Id sampled_type{TypeSampledImage(image_type)};
  1017. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, sampled_type)};
  1018. const Id desc_type{DescType(*this, sampled_type, pointer_type, desc.count)};
  1019. const Id id{AddGlobalVariable(desc_type, spv::StorageClass::UniformConstant)};
  1020. Decorate(id, spv::Decoration::Binding, binding);
  1021. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1022. Name(id, NameOf(stage, desc, "tex"));
  1023. textures.push_back({
  1024. .id = id,
  1025. .sampled_type = sampled_type,
  1026. .pointer_type = pointer_type,
  1027. .image_type = image_type,
  1028. .count = desc.count,
  1029. });
  1030. if (profile.supported_spirv >= 0x00010400) {
  1031. interfaces.push_back(id);
  1032. }
  1033. ++binding;
  1034. }
  1035. if (info.uses_atomic_image_u32) {
  1036. image_u32 = TypePointer(spv::StorageClass::Image, U32[1]);
  1037. }
  1038. }
  1039. void EmitContext::DefineImages(const Info& info, u32& binding) {
  1040. images.reserve(info.image_descriptors.size());
  1041. for (const ImageDescriptor& desc : info.image_descriptors) {
  1042. if (desc.count != 1) {
  1043. throw NotImplementedException("Array of images");
  1044. }
  1045. const Id image_type{ImageType(*this, desc)};
  1046. const Id pointer_type{TypePointer(spv::StorageClass::UniformConstant, image_type)};
  1047. const Id id{AddGlobalVariable(pointer_type, spv::StorageClass::UniformConstant)};
  1048. Decorate(id, spv::Decoration::Binding, binding);
  1049. Decorate(id, spv::Decoration::DescriptorSet, 0U);
  1050. Name(id, NameOf(stage, desc, "img"));
  1051. images.push_back({
  1052. .id = id,
  1053. .image_type = image_type,
  1054. .count = desc.count,
  1055. });
  1056. if (profile.supported_spirv >= 0x00010400) {
  1057. interfaces.push_back(id);
  1058. }
  1059. ++binding;
  1060. }
  1061. }
  1062. void EmitContext::DefineInputs(const Info& info) {
  1063. if (info.uses_workgroup_id) {
  1064. workgroup_id = DefineInput(*this, U32[3], false, spv::BuiltIn::WorkgroupId);
  1065. }
  1066. if (info.uses_local_invocation_id) {
  1067. local_invocation_id = DefineInput(*this, U32[3], false, spv::BuiltIn::LocalInvocationId);
  1068. }
  1069. if (info.uses_invocation_id) {
  1070. invocation_id = DefineInput(*this, U32[1], false, spv::BuiltIn::InvocationId);
  1071. }
  1072. if (info.uses_sample_id) {
  1073. sample_id = DefineInput(*this, U32[1], false, spv::BuiltIn::SampleId);
  1074. }
  1075. if (info.uses_is_helper_invocation) {
  1076. is_helper_invocation = DefineInput(*this, U1, false, spv::BuiltIn::HelperInvocation);
  1077. }
  1078. if (info.uses_subgroup_mask) {
  1079. subgroup_mask_eq = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupEqMaskKHR);
  1080. subgroup_mask_lt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLtMaskKHR);
  1081. subgroup_mask_le = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupLeMaskKHR);
  1082. subgroup_mask_gt = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGtMaskKHR);
  1083. subgroup_mask_ge = DefineInput(*this, U32[4], false, spv::BuiltIn::SubgroupGeMaskKHR);
  1084. }
  1085. if (info.uses_subgroup_invocation_id || info.uses_subgroup_shuffles ||
  1086. (profile.warp_size_potentially_larger_than_guest &&
  1087. (info.uses_subgroup_vote || info.uses_subgroup_mask))) {
  1088. subgroup_local_invocation_id =
  1089. DefineInput(*this, U32[1], false, spv::BuiltIn::SubgroupLocalInvocationId);
  1090. }
  1091. if (info.uses_fswzadd) {
  1092. const Id f32_one{Const(1.0f)};
  1093. const Id f32_minus_one{Const(-1.0f)};
  1094. const Id f32_zero{Const(0.0f)};
  1095. fswzadd_lut_a = ConstantComposite(F32[4], f32_minus_one, f32_one, f32_minus_one, f32_zero);
  1096. fswzadd_lut_b =
  1097. ConstantComposite(F32[4], f32_minus_one, f32_minus_one, f32_one, f32_minus_one);
  1098. }
  1099. if (info.loads_primitive_id) {
  1100. primitive_id = DefineInput(*this, U32[1], false, spv::BuiltIn::PrimitiveId);
  1101. }
  1102. if (info.loads_position) {
  1103. const bool is_fragment{stage != Stage::Fragment};
  1104. const spv::BuiltIn built_in{is_fragment ? spv::BuiltIn::Position : spv::BuiltIn::FragCoord};
  1105. input_position = DefineInput(*this, F32[4], true, built_in);
  1106. }
  1107. if (info.loads_instance_id) {
  1108. if (profile.support_vertex_instance_id) {
  1109. instance_id = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceId);
  1110. } else {
  1111. instance_index = DefineInput(*this, U32[1], true, spv::BuiltIn::InstanceIndex);
  1112. base_instance = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseInstance);
  1113. }
  1114. }
  1115. if (info.loads_vertex_id) {
  1116. if (profile.support_vertex_instance_id) {
  1117. vertex_id = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexId);
  1118. } else {
  1119. vertex_index = DefineInput(*this, U32[1], true, spv::BuiltIn::VertexIndex);
  1120. base_vertex = DefineInput(*this, U32[1], true, spv::BuiltIn::BaseVertex);
  1121. }
  1122. }
  1123. if (info.loads_front_face) {
  1124. front_face = DefineInput(*this, U1, true, spv::BuiltIn::FrontFacing);
  1125. }
  1126. if (info.loads_point_coord) {
  1127. point_coord = DefineInput(*this, F32[2], true, spv::BuiltIn::PointCoord);
  1128. }
  1129. if (info.loads_tess_coord) {
  1130. tess_coord = DefineInput(*this, F32[3], false, spv::BuiltIn::TessCoord);
  1131. }
  1132. for (size_t index = 0; index < info.input_generics.size(); ++index) {
  1133. const InputVarying generic{info.input_generics[index]};
  1134. if (!generic.used) {
  1135. continue;
  1136. }
  1137. const AttributeType input_type{runtime_info.generic_input_types[index]};
  1138. if (input_type == AttributeType::Disabled) {
  1139. continue;
  1140. }
  1141. const Id type{GetAttributeType(*this, input_type)};
  1142. const Id id{DefineInput(*this, type, true)};
  1143. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1144. Name(id, fmt::format("in_attr{}", index));
  1145. input_generics[index] = id;
  1146. if (stage != Stage::Fragment) {
  1147. continue;
  1148. }
  1149. switch (generic.interpolation) {
  1150. case Interpolation::Smooth:
  1151. // Default
  1152. // Decorate(id, spv::Decoration::Smooth);
  1153. break;
  1154. case Interpolation::NoPerspective:
  1155. Decorate(id, spv::Decoration::NoPerspective);
  1156. break;
  1157. case Interpolation::Flat:
  1158. Decorate(id, spv::Decoration::Flat);
  1159. break;
  1160. }
  1161. }
  1162. if (stage == Stage::TessellationEval) {
  1163. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1164. if (!info.uses_patches[index]) {
  1165. continue;
  1166. }
  1167. const Id id{DefineInput(*this, F32[4], false)};
  1168. Decorate(id, spv::Decoration::Patch);
  1169. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1170. patches[index] = id;
  1171. }
  1172. }
  1173. }
  1174. void EmitContext::DefineOutputs(const IR::Program& program) {
  1175. const Info& info{program.info};
  1176. const std::optional<u32> invocations{program.invocations};
  1177. if (info.stores_position || stage == Stage::VertexB) {
  1178. output_position = DefineOutput(*this, F32[4], invocations, spv::BuiltIn::Position);
  1179. }
  1180. if (info.stores_point_size || runtime_info.fixed_state_point_size) {
  1181. if (stage == Stage::Fragment) {
  1182. throw NotImplementedException("Storing PointSize in fragment stage");
  1183. }
  1184. output_point_size = DefineOutput(*this, F32[1], invocations, spv::BuiltIn::PointSize);
  1185. }
  1186. if (info.stores_clip_distance) {
  1187. if (stage == Stage::Fragment) {
  1188. throw NotImplementedException("Storing ClipDistance in fragment stage");
  1189. }
  1190. const Id type{TypeArray(F32[1], Const(8U))};
  1191. clip_distances = DefineOutput(*this, type, invocations, spv::BuiltIn::ClipDistance);
  1192. }
  1193. if (info.stores_layer &&
  1194. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1195. if (stage == Stage::Fragment) {
  1196. throw NotImplementedException("Storing Layer in fragment stage");
  1197. }
  1198. layer = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::Layer);
  1199. }
  1200. if (info.stores_viewport_index &&
  1201. (profile.support_viewport_index_layer_non_geometry || stage == Stage::Geometry)) {
  1202. if (stage == Stage::Fragment) {
  1203. throw NotImplementedException("Storing ViewportIndex in fragment stage");
  1204. }
  1205. viewport_index = DefineOutput(*this, U32[1], invocations, spv::BuiltIn::ViewportIndex);
  1206. }
  1207. if (info.stores_viewport_mask && profile.support_viewport_mask) {
  1208. viewport_mask = DefineOutput(*this, TypeArray(U32[1], Const(1u)), std::nullopt,
  1209. spv::BuiltIn::ViewportMaskNV);
  1210. }
  1211. for (size_t index = 0; index < info.stores_generics.size(); ++index) {
  1212. if (info.stores_generics[index]) {
  1213. DefineGenericOutput(*this, index, invocations);
  1214. }
  1215. }
  1216. switch (stage) {
  1217. case Stage::TessellationControl:
  1218. if (info.stores_tess_level_outer) {
  1219. const Id type{TypeArray(F32[1], Const(4U))};
  1220. output_tess_level_outer =
  1221. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelOuter);
  1222. Decorate(output_tess_level_outer, spv::Decoration::Patch);
  1223. }
  1224. if (info.stores_tess_level_inner) {
  1225. const Id type{TypeArray(F32[1], Const(2U))};
  1226. output_tess_level_inner =
  1227. DefineOutput(*this, type, std::nullopt, spv::BuiltIn::TessLevelInner);
  1228. Decorate(output_tess_level_inner, spv::Decoration::Patch);
  1229. }
  1230. for (size_t index = 0; index < info.uses_patches.size(); ++index) {
  1231. if (!info.uses_patches[index]) {
  1232. continue;
  1233. }
  1234. const Id id{DefineOutput(*this, F32[4], std::nullopt)};
  1235. Decorate(id, spv::Decoration::Patch);
  1236. Decorate(id, spv::Decoration::Location, static_cast<u32>(index));
  1237. patches[index] = id;
  1238. }
  1239. break;
  1240. case Stage::Fragment:
  1241. for (u32 index = 0; index < 8; ++index) {
  1242. if (!info.stores_frag_color[index] && !profile.need_declared_frag_colors) {
  1243. continue;
  1244. }
  1245. frag_color[index] = DefineOutput(*this, F32[4], std::nullopt);
  1246. Decorate(frag_color[index], spv::Decoration::Location, index);
  1247. Name(frag_color[index], fmt::format("frag_color{}", index));
  1248. }
  1249. if (info.stores_frag_depth) {
  1250. frag_depth = DefineOutput(*this, F32[1], std::nullopt);
  1251. Decorate(frag_depth, spv::Decoration::BuiltIn, spv::BuiltIn::FragDepth);
  1252. }
  1253. if (info.stores_sample_mask) {
  1254. sample_mask = DefineOutput(*this, U32[1], std::nullopt);
  1255. Decorate(sample_mask, spv::Decoration::BuiltIn, spv::BuiltIn::SampleMask);
  1256. }
  1257. break;
  1258. default:
  1259. break;
  1260. }
  1261. }
  1262. } // namespace Shader::Backend::SPIRV