spirv_emit_context.cpp 70 KB

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