spirv_emit_context.cpp 61 KB

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