emit_context.cpp 62 KB

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