spirv_emit_context.cpp 69 KB

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